@amical/aiagent-sdk 0.1.7 → 0.1.9

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.
@@ -6,7 +6,7 @@ var ai = require('ai');
6
6
  var openai = require('@ai-sdk/openai');
7
7
  var difyAiProvider = require('dify-ai-provider');
8
8
  var fs2 = require('fs/promises');
9
- var path2 = require('path');
9
+ var path = require('path');
10
10
  var os = require('os');
11
11
  var child_process = require('child_process');
12
12
  var util = require('util');
@@ -35,7 +35,7 @@ function _interopNamespace(e) {
35
35
 
36
36
  var matter__default = /*#__PURE__*/_interopDefault(matter);
37
37
  var fs2__namespace = /*#__PURE__*/_interopNamespace(fs2);
38
- var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
38
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
39
39
  var os__namespace = /*#__PURE__*/_interopNamespace(os);
40
40
 
41
41
  // src/shared/tools.ts
@@ -582,7 +582,7 @@ var ClineAgent = class {
582
582
  }
583
583
  }
584
584
  /**
585
- * 获取当前 Agent 的系统提示词
585
+ * 获取当前 Agent 的系统提示词
586
586
  * 如果 force 为 true,则强制重新获取系统提示词
587
587
  */
588
588
  async getPrompt(force = false) {
@@ -720,9 +720,12 @@ ${content.trim()}\`\`\``);
720
720
  const history = await this.memory.getHistory();
721
721
  const stream = this.api.createMessage(sysPrompt, history);
722
722
  let fullResponseText = "";
723
+ let fullReasoningText = "";
723
724
  for await (const chunk of stream) {
724
725
  if (chunk.type === "text" && chunk.text) {
725
726
  fullResponseText += chunk.text;
727
+ } else if (chunk.type === "reasoning" && chunk.reasoning) {
728
+ fullReasoningText += chunk.reasoning;
726
729
  }
727
730
  if (this.onStreamChunk) {
728
731
  this.onStreamChunk(chunk);
@@ -730,7 +733,8 @@ ${content.trim()}\`\`\``);
730
733
  }
731
734
  await this.memory.appendMessage({
732
735
  role: "assistant",
733
- content: fullResponseText
736
+ content: fullResponseText,
737
+ ...fullReasoningText ? { reasoning: fullReasoningText } : {}
734
738
  });
735
739
  const parsedBlocks = parseAssistantMessageV2(fullResponseText, this.allToolParamNames);
736
740
  const toolUses = parsedBlocks.filter((b) => b.type === "tool_use");
@@ -853,15 +857,20 @@ STDERR: ${result.stderr}` });
853
857
  const path3 = tool.params.path || this.runtime.env.cwd();
854
858
  const regexStr = tool.params.regex;
855
859
  const filePattern = tool.params.file_pattern;
856
- if (regexStr && this.runtime.fs.searchFiles) {
860
+ if (regexStr && path3) {
857
861
  try {
858
- const result = await this.runtime.fs.searchFiles(path3, regexStr, filePattern);
862
+ let result;
863
+ if (typeof this.runtime.fs.searchFiles === "function") {
864
+ result = await this.runtime.fs.searchFiles(path3, regexStr, filePattern);
865
+ } else {
866
+ result = await this.searchFiles(path3, regexStr, filePattern);
867
+ }
859
868
  toolResults.push({ tool, result: `${result}` });
860
869
  } catch (e) {
861
870
  toolResults.push({ tool, result: `Error: ${e.message}` });
862
871
  }
863
872
  } else {
864
- toolResults.push({ tool, result: `Error: searchFiles not supported by runtime or missing regex.` });
873
+ toolResults.push({ tool, result: `Error: miss path or regex params` });
865
874
  }
866
875
  } else if (tool.name === "agent_use_mcp_tool" /* MCP_USE */) {
867
876
  const serverName = tool.params.server_name;
@@ -966,9 +975,14 @@ IMPORTANT: The skill is now loaded. Do NOT call agent_load_skill again for this
966
975
  }
967
976
  }
968
977
  if (this.state === "thinking" /* THINKING */ && toolResults.length > 0) {
969
- const toolResultsContext = toolResults.map((tr) => `<${TOOL_RESULT_BLOCK} tool_name="${tr.tool.name}">
978
+ let toolResultsContext = toolResults.map((tr) => `<${TOOL_RESULT_BLOCK} tool_name="${tr.tool.name}">
970
979
  ${typeof tr.result === "string" ? tr.result.trim() : JSON.stringify(tr.result)}
971
980
  </${TOOL_RESULT_BLOCK}>`).join("\n\n");
