@epoch-agent/plugin-file 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,219 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
204
+ --------------------------------------------------------------------------------
205
+
206
+ epoch-agent
207
+ Copyright 2024-2026 bowen
208
+
209
+ Portions of this software are derived from the Gemini CLI
210
+ (https://github.com/google-gemini/gemini-cli), Copyright 2025 Google LLC,
211
+ licensed under the Apache License, Version 2.0. Those files have been modified;
212
+ each one retains its original copyright notice and SPDX-License-Identifier
213
+ header. See the NOTICE file in the project source repository for the complete
214
+ list of derived files.
215
+
216
+ This software also quotes, with attribution, two lines of prose from OpenAI
217
+ Codex (https://github.com/openai/codex), Copyright 2025 OpenAI, licensed under
218
+ the Apache License, Version 2.0. No source file is a derived work of Codex.
219
+ See the NOTICE file for details.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # @epoch-agent/plugin-file
2
+
3
+ 文件工具插件。**8 个工具**。
4
+
5
+ - ✅ **做**:读 / 写 / 精确编辑 / V4A 多文件补丁 / 搜索 / 列目录
6
+ - ❌ **不做**:git 操作、跨机同步、任何引擎逻辑
7
+ - **依赖**:`diff`(算 diff)。[protocol](../../protocol) 和 [infra](../../infra) 是 peer
8
+
9
+ ## 工具
10
+
11
+ 只读五个:`file_read` `file_multi_read` `file_search` `file_list` `file_diff_preview`;
12
+ 破坏性三个:`file_write` `file_patch` `file_multi_patch`。
13
+
14
+ **每个工具干什么、分页与 `output_mode` 那些边界在
15
+ [docs/TOOLS.md](../../../docs/TOOLS.md#文件)** —— 那份是工具清单的唯一真源,
16
+ 这里只写这个包自己的实现取舍。
17
+
18
+ `file_search` 用 **ripgrep**,但**不要求用户自己装**:`rg` 从哪来由 infra 的
19
+ [`resolveRipgrep()`](../../infra/src/ripgrep.ts) 三级决定 —— 系统 PATH 上有就用系统的,
20
+ 没有就用随包带的 vendor 二进制,两个都没有才退回「工具在、一调才报错 + 给安装提示」
21
+ 的老行为(启动诊断一条 warn,其余七个工具不受影响)。
22
+
23
+ 本插件**不再导出** `probeRipgrep()` / `RIPGREP_INSTALL_HINT`,它们搬去 infra 了:
24
+ `file_list` 和将来的 `@` 文件补全也要用同一份解析,而 plugin 之间不许互相依赖。
25
+ 这里只管**参数怎么拼**和**输出怎么收**。
26
+
27
+ 只读的四个 + `file_diff_preview` 标了 `supportsParallel: true`,引擎可以并发调。
28
+
29
+ ## 处理的几类脏输入
30
+
31
+ - **二进制**:扩展名黑名单拦截(`.png` / `.exe` / `.zip` 等),不把乱码喂给模型
32
+ - **BOM**:剥掉 Windows 编辑器留的 UTF-8 BOM,否则第一行的 patch 匹配永远不中
33
+ - **行尾**:CRLF ↔ LF 归一,patch 匹配不受平台影响
34
+ - **路径**:`~` 和 `~user` 展开
35
+ - **工作区边界**:`resolveSafePath` 防路径穿越——resolve 之后用 `relative` 判,
36
+ 不是 `startsWith`。判定本身是 infra 的
37
+ [`isInWorkspace()`](../../infra/src/workspace.ts)(全仓唯一一份,权限层和
38
+ plugin-terminal 共用),这里只管 `~` 展开和抛 `PathEscapeError`。
39
+ `ctx.extraRoots`(`epoch --add-dir`)一并透传:落在额外根里的**绝对路径**
40
+ 不算越界,但**相对路径仍然只按 `ctx.workDir` 解析**——否则 `src/a.ts` 会在每个
41
+ 根里各找一遍,同一个相对路径有多个答案,而模型无从知道命中的是哪一个
42
+ - **读类工具多认一格:本会话的 artifact 目录**(方案 47)。`file_read` /
43
+ `file_search` / `file_list` / `file_multi_read` 走的是 `resolveReadablePath`,
44
+ 它在上面那套之外再认 `artifactsDir(ctx.sessionId)`。理由是大输出落盘之后
45
+ 取回提示会告诉模型「用 `file_search` 在这个路径里搜」,而那个路径在工作区外——
46
+ 不放开这一格,那句提示就是一句**必定失败**的指令。
47
+ 口子收窄到三条:**只放开读**(`file_write` / `file_patch` 仍走 `resolveSafePath`,
48
+ 模型没有理由改写「命令当时输出了什么」这份证据)、**只放开本会话那一个子目录**
49
+ (不是 `~/.epoch/artifacts`,更不是 `~/.epoch`——后者等于把 `.env` 里的 API key 和
50
+ `sessions.db` 一起交出去)、**`sessionId` 由引擎给且 `artifactsDir()` 内部再洗一次**。
51
+ 这三条各有一条否定用例钉着,见 `__tests__/artifact-readable.test.ts`
52
+
53
+ ## `file_diff_preview` 的 operation 是故意填错的
54
+
55
+ 它的真实语义是只读(只算 diff 不落盘),`annotations` 照实写。但 `operation` 仍填
56
+ `file_write`:老白名单把它归在 `FILE_WRITE_TOOLS` 里,只改一边会让 `recordApproval`
57
+ 那条路径与这里分叉。往严的方向偏,代价只是多一次确认。
58
+
59
+ ## 开发
60
+
61
+ ```bash
62
+ pnpm --filter @epoch-agent/plugin-file test
63
+ ```
64
+
65
+ `path-boundary.test.ts` 记的是具体的穿越手法,改 `resolveSafePath` 之前先读它。
@@ -0,0 +1,32 @@
1
+ import { EpochPlugin } from '@epoch-agent/protocol';
2
+
3
+ /**
4
+ * @epoch-agent/plugin-file — 文件读写、搜索、精确编辑
5
+ *
6
+ * 目录结构:
7
+ * src/
8
+ * ├── utils.ts # 共享工具函数
9
+ * ├── tools/
10
+ * │ ├── file-read.ts # 分页读取,带行号
11
+ * │ ├── file-multi-read.ts# 批量读取
12
+ * │ ├── file-search.ts # ripgrep 搜索
13
+ * │ ├── file-write.ts # 安全写入(备份+校验)
14
+ * │ ├── file-patch.ts # 精确编辑(apply_patch)
15
+ * │ └── file-list.ts # 目录列表
16
+ * └── index.ts # 插件定义入口
17
+ *
18
+ * 每个工具都同时声明三件事,缺一件权限系统就得靠猜:
19
+ * - `annotations`:MCP 规范那套风险 hint,给透传 / 展示 / 推断用
20
+ * - `operation`:权限类别,直接决定审批走不走。填了就不依赖推断
21
+ * - `describeTarget`:这次操作的对象,用作审批缓存 key。不填就只能从
22
+ * command/path/target/filePath/paths 五个候选参数名里猜
23
+ * 消费方见 core 的 permission/operation-type.ts 和 agent/tool-executor.ts。
24
+ *
25
+ * `operation` 的取值必须与 operation-type.ts 的工具名白名单一致 ——
26
+ * `recordApproval` 只拿到工具名、走的是白名单那条路,两边分叉就等于
27
+ * 「批准了也命不中缓存」。core 的 operation-type.test.ts 有一致性用例守着。
28
+ */
29
+
30
+ declare const filePlugin: EpochPlugin;
31
+
32
+ export { filePlugin };
package/dist/index.js ADDED
@@ -0,0 +1,960 @@
1
+ // src/tools/file-multi-patch.ts
2
+ import { randomUUID } from "crypto";
3
+ import {
4
+ accessSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ renameSync,
8
+ unlinkSync,
9
+ writeFileSync
10
+ } from "fs";
11
+ import { dirname, isAbsolute, join, resolve } from "path";
12
+ import { structuredPatch } from "diff";
13
+ import { isInWorkspace } from "@epoch-agent/infra";
14
+ function parseV4APatch(patch, workDir) {
15
+ const hunks = [];
16
+ const blocks = patch.split(/\*\*\* Begin Patch\b/).filter((b) => b.trim());
17
+ for (const block of blocks) {
18
+ const endIdx = block.indexOf("*** End Patch");
19
+ if (endIdx === -1) continue;
20
+ const body = block.slice(0, endIdx);
21
+ const fileMatch = body.match(/\*\*\* Update File:\s*(.+)/);
22
+ if (!fileMatch) continue;
23
+ const filePath = fileMatch[1]?.trim() ?? "";
24
+ const absPath = isAbsolute(filePath) ? filePath : resolve(workDir, filePath);
25
+ const fileBody = body.slice(body.indexOf(fileMatch[0]) + fileMatch[0].length);
26
+ const hasAddLines = /^\+/m.test(fileBody);
27
+ const hasDelLines = /^-/m.test(fileBody);
28
+ const contextLines = fileBody.split("\n").filter((l) => !l.startsWith("@@") && !l.startsWith("+") && !l.startsWith("-"));
29
+ if (hasAddLines && !hasDelLines) {
30
+ const content = fileBody.split("\n").filter((l) => l.startsWith("+")).map((l) => l.slice(1).replace(/^ +/, "")).join("\n");
31
+ hunks.push({ type: "add", filePath: absPath, content });
32
+ } else if (hasDelLines && !hasAddLines && contextLines.join("").trim() === "") {
33
+ hunks.push({ type: "delete", filePath: absPath });
34
+ } else {
35
+ const addLines = fileBody.split("\n").filter((l) => l.startsWith("+")).map((l) => l.slice(1).replace(/^ +/, ""));
36
+ const delLines = fileBody.split("\n").filter((l) => l.startsWith("-")).map((l) => l.slice(1).replace(/^ +/, ""));
37
+ hunks.push({
38
+ type: "update",
39
+ filePath: absPath,
40
+ oldString: delLines.join("\n"),
41
+ newString: addLines.join("\n")
42
+ });
43
+ }
44
+ }
45
+ return hunks;
46
+ }
47
+ function applyPatch(hunks, _workDir) {
48
+ const changes = [];
49
+ let exact = true;
50
+ for (const hunk of hunks) {
51
+ try {
52
+ switch (hunk.type) {
53
+ case "add": {
54
+ if (hunk.content === void 0) continue;
55
+ try {
56
+ accessSync(hunk.filePath);
57
+ changes.push({ path: hunk.filePath, type: "added", newContent: hunk.content });
58
+ continue;
59
+ } catch {
60
+ }
61
+ atomicWrite(hunk.filePath, hunk.content);
62
+ changes.push({ path: hunk.filePath, type: "added", newContent: hunk.content });
63
+ break;
64
+ }
65
+ case "delete": {
66
+ try {
67
+ const oldContent = readFileSync(hunk.filePath, "utf-8");
68
+ atomicDelete(hunk.filePath);
69
+ changes.push({ path: hunk.filePath, type: "deleted", oldContent });
70
+ } catch {
71
+ exact = false;
72
+ changes.push({ path: hunk.filePath, type: "deleted" });
73
+ }
74
+ break;
75
+ }
76
+ case "update": {
77
+ if (hunk.oldString === void 0 || hunk.newString === void 0) continue;
78
+ const oldContent = readFileSync(hunk.filePath, "utf-8");
79
+ if (!oldContent.includes(hunk.oldString.trim())) {
80
+ exact = false;
81
+ }
82
+ const newContent = oldContent.replace(hunk.oldString, hunk.newString);
83
+ atomicWrite(hunk.filePath, newContent);
84
+ const diff = generateDiff(hunk.filePath, oldContent, newContent);
85
+ changes.push({
86
+ path: hunk.filePath,
87
+ type: "modified",
88
+ oldContent,
89
+ newContent,
90
+ unifiedDiff: diff
91
+ });
92
+ break;
93
+ }
94
+ }
95
+ } catch {
96
+ exact = false;
97
+ changes.push({ path: hunk.filePath, type: "modified" });
98
+ }
99
+ }
100
+ const added = changes.filter((c) => c.type === "added").length;
101
+ const modified = changes.filter((c) => c.type === "modified").length;
102
+ const deleted = changes.filter((c) => c.type === "deleted").length;
103
+ const summary = [
104
+ `\u5DF2\u4FEE\u6539 ${changes.length} \u4E2A\u6587\u4EF6: ${added} \u65B0\u589E, ${modified} \u4FEE\u6539, ${deleted} \u5220\u9664`,
105
+ exact ? "(\u6240\u6709\u53D8\u66F4\u7CBE\u786E\u5E94\u7528)" : "(\u90E8\u5206\u53D8\u66F4\u9700\u6A21\u7CCA\u5339\u914D)"
106
+ ].join(" ");
107
+ return { success: changes.length > 0, changes, exact, summary };
108
+ }
109
+ var DIFF_CONTEXT_LINES = 3;
110
+ function generateDiff(filePath, oldContent, newContent) {
111
+ const patch = structuredPatch(filePath, filePath, oldContent, newContent, void 0, void 0, {
112
+ context: DIFF_CONTEXT_LINES
113
+ });
114
+ if (patch.hunks.length === 0) return "";
115
+ const lines = [`--- ${filePath}`, `+++ ${filePath}`];
116
+ for (const hunk of patch.hunks) {
117
+ lines.push(
118
+ `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
119
+ ...hunk.lines
120
+ );
121
+ }
122
+ return lines.join("\n");
123
+ }
124
+ function atomicWrite(filePath, content) {
125
+ const dir = dirname(filePath);
126
+ mkdirSync(dir, { recursive: true });
127
+ const tmp = join(dir, `.epoch-atomic-${randomUUID().slice(0, 8)}.tmp`);
128
+ writeFileSync(tmp, content, "utf-8");
129
+ renameSync(tmp, filePath);
130
+ }
131
+ function atomicDelete(filePath) {
132
+ const backupPath = `${filePath}.epoch-backup-${randomUUID().slice(0, 8)}`;
133
+ try {
134
+ renameSync(filePath, backupPath);
135
+ } catch {
136
+ try {
137
+ unlinkSync(filePath);
138
+ } catch {
139
+ }
140
+ }
141
+ }
142
+ async function execMultiPatch(args, ctx) {
143
+ const patch = String(args["patch"] || "");
144
+ if (!patch.trim())
145
+ return {
146
+ success: false,
147
+ output: "",
148
+ error: { code: 4001, message: "\u8865\u4E01\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A" },
149
+ duration: 0
150
+ };
151
+ const hunks = parseV4APatch(patch, ctx.workDir);
152
+ if (hunks.length === 0)
153
+ return {
154
+ success: false,
155
+ output: "",
156
+ error: { code: 4002, message: "\u65E0\u6CD5\u89E3\u6790 V4A \u8865\u4E01\u683C\u5F0F" },
157
+ duration: 0
158
+ };
159
+ for (const h of hunks) {
160
+ if (!isInWorkspace(h.filePath, ctx.workDir, ctx.extraRoots)) {
161
+ return {
162
+ success: false,
163
+ output: "",
164
+ error: {
165
+ code: 4003,
166
+ message: `\u8DEF\u5F84\u8D8A\u754C\u62D2\u7EDD: ${h.filePath} \u4E0D\u5728\u5DE5\u4F5C\u533A ${ctx.workDir} \u5185`
167
+ },
168
+ duration: 0
169
+ };
170
+ }
171
+ }
172
+ const result = applyPatch(hunks, ctx.workDir);
173
+ return {
174
+ success: result.success,
175
+ output: result.summary + "\n\n" + result.changes.map(
176
+ (c) => c.unifiedDiff ? `=== ${c.path} ===
177
+ ${c.unifiedDiff}` : `${c.type}: ${c.path}`
178
+ ).join("\n\n"),
179
+ duration: 0
180
+ };
181
+ }
182
+
183
+ // src/tools/file-diff-preview.ts
184
+ async function execDiffPreview(args, ctx) {
185
+ const patch = String(args["patch"] || "");
186
+ if (!patch.trim())
187
+ return {
188
+ success: false,
189
+ output: "",
190
+ error: { code: 4101, message: "\u8865\u4E01\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A" },
191
+ duration: 0
192
+ };
193
+ const hunks = parseV4APatch(patch, ctx.workDir);
194
+ if (hunks.length === 0)
195
+ return {
196
+ success: false,
197
+ output: "",
198
+ error: { code: 4102, message: "\u65E0\u6CD5\u89E3\u6790 V4A \u8865\u4E01\u683C\u5F0F" },
199
+ duration: 0
200
+ };
201
+ const summary = buildDiffSummary(hunks, ctx.workDir);
202
+ return {
203
+ success: true,
204
+ output: summary,
205
+ duration: 0
206
+ };
207
+ }
208
+ function buildDiffSummary(hunks, workDir) {
209
+ const lines = [];
210
+ const addCount = hunks.filter((h) => h.type === "add").length;
211
+ const updateCount = hunks.filter((h) => h.type === "update").length;
212
+ const deleteCount = hunks.filter((h) => h.type === "delete").length;
213
+ const counts = [];
214
+ if (addCount) counts.push(`${addCount} \u65B0\u589E`);
215
+ if (updateCount) counts.push(`${updateCount} \u4FEE\u6539`);
216
+ if (deleteCount) counts.push(`${deleteCount} \u5220\u9664`);
217
+ lines.push(`\u{1F4DD} \u8865\u4E01\u9884\u89C8 \u2014 ${hunks.length} \u4E2A\u6587\u4EF6\u5C06\u88AB\u4FEE\u6539 (${counts.join(", ")})`);
218
+ lines.push("");
219
+ for (const hunk of hunks) {
220
+ const icon = hunk.type === "add" ? "\u{1F4C4} ADD" : hunk.type === "delete" ? "\u{1F5D1}\uFE0F DELETE" : "\u270F\uFE0F UPDATE";
221
+ const short = hunk.filePath.replace(workDir + "/", "");
222
+ lines.push(`${icon} ${short}`);
223
+ if (hunk.type === "add" && hunk.content) {
224
+ for (const l of hunk.content.split("\n").slice(0, 10)) {
225
+ lines.push(` + ${l}`);
226
+ }
227
+ if (hunk.content.split("\n").length > 10)
228
+ lines.push(` ... (${hunk.content.split("\n").length - 10} more lines)`);
229
+ } else if (hunk.type === "delete" && hunk.oldString) {
230
+ for (const l of hunk.oldString.split("\n").slice(0, 5)) {
231
+ lines.push(` - ${l}`);
232
+ }
233
+ } else if (hunk.type === "update") {
234
+ if (hunk.oldString) {
235
+ for (const l of hunk.oldString.split("\n").slice(0, 5)) {
236
+ lines.push(` - ${l}`);
237
+ }
238
+ }
239
+ if (hunk.newString) {
240
+ for (const l of hunk.newString.split("\n").slice(0, 5)) {
241
+ lines.push(` + ${l}`);
242
+ }
243
+ }
244
+ }
245
+ lines.push("");
246
+ }
247
+ lines.push("---");
248
+ lines.push("\u786E\u8BA4\u65E0\u8BEF\u540E\uFF0C\u4F7F\u7528 file_multi_patch \u5DE5\u5177\u5E94\u7528\u4EE5\u4E0A\u53D8\u66F4\u3002");
249
+ return lines.join("\n");
250
+ }
251
+
252
+ // src/tools/file-list.ts
253
+ import { readdirSync, statSync } from "fs";
254
+ import { join as join2 } from "path";
255
+
256
+ // src/utils.ts
257
+ import { homedir } from "os";
258
+ import { resolve as resolve2 } from "path";
259
+ import { artifactsDir, isInWorkspace as isInWorkspace2 } from "@epoch-agent/infra";
260
+ var MAX_OUTPUT_BYTES = 5e4;
261
+ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
262
+ ".png",
263
+ ".jpg",
264
+ ".jpeg",
265
+ ".gif",
266
+ ".bmp",
267
+ ".ico",
268
+ ".svg",
269
+ ".pdf",
270
+ ".doc",
271
+ ".docx",
272
+ ".xls",
273
+ ".xlsx",
274
+ ".ppt",
275
+ ".pptx",
276
+ ".zip",
277
+ ".tar",
278
+ ".gz",
279
+ ".bz2",
280
+ ".7z",
281
+ ".rar",
282
+ ".exe",
283
+ ".dll",
284
+ ".so",
285
+ ".dylib",
286
+ ".o",
287
+ ".a",
288
+ ".pyc",
289
+ ".pyo",
290
+ ".class",
291
+ ".jar",
292
+ ".mp3",
293
+ ".mp4",
294
+ ".avi",
295
+ ".mov",
296
+ ".wav",
297
+ ".flac",
298
+ ".ttf",
299
+ ".otf",
300
+ ".woff",
301
+ ".woff2",
302
+ ".db",
303
+ ".sqlite",
304
+ ".sqlite3"
305
+ ]);
306
+ function expandPath(filePath) {
307
+ if (filePath.startsWith("~")) {
308
+ return filePath.replace(/^~(?=$|[/\\])/, homedir());
309
+ }
310
+ return filePath;
311
+ }
312
+ var PathEscapeError = class extends Error {
313
+ constructor(attempted, workDir) {
314
+ super(`\u8DEF\u5F84\u8D8A\u754C\uFF1A${attempted} \u4E0D\u5728\u5DE5\u4F5C\u533A ${workDir} \u5185`);
315
+ this.attempted = attempted;
316
+ this.workDir = workDir;
317
+ this.name = "PathEscapeError";
318
+ }
319
+ attempted;
320
+ workDir;
321
+ };
322
+ function resolveSafePath(filePath, workDir, extraRoots = []) {
323
+ const expanded = expandPath(filePath);
324
+ const abs = resolve2(workDir, expanded);
325
+ if (!isInWorkspace2(abs, workDir, extraRoots)) {
326
+ throw new PathEscapeError(filePath, resolve2(workDir));
327
+ }
328
+ return abs;
329
+ }
330
+ function resolveReadablePath(filePath, workDir, extraRoots = [], sessionId, homeDir) {
331
+ if (!sessionId) return resolveSafePath(filePath, workDir, extraRoots);
332
+ return resolveSafePath(filePath, workDir, [...extraRoots, artifactsDir(sessionId, homeDir)]);
333
+ }
334
+ function isBinaryFile(filePath) {
335
+ const ext = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
336
+ return BINARY_EXTENSIONS.has(ext);
337
+ }
338
+ function stripBom(content) {
339
+ if (content.charCodeAt(0) === 65279) {
340
+ return { text: content.slice(1), hadBom: true };
341
+ }
342
+ return { text: content, hadBom: false };
343
+ }
344
+ function detectLineEnding(content) {
345
+ const hasCRLF = content.includes("\r\n");
346
+ const hasLFOnly = content.includes("\n") && !hasCRLF;
347
+ if (hasCRLF && !hasLFOnly) return "crlf";
348
+ if (hasLFOnly && !hasCRLF) return "lf";
349
+ if (hasCRLF && content.replace(/\r\n/g, "").includes("\n")) return "mixed";
350
+ return "lf";
351
+ }
352
+ function normalizeLineEndings(content, target) {
353
+ if (target === "lf") return content.replace(/\r\n/g, "\n");
354
+ return content.replace(/(?<!\r)\n/g, "\r\n");
355
+ }
356
+ function paginateContent(content, offset = 1, limit = 500) {
357
+ const lines = content.split("\n");
358
+ const totalLines = lines.length;
359
+ if (offset > totalLines) return { content: "", totalLines };
360
+ const end = Math.min(offset + limit - 1, totalLines);
361
+ const sliced = lines.slice(offset - 1, end).join("\n");
362
+ const result = {
363
+ content: sliced,
364
+ totalLines
365
+ };
366
+ if (end < totalLines) result.nextOffset = end + 1;
367
+ return result;
368
+ }
369
+ function truncateOutput(text) {
370
+ if (text.length > MAX_OUTPUT_BYTES) {
371
+ return text.slice(0, MAX_OUTPUT_BYTES) + `
372
+ [\u8F93\u51FA\u5DF2\u622A\u65AD\uFF0C\u5171 ${text.length} \u5B57\u8282\uFF0C\u663E\u793A\u524D ${MAX_OUTPUT_BYTES} \u5B57\u8282]`;
373
+ }
374
+ return text;
375
+ }
376
+ function formatWithLineNumbers(content, startLine) {
377
+ return content.split("\n").map((line, i) => String(startLine + i).padStart(4, " ") + "|" + line).join("\n");
378
+ }
379
+
380
+ // src/tools/file-list.ts
381
+ function formatEntry(entry) {
382
+ const size = entry.type === "directory" ? "-" : entry.size.toLocaleString("en-US");
383
+ const name = entry.type === "directory" ? `${entry.name}/` : entry.name;
384
+ return `${entry.type.padEnd(4)} ${size.padStart(12)} ${name}`;
385
+ }
386
+ function collect(dir) {
387
+ const entries = [];
388
+ for (const dirent of readdirSync(dir, { withFileTypes: true })) {
389
+ const type = dirent.isDirectory() ? "directory" : "file";
390
+ let size = 0;
391
+ if (type === "file") {
392
+ try {
393
+ size = statSync(join2(dir, dirent.name)).size;
394
+ } catch {
395
+ size = 0;
396
+ }
397
+ }
398
+ entries.push({ name: dirent.name, type, size });
399
+ }
400
+ entries.sort(
401
+ (a, b) => a.type === b.type ? a.name.localeCompare(b.name) : a.type === "directory" ? -1 : 1
402
+ );
403
+ return entries;
404
+ }
405
+ function execList(args, ctx) {
406
+ const path = String(args["path"] ?? ".");
407
+ let resolved;
408
+ try {
409
+ resolved = resolveReadablePath(path, ctx.workDir, ctx.extraRoots, ctx.sessionId, ctx.homeDir);
410
+ } catch (err) {
411
+ return Promise.resolve({
412
+ success: false,
413
+ output: "",
414
+ error: { code: 2006, message: err instanceof Error ? err.message : String(err) },
415
+ duration: 0
416
+ });
417
+ }
418
+ try {
419
+ const entries = collect(resolved);
420
+ const body = entries.length === 0 ? "(\u7A7A\u76EE\u5F55)" : entries.map(formatEntry).join("\n");
421
+ return Promise.resolve({
422
+ success: true,
423
+ output: truncateOutput(`${resolved}
424
+ ${body}
425
+ \u5171 ${entries.length} \u9879`),
426
+ duration: 0
427
+ });
428
+ } catch (err) {
429
+ const code = err.code;
430
+ const message = err instanceof Error ? err.message : String(err);
431
+ return Promise.resolve({
432
+ success: false,
433
+ output: "",
434
+ error: {
435
+ code: 2005,
436
+ message,
437
+ ...code === "ENOTDIR" ? { suggestion: "\u76EE\u6807\u662F\u6587\u4EF6\uFF0C\u8BFB\u5185\u5BB9\u8BF7\u7528 file_read" } : {}
438
+ },
439
+ duration: 0
440
+ });
441
+ }
442
+ }
443
+
444
+ // src/tools/file-multi-read.ts
445
+ import { readFile } from "fs/promises";
446
+ async function execMultiRead(args, ctx) {
447
+ const paths = args["paths"];
448
+ if (!paths?.length) {
449
+ return {
450
+ success: false,
451
+ output: "",
452
+ error: { code: 2004, message: "\u53C2\u6570 paths \u4E0D\u80FD\u4E3A\u7A7A" },
453
+ duration: 0
454
+ };
455
+ }
456
+ const results = [];
457
+ for (const p of paths.slice(0, 10)) {
458
+ try {
459
+ const resolved = resolveReadablePath(
460
+ p,
461
+ ctx.workDir,
462
+ ctx.extraRoots,
463
+ ctx.sessionId,
464
+ ctx.homeDir
465
+ );
466
+ const content = await readFile(resolved, "utf-8");
467
+ const output = formatWithLineNumbers(content, 0);
468
+ results.push(`--- ${p} ---
469
+ ${truncateOutput(output)}`);
470
+ } catch (err) {
471
+ const message = err instanceof Error ? err.message : String(err);
472
+ results.push(`--- ${p} ---
473
+ [\u8BFB\u53D6\u5931\u8D25: ${message}]`);
474
+ }
475
+ }
476
+ return { success: true, output: results.join("\n\n"), duration: 0 };
477
+ }
478
+
479
+ // src/tools/file-patch.ts
480
+ import { readFile as readFile2, writeFile } from "fs/promises";
481
+ import { basename } from "path";
482
+ async function execPatch(args, ctx) {
483
+ const path = String(args["path"] ?? "");
484
+ const oldString = String(args["old_string"] ?? "");
485
+ const newString = String(args["new_string"] ?? "");
486
+ const replaceAll = Boolean(args["replace_all"]);
487
+ if (!path || !oldString) {
488
+ return {
489
+ success: false,
490
+ output: "",
491
+ error: { code: 2004, message: "\u53C2\u6570 path \u548C old_string \u4E0D\u80FD\u4E3A\u7A7A" },
492
+ duration: 0
493
+ };
494
+ }
495
+ const startTime = Date.now();
496
+ try {
497
+ const resolved = resolveSafePath(path, ctx.workDir, ctx.extraRoots);
498
+ const rawContent = await readFile2(resolved, "utf-8");
499
+ const lineEnding = detectLineEnding(rawContent);
500
+ const content = normalizeLineEndings(rawContent, "lf");
501
+ const normalizedOld = normalizeLineEndings(oldString, "lf");
502
+ const normalizedNew = normalizeLineEndings(newString, lineEnding === "crlf" ? "crlf" : "lf");
503
+ const indices = findAllMatches(content, normalizedOld);
504
+ if (indices.length === 0) {
505
+ const fuzzy = fuzzyMatch(content, normalizedOld);
506
+ if (fuzzy) {
507
+ const newContent2 = content.slice(0, fuzzy.start) + normalizedNew + content.slice(fuzzy.end);
508
+ await writeFile(resolved, newContent2, "utf-8");
509
+ return {
510
+ success: true,
511
+ output: `\u2705 \u6A21\u7CCA\u5339\u914D\u6210\u529F\uFF0C\u5DF2\u4FEE\u6539 ${basename(resolved)}`,
512
+ duration: Date.now() - startTime
513
+ };
514
+ }
515
+ return {
516
+ success: false,
517
+ output: "",
518
+ error: {
519
+ code: 2004,
520
+ message: `old_string \u672A\u5728\u6587\u4EF6\u4E2D\u627E\u5230\u3002\u5C1D\u8BD5\u4E86 9 \u79CD\u6A21\u7CCA\u5339\u914D\u7B56\u7565\u5747\u5931\u8D25\u3002`,
521
+ suggestion: "\u8BF7\u7528 file_read \u786E\u8BA4\u5F53\u524D\u6587\u4EF6\u5185\u5BB9\uFF0C\u786E\u4FDD old_string \u51C6\u786E"
522
+ },
523
+ duration: Date.now() - startTime
524
+ };
525
+ }
526
+ if (indices.length > 1 && !replaceAll) {
527
+ return {
528
+ success: false,
529
+ output: `\u5339\u914D\u5230 ${indices.length} \u5904\uFF0C\u8BF7\u4F7F\u7528 replace_all=true \u6216\u63D0\u4F9B\u66F4\u7CBE\u786E\u7684\u4E0A\u4E0B\u6587`,
530
+ error: {
531
+ code: 2004,
532
+ message: `\u5339\u914D\u5230 ${indices.length} \u5904\uFF0C\u9700\u660E\u786E\u6307\u5B9A`,
533
+ suggestion: "\u5C06 replace_all \u8BBE\u4E3A true \u6216\u589E\u52A0\u66F4\u591A\u4E0A\u4E0B\u6587\u8BA9\u5339\u914D\u552F\u4E00"
534
+ },
535
+ duration: Date.now() - startTime
536
+ };
537
+ }
538
+ let newContent = content;
539
+ for (let i = indices.length - 1; i >= 0; i--) {
540
+ const idx = indices[i];
541
+ if (idx === void 0) continue;
542
+ newContent = newContent.slice(0, idx) + normalizedNew + newContent.slice(idx + normalizedOld.length);
543
+ }
544
+ await writeFile(resolved, newContent, "utf-8");
545
+ return {
546
+ success: true,
547
+ output: `\u2705 \u5DF2\u4FEE\u6539 ${basename(resolved)}\uFF08${indices.length} \u5904\u66FF\u6362\uFF09`,
548
+ duration: Date.now() - startTime
549
+ };
550
+ } catch (err) {
551
+ const message = err instanceof Error ? err.message : String(err);
552
+ return {
553
+ success: false,
554
+ output: "",
555
+ error: { code: 2005, message },
556
+ duration: Date.now() - startTime
557
+ };
558
+ }
559
+ }
560
+ function findAllMatches(content, old) {
561
+ const indices = [];
562
+ let pos = 0;
563
+ while ((pos = content.indexOf(old, pos)) !== -1) {
564
+ indices.push(pos);
565
+ pos += old.length;
566
+ }
567
+ return indices;
568
+ }
569
+ function fuzzyMatch(content, old) {
570
+ const strategies = [
571
+ () => simpleMatch(content, old.trim()),
572
+ () => simpleMatch(content.replace(/\r\n/g, "\n"), old.replace(/\r\n/g, "\n")),
573
+ () => simpleMatch(content, old.replace(/\t/g, " ")),
574
+ () => lineTrimMatch(content, old),
575
+ () => simpleMatch(content.replace(/\s+/g, " "), old.replace(/\s+/g, " "))
576
+ ];
577
+ for (const fn of strategies) {
578
+ try {
579
+ const r = fn();
580
+ if (r) return r;
581
+ } catch {
582
+ }
583
+ }
584
+ return null;
585
+ }
586
+ function simpleMatch(content, old) {
587
+ const idx = content.indexOf(old);
588
+ return idx === -1 ? null : { start: idx, end: idx + old.length };
589
+ }
590
+ function lineTrimMatch(content, old) {
591
+ const cl = content.split("\n").map((l) => l.trim());
592
+ const ol = old.split("\n").map((l) => l.trim());
593
+ for (let i = 0; i <= cl.length - ol.length; i++) {
594
+ if (ol.every((line, j) => cl[i + j] === line)) {
595
+ return { start: content.indexOf(ol[0] ?? ""), end: content.length };
596
+ }
597
+ }
598
+ return null;
599
+ }
600
+
601
+ // src/tools/file-read.ts
602
+ import { readFile as readFile3 } from "fs/promises";
603
+ async function execRead(args, ctx) {
604
+ const path = String(args["path"] ?? "");
605
+ const offset = Number(args["offset"] ?? 1);
606
+ const limit = Number(args["limit"] ?? 500);
607
+ if (!path) {
608
+ return {
609
+ success: false,
610
+ output: "",
611
+ error: { code: 2004, message: "\u53C2\u6570 path \u4E0D\u80FD\u4E3A\u7A7A" },
612
+ duration: 0
613
+ };
614
+ }
615
+ try {
616
+ const resolved = resolveReadablePath(
617
+ path,
618
+ ctx.workDir,
619
+ ctx.extraRoots,
620
+ ctx.sessionId,
621
+ ctx.homeDir
622
+ );
623
+ if (isBinaryFile(resolved)) {
624
+ return { success: true, output: `[\u4E8C\u8FDB\u5236\u6587\u4EF6\uFF0C\u65E0\u6CD5\u8BFB\u53D6: ${path}]`, duration: 0 };
625
+ }
626
+ const raw = await readFile3(resolved, "utf-8");
627
+ const { text: content, hadBom } = stripBom(raw);
628
+ const result = paginateContent(content, offset, limit);
629
+ let output = formatWithLineNumbers(result.content, offset);
630
+ output = output || "(\u6587\u4EF6\u4E3A\u7A7A)";
631
+ if (result.nextOffset) {
632
+ output += `
633
+
634
+ [\u7B2C ${result.nextOffset - 1} \u884C / \u5171 ${result.totalLines} \u884C\uFF0C\u4F7F\u7528 offset=${result.nextOffset} \u4E0B\u4E00\u9875]`;
635
+ }
636
+ if (hadBom) {
637
+ output = `[\u68C0\u6D4B\u5230 UTF-8 BOM\uFF0C\u5DF2\u81EA\u52A8\u5265\u79BB]
638
+ ${output}`;
639
+ }
640
+ return { success: true, output, duration: 0 };
641
+ } catch (err) {
642
+ const message = err instanceof Error ? err.message : String(err);
643
+ return { success: false, output: "", error: { code: 2001, message }, duration: 0 };
644
+ }
645
+ }
646
+
647
+ // src/tools/file-search.ts
648
+ import { spawn } from "child_process";
649
+ import { resolveRipgrep, RIPGREP_INSTALL_HINT, WINDOWS_HIDE_FLAGS } from "@epoch-agent/infra";
650
+ function execSearch(args, ctx) {
651
+ return new Promise((resolve4) => {
652
+ const pattern = String(args["pattern"] ?? "");
653
+ const searchPath = String(args["path"] ?? ".");
654
+ const include = String(args["include"] ?? "");
655
+ const limit = Number(args["limit"] ?? 50);
656
+ const outputMode = args["output_mode"] || "content";
657
+ if (!pattern) {
658
+ resolve4({
659
+ success: false,
660
+ output: "",
661
+ error: { code: 2004, message: "\u53C2\u6570 pattern \u4E0D\u80FD\u4E3A\u7A7A" },
662
+ duration: 0
663
+ });
664
+ return;
665
+ }
666
+ let resolvedDir;
667
+ try {
668
+ resolvedDir = resolveReadablePath(
669
+ searchPath,
670
+ ctx.workDir,
671
+ ctx.extraRoots,
672
+ ctx.sessionId,
673
+ ctx.homeDir
674
+ );
675
+ } catch (err) {
676
+ resolve4({
677
+ success: false,
678
+ output: "",
679
+ error: { code: 2006, message: err instanceof Error ? err.message : String(err) },
680
+ duration: 0
681
+ });
682
+ return;
683
+ }
684
+ const rgArgs = [
685
+ "--line-number",
686
+ "--no-heading",
687
+ "--color",
688
+ "never",
689
+ "-m",
690
+ String(limit),
691
+ pattern,
692
+ resolvedDir
693
+ ];
694
+ if (include) rgArgs.splice(0, 0, "--glob", include);
695
+ if (outputMode === "files_only") rgArgs.splice(0, 0, "-l");
696
+ if (outputMode === "count") rgArgs.splice(0, 0, "-c");
697
+ const child = spawn(resolveRipgrep().command, rgArgs, {
698
+ timeout: 3e4,
699
+ stdio: ["ignore", "pipe", "pipe"],
700
+ ...WINDOWS_HIDE_FLAGS
701
+ });
702
+ let stdout = "";
703
+ let stderr = "";
704
+ child.stdout?.on("data", (chunk) => {
705
+ stdout += chunk.toString();
706
+ });
707
+ child.stderr?.on("data", (chunk) => {
708
+ stderr += chunk.toString();
709
+ });
710
+ child.on("close", (code) => {
711
+ if (code === 0 || code === 1) {
712
+ resolve4({ success: true, output: truncateOutput(stdout) || "(\u65E0\u5339\u914D)", duration: 0 });
713
+ } else {
714
+ resolve4({
715
+ success: false,
716
+ output: "",
717
+ error: { code: 2005, message: stderr || `rg \u6267\u884C\u5931\u8D25 (exit ${code})` },
718
+ duration: 0
719
+ });
720
+ }
721
+ });
722
+ child.on("error", (err) => {
723
+ const notFound = err.code === "ENOENT";
724
+ resolve4({
725
+ success: false,
726
+ output: "",
727
+ error: {
728
+ code: 2005,
729
+ message: `ripgrep \u672A\u5B89\u88C5\u6216\u4E0D\u53EF\u7528: ${err.message}`,
730
+ ...notFound ? { suggestion: `\u5B89\u88C5 ripgrep \u540E\u91CD\u8BD5\uFF1A${RIPGREP_INSTALL_HINT}` } : {}
731
+ },
732
+ duration: 0
733
+ });
734
+ });
735
+ });
736
+ }
737
+
738
+ // src/tools/file-write.ts
739
+ import { mkdir, readFile as readFile4, rename, stat, unlink, writeFile as writeFile2 } from "fs/promises";
740
+ import { basename as basename2, resolve as resolve3 } from "path";
741
+ async function execWrite(args, ctx) {
742
+ const path = String(args["path"] ?? "");
743
+ const content = String(args["content"] ?? "");
744
+ if (!path) {
745
+ return {
746
+ success: false,
747
+ output: "",
748
+ error: { code: 2004, message: "\u53C2\u6570 path \u4E0D\u80FD\u4E3A\u7A7A" },
749
+ duration: 0
750
+ };
751
+ }
752
+ const startTime = Date.now();
753
+ try {
754
+ const resolved = resolveSafePath(path, ctx.workDir, ctx.extraRoots);
755
+ let existed = false;
756
+ try {
757
+ await stat(resolved);
758
+ existed = true;
759
+ await rename(resolved, `${resolved}.bak`);
760
+ } catch {
761
+ }
762
+ await mkdir(resolve3(resolved, ".."), { recursive: true });
763
+ await writeFile2(resolved, content, "utf-8");
764
+ const written = await readFile4(resolved, "utf-8");
765
+ if (written !== content) {
766
+ await rename(`${resolved}.bak`, resolved);
767
+ throw new Error("\u6587\u4EF6\u5199\u5165\u6821\u9A8C\u5931\u8D25\uFF0C\u5DF2\u4ECE\u5907\u4EFD\u6062\u590D");
768
+ }
769
+ try {
770
+ await unlink(`${resolved}.bak`);
771
+ } catch {
772
+ }
773
+ return {
774
+ success: true,
775
+ output: existed ? `\u2705 \u5DF2\u66F4\u65B0 ${basename2(resolved)} (${content.length} \u5B57\u8282)` : `\u2705 \u5DF2\u521B\u5EFA ${basename2(resolved)} (${content.length} \u5B57\u8282)`,
776
+ duration: Date.now() - startTime
777
+ };
778
+ } catch (err) {
779
+ const message = err instanceof Error ? err.message : String(err);
780
+ return {
781
+ success: false,
782
+ output: "",
783
+ error: { code: 2005, message },
784
+ duration: Date.now() - startTime
785
+ };
786
+ }
787
+ }
788
+
789
+ // src/index.ts
790
+ var READ_ONLY = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
791
+ var DESTRUCTIVE = {
792
+ readOnlyHint: false,
793
+ destructiveHint: true,
794
+ idempotentHint: false,
795
+ openWorldHint: false
796
+ };
797
+ function pathTarget(args) {
798
+ return String(args["path"] ?? "");
799
+ }
800
+ function dirTarget(args) {
801
+ return String(args["path"] ?? ".");
802
+ }
803
+ function patchTarget(args) {
804
+ const patch = String(args["patch"] ?? "");
805
+ const files = [...patch.matchAll(/^\*\*\* (?:Update|Add|Delete) File:\s*(.+)$/gm)].map(
806
+ (m) => (m[1] ?? "").trim()
807
+ );
808
+ return files.length > 0 ? files.join(",") : "";
809
+ }
810
+ var filePlugin = {
811
+ name: "@epoch-agent/plugin-file",
812
+ version: "0.0.0",
813
+ description: "\u6587\u4EF6\u8BFB\u5199\u3001\u641C\u7D22\u3001\u7CBE\u786E\u7F16\u8F91",
814
+ tools: [
815
+ {
816
+ name: "file_read",
817
+ description: "\u5206\u9875\u8BFB\u53D6\u6587\u4EF6\u5185\u5BB9\uFF0C\u5E26\u884C\u53F7\u3002\u9ED8\u8BA4\u4E00\u6B21\u8BFB 500 \u884C\uFF0C\u8D85\u8FC7\u7528 offset \u7FFB\u9875\u3002",
818
+ parameters: {
819
+ type: "object",
820
+ properties: {
821
+ path: { type: "string", description: "\u6587\u4EF6\u8DEF\u5F84\uFF08\u76F8\u5BF9\u5DE5\u4F5C\u76EE\u5F55\u6216\u7EDD\u5BF9\u8DEF\u5F84\uFF09" },
822
+ offset: { type: "number", description: "\u4ECE\u7B2C\u51E0\u884C\u5F00\u59CB\u8BFB\uFF08\u9ED8\u8BA4 1\uFF09" },
823
+ limit: { type: "number", description: "\u8BFB\u591A\u5C11\u884C\uFF08\u9ED8\u8BA4 500\uFF0C\u6700\u5927 2000\uFF09" }
824
+ },
825
+ required: ["path"]
826
+ },
827
+ supportsParallel: true,
828
+ annotations: READ_ONLY,
829
+ operation: "file_read",
830
+ describeTarget: pathTarget,
831
+ execute: execRead
832
+ },
833
+ {
834
+ name: "file_multi_read",
835
+ description: "\u4E00\u6B21\u8BFB\u53D6\u591A\u4E2A\u6587\u4EF6\uFF0C\u9002\u5408\u4E86\u89E3\u9879\u76EE\u7ED3\u6784\u3002\u6700\u591A\u540C\u65F6\u8BFB 10 \u4E2A\u3002",
836
+ parameters: {
837
+ type: "object",
838
+ properties: {
839
+ paths: { type: "array", items: { type: "string" }, description: "\u6587\u4EF6\u8DEF\u5F84\u5217\u8868" }
840
+ },
841
+ required: ["paths"]
842
+ },
843
+ supportsParallel: true,
844
+ annotations: READ_ONLY,
845
+ operation: "file_read",
846
+ describeTarget: (args) => {
847
+ const paths = args["paths"];
848
+ return Array.isArray(paths) ? paths.map(String).join(",") : String(paths ?? "");
849
+ },
850
+ execute: execMultiRead
851
+ },
852
+ {
853
+ name: "file_search",
854
+ description: "\u7528 ripgrep \u641C\u7D22\u6587\u4EF6\u5185\u5BB9\uFF08\u6B63\u5219\uFF09\u3002\u652F\u6301\u6307\u5B9A\u76EE\u5F55\u3001\u6587\u4EF6\u7C7B\u578B\u3001\u8F93\u51FA\u6A21\u5F0F\u3002",
855
+ parameters: {
856
+ type: "object",
857
+ properties: {
858
+ pattern: { type: "string", description: "\u641C\u7D22\u6A21\u5F0F\uFF08\u6B63\u5219\uFF09" },
859
+ path: { type: "string", description: "\u641C\u7D22\u76EE\u5F55\uFF08\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55\uFF09" },
860
+ include: { type: "string", description: '\u6587\u4EF6\u7C7B\u578B\u8FC7\u6EE4\uFF0C\u5982 "*.ts"' },
861
+ limit: { type: "number", description: "\u6700\u591A\u8FD4\u56DE\u6761\u6570\uFF08\u9ED8\u8BA4 50\uFF09" },
862
+ output_mode: {
863
+ type: "string",
864
+ enum: ["content", "files_only", "count"],
865
+ description: "\u8F93\u51FA\u6A21\u5F0F"
866
+ }
867
+ },
868
+ required: ["pattern"]
869
+ },
870
+ supportsParallel: true,
871
+ annotations: READ_ONLY,
872
+ operation: "file_read",
873
+ // 搜索的对象是目录,不是 pattern
874
+ describeTarget: dirTarget,
875
+ execute: execSearch
876
+ },
877
+ {
878
+ name: "file_write",
879
+ description: "\u521B\u5EFA\u6216\u8986\u76D6\u6587\u4EF6\u3002\u5199\u5165\u524D\u81EA\u52A8\u5907\u4EFD\uFF0C\u5199\u5165\u540E\u6821\u9A8C\u5B8C\u6574\u6027\uFF0C\u5931\u8D25\u5219\u4ECE\u5907\u4EFD\u6062\u590D\u3002",
880
+ parameters: {
881
+ type: "object",
882
+ properties: {
883
+ path: { type: "string", description: "\u6587\u4EF6\u8DEF\u5F84" },
884
+ content: { type: "string", description: "\u6587\u4EF6\u5B8C\u6574\u5185\u5BB9" }
885
+ },
886
+ required: ["path", "content"]
887
+ },
888
+ supportsParallel: false,
889
+ annotations: DESTRUCTIVE,
890
+ operation: "file_write",
891
+ describeTarget: pathTarget,
892
+ execute: execWrite
893
+ },
894
+ {
895
+ name: "file_patch",
896
+ description: "\u7CBE\u786E\u7F16\u8F91\u6587\u4EF6\uFF1A\u53EA\u6539\u6307\u5B9A\u5185\u5BB9\uFF0C\u4E0D\u91CD\u5199\u6574\u4E2A\u6587\u4EF6\u3002\u6BD4 file_write \u66F4\u5B89\u5168\u3002",
897
+ parameters: {
898
+ type: "object",
899
+ properties: {
900
+ path: { type: "string", description: "\u6587\u4EF6\u8DEF\u5F84" },
901
+ old_string: { type: "string", description: "\u8981\u66FF\u6362\u7684\u539F\u59CB\u6587\u672C\uFF08\u591A\u7528\u51E0\u884C\u4E0A\u4E0B\u6587\u786E\u4FDD\u552F\u4E00\uFF09" },
902
+ new_string: { type: "string", description: "\u66FF\u6362\u540E\u7684\u6587\u672C" },
903
+ replace_all: { type: "boolean", description: "\u662F\u5426\u66FF\u6362\u6240\u6709\u5339\u914D\u5904\uFF08\u9ED8\u8BA4 false\uFF09" }
904
+ },
905
+ required: ["path", "old_string", "new_string"]
906
+ },
907
+ supportsParallel: false,
908
+ annotations: DESTRUCTIVE,
909
+ operation: "file_write",
910
+ describeTarget: pathTarget,
911
+ execute: execPatch
912
+ },
913
+ {
914
+ name: "file_list",
915
+ description: "\u5217\u51FA\u76EE\u5F55\u5185\u5BB9\u3002",
916
+ parameters: {
917
+ type: "object",
918
+ properties: { path: { type: "string", description: "\u76EE\u5F55\u8DEF\u5F84\uFF08\u9ED8\u8BA4\u5F53\u524D\u76EE\u5F55\uFF09" } }
919
+ },
920
+ supportsParallel: true,
921
+ annotations: READ_ONLY,
922
+ operation: "file_read",
923
+ describeTarget: dirTarget,
924
+ execute: execList
925
+ },
926
+ {
927
+ name: "file_diff_preview",
928
+ description: "\u9884\u89C8 V4A \u8865\u4E01\u2014\u2014\u4E0D\u4FEE\u6539\u6587\u4EF6\uFF0C\u4EC5\u5C55\u793A\u53D8\u66F4\u6458\u8981\u3002\u5148\u9884\u89C8\u786E\u8BA4\uFF0C\u518D\u7528 file_multi_patch \u5E94\u7528\u3002\u683C\u5F0F\u540C file_multi_patch\u3002",
929
+ parameters: {
930
+ type: "object",
931
+ properties: { patch: { type: "string", description: "V4A \u683C\u5F0F\u7684\u591A\u6587\u4EF6\u8865\u4E01\u5185\u5BB9" } },
932
+ required: ["patch"]
933
+ },
934
+ // 真实语义是只读(只算 diff 不落盘),annotations 照实写。
935
+ // 但 operation 仍填 file_write:老白名单把它归在 FILE_WRITE_TOOLS 里,
936
+ // 只改一边会让 recordApproval 那条路径与这里分叉。往严的方向偏,
937
+ // 代价只是多一次确认;纠正白名单本身是方案 06 的地盘。
938
+ annotations: READ_ONLY,
939
+ operation: "file_write",
940
+ describeTarget: patchTarget,
941
+ execute: execDiffPreview
942
+ },
943
+ {
944
+ name: "file_multi_patch",
945
+ description: "V4A \u591A\u6587\u4EF6\u8865\u4E01\u2014\u2014\u4E00\u6B21\u4FEE\u6539\u591A\u4E2A\u6587\u4EF6\u3002\u683C\u5F0F\uFF1A*** Begin Patch / *** Update File: / @@ / -\u65E7\u884C +\u65B0\u884C / *** End Patch\u3002\u652F\u6301\u6279\u91CF\u589E\u5220\u6539\u3002",
946
+ parameters: {
947
+ type: "object",
948
+ properties: { patch: { type: "string", description: "V4A \u683C\u5F0F\u7684\u591A\u6587\u4EF6\u8865\u4E01\u5185\u5BB9" } },
949
+ required: ["patch"]
950
+ },
951
+ annotations: DESTRUCTIVE,
952
+ operation: "file_write",
953
+ describeTarget: patchTarget,
954
+ execute: execMultiPatch
955
+ }
956
+ ]
957
+ };
958
+ export {
959
+ filePlugin
960
+ };
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@epoch-agent/plugin-file",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "epoch-agent 文件系统操作插件",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/Ddbor/epoch-agent.git"
9
+ },
10
+ "license": "Apache-2.0",
11
+ "author": "epoch-agent",
12
+ "type": "module",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "main": "./dist/index.js",
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "diff": "^9.0.0",
25
+ "@epoch-agent/infra": "0.1.0",
26
+ "@epoch-agent/protocol": "0.1.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^26.1.2",
30
+ "tsup": "^8.3.6",
31
+ "typescript": "^5.8.3"
32
+ },
33
+ "engines": {
34
+ "node": ">=22.0.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsup",
38
+ "dev": "tsup --watch",
39
+ "typecheck": "tsc --noEmit"
40
+ }
41
+ }