@ai-zen/agents-sdk 1.0.0-alpha.8 → 1.0.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 +661 -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 +21 -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 +246 -0
- package/dist/runtime/HandoffService.js +475 -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
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) {
|
|
@@ -1,20 +1,32 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { spawn } from "child_process";
|
|
2
2
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
3
3
|
import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headTailPreview } from "./outputGuard.js";
|
|
4
|
+
/**
|
|
5
|
+
* stdout + stderr 的内存上限(字节,两流合计)。
|
|
6
|
+
*
|
|
7
|
+
* `exec` 默认 maxBuffer 只有 1MB:超限时它直接杀掉子进程、只留下前 1MB,还把
|
|
8
|
+
* `error.code` 变成一个字符串错误码。这里显式放大上限,并在真的截断时如实标注
|
|
9
|
+
* `truncated`(尾部内容已丢失)。
|
|
10
|
+
*/
|
|
11
|
+
const MAX_BUFFER = 16 * 1024 * 1024;
|
|
12
|
+
/** 进程组 SIGKILL 之后等待回调的兜底时长:万一管道被孤儿进程占住,也不至于永久挂起 */
|
|
13
|
+
const KILL_GRACE_MS = 2000;
|
|
14
|
+
/** 子进程已退出、但 stdio 仍被后代占住时,攒完已到达的输出就收尾 */
|
|
15
|
+
const STDIO_DRAIN_MS = 200;
|
|
4
16
|
export class ExecTool extends SdkCallbackTool {
|
|
5
17
|
function = {
|
|
6
18
|
name: "exec",
|
|
7
|
-
description: "
|
|
19
|
+
description: "Execute a shell command",
|
|
8
20
|
parameters: {
|
|
9
21
|
type: "object",
|
|
10
22
|
properties: {
|
|
11
23
|
command: {
|
|
12
24
|
type: "string",
|
|
13
|
-
description: "
|
|
25
|
+
description: "Command to execute",
|
|
14
26
|
},
|
|
15
27
|
timeout: {
|
|
16
28
|
type: "number",
|
|
17
|
-
description: "
|
|
29
|
+
description: "Timeout in milliseconds (required). The process is killed on timeout. For long-running commands, prefer spawn to run them asynchronously.",
|
|
18
30
|
},
|
|
19
31
|
},
|
|
20
32
|
required: ["command", "timeout"],
|
|
@@ -29,7 +41,7 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
29
41
|
const { timeout } = input;
|
|
30
42
|
// 运行时双校验:timeout 必填且必须为正数
|
|
31
43
|
if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0) {
|
|
32
|
-
throw new Error(`exec:
|
|
44
|
+
throw new Error(`exec: timeout is required and must be a positive number (milliseconds), got: ${JSON.stringify(timeout)}`);
|
|
33
45
|
}
|
|
34
46
|
const signal = ctx?.signal;
|
|
35
47
|
const result = await new Promise((resolve) => {
|
|
@@ -37,7 +49,7 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
37
49
|
if (signal?.aborted) {
|
|
38
50
|
resolve({
|
|
39
51
|
stdout: "",
|
|
40
|
-
stderr: "
|
|
52
|
+
stderr: "Process aborted",
|
|
41
53
|
exitCode: null,
|
|
42
54
|
killed: true,
|
|
43
55
|
terminated: "aborted",
|
|
@@ -46,42 +58,136 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
46
58
|
}
|
|
47
59
|
let child;
|
|
48
60
|
let settled = false;
|
|
61
|
+
let terminated;
|
|
62
|
+
let truncated = false;
|
|
63
|
+
let bytes = 0;
|
|
64
|
+
const out = [];
|
|
65
|
+
const err = [];
|
|
66
|
+
let timeoutTimer;
|
|
67
|
+
let graceTimer;
|
|
68
|
+
let drainTimer;
|
|
69
|
+
let exitCode = null;
|
|
70
|
+
let exitSignal = null;
|
|
71
|
+
let exited = false;
|
|
49
72
|
const settle = (value) => {
|
|
50
73
|
if (settled)
|
|
51
74
|
return;
|
|
52
75
|
settled = true;
|
|
76
|
+
if (timeoutTimer)
|
|
77
|
+
clearTimeout(timeoutTimer);
|
|
78
|
+
if (graceTimer)
|
|
79
|
+
clearTimeout(graceTimer);
|
|
80
|
+
if (drainTimer)
|
|
81
|
+
clearTimeout(drainTimer);
|
|
53
82
|
signal?.removeEventListener("abort", onAbort);
|
|
54
83
|
resolve(value);
|
|
55
84
|
};
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const terminated = killed
|
|
59
|
-
? (signal?.aborted ? "aborted" : "timeout")
|
|
60
|
-
: undefined;
|
|
85
|
+
/** 用已收集到的输出收尾(子进程已退出或被杀) */
|
|
86
|
+
const settleFromCollected = (forced) => {
|
|
61
87
|
settle({
|
|
62
|
-
stdout,
|
|
63
|
-
stderr,
|
|
64
|
-
exitCode
|
|
65
|
-
killed,
|
|
88
|
+
stdout: Buffer.concat(out).toString(),
|
|
89
|
+
stderr: Buffer.concat(err).toString(),
|
|
90
|
+
exitCode,
|
|
91
|
+
killed: terminated !== undefined || exitSignal !== null,
|
|
92
|
+
terminated: terminated ?? forced,
|
|
93
|
+
truncated: truncated || undefined,
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* 杀整个进程组,而不是只杀 shell。
|
|
98
|
+
*
|
|
99
|
+
* `detached: true` 让子进程成为新进程组的组长,`-pid` 即「该组所有进程」;
|
|
100
|
+
* 只 kill shell 会把后代留成孤儿(`cmd | cat`、`sh -c 'sleep 100 &'` 都会漏)。
|
|
101
|
+
* 注意:`child_process.exec()` 会忽略 `detached`(实测 Node 26),故这里用 spawn。
|
|
102
|
+
* Windows 不支持负 pid,回退为只杀子进程。
|
|
103
|
+
*/
|
|
104
|
+
const killProcessGroup = () => {
|
|
105
|
+
if (!child?.pid)
|
|
106
|
+
return;
|
|
107
|
+
if (process.platform === "win32") {
|
|
108
|
+
child.kill("SIGKILL");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
process.kill(-child.pid, "SIGKILL");
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
child.kill("SIGKILL");
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
child = spawn(command, {
|
|
119
|
+
cwd: this.env.cwd,
|
|
120
|
+
shell: true,
|
|
121
|
+
detached: process.platform !== "win32",
|
|
122
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
123
|
+
});
|
|
124
|
+
const collect = (target) => (chunk) => {
|
|
125
|
+
if (truncated)
|
|
126
|
+
return;
|
|
127
|
+
bytes += chunk.length;
|
|
128
|
+
target.push(chunk);
|
|
129
|
+
// 超过内存上限:停手并杀掉进程组,尾部本来也存不下
|
|
130
|
+
if (bytes > MAX_BUFFER) {
|
|
131
|
+
truncated = true;
|
|
132
|
+
killProcessGroup();
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
child.stdout?.on("data", collect(out));
|
|
136
|
+
child.stderr?.on("data", collect(err));
|
|
137
|
+
child.on("error", (e) => {
|
|
138
|
+
settle({
|
|
139
|
+
stdout: "",
|
|
140
|
+
stderr: e.message,
|
|
141
|
+
exitCode: null,
|
|
142
|
+
killed: false,
|
|
66
143
|
terminated,
|
|
67
144
|
});
|
|
68
145
|
});
|
|
69
|
-
|
|
146
|
+
child.on("exit", (code, sig) => {
|
|
147
|
+
exited = true;
|
|
148
|
+
exitCode = code;
|
|
149
|
+
exitSignal = sig;
|
|
150
|
+
// 已退出但 stdio 可能还被后代占着(如 `cmd &`):只等一小会儿就收尾
|
|
151
|
+
drainTimer = setTimeout(() => settleFromCollected(), STDIO_DRAIN_MS);
|
|
152
|
+
});
|
|
153
|
+
child.on("close", (code, sig) => {
|
|
154
|
+
if (!exited) {
|
|
155
|
+
exitCode = code;
|
|
156
|
+
exitSignal = sig;
|
|
157
|
+
}
|
|
158
|
+
settleFromCollected();
|
|
159
|
+
});
|
|
160
|
+
// 中断:整组 kill,并立即返回(不等待回调,避免挂起)
|
|
70
161
|
const onAbort = () => {
|
|
71
|
-
|
|
72
|
-
|
|
162
|
+
terminated = "aborted";
|
|
163
|
+
killProcessGroup();
|
|
73
164
|
settle({
|
|
74
165
|
stdout: "",
|
|
75
|
-
stderr: "
|
|
166
|
+
stderr: "Process aborted",
|
|
76
167
|
exitCode: null,
|
|
77
168
|
killed: true,
|
|
78
169
|
terminated: "aborted",
|
|
79
170
|
});
|
|
80
171
|
};
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
172
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
173
|
+
// 超时:整组 kill 后优先等回调,好把已收集到的输出带回去
|
|
174
|
+
timeoutTimer = setTimeout(() => {
|
|
175
|
+
terminated = "timeout";
|
|
176
|
+
killProcessGroup();
|
|
177
|
+
graceTimer = setTimeout(() => {
|
|
178
|
+
settle({
|
|
179
|
+
stdout: Buffer.concat(out).toString(),
|
|
180
|
+
stderr: Buffer.concat(err).toString(),
|
|
181
|
+
exitCode: null,
|
|
182
|
+
killed: true,
|
|
183
|
+
terminated: "timeout",
|
|
184
|
+
});
|
|
185
|
+
}, KILL_GRACE_MS);
|
|
186
|
+
}, timeout);
|
|
84
187
|
});
|
|
188
|
+
const truncationNote = result.truncated
|
|
189
|
+
? `Output reached the ${MAX_BUFFER}-byte in-memory cap: it was truncated there and the tail is lost (the process was killed by maxBuffer).`
|
|
190
|
+
: undefined;
|
|
85
191
|
// 输出保护:stdout + stderr 合计超过 maxToolOutput 时,分文件落盘并返回警告 + 头尾预览
|
|
86
192
|
const limit = this.env.config.maxToolOutput ?? DEFAULT_MAX_TOOL_OUTPUT;
|
|
87
193
|
const guarded = await guardOutput({
|
|
@@ -97,8 +203,9 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
97
203
|
const stderr = headTailPreview(result.stderr);
|
|
98
204
|
return JSON.stringify({
|
|
99
205
|
outputTooLarge: true,
|
|
100
|
-
warning:
|
|
101
|
-
|
|
206
|
+
warning: `Output too large: stdout + stderr total ${result.stdout.length + result.stderr.length} characters, ` +
|
|
207
|
+
`exceeds the limit of ${limit} characters. The output as captured is available in separate files (stdout.log / stderr.log); use read to fetch it in chunks`,
|
|
208
|
+
...(truncationNote ? { truncated: true, truncationNote } : {}),
|
|
102
209
|
files: ctx.files,
|
|
103
210
|
stdout: { chars: result.stdout.length, lines: countLines(result.stdout), ...stdout },
|
|
104
211
|
stderr: { chars: result.stderr.length, lines: countLines(result.stderr), ...stderr },
|
|
@@ -109,7 +216,9 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
109
216
|
},
|
|
110
217
|
});
|
|
111
218
|
// 未超限:content 为原始结果对象,按原有结构序列化;超限:buildWarning 已生成返回字符串
|
|
112
|
-
|
|
219
|
+
if (typeof guarded === "string")
|
|
220
|
+
return guarded;
|
|
221
|
+
return JSON.stringify(result.truncated ? { ...guarded, truncated: true, truncationNote } : guarded);
|
|
113
222
|
}
|
|
114
223
|
}
|
|
115
224
|
/** 统计文本行数(空文本记 0 行) */
|
|
@@ -3,13 +3,13 @@ import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
|
3
3
|
export class ExistTool extends SdkCallbackTool {
|
|
4
4
|
function = {
|
|
5
5
|
name: "exist",
|
|
6
|
-
description: "
|
|
6
|
+
description: "Check whether a file or directory exists",
|
|
7
7
|
parameters: {
|
|
8
8
|
type: "object",
|
|
9
9
|
properties: {
|
|
10
10
|
path: {
|
|
11
11
|
type: "string",
|
|
12
|
-
description: "
|
|
12
|
+
description: "File or directory path",
|
|
13
13
|
},
|
|
14
14
|
},
|
|
15
15
|
required: ["path"],
|