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.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""``SandboxOperations``:在 ``ShellOperations`` 这一层套上技术边界。
|
|
2
|
+
|
|
3
|
+
选这一层有两个原因:
|
|
4
|
+
|
|
5
|
+
1. 工具只认 :class:`~braid_coding_agent.tools.operations.ShellOperations`。包装它,
|
|
6
|
+
``bash`` 的实现一行都不用改,换会话、换 ``cwd``、换 shell 都是同一个对象。
|
|
7
|
+
2. 边界属于「执行」而不是「策略」。权限引擎回答「要不要问用户」,这里回答
|
|
8
|
+
「放行了之后,最多能做到什么」。两句话写在两个地方,调试时不会互相甩锅。
|
|
9
|
+
|
|
10
|
+
```text
|
|
11
|
+
PermissionEngine.authorize → ask / allow / deny
|
|
12
|
+
↓ allow
|
|
13
|
+
SandboxOperations.exec → sandbox-exec -p <profile> bash -c <cmd>
|
|
14
|
+
↓ 或 bwrap ... -- bash -c <cmd>
|
|
15
|
+
LocalShellOperations.exec → 子进程,输出流回 bash 工具
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## ``network-only`` 为什么存在
|
|
19
|
+
|
|
20
|
+
内核沙箱要求系统提供一个能用的后端。macOS 27 上 ``sandbox-exec`` 已经会出现
|
|
21
|
+
``sandbox_apply: Operation not permitted``(App Sandbox 与虚拟化环境都会触发),
|
|
22
|
+
Linux 上也可能没有 ``bwrap``。此时把整个 ``bash`` 关掉太粗暴,把它当无事发生又太
|
|
23
|
+
不诚实。``network-only`` 是第三条路:文件不受限,出口仍然按域名过滤,并且
|
|
24
|
+
:class:`SandboxInfo` 会明说 ``filesystem = "unconfined"``。
|
|
25
|
+
|
|
26
|
+
## 结果里为什么要带 ``sandbox`` 字段
|
|
27
|
+
|
|
28
|
+
模型看不到进程边界。``curl`` 被代理拒绝时,它拿到的只有 ``exit code 1``。把
|
|
29
|
+
模式、后端、网络策略与被拒绝的主机写进工具结果,模型下一回合就能自己改方案
|
|
30
|
+
(换域名、请用户加白名单、改用只读信息),而不是反复重试同一条命令。
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import os
|
|
36
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
37
|
+
from dataclasses import dataclass
|
|
38
|
+
|
|
39
|
+
from braid_ai.cancel import CancelToken
|
|
40
|
+
from braid_ai.types import JsonValue
|
|
41
|
+
from braid_coding_agent.sandbox.backend import SandboxBackend, detect_backend
|
|
42
|
+
from braid_coding_agent.sandbox.bubblewrap import bubblewrap_argv
|
|
43
|
+
from braid_coding_agent.sandbox.policy import (
|
|
44
|
+
FilesystemScope,
|
|
45
|
+
NetworkMode,
|
|
46
|
+
NetworkPolicy,
|
|
47
|
+
SandboxMode,
|
|
48
|
+
SandboxSettings,
|
|
49
|
+
)
|
|
50
|
+
from braid_coding_agent.sandbox.proxy import EgressProxy, NetworkDenial
|
|
51
|
+
from braid_coding_agent.sandbox.seatbelt import seatbelt_profile
|
|
52
|
+
from braid_coding_agent.tools.operations import LocalShellOperations, ShellOperations
|
|
53
|
+
|
|
54
|
+
#: 代理相关环境变量。大小写两套都写:curl 读小写优先,很多 Python 库读大写。
|
|
55
|
+
_PROXY_ENV_KEYS: tuple[str, ...] = (
|
|
56
|
+
"HTTP_PROXY",
|
|
57
|
+
"HTTPS_PROXY",
|
|
58
|
+
"ALL_PROXY",
|
|
59
|
+
"http_proxy",
|
|
60
|
+
"https_proxy",
|
|
61
|
+
"all_proxy",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(slots=True, frozen=True)
|
|
66
|
+
class SandboxInfo:
|
|
67
|
+
"""一次运行实际生效的边界。写进 ``bash`` 结果、``/sandbox`` 与提示词之外的地方。"""
|
|
68
|
+
|
|
69
|
+
mode: SandboxMode
|
|
70
|
+
backend: str
|
|
71
|
+
filesystem: FilesystemScope
|
|
72
|
+
network: NetworkMode
|
|
73
|
+
proxy: str | None = None
|
|
74
|
+
note: str | None = None
|
|
75
|
+
|
|
76
|
+
def to_json(self) -> dict[str, JsonValue]:
|
|
77
|
+
payload: dict[str, JsonValue] = {
|
|
78
|
+
"mode": self.mode,
|
|
79
|
+
"backend": self.backend,
|
|
80
|
+
"filesystem": self.filesystem,
|
|
81
|
+
"network": self.network,
|
|
82
|
+
}
|
|
83
|
+
if self.proxy is not None:
|
|
84
|
+
payload["proxy"] = self.proxy
|
|
85
|
+
if self.note is not None:
|
|
86
|
+
payload["note"] = self.note
|
|
87
|
+
return payload
|
|
88
|
+
|
|
89
|
+
def summary(self) -> str:
|
|
90
|
+
"""一行给终端看的话:``workspace-write · seatbelt · 网络 proxy``。"""
|
|
91
|
+
parts = [self.mode, self.backend, f"网络 {self.network}"]
|
|
92
|
+
if self.proxy is not None:
|
|
93
|
+
parts.append(self.proxy)
|
|
94
|
+
return " · ".join(parts)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class SandboxOperations:
|
|
98
|
+
"""把命令送进沙箱执行。构造后先 ``await start()``,用完 ``await close()``。"""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
settings: SandboxSettings,
|
|
103
|
+
*,
|
|
104
|
+
workspace: str,
|
|
105
|
+
backend: SandboxBackend | None = None,
|
|
106
|
+
proxy: EgressProxy | None = None,
|
|
107
|
+
shell: str = "bash",
|
|
108
|
+
local: ShellOperations | None = None,
|
|
109
|
+
) -> None:
|
|
110
|
+
self._settings = settings
|
|
111
|
+
self._workspace = os.path.abspath(workspace)
|
|
112
|
+
self._backend = backend
|
|
113
|
+
self._proxy = proxy
|
|
114
|
+
self._shell = shell
|
|
115
|
+
self._local: ShellOperations = (
|
|
116
|
+
local if local is not None else LocalShellOperations(shell=shell)
|
|
117
|
+
)
|
|
118
|
+
self._started = False
|
|
119
|
+
|
|
120
|
+
# ---------------------------------------------------------------- 生命周期
|
|
121
|
+
|
|
122
|
+
async def start(self) -> None:
|
|
123
|
+
"""起代理、探测后端并拼好 argv 前缀。可重复调用。"""
|
|
124
|
+
if self._started:
|
|
125
|
+
return
|
|
126
|
+
if self._proxy is not None:
|
|
127
|
+
await self._proxy.start()
|
|
128
|
+
if self._backend is not None:
|
|
129
|
+
self._local = LocalShellOperations(shell=self._shell, prefix=self.command_prefix())
|
|
130
|
+
self._started = True
|
|
131
|
+
|
|
132
|
+
async def close(self) -> None:
|
|
133
|
+
if self._proxy is not None:
|
|
134
|
+
await self._proxy.close()
|
|
135
|
+
self._started = False
|
|
136
|
+
|
|
137
|
+
# ------------------------------------------------------------------ 判定面
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def settings(self) -> SandboxSettings:
|
|
141
|
+
return self._settings
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def workspace(self) -> str:
|
|
145
|
+
return self._workspace
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def policy(self) -> NetworkPolicy | None:
|
|
149
|
+
"""出口代理正在用的判定表。``None`` 表示本次运行没有出口过滤。"""
|
|
150
|
+
return self._proxy.policy if self._proxy is not None else None
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def info(self) -> SandboxInfo:
|
|
154
|
+
return SandboxInfo(
|
|
155
|
+
mode=self._settings.mode,
|
|
156
|
+
backend=self._backend.name if self._backend is not None else "none",
|
|
157
|
+
filesystem=self._settings.filesystem_scope,
|
|
158
|
+
network=self._settings.network,
|
|
159
|
+
proxy=self._proxy.url if self._proxy is not None and self._proxy.port else None,
|
|
160
|
+
note=self._note(),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def take_denials(self) -> tuple[NetworkDenial, ...]:
|
|
164
|
+
"""取走上次执行以来被代理拒绝的出站连接。"""
|
|
165
|
+
if self._proxy is None:
|
|
166
|
+
return ()
|
|
167
|
+
return self._proxy.take_denials()
|
|
168
|
+
|
|
169
|
+
# ------------------------------------------------------------------- 执行
|
|
170
|
+
|
|
171
|
+
async def exec(
|
|
172
|
+
self,
|
|
173
|
+
command: str,
|
|
174
|
+
cwd: str,
|
|
175
|
+
*,
|
|
176
|
+
on_data: Callable[[bytes], None],
|
|
177
|
+
timeout: float | None,
|
|
178
|
+
signal: CancelToken | None,
|
|
179
|
+
env: Mapping[str, str] | None,
|
|
180
|
+
) -> int:
|
|
181
|
+
"""与 :meth:`ShellOperations.exec` 同形,额外注入代理与标记环境变量。"""
|
|
182
|
+
if not self._started:
|
|
183
|
+
await self.start()
|
|
184
|
+
return await self._local.exec(
|
|
185
|
+
command,
|
|
186
|
+
cwd,
|
|
187
|
+
on_data=on_data,
|
|
188
|
+
timeout=timeout,
|
|
189
|
+
signal=signal,
|
|
190
|
+
env=self._child_env(env),
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
# ------------------------------------------------------------------- 内部
|
|
194
|
+
|
|
195
|
+
def _child_env(self, env: Mapping[str, str] | None) -> Mapping[str, str]:
|
|
196
|
+
"""在调用方给的环境上补代理变量与 ``BRAID_SANDBOX``。
|
|
197
|
+
|
|
198
|
+
不设 ``NO_PROXY``:绕过代理的例外会让「按域名放行」出现一条静默的旁路,
|
|
199
|
+
而且回环地址本来就不该是出站目标。需要访问本机服务时把主机加进允许列表。
|
|
200
|
+
"""
|
|
201
|
+
merged: dict[str, str] = dict(os.environ if env is None else env)
|
|
202
|
+
merged["BRAID_SANDBOX"] = self._settings.mode
|
|
203
|
+
if self._proxy is not None and self._proxy.port:
|
|
204
|
+
for key in _PROXY_ENV_KEYS:
|
|
205
|
+
merged[key] = self._proxy.url
|
|
206
|
+
return merged
|
|
207
|
+
|
|
208
|
+
def command_prefix(self) -> tuple[str, ...]:
|
|
209
|
+
"""本次运行加在 ``bash`` 之前的 argv。没有内核后端时是空元组。
|
|
210
|
+
|
|
211
|
+
公开它有两个用处:``start()`` 用它构造执行器;排查"沙箱到底有没有生效"时,
|
|
212
|
+
把这段 argv 打出来比读 profile 快得多(``/sandbox`` 与测试都用它)。
|
|
213
|
+
"""
|
|
214
|
+
if self._backend is None:
|
|
215
|
+
return ()
|
|
216
|
+
if self._backend.name == "seatbelt":
|
|
217
|
+
profile = seatbelt_profile(
|
|
218
|
+
workspace=self._workspace,
|
|
219
|
+
read_scope=self._settings.read,
|
|
220
|
+
writable=self._settings.mode == "workspace-write",
|
|
221
|
+
writable_paths=self._writable_roots(),
|
|
222
|
+
readable_paths=self._settings.readable_paths,
|
|
223
|
+
proxy_port=self._proxy.port if self._proxy is not None else None,
|
|
224
|
+
# 有代理时"全断"由代理返回 403 完成:内核只放行代理端口,出口仍然为零,
|
|
225
|
+
# 但模型能拿到"为什么被拒"。没有代理(network = "allow" 不会走到这里)
|
|
226
|
+
# 才退回内核级断网。
|
|
227
|
+
deny_network=self._settings.network == "deny" and self._proxy is None,
|
|
228
|
+
)
|
|
229
|
+
return (self._backend.executable, "-p", profile)
|
|
230
|
+
|
|
231
|
+
return tuple(
|
|
232
|
+
bubblewrap_argv(
|
|
233
|
+
workspace=self._workspace,
|
|
234
|
+
chdir=self._workspace,
|
|
235
|
+
read_scope=self._settings.read,
|
|
236
|
+
writable=self._settings.mode == "workspace-write",
|
|
237
|
+
writable_paths=self._writable_roots(),
|
|
238
|
+
readable_paths=self._settings.readable_paths,
|
|
239
|
+
unshare_net=self._settings.network == "deny",
|
|
240
|
+
)
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
def _writable_roots(self) -> tuple[str, ...]:
|
|
244
|
+
"""工作区之外还允许写的目录:配置里声明的 + 临时目录。
|
|
245
|
+
|
|
246
|
+
临时目录必须带上:``mktemp``、编译器的中间文件、``pip`` 的构建目录都在那里,
|
|
247
|
+
少一条会让大量正常命令以「Permission denied」失败。
|
|
248
|
+
"""
|
|
249
|
+
roots = [*self._settings.writable_paths]
|
|
250
|
+
for name in ("TMPDIR", "TMP", "TEMP"):
|
|
251
|
+
value = os.environ.get(name)
|
|
252
|
+
if value:
|
|
253
|
+
roots.append(value)
|
|
254
|
+
return tuple(roots)
|
|
255
|
+
|
|
256
|
+
def _note(self) -> str | None:
|
|
257
|
+
if self._settings.mode == "network-only":
|
|
258
|
+
return "仅出口过滤:文件系统不受限,代理只拦得住遵守 HTTP(S)_PROXY 的程序"
|
|
259
|
+
if (
|
|
260
|
+
self._backend is not None
|
|
261
|
+
and self._backend.name == "bubblewrap"
|
|
262
|
+
and self._settings.network == "proxy"
|
|
263
|
+
):
|
|
264
|
+
return (
|
|
265
|
+
"Linux 上内核沙箱无法只放行代理端口,域名过滤依赖代理环境变量;"
|
|
266
|
+
'需要硬边界请把 network 设成 "deny"'
|
|
267
|
+
)
|
|
268
|
+
return None
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
async def build_sandbox_operations(
|
|
272
|
+
settings: SandboxSettings,
|
|
273
|
+
*,
|
|
274
|
+
workspace: str,
|
|
275
|
+
model_hosts: Sequence[str] = (),
|
|
276
|
+
shell: str = "bash",
|
|
277
|
+
platform: str | None = None,
|
|
278
|
+
) -> SandboxOperations | None:
|
|
279
|
+
"""按配置装配沙箱。``mode = "off"`` 返回 ``None``(保持今天的行为)。
|
|
280
|
+
|
|
281
|
+
:raises SandboxUnavailableError: 配置要求内核沙箱但后端不可用。调用方必须让
|
|
282
|
+
进程停下——静默退回无沙箱执行是最糟的一种「成功」。
|
|
283
|
+
"""
|
|
284
|
+
if not settings.enabled:
|
|
285
|
+
return None
|
|
286
|
+
backend = (
|
|
287
|
+
detect_backend(settings.backend, platform=platform, executable=settings.executable)
|
|
288
|
+
if settings.needs_kernel_backend
|
|
289
|
+
else None
|
|
290
|
+
)
|
|
291
|
+
proxy: EgressProxy | None = None
|
|
292
|
+
if settings.network in ("proxy", "deny"):
|
|
293
|
+
proxy = EgressProxy(settings.network_policy(model_hosts))
|
|
294
|
+
operations = SandboxOperations(
|
|
295
|
+
settings, workspace=workspace, backend=backend, proxy=proxy, shell=shell
|
|
296
|
+
)
|
|
297
|
+
await operations.start()
|
|
298
|
+
return operations
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
__all__ = ["SandboxInfo", "SandboxOperations", "build_sandbox_operations"]
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""沙箱策略:一次运行允许「写到哪里」与「连到哪里」。
|
|
2
|
+
|
|
3
|
+
策略与执行机制分开。:class:`SandboxSettings` 只描述意图——运行模式、网络策略、
|
|
4
|
+
可写与可读的额外目录;**怎么实现**由后端决定(macOS 的 ``sandbox-exec``、
|
|
5
|
+
Linux 的 ``bubblewrap``,或者只靠出口代理的 ``network-only``)。分开的理由和
|
|
6
|
+
权限引擎一致:同一份策略要能在两个平台上都说得清,而两者的实现语言毫无相似之处。
|
|
7
|
+
|
|
8
|
+
## 三个层次
|
|
9
|
+
|
|
10
|
+
```text
|
|
11
|
+
mode = "off" 不干预:bash 与今天一样以当前用户权限运行
|
|
12
|
+
mode = "network-only" 只做出口过滤:代理进程按域名放行,靠代理环境变量生效
|
|
13
|
+
mode = "workspace-write" 内核沙箱:写限于工作区与临时目录,网络只留代理端口
|
|
14
|
+
mode = "read-only" 内核沙箱:连工作区都不可写
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
``network-only`` 是给「内核沙箱在这台机器上不可用」准备的中间档。它拦得住遵守
|
|
18
|
+
``HTTP_PROXY`` 的程序(curl、git、npm、pip、requests),拦不住直接开 socket 的程序。
|
|
19
|
+
这句话必须写进文档与工具结果:把协作式过滤说成安全边界,比不做过滤更危险。
|
|
20
|
+
|
|
21
|
+
## 网络策略的默认值
|
|
22
|
+
|
|
23
|
+
``network = "proxy"``,允许列表的起点是**模型 API 域名**(从 provider 的 ``base_url``
|
|
24
|
+
取主机名,由 :meth:`SandboxSettings.network_policy` 注入)。理由是失败关闭的另一半:
|
|
25
|
+
沙箱开启时,``bash`` 里的 ``curl`` 默认什么都不通,除非用户明确把域名加进
|
|
26
|
+
``allow_domains``。``network = "deny"`` 连代理端口都不需要,直接全断。
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from collections.abc import Iterable, Sequence
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from typing import Literal
|
|
34
|
+
|
|
35
|
+
from braid_coding_agent.netsafe import normalize_host
|
|
36
|
+
|
|
37
|
+
type SandboxMode = Literal["off", "network-only", "workspace-write", "read-only"]
|
|
38
|
+
type NetworkMode = Literal["deny", "proxy", "allow"]
|
|
39
|
+
type ReadScope = Literal["all", "workspace"]
|
|
40
|
+
type BackendName = Literal["auto", "seatbelt", "bubblewrap"]
|
|
41
|
+
type FilesystemScope = Literal["workspace-write", "read-only", "unconfined"]
|
|
42
|
+
|
|
43
|
+
SANDBOX_MODES: tuple[SandboxMode, ...] = ("off", "network-only", "workspace-write", "read-only")
|
|
44
|
+
NETWORK_MODES: tuple[NetworkMode, ...] = ("deny", "proxy", "allow")
|
|
45
|
+
READ_SCOPES: tuple[ReadScope, ...] = ("all", "workspace")
|
|
46
|
+
BACKEND_NAMES: tuple[BackendName, ...] = ("auto", "seatbelt", "bubblewrap")
|
|
47
|
+
|
|
48
|
+
#: 需要内核沙箱的模式。``off`` 与 ``network-only`` 不需要任何外部程序。
|
|
49
|
+
KERNEL_MODES: frozenset[SandboxMode] = frozenset({"workspace-write", "read-only"})
|
|
50
|
+
|
|
51
|
+
#: 内核沙箱之外仍然可写的位置:``/dev/null`` 与临时目录。临时目录由调用方按
|
|
52
|
+
#: ``TMPDIR`` 注入,这里只放无条件成立的几条。
|
|
53
|
+
DEV_WRITE_PATHS: tuple[str, ...] = ("/dev/null", "/dev/stdout", "/dev/stderr", "/dev/tty")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(slots=True, frozen=True)
|
|
57
|
+
class SandboxSettings:
|
|
58
|
+
"""一份合并完成的沙箱配置。字段与 ``sandbox`` 对象一一对应。
|
|
59
|
+
|
|
60
|
+
``allow_domains`` / ``deny_domains`` 用 ``fnmatch`` 风格的域名模式:``*`` 匹配
|
|
61
|
+
全部,``*.example.com`` 同时覆盖 ``example.com`` 本身与它的子域。``deny_domains``
|
|
62
|
+
先判,所以「放行一家公司的整个域、只拒绝其中一个子域」写得出来。
|
|
63
|
+
|
|
64
|
+
``readable_paths`` 与 ``read`` 只在 ``read = "workspace"`` 时有意义:默认
|
|
65
|
+
``read = "all"`` 跟随 Codex 的选择——**读不是这条边界**,写与网络才是。把读也
|
|
66
|
+
收窄会让 ``git``、``ssh``、语言运行时读不到自己的配置,而攻击面几乎没有变化。
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
mode: SandboxMode = "off"
|
|
70
|
+
backend: BackendName = "auto"
|
|
71
|
+
network: NetworkMode = "proxy"
|
|
72
|
+
read: ReadScope = "all"
|
|
73
|
+
allow_domains: tuple[str, ...] = ()
|
|
74
|
+
deny_domains: tuple[str, ...] = ()
|
|
75
|
+
writable_paths: tuple[str, ...] = ()
|
|
76
|
+
readable_paths: tuple[str, ...] = ()
|
|
77
|
+
#: 后端可执行文件的显式路径。空表示按平台在 PATH 上找(``sandbox-exec`` / ``bwrap``)。
|
|
78
|
+
#: 有的机器把 bwrap 装在 PATH 之外,有的发行版只提供打包版路径。
|
|
79
|
+
executable: str | None = None
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def enabled(self) -> bool:
|
|
83
|
+
return self.mode != "off"
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def needs_kernel_backend(self) -> bool:
|
|
87
|
+
"""是否必须探测到一个可用的内核沙箱后端。"""
|
|
88
|
+
return self.mode in KERNEL_MODES
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def filesystem_scope(self) -> FilesystemScope:
|
|
92
|
+
if self.mode == "workspace-write":
|
|
93
|
+
return "workspace-write"
|
|
94
|
+
if self.mode == "read-only":
|
|
95
|
+
return "read-only"
|
|
96
|
+
return "unconfined"
|
|
97
|
+
|
|
98
|
+
def network_policy(self, model_hosts: Iterable[str] = ()) -> NetworkPolicy:
|
|
99
|
+
"""把模型 API 域名并进允许列表,得到代理要用的判定对象。
|
|
100
|
+
|
|
101
|
+
模型域名永远在列表里:沙箱开着的时候,``bash`` 里跑一个调用模型端点的小脚本
|
|
102
|
+
是很常见的用法(例如本仓库的实测脚本),让用户为了它手写一遍域名不合理。
|
|
103
|
+
想彻底关掉过滤就把 ``network`` 设成 ``allow``。
|
|
104
|
+
"""
|
|
105
|
+
merged: list[str] = []
|
|
106
|
+
for host in (*model_hosts, *self.allow_domains):
|
|
107
|
+
normalized = normalize_host(host)
|
|
108
|
+
if normalized and normalized not in merged:
|
|
109
|
+
merged.append(normalized)
|
|
110
|
+
return NetworkPolicy(mode=self.network, allow=tuple(merged), deny=self.deny_domains)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(slots=True, frozen=True)
|
|
114
|
+
class NetworkPolicy:
|
|
115
|
+
"""出口代理的判定表。``check`` 返回 ``None`` 表示放行,否则是拒绝原因。"""
|
|
116
|
+
|
|
117
|
+
mode: NetworkMode = "proxy"
|
|
118
|
+
allow: tuple[str, ...] = ()
|
|
119
|
+
deny: tuple[str, ...] = ()
|
|
120
|
+
|
|
121
|
+
def check(self, host: str, port: int) -> str | None:
|
|
122
|
+
"""判定一次出站连接。``port`` 只用于拒绝消息,不参与匹配。"""
|
|
123
|
+
normalized = normalize_host(host)
|
|
124
|
+
if not normalized:
|
|
125
|
+
return "目标主机为空"
|
|
126
|
+
for pattern in self.deny:
|
|
127
|
+
if host_matches(pattern, normalized):
|
|
128
|
+
return f"命中拒绝列表 {pattern}({normalized}:{port})"
|
|
129
|
+
if self.mode == "deny":
|
|
130
|
+
return f"网络策略为 deny({normalized}:{port})"
|
|
131
|
+
if self.mode == "allow":
|
|
132
|
+
return None
|
|
133
|
+
if not self.allow:
|
|
134
|
+
# 没有允许列表时按放行处理:空表加 deny 才是「全关」,两者由 mode 区分。
|
|
135
|
+
return None
|
|
136
|
+
for pattern in self.allow:
|
|
137
|
+
if host_matches(pattern, normalized):
|
|
138
|
+
return None
|
|
139
|
+
return f"{normalized}:{port} 不在允许列表(共 {len(self.allow)} 条)"
|
|
140
|
+
|
|
141
|
+
def to_json(self) -> dict[str, object]:
|
|
142
|
+
return {"mode": self.mode, "allow": list(self.allow), "deny": list(self.deny)}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def split_host_port(authority: str, *, default_port: int) -> tuple[str, int]:
|
|
146
|
+
"""把 ``host:port`` / ``host`` / ``[::1]:port`` 拆开。非法端口回落默认值。"""
|
|
147
|
+
text = authority.strip()
|
|
148
|
+
if text.startswith("["):
|
|
149
|
+
closing = text.find("]")
|
|
150
|
+
if closing == -1:
|
|
151
|
+
return text, default_port
|
|
152
|
+
host = text[1:closing]
|
|
153
|
+
tail = text[closing + 1 :]
|
|
154
|
+
port_text = tail[1:] if tail.startswith(":") else ""
|
|
155
|
+
return host, _as_port(port_text, default_port)
|
|
156
|
+
if text.count(":") == 1:
|
|
157
|
+
host, _, port_text = text.partition(":")
|
|
158
|
+
return host, _as_port(port_text, default_port)
|
|
159
|
+
# 没有端口,或者裸 IPv6(多个冒号):原样当主机名。
|
|
160
|
+
return text, default_port
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _as_port(text: str, default: int) -> int:
|
|
164
|
+
if not text:
|
|
165
|
+
return default
|
|
166
|
+
try:
|
|
167
|
+
port = int(text)
|
|
168
|
+
except ValueError:
|
|
169
|
+
return default
|
|
170
|
+
return port if 0 < port < 65536 else default
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def host_matches(pattern: str, host: str) -> bool:
|
|
174
|
+
"""域名模式匹配。``*`` 全通,``*.`` 前缀同时覆盖裸域。
|
|
175
|
+
|
|
176
|
+
为什么 ``*.example.com`` 也匹配 ``example.com``:用户写下这条规则时想的是
|
|
177
|
+
「这家公司自己的站」,让他再补一条裸域规则只会制造一次「明明加了还是被拒」。
|
|
178
|
+
"""
|
|
179
|
+
rule = normalize_host(pattern)
|
|
180
|
+
if not rule:
|
|
181
|
+
return False
|
|
182
|
+
if rule == "*":
|
|
183
|
+
return True
|
|
184
|
+
if rule.startswith("*."):
|
|
185
|
+
base = rule[2:]
|
|
186
|
+
return bool(base) and (host == base or host.endswith("." + base))
|
|
187
|
+
if rule.startswith("."):
|
|
188
|
+
base = rule[1:]
|
|
189
|
+
return bool(base) and (host == base or host.endswith("." + base))
|
|
190
|
+
return host == rule
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def dedupe_domains(values: Sequence[str]) -> tuple[str, ...]:
|
|
194
|
+
"""归一化并去重,保持书写顺序。配置合并与命令行追加都会用到。"""
|
|
195
|
+
seen: list[str] = []
|
|
196
|
+
for value in values:
|
|
197
|
+
normalized = normalize_host(value)
|
|
198
|
+
if normalized and normalized not in seen:
|
|
199
|
+
seen.append(normalized)
|
|
200
|
+
return tuple(seen)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = [
|
|
204
|
+
"BACKEND_NAMES",
|
|
205
|
+
"DEV_WRITE_PATHS",
|
|
206
|
+
"KERNEL_MODES",
|
|
207
|
+
"NETWORK_MODES",
|
|
208
|
+
"READ_SCOPES",
|
|
209
|
+
"SANDBOX_MODES",
|
|
210
|
+
"BackendName",
|
|
211
|
+
"FilesystemScope",
|
|
212
|
+
"NetworkMode",
|
|
213
|
+
"NetworkPolicy",
|
|
214
|
+
"ReadScope",
|
|
215
|
+
"SandboxMode",
|
|
216
|
+
"SandboxSettings",
|
|
217
|
+
"dedupe_domains",
|
|
218
|
+
"host_matches",
|
|
219
|
+
"normalize_host",
|
|
220
|
+
"split_host_port",
|
|
221
|
+
]
|