@ai-zen/agents-sdk 1.2.0-alpha.2 → 2.0.0-alpha.1
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 +77 -0
- package/README.md +397 -113
- package/README.zh.md +314 -112
- package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
- package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +56 -6
- package/dist/agent-plugins/AutoMigratePlugin.js +64 -15
- package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +12 -9
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +6 -7
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +32 -24
- package/dist/agent-plugins/ContextGuardPlugin.js +37 -22
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +38 -46
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +37 -50
- package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +15 -1
- package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -1
- package/dist/config/ConfigManager.d.ts +13 -5
- package/dist/config/ConfigManager.js +58 -39
- package/dist/config/constants.d.ts +1 -1
- package/dist/config/constants.js +2 -2
- package/dist/config/factory-skills.js +2 -2
- package/dist/config/normalize.d.ts +93 -0
- package/dist/config/normalize.js +158 -0
- package/dist/crud/AgentRepository.d.ts +3 -1
- package/dist/crud/AgentRepository.js +4 -2
- package/dist/index.d.ts +22 -9
- package/dist/index.js +16 -6
- package/dist/runtime/AgentRuntime.d.ts +293 -0
- package/dist/runtime/AgentRuntime.js +457 -0
- package/dist/runtime/HandoffGuardPlugin.d.ts +85 -16
- package/dist/runtime/HandoffGuardPlugin.js +140 -19
- package/dist/runtime/HandoffService.d.ts +255 -91
- package/dist/runtime/HandoffService.js +392 -177
- package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
- package/dist/runtime/RuntimePeerSessions.js +50 -0
- package/dist/runtime/Scopes.d.ts +123 -0
- package/dist/runtime/Scopes.js +169 -0
- package/dist/runtime/SdkAgent.d.ts +21 -11
- package/dist/runtime/SdkAgent.js +24 -8
- package/dist/runtime/completeOnce.d.ts +3 -3
- package/dist/runtime/completeOnce.js +3 -3
- package/dist/runtime/createAgent.d.ts +29 -7
- package/dist/runtime/createAgent.js +57 -12
- package/dist/runtime/createModel.d.ts +4 -4
- package/dist/runtime/createModel.js +6 -6
- package/dist/runtime/lastPromptTokens.d.ts +18 -0
- package/dist/runtime/lastPromptTokens.js +26 -0
- package/dist/runtime/resolveModel.d.ts +9 -9
- package/dist/runtime/resolveModel.js +8 -8
- package/dist/scope/Scope.d.ts +42 -14
- package/dist/scope/Scope.js +55 -16
- package/dist/scope/ScopePlugin.d.ts +2 -8
- package/dist/scope/disclosure.d.ts +1 -1
- package/dist/scope/disclosure.js +1 -1
- package/dist/scope/plugins/allInOne.d.ts +13 -1
- package/dist/scope/plugins/allInOne.js +9 -5
- package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
- package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
- package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
- package/dist/scope/plugins/builtin/ExecTool.js +10 -199
- package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
- package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
- package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
- package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
- package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
- package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
- package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
- package/dist/scope/plugins/builtin/SleepTool.js +2 -3
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
- package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
- package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
- package/dist/scope/plugins/builtin/WriteTool.js +8 -1
- package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
- package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
- package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
- package/dist/scope/plugins/builtin/commandOutput.js +55 -0
- package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
- package/dist/scope/plugins/builtin/commandRun.js +169 -0
- package/dist/scope/plugins/builtin/discover.d.ts +1 -3
- package/dist/scope/plugins/builtin/discover.js +1 -3
- package/dist/scope/plugins/builtin/index.d.ts +5 -7
- package/dist/scope/plugins/builtin/index.js +7 -7
- package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
- package/dist/scope/plugins/builtin/outputGuard.js +1 -5
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +61 -9
- package/dist/scope/plugins/mcp/McpConnectionManager.js +174 -72
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +37 -4
- package/dist/scope/plugins/mcp/McpScopePlugin.js +100 -9
- package/dist/scope/plugins/mcp/discover.d.ts +9 -2
- package/dist/scope/plugins/mcp/discover.js +12 -14
- package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
- package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
- package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
- package/dist/scope/plugins/mcp/mcpTools.js +220 -39
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +25 -0
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +32 -0
- package/dist/scope/plugins/peers/peerSessionTools.d.ts +173 -0
- package/dist/scope/plugins/peers/peerSessionTools.js +292 -0
- package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
- package/dist/scope/plugins/skills/discover.d.ts +15 -8
- package/dist/scope/plugins/skills/discover.js +15 -26
- package/dist/scope/plugins/skills/skillTools.d.ts +9 -8
- package/dist/scope/plugins/skills/skillTools.js +21 -13
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
- package/dist/scope/plugins/subagents/discover.d.ts +7 -1
- package/dist/scope/plugins/subagents/discover.js +7 -3
- package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
- package/dist/scope/plugins/subagents/subAgentTools.js +14 -1
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
- package/dist/scope/plugins/usertools/discover.d.ts +7 -8
- package/dist/scope/plugins/usertools/discover.js +17 -27
- package/dist/shared/EntityRepository.d.ts +22 -5
- package/dist/shared/EntityRepository.js +45 -29
- package/dist/shared/content-blocks.d.ts +9 -3
- package/dist/shared/content-blocks.js +12 -19
- package/dist/shared/errors.d.ts +8 -3
- package/dist/shared/errors.js +9 -4
- package/dist/shared/logger.d.ts +21 -10
- package/dist/shared/logger.js +9 -15
- package/dist/types/index.d.ts +38 -13
- package/package.json +2 -2
- package/dist/config/migrate.d.ts +0 -115
- package/dist/config/migrate.js +0 -200
- package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
- package/dist/scope/plugins/builtin/test-helpers.js +0 -4
|
@@ -1,15 +1,27 @@
|
|
|
1
1
|
import type { ScopePlugin } from "../ScopePlugin.js";
|
|
2
|
+
import type { LogSink } from "../../shared/logger.js";
|
|
3
|
+
import type { McpTaskNoticePort } from "./mcp/mcpTaskNotice.js";
|
|
2
4
|
/** allInOne 的装配选项:各类能力来源的路径(绝对或相对 scope.cwd) */
|
|
3
5
|
export interface AllInOneOptions {
|
|
4
6
|
skillsPaths?: string[];
|
|
5
7
|
toolsPaths?: string[];
|
|
6
8
|
subAgentsPaths?: string[];
|
|
7
9
|
mcpPaths?: string[];
|
|
10
|
+
/**
|
|
11
|
+
* 日志口(可选):四个会读盘的插件(用户工具 / Skill / MCP / subagent)把它们发现的
|
|
12
|
+
* 「这个文件读不出来」报到这里;不传则一律不记(库缺省沉默)。
|
|
13
|
+
*/
|
|
14
|
+
logger?: LogSink;
|
|
15
|
+
/**
|
|
16
|
+
* MCP 任务通知的投递口(可选):由宿主实现。不给时任务状态只当没收到,
|
|
17
|
+
* `call_mcp_tool` 的任务参数照旧可用。
|
|
18
|
+
*/
|
|
19
|
+
mcpTaskNotice?: McpTaskNoticePort;
|
|
8
20
|
}
|
|
9
21
|
/**
|
|
10
22
|
* 标准能力插件工厂 —— 恒返回 5 个标准插件("全家桶")。
|
|
11
23
|
*
|
|
12
|
-
*
|
|
24
|
+
* 顺序即优先级(去重时后注册覆盖先注册,见 `Scope.instantiate`):
|
|
13
25
|
* builtin → user-tools → skills → mcp → subagents
|
|
14
26
|
* 因此用户工具可覆盖同名内置工具。
|
|
15
27
|
*
|
|
@@ -6,7 +6,7 @@ import { SubAgentsScopePlugin } from "./subagents/SubAgentsScopePlugin.js";
|
|
|
6
6
|
/**
|
|
7
7
|
* 标准能力插件工厂 —— 恒返回 5 个标准插件("全家桶")。
|
|
8
8
|
*
|
|
9
|
-
*
|
|
9
|
+
* 顺序即优先级(去重时后注册覆盖先注册,见 `Scope.instantiate`):
|
|
10
10
|
* builtin → user-tools → skills → mcp → subagents
|
|
11
11
|
* 因此用户工具可覆盖同名内置工具。
|
|
12
12
|
*
|
|
@@ -15,9 +15,13 @@ import { SubAgentsScopePlugin } from "./subagents/SubAgentsScopePlugin.js";
|
|
|
15
15
|
export function allInOne(options) {
|
|
16
16
|
return [
|
|
17
17
|
new BuiltinToolsScopePlugin(),
|
|
18
|
-
new UserToolsScopePlugin({ paths: options?.toolsPaths }),
|
|
19
|
-
new SkillsScopePlugin({ paths: options?.skillsPaths }),
|
|
20
|
-
new McpScopePlugin({
|
|
21
|
-
|
|
18
|
+
new UserToolsScopePlugin({ paths: options?.toolsPaths, logger: options?.logger }),
|
|
19
|
+
new SkillsScopePlugin({ paths: options?.skillsPaths, logger: options?.logger }),
|
|
20
|
+
new McpScopePlugin({
|
|
21
|
+
paths: options?.mcpPaths,
|
|
22
|
+
logger: options?.logger,
|
|
23
|
+
taskNotice: options?.mcpTaskNotice,
|
|
24
|
+
}),
|
|
25
|
+
new SubAgentsScopePlugin({ paths: options?.subAgentsPaths, logger: options?.logger }),
|
|
22
26
|
];
|
|
23
27
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
2
|
+
import type { ToolEnv } from "../../../types/index.js";
|
|
3
|
+
import type { AgentNS, ToolCallContext } from "@ai-zen/agents-core";
|
|
4
|
+
export declare class AsyncExecTool extends SdkCallbackTool {
|
|
5
|
+
function: AgentNS.FunctionDefine;
|
|
6
|
+
constructor(env: ToolEnv);
|
|
7
|
+
call(input: {
|
|
8
|
+
command: string;
|
|
9
|
+
cwd?: string;
|
|
10
|
+
timeout?: number;
|
|
11
|
+
}, ctx?: ToolCallContext): Promise<string>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
2
|
+
import { DEFAULT_MAX_TOOL_OUTPUT } from "./outputGuard.js";
|
|
3
|
+
import { runCommand } from "./commandRun.js";
|
|
4
|
+
import { commandOutputContent } from "./commandOutput.js";
|
|
5
|
+
import { ASYNC_EXEC_TOOL, deliverAsyncResult, nextTaskId, trackCommand } from "./asyncTasks.js";
|
|
6
|
+
export class AsyncExecTool extends SdkCallbackTool {
|
|
7
|
+
function = {
|
|
8
|
+
name: ASYNC_EXEC_TOOL,
|
|
9
|
+
description: "Run a shell command in the background and return immediately. Do not wait for it: this call is " +
|
|
10
|
+
"over the moment it returns. The system will notify you when the command ends (it exits, its " +
|
|
11
|
+
"timeout fires, or it fails to start) by pushing that command's output and exit status back into " +
|
|
12
|
+
"this session as a new message; that notification is the only way the result arrives. So do not " +
|
|
13
|
+
"wait and do not poll: nothing comes back while the command is still running, and there is no " +
|
|
14
|
+
"tool that checks a background task. Use exec when the result must be in hand before the next " +
|
|
15
|
+
"step; use async_exec for long commands (builds, test suites, scripts) whose result is worth " +
|
|
16
|
+
"coming back to.",
|
|
17
|
+
parameters: {
|
|
18
|
+
type: "object",
|
|
19
|
+
properties: {
|
|
20
|
+
command: {
|
|
21
|
+
type: "string",
|
|
22
|
+
description: "Command to execute (parsed and run by the shell, same as exec)",
|
|
23
|
+
},
|
|
24
|
+
cwd: {
|
|
25
|
+
type: "string",
|
|
26
|
+
description: "Working directory (optional, defaults to the current working directory)",
|
|
27
|
+
},
|
|
28
|
+
timeout: {
|
|
29
|
+
type: "number",
|
|
30
|
+
description: "Timeout in milliseconds (optional). When it fires the whole process group is killed, and " +
|
|
31
|
+
"the pushed result says the command was killed by the timeout.",
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
required: ["command"],
|
|
35
|
+
additionalProperties: false,
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
constructor(env) {
|
|
39
|
+
super({ env });
|
|
40
|
+
}
|
|
41
|
+
async call(input, ctx) {
|
|
42
|
+
const agent = ctx?.agent;
|
|
43
|
+
if (!agent)
|
|
44
|
+
throw new Error(`${ASYNC_EXEC_TOOL} must be called by an agent`);
|
|
45
|
+
const command = input.command;
|
|
46
|
+
const timeout = input.timeout;
|
|
47
|
+
if (timeout !== undefined &&
|
|
48
|
+
(typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0)) {
|
|
49
|
+
throw new Error(`${ASYNC_EXEC_TOOL}: timeout must be a positive number (milliseconds) when given, got: ${JSON.stringify(timeout)}`);
|
|
50
|
+
}
|
|
51
|
+
const cwd = input.cwd ? this.resolve(input.cwd) : this.env.cwd;
|
|
52
|
+
const log = this.env.log;
|
|
53
|
+
const taskId = nextTaskId(agent, ASYNC_EXEC_TOOL);
|
|
54
|
+
const run = runCommand({ command, cwd, timeoutMs: timeout });
|
|
55
|
+
const untrack = trackCommand(agent, run, log);
|
|
56
|
+
// 结果一路走投递回来:这里不 await 它,工具当场返回
|
|
57
|
+
void run.result
|
|
58
|
+
.then(async (result) => {
|
|
59
|
+
const content = await commandOutputContent({
|
|
60
|
+
tool: ASYNC_EXEC_TOOL,
|
|
61
|
+
fields: {
|
|
62
|
+
task: ASYNC_EXEC_TOOL,
|
|
63
|
+
taskId,
|
|
64
|
+
command,
|
|
65
|
+
...(timeout !== undefined ? { timeout } : {}),
|
|
66
|
+
message: outcomeMessage(result, command, timeout),
|
|
67
|
+
},
|
|
68
|
+
result,
|
|
69
|
+
limit: this.env.config.maxToolOutput ?? DEFAULT_MAX_TOOL_OUTPUT,
|
|
70
|
+
});
|
|
71
|
+
deliverAsyncResult({ agent, label: ASYNC_EXEC_TOOL, content, log });
|
|
72
|
+
})
|
|
73
|
+
.catch((error) => {
|
|
74
|
+
log?.error(`[${ASYNC_EXEC_TOOL}] task "${taskId}" ended but its result was not delivered`, {
|
|
75
|
+
error,
|
|
76
|
+
});
|
|
77
|
+
})
|
|
78
|
+
.finally(untrack);
|
|
79
|
+
return JSON.stringify({
|
|
80
|
+
started: true,
|
|
81
|
+
taskId,
|
|
82
|
+
command,
|
|
83
|
+
...(timeout !== undefined ? { timeout } : {}),
|
|
84
|
+
note: `The command runs in the background as task "${taskId}". Do not wait for it: the system will notify you by pushing its result into this session when the command ends. Nothing checks a background task, so do not poll.`,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** 这一次的收场:正文里要能看出是正常结束、超时被杀还是输出被截断 */
|
|
89
|
+
function outcomeMessage(result, command, timeoutMs) {
|
|
90
|
+
if (result.terminated === "timeout") {
|
|
91
|
+
return `Command "${command}" was killed by its ${timeoutMs}ms timeout, together with every process it started; the output below is what it produced before that.`;
|
|
92
|
+
}
|
|
93
|
+
if (result.terminated === "aborted") {
|
|
94
|
+
return `Command "${command}" was stopped before it finished; the output below is what it produced before that.`;
|
|
95
|
+
}
|
|
96
|
+
if (result.truncated) {
|
|
97
|
+
return `Command "${command}" wrote more than the in-memory cap, so it was killed there and the tail of its output is lost.`;
|
|
98
|
+
}
|
|
99
|
+
if (result.exitCode === null) {
|
|
100
|
+
return `Command "${command}" ended without an exit code; what came back is below.`;
|
|
101
|
+
}
|
|
102
|
+
return `Command "${command}" finished with exit code ${result.exitCode}.`;
|
|
103
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
2
|
+
import type { ToolEnv } from "../../../types/index.js";
|
|
3
|
+
import type { AgentNS, ToolCallContext } from "@ai-zen/agents-core";
|
|
4
|
+
export declare class AsyncTimeoutTool extends SdkCallbackTool {
|
|
5
|
+
function: AgentNS.FunctionDefine;
|
|
6
|
+
constructor(env: ToolEnv);
|
|
7
|
+
call(input: {
|
|
8
|
+
ms: number;
|
|
9
|
+
}, ctx?: ToolCallContext): Promise<string>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
2
|
+
import { ASYNC_TIMEOUT_TOOL, deliverAsyncResult, nextTaskId, trackTimer } from "./asyncTasks.js";
|
|
3
|
+
/** setTimeout 能吃下的最大延时(2^31-1 毫秒);再长它会立刻触发。 */
|
|
4
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
5
|
+
export class AsyncTimeoutTool extends SdkCallbackTool {
|
|
6
|
+
function = {
|
|
7
|
+
name: ASYNC_TIMEOUT_TOOL,
|
|
8
|
+
description: "Set a timer and return immediately. Do not wait for it: this call is over the moment it returns. " +
|
|
9
|
+
"The system will notify you when the time is up by pushing a message back into this session, " +
|
|
10
|
+
"carrying that timer's id; that notification is the only way a timer reports, so do not wait and " +
|
|
11
|
+
"do not poll: nothing comes back before the timer fires. Use it when the wait itself is the " +
|
|
12
|
+
"point: give another process a head start, come back to a value later, or space out work. There " +
|
|
13
|
+
"is no upper limit on `ms`: this is a timer that delivers one message, not a limit on how long a " +
|
|
14
|
+
"run may take.",
|
|
15
|
+
parameters: {
|
|
16
|
+
type: "object",
|
|
17
|
+
properties: {
|
|
18
|
+
ms: {
|
|
19
|
+
type: "number",
|
|
20
|
+
description: "Milliseconds to wait before the message is delivered (a positive number, no upper limit).",
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
required: ["ms"],
|
|
24
|
+
additionalProperties: false,
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
constructor(env) {
|
|
28
|
+
super({ env });
|
|
29
|
+
}
|
|
30
|
+
async call(input, ctx) {
|
|
31
|
+
const agent = ctx?.agent;
|
|
32
|
+
if (!agent)
|
|
33
|
+
throw new Error(`${ASYNC_TIMEOUT_TOOL} must be called by an agent`);
|
|
34
|
+
const ms = input.ms;
|
|
35
|
+
if (typeof ms !== "number" || !Number.isFinite(ms) || ms <= 0) {
|
|
36
|
+
throw new Error(`${ASYNC_TIMEOUT_TOOL}: ms must be a positive number of milliseconds, got: ${JSON.stringify(ms)}`);
|
|
37
|
+
}
|
|
38
|
+
const log = this.env.log;
|
|
39
|
+
const taskId = nextTaskId(agent, ASYNC_TIMEOUT_TOOL);
|
|
40
|
+
scheduleTimer({
|
|
41
|
+
agent,
|
|
42
|
+
ms,
|
|
43
|
+
log,
|
|
44
|
+
fire: () => {
|
|
45
|
+
deliverAsyncResult({
|
|
46
|
+
agent,
|
|
47
|
+
label: ASYNC_TIMEOUT_TOOL,
|
|
48
|
+
content: JSON.stringify({
|
|
49
|
+
task: ASYNC_TIMEOUT_TOOL,
|
|
50
|
+
taskId,
|
|
51
|
+
ms,
|
|
52
|
+
message: `Time is up: timer "${taskId}" was set for ${ms}ms and has fired.`,
|
|
53
|
+
}),
|
|
54
|
+
log,
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
return JSON.stringify({
|
|
59
|
+
started: true,
|
|
60
|
+
taskId,
|
|
61
|
+
ms,
|
|
62
|
+
note: `The timer runs as task "${taskId}". Do not wait for it: the system will notify you in ${ms}ms. Nothing checks a timer, so do not poll.`,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* 排一个定时器,并把它的回收登记到执行体名下。
|
|
68
|
+
*
|
|
69
|
+
* 超过 {@link MAX_TIMER_MS} 的等待要分段排:setTimeout 拿到更长的延时会立刻触发,那样
|
|
70
|
+
* 一次跨月的定时会在下一拍就报「时间到了」。分段之后每一段到点再排下一段,对外仍然是一次定时。
|
|
71
|
+
*/
|
|
72
|
+
function scheduleTimer(options) {
|
|
73
|
+
const { agent, ms, fire, log } = options;
|
|
74
|
+
let remaining = ms;
|
|
75
|
+
let untrack = () => undefined;
|
|
76
|
+
const scheduleNext = () => {
|
|
77
|
+
const step = Math.min(remaining, MAX_TIMER_MS);
|
|
78
|
+
untrack = trackTimer(agent, setTimeout(tick, step), log);
|
|
79
|
+
};
|
|
80
|
+
const tick = () => {
|
|
81
|
+
untrack();
|
|
82
|
+
remaining -= MAX_TIMER_MS;
|
|
83
|
+
if (remaining > 0) {
|
|
84
|
+
scheduleNext();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
fire();
|
|
88
|
+
};
|
|
89
|
+
scheduleNext();
|
|
90
|
+
}
|
|
@@ -3,7 +3,7 @@ import type { AgentDefinition } from "../../../types/index.js";
|
|
|
3
3
|
import type { Scope, FilterOutput } from "../../Scope.js";
|
|
4
4
|
import type { ScopeCandidates, ScopePlugin } from "../../ScopePlugin.js";
|
|
5
5
|
/**
|
|
6
|
-
* 内置工具插件 ——
|
|
6
|
+
* 内置工具插件 —— 注册表 `BUILTIN_TOOL_CLASSES` 里的那批内置工具。
|
|
7
7
|
*
|
|
8
8
|
* 发现层零过滤;可用性由各工具 `isAvailable(config, definition)` 自陈,
|
|
9
9
|
* 在本插件 `candidates()` 阶段按声明剔除(如 GenerateImageTool 依赖 defaultImageModel、
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { discoverBuiltinTools } from "./discover.js";
|
|
2
2
|
/**
|
|
3
|
-
* 内置工具插件 ——
|
|
3
|
+
* 内置工具插件 —— 注册表 `BUILTIN_TOOL_CLASSES` 里的那批内置工具。
|
|
4
4
|
*
|
|
5
5
|
* 发现层零过滤;可用性由各工具 `isAvailable(config, definition)` 自陈,
|
|
6
6
|
* 在本插件 `candidates()` 阶段按声明剔除(如 GenerateImageTool 依赖 defaultImageModel、
|
|
@@ -97,7 +97,7 @@ export class DownloadFileTool extends SdkCallbackTool {
|
|
|
97
97
|
success: false,
|
|
98
98
|
...(aborted ? { aborted: true } : {}),
|
|
99
99
|
error: error?.message || "Download failed",
|
|
100
|
-
//
|
|
100
|
+
// 已开始写盘时文件可能不完整:只如实告知,不去删(同路径的原文件可能本来就存在)
|
|
101
101
|
...(startedWriting
|
|
102
102
|
? { note: "The file at the save path may be incomplete or overwritten" }
|
|
103
103
|
: {}),
|
|
@@ -1,18 +1,7 @@
|
|
|
1
|
-
import { spawn } from "child_process";
|
|
2
1
|
import { SdkCallbackTool } from "./SdkCallbackTool.js";
|
|
3
|
-
import { DEFAULT_MAX_TOOL_OUTPUT
|
|
4
|
-
|
|
5
|
-
|
|
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;
|
|
2
|
+
import { DEFAULT_MAX_TOOL_OUTPUT } from "./outputGuard.js";
|
|
3
|
+
import { runCommand } from "./commandRun.js";
|
|
4
|
+
import { commandOutputContent } from "./commandOutput.js";
|
|
16
5
|
export class ExecTool extends SdkCallbackTool {
|
|
17
6
|
function = {
|
|
18
7
|
name: "exec",
|
|
@@ -26,7 +15,7 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
26
15
|
},
|
|
27
16
|
timeout: {
|
|
28
17
|
type: "number",
|
|
29
|
-
description: "Timeout in milliseconds (required). The process is killed on timeout. For long-running commands, prefer
|
|
18
|
+
description: "Timeout in milliseconds (required). The process is killed on timeout. For long-running commands, prefer async_exec, which returns immediately and pushes the result back into this session.",
|
|
30
19
|
},
|
|
31
20
|
},
|
|
32
21
|
required: ["command", "timeout"],
|
|
@@ -37,195 +26,17 @@ export class ExecTool extends SdkCallbackTool {
|
|
|
37
26
|
super({ env });
|
|
38
27
|
}
|
|
39
28
|
async call(input, ctx) {
|
|
40
|
-
const command = input
|
|
41
|
-
const { timeout } = input;
|
|
29
|
+
const { command, timeout } = input;
|
|
42
30
|
// 运行时双校验:timeout 必填且必须为正数
|
|
43
31
|
if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0) {
|
|
44
32
|
throw new Error(`exec: timeout is required and must be a positive number (milliseconds), got: ${JSON.stringify(timeout)}`);
|
|
45
33
|
}
|
|
46
|
-
const
|
|
47
|
-
const result = await
|
|
48
|
-
|
|
49
|
-
if (signal?.aborted) {
|
|
50
|
-
resolve({
|
|
51
|
-
stdout: "",
|
|
52
|
-
stderr: "Process aborted",
|
|
53
|
-
exitCode: null,
|
|
54
|
-
killed: true,
|
|
55
|
-
terminated: "aborted",
|
|
56
|
-
});
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
let child;
|
|
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;
|
|
72
|
-
const settle = (value) => {
|
|
73
|
-
if (settled)
|
|
74
|
-
return;
|
|
75
|
-
settled = true;
|
|
76
|
-
if (timeoutTimer)
|
|
77
|
-
clearTimeout(timeoutTimer);
|
|
78
|
-
if (graceTimer)
|
|
79
|
-
clearTimeout(graceTimer);
|
|
80
|
-
if (drainTimer)
|
|
81
|
-
clearTimeout(drainTimer);
|
|
82
|
-
signal?.removeEventListener("abort", onAbort);
|
|
83
|
-
resolve(value);
|
|
84
|
-
};
|
|
85
|
-
/** 用已收集到的输出收尾(子进程已退出或被杀) */
|
|
86
|
-
const settleFromCollected = (forced) => {
|
|
87
|
-
settle({
|
|
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
|
-
// 与 `SpawnTool` 同一条约定:输出走管道,不需要也不该给用户弹一个终端窗口。
|
|
124
|
-
// 这一条尤其要紧 —— 服务端自己是 detached 起的、没有控制台,不 hide 的话这里
|
|
125
|
-
// **每次工具调用**都会新分配一个控制台窗口。
|
|
126
|
-
windowsHide: true,
|
|
127
|
-
});
|
|
128
|
-
const collect = (target) => (chunk) => {
|
|
129
|
-
if (truncated)
|
|
130
|
-
return;
|
|
131
|
-
bytes += chunk.length;
|
|
132
|
-
target.push(chunk);
|
|
133
|
-
// 超过内存上限:停手并杀掉进程组,尾部本来也存不下
|
|
134
|
-
if (bytes > MAX_BUFFER) {
|
|
135
|
-
truncated = true;
|
|
136
|
-
killProcessGroup();
|
|
137
|
-
}
|
|
138
|
-
};
|
|
139
|
-
child.stdout?.on("data", collect(out));
|
|
140
|
-
child.stderr?.on("data", collect(err));
|
|
141
|
-
child.on("error", (e) => {
|
|
142
|
-
settle({
|
|
143
|
-
stdout: "",
|
|
144
|
-
stderr: e.message,
|
|
145
|
-
exitCode: null,
|
|
146
|
-
killed: false,
|
|
147
|
-
terminated,
|
|
148
|
-
});
|
|
149
|
-
});
|
|
150
|
-
child.on("exit", (code, sig) => {
|
|
151
|
-
exited = true;
|
|
152
|
-
exitCode = code;
|
|
153
|
-
exitSignal = sig;
|
|
154
|
-
// 已退出但 stdio 可能还被后代占着(如 `cmd &`):只等一小会儿就收尾
|
|
155
|
-
drainTimer = setTimeout(() => settleFromCollected(), STDIO_DRAIN_MS);
|
|
156
|
-
});
|
|
157
|
-
child.on("close", (code, sig) => {
|
|
158
|
-
if (!exited) {
|
|
159
|
-
exitCode = code;
|
|
160
|
-
exitSignal = sig;
|
|
161
|
-
}
|
|
162
|
-
settleFromCollected();
|
|
163
|
-
});
|
|
164
|
-
// 中断:整组 kill,并立即返回(不等待回调,避免挂起)
|
|
165
|
-
const onAbort = () => {
|
|
166
|
-
terminated = "aborted";
|
|
167
|
-
killProcessGroup();
|
|
168
|
-
settle({
|
|
169
|
-
stdout: "",
|
|
170
|
-
stderr: "Process aborted",
|
|
171
|
-
exitCode: null,
|
|
172
|
-
killed: true,
|
|
173
|
-
terminated: "aborted",
|
|
174
|
-
});
|
|
175
|
-
};
|
|
176
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
177
|
-
// 超时:整组 kill 后优先等回调,好把已收集到的输出带回去
|
|
178
|
-
timeoutTimer = setTimeout(() => {
|
|
179
|
-
terminated = "timeout";
|
|
180
|
-
killProcessGroup();
|
|
181
|
-
graceTimer = setTimeout(() => {
|
|
182
|
-
settle({
|
|
183
|
-
stdout: Buffer.concat(out).toString(),
|
|
184
|
-
stderr: Buffer.concat(err).toString(),
|
|
185
|
-
exitCode: null,
|
|
186
|
-
killed: true,
|
|
187
|
-
terminated: "timeout",
|
|
188
|
-
});
|
|
189
|
-
}, KILL_GRACE_MS);
|
|
190
|
-
}, timeout);
|
|
191
|
-
});
|
|
192
|
-
const truncationNote = result.truncated
|
|
193
|
-
? `Output reached the ${MAX_BUFFER}-byte in-memory cap: it was truncated there and the tail is lost (the process was killed by maxBuffer).`
|
|
194
|
-
: undefined;
|
|
195
|
-
// 输出保护:stdout + stderr 合计超过 maxToolOutput 时,分文件落盘并返回警告 + 头尾预览
|
|
196
|
-
const limit = this.env.config.maxToolOutput ?? DEFAULT_MAX_TOOL_OUTPUT;
|
|
197
|
-
const guarded = await guardOutput({
|
|
34
|
+
const run = runCommand({ command, cwd: this.env.cwd, timeoutMs: timeout, signal: ctx?.signal });
|
|
35
|
+
const result = await run.result;
|
|
36
|
+
return commandOutputContent({
|
|
198
37
|
tool: "exec",
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
dump: (_dir, output) => [
|
|
202
|
-
{ name: "stdout.log", content: output.stdout },
|
|
203
|
-
{ name: "stderr.log", content: output.stderr },
|
|
204
|
-
],
|
|
205
|
-
buildWarning: (ctx) => {
|
|
206
|
-
const stdout = headTailPreview(result.stdout);
|
|
207
|
-
const stderr = headTailPreview(result.stderr);
|
|
208
|
-
return JSON.stringify({
|
|
209
|
-
outputTooLarge: true,
|
|
210
|
-
warning: `Output too large: stdout + stderr total ${result.stdout.length + result.stderr.length} characters, ` +
|
|
211
|
-
`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`,
|
|
212
|
-
...(truncationNote ? { truncated: true, truncationNote } : {}),
|
|
213
|
-
files: ctx.files,
|
|
214
|
-
stdout: { chars: result.stdout.length, lines: countLines(result.stdout), ...stdout },
|
|
215
|
-
stderr: { chars: result.stderr.length, lines: countLines(result.stderr), ...stderr },
|
|
216
|
-
exitCode: result.exitCode,
|
|
217
|
-
killed: result.killed,
|
|
218
|
-
terminated: result.terminated,
|
|
219
|
-
});
|
|
220
|
-
},
|
|
38
|
+
result,
|
|
39
|
+
limit: this.env.config.maxToolOutput ?? DEFAULT_MAX_TOOL_OUTPUT,
|
|
221
40
|
});
|
|
222
|
-
// 未超限:content 为原始结果对象,按原有结构序列化;超限:buildWarning 已生成返回字符串
|
|
223
|
-
if (typeof guarded === "string")
|
|
224
|
-
return guarded;
|
|
225
|
-
return JSON.stringify(result.truncated ? { ...guarded, truncated: true, truncationNote } : guarded);
|
|
226
41
|
}
|
|
227
42
|
}
|
|
228
|
-
/** 统计文本行数(空文本记 0 行) */
|
|
229
|
-
function countLines(text) {
|
|
230
|
-
return text.length === 0 ? 0 : text.split("\n").length;
|
|
231
|
-
}
|
|
@@ -145,7 +145,7 @@ export class FindTextTool extends SdkCallbackTool {
|
|
|
145
145
|
}
|
|
146
146
|
/**
|
|
147
147
|
* 输出保护:结果 JSON 超过 maxToolOutput 时落盘为 result.json,
|
|
148
|
-
* 返回警告 +
|
|
148
|
+
* 返回警告 + 头部预览;未超限则原样返回。
|
|
149
149
|
*/
|
|
150
150
|
async protect(json) {
|
|
151
151
|
const limit = this.env.config.maxToolOutput ?? DEFAULT_MAX_TOOL_OUTPUT;
|
|
@@ -5,12 +5,9 @@ import type { AgentDefinition, AppConfig, ToolEnv } from "../../../types/index.j
|
|
|
5
5
|
* 根据文字描述生成图片。**统一返回字符串**(JSON,含图片 URL 列表):
|
|
6
6
|
* 生成结果如何处理(查看/下载/转发)由模型与上层自由决定——
|
|
7
7
|
* 需要让模型看图时,模型可主动调用 view_image(URL);需要保存时用 download_file。
|
|
8
|
-
*
|
|
9
|
-
* 依赖 AppConfig 中的 imageModels 和 defaultImageModel 配置(isAvailable 声明),
|
|
10
|
-
* 未配置时由 buildTools 过滤,不暴露给 Agent。
|
|
11
8
|
*/
|
|
12
9
|
export declare class GenerateImageTool extends SdkCallbackTool {
|
|
13
|
-
/**
|
|
10
|
+
/** 可用性只判 `defaultImageModel`;`imageModels` 为空时由 call() 自己报错 */
|
|
14
11
|
isAvailable(config: AppConfig, _definition: AgentDefinition): boolean;
|
|
15
12
|
function: AgentNS.FunctionDefine;
|
|
16
13
|
constructor(env: ToolEnv);
|
|
@@ -19,12 +19,9 @@ const defaultGenerateImage = async ({ endpoint, model, prompt, size, quality, si
|
|
|
19
19
|
* 根据文字描述生成图片。**统一返回字符串**(JSON,含图片 URL 列表):
|
|
20
20
|
* 生成结果如何处理(查看/下载/转发)由模型与上层自由决定——
|
|
21
21
|
* 需要让模型看图时,模型可主动调用 view_image(URL);需要保存时用 download_file。
|
|
22
|
-
*
|
|
23
|
-
* 依赖 AppConfig 中的 imageModels 和 defaultImageModel 配置(isAvailable 声明),
|
|
24
|
-
* 未配置时由 buildTools 过滤,不暴露给 Agent。
|
|
25
22
|
*/
|
|
26
23
|
export class GenerateImageTool extends SdkCallbackTool {
|
|
27
|
-
/**
|
|
24
|
+
/** 可用性只判 `defaultImageModel`;`imageModels` 为空时由 call() 自己报错 */
|
|
28
25
|
isAvailable(config, _definition) {
|
|
29
26
|
return !!config.defaultImageModel;
|
|
30
27
|
}
|
|
@@ -99,7 +96,7 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
99
96
|
});
|
|
100
97
|
}
|
|
101
98
|
const modelName = input.model || imageModel.modelName;
|
|
102
|
-
// 出网动作走注入的 deps(缺省时用 OpenAI SDK
|
|
99
|
+
// 出网动作走注入的 deps(缺省时用 OpenAI SDK)
|
|
103
100
|
const generateImage = this.env.deps?.generateImage ?? defaultGenerateImage;
|
|
104
101
|
const result = await generateImage({
|
|
105
102
|
endpoint,
|
|
@@ -131,9 +128,6 @@ export class GenerateImageTool extends SdkCallbackTool {
|
|
|
131
128
|
error: "The endpoint returned no image: neither `url` nor `b64_json` was present in the response",
|
|
132
129
|
});
|
|
133
130
|
}
|
|
134
|
-
// 统一返回字符串(JSON):生成结果如何处理(查看/下载/转发)由模型与上层自由决定,
|
|
135
|
-
// 不替模型做「看或不看」的假设。需要让模型看图 → 模型可主动调用 view_image;
|
|
136
|
-
// 需要保存 → download_file 下载。
|
|
137
131
|
const hasUrl = images.some((img) => img.url);
|
|
138
132
|
return JSON.stringify({
|
|
139
133
|
success: true,
|
|
@@ -12,7 +12,7 @@ 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: "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.",
|
|
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/mixed). 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: {
|
|
@@ -9,13 +9,13 @@ export interface SdkCallbackToolOptions {
|
|
|
9
9
|
/**
|
|
10
10
|
* SdkCallbackTool — SDK 内置工具基类。
|
|
11
11
|
*
|
|
12
|
-
* 环境(ToolEnv)在构造时注入,工具逻辑在子类的 call()
|
|
13
|
-
*
|
|
12
|
+
* 环境(ToolEnv)在构造时注入,工具逻辑在子类的 call() 中实现 —— 用 env.cwd
|
|
13
|
+
* 而不是全局 process.cwd(),也不在运行时反查 Agent 上下文。
|
|
14
14
|
*
|
|
15
15
|
* 设计原则:
|
|
16
16
|
* - 一个工具一个类,文件名 = 类名(PascalCase)
|
|
17
17
|
* - 依赖环境(cwd、config)通过构造参数显式注入
|
|
18
|
-
* -
|
|
18
|
+
* - 相对路径统一走 `resolve()`,以 env.cwd 为基准
|
|
19
19
|
*/
|
|
20
20
|
export declare abstract class SdkCallbackTool extends Tool {
|
|
21
21
|
/** 注入的工具环境 */
|
|
@@ -26,7 +26,7 @@ export declare abstract class SdkCallbackTool extends Tool {
|
|
|
26
26
|
* 工具对当前 Agent 的可用性判断。由工具自行声明,直接透传完整
|
|
27
27
|
* app config 与 agent definition(含 modelId / permissions 等),工具自取所需
|
|
28
28
|
* (如是否配置了图片模型、当前模型是否为视觉模型)。
|
|
29
|
-
* 在
|
|
29
|
+
* 在 `BuiltinToolsScopePlugin.candidates()` 里调用;返回 false 的工具不进候选集。
|
|
30
30
|
* 不实现则默认可用。
|
|
31
31
|
*/
|
|
32
32
|
isAvailable?(config: AppConfig, definition: AgentDefinition): boolean;
|