@amical/aiagent-sdk 0.1.9 → 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.
package/dist/index.mjs CHANGED
@@ -12,6 +12,7 @@ var AgentDefaultTool = /* @__PURE__ */ ((AgentDefaultTool2) => {
12
12
  AgentDefaultTool2["FILE_DELETE"] = "agent_delete_file";
13
13
  AgentDefaultTool2["DIR_DELETE"] = "agent_delete_directory";
14
14
  AgentDefaultTool2["SEARCH"] = "agent_search_files";
15
+ AgentDefaultTool2["SEARCH_CONTENT"] = "agent_search_file_content";
15
16
  AgentDefaultTool2["LIST_FILES"] = "agent_list_files";
16
17
  AgentDefaultTool2["LIST_CODE_DEF"] = "agent_list_code_definition_names";
17
18
  AgentDefaultTool2["BROWSER"] = "agent_browser_action";
@@ -185,11 +186,22 @@ return (
185
186
  },
186
187
  {
187
188
  name: "agent_search_files" /* SEARCH */,
188
- description: "Search for files in a directory that match a regex pattern or glob pattern.",
189
+ description: "Search for files or directories by name in a directory tree, matching the name against a regex (and optionally a glob). Directories are traversed level by level: all matches in the current level are returned before descending into deeper levels. Use this tool only to locate files/directories by name.",
189
190
  params: {
190
191
  path: "(required) The absolute or relative directory path to search.",
191
- regex: "(required) The regex pattern to match files against.",
192
- file_pattern: "(optional) glob pattern like *.ts."
192
+ regex: "(required) The regex pattern to match file or directory names against.",
193
+ file_pattern: "(optional) glob pattern like *.ts.",
194
+ include_node_modules: "(optional) set to true to include node_modules in the search. Defaults to false, so node_modules is skipped."
195
+ }
196
+ },
197
+ {
198
+ name: "agent_search_file_content" /* SEARCH_CONTENT */,
199
+ description: "Search the contents of files in a directory tree for a regex pattern. Use this tool when you need to find text or code inside files rather than matching file or directory names.",
200
+ params: {
201
+ path: "(required) The absolute or relative directory path to search.",
202
+ regex: "(required) The regex pattern to match file content against.",
203
+ file_pattern: "(optional) glob pattern like *.ts to limit which files are searched.",
204
+ include_node_modules: "(optional) set to true to include node_modules in the search. Defaults to false, so node_modules is skipped."
193
205
  }
194
206
  },
195
207
  {
@@ -258,6 +270,7 @@ var READ_ONLY_TOOLS = [
258
270
  "agent_list_files" /* LIST_FILES */,
259
271
  "agent_read_file" /* FILE_READ */,
260
272
  "agent_search_files" /* SEARCH */,
273
+ "agent_search_file_content" /* SEARCH_CONTENT */,
261
274
  "agent_list_code_definition_names" /* LIST_CODE_DEF */,
262
275
  "agent_browser_action" /* BROWSER */,
263
276
  "agent_ask_followup_question" /* ASK */,
@@ -266,6 +279,44 @@ var READ_ONLY_TOOLS = [
266
279
  "agent_load_skill" /* LOAD_SKILL */,
267
280
  "agent_use_subagents" /* USE_SUBAGENTS */
268
281
  ];
282
+
283
+ // src/shared/custom-tools.ts
284
+ function isCustomToolGroup(tool) {
285
+ return Array.isArray(tool.children) && tool.children.length > 0;
286
+ }
287
+ function collectCustomToolNames(tools) {
288
+ const names = [];
289
+ const visit = (list) => {
290
+ for (const tool of list) {
291
+ names.push(tool.name);
292
+ if (Array.isArray(tool.children) && tool.children.length > 0) {
293
+ visit(tool.children);
294
+ }
295
+ }
296
+ };
297
+ visit(tools);
298
+ return names;
299
+ }
300
+ function renderCustomToolPrompt(tool, cwd = "") {
301
+ const params = tool.params ? Object.entries(tool.params) : [];
302
+ const replaceCwd = (text) => String(text).replaceAll("${context.cwd}", cwd);
303
+ const paramLines = params.map(([name, description]) => `- ${name}: ${replaceCwd(description)}`).join("\n");
304
+ const usageLines = params.map(([name, description]) => `<${name}>${replaceCwd(description)}</${name}>`).join("\n");
305
+ return `### ${tool.name}
306
+ Description: ${tool.description}
307
+ Parameters:
308
+ ${paramLines}
309
+ - 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)
310
+ Usage:
311
+ <${tool.name}>
312
+ ${usageLines}
313
+ <task_progress>Checklist here (optional)</task_progress>
314
+ </${tool.name}>
315
+ `;
316
+ }
317
+ function renderCustomToolsPrompt(tools, cwd = "") {
318
+ return tools.map((tool) => renderCustomToolPrompt(tool, cwd)).join("\n");
319
+ }
269
320
  function parseAssistantMessageV2(assistantMessage, toolParamNames2) {
270
321
  const contentBlocks = [];
271
322
  let currentTextContentStart = 0;
@@ -427,6 +478,7 @@ var toolParamNames = [
427
478
  "diff",
428
479
  "regex",
429
480
  "file_pattern",
481
+ "include_node_modules",
430
482
  "recursive",
431
483
  "action",
432
484
  "url",
@@ -465,6 +517,66 @@ var toolParamNames = [
465
517
  "start_line",
466
518
  "end_line"
467
519
  ];
520
+ var TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
521
+ "txt",
522
+ "md",
523
+ "markdown",
524
+ "json",
525
+ "js",
526
+ "mjs",
527
+ "cjs",
528
+ "ts",
529
+ "tsx",
530
+ "jsx",
531
+ "html",
532
+ "htm",
533
+ "css",
534
+ "scss",
535
+ "sass",
536
+ "less",
537
+ "py",
538
+ "java",
539
+ "c",
540
+ "cpp",
541
+ "cc",
542
+ "cxx",
543
+ "h",
544
+ "hpp",
545
+ "cs",
546
+ "go",
547
+ "rs",
548
+ "rb",
549
+ "php",
550
+ "sh",
551
+ "bash",
552
+ "zsh",
553
+ "bat",
554
+ "cmd",
555
+ "ps1",
556
+ "yaml",
557
+ "yml",
558
+ "toml",
559
+ "ini",
560
+ "cfg",
561
+ "conf",
562
+ "xml",
563
+ "svg",
564
+ "csv",
565
+ "log",
566
+ "sql",
567
+ "vue",
568
+ "svelte",
569
+ "astro",
570
+ "graphql",
571
+ "gql",
572
+ "prisma",
573
+ "env",
574
+ "gitignore",
575
+ "dockerfile",
576
+ "makefile",
577
+ "properties",
578
+ "lock"
579
+ ]);
468
580
  var AgentState = /* @__PURE__ */ ((AgentState2) => {
469
581
  AgentState2["IDLE"] = "idle";
470
582
  AgentState2["THINKING"] = "thinking";
@@ -488,9 +600,19 @@ var ClineAgent = class {
488
600
  skillDir;
489
601
  rulesDir;
490
602
  customTools;
603
+ /** 当前可用(已展开集合)的顶层工具列表,传给 PromptManager 渲染 */
604
+ activeCustomTools;
605
+ /** 所有已知工具名(含未激活 children),便于查找定义 */
606
+ customToolsByName;
491
607
  customToolNames;
492
608
  allowDefaultTools;
493
609
  customInstructions;
610
+ /** 已激活的工具集入口名 */
611
+ activatedGroups = /* @__PURE__ */ new Set();
612
+ /** activeCustomTools 变更版本号,用于 Prompt 缓存失效 */
613
+ activeToolsVersion = 0;
614
+ /** 缓存 sysPrompt 时记录的版本号 */
615
+ promptActiveToolsVersion = -1;
494
616
  sysPrompt;
495
617
  noUseTollSysPrompt;
496
618
  // 简单的事件回调系统,供宿主环境注册以监听 Agent 内部事件
@@ -510,31 +632,38 @@ var ClineAgent = class {
510
632
  this.allowDefaultTools.push("agent_attempt_completion" /* ATTEMPT */);
511
633
  }
512
634
  this.customInstructions = options.customInstructions;
635
+ this.customToolsByName = /* @__PURE__ */ new Map();
636
+ this.activeCustomTools = [...this.customTools];
637
+ this.customToolNames = new Set(collectCustomToolNames(this.customTools));
513
638
  if (this.customTools.length > 0) {
514
- const dynamicToolNames = /* @__PURE__ */ new Set();
515
639
  const customToolParams = /* @__PURE__ */ new Set();
516
- for (const customTool of this.customTools) {
517
- dynamicToolNames.add(customTool.name);
518
- if (customTool.params) {
519
- for (const key in customTool.params) {
520
- if (!Object.hasOwn(customTool.params, key)) continue;
521
- customToolParams.add(key);
640
+ const visit = (tools) => {
641
+ for (const customTool of tools) {
642
+ this.customToolsByName.set(customTool.name, customTool);
643
+ if (customTool.params) {
644
+ for (const key in customTool.params) {
645
+ if (!Object.hasOwn(customTool.params, key)) continue;
646
+ customToolParams.add(key);
647
+ }
648
+ }
649
+ if (Array.isArray(customTool.children) && customTool.children.length > 0) {
650
+ visit(customTool.children);
522
651
  }
523
652
  }
524
- }
653
+ };
654
+ visit(this.customTools);
525
655
  const defaultToolNames = Object.values(AgentDefaultTool);
526
- const overlappingTools = Array.from(dynamicToolNames).filter((name) => defaultToolNames.includes(name));
656
+ const overlappingTools = Array.from(this.customToolNames).filter((name) => defaultToolNames.includes(name));
527
657
  if (overlappingTools.length > 0) {
528
658
  throw new Error(`Custom tools and default tools have overlapping names: ${overlappingTools.join(", ")}`);
529
659
  }
530
- if (dynamicToolNames.size > 0) {
531
- setDynamicToolUseNames("customUser", Array.from(dynamicToolNames));
660
+ if (this.customToolNames.size > 0) {
661
+ setDynamicToolUseNames("customUser", Array.from(this.customToolNames));
532
662
  }
533
663
  if (customToolParams.size > 0) {
534
664
  this.allToolParamNames = Array.from(/* @__PURE__ */ new Set([...this.allToolParamNames, ...Array.from(customToolParams)]));
535
665
  }
536
666
  }
537
- this.customToolNames = new Set(this.customTools.map((t) => t.name));
538
667
  this.skillDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/skills");
539
668
  this.rulesDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/rules");
540
669
  }
@@ -558,10 +687,11 @@ var ClineAgent = class {
558
687
  shell: this.runtime.env.shell(),
559
688
  skills: await this.getSkills(),
560
689
  agentRules: await this.getAgentRules(),
561
- customTools: this.customTools,
690
+ customTools: this.activeCustomTools,
562
691
  allowDefaultTools: this.allowDefaultTools,
563
692
  customInstructions: this.customInstructions
564
693
  };
694
+ this.promptActiveToolsVersion = this.activeToolsVersion;
565
695
  this.sysPrompt = await this.promptManager.getSystemPrompt(context);
566
696
  this.noUseTollSysPrompt = this.promptManager.getNoUseToolInstructions(context);
567
697
  return { sysPrompt: this.sysPrompt, noUseTollSysPrompt: this.noUseTollSysPrompt };
@@ -670,9 +800,9 @@ ${content.trim()}\`\`\``);
670
800
  * 核心任务循环
671
801
  */
672
802
  async loop() {
673
- const { sysPrompt, noUseTollSysPrompt } = await this.getPrompt(true);
674
- const { customTools, customToolNames } = this;
803
+ const { customToolsByName, customToolNames } = this;
675
804
  while (this.state === "thinking" /* THINKING */) {
805
+ const { sysPrompt, noUseTollSysPrompt } = await this.getCurrentPrompt();
676
806
  this.loopCount++;
677
807
  if (this.loopCount > this.maxLoopCount) {
678
808
  await this.memory.appendMessage({
@@ -717,7 +847,33 @@ ${content.trim()}\`\`\``);
717
847
  }
718
848
  }
719
849
  if (customToolNames.has(tool.name)) {
720
- const customTool = customTools.find((t) => t.name === tool.name);
850
+ const customTool = customToolsByName.get(tool.name);
851
+ if (!customTool) {
852
+ toolResults.push({ tool, result: `Error: Custom tool "${tool.name}" not found.` });
853
+ continue;
854
+ }
855
+ if (isCustomToolGroup(customTool)) {
856
+ let groupResult;
857
+ if (customTool.onCall) {
858
+ try {
859
+ groupResult = await customTool.onCall(tool.params);
860
+ } catch (error) {
861
+ toolResults.push({ tool, result: `Error: ${error.message}` });
862
+ continue;
863
+ }
864
+ }
865
+ const childrenPrompt = this.activateCustomToolGroup(customTool);
866
+ const finalPrompt = `# New Available Tools
867
+
868
+ The following are instructions for using the new available tools.
869
+
870
+ ${childrenPrompt}`;
871
+ const promptBlock = groupResult !== void 0 ? `${typeof groupResult === "string" ? groupResult : JSON.stringify(groupResult)}
872
+
873
+ ${finalPrompt}` : finalPrompt;
874
+ toolResults.push({ tool, result: promptBlock });
875
+ continue;
876
+ }
721
877
  if (customTool.onCall) {
722
878
  try {
723
879
  const res = await customTool.onCall(tool.params);
@@ -820,15 +976,36 @@ STDERR: ${result.stderr}` });
820
976
  const path = tool.params.path || this.runtime.env.cwd();
821
977
  const regexStr = tool.params.regex;
822
978
  const filePattern = tool.params.file_pattern;
979
+ const includeNodeModules = tool.params.include_node_modules === "true";
823
980
  if (regexStr && path) {
824
981
  try {
825
982
  let result;
826
983
  if (typeof this.runtime.fs.searchFiles === "function") {
827
984
  result = await this.runtime.fs.searchFiles(path, regexStr, filePattern);
828
985
  } else {
829
- result = await this.searchFiles(path, regexStr, filePattern);
986
+ result = await this.searchFiles(path, regexStr, filePattern, includeNodeModules);
830
987
  }
831
- toolResults.push({ tool, result: `${result}` });
988
+ toolResults.push({ tool, result });
989
+ } catch (e) {
990
+ toolResults.push({ tool, result: `Error: ${e.message}` });
991
+ }
992
+ } else {
993
+ toolResults.push({ tool, result: `Error: miss path or regex params` });
994
+ }
995
+ } else if (tool.name === "agent_search_file_content" /* SEARCH_CONTENT */) {
996
+ const path = tool.params.path || this.runtime.env.cwd();
997
+ const regexStr = tool.params.regex;
998
+ const filePattern = tool.params.file_pattern;
999
+ const includeNodeModules = tool.params.include_node_modules === "true";
1000
+ if (regexStr && path) {
1001
+ try {
1002
+ let result;
1003
+ if (typeof this.runtime.fs.searchFileContent === "function") {
1004
+ result = await this.runtime.fs.searchFileContent(path, regexStr, filePattern);
1005
+ } else {
1006
+ result = await this.searchFileContent(path, regexStr, filePattern, includeNodeModules);
1007
+ }
1008
+ toolResults.push({ tool, result });
832
1009
  } catch (e) {
833
1010
  toolResults.push({ tool, result: `Error: ${e.message}` });
834
1011
  }
@@ -957,6 +1134,27 @@ ${this.promptManager.getUsedToolResultInstructions()}`;
957
1134
  }
958
1135
  }
959
1136
  }
1137
+ /**
1138
+ * 激活自定义工具集:将入口的 children 注册到活跃工具列表并返回渲染后的 prompt。
1139
+ */
1140
+ activateCustomToolGroup(group) {
1141
+ if (this.activatedGroups.has(group.name)) {
1142
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1143
+ }
1144
+ this.activatedGroups.add(group.name);
1145
+ this.activeCustomTools = [...this.activeCustomTools, ...group.children || []];
1146
+ this.activeToolsVersion++;
1147
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1148
+ }
1149
+ /**
1150
+ * 检查自上次获取 prompt 后是否有工具集被激活,若有则刷新缓存。
1151
+ */
1152
+ async getCurrentPrompt() {
1153
+ if (this.promptActiveToolsVersion !== this.activeToolsVersion) {
1154
+ return this.getPrompt(true);
1155
+ }
1156
+ return this.getPrompt();
1157
+ }
960
1158
  /**
961
1159
  * 简单的 Diff 解析与替换辅助方法
962
1160
  */
@@ -1003,13 +1201,80 @@ ${searchBlock.substring(0, 100)}...`);
1003
1201
  async getHistory() {
1004
1202
  return this.memory.getHistory();
1005
1203
  }
1006
- async searchFiles(dirpath, regex, filePattern) {
1204
+ /**
1205
+ * 判断文件是否为可进行内容搜索的文本类文件
1206
+ */
1207
+ isTextFile(name) {
1208
+ const ext = name.includes(".") ? String(name.split(".").pop()).toLowerCase() : "";
1209
+ if (!ext) {
1210
+ return true;
1211
+ }
1212
+ return TEXT_FILE_EXTENSIONS.has(ext);
1213
+ }
1214
+ /**
1215
+ * 按文件名/目录名搜索,层级优先(BFS):
1216
+ * 每一层先匹配完当前层级的所有条目,再进入更深的子目录。
1217
+ */
1218
+ async searchFiles(dirpath, regex, filePattern, includeNodeModules = false) {
1007
1219
  const matches = [];
1008
- const contentRe = new RegExp(regex);
1009
- const nameRe = filePattern ? new RegExp(filePattern.replace(/\./g, "\\.").replace(/\*/g, ".*")) : null;
1220
+ const MAX_RESULTS = 100;
1221
+ const MAX_DEPTH = 8;
1010
1222
  const SKIP_DIRS = /* @__PURE__ */ new Set([".git", "dist", ".agent", ".turbopack"]);
1223
+ const shouldSkipDir = (name) => SKIP_DIRS.has(name) || name === "node_modules" && !includeNodeModules;
1224
+ const nameRe = new RegExp(regex);
1225
+ const globRe = filePattern ? new RegExp(filePattern.replace(/\./g, "\\.").replace(/\*/g, ".*")) : null;
1226
+ const queue = [{ dir: dirpath, depth: 0 }];
1227
+ while (queue.length > 0 && matches.length < MAX_RESULTS) {
1228
+ const { dir, depth } = queue.shift();
1229
+ if (depth > MAX_DEPTH) {
1230
+ continue;
1231
+ }
1232
+ let entries;
1233
+ try {
1234
+ entries = await this.runtime.fs.readDir(dir, { recursive: false });
1235
+ } catch {
1236
+ continue;
1237
+ }
1238
+ for (const entry of entries) {
1239
+ if (matches.length >= MAX_RESULTS) {
1240
+ break;
1241
+ }
1242
+ const child = dir === "." ? entry.name : `${dir}/${entry.name}`;
1243
+ if (entry.isDirectory()) {
1244
+ if (!shouldSkipDir(entry.name)) {
1245
+ if (nameRe.test(entry.name)) {
1246
+ matches.push(`${child}/`);
1247
+ }
1248
+ queue.push({ dir: child, depth: depth + 1 });
1249
+ }
1250
+ } else if (entry.isFile()) {
1251
+ if (globRe && !globRe.test(entry.name)) {
1252
+ continue;
1253
+ }
1254
+ if (nameRe.test(entry.name)) {
1255
+ matches.push(child);
1256
+ }
1257
+ }
1258
+ }
1259
+ }
1260
+ if (matches.length === 0) {
1261
+ return "No files found.";
1262
+ }
1263
+ return matches.join("\n");
1264
+ }
1265
+ /**
1266
+ * 按文件内容搜索:正则匹配文件内容,返回匹配文件路径。
1267
+ */
1268
+ async searchFileContent(dirpath, regex, filePattern, includeNodeModules = false) {
1269
+ const matches = [];
1270
+ const MAX_RESULTS = 100;
1271
+ const MAX_DEPTH = 8;
1272
+ const SKIP_DIRS = /* @__PURE__ */ new Set([".git", "dist", ".agent", ".turbopack"]);
1273
+ const shouldSkipDir = (name) => SKIP_DIRS.has(name) || name === "node_modules" && !includeNodeModules;
1274
+ const contentRe = new RegExp(regex);
1275
+ const globRe = filePattern ? new RegExp(filePattern.replace(/\./g, "\\.").replace(/\*/g, ".*")) : null;
1011
1276
  const walk = async (dir, depth) => {
1012
- if (depth > 8 || matches.length >= 100) {
1277
+ if (depth > MAX_DEPTH || matches.length >= MAX_RESULTS) {
1013
1278
  return;
1014
1279
  }
1015
1280
  let entries;
@@ -1019,21 +1284,24 @@ ${searchBlock.substring(0, 100)}...`);
1019
1284
  return;
1020
1285
  }
1021
1286
  for (const entry of entries) {
1022
- if (matches.length >= 100) {
1287
+ if (matches.length >= MAX_RESULTS) {
1023
1288
  break;
1024
1289
  }
1025
1290
  const child = dir === "." ? entry.name : `${dir}/${entry.name}`;
1026
1291
  if (entry.isDirectory()) {
1027
- if (!SKIP_DIRS.has(entry.name)) {
1292
+ if (!shouldSkipDir(entry.name)) {
1028
1293
  await walk(child, depth + 1);
1029
1294
  }
1030
1295
  } else if (entry.isFile()) {
1031
- if (nameRe && !nameRe.test(entry.name)) {
1296
+ if (!this.isTextFile(entry.name)) {
1297
+ continue;
1298
+ }
1299
+ if (globRe && !globRe.test(entry.name)) {
1032
1300
  continue;
1033
1301
  }
1034
1302
  try {
1035
- const content = (await this.runtime.fs.readFile(child, "utf8")).toString();
1036
- if (contentRe.test(content)) {
1303
+ const content = await this.runtime.fs.readFile(child);
1304
+ if (typeof content === "string" && contentRe.test(content)) {
1037
1305
  matches.push(child);
1038
1306
  }
1039
1307
  } catch {
@@ -1042,6 +1310,9 @@ ${searchBlock.substring(0, 100)}...`);
1042
1310
  }
1043
1311
  };
1044
1312
  await walk(dirpath, 0);
1313
+ if (matches.length === 0) {
1314
+ return "No files found with matching content.";
1315
+ }
1045
1316
  return matches.join("\n");
1046
1317
  }
1047
1318
  };
@@ -1050,6 +1321,6 @@ ${searchBlock.substring(0, 100)}...`);
1050
1321
  var VERSION = "0.1.0";
1051
1322
  globalThis.AI_SDK_LOG_WARNINGS = false;
1052
1323
 
1053
- export { AgentDefaultTool, AgentState, ClineAgent, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames };
1324
+ export { AgentDefaultTool, AgentState, ClineAgent, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, collectCustomToolNames, defaultTools, getToolUseNames, isCustomToolGroup, parseAssistantMessageV2, renderCustomToolPrompt, renderCustomToolsPrompt, setDynamicToolUseNames, toolParamNames, toolUseNames };
1054
1325
  //# sourceMappingURL=index.mjs.map
1055
1326
  //# sourceMappingURL=index.mjs.map