openloops 0.1.30 → 0.1.32

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.
Files changed (251) hide show
  1. package/README.md +1 -1
  2. package/dist/clients/llm-client.d.ts +6 -1
  3. package/dist/clients/llm-client.js +77 -17
  4. package/dist/clients/llm-client.mjs +77 -17
  5. package/dist/clients/llm-error.d.ts +9 -0
  6. package/dist/clients/llm-error.js +69 -0
  7. package/dist/clients/llm-error.mjs +45 -0
  8. package/dist/clients/llm-types.d.ts +61 -0
  9. package/dist/clients/llm-types.js +16 -0
  10. package/dist/clients/llm-types.mjs +0 -0
  11. package/dist/clients/pi-ai-adapter.d.ts +7 -0
  12. package/dist/clients/pi-ai-adapter.js +137 -0
  13. package/dist/clients/pi-ai-adapter.mjs +113 -0
  14. package/dist/{agent → harness}/agent-loop.d.ts +11 -1
  15. package/dist/{agent → harness}/agent-state.js +1 -1
  16. package/dist/{agent → harness}/agent-state.mjs +1 -1
  17. package/dist/{agent → harness}/agent.d.ts +34 -3
  18. package/dist/harness/agent.js +546 -0
  19. package/dist/harness/agent.mjs +530 -0
  20. package/dist/{agent → harness}/index.js +5 -5
  21. package/dist/harness/native-tools.d.ts +23 -0
  22. package/dist/harness/native-tools.js +198 -0
  23. package/dist/harness/native-tools.mjs +174 -0
  24. package/dist/harness/tool-catalog.d.ts +16 -0
  25. package/dist/harness/tool-catalog.js +85 -0
  26. package/dist/harness/tool-catalog.mjs +59 -0
  27. package/dist/harness/tool-pipeline.d.ts +42 -0
  28. package/dist/harness/tool-pipeline.js +192 -0
  29. package/dist/harness/tool-pipeline.mjs +169 -0
  30. package/dist/harness/utils/describe-shape.d.ts +2 -0
  31. package/dist/harness/utils/describe-shape.js +56 -0
  32. package/dist/harness/utils/describe-shape.mjs +32 -0
  33. package/dist/harness/workspace.d.ts +44 -0
  34. package/dist/harness/workspace.js +95 -0
  35. package/dist/harness/workspace.mjs +78 -0
  36. package/dist/index.d.ts +1 -1
  37. package/dist/index.js +2 -2
  38. package/dist/index.mjs +1 -1
  39. package/dist/loops/agi/index.d.ts +1 -0
  40. package/dist/loops/agi/index.js +22 -0
  41. package/dist/loops/agi/index.mjs +1 -0
  42. package/dist/loops/agi/loop.d.ts +24 -0
  43. package/dist/loops/agi/loop.js +207 -0
  44. package/dist/loops/agi/loop.mjs +184 -0
  45. package/dist/loops/agi/skills/reasoning-engine.d.ts +14 -0
  46. package/dist/loops/agi/skills/reasoning-engine.js +93 -0
  47. package/dist/loops/agi/skills/reasoning-engine.mjs +70 -0
  48. package/dist/loops/index.d.ts +1 -0
  49. package/dist/loops/index.js +3 -1
  50. package/dist/loops/index.mjs +1 -0
  51. package/dist/loops/plan-execute/plan-execute-loop.d.ts +2 -1
  52. package/dist/loops/plan-execute/plan-execute-loop.js +90 -35
  53. package/dist/loops/plan-execute/plan-execute-loop.mjs +80 -25
  54. package/dist/loops/shared/skills/action-planner.js +7 -4
  55. package/dist/loops/shared/skills/action-planner.mjs +7 -4
  56. package/dist/loops/shared/skills/final-responder.js +4 -3
  57. package/dist/loops/shared/skills/final-responder.mjs +4 -3
  58. package/dist/loops/shared/skills/state-observer.js +6 -2
  59. package/dist/loops/shared/skills/state-observer.mjs +6 -2
  60. package/dist/services/chats/entities/chat-message.entity.d.ts +4 -1
  61. package/dist/services/chats/entities/chat-message.entity.js +7 -3
  62. package/dist/services/chats/entities/chat-message.entity.mjs +7 -3
  63. package/dist/services/chats/entities/chat.entity.d.ts +10 -11
  64. package/dist/services/chats/entities/chat.entity.js +17 -21
  65. package/dist/services/chats/entities/chat.entity.mjs +17 -21
  66. package/dist/services/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.d.ts +2 -0
  67. package/dist/services/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.js +4 -4
  68. package/dist/services/chats/lambdas/get-chat-by-id/get-chat-by-id.use-case.mjs +2 -2
  69. package/dist/services/llmcalls/entities/llmcall.entity.d.ts +1 -1
  70. package/dist/services/tasks/entities/agent-action.entity.d.ts +111 -0
  71. package/dist/services/tasks/entities/agent-action.entity.js +269 -0
  72. package/dist/services/tasks/entities/agent-action.entity.mjs +245 -0
  73. package/dist/services/tasks/entities/agent-task.entity.d.ts +172 -0
  74. package/dist/services/tasks/entities/agent-task.entity.js +665 -0
  75. package/dist/services/tasks/entities/agent-task.entity.mjs +633 -0
  76. package/dist/services/tasks/entities/index.d.ts +2 -0
  77. package/dist/services/tasks/entities/index.js +24 -0
  78. package/dist/services/tasks/entities/index.mjs +2 -0
  79. package/dist/services/tasks/index.d.ts +3 -0
  80. package/dist/services/tasks/index.js +26 -0
  81. package/dist/services/tasks/index.mjs +3 -0
  82. package/dist/services/tasks/lambdas/create-agent-action/create-agent-action.use-case.d.ts +14 -0
  83. package/dist/services/tasks/lambdas/create-agent-action/create-agent-action.use-case.js +60 -0
  84. package/dist/services/tasks/lambdas/create-agent-action/create-agent-action.use-case.mjs +31 -0
  85. package/dist/services/tasks/lambdas/create-agent-action/index.d.ts +1 -0
  86. package/dist/services/tasks/lambdas/create-agent-action/index.js +22 -0
  87. package/dist/services/tasks/lambdas/create-agent-action/index.mjs +1 -0
  88. package/dist/services/tasks/lambdas/create-agent-task/create-agent-task.use-case.d.ts +14 -0
  89. package/dist/services/tasks/lambdas/create-agent-task/create-agent-task.use-case.js +60 -0
  90. package/dist/services/tasks/lambdas/create-agent-task/create-agent-task.use-case.mjs +31 -0
  91. package/dist/services/tasks/lambdas/create-agent-task/index.d.ts +1 -0
  92. package/dist/services/tasks/lambdas/create-agent-task/index.js +22 -0
  93. package/dist/services/tasks/lambdas/create-agent-task/index.mjs +1 -0
  94. package/dist/services/tasks/lambdas/get-agent-task-by-id/get-agent-task-by-id.use-case.d.ts +14 -0
  95. package/dist/services/tasks/lambdas/get-agent-task-by-id/get-agent-task-by-id.use-case.js +55 -0
  96. package/dist/services/tasks/lambdas/get-agent-task-by-id/get-agent-task-by-id.use-case.mjs +26 -0
  97. package/dist/services/tasks/lambdas/get-agent-task-by-id/index.d.ts +1 -0
  98. package/dist/services/tasks/lambdas/get-agent-task-by-id/index.js +22 -0
  99. package/dist/services/tasks/lambdas/get-agent-task-by-id/index.mjs +1 -0
  100. package/dist/services/tasks/lambdas/index.d.ts +7 -0
  101. package/dist/services/tasks/lambdas/index.js +46 -0
  102. package/dist/services/tasks/lambdas/index.mjs +17 -0
  103. package/dist/services/tasks/lambdas/list-agent-actions-by-task/index.d.ts +1 -0
  104. package/dist/services/tasks/lambdas/list-agent-actions-by-task/index.js +22 -0
  105. package/dist/services/tasks/lambdas/list-agent-actions-by-task/index.mjs +1 -0
  106. package/dist/services/tasks/lambdas/list-agent-actions-by-task/list-agent-actions-by-task.use-case.d.ts +16 -0
  107. package/dist/services/tasks/lambdas/list-agent-actions-by-task/list-agent-actions-by-task.use-case.js +62 -0
  108. package/dist/services/tasks/lambdas/list-agent-actions-by-task/list-agent-actions-by-task.use-case.mjs +33 -0
  109. package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/index.d.ts +1 -0
  110. package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/index.js +22 -0
  111. package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/index.mjs +1 -0
  112. package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/list-agent-tasks-by-chat.use-case.d.ts +16 -0
  113. package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/list-agent-tasks-by-chat.use-case.js +62 -0
  114. package/dist/services/tasks/lambdas/list-agent-tasks-by-chat/list-agent-tasks-by-chat.use-case.mjs +33 -0
  115. package/dist/services/tasks/lambdas/update-agent-action/index.d.ts +1 -0
  116. package/dist/services/tasks/lambdas/update-agent-action/index.js +22 -0
  117. package/dist/services/tasks/lambdas/update-agent-action/index.mjs +1 -0
  118. package/dist/services/tasks/lambdas/update-agent-action/update-agent-action.use-case.d.ts +15 -0
  119. package/dist/services/tasks/lambdas/update-agent-action/update-agent-action.use-case.js +67 -0
  120. package/dist/services/tasks/lambdas/update-agent-action/update-agent-action.use-case.mjs +38 -0
  121. package/dist/services/tasks/lambdas/update-agent-task/index.d.ts +1 -0
  122. package/dist/services/tasks/lambdas/update-agent-task/index.js +22 -0
  123. package/dist/services/tasks/lambdas/update-agent-task/index.mjs +1 -0
  124. package/dist/services/tasks/lambdas/update-agent-task/update-agent-task.use-case.d.ts +15 -0
  125. package/dist/services/tasks/lambdas/update-agent-task/update-agent-task.use-case.js +67 -0
  126. package/dist/services/tasks/lambdas/update-agent-task/update-agent-task.use-case.mjs +38 -0
  127. package/dist/services/tasks/module.d.ts +15 -0
  128. package/dist/services/tasks/module.js +76 -0
  129. package/dist/services/tasks/module.mjs +47 -0
  130. package/dist/services/tasks/repositories/agent-action.repository.d.ts +8 -0
  131. package/dist/services/tasks/repositories/agent-action.repository.js +62 -0
  132. package/dist/services/tasks/repositories/agent-action.repository.mjs +33 -0
  133. package/dist/services/tasks/repositories/agent-task.repository.d.ts +9 -0
  134. package/dist/services/tasks/repositories/agent-task.repository.js +65 -0
  135. package/dist/services/tasks/repositories/agent-task.repository.mjs +36 -0
  136. package/dist/services/tasks/repositories/index.d.ts +2 -0
  137. package/dist/services/tasks/repositories/index.js +24 -0
  138. package/dist/services/tasks/repositories/index.mjs +2 -0
  139. package/dist/services/traces/entities/agent-trace-entry.entity.d.ts +30 -0
  140. package/dist/services/traces/entities/agent-trace-entry.entity.js +85 -0
  141. package/dist/services/traces/entities/agent-trace-entry.entity.mjs +62 -0
  142. package/dist/services/traces/entities/index.d.ts +1 -0
  143. package/dist/services/traces/entities/index.js +22 -0
  144. package/dist/services/traces/entities/index.mjs +1 -0
  145. package/dist/services/traces/index.d.ts +3 -0
  146. package/dist/services/traces/index.js +26 -0
  147. package/dist/services/traces/index.mjs +3 -0
  148. package/dist/services/traces/lambdas/create-agent-traces/create-agent-traces.use-case.d.ts +16 -0
  149. package/dist/services/traces/lambdas/create-agent-traces/create-agent-traces.use-case.js +62 -0
  150. package/dist/services/traces/lambdas/create-agent-traces/create-agent-traces.use-case.mjs +33 -0
  151. package/dist/services/traces/lambdas/create-agent-traces/index.d.ts +1 -0
  152. package/dist/services/traces/lambdas/create-agent-traces/index.js +22 -0
  153. package/dist/services/traces/lambdas/create-agent-traces/index.mjs +1 -0
  154. package/dist/services/traces/lambdas/index.d.ts +2 -0
  155. package/dist/services/traces/lambdas/index.js +31 -0
  156. package/dist/services/traces/lambdas/index.mjs +7 -0
  157. package/dist/services/traces/lambdas/list-agent-traces-by-chat/index.d.ts +1 -0
  158. package/dist/services/traces/lambdas/list-agent-traces-by-chat/index.js +22 -0
  159. package/dist/services/traces/lambdas/list-agent-traces-by-chat/index.mjs +1 -0
  160. package/dist/services/traces/lambdas/list-agent-traces-by-chat/list-agent-traces-by-chat.use-case.d.ts +18 -0
  161. package/dist/services/traces/lambdas/list-agent-traces-by-chat/list-agent-traces-by-chat.use-case.js +67 -0
  162. package/dist/services/traces/lambdas/list-agent-traces-by-chat/list-agent-traces-by-chat.use-case.mjs +38 -0
  163. package/dist/services/traces/module.d.ts +5 -0
  164. package/dist/services/traces/module.js +41 -0
  165. package/dist/services/traces/module.mjs +17 -0
  166. package/dist/services/traces/repositories/agent-trace.repository.d.ts +7 -0
  167. package/dist/services/traces/repositories/agent-trace.repository.js +55 -0
  168. package/dist/services/traces/repositories/agent-trace.repository.mjs +26 -0
  169. package/dist/services/traces/repositories/index.d.ts +1 -0
  170. package/dist/services/traces/repositories/index.js +22 -0
  171. package/dist/services/traces/repositories/index.mjs +1 -0
  172. package/dist/services/workspaces/entities/index.d.ts +1 -0
  173. package/dist/services/workspaces/entities/index.js +22 -0
  174. package/dist/services/workspaces/entities/index.mjs +1 -0
  175. package/dist/services/workspaces/entities/workspace-item.entity.d.ts +33 -0
  176. package/dist/services/workspaces/entities/workspace-item.entity.js +95 -0
  177. package/dist/services/workspaces/entities/workspace-item.entity.mjs +72 -0
  178. package/dist/services/workspaces/index.d.ts +3 -0
  179. package/dist/services/workspaces/index.js +26 -0
  180. package/dist/services/workspaces/index.mjs +3 -0
  181. package/dist/services/workspaces/lambdas/delete-workspace-item/delete-workspace-item.use-case.d.ts +17 -0
  182. package/dist/services/workspaces/lambdas/delete-workspace-item/delete-workspace-item.use-case.js +68 -0
  183. package/dist/services/workspaces/lambdas/delete-workspace-item/delete-workspace-item.use-case.mjs +39 -0
  184. package/dist/services/workspaces/lambdas/delete-workspace-item/index.d.ts +1 -0
  185. package/dist/services/workspaces/lambdas/delete-workspace-item/index.js +22 -0
  186. package/dist/services/workspaces/lambdas/delete-workspace-item/index.mjs +1 -0
  187. package/dist/services/workspaces/lambdas/get-workspace-item/get-workspace-item.use-case.d.ts +17 -0
  188. package/dist/services/workspaces/lambdas/get-workspace-item/get-workspace-item.use-case.js +67 -0
  189. package/dist/services/workspaces/lambdas/get-workspace-item/get-workspace-item.use-case.mjs +38 -0
  190. package/dist/services/workspaces/lambdas/get-workspace-item/index.d.ts +1 -0
  191. package/dist/services/workspaces/lambdas/get-workspace-item/index.js +22 -0
  192. package/dist/services/workspaces/lambdas/get-workspace-item/index.mjs +1 -0
  193. package/dist/services/workspaces/lambdas/index.d.ts +5 -0
  194. package/dist/services/workspaces/lambdas/index.js +40 -0
  195. package/dist/services/workspaces/lambdas/index.mjs +13 -0
  196. package/dist/services/workspaces/lambdas/list-workspace-items/index.d.ts +1 -0
  197. package/dist/services/workspaces/lambdas/list-workspace-items/index.js +22 -0
  198. package/dist/services/workspaces/lambdas/list-workspace-items/index.mjs +1 -0
  199. package/dist/services/workspaces/lambdas/list-workspace-items/list-workspace-items.use-case.d.ts +18 -0
  200. package/dist/services/workspaces/lambdas/list-workspace-items/list-workspace-items.use-case.js +69 -0
  201. package/dist/services/workspaces/lambdas/list-workspace-items/list-workspace-items.use-case.mjs +40 -0
  202. package/dist/services/workspaces/lambdas/save-workspace-item/index.d.ts +1 -0
  203. package/dist/services/workspaces/lambdas/save-workspace-item/index.js +22 -0
  204. package/dist/services/workspaces/lambdas/save-workspace-item/index.mjs +1 -0
  205. package/dist/services/workspaces/lambdas/save-workspace-item/save-workspace-item.use-case.d.ts +14 -0
  206. package/dist/services/workspaces/lambdas/save-workspace-item/save-workspace-item.use-case.js +76 -0
  207. package/dist/services/workspaces/lambdas/save-workspace-item/save-workspace-item.use-case.mjs +47 -0
  208. package/dist/services/workspaces/lambdas/search-workspace-items/index.d.ts +1 -0
  209. package/dist/services/workspaces/lambdas/search-workspace-items/index.js +22 -0
  210. package/dist/services/workspaces/lambdas/search-workspace-items/index.mjs +1 -0
  211. package/dist/services/workspaces/lambdas/search-workspace-items/search-workspace-items.use-case.d.ts +19 -0
  212. package/dist/services/workspaces/lambdas/search-workspace-items/search-workspace-items.use-case.js +73 -0
  213. package/dist/services/workspaces/lambdas/search-workspace-items/search-workspace-items.use-case.mjs +44 -0
  214. package/dist/services/workspaces/module.d.ts +11 -0
  215. package/dist/services/workspaces/module.js +62 -0
  216. package/dist/services/workspaces/module.mjs +35 -0
  217. package/dist/services/workspaces/repositories/index.d.ts +1 -0
  218. package/dist/services/workspaces/repositories/index.js +22 -0
  219. package/dist/services/workspaces/repositories/index.mjs +1 -0
  220. package/dist/services/workspaces/repositories/workspace-item.repository.d.ts +18 -0
  221. package/dist/services/workspaces/repositories/workspace-item.repository.js +74 -0
  222. package/dist/services/workspaces/repositories/workspace-item.repository.mjs +45 -0
  223. package/dist/skills/runtime-context.d.ts +8 -0
  224. package/dist/skills/runtime-context.js +65 -0
  225. package/dist/skills/runtime-context.mjs +42 -0
  226. package/dist/skills/skill.d.ts +7 -0
  227. package/dist/skills/skill.js +26 -60
  228. package/dist/skills/skill.mjs +26 -60
  229. package/dist/tools/tool.d.ts +6 -0
  230. package/dist/tools/tool.js +56 -0
  231. package/dist/tools/tool.mjs +56 -0
  232. package/package.json +4 -4
  233. package/dist/agent/agent.js +0 -327
  234. package/dist/agent/agent.mjs +0 -303
  235. package/dist/services/chats/entities/agent-action.entity.d.ts +0 -58
  236. package/dist/services/chats/entities/agent-action.entity.js +0 -151
  237. package/dist/services/chats/entities/agent-action.entity.mjs +0 -128
  238. package/dist/services/chats/entities/agent-task.entity.d.ts +0 -59
  239. package/dist/services/chats/entities/agent-task.entity.js +0 -231
  240. package/dist/services/chats/entities/agent-task.entity.mjs +0 -207
  241. package/dist/services/chats/entities/chat-context.entity.d.ts +0 -39
  242. package/dist/services/chats/entities/chat-context.entity.js +0 -70
  243. package/dist/services/chats/entities/chat-context.entity.mjs +0 -47
  244. /package/dist/{agent → harness}/agent-loop.js +0 -0
  245. /package/dist/{agent → harness}/agent-loop.mjs +0 -0
  246. /package/dist/{agent → harness}/agent-state.d.ts +0 -0
  247. /package/dist/{agent → harness}/index.d.ts +0 -0
  248. /package/dist/{agent → harness}/index.mjs +0 -0
  249. /package/dist/{agent → harness}/utils/rank-tools-by-keywords.d.ts +0 -0
  250. /package/dist/{agent → harness}/utils/rank-tools-by-keywords.js +0 -0
  251. /package/dist/{agent → harness}/utils/rank-tools-by-keywords.mjs +0 -0
