@vessel-agent/basic-tools 0.0.0-stage → 2.3.0-beta.3

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,151 @@
1
+ /**
2
+ * basic-tools read 工具(W1-3 纯移动自 index.ts,零行为变更):
3
+ * 带行号读文件(offset/limit 分页),路径边界与 bash 同一套。
4
+ */
5
+
6
+ import { existsSync, readFileSync, statSync } from 'node:fs';
7
+ import type { ToolContext, ToolDefinition } from '@vessel-agent/core';
8
+ import { activeBoundary } from '../call-scope.js';
9
+ import type { BasicToolsConfig } from '../config.js';
10
+ import {
11
+ dependsOnBaseCwd,
12
+ evaluatePath,
13
+ type PathBoundary,
14
+ resolveCallCwd,
15
+ resolveToolPath,
16
+ } from '../path-boundary.js';
17
+ import {
18
+ boundToolOutput,
19
+ CANCELLED_TEXT,
20
+ isRecord,
21
+ MAX_READ_BYTES,
22
+ PATH_DENIED_TEXT,
23
+ readNumber,
24
+ readString,
25
+ } from '../shared.js';
26
+ import { splitLines } from '../text.js';
27
+
28
+ /** read 缺省读取行数(导出供 doc-subscription read 订阅规范化同口径,单一真源) */
29
+ export const DEFAULT_READ_LIMIT = 2000;
30
+
31
+ // ── read ─────────────────────────────────────────
32
+
33
+ /** 读出带行号的文本片段(行号从 1 开始,`<行号>\t<内容>`) */
34
+ function readFileSlice(
35
+ args: unknown,
36
+ ctx: ToolContext,
37
+ boundary: PathBoundary,
38
+ config: BasicToolsConfig,
39
+ ): string {
40
+ const signal = ctx.signal;
41
+ if (signal?.aborted) return CANCELLED_TEXT;
42
+ if (!isRecord(args)) return '错误:read 需要 { path: string }';
43
+ const inputPath = readString(args, 'path');
44
+ if (inputPath === '') return '错误:path 不能为空';
45
+ const baseCwd = resolveCallCwd(config, ctx.cwd);
46
+ const absolute = resolveToolPath(baseCwd.path, inputPath);
47
+ // 防御性检查:即使调用方绕过 checkPermission,也绝不读取敏感路径。
48
+ // 相对路径先按 baseCwd 解析,边界按解析后的绝对路径判定(不因 baseCwd 放宽)。
49
+ if (evaluatePath(absolute, boundary) === 'deny') {
50
+ return PATH_DENIED_TEXT;
51
+ }
52
+ if (dependsOnBaseCwd(inputPath) && baseCwd.issue !== undefined) return baseCwd.issue;
53
+
54
+ if (!existsSync(absolute)) return `错误:文件不存在:${inputPath}`;
55
+
56
+ let stat: ReturnType<typeof statSync>;
57
+ try {
58
+ stat = statSync(absolute);
59
+ } catch (error) {
60
+ return `错误:无法访问 ${inputPath}:${String(error)}`;
61
+ }
62
+ if (stat.isDirectory()) return `错误:${inputPath} 是目录,不是文件(用 bash 列出目录)`;
63
+ if (!stat.isFile()) return `错误:${inputPath} 不是普通文件`;
64
+ if (stat.size > MAX_READ_BYTES) {
65
+ return `错误:文件过大(${stat.size} 字节,上限 ${MAX_READ_BYTES} 字节)。请用 bash 分块读取(如 sed -n '1,2000p')。`;
66
+ }
67
+
68
+ let text: string;
69
+ try {
70
+ text = readFileSync(absolute, 'utf-8');
71
+ } catch (error) {
72
+ return `错误:读取失败:${String(error)}`;
73
+ }
74
+ if (text.includes('\0')) {
75
+ return `错误:${inputPath} 看起来是二进制文件(含 NUL 字节),read 只处理文本。`;
76
+ }
77
+
78
+ const lines = splitLines(text);
79
+ const total = lines.length;
80
+ if (total === 0) return `(空文件:${inputPath})`;
81
+
82
+ const offset = readNumber(args, 'offset') ?? 1;
83
+ if (!Number.isInteger(offset) || offset < 1) {
84
+ return '错误:offset 必须是不小于 1 的整数(行号从 1 开始)';
85
+ }
86
+ if (offset > total) {
87
+ return `错误:offset(${offset})超过文件总行数(${total})`;
88
+ }
89
+
90
+ const limit = readNumber(args, 'limit') ?? DEFAULT_READ_LIMIT;
91
+ if (!Number.isInteger(limit) || limit < 1) {
92
+ return '错误:limit 必须是不小于 1 的整数';
93
+ }
94
+
95
+ const slice = lines.slice(offset - 1, offset - 1 + limit);
96
+ const numbered = slice.map((line, index) => `${offset + index}\t${line}`).join('\n');
97
+ const lastLine = offset - 1 + slice.length;
98
+
99
+ if (lastLine < total) {
100
+ return `${numbered}\n\n已截断,共 ${total} 行,用 offset/limit 继续读(本次已读第 ${offset}-${lastLine} 行)`;
101
+ }
102
+ return numbered;
103
+ }
104
+
105
+ /** 构造 read 工具(路径边界随配置固定;默认工作目录按调用期解析) */
106
+ export function createReadTool(boundary: PathBoundary, config: BasicToolsConfig): ToolDefinition {
107
+ return {
108
+ name: 'read',
109
+ description:
110
+ 'Read a text file and return its content with line numbers (1-based, `<line>\\t<content>`). ' +
111
+ `Use offset/limit to page through large files (limit defaults to ${DEFAULT_READ_LIMIT} lines). ` +
112
+ 'Prefer this tool over bash commands such as cat/sed/head/tail/awk for reading file contents. ' +
113
+ 'Reading does NOT auto-subscribe by default; subscribe:true opts in to change notices ' +
114
+ 'for the line ranges you read.',
115
+ inputSchema: {
116
+ type: 'object',
117
+ properties: {
118
+ path: { type: 'string', description: 'File path' },
119
+ offset: { type: 'number', description: 'First line to read (1-based, default 1)' },
120
+ limit: {
121
+ type: 'number',
122
+ description: `How many lines to read (default ${DEFAULT_READ_LIMIT})`,
123
+ },
124
+ subscribe: {
125
+ type: 'boolean',
126
+ description:
127
+ 'Opt in to change notices for the line ranges you read (default off: a one-off read ' +
128
+ 'does not subscribe). true = explicit opt-in subscription; false = no subscription. ' +
129
+ 'Opt-in read subscriptions expire when the read references leave the context window.',
130
+ },
131
+ },
132
+ required: ['path'],
133
+ },
134
+ // 只读操作无副作用;敏感路径 deny、配置 allowed_roots 后越界 ask
135
+ concurrencySafe: true,
136
+ checkPermission: async (input, ctx) => {
137
+ if (!isRecord(input)) return 'allow';
138
+ const inputPath = readString(input, 'path');
139
+ if (inputPath === '') return 'allow';
140
+ // 与 handler 同一条解析路径:相对路径按调用期默认目录,再按绝对路径判定边界
141
+ return evaluatePath(
142
+ resolveToolPath(resolveCallCwd(config, ctx.cwd).path, inputPath),
143
+ boundary,
144
+ );
145
+ },
146
+ // 出口闸(token 预算):2000 行 × 每行几千字符的文件同样能一次灌满窗口,
147
+ // 所以 read 也必须过同一个 boundToolResult,而不是只靠「文件 ≤ 8 MiB」这一道闸。
148
+ handler: async (args, ctx) =>
149
+ boundToolOutput(ctx, 'read', readFileSlice(args, ctx, activeBoundary(boundary), config)),
150
+ };
151
+ }
@@ -0,0 +1,494 @@
1
+ /**
2
+ * basic-tools write 工具(W1-3 纯移动自 index.ts,零行为变更):
3
+ * 建文件 / 整体替换 / 追加,内容逐字节落盘不经 shell;写临界区经 runWithWriteLock。
4
+ */
5
+
6
+ import { randomUUID } from 'node:crypto';
7
+ import {
8
+ closeSync,
9
+ existsSync,
10
+ fchmodSync,
11
+ fsyncSync,
12
+ linkSync,
13
+ mkdirSync,
14
+ openSync,
15
+ readFileSync,
16
+ readSync,
17
+ renameSync,
18
+ statSync,
19
+ unlinkSync,
20
+ writeFileSync,
21
+ } from 'node:fs';
22
+ import * as path from 'node:path';
23
+ import type { ToolContext, ToolDefinition } from '@vessel-agent/core';
24
+ import { activeBoundary } from '../call-scope.js';
25
+ import type { BasicToolsConfig } from '../config.js';
26
+ import {
27
+ canonicalPath,
28
+ dependsOnBaseCwd,
29
+ evaluatePath,
30
+ isDirectory,
31
+ type PathBoundary,
32
+ resolveCallCwd,
33
+ resolveToolPath,
34
+ } from '../path-boundary.js';
35
+ import {
36
+ CANCELLED_TEXT,
37
+ isRecord,
38
+ MAX_LINE_SCAN_BYTES,
39
+ MAX_WRITE_BYTES,
40
+ PATH_DENIED_TEXT,
41
+ readString,
42
+ } from '../shared.js';
43
+ import { splitLines } from '../text.js';
44
+ import {
45
+ recordCoordNotice,
46
+ runWithWriteLock,
47
+ WRITE_CONFLICT_SCOPE,
48
+ WRITE_CONFLICT_SUMMARY,
49
+ } from '../write-coord.js';
50
+
51
+ // ── write ────────────────────────────────────────
52
+ //
53
+ // 存在理由:`edit` 只能替换**已有文件里的精确文本**,所以「建文件 / 追加」只能走
54
+ // `bash` 的 heredoc / 重定向 —— 而那条路内容要过一遍 shell + 沙箱预处理,反引号 / `$(`
55
+ // / `${…}` 会被先展开,写坏了 bash 退出码照样 0(0.56 真机事故:写架构文档时整段代码块
56
+ // 静默消失)。`write` 把 content 当**数据**收:不经过 shell、不做任何转义或展开,
57
+ // 落盘字节 = 入参字节。
58
+ //
59
+ // 契约(宁可不便利,不许静默):
60
+ // - `create`(缺省):文件已存在则**报错**,不静默覆盖 —— 覆盖是破坏性操作,
61
+ // 必须由调用方显式说 `overwrite`。
62
+ // - `overwrite`:整体替换;目标不存在时等价于建文件(语义是「把这个路径的内容变成这段」,
63
+ // 不把「文件本来不存在」当成错误,但会在回执里说清)。
64
+ // - `append`:追加到末尾;目标不存在时创建(与 `>>` 一致)。
65
+ // - 父目录:**只自动创建一级**不存在的父目录。更深的不猜 —— 猜错目录是「写到一个
66
+ // 你以为不存在的地方」这类事故的源头,模型该自己先说清路径(`mkdir` 在 bash 里)。
67
+ // - 上限 4 MiB(`MAX_WRITE_BYTES`),超了报错并给字节数,不截断。
68
+ //
69
+ // 原子性:create / overwrite 先写**同目录**临时文件 + fsync,再落位(同目录是为了 rename
70
+ // 不会跨设备)。create 落位用 `link` 而不是 `rename`:rename 会静默覆盖,link 在目标已存在时
71
+ // 报 EEXIST —— 这样「检查已存在」和「落盘」之间没有 TOCTOU 窗口。append 走 `O_APPEND` + fsync。
72
+
73
+ /** write 的三种模式 */
74
+ type WriteMode = 'create' | 'overwrite' | 'append';
75
+
76
+ /** 千分位格式化(只用于回执 / 报错里的读数,不用 locale,保证确定性) */
77
+ function groupThousands(value: number): string {
78
+ return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
79
+ }
80
+
81
+ /** 按 `splitLines` 同一口径数行数(末尾换行不额外算一行) */
82
+ function countTextLines(text: string): number {
83
+ return splitLines(text).length;
84
+ }
85
+
86
+ /** errno 码判定(`code` 是 Node 错误对象上的稳定字段) */
87
+ function isErrnoCode(error: unknown, code: string): boolean {
88
+ return isRecord(error) && (error as { code?: unknown }).code === code;
89
+ }
90
+
91
+ /** 不支持硬链接的 errno(create 的排他落盘在这些盘上退回 rename) */
92
+ const LINK_UNSUPPORTED_CODES = new Set([
93
+ 'ENOSYS',
94
+ 'EPERM',
95
+ 'EOPNOTSUPP',
96
+ 'ENOTSUP',
97
+ 'EXDEV',
98
+ 'EMLINK',
99
+ ]);
100
+
101
+ /** 同目录临时文件路径(create / overwrite 共用;pid + 时间戳 + 随机段,避免并发撞名) */
102
+ function tempPathFor(absolutePath: string): string {
103
+ const nonce = randomUUID().slice(0, 8);
104
+ return `${absolutePath}.vessel-tmp-${process.pid}-${Date.now()}-${nonce}`;
105
+ }
106
+
107
+ /**
108
+ * 原子整体写(overwrite 用):临时文件 → fsync → rename。
109
+ * fsync 在 rename **之前**:否则崩溃可能留下「名字对了、内容是空的」文件。
110
+ */
111
+ function writeFileAtomicDurable(absolutePath: string, content: string, mode?: number): void {
112
+ const tempPath = tempPathFor(absolutePath);
113
+ try {
114
+ const fd = openSync(tempPath, 'w');
115
+ try {
116
+ writeFileSync(fd, content, 'utf-8');
117
+ // 覆盖时沿用原文件的权限位:临时文件的默认 0644 会把可执行脚本 / 0600 的密钥文件降级,
118
+ // 而「内容对了、权限变了」这种副作用同样不会被任何工具报出来。
119
+ if (mode !== undefined) fchmodSync(fd, mode);
120
+ fsyncSync(fd);
121
+ } finally {
122
+ closeSync(fd);
123
+ }
124
+ renameSync(tempPath, absolutePath);
125
+ } catch (error) {
126
+ try {
127
+ unlinkSync(tempPath);
128
+ } catch {
129
+ // 临时文件可能未创建,忽略
130
+ }
131
+ throw error;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * 排他落盘(create 用):临时文件 → fsync → link。
137
+ * link 在目标已存在时抛 EEXIST,不会像 rename 那样静默覆盖 —— 这是「create 绝不覆盖」的
138
+ * 最后一道保证(前面的 existsSync 只用于给出更好的报错文案)。
139
+ *
140
+ * 回退:极少数文件系统不支持硬链接(exFAT / 部分网络盘)。那时退回「二次确认不存在 + rename」,
141
+ * 与前面的 existsSync 检查之间留一个极窄的窗口 —— 但在不支持硬链接的盘上,「工具直接坏掉」
142
+ * 是更糟的结果,而且窗口只在多人同时写同一路径时才可能被踩到。
143
+ */
144
+ function createFileExclusiveDurable(absolutePath: string, content: string): void {
145
+ const tempPath = tempPathFor(absolutePath);
146
+ try {
147
+ const fd = openSync(tempPath, 'w');
148
+ try {
149
+ writeFileSync(fd, content, 'utf-8');
150
+ fsyncSync(fd);
151
+ } finally {
152
+ closeSync(fd);
153
+ }
154
+ try {
155
+ linkSync(tempPath, absolutePath);
156
+ } catch (error) {
157
+ if (!LINK_UNSUPPORTED_CODES.has(String((error as { code?: unknown }).code))) throw error;
158
+ if (existsSync(absolutePath)) {
159
+ const conflict = new Error(`文件已存在:${absolutePath}`) as NodeJS.ErrnoException;
160
+ conflict.code = 'EEXIST';
161
+ throw conflict;
162
+ }
163
+ renameSync(tempPath, absolutePath);
164
+ }
165
+ } finally {
166
+ try {
167
+ unlinkSync(tempPath);
168
+ } catch {
169
+ // 未创建 / 已清理,忽略
170
+ }
171
+ }
172
+ }
173
+
174
+ /** 追加(append 用):O_APPEND 一次写入并 fsync */
175
+ function appendToFileDurable(absolutePath: string, content: string): void {
176
+ const fd = openSync(absolutePath, 'a');
177
+ try {
178
+ writeFileSync(fd, content, 'utf-8');
179
+ fsyncSync(fd);
180
+ } finally {
181
+ closeSync(fd);
182
+ }
183
+ }
184
+
185
+ /** 流式扫一遍文件的行数 / 字节数(append 的「共 N 行」读数用;不整读进内存) */
186
+ function scanFileStats(absolutePath: string): { lines: number; bytes: number } | undefined {
187
+ // 先看体积:超过扫描上限就干脆不数(见 `MAX_LINE_SCAN_BYTES`),别让一次 append 顺带读 GB 级文件
188
+ try {
189
+ if (Number(statSync(absolutePath).size) > MAX_LINE_SCAN_BYTES) return undefined;
190
+ } catch {
191
+ return undefined;
192
+ }
193
+ let fd: number | undefined;
194
+ const chunk = Buffer.allocUnsafe(64 * 1024);
195
+ let newlines = 0;
196
+ let bytes = 0;
197
+ let lastByte = -1;
198
+ try {
199
+ fd = openSync(absolutePath, 'r');
200
+ for (;;) {
201
+ const read = readSync(fd, chunk, 0, chunk.length, null);
202
+ if (read <= 0) break;
203
+ for (let i = 0; i < read; i += 1) {
204
+ if (chunk[i] === 0x0a) newlines += 1;
205
+ }
206
+ lastByte = chunk[read - 1] ?? lastByte;
207
+ bytes += read;
208
+ }
209
+ } catch {
210
+ return undefined;
211
+ } finally {
212
+ if (fd !== undefined) closeSync(fd);
213
+ }
214
+ if (bytes === 0) return { lines: 0, bytes: 0 };
215
+ return { lines: lastByte === 0x0a ? newlines : newlines + 1, bytes };
216
+ }
217
+
218
+ /** 文件最后一个字节(判断追加是否接在「没有换行的最后一行」后面;空文件返回 undefined) */
219
+ function lastByteOf(absolutePath: string): number | undefined {
220
+ let fd: number | undefined;
221
+ try {
222
+ const size = statSync(absolutePath).size;
223
+ if (size === 0) return undefined;
224
+ fd = openSync(absolutePath, 'r');
225
+ const one = Buffer.allocUnsafe(1);
226
+ const read = readSync(fd, one, 0, 1, size - 1);
227
+ return read === 1 ? one[0] : undefined;
228
+ } catch {
229
+ return undefined;
230
+ } finally {
231
+ if (fd !== undefined) closeSync(fd);
232
+ }
233
+ }
234
+
235
+ /** create 撞已有文件时的报错:说清三条出路,别让模型猜 */
236
+ function existingFileMessage(inputPath: string): string {
237
+ return (
238
+ `错误:文件已存在:${inputPath}(未做任何改动)。` +
239
+ '要整体替换用 mode=overwrite;要局部修改用 edit(逐字符唯一匹配,找不到会报错);' +
240
+ '要追加用 mode=append。'
241
+ );
242
+ }
243
+
244
+ /** 单次内容超过上限的报错(不截断、不静默写半截) */
245
+ function tooLargeMessage(bytes: number): string {
246
+ return (
247
+ `错误:内容过大(${groupThousands(bytes)} 字节,单次上限 ${groupThousands(MAX_WRITE_BYTES)} 字节 = 4 MiB),未写入。` +
248
+ '请拆成多次 write(create + append),或改用 bash 搬运大文件。'
249
+ );
250
+ }
251
+
252
+ /**
253
+ * 建文件 / 整体替换 / 追加。
254
+ * 路径解析与边界判定与 read / edit **同一条实现**(`resolveToolPath` + `evaluatePath`),
255
+ * 所以 deny_paths / 内置 denylist / symlink 逃逸 / 成员 cwd 的语义与它们逐条一致。
256
+ */
257
+ function writeFileText(
258
+ args: unknown,
259
+ ctx: ToolContext,
260
+ boundary: PathBoundary,
261
+ config: BasicToolsConfig,
262
+ ): string {
263
+ const signal = ctx.signal;
264
+ if (signal?.aborted) return CANCELLED_TEXT;
265
+ if (!isRecord(args)) return '错误:write 需要 { path, content, mode? }';
266
+ const inputPath = readString(args, 'path');
267
+ if (inputPath === '') return '错误:path 不能为空';
268
+ // content 用 typeof 判而不是 readString:空字符串是合法内容(建空文件),不能和「没传」混淆
269
+ if (typeof args.content !== 'string') {
270
+ return '错误:content 必须是字符串(UTF-8 文本);要建空文件请显式传 content: ""';
271
+ }
272
+ const content = args.content;
273
+
274
+ const rawMode = args.mode;
275
+ let mode: WriteMode;
276
+ if (rawMode === undefined || rawMode === 'create') mode = 'create';
277
+ else if (rawMode === 'overwrite' || rawMode === 'append') mode = rawMode;
278
+ else {
279
+ return `错误:mode 只能是 create / overwrite / append(收到 ${JSON.stringify(rawMode)});缺省是 create。`;
280
+ }
281
+
282
+ const bytes = Buffer.byteLength(content, 'utf-8');
283
+ if (bytes > MAX_WRITE_BYTES) return tooLargeMessage(bytes);
284
+
285
+ const baseCwd = resolveCallCwd(config, ctx.cwd);
286
+ const absolute = resolveToolPath(baseCwd.path, inputPath);
287
+ // 防御性检查:与 read / edit 同一条边界;绕过 checkPermission 也不得写敏感路径。
288
+ // symlink 逃逸同样在这里被拦:evaluatePath 按 canonicalPath(realpath)判定。
289
+ if (evaluatePath(absolute, boundary) === 'deny') return PATH_DENIED_TEXT;
290
+ if (dependsOnBaseCwd(inputPath) && baseCwd.issue !== undefined) return baseCwd.issue;
291
+
292
+ // 目标现状:只区分「不存在 / 普通文件 / 别的」。硬链接与符号链接的**指向**已由边界判定处理。
293
+ let existing: ReturnType<typeof statSync> | undefined;
294
+ if (existsSync(absolute)) {
295
+ try {
296
+ existing = statSync(absolute);
297
+ } catch (error) {
298
+ return `错误:无法访问 ${inputPath}:${String(error)}`;
299
+ }
300
+ if (existing.isDirectory()) return `错误:${inputPath} 是目录,不是文件`;
301
+ if (!existing.isFile()) return `错误:${inputPath} 不是普通文件`;
302
+ }
303
+
304
+ if (mode === 'create' && existing !== undefined) return existingFileMessage(inputPath);
305
+
306
+ // 父目录:只自动建一级(见本节顶部注释)。目标已存在时父目录必然存在,跳过。
307
+ let createdDir = false;
308
+ if (existing === undefined) {
309
+ const parent = path.dirname(absolute);
310
+ if (!isDirectory(parent)) {
311
+ if (existsSync(parent)) {
312
+ return `错误:${path.dirname(inputPath)} 已存在但不是目录,无法在其下建文件。`;
313
+ }
314
+ if (!isDirectory(path.dirname(parent))) {
315
+ return (
316
+ `错误:父目录不存在:${path.dirname(inputPath)}(write 只自动创建**一级**不存在的父目录,` +
317
+ '更深的路径请先用 bash 进入目标目录再写,或先 mkdir 建好)。'
318
+ );
319
+ }
320
+ try {
321
+ mkdirSync(parent);
322
+ createdDir = true;
323
+ } catch (error) {
324
+ return `错误:创建父目录失败:${String(error)}`;
325
+ }
326
+ }
327
+ }
328
+
329
+ // 落盘前再查一次取消:不允许「取消后留下半次写入」
330
+ if (signal?.aborted) return CANCELLED_TEXT;
331
+
332
+ const dirNote = createdDir ? ` · 新建父目录 ${path.dirname(inputPath)}` : '';
333
+
334
+ // 落盘目标:目标已存在时按 realpath 写**指到的那个文件**(符号链接不被替换成普通文件)。
335
+ // 边界判定用的也是 canonicalPath,所以在「链接指向 deny 目录」这种情况下早就在上面被拒了;
336
+ // 这里只解决「链接指向允许目录」时的写入语义,与 bash 的 `>` 一致。
337
+ const writeTarget = existing === undefined ? absolute : canonicalPath(absolute);
338
+
339
+ // expected_content(可选,仅 overwrite;蜂群 Phase 1 第一重保险):临界区内逐字节比对,
340
+ // 不符 → 稳定错误不写,逼重读(防 L-010 类陈旧 read 后 overwrite 静默抹除)。
341
+ // 不传 = 今天行为零回归。比对在写锁临界区内完成(handler 层持锁,见 runWithWriteLock)。
342
+ if (mode === 'overwrite' && args.expected_content !== undefined) {
343
+ if (typeof args.expected_content !== 'string') {
344
+ return '错误:expected_content 必须是字符串(UTF-8 文本,你最近一次读到的当前全文)。';
345
+ }
346
+ let current: Buffer;
347
+ try {
348
+ current = existing === undefined ? Buffer.alloc(0) : readFileSync(writeTarget);
349
+ } catch (error) {
350
+ return `错误:读取当前内容失败(expected_content 比对):${String(error)}`;
351
+ }
352
+ if (!current.equals(Buffer.from(args.expected_content, 'utf-8'))) {
353
+ const currentLines = countTextLines(current.toString('utf-8'));
354
+ // 表面记录(additive):并发修改冲突是环境事实,下次请求前注入 conflict 卡;
355
+ // 工具失败语义不变,仍返回原错误文本。签名按绝对路径(同一文件的不同拼写去重)。
356
+ recordCoordNotice(ctx.session_id, {
357
+ scope: WRITE_CONFLICT_SCOPE,
358
+ summary: WRITE_CONFLICT_SUMMARY,
359
+ details: [
360
+ `path: ${inputPath}`,
361
+ `current: ${groupThousands(current.byteLength)} bytes / ${groupThousands(currentLines)} lines`,
362
+ ],
363
+ signature: `${WRITE_CONFLICT_SCOPE}|${absolute}`,
364
+ });
365
+ return (
366
+ `错误:expected_content 与当前文件内容不符,未写入(当前 ${groupThousands(current.byteLength)} 字节 / ` +
367
+ `${groupThousands(currentLines)} 行)。文件在你读取后已被改动:请用 read 重读最新内容,` +
368
+ '更新 expected_content 后重试,或改用 edit 做局部修改。'
369
+ );
370
+ }
371
+ }
372
+
373
+ if (mode === 'append') {
374
+ // 追加前记一下原文件末尾:没有换行的文件直接追加会把内容接到最后一行后面,值得说一句
375
+ const previousSize = existing === undefined ? 0 : Number(existing.size);
376
+ const tailByte =
377
+ existing === undefined || previousSize === 0 ? undefined : lastByteOf(writeTarget);
378
+ try {
379
+ appendToFileDurable(writeTarget, content);
380
+ } catch (error) {
381
+ return `错误:写入失败:${String(error)}`;
382
+ }
383
+ const stats = scanFileStats(writeTarget);
384
+ const totalBytes = stats === undefined ? previousSize + bytes : stats.bytes;
385
+ const totalLinesPart = stats === undefined ? '' : ` · 共 ${groupThousands(stats.lines)} 行`;
386
+ // 原文件末尾没有换行时,追加的第一行会**接到最后一行后面**(净增行数比 content 行数少 1)。
387
+ // 不替调用方补换行(content 必须逐字节落盘),但把这件事和真实净增行数说清楚。
388
+ const merged = tailByte !== undefined && tailByte !== 0x0a && content !== '';
389
+ const contentLines = countTextLines(content);
390
+ const addedLines = merged ? Math.max(0, contentLines - 1) : contentLines;
391
+ const mergeNote = merged ? '(原文件末尾没有换行,追加内容接在最后一行之后)' : '';
392
+ const createdNote = existing === undefined ? ' · 文件原先不存在,已创建' : '';
393
+ return (
394
+ `已追加 ${inputPath}(append · +${groupThousands(addedLines)} 行${totalLinesPart} · ` +
395
+ `${groupThousands(totalBytes)} 字节${createdNote}${dirNote})${mergeNote}`
396
+ );
397
+ }
398
+
399
+ try {
400
+ if (mode === 'create') createFileExclusiveDurable(absolute, content);
401
+ else
402
+ writeFileAtomicDurable(
403
+ writeTarget,
404
+ content,
405
+ existing === undefined ? undefined : Number(existing.mode) & 0o7777,
406
+ );
407
+ } catch (error) {
408
+ // 并发下 existsSync 可能漏判(另一进程刚好建成):link 的 EEXIST 是准确答案
409
+ if (isErrnoCode(error, 'EEXIST')) return existingFileMessage(inputPath);
410
+ return `错误:写入失败:${String(error)}`;
411
+ }
412
+
413
+ const lines = countTextLines(content);
414
+ if (mode === 'overwrite' && existing !== undefined) {
415
+ // statSync 的 size 在 bigint 模式下是 bigint;这里统一按 number 展示(回执只用于读数)
416
+ const previousBytes = Number(existing.size);
417
+ return `已写入 ${inputPath}(overwrite · ${groupThousands(lines)} 行 · ${groupThousands(bytes)} 字节 · 原 ${groupThousands(previousBytes)} 字节${dirNote})`;
418
+ }
419
+ const createdNote = mode === 'overwrite' ? ' · 文件原先不存在,已创建' : '';
420
+ return `已写入 ${inputPath}(${mode} · ${groupThousands(lines)} 行 · ${groupThousands(bytes)} 字节${createdNote}${dirNote})`;
421
+ }
422
+
423
+ /** 构造 write 工具(相对路径按调用期默认目录解析;路径边界与 read / edit 相同) */
424
+ export function createWriteTool(boundary: PathBoundary, config: BasicToolsConfig): ToolDefinition {
425
+ return {
426
+ name: 'write',
427
+ description:
428
+ 'Write a whole file: create, replace entirely, or append. Use this — not bash heredocs / ' +
429
+ 'redirection — whenever the content is text you already have: it is stored byte-for-byte ' +
430
+ '(no shell expansion, so backticks, $(...), ' +
431
+ // `\${...}` 是字面量(说给模型看的 shell 展开写法),不是插值
432
+ `\${...} and quotes are safe). ` +
433
+ 'mode=create (default) creates a new file and ERRORS if the path already exists (never a ' +
434
+ 'silent overwrite); mode=overwrite replaces the whole file; mode=append adds to the end. ' +
435
+ 'For a partial change inside an existing file use `edit` instead (exact, unique match; it ' +
436
+ 'fails loudly when the text does not match). Only ONE missing parent directory is created ' +
437
+ 'automatically. Max content 4 MiB per call. Returns line/byte counts. ' +
438
+ 'Good design saves retries: pass expected_content (the exact current content you last read) ' +
439
+ 'with mode=overwrite so a concurrent change is caught before you clobber it. ' +
440
+ 'edit/write auto-subscribe the touched file for change notices (unless config autoSubscribe=off); ' +
441
+ 'subscribe:false opts out. Auto subscriptions are dropped on rotate and re-attach on the next edit/write.',
442
+ inputSchema: {
443
+ type: 'object',
444
+ properties: {
445
+ path: { type: 'string', description: 'File path' },
446
+ content: {
447
+ type: 'string',
448
+ description: 'UTF-8 text written verbatim (no escaping, no shell expansion)',
449
+ },
450
+ mode: {
451
+ type: 'string',
452
+ enum: ['create', 'overwrite', 'append'],
453
+ description:
454
+ 'create (default; error if the file exists) | overwrite (replace whole content) | ' +
455
+ 'append (add at the end)',
456
+ },
457
+ expected_content: {
458
+ type: 'string',
459
+ description:
460
+ 'Optional, mode=overwrite only: the exact current content you last read. The write is ' +
461
+ 'rejected (nothing written) if the file bytes differ — detects concurrent changes instead ' +
462
+ 'of silently clobbering them. Omit for legacy behavior.',
463
+ },
464
+ subscribe: {
465
+ type: 'boolean',
466
+ description:
467
+ 'Auto-subscribe this file for change notices (default on unless config autoSubscribe=off). ' +
468
+ 'Set false when confident the write is final and you want to save tokens. Auto (edit-origin) ' +
469
+ 'subscriptions are dropped on rotate and re-attach on your next edit/write of the file.',
470
+ },
471
+ },
472
+ required: ['path', 'content'],
473
+ },
474
+ // 写有副作用,与 bash / edit 同口径:默认 ask,由 core PermissionPolicy 统一定夺;
475
+ // deny 直接拒绝,allowed_roots 越界返回 ask(与 read / edit 完全同一条解析路径)。
476
+ checkPermission: async (input, ctx) => {
477
+ if (isRecord(input)) {
478
+ const inputPath = readString(input, 'path');
479
+ if (inputPath !== '') {
480
+ const decision = evaluatePath(
481
+ resolveToolPath(resolveCallCwd(config, ctx.cwd).path, inputPath),
482
+ boundary,
483
+ );
484
+ if (decision !== 'allow') return decision;
485
+ }
486
+ }
487
+ return 'ask';
488
+ },
489
+ handler: async (args, ctx) =>
490
+ runWithWriteLock(config, ctx, 'write', () =>
491
+ writeFileText(args, ctx, activeBoundary(boundary), config),
492
+ ),
493
+ };
494
+ }