@amical/aiagent-sdk 0.1.10 → 0.1.12

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
@@ -130,9 +130,11 @@ return (
130
130
  },
131
131
  {
132
132
  name: "agent_read_file" /* FILE_READ */,
133
- description: "Read the contents of a specific file.",
133
+ description: "Read the contents of a specific file. The returned content includes line numbers (e.g. '10|const x = 1;') so you can reference exact lines when editing.",
134
134
  params: {
135
- path: "(required) The absolute or relative file path to read."
135
+ path: "(required) The absolute or relative file path to read.",
136
+ start_line: "(optional) The 1-based line number to start reading from (inclusive). Defaults to 1.",
137
+ end_line: "(optional) The 1-based line number to stop reading at (inclusive). Defaults to the last line."
136
138
  }
137
139
  },
138
140
  {
@@ -279,6 +281,44 @@ var READ_ONLY_TOOLS = [
279
281
  "agent_load_skill" /* LOAD_SKILL */,
280
282
  "agent_use_subagents" /* USE_SUBAGENTS */
281
283
  ];
284
+
285
+ // src/shared/custom-tools.ts
286
+ function isCustomToolGroup(tool) {
287
+ return Array.isArray(tool.children) && tool.children.length > 0;
288
+ }
289
+ function collectCustomToolNames(tools) {
290
+ const names = [];
291
+ const visit = (list) => {
292
+ for (const tool of list) {
293
+ names.push(tool.name);
294
+ if (Array.isArray(tool.children) && tool.children.length > 0) {
295
+ visit(tool.children);
296
+ }
297
+ }
298
+ };
299
+ visit(tools);
300
+ return names;
301
+ }
302
+ function renderCustomToolPrompt(tool, cwd = "") {
303
+ const params = tool.params ? Object.entries(tool.params) : [];
304
+ const replaceCwd = (text) => String(text).replaceAll("${context.cwd}", cwd);
305
+ const paramLines = params.map(([name, description]) => `- ${name}: ${replaceCwd(description)}`).join("\n");
306
+ const usageLines = params.map(([name, description]) => `<${name}>${replaceCwd(description)}</${name}>`).join("\n");
307
+ return `### ${tool.name}
308
+ Description: ${tool.description}
309
+ Parameters:
310
+ ${paramLines}
311
+ - 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)
312
+ Usage:
313
+ <${tool.name}>
314
+ ${usageLines}
315
+ <task_progress>Checklist here (optional)</task_progress>
316
+ </${tool.name}>
317
+ `;
318
+ }
319
+ function renderCustomToolsPrompt(tools, cwd = "") {
320
+ return tools.map((tool) => renderCustomToolPrompt(tool, cwd)).join("\n");
321
+ }
282
322
  function parseAssistantMessageV2(assistantMessage, toolParamNames2) {
283
323
  const contentBlocks = [];
284
324
  let currentTextContentStart = 0;
@@ -537,7 +577,17 @@ var TEXT_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
537
577
  "dockerfile",
538
578
  "makefile",
539
579
  "properties",
540
- "lock"
580
+ "lock",
581
+ "node-version",
582
+ "nvmrc",
583
+ "editorconfig",
584
+ "prettierrc",
585
+ "eslintrc",
586
+ "babelrc",
587
+ "stylelintrc",
588
+ "huskyrc",
589
+ "commitlintrc",
590
+ "lintstagedrc"
541
591
  ]);
