@amical/aiagent-sdk 0.1.10 → 0.1.11

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.
@@ -1,5 +1,5 @@
1
1
  import { IApiHandler, ApiProviderInfo, AgentMessage, ApiStreamChunk, IPromptManager, IMcpManager, McpServerInfo, McpTool, McpToolCallResult, IAgentRuntime, ClineAgent } from '../index.mjs';
2
- export { AgentDefaultTool, AgentOptions, AgentState, AssistantMessageContent, IMemoryManager, READ_ONLY_TOOLS, ReasoningStreamContent, TOOL_RESULT_BLOCK, TextStreamContent, ToolParamName, ToolUse, VERSION, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames } from '../index.mjs';
2
+ export { AgentDefaultTool, AgentOptions, AgentState, AssistantMessageContent, CustomToolDefinition, IMemoryManager, READ_ONLY_TOOLS, ReasoningStreamContent, TOOL_RESULT_BLOCK, TextStreamContent, ToolParamName, ToolUse, VERSION, collectCustomToolNames, defaultTools, getToolUseNames, isCustomToolGroup, parseAssistantMessageV2, renderCustomToolPrompt, renderCustomToolsPrompt, setDynamicToolUseNames, toolParamNames, toolUseNames } from '../index.mjs';
3
3
  import { W as WebMemoryManager } from '../WebMemoryManager-Bk19j8i6.mjs';
4
4
 