@@ -0,0 +1,546 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var agent_exports = {};
20
+ __export(agent_exports, {
21
+ AGENT_ERROR_CODES: () => AGENT_ERROR_CODES,
22
+ Agent: () => Agent
23
+ });
24
+ module.exports = __toCommonJS(agent_exports);
25
+ var import_reflect_metadata = require("reflect-metadata");
26
+ var import_mongodb = require("mongodb");
27
+ var import_logger = require("../common/logger/index.js");
28
+ var import_entities = require("../services/mcp-servers/entities/index.js");
29
+ var import_chats = require("../services/chats/index.js");
30
+ var import_chat = require("../services/chats/entities/chat.entity.js");
31
+ var import_tasks = require("../services/tasks/index.js");
32
+ var import_agent_task = require("../services/tasks/entities/agent-task.entity.js");
33
+ var import_agent_action = require("../services/tasks/entities/agent-action.entity.js");
34
+ var import_traces = require("../services/traces/index.js");
35
+ var import_tool = require("../tools/tool.js");
36
+ var import_mcp_servers = require("../services/mcp-servers/index.js");
37
+ var import_rank_tools_by_keywords = require("./utils/rank-tools-by-keywords");
38
+ var import_agent_state = require("./agent-state");
39
+ var import_workspace = require("./workspace");
40
+ var import_tool_pipeline = require("./tool-pipeline");
41
+ var import_native_tools = require("./native-tools");
42
+ var import_tool_catalog = require("./tool-catalog");
43
+ var import_llm_error = require("../clients/llm-error.js");
44
+ const MCP_CONNECT_RETRY_DELAYS_MS = [1e3, 2e3];
45
+ const AGENT_ERROR_CODES = {
46
+ NODE_NOT_FOUND: "AGENT_NODE_NOT_FOUND",
47
+ RUN_FAILED: "AGENT_RUN_FAILED",
48
+ MAX_ITERATIONS_REACHED: "AGENT_MAX_ITERATIONS_REACHED"
49
+ };
50
+ const DEFAULT_MAX_ITERATIONS = 50;
51
+ class Agent {
52
+ logger = new import_logger.Logger();
53
+ _loop;
54
+ _identity;
55
+ maxIterations;
56
+ _tools;
57
+ _mcpTools = [];
58
+ _mcps = [];
59
+ mcpLoading;
60
+ _unavailableSources = [];
61
+ _preHooks = [];
62
+ _postHooks = [];
63
+ currentChat;
64
+ chatOptions;
65
+ currentUser;
66
+ currentSession;
67
+ currentMessage = "";
68
+ answerId = "";
69
+ userMessageId;
70
+ iteration = 0;
71
+ replyCount = 0;
72
+ stopLoop = false;
73
+ stopRequested = false;
74
+ workspace;
75
+ pipeline;
76
+ snapshots = /* @__PURE__ */ new Map();
77
+ pendingNextNode;
78
+ static async interruptExecution(chatId, currentUser) {
79
+ const logger = new import_logger.Logger();
80
+ logger.debug("[AGENT] Interrupt execution triggered");
81
+ await (0, import_chats.updateChat)({
82
+ id: chatId,
83
+ payload: { state: { stopRequested: true } },
84
+ currentUser
85
+ });
86
+ }
87
+ static async createChatSession(currentUser, loop) {
88
+ if (!currentUser) throw new Error("[AGENT] CurrentUser is required to create a new chat");
89
+ const newChat = import_chat.Chat.withDefaults(loop?.name);
90
+ const { data } = await (0, import_chats.createChat)({
91
+ payload: newChat.toJSON(),
92
+ currentUser
93
+ });
94
+ if (!data) throw new Error("[AGENT] There was an error creating the chat");
95
+ return import_chat.Chat.fromJSON(data);
96
+ }
97
+ constructor(agentOptions) {
98
+ if (!agentOptions?.loop) throw new Error("[AGENT] An AgentLoop instance is required");
99
+ this._loop = agentOptions.loop;
100
+ this._tools = agentOptions.tools ?? [];
101
+ this._identity = agentOptions.identity;
102
+ this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
103
+ this.currentChat = import_chat.Chat.withDefaults(this._loop.name);
104
+ }
105
+ get tools() {
106
+ return [...this._tools, ...this._mcpTools];
107
+ }
108
+ get mcps() {
109
+ return this._mcps;
110
+ }
111
+ get notifyOnCompletion() {
112
+ return this.currentChat?.settings?.notifyOnCompletion;
113
+ }
114
+ get lastAssistantAnswer() {
115
+ return this.currentChat.lastAnswer;
116
+ }
117
+ async run(props) {
118
+ try {
119
+ const { input, options, currentUser, currentSession } = props || {};
120
+ const { chatId, message } = input || {};
121
+ this.logger.debug(input, "[AGENT] Agent started");
122
+ if (!this._loop?.nodes || !this._loop?.initialNode) throw new Error("[AGENT] Loop is missing");
123
+ if (!message) throw new Error("[AGENT] Message is required");
124
+ if (!currentUser) throw new Error("[AGENT] CurrentUser is required");
125
+ this.stopLoop = false;
126
+ this.stopRequested = false;
127
+ this.pendingNextNode = void 0;
128
+ this.replyCount = 0;
129
+ this.mcpLoading = void 0;
130
+ this._mcpTools = [];
131
+ this._unavailableSources = [];
132
+ this.workspace = void 0;
133
+ this.pipeline = void 0;
134
+ this.snapshots.clear();
135
+ this.iteration = 0;
136
+ this.userMessageId = void 0;
137
+ this.currentUser = currentUser;
138
+ this.currentSession = currentSession;
139
+ this.currentMessage = message;
140
+ this.chatOptions = options;
141
+ this.answerId = new import_mongodb.ObjectId().toString();
142
+ await this.preRunner(chatId);
143
+ await this.runLoop();
144
+ await this.postRunner();
145
+ return { data: this.currentChat };
146
+ } catch (error) {
147
+ const message = error?.message ?? String(error);
148
+ this.logger.error({ error: message, stack: error?.stack }, "[AGENT] Run failed");
149
+ const llmError = error instanceof import_llm_error.LLMError ? error : void 0;
150
+ const reported = llmError?.userMessage ?? message;
151
+ await this.failRun(reported, llmError);
152
+ return { data: this.currentChat?._id ? this.currentChat : void 0, error: reported };
153
+ }
154
+ }
155
+ stopAgent() {
156
+ this.stopLoop = true;
157
+ }
158
+ addTool(tool) {
159
+ this._tools.push(tool);
160
+ }
161
+ addHook(type, fn) {
162
+ if (type === "pre_execution") this._preHooks.push(fn);
163
+ if (type === "post_execution") this._postHooks.push(fn);
164
+ }
165
+ async preRunner(chatId) {
166
+ let chatData;
167
+ if (chatId) {
168
+ const { data } = await (0, import_chats.getChatById)({ id: chatId, currentUser: this.currentUser });
169
+ chatData = data?._id ? data : void 0;
170
+ }
171
+ if (!chatData) {
172
+ this.logger.debug("[AGENT] Not existing chat found");
173
+ if (!this.currentUser) throw new Error("[AGENT] CurrentUser params is required");
174
+ this.currentChat = await Agent.createChatSession(this.currentUser, this._loop);
175
+ } else {
176
+ this.logger.debug("[AGENT] Existing chat found");
177
+ this.currentChat = import_chat.Chat.fromJSON(chatData);
178
+ this.currentChat.state?.setStopRequested(false);
179
+ this.currentChat.switchLoop(this._loop.name);
180
+ await this.loadTasks();
181
+ }
182
+ const userMessage = this.currentChat.pushMessage({
183
+ role: "user",
184
+ content: this.currentMessage
185
+ });
186
+ this.userMessageId = userMessage._id?.toString();
187
+ if (this.chatOptions?.notifyOnCompletion) this.currentChat.settings?.setNotifyOnCompletion(true);
188
+ if (this.chatOptions?.isPrivateSession) this.currentChat.settings?.setIsPrivateSession(true);
189
+ if (this.chatOptions?.modelName) this.currentChat.settings?.setModelName(this.chatOptions.modelName);
190
+ if (this.chatOptions?.loopName) this.currentChat.settings?.setLoopName(this.chatOptions.loopName);
191
+ this.currentChat.state?.setStatus(import_agent_state.AgentStatus.PROCESSING);
192
+ this.currentChat.state?.setCurrentActivity("Starting...");
193
+ await this.persist({ resetStop: true });
194
+ for (const hook of this._preHooks) {
195
+ await hook();
196
+ }
197
+ }
198
+ async postRunner() {
199
+ for (const hook of this._postHooks) {
200
+ await hook();
201
+ }
202
+ this.currentChat.state?.setCurrentActivity("stopped");
203
+ await this.persist();
204
+ await this.disconnectMcpServers();
205
+ }
206
+ async failRun(message, llmError) {
207
+ try {
208
+ this.currentChat.state?.setStatus(import_agent_state.AgentStatus.FAILED);
209
+ this.currentChat.state?.setCurrentActivity("stopped");
210
+ this.currentChat.state?.setLastError({ code: llmError?.code ?? AGENT_ERROR_CODES.RUN_FAILED, message, isRetryable: llmError?.isRetryable ?? true, timestamp: /* @__PURE__ */ new Date() });
211
+ this.currentChat.addTrace({ node: "agent", kind: "agent", reasoning: `Run failed: ${message}` });
212
+ this.currentChat.failTask();
213
+ await this.persist();
214
+ } catch (saveError) {
215
+ this.logger.error({ error: saveError?.message ?? saveError }, "[AGENT] Failed to persist failed run state");
216
+ } finally {
217
+ await this.disconnectMcpServers();
218
+ }
219
+ }
220
+ fingerprint(entity) {
221
+ return JSON.stringify(entity.toDocument());
222
+ }
223
+ async loadTasks() {
224
+ const chatId = this.currentChat._id?.toString();
225
+ if (!chatId) return;
226
+ const { data: taskDocs } = await (0, import_tasks.listAgentTasksByChat)({ chatId, currentUser: this.currentUser });
227
+ const tasks = taskDocs.map((doc) => import_agent_task.AgentTask.fromJSON(doc)).reverse();
228
+ const activeTaskId = this.currentChat.state?.activeTaskId;
229
+ if (activeTaskId && !tasks.some((task) => task.id === activeTaskId)) {
230
+ const { data } = await (0, import_tasks.getAgentTaskById)({ id: activeTaskId, currentUser: this.currentUser });
231
+ if (data) tasks.push(import_agent_task.AgentTask.fromJSON(data));
232
+ }
233
+ for (const task of tasks) {
234
+ task.hydrated = false;
235
+ this.snapshots.set(`task:${task.id}`, this.fingerprint(task));
236
+ }
237
+ this.currentChat.tasks = tasks;
238
+ const activeTask = this.currentChat.activeTask;
239
+ if (activeTask) await this.hydrateTask(activeTask);
240
+ }
241
+ async hydrateTask(task) {
242
+ if (task.hydrated) return;
243
+ const { data } = await (0, import_tasks.listAgentActionsByTask)({ taskId: task.id, currentUser: this.currentUser });
244
+ const actions = data.map((doc) => import_agent_action.AgentAction.fromJSON(doc));
245
+ for (const action of actions) this.snapshots.set(`action:${action.id}`, this.fingerprint(action));
246
+ task.setActions(actions);
247
+ }
248
+ async persistTask(task) {
249
+ const key = `task:${task.id}`;
250
+ const current = this.fingerprint(task);
251
+ const previous = this.snapshots.get(key);
252
+ if (previous === current) return;
253
+ if (previous === void 0) {
254
+ await (0, import_tasks.createAgentTask)({ payload: task.toJSON(), currentUser: this.currentUser });
255
+ } else {
256
+ await (0, import_tasks.updateAgentTask)({ id: task.id, payload: task.toJSON(), currentUser: this.currentUser });
257
+ }
258
+ this.snapshots.set(key, current);
259
+ }
260
+ async persistAction(action) {
261
+ const key = `action:${action.id}`;
262
+ const current = this.fingerprint(action);
263
+ const previous = this.snapshots.get(key);
264
+ if (previous === current) return;
265
+ if (previous === void 0) {
266
+ await (0, import_tasks.createAgentAction)({ payload: action.toJSON(), currentUser: this.currentUser });
267
+ } else {
268
+ await (0, import_tasks.updateAgentAction)({ id: action.id, payload: action.toJSON(), currentUser: this.currentUser });
269
+ }
270
+ this.snapshots.set(key, current);
271
+ }
272
+ async persistTasks() {
273
+ if (!this.currentChat._id) return;
274
+ for (const task of this.currentChat.tasks) {
275
+ await this.persistTask(task);
276
+ if (task.hydrated) await Promise.all(task.actions.map((action) => this.persistAction(action)));
277
+ }
278
+ }
279
+ async flushTraces() {
280
+ const traces = this.currentChat.drainTraces();
281
+ const chatId = this.currentChat._id;
282
+ if (!traces.length || !chatId) return;
283
+ try {
284
+ await (0, import_traces.createAgentTraces)({
285
+ payload: traces.map((trace) => ({
286
+ chatId,
287
+ taskId: trace.taskId,
288
+ node: trace.node,
289
+ reasoning: trace.reasoning,
290
+ timestamp: trace.timestamp,
291
+ answerId: this.answerId,
292
+ messageId: this.userMessageId,
293
+ kind: trace.kind ?? "skill",
294
+ iteration: trace.iteration ?? this.iteration,
295
+ durationMs: trace.durationMs
296
+ })),
297
+ currentUser: this.currentUser
298
+ });
299
+ } catch (error) {
300
+ this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to persist traces");
301
+ }
302
+ }
303
+ async persist(props) {
304
+ await this.persistTasks();
305
+ await this.saveChat(props);
306
+ await this.flushTraces();
307
+ }
308
+ ensureTools() {
309
+ this.mcpLoading ??= this.loadMcpServers();
310
+ return this.mcpLoading.then(() => this.tools);
311
+ }
312
+ async loadMcpServers() {
313
+ if (!this.currentUser) return;
314
+ let servers = [];
315
+ try {
316
+ const response = await (0, import_mcp_servers.listMcpServersByUser)({ currentUser: this.currentUser });
317
+ servers = response?.data ?? [];
318
+ } catch (error) {
319
+ this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to list MCP servers");
320
+ this._unavailableSources.push("configured tool servers");
321
+ return;
322
+ }
323
+ const results = await Promise.allSettled(servers.map(async (props) => {
324
+ const mcpServer = import_entities.McpServer.fromJSON(props);
325
+ for (let attempt = 0; attempt <= MCP_CONNECT_RETRY_DELAYS_MS.length; attempt++) {
326
+ try {
327
+ const mcpClient = await mcpServer.connect();
328
+ const { tools: mcpTools } = await mcpClient.listTools();
329
+ const tools = mcpTools.map((mcpTool) => import_tool.Tool.fromMcp(mcpTool, mcpClient, { namespace: mcpServer.name ?? "mcp" }));
330
+ return { mcpServer, tools };
331
+ } catch (error) {
332
+ this.logger.error({ error, mcpServer: mcpServer.name, attempt: attempt + 1 }, "[AGENT] Failed to connect MCP server");
333
+ await Promise.resolve().then(() => mcpServer.disconnect()).catch(() => void 0);
334
+ const delay = MCP_CONNECT_RETRY_DELAYS_MS[attempt];
335
+ if (delay === void 0) break;
336
+ await new Promise((resolve) => setTimeout(resolve, delay));
337
+ }
338
+ }
339
+ this._unavailableSources.push(mcpServer.name ?? "mcp");
340
+ this.currentChat?.addTrace({ node: "agent", kind: "agent", reasoning: `Tool source unavailable: ${mcpServer.name ?? "mcp"}` });
341
+ return void 0;
342
+ }));
343
+ for (const result of results) {
344
+ if (result.status === "rejected") {
345
+ this.logger.error({ error: result.reason }, "[AGENT] Failed to load MCP server");
346
+ continue;
347
+ }
348
+ if (!result.value) continue;
349
+ this._mcpTools.push(...result.value.tools);
350
+ this._mcps.push(result.value.mcpServer);
351
+ }
352
+ }
353
+ async disconnectMcpServers() {
354
+ await this.mcpLoading?.catch(() => void 0);
355
+ const servers = this._mcps;
356
+ this._mcps = [];
357
+ this._mcpTools = [];
358
+ this.mcpLoading = void 0;
359
+ await Promise.allSettled(servers.map((mcpServer) => mcpServer.disconnect().catch((error) => {
360
+ this.logger.error({ error, mcpServer: mcpServer.name }, "[AGENT] Failed to disconnect MCP server");
361
+ })));
362
+ }
363
+ async saveChat(props) {
364
+ if (this.currentChat?._id) {
365
+ this.logger.debug("[AGENT] Updating chat...");
366
+ if (!props?.resetStop) {
367
+ this.logger.debug("[Agent] Removing stopRequested");
368
+ delete this.currentChat.state?.stopRequested;
369
+ }
370
+ await (0, import_chats.updateChat)({
371
+ id: this.currentChat._id.toString(),
372
+ payload: this.currentChat.toJSON(),
373
+ currentUser: this.currentUser
374
+ });
375
+ }
376
+ }
377
+ async checkInterruptionRequest() {
378
+ const chatId = this.currentChat?._id?.toString();
379
+ if (!chatId) return;
380
+ const { data } = await (0, import_chats.getChatById)({ id: chatId, select: { state: 1 }, currentUser: this.currentUser });
381
+ if (data?.state?.stopRequested) this.stopRequested = true;
382
+ }
383
+ async runLoop() {
384
+ this.logger.info("[AGENT] Agent Loop started");
385
+ let iterations = 0;
386
+ while (!this.stopLoop) {
387
+ if (iterations >= this.maxIterations) {
388
+ this.logger.error({ maxIterations: this.maxIterations, loop: this._loop.name }, "[AGENT] Iteration limit reached");
389
+ this.currentChat.state?.setStatus(import_agent_state.AgentStatus.FAILED);
390
+ this.currentChat.state?.setLastError({
391
+ code: AGENT_ERROR_CODES.MAX_ITERATIONS_REACHED,
392
+ message: `The agent loop "${this._loop.name}" reached the limit of ${this.maxIterations} iterations`,
393
+ isRetryable: false,
394
+ timestamp: /* @__PURE__ */ new Date()
395
+ });
396
+ this.currentChat.addTrace({ node: "agent", kind: "agent", reasoning: "Iteration limit reached" });
397
+ this.currentChat.failTask();
398
+ this.stopLoop = true;
399
+ break;
400
+ }
401
+ iterations++;
402
+ this.iteration = iterations;
403
+ await this.checkInterruptionRequest();
404
+ if (this.stopRequested) {
405
+ this.stopLoop = true;
406
+ this.currentChat.state?.setStatus(import_agent_state.AgentStatus.IDLE);
407
+ this.resetNextNode();
408
+ this.currentChat.state?.setStopRequested(false);
409
+ break;
410
+ }
411
+ const activeTask = this.currentChat.activeTask;
412
+ const nodeName = activeTask?.nextNode ?? this.pendingNextNode ?? this.resolveNodeName(this._loop.initialNode);
413
+ const nodeFn = nodeName ? this._loop.nodes[nodeName] : void 0;
414
+ if (!nodeFn) {
415
+ this.logger.error({ nodeName, loop: this._loop.name }, "[AGENT] Node not found in current loop");
416
+ this.currentChat.state?.setStatus(import_agent_state.AgentStatus.FAILED);
417
+ this.currentChat.state?.setLastError({
418
+ code: AGENT_ERROR_CODES.NODE_NOT_FOUND,
419
+ message: `Node "${nodeName}" is not implemented by loop "${this._loop.name}"`,
420
+ isRetryable: false,
421
+ timestamp: /* @__PURE__ */ new Date()
422
+ });
423
+ this.currentChat.addTrace({ node: nodeName ?? "", kind: "agent", reasoning: "Node not found" });
424
+ this.stopLoop = true;
425
+ break;
426
+ }
427
+ const startedAt = Date.now();
428
+ await nodeFn.call(this._loop, this.buildRunContext());
429
+ this.currentChat.addTrace({ node: nodeName, kind: "node", durationMs: Date.now() - startedAt, taskId: activeTask?.id });
430
+ await this.persist();
431
+ if (!this.currentChat.state || this.currentChat.state?.status === import_agent_state.AgentStatus.IDLE || this.currentChat.state?.status === import_agent_state.AgentStatus.FAILED || this.currentChat.state?.status === import_agent_state.AgentStatus.AWAITING_USER_INPUT || this.currentChat.state?.status === import_agent_state.AgentStatus.AWAITING_USER_CONFIRMATION) {
432
+ this.stopLoop = true;
433
+ break;
434
+ }
435
+ }
436
+ if (this.currentChat.state?.status === import_agent_state.AgentStatus.PROCESSING) this.currentChat.state.setStatus(import_agent_state.AgentStatus.IDLE);
437
+ this.logger.info("[AGENT] Agent Loop stopped");
438
+ }
439
+ resetNextNode() {
440
+ const resolved = this.resolveNodeName(this._loop.initialNode);
441
+ const active = this.currentChat.activeTask;
442
+ if (active) active.setNextNode(resolved);
443
+ else this.pendingNextNode = resolved;
444
+ }
445
+ resolveNodeName(node) {
446
+ if (typeof node !== "function") return node;
447
+ return Object.entries(this._loop.nodes).find(([, fn]) => fn === node)?.[0];
448
+ }
449
+ searchTools(keywords, opts) {
450
+ this.logger.debug({ opts }, "[AGENT] Searching tools");
451
+ const page = opts?.page ?? 1;
452
+ const limit = opts?.limit ?? 5;
453
+ const matchedTools = (0, import_rank_tools_by_keywords.rankToolsByKeywords)(keywords, this.tools.filter(import_tool_catalog.isDeclarable));
454
+ const startIndex = (page - 1) * limit;
455
+ return matchedTools.slice(startIndex, startIndex + limit);
456
+ }
457
+ reply(content) {
458
+ const isFirstReply = this.replyCount === 0;
459
+ this.replyCount++;
460
+ this.currentChat.pushMessage({ _id: isFirstReply ? this.answerId : void 0, answerId: this.answerId, role: "assistant", content });
461
+ }
462
+ get baseParams() {
463
+ return {
464
+ currentUser: this.currentUser,
465
+ sessionId: this.currentChat._id?.toString() ?? "",
466
+ answerId: this.answerId
467
+ };
468
+ }
469
+ getWorkspace() {
470
+ this.workspace ??= new import_workspace.AgentWorkspace(this.currentChat._id.toString(), this.currentUser, this.answerId);
471
+ return this.workspace;
472
+ }
473
+ getPipeline() {
474
+ this.pipeline ??= new import_tool_pipeline.ToolPipeline({
475
+ workspace: this.getWorkspace(),
476
+ tools: () => this.tools,
477
+ searchTools: (keywords, opts) => this.searchTools(keywords, opts),
478
+ baseParams: this.baseParams,
479
+ logger: this.logger
480
+ });
481
+ return this.pipeline;
482
+ }
483
+ async runAction(action, opts) {
484
+ await this.ensureTools();
485
+ const task = this.currentChat.activeTask;
486
+ if (!task) throw new Error("[AGENT] There is no active task to run the action in");
487
+ return this.getPipeline().run(task, action, opts);
488
+ }
489
+ async reopenTask(taskId) {
490
+ const task = this.currentChat.getTask(taskId);
491
+ if (!task) return void 0;
492
+ await this.hydrateTask(task);
493
+ return this.currentChat.reopenTask(taskId);
494
+ }
495
+ buildRunContext() {
496
+ const sessionId = this.currentChat._id?.toString() ?? "";
497
+ const agent = this;
498
+ return {
499
+ identity: this._identity,
500
+ task: this.currentChat.activeTask,
501
+ chat: this.currentChat,
502
+ chatOptions: this.chatOptions,
503
+ currentUser: this.currentUser,
504
+ currentSession: this.currentSession,
505
+ currentMessage: this.currentMessage,
506
+ answerId: this.answerId,
507
+ get tools() {
508
+ return agent.tools;
509
+ },
510
+ ensureTools: () => this.ensureTools(),
511
+ searchTools: this.searchTools.bind(this),
512
+ toolCatalog: async () => {
513
+ const catalog = (0, import_tool_catalog.buildToolCatalog)(await this.ensureTools(), import_native_tools.NATIVE_TOOLS, this.currentChat.activeTask?.discoveredToolNames ?? []);
514
+ return this._unavailableSources.length ? { ...catalog, context: { ...catalog.context, unavailable_sources: this._unavailableSources } } : catalog;
515
+ },
516
+ workspace: this.getWorkspace(),
517
+ runAction: (action, opts) => this.runAction(action, opts),
518
+ requiresApproval: (action) => this.getPipeline().requiresApproval(action),
519
+ reopenTask: (taskId) => this.reopenTask(taskId),
520
+ baseParams: this.baseParams,
521
+ skillParams: {
522
+ provider: this.chatOptions?.modelProvider,
523
+ modelName: this.chatOptions?.modelName,
524
+ sessionId,
525
+ answerId: this.answerId,
526
+ userMessage: this.currentMessage,
527
+ currentUser: this.currentUser,
528
+ currentSession: this.currentSession,
529
+ chat: this.currentChat
530
+ },
531
+ reply: (content) => this.reply(content),
532
+ setNextNode: (node) => {
533
+ const resolved = this.resolveNodeName(node);
534
+ const active = this.currentChat.activeTask;
535
+ if (active) active.setNextNode(resolved);
536
+ else this.pendingNextNode = resolved;
537
+ },
538
+ logger: this.logger
539
+ };
540
+ }
541
+ }
542
+ // Annotate the CommonJS export names for ESM import in node:
543
+ 0 && (module.exports = {
544
+ AGENT_ERROR_CODES,
545
+ Agent
546
+ });