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,180 @@
1
+ """``question``:在关键歧义处向用户提一个结构化问题。
2
+
3
+ ## 为什么需要一个工具,而不是让模型在文本里问
4
+
5
+ 模型**已经**可以在回答里写"你想用 MySQL 还是 SQLite?",然后结束这一回合。这条路在
6
+ 真实使用里有两个问题:
7
+
8
+ 1. 用户要重新组织一句话,模型要重新理解一遍,两边都在猜对方的意思;
9
+ 2. 用户的回答会作为一条普通 user 消息进入转录,与"任务要求"混在一起,压缩时同等
10
+ 对待。一个已经被回答过的疑问,会在三次压缩之后重新变成一段没有上下文的对话。
11
+
12
+ 工具化的提问把这件事变成**一次同步往返**:问题有结构(选项、是否多选),答案有
13
+ 结构(选了哪几个、补充了什么),并且以 ``toolResult`` 的形式回到模型——它明确挂在
14
+ 这次调用上,不会被误读成新任务。
15
+
16
+ ## 取消为什么必须是 ``is_error``
17
+
18
+ 用户随时可以不回答。这时模型不能停在那里等,也不能假装自己得到了回答。结果标成
19
+ ``is_error`` 并给出"采用默认假设继续"的出路,模型才有明确的下一步;把取消伪装成
20
+ 空回答会让它以为用户说了什么,然后按一个不存在的选择继续做下去。
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
26
+ from braid_ai.cancel import CancelToken
27
+ from braid_ai.types import JsonValue, TextContent
28
+ from braid_coding_agent.questions import (
29
+ QuestionAnswer,
30
+ QuestionHandler,
31
+ QuestionOption,
32
+ QuestionRequest,
33
+ )
34
+ from braid_coding_agent.tools.args import object_list_arg, optional_bool_arg, string_arg
35
+
36
+ __all__ = [
37
+ "PROMPT_GUIDELINES",
38
+ "PROMPT_SNIPPET",
39
+ "QUESTION_PARAMETERS",
40
+ "create_question_tool",
41
+ ]
42
+
43
+ QUESTION_PARAMETERS: dict[str, JsonValue] = {
44
+ "type": "object",
45
+ "properties": {
46
+ "question": {
47
+ "type": "string",
48
+ "description": "The question to ask, in one sentence",
49
+ },
50
+ "options": {
51
+ "type": "array",
52
+ "description": (
53
+ "Candidate answers. An empty list asks for free-form text. Keep it to 2-4 "
54
+ "options; the user can always type something else."
55
+ ),
56
+ "items": {
57
+ "type": "object",
58
+ "properties": {
59
+ "label": {"type": "string", "description": "Short answer text"},
60
+ "description": {
61
+ "type": "string",
62
+ "description": "What this choice implies (optional)",
63
+ },
64
+ },
65
+ "required": ["label"],
66
+ "additionalProperties": False,
67
+ },
68
+ },
69
+ "multiple": {
70
+ "type": "boolean",
71
+ "description": "Whether the user may pick more than one option",
72
+ },
73
+ },
74
+ "required": ["question", "options"],
75
+ "additionalProperties": False,
76
+ }
77
+
78
+ #: 取消时的结果文本。三句话各自负责一件事:说明发生了什么、给出下一步、要求交代假设。
79
+ _CANCELLED_TEXT = (
80
+ "用户没有回答这个问题(已取消)。请采用最合理的默认假设继续,"
81
+ "并在最终回答里写明你采用了什么假设、为什么。"
82
+ )
83
+
84
+ _EMPTY_TEXT = (
85
+ "用户没有给出有效回答(既没有选择选项也没有补充说明,按取消处理)。"
86
+ "请按默认假设继续,并说明你的假设。"
87
+ )
88
+
89
+
90
+ def create_question_tool(ask: QuestionHandler | None) -> AgentTool:
91
+ """构造 ``question``。``ask`` 为 ``None`` 时每次调用都按取消收尾。
92
+
93
+ ``None`` 不是错误配置:``print`` 与 ``json`` 模式没有交互通道,那时提问本来
94
+ 就没有接收方,立刻返回比挂在一个永远不会到的答案上好。
95
+ """
96
+
97
+ async def execute(
98
+ tool_call_id: str,
99
+ args: dict[str, JsonValue],
100
+ signal: CancelToken | None,
101
+ on_update: ToolUpdateSink,
102
+ ) -> AgentToolResult:
103
+ del tool_call_id, on_update
104
+ question = string_arg(args, "question").strip()
105
+ if not question:
106
+ raise ValueError("提问的问题不能为空")
107
+ options = tuple(
108
+ _option(item, index) for index, item in enumerate(object_list_arg(args, "options"), 1)
109
+ )
110
+ request = QuestionRequest(
111
+ question=question,
112
+ options=options,
113
+ multiple=optional_bool_arg(args, "multiple") or False,
114
+ )
115
+ answer = QuestionAnswer(cancelled=True) if ask is None else await ask(request, signal)
116
+ return _result(request, answer)
117
+
118
+ return AgentTool(
119
+ name="question",
120
+ label="question",
121
+ description=(
122
+ "Ask the user a structured question when a decision cannot be inferred from the "
123
+ "code or the request (which database, which of two APIs, whether to keep an old "
124
+ "behaviour). Do not use it to confirm what you can verify yourself. The answer "
125
+ "comes back as this tool's result; if the user cancels, pick the most reasonable "
126
+ "default and state the assumption in your final answer."
127
+ ),
128
+ parameters=QUESTION_PARAMETERS,
129
+ execute=execute,
130
+ )
131
+
132
+
133
+ def _option(item: dict[str, JsonValue], index: int) -> QuestionOption:
134
+ raw_label = item.get("label")
135
+ if not isinstance(raw_label, str) or not raw_label.strip():
136
+ raise ValueError(f"第 {index} 个选项缺少 label")
137
+ raw_description = item.get("description")
138
+ return QuestionOption(
139
+ label=raw_label.strip(),
140
+ description=raw_description.strip() if isinstance(raw_description, str) else "",
141
+ )
142
+
143
+
144
+ def _result(request: QuestionRequest, answer: QuestionAnswer) -> AgentToolResult:
145
+ """把回答折成工具结果。取消与空回答都走 ``is_error``。"""
146
+ details: JsonValue = {
147
+ "question": request.question,
148
+ "selected": list(answer.selected),
149
+ "custom": answer.custom,
150
+ "cancelled": answer.cancelled,
151
+ }
152
+ if answer.cancelled:
153
+ return AgentToolResult(
154
+ content=[TextContent(text=_CANCELLED_TEXT)], details=details, is_error=True
155
+ )
156
+ if answer.is_empty:
157
+ return AgentToolResult(
158
+ content=[TextContent(text=_EMPTY_TEXT)], details=details, is_error=True
159
+ )
160
+ selected = "、".join(answer.selected)
161
+ custom = answer.custom.strip()
162
+ if selected and custom:
163
+ text = f"用户选择:{selected};补充:{custom}"
164
+ elif selected:
165
+ text = f"用户选择:{selected}"
166
+ else:
167
+ text = f"用户回答:{custom}"
168
+ return AgentToolResult(content=[TextContent(text=text)], details=details)
169
+
170
+
171
+ #: 系统提示词里这一行怎么介绍 ``question``。
172
+ PROMPT_SNIPPET = "Ask the user to choose between options when the request is ambiguous"
173
+
174
+ #: 只有 ``question`` 可执行时才出现的规则条目。
175
+ PROMPT_GUIDELINES: tuple[str, ...] = (
176
+ "Ask a question only when the ambiguity changes what you would build and you cannot "
177
+ "resolve it by reading the code; prefer one question with concrete options over prose",
178
+ "When a question is cancelled, pick the most reasonable default, continue, and state the "
179
+ "assumption in your final answer",
180
+ )
@@ -0,0 +1,223 @@
1
+ """``read``:把文件内容变成模型可以继续行动的一段文本。
2
+
3
+ 设计上的三件事按重要性排列:
4
+
5
+ 1. **截断要可继续**。超过上限时附一句
6
+ ``[Showing lines 1-2000 of 5000. Use offset=2001 to continue.]``——模型下一次调用
7
+ 就有了确切的参数,不必自己数行。
8
+ 2. **首行超限要换工具**。一行 200KB 的文件(压缩后的 JS、单行 JSON)无论怎么截都
9
+ 凑不出"前 N 行",这时给出 ``bash: sed -n '1p' … | head -c …`` 的替代命令。
10
+ 3. **路径错误要说清是哪个路径**。模型写错路径很常见,错误里必须带绝对路径,
11
+ 否则它会在同一个错误上反复重试。
12
+
13
+ 图片只返回占位文本。二进制文件不做特殊
14
+ 识别:按 UTF-8 解码、非法字节替换成 ``�``。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+
21
+ from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
22
+ from braid_ai.cancel import CancelToken
23
+ from braid_ai.types import JsonValue, TextContent
24
+ from braid_coding_agent.tools.args import optional_integer_arg, string_arg
25
+ from braid_coding_agent.tools.operations import (
26
+ FileOperations,
27
+ LocalFileOperations,
28
+ ensure_not_cancelled,
29
+ )
30
+ from braid_coding_agent.tools.path_utils import resolve_to_cwd
31
+ from braid_coding_agent.tools.truncate import (
32
+ DEFAULT_MAX_BYTES,
33
+ DEFAULT_MAX_LINES,
34
+ byte_length,
35
+ format_size,
36
+ truncate_head,
37
+ )
38
+
39
+ #: 扩展名 → MIME。只看扩展名:读文件头再判断要多读一次,而模型给的路径通常带扩展名。
40
+ _IMAGE_MIME_TYPES: dict[str, str] = {
41
+ ".jpg": "image/jpeg",
42
+ ".jpeg": "image/jpeg",
43
+ ".png": "image/png",
44
+ ".gif": "image/gif",
45
+ ".webp": "image/webp",
46
+ ".bmp": "image/bmp",
47
+ }
48
+
49
+ READ_PARAMETERS: dict[str, JsonValue] = {
50
+ "type": "object",
51
+ "properties": {
52
+ "path": {
53
+ "type": "string",
54
+ "description": "Path to the file to read (relative or absolute)",
55
+ },
56
+ "offset": {
57
+ "type": "integer",
58
+ "description": "Line number to start reading from (1-indexed)",
59
+ },
60
+ "limit": {
61
+ "type": "integer",
62
+ "description": "Maximum number of lines to read",
63
+ },
64
+ },
65
+ "required": ["path"],
66
+ "additionalProperties": False,
67
+ }
68
+
69
+
70
+ def detect_image_mime_type(path: str) -> str | None:
71
+ """按扩展名判断图片类型。不是图片返回 ``None``。"""
72
+ return _IMAGE_MIME_TYPES.get(os.path.splitext(path)[1].lower())
73
+
74
+
75
+ def create_read_tool(
76
+ cwd: str,
77
+ *,
78
+ operations: FileOperations | None = None,
79
+ max_lines: int = DEFAULT_MAX_LINES,
80
+ max_bytes: int = DEFAULT_MAX_BYTES,
81
+ ) -> AgentTool:
82
+ """构造 ``read`` 工具。``cwd`` 是相对路径的基准目录。"""
83
+ ops: FileOperations = operations if operations is not None else LocalFileOperations()
84
+
85
+ async def execute(
86
+ tool_call_id: str,
87
+ args: dict[str, JsonValue],
88
+ signal: CancelToken | None,
89
+ on_update: ToolUpdateSink,
90
+ ) -> AgentToolResult:
91
+ path = string_arg(args, "path")
92
+ offset = optional_integer_arg(args, "offset")
93
+ limit = optional_integer_arg(args, "limit")
94
+ absolute_path = resolve_to_cwd(path, cwd)
95
+
96
+ ensure_not_cancelled(signal)
97
+ if not await ops.exists(absolute_path):
98
+ raise FileNotFoundError(f"File not found: {absolute_path}")
99
+ await ops.check_access(absolute_path)
100
+ ensure_not_cancelled(signal)
101
+
102
+ mime_type = detect_image_mime_type(absolute_path)
103
+ if mime_type is not None:
104
+ size = len(await ops.read_bytes(absolute_path))
105
+ return AgentToolResult(
106
+ content=[
107
+ TextContent(
108
+ text=(
109
+ f"Read image file [{mime_type}] ({format_size(size)}).\n"
110
+ "[This build does not send image content to the model. "
111
+ "Use bash if you need to inspect it.]"
112
+ )
113
+ )
114
+ ],
115
+ details={"image": {"path": absolute_path, "mime_type": mime_type, "bytes": size}},
116
+ )
117
+
118
+ raw = await ops.read_bytes(absolute_path)
119
+ ensure_not_cancelled(signal)
120
+ text = raw.decode("utf-8", errors="replace")
121
+ return _read_text(
122
+ text, path=path, offset=offset, limit=limit, max_lines=max_lines, max_bytes=max_bytes
123
+ )
124
+
125
+ return AgentTool(
126
+ name="read",
127
+ label="read",
128
+ description=(
129
+ "Read the contents of a file. Supports text files; images are reported as a "
130
+ f"placeholder. Output is truncated to {max_lines} lines or {max_bytes // 1024}KB "
131
+ "(whichever is hit first). Use offset/limit for large files. When you need the "
132
+ "full file, continue with offset until complete."
133
+ ),
134
+ parameters=READ_PARAMETERS,
135
+ execute=execute,
136
+ )
137
+
138
+
139
+ def _read_text(
140
+ text: str,
141
+ *,
142
+ path: str,
143
+ offset: int | None,
144
+ limit: int | None,
145
+ max_lines: int,
146
+ max_bytes: int,
147
+ ) -> AgentToolResult:
148
+ """把文件文本按 offset/limit 与上限切好,拼出继续提示。纯函数,便于单测。"""
149
+ all_lines = text.split("\n")
150
+ total_lines = len(all_lines)
151
+ start = max(0, offset - 1) if offset else 0
152
+ start_display = start + 1
153
+ if start >= total_lines:
154
+ raise ValueError(f"Offset {offset} is beyond end of file ({total_lines} lines total)")
155
+
156
+ user_limited: int | None = None
157
+ if limit is not None:
158
+ end = min(start + limit, total_lines)
159
+ selected = "\n".join(all_lines[start:end])
160
+ user_limited = end - start
161
+ else:
162
+ selected = "\n".join(all_lines[start:])
163
+
164
+ truncation = truncate_head(selected, max_lines=max_lines, max_bytes=max_bytes)
165
+ if truncation.first_line_exceeds_limit:
166
+ first_line_size = format_size(byte_length(all_lines[start]))
167
+ output = (
168
+ f"[Line {start_display} is {first_line_size}, exceeds {format_size(max_bytes)} limit. "
169
+ f"Use bash: sed -n '{start_display}p' {path} | head -c {max_bytes}]"
170
+ )
171
+ return AgentToolResult(
172
+ content=[TextContent(text=output)], details={"truncation": truncation.to_details()}
173
+ )
174
+
175
+ if truncation.truncated:
176
+ end_display = start_display + truncation.output_lines - 1
177
+ next_offset = end_display + 1
178
+ if truncation.truncated_by == "lines":
179
+ notice = (
180
+ f"\n\n[Showing lines {start_display}-{end_display} of {total_lines}. "
181
+ f"Use offset={next_offset} to continue.]"
182
+ )
183
+ else:
184
+ notice = (
185
+ f"\n\n[Showing lines {start_display}-{end_display} of {total_lines} "
186
+ f"({format_size(max_bytes)} limit). Use offset={next_offset} to continue.]"
187
+ )
188
+ return AgentToolResult(
189
+ content=[TextContent(text=truncation.content + notice)],
190
+ details={"truncation": truncation.to_details()},
191
+ )
192
+
193
+ if user_limited is not None and start + user_limited < total_lines:
194
+ remaining = total_lines - (start + user_limited)
195
+ next_offset = start + user_limited + 1
196
+ return AgentToolResult(
197
+ content=[
198
+ TextContent(
199
+ text=(
200
+ f"{truncation.content}\n\n[{remaining} more lines in file. "
201
+ f"Use offset={next_offset} to continue.]"
202
+ )
203
+ )
204
+ ]
205
+ )
206
+
207
+ return AgentToolResult(content=[TextContent(text=truncation.content)])
208
+
209
+
210
+ #: 系统提示词里这一行怎么介绍 ``read``。空字符串表示不出现在工具清单里。
211
+ PROMPT_SNIPPET = "Read file contents"
212
+
213
+ #: 只有在 ``read`` 可执行时才出现的规则条目。
214
+ PROMPT_GUIDELINES: tuple[str, ...] = ("Use read to examine files instead of cat or sed.",)
215
+
216
+
217
+ __all__ = [
218
+ "PROMPT_GUIDELINES",
219
+ "PROMPT_SNIPPET",
220
+ "READ_PARAMETERS",
221
+ "create_read_tool",
222
+ "detect_image_mime_type",
223
+ ]
@@ -0,0 +1,102 @@
1
+ """``submit_plan``:把实施计划交给用户批准。
2
+
3
+ ## 为什么计划必须经过一次工具调用
4
+
5
+ 模型在回答里写一份计划,然后说"如果没问题我就开始",是普通对话;它没有给出一个
6
+ 可以判定的边界,用户也没法用一次明确的动作回答。工具调用把这个边界变成数据:
7
+ 计划文本进会话树,界面据此渲染,审批结论决定模式切换,而"本轮到此为止"是一条
8
+ 明确指令,模型不必猜用户会不会同意。
9
+
10
+ ## 为什么审批不在这里等答案
11
+
12
+ 审批会切换权限模式,而系统提示词里的规划指引是按回合算的:在一次 run 中间换模式,
13
+ 后面的请求仍带着"当前处于规划模式、只读"的段落,会与已经放宽的权限打架。把审批放到
14
+ 回合边界(REPL / TUI 在 ``prompt`` 返回之后问)之后,每一边的提示词都与权限一致:
15
+ 批准之后的下一轮拿到的是已批准计划与正常权限,继续修改的下一轮仍是规划模式。
16
+
17
+ ## 谁说了算
18
+
19
+ 只有交互方给出的答案能改变状态(``PlanMode.approve`` / ``leave``)。模型的文字、
20
+ 模型的自我判断、以及"计划里写了已批准"都不构成批准;非交互入口提交的计划停在
21
+ "等待批准",用户可以在 REPL / RPC 里显式批准。
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from braid_agent.tools import AgentTool, AgentToolResult, ToolUpdateSink
27
+ from braid_ai.cancel import CancelToken
28
+ from braid_ai.types import JsonValue, TextContent
29
+ from braid_coding_agent.session.plan_mode import PlanMode
30
+ from braid_coding_agent.tools.args import string_arg
31
+
32
+ __all__ = [
33
+ "SUBMIT_PLAN_PARAMETERS",
34
+ "create_submit_plan_tool",
35
+ ]
36
+
37
+ SUBMIT_PLAN_PARAMETERS: dict[str, JsonValue] = {
38
+ "type": "object",
39
+ "properties": {
40
+ "plan": {
41
+ "type": "string",
42
+ "description": (
43
+ "The complete implementation plan in Markdown: goal and expected behaviour, "
44
+ "approach, modules and interface changes, ordered steps with dependencies, "
45
+ "edge cases, tests and acceptance criteria, assumptions and risks."
46
+ ),
47
+ },
48
+ },
49
+ "required": ["plan"],
50
+ "additionalProperties": False,
51
+ }
52
+
53
+
54
+ def create_submit_plan_tool(plan_mode: PlanMode) -> AgentTool:
55
+ """构造 ``submit_plan``。计划落在 ``plan_mode`` 的会话树上,等交互方审批。"""
56
+
57
+ async def execute(
58
+ tool_call_id: str,
59
+ args: dict[str, JsonValue],
60
+ signal: CancelToken | None,
61
+ on_update: ToolUpdateSink,
62
+ ) -> AgentToolResult:
63
+ del tool_call_id, on_update
64
+ text = string_arg(args, "plan").strip()
65
+ if not text:
66
+ raise ValueError("计划内容不能为空")
67
+ if signal is not None and signal.cancelled:
68
+ # 打断之后再落一版计划会让用户以为提交成功:这一版不算数。
69
+ return AgentToolResult(
70
+ content=[TextContent(text="运行已取消,计划没有提交。")],
71
+ details={"decision": "cancelled"},
72
+ is_error=True,
73
+ )
74
+ state = await plan_mode.submit(text)
75
+ details: JsonValue = {"decision": "pending", "planMode": state.to_wire()}
76
+ return AgentToolResult(
77
+ content=[
78
+ TextContent(
79
+ text=(
80
+ f"计划已提交(第 {state.revision} 版),正在等待用户批准。\n"
81
+ "本轮到此为止:不要开始实施,不要修改任何文件。"
82
+ "用户批准后你会收到一条新的指令,其中带着完整计划;"
83
+ "用户要求修改时会带着修改意见。"
84
+ )
85
+ )
86
+ ],
87
+ details=details,
88
+ )
89
+
90
+ return AgentTool(
91
+ name="submit_plan",
92
+ label="submit_plan",
93
+ description=(
94
+ "Submit the implementation plan and end the current turn.\n\n"
95
+ "Use this only in plan mode, once the plan is complete. Pass the whole plan as "
96
+ "one Markdown document; the user reads it and chooses to approve, keep revising, "
97
+ "or leave plan mode. Nothing is executed until the user approves, so do not call "
98
+ "other tools after this one in the same turn."
99
+ ),
100
+ parameters=SUBMIT_PLAN_PARAMETERS,
101
+ execute=execute,
102
+ )