@ai-zen/agents-sdk 1.0.0-alpha.25 → 1.0.0-alpha.26
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 +134 -0
- package/README.md +5 -5
- package/README.zh.md +5 -5
- package/dist/agent-plugins/AutoMigratePlugin.js +1 -3
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +1 -3
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +15 -1
- package/dist/agent-plugins/ContextGuardPlugin.js +11 -1
- package/dist/config/ConfigManager.js +1 -1
- package/dist/config/constants.js +5 -8
- package/dist/config/migrate.js +1 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/runtime/HandoffService.d.ts +5 -4
- package/dist/runtime/HandoffService.js +17 -14
- package/dist/runtime/createAgent.js +1 -3
- package/dist/scope/Scope.d.ts +3 -1
- package/dist/scope/Scope.js +3 -1
- package/dist/scope/plugins/builtin/BatchEditTool.js +15 -8
- package/dist/scope/plugins/builtin/DownloadFileTool.d.ts +1 -0
- package/dist/scope/plugins/builtin/DownloadFileTool.js +54 -30
- package/dist/scope/plugins/builtin/EditTool.js +13 -18
- package/dist/scope/plugins/builtin/ExecTool.js +127 -18
- package/dist/scope/plugins/builtin/FindTextTool.js +6 -1
- package/dist/scope/plugins/builtin/GenerateImageTool.js +80 -14
- package/dist/scope/plugins/builtin/GlobTool.js +6 -1
- package/dist/scope/plugins/builtin/SpawnTool.js +28 -45
- package/dist/scope/plugins/builtin/ViewImageTool.js +6 -2
- 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 +88 -9
- package/dist/scope/plugins/mcp/McpScopePlugin.js +7 -6
- package/dist/scope/plugins/mcp/mcpTools.d.ts +2 -2
- package/dist/scope/plugins/mcp/mcpTools.js +42 -10
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +2 -3
- package/dist/scope/plugins/skills/discover.js +25 -5
- package/dist/scope/plugins/skills/skillTools.js +13 -1
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +1 -3
- package/dist/scope/plugins/usertools/discover.js +8 -2
- package/dist/shared/EntityRepository.js +1 -3
- package/dist/shared/content-blocks.d.ts +5 -12
- package/dist/shared/content-blocks.js +1 -1
- package/dist/types/index.d.ts +48 -0
- package/package.json +4 -5
|
@@ -1,5 +1,8 @@
|
|
|
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 = {
|
|
@@ -16,8 +19,12 @@ export class DownloadFileTool extends SdkCallbackTool {
|
|
|
16
19
|
type: "string",
|
|
17
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.",
|
|
18
21
|
},
|
|
22
|
+
timeout: {
|
|
23
|
+
type: "number",
|
|
24
|
+
description: "Timeout in milliseconds (required). The download is aborted on timeout. Large files need a larger value.",
|
|
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 must not be empty");
|
|
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,
|
|
98
|
+
...(aborted ? { aborted: true } : {}),
|
|
79
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,17 +1,6 @@
|
|
|
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",
|
|
@@ -56,6 +45,14 @@ export class EditTool extends SdkCallbackTool {
|
|
|
56
45
|
const newText = input.newText;
|
|
57
46
|
const isReplaceAll = input.isReplaceAll ?? false;
|
|
58
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
|
+
}
|
|
59
56
|
const count = countOccurrences(content, oldText);
|
|
60
57
|
if (count === 0) {
|
|
61
58
|
return JSON.stringify({
|
|
@@ -63,21 +60,19 @@ export class EditTool extends SdkCallbackTool {
|
|
|
63
60
|
matchCount: 0,
|
|
64
61
|
});
|
|
65
62
|
}
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
: content.replace(oldText, newText);
|
|
69
|
-
await fsp.writeFile(filePath, newContent);
|
|
63
|
+
const { content: nextContent, replacedCount } = replaceText(content, oldText, newText, isReplaceAll);
|
|
64
|
+
await fsp.writeFile(filePath, nextContent);
|
|
70
65
|
if (!isReplaceAll && count > 1) {
|
|
71
66
|
return JSON.stringify({
|
|
72
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`,
|
|
73
68
|
matchCount: count,
|
|
74
|
-
replacedCount
|
|
69
|
+
replacedCount,
|
|
75
70
|
});
|
|
76
71
|
}
|
|
77
72
|
return JSON.stringify({
|
|
78
73
|
result: "success",
|
|
79
74
|
matchCount: count,
|
|
80
|
-
replacedCount
|
|
75
|
+
replacedCount,
|
|
81
76
|
});
|
|
82
77
|
}
|
|
83
78
|
catch (error) {
|
|
@@ -1,6 +1,18 @@
|
|
|
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",
|
|
@@ -46,30 +58,109 @@ 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
166
|
stderr: "Process aborted",
|
|
@@ -78,10 +169,25 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
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({
|
|
@@ -98,7 +204,8 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
98
204
|
return JSON.stringify({
|
|
99
205
|
outputTooLarge: true,
|
|
100
206
|
warning: `Output too large: stdout + stderr total ${result.stdout.length + result.stderr.length} characters, ` +
|
|
101
|
-
`exceeds the limit of ${limit} 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 行) */
|
|
@@ -2,6 +2,7 @@ import * as fsp from "fs/promises";
|
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
4
4
|
import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headPreview } from "./outputGuard.js";
|
|
5
|
+
import { checkBaseDirectory } from "./searchBase.js";
|
|
5
6
|
/** 默认总匹配数上限 */
|
|
6
7
|
const DEFAULT_MAX_MATCHES = 200;
|
|
7
8
|
/** 默认文件大小上限(字节,与 ReadTool 的 300KB 口径一致) */
|
|
@@ -33,7 +34,7 @@ export class FindTextTool extends SdkCallbackTool {
|
|
|
33
34
|
},
|
|
34
35
|
exclude: {
|
|
35
36
|
type: "array",
|
|
36
|
-
description:
|
|
37
|
+
description: 'Array of glob patterns to exclude. When omitted, defaults to ["**/node_modules/**"]; pass an explicit list to override.',
|
|
37
38
|
items: {
|
|
38
39
|
type: "string",
|
|
39
40
|
},
|
|
@@ -61,6 +62,10 @@ export class FindTextTool extends SdkCallbackTool {
|
|
|
61
62
|
const signal = ctx?.signal;
|
|
62
63
|
try {
|
|
63
64
|
const cwd = input.path ? this.resolve(input.path) : this.env.cwd;
|
|
65
|
+
// 基目录不存在/不是目录时明确报错:静默返回 [] 会被模型当成「没找到匹配」
|
|
66
|
+
const baseError = await checkBaseDirectory(cwd);
|
|
67
|
+
if (baseError)
|
|
68
|
+
return baseError;
|
|
64
69
|
const result = [];
|
|
65
70
|
const text = input.text;
|
|
66
71
|
const regexStr = input.regex;
|
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import OpenAI from "openai";
|
|
2
|
+
import * as fsp from "fs/promises";
|
|
3
|
+
import * as os from "os";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
import { randomBytes } from "crypto";
|
|
2
6
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
7
|
+
/** 默认图片生成实现:走 OpenAI SDK 的 `images.generate`(任何 OpenAI 兼容端点均可) */
|
|
8
|
+
const defaultGenerateImage = async ({ endpoint, model, prompt, size, quality, signal, }) => {
|
|
9
|
+
const client = new OpenAI({ apiKey: endpoint.apiKey, baseURL: endpoint.baseUrl });
|
|
10
|
+
// 厂商特有字段(size / quality)用 any 透传
|
|
11
|
+
const result = await client.images.generate({ model, prompt, size, quality }, { signal });
|
|
12
|
+
return {
|
|
13
|
+
created: result.created,
|
|
14
|
+
// 有的端点只返回 b64_json,两类字段都原样带出去,由调用方决定怎么落地
|
|
15
|
+
data: (result.data ?? []),
|
|
16
|
+
};
|
|
17
|
+
};
|
|
3
18
|
/**
|
|
4
19
|
* 根据文字描述生成图片。**统一返回字符串**(JSON,含图片 URL 列表):
|
|
5
20
|
* 生成结果如何处理(查看/下载/转发)由模型与上层自由决定——
|
|
@@ -29,7 +44,7 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
29
44
|
},
|
|
30
45
|
size: {
|
|
31
46
|
type: "string",
|
|
32
|
-
description:
|
|
47
|
+
description: "Image size. Defaults to the model default size. cogview series: 1024x1024, 768x1344, 864x1152, 1344x768, 1152x864, 1440x720, 720x1440. glm-image: 1280x1280, 1568x1056, 1056x1568, 1472x1088, 1088x1472, 1728x960, 960x1728.",
|
|
33
48
|
},
|
|
34
49
|
quality: {
|
|
35
50
|
type: "string",
|
|
@@ -83,31 +98,52 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
83
98
|
error: `API Key for endpoint "${endpoint.name}" is not set`,
|
|
84
99
|
});
|
|
85
100
|
}
|
|
86
|
-
const client = new OpenAI({
|
|
87
|
-
apiKey: endpoint.apiKey,
|
|
88
|
-
baseURL: endpoint.baseUrl,
|
|
89
|
-
});
|
|
90
101
|
const modelName = input.model || imageModel.modelName;
|
|
91
|
-
//
|
|
92
|
-
const
|
|
102
|
+
// 出网动作走注入的 deps(缺省时用 OpenAI SDK),测试无需 mock openai 模块
|
|
103
|
+
const generateImage = this.env.deps?.generateImage ?? defaultGenerateImage;
|
|
104
|
+
const result = await generateImage({
|
|
105
|
+
endpoint,
|
|
93
106
|
model: modelName,
|
|
94
107
|
prompt: prompt.trim(),
|
|
95
108
|
size: input.size || imageModel.defaultSize || undefined,
|
|
96
109
|
quality: input.quality || imageModel.defaultQuality || undefined,
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
110
|
+
signal,
|
|
111
|
+
});
|
|
112
|
+
// 逐个收集:有 url 的直接给链接;只有 b64_json 的端点则落盘后给本地路径。
|
|
113
|
+
// 只看 url 会把「只返回 b64_json 的模型」变成 success: true + images: [](假成功)。
|
|
114
|
+
const images = [];
|
|
115
|
+
for (const [index, item] of (result.data ?? []).entries()) {
|
|
116
|
+
if (item.url) {
|
|
117
|
+
images.push({ index, url: item.url });
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (item.b64_json) {
|
|
121
|
+
images.push({ index, filePath: await saveBase64Image(item.b64_json) });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (images.length === 0) {
|
|
125
|
+
return JSON.stringify({
|
|
126
|
+
success: false,
|
|
127
|
+
model: imageModel.name,
|
|
128
|
+
modelId: imageModel.id,
|
|
129
|
+
created: result.created,
|
|
130
|
+
images: [],
|
|
131
|
+
error: "The endpoint returned no image: neither `url` nor `b64_json` was present in the response",
|
|
132
|
+
});
|
|
133
|
+
}
|
|
101
134
|
// 统一返回字符串(JSON):生成结果如何处理(查看/下载/转发)由模型与上层自由决定,
|
|
102
|
-
// 不替模型做「看或不看」的假设。需要让模型看图 → 模型可主动调用 view_image
|
|
135
|
+
// 不替模型做「看或不看」的假设。需要让模型看图 → 模型可主动调用 view_image;
|
|
103
136
|
// 需要保存 → download_file 下载。
|
|
137
|
+
const hasUrl = images.some((img) => img.url);
|
|
104
138
|
return JSON.stringify({
|
|
105
139
|
success: true,
|
|
106
140
|
model: imageModel.name,
|
|
107
141
|
modelId: imageModel.id,
|
|
108
142
|
created: result.created,
|
|
109
|
-
images
|
|
110
|
-
note:
|
|
143
|
+
images,
|
|
144
|
+
note: hasUrl
|
|
145
|
+
? "Image links are temporary and expire after 30 days. To inspect the image content, use the view_image tool (pass the image URL); to save it, use download_file."
|
|
146
|
+
: "The endpoint returned base64 images; they were written to local files, so use view_image with the filePath to inspect them.",
|
|
111
147
|
}, null, 2);
|
|
112
148
|
}
|
|
113
149
|
catch (error) {
|
|
@@ -126,3 +162,33 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
126
162
|
}
|
|
127
163
|
}
|
|
128
164
|
}
|
|
165
|
+
/** 依据 base64 头部字节判断图片扩展名(判断不了就当 png) */
|
|
166
|
+
function imageExtension(buffer) {
|
|
167
|
+
if (buffer.length >= 8 && buffer.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) {
|
|
168
|
+
return "png";
|
|
169
|
+
}
|
|
170
|
+
if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
|
|
171
|
+
return "jpg";
|
|
172
|
+
}
|
|
173
|
+
if (buffer.length >= 6 && buffer.subarray(0, 3).toString("latin1") === "GIF")
|
|
174
|
+
return "gif";
|
|
175
|
+
if (buffer.length >= 12 &&
|
|
176
|
+
buffer.subarray(0, 4).toString("latin1") === "RIFF" &&
|
|
177
|
+
buffer.subarray(8, 12).toString("latin1") === "WEBP") {
|
|
178
|
+
return "webp";
|
|
179
|
+
}
|
|
180
|
+
return "png";
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* 把 `b64_json` 写成本地文件,返回绝对路径。
|
|
184
|
+
*
|
|
185
|
+
* 落盘到系统临时目录下的独立子目录(与工具输出落盘同一习惯),不污染工作目录。
|
|
186
|
+
*/
|
|
187
|
+
async function saveBase64Image(b64) {
|
|
188
|
+
const buffer = Buffer.from(b64, "base64");
|
|
189
|
+
const dir = path.join(os.tmpdir(), "ai-zen", "generated-images");
|
|
190
|
+
await fsp.mkdir(dir, { recursive: true });
|
|
191
|
+
const filePath = path.join(dir, `image-${Date.now()}-${randomBytes(4).toString("hex")}.${imageExtension(buffer)}`);
|
|
192
|
+
await fsp.writeFile(filePath, buffer);
|
|
193
|
+
return filePath;
|
|
194
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as fsp from "fs/promises";
|
|
2
2
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
3
3
|
import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headPreview } from "./outputGuard.js";
|
|
4
|
+
import { checkBaseDirectory } from "./searchBase.js";
|
|
4
5
|
export class GlobTool extends SdkCallbackTool {
|
|
5
6
|
function = {
|
|
6
7
|
name: "glob",
|
|
@@ -18,7 +19,7 @@ export class GlobTool extends SdkCallbackTool {
|
|
|
18
19
|
},
|
|
19
20
|
exclude: {
|
|
20
21
|
type: "array",
|
|
21
|
-
description:
|
|
22
|
+
description: 'Glob patterns to exclude. When omitted, defaults to ["**/node_modules/**"]; pass an explicit list to override.',
|
|
22
23
|
items: {
|
|
23
24
|
type: "string",
|
|
24
25
|
},
|
|
@@ -35,6 +36,10 @@ export class GlobTool extends SdkCallbackTool {
|
|
|
35
36
|
const signal = ctx?.signal;
|
|
36
37
|
try {
|
|
37
38
|
const cwd = input.path ? this.resolve(input.path) : this.env.cwd;
|
|
39
|
+
// 基目录不存在/不是目录时明确报错:静默返回 [] 会被模型当成「文件不存在」
|
|
40
|
+
const baseError = await checkBaseDirectory(cwd);
|
|
41
|
+
if (baseError)
|
|
42
|
+
return baseError;
|
|
38
43
|
const result = [];
|
|
39
44
|
for await (const file of fsp.glob(input.pattern, {
|
|
40
45
|
exclude: input.exclude || ["**/node_modules/**"],
|
|
@@ -31,7 +31,13 @@ export class SpawnTool extends SdkCallbackTool {
|
|
|
31
31
|
const command = input.command;
|
|
32
32
|
const cwd = input.cwd ? this.resolve(input.cwd) : this.env.cwd;
|
|
33
33
|
const detached = input.detached ?? false;
|
|
34
|
-
|
|
34
|
+
/**
|
|
35
|
+
* 本工具只回答「进程是否已启动」,**不跟踪退出状态**。
|
|
36
|
+
*
|
|
37
|
+
* 它 spawn 后立刻返回,输出也走 `stdio: "ignore"` 丢弃;因此命令不存在、语法错误、
|
|
38
|
+
* 脚本起来就崩这类「早退失败」在这里一律看不见 —— 以前会把它们报成 `success: true`,
|
|
39
|
+
* 现在如实命名为 `started`,并在 note 里说清。需要成败/输出/退出码请用 exec。
|
|
40
|
+
*/
|
|
35
41
|
return new Promise((resolve) => {
|
|
36
42
|
const child = spawn(command, [], {
|
|
37
43
|
cwd,
|
|
@@ -41,57 +47,34 @@ export class SpawnTool extends SdkCallbackTool {
|
|
|
41
47
|
windowsHide: true,
|
|
42
48
|
});
|
|
43
49
|
let resolved = false;
|
|
44
|
-
|
|
50
|
+
let timer;
|
|
51
|
+
const done = (payload) => {
|
|
45
52
|
if (resolved)
|
|
46
53
|
return;
|
|
47
54
|
resolved = true;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
55
|
+
if (timer)
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
resolve(JSON.stringify(payload));
|
|
58
|
+
};
|
|
59
|
+
const startedPayload = () => ({
|
|
60
|
+
started: true,
|
|
61
|
+
pid: child.pid ?? null,
|
|
62
|
+
message: `Process started (PID: ${child.pid ?? "unknown"})`,
|
|
63
|
+
note: "This tool only reports that the process was started; it does not track the exit status. Use exec if you need the exit code or the output.",
|
|
53
64
|
});
|
|
54
|
-
child.on("
|
|
55
|
-
|
|
56
|
-
return;
|
|
57
|
-
resolved = true;
|
|
58
|
-
resolve(JSON.stringify({
|
|
59
|
-
success: true,
|
|
60
|
-
pid: child.pid ?? null,
|
|
61
|
-
message: `Process started (PID: ${child.pid ?? "unknown"})`,
|
|
62
|
-
}));
|
|
65
|
+
child.on("error", (err) => {
|
|
66
|
+
done({ started: false, pid: null, message: `Failed to start: ${err.message}` });
|
|
63
67
|
});
|
|
64
|
-
child.on("
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
resolved = true;
|
|
68
|
-
resolve(JSON.stringify({
|
|
69
|
-
success: code === 0,
|
|
70
|
-
pid: child.pid ?? null,
|
|
71
|
-
exitCode: code,
|
|
72
|
-
message: code === null
|
|
73
|
-
? `Process exited (PID: ${child.pid ?? "unknown"})`
|
|
74
|
-
: `Process exited (PID: ${child.pid ?? "unknown"}, exit code: ${code})`,
|
|
75
|
-
}));
|
|
68
|
+
child.on("spawn", () => {
|
|
69
|
+
child.unref();
|
|
70
|
+
done(startedPayload());
|
|
76
71
|
});
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
resolve(JSON.stringify({
|
|
82
|
-
success: true,
|
|
83
|
-
pid: child.pid ?? null,
|
|
84
|
-
message: `Process started (PID: ${child.pid ?? "unknown"})`,
|
|
85
|
-
}));
|
|
72
|
+
// 兜底:`spawn` 事件理论上必然触发,这里保证工具不会挂住
|
|
73
|
+
timer = setTimeout(() => {
|
|
74
|
+
child.unref();
|
|
75
|
+
done(startedPayload());
|
|
86
76
|
}, 500);
|
|
87
|
-
|
|
88
|
-
clearTimeout(timeout);
|
|
89
|
-
child.removeAllListeners();
|
|
90
|
-
};
|
|
91
|
-
child.on("spawn", cleanup);
|
|
92
|
-
child.on("error", cleanup);
|
|
93
|
-
child.on("exit", cleanup);
|
|
94
|
-
child.unref();
|
|
77
|
+
timer.unref?.();
|
|
95
78
|
});
|
|
96
79
|
}
|
|
97
80
|
}
|