@ai-zen/agents-sdk 1.0.0-alpha.9 → 1.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/CHANGELOG.md +691 -2
- package/README.md +22 -6
- package/README.zh.md +23 -7
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -9
- package/dist/agent-plugins/AutoMigratePlugin.js +26 -10
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +28 -16
- package/dist/agent-plugins/ContextGuardPlugin.js +23 -17
- package/dist/agent-plugins/UnknownToolHintPlugin.js +4 -4
- package/dist/config/ConfigManager.d.ts +57 -8
- package/dist/config/ConfigManager.js +167 -26
- package/dist/config/constants.d.ts +7 -0
- package/dist/config/constants.js +70 -43
- package/dist/config/factory-skills.d.ts +33 -0
- package/dist/config/factory-skills.js +126 -0
- package/dist/config/migrate.d.ts +106 -0
- package/dist/config/migrate.js +196 -0
- package/dist/config/reasoning-presets.d.ts +37 -0
- package/dist/config/reasoning-presets.js +64 -0
- package/dist/index.d.ts +13 -7
- package/dist/index.js +11 -3
- package/dist/runtime/HandoffGuardPlugin.d.ts +35 -0
- package/dist/runtime/HandoffGuardPlugin.js +65 -0
- package/dist/runtime/HandoffService.d.ts +288 -0
- package/dist/runtime/HandoffService.js +538 -0
- package/dist/runtime/SdkAgent.d.ts +7 -1
- package/dist/runtime/SdkAgent.js +3 -0
- package/dist/runtime/createAgent.d.ts +20 -1
- package/dist/runtime/createAgent.js +14 -9
- package/dist/runtime/createModel.d.ts +8 -4
- package/dist/runtime/createModel.js +22 -5
- package/dist/scope/PermissionEvaluator.js +1 -1
- package/dist/scope/Scope.d.ts +3 -1
- package/dist/scope/Scope.js +4 -2
- package/dist/scope/plugins/builtin/BatchEditTool.js +24 -14
- package/dist/scope/plugins/builtin/CopyTool.js +4 -4
- package/dist/scope/plugins/builtin/CwdTool.js +1 -1
- package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
- package/dist/scope/plugins/builtin/DownloadFileTool.js +58 -34
- package/dist/scope/plugins/builtin/EditTool.js +25 -25
- package/dist/scope/plugins/builtin/ExecTool.js +134 -25
- package/dist/scope/plugins/builtin/ExistTool.js +2 -2
- package/dist/scope/plugins/builtin/FindTextTool.js +15 -10
- package/dist/scope/plugins/builtin/GenerateImageTool.js +91 -25
- package/dist/scope/plugins/builtin/GlobTool.js +10 -5
- package/dist/scope/plugins/builtin/InspectFileTool.js +7 -7
- package/dist/scope/plugins/builtin/LsTool.js +5 -5
- package/dist/scope/plugins/builtin/MkdirTool.js +3 -3
- package/dist/scope/plugins/builtin/ReadTool.js +8 -8
- package/dist/scope/plugins/builtin/RenameTool.js +3 -3
- package/dist/scope/plugins/builtin/RmTool.js +3 -3
- package/dist/scope/plugins/builtin/SleepTool.js +6 -6
- package/dist/scope/plugins/builtin/SpawnTool.js +32 -49
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +6 -4
- package/dist/scope/plugins/builtin/ViewImageTool.js +50 -62
- package/dist/scope/plugins/builtin/WriteTool.js +3 -3
- package/dist/scope/plugins/builtin/searchBase.d.ts +9 -0
- package/dist/scope/plugins/builtin/searchBase.js +17 -0
- package/dist/scope/plugins/builtin/test-helpers.d.ts +3 -3
- package/dist/scope/plugins/builtin/test-helpers.js +3 -3
- package/dist/scope/plugins/builtin/textEdit.d.ts +17 -0
- package/dist/scope/plugins/builtin/textEdit.js +37 -0
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +9 -1
- package/dist/scope/plugins/mcp/McpConnectionManager.js +95 -16
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/mcp/McpScopePlugin.js +8 -6
- package/dist/scope/plugins/mcp/discover.js +1 -1
- package/dist/scope/plugins/mcp/mcpTools.d.ts +9 -3
- package/dist/scope/plugins/mcp/mcpTools.js +247 -37
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
- package/dist/scope/plugins/skills/discover.js +28 -9
- package/dist/scope/plugins/skills/skillTools.js +30 -20
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
- package/dist/scope/plugins/subagents/subAgentTools.js +4 -3
- package/dist/scope/plugins/usertools/discover.d.ts +8 -3
- package/dist/scope/plugins/usertools/discover.js +139 -12
- package/dist/shared/EntityRepository.d.ts +10 -1
- package/dist/shared/EntityRepository.js +18 -6
- package/dist/shared/content-blocks.d.ts +101 -0
- package/dist/shared/content-blocks.js +253 -0
- package/dist/shared/errors.d.ts +4 -8
- package/dist/shared/errors.js +8 -14
- package/dist/types/index.d.ts +170 -8
- package/package.json +16 -7
- package/dist/runtime/TaskMigrationService.d.ts +0 -128
- package/dist/runtime/TaskMigrationService.js +0 -211
|
@@ -1,20 +1,37 @@
|
|
|
1
1
|
import OpenAI from "openai";
|
|
2
|
+
/**
|
|
3
|
+
* 参数覆盖 —— 浅合并,一行。
|
|
4
|
+
*
|
|
5
|
+
* 这是 SDK 对「模型参数」的唯一处理逻辑:不解释键名、不做档位推导、不知道厂商差异。
|
|
6
|
+
* 需要多层次语义(如「思考档位」)的应用,应该在**写配置时**就把档位展开成具体参数,
|
|
7
|
+
* 存进 `Model.defaultParams` / `AgentDefinition.modelParams`,运行期不再查表。
|
|
8
|
+
*
|
|
9
|
+
* 没有覆盖时返回原对象(保持 `undefined` 语义,避免凭空塞一个空对象)。
|
|
10
|
+
*/
|
|
11
|
+
function mergeParams(base, overrides) {
|
|
12
|
+
if (!overrides || Object.keys(overrides).length === 0)
|
|
13
|
+
return base;
|
|
14
|
+
return { ...base, ...overrides };
|
|
15
|
+
}
|
|
2
16
|
/**
|
|
3
17
|
* 模型工厂 — 根据 modelId 和 Scope 装配 openai SDK client。
|
|
4
18
|
*
|
|
5
19
|
* 端点(baseUrl / apiKey)来自 config.endpoints,发送给 API 的模型名 = modelName || id。
|
|
6
20
|
* 任何 OpenAI 兼容端点(OpenAI / 智谱 BigModel / DeepSeek 等)均可通过 baseURL 接入。
|
|
21
|
+
*
|
|
22
|
+
* `overrides` 是 **Agent 级参数覆盖**(`AgentDefinition.modelParams`):
|
|
23
|
+
* 同一个模型可以给不同 Agent 配不同参数,而模型自身的 `defaultParams` 保持不变。
|
|
7
24
|
*/
|
|
8
|
-
export function createModel(scope, modelId) {
|
|
25
|
+
export function createModel(scope, modelId, overrides) {
|
|
9
26
|
const config = scope.config;
|
|
10
27
|
const modelConfig = config.models.find((m) => m.id === modelId);
|
|
11
28
|
if (!modelConfig)
|
|
12
|
-
throw new Error(
|
|
29
|
+
throw new Error(`Model "${modelId}" not found`);
|
|
13
30
|
const endpointConfig = config.endpoints.find((e) => e.id === modelConfig.endpointId);
|
|
14
31
|
if (!endpointConfig)
|
|
15
|
-
throw new Error(
|
|
32
|
+
throw new Error(`Endpoint "${modelConfig.endpointId}" is not configured`);
|
|
16
33
|
if (!endpointConfig.apiKey) {
|
|
17
|
-
throw new Error(
|
|
34
|
+
throw new Error(`API key for endpoint "${endpointConfig.name}" is not set`);
|
|
18
35
|
}
|
|
19
36
|
const client = new OpenAI({
|
|
20
37
|
apiKey: endpointConfig.apiKey,
|
|
@@ -25,6 +42,6 @@ export function createModel(scope, modelId) {
|
|
|
25
42
|
return {
|
|
26
43
|
client,
|
|
27
44
|
model: apiModelName,
|
|
28
|
-
modelConfig: modelConfig.defaultParams,
|
|
45
|
+
modelConfig: mergeParams(modelConfig.defaultParams, overrides),
|
|
29
46
|
};
|
|
30
47
|
}
|
package/dist/scope/Scope.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Tool } from "@ai-zen/agents-core";
|
|
2
|
-
import type { AppConfig, AgentDefinition, ToolEnv } from "../types/index.js";
|
|
2
|
+
import type { AppConfig, AgentDefinition, ToolEnv, ToolEnvDeps } from "../types/index.js";
|
|
3
3
|
import type { ScopePlugin } from "./ScopePlugin.js";
|
|
4
4
|
/**
|
|
5
5
|
* 能力过滤系统的公共类型。
|
|
@@ -64,6 +64,8 @@ export declare class Scope {
|
|
|
64
64
|
config: AppConfig;
|
|
65
65
|
agentsDir: string;
|
|
66
66
|
cwd?: string;
|
|
67
|
+
/** 出网/外部依赖的注入点(缺省全部走真实 OpenAI SDK),会透传到 ToolEnv.deps */
|
|
68
|
+
deps?: ToolEnvDeps;
|
|
67
69
|
});
|
|
68
70
|
/** 已注册插件(只读视图) */
|
|
69
71
|
get plugins(): readonly ScopePlugin[];
|
package/dist/scope/Scope.js
CHANGED
|
@@ -36,7 +36,9 @@ export class Scope {
|
|
|
36
36
|
constructor(options) {
|
|
37
37
|
this.config = options.config;
|
|
38
38
|
this.cwd = options.cwd ?? process.cwd();
|
|
39
|
-
this.env =
|
|
39
|
+
this.env = options.deps
|
|
40
|
+
? { cwd: this.cwd, config: this.config, deps: options.deps }
|
|
41
|
+
: { cwd: this.cwd, config: this.config };
|
|
40
42
|
this.agentsDir = options.agentsDir;
|
|
41
43
|
}
|
|
42
44
|
// ==================================================================
|
|
@@ -57,7 +59,7 @@ export class Scope {
|
|
|
57
59
|
*/
|
|
58
60
|
use(...plugins) {
|
|
59
61
|
if (this._initialized) {
|
|
60
|
-
throw new Error("Scope.use()
|
|
62
|
+
throw new Error("Scope.use() must be called before init()");
|
|
61
63
|
}
|
|
62
64
|
for (const plugin of plugins) {
|
|
63
65
|
this._plugins.push(plugin);
|
|
@@ -1,33 +1,38 @@
|
|
|
1
1
|
import * as fsp from "fs/promises";
|
|
2
2
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
3
|
+
import { replaceText } from "./textEdit.js";
|
|
3
4
|
export class BatchEditTool extends SdkCallbackTool {
|
|
4
5
|
function = {
|
|
5
6
|
name: "batch_edit",
|
|
6
|
-
description:
|
|
7
|
+
description: [
|
|
8
|
+
"Edit text in a file in batches. Prefer this tool when making edits to a file.",
|
|
9
|
+
"Submit all changes to the same file in a single call (the replacements array) instead of calling edit in parallel multiple times — parallel edits to the same file overwrite each other.",
|
|
10
|
+
"Replacements are applied in order, each on the result of the previous one: a later oldText is matched against the content already produced by the earlier replacements.",
|
|
11
|
+
].join("\n"),
|
|
7
12
|
parameters: {
|
|
8
13
|
type: "object",
|
|
9
14
|
properties: {
|
|
10
15
|
path: {
|
|
11
16
|
type: "string",
|
|
12
|
-
description: "
|
|
17
|
+
description: "File path",
|
|
13
18
|
},
|
|
14
19
|
replacements: {
|
|
15
20
|
type: "array",
|
|
16
|
-
description: "
|
|
21
|
+
description: "Array of replacements",
|
|
17
22
|
items: {
|
|
18
23
|
type: "object",
|
|
19
24
|
properties: {
|
|
20
25
|
oldText: {
|
|
21
26
|
type: "string",
|
|
22
|
-
description: "
|
|
27
|
+
description: "Text to replace",
|
|
23
28
|
},
|
|
24
29
|
newText: {
|
|
25
30
|
type: "string",
|
|
26
|
-
description: "
|
|
31
|
+
description: "Replacement text",
|
|
27
32
|
},
|
|
28
33
|
isReplaceAll: {
|
|
29
34
|
type: "boolean",
|
|
30
|
-
description: "
|
|
35
|
+
description: "Whether to replace all matches (by default only the first match is replaced). Make sure the oldText you provide is precise enough to avoid unintended replacements",
|
|
31
36
|
default: false,
|
|
32
37
|
},
|
|
33
38
|
},
|
|
@@ -53,21 +58,26 @@ export class BatchEditTool extends SdkCallbackTool {
|
|
|
53
58
|
// 成功项不回显原文与新文,仅计入成功数,避免大段文本回显撑大输出
|
|
54
59
|
const failed = [];
|
|
55
60
|
for (const replacement of input.replacements) {
|
|
56
|
-
|
|
61
|
+
// 空串会匹配每一个位置,不是有意义的编辑,单独拒绝
|
|
62
|
+
if (replacement.oldText === "") {
|
|
57
63
|
failed.push({
|
|
58
64
|
oldText: replacement.oldText,
|
|
59
65
|
newText: replacement.newText,
|
|
60
|
-
reason: "
|
|
66
|
+
reason: "oldText must not be empty",
|
|
61
67
|
});
|
|
62
68
|
continue;
|
|
63
69
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
70
|
+
const { content: nextContent, replacedCount: count } = replaceText(newContent, replacement.oldText, replacement.newText, replacement.isReplaceAll ?? false);
|
|
71
|
+
if (count === 0) {
|
|
72
|
+
failed.push({
|
|
73
|
+
oldText: replacement.oldText,
|
|
74
|
+
newText: replacement.newText,
|
|
75
|
+
reason: "No exact match found for this oldText (matched against the content after the previous replacements in this batch)",
|
|
76
|
+
});
|
|
77
|
+
continue;
|
|
69
78
|
}
|
|
70
|
-
|
|
79
|
+
newContent = nextContent;
|
|
80
|
+
replacedCount += count;
|
|
71
81
|
}
|
|
72
82
|
await fsp.writeFile(filePath, newContent);
|
|
73
83
|
if (failed.length === 0) {
|
|
@@ -3,21 +3,21 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
|
3
3
|
export class CopyTool extends SdkCallbackTool {
|
|
4
4
|
function = {
|
|
5
5
|
name: "copy",
|
|
6
|
-
description: "
|
|
6
|
+
description: "Copy a file or directory (equivalent to the cp command)",
|
|
7
7
|
parameters: {
|
|
8
8
|
type: "object",
|
|
9
9
|
properties: {
|
|
10
10
|
src: {
|
|
11
11
|
type: "string",
|
|
12
|
-
description: "
|
|
12
|
+
description: "Source path",
|
|
13
13
|
},
|
|
14
14
|
dest: {
|
|
15
15
|
type: "string",
|
|
16
|
-
description: "
|
|
16
|
+
description: "Destination path",
|
|
17
17
|
},
|
|
18
18
|
recursive: {
|
|
19
19
|
type: "boolean",
|
|
20
|
-
description: "
|
|
20
|
+
description: "Whether to copy directories recursively; must be true when copying a directory",
|
|
21
21
|
},
|
|
22
22
|
},
|
|
23
23
|
required: ["src", "dest"],
|
|
@@ -2,7 +2,7 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
|
2
2
|
export class CwdTool extends SdkCallbackTool {
|
|
3
3
|
function = {
|
|
4
4
|
name: "cwd",
|
|
5
|
-
description: "
|
|
5
|
+
description: "Get the current working directory (cwd)",
|
|
6
6
|
parameters: {
|
|
7
7
|
type: "object",
|
|
8
8
|
properties: {},
|
|
@@ -1,23 +1,30 @@
|
|
|
1
1
|
import * as fsp from "fs/promises";
|
|
2
2
|
import * as path from "path";
|
|
3
|
+
import { createWriteStream } from "fs";
|
|
4
|
+
import { Readable } from "node:stream";
|
|
5
|
+
import { pipeline } from "node:stream/promises";
|
|
3
6
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
4
7
|
export class DownloadFileTool extends SdkCallbackTool {
|
|
5
8
|
function = {
|
|
6
9
|
name: "download_file",
|
|
7
|
-
description: "
|
|
10
|
+
description: "Download a file from a URL (images, PDFs and other binary files) and save it to the local disk. The file name is inferred from the URL, or you can specify the save path.",
|
|
8
11
|
parameters: {
|
|
9
12
|
type: "object",
|
|
10
13
|
properties: {
|
|
11
14
|
url: {
|
|
12
15
|
type: "string",
|
|
13
|
-
description: "
|
|
16
|
+
description: "URL to download the file from",
|
|
14
17
|
},
|
|
15
18
|
outputPath: {
|
|
16
19
|
type: "string",
|
|
17
|
-
description: "
|
|
20
|
+
description: "Save path (optional). May be a directory or a full file path. If omitted, the file is saved to the current working directory with the file name inferred from the URL.",
|
|
21
|
+
},
|
|
22
|
+
timeout: {
|
|
23
|
+
type: "number",
|
|
24
|
+
description: "Timeout in milliseconds (required). The download is aborted on timeout. Large files need a larger value.",
|
|
18
25
|
},
|
|
19
26
|
},
|
|
20
|
-
required: ["url"],
|
|
27
|
+
required: ["url", "timeout"],
|
|
21
28
|
additionalProperties: false,
|
|
22
29
|
},
|
|
23
30
|
};
|
|
@@ -25,12 +32,18 @@ export class DownloadFileTool extends SdkCallbackTool {
|
|
|
25
32
|
super({ env });
|
|
26
33
|
}
|
|
27
34
|
async call(input, ctx) {
|
|
28
|
-
const
|
|
35
|
+
const url = input.url;
|
|
36
|
+
const { timeout } = input;
|
|
37
|
+
if (!url)
|
|
38
|
+
throw new Error("download_file: url must not be empty");
|
|
39
|
+
// 运行时双校验:timeout 必填且必须为正数(与 exec 同口径)
|
|
40
|
+
if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0) {
|
|
41
|
+
throw new Error(`download_file: timeout is required and must be a positive number (milliseconds), got: ${JSON.stringify(timeout)}`);
|
|
42
|
+
}
|
|
29
43
|
let savePath;
|
|
44
|
+
// 是否已开始写盘:仅用于如实说明"文件可能不完整",不做任何删除动作
|
|
45
|
+
let startedWriting = false;
|
|
30
46
|
try {
|
|
31
|
-
const url = input.url;
|
|
32
|
-
if (!url)
|
|
33
|
-
throw new Error("url 不能为空");
|
|
34
47
|
if (input.outputPath) {
|
|
35
48
|
savePath = this.resolve(input.outputPath);
|
|
36
49
|
const stat = await fsp.stat(savePath).catch(() => null);
|
|
@@ -46,37 +59,48 @@ export class DownloadFileTool extends SdkCallbackTool {
|
|
|
46
59
|
savePath = path.join(this.env.cwd, fileName);
|
|
47
60
|
}
|
|
48
61
|
await fsp.mkdir(path.dirname(savePath), { recursive: true });
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
// 中断(abort)时清理可能残留的半成品文件
|
|
69
|
-
if (signal?.aborted && savePath) {
|
|
70
|
-
await fsp.rm(savePath, { force: true }).catch(() => { });
|
|
62
|
+
// 总时长上限:fetch 自身只对"响应头"有兜底,响应体可以无限期地流下去
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timer = setTimeout(() => controller.abort(new Error(`timeout after ${timeout}ms`)), timeout);
|
|
65
|
+
const onAbort = () => controller.abort(ctx?.signal?.reason);
|
|
66
|
+
ctx?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
67
|
+
try {
|
|
68
|
+
const response = await fetch(url, { signal: controller.signal });
|
|
69
|
+
if (!response.ok) {
|
|
70
|
+
throw new Error(`Download failed: HTTP ${response.status} ${response.statusText}`);
|
|
71
|
+
}
|
|
72
|
+
if (!response.body) {
|
|
73
|
+
throw new Error("Download failed: response has no body");
|
|
74
|
+
}
|
|
75
|
+
const contentType = response.headers.get("content-type") || "";
|
|
76
|
+
// 流式写盘:不把整个文件读进内存(大文件下 arrayBuffer() 会吃掉数倍于文件大小的堆)
|
|
77
|
+
startedWriting = true;
|
|
78
|
+
await pipeline(Readable.fromWeb(response.body), createWriteStream(savePath));
|
|
79
|
+
const stats = await fsp.stat(savePath);
|
|
80
|
+
const fileSizeKB = (stats.size / 1024).toFixed(1);
|
|
71
81
|
return JSON.stringify({
|
|
72
|
-
success:
|
|
73
|
-
|
|
74
|
-
|
|
82
|
+
success: true,
|
|
83
|
+
filePath: path.resolve(savePath),
|
|
84
|
+
fileSize: `${fileSizeKB} KB`,
|
|
85
|
+
contentType,
|
|
86
|
+
note: "File saved to local disk",
|
|
75
87
|
});
|
|
76
88
|
}
|
|
89
|
+
finally {
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
ctx?.signal?.removeEventListener("abort", onAbort);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
const aborted = ctx?.signal?.aborted ?? false;
|
|
77
96
|
return JSON.stringify({
|
|
78
97
|
success: false,
|
|
79
|
-
|
|
98
|
+
...(aborted ? { aborted: true } : {}),
|
|
99
|
+
error: error?.message || "Download failed",
|
|
100
|
+
// 已开始写盘时文件可能不完整:只如实告知,绝不去删(同路径的原文件可能本来就存在)
|
|
101
|
+
...(startedWriting
|
|
102
|
+
? { note: "The file at the save path may be incomplete or overwritten" }
|
|
103
|
+
: {}),
|
|
80
104
|
});
|
|
81
105
|
}
|
|
82
106
|
}
|
|
@@ -1,39 +1,33 @@
|
|
|
1
1
|
import * as fsp from "fs/promises";
|
|
2
2
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
3
|
-
|
|
4
|
-
let count = 0;
|
|
5
|
-
let pos = 0;
|
|
6
|
-
while (true) {
|
|
7
|
-
pos = content.indexOf(text, pos);
|
|
8
|
-
if (pos === -1)
|
|
9
|
-
break;
|
|
10
|
-
count++;
|
|
11
|
-
pos += text.length;
|
|
12
|
-
}
|
|
13
|
-
return count;
|
|
14
|
-
}
|
|
3
|
+
import { countOccurrences, replaceText } from "./textEdit.js";
|
|
15
4
|
export class EditTool extends SdkCallbackTool {
|
|
16
5
|
function = {
|
|
17
6
|
name: "edit",
|
|
18
|
-
description:
|
|
7
|
+
description: [
|
|
8
|
+
"Edit text in a file, supporting exact replacement or replacing all matches.",
|
|
9
|
+
"",
|
|
10
|
+
"Concurrency limit (important): never edit the same file in parallel. Do not issue multiple edit calls for the same path within one reply — each call reads the old content and writes it back, so the later write overwrites the earlier one, losing changes or corrupting the file.",
|
|
11
|
+
"To apply multiple changes to one file, use batch_edit instead and submit all replacements in a single call. Only edit different files in parallel.",
|
|
12
|
+
].join("\n"),
|
|
19
13
|
parameters: {
|
|
20
14
|
type: "object",
|
|
21
15
|
properties: {
|
|
22
16
|
path: {
|
|
23
17
|
type: "string",
|
|
24
|
-
description: "
|
|
18
|
+
description: "File path",
|
|
25
19
|
},
|
|
26
20
|
oldText: {
|
|
27
21
|
type: "string",
|
|
28
|
-
description: "
|
|
22
|
+
description: "Text to replace",
|
|
29
23
|
},
|
|
30
24
|
newText: {
|
|
31
25
|
type: "string",
|
|
32
|
-
description: "
|
|
26
|
+
description: "Replacement text",
|
|
33
27
|
},
|
|
34
28
|
isReplaceAll: {
|
|
35
29
|
type: "boolean",
|
|
36
|
-
description: "
|
|
30
|
+
description: "Whether to replace all matches (default false, only the first match is replaced). Make sure the oldText you provide is precise enough to avoid unintended replacements",
|
|
37
31
|
default: false,
|
|
38
32
|
},
|
|
39
33
|
},
|
|
@@ -51,28 +45,34 @@ export class EditTool extends SdkCallbackTool {
|
|
|
51
45
|
const newText = input.newText;
|
|
52
46
|
const isReplaceAll = input.isReplaceAll ?? false;
|
|
53
47
|
const content = await fsp.readFile(filePath, "utf-8");
|
|
48
|
+
// 空串会匹配每一个位置(不是一个有意义的编辑),直接拒绝
|
|
49
|
+
if (oldText === "") {
|
|
50
|
+
return JSON.stringify({
|
|
51
|
+
result: "oldText must not be empty",
|
|
52
|
+
matchCount: 0,
|
|
53
|
+
replacedCount: 0,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
54
56
|
const count = countOccurrences(content, oldText);
|
|
55
57
|
if (count === 0) {
|
|
56
58
|
return JSON.stringify({
|
|
57
|
-
result: "
|
|
59
|
+
result: "No exact match found for the text to replace",
|
|
58
60
|
matchCount: 0,
|
|
59
61
|
});
|
|
60
62
|
}
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
: content.replace(oldText, newText);
|
|
64
|
-
await fsp.writeFile(filePath, newContent);
|
|
63
|
+
const { content: nextContent, replacedCount } = replaceText(content, oldText, newText, isReplaceAll);
|
|
64
|
+
await fsp.writeFile(filePath, nextContent);
|
|
65
65
|
if (!isReplaceAll && count > 1) {
|
|
66
66
|
return JSON.stringify({
|
|
67
|
-
result:
|
|
67
|
+
result: `Warning: replace-all is off (isReplaceAll=false), but the text "${oldText}" occurs ${count} times in the file; only the first match was replaced. Set isReplaceAll to true to replace all matches`,
|
|
68
68
|
matchCount: count,
|
|
69
|
-
replacedCount
|
|
69
|
+
replacedCount,
|
|
70
70
|
});
|
|
71
71
|
}
|
|
72
72
|
return JSON.stringify({
|
|
73
73
|
result: "success",
|
|
74
74
|
matchCount: count,
|
|
75
|
-
replacedCount
|
|
75
|
+
replacedCount,
|
|
76
76
|
});
|
|
77
77
|
}
|
|
78
78
|
catch (error) {
|