@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,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"],
|
|
@@ -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 口径一致) */
|
|
@@ -11,7 +12,7 @@ const DEFAULT_MAX_LINE_LENGTH = 200;
|
|
|
11
12
|
export class FindTextTool extends SdkCallbackTool {
|
|
12
13
|
function = {
|
|
13
14
|
name: "find_text",
|
|
14
|
-
description: "
|
|
15
|
+
description: "Find where text occurs, supporting plain text or regex matching; returns file names with line numbers and line content. To avoid blowing up the context, the total match count, per-file size and line content length are limited by default, and results beyond the limits are truncated and marked truncated.",
|
|
15
16
|
parameters: {
|
|
16
17
|
type: "object",
|
|
17
18
|
properties: {
|
|
@@ -25,30 +26,30 @@ export class FindTextTool extends SdkCallbackTool {
|
|
|
25
26
|
},
|
|
26
27
|
text: {
|
|
27
28
|
type: "string",
|
|
28
|
-
description: "
|
|
29
|
+
description: "Text to search for (mutually exclusive with regex)",
|
|
29
30
|
},
|
|
30
31
|
regex: {
|
|
31
32
|
type: "string",
|
|
32
|
-
description: "
|
|
33
|
+
description: "Regular expression (mutually exclusive with text, e.g. \\bconst\\s+\\w+)",
|
|
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
|
},
|
|
40
41
|
},
|
|
41
42
|
maxMatches: {
|
|
42
43
|
type: "number",
|
|
43
|
-
description: "
|
|
44
|
+
description: "Maximum total matches (default 200)",
|
|
44
45
|
},
|
|
45
46
|
maxFileSize: {
|
|
46
47
|
type: "number",
|
|
47
|
-
description: "
|
|
48
|
+
description: "Maximum file size in bytes; larger files are skipped (default 307200, i.e. 300KB)",
|
|
48
49
|
},
|
|
49
50
|
maxLineLength: {
|
|
50
51
|
type: "number",
|
|
51
|
-
description: "
|
|
52
|
+
description: "Truncation length for line content and matched substrings (default 200)",
|
|
52
53
|
},
|
|
53
54
|
},
|
|
54
55
|
required: ["path", "pattern"],
|
|
@@ -61,11 +62,15 @@ 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;
|
|
67
72
|
if (!text && !regexStr) {
|
|
68
|
-
return "
|
|
73
|
+
return "Provide either the text or the regex parameter";
|
|
69
74
|
}
|
|
70
75
|
const regex = regexStr ? new RegExp(regexStr) : null;
|
|
71
76
|
const maxMatches = input.maxMatches ?? DEFAULT_MAX_MATCHES;
|
|
@@ -153,8 +158,8 @@ export class FindTextTool extends SdkCallbackTool {
|
|
|
153
158
|
const preview = headPreview(json);
|
|
154
159
|
return JSON.stringify({
|
|
155
160
|
outputTooLarge: true,
|
|
156
|
-
warning:
|
|
157
|
-
|
|
161
|
+
warning: `Output too large: the results total ${json.length} characters, exceeding the limit of ${limit} characters. ` +
|
|
162
|
+
`The full result has been written to disk (result.json) and can be read in chunks with read.`,
|
|
158
163
|
files: ctx.files,
|
|
159
164
|
chars: json.length,
|
|
160
165
|
...preview,
|
|
@@ -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
|
* 生成结果如何处理(查看/下载/转发)由模型与上层自由决定——
|
|
@@ -15,25 +30,25 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
15
30
|
}
|
|
16
31
|
function = {
|
|
17
32
|
name: "generate_image",
|
|
18
|
-
description: "
|
|
33
|
+
description: "Generate an image from a text description and return a list of image URLs (JSON). To inspect the image content, use the view_image tool (pass the image URL); to save it locally, use download_file.",
|
|
19
34
|
parameters: {
|
|
20
35
|
type: "object",
|
|
21
36
|
properties: {
|
|
22
37
|
prompt: {
|
|
23
38
|
type: "string",
|
|
24
|
-
description: "
|
|
39
|
+
description: "Text description of the desired image; describe the subject, style, composition and other details",
|
|
25
40
|
},
|
|
26
41
|
model: {
|
|
27
42
|
type: "string",
|
|
28
|
-
description: "
|
|
43
|
+
description: "Image model ID. Defaults to the configured default image model; if the given model does not exist, this tool returns the list of currently available models.",
|
|
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",
|
|
36
|
-
description: "
|
|
51
|
+
description: "Image quality. hd: fine (about 20 seconds), standard: fast (about 5-10 seconds)",
|
|
37
52
|
enum: ["hd", "standard"],
|
|
38
53
|
},
|
|
39
54
|
},
|
|
@@ -49,7 +64,7 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
49
64
|
try {
|
|
50
65
|
const prompt = input.prompt;
|
|
51
66
|
if (!prompt || !prompt.trim()) {
|
|
52
|
-
return JSON.stringify({ success: false, error: "prompt
|
|
67
|
+
return JSON.stringify({ success: false, error: "prompt must not be empty" });
|
|
53
68
|
}
|
|
54
69
|
const config = this.env.config;
|
|
55
70
|
const imageModels = config.imageModels;
|
|
@@ -57,7 +72,7 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
57
72
|
if (!imageModels || imageModels.length === 0) {
|
|
58
73
|
return JSON.stringify({
|
|
59
74
|
success: false,
|
|
60
|
-
error: "
|
|
75
|
+
error: "No image generation model configured. Add imageModels to the configuration.",
|
|
61
76
|
});
|
|
62
77
|
}
|
|
63
78
|
const modelId = input.model || defaultImageModel;
|
|
@@ -67,47 +82,68 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
67
82
|
if (!imageModel) {
|
|
68
83
|
return JSON.stringify({
|
|
69
84
|
success: false,
|
|
70
|
-
error:
|
|
85
|
+
error: `Image model "${modelId}" does not exist. Available image models: ${imageModels.map((m) => m.id).join(", ")}`,
|
|
71
86
|
});
|
|
72
87
|
}
|
|
73
88
|
const endpoint = config.endpoints.find((e) => e.id === imageModel.endpointId);
|
|
74
89
|
if (!endpoint) {
|
|
75
90
|
return JSON.stringify({
|
|
76
91
|
success: false,
|
|
77
|
-
error:
|
|
92
|
+
error: `Endpoint "${imageModel.endpointId}" for image model "${imageModel.name}" is not configured`,
|
|
78
93
|
});
|
|
79
94
|
}
|
|
80
95
|
if (!endpoint.apiKey) {
|
|
81
96
|
return JSON.stringify({
|
|
82
97
|
success: false,
|
|
83
|
-
error:
|
|
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) {
|
|
@@ -116,13 +152,43 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
116
152
|
return JSON.stringify({
|
|
117
153
|
success: false,
|
|
118
154
|
aborted: true,
|
|
119
|
-
error: "
|
|
155
|
+
error: "Image generation aborted",
|
|
120
156
|
});
|
|
121
157
|
}
|
|
122
158
|
return JSON.stringify({
|
|
123
159
|
success: false,
|
|
124
|
-
error: error instanceof Error ? error.message : "
|
|
160
|
+
error: error instanceof Error ? error.message : "Image generation failed",
|
|
125
161
|
});
|
|
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,10 +1,11 @@
|
|
|
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",
|
|
7
|
-
description: "
|
|
8
|
+
description: "Recursively scan for and find files using a glob pattern. This is the preferred tool for file system searches, far better than a plain 'ls' listing. Prefer this tool when you need to find files of a specific type, walk a directory tree, or exclude specific files.",
|
|
8
9
|
parameters: {
|
|
9
10
|
type: "object",
|
|
10
11
|
properties: {
|
|
@@ -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/**"],
|
|
@@ -68,9 +73,9 @@ export class GlobTool extends SdkCallbackTool {
|
|
|
68
73
|
const preview = headPreview(json);
|
|
69
74
|
return JSON.stringify({
|
|
70
75
|
outputTooLarge: true,
|
|
71
|
-
warning:
|
|
72
|
-
|
|
73
|
-
|
|
76
|
+
warning: `Output too large: the matches total ${json.length} characters, exceeding the limit of ${limit} characters. ` +
|
|
77
|
+
`The full result has been written to disk (result.json) and can be read in chunks with read; ` +
|
|
78
|
+
`alternatively, narrow the scope with a more precise pattern or exclude and search again.`,
|
|
74
79
|
files: ctx.files,
|
|
75
80
|
chars: json.length,
|
|
76
81
|
...preview,
|
|
@@ -12,17 +12,17 @@ import { DEFAULT_MAX_TOOL_OUTPUT } from "./outputGuard.js";
|
|
|
12
12
|
export class InspectFileTool extends SdkCallbackTool {
|
|
13
13
|
function = {
|
|
14
14
|
name: "inspect_file",
|
|
15
|
-
description: "
|
|
15
|
+
description: "Inspect a file's structural overview: total lines, total characters, the longest line's column count and its line index, average column count, and line ending type (LF/CRLF). Optionally returns a per-line column count map. Useful for sizing up a file before reading it, so you can decide which range to read. Streaming scan only, not subject to the 300KB read threshold of read.",
|
|
16
16
|
parameters: {
|
|
17
17
|
type: "object",
|
|
18
18
|
properties: {
|
|
19
19
|
path: {
|
|
20
20
|
type: "string",
|
|
21
|
-
description: "
|
|
21
|
+
description: "File path",
|
|
22
22
|
},
|
|
23
23
|
withColCountMap: {
|
|
24
24
|
type: "boolean",
|
|
25
|
-
description: "
|
|
25
|
+
description: "Whether to return a per-line column count map (object: line index → column count, line index is 0-based). Default false. When there are many lines the map may be too large; in that case only the overview fields are returned.",
|
|
26
26
|
default: false,
|
|
27
27
|
},
|
|
28
28
|
},
|
|
@@ -38,7 +38,7 @@ export class InspectFileTool extends SdkCallbackTool {
|
|
|
38
38
|
const filePath = this.resolve(input.path);
|
|
39
39
|
const stats = await fsp.stat(filePath);
|
|
40
40
|
if (!stats.isFile()) {
|
|
41
|
-
return `"${filePath}"
|
|
41
|
+
return `"${filePath}" is not a file`;
|
|
42
42
|
}
|
|
43
43
|
const withColCountMap = input.withColCountMap ?? false;
|
|
44
44
|
const result = await scan(filePath, withColCountMap);
|
|
@@ -61,9 +61,9 @@ export class InspectFileTool extends SdkCallbackTool {
|
|
|
61
61
|
return JSON.stringify({
|
|
62
62
|
...summary,
|
|
63
63
|
colCountMapOmitted: true,
|
|
64
|
-
warning:
|
|
65
|
-
|
|
66
|
-
|
|
64
|
+
warning: `Line length details too large: overview plus colCountMap total ${payload.length} characters, ` +
|
|
65
|
+
`exceeding the limit of ${limit} characters; not written to disk. The file is beyond the supported size, ` +
|
|
66
|
+
`so use find_text to locate the target and then read it in chunks by range.`,
|
|
67
67
|
});
|
|
68
68
|
}
|
|
69
69
|
return payload;
|
|
@@ -4,13 +4,13 @@ import { DEFAULT_MAX_TOOL_OUTPUT, guardOutput, headPreview } from "./outputGuard
|
|
|
4
4
|
export class LsTool extends SdkCallbackTool {
|
|
5
5
|
function = {
|
|
6
6
|
name: "ls",
|
|
7
|
-
description: "
|
|
7
|
+
description: "List a directory",
|
|
8
8
|
parameters: {
|
|
9
9
|
type: "object",
|
|
10
10
|
properties: {
|
|
11
11
|
path: {
|
|
12
12
|
type: "string",
|
|
13
|
-
description: "
|
|
13
|
+
description: "Directory path",
|
|
14
14
|
},
|
|
15
15
|
},
|
|
16
16
|
required: ["path"],
|
|
@@ -35,9 +35,9 @@ export class LsTool extends SdkCallbackTool {
|
|
|
35
35
|
const preview = headPreview(json);
|
|
36
36
|
return JSON.stringify({
|
|
37
37
|
outputTooLarge: true,
|
|
38
|
-
warning:
|
|
39
|
-
|
|
40
|
-
|
|
38
|
+
warning: `Output too large: ${entries.length} directory entries, ${json.length} characters in total, exceeding the limit of ${limit} characters. ` +
|
|
39
|
+
`The full list has been written to disk (result.json) and can be read in chunks with read; ` +
|
|
40
|
+
`alternatively, use glob to filter by pattern.`,
|
|
41
41
|
files: ctx.files,
|
|
42
42
|
chars: json.length,
|
|
43
43
|
...preview,
|