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,243 @@
1
+ """界面主题:两套配色、truecolor ANSI 序列与显示宽度工具。
2
+
3
+ ``display_width`` 放在这里,供 ``stream.py`` 的折行与面板对齐共用;主题模块不依赖
4
+ 渲染器,因此没有循环导入。颜色只在 ``RenderStyle.color`` 为真时写入输出,
5
+ 管道与日志采集始终拿到纯文本。
6
+
7
+ ## 主题怎么选
8
+
9
+ ``--theme`` 的默认值是 ``auto``:先读 ``BRAID_THEME``,再用 OSC 11 向终端查询
10
+ 背景色,按亮度选浅色或深色配色;查询不到时默认深色。显式 ``light`` / ``dark``
11
+ 永远优先——auto 的探测会读 stdin,用户已经明确指定时不该冒这个险。
12
+
13
+ 为什么默认深色:浅色配色的正文是近黑色 ``#1f2328``,在深色终端背景上对比度不足
14
+ 2:1,等于看不见;反过来深色配色的浅色正文在浅色背景上同样不可用,但开发终端以
15
+ 深色为主。探测成功时按背景选,探测失败就挑覆盖更广的那一套。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import re
22
+ import select
23
+ import sys
24
+ from collections.abc import Callable, Mapping
25
+ from contextlib import suppress
26
+ from dataclasses import dataclass
27
+
28
+ from wcwidth import wcswidth, wcwidth
29
+
30
+ __all__ = [
31
+ "DARK_THEME",
32
+ "LIGHT_THEME",
33
+ "THEMES",
34
+ "THEME_NAMES",
35
+ "Theme",
36
+ "detect_theme",
37
+ "display_width",
38
+ "pad_to_width",
39
+ "paint",
40
+ "progress_bar",
41
+ "resolve_theme",
42
+ ]
43
+
44
+ _RESET = "\x1b[0m"
45
+
46
+
47
+ @dataclass(slots=True, frozen=True)
48
+ class Theme:
49
+ """一套终端配色。``palette`` 的键是角色名,值是 ``#rrggbb``。"""
50
+
51
+ name: str
52
+ palette: Mapping[str, str]
53
+
54
+ def color(self, role: str) -> str:
55
+ """取角色对应的颜色;未知角色在调用处就地失败。"""
56
+ return self.palette[role]
57
+
58
+
59
+ LIGHT_THEME = Theme(
60
+ "light",
61
+ {
62
+ "bg": "#f7f8fa",
63
+ "panel": "#ffffff",
64
+ "fg": "#1f2328",
65
+ "muted": "#6b7280",
66
+ "accent": "#5b5bd6",
67
+ "user": "#0969da",
68
+ "ok": "#1a7f37",
69
+ "warn": "#9a6700",
70
+ "err": "#cf222e",
71
+ "border": "#d8dee4",
72
+ "sel": "#eef2ff",
73
+ "add_bg": "#e6ffec",
74
+ "del_bg": "#ffebe9",
75
+ },
76
+ )
77
+
78
+ DARK_THEME = Theme(
79
+ "dark",
80
+ {
81
+ "bg": "#16181d",
82
+ "panel": "#1d2027",
83
+ "fg": "#e6e8eb",
84
+ "muted": "#8b949e",
85
+ "accent": "#a78bfa",
86
+ "user": "#79c0ff",
87
+ "ok": "#3fb950",
88
+ "warn": "#d29922",
89
+ "err": "#f85149",
90
+ "border": "#30363d",
91
+ "sel": "#2d2f45",
92
+ "add_bg": "#1a3324",
93
+ "del_bg": "#3a1f22",
94
+ },
95
+ )
96
+
97
+ THEMES: dict[str, Theme] = {"light": LIGHT_THEME, "dark": DARK_THEME}
98
+ #: CLI 可选的三个值。auto 按终端背景探测,探测不到时取深色。
99
+ THEME_NAMES: tuple[str, ...] = ("auto", "light", "dark")
100
+ #: 显式指定主题的环境变量(低优先于命令行)。
101
+ ENV_THEME = "BRAID_THEME"
102
+
103
+ #: OSC 11 的应答形如 ``\x1b]11;rgb:1f1f/1f1f/2828\x07``;颜色分量可能是 2 或 4 位十六进制。
104
+ _OSC11 = re.compile(r"rgb:([0-9a-fA-F]{2,4})/([0-9a-fA-F]{2,4})/([0-9a-fA-F]{2,4})")
105
+ _HEX_RGB = re.compile(r"#([0-9a-fA-F]{6})\b")
106
+
107
+
108
+ def _channel(value: str) -> int:
109
+ """把 2 或 4 位十六进制颜色分量归一到 0-255。"""
110
+ if len(value) == 2:
111
+ return int(value, 16)
112
+ return int(value[:2], 16)
113
+
114
+
115
+ def _background_rgb(reply: str | None) -> tuple[int, int, int] | None:
116
+ """从 OSC 11 应答里解出背景 RGB;不是颜色应答就返回 ``None``。"""
117
+ if not reply:
118
+ return None
119
+ match = _OSC11.search(reply)
120
+ if match:
121
+ return tuple(_channel(part) for part in match.groups()) # type: ignore[return-value]
122
+ match = _HEX_RGB.search(reply)
123
+ if match:
124
+ value = match.group(1)
125
+ return int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16)
126
+ return None
127
+
128
+
129
+ def _is_dark(rgb: tuple[int, int, int]) -> bool:
130
+ """按 sRGB 相对亮度判断背景深浅。阈值 0.5 接近人眼对"深色背景"的判断。"""
131
+ linear: list[float] = []
132
+ for component in rgb:
133
+ scaled = component / 255
134
+ linear.append(scaled / 12.92 if scaled <= 0.04045 else ((scaled + 0.055) / 1.055) ** 2.4)
135
+ red, green, blue = linear[0], linear[1], linear[2]
136
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue < 0.5
137
+
138
+
139
+ def _osc11_probe() -> str | None:
140
+ """向终端查询背景色。非 TTY、超时或答非所问都直接放弃,不阻塞启动。
141
+
142
+ OSC 应答不带换行,规范模式的 stdin 读不到它,所以查询前后短暂切 raw 模式并
143
+ 恢复。逐字节读而不是一次读 64:查询发生在输入循环启动之前,用户可能已经开始
144
+ 打字;第一个字节不是 ESC 就立刻停手,最多吃掉一个字符。
145
+ """
146
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
147
+ return None
148
+ try:
149
+ import termios
150
+ except ImportError: # Windows:没有 termios,放弃探测
151
+ return None
152
+ try:
153
+ fd = sys.stdin.fileno()
154
+ saved = termios.tcgetattr(fd)
155
+ except (OSError, ValueError, termios.error):
156
+ return None
157
+ try:
158
+ # 只关规范输入与回显,保留 ISIG 与输出标志;VMIN=1 / VTIME=0 配合 select。
159
+ raw = list(saved)
160
+ raw[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.ICRNL)
161
+ raw[3] &= ~(termios.ICANON | termios.ECHO)
162
+ cc = list(saved[6])
163
+ cc[termios.VMIN] = 1
164
+ cc[termios.VTIME] = 0
165
+ raw[6] = cc
166
+ termios.tcsetattr(fd, termios.TCSANOW, raw)
167
+ sys.stdout.write("\x1b]11;?\x07")
168
+ sys.stdout.flush()
169
+ data = ""
170
+ while len(data) < 64:
171
+ readable, _, _ = select.select([sys.stdin], [], [], 0.15)
172
+ if not readable:
173
+ return None
174
+ byte = os.read(fd, 1)
175
+ if not byte:
176
+ return None
177
+ data += byte.decode("utf-8", "replace")
178
+ if not data.startswith("\x1b"):
179
+ return None
180
+ if data.endswith("\x07") or data.endswith("\x1b\\"):
181
+ return data
182
+ except (OSError, ValueError, termios.error):
183
+ return None
184
+ finally:
185
+ with suppress(OSError, ValueError, termios.error):
186
+ termios.tcsetattr(fd, termios.TCSANOW, saved)
187
+ return None
188
+
189
+
190
+ def detect_theme(
191
+ *, env: Mapping[str, str] | None = None, probe: Callable[[], str | None] | None = None
192
+ ) -> Theme:
193
+ """按环境变量与终端背景选主题;探测失败取深色。
194
+
195
+ :param env: 环境变量表,缺省读 ``os.environ``;测试可注入普通字典。
196
+ :param probe: OSC 11 查询函数,注入后不再碰真实终端。
197
+ """
198
+ values = os.environ if env is None else env
199
+ override = values.get(ENV_THEME)
200
+ if override in THEMES:
201
+ return THEMES[override]
202
+ rgb = _background_rgb((probe if probe is not None else _osc11_probe)())
203
+ return DARK_THEME if rgb is None or _is_dark(rgb) else LIGHT_THEME
204
+
205
+
206
+ def resolve_theme(
207
+ name: str,
208
+ *,
209
+ env: Mapping[str, str] | None = None,
210
+ probe: Callable[[], str | None] | None = None,
211
+ ) -> Theme:
212
+ """按名字取主题;``auto`` 走 :func:`detect_theme`,未知名字就地失败。"""
213
+ if name == "auto":
214
+ return detect_theme(env=env, probe=probe)
215
+ return THEMES[name]
216
+
217
+
218
+ def display_width(text: str) -> int:
219
+ """字符串在等宽终端里占的列数。控制字符按 1 列算。"""
220
+ width = wcswidth(text)
221
+ return width if width >= 0 else sum(max(wcwidth(char), 1) for char in text)
222
+
223
+
224
+ def pad_to_width(text: str, width: int) -> str:
225
+ """按显示宽度补空格;超长文本保持原样。"""
226
+ return text + " " * max(0, width - display_width(text))
227
+
228
+
229
+ def progress_bar(percent: float, width: int = 20) -> str:
230
+ """生成不带颜色的进度条,颜色由 :func:`paint` 负责。"""
231
+ filled = max(0, min(width, round(width * percent / 100)))
232
+ return "█" * filled + "░" * (width - filled)
233
+
234
+
235
+ def _rgb(value: str) -> tuple[int, int, int]:
236
+ return int(value[1:3], 16), int(value[3:5], 16), int(value[5:7], 16)
237
+
238
+
239
+ def paint(text: str, role: str, theme: Theme, *, bold: bool = False) -> str:
240
+ """用 truecolor 前景色包住一段文字,末尾复位。"""
241
+ red, green, blue = _rgb(theme.color(role))
242
+ prefix = "\x1b[1m" if bold else ""
243
+ return f"{prefix}\x1b[38;2;{red};{green};{blue}m{text}{_RESET}"
@@ -0,0 +1,89 @@
1
+ """操作系统沙箱与网络边界。
2
+
3
+ | 模块 | 职责 |
4
+ |---|---|
5
+ | :mod:`.policy` | 运行模式、网络策略、域名匹配;纯数据与纯函数 |
6
+ | :mod:`.backend` | 后端探测(``sandbox-exec`` / ``bwrap``)与不可用时的修复建议 |
7
+ | :mod:`.seatbelt` | macOS SBPL profile 生成 |
8
+ | :mod:`.bubblewrap` | Linux ``bwrap`` argv 生成 |
9
+ | :mod:`.proxy` | 本地出口代理:按域名放行、拒绝记录 |
10
+ | :mod:`.operations` | :class:`SandboxOperations`:把上面几件装进 ``ShellOperations`` |
11
+
12
+ 对外只导出装配入口与两个数据类型。CLI 需要的是「给一份配置,还我一个能跑命令的
13
+ 对象」;其余细节(profile 文本、argv 顺序)属于实现,测试直接进子模块取。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import importlib
19
+ from typing import TYPE_CHECKING
20
+
21
+ if TYPE_CHECKING:
22
+ from braid_coding_agent.sandbox.backend import (
23
+ SandboxBackend,
24
+ SandboxUnavailableError,
25
+ detect_backend,
26
+ )
27
+ from braid_coding_agent.sandbox.operations import (
28
+ SandboxInfo,
29
+ SandboxOperations,
30
+ build_sandbox_operations,
31
+ )
32
+ from braid_coding_agent.sandbox.policy import (
33
+ NETWORK_MODES,
34
+ SANDBOX_MODES,
35
+ NetworkMode,
36
+ NetworkPolicy,
37
+ SandboxMode,
38
+ SandboxSettings,
39
+ dedupe_domains,
40
+ )
41
+ from braid_coding_agent.sandbox.proxy import EgressProxy, NetworkDenial
42
+
43
+ _LAZY_EXPORTS: dict[str, str] = {
44
+ "SandboxBackend": "braid_coding_agent.sandbox.backend",
45
+ "SandboxUnavailableError": "braid_coding_agent.sandbox.backend",
46
+ "detect_backend": "braid_coding_agent.sandbox.backend",
47
+ "SandboxInfo": "braid_coding_agent.sandbox.operations",
48
+ "SandboxOperations": "braid_coding_agent.sandbox.operations",
49
+ "build_sandbox_operations": "braid_coding_agent.sandbox.operations",
50
+ "NETWORK_MODES": "braid_coding_agent.sandbox.policy",
51
+ "SANDBOX_MODES": "braid_coding_agent.sandbox.policy",
52
+ "NetworkMode": "braid_coding_agent.sandbox.policy",
53
+ "NetworkPolicy": "braid_coding_agent.sandbox.policy",
54
+ "SandboxMode": "braid_coding_agent.sandbox.policy",
55
+ "SandboxSettings": "braid_coding_agent.sandbox.policy",
56
+ "dedupe_domains": "braid_coding_agent.sandbox.policy",
57
+ "EgressProxy": "braid_coding_agent.sandbox.proxy",
58
+ "NetworkDenial": "braid_coding_agent.sandbox.proxy",
59
+ }
60
+
61
+
62
+ def __getattr__(name: str) -> object:
63
+ """按需导入导出名。"""
64
+ module_name = _LAZY_EXPORTS.get(name)
65
+ if module_name is None:
66
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
67
+ module = importlib.import_module(module_name)
68
+ value = getattr(module, name)
69
+ globals()[name] = value
70
+ return value
71
+
72
+
73
+ __all__ = [
74
+ "NETWORK_MODES",
75
+ "SANDBOX_MODES",
76
+ "EgressProxy",
77
+ "NetworkDenial",
78
+ "NetworkMode",
79
+ "NetworkPolicy",
80
+ "SandboxBackend",
81
+ "SandboxInfo",
82
+ "SandboxMode",
83
+ "SandboxOperations",
84
+ "SandboxSettings",
85
+ "SandboxUnavailableError",
86
+ "build_sandbox_operations",
87
+ "dedupe_domains",
88
+ "detect_backend",
89
+ ]
@@ -0,0 +1,184 @@
1
+ """后端探测:这台机器到底能不能把进程关进笼子。
2
+
3
+ 探测**不是** ``shutil.which``。macOS 27 上 ``/usr/bin/sandbox-exec`` 还在,但应用任何
4
+ profile 都直接返回 ``sandbox_apply: Operation not permitted``(虚拟化环境、MDM 策略与
5
+ App Sandbox 都会造成这一结果);Linux 上 ``bwrap`` 装好了却因为不允许非特权用户命名空间
6
+ 而失败的情况同样常见。只查文件存在,等于把「沙箱已经生效」这句话变成一句谎。
7
+
8
+ 所以每个后端都要跑一次真实的最小调用:
9
+
10
+ - macOS:``sandbox-exec -p "(version 1)(allow default)" /usr/bin/true``
11
+ - Linux:``bwrap --unshare-user --unshare-net --ro-bind / / /bin/true``
12
+
13
+ 失败时 :class:`SandboxUnavailableError` 带上后端名、原始错误与可执行的修复建议。
14
+ 调用方(CLI)把它翻成退出码 1——**不允许静默退回无沙箱执行**,那会让用户以为自己在
15
+ 沙箱里,而实际上没有。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Literal, NoReturn
26
+
27
+ from braid_coding_agent.sandbox.policy import BackendName
28
+
29
+ #: 探测超时(秒)。正常机器上是毫秒级;卡住说明系统调用在等一个不会来的应答。
30
+ PROBE_TIMEOUT_SECONDS = 10.0
31
+
32
+
33
+ class SandboxUnavailableError(RuntimeError):
34
+ """请求了内核沙箱,但这台机器给不出来。CLI 用它作为启动失败的原因。"""
35
+
36
+ def __init__(self, *, backend: str, reason: str, hint: str) -> None:
37
+ super().__init__(reason)
38
+ self.backend = backend
39
+ self.reason = reason
40
+ self.hint = hint
41
+
42
+ def message(self) -> str:
43
+ """给用户看的一行结论 + 一段修复建议。"""
44
+ return f"沙箱不可用({self.backend}):{self.reason}\n修复方式:{self.hint}"
45
+
46
+
47
+ @dataclass(slots=True, frozen=True)
48
+ class SandboxBackend:
49
+ """一个可用的后端。``executable`` 是最终执行的绝对路径。"""
50
+
51
+ name: Literal["seatbelt", "bubblewrap"]
52
+ executable: str
53
+
54
+ def probe(self) -> str | None:
55
+ """再探一次(幂等)。返回 ``None`` 表示可用,否则是不可用原因。"""
56
+ if self.name == "seatbelt":
57
+ return probe_seatbelt(self.executable)
58
+ return probe_bubblewrap(self.executable)
59
+
60
+
61
+ def probe_seatbelt(executable: str) -> str | None:
62
+ """用最小 profile 起一个 ``true``。失败原因取 stderr 的第一行有用信息。"""
63
+ return _run_probe(executable, ["-p", "(version 1)(allow default)", "/usr/bin/true"], "seatbelt")
64
+
65
+
66
+ def probe_bubblewrap(executable: str) -> str | None:
67
+ """按 Codex 的探测方式起一个 ``/bin/true``:同时验证 bwrap 与用户命名空间。"""
68
+ return _run_probe(
69
+ executable,
70
+ ["--unshare-user", "--unshare-net", "--ro-bind", "/", "/", "/bin/true"],
71
+ "bubblewrap",
72
+ )
73
+
74
+
75
+ def _run_probe(executable: str, argv: list[str], backend: str) -> str | None:
76
+ try:
77
+ # 固定 argv,无 shell 展开,不引入注入面。
78
+ completed = subprocess.run(
79
+ [executable, *argv],
80
+ capture_output=True,
81
+ timeout=PROBE_TIMEOUT_SECONDS,
82
+ check=False,
83
+ )
84
+ except subprocess.TimeoutExpired:
85
+ return f"{executable} 在 {PROBE_TIMEOUT_SECONDS:g} 秒内没有返回({backend} 探测超时)"
86
+ except OSError as exc:
87
+ return f"无法执行 {executable}:{exc}"
88
+ if completed.returncode == 0:
89
+ return None
90
+ stderr = completed.stderr.decode("utf-8", "replace").strip()
91
+ detail = _first_meaningful_line(stderr) or f"退出码 {completed.returncode}"
92
+ return f"{Path(executable).name} 探测失败:{detail}"
93
+
94
+
95
+ def _first_meaningful_line(text: str) -> str:
96
+ for line in text.splitlines():
97
+ stripped = line.strip()
98
+ if stripped:
99
+ return stripped
100
+ return ""
101
+
102
+
103
+ def detect_backend(
104
+ preferred: BackendName = "auto",
105
+ *,
106
+ platform: str | None = None,
107
+ executable: str | None = None,
108
+ ) -> SandboxBackend:
109
+ """挑一个能用的后端;一个都没有时抛 :class:`SandboxUnavailableError`。
110
+
111
+ ``auto`` 只按当前平台试它自己的那一个:跨平台的候选(在 macOS 上找 bwrap)没有
112
+ 意义,两个平台的隔离语义差别大到不能互换。
113
+ """
114
+ current = platform if platform is not None else sys.platform
115
+ if current.startswith("win"):
116
+ raise SandboxUnavailableError(
117
+ backend="windows",
118
+ reason="Windows 原生沙箱尚未实现(S37 首版要求 WSL)",
119
+ hint=(
120
+ "在 WSL2 里运行 braid:`wsl --install`,进入 WSL 后安装 bubblewrap,"
121
+ "再在那里跑 `braid --sandbox workspace-write`;或改用 `--sandbox network-only`"
122
+ ),
123
+ )
124
+
125
+ if current == "darwin":
126
+ name: Literal["seatbelt", "bubblewrap"] = "seatbelt"
127
+ program = "sandbox-exec"
128
+ else:
129
+ name = "bubblewrap"
130
+ program = "bwrap"
131
+
132
+ if preferred != "auto" and preferred != name:
133
+ raise SandboxUnavailableError(
134
+ backend=str(preferred),
135
+ reason=f"当前平台 {current} 不支持后端 {preferred}(只有 {name} 可用)",
136
+ hint=_INSTALL_HINTS[name],
137
+ )
138
+
139
+ resolved = executable if executable is not None else shutil.which(program)
140
+ if resolved is None:
141
+ raise SandboxUnavailableError(
142
+ backend=name, reason=f"PATH 上找不到 {program}", hint=_INSTALL_HINTS[name]
143
+ )
144
+ backend = SandboxBackend(name=name, executable=resolved)
145
+ failure = backend.probe()
146
+ if failure is not None:
147
+ raise SandboxUnavailableError(backend=name, reason=failure, hint=_INSTALL_HINTS[name])
148
+ return backend
149
+
150
+
151
+ _INSTALL_HINTS: dict[str, str] = {
152
+ "seatbelt": (
153
+ "sandbox-exec 随 macOS 提供,不需要安装。它在这里无法应用 profile,通常是因为"
154
+ "进程本身已在另一个沙箱里(虚拟化环境、MDM 策略或 App 沙箱会禁止嵌套)。"
155
+ '在普通终端里重试,或改用 `sandbox.mode = "network-only"` 只做出口过滤'
156
+ ),
157
+ "bubblewrap": (
158
+ "安装 bubblewrap:Debian/Ubuntu `sudo apt install bubblewrap`,"
159
+ "Fedora `sudo dnf install bubblewrap`,Arch `sudo pacman -S bubblewrap`;"
160
+ "并确认允许非特权用户命名空间(`sysctl kernel.unprivileged_userns_clone=1`)"
161
+ ),
162
+ }
163
+
164
+
165
+ def install_hint(backend: str) -> str:
166
+ """某个后端的安装/修复建议。未知后端返回一句通用说明。"""
167
+ return _INSTALL_HINTS.get(backend, "请检查平台的沙箱工具是否安装并可用")
168
+
169
+
170
+ def raise_unavailable(backend: str, reason: str) -> NoReturn:
171
+ """给调用方一个统一的抛法,避免各处自己拼 hint。"""
172
+ raise SandboxUnavailableError(backend=backend, reason=reason, hint=install_hint(backend))
173
+
174
+
175
+ __all__ = [
176
+ "PROBE_TIMEOUT_SECONDS",
177
+ "SandboxBackend",
178
+ "SandboxUnavailableError",
179
+ "detect_backend",
180
+ "install_hint",
181
+ "probe_bubblewrap",
182
+ "probe_seatbelt",
183
+ "raise_unavailable",
184
+ ]
@@ -0,0 +1,96 @@
1
+ """Linux bubblewrap:用命名空间拼出「只读系统 + 可写工作区 + 无网络」的执行环境。
2
+
3
+ ``bwrap`` 是最贴近内核原语的沙箱工具:它不生成策略文本,只做一串命名空间操作。
4
+ 这里构造的 argv 与 Codex CLI 的做法一致:
5
+
6
+ ```text
7
+ bwrap --unshare-user --unshare-pid --unshare-uts --unshare-ipc --unshare-cgroup-try
8
+ --die-with-parent --new-session
9
+ --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp
10
+ --bind <workspace> <workspace> --bind <extra> <extra>
11
+ --chdir <cwd> -- <command...>
12
+ ```
13
+
14
+ ``--ro-bind / /`` 先挂一份只读根,再用 ``--bind`` 把工作区挂回可写——这是「除工作区
15
+ 外全只读」的最短写法。``--die-with-parent`` 保证父进程被取消时沙箱里不会留下孤儿。
16
+
17
+ ## Linux 上网络只能全断或全通
18
+
19
+ 要在「新的网络命名空间」里访问宿主机上的出口代理,需要 veth 配对与 CAP_NET_ADMIN;
20
+ ``bwrap`` 没有提供这条路径。所以:
21
+
22
+ - ``network = "deny"``:``--unshare-net``,内核层面彻底断网(**强边界**)。
23
+ - ``network = "proxy"``:共享宿主机网络命名空间,域名过滤由代理的 ``HTTP_PROXY``
24
+ 环境变量完成(**协作式**)。这一差别会写进 ``bash`` 的 ``sandbox`` 字段,用户不会
25
+ 把「能绕过」误当成「不能绕过」。需要强边界就把 ``network`` 设成 ``deny``。
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ from collections.abc import Sequence
32
+
33
+ from braid_coding_agent.sandbox.policy import ReadScope
34
+ from braid_coding_agent.sandbox.seatbelt import SYSTEM_READ_PATHS
35
+
36
+ #: 除去后面要重新挂载的目录,其余全部只读绑定。
37
+ _BASE_FLAGS: tuple[str, ...] = (
38
+ "--unshare-user",
39
+ "--unshare-pid",
40
+ "--unshare-uts",
41
+ "--unshare-ipc",
42
+ "--unshare-cgroup-try",
43
+ "--die-with-parent",
44
+ "--new-session",
45
+ )
46
+
47
+
48
+ def bubblewrap_argv(
49
+ *,
50
+ workspace: str,
51
+ chdir: str,
52
+ read_scope: ReadScope = "all",
53
+ writable: bool = True,
54
+ writable_paths: Sequence[str] = (),
55
+ readable_paths: Sequence[str] = (),
56
+ unshare_net: bool = False,
57
+ ) -> list[str]:
58
+ """构造 ``bwrap`` 的完整 argv,以 ``--`` 结尾(后面接真正要跑的命令)。"""
59
+ argv: list[str] = ["bwrap", *_BASE_FLAGS]
60
+ if unshare_net:
61
+ argv.append("--unshare-net")
62
+
63
+ if read_scope == "all":
64
+ argv.extend(["--ro-bind", "/", "/"])
65
+ else:
66
+ for path in _existing((*SYSTEM_READ_PATHS, workspace, *readable_paths)):
67
+ argv.extend(["--ro-bind", path, path])
68
+
69
+ # /dev 与 /proc 必须是新挂载:只读根里的它们不可用(没有 pty、没有 /proc/self)。
70
+ argv.extend(["--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp"])
71
+
72
+ bind_flag = "--bind" if writable else "--ro-bind"
73
+ # 工作区无条件绑定:它是 ``--chdir`` 的目标,不绑就等于让 bwrap 在启动时失败。
74
+ argv.extend([bind_flag, workspace, workspace])
75
+ for path in _existing(writable_paths if writable else ()):
76
+ if os.path.abspath(path) != workspace:
77
+ argv.extend([bind_flag, path, path])
78
+
79
+ argv.extend(["--chdir", chdir, "--"])
80
+ return argv
81
+
82
+
83
+ def _existing(paths: Sequence[str]) -> tuple[str, ...]:
84
+ """只绑定真实存在的目录;不存在的可写目录由调用方保证已创建。"""
85
+ seen: list[str] = []
86
+ for raw in paths:
87
+ if not raw:
88
+ continue
89
+ absolute = os.path.abspath(os.path.expanduser(raw))
90
+ if absolute in seen or not os.path.exists(absolute):
91
+ continue
92
+ seen.append(absolute)
93
+ return tuple(seen)
94
+
95
+
96
+ __all__ = ["bubblewrap_argv"]