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.
- mainspring_coding_tools/__init__.py +154 -0
- mainspring_coding_tools/__main__.py +112 -0
- mainspring_coding_tools/cli.py +362 -0
- mainspring_coding_tools/coding.py +326 -0
- mainspring_coding_tools/files.py +458 -0
- mainspring_coding_tools/jobs.py +356 -0
- mainspring_coding_tools/payload.py +40 -0
- mainspring_coding_tools/persona.py +45 -0
- mainspring_coding_tools/py.typed +0 -0
- mainspring_coding_tools/safety.py +424 -0
- mainspring_coding_tools/search.py +204 -0
- mainspring_coding_tools/shell.py +336 -0
- mainspring_coding_tools/web.py +590 -0
- mainspring_coding_tools-0.1.0.dist-info/METADATA +59 -0
- mainspring_coding_tools-0.1.0.dist-info/RECORD +18 -0
- mainspring_coding_tools-0.1.0.dist-info/WHEEL +4 -0
- mainspring_coding_tools-0.1.0.dist-info/entry_points.txt +3 -0
- mainspring_coding_tools-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
"""安全总闸 SafetyPolicy(T10-6):路径白名单 / 危险命令表 / 审批默认值。
|
|
2
|
+
|
|
3
|
+
T10-2 起只有「路径白名单」这一格,T10-3/T10-4 各加了审批与命令裁决,
|
|
4
|
+
T10-6 把它们收口成**单点可信**的总闸:``build_controls()`` 一次产出
|
|
5
|
+
行为裁决 Hook 与文本两阶段 Guardrail,工具侧只保留纵深防御的二次校验。
|
|
6
|
+
路径判定从 T10-2 第一行起就只有一处实现,本卡不重写、不散落。
|
|
7
|
+
|
|
8
|
+
根目录纪律(与 T10-6 的 fail-closed 同口径):
|
|
9
|
+
|
|
10
|
+
- 模型传进来的路径一律按**项目根相对路径**解释,绝对路径直接拒绝
|
|
11
|
+
(Windows 盘符 / UNC / POSIX 根路径形态各异,放行等于把白名单交给模型);
|
|
12
|
+
- ``..`` 穿越与符号链接由 ``Path.resolve()`` 消解后判定真实位置;
|
|
13
|
+
- 目录遍历跳过构建产物与虚拟环境(``.venv`` / ``site-packages`` / ``.git`` 等),
|
|
14
|
+
否则一次 grep 会扫进几十万个文件。
|
|
15
|
+
|
|
16
|
+
分散在各工具里的安全判断收口到一处,单点可信:
|
|
17
|
+
|
|
18
|
+
- ``project_root`` 白名单:一律拒绝根外路径;先 ``resolve()`` 再判定,
|
|
19
|
+
``..`` 穿越、符号链接、绝对路径三种逃逸形态全覆盖;
|
|
20
|
+
- ``dangerous_patterns``:删除类 / 网络提权类 / 环境写类命令模式表,
|
|
21
|
+
命中即 deny(不可由 yaml 关闭,只有审批开关可配);
|
|
22
|
+
- ``approve_writes`` / ``approve_commands``:读默认放行、写与执行默认
|
|
23
|
+
``require_approval``,经 core 的 ``PermissionHook`` 风格裁决进 Runner 挂起;
|
|
24
|
+
- **fail-closed**:安全组件自身抛异常一律按 deny 处理,绝不 fail-open;
|
|
25
|
+
与 core 的 ``HookPipeline.pre`` / ``GuardrailPipeline._evaluate`` 同纪律;
|
|
26
|
+
- 配置不另发明配置面:策略经 core.config 的 yaml 插值机制装配,
|
|
27
|
+
版本随快照留痕,审计可回溯。
|
|
28
|
+
|
|
29
|
+
组合形态:文本两阶段检查走 ``Guardrail``(输入 / 输出),行为裁决走
|
|
30
|
+
``Hook.pre_tool_use``(allow / deny / require_approval 三态)。本模块只产出
|
|
31
|
+
策略对象与两个适配器,不重编排 Runner 循环(M1 红线:循环体冻结)。
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import json
|
|
37
|
+
import os
|
|
38
|
+
import re
|
|
39
|
+
import shlex
|
|
40
|
+
from collections.abc import Mapping, Sequence
|
|
41
|
+
from dataclasses import dataclass, field
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
from typing import Any
|
|
44
|
+
|
|
45
|
+
from mainspring.config import _interpolate, _parse_yaml # 复用 core 的 ${VAR} 插值口径
|
|
46
|
+
from mainspring.guardrails import Guardrail, InputGuardrail, OutputGuardrail
|
|
47
|
+
from mainspring.hooks import Hook
|
|
48
|
+
from mainspring.types import HookVerdict, RunContext, ToolCall, ToolResult
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"COMMAND_TOOLS",
|
|
52
|
+
"CONTROL_TOOLS",
|
|
53
|
+
"DANGEROUS_COMMAND_PATTERNS",
|
|
54
|
+
"DEFAULT_TEXT_MARKERS",
|
|
55
|
+
"SKIP_DIRS",
|
|
56
|
+
"WRITE_TOOLS",
|
|
57
|
+
"ApprovalHook",
|
|
58
|
+
"CommandSafetyHook",
|
|
59
|
+
"SafetyHook",
|
|
60
|
+
"SafetyPolicy",
|
|
61
|
+
"SafetyTextGuardrail",
|
|
62
|
+
"UnsafeCommand",
|
|
63
|
+
"UnsafePath",
|
|
64
|
+
"check_command",
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
# 写 / 执行类工具:审批默认值的唯一分类表(读类恒放行)。
|
|
68
|
+
WRITE_TOOLS = frozenset({"write_file", "edit_file"})
|
|
69
|
+
# bash 与 bash_bg 同走一条执行审批链:后台启动不因「立即返回」绕过人审(T15-⑨)。
|
|
70
|
+
COMMAND_TOOLS = frozenset({"bash", "bash_bg"})
|
|
71
|
+
# 控制类工具(T15-⑨):job_kill 的对象是本会话内已审批启动的后台任务,但终止
|
|
72
|
+
# 进程树仍是执行类副作用,随 approve_commands 开关走人审;参数只有 job_id,
|
|
73
|
+
# check_arguments 对它无需命令 / 路径检查。
|
|
74
|
+
CONTROL_TOOLS = frozenset({"job_kill"})
|
|
75
|
+
|
|
76
|
+
# 文本两阶段护栏的特征串:只拦明确的「绕过安全策略」话术,不做宽泛语义审查。
|
|
77
|
+
# 行为裁决才是主闸门,这里是纵深防御(命中即 deny,由 GuardrailPipeline 收口)。
|
|
78
|
+
DEFAULT_TEXT_MARKERS: tuple[str, ...] = (
|
|
79
|
+
"忽略安全策略",
|
|
80
|
+
"绕过审批",
|
|
81
|
+
"disable safety",
|
|
82
|
+
"ignore safety policy",
|
|
83
|
+
"bypass approval",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
# 遍历跳过目录:构建产物 / 虚拟环境 / 缓存。写死一份在项目内,工具侧不各写一套。
|
|
87
|
+
SKIP_DIRS = frozenset(
|
|
88
|
+
{
|
|
89
|
+
".git",
|
|
90
|
+
".venv",
|
|
91
|
+
"venv",
|
|
92
|
+
"__pycache__",
|
|
93
|
+
"site-packages",
|
|
94
|
+
"node_modules",
|
|
95
|
+
"dist",
|
|
96
|
+
"build",
|
|
97
|
+
".mypy_cache",
|
|
98
|
+
".pytest_cache",
|
|
99
|
+
".ruff_cache",
|
|
100
|
+
".import_linter_cache",
|
|
101
|
+
"htmlcov",
|
|
102
|
+
"site",
|
|
103
|
+
}
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class UnsafePath(ValueError):
|
|
108
|
+
"""路径不在项目根白名单内(含绝对路径 / ``..`` 穿越 / 符号链接逃逸)。"""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class SafetyPolicy:
|
|
113
|
+
"""可配置总闸:路径白名单 / 危险命令表 / 审批开关 / 文本特征 / 版本号。
|
|
114
|
+
|
|
115
|
+
``root`` 在构造时 resolve 一次:后续所有判定都用同一份真实路径,
|
|
116
|
+
不受进程 cwd 变化影响(CLI / server 常在不同目录下启动)。
|
|
117
|
+
``policy_version`` 随策略进快照留痕,审计可回溯(改默认值须升版本)。
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
root: Path = field(default_factory=Path.cwd)
|
|
121
|
+
approve_writes: bool = True
|
|
122
|
+
approve_commands: bool = True
|
|
123
|
+
extra_dangerous_patterns: tuple[tuple[str, str], ...] = ()
|
|
124
|
+
text_markers: tuple[str, ...] = DEFAULT_TEXT_MARKERS
|
|
125
|
+
policy_version: str = "1"
|
|
126
|
+
|
|
127
|
+
def __post_init__(self) -> None:
|
|
128
|
+
object.__setattr__(self, "root", self.root.resolve())
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def all_patterns(self) -> tuple[tuple[str, str], ...]:
|
|
132
|
+
"""内置危险命令表 + 可追加表;**内置表不可由 yaml 关闭**,只能加严。"""
|
|
133
|
+
return (*DANGEROUS_COMMAND_PATTERNS, *self.extra_dangerous_patterns)
|
|
134
|
+
|
|
135
|
+
def requires_approval(self, name: str) -> bool:
|
|
136
|
+
"""读类恒放行;写 / 执行 / 控制类按各自开关(默认都开)。"""
|
|
137
|
+
if name in WRITE_TOOLS:
|
|
138
|
+
return self.approve_writes
|
|
139
|
+
if name in COMMAND_TOOLS or name in CONTROL_TOOLS:
|
|
140
|
+
return self.approve_commands
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
def check_arguments(self, call: ToolCall) -> None:
|
|
144
|
+
"""工具调用参数的安全检查:危险命令 / 根外路径,任何异常都由 Hook 按 deny 收口。"""
|
|
145
|
+
arguments = json.loads(call.arguments or "{}")
|
|
146
|
+
if not isinstance(arguments, dict):
|
|
147
|
+
raise UnsafeCommand("工具参数必须是 JSON 对象")
|
|
148
|
+
if call.name in COMMAND_TOOLS:
|
|
149
|
+
check_command(self, str(arguments.get("command", "")))
|
|
150
|
+
return
|
|
151
|
+
for key in ("path", "pattern"):
|
|
152
|
+
value = arguments.get(key)
|
|
153
|
+
if isinstance(value, str) and value:
|
|
154
|
+
self.resolve(value) # 绝对路径 / .. / 符号链接统一在这里判定
|
|
155
|
+
|
|
156
|
+
def build_controls(self) -> tuple[list[Hook], list[Guardrail]]:
|
|
157
|
+
"""单点总装:行为裁决 Hook + todo 绑定 Hook + 文本两阶段 Guardrail。
|
|
158
|
+
|
|
159
|
+
返回的是可直接塞进 ``Agent.hooks`` / ``Agent.guardrails`` 的列表;
|
|
160
|
+
不碰 Runner 循环体(M1 红线),也不在工具侧另开审批判断。
|
|
161
|
+
"""
|
|
162
|
+
from .coding import TodoBindingHook # 局部导入:coding 不反向依赖 safety,但别在模块级成环
|
|
163
|
+
|
|
164
|
+
return (
|
|
165
|
+
[SafetyHook(self), TodoBindingHook()],
|
|
166
|
+
[SafetyTextGuardrail(self.text_markers)],
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
@classmethod
|
|
170
|
+
def from_mapping(cls, data: Mapping[str, Any]) -> SafetyPolicy:
|
|
171
|
+
"""纯数据 → 策略:手写字面量校验,未知字段显式报错(不静默忽略拼错的配置)。"""
|
|
172
|
+
allowed = {
|
|
173
|
+
"root",
|
|
174
|
+
"approve_writes",
|
|
175
|
+
"approve_commands",
|
|
176
|
+
"extra_dangerous_patterns",
|
|
177
|
+
"text_markers",
|
|
178
|
+
"policy_version",
|
|
179
|
+
}
|
|
180
|
+
unknown = sorted(set(data) - allowed)
|
|
181
|
+
if unknown:
|
|
182
|
+
raise ValueError(
|
|
183
|
+
f"SafetyPolicy 未知配置字段:{', '.join(unknown)};可用:{', '.join(sorted(allowed))}"
|
|
184
|
+
)
|
|
185
|
+
for key in ("approve_writes", "approve_commands"):
|
|
186
|
+
if key in data and not isinstance(data[key], bool):
|
|
187
|
+
raise ValueError(f"{key} 必须是布尔值,收到 {data[key]!r}")
|
|
188
|
+
extra = data.get("extra_dangerous_patterns") or ()
|
|
189
|
+
if not isinstance(extra, (list, tuple)):
|
|
190
|
+
raise ValueError("extra_dangerous_patterns 必须是 [模式, 原因] 对的列表")
|
|
191
|
+
return cls(
|
|
192
|
+
root=Path(str(data.get("root", Path.cwd()))),
|
|
193
|
+
approve_writes=bool(data.get("approve_writes", True)),
|
|
194
|
+
approve_commands=bool(data.get("approve_commands", True)),
|
|
195
|
+
extra_dangerous_patterns=tuple((str(a), str(b)) for a, b in extra),
|
|
196
|
+
text_markers=tuple(
|
|
197
|
+
str(item) for item in (data.get("text_markers") or DEFAULT_TEXT_MARKERS)
|
|
198
|
+
),
|
|
199
|
+
policy_version=str(data.get("policy_version", "1")),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
@classmethod
|
|
203
|
+
def from_yaml(
|
|
204
|
+
cls,
|
|
205
|
+
path: str | Path,
|
|
206
|
+
*,
|
|
207
|
+
env: Mapping[str, str] | None = None,
|
|
208
|
+
) -> SafetyPolicy:
|
|
209
|
+
"""yaml → 策略:复用 core.config 的 ``${VAR}`` 插值与行号索引,不另造配置面。
|
|
210
|
+
|
|
211
|
+
core 未把插值函数列进公开 API,这里显式 import 其私有实现——签名一变
|
|
212
|
+
本处立即红,耦合可见比悄悄复制一份插值逻辑更安全。
|
|
213
|
+
"""
|
|
214
|
+
file_path = Path(path)
|
|
215
|
+
text = file_path.read_text(encoding="utf-8")
|
|
216
|
+
data, lines = _parse_yaml(text, str(file_path))
|
|
217
|
+
environ = os.environ if env is None else env
|
|
218
|
+
interpolated = _interpolate(data or {}, (), environ, lines, str(file_path))
|
|
219
|
+
if not isinstance(interpolated, dict):
|
|
220
|
+
raise ValueError(f"SafetyPolicy 配置根节点必须是映射:{file_path}")
|
|
221
|
+
return cls.from_mapping(interpolated)
|
|
222
|
+
|
|
223
|
+
def resolve(self, path: str) -> Path:
|
|
224
|
+
"""把模型给的相对路径解析成根内真实路径;根外一律抛 ``UnsafePath``。"""
|
|
225
|
+
raw = Path(path)
|
|
226
|
+
if raw.is_absolute():
|
|
227
|
+
raise UnsafePath(f"拒绝绝对路径 {path}:路径必须相对项目根")
|
|
228
|
+
target = (self.root / raw).resolve()
|
|
229
|
+
self._ensure_inside(target, path)
|
|
230
|
+
return target
|
|
231
|
+
|
|
232
|
+
def contains(self, target: Path) -> bool:
|
|
233
|
+
"""真实路径是否落在根内(根本身也算)。"""
|
|
234
|
+
resolved = target.resolve()
|
|
235
|
+
return resolved == self.root or self.root in resolved.parents
|
|
236
|
+
|
|
237
|
+
def relative(self, target: Path) -> str:
|
|
238
|
+
"""项目相对的 POSIX 风格路径:payload 跨平台一致,快照不因 Windows 反斜杠漂移。"""
|
|
239
|
+
return target.resolve().relative_to(self.root).as_posix()
|
|
240
|
+
|
|
241
|
+
def iter_files(self, subpath: str = ".", file_glob: str = "*") -> list[Path]:
|
|
242
|
+
"""列出根内待扫描文件:跳过构建产物目录,按相对路径排序保证结果确定。
|
|
243
|
+
|
|
244
|
+
``file_glob`` 交给 ``Path.rglob``;含 ``..`` 的模式直接拒绝,
|
|
245
|
+
避免 pathlib 各版本对上跳形态的处理差异变成安全缺口。
|
|
246
|
+
"""
|
|
247
|
+
if ".." in Path(file_glob).parts or ".." in Path(subpath).parts:
|
|
248
|
+
raise UnsafePath(f"拒绝含 .. 的遍历模式:{subpath} / {file_glob}")
|
|
249
|
+
base = self.resolve(subpath)
|
|
250
|
+
candidates = [base] if base.is_file() else base.rglob(file_glob)
|
|
251
|
+
files: list[Path] = []
|
|
252
|
+
for candidate in candidates:
|
|
253
|
+
if not candidate.is_file() or not self.contains(candidate):
|
|
254
|
+
continue
|
|
255
|
+
parts = candidate.resolve().relative_to(self.root).parts
|
|
256
|
+
if any(part in SKIP_DIRS for part in parts[:-1]):
|
|
257
|
+
continue
|
|
258
|
+
files.append(candidate)
|
|
259
|
+
return sorted(files, key=lambda item: self.relative(item))
|
|
260
|
+
|
|
261
|
+
def _ensure_inside(self, target: Path, original: str) -> None:
|
|
262
|
+
if not self.contains(target):
|
|
263
|
+
raise UnsafePath(f"路径 {original} 越出项目根 {self.root}(解析为 {target})")
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class ApprovalHook:
|
|
267
|
+
"""写 / 执行类工具的三态裁决 Hook(T10-3 起;T10-6 收口进 SafetyPolicy)。
|
|
268
|
+
|
|
269
|
+
core 的 ``PermissionHook`` 只做白名单(allow / deny),**不产 require_approval**;
|
|
270
|
+
挂起要经自定义 Hook 的 ``pre_tool_use`` 返回三态裁决,由 Runner 落 pending 快照。
|
|
271
|
+
``enabled=False``(yaml 关掉审批开关)时整条挂起链消失,读类工具恒放行。
|
|
272
|
+
|
|
273
|
+
裁决异常不会被 HookPipeline 悄悄放过:它把任何异常按 deny 收口(fail-closed),
|
|
274
|
+
与本外挂的安全纪律一致。
|
|
275
|
+
"""
|
|
276
|
+
|
|
277
|
+
name = "coding-approval"
|
|
278
|
+
|
|
279
|
+
def __init__(self, names: Sequence[str], *, enabled: bool = True) -> None:
|
|
280
|
+
self.names = frozenset(names)
|
|
281
|
+
self.enabled = enabled
|
|
282
|
+
|
|
283
|
+
async def pre_tool_use(self, call: ToolCall, ctx: RunContext[Any]) -> HookVerdict:
|
|
284
|
+
if self.enabled and call.name in self.names:
|
|
285
|
+
return HookVerdict(
|
|
286
|
+
action="require_approval",
|
|
287
|
+
reason=f"{call.name} 属于写 / 执行类工具,需人工确认后执行",
|
|
288
|
+
)
|
|
289
|
+
return HookVerdict(action="allow")
|
|
290
|
+
|
|
291
|
+
async def post_tool_use(self, call: ToolCall, result: ToolResult, ctx: RunContext[Any]) -> None:
|
|
292
|
+
"""审批 Hook 不观察结果(审计由 tool_call 事件承担)。"""
|
|
293
|
+
return None
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
class UnsafeCommand(ValueError):
|
|
297
|
+
"""命令命中危险模式或含越界路径,不可执行(不可由审批开关放行)。"""
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# 危险命令模式表(T10-4):删除类 / 网络提权类 / 环境写类。
|
|
301
|
+
# 命中即 deny,**不提供开关**——审批是给人看副作用,不是给危险命令开绿灯。
|
|
302
|
+
# 模式是启发式而非语法解析器:拦的是最常见的高风险形态,强隔离仍靠注入的引擎。
|
|
303
|
+
DANGEROUS_COMMAND_PATTERNS: tuple[tuple[str, str], ...] = (
|
|
304
|
+
(r"\brm\s+-[a-z]*[rf]", "递归 / 强制删除"),
|
|
305
|
+
(r"\brmdir\s+/[sq]\b|\bdel\s+/[sqf]\b", "Windows 递归删除"),
|
|
306
|
+
(r"\bdd\s+if=|\bmkfs\b|\bshutdown\b|\breboot\b", "块设备 / 关机类"),
|
|
307
|
+
(r"\bcurl\b|\bwget\b|\bssh\b|\bscp\b", "网络访问"),
|
|
308
|
+
(r"\bsudo\b|\bsu\b|\brunas\b", "提权"),
|
|
309
|
+
(r"\bgit\s+push\b|\buv\s+publish\b|\btwine\s+upload\b", "外发 / 发布"),
|
|
310
|
+
(r"\b(?:export|setx)\s+\w+\s*=|\bset\s+\w+\s*=", "环境变量写入"),
|
|
311
|
+
(r"\bchmod\b|\bchown\b|\bicacls\b", "权限变更"),
|
|
312
|
+
(r"\bpip\s+install\b|\buv\s+add\b|\bnpm\s+install\b", "依赖安装(隐含出网与写环境)"),
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def check_command(policy: SafetyPolicy, command: str) -> None:
|
|
317
|
+
"""命令执行前的安全检查:危险模式 + 项目根路径白名单(绝对路径 / ``..`` / 符号链接)。
|
|
318
|
+
|
|
319
|
+
路径判定沿用 ``SafetyPolicy.resolve``(先 ``Path.resolve()`` 再判根),
|
|
320
|
+
所以符号链接指向根外时按真实目标拒绝;``cwd`` 由执行侧强制设为项目根,
|
|
321
|
+
模型无法传参改它。检查是启发式:复杂 shell 拼接(变量展开 / 子 shell)不在
|
|
322
|
+
v1 的静态分析范围内,这一档对应 M8 的①防误伤,②防恶意靠注入强隔离引擎。
|
|
323
|
+
"""
|
|
324
|
+
if not command.strip():
|
|
325
|
+
raise UnsafeCommand("命令不能为空")
|
|
326
|
+
for pattern, reason in policy.all_patterns:
|
|
327
|
+
if re.search(pattern, command, re.IGNORECASE):
|
|
328
|
+
raise UnsafeCommand(f"危险命令命中「{reason}」,不可执行:{command[:120]}")
|
|
329
|
+
try:
|
|
330
|
+
tokens = shlex.split(command, posix=os.name != "nt")
|
|
331
|
+
except ValueError: # 引号不闭合:退化成空白切分,路径检查照样做
|
|
332
|
+
tokens = command.split()
|
|
333
|
+
for raw in tokens:
|
|
334
|
+
token = raw.strip("\"'")
|
|
335
|
+
if not token:
|
|
336
|
+
continue
|
|
337
|
+
if re.match(r"^[A-Za-z]:[\\/]", token) or token.startswith(("/", "\\")):
|
|
338
|
+
raise UnsafeCommand(f"拒绝绝对路径 {token}:命令路径必须相对项目根")
|
|
339
|
+
if ".." in Path(token).parts:
|
|
340
|
+
raise UnsafeCommand(f"拒绝含 .. 的路径 {token}")
|
|
341
|
+
if "/" in token or "\\" in token:
|
|
342
|
+
policy.resolve(token) # 符号链接消解 + 根白名单(越界抛 UnsafePath)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
class CommandSafetyHook:
|
|
346
|
+
"""命令执行的行为裁决 Hook(T10-4;T10-6 收口进 SafetyPolicy 总闸)。
|
|
347
|
+
|
|
348
|
+
Hook 侧裁决让 deny 落 ``hook`` 事件(可审计),工具侧再校验一次是纵深防御——
|
|
349
|
+
即使装配层漏挂 Hook,危险命令也不会真的落到 shell 里。任何解析 / 检查异常
|
|
350
|
+
一律按 deny 收口(fail-closed),绝不因为「看不懂」就放行。
|
|
351
|
+
"""
|
|
352
|
+
|
|
353
|
+
name = "command-safety"
|
|
354
|
+
|
|
355
|
+
def __init__(self, policy: SafetyPolicy) -> None:
|
|
356
|
+
self.policy = policy
|
|
357
|
+
|
|
358
|
+
async def pre_tool_use(self, call: ToolCall, ctx: RunContext[Any]) -> HookVerdict:
|
|
359
|
+
if call.name != "bash":
|
|
360
|
+
return HookVerdict(action="allow")
|
|
361
|
+
try:
|
|
362
|
+
arguments = json.loads(call.arguments or "{}")
|
|
363
|
+
check_command(self.policy, str(arguments.get("command", "")))
|
|
364
|
+
except Exception as exc: # fail-closed:看不懂的命令不放行
|
|
365
|
+
return HookVerdict(action="deny", reason=f"命令安全检查拒绝:{exc}")
|
|
366
|
+
return HookVerdict(action="allow")
|
|
367
|
+
|
|
368
|
+
async def post_tool_use(self, call: ToolCall, result: ToolResult, ctx: RunContext[Any]) -> None:
|
|
369
|
+
"""命令侧不观察结果(审计由 hook / tool_call 事件承担)。"""
|
|
370
|
+
return None
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class SafetyHook:
|
|
374
|
+
"""T10-6 统一行为裁决:deny 优先、审批次之、其余放行,任何异常一律 deny。
|
|
375
|
+
|
|
376
|
+
把 T10-3 的审批与 T10-4 的命令裁决收口成一次 ``pre_tool_use``:
|
|
377
|
+
装配层只需挂这一个 Hook + ``TodoBindingHook``,不再逐个记挂哪个工具该配谁。
|
|
378
|
+
``check_arguments`` 的异常(含解析失败 / 策略自身抛错)不会被吞掉变成 allow,
|
|
379
|
+
这正是 fail-closed 的落点;core 的 ``HookPipeline`` 还会再兜一层同样的纪律。
|
|
380
|
+
"""
|
|
381
|
+
|
|
382
|
+
name = "coding-safety"
|
|
383
|
+
|
|
384
|
+
def __init__(self, policy: SafetyPolicy) -> None:
|
|
385
|
+
self.policy = policy
|
|
386
|
+
|
|
387
|
+
async def pre_tool_use(self, call: ToolCall, ctx: RunContext[Any]) -> HookVerdict:
|
|
388
|
+
try:
|
|
389
|
+
self.policy.check_arguments(call) # 危险命令 / 根外路径:不可商量
|
|
390
|
+
if self.policy.requires_approval(call.name):
|
|
391
|
+
return HookVerdict(
|
|
392
|
+
action="require_approval",
|
|
393
|
+
reason=f"{call.name} 属于写 / 执行类工具,需人工确认后执行",
|
|
394
|
+
)
|
|
395
|
+
return HookVerdict(action="allow")
|
|
396
|
+
except Exception as exc: # fail-closed:策略崩了也不能放行
|
|
397
|
+
return HookVerdict(
|
|
398
|
+
action="deny",
|
|
399
|
+
reason=f"安全组件异常,已按 deny 收口:{type(exc).__name__}: {exc}",
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
async def post_tool_use(self, call: ToolCall, result: ToolResult, ctx: RunContext[Any]) -> None:
|
|
403
|
+
return None
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
class SafetyTextGuardrail(InputGuardrail, OutputGuardrail):
|
|
407
|
+
"""文本两阶段护栏:只拦明确的「绕过安全策略」话术,不做宽泛语义审查。
|
|
408
|
+
|
|
409
|
+
双继承让 ``GuardrailPipeline`` 在 input / output 两个阶段都选中它;
|
|
410
|
+
真正的行为裁决在 ``SafetyHook``,这里是纵深防御。护栏自身抛异常时
|
|
411
|
+
core 的 pipeline 同样按 deny 收口,不存在 fail-open 的分叉。
|
|
412
|
+
"""
|
|
413
|
+
|
|
414
|
+
name = "coding-safety-text"
|
|
415
|
+
|
|
416
|
+
def __init__(self, markers: Sequence[str] = DEFAULT_TEXT_MARKERS) -> None:
|
|
417
|
+
self.markers = tuple(markers)
|
|
418
|
+
|
|
419
|
+
async def check(self, text: str, ctx: RunContext[Any]) -> HookVerdict:
|
|
420
|
+
lowered = text.lower()
|
|
421
|
+
for marker in self.markers:
|
|
422
|
+
if marker.lower() in lowered:
|
|
423
|
+
return HookVerdict(action="deny", reason=f"文本命中绕过安全策略特征「{marker}」")
|
|
424
|
+
return HookVerdict(action="allow")
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""只读检索工具(T10-2 的 glob / grep)。
|
|
2
|
+
|
|
3
|
+
设计不变量:
|
|
4
|
+
|
|
5
|
+
- **纯 Python 实现,零第三方依赖**:glob 走 ``pathlib`` 模式匹配、grep 走 ``re``
|
|
6
|
+
+ 逐行扫描;``rg`` 属 M12 之后的可选性能增强,不进默认路径(依赖红线 +
|
|
7
|
+
跨平台一致性)。
|
|
8
|
+
- **结构化 payload**:glob 返回按修改时间排序的路径列表(带 ``truncated`` 标志),
|
|
9
|
+
grep 返回 ``files_with_matches`` / ``content`` / ``count`` 三模式的命中列表
|
|
10
|
+
(路径 + 行号 + 行文本 + 截断标志);文本表格只是投影。
|
|
11
|
+
- **路径先过 SafetyPolicy**:项目根外的路径与 glob 逃逸一律拒绝,
|
|
12
|
+
符号链接指向根外时按解析后的真实路径判定;遍历跳过构建产物目录。
|
|
13
|
+
- **错误回填而非抛错**:非法正则、不存在的根目录、二进制文件跳过等统一走
|
|
14
|
+
``is_error=True`` 的 ToolResult,让模型读到可自愈的原因后改参数重试。
|
|
15
|
+
- 扫描结果上限可配置,防止一次 grep 把整个上下文窗口吃光(与 core 的
|
|
16
|
+
``tool_result_max_chars`` 截断是两道互补防线)。
|
|
17
|
+
|
|
18
|
+
用法示例::
|
|
19
|
+
|
|
20
|
+
from mainspring_coding_tools.search import build_search_tools
|
|
21
|
+
|
|
22
|
+
tools = build_search_tools(SafetyPolicy(Path.cwd()))
|
|
23
|
+
# grep(pattern="class Runner", mode="content", file_glob="*.py")
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import re
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any, Literal
|
|
31
|
+
|
|
32
|
+
from mainspring.tool import Tool, tool
|
|
33
|
+
|
|
34
|
+
from .payload import base_payload, truncated_slice
|
|
35
|
+
from .safety import SKIP_DIRS, SafetyPolicy, UnsafePath
|
|
36
|
+
|
|
37
|
+
__all__ = ["GrepMode", "build_search_tools", "glob_payload", "grep_payload"]
|
|
38
|
+
|
|
39
|
+
GrepMode = Literal["files_with_matches", "content", "count"]
|
|
40
|
+
_DEFAULT_LIMIT = 200
|
|
41
|
+
_MODES: tuple[str, ...] = ("files_with_matches", "content", "count")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def glob_payload(
|
|
45
|
+
policy: SafetyPolicy, *, pattern: str, limit: int = _DEFAULT_LIMIT
|
|
46
|
+
) -> dict[str, Any]:
|
|
47
|
+
"""glob 纯逻辑:相对根的模式匹配,按修改时间倒序,跳过构建产物与根外符号链接。"""
|
|
48
|
+
if limit < 1:
|
|
49
|
+
raise ValueError(f"limit 必须为正,收到 {limit}")
|
|
50
|
+
raw = Path(pattern)
|
|
51
|
+
if raw.is_absolute() or ".." in raw.parts:
|
|
52
|
+
raise UnsafePath(f"拒绝越界的 glob 模式:{pattern}")
|
|
53
|
+
matches: list[Path] = []
|
|
54
|
+
for candidate in policy.root.glob(pattern):
|
|
55
|
+
if not candidate.is_file() or not policy.contains(candidate):
|
|
56
|
+
continue
|
|
57
|
+
parts = candidate.resolve().relative_to(policy.root).parts
|
|
58
|
+
if any(part in SKIP_DIRS for part in parts[:-1]):
|
|
59
|
+
continue
|
|
60
|
+
matches.append(candidate)
|
|
61
|
+
# 二级键用相对路径:mtime 相同的文件(同一批写入)也要有确定顺序,快照才稳
|
|
62
|
+
matches.sort(key=lambda item: (-item.stat().st_mtime, policy.relative(item)))
|
|
63
|
+
limited, truncated = truncated_slice(matches, limit)
|
|
64
|
+
entries: list[dict[str, Any]] = [
|
|
65
|
+
{"path": policy.relative(item), "size": item.stat().st_size} for item in limited
|
|
66
|
+
]
|
|
67
|
+
return base_payload(
|
|
68
|
+
"glob",
|
|
69
|
+
pattern=pattern,
|
|
70
|
+
count=len(matches),
|
|
71
|
+
truncated=truncated,
|
|
72
|
+
matches=entries,
|
|
73
|
+
text="\n".join(entry["path"] for entry in entries),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def grep_payload(
|
|
78
|
+
policy: SafetyPolicy,
|
|
79
|
+
*,
|
|
80
|
+
pattern: str,
|
|
81
|
+
path: str = ".",
|
|
82
|
+
file_glob: str = "*",
|
|
83
|
+
mode: GrepMode = "content",
|
|
84
|
+
max_matches: int = _DEFAULT_LIMIT,
|
|
85
|
+
) -> dict[str, Any]:
|
|
86
|
+
"""grep 纯逻辑:正则 + 文件类型过滤,三模式共用一次扫描,结果结构不同但同协议。"""
|
|
87
|
+
if mode not in _MODES:
|
|
88
|
+
raise ValueError(f"未知 grep 模式 {mode};可用:{', '.join(_MODES)}")
|
|
89
|
+
if max_matches < 1:
|
|
90
|
+
raise ValueError(f"max_matches 必须为正,收到 {max_matches}")
|
|
91
|
+
try:
|
|
92
|
+
compiled = re.compile(pattern)
|
|
93
|
+
except re.error as exc:
|
|
94
|
+
raise ValueError(f"非法正则 {pattern!r}:{exc};请修正后重试") from exc
|
|
95
|
+
base = policy.resolve(path)
|
|
96
|
+
if not base.exists():
|
|
97
|
+
raise ValueError(f"检索路径不存在:{path}")
|
|
98
|
+
|
|
99
|
+
hits: list[tuple[str, int, str]] = []
|
|
100
|
+
for candidate in policy.iter_files(path, file_glob):
|
|
101
|
+
relative = policy.relative(candidate)
|
|
102
|
+
for number, line in enumerate(
|
|
103
|
+
candidate.read_text(encoding="utf-8", errors="replace").splitlines(), 1
|
|
104
|
+
):
|
|
105
|
+
if "\x00" in line: # 二进制文件被 file_glob 兜进来时跳过,不污染命中列表
|
|
106
|
+
continue
|
|
107
|
+
if compiled.search(line):
|
|
108
|
+
hits.append((relative, number, line))
|
|
109
|
+
|
|
110
|
+
common: dict[str, Any] = {
|
|
111
|
+
"pattern": pattern,
|
|
112
|
+
"path": path,
|
|
113
|
+
"file_glob": file_glob,
|
|
114
|
+
"mode": mode,
|
|
115
|
+
}
|
|
116
|
+
if mode == "content":
|
|
117
|
+
limited, truncated = truncated_slice(hits, max_matches)
|
|
118
|
+
entries: list[dict[str, Any]] = [
|
|
119
|
+
{"path": item[0], "line": item[1], "text": item[2]} for item in limited
|
|
120
|
+
]
|
|
121
|
+
return base_payload(
|
|
122
|
+
"grep",
|
|
123
|
+
**common,
|
|
124
|
+
count=len(hits),
|
|
125
|
+
truncated=truncated,
|
|
126
|
+
matches=entries,
|
|
127
|
+
text="\n".join(f"{e['path']}:{e['line']}→{e['text']}" for e in entries),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
counts: dict[str, int] = {}
|
|
131
|
+
for relative, _number, _text in hits:
|
|
132
|
+
counts[relative] = counts.get(relative, 0) + 1
|
|
133
|
+
files: list[dict[str, Any]] = [
|
|
134
|
+
{"path": key, "count": value} for key, value in sorted(counts.items())
|
|
135
|
+
]
|
|
136
|
+
limited_files, truncated_files = truncated_slice(files, max_matches)
|
|
137
|
+
return base_payload(
|
|
138
|
+
"grep",
|
|
139
|
+
**common,
|
|
140
|
+
count=len(hits),
|
|
141
|
+
truncated=truncated_files,
|
|
142
|
+
files=limited_files,
|
|
143
|
+
text="\n".join(f"{e['path']}:{e['count']}" for e in limited_files),
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def build_search_tools(policy: SafetyPolicy) -> list[Tool]:
|
|
148
|
+
"""产出 glob / grep 两个只读工具;策略由工厂闭包定死,不进模型可见参数。"""
|
|
149
|
+
|
|
150
|
+
def glob(pattern: str, limit: int = _DEFAULT_LIMIT) -> dict[str, Any]:
|
|
151
|
+
"""按 glob 模式列出项目内文件路径,按修改时间倒序;结果超限时标记 truncated。"""
|
|
152
|
+
return glob_payload(policy, pattern=pattern, limit=limit)
|
|
153
|
+
|
|
154
|
+
def grep(
|
|
155
|
+
pattern: str,
|
|
156
|
+
path: str = ".",
|
|
157
|
+
file_glob: str = "*",
|
|
158
|
+
mode: GrepMode = "content",
|
|
159
|
+
max_matches: int = _DEFAULT_LIMIT,
|
|
160
|
+
) -> dict[str, Any]:
|
|
161
|
+
"""用正则检索项目内文本;mode 可选 content(命中行)/ files_with_matches / count。"""
|
|
162
|
+
return grep_payload(
|
|
163
|
+
policy,
|
|
164
|
+
pattern=pattern,
|
|
165
|
+
path=path,
|
|
166
|
+
file_glob=file_glob,
|
|
167
|
+
mode=mode,
|
|
168
|
+
max_matches=max_matches,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# 闭包 + PEP 563 的字符串注解无法被 @tool 的 get_type_hints 稳定解析,
|
|
172
|
+
# 显式还原成真实类型对象(同 files.py,与 M7 @sandboxed 同款防御)。
|
|
173
|
+
glob.__annotations__ = {"pattern": str, "limit": int, "return": dict[str, Any]}
|
|
174
|
+
grep.__annotations__ = {
|
|
175
|
+
"pattern": str,
|
|
176
|
+
"path": str,
|
|
177
|
+
"file_glob": str,
|
|
178
|
+
"mode": GrepMode,
|
|
179
|
+
"max_matches": int,
|
|
180
|
+
"return": dict[str, Any],
|
|
181
|
+
}
|
|
182
|
+
return [
|
|
183
|
+
tool(
|
|
184
|
+
glob,
|
|
185
|
+
name="glob",
|
|
186
|
+
description=(
|
|
187
|
+
"按 glob 模式列出项目内文件路径(如 core/*.py、**/*.md),按修改时间倒序;"
|
|
188
|
+
"返回结构化路径列表与截断标志。路径必须相对项目根。"
|
|
189
|
+
),
|
|
190
|
+
strict=True,
|
|
191
|
+
timeout=15.0,
|
|
192
|
+
),
|
|
193
|
+
tool(
|
|
194
|
+
grep,
|
|
195
|
+
name="grep",
|
|
196
|
+
description=(
|
|
197
|
+
"用正则表达式检索项目内文本文件;path 为相对根目录,file_glob 过滤文件类型,"
|
|
198
|
+
"mode 取 content(命中行)/ files_with_matches(命中文件)/ count(每文件命中数)。"
|
|
199
|
+
"返回结构化命中列表与截断标志。"
|
|
200
|
+
),
|
|
201
|
+
strict=True,
|
|
202
|
+
timeout=30.0,
|
|
203
|
+
),
|
|
204
|
+
]
|