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,458 @@
|
|
|
1
|
+
"""文件读 / 写工具(T10-2 的 read_file、T10-3 的 write_file / edit_file)。
|
|
2
|
+
|
|
3
|
+
设计不变量:
|
|
4
|
+
|
|
5
|
+
- **路径一律先过 SafetyPolicy**:项目根白名单 + ``Path.resolve()`` 消解 ``..`` /
|
|
6
|
+
符号链接 / 绝对路径,根外一律拒绝;路径校验不是工具各自的可选步骤。
|
|
7
|
+
- **UTF-8 显式声明**:``read_text(encoding="utf-8")`` / ``write_text(encoding="utf-8")``,
|
|
8
|
+
Windows 中文路径与中文内容都是验收项,不靠系统 locale 碰运气。
|
|
9
|
+
- **read_file 输出结构化**::
|
|
10
|
+
|
|
11
|
+
{"path": "core/runner.py", "lines": [{"n": 1, "text": "..."}],
|
|
12
|
+
"start_line": 1, "end_line": 80, "total_lines": 1503, "truncated": true}
|
|
13
|
+
|
|
14
|
+
``LINE→内容`` 只是给人看的文本投影;大文件截断必须带 ``truncated`` 标志,
|
|
15
|
+
不能悄悄丢行。
|
|
16
|
+
- **write / edit 产出 diff payload**:改动前后全文 + unified diff 文本 + 涉及文件,
|
|
17
|
+
冻结格式(``payload_version``)后 M11 前端直接消费,不允许前端自行 diff 计算。
|
|
18
|
+
- **edit 优先于整文件重写**:``old_string`` 不唯一即拒绝并要求附更多上下文,
|
|
19
|
+
``replace_all`` 显式开启才批量替换;编码 persona 提示词配套引导(T10-7)。
|
|
20
|
+
- 错误路径(文件不存在 / 只读 / 路径越界 / old_string 歧义)一律由 core 工具执行
|
|
21
|
+
管道收口成 ``is_error=True`` 的 ToolResult,不向 run 抛异常。
|
|
22
|
+
|
|
23
|
+
装配形态:**工厂注入策略**,不给模型传 root 参数——根目录是宿主的安全边界,
|
|
24
|
+
一旦进 schema 就等于把它交给模型决定。``@tool`` 需要真实类型注解生成 schema,
|
|
25
|
+
而闭包函数在 ``from __future__ import annotations`` 下拿到的是字符串,故工厂内
|
|
26
|
+
显式还原 ``__annotations__``(与 M7 ``@sandboxed`` 同类问题的同款解法)。
|
|
27
|
+
|
|
28
|
+
用法示例::
|
|
29
|
+
|
|
30
|
+
from mainspring_coding_tools.files import build_file_tools
|
|
31
|
+
|
|
32
|
+
tools = build_file_tools(SafetyPolicy(Path.cwd()))
|
|
33
|
+
agent = Agent(..., tools=tools)
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import difflib
|
|
39
|
+
import json
|
|
40
|
+
import os
|
|
41
|
+
from collections.abc import Sequence
|
|
42
|
+
from pathlib import Path
|
|
43
|
+
from typing import Any
|
|
44
|
+
|
|
45
|
+
from mainspring.tool import Tool, tool
|
|
46
|
+
from mainspring.types import ToolCall
|
|
47
|
+
|
|
48
|
+
from .payload import base_payload
|
|
49
|
+
from .safety import SafetyPolicy
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"build_file_tools",
|
|
53
|
+
"build_read_file_tools",
|
|
54
|
+
"build_write_tools",
|
|
55
|
+
"edit_payload",
|
|
56
|
+
"preview_diff_payload",
|
|
57
|
+
"read_file_payload",
|
|
58
|
+
"write_payload",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
_DEFAULT_MAX_LINES = 2000
|
|
62
|
+
# 单次读取的 payload 预算(T22),按**序列化后**的字符数估算而不是投影长度:
|
|
63
|
+
# read_file 的 payload 里 text(给人读的投影)与 lines(给前端的结构化数据)是同一份
|
|
64
|
+
# 内容的两份拷贝,JSON 序列化后约为投影的 2 倍。只按投影截断会踩坑——实测
|
|
65
|
+
# 投影 12000 字符的 payload 序列化后 26919,超过 core 的 tool_result_max_chars
|
|
66
|
+
# 后被头尾截断,续读提示正好落在被砍的中间段,模型于是以为「文件没有内容了」。
|
|
67
|
+
# 所以每行按 2*len+40(text + lines 的 JSON 骨架)计费,预算必须 ≤ 部署侧
|
|
68
|
+
# `agent.context.tool_result_max_chars`(mainspring.yaml 默认 20000)。
|
|
69
|
+
_DEFAULT_MAX_PAYLOAD_CHARS = 16000
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _bounded_slice(
|
|
73
|
+
window: Sequence[str], max_lines: int, max_payload_chars: int
|
|
74
|
+
) -> tuple[list[str], bool]:
|
|
75
|
+
"""行数与 payload 预算双上限,取更严的一个;返回(保留下来的行, 是否截断)。
|
|
76
|
+
|
|
77
|
+
每行按 ``2*len+40`` 计费:text 投影一份、lines 里的 JSON 一份,再加 ``{"n": 1, "text": ""}``
|
|
78
|
+
的骨架开销。允许单行超预算时仍保留该行——宁可给一行超长内容,也不返回空段落
|
|
79
|
+
让模型以为文件是空的。
|
|
80
|
+
"""
|
|
81
|
+
cap = max(1, max_lines)
|
|
82
|
+
kept: list[str] = []
|
|
83
|
+
used = 0
|
|
84
|
+
for text in window:
|
|
85
|
+
if len(kept) >= cap:
|
|
86
|
+
break
|
|
87
|
+
cost = 2 * len(text) + 40
|
|
88
|
+
if kept and used + cost > max_payload_chars:
|
|
89
|
+
break
|
|
90
|
+
kept.append(text)
|
|
91
|
+
used += cost
|
|
92
|
+
return kept, len(kept) < len(window)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def read_file_payload(
|
|
96
|
+
policy: SafetyPolicy,
|
|
97
|
+
*,
|
|
98
|
+
path: str,
|
|
99
|
+
start_line: int = 1,
|
|
100
|
+
end_line: int = 0,
|
|
101
|
+
max_lines: int = _DEFAULT_MAX_LINES,
|
|
102
|
+
max_payload_chars: int = _DEFAULT_MAX_PAYLOAD_CHARS,
|
|
103
|
+
) -> dict[str, Any]:
|
|
104
|
+
"""read_file 的纯逻辑:给定策略与参数产出结构化 payload,便于直接做快照测试。
|
|
105
|
+
|
|
106
|
+
参数用哨兵值而不是 ``int | None``:后者在 JSON Schema 里是 anyOf,
|
|
107
|
+
各家 strict 模式对 nullable 的处理不一致(有些要求 ``type: ["integer","null"]``),
|
|
108
|
+
哨兵 ``0`` 表示「读到末尾」把 schema 保持成纯标量,跨厂商零分歧。
|
|
109
|
+
|
|
110
|
+
截断时 payload 带 ``next_start_line``,文本投影末尾追加一句续读指令——
|
|
111
|
+
模型不必自己推算下一段从哪开始,也不会把「只读了前一半」当成全文。
|
|
112
|
+
"""
|
|
113
|
+
if start_line < 1:
|
|
114
|
+
raise ValueError(
|
|
115
|
+
f"start_line 必须从 1 开始(首行是 1;要从头读就传 start_line=1),收到 {start_line}"
|
|
116
|
+
)
|
|
117
|
+
if max_lines < 1:
|
|
118
|
+
raise ValueError(f"max_lines 必须为正,收到 {max_lines}")
|
|
119
|
+
if max_payload_chars < 1:
|
|
120
|
+
raise ValueError(f"max_payload_chars 必须为正,收到 {max_payload_chars}")
|
|
121
|
+
target = policy.resolve(path)
|
|
122
|
+
if not target.is_file():
|
|
123
|
+
raise ValueError(f"文件不存在或不是普通文件:{path}")
|
|
124
|
+
lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
125
|
+
total = len(lines)
|
|
126
|
+
start = start_line
|
|
127
|
+
end = total if end_line <= 0 else min(end_line, total)
|
|
128
|
+
if end < start:
|
|
129
|
+
# 空文件 / 起始行超出文件末尾:返回空窗口而不是报错,模型据此自行判断
|
|
130
|
+
end = start - 1
|
|
131
|
+
window = lines[start - 1 : end]
|
|
132
|
+
limited, truncated = _bounded_slice(window, max_lines, max_payload_chars)
|
|
133
|
+
entries = [{"n": start + index, "text": text} for index, text in enumerate(limited)]
|
|
134
|
+
projection = "\n".join(f"{entry['n']}→{entry['text']}" for entry in entries)
|
|
135
|
+
last_line = start + len(entries) - 1 if entries else start
|
|
136
|
+
next_start_line = last_line + 1 if truncated else None
|
|
137
|
+
relative = policy.relative(target)
|
|
138
|
+
if next_start_line is not None:
|
|
139
|
+
remaining = total - last_line
|
|
140
|
+
projection += (
|
|
141
|
+
f"\n[本段只读到第 {last_line} 行,共 {total} 行,还有 {remaining} 行未读。"
|
|
142
|
+
f'必须继续调用 read_file(path="{relative}", start_line={next_start_line}) '
|
|
143
|
+
f"读完剩余内容;全文读完之前不要下结论。]"
|
|
144
|
+
)
|
|
145
|
+
return base_payload(
|
|
146
|
+
"read_file",
|
|
147
|
+
path=relative,
|
|
148
|
+
encoding="utf-8",
|
|
149
|
+
start_line=start,
|
|
150
|
+
end_line=last_line,
|
|
151
|
+
total_lines=total,
|
|
152
|
+
truncated=truncated,
|
|
153
|
+
next_start_line=next_start_line,
|
|
154
|
+
lines=entries,
|
|
155
|
+
text=projection,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _read_utf8(target: Path) -> str:
|
|
160
|
+
"""读已有文件:通用换行归一成 LF,让 diff 只显示真实改动行(工具统一 LF 口径)。"""
|
|
161
|
+
return target.read_text(encoding="utf-8")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _write_utf8(target: Path, text: str) -> None:
|
|
165
|
+
"""写文件:UTF-8 + 显式 LF,自动建父目录;Windows 不把 \\n 悄悄变成 \\r\\n。"""
|
|
166
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
with target.open("w", encoding="utf-8", newline="\n") as handle:
|
|
168
|
+
handle.write(text)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _unified_diff(relative: str, before: str, after: str) -> str:
|
|
172
|
+
"""生成 git 风格 unified diff 文本;lineterm="" 让 join 不产生多余空行。"""
|
|
173
|
+
return "\n".join(
|
|
174
|
+
difflib.unified_diff(
|
|
175
|
+
before.splitlines(),
|
|
176
|
+
after.splitlines(),
|
|
177
|
+
fromfile=f"a/{relative}",
|
|
178
|
+
tofile=f"b/{relative}",
|
|
179
|
+
lineterm="",
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _diff_payload(
|
|
185
|
+
name: str,
|
|
186
|
+
relative: str,
|
|
187
|
+
before: str,
|
|
188
|
+
after: str,
|
|
189
|
+
*,
|
|
190
|
+
created: bool,
|
|
191
|
+
replacements: int,
|
|
192
|
+
) -> dict[str, Any]:
|
|
193
|
+
"""write / edit 共用同一份 diff payload(T12-2 前冻结,前端直接消费)。
|
|
194
|
+
|
|
195
|
+
``files`` 是涉及文件列表(当前单文件,留成列表是为了将来批量写不用改协议);
|
|
196
|
+
``before`` / ``after`` 是改动前后全文,``unified_diff`` 是投影兼高亮数据源。
|
|
197
|
+
"""
|
|
198
|
+
diff = _unified_diff(relative, before, after)
|
|
199
|
+
return base_payload(
|
|
200
|
+
name,
|
|
201
|
+
path=relative,
|
|
202
|
+
files=[relative],
|
|
203
|
+
before=before,
|
|
204
|
+
after=after,
|
|
205
|
+
unified_diff=diff,
|
|
206
|
+
created=created,
|
|
207
|
+
replacements=replacements,
|
|
208
|
+
text=diff or "(无改动)",
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def write_payload(policy: SafetyPolicy, *, path: str, content: str) -> dict[str, Any]:
|
|
213
|
+
"""write_file 纯逻辑:整文件写入 + diff payload;新文件自动建父目录。"""
|
|
214
|
+
target = policy.resolve(path)
|
|
215
|
+
created = not target.exists()
|
|
216
|
+
if target.exists() and not os.access(target, os.W_OK):
|
|
217
|
+
raise PermissionError(f"文件只读,拒绝写入:{path}")
|
|
218
|
+
before = "" if created else _read_utf8(target)
|
|
219
|
+
_write_utf8(target, content)
|
|
220
|
+
return _diff_payload(
|
|
221
|
+
"write_file",
|
|
222
|
+
policy.relative(target),
|
|
223
|
+
before,
|
|
224
|
+
content,
|
|
225
|
+
created=created,
|
|
226
|
+
replacements=1,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def edit_payload(
|
|
231
|
+
policy: SafetyPolicy,
|
|
232
|
+
*,
|
|
233
|
+
path: str,
|
|
234
|
+
old_string: str,
|
|
235
|
+
new_string: str,
|
|
236
|
+
replace_all: bool = False,
|
|
237
|
+
) -> dict[str, Any]:
|
|
238
|
+
"""edit_file 纯逻辑:精确字符串替换 + diff payload,对齐 Claude Code 的 edit 语义。
|
|
239
|
+
|
|
240
|
+
``old_string`` 不唯一即拒绝并要求附更多上下文——静默替换第一个命中会把
|
|
241
|
+
「模型以为改的是 A 处、实际改了 B 处」变成不可发现的错误。
|
|
242
|
+
"""
|
|
243
|
+
if not old_string:
|
|
244
|
+
raise ValueError("old_string 不能为空:请给出要替换的精确文本")
|
|
245
|
+
target = policy.resolve(path)
|
|
246
|
+
if not target.is_file():
|
|
247
|
+
raise ValueError(f"文件不存在或不是普通文件:{path}")
|
|
248
|
+
if not os.access(target, os.W_OK):
|
|
249
|
+
raise PermissionError(f"文件只读,拒绝编辑:{path}")
|
|
250
|
+
before = _read_utf8(target)
|
|
251
|
+
count = before.count(old_string)
|
|
252
|
+
if count == 0:
|
|
253
|
+
raise ValueError(f"old_string 未在 {path} 中找到:请先用 read_file 确认原文")
|
|
254
|
+
if count > 1 and not replace_all:
|
|
255
|
+
raise ValueError(
|
|
256
|
+
f"old_string 在 {path} 中出现 {count} 次,不唯一;"
|
|
257
|
+
"请附更多上下文使其唯一,或显式 replace_all=True 批量替换"
|
|
258
|
+
)
|
|
259
|
+
after = (
|
|
260
|
+
before.replace(old_string, new_string)
|
|
261
|
+
if replace_all
|
|
262
|
+
else before.replace(old_string, new_string, 1)
|
|
263
|
+
)
|
|
264
|
+
_write_utf8(target, after)
|
|
265
|
+
return _diff_payload(
|
|
266
|
+
"edit_file",
|
|
267
|
+
policy.relative(target),
|
|
268
|
+
before,
|
|
269
|
+
after,
|
|
270
|
+
created=False,
|
|
271
|
+
replacements=count if replace_all else 1,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def build_read_file_tools(policy: SafetyPolicy) -> list[Tool]:
|
|
276
|
+
"""只读文件工具(T10-2 的 read_file)。"""
|
|
277
|
+
|
|
278
|
+
def read_file(
|
|
279
|
+
path: str,
|
|
280
|
+
start_line: int = 1,
|
|
281
|
+
end_line: int = 0,
|
|
282
|
+
max_lines: int = _DEFAULT_MAX_LINES,
|
|
283
|
+
) -> dict[str, Any]:
|
|
284
|
+
"""读取项目内文本文件的指定行范围,返回带行号的结构化内容;大文件自动截断。"""
|
|
285
|
+
return read_file_payload(
|
|
286
|
+
policy,
|
|
287
|
+
path=path,
|
|
288
|
+
start_line=start_line,
|
|
289
|
+
end_line=end_line,
|
|
290
|
+
max_lines=max_lines,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
read_file.__annotations__ = {
|
|
294
|
+
"path": str,
|
|
295
|
+
"start_line": int,
|
|
296
|
+
"end_line": int,
|
|
297
|
+
"max_lines": int,
|
|
298
|
+
"return": dict[str, Any],
|
|
299
|
+
}
|
|
300
|
+
return [
|
|
301
|
+
tool(
|
|
302
|
+
read_file,
|
|
303
|
+
name="read_file",
|
|
304
|
+
description=(
|
|
305
|
+
"读取项目内文本文件的指定行范围,返回带行号的结构化内容与可读投影;"
|
|
306
|
+
"start_line 从 1 开始(首行是 1,从头读就传 start_line=1,不要传 0);"
|
|
307
|
+
"end_line=0 表示读到文件末尾;单次输出按行数与字符双上限截断,"
|
|
308
|
+
"截断时置 truncated 并给出 next_start_line——大文件按它逐段读完即可,"
|
|
309
|
+
"不要试图一次读完整个文件。路径必须相对项目根。"
|
|
310
|
+
),
|
|
311
|
+
strict=True,
|
|
312
|
+
timeout=15.0,
|
|
313
|
+
)
|
|
314
|
+
]
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def build_write_tools(policy: SafetyPolicy) -> list[Tool]:
|
|
318
|
+
"""写类工具(T10-3):write_file / edit_file,均产出结构化 diff payload。
|
|
319
|
+
|
|
320
|
+
审批不在这里实现:工具只负责「怎么改」,「该不该改」由 ``ApprovalHook`` 经
|
|
321
|
+
core 的 HITL 挂起点裁决(M1 红线:循环体冻结,不改 Runner)。
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
def write_file(path: str, content: str) -> dict[str, Any]:
|
|
325
|
+
"""整文件写入项目内文本文件(自动建父目录),返回改动前后与 unified diff。"""
|
|
326
|
+
return write_payload(policy, path=path, content=content)
|
|
327
|
+
|
|
328
|
+
def edit_file(
|
|
329
|
+
path: str,
|
|
330
|
+
old_string: str,
|
|
331
|
+
new_string: str,
|
|
332
|
+
replace_all: bool = False,
|
|
333
|
+
) -> dict[str, Any]:
|
|
334
|
+
"""精确字符串替换;old_string 不唯一时拒绝并要求附更多上下文或显式 replace_all。"""
|
|
335
|
+
return edit_payload(
|
|
336
|
+
policy,
|
|
337
|
+
path=path,
|
|
338
|
+
old_string=old_string,
|
|
339
|
+
new_string=new_string,
|
|
340
|
+
replace_all=replace_all,
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
write_file.__annotations__ = {"path": str, "content": str, "return": dict[str, Any]}
|
|
344
|
+
edit_file.__annotations__ = {
|
|
345
|
+
"path": str,
|
|
346
|
+
"old_string": str,
|
|
347
|
+
"new_string": str,
|
|
348
|
+
"replace_all": bool,
|
|
349
|
+
"return": dict[str, Any],
|
|
350
|
+
}
|
|
351
|
+
return [
|
|
352
|
+
tool(
|
|
353
|
+
write_file,
|
|
354
|
+
name="write_file",
|
|
355
|
+
description=(
|
|
356
|
+
"整文件写入项目内文本文件(自动建父目录),返回改动前后全文与 unified diff;"
|
|
357
|
+
"大改动优先用 edit_file 做精确替换。路径必须相对项目根。"
|
|
358
|
+
),
|
|
359
|
+
strict=True,
|
|
360
|
+
timeout=15.0,
|
|
361
|
+
),
|
|
362
|
+
tool(
|
|
363
|
+
edit_file,
|
|
364
|
+
name="edit_file",
|
|
365
|
+
description=(
|
|
366
|
+
"按精确字符串替换修改文件,返回改动前后全文与 unified diff;"
|
|
367
|
+
"old_string 不唯一会拒绝并要求附更多上下文,replace_all=True 才批量替换。"
|
|
368
|
+
"路径必须相对项目根。"
|
|
369
|
+
),
|
|
370
|
+
strict=True,
|
|
371
|
+
timeout=15.0,
|
|
372
|
+
),
|
|
373
|
+
]
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def build_file_tools(policy: SafetyPolicy) -> list[Tool]:
|
|
377
|
+
"""全部文件类工具:read_file / write_file / edit_file(共用同一份策略)。"""
|
|
378
|
+
return [*build_read_file_tools(policy), *build_write_tools(policy)]
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def preview_diff_payload(policy: SafetyPolicy, call: ToolCall) -> dict[str, Any]:
|
|
382
|
+
"""审批卡片用的**只读** diff 预览(T10-8):算出改动后长什么样,绝不落盘。
|
|
383
|
+
|
|
384
|
+
与 ``write_payload`` / ``edit_payload`` 共用 ``_diff_payload``,所以终端预览与
|
|
385
|
+
approve 之后真正产出的 diff payload 形状一致——人在 y/n 之前看到的,就是批准
|
|
386
|
+
之后会发生的。预览失败(路径越界 / 文件不存在 / old_string 未命中)不抛异常,
|
|
387
|
+
回填 ``previewable=False`` + 原因:审批交互不能因为展示层炸掉而卡死。
|
|
388
|
+
|
|
389
|
+
命令类工具没有文件 diff,返回 ``command`` 原文供人审阅,不伪造 diff。
|
|
390
|
+
"""
|
|
391
|
+
try:
|
|
392
|
+
args = json.loads(call.arguments or "{}")
|
|
393
|
+
except (ValueError, TypeError):
|
|
394
|
+
args = {}
|
|
395
|
+
if call.name == "bash":
|
|
396
|
+
return base_payload(
|
|
397
|
+
call.name,
|
|
398
|
+
kind="preview",
|
|
399
|
+
previewable=False,
|
|
400
|
+
reason="命令执行没有文件 diff,请直接审阅命令原文",
|
|
401
|
+
command=str(args.get("command", "")),
|
|
402
|
+
unified_diff="",
|
|
403
|
+
text=f"$ {args.get('command', '')}",
|
|
404
|
+
)
|
|
405
|
+
if call.name not in {"write_file", "edit_file"}:
|
|
406
|
+
return base_payload(
|
|
407
|
+
call.name,
|
|
408
|
+
kind="preview",
|
|
409
|
+
previewable=False,
|
|
410
|
+
reason=f"{call.name} 不改动文件,无需 diff 预览",
|
|
411
|
+
unified_diff="",
|
|
412
|
+
text=call.arguments,
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
try:
|
|
416
|
+
target = policy.resolve(str(args.get("path", "")))
|
|
417
|
+
except (ValueError, OSError) as exc: # 预览是展示层:策略异常只影响展示,裁决权仍在 Hook
|
|
418
|
+
return base_payload(
|
|
419
|
+
call.name,
|
|
420
|
+
kind="preview",
|
|
421
|
+
previewable=False,
|
|
422
|
+
reason=f"路径预览失败:{exc}",
|
|
423
|
+
unified_diff="",
|
|
424
|
+
text=call.arguments,
|
|
425
|
+
)
|
|
426
|
+
before = "" if not target.is_file() else _read_utf8(target)
|
|
427
|
+
if call.name == "write_file":
|
|
428
|
+
after = str(args.get("content", ""))
|
|
429
|
+
replacements = 1
|
|
430
|
+
else:
|
|
431
|
+
old = str(args.get("old_string", ""))
|
|
432
|
+
new = str(args.get("new_string", ""))
|
|
433
|
+
count = before.count(old) if old else 0
|
|
434
|
+
if count == 0:
|
|
435
|
+
return base_payload(
|
|
436
|
+
call.name,
|
|
437
|
+
kind="preview",
|
|
438
|
+
path=policy.relative(target),
|
|
439
|
+
previewable=False,
|
|
440
|
+
reason="old_string 未命中当前文件,预览不可用(工具执行时也会拒绝)",
|
|
441
|
+
unified_diff="",
|
|
442
|
+
text=call.arguments,
|
|
443
|
+
)
|
|
444
|
+
after = before.replace(old, new) if args.get("replace_all") else before.replace(old, new, 1)
|
|
445
|
+
replacements = count if args.get("replace_all") else 1
|
|
446
|
+
return {
|
|
447
|
+
**_diff_payload(
|
|
448
|
+
call.name,
|
|
449
|
+
policy.relative(target),
|
|
450
|
+
before,
|
|
451
|
+
after,
|
|
452
|
+
created=not target.exists(),
|
|
453
|
+
replacements=replacements,
|
|
454
|
+
),
|
|
455
|
+
"kind": "preview",
|
|
456
|
+
"previewable": True,
|
|
457
|
+
"reason": None,
|
|
458
|
+
}
|