542
592
  var AgentState = /* @__PURE__ */ ((AgentState2) => {
543
593
  AgentState2["IDLE"] = "idle";
@@ -562,9 +612,19 @@ var ClineAgent = class {
562
612
  skillDir;
563
613
  rulesDir;
564
614
  customTools;
615
+ /** 当前可用(已展开集合)的顶层工具列表,传给 PromptManager 渲染 */
616
+ activeCustomTools;
617
+ /** 所有已知工具名(含未激活 children),便于查找定义 */
618
+ customToolsByName;
565
619
  customToolNames;
566
620
  allowDefaultTools;
567
621
  customInstructions;
622
+ /** 已激活的工具集入口名 */
623
+ activatedGroups = /* @__PURE__ */ new Set();
624
+ /** activeCustomTools 变更版本号,用于 Prompt 缓存失效 */
625
+ activeToolsVersion = 0;
626
+ /** 缓存 sysPrompt 时记录的版本号 */
627
+ promptActiveToolsVersion = -1;
568
628
  sysPrompt;
569
629
  noUseTollSysPrompt;
570
630
  // 简单的事件回调系统,供宿主环境注册以监听 Agent 内部事件
@@ -584,33 +644,47 @@ var ClineAgent = class {
584
644
  this.allowDefaultTools.push("agent_attempt_completion" /* ATTEMPT */);
585
645
  }
586
646
  this.customInstructions = options.customInstructions;
647
+ this.customToolsByName = /* @__PURE__ */ new Map();
648
+ this.activeCustomTools = [...this.customTools];
649
+ this.customToolNames = new Set(collectCustomToolNames(this.customTools));
587
650
  if (this.customTools.length > 0) {
588
- const dynamicToolNames = /* @__PURE__ */ new Set();
589
651
  const customToolParams = /* @__PURE__ */ new Set();
590
- for (const customTool of this.customTools) {
591
- dynamicToolNames.add(customTool.name);
592
- if (customTool.params) {
593
- for (const key in customTool.params) {
594
- if (!Object.hasOwn(customTool.params, key)) continue;
595
- 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);
596
663
  }
597
664
  }
598
- }
665
+ };
666
+ visit(this.customTools);
599
667
  const defaultToolNames = Object.values(AgentDefaultTool);
600
- const overlappingTools = Array.from(dynamicToolNames).filter((name) => defaultToolNames.includes(name));
668
+ const overlappingTools = Array.from(this.customToolNames).filter((name) => defaultToolNames.includes(name));
601
669
  if (overlappingTools.length > 0) {
602
670
  throw new Error(`Custom tools and default tools have overlapping names: ${overlappingTools.join(", ")}`);
603
671
  }
604
- if (dynamicToolNames.size > 0) {
605
- setDynamicToolUseNames("customUser", Array.from(dynamicToolNames));
672
+ if (this.customToolNames.size > 0) {
673
+ setDynamicToolUseNames("customUser", Array.from(this.customToolNames));
606
674
  }
607
675
  if (customToolParams.size > 0) {
608
676
  this.allToolParamNames = Array.from(/* @__PURE__ */ new Set([...this.allToolParamNames, ...Array.from(customToolParams)]));
609
677
  }
610
678
  }
611
- this.customToolNames = new Set(this.customTools.map((t) => t.name));
612
679
  this.skillDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/skills");
613
680
  this.rulesDir = this.runtime.path.join(this.runtime.env.cwd(), ".agents/rules");
681
+ const originalOnCondense = this.memory.onCondense;
682
+ this.memory.onCondense = async () => {
683
+ this.api.clearConversationId();
684
+ if (originalOnCondense) {
685
+ await originalOnCondense();
686
+ }
687
+ };
614
688
  }
615
689
  setState(newState) {
616
690
  this.state = newState;
@@ -632,10 +706,11 @@ var ClineAgent = class {
632
706
  shell: this.runtime.env.shell(),
633
707
  skills: await this.getSkills(),
634
708
  agentRules: await this.getAgentRules(),
635
- customTools: this.customTools,
709
+ customTools: this.activeCustomTools,
636
710
  allowDefaultTools: this.allowDefaultTools,
637
711
  customInstructions: this.customInstructions
638
712
  };
713
+ this.promptActiveToolsVersion = this.activeToolsVersion;
639
714
  this.sysPrompt = await this.promptManager.getSystemPrompt(context);
640
715
  this.noUseTollSysPrompt = this.promptManager.getNoUseToolInstructions(context);
641
716
  return { sysPrompt: this.sysPrompt, noUseTollSysPrompt: this.noUseTollSysPrompt };
@@ -667,16 +742,6 @@ var ClineAgent = class {
667
742
  async getAgentRules() {
668
743
  const cwd = this.runtime.env.cwd();
669
744
  const rules = [];
670
- const agentsMdPath = this.runtime.path.join(cwd, "Agents.md");
671
- try {
672
- if (await this.runtime.fs.fileExists(agentsMdPath)) {
673
- const content = await this.runtime.fs.readFile(agentsMdPath);
674
- if (content && content.trim()) {
675
- rules.push(content.trim());
676
- }
677
- }
678
- } catch (e) {
679
- }
680
745
  try {
681
746
  if (await this.runtime.fs.fileExists(this.rulesDir)) {
682
747
  const files = await this.runtime.fs.readDir(this.rulesDir);
@@ -702,6 +767,28 @@ ${content.trim()}\`\`\``);
702
767
  }
703
768
  } catch (e) {
704
769
  }
770
+ try {
771
+ const getAgentsMdPath = async () => {
772
+ const agentsMdPathList = [
773
+ this.runtime.path.join(cwd, "AGENTS.md"),
774
+ this.runtime.path.join(cwd, "Agents.md"),
775
+ this.runtime.path.join(cwd, "agents.md")
776
+ ];
777
+ for (const item of agentsMdPathList) {
778
+ if (await this.runtime.fs.fileExists(item)) {
779
+ return item;
780
+ }
781
+ }
782
+ };
783
+ const agentsMdPath = await getAgentsMdPath();
784
+ if (agentsMdPath) {
785
+ const content = await this.runtime.fs.readFile(agentsMdPath);
786
+ if (content && content.trim()) {
787
+ rules.push(content.trim());
788
+ }
789
+ }
790
+ } catch (e) {
791
+ }
705
792
  return rules.join("\n---\n");
706
793
  }
707
794
  async getSkills() {
@@ -744,9 +831,9 @@ ${content.trim()}\`\`\``);
744
831
  * 核心任务循环
745
832
  */
746
833
  async loop() {
747
- const { sysPrompt, noUseTollSysPrompt } = await this.getPrompt(true);
748
- const { customTools, customToolNames } = this;
834
+ const { customToolsByName, customToolNames } = this;
749
835
  while (this.state === "thinking" /* THINKING */) {
836
+ const { sysPrompt, noUseTollSysPrompt } = await this.getCurrentPrompt();
750
837
  this.loopCount++;
751
838
  if (this.loopCount > this.maxLoopCount) {
752
839
  await this.memory.appendMessage({
@@ -791,7 +878,33 @@ ${content.trim()}\`\`\``);
791
878
  }
792
879
  }
793
880
  if (customToolNames.has(tool.name)) {
794
- const customTool = customTools.find((t) => t.name === tool.name);
881
+ const customTool = customToolsByName.get(tool.name);
882
+ if (!customTool) {
883
+ toolResults.push({ tool, result: `Error: Custom tool "${tool.name}" not found.` });
884
+ continue;
885
+ }
886
+ if (isCustomToolGroup(customTool)) {
887
+ let groupResult;
888
+ if (customTool.onCall) {
889
+ try {
890
+ groupResult = await customTool.onCall(tool.params);
891
+ } catch (error) {
892
+ toolResults.push({ tool, result: `Error: ${error.message}` });
893
+ continue;
894
+ }
895
+ }
896
+ const childrenPrompt = this.activateCustomToolGroup(customTool);
897
+ const finalPrompt = `# New Available Tools
898
+
899
+ The following are instructions for using the new available tools.
900
+
901
+ ${childrenPrompt}`;
902
+ const promptBlock = groupResult !== void 0 ? `${typeof groupResult === "string" ? groupResult : JSON.stringify(groupResult)}
903
+
904
+ ${finalPrompt}` : finalPrompt;
905
+ toolResults.push({ tool, result: promptBlock });
906
+ continue;
907
+ }
795
908
  if (customTool.onCall) {
796
909
  try {
797
910
  const res = await customTool.onCall(tool.params);
@@ -813,7 +926,8 @@ ${content.trim()}\`\`\``);
813
926
  if (path) {
814
927
  try {
815
928
  const content = await this.runtime.fs.readFile(path);
816
- toolResults.push({ tool, result: content });
929
+ const result = this.formatFileContentWithLineNumbers(content, tool.params.start_line, tool.params.end_line);
930
+ toolResults.push({ tool, result });
817
931
  } catch (error) {
818
932
  toolResults.push({ tool, result: `Error: ${error.message}` });
819
933
  }
@@ -826,6 +940,8 @@ ${content.trim()}\`\`\``);
826
940
  const result = await this.runtime.terminal.execCommand(cmd);
827
941
  toolResults.push({ tool, result: `STDOUT: ${result.stdout}
828
942
  STDERR: ${result.stderr}` });
943
+ } else {
944
+ toolResults.push({ tool, result: "Error: No command provided." });
829
945
  }
830
946
  } else if (tool.name === "agent_write_to_file" /* FILE_NEW */) {
831
947
  const path = tool.params.path;
@@ -837,12 +953,18 @@ STDERR: ${result.stderr}` });
837
953
  } catch (error) {
838
954
  toolResults.push({ tool, result: `Error: ${error.message}` });
839
955
  }
956
+ } else {
957
+ toolResults.push({ tool, result: "Error: Missing path or content." });
840
958
  }
841
959
  } else if (tool.name === "agent_list_files" /* LIST_FILES */) {
842
960
  const path = tool.params.path || this.runtime.env.cwd();
961
+ const recursive = tool.params.recursive === "true";
843
962
  try {
844
- const files = await this.runtime.fs.readDir(path);
845
- toolResults.push({ tool, result: files.map((f) => f.name + (f.isDirectory() ? "/" : "")).join("\n") });
963
+ const files = await this.runtime.fs.readDir(path, { recursive });
964
+ toolResults.push({
965
+ tool,
966
+ result: files.map((f) => `${f.isDirectory() ? "[DIR] " : " "}${f.name}${f.isDirectory() ? "/" : ""}`).join("\n")
967
+ });
846
968
  } catch (e) {
847
969
  toolResults.push({ tool, result: `Error: ${e.message}` });
848
970
  }
@@ -982,10 +1104,15 @@ STDERR: ${result.stderr}` });
982
1104
  try {
983
1105
  const res = await fetch(url);
984
1106
  const text = await res.text();
985
- toolResults.push({ tool, result: text.substring(0, 3e3) });
1107
+ const MAX_LEN = 8e3;
1108
+ const truncated = text.length > MAX_LEN ? `${text.substring(0, MAX_LEN)}
1109
+ ...[truncated ${text.length - MAX_LEN} chars]` : text;
1110
+ toolResults.push({ tool, result: truncated });
986
1111
  } catch (e) {
987
1112
  toolResults.push({ tool, result: `Error: ${e.message}` });
988
1113
  }
1114
+ } else {
1115
+ toolResults.push({ tool, result: "Error: No url provided." });
989
1116
  }
990
1117
  } else if (tool.name === "agent_focus_chain" /* TODO */) {
991
1118
  toolResults.push({ tool, result: `Focus chain updated successfully.` });
@@ -1052,6 +1179,65 @@ ${this.promptManager.getUsedToolResultInstructions()}`;
1052
1179
  }
1053
1180
  }
1054
1181
  }
1182
+ /**
1183
+ * 激活自定义工具集:将入口的 children 注册到活跃工具列表并返回渲染后的 prompt。
1184
+ */
1185
+ activateCustomToolGroup(group) {
1186
+ if (this.activatedGroups.has(group.name)) {
1187
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1188
+ }
1189
+ this.activatedGroups.add(group.name);
1190
+ this.activeCustomTools = [...this.activeCustomTools, ...group.children || []];
1191
+ this.activeToolsVersion++;
1192
+ return renderCustomToolsPrompt(group.children || [], this.runtime.env.cwd());
1193
+ }
1194
+ /**
1195
+ * 检查自上次获取 prompt 后是否有工具集被激活,若有则刷新缓存。
1196
+ */
1197
+ async getCurrentPrompt() {
1198
+ if (this.promptActiveToolsVersion !== this.activeToolsVersion) {
1199
+ return this.getPrompt(true);
1200
+ }
1201
+ return this.getPrompt();
1202
+ }
1203
+ /**
1204
+ * 将文件内容格式化为带行号文本(模拟编辑器行号显示),
1205
+ * 支持通过 start_line / end_line 截取读取范围。
1206
+ */
1207
+ formatFileContentWithLineNumbers(content, startLineParam, endLineParam) {
1208
+ const lines = content.split(/\r?\n/);
1209
+ const normalized = lines.length > 0 && lines[lines.length - 1] === "" ? lines.slice(0, -1) : lines;
1210
+ const total = normalized.length;
1211
+ if (total === 0) {
1212
+ return "1|(empty file)";
1213
+ }
1214
+ const parseLine = (val, fallback) => {
1215
+ if (val === void 0 || val === null || val.trim() === "") {
1216
+ return fallback;
1217
+ }
1218
+ const num = Number.parseInt(val, 10);
1219
+ if (!Number.isFinite(num) || num <= 0) {
1220
+ return fallback;
1221
+ }
1222
+ return num;
1223
+ };
1224
+ const start = parseLine(startLineParam, 1);
1225
+ const end = parseLine(endLineParam, total);
1226
+ if (start > end) {
1227
+ return `Error: start_line (${start}) cannot be greater than end_line (${end}).`;
1228
+ }
1229
+ if (start > total) {
1230
+ return `Error: start_line (${start}) is out of range. The file has ${total} lines.`;
1231
+ }
1232
+ const from = Math.max(1, start);
1233
+ const to = Math.min(total, end);
1234
+ const width = String(total).length;
1235
+ const selected = normalized.slice(from - 1, to);
1236
+ const numbered = selected.map((line, idx) => `${String(from + idx).padStart(width)}|${line}`).join("\n");
1237
+ const header = from === 1 && to === total ? `1-${total}/${total}` : `${from}-${to}/${total}`;
1238
+ return `${header}
1239
+ ${numbered}`;
1240
+ }
1055
1241
  /**
1056
1242
  * 简单的 Diff 解析与替换辅助方法
1057
1243
  */
@@ -1218,6 +1404,6 @@ ${searchBlock.substring(0, 100)}...`);
1218
1404
  var VERSION = "0.1.0";
1219
1405
  globalThis.AI_SDK_LOG_WARNINGS = false;
1220
1406
 
1221
- export { AgentDefaultTool, AgentState, ClineAgent, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, defaultTools, getToolUseNames, parseAssistantMessageV2, setDynamicToolUseNames, toolParamNames, toolUseNames };
1407
+ export { AgentDefaultTool, AgentState, ClineAgent, READ_ONLY_TOOLS, TOOL_RESULT_BLOCK, VERSION, collectCustomToolNames, defaultTools, getToolUseNames, isCustomToolGroup, parseAssistantMessageV2, renderCustomToolPrompt, renderCustomToolsPrompt, setDynamicToolUseNames, toolParamNames, toolUseNames };
1222
1408
  //# sourceMappingURL=index.mjs.map
1223
1409
  //# sourceMappingURL=index.mjs.map