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