@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.
@@ -489,6 +489,44 @@ var toolParamNames = [
489
489
  "start_line",
490
490
  "end_line"
491
491
  ];
492
+
493
+ // src/shared/custom-tools.ts
494
+ function isCustomToolGroup(tool) {
495
+ return Array.isArray(tool.children) && tool.children.length > 0;
496
+ }
497
+ function collectCustomToolNames(tools) {
498
+ const names = [];
499
+ const visit = (list) => {
500
+ for (const tool of list) {
501
+ names.push(tool.name);
502
+ if (Array.isArray(tool.children) && tool.children.length > 0) {
503
+ visit(tool.children);
504
+ }
505
+ }
506
+ };
507
+ visit(tools);
508
+ return names;
509
+ }
510
+ function renderCustomToolPrompt(tool, cwd = "") {
511
+ const params = tool.params ? Object.entries(tool.params) : [];
512
+ const replaceCwd = (text) => String(text).replaceAll("${context.cwd}", cwd);
513
+ const paramLines = params.map(([name, description]) => `- ${name}: ${replaceCwd(description)}`).join("\n");
514
+ const usageLines = params.map(([name, description]) => `<${name}>${replaceCwd(description)}</${name}>`).join("\n");
515
+ return `### ${tool.name}
516
+ Description: ${tool.description}
517
+ Parameters:
518
+ ${paramLines}
519
+ - 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)
520
+ Usage:
521
+ <${tool.name}>
522
+ ${usageLines}
523
+ <task_progress>Checklist here (optional)</task_progress>
524
+ </${tool.name}>
525
+ `;
526
+ }
527
+ function renderCustomToolsPrompt(tools, cwd = "") {
528
+ return tools.map((tool) => renderCustomToolPrompt(tool, cwd)).join("\n");
529
+ }
492
530
  var TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
493
531
  "txt",
494
532
  "md",