981
+ const lastResult = toolResults[toolResults.length - 1];
982
+ if (lastResult && lastResult.tool.name !== "agent_attempt_completion" /* ATTEMPT */) {
983
+ toolResultsContext += `
984
+ ${this.promptManager.getUsedToolResultInstructions()}`;
985
+ }
972
986
  if (this.onStreamChunk) {
973
987
  this.onStreamChunk({ type: "text", text: toolResultsContext });
974
988
  }
@@ -1026,6 +1040,47 @@ ${searchBlock.substring(0, 100)}...`);
1026
1040
  async getHistory() {
1027
1041
  return this.memory.getHistory();
1028
1042
  }
1043
+ async searchFiles(dirpath, regex, filePattern) {
1044
+ const matches = [];
1045
+ const contentRe = new RegExp(regex);
1046
+ const nameRe = filePattern ? new RegExp(filePattern.replace(/\./g, "\\.").replace(/\*/g, ".*")) : null;
1047
+ const SKIP_DIRS = /* @__PURE__ */ new Set([".git", "dist", ".agent", ".turbopack"]);
1048
+ const walk = async (dir, depth) => {
1049
+ if (depth > 8 || matches.length >= 100) {
1050
+ return;
1051
+ }
1052
+ let entries;
1053
+ try {
1054
+ entries = await this.runtime.fs.readDir(dir, { recursive: false });
1055
+ } catch {
1056
+ return;
1057
+ }
1058
+ for (const entry of entries) {
1059
+ if (matches.length >= 100) {
1060
+ break;
1061
+ }
1062
+ const child = dir === "." ? entry.name : `${dir}/${entry.name}`;
1063
+ if (entry.isDirectory()) {
1064
+ if (!SKIP_DIRS.has(entry.name)) {
1065
+ await walk(child, depth + 1);
1066
+ }
1067
+ } else if (entry.isFile()) {
1068
+ if (nameRe && !nameRe.test(entry.name)) {
1069
+ continue;
1070
+ }
1071
+ try {
1072
+ const content = (await this.runtime.fs.readFile(child, "utf8")).toString();
1073
+ if (contentRe.test(content)) {
1074
+ matches.push(child);
1075
+ }
1076
+ } catch {
1077
+ }
1078
+ }
1079
+ }
1080
+ };
1081
+ await walk(dirpath, 0);
1082
+ return matches.join("\n");
1083
+ }
1029
1084
  };
1030
1085
  var NodeApiHandler = class {
1031
1086
  config;
@@ -1088,6 +1143,11 @@ var NodeApiHandler = class {
1088
1143
  type: "text",
1089
1144
  text: part.textDelta || part.text || ""
1090
1145
  };
1146
+ } else if (part.type === "reasoning-delta") {
1147
+ yield {
1148
+ type: "reasoning",
1149
+ reasoning: part.delta || part.text || ""
1150
+ };
1091
1151
  } else if (part.type === "finish") {
1092
1152
  yield {
1093
1153
  type: "usage",
@@ -1395,6 +1455,21 @@ Otherwise, if you have not completed the task and do not need additional informa
1395
1455
  (This is an automated message, so do not respond to it conversationally.)
1396
1456
  ${this?.getEnvironmentInfoPrompt?.(context)}`;
1397
1457
  }
1458
+ getUsedToolResultInstructions() {
1459
+ return `The above are the results of the tool call. Please continue to complete the remaining tasks.
1460
+
1461
+ # TODO LIST UPDATE REQUIRED - You MUST include the task_progress parameter in your NEXT tool call.
1462
+
1463
+ 1. To create or update a todo list, include the task_progress parameter in the next tool call
1464
+ 2. Review each item and update its status:
1465
+ - Mark completed items with: - [x]
1466
+ - Keep incomplete items as: - [ ]
1467
+ - Add new items if you discover additional steps
1468
+ 3. Modify the list as needed:
1469
+ - Add any new steps you've discovered
1470
+ - Reorder if the sequence has changed
1471
+ 4. Ensure the list accurately reflects the current state`;
1472
+ }
1398
1473
  };
