@cicctencent/agent-midway 0.1.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.
Files changed (160) hide show
  1. package/README.md +280 -0
  2. package/dist/adapters/express.d.ts +8 -0
  3. package/dist/adapters/express.js +91 -0
  4. package/dist/adapters/index.d.ts +5 -0
  5. package/dist/adapters/index.js +21 -0
  6. package/dist/adapters/koa.d.ts +3 -0
  7. package/dist/adapters/koa.js +75 -0
  8. package/dist/adapters/midway.d.ts +5 -0
  9. package/dist/adapters/midway.js +11 -0
  10. package/dist/adapters/next.d.ts +12 -0
  11. package/dist/adapters/next.js +89 -0
  12. package/dist/adapters/shared.d.ts +4 -0
  13. package/dist/adapters/shared.js +31 -0
  14. package/dist/channel/dingtalk.d.ts +18 -0
  15. package/dist/channel/dingtalk.js +68 -0
  16. package/dist/channel/feishu.d.ts +20 -0
  17. package/dist/channel/feishu.js +96 -0
  18. package/dist/channel/index.d.ts +46 -0
  19. package/dist/channel/index.js +311 -0
  20. package/dist/channel/types.d.ts +77 -0
  21. package/dist/channel/types.js +7 -0
  22. package/dist/channel/wecom.d.ts +22 -0
  23. package/dist/channel/wecom.js +106 -0
  24. package/dist/component.d.ts +49 -0
  25. package/dist/component.js +129 -0
  26. package/dist/connector/calendar-adapter.d.ts +19 -0
  27. package/dist/connector/calendar-adapter.js +236 -0
  28. package/dist/connector/db-adapter.d.ts +28 -0
  29. package/dist/connector/db-adapter.js +193 -0
  30. package/dist/connector/email-adapter.d.ts +23 -0
  31. package/dist/connector/email-adapter.js +192 -0
  32. package/dist/connector/fs-adapter.d.ts +15 -0
  33. package/dist/connector/fs-adapter.js +199 -0
  34. package/dist/connector/http-adapter.d.ts +29 -0
  35. package/dist/connector/http-adapter.js +181 -0
  36. package/dist/connector/index.d.ts +24 -0
  37. package/dist/connector/index.js +454 -0
  38. package/dist/connector/mcp-adapter.d.ts +27 -0
  39. package/dist/connector/mcp-adapter.js +156 -0
  40. package/dist/connector/mq-adapter.d.ts +25 -0
  41. package/dist/connector/mq-adapter.js +181 -0
  42. package/dist/connector/types.d.ts +205 -0
  43. package/dist/connector/types.js +9 -0
  44. package/dist/controller/a2a.controller.d.ts +41 -0
  45. package/dist/controller/a2a.controller.js +150 -0
  46. package/dist/controller/agent-profile.controller.d.ts +97 -0
  47. package/dist/controller/agent-profile.controller.js +200 -0
  48. package/dist/controller/agent.controller.d.ts +199 -0
  49. package/dist/controller/agent.controller.js +414 -0
  50. package/dist/controller/application.controller.d.ts +113 -0
  51. package/dist/controller/application.controller.js +217 -0
  52. package/dist/controller/automation.controller.d.ts +113 -0
  53. package/dist/controller/automation.controller.js +246 -0
  54. package/dist/controller/channel.controller.d.ts +73 -0
  55. package/dist/controller/channel.controller.js +183 -0
  56. package/dist/controller/chat.controller.d.ts +188 -0
  57. package/dist/controller/chat.controller.js +375 -0
  58. package/dist/controller/connector.controller.d.ts +134 -0
  59. package/dist/controller/connector.controller.js +257 -0
  60. package/dist/controller/knowledge-base.controller.d.ts +157 -0
  61. package/dist/controller/knowledge-base.controller.js +278 -0
  62. package/dist/controller/mcp-server.controller.d.ts +115 -0
  63. package/dist/controller/mcp-server.controller.js +236 -0
  64. package/dist/controller/model-config.controller.d.ts +139 -0
  65. package/dist/controller/model-config.controller.js +274 -0
  66. package/dist/controller/observability.controller.d.ts +124 -0
  67. package/dist/controller/observability.controller.js +142 -0
  68. package/dist/controller/security.controller.d.ts +91 -0
  69. package/dist/controller/security.controller.js +172 -0
  70. package/dist/controller/settings.controller.d.ts +83 -0
  71. package/dist/controller/settings.controller.js +280 -0
  72. package/dist/core/ai-workstation.d.ts +17 -0
  73. package/dist/core/ai-workstation.js +129 -0
  74. package/dist/core/index.d.ts +4 -0
  75. package/dist/core/index.js +20 -0
  76. package/dist/core/service-container.d.ts +12 -0
  77. package/dist/core/service-container.js +54 -0
  78. package/dist/core/sse.d.ts +6 -0
  79. package/dist/core/sse.js +56 -0
  80. package/dist/core/types.d.ts +72 -0
  81. package/dist/core/types.js +2 -0
  82. package/dist/dto/agent.dto.d.ts +21 -0
  83. package/dist/dto/agent.dto.js +79 -0
  84. package/dist/dto/ai-config.dto.d.ts +67 -0
  85. package/dist/dto/ai-config.dto.js +249 -0
  86. package/dist/dto/chat.dto.d.ts +40 -0
  87. package/dist/dto/chat.dto.js +122 -0
  88. package/dist/index.d.ts +101 -0
  89. package/dist/index.js +195 -0
  90. package/dist/memory/db-store.d.ts +33 -0
  91. package/dist/memory/db-store.js +143 -0
  92. package/dist/memory/index.d.ts +187 -0
  93. package/dist/memory/index.js +443 -0
  94. package/dist/model/ai-agent-profile.entity.d.ts +32 -0
  95. package/dist/model/ai-agent-profile.entity.js +289 -0
  96. package/dist/model/ai-application.entity.d.ts +20 -0
  97. package/dist/model/ai-application.entity.js +166 -0
  98. package/dist/model/ai-chat-memory.entity.d.ts +16 -0
  99. package/dist/model/ai-chat-memory.entity.js +123 -0
  100. package/dist/model/ai-chat-message.entity.d.ts +16 -0
  101. package/dist/model/ai-chat-message.entity.js +122 -0
  102. package/dist/model/ai-chat-skill.entity.d.ts +19 -0
  103. package/dist/model/ai-chat-skill.entity.js +155 -0
  104. package/dist/model/ai-chat-thread.entity.d.ts +15 -0
  105. package/dist/model/ai-chat-thread.entity.js +113 -0
  106. package/dist/model/ai-chat-workspace.entity.d.ts +17 -0
  107. package/dist/model/ai-chat-workspace.entity.js +136 -0
  108. package/dist/model/ai-kb-document.entity.d.ts +16 -0
  109. package/dist/model/ai-kb-document.entity.js +122 -0
  110. package/dist/model/ai-knowledge-base.entity.d.ts +22 -0
  111. package/dist/model/ai-knowledge-base.entity.js +185 -0
  112. package/dist/model/ai-mcp-server.entity.d.ts +23 -0
  113. package/dist/model/ai-mcp-server.entity.js +198 -0
  114. package/dist/model/ai-model-config.entity.d.ts +24 -0
  115. package/dist/model/ai-model-config.entity.js +200 -0
  116. package/dist/service/a2a.service.d.ts +142 -0
  117. package/dist/service/a2a.service.js +537 -0
  118. package/dist/service/agent-profile.service.d.ts +34 -0
  119. package/dist/service/agent-profile.service.js +110 -0
  120. package/dist/service/agent-server.service.d.ts +91 -0
  121. package/dist/service/agent-server.service.js +634 -0
  122. package/dist/service/agent-task-queue.service.d.ts +98 -0
  123. package/dist/service/agent-task-queue.service.js +283 -0
  124. package/dist/service/ai-chat.service.d.ts +103 -0
  125. package/dist/service/ai-chat.service.js +431 -0
  126. package/dist/service/ai-skill.service.d.ts +116 -0
  127. package/dist/service/ai-skill.service.js +457 -0
  128. package/dist/service/application.service.d.ts +42 -0
  129. package/dist/service/application.service.js +139 -0
  130. package/dist/service/automation.service.d.ts +37 -0
  131. package/dist/service/automation.service.js +196 -0
  132. package/dist/service/connector.service.d.ts +136 -0
  133. package/dist/service/connector.service.js +524 -0
  134. package/dist/service/knowledge-base.service.d.ts +138 -0
  135. package/dist/service/knowledge-base.service.js +528 -0
  136. package/dist/service/mcp-server.service.d.ts +39 -0
  137. package/dist/service/mcp-server.service.js +143 -0
  138. package/dist/service/model-config.service.d.ts +57 -0
  139. package/dist/service/model-config.service.js +168 -0
  140. package/dist/service/observability.service.d.ts +145 -0
  141. package/dist/service/observability.service.js +281 -0
  142. package/dist/service/openai.service.d.ts +88 -0
  143. package/dist/service/openai.service.js +406 -0
  144. package/dist/service/prompt-builder.service.d.ts +50 -0
  145. package/dist/service/prompt-builder.service.js +246 -0
  146. package/dist/tools/code-exec.tool.d.ts +37 -0
  147. package/dist/tools/code-exec.tool.js +162 -0
  148. package/dist/tools/datetime.tool.d.ts +21 -0
  149. package/dist/tools/datetime.tool.js +379 -0
  150. package/dist/tools/http-request.tool.d.ts +43 -0
  151. package/dist/tools/http-request.tool.js +455 -0
  152. package/dist/tools/registry.d.ts +71 -0
  153. package/dist/tools/registry.js +77 -0
  154. package/dist/tools/text-process.tool.d.ts +7 -0
  155. package/dist/tools/text-process.tool.js +366 -0
  156. package/dist/tools/web-search.tool.d.ts +28 -0
  157. package/dist/tools/web-search.tool.js +304 -0
  158. package/dist/types.d.ts +70 -0
  159. package/dist/types.js +7 -0
  160. package/package.json +69 -0
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PromptBuilderService = void 0;
13
+ const core_1 = require("@midwayjs/core");
14
+ const agent_profile_service_1 = require("./agent-profile.service");
15
+ const mcp_server_service_1 = require("./mcp-server.service");
16
+ const ai_skill_service_1 = require("./ai-skill.service");
17
+ const agent_server_1 = require("@cicctencent/agent-server");
18
+ /**
19
+ * Prompt 构建服务
20
+ *
21
+ * 负责构建 Agent 的系统提示词,包括:
22
+ * - 基础 Prompt(来自 Agent Profile)
23
+ * - 工具说明注入
24
+ * - 记忆上下文
25
+ * - Skill 上下文
26
+ */
27
+ let PromptBuilderService = class PromptBuilderService {
28
+ /**
29
+ * 构建完整的系统提示词
30
+ */
31
+ async buildSystemPrompt(applicationId, profileId, options) {
32
+ const parts = [];
33
+ // 1. 获取 Agent Profile
34
+ let profile = null;
35
+ if (profileId) {
36
+ profile = await this.agentProfileService.get(profileId, applicationId);
37
+ }
38
+ else {
39
+ profile = await this.agentProfileService.getDefault(applicationId);
40
+ }
41
+ // 2. 基础 Prompt
42
+ if (profile?.basePrompt) {
43
+ parts.push(profile.basePrompt);
44
+ }
45
+ else {
46
+ parts.push(this.getDefaultPrompt(profile?.agentType));
47
+ }
48
+ // 3. 工具说明
49
+ if (options?.includeTools !== false && profile) {
50
+ const toolSection = await this.buildToolSection(profile, applicationId);
51
+ if (toolSection) {
52
+ parts.push(toolSection);
53
+ }
54
+ }
55
+ // 4. Skill 上下文
56
+ if (options?.includeSkills !== false && profile) {
57
+ const skillSection = await this.buildSkillSection(profile);
58
+ if (skillSection) {
59
+ parts.push(skillSection);
60
+ }
61
+ }
62
+ // 5. 记忆上下文
63
+ if (options?.includeMemory && options?.memoryContext) {
64
+ parts.push(`\n## 记忆上下文\n\n${options.memoryContext}`);
65
+ }
66
+ // 6. 领域上下文
67
+ if (profile?.domain) {
68
+ parts.push(`\n## 领域\n\n你正在为「${profile.domain}」领域提供服务。`);
69
+ }
70
+ return parts.join('\n\n');
71
+ }
72
+ /**
73
+ * 构建工具说明部分(使用 agent-server 共享片段)
74
+ */
75
+ async buildToolSection(profile, applicationId) {
76
+ const tools = [];
77
+ // 内置工具说明
78
+ tools.push('- 你可以使用以下内置工具来完成任务');
79
+ // MCP Server 工具
80
+ if (profile.mcpServers && profile.mcpServers.length > 0) {
81
+ for (const serverId of profile.mcpServers) {
82
+ const serverTools = await this.mcpServerService.getTools(Number(serverId), applicationId);
83
+ for (const tool of serverTools) {
84
+ tools.push(` - ${tool.name || tool.id}: ${tool.description || ''}`);
85
+ }
86
+ }
87
+ }
88
+ // 禁用的工具
89
+ if (profile.disabledTools && profile.disabledTools.length > 0) {
90
+ tools.push(`\n- 以下工具已被禁用: ${profile.disabledTools.join(', ')}`);
91
+ }
92
+ if (tools.length <= 1)
93
+ return '';
94
+ // 合并 agent-server 的结果综合指引
95
+ const synthesisPrompt = agent_server_1.RESULT_SYNTHESIS_PROMPT;
96
+ return `## 可用工具\n\n${tools.join('\n')}${synthesisPrompt}`;
97
+ }
98
+ /**
99
+ * 构建 Skill 上下文部分
100
+ */
101
+ async buildSkillSection(profile) {
102
+ if (!profile.alwaysInjectSkills ||
103
+ profile.alwaysInjectSkills.length === 0) {
104
+ return '';
105
+ }
106
+ try {
107
+ const skillContext = await this.skillService.previewSkillContext(profile.agentType || 'chat');
108
+ if (skillContext) {
109
+ return `## 技能上下文\n\n${skillContext}`;
110
+ }
111
+ }
112
+ catch {
113
+ // Skill 服务不可用时静默跳过
114
+ }
115
+ return '';
116
+ }
117
+ /**
118
+ * 构建默认 Agent 的系统提示词(使用 agent-server 共享片段)
119
+ */
120
+ getDefaultPrompt(agentType) {
121
+ const basePrompt = `你是一个智能助手,能够帮助用户完成各种任务。
122
+
123
+ ## 核心能力
124
+ - 理解用户的自然语言指令
125
+ - 使用可用工具获取信息和执行操作
126
+ - 提供准确、有用的回答
127
+
128
+ ## 行为准则
129
+ - 始终保持友好和专业的态度
130
+ - 当不确定时,主动询问用户以获取更多信息
131
+ - 使用工具时,说明你在做什么以及为什么`;
132
+ // 合并 agent-server 的全局基础规则
133
+ let prompt = basePrompt + agent_server_1.GLOBAL_BASE_RULES;
134
+ if (agentType === 'data-analyst') {
135
+ prompt += `
136
+
137
+ ## 数据分析专家
138
+ 你专注于数据分析任务,能够:
139
+ - 查询和分析数据
140
+ - 生成图表和报告
141
+ - 提供数据驱动的洞察和建议`;
142
+ // 添加结果综合指引
143
+ prompt += agent_server_1.RESULT_SYNTHESIS_PROMPT;
144
+ }
145
+ return prompt;
146
+ }
147
+ /**
148
+ * 构建 Specialist Agent 的系统提示词(使用 agent-server 共享片段)
149
+ */
150
+ buildSpecialistPrompt(profile, toolRegistry, skillManager) {
151
+ const base = profile.basePrompt || '你是一个专业的 AI 助手,能够使用工具完成任务。';
152
+ // 合并通用规则(来自 agent-server)
153
+ let prompt = base + agent_server_1.GLOBAL_BASE_RULES;
154
+ // 始终注入 alwaysInjectSkills 中的 Skill 内容
155
+ if (profile.alwaysInjectSkills?.length && skillManager) {
156
+ for (const skillId of profile.alwaysInjectSkills) {
157
+ const skill = skillManager.get(skillId);
158
+ if (skill?.content) {
159
+ prompt += `\n\n## ${skill.name || skillId}\n\n${skill.content}`;
160
+ }
161
+ }
162
+ }
163
+ // 工具优先引导(使用 agent-server 共享片段)
164
+ if (toolRegistry) {
165
+ const capabilities = (0, agent_server_1.getAgentToolCapabilities)(toolRegistry);
166
+ if (capabilities.mcpToolNames.length > 0) {
167
+ const toolList = (0, agent_server_1.buildMCPToolDescList)(toolRegistry, true);
168
+ prompt += (0, agent_server_1.buildSpecialistMcpPriorityPrompt)(profile.name, toolList);
169
+ prompt += agent_server_1.RESULT_SYNTHESIS_PROMPT;
170
+ // 数据可视化引导
171
+ if (capabilities.hasOutputTools || capabilities.hasShowWidget) {
172
+ prompt += (0, agent_server_1.buildDataPresentationPrompt)(capabilities, {
173
+ jsonFileExample: 'data.json',
174
+ includeHtmlQualityRules: true,
175
+ });
176
+ }
177
+ prompt += agent_server_1.SPECIALIST_EFFICIENCY_RULES;
178
+ }
179
+ // 通用角色边界规则
180
+ prompt += agent_server_1.OUTPUT_CONCISION_RULES;
181
+ prompt += agent_server_1.SUB_AGENT_RESULT_SUMMARY_RULES;
182
+ prompt += (0, agent_server_1.buildSpecialistOutputBoundaryPrompt)(capabilities, {
183
+ includeDocumentFormatRules: true,
184
+ });
185
+ }
186
+ // 领域上下文
187
+ if (profile.domain) {
188
+ prompt += `\n\n## 领域\n\n你正在为「${profile.domain}」领域提供服务。`;
189
+ }
190
+ return prompt;
191
+ }
192
+ /**
193
+ * 解析工具显示名(delegate_task → "分发任务 → {agentName}")
194
+ */
195
+ resolveToolDisplayName(toolName, args, toolRegistry) {
196
+ // delegate_task:显示目标 Agent 名称
197
+ if (toolName === 'delegate_task') {
198
+ const agentName = args.agent || '';
199
+ return agentName ? `分发任务 → ${agentName}` : '分发任务';
200
+ }
201
+ // 内置工具
202
+ if (agent_server_1.BUILTIN_TOOL_LABELS[toolName]) {
203
+ return agent_server_1.BUILTIN_TOOL_LABELS[toolName];
204
+ }
205
+ // MCP 工具
206
+ if (toolName.startsWith('mcp_') && toolRegistry) {
207
+ const tool = toolRegistry.get(toolName);
208
+ const serverName = tool?.metadata?.mcpServer || '';
209
+ const connectorId = tool?.metadata?.connectorId || '';
210
+ const originalName = tool?.metadata?.originalName || '';
211
+ const readable = (originalName || toolName.slice(4))
212
+ .replace(/_/g, ' ')
213
+ .replace(/\b\w/g, c => c.toUpperCase());
214
+ const parts = [];
215
+ if (serverName)
216
+ parts.push(serverName);
217
+ if (connectorId)
218
+ parts.push(connectorId);
219
+ return parts.length > 0 ? `${readable} (${parts.join(' · ')})` : readable;
220
+ }
221
+ // 其他工具
222
+ const readable = toolName.replace(/_/g, ' ');
223
+ return readable.charAt(0).toUpperCase() + readable.slice(1);
224
+ }
225
+ };
226
+ exports.PromptBuilderService = PromptBuilderService;
227
+ __decorate([
228
+ (0, core_1.Inject)(),
229
+ __metadata("design:type", Object)
230
+ ], PromptBuilderService.prototype, "ctx", void 0);
231
+ __decorate([
232
+ (0, core_1.Inject)(),
233
+ __metadata("design:type", agent_profile_service_1.AgentProfileService)
234
+ ], PromptBuilderService.prototype, "agentProfileService", void 0);
235
+ __decorate([
236
+ (0, core_1.Inject)(),
237
+ __metadata("design:type", mcp_server_service_1.MCPServerService)
238
+ ], PromptBuilderService.prototype, "mcpServerService", void 0);
239
+ __decorate([
240
+ (0, core_1.Inject)(),
241
+ __metadata("design:type", ai_skill_service_1.AISkillService)
242
+ ], PromptBuilderService.prototype, "skillService", void 0);
243
+ exports.PromptBuilderService = PromptBuilderService = __decorate([
244
+ (0, core_1.Provide)(),
245
+ (0, core_1.Scope)(core_1.ScopeEnum.Request, { allowDowngrade: true })
246
+ ], PromptBuilderService);
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 代码执行工具
3
+ *
4
+ * 让 Agent 能够在安全沙箱中执行 JavaScript 代码片段,
5
+ * 用于数据计算、格式转换、统计分析等任务。
6
+ *
7
+ * 工具说明:
8
+ * - execute_code:在沙箱中执行任意 JS 代码,支持标准库
9
+ * - analyze_data:对 JSON 数组数据执行常见分析操作(摘要/排序/过滤/分组)
10
+ *
11
+ * 安全机制:
12
+ * - 使用 Function 构造器在受限作用域中执行,无法访问外部模块
13
+ * - 仅暴露安全的标准库(Math、JSON、Date、Array、Object 等)
14
+ * - 执行超时控制(默认 5s,最大 30s)
15
+ * - 输出长度限制(最大 10KB)
16
+ *
17
+ * 生产环境升级路径:
18
+ * - 使用 vm2 / isolated-vm / Docker 容器实现更强的隔离
19
+ * - 支持 Python 执行(通过 Pyodide 或子进程)
20
+ */
21
+ import type { ToolDefinition } from '../types';
22
+ /** 代码执行工具 */
23
+ export declare const executeCodeTool: ToolDefinition<{
24
+ code: string;
25
+ language?: string;
26
+ timeout?: number;
27
+ }, {
28
+ result: any;
29
+ stdout: string;
30
+ error?: string;
31
+ }>;
32
+ /** 数据分析工具(基于代码执行) */
33
+ export declare const analyzeDataTool: ToolDefinition<{
34
+ data: any;
35
+ operation: string;
36
+ description?: string;
37
+ }, any>;
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.analyzeDataTool = exports.executeCodeTool = void 0;
4
+ /** 安全沙箱执行代码 */
5
+ async function executeInSandbox(code, timeout) {
6
+ const logs = [];
7
+ const maxOutputLength = 10000;
8
+ // 构造受限的执行上下文
9
+ const sandbox = {
10
+ console: {
11
+ log: (...args) => logs.push(args.map(String).join(' ')),
12
+ warn: (...args) => logs.push(`[WARN] ${args.map(String).join(' ')}`),
13
+ error: (...args) => logs.push(`[ERROR] ${args.map(String).join(' ')}`),
14
+ },
15
+ Math,
16
+ JSON,
17
+ Date,
18
+ Array,
19
+ Object,
20
+ String,
21
+ Number,
22
+ Boolean,
23
+ RegExp,
24
+ Map,
25
+ Set,
26
+ parseInt,
27
+ parseFloat,
28
+ isNaN,
29
+ isFinite,
30
+ encodeURIComponent,
31
+ decodeURIComponent,
32
+ };
33
+ try {
34
+ // 使用 Function 构造器在受限作用域中执行
35
+ const paramNames = Object.keys(sandbox);
36
+ const paramValues = Object.values(sandbox);
37
+ const fn = new Function(...paramNames, `"use strict";\n${code}`);
38
+ // 超时控制
39
+ const result = await Promise.race([
40
+ Promise.resolve(fn(...paramValues)),
41
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`执行超时 (${timeout}ms)`)), timeout)),
42
+ ]);
43
+ const stdout = logs.join('\n').slice(0, maxOutputLength);
44
+ return { result, stdout };
45
+ }
46
+ catch (e) {
47
+ return {
48
+ result: null,
49
+ stdout: logs.join('\n').slice(0, maxOutputLength),
50
+ error: e.message || String(e),
51
+ };
52
+ }
53
+ }
54
+ /** 代码执行工具 */
55
+ exports.executeCodeTool = {
56
+ id: 'execute_code',
57
+ name: '执行代码',
58
+ description: '在安全沙箱中执行 JavaScript 代码片段。可用于数据计算、格式转换、统计分析等。支持 Math、JSON、Date、Array、Object 等标准库。使用 console.log 输出中间结果。',
59
+ category: 'compute',
60
+ parameters: {
61
+ type: 'object',
62
+ properties: {
63
+ code: {
64
+ type: 'string',
65
+ description: 'JavaScript 代码。最后一行表达式或 return 语句的值作为返回结果。',
66
+ },
67
+ language: {
68
+ type: 'string',
69
+ description: '编程语言(当前仅支持 javascript)',
70
+ enum: ['javascript'],
71
+ default: 'javascript',
72
+ },
73
+ timeout: {
74
+ type: 'integer',
75
+ description: '执行超时时间(毫秒),默认 5000,最大 30000',
76
+ minimum: 1000,
77
+ maximum: 30000,
78
+ default: 5000,
79
+ },
80
+ },
81
+ required: ['code'],
82
+ },
83
+ async execute(input) {
84
+ const timeout = Math.min(Math.max(Number(input.timeout) || 5000, 1000), 30000);
85
+ return executeInSandbox(input.code, timeout);
86
+ },
87
+ };
88
+ /** 数据分析工具(基于代码执行) */
89
+ exports.analyzeDataTool = {
90
+ id: 'analyze_data',
91
+ name: '数据分析',
92
+ description: '对输入的数据执行分析操作。支持:统计摘要(sum/avg/min/max/count)、排序、过滤、分组聚合等。',
93
+ category: 'compute',
94
+ parameters: {
95
+ type: 'object',
96
+ properties: {
97
+ data: {
98
+ type: 'string',
99
+ description: 'JSON 格式的数据(数组或对象)',
100
+ },
101
+ operation: {
102
+ type: 'string',
103
+ description: '分析操作类型',
104
+ enum: [
105
+ 'summary',
106
+ 'sort',
107
+ 'filter',
108
+ 'group',
109
+ 'transform',
110
+ 'custom',
111
+ ],
112
+ },
113
+ description: {
114
+ type: 'string',
115
+ description: '分析目标的自然语言描述,如"按月份分组计算总营收"',
116
+ },
117
+ },
118
+ required: ['data', 'operation'],
119
+ },
120
+ async execute(input) {
121
+ try {
122
+ const data = typeof input.data === 'string'
123
+ ? JSON.parse(input.data)
124
+ : input.data;
125
+ if (!Array.isArray(data)) {
126
+ return { error: 'data 必须是 JSON 数组格式' };
127
+ }
128
+ const result = {
129
+ operation: input.operation,
130
+ rowCount: data.length,
131
+ };
132
+ switch (input.operation) {
133
+ case 'summary': {
134
+ if (!data.length)
135
+ return { ...result, summary: '空数据集' };
136
+ const numericKeys = Object.keys(data[0]).filter(k => typeof data[0][k] === 'number');
137
+ const summary = {};
138
+ for (const key of numericKeys) {
139
+ const values = data.map(row => Number(row[key] || 0));
140
+ summary[key] = {
141
+ sum: values.reduce((a, b) => a + b, 0),
142
+ avg: values.reduce((a, b) => a + b, 0) /
143
+ values.length,
144
+ min: Math.min(...values),
145
+ max: Math.max(...values),
146
+ count: values.length,
147
+ };
148
+ }
149
+ result.summary = summary;
150
+ break;
151
+ }
152
+ default:
153
+ result.hint = `操作 "${input.operation}" 的详细实现待完善,请使用 execute_code 工具自定义分析逻辑。`;
154
+ result.sampleData = data.slice(0, 5);
155
+ }
156
+ return result;
157
+ }
158
+ catch (e) {
159
+ return { error: `数据分析失败: ${e.message}` };
160
+ }
161
+ },
162
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 日期时间工具
3
+ *
4
+ * 让 Agent 能够执行各种日期时间操作:格式化、解析、计算、时区转换等。
5
+ *
6
+ * 工具说明:
7
+ * - datetime_format:日期时间格式化与解析
8
+ * - datetime_calc:日期时间计算(加减、差值、范围)
9
+ *
10
+ * 特性:
11
+ * - 支持多种输入格式(ISO 8601、时间戳、自然语言描述)
12
+ * - 支持常见时区转换(UTC、Asia/Shanghai、America/New_York 等)
13
+ * - 支持日期加减运算(年/月/日/时/分/秒)
14
+ * - 支持日期差值计算
15
+ * - 支持工作日/周末判断、季度/周数计算
16
+ */
17
+ import type { ToolDefinition } from '../types';
18
+ /** 日期时间格式化工具 */
19
+ export declare const datetimeFormatTool: ToolDefinition;
20
+ /** 日期时间计算工具 */
21
+ export declare const datetimeCalcTool: ToolDefinition;