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,320 @@
1
+ """出口代理:一个只放行白名单域名的本地 HTTP 代理。
2
+
3
+ 沙箱负责「只能连本机」,这个代理负责「本机这个端口能把话带给谁」。两者合起来才是
4
+ 一次完整的网络边界:内核挡住直接出站,代理按域名放行。
5
+
6
+ ## 为什么是代理而不是 DNS 过滤或防火墙
7
+
8
+ - 域名知道得最晚的地方就是代理:``CONNECT api.example.com:443`` 明确写出目标主机,
9
+ 而 DNS 过滤只看得到解析请求,防火墙只看得到 IP。
10
+ - 代理不需要 root、不需要改系统配置,进程级启停,随会话生命周期存在。
11
+ - 它对被代理的程序是**标准协议**。curl、git、npm、pip、requests 都读 ``HTTPS_PROXY``,
12
+ 因此没有为每个工具写一份适配。
13
+
14
+ ## 它拦不住什么
15
+
16
+ 不读环境变量、直接 ``connect()`` 的程序(自写的 socket 客户端、部分 Go 程序的
17
+ ``GODEBUG`` 配置)可以绕过它。所以:
18
+
19
+ - ``mode = "workspace-write"`` 时,Seatbelt 只放行代理端口,绕过代理也没用(强边界);
20
+ - ``mode = "network-only"`` 时,代理就是全部边界(协作式,文档与工具结果都这么说)。
21
+
22
+ ## TLS 不落地
23
+
24
+ ``CONNECT`` 只做字节隧道:代理看到的是目标主机名,看不到加密内容,也不做 MITM。
25
+ 放行判定只看 ``host:port``。
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import asyncio
31
+ import contextlib
32
+ from dataclasses import dataclass
33
+ from urllib.parse import SplitResult, urlsplit
34
+
35
+ from braid_ai.types import JsonValue
36
+ from braid_coding_agent.sandbox.policy import NetworkPolicy, normalize_host, split_host_port
37
+
38
+ #: 请求头上限。超过就断开:一个 8KB 的请求行不是正常客户端。
39
+ MAX_HEAD_BYTES = 64 * 1024
40
+ #: 拒绝记录的条数上限。工具结果只需要几条样例,积少成多没有意义。
41
+ MAX_DENIALS = 32
42
+ #: 隧道与转发阶段每次读的字节数。
43
+ CHUNK = 64 * 1024
44
+
45
+
46
+ @dataclass(slots=True, frozen=True)
47
+ class NetworkDenial:
48
+ """一次被拒绝的出站连接。``reason`` 会原样进入工具结果。"""
49
+
50
+ host: str
51
+ port: int
52
+ method: str
53
+ reason: str
54
+
55
+ def to_json(self) -> dict[str, JsonValue]:
56
+ return {
57
+ "host": self.host,
58
+ "port": self.port,
59
+ "method": self.method,
60
+ "reason": self.reason,
61
+ }
62
+
63
+
64
+ class EgressProxy:
65
+ """本地 HTTP 代理。``start()`` 之前 :attr:`port` 为 0(由系统分配)。"""
66
+
67
+ def __init__(
68
+ self,
69
+ policy: NetworkPolicy,
70
+ *,
71
+ host: str = "127.0.0.1",
72
+ port: int = 0,
73
+ max_denials: int = MAX_DENIALS,
74
+ ) -> None:
75
+ self._policy = policy
76
+ self._host = host
77
+ self._requested_port = port
78
+ self._max_denials = max_denials
79
+ self._server: asyncio.AbstractServer | None = None
80
+ self._port = 0
81
+ self._denials: list[NetworkDenial] = []
82
+ self._tasks: set[asyncio.Task[None]] = set()
83
+
84
+ @property
85
+ def policy(self) -> NetworkPolicy:
86
+ return self._policy
87
+
88
+ @property
89
+ def port(self) -> int:
90
+ return self._port
91
+
92
+ @property
93
+ def url(self) -> str:
94
+ return f"http://{self._host}:{self._port}"
95
+
96
+ @property
97
+ def denials(self) -> tuple[NetworkDenial, ...]:
98
+ return tuple(self._denials)
99
+
100
+ def take_denials(self) -> tuple[NetworkDenial, ...]:
101
+ """取走自上次调用以来新增的拒绝记录。``bash`` 每次执行后调用一次。"""
102
+ if not self._denials:
103
+ return ()
104
+ taken = tuple(self._denials)
105
+ self._denials.clear()
106
+ return taken
107
+
108
+ async def start(self) -> None:
109
+ if self._server is not None:
110
+ return
111
+ self._server = await asyncio.start_server(
112
+ self._handle_client, self._host, self._requested_port
113
+ )
114
+ socket = self._server.sockets[0] if self._server.sockets else None
115
+ self._port = int(socket.getsockname()[1]) if socket is not None else self._requested_port
116
+
117
+ async def close(self) -> None:
118
+ server = self._server
119
+ self._server = None
120
+ if server is not None:
121
+ server.close()
122
+ await server.wait_closed()
123
+ tasks = [task for task in self._tasks if not task.done()]
124
+ for task in tasks:
125
+ task.cancel()
126
+ if tasks:
127
+ await asyncio.gather(*tasks, return_exceptions=True)
128
+
129
+ # ------------------------------------------------------------- 连接处理
130
+
131
+ async def _handle_client(
132
+ self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
133
+ ) -> None:
134
+ task = asyncio.current_task()
135
+ if task is not None:
136
+ self._tasks.add(task)
137
+ try:
138
+ await self._serve(reader, writer)
139
+ except (ConnectionError, asyncio.IncompleteReadError, TimeoutError):
140
+ pass
141
+ finally:
142
+ if task is not None:
143
+ self._tasks.discard(task)
144
+ writer.close()
145
+ with contextlib.suppress(ConnectionError, TimeoutError):
146
+ await writer.wait_closed()
147
+
148
+ async def _serve(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
149
+ try:
150
+ head = await reader.readuntil(b"\r\n\r\n")
151
+ except asyncio.LimitOverrunError:
152
+ await _write_response(writer, 431, "请求头过长")
153
+ return
154
+ if not head:
155
+ return
156
+ lines = head.decode("latin-1").split("\r\n")
157
+ request_line = lines[0]
158
+ parts = request_line.split(" ")
159
+ if len(parts) < 2:
160
+ await _write_response(writer, 400, "无法解析的请求行")
161
+ return
162
+ method, target = parts[0], parts[1]
163
+
164
+ if method.upper() == "CONNECT":
165
+ host, port = split_host_port(target, default_port=443)
166
+ if await self._denied(writer, method, host, port):
167
+ return
168
+ await self._tunnel(reader, writer, head, host, port)
169
+ return
170
+
171
+ parsed = urlsplit(target)
172
+ if not parsed.scheme or not parsed.hostname:
173
+ # 代理只接 absolute-form(``GET http://host/path``)。收到 origin-form
174
+ # 说明有程序把代理当成了目标服务器本身,回一条明确的错误。
175
+ await _write_response(writer, 400, "代理只接受绝对 URI 请求(http://host/...)")
176
+ return
177
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
178
+ if await self._denied(writer, method, parsed.hostname, port):
179
+ return
180
+ await self._forward(reader, writer, head, parsed.hostname, port, parsed)
181
+
182
+ async def _denied(
183
+ self, writer: asyncio.StreamWriter, method: str, host: str, port: int
184
+ ) -> bool:
185
+ """判定并记录。返回 ``True`` 表示已经写好拒绝响应。"""
186
+ reason = self._policy.check(host, port)
187
+ if reason is None:
188
+ return False
189
+ denial = NetworkDenial(host=normalize_host(host), port=port, method=method, reason=reason)
190
+ if len(self._denials) < self._max_denials:
191
+ self._denials.append(denial)
192
+ await _write_response(
193
+ writer,
194
+ 403,
195
+ f"braid network policy: {reason}",
196
+ )
197
+ return True
198
+
199
+ async def _tunnel(
200
+ self,
201
+ reader: asyncio.StreamReader,
202
+ writer: asyncio.StreamWriter,
203
+ head: bytes,
204
+ host: str,
205
+ port: int,
206
+ ) -> None:
207
+ """``CONNECT``:回 200 之后原样双向转发字节。"""
208
+ del head
209
+ try:
210
+ upstream_reader, upstream_writer = await asyncio.wait_for(
211
+ asyncio.open_connection(host, port), timeout=10
212
+ )
213
+ except (OSError, TimeoutError) as exc:
214
+ await _write_response(writer, 502, f"无法连接 {host}:{port}:{exc}")
215
+ return
216
+ try:
217
+ writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
218
+ await writer.drain()
219
+ await _pump_both(reader, writer, upstream_reader, upstream_writer)
220
+ finally:
221
+ upstream_writer.close()
222
+ with contextlib.suppress(ConnectionError, TimeoutError):
223
+ await upstream_writer.wait_closed()
224
+
225
+ async def _forward(
226
+ self,
227
+ reader: asyncio.StreamReader,
228
+ writer: asyncio.StreamWriter,
229
+ head: bytes,
230
+ host: str,
231
+ port: int,
232
+ parsed: SplitResult,
233
+ ) -> None:
234
+ """普通 HTTP:把请求行改回 origin-form 后转发,响应原样回传。"""
235
+ try:
236
+ upstream_reader, upstream_writer = await asyncio.wait_for(
237
+ asyncio.open_connection(host, port), timeout=10
238
+ )
239
+ except (OSError, TimeoutError) as exc:
240
+ await _write_response(writer, 502, f"无法连接 {host}:{port}:{exc}")
241
+ return
242
+ try:
243
+ upstream_writer.write(_origin_form_head(head, parsed))
244
+ await upstream_writer.drain()
245
+ await _pump_both(reader, writer, upstream_reader, upstream_writer)
246
+ finally:
247
+ upstream_writer.close()
248
+ with contextlib.suppress(ConnectionError, TimeoutError):
249
+ await upstream_writer.wait_closed()
250
+
251
+
252
+ def _origin_form_head(head: bytes, parsed: SplitResult) -> bytes:
253
+ """把 ``GET http://h/p?q HTTP/1.1`` 改成 ``GET /p?q HTTP/1.1``,并强制短线连接。"""
254
+ lines = head.decode("latin-1").split("\r\n")
255
+ parts = lines[0].split(" ")
256
+ path = parsed.path or "/"
257
+ if parsed.query:
258
+ path = f"{path}?{parsed.query}"
259
+ if len(parts) >= 3:
260
+ parts[1] = path
261
+ lines[0] = " ".join(parts)
262
+ rewritten: list[str] = [lines[0]]
263
+ for line in lines[1:]:
264
+ lowered = line.lower()
265
+ if lowered.startswith("proxy-connection:"):
266
+ continue
267
+ if lowered.startswith("connection:"):
268
+ continue
269
+ rewritten.append(line)
270
+ rewritten.append("Connection: close")
271
+ rewritten.extend(["", ""])
272
+ return "\r\n".join(rewritten).encode("latin-1")
273
+
274
+
275
+ async def _pump_both(
276
+ client_reader: asyncio.StreamReader,
277
+ client_writer: asyncio.StreamWriter,
278
+ upstream_reader: asyncio.StreamReader,
279
+ upstream_writer: asyncio.StreamWriter,
280
+ ) -> None:
281
+ """两个方向的字节搬运。任一方向结束就整体收尾。"""
282
+
283
+ async def pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
284
+ try:
285
+ while True:
286
+ chunk = await reader.read(CHUNK)
287
+ if not chunk:
288
+ return
289
+ writer.write(chunk)
290
+ await writer.drain()
291
+ except (ConnectionError, TimeoutError):
292
+ return
293
+
294
+ tasks = [
295
+ asyncio.create_task(pipe(client_reader, upstream_writer)),
296
+ asyncio.create_task(pipe(upstream_reader, client_writer)),
297
+ ]
298
+ done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
299
+ for task in pending:
300
+ task.cancel()
301
+ await asyncio.gather(*done, *pending, return_exceptions=True)
302
+
303
+
304
+ async def _write_response(writer: asyncio.StreamWriter, status: int, body: str) -> None:
305
+ payload = body.encode("utf-8")
306
+ reason = {400: "Bad Request", 403: "Forbidden", 431: "Request Header Fields Too Large"}.get(
307
+ status, "Error"
308
+ )
309
+ head = (
310
+ f"HTTP/1.1 {status} {reason}\r\n"
311
+ "Content-Type: text/plain; charset=utf-8\r\n"
312
+ f"Content-Length: {len(payload)}\r\n"
313
+ "Connection: close\r\n\r\n"
314
+ ).encode("latin-1")
315
+ with contextlib.suppress(ConnectionError, TimeoutError):
316
+ writer.write(head + payload)
317
+ await writer.drain()
318
+
319
+
320
+ __all__ = ["MAX_DENIALS", "EgressProxy", "NetworkDenial"]
@@ -0,0 +1,222 @@
1
+ """macOS Seatbelt profile:用 ``sandbox-exec -p <profile>`` 把 bash 关进笼子。
2
+
3
+ profile 是 SBPL(Sandbox Profile Language),一份 ``(deny default)`` 开头的白名单。
4
+ 这里生成三组规则:
5
+
6
+ 1. **基础**:进程创建、信号、``/dev/null``、sysctl 读、目录服务查询、pty。少一条
7
+ 都会让最普通的 ``ls`` 或 ``python3`` 起不来,而症状是「命令莫名失败」,很难查。
8
+ 2. **文件**:默认全盘可读(``file-read*``),写只放工作区、临时目录与用户额外
9
+ 声明的目录,``read-only`` 模式连工作区都不放。
10
+ 3. **网络**:``deny default`` 已经断掉网络;代理模式额外只放行 ``127.0.0.1:<port>``。
11
+
12
+ ## 为什么默认全盘可读
13
+
14
+ 读不是这条边界要守的东西。把读也收窄,``git`` 读不到 ``~/.gitconfig``、语言运行时读不到
15
+ 自己的标准库缓存、``ssh`` 读不到 known_hosts,用户看到的是「沙箱一开,什么都跑不动」。
16
+ 真正的边界是**写**(改坏用户的数据)与**网络**(把数据发出去)。凭证的读由权限引擎的
17
+ 路径规则负责(``**/.env`` 与 ``~/.ssh/**`` 默认 deny),两者分工明确。
18
+
19
+ ## 关于 ``sandbox-exec`` 已弃用
20
+
21
+ Apple 从 macOS 10.15 起标记 ``sandbox-exec`` 为 deprecated,但仍随系统提供;Codex CLI
22
+ 在 macOS 上用的就是它。本模块不依赖任何私有 API:只生成 profile 文本,由系统自带的
23
+ ``sandbox-exec`` 执行。探测失败时由 :mod:`braid_coding_agent.sandbox.backend` 报出原因,
24
+ 不会退回无沙箱执行。
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import os
30
+ from collections.abc import Sequence
31
+
32
+ from braid_coding_agent.sandbox.policy import ReadScope
33
+
34
+ #: ``read = "workspace"`` 时可读的系统目录。只放运行一条命令必需的那些。
35
+ SYSTEM_READ_PATHS: tuple[str, ...] = (
36
+ "/bin",
37
+ "/sbin",
38
+ "/usr",
39
+ "/System",
40
+ "/Library",
41
+ "/opt",
42
+ "/etc",
43
+ "/private/etc",
44
+ "/private/var/db",
45
+ "/private/var/select",
46
+ "/dev",
47
+ "/Applications",
48
+ )
49
+
50
+ #: 基础策略:进程、信号、设备、sysctl、目录服务、pty。
51
+ #: 取值参考 Chrome 的 macOS 沙箱策略与 Codex CLI 的 ``seatbelt_base_policy.sbpl``。
52
+ _BASE_LINES: tuple[str, ...] = (
53
+ "(version 1)",
54
+ "; braid: 默认拒绝,下面逐条放开",
55
+ "(deny default)",
56
+ "(allow process-exec)",
57
+ "(allow process-fork)",
58
+ "(allow signal (target same-sandbox))",
59
+ "(allow process-info* (target same-sandbox))",
60
+ '(allow file-write-data (require-all (path "/dev/null") (vnode-type CHARACTER-DEVICE)))',
61
+ "(allow sysctl-read",
62
+ ' (sysctl-name "hw.activecpu")',
63
+ ' (sysctl-name "hw.machine")',
64
+ ' (sysctl-name "hw.memsize")',
65
+ ' (sysctl-name "hw.ncpu")',
66
+ ' (sysctl-name "hw.logicalcpu")',
67
+ ' (sysctl-name "hw.logicalcpu_max")',
68
+ ' (sysctl-name "hw.physicalcpu")',
69
+ ' (sysctl-name "hw.physicalcpu_max")',
70
+ ' (sysctl-name "hw.pagesize")',
71
+ ' (sysctl-name "hw.cachelinesize")',
72
+ ' (sysctl-name "hw.l1dcachesize")',
73
+ ' (sysctl-name "hw.l2cachesize")',
74
+ ' (sysctl-name "hw.l3cachesize")',
75
+ ' (sysctl-name "hw.cputype")',
76
+ ' (sysctl-name "hw.cpusubtype")',
77
+ ' (sysctl-name "hw.tbfrequency")',
78
+ ' (sysctl-name-prefix "hw.optional.arm.")',
79
+ ' (sysctl-name "hw.packages")',
80
+ ' (sysctl-name "machdep.cpu.brand_string")',
81
+ ' (sysctl-name "kern.argmax")',
82
+ ' (sysctl-name "kern.hostname")',
83
+ ' (sysctl-name "kern.maxfilesperproc")',
84
+ ' (sysctl-name "kern.maxproc")',
85
+ ' (sysctl-name "kern.osproductversion")',
86
+ ' (sysctl-name "kern.osrelease")',
87
+ ' (sysctl-name "kern.ostype")',
88
+ ' (sysctl-name "kern.osversion")',
89
+ ' (sysctl-name "kern.usrstack64")',
90
+ ' (sysctl-name "kern.version")',
91
+ ' (sysctl-name "kern.sysv.semmns")',
92
+ ' (sysctl-name "vm.loadavg")',
93
+ ' (sysctl-name-prefix "hw.perflevel")',
94
+ ' (sysctl-name-prefix "kern.proc.pid.")',
95
+ ")",
96
+ '(allow sysctl-write (sysctl-name "kern.grade_cputype"))',
97
+ '(allow iokit-open (iokit-registry-entry-class "RootDomainUserClient"))',
98
+ "; 查用户名与主目录:ls -l 与 python 的 expanduser 都要它",
99
+ '(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))',
100
+ "(allow ipc-posix-sem)",
101
+ "; openpty:交互式命令与部分运行时需要 pty",
102
+ "(allow pseudo-tty)",
103
+ '(allow file-read* file-write* file-ioctl (literal "/dev/ptmx"))',
104
+ "(allow file-read* file-write*",
105
+ ' (require-all (regex #"^/dev/ttys[0-9]+") (extension "com.apple.sandbox.pty")))',
106
+ '(allow file-ioctl (regex #"^/dev/ttys[0-9]+"))',
107
+ )
108
+
109
+ #: 代理模式下需要额外放行的目录服务:TLS 证书校验与网络配置查询。
110
+ _NETWORK_SERVICE_LINES: tuple[str, ...] = (
111
+ "; 代理模式下仍要能做 TLS 校验与读网络配置(DNS 由代理进程负责,不在这里)",
112
+ "(allow mach-lookup",
113
+ ' (global-name "com.apple.bsd.dirhelper")',
114
+ ' (global-name "com.apple.system.opendirectoryd.membership")',
115
+ ' (global-name "com.apple.SecurityServer")',
116
+ ' (global-name "com.apple.ocspd")',
117
+ ' (global-name "com.apple.trustd.agent")',
118
+ ' (global-name "com.apple.networkd")',
119
+ ' (global-name "com.apple.SystemConfiguration.DNSConfiguration")',
120
+ ' (global-name "com.apple.SystemConfiguration.configd")',
121
+ ")",
122
+ '(allow sysctl-read (sysctl-name-regex #"^net.routetable"))',
123
+ )
124
+
125
+
126
+ def seatbelt_profile(
127
+ *,
128
+ workspace: str,
129
+ read_scope: ReadScope = "all",
130
+ writable: bool = True,
131
+ writable_paths: Sequence[str] = (),
132
+ readable_paths: Sequence[str] = (),
133
+ proxy_port: int | None = None,
134
+ deny_network: bool = False,
135
+ ) -> str:
136
+ """拼出一份完整 profile。
137
+
138
+ :param workspace: 工作目录。``writable`` 为真时它是唯一必然可写的路径。
139
+ :param read_scope: ``"all"`` 全盘可读;``"workspace"`` 只读系统目录、工作区与临时目录。
140
+ :param writable: ``read-only`` 模式传 ``False``。
141
+ :param writable_paths: 工作区之外额外可写的目录(配置里的 ``writable_paths``)。
142
+ :param readable_paths: ``read_scope="workspace"`` 时额外可读的目录。
143
+ :param proxy_port: 代理端口。给了就只放行到 ``127.0.0.1:<port>`` 的出站连接。
144
+ :param deny_network: 显式断网(``network = "deny"``)。``deny default`` 已经断了,
145
+ 这条只是一个可读的标记。
146
+ """
147
+ lines: list[str] = list(_BASE_LINES)
148
+
149
+ lines.append("; 文件读")
150
+ if read_scope == "all":
151
+ lines.append("(allow file-read*)")
152
+ else:
153
+ for path in _unique_paths((*SYSTEM_READ_PATHS, workspace, *readable_paths, *_tmp_paths())):
154
+ lines.append(f"(allow file-read* (subpath {_quote(path)}))")
155
+
156
+ if writable:
157
+ roots = _unique_paths((workspace, *writable_paths, *_tmp_paths()))
158
+ lines.append("; 文件写:只给工作区、临时目录与显式声明的目录")
159
+ for path in roots:
160
+ lines.append(f"(allow file-write* (subpath {_quote(path)}))")
161
+ lines.append("; /dev 下的几个字符设备:命令往 /dev/null 写日志是常态")
162
+ lines.append(
163
+ '(allow file-write* (literal "/dev/null") (literal "/dev/stdout") '
164
+ '(literal "/dev/stderr") (literal "/dev/tty"))'
165
+ )
166
+ lines.append("; 工作区目录本身不允许被 unlink / 改名:rm -rf . 不该抹掉绑定根")
167
+ lines.append(
168
+ f"(deny file-write-unlink (require-all (literal {_quote(workspace)}) "
169
+ "(vnode-type DIRECTORY)))"
170
+ )
171
+ else:
172
+ lines.append("; read-only:除 /dev/null 外没有任何写权限")
173
+ lines.append(
174
+ '(allow file-write* (literal "/dev/null") (literal "/dev/stdout") '
175
+ '(literal "/dev/stderr"))'
176
+ )
177
+
178
+ if deny_network:
179
+ lines.append("; 网络:全断(deny default 已覆盖,这里写明意图)")
180
+ lines.append("(deny network*)")
181
+ elif proxy_port is not None:
182
+ lines.extend(_NETWORK_SERVICE_LINES)
183
+ lines.append("; 网络:只允许连本机代理端口,其余出站一律拒绝")
184
+ for host in ("127.0.0.1", "localhost"):
185
+ lines.append(f'(allow network-outbound (remote ip "{host}:{proxy_port}"))')
186
+ # proxy_port 为 None 且未显式断网:调用方只想要文件边界(network = "allow")。
187
+
188
+ return "\n".join(lines) + "\n"
189
+
190
+
191
+ def _tmp_paths() -> tuple[str, ...]:
192
+ """临时目录。带上 realpath:``/tmp`` 在 macOS 上是 ``/private/tmp`` 的符号链接,
193
+ 只写前者会让 ``mktemp`` 创建的文件被拒绝写入。"""
194
+ candidates = ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"]
195
+ for name in ("TMPDIR", "TMP", "TEMP"):
196
+ value = os.environ.get(name)
197
+ if value:
198
+ candidates.append(value.rstrip("/") or "/")
199
+ candidates.append("/private/var/folders")
200
+ return _unique_paths(candidates)
201
+
202
+
203
+ def _unique_paths(paths: Sequence[str]) -> tuple[str, ...]:
204
+ """归一成绝对路径,并把符号链接目标一并带上;顺序保持,重复去掉。"""
205
+ seen: list[str] = []
206
+ for raw in paths:
207
+ if not raw:
208
+ continue
209
+ absolute = os.path.abspath(os.path.expanduser(raw))
210
+ for item in (absolute, os.path.realpath(absolute)):
211
+ cleaned = item.rstrip("/") or "/"
212
+ if cleaned not in seen:
213
+ seen.append(cleaned)
214
+ return tuple(seen)
215
+
216
+
217
+ def _quote(path: str) -> str:
218
+ """SBPL 字符串字面量:转义反斜杠与双引号。"""
219
+ return '"' + path.replace("\\", "\\\\").replace('"', '\\"') + '"'
220
+
221
+
222
+ __all__ = ["SYSTEM_READ_PATHS", "seatbelt_profile"]
@@ -0,0 +1,31 @@
1
+ """Braid 的 Python SDK:把 HTTP 接口包成对象调用。
2
+
3
+ ```python
4
+ from braid_coding_agent.sdk import BraidClient
5
+
6
+ with BraidClient("http://127.0.0.1:4096", token="...") as client:
7
+ session = client.create_session(name="演示")
8
+ print(client.run(session.id, "介绍一下这个仓库").text)
9
+ ```
10
+
11
+ 同步与异步两个客户端的方法名、参数与返回值一致。事件体的字段由服务端定义,
12
+ SDK 只负责搬运:新增一个事件类型不需要改 SDK。
13
+ """
14
+
15
+ from braid_coding_agent.sdk.async_client import AsyncBraidClient, AsyncEventStream
16
+ from braid_coding_agent.sdk.client import DEFAULT_BASE_URL, BraidClient, EventStream
17
+ from braid_coding_agent.sdk.errors import BraidApiError
18
+ from braid_coding_agent.sdk.events import Event
19
+ from braid_coding_agent.sdk.types import RunResult, Session
20
+
21
+ __all__ = [
22
+ "DEFAULT_BASE_URL",
23
+ "AsyncBraidClient",
24
+ "AsyncEventStream",
25
+ "BraidApiError",
26
+ "BraidClient",
27
+ "Event",
28
+ "EventStream",
29
+ "RunResult",
30
+ "Session",
31
+ ]