1399
1474
  var NodeMemoryManager = class {
1400
1475
  filePath;
@@ -1404,14 +1479,14 @@ var NodeMemoryManager = class {
1404
1479
  * @param maxMessages 保留的最大消息数量,用于简单的历史截断(默认 150)
1405
1480
  */
1406
1481
  constructor(dbPath, maxMessages = 150) {
1407
- this.filePath = path2__namespace.resolve(dbPath);
1482
+ this.filePath = path__namespace.resolve(dbPath);
1408
1483
  this.maxMessages = maxMessages;
1409
1484
  }
1410
1485
  async ensureFile() {
1411
1486
  try {
1412
1487
  await fs2__namespace.access(this.filePath);
1413
1488
  } catch {
1414
- const dir = path2__namespace.dirname(this.filePath);
1489
+ const dir = path__namespace.dirname(this.filePath);
1415
1490
  await fs2__namespace.mkdir(dir, { recursive: true });
1416
1491
  await fs2__namespace.writeFile(this.filePath, "[]", "utf-8");
1417
1492
  }
@@ -1587,10 +1662,13 @@ var NodeMcpManager = class {
1587
1662
  var execAsync = util.promisify(child_process.exec);
1588
1663
  var DefaultNodeRuntime = class {
1589
1664
  fs = {
1590
- readFile: async (filepath) => fs2__namespace.readFile(filepath, "utf-8"),
1665
+ readFile: async (filepath, options = "utf8") => fs2__namespace.readFile(filepath, options),
1591
1666
  writeFile: async (filepath, content) => {
1592
- await fs2__namespace.mkdir(path2__namespace.dirname(filepath), { recursive: true });
1593
- await fs2__namespace.writeFile(filepath, content, "utf-8");
1667
+ const dir = filepath.substring(0, filepath.lastIndexOf("/"));
1668
+ if (dir && dir !== filepath) {
1669
+ await fs2__namespace.mkdir(dir, { recursive: true });
1670
+ }
1671
+ await fs2__namespace.writeFile(filepath, content, "utf8");
1594
1672
  },
1595
1673
  deleteFile: (filepath) => fs2__namespace.unlink(filepath),
1596
1674
  deleteDirectory: (dirpath) => fs2__namespace.rm(dirpath, { recursive: true, force: true }),
@@ -1602,13 +1680,13 @@ var DefaultNodeRuntime = class {
1602
1680
  return false;
1603
1681
  }
1604
1682
  },
1605
- readDir: (dirpath) => fs2__namespace.readdir(dirpath, { withFileTypes: true }),
1683
+ readDir: (dirpath, options) => fs2__namespace.readdir(dirpath, { withFileTypes: true, ...options || {} }),
1606
1684
  mkdir: async (dirpath) => {
1607
1685
  await fs2__namespace.mkdir(dirpath, { recursive: true });
1608
1686
  }
1609
1687
  };
1610
1688
  path = {
1611
- join: (...paths) => path2__namespace.join(...paths)
1689
+ join: (...paths) => path__namespace.join(...paths)
1612
1690
  };
1613
1691
  env = {
1614
1692
  get: (key) => process.env[key],
@@ -1630,7 +1708,7 @@ var DefaultNodeRuntime = class {
1630
1708
  function createNodeAgent(options) {
1631
1709
  const runtime = new DefaultNodeRuntime();
1632
1710
  const api = new NodeApiHandler(options.apiConfig);
1633
- const memory = options.memory || new NodeMemoryManager(options.dbPath || path2__namespace.join(runtime.env.cwd(), ".cline_memory.json"));
1711
+ const memory = options.memory || new NodeMemoryManager(options.dbPath || path__namespace.join(runtime.env.cwd(), ".cline_memory.json"));
1634
1712
  const customTools = options.customTools || [];
1635
1713
  const customToolNames = new Set(customTools.map((t) => t.name));
1636
1714
  const promptManager = new NodePromptManager();