openloops 0.1.38 → 0.2.1

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 (266) hide show
  1. package/README.md +60 -5
  2. package/dist/clients/index.d.ts +2 -2
  3. package/dist/clients/index.js +4 -4
  4. package/dist/clients/index.mjs +2 -2
  5. package/dist/clients/llm/index.d.ts +1 -0
  6. package/dist/{loops/plan-execute → clients/llm}/index.js +4 -4
  7. package/dist/clients/llm/index.mjs +1 -0
  8. package/dist/clients/{llm-client.d.ts → llm/llm-client.d.ts} +3 -14
  9. package/dist/clients/{llm-client.js → llm/llm-client.js} +14 -37
  10. package/dist/clients/{llm-client.mjs → llm/llm-client.mjs} +15 -38
  11. package/dist/clients/{llm-error.mjs → llm/llm-error.mjs} +1 -1
  12. package/dist/clients/{llm-types.d.ts → llm/llm-types.d.ts} +1 -1
  13. package/dist/clients/llm/model-resolution.d.ts +20 -0
  14. package/dist/clients/llm/model-resolution.js +83 -0
  15. package/dist/clients/llm/model-resolution.mjs +46 -0
  16. package/dist/clients/{pi-ai-adapter.mjs → llm/pi-ai-adapter.mjs} +1 -1
  17. package/dist/clients/serper/index.d.ts +1 -0
  18. package/dist/clients/serper/index.js +22 -0
  19. package/dist/clients/serper/index.mjs +1 -0
  20. package/dist/clients/{serper-client.js → serper/serper-client.js} +2 -2
  21. package/dist/clients/{serper-client.mjs → serper/serper-client.mjs} +3 -3
  22. package/dist/harness/agent-loop.d.ts +0 -1
  23. package/dist/harness/agent.d.ts +6 -1
  24. package/dist/harness/agent.js +21 -13
  25. package/dist/harness/agent.mjs +21 -13
  26. package/dist/harness/native-tools.d.ts +1 -1
  27. package/dist/{loops/shared → harness}/skills/approval-request.d.ts +1 -1
  28. package/dist/{loops/shared → harness}/skills/approval-request.js +1 -1
  29. package/dist/{loops/shared → harness}/skills/approval-request.mjs +2 -2
  30. package/dist/{loops/shared → harness}/skills/autonomous-answer.d.ts +1 -1
  31. package/dist/{loops/shared → harness}/skills/autonomous-answer.js +1 -1
  32. package/dist/{loops/shared → harness}/skills/autonomous-answer.mjs +2 -2
  33. package/dist/{loops/shared → harness}/skills/confirmation-gate.d.ts +1 -1
  34. package/dist/{loops/shared → harness}/skills/confirmation-gate.js +1 -1
  35. package/dist/{loops/shared → harness}/skills/confirmation-gate.mjs +2 -2
  36. package/dist/harness/skills/index.d.ts +4 -0
  37. package/dist/{loops/plan-execute → harness}/skills/index.js +8 -8
  38. package/dist/harness/skills/index.mjs +4 -0
  39. package/dist/{loops/shared → harness}/skills/mcp-change-review.d.ts +1 -1
  40. package/dist/{loops/shared → harness}/skills/mcp-change-review.js +1 -1
  41. package/dist/{loops/shared → harness}/skills/mcp-change-review.mjs +2 -2
  42. package/dist/harness/tool-catalog.d.ts +1 -1
  43. package/dist/loops/index.d.ts +0 -1
  44. package/dist/loops/index.js +0 -2
  45. package/dist/loops/index.mjs +0 -1
  46. package/dist/loops/shared/skills/index.d.ts +0 -4
  47. package/dist/loops/shared/skills/index.js +1 -9
  48. package/dist/loops/shared/skills/index.mjs +0 -4
  49. package/dist/services/agentic-jobs/entities/agentic-job-run.entity.d.ts +42 -0
  50. package/dist/services/agentic-jobs/entities/agentic-job-run.entity.js +103 -0
  51. package/dist/services/agentic-jobs/entities/agentic-job-run.entity.mjs +80 -0
  52. package/dist/services/agentic-jobs/entities/agentic-job.entity.d.ts +39 -0
  53. package/dist/services/agentic-jobs/entities/agentic-job.entity.js +113 -0
  54. package/dist/services/agentic-jobs/entities/agentic-job.entity.mjs +90 -0
  55. package/dist/services/agentic-jobs/entities/index.d.ts +3 -0
  56. package/dist/services/agentic-jobs/entities/index.js +26 -0
  57. package/dist/services/agentic-jobs/entities/index.mjs +3 -0
  58. package/dist/services/agentic-jobs/entities/recurrence.d.ts +18 -0
  59. package/dist/services/agentic-jobs/entities/recurrence.js +84 -0
  60. package/dist/services/agentic-jobs/entities/recurrence.mjs +59 -0
  61. package/dist/services/agentic-jobs/index.d.ts +4 -0
  62. package/dist/services/agentic-jobs/index.js +28 -0
  63. package/dist/services/agentic-jobs/index.mjs +4 -0
  64. package/dist/services/agentic-jobs/module.d.ts +31 -0
  65. package/dist/services/agentic-jobs/module.js +132 -0
  66. package/dist/services/agentic-jobs/module.mjs +95 -0
  67. package/dist/services/agentic-jobs/repositories/agentic-job-run.repository.d.ts +11 -0
  68. package/dist/services/agentic-jobs/repositories/agentic-job-run.repository.js +71 -0
  69. package/dist/services/agentic-jobs/repositories/agentic-job-run.repository.mjs +42 -0
  70. package/dist/services/agentic-jobs/repositories/agentic-job.repository.d.ts +27 -0
  71. package/dist/services/agentic-jobs/repositories/agentic-job.repository.js +127 -0
  72. package/dist/services/agentic-jobs/repositories/agentic-job.repository.mjs +98 -0
  73. package/dist/services/agentic-jobs/repositories/index.d.ts +2 -0
  74. package/dist/services/agentic-jobs/repositories/index.js +24 -0
  75. package/dist/services/agentic-jobs/repositories/index.mjs +2 -0
  76. package/dist/services/agentic-jobs/runner/agentic-job-runner.d.ts +48 -0
  77. package/dist/services/agentic-jobs/runner/agentic-job-runner.js +181 -0
  78. package/dist/services/agentic-jobs/runner/agentic-job-runner.mjs +157 -0
  79. package/dist/services/agentic-jobs/use-cases/attach-agentic-job-run-chat.use-case.d.ts +15 -0
  80. package/dist/services/agentic-jobs/use-cases/attach-agentic-job-run-chat.use-case.js +58 -0
  81. package/dist/services/agentic-jobs/use-cases/attach-agentic-job-run-chat.use-case.mjs +29 -0
  82. package/dist/services/agentic-jobs/use-cases/claim-due-agentic-jobs.use-case.d.ts +29 -0
  83. package/dist/services/agentic-jobs/use-cases/claim-due-agentic-jobs.use-case.js +110 -0
  84. package/dist/services/agentic-jobs/use-cases/claim-due-agentic-jobs.use-case.mjs +81 -0
  85. package/dist/services/agentic-jobs/use-cases/create-agentic-job.use-case.d.ts +14 -0
  86. package/dist/services/agentic-jobs/use-cases/create-agentic-job.use-case.js +73 -0
  87. package/dist/services/agentic-jobs/use-cases/create-agentic-job.use-case.mjs +44 -0
  88. package/dist/services/agentic-jobs/use-cases/delete-agentic-job.use-case.d.ts +15 -0
  89. package/dist/services/agentic-jobs/use-cases/delete-agentic-job.use-case.js +65 -0
  90. package/dist/services/agentic-jobs/use-cases/delete-agentic-job.use-case.mjs +36 -0
  91. package/dist/services/agentic-jobs/use-cases/finish-agentic-job-run.use-case.d.ts +19 -0
  92. package/dist/services/agentic-jobs/use-cases/finish-agentic-job-run.use-case.js +75 -0
  93. package/dist/services/agentic-jobs/use-cases/finish-agentic-job-run.use-case.mjs +46 -0
  94. package/dist/services/agentic-jobs/use-cases/get-agentic-job-by-id.use-case.d.ts +14 -0
  95. package/dist/services/agentic-jobs/use-cases/get-agentic-job-by-id.use-case.js +55 -0
  96. package/dist/services/agentic-jobs/use-cases/get-agentic-job-by-id.use-case.mjs +26 -0
  97. package/dist/services/agentic-jobs/use-cases/list-agentic-job-runs-by-job.use-case.d.ts +16 -0
  98. package/dist/services/agentic-jobs/use-cases/list-agentic-job-runs-by-job.use-case.js +57 -0
  99. package/dist/services/agentic-jobs/use-cases/list-agentic-job-runs-by-job.use-case.mjs +28 -0
  100. package/dist/services/agentic-jobs/use-cases/list-agentic-job-runs-by-user.use-case.d.ts +16 -0
  101. package/dist/services/agentic-jobs/use-cases/list-agentic-job-runs-by-user.use-case.js +57 -0
  102. package/dist/services/agentic-jobs/use-cases/list-agentic-job-runs-by-user.use-case.mjs +28 -0
  103. package/dist/services/agentic-jobs/use-cases/list-agentic-jobs-by-user.use-case.d.ts +15 -0
  104. package/dist/services/agentic-jobs/use-cases/list-agentic-jobs-by-user.use-case.js +57 -0
  105. package/dist/services/agentic-jobs/use-cases/list-agentic-jobs-by-user.use-case.mjs +28 -0
  106. package/dist/services/agentic-jobs/use-cases/preview-agentic-job-runs.use-case.d.ts +15 -0
  107. package/dist/services/agentic-jobs/use-cases/preview-agentic-job-runs.use-case.js +52 -0
  108. package/dist/services/agentic-jobs/use-cases/preview-agentic-job-runs.use-case.mjs +23 -0
  109. package/dist/services/agentic-jobs/use-cases/renew-agentic-job-lease.use-case.d.ts +18 -0
  110. package/dist/services/agentic-jobs/use-cases/renew-agentic-job-lease.use-case.js +58 -0
  111. package/dist/services/agentic-jobs/use-cases/renew-agentic-job-lease.use-case.mjs +29 -0
  112. package/dist/services/agentic-jobs/use-cases/start-agentic-job-run.use-case.d.ts +21 -0
  113. package/dist/services/agentic-jobs/use-cases/start-agentic-job-run.use-case.js +67 -0
  114. package/dist/services/agentic-jobs/use-cases/start-agentic-job-run.use-case.mjs +38 -0
  115. package/dist/services/agentic-jobs/use-cases/sync-agentic-job-run.use-case.d.ts +20 -0
  116. package/dist/services/agentic-jobs/use-cases/sync-agentic-job-run.use-case.js +86 -0
  117. package/dist/services/agentic-jobs/use-cases/sync-agentic-job-run.use-case.mjs +56 -0
  118. package/dist/services/agentic-jobs/use-cases/sync-agentic-job-runs.use-case.d.ts +19 -0
  119. package/dist/services/agentic-jobs/use-cases/sync-agentic-job-runs.use-case.js +68 -0
  120. package/dist/services/agentic-jobs/use-cases/sync-agentic-job-runs.use-case.mjs +39 -0
  121. package/dist/services/agentic-jobs/use-cases/update-agentic-job.use-case.d.ts +15 -0
  122. package/dist/services/agentic-jobs/use-cases/update-agentic-job.use-case.js +83 -0
  123. package/dist/services/agentic-jobs/use-cases/update-agentic-job.use-case.mjs +54 -0
  124. package/dist/services/agentic-jobs/utils/job-fields.d.ts +14 -0
  125. package/dist/services/agentic-jobs/utils/job-fields.js +61 -0
  126. package/dist/services/agentic-jobs/utils/job-fields.mjs +37 -0
  127. package/dist/services/agentic-jobs/utils/next-run.d.ts +4 -0
  128. package/dist/services/agentic-jobs/utils/next-run.js +62 -0
  129. package/dist/services/agentic-jobs/utils/next-run.mjs +37 -0
  130. package/dist/services/agentic-jobs/utils/open-run.d.ts +12 -0
  131. package/dist/services/agentic-jobs/utils/open-run.js +47 -0
  132. package/dist/services/agentic-jobs/utils/open-run.mjs +24 -0
  133. package/dist/services/agentic-jobs/utils/settings.d.ts +2 -0
  134. package/dist/services/agentic-jobs/utils/settings.js +34 -0
  135. package/dist/services/agentic-jobs/utils/settings.mjs +10 -0
  136. package/dist/services/chats/entities/chat.entity.d.ts +0 -5
  137. package/dist/services/chats/entities/chat.entity.js +0 -10
  138. package/dist/services/chats/entities/chat.entity.mjs +0 -10
  139. package/dist/services/llmcalls/module.d.ts +4 -2
  140. package/dist/services/llmcalls/module.js +13 -6
  141. package/dist/services/llmcalls/module.mjs +11 -5
  142. package/dist/services/llmcalls/use-cases/get-llm-usage-by-chat.use-case.d.ts +14 -0
  143. package/dist/services/llmcalls/use-cases/get-llm-usage-by-chat.use-case.js +62 -0
  144. package/dist/services/llmcalls/use-cases/get-llm-usage-by-chat.use-case.mjs +33 -0
  145. package/dist/services/llmcalls/use-cases/get-llm-usage-by-message.use-case.d.ts +14 -0
  146. package/dist/services/llmcalls/use-cases/{get-llm-usage.use-case.js → get-llm-usage-by-message.use-case.js} +18 -37
  147. package/dist/services/llmcalls/use-cases/get-llm-usage-by-message.use-case.mjs +33 -0
  148. package/dist/services/llmcalls/utils/usage-totals.d.ts +20 -0
  149. package/dist/services/llmcalls/utils/usage-totals.js +31 -0
  150. package/dist/services/llmcalls/utils/usage-totals.mjs +29 -0
  151. package/dist/services/tasks/entities/agent-task.entity.d.ts +2 -24
  152. package/dist/services/tasks/entities/agent-task.entity.js +2 -75
  153. package/dist/services/tasks/entities/agent-task.entity.mjs +2 -75
  154. package/dist/services/users/entities/user-default-model.d.ts +11 -0
  155. package/dist/services/users/entities/user-default-model.js +42 -0
  156. package/dist/services/users/entities/user-default-model.mjs +19 -0
  157. package/dist/services/users/entities/user-preferences.d.ts +4 -1
  158. package/dist/services/users/entities/user-preferences.js +8 -3
  159. package/dist/services/users/entities/user-preferences.mjs +8 -3
  160. package/dist/services/users/use-cases/create-user.use-case.js +3 -1
  161. package/dist/services/users/use-cases/create-user.use-case.mjs +3 -1
  162. package/dist/services/users/use-cases/update-user.use-case.js +4 -1
  163. package/dist/services/users/use-cases/update-user.use-case.mjs +4 -1
  164. package/dist/services/users/utils/default-model.d.ts +6 -0
  165. package/dist/services/users/utils/default-model.js +38 -0
  166. package/dist/services/users/utils/default-model.mjs +15 -0
  167. package/dist/skills/call-modes.d.ts +1 -1
  168. package/dist/skills/skill.d.ts +1 -1
  169. package/dist/skills/skill.js +1 -1
  170. package/dist/skills/skill.mjs +1 -1
  171. package/dist/tools/core/web-search/web-search.tool.js +1 -1
  172. package/dist/tools/core/web-search/web-search.tool.mjs +1 -1
  173. package/docs/README.md +46 -0
  174. package/docs/agent.md +202 -0
  175. package/docs/agentic-jobs.md +207 -0
  176. package/docs/assets/harness-car.svg +79 -0
  177. package/docs/authentication.md +40 -0
  178. package/docs/chats.md +88 -0
  179. package/docs/configuration.md +83 -0
  180. package/docs/guardrails.md +71 -0
  181. package/docs/harness.md +92 -0
  182. package/docs/integration-guide.md +138 -0
  183. package/docs/llms.txt +35 -0
  184. package/docs/loops.md +136 -0
  185. package/docs/mcp-servers.md +148 -0
  186. package/docs/skills.md +104 -0
  187. package/docs/tools.md +90 -0
  188. package/docs/usage.md +91 -0
  189. package/docs/users.md +108 -0
  190. package/examples/agentic-jobs/create-agentic-job.ts +24 -0
  191. package/examples/agentic-jobs/list-agentic-job-runs.ts +28 -0
  192. package/examples/agentic-jobs/list-agentic-jobs.ts +25 -0
  193. package/examples/agentic-jobs/preview-agentic-job-runs.ts +16 -0
  194. package/examples/agentic-jobs/run-agentic-job-now.ts +19 -0
  195. package/examples/agentic-jobs/run-agentic-job-worker.ts +29 -0
  196. package/examples/agentic-jobs/update-agentic-job.ts +36 -0
  197. package/examples/authentication/login.ts +17 -0
  198. package/examples/chats/delete-chat.ts +32 -0
  199. package/examples/chats/get-chat-by-id.ts +32 -0
  200. package/examples/chats/list-autonomous-chats.ts +23 -0
  201. package/examples/chats/list-chats.ts +20 -0
  202. package/examples/guardrails/custom-guard.ts +11 -0
  203. package/examples/loops/custom-loop.ts +50 -0
  204. package/examples/mcps/create-mcp.ts +24 -0
  205. package/examples/mcps/decide-mcp.ts +40 -0
  206. package/examples/mcps/delete-mcp.ts +32 -0
  207. package/examples/mcps/get-mcp-by-id.ts +17 -0
  208. package/examples/mcps/list-all-mcps.ts +14 -0
  209. package/examples/mcps/list-user-mcps.ts +23 -0
  210. package/examples/mcps/update-mcp.ts +23 -0
  211. package/examples/mcps/verify-mcp.ts +17 -0
  212. package/examples/run-agent/interrupt-agent.ts +16 -0
  213. package/examples/run-agent/run-agent-autonomous.ts +34 -0
  214. package/examples/run-agent/run-agent-strict-mode.ts +30 -0
  215. package/examples/run-agent/run-agent-with-confirmation.ts +49 -0
  216. package/examples/run-agent/run-agent-with-fallback-model.ts +25 -0
  217. package/examples/run-agent/run-agent-with-guards.ts +33 -0
  218. package/examples/run-agent/run-agent-with-hooks.ts +55 -0
  219. package/examples/run-agent/run-agent-with-identity.ts +36 -0
  220. package/examples/run-agent/run-agent-with-model.ts +33 -0
  221. package/examples/run-agent/run-agent-with-tools.ts +31 -0
  222. package/examples/tools/basic-tool.ts +35 -0
  223. package/examples/tools/destructive-tool.ts +34 -0
  224. package/examples/tools/web-search-tool.ts +37 -0
  225. package/examples/usage/get-chat-usage.ts +20 -0
  226. package/examples/usage/get-message-usage.ts +20 -0
  227. package/examples/usage/get-usage-stats-by-range.ts +23 -0
  228. package/examples/usage/get-usage-stats.ts +18 -0
  229. package/examples/users/create-user.ts +19 -0
  230. package/examples/users/delete-user.ts +36 -0
  231. package/examples/users/get-user-by-id.ts +18 -0
  232. package/examples/users/list-users.ts +18 -0
  233. package/examples/users/set-default-model.ts +36 -0
  234. package/examples/users/update-user.ts +22 -0
  235. package/package.json +9 -5
  236. package/dist/loops/plan-execute/index.d.ts +0 -1
  237. package/dist/loops/plan-execute/index.mjs +0 -1
  238. package/dist/loops/plan-execute/loop.d.ts +0 -26
  239. package/dist/loops/plan-execute/loop.js +0 -267
  240. package/dist/loops/plan-execute/loop.mjs +0 -249
  241. package/dist/loops/plan-execute/skills/action-planner.d.ts +0 -35
  242. package/dist/loops/plan-execute/skills/action-planner.js +0 -71
  243. package/dist/loops/plan-execute/skills/action-planner.mjs +0 -48
  244. package/dist/loops/plan-execute/skills/final-responder.d.ts +0 -7
  245. package/dist/loops/plan-execute/skills/final-responder.js +0 -58
  246. package/dist/loops/plan-execute/skills/final-responder.mjs +0 -35
  247. package/dist/loops/plan-execute/skills/index.d.ts +0 -4
  248. package/dist/loops/plan-execute/skills/index.mjs +0 -4
  249. package/dist/loops/plan-execute/skills/state-observer.d.ts +0 -10
  250. package/dist/loops/plan-execute/skills/state-observer.js +0 -61
  251. package/dist/loops/plan-execute/skills/state-observer.mjs +0 -38
  252. package/dist/loops/plan-execute/skills/strategy-engine.d.ts +0 -11
  253. package/dist/loops/plan-execute/skills/strategy-engine.js +0 -61
  254. package/dist/loops/plan-execute/skills/strategy-engine.mjs +0 -38
  255. package/dist/services/llmcalls/use-cases/get-llm-usage.use-case.d.ts +0 -24
  256. package/dist/services/llmcalls/use-cases/get-llm-usage.use-case.mjs +0 -51
  257. package/dist/skills/skill-runner.d.ts +0 -30
  258. package/dist/skills/skill-runner.js +0 -121
  259. package/dist/skills/skill-runner.mjs +0 -92
  260. /package/dist/clients/{llm-error.d.ts → llm/llm-error.d.ts} +0 -0
  261. /package/dist/clients/{llm-error.js → llm/llm-error.js} +0 -0
  262. /package/dist/clients/{llm-types.js → llm/llm-types.js} +0 -0
  263. /package/dist/clients/{llm-types.mjs → llm/llm-types.mjs} +0 -0
  264. /package/dist/clients/{pi-ai-adapter.d.ts → llm/pi-ai-adapter.d.ts} +0 -0
  265. /package/dist/clients/{pi-ai-adapter.js → llm/pi-ai-adapter.js} +0 -0
  266. /package/dist/clients/{serper-client.d.ts → serper/serper-client.d.ts} +0 -0