5
5
  interface WebApiHandlerConfig {
@@ -1,5 +1,5 @@
1
1
  import { IApiHandler, ApiProviderInfo, AgentMessage, ApiStreamChunk, IPromptManager, IMcpManager, McpServerInfo, McpTool, McpToolCallResult, IAgentRuntime, ClineAgent } from '../index.js';
2
- export { AgentDefaultTool, AgentOptions, AgentState, AssistantMessageContent, IMemoryManager, READ_ONLY_TOOLS, ReasoningStreamContent, TOOL_RESULT_BLOCK, TextStreamContent, ToolParamName, ToolUse, VERSION, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames } from '../index.js';
2
+ export { AgentDefaultTool, AgentOptions, AgentState, AssistantMessageContent, CustomToolDefinition, IMemoryManager, READ_ONLY_TOOLS, ReasoningStreamContent, TOOL_RESULT_BLOCK, TextStreamContent, ToolParamName, ToolUse, VERSION, collectCustomToolNames, defaultTools, getToolUseNames, isCustomToolGroup, parseAssistantMessageV2, renderCustomToolPrompt, renderCustomToolsPrompt, setDynamicToolUseNames, toolParamNames, toolUseNames } from '../index.js';
3
3
  import { W as WebMemoryManager } from '../WebMemoryManager-DXxLUDBB.js';
4
4
 
5
5
  interface WebApiHandlerConfig {
@@ -491,6 +491,44 @@ var toolParamNames = [
491
491
  "start_line",
492
492
  "end_line"
493
493
  ];
494
+
495
+ // src/shared/custom-tools.ts
496
+ function isCustomToolGroup(tool) {
497
+ return Array.isArray(tool.children) && tool.children.length > 0;
498
+ }
499
+ function collectCustomToolNames(tools) {
500
+ const names = [];
501
+ const visit = (list) => {
502
+ for (const tool of list) {
503
+ names.push(tool.name);
504
+ if (Array.isArray(tool.children) && tool.children.length > 0) {
505
+ visit(tool.children);
506
+ }
507
+ }
508
+ };
509
+ visit(tools);
510
+ return names;
511
+ }
512
+ function renderCustomToolPrompt(tool, cwd = "") {
513
+ const params = tool.params ? Object.entries(tool.params) : [];
514
+ const replaceCwd = (text) => String(text).replaceAll("${context.cwd}", cwd);
515
+ const paramLines = params.map(([name, description]) => `- ${name}: ${replaceCwd(description)}`).join("\n");
516
+ const usageLines = params.map(([name, description]) => `<${name}>${replaceCwd(description)}</${name}>`).join("\n");
517
+ return `### ${tool.name}
518
+ Description: ${tool.description}
519
+ Parameters:
520
+ ${paramLines}
521
+ - task_progress: (optional) A checklist showing task progress after this tool use is completed. The task_progress parameter must be included as a separate parameter inside of the parent tool call, it must be separate from other parameters such as content, arguments, etc. (See 'UPDATING TASK PROGRESS' section for more details)
522
+ Usage:
523
+ <${tool.name}>
524
+ ${usageLines}
525
+ <task_progress>Checklist here (optional)</task_progress>
526
+ </${tool.name}>
527
+ `;
528
+ }
529
+ function renderCustomToolsPrompt(tools, cwd = "") {
530
+ return tools.map((tool) => renderCustomToolPrompt(tool, cwd)).join("\n");
531
+ }
494
532
  var TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
495
533
  "txt",
496
534
  "md",
@@ -574,9 +612,19 @@ var ClineAgent = class {
574
612
  skillDir;
575
613
  rulesDir;
576
614
  customTools;
615
+ /** 当前可用(已展开集合)的顶层工具列表,传给 PromptManager 渲染 */
616
+ activeCustomTools;
617
+ /** 所有已知工具名(含未激活 children),便于查找定义 */
618
+ customToolsByName;
577
619
  customToolNames;
578
620
  allowDefaultTools;
579
621
  customInstructions;
622
+ /** 已激活的工具集入口名 */
623
+ activatedGroups = /* @__PURE__ */ new Set();
624
+ /** activeCustomTools 变更版本号,用于 Prompt 缓存失效 */
625
+ activeToolsVersion = 0;
626
+ /** 缓存 sysPrompt 时记录的版本号 */
627
+ promptActiveToolsVersion = -1;
580
628
  sysPrompt;
581
629
  noUseTollSysPrompt;
582
630
  // 简单的事件回调系统,供宿主环境注册以监听 Agent 内部事件
@@ -596,31 +644,38 @@ var ClineAgent = class {
596
644
  this.allowDefaultTools.push("agent_attempt_completion" /* ATTEMPT */);
597
645
  }
598
646
  this.customInstructions = options.customInstructions;
647
+ this.customToolsByName = /* @__PURE__ */ new Map();
648
+ this.activeCustomTools = [...this.customTools];
649
+ this.customToolNames = new Set(collectCustomToolNames(this.customTools));
599
650
  if (this.customTools.length > 0) {
600
- const dynamicToolNames = /* @__PURE__ */ new Set();
601
651
  const customToolParams = /* @__PURE__ */ new Set();
602
- for (const customTool of this.customTools) {
603
- dynamicToolNames.add(customTool.name);
604
- if (customTool.params) {
605
- for (const key in customTool.params) {
606
- if (!Object.hasOwn(customTool.params, key)) continue;
607
- customToolParams.add(key);
652
+ const visit = (tools) => {
653
+ for (const customTool of tools) {
654
+ this.customToolsByName.set(customTool.name, customTool);
655
+ if (customTool.params) {
656
+ for (const key in customTool.params) {
657
+ if (!Object.hasOwn(customTool.params, key)) continue;
658
+ customToolParams.add(key);
659
+ }
660
+ }
661
+ if (Array.isArray(customTool.children) && customTool.children.length > 0) {
662
+ visit(customTool.children);
608
663
  }
609
664
  }
610
- }
665
+ };
666
+ visit(this.customTools);
611
667
  const defaultToolNames = Object.values(AgentDefaultTool);
612
- const overlappingTools = Array.from(dynamicToolNames).filter((name) => defaultToolNames.includes(name));
668
+ const overlappingTools = Array.from(this.customToolNames).filter((name) => defaultToolNames.includes(name));
613
669
  if (overlappingTools.length > 0) {
614
670
  throw new Error(`Custom tools and default tools have overlapping names: ${overlappingTools.join(", ")}`);
615
671
  }
616
- if (dynamicToolNames.size > 0) {
617
- setDynamicToolUseNames("customUser", Array.from(dynamicToolNames));
672
+ if (this.customToolNames.size > 0) {
673
+ setDynamicToolUseNames("customUser", Array.from(this.customToolNames));
618
674
  }
619
675
  if (customToolParams.size > 0) {
620
676
  this.allToolParamNames = Array.from(/* @__PURE__ */ new Set([...this.allToolParamNames, ...Array.from(customToolParams)]));
621
677
  }
622
678
  }
623
- this.customToolNames = new Set(this.customTools.map((t) => t.name));
624
679
  this.skillDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/skills");
625
680
  this.rulesDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/rules");
626
681
  }
@@ -644,10 +699,11 @@ var ClineAgent = class {
644
699
  shell: this.runtime.env.shell(),
645
700
  skills: await this.getSkills(),
646
701
  agentRules: await this.getAgentRules(),
647
- customTools: this.customTools,
702
+ customTools: this.activeCustomTools,
648
703
  allowDefaultTools: this.allowDefaultTools,
649
704
  customInstructions: this.customInstructions
650
705
  };
706
+ this.promptActiveToolsVersion = this.activeToolsVersion;
651
707
  this.sysPrompt = await this.promptManager.getSystemPrompt(context);
652
708
  this.noUseTollSysPrompt = this.promptManager.getNoUseToolInstructions(context);
653
709
  return { sysPrompt: this.sysPrompt, noUseTollSysPrompt: this.noUseTollSysPrompt };
@@ -756,9 +812,9 @@ ${content.trim()}\`\`\``);
756
812
  * 核心任务循环
757
813
  */
758
814
  async loop() {
759
- const { sysPrompt, noUseTollSysPrompt } = await this.getPrompt(true);
760
- const { customTools, customToolNames } = this;
815
+ const { customToolsByName, customToolNames } = this;
761
816
  while (this.state === "thinking" /* THINKING */) {
817
+ const { sysPrompt, noUseTollSysPrompt } = await this.getCurrentPrompt();
762
818
  this.loopCount++;
763
819
  if (this.loopCount > this.maxLoopCount) {
764
820
  await this.memory.appendMessage({
@@ -803,7 +859,33 @@ ${content.trim()}\`\`\``);
803
859
  }
804
860
  }
805
861
  if (customToolNames.has(tool.name)) {
806
- const customTool = customTools.find((t) => t.name === tool.name);
862
+ const customTool = customToolsByName.get(tool.name);
863
+ if (!customTool) {
864
+ toolResults.push({ tool, result: `Error: Custom tool "${tool.name}" not found.` });
865
+ continue;
866
+ }
867
+ if (isCustomToolGroup(customTool)) {
868
+ let groupResult;
869
+ if (customTool.onCall) {
870
+ try {
871
+ groupResult = await customTool.onCall(tool.params);
872
+ } catch (error) {
873
+ toolResults.push({ tool, result: `Error: ${error.message}` });
874
+ continue;
875
+ }
876
+ }
877
+ const childrenPrompt = this.activateCustomToolGroup(customTool);
878
+ const finalPrompt = `# New Available Tools
879
+
880
+ The following are instructions for using the new available tools.
881
+
882
+ ${childrenPrompt}`;
883
+ const promptBlock = groupResult !== void 0 ? `${typeof groupResult === "string" ? groupResult : JSON.stringify(groupResult)}
884
+
885
+ ${finalPrompt}` : finalPrompt;
886
+ toolResults.push({ tool, result: promptBlock });
887
+ continue;
888
+ }
807
889
  if (customTool.onCall) {
808
890
  try {
809
891
  const res = await customTool.onCall(tool.params);
@@ -1064,6 +1146,27 @@ ${this.promptManager.getUsedToolResultInstructions()}`;
1064
1146
  }
1065
1147
  }
1066
1148
  }
1149
+ /**
1150
+ * 激活自定义工具集:将入口的 children 注册到活跃工具列表并返回渲染后的 prompt。
1151
+ */
1152
+ activateCustomToolGroup(group) {
1153
+ if (this.activatedGroups.has(group.name)) {
1154
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1155
+ }
1156
+ this.activatedGroups.add(group.name);
1157
+ this.activeCustomTools = [...this.activeCustomTools, ...group.children || []];
1158
+ this.activeToolsVersion++;
1159
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1160
+ }
1161
+ /**
1162
+ * 检查自上次获取 prompt 后是否有工具集被激活,若有则刷新缓存。
1163
+ */
1164
+ async getCurrentPrompt() {
1165
+ if (this.promptActiveToolsVersion !== this.activeToolsVersion) {
1166
+ return this.getPrompt(true);
1167
+ }
1168
+ return this.getPrompt();
1169
+ }
1067
1170
  /**
1068
1171
  * 简单的 Diff 解析与替换辅助方法
1069
1172
  */
@@ -1425,10 +1528,11 @@ ${context.customInstructions}
1425
1528
  if (allowDefaultTools) {
1426
1529
  useDefaultTools = defaultTools.filter((tool) => allowDefaultTools.includes(tool.name));
1427
1530
  }
1531
+ const renderedCustomTools = renderCustomToolsPrompt(customTools, context.cwd);
1428
1532
  return `# Available Tools
1429
1533
  You can use the following tools by formatting your output as XML blocks. Only use ONE tool per message, and ALWAYS wait for the user's response with the execution result before proceeding.
1430
1534
 
1431
- ${[...useDefaultTools, ...customTools].map((tool) => {
1535
+ ${[...useDefaultTools].map((tool) => {
1432
1536
  return `### ${tool.name}
1433
1537
  Description: ${tool.description}
1434
1538
  Parameters:
@@ -1441,6 +1545,8 @@ ${Object.entries(tool.params).map(([name, description]) => `<${name}>${descripti
1441
1545
  </${tool.name}>
1442
1546
  `;
1443
1547
  }).join("\n")}
1548
+ ${renderedCustomTools ? `
1549
+ ${renderedCustomTools}` : ""}
1444
1550
 
1445
1551
  # Tool Use Examples
1446
1552
  ${useDefaultTools.filter((item) => Boolean(item.example)).map((item) => item.example).join("\n")}}
@@ -1807,10 +1913,14 @@ exports.WebApiHandler = WebApiHandler;
1807
1913
  exports.WebMcpManager = WebMcpManager;
1808
1914
  exports.WebMemoryManager = WebMemoryManager;
1809
1915
  exports.WebPromptManager = WebPromptManager;
1916
+ exports.collectCustomToolNames = collectCustomToolNames;
1810
1917
  exports.createWebAgent = createWebAgent;
1811
1918
  exports.defaultTools = defaultTools;
1812
1919
  exports.getToolUseNames = getToolUseNames;
1920
+ exports.isCustomToolGroup = isCustomToolGroup;
1813
1921
  exports.parseAssistantMessageV2 = parseAssistantMessageV2;
1922
+ exports.renderCustomToolPrompt = renderCustomToolPrompt;
1923
+ exports.renderCustomToolsPrompt = renderCustomToolsPrompt;
1814
1924
  exports.setDynamicToolUseNames = setDynamicToolUseNames;
1815
1925
  exports.toolParamNames = toolParamNames;
1816
1926
  exports.toolUseNames = toolUseNames;