mainspring-coding-tools 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.
@@ -0,0 +1,336 @@
1
+ """命令执行工具 bash(T10-4)与沙箱引擎注入边界。
2
+
3
+ **为什么不能直接用 ``@sandboxed`` 包整个工具**:M7 worker 的 audit hook 明确拒绝
4
+ ``subprocess.Popen``(「沙箱里再起进程 = 隔离承诺作废」),而命令执行工具的本体就是
5
+ 启动一个进程。二者不可能共用同一条 worker 帧协议,硬套只会得到一个运行时必红的
6
+ 工具。M8 引擎抽象里可复用的部分是引擎层 ``check_available()``(注册期能力探测)、
7
+ ``env(policy)``(环境收敛)与强隔离启动前缀,不是 Python worker 本身。
8
+
9
+ 因此本模块定死一条装配口径:
10
+
11
+ - 外挂**不 import** ``mainspring_sandbox``(import-linter 的 extras independence
12
+ 契约是硬红线),引擎实例由 CLI / server 装配层注入,形状用本模块的 Protocol
13
+ 描述(鸭子类型,实现方是 M8 的 ``SubprocessEngine`` / ``BwrapEngine``);
14
+ - 宿主侧用 stdlib ``subprocess`` 启动 shell,工作目录 = 项目根,墙钟超时
15
+ terminate → 宽限 → kill(沿用 sandbox 的 ``_terminate`` 语义),stdout/stderr
16
+ 合并捕获并截断;
17
+ - 危险命令模式表(删除类 / 网络提权类 / 环境写类)命中即 deny,不可商量;
18
+ 写类与执行类默认 ``require_approval``,与 T10-3 共用同一条 HITL 链;
19
+ - exit code 非零是**正常结果**(附 stderr),不是框架错误;
20
+ - 结构化 payload 固定为命令 / cwd / exit_code / stdout / stderr / duration_ms /
21
+ truncated / timed_out,前端 bash 卡片直接消费。
22
+
23
+ 跨进程序列化仍遵守 M7 的 JSON 帧纪律:参数和返回值必须可 JSON 序列化,
24
+ 不传文件句柄 / 连接对象。
25
+
26
+ **引擎注入协议(鸭子类型,零 import)**:``CommandEngine`` 只要有
27
+ ``check_available()`` / ``env(policy)`` 与「启动前缀」即可。M8 的
28
+ ``SubprocessEngine`` / ``BwrapEngine`` / ``SeatbeltEngine`` 通过公开的
29
+ ``command(request, policy)`` 提供前缀(剥掉末尾固定 worker argv),默认内置
30
+ ``LocalEngine`` 通过 ``shell_prefix(policy)`` 返回空前缀。装配层把引擎实例送进来,
31
+ 外挂侧不出现任何 ``mainspring_sandbox`` 字样——import-linter 的 extras
32
+ independence 契约因此仍是 KEPT。
33
+
34
+ **attach/release 可选钩子**:Windows 的 Job Object 约束(②档的 Windows 兑现)
35
+ 不是前缀形态——``cmd /c`` 只能整串执行,无前缀可加。带句柄生命周期约束的引擎
36
+ 可另选提供 ``attach(proc) -> handle``(Popen 后挂约束)与 ``release(handle)``
37
+ (命令生命周期结束时收约束)。本模块对二者只做鸭子类型探测:有 ``attach``
38
+ 就在 Popen 后调用(失败即杀掉刚起的进程并原样上抛,不留孤儿),收尾时统一
39
+ ``release``。``WindowsJobEngine`` 的 KILL_ON_JOB_CLOSE 在 release 时内核级
40
+ 杀整棵树,散兵孙进程被内核兜底。
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import contextlib
46
+ import os
47
+ import subprocess
48
+ import sys
49
+ import time
50
+ from dataclasses import dataclass
51
+ from typing import Any, Protocol, runtime_checkable
52
+
53
+ from mainspring.tool import Tool, tool
54
+
55
+ from .payload import base_payload
56
+ from .safety import SafetyPolicy, check_command
57
+
58
+ __all__ = [
59
+ "CommandEngine",
60
+ "CommandPolicy",
61
+ "LocalEngine",
62
+ "build_shell_tools",
63
+ "run_command",
64
+ ]
65
+
66
+ _WORKER_ARGV = (sys.executable, "-m", "mainspring_sandbox.worker")
67
+ _MAX_TIMEOUT_S = 300.0
68
+ _MAX_OUTPUT_CHARS = 50_000
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class CommandPolicy:
73
+ """命令执行策略:形状与 M8 ``SandboxPolicy`` 的公共字段对齐(鸭子类型可互喂)。
74
+
75
+ ``paths`` / ``allow_network`` / ``env_allowlist`` 供强隔离引擎的
76
+ ``command(request, policy)`` 翻译策略;``timeout_s`` / ``max_output_chars``
77
+ 由宿主侧共享管道消费。不 import SandboxPolicy,避免外挂间依赖箭头。
78
+ """
79
+
80
+ timeout_s: float = 30.0
81
+ max_output_chars: int = 20_000
82
+ paths: tuple[str, ...] = ()
83
+ allow_network: bool = False
84
+ env_allowlist: tuple[str, ...] = ()
85
+
86
+
87
+ @runtime_checkable
88
+ class CommandEngine(Protocol):
89
+ """注入引擎的最小契约(M8 引擎天然满足,见模块 docstring)。
90
+
91
+ ``attach`` / ``release`` 是可选句柄生命周期钩子,不在 Protocol 形状内:
92
+ 前缀型引擎(M8 全家)不需要,句柄型引擎(WindowsJobEngine)自带,本模块
93
+ 用 ``getattr`` 探测——鸭子类型保持零 import 红线。
94
+ """
95
+
96
+ def check_available(self) -> None:
97
+ """注册期能力探测;缺引擎必须显式报错,不静默降级。"""
98
+ ...
99
+
100
+ def env(self, policy: CommandPolicy) -> dict[str, str]:
101
+ """收敛后的子进程环境变量。"""
102
+ ...
103
+
104
+
105
+ class LocalEngine:
106
+ """默认引擎(①防误伤档):本机 shell 直跑,零前缀、零第三方依赖。
107
+
108
+ 环境变量沿用 ``M8 SubprocessEngine.env`` 的最小维持口径,但保留 PATH——
109
+ 命令执行工具要能找到 python / pytest;这一档不承诺隔离,防恶意靠注入
110
+ ``BwrapEngine`` / ``SeatbeltEngine``(②档,真机拦截待补)。
111
+ """
112
+
113
+ name = "local"
114
+
115
+ def check_available(self) -> None:
116
+ return None
117
+
118
+ def shell_prefix(self, policy: CommandPolicy) -> list[str]:
119
+ return []
120
+
121
+ def env(self, policy: CommandPolicy) -> dict[str, str]:
122
+ keys = ("PATH", "SystemRoot", "COMSPEC", "PATHEXT", "TEMP", "TMP")
123
+ env = {key: value for key in keys if (value := os.environ.get(key)) is not None}
124
+ env["PYTHONIOENCODING"] = "utf-8" # Windows 控制台中文输出按 UTF-8 解码
125
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
126
+ for key in policy.env_allowlist:
127
+ if (value := os.environ.get(key)) is not None:
128
+ env[key] = value
129
+ return env
130
+
131
+
132
+ def _engine_prefix(engine: CommandEngine, policy: CommandPolicy) -> list[str]:
133
+ """取引擎启动前缀:M8 引擎走 ``command()``,自定义引擎走 ``shell_prefix()``。
134
+
135
+ M8 的 ``command()`` 末尾恒定是 worker argv,剥掉它剩下的就是 bwrap /
136
+ sandbox-exec 前缀。末尾不匹配时显式报错——引擎升级改了 worker 启动形态,
137
+ 宁可装配即红,也不静默丢掉隔离前缀(这正是 M8 能力标志纪律的延伸)。
138
+ """
139
+ custom = getattr(engine, "shell_prefix", None)
140
+ if callable(custom):
141
+ return list(custom(policy))
142
+ command_fn = getattr(engine, "command", None)
143
+ if not callable(command_fn):
144
+ raise TypeError(f"引擎 {type(engine).__name__} 既不提供 shell_prefix 也不提供 command")
145
+ argv = list(command_fn({"v": 1}, policy))
146
+ if tuple(argv[-3:]) != _WORKER_ARGV:
147
+ raise ValueError(
148
+ f"引擎 {type(engine).__name__} 的 command() 末尾不是已知 worker argv,"
149
+ "拒绝在未知形态下丢弃隔离前缀"
150
+ )
151
+ return argv[:-3]
152
+
153
+
154
+ def _clip(text: str, limit: int) -> tuple[str, bool]:
155
+ if len(text) <= limit:
156
+ return text, False
157
+ return f"{text[:limit]}\n...[输出已截断,共 {len(text)} 字符]", True
158
+
159
+
160
+ def _terminate(proc: subprocess.Popen[bytes]) -> None:
161
+ """terminate → 宽限 2s → kill,沿用 M8 共享管道的真取消语义(不 import 它)。
162
+
163
+ Windows 额外先 ``taskkill /T``:``cmd.exe /c`` 会派生孙进程,只 terminate
164
+ 外壳的话 stdout 句柄仍被孙进程持有,``communicate()`` 会一直等到它自己退出,
165
+ 「超时」就只剩个标志、没有真取消。taskkill 不可用时退回原路径(best effort),
166
+ 并把这条限制写进指南,不假装跨进程树强杀是承诺面。
167
+ """
168
+ if os.name == "nt":
169
+ with contextlib.suppress(OSError, subprocess.TimeoutExpired):
170
+ subprocess.run(
171
+ ["taskkill", "/PID", str(proc.pid), "/T", "/F"],
172
+ stdin=subprocess.DEVNULL,
173
+ stdout=subprocess.DEVNULL,
174
+ stderr=subprocess.DEVNULL,
175
+ timeout=2.0,
176
+ check=False,
177
+ )
178
+ try:
179
+ proc.terminate() # 进程可能已被 taskkill 收掉,terminate 对已退出进程是 no-op
180
+ proc.wait(timeout=2.0)
181
+ except (OSError, subprocess.TimeoutExpired):
182
+ with contextlib.suppress(OSError, subprocess.TimeoutExpired):
183
+ proc.kill()
184
+ proc.wait(timeout=2.0)
185
+
186
+
187
+ def _spawn(
188
+ policy: SafetyPolicy,
189
+ command: str,
190
+ engine: CommandEngine,
191
+ config: CommandPolicy,
192
+ ) -> tuple[subprocess.Popen[bytes], Any]:
193
+ """安全检查之后的公共启动路径(前台 ``run_command`` 与后台任务共用)。
194
+
195
+ 引擎启动前缀(可选强隔离)→ cmd /c 整串(Windows)或 argv 列表(POSIX)→
196
+ Popen → ``attach`` 句柄钩子(可选)。返回 ``(proc, handle)``,句柄由调用方在
197
+ 生命周期结束时 ``release``;前台命令随 communicate 收尾,后台任务随收割终止。
198
+ """
199
+ check_command(policy, command) # 纵深防御:Hook 漏挂时这里仍然拒绝
200
+ prefix = _engine_prefix(engine, config)
201
+ shell = os.environ.get("COMSPEC", "cmd.exe") if os.name == "nt" else "/bin/sh"
202
+ flag = "/c" if os.name == "nt" else "-c"
203
+ # Windows 的 cmd.exe /c 对 argv 列表里的嵌套双引号会拆碎(实测
204
+ # `python -c "print(1)"` 会变成 `-c "import` + 语法错误),必须传整条命令
205
+ # 字符串让 cmd 自己按命令行解析;POSIX 侧保持 argv 列表,强隔离前缀才拼得上。
206
+ if os.name == "nt":
207
+ if prefix:
208
+ raise ValueError(
209
+ "Windows 走 cmd /c 整串形态,不支持前缀型强隔离引擎;"
210
+ "Windows 侧约束请注入 WindowsJobEngine(attach/release 钩子)"
211
+ )
212
+ launch: str | list[str] = f'"{shell}" {flag} {command}'
213
+ else:
214
+ launch = [*prefix, shell, flag, command]
215
+ proc = subprocess.Popen(
216
+ launch,
217
+ cwd=policy.root, # 工作目录由宿主定死,模型无法传参改它
218
+ stdin=subprocess.DEVNULL, # 不许等输入(MCP/单通道协议的死等教训)
219
+ stdout=subprocess.PIPE,
220
+ stderr=subprocess.PIPE,
221
+ env=engine.env(config),
222
+ )
223
+ handle: Any = None
224
+ attach = getattr(engine, "attach", None)
225
+ if callable(attach):
226
+ try:
227
+ handle = attach(proc) # 句柄型引擎在 Popen 后挂约束(Job Object)
228
+ except BaseException:
229
+ proc.kill() # 挂约束失败不留孤儿,再原样上抛
230
+ raise
231
+ return proc, handle
232
+
233
+
234
+ def run_command(
235
+ policy: SafetyPolicy,
236
+ command: str,
237
+ *,
238
+ engine: CommandEngine | None = None,
239
+ command_policy: CommandPolicy | None = None,
240
+ timeout_s: float = 0.0,
241
+ max_output_chars: int = 0,
242
+ ) -> dict[str, Any]:
243
+ """执行一条 shell 命令并返回结构化 payload(纯逻辑入口,便于直接做用例)。
244
+
245
+ 三层防护:``check_command``(危险模式 + 路径白名单)→ 引擎启动前缀(可选强隔离)
246
+ → 墙钟真取消。exit code 非零是正常结果,不会变成 ``is_error`` 的 ToolResult。
247
+ """
248
+ chosen: CommandEngine = engine if engine is not None else LocalEngine()
249
+ chosen.check_available() # 注册期已验,执行期再验一次不贵
250
+ config = command_policy or CommandPolicy()
251
+ timeout = min(_MAX_TIMEOUT_S, timeout_s if timeout_s > 0 else config.timeout_s)
252
+ limit = min(
253
+ _MAX_OUTPUT_CHARS, max_output_chars if max_output_chars > 0 else config.max_output_chars
254
+ )
255
+ started = time.monotonic()
256
+ proc, handle = _spawn(policy, command, chosen, config)
257
+ timed_out = False
258
+ try:
259
+ out, err = proc.communicate(timeout=timeout)
260
+ except subprocess.TimeoutExpired:
261
+ _terminate(proc)
262
+ out, err = proc.communicate()
263
+ timed_out = True
264
+ finally:
265
+ # 收约束:KILL_ON_JOB_CLOSE 让内核杀掉树内残留(含持有 stdout 的孙进程)。
266
+ # 前缀型引擎没有 release,此处为 no-op。
267
+ release = getattr(chosen, "release", None)
268
+ if handle is not None and callable(release):
269
+ release(handle)
270
+ duration_ms = int((time.monotonic() - started) * 1000)
271
+ stdout, stdout_clipped = _clip(out.decode("utf-8", errors="replace"), limit)
272
+ stderr, stderr_clipped = _clip(err.decode("utf-8", errors="replace"), limit)
273
+ projection = f"$ {command}\nexit_code={proc.returncode}"
274
+ if stdout:
275
+ projection += f"\n{stdout}"
276
+ if stderr:
277
+ projection += f"\n[stderr]\n{stderr}"
278
+ if timed_out:
279
+ projection += f"\n[超时 {timeout}s,进程已终止]"
280
+ return base_payload(
281
+ "bash",
282
+ command=command,
283
+ cwd=".",
284
+ exit_code=proc.returncode,
285
+ stdout=stdout,
286
+ stderr=stderr,
287
+ duration_ms=duration_ms,
288
+ truncated=stdout_clipped or stderr_clipped,
289
+ timed_out=timed_out,
290
+ text=projection,
291
+ )
292
+
293
+
294
+ def build_shell_tools(
295
+ policy: SafetyPolicy,
296
+ *,
297
+ engine: CommandEngine | None = None,
298
+ command_policy: CommandPolicy | None = None,
299
+ ) -> list[Tool]:
300
+ """产出 bash 工具;引擎由装配层注入,注册期做能力探测(缺引擎即报错)。"""
301
+ chosen: CommandEngine = engine if engine is not None else LocalEngine()
302
+ chosen.check_available()
303
+ config = command_policy or CommandPolicy()
304
+ # 装配期形状校验:引擎升级改了启动形态立即红,不把「前缀丢了」拖到执行时才发现
305
+ _engine_prefix(chosen, config)
306
+
307
+ def bash(command: str, timeout_s: float = 0.0, max_output_chars: int = 0) -> dict[str, Any]:
308
+ """在项目根执行一条 shell 命令,返回退出码 / stdout / stderr / 超时与截断标志。"""
309
+ return run_command(
310
+ policy,
311
+ command,
312
+ engine=chosen,
313
+ command_policy=config,
314
+ timeout_s=timeout_s,
315
+ max_output_chars=max_output_chars,
316
+ )
317
+
318
+ bash.__annotations__ = {
319
+ "command": str,
320
+ "timeout_s": float,
321
+ "max_output_chars": int,
322
+ "return": dict[str, Any],
323
+ }
324
+ return [
325
+ tool(
326
+ bash,
327
+ name="bash",
328
+ description=(
329
+ "在项目根执行 shell 命令(构建 / 测试 / 搜索),返回退出码、stdout/stderr、"
330
+ "耗时、超时与截断标志;timeout_s=0 用默认超时,max_output_chars=0 用默认上限。"
331
+ "危险命令与项目根外路径一律拒绝。"
332
+ ),
333
+ strict=True,
334
+ timeout=max(_MAX_TIMEOUT_S, config.timeout_s) + 10.0,
335
+ )
336
+ ]