package/docs/chats.md ADDED
@@ -0,0 +1,88 @@
1
+ # Chats
2
+
3
+ Every conversation with an agent is a chat. The `Agent` creates and updates chats by itself, so you only use these functions to build the surrounding experience: a list of conversations, loading one, deleting it.
4
+
5
+ ```typescript
6
+ import { createChat, getChatById, listChatsByUser, updateChat, deleteChat } from 'openloops/chats'
7
+ ```
8
+
9
+ ## The chat record
10
+
11
+ | Field | Meaning |
12
+ | --- | --- |
13
+ | `state` | `status`, detected `language`, `activeTaskId`, `currentActivity`, `lastError` and `stopRequested`. See [agent](agent.md#the-result) for the statuses. |
14
+ | `settings` | `modelProvider` and `modelName` (the model the chat uses, saved on every run), `loopName`, `executionMode`, `notifyOnCompletion` and `isPrivateSession`. |
15
+ | `messages` | The conversation. Each message has `role` (`user` or `assistant`), `source`, `content`, `answerId` and `excludeFromContext`. |
16
+
17
+ Every assistant message of one answer shares an `answerId`. It is the id you pass as `messageId` to [usage](usage.md).
18
+
19
+ `role` says on which side of the conversation a message is, and `source` says who produced it:
20
+
21
+ | `source` | Meaning |
22
+ | --- | --- |
23
+ | `user` | Written by the person. |
24
+ | `model` | Written by the model: the answers and questions of the agent. |
25
+ | `harness` | Written by the harness: the reply of a [guardrail](guardrails.md), the question that asks for an approval, the acknowledgement of a cancelled task and, in an autonomous run, the answer of the automatic evaluator, which has `role: 'user'`. |
26
+
27
+ A message saved before `source` existed has none.
28
+
29
+ Messages with `excludeFromContext` are shown in the history but never sent to the model. They are the ones blocked by a guardrail and, in an autonomous run, the questions of the model together with the automatic answers.
30
+
31
+ ## Listing a user's chats
32
+
33
+ ```typescript
34
+ const result = await listChatsByUser({
35
+ options: { page: 1, limit: 10 },
36
+ currentUser,
37
+ })
38
+ ```
39
+
40
+ Sorted by last update, newest first. Defaults to page 1 and 10 chats.
41
+
42
+ ```typescript
43
+ const autonomous = await listChatsByUser({ executionMode: 'autonomous', currentUser })
44
+
45
+ const interactive = await listChatsByUser({ executionMode: 'interactive', currentUser })
46
+ ```
47
+
48
+ `executionMode` is optional. `autonomous` returns the chats that were created by an autonomous run and `interactive` returns the rest, including the chats saved before the mode existed. Combine it with `state.status` to show the autonomous runs that need attention: `awaiting_user_confirmation` or `awaiting_user_input` mean the run is paused until the user answers in the chat, and `failed` means it failed.
49
+
50
+ ## Getting one chat
51
+
52
+ ```typescript
53
+ const result = await getChatById({ id: chatId, currentUser })
54
+
55
+ const state = await getChatById({ id: chatId, select: { state: 1 }, currentUser })
56
+ ```
57
+
58
+ `select` limits the fields that come back, which is handy for polling the status of a long run.
59
+
60
+ ## Creating and updating
61
+
62
+ ```typescript
63
+ const created = await createChat({ payload: { settings: { loopName: 'agi' } }, currentUser })
64
+
65
+ await updateChat({ id: chatId, payload: { settings: { modelProvider: 'anthropic', modelName: 'claude-haiku-5-5' } }, currentUser })
66
+ ```
67
+
68
+ You rarely need `createChat`: `agent.run` creates the chat when you omit `chatId`.
69
+
70
+ ## Deleting a chat
71
+
72
+ ```typescript
73
+ await deleteChat({ id: chatId, currentUser })
74
+
75
+ await deleteChat({ id: chatId, hardDelete: true, currentUser })
76
+ ```
77
+
78
+ The first one is a soft delete. A hard delete is for admins only.
79
+
80
+ ## Stopping a running chat
81
+
82
+ ```typescript
83
+ import { Agent } from 'openloops/core'
84
+
85
+ await Agent.interruptExecution(chatId, currentUser)
86
+ ```
87
+
88
+ See [agent](agent.md#stopping-a-running-turn).
@@ -0,0 +1,83 @@
1
+ # Configuration
2
+
3
+ `openloops` reads its configuration from environment variables. Copy `.env.example` and fill in what you use.
4
+
5
+ | Variable | Required | What it is for |
6
+ | --- | --- | --- |
7
+ | `OPENLOOPS_DB_URI` | yes | MongoDB connection string. |
8
+ | `OPENLOOPS_DB_NAME` | no | Database name. Defaults to `openloops`. |
9
+ | `SECRET_MANAGER_KEY` | yes | Key used to decrypt values that start with `ENC:`. The library throws when it loads without it. |
10
+ | `ANTHROPIC_API_KEY` | for the default model | API key of the default provider, `anthropic`. |
11
+ | `OPENAI_API_KEY`, `GEMINI_API_KEY` | for those providers | API keys of the other providers you choose per chat. |
12
+ | `JWT_SECRET` | for `login` | Secret that signs the tokens. See [authentication](authentication.md). |
13
+ | `SERPER_API_KEY` | for `webSearchTool` | See [tools](tools.md#built-in-tools). |
14
+ | `AGENTIC_JOBS_POLL_INTERVAL_MS` | no | How often the runner of [agentic jobs](agentic-jobs.md) checks what is due, in milliseconds. Defaults to `60000`. |
15
+ | `AGENTIC_JOBS_LEASE_MS` | no | How long a job stays locked while it runs, in milliseconds. Defaults to `600000`. |
16
+ | `LLM_FALLBACK_PROVIDER`, `LLM_FALLBACK_MODEL` | no | The model to use when nothing else chooses one, for the whole deployment. Set both or neither. See [Which model a chat uses](#which-model-a-chat-uses). |
17
+ | `LLM_CALL_TIMEOUT_MS` | no | Longest time to wait for one attempt of a model call, in milliseconds. Defaults to `60000`. See [Timeouts](#timeouts). |
18
+ | `MCP_TOOL_TIMEOUT_MS` | no | Longest time to wait for a tool of an MCP server, in milliseconds. Defaults to `60000`. See [Timeouts](#timeouts). |
19
+ | `SENTRY_DSN` | no | Errors are reported to Sentry when set, unless `IS_LOCAL` is `true` or `NODE_ENV` is `development`. |
20
+ | `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL` | no | Traces every LLM call in Langfuse when all three are set. |
21
+ | `IS_LOCAL`, `NODE_ENV` | no | Local development switches. |
22
+
23
+ Any value can be stored encrypted by prefixing it with `ENC:`. It is decrypted with `SECRET_MANAGER_KEY` when it is read.
24
+
25
+ ## Which model a chat uses
26
+
27
+ Every time an agent runs, the model is the first one of this list that exists:
28
+
29
+ 1. **The model sent in that run** (`modelProvider` and `modelName`, always together). It is saved in the chat as the last one used.
30
+ 2. **The model saved in the chat.** If a run does not send one, the chat keeps using the last one that was sent, even if the user changed it between runs.
31
+ 3. **The default model of the user** (`preferences.defaultModel`, see [users](users.md#default-model)). It is used when the chat has no model yet, and it is saved in the chat.
32
+ 4. **The `fallbackModel` of the agent** (`new Agent({ fallbackModel: { provider, model } })`).
33
+ 5. **The fallback of the backend**: the variables `LLM_FALLBACK_PROVIDER` and `LLM_FALLBACK_MODEL`, which must be set together.
34
+ 6. **The fallback of the client**: `anthropic` with `claude-haiku-5-5`.
35
+
36
+ The model that is chosen is always saved in the chat, so changing the preference of a user or a fallback only affects the chats that start afterwards. Calls that are not made by an agent, such as the `call_ai` tool, use the default model of the user, then the fallback of the backend, then the one of the client.
37
+
38
+ ### The fallback of the client
39
+
40
+ The last fallback is `anthropic` with `claude-haiku-5-5`, so `ANTHROPIC_API_KEY` is the only model key you need to start.
41
+
42
+ It was chosen with the project's own evals (the `evals/` folder of the repository, results of 2026-10-12), in the default `plain_chat` mode and next to `gpt-6-luna`, `gpt-4o-mini` and `gemini-2.5-flash`. The skill rows use the real prompt of the reasoning engine:
43
+
44
+ | | `claude-haiku-5-5` | Others in the same evals |
45
+ | --- | --- | --- |
46
+ | Accuracy of the reasoning engine skill | 20 of 20 runs, in two executions | 20 of 20 for `gpt-6-luna`, 10 of 10 for `gpt-4o-mini` (one execution), 17 of 20 for `gemini-2.5-flash` |
47
+ | Accuracy on the 10 case model suite | 30 of 30 runs | 30 of 30 for `gpt-6-luna`, 27 of 30 for `gpt-4o-mini` |
48
+ | Prompt tokens read from the cache | 70% to 71% | 53% to 55% for `gpt-6-luna`, 62% for `gpt-4o-mini`, 44% to 73% for `gemini-2.5-flash` |
49
+ | Price per million tokens | $0.10 input, $0.50 output, $0.01 cached input | $0.10 and $0.50 for `gpt-6-luna`, $0.15 and $0.60 for `gpt-4o-mini` |
50
+
51
+ It is in the low price tier, it makes the most of the prompt cache, which matters because the prompt of an agent is large and repeats in every cycle, and it was among the most accurate. These are small samples (10 runs per setup in the skill evals, 3 repetitions per case in the model suite) and results change as providers update their models, so run the evals again before relying on the numbers for another prompt or model.
52
+
53
+ ## Timeouts
54
+
55
+ A model call that never answers would block the whole run, so every attempt has a time limit:
56
+
57
+ - **Model calls.** An attempt that does not answer within `LLM_CALL_TIMEOUT_MS` (60 seconds by default) is cancelled and the same call is made again, up to 3 attempts in total. When all of them time out, the run fails with the error code `LLM_TIMEOUT` and a message for the user, and the chat is left as `failed` so the user can send the message again. Waiting for a provider that asks to slow down is a separate mechanism and is not affected.
58
+ - **Tools of MCP servers.** A tool that does not answer within `MCP_TOOL_TIMEOUT_MS` (60 seconds by default) fails. The time starts again every time the server reports progress, so a long tool that is alive is not cut off. A tool call is never repeated automatically, because it may have changed something. The model is told that the result is unknown and that it must check before repeating it.
59
+ - **Langfuse.** Sending the trace of a call to Langfuse waits at most 5 seconds. If it takes longer or fails, the run continues without it.
60
+
61
+ A value that is not a positive whole number is ignored and the default is used.
62
+
63
+ ## Choosing the model
64
+
65
+ Choose the model of a chat when you run it:
66
+
67
+ ```typescript
68
+ await agent.run({
69
+ input: { message: 'hi' },
70
+ options: { modelProvider: 'anthropic', modelName: 'claude-haiku-5-5' },
71
+ currentUser,
72
+ })
73
+ ```
74
+
75
+ The provider and the model go together: sending only one of them is an error. The choice is saved in the chat and used for its next runs until you send another one. Set the API key variable that the provider expects.
76
+
77
+ The model call goes through a single client that retries, cancels and repeats an attempt that does not answer in time, waits when the provider asks to slow down, drops a temperature setting the model rejects and turns provider errors into messages that are safe to show to the user.
78
+
79
+ ## What is recorded
80
+
81
+ - Every LLM call, with its response, tokens and cost. See [usage](usage.md).
82
+ - A trace for every node and skill of a run, with the reasoning of the model. They are stored per chat for debugging and audit.
83
+ - The full ledger of actions of every task, with arguments, results and errors.
@@ -0,0 +1,71 @@
1
+ # Guardrails
2
+
3
+ A guardrail is a rule that can stop a message before the agent spends anything on it. Guards are plain instances, like tools, and you register them on the `Agent`.
4
+
5
+ ```typescript
6
+ import { Guard, inputGuards } from 'openloops/guardrails'
7
+ ```
8
+
9
+ ## Using the ready-made guards
10
+
11
+ ```typescript
12
+ import { Agent } from 'openloops/core'
13
+ import { AgiLoop } from 'openloops/loops'
14
+ import { inputGuards } from 'openloops/guardrails'
15
+
16
+ const agent = new Agent({
17
+ loop: new AgiLoop(),
18
+ guards: [inputGuards.blockCode, inputGuards.blockEmail],
19
+ })
20
+
21
+ agent.addGuard(inputGuards.blockCard)
22
+ ```
23
+
24
+ | Guard | Blocks |
25
+ | --- | --- |
26
+ | `inputGuards.blockCode` | Messages with fenced code blocks (\`\`\` or ~~~). Inline snippets and error messages pass. |
27
+ | `inputGuards.blockEmail` | Messages that contain an email address. |
28
+ | `inputGuards.blockCard` | Messages that contain a payment card number. It looks for 13 to 19 digits that pass the Luhn check, so order numbers are left alone. |
29
+
30
+ The agent also registers a guard that blocks messages longer than `maxInputLength` (100000 characters by default).
31
+
32
+ ## Changing the reply
33
+
34
+ Ready-made guards are shared and read-only. `withReply` returns a copy with another message but the same name, reference and handler:
35
+
36
+ ```typescript
37
+ agent.addGuard(inputGuards.blockCard.withReply('Never send card numbers in the chat.'))
38
+ ```
39
+
40
+ ## Writing your own
41
+
42
+ ```typescript
43
+ const noSpam = new Guard({
44
+ name: 'no_spam',
45
+ description: 'Blocks obvious spam phrases',
46
+ type: 'input',
47
+ reply: 'This looks like spam.',
48
+ handler: ({ message }) => /buy now/i.test(message)
49
+ ? { passed: false, reason: 'Spam phrase' }
50
+ : { passed: true },
51
+ })
52
+ ```
53
+
54
+ | Prop | What it does |
55
+ | --- | --- |
56
+ | `name` | Unique name. Identifies the guard in the traces. |
57
+ | `type` | Where it runs. Only `'input'` exists: it runs on the user message before the model. |
58
+ | `reply` | What the user receives when the guard blocks. |
59
+ | `ref` | Reference shown to the user and written to the traces. Derived from `name` when omitted. |
60
+ | `handler` | Receives `{ message, chat, currentUser, currentSession, skillParams, logger }` and returns `{ passed, reason? }`. May be async. |
61
+
62
+ ## What happens when a guard blocks
63
+
64
+ - Guards run in registration order and the first one that blocks wins.
65
+ - The model is never called and no task is created.
66
+ - The user receives the guard's `reply` followed by `Ref: <ref>`. The `reason` is never shown to the user. It is only written to the chat traces, so it can be specific.
67
+ - The blocked message is stored, flagged so it is left out of the history the model reads later.
68
+ - A chat that was waiting for a confirmation keeps waiting for it. Any other chat goes back to `idle`.
69
+ - If a handler throws, the message is blocked with a generic reply instead of passing unchecked.
70
+
71
+ Guards run on every run, including the message that answers a confirmation.
@@ -0,0 +1,92 @@
1
+ # The harness
2
+
3
+ An agent is three things: a **model** that thinks, a **harness** that gives it hands, memory and rules, and a **loop** that decides what it is for. `openloops` is the harness, and it ships a loop. You can change the model or the loop and the harness stays the same.
4
+
5
+ The harness is everything between a loop and the outside world. A loop decides what to do. The harness makes sure it is done safely, remembers it and shows the result back to the model in a form it can use. You get all of this by using [`Agent`](agent.md) with any loop.
6
+
7
+ ## The parts of the harness
8
+
9
+ | Part | What it does | Where it is explained |
10
+ | --- | --- | --- |
11
+ | **Transmission** | Takes the model to the outside world: the tools, found on demand and validated before they run. | [Tool pipeline](#tool-pipeline), [native tools](#native-tools), [tool discovery](#tool-discovery), [tools](tools.md), [MCP servers](mcp-servers.md) |
12
+ | **Brakes** | Stops the agent when it should stop: approvals, guardrails, timeouts and limits. | [Approvals](#approvals), [limits](#limits), [guardrails](guardrails.md), [timeouts](configuration.md#timeouts) |
13
+ | **Logbook** | Remembers and records: the workspace, the history of every task and the usage of every call. | [Workspace](#workspace), [observability](#observability), [chats](chats.md), [usage](usage.md) |
14
+ | **Steering** | Decides how the agent is driven: interactive or autonomous, scheduled, and with which model. | [Autonomous runs](#autonomous-runs), [language](#language), [the Agent](agent.md), [agentic jobs](agentic-jobs.md) |
15
+
16
+ ## Tool pipeline
17
+
18
+ Every action goes through the same pipeline before and after the tool runs:
19
+
20
+ | Step | What it does |
21
+ | --- | --- |
22
+ | Name resolution | Fixes a tool name written without its server prefix or with different case when there is only one match. |
23
+ | Approval | A destructive tool, or a tool of an MCP server the user has not approved, does not run until the user confirms. |
24
+ | References | Replaces `{{step_<ref>.output.<path>}}` and `{{context.<name>}}` placeholders in the arguments with real values. An unresolved reference fails the action with a clear message. |
25
+ | Validation | Checks the arguments against the tool's schema. |
26
+ | Grounding | Rejects identifiers (ids, uuids, hashes) that appear in the arguments but not in the user's messages nor in any previous result. Models invent ids, and this stops a made-up id from reaching a real system. The same check is applied to the final answer. |
27
+ | Duplicates | An identical call that already failed with a non transient error is blocked, so the model changes its approach instead of repeating it. |
28
+ | Execution | Runs the tool and records the output, the error and the timing. |
29
+ | Notes | Adds a short harness note to errors that say not found, validation failed or ambiguous match, telling the model what to do next. |
30
+ | Offloading | Large outputs are saved in the workspace and the model gets a stub it can read from. |
31
+
32
+ ## Native tools
33
+
34
+ The model always has these tools, next to the ones you register:
35
+
36
+ | Tool | What it does |
37
+ | --- | --- |
38
+ | `search_tools` | Finds tools by keyword. With `server` it lists the tools of one MCP server. |
39
+ | `read_context` | Reads a workspace item. Supports a `path` into structured content, paging and `find` to locate an entry inside a large result without reading the whole list. |
40
+ | `save_context` | Keeps a note in the task workspace. It can be referenced later as `{{context.<name>}}`. |
41
+ | `ask_user` | Pauses the task to ask the user a question. The answer comes back as the result of the action. |
42
+ | `respond` | Delivers the final answer and ends the task. |
43
+
44
+ ## Workspace
45
+
46
+ Tool outputs can be huge. When an output is longer than a few thousand characters it is saved in the workspace of the task. In the next cycle the model sees only a stub with its name, an outline of its shape and a preview, and loads what it needs with `read_context`. Outputs beyond a larger limit are never placed in the prompt at all. Notes the model saves with `save_context` live in the same place.
47
+
48
+ Workspace items belong to a chat and a task, so they survive between runs of the same conversation.
49
+
50
+ ## Tool discovery
51
+
52
+ When your agent has more than 15 local tools, the model gets a summary per source instead of the full catalog and finds tools with `search_tools`. Tools found this way are declared from the next cycle on.
53
+
54
+ MCP tools are always discovered this way. The model sees an index of the user's servers and searches or lists them on demand. See [MCP servers](mcp-servers.md#how-the-agent-uses-the-servers).
55
+
56
+ ## Approvals
57
+
58
+ Two things make an action wait for the user:
59
+
60
+ - The tool is destructive.
61
+ - The tool belongs to an MCP server that was never approved, or whose tools changed in a way that needs review.
62
+
63
+ The harness pauses the task, writes the question with a skill, stores the pending actions and leaves the chat as `awaiting_user_confirmation`. On the next message, a second skill reads the answer. When the user confirms, the pending actions run. When they decline, the task is cancelled. When the answer is unclear, the question is asked again.
64
+
65
+ Approving an MCP server through the chat records the decision on behalf of the user for that version of the server's manifest. If the server changes between the question and the answer, the approval is not applied and the user is asked again.
66
+
67
+ ## Autonomous runs
68
+
69
+ When a run is autonomous (`executionMode: 'autonomous'`, see [agent](agent.md#autonomous-mode)) the harness stands in for the user in one place and refuses to in the rest:
70
+
71
+ - Questions the model asks with `ask_user` go to a small evaluator skill. It sees the goal, the message that created the task, what the agent learned and its latest results. It answers only when that context settles the question and never grants permissions. Its answer reaches the model with a note that it is automatic, it is not stored as something the user said and it does not count as a source for identifiers, so an id it invents is still rejected by the grounding check.
72
+ - Approvals are never given automatically beyond what an interactive run already does. When something needs the user, the task is paused in the chat and resumes when the user answers.
73
+
74
+ ## Language
75
+
76
+ The reasoning engine reports in every turn the language in which it talks to the user, and the harness keeps it in `chat.state.language`. It is what every skill receives as `detected_language`. The model keeps the language of the conversation, changes it only when the user explicitly asks for another one, and ignores the language of pasted text, documents and tool results. A value that is not a two letter code is discarded and the previous language stays.
77
+
78
+ ## Limits
79
+
80
+ | Limit | Value |
81
+ | --- | --- |
82
+ | Loop iterations per run | `maxIterations`, 50 by default |
83
+ | Reasoning turns per task (`AgiLoop`) | 20 |
84
+ | Automatic answers per autonomous task | 3 |
85
+ | Tool calls per task (`AgiLoop`) | 40 |
86
+ | Message length | `maxInputLength`, 100000 characters by default |
87
+
88
+ When a task hits a limit the agent answers with what it achieved and says what it could not do.
89
+
90
+ ## Observability
91
+
92
+ Every node, skill and guard writes a trace with its reasoning. Every turn of a task records the model, mode, skill and loop versions, cost and number of blocks. Every action keeps its arguments, output and error. Together they answer why an agent did what it did.
@@ -0,0 +1,138 @@
1
+ # Integration guide
2
+
3
+ This page is for whoever builds the backend that uses `openloops`, a person or a coding agent. It tells you what to write. The other pages explain each piece in detail, and the [index](README.md) lists them.
4
+
5
+ ## What the package is, and what it is not
6
+
7
+ `openloops` is a harness for agents, and it gives you a set of use cases that read and write MongoDB. It does **not** include an HTTP server, routes, controllers, sessions or authorization. Your backend owns those, and calls `openloops` from its own handlers.
8
+
9
+ Requirements: Node 22 or newer and a MongoDB database. Install it with `npm install openloops` or `yarn add openloops`, set the environment variables of [configuration](configuration.md), and import from the subpaths (`openloops/core`, `openloops/mcps`, and so on).
10
+
11
+ ## Tell your coding agent where this is
12
+
13
+ A coding agent only finds this documentation if something points it here. Add this to the `CLAUDE.md` or `AGENTS.md` of your backend, once:
14
+
15
+ ```
16
+ This project uses the `openloops` package. Before writing code that uses it, read
17
+ `node_modules/openloops/docs/integration-guide.md`. Its full documentation is in
18
+ `node_modules/openloops/docs` and its examples are in `node_modules/openloops/examples`.
19
+ The package has no controllers: the authorization of every endpoint is the responsibility of this backend.
20
+ ```
21
+
22
+ ## The rule that matters most: authorization is yours
23
+
24
+ The use cases trust the `currentUser` you pass and the ids you give them.
25
+
26
+ - Functions that list by user (`listChatsByUser`, `listMcpServersByUser`, `listAgenticJobsByUser`, `listAgenticJobRunsByUser`) only return records of that user.
27
+ - Functions that take an **id** (`getChatById`, `updateChat`, `deleteChat`, `getMcpServerById`, `updateMcpServer`, `deleteMcpServer`, `decideMcpServerTrust`, `getAgenticJobById`, `updateAgenticJob`, `deleteAgenticJob`, `listAgenticJobRunsByJob`, `runner.runNow`) **do not check who owns the record**.
28
+
29
+ So, before calling any of the second kind, load the record and check that `ownerId` is the user of the request. Do it in one place, a middleware or a helper, and never pass an id from a request straight to a use case.
30
+
31
+ Also note that `getChatById` returns `{}` in `data` when the chat does not exist, so check for `data._id`.
32
+
33
+ ## Which endpoint calls what
34
+
35
+ | Your endpoint | `openloops` call |
36
+ | --- | --- |
37
+ | Send a message | `new Agent({ loop, tools, guards }).run({ input: { message, chatId? }, currentUser })` |
38
+ | Stop a running message | `Agent.interruptExecution(chatId, currentUser)` |
39
+ | List, read, delete chats | `listChatsByUser` (with `executionMode` to separate interactive from autonomous), `getChatById`, `deleteChat` |
40
+ | Poll the state of a chat | `getChatById({ id, select: { state: 1 } })` |
41
+ | Manage MCP servers | `createMcpServer`, `listMcpServersByUser`, `getMcpServerById`, `updateMcpServer`, `deleteMcpServer`, `verifyMcpServerConnection` |
42
+ | Approve or block an MCP server from a screen | `decideMcpServerTrust` |
43
+ | Usage of a chat or of an answer | `getLLMUsageByChat`, `getLLMUsageByMessage` |
44
+ | Usage statistics of a user | `getLLMUsageStats` |
45
+ | Create the schedule of an agent | `createAgenticJob`, `updateAgenticJob`, `listAgenticJobsByUser`, `getAgenticJobById`, `deleteAgenticJob`, `previewAgenticJobRuns` |
46
+ | History of scheduled runs | `listAgenticJobRunsByJob`, `listAgenticJobRunsByUser` |
47
+ | "Run now" | `runner.runNow({ jobId })` |
48
+ | Sign in, users | `login`, `createUser`, `getUserById`, `updateUser`, `deleteUser` |
49
+
50
+ ## Running the agent for a message
51
+
52
+ ```typescript
53
+ import { Agent } from 'openloops/core'
54
+ import { AgiLoop } from 'openloops/loops'
55
+ import { CurrentUser } from 'openloops/base'
56
+ import { inputGuards } from 'openloops/guardrails'
57
+
58
+ const currentUser = await CurrentUser.asyncFromDB(userIdFromYourAuth)
59
+
60
+ const agent = new Agent({
61
+ loop: new AgiLoop(),
62
+ tools: yourTools,
63
+ guards: [inputGuards.blockCard],
64
+ })
65
+
66
+ const { data, error } = await agent.run({
67
+ input: { message, chatId },
68
+ currentUser,
69
+ })
70
+ ```
71
+
72
+ - **Create an `Agent` for every run.** An instance keeps the state of the run it executes, so do not share one between requests that can overlap. Tools and guards are stateless and can be shared.
73
+ - **Choose the loop yourself.** There is no default. Use `AgiLoop`.
74
+ - **A run does not stream.** `agent.run` returns when the turn ends, which can take from seconds to minutes. Either give the request a long timeout, or start the run without waiting for it and let the client poll `getChatById` with `select: { state: 1 }` until the status stops being `processing`.
75
+ - **It does not throw for failures inside the run.** Read `error` and `data.state.status`. See [agent](agent.md#the-result).
76
+ - **Send the chat to your client with `data.toJSON()`**, after you have removed what the client must not see.
77
+
78
+ ## What the client has to handle
79
+
80
+ Show `data.messages`, and look at `data.state.status`:
81
+
82
+ | Status | What your screen does |
83
+ | --- | --- |
84
+ | `idle` | Ready for a new message. |
85
+ | `processing` | A run is in progress. Show a loading state and offer to stop it. |
86
+ | `awaiting_user_input` | The agent asked a question. The answer is sent as a normal message in the same chat. |
87
+ | `awaiting_user_confirmation` | The agent needs an approval, for a destructive tool or for an MCP server. The question is the last message, and the answer is sent as a normal message in the same chat. |
88
+ | `failed` | Show `data.state.lastError.message` and let the user try again. |
89
+
90
+ Messages have a `source` (`user`, `model` or `harness`) and some have `excludeFromContext`. Messages with `source: 'harness'` are written by the system, for example a guardrail reply or an approval question, and you may want to style them differently. See [chats](chats.md).
91
+
92
+ ## MCP servers
93
+
94
+ Your users register their own servers, and every server must be approved before the agent runs any of its tools. The approval normally happens in the chat. If you also want a screen, call `decideMcpServerTrust` with the hash of the manifest the user reviewed (`history[0].hash`). See [MCP servers](mcp-servers.md).
95
+
96
+ **Do not send `headers` or `history` of an MCP server to the client as they are.** `headers` hold credentials and `history` holds the full manifests. Mask the header values and send only what the screen needs, such as the name, `trust`, `status`, `lastError` and the hash of the latest manifest.
97
+
98
+ ## Scheduled agents (agentic jobs)
99
+
100
+ Two parts, as described in [agentic jobs](agentic-jobs.md):
101
+
102
+ 1. Endpoints that create and manage jobs and read their runs, from the table above.
103
+ 2. A worker process that you start once, with the options of the agent your jobs should use:
104
+
105
+ ```typescript
106
+ import { createAgenticJobRunner } from 'openloops/agentic-jobs'
107
+
108
+ const runner = createAgenticJobRunner({
109
+ agent: { tools: yourTools, guards: yourGuards },
110
+ onRunFinished: async ({ job, run }) => { /* notify the owner */ },
111
+ })
112
+
113
+ runner.start()
114
+ ```
115
+
116
+ - It is safe to start the worker in several instances: a due job is taken by one of them.
117
+ - Stop it with `runner.stop()` when the process receives `SIGTERM`.
118
+ - Create the indexes listed in [agentic jobs](agentic-jobs.md#indexes).
119
+ - A job that needs the user (a destructive tool, an unapproved server, a question) pauses its run, and the user answers in the chat of that run. Show those runs, which you can list with `listAgenticJobRunsByUser({ status: 'paused' })`.
120
+
121
+ ## Security checklist
122
+
123
+ - Check ownership before every call that takes an id.
124
+ - Mask `headers` and `history` of MCP servers.
125
+ - Add input guards for what your product must never receive, such as card numbers.
126
+ - Mark your own destructive tools with `destructive: true`. The agent asks for confirmation before running them. Do not rely on a tool being treated as destructive by default, because it is not.
127
+ - Use `strictMode: true` in the agent when the tools of an MCP server must be reviewed by the user on every change.
128
+ - Keep API keys and the secrets of [configuration](configuration.md) out of the code. Values can be stored encrypted with the `ENC:` prefix.
129
+ - Set limits on how many scheduled jobs and how often they run in your own layer, since `openloops` does not limit them yet.
130
+
131
+ ## Common mistakes
132
+
133
+ - Sharing one `Agent` between concurrent requests.
134
+ - Waiting for `agent.run` inside a request with a short timeout.
135
+ - Passing `chatId`, `jobId` or `mcpServerId` from the client without checking the owner.
136
+ - Treating `error` as an exception that is thrown. It is returned.
137
+ - Forgetting that a run in `awaiting_user_confirmation` is waiting for the next message of the user, and that the next message is the answer.
138
+ - Starting the scheduled jobs worker without creating its indexes.
package/docs/llms.txt ADDED
@@ -0,0 +1,35 @@
1
+ # openloops
2
+
3
+ > A TypeScript runtime for AI agents that run in your backend. It persists chats, tasks and tool calls in MongoDB, scopes everything to a user, asks for approval before destructive tools and unapproved MCP servers, and can run agents on a schedule. It has no HTTP layer: your backend calls its use cases and owns authorization.
4
+
5
+ Start with the integration guide, then read only the pages you need. All pages are in this folder.
6
+
7
+ ## Start here
8
+
9
+ - [Integration guide](integration-guide.md): what to write in a backend, which endpoint calls what, and the security checklist
10
+ - [README](../README.md): what it is, the quick start and the package structure
11
+
12
+ ## Run an agent
13
+
14
+ - [The Agent](agent.md): options, running a turn, statuses, confirmations, autonomous mode
15
+ - [Configuration](configuration.md): environment variables, default model, timeouts
16
+ - [Chats](chats.md): the chat record, message source, listing and deleting
17
+
18
+ ## Shape the agent
19
+
20
+ - [Building an AgentLoop](loops.md): AgiLoop, the loop contract, RunContext and Harness
21
+ - [Skills](skills.md): LLM-backed reasoning steps and call modes
22
+ - [Tools](tools.md): writing tools, validation, built-in tools
23
+ - [Guardrails](guardrails.md): input guards before the model
24
+ - [The harness](harness.md): tool pipeline, workspace, approvals, language, limits
25
+
26
+ ## Connect and schedule
27
+
28
+ - [MCP servers](mcp-servers.md): registering servers, the trust flow, approving and blocking
29
+ - [Agentic jobs](agentic-jobs.md): scheduled agent runs, recurrence, history and the runner
30
+
31
+ ## Users and cost
32
+
33
+ - [User management](users.md)
34
+ - [Authentication](authentication.md)
35
+ - [LLM usage tracking](usage.md)
package/docs/loops.md ADDED
@@ -0,0 +1,136 @@
1
+ # Building an `AgentLoop`
2
+
3
+ An `AgentLoop` decides how your agent thinks and acts: when it answers directly, when it uses tools, when it asks the user. `openloops` ships `AgiLoop`, which is the one to use for general agents, and you can write your own for anything else.
4
+
5
+ ```typescript
6
+ import { AgentLoop, AgentStatus, Harness, RunContext } from 'openloops/core'
7
+ import { AgiLoop } from 'openloops/loops'
8
+ ```
9
+
10
+ ## `AgiLoop`
11
+
12
+ `AgiLoop` is a reasoning loop. It answers directly when it can, and otherwise works in cycles of think, act and observe until it can give a final answer.
13
+
14
+ | Node | What it does |
15
+ | --- | --- |
16
+ | `fast_responder` | Initial node. Answers directly when no tools or memory are needed. It is skipped in an autonomous run. |
17
+ | `reasoning_engine` | Reads the situation or the results of the last actions, rewrites its working state, decides the next actions and reports the language of the conversation. |
18
+ | `action_engine` | Runs the actions the reasoning engine asked for, asks the user for confirmation when needed, delivers the final answer. |
19
+
20
+ The loop works within a budget per task (20 reasoning turns and 40 tool calls) and stops with an honest answer when the model repeats itself, keeps only reading notes, or runs out of budget. It also rejects final answers that cite identifiers that never appeared in a result or in the user's words.
21
+
22
+ ```typescript
23
+ const agent = new Agent({ loop: new AgiLoop() })
24
+ ```
25
+
26
+ ## The contract
27
+
28
+ ```typescript
29
+ export class MyLoop extends AgentLoop {
30
+ get initialNode () {
31
+ return this.nodes.respond
32
+ }
33
+
34
+ get nodes () {
35
+ return {
36
+ respond: this.respond,
37
+ }
38
+ }
39
+
40
+ get name () {
41
+ return 'my-loop'
42
+ }
43
+
44
+ get version () {
45
+ return '1.0.0'
46
+ }
47
+
48
+ get author () {
49
+ return { name: 'You', email: 'you@example.com', website: 'https://example.com' }
50
+ }
51
+
52
+ private async respond (ctx: RunContext, harness: Harness): Promise<void> {
53
+ harness.reply('Hello!')
54
+ ctx.chat.state?.setStatus(AgentStatus.IDLE)
55
+ }
56
+ }
57
+ ```
58
+
59
+ - `nodes` is a getter, so it can reference node methods declared later in the class.
60
+ - `initialNode` is where a new task starts. Return a direct reference such as `this.nodes.respond` so a typo is caught by TypeScript.
61
+ - `name` is stored on the chat so `openloops` knows which loop drives it. Bump `version` every time the loop or its prompts change; it is recorded in the metadata of every turn.
62
+ - A node decides what runs next with `harness.setNextNode(...)`. The loop stops when a node leaves the status as `idle`, `failed`, `awaiting_user_input` or `awaiting_user_confirmation`.
63
+
64
+ Nodes are called with the loop as `this`, so private helpers work as usual.
65
+
66
+ ## `RunContext`
67
+
68
+ The first argument of a node is everything it needs to read:
69
+
70
+ ```typescript
71
+ ctx.currentMessage
72
+ ctx.currentUser
73
+ ctx.currentSession
74
+ ctx.identity
75
+ ctx.chat
76
+ ctx.task
77
+ ctx.chatOptions
78
+ ctx.tools
79
+ ctx.skillParams
80
+ ctx.baseParams
81
+ ctx.logger
82
+ ```
83
+
84
+ - `ctx.chat` is the `Chat` entity: state, settings, messages and tasks.
85
+ - `ctx.task` is the active `AgentTask`, if one exists.
86
+ - `ctx.skillParams` is what you spread into `Skill.run`. See [skills](skills.md).
87
+ - `ctx.baseParams` is what a `Tool` receives next to its arguments.
88
+
89
+ ## `Harness`
90
+
91
+ The second argument is the services of the [harness](harness.md) that the loop can call:
92
+
93
+ | Member | What it does |
94
+ | --- | --- |
95
+ | `reply(content)` | Sends a message to the user. |
96
+ | `executionMode` | `interactive` or `autonomous`, taken from the run. |
97
+ | `answerQuestion(question)` | In an autonomous run, answers a question of the model on behalf of the absent user and returns the answer, or `undefined` when it cannot. In an interactive run it always returns `undefined`, and the loop pauses and asks the user. |
98
+ | `setNextNode(node)` | Chooses the next node. `undefined` falls back to the initial node on the next message. |
99
+ | `toolCatalog()` | Returns the tools to declare to the model and the context that describes the rest. Handles discovery and MCP servers. |
100
+ | `searchTools(keywords, opts)` | Ranks the available tools by keyword. `opts.server` limits it to one MCP server. |
101
+ | `ensureTools()` | Loads the list of MCP servers and returns the tools known so far. |
102
+ | `runAction(action, opts)` | Runs an action through the tool pipeline. |
103
+ | `requiresApproval(action)` | Tells whether an action needs the user's confirmation before it can run. |
104
+ | `requestApproval(actions, { resumeAt })` | Asks the user to confirm and resumes at `resumeAt` once they answer. |
105
+ | `workspace` | Saves and reads notes and large outputs of the task. |
106
+
107
+ Always go through `runAction`. It applies validation, grounding checks, duplicate protection, output offloading and the approval rules described in [harness](harness.md#tool-pipeline). Do not call `tool.run` yourself.
108
+
109
+ ## Tasks
110
+
111
+ A task is one thing the user asked the agent to do. A later "actually, search the web instead" starts a different task in the same chat.
112
+
113
+ ```typescript
114
+ const task = ctx.task ?? ctx.chat.createTask(ctx.currentMessage)
115
+
116
+ ctx.chat.completeTask(task.id, 'summary')
117
+ ctx.chat.failTask(task.id)
118
+ ctx.chat.cancelTask(task.id)
119
+ ctx.chat.lastCompletedTask()
120
+ ```
121
+
122
+ A task carries its ledger of actions (tool calls), the turns of the model, what the model learned and the schemas of the tools it has seen.
123
+
124
+ ## Running skills
125
+
126
+ ```typescript
127
+ const result = await mySkill.run({ ...ctx.skillParams, contextInjection: { goal: ctx.task?.goal } })
128
+ ```
129
+
130
+ Every skill run is traced automatically. See [skills](skills.md).
131
+
132
+ ## The shared skill
133
+
134
+ `openloops/loops` exports `fastResponder`, the skill that every loop can reuse as its first step: it answers general conversation directly, or says that it cannot and the loop continues with its reasoning.
135
+
136
+ The approvals and the answers of autonomous runs are written by skills that belong to the harness. They are internal, and you do not need to call them: `Agent` runs them for you when you use `harness.requestApproval` and `harness.answerQuestion`.