@ai-zen/agents-sdk 1.0.0-alpha.24 → 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 +209 -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.d.ts +31 -0
- package/dist/config/migrate.js +52 -4
- 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.d.ts +10 -1
- package/dist/shared/EntityRepository.js +18 -6
- 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 +5 -6
|
@@ -96,14 +96,16 @@ export class HandoffService {
|
|
|
96
96
|
// 静态纯工具(供上层复用 / 单测)
|
|
97
97
|
// ==================================================================
|
|
98
98
|
/**
|
|
99
|
-
* 交接文件名:`<YYYYMMDD-HHmmss
|
|
99
|
+
* 交接文件名:`<YYYYMMDD-HHmmss>.md`(本地时间,便于人眼归档)。
|
|
100
|
+
*
|
|
101
|
+
* 只有到秒的时间戳。同一秒内两次交接会撞名 —— 不做去重兜底:同一时刻并发交接
|
|
102
|
+
* 本来就是调用方该避免的事,加随机后缀只会让文件名更难认。
|
|
100
103
|
*/
|
|
101
|
-
static createHandoffFileName(date = new Date()
|
|
104
|
+
static createHandoffFileName(date = new Date()) {
|
|
102
105
|
const p = (n) => String(n).padStart(2, "0");
|
|
103
106
|
const stamp = `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}` +
|
|
104
107
|
`-${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}`;
|
|
105
|
-
|
|
106
|
-
return `${stamp}${suffix}.md`;
|
|
108
|
+
return `${stamp}.md`;
|
|
107
109
|
}
|
|
108
110
|
/**
|
|
109
111
|
* 拼装「本轮交接」指令:`[Skill 正文] + [本次交接参数]`。
|
|
@@ -189,12 +191,15 @@ export class HandoffService {
|
|
|
189
191
|
const { agent } = ctx;
|
|
190
192
|
const strategy = params.strategy ?? this.defaultStrategy;
|
|
191
193
|
const breakpointMessages = HandoffService.createPostMessages(ctx.handoffPath);
|
|
194
|
+
// 交接回合可能已经把 messages 换成新会话,definition 也可能是手写的(没有 messages):
|
|
195
|
+
// 这里按空模板处理,好让报错落在"模型该补的配置"上,而不是原生 TypeError
|
|
196
|
+
const templateMessages = agent.definition.messages ?? [];
|
|
192
197
|
if (strategy === "prune") {
|
|
193
198
|
// 浅拷贝模板消息,避免污染 definition.messages 引用的对象
|
|
194
|
-
agent.messages = [...
|
|
199
|
+
agent.messages = [...templateMessages, ...breakpointMessages];
|
|
195
200
|
}
|
|
196
201
|
else {
|
|
197
|
-
const preserveCount = Math.min(
|
|
202
|
+
const preserveCount = Math.min(templateMessages.length, agent.messages.length);
|
|
198
203
|
agent.messages = [
|
|
199
204
|
...agent.messages.map((m, i) => ({
|
|
200
205
|
...m,
|
|
@@ -273,9 +278,9 @@ export class HandoffService {
|
|
|
273
278
|
}
|
|
274
279
|
}
|
|
275
280
|
async runHandoff(params, migrating) {
|
|
276
|
-
const { agent, promptTokens, handoffTokens,
|
|
281
|
+
const { agent, promptTokens, handoffTokens, signal } = params;
|
|
277
282
|
const requestedMode = params.mode ?? this.defaultMode;
|
|
278
|
-
const handoffPath = join(this.handoffDirPath, HandoffService.createHandoffFileName(new Date()
|
|
283
|
+
const handoffPath = join(this.handoffDirPath, HandoffService.createHandoffFileName(new Date()));
|
|
279
284
|
const model = this.model ?? agent.model;
|
|
280
285
|
const messageCountBefore = agent.messages.length;
|
|
281
286
|
// 迁移前上下文(不含文档,语义固定)
|
|
@@ -357,13 +362,11 @@ export class HandoffService {
|
|
|
357
362
|
// 取消时只删本次新建的文件,不碰本已存在的同名文件
|
|
358
363
|
const existedBefore = await this.fileExists(handoffPath);
|
|
359
364
|
/*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
*
|
|
363
|
-
* -
|
|
364
|
-
* 交接回合结束后 lastUsage 由本轮真实响应用量回填,无需恢复旧值。
|
|
365
|
+
* 交接回合的护栏让行由 `ContextGuardPlugin.isSuspended` 负责(接线为
|
|
366
|
+
* `() => handoffService.busy`),这里不再去改写用量数据:
|
|
367
|
+
* - `lastUsage` 是从 `messages` 派生的只读值,本就不可写;
|
|
368
|
+
* - 「谁做限制谁放宽」—— 限制在护栏自己身上,放宽也必须写在护栏的选项里。
|
|
365
369
|
*/
|
|
366
|
-
agent.lastUsage = undefined;
|
|
367
370
|
guard.arm(handoffPath, cwd);
|
|
368
371
|
try {
|
|
369
372
|
await agent.send(HandoffService.createHandoffInstruction({
|
|
@@ -22,9 +22,7 @@ export async function createAgent(scope, agentId, options = {}) {
|
|
|
22
22
|
const { client, model, modelConfig } = createModel(scope, modelId, definition.modelParams);
|
|
23
23
|
const tools = scope.buildTools(definition, {
|
|
24
24
|
exclude: {
|
|
25
|
-
subagents: definition.function?.name
|
|
26
|
-
? [definition.function.name]
|
|
27
|
-
: undefined,
|
|
25
|
+
subagents: definition.function?.name ? [definition.function.name] : undefined,
|
|
28
26
|
},
|
|
29
27
|
});
|
|
30
28
|
const agent = new SdkAgent({
|
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
|
// ==================================================================
|
|
@@ -1,11 +1,13 @@
|
|
|
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
7
|
description: [
|
|
7
8
|
"Edit text in a file in batches. Prefer this tool when making edits to a file.",
|
|
8
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.",
|
|
9
11
|
].join("\n"),
|
|
10
12
|
parameters: {
|
|
11
13
|
type: "object",
|
|
@@ -56,21 +58,26 @@ export class BatchEditTool extends SdkCallbackTool {
|
|
|
56
58
|
// 成功项不回显原文与新文,仅计入成功数,避免大段文本回显撑大输出
|
|
57
59
|
const failed = [];
|
|
58
60
|
for (const replacement of input.replacements) {
|
|
59
|
-
|
|
61
|
+
// 空串会匹配每一个位置,不是有意义的编辑,单独拒绝
|
|
62
|
+
if (replacement.oldText === "") {
|
|
60
63
|
failed.push({
|
|
61
64
|
oldText: replacement.oldText,
|
|
62
65
|
newText: replacement.newText,
|
|
63
|
-
reason: "
|
|
66
|
+
reason: "oldText must not be empty",
|
|
64
67
|
});
|
|
65
68
|
continue;
|
|
66
69
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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;
|
|
72
78
|
}
|
|
73
|
-
|
|
79
|
+
newContent = nextContent;
|
|
80
|
+
replacedCount += count;
|
|
74
81
|
}
|
|
75
82
|
await fsp.writeFile(filePath, newContent);
|
|
76
83
|
if (failed.length === 0) {
|
|
@@ -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;
|