@@ -572,9 +610,19 @@ var ClineAgent = class {
572
610
  skillDir;
573
611
  rulesDir;
574
612
  customTools;
613
+ /** 当前可用(已展开集合)的顶层工具列表,传给 PromptManager 渲染 */
614
+ activeCustomTools;
615
+ /** 所有已知工具名(含未激活 children),便于查找定义 */
616
+ customToolsByName;
575
617
  customToolNames;
576
618
  allowDefaultTools;
577
619
  customInstructions;
620
+ /** 已激活的工具集入口名 */
621
+ activatedGroups = /* @__PURE__ */ new Set();
622
+ /** activeCustomTools 变更版本号,用于 Prompt 缓存失效 */
623
+ activeToolsVersion = 0;
624
+ /** 缓存 sysPrompt 时记录的版本号 */
625
+ promptActiveToolsVersion = -1;
578
626
  sysPrompt;
579
627
  noUseTollSysPrompt;
580
628
  // 简单的事件回调系统,供宿主环境注册以监听 Agent 内部事件
@@ -594,31 +642,38 @@ var ClineAgent = class {
594
642
  this.allowDefaultTools.push("agent_attempt_completion" /* ATTEMPT */);
595
643
  }
596
644
  this.customInstructions = options.customInstructions;
645
+ this.customToolsByName = /* @__PURE__ */ new Map();
646
+ this.activeCustomTools = [...this.customTools];
647
+ this.customToolNames = new Set(collectCustomToolNames(this.customTools));
597
648
  if (this.customTools.length > 0) {
598
- const dynamicToolNames = /* @__PURE__ */ new Set();
599
649
  const customToolParams = /* @__PURE__ */ new Set();
600
- for (const customTool of this.customTools) {
601
- dynamicToolNames.add(customTool.name);
602
- if (customTool.params) {
603
- for (const key in customTool.params) {
604
- if (!Object.hasOwn(customTool.params, key)) continue;
605
- customToolParams.add(key);
650
+ const visit = (tools) => {
651
+ for (const customTool of tools) {
652
+ this.customToolsByName.set(customTool.name, customTool);
653
+ if (customTool.params) {
654
+ for (const key in customTool.params) {
655
+ if (!Object.hasOwn(customTool.params, key)) continue;
656
+ customToolParams.add(key);
657
+ }
658
+ }
659
+ if (Array.isArray(customTool.children) && customTool.children.length > 0) {
660
+ visit(customTool.children);
606
661
  }
607
662
  }
608
- }
663
+ };
664
+ visit(this.customTools);
609
665
  const defaultToolNames = Object.values(AgentDefaultTool);
610
- const overlappingTools = Array.from(dynamicToolNames).filter((name) => defaultToolNames.includes(name));
666
+ const overlappingTools = Array.from(this.customToolNames).filter((name) => defaultToolNames.includes(name));
611
667
  if (overlappingTools.length > 0) {
612
668
  throw new Error(`Custom tools and default tools have overlapping names: ${overlappingTools.join(", ")}`);
613
669
  }
614
- if (dynamicToolNames.size > 0) {
615
- setDynamicToolUseNames("customUser", Array.from(dynamicToolNames));
670
+ if (this.customToolNames.size > 0) {
671
+ setDynamicToolUseNames("customUser", Array.from(this.customToolNames));
616
672
  }
617
673
  if (customToolParams.size > 0) {
618
674
  this.allToolParamNames = Array.from(/* @__PURE__ */ new Set([...this.allToolParamNames, ...Array.from(customToolParams)]));
619
675
  }
620
676
  }
621
- this.customToolNames = new Set(this.customTools.map((t) => t.name));
622
677
  this.skillDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/skills");
623
678
  this.rulesDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/rules");
624
679
  }
@@ -642,10 +697,11 @@ var ClineAgent = class {
642
697
  shell: this.runtime.env.shell(),
643
698
  skills: await this.getSkills(),
644
699
  agentRules: await this.getAgentRules(),
645
- customTools: this.customTools,
700
+ customTools: this.activeCustomTools,
646
701
  allowDefaultTools: this.allowDefaultTools,
647
702
  customInstructions: this.customInstructions
648
703
  };
704
+ this.promptActiveToolsVersion = this.activeToolsVersion;
649
705
  this.sysPrompt = await this.promptManager.getSystemPrompt(context);
650
706
  this.noUseTollSysPrompt = this.promptManager.getNoUseToolInstructions(context);
651
707
  return { sysPrompt: this.sysPrompt, noUseTollSysPrompt: this.noUseTollSysPrompt };
@@ -754,9 +810,9 @@ ${content.trim()}\`\`\``);
754
810
  * 核心任务循环
755
811
  */
756
812
  async loop() {
757
- const { sysPrompt, noUseTollSysPrompt } = await this.getPrompt(true);
758
- const { customTools, customToolNames } = this;
813
+ const { customToolsByName, customToolNames } = this;
759
814
  while (this.state === "thinking" /* THINKING */) {
815
+ const { sysPrompt, noUseTollSysPrompt } = await this.getCurrentPrompt();
760
816
  this.loopCount++;
761
817
  if (this.loopCount > this.maxLoopCount) {
762
818
  await this.memory.appendMessage({
@@ -801,7 +857,33 @@ ${content.trim()}\`\`\``);
801
857
  }
802
858
  }
803
859
  if (customToolNames.has(tool.name)) {
804
- const customTool = customTools.find((t) => t.name === tool.name);
860
+ const customTool = customToolsByName.get(tool.name);
861
+ if (!customTool) {
862
+ toolResults.push({ tool, result: `Error: Custom tool "${tool.name}" not found.` });
863
+ continue;
864
+ }
865
+ if (isCustomToolGroup(customTool)) {
866
+ let groupResult;
867
+ if (customTool.onCall) {
868
+ try {
869
+ groupResult = await customTool.onCall(tool.params);
870
+ } catch (error) {
871
+ toolResults.push({ tool, result: `Error: ${error.message}` });
872
+ continue;
873
+ }
874
+ }
875
+ const childrenPrompt = this.activateCustomToolGroup(customTool);
876
+ const finalPrompt = `# New Available Tools
877
+
878
+ The following are instructions for using the new available tools.
879
+
880
+ ${childrenPrompt}`;
881
+ const promptBlock = groupResult !== void 0 ? `${typeof groupResult === "string" ? groupResult : JSON.stringify(groupResult)}
882
+
883
+ ${finalPrompt}` : finalPrompt;
884
+ toolResults.push({ tool, result: promptBlock });
885
+ continue;
886
+ }
805
887
  if (customTool.onCall) {
806
888
  try {
807
889
  const res = await customTool.onCall(tool.params);
@@ -1062,6 +1144,27 @@ ${this.promptManager.getUsedToolResultInstructions()}`;
1062
1144
  }
1063
1145
  }
1064
1146
  }
1147
+ /**
1148
+ * 激活自定义工具集:将入口的 children 注册到活跃工具列表并返回渲染后的 prompt。
1149
+ */
1150
+ activateCustomToolGroup(group) {
1151
+ if (this.activatedGroups.has(group.name)) {
1152
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1153
+ }
1154
+ this.activatedGroups.add(group.name);
1155
+ this.activeCustomTools = [...this.activeCustomTools, ...group.children || []];
1156
+ this.activeToolsVersion++;
1157
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1158
+ }
1159
+ /**
1160
+ * 检查自上次获取 prompt 后是否有工具集被激活,若有则刷新缓存。
1161
+ */
1162
+ async getCurrentPrompt() {
1163
+ if (this.promptActiveToolsVersion !== this.activeToolsVersion) {
1164
+ return this.getPrompt(true);
1165
+ }
1166
+ return this.getPrompt();
1167
+ }
1065
1168
  /**
1066
1169
  * 简单的 Diff 解析与替换辅助方法
1067
1170
  */
@@ -1423,10 +1526,11 @@ ${context.customInstructions}
1423
1526
  if (allowDefaultTools) {
1424
1527
  useDefaultTools = defaultTools.filter((tool) => allowDefaultTools.includes(tool.name));
1425
1528
  }
1529
+ const renderedCustomTools = renderCustomToolsPrompt(customTools, context.cwd);
1426
1530
  return `# Available Tools
1427
1531
  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.
1428
1532
 
1429
- ${[...useDefaultTools, ...customTools].map((tool) => {
1533
+ ${[...useDefaultTools].map((tool) => {
1430
1534
  return `### ${tool.name}
1431
1535
  Description: ${tool.description}
1432
1536
  Parameters:
@@ -1439,6 +1543,8 @@ ${Object.entries(tool.params).map(([name, description]) => `<${name}>${descripti
1439
1543
  </${tool.name}>
1440
1544
  `;
1441
1545
  }).join("\n")}
1546
+ ${renderedCustomTools ? `
1547
+ ${renderedCustomTools}` : ""}
1442
1548
 
1443
1549
  # Tool Use Examples
1444
1550
  ${useDefaultTools.filter((item) => Boolean(item.example)).map((item) => item.example).join("\n")}}
@@ -1875,6 +1981,6 @@ function createNodeAgent(options) {
1875
1981
  return agent;
1876
1982
  }
1877
1983
 
1878
- export { AgentDefaultTool, AgentState, ClineAgent, DefaultNodeRuntime, NodeApiHandler, NodeMcpManager, NodeMemoryManager, NodePromptManager, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, createNodeAgent, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames };
1984
+ export { AgentDefaultTool, AgentState, ClineAgent, DefaultNodeRuntime, NodeApiHandler, NodeMcpManager, NodeMemoryManager, NodePromptManager, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, collectCustomToolNames, createNodeAgent, defaultTools, getToolUseNames, isCustomToolGroup, parseAssistantMessageV2, renderCustomToolPrompt, renderCustomToolsPrompt, setDynamicToolUseNames, toolParamNames, toolUseNames };
1879
1985
  //# sourceMappingURL=nodeRuntime.mjs.map
1880
1986
  //# sourceMappingURL=nodeRuntime.mjs.map