openloops 0.8.0 → 0.8.2

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 (40) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +23 -36
  3. package/dist/common/error/error-reporter.d.ts +11 -0
  4. package/dist/common/error/error-reporter.js +36 -0
  5. package/dist/common/error/error-reporter.mjs +11 -0
  6. package/dist/common/error/index.d.ts +1 -0
  7. package/dist/common/error/index.js +3 -1
  8. package/dist/common/error/index.mjs +1 -0
  9. package/dist/common/error/reportError.js +10 -0
  10. package/dist/common/error/reportError.mjs +10 -0
  11. package/dist/common/error/sentry-client.d.ts +2 -2
  12. package/dist/common/error/sentry-client.js +19 -24
  13. package/dist/common/error/sentry-client.mjs +19 -14
  14. package/dist/common/index.d.ts +2 -0
  15. package/dist/common/index.js +9 -0
  16. package/dist/common/index.mjs +4 -0
  17. package/dist/common/repositories/mongo-db.client.js +1 -1
  18. package/dist/common/repositories/mongo-db.client.mjs +1 -1
  19. package/dist/common/repositories/mongo-db.repository.js +1 -1
  20. package/dist/common/repositories/mongo-db.repository.mjs +1 -1
  21. package/dist/common/utils/secret-manager.js +1 -1
  22. package/dist/common/utils/secret-manager.mjs +1 -1
  23. package/dist/harness/agent.d.ts +1 -0
  24. package/dist/harness/agent.js +9 -0
  25. package/dist/harness/agent.mjs +9 -0
  26. package/dist/services/automations/runner/automation-runner.js +6 -1
  27. package/dist/services/automations/runner/automation-runner.mjs +6 -1
  28. package/dist/services/chats/utils/title.js +3 -1
  29. package/dist/services/chats/utils/title.mjs +3 -1
  30. package/docs/README.md +1 -0
  31. package/docs/agent.md +2 -0
  32. package/docs/assets/harness-car.svg +11 -11
  33. package/docs/chats.md +1 -1
  34. package/docs/configuration.md +5 -1
  35. package/docs/error-reporting.md +219 -0
  36. package/docs/integration-guide.md +4 -0
  37. package/docs/llms.txt +2 -1
  38. package/docs/loops.md +1 -1
  39. package/examples/errors/error-reporting.ts +75 -0
  40. package/package.json +21 -7
@@ -1,5 +1,6 @@
1
1
  import { ObjectId } from "mongodb";
2
2
  import { Logger } from "../common/logger/index.js";
3
+ import { reportError } from "../common/error/index.js";
3
4
  import { McpServer, needsUserReview } from "../services/mcp-servers/entities/index.js";
4
5
  import { createChat, updateChat, getChatById } from "../services/chats/index.js";
5
6
  import { Chat } from "../services/chats/entities/chat.entity.js";
@@ -175,6 +176,7 @@ class Agent {
175
176
  const llmError = error instanceof LLMError ? error : void 0;
176
177
  const reported = llmError?.userMessage ?? message;
177
178
  await this.failRun(reported, llmError);
179
+ await this.reportFailure(error, llmError ? { code: llmError.code } : {});
178
180
  return { data: this.currentChat?._id ? this.currentChat : void 0, error: reported };
179
181
  }
180
182
  }
@@ -205,6 +207,7 @@ class Agent {
205
207
  listener(activity);
206
208
  } catch (error) {
207
209
  this.logger.warn({ error: error?.message ?? error }, "[AGENT] An activity listener failed");
210
+ void this.reportFailure(error, { listener: "activity" });
208
211
  }
209
212
  }
210
213
  }
@@ -278,6 +281,7 @@ class Agent {
278
281
  result = await guard.run(context);
279
282
  } catch (error) {
280
283
  this.logger.error({ error: error?.message ?? error, guard: guard.name }, "[AGENT] Guard failed");
284
+ await this.reportFailure(error, { stage: "guard", guard: guard.name });
281
285
  failed = true;
282
286
  result = { passed: false, reason: `Guard failed: ${error?.message ?? error}` };
283
287
  }
@@ -362,6 +366,9 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
362
366
  await this.persist();
363
367
  await this.disconnectMcpServers();
364
368
  }
369
+ async reportFailure(error, details = {}) {
370
+ await reportError(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
371
+ }
365
372
  async failRun(message, llmError) {
366
373
  try {
367
374
  this.currentChat.state?.setStatus(AgentStatus.FAILED);
@@ -371,6 +378,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
371
378
  await this.persist();
372
379
  } catch (saveError) {
373
380
  this.logger.error({ error: saveError?.message ?? saveError }, "[AGENT] Failed to persist failed run state");
381
+ await this.reportFailure(saveError, { stage: "persist" });
374
382
  } finally {
375
383
  await this.disconnectMcpServers();
376
384
  }
@@ -458,6 +466,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
458
466
  });
459
467
  } catch (error) {
460
468
  this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to persist traces");
469
+ await this.reportFailure(error, { stage: "traces" });
461
470
  }
462
471
  }
463
472
  async persist(props) {
@@ -25,6 +25,7 @@ module.exports = __toCommonJS(automation_runner_exports);
25
25
  var import_node_crypto = require("node:crypto");
26
26
  var import_node_os = require("node:os");
27
27
  var import_logger = require("../../../common/logger/index.js");
28
+ var import_error = require("../../../common/error/index.js");
28
29
  var import_base = require("../../../common/base/index.js");
29
30
  var import_agent = require("../../../harness/agent.js");
30
31
  var import_loop = require("../../../loops/agi/loop.js");
@@ -83,6 +84,7 @@ class AutomationRunner {
83
84
  await new import_sync_automation_runs.SyncAutomationRunsUseCase().execute({});
84
85
  } catch (error) {
85
86
  this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] Failed to sync the open runs");
87
+ await (0, import_error.reportError)(error, { source: "automations", stage: "sync" });
86
88
  }
87
89
  if (capacity <= 0) return;
88
90
  const data = await new import_claim_due_automations.ClaimDueAutomationsUseCase().execute({ workerId: this.workerId, limit: capacity, leaseMs: this.options.leaseMs ?? (0, import_settings.leaseMs)() });
@@ -101,8 +103,9 @@ class AutomationRunner {
101
103
  }
102
104
  async loop() {
103
105
  while (this.running) {
104
- this.ticking = this.tick().catch((error) => {
106
+ this.ticking = this.tick().catch(async (error) => {
105
107
  this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] The worker failed to check the due automations");
108
+ await (0, import_error.reportError)(error, { source: "automations", stage: "tick" });
106
109
  });
107
110
  await this.ticking;
108
111
  if (!this.running) break;
@@ -136,6 +139,7 @@ class AutomationRunner {
136
139
  } catch (failure) {
137
140
  error = { code: failure?.code ?? "RUNNER_ERROR", message: failure?.message ?? String(failure) };
138
141
  this.logger.error({ error: error.message, automationId, runId }, "[AUTOMATIONS] A run failed");
142
+ await (0, import_error.reportError)(failure, { source: "automations", stage: "run", automationId, runId });
139
143
  } finally {
140
144
  clearInterval(heartbeat);
141
145
  }
@@ -177,6 +181,7 @@ class AutomationRunner {
177
181
  await this.options.onRunFinished(event);
178
182
  } catch (error) {
179
183
  this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] The onRunFinished callback failed");
184
+ await (0, import_error.reportError)(error, { source: "automations", stage: "onRunFinished" });
180
185
  }
181
186
  }
182
187
  }
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { hostname } from "node:os";
3
3
  import { Logger } from "../../../common/logger/index.js";
4
+ import { reportError } from "../../../common/error/index.js";
4
5
  import { CurrentUser, CurrentSession } from "../../../common/base/index.js";
5
6
  import { Agent } from "../../../harness/agent.js";
6
7
  import { AgiLoop } from "../../../loops/agi/loop.js";
@@ -59,6 +60,7 @@ class AutomationRunner {
59
60
  await new SyncAutomationRunsUseCase().execute({});
60
61
  } catch (error) {
61
62
  this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] Failed to sync the open runs");
63
+ await reportError(error, { source: "automations", stage: "sync" });
62
64
  }
63
65
  if (capacity <= 0) return;
64
66
  const data = await new ClaimDueAutomationsUseCase().execute({ workerId: this.workerId, limit: capacity, leaseMs: this.options.leaseMs ?? defaultLeaseMs() });
@@ -77,8 +79,9 @@ class AutomationRunner {
77
79
  }
78
80
  async loop() {
79
81
  while (this.running) {
80
- this.ticking = this.tick().catch((error) => {
82
+ this.ticking = this.tick().catch(async (error) => {
81
83
  this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] The worker failed to check the due automations");
84
+ await reportError(error, { source: "automations", stage: "tick" });
82
85
  });
83
86
  await this.ticking;
84
87
  if (!this.running) break;
@@ -112,6 +115,7 @@ class AutomationRunner {
112
115
  } catch (failure) {
113
116
  error = { code: failure?.code ?? "RUNNER_ERROR", message: failure?.message ?? String(failure) };
114
117
  this.logger.error({ error: error.message, automationId, runId }, "[AUTOMATIONS] A run failed");
118
+ await reportError(failure, { source: "automations", stage: "run", automationId, runId });
115
119
  } finally {
116
120
  clearInterval(heartbeat);
117
121
  }
@@ -153,6 +157,7 @@ class AutomationRunner {
153
157
  await this.options.onRunFinished(event);
154
158
  } catch (error) {
155
159
  this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] The onRunFinished callback failed");
160
+ await reportError(error, { source: "automations", stage: "onRunFinished" });
156
161
  }
157
162
  }
158
163
  }
@@ -22,10 +22,12 @@ __export(title_exports, {
22
22
  normalizeTitle: () => normalizeTitle
23
23
  });
24
24
  module.exports = __toCommonJS(title_exports);
25
+ var import_helpers = require("../../../common/helpers/index.js");
25
26
  const MAX_TITLE_LENGTH = 80;
26
27
  function normalizeTitle(text) {
27
28
  if (typeof text !== "string") return void 0;
28
- const title = Array.from(text.replace(/\s+/g, " ").trim()).slice(0, MAX_TITLE_LENGTH).join("").trim();
29
+ const clean = (0, import_helpers.sanitizeString)(text) ?? "";
30
+ const title = Array.from(clean.replace(/\s+/g, " ").trim()).slice(0, MAX_TITLE_LENGTH).join("").trim();
29
31
  return title || void 0;
30
32
  }
31
33
  // Annotate the CommonJS export names for ESM import in node:
@@ -1,7 +1,9 @@
1
+ import { sanitizeString } from "../../../common/helpers/index.js";
1
2
  const MAX_TITLE_LENGTH = 80;
2
3
  function normalizeTitle(text) {
3
4
  if (typeof text !== "string") return void 0;
4
- const title = Array.from(text.replace(/\s+/g, " ").trim()).slice(0, MAX_TITLE_LENGTH).join("").trim();
5
+ const clean = sanitizeString(text) ?? "";
6
+ const title = Array.from(clean.replace(/\s+/g, " ").trim()).slice(0, MAX_TITLE_LENGTH).join("").trim();
5
7
  return title || void 0;
6
8
  }
7
9
  export {
package/docs/README.md CHANGED
@@ -15,6 +15,7 @@ Start with the [README](../README.md) for what `openloops` is and how to run it.
15
15
  | --- | --- |
16
16
  | [The `Agent`](agent.md) | Options, running a turn, the result and its statuses, confirmations, autonomous mode, hooks and interruption. |
17
17
  | [Configuration](configuration.md) | Environment variables, choosing the model and what is recorded. |
18
+ | [Reporting errors](error-reporting.md) | Declare one function, once, to send the errors that the package catches to Sentry or to the tool you use: what it receives, what is reported, serverless and moving from `SENTRY_DSN`. |
18
19
  | [Automations](automations.md) | Tasks that the agent runs by itself, on a schedule, when an event arrives or both: triggers, tokens, the queue, the history of runs and the runner that executes them. If you used `agentic-jobs`, read [the migration steps](automations.md#migrating-from-agentic-jobs). Updating to 0.5.0 breaks the shape of the triggers, read [the migration to 0.5.0](automations.md#migrating-to-050). |
19
20
  | [Chats](chats.md) | The chat record, its title and messages and their `source`, listing and searching chats, reading and deleting them. Updating to 0.8.0 needs [a migration of the titles](chats.md#migrating-to-080). |
20
21
 
package/docs/agent.md CHANGED
@@ -239,3 +239,5 @@ If a turn fails for any reason, `Agent` marks the chat as failed, saves it, clos
239
239
  | `LLM_FAILED` | Anything else. | yes |
240
240
 
241
241
  The provider tells these apart with free text, so a message that does not match any of them ends in `LLM_FAILED`.
242
+
243
+ A failed run is also handed to the error reporter you registered, with the `code`, the `chatId` and the `userId`. See [reporting errors](error-reporting.md).
@@ -1,6 +1,6 @@
1
1
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 560 310" width="560" height="310" role="img" aria-labelledby="t d">
2
2
  <title id="t">The openloops harness</title>
3
- <desc id="d">A car made of an engine (the AI model), a chassis (the harness) and a body (the loop). The body changes while the engine and the chassis stay the same: a different body, a different agent.</desc>
3
+ <desc id="d">A car made of an engine (the AI model), a chassis (Openloops) and a body (your product). The body changes while the engine and the chassis stay the same: a different body, a different agent.</desc>
4
4
  <style>
5
5
  .mono{font-family:ui-monospace, SFMono-Regular, Menlo, Consolas, monospace}
6
6
  .body,.role{opacity:0;animation:cycle 12.8s infinite both;transform-box:fill-box}
@@ -22,25 +22,25 @@
22
22
  <path d="M 90 150 L 90 128 Q 90 118 104 116 L 190 110 L 225 82 Q 232 76 244 76 L 330 76 Q 342 76 350 84 L 378 110 L 462 118 Q 478 120 478 134 L 478 150 Z" fill="#cbd5e1" fill-opacity="0.04" stroke="#cbd5e1" stroke-width="1.75" stroke-linejoin="round"/>
23
23
  <path d="M 232 84 L 292 84 L 292 108 L 205 108 Z M 300 84 L 336 84 L 366 108 L 300 108 Z" fill="#cbd5e1" fill-opacity="0.08" stroke="#cbd5e1" stroke-width="1" stroke-linejoin="round"/>
24
24
  <line x1="290" y1="62" x2="290" y2="72" stroke="#64748b" stroke-width="1" stroke-dasharray="3 3"/>
25
- <text class="mono" x="290" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">LOOP</tspan><tspan fill="#94a3b8">)</tspan></text>
25
+ <text class="mono" x="290" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">YOUR PRODUCT</tspan><tspan fill="#94a3b8">)</tspan></text>
26
26
  </g>
27
- <g class="body b1" style="animation-delay:3.2s">
27
+ <g class="body b1" style="animation-delay:6.4s">
28
28
  <path d="M 90 150 L 90 132 Q 90 124 102 122 L 200 116 Q 240 84 290 84 L 330 84 Q 350 86 362 104 L 372 114 L 462 124 Q 480 128 480 138 L 480 150 Z" fill="#cbd5e1" fill-opacity="0.04" stroke="#cbd5e1" stroke-width="1.75" stroke-linejoin="round"/>
29
29
  <path d="M 232 112 Q 258 92 290 92 L 330 92 Q 342 94 350 110 Z" fill="#cbd5e1" fill-opacity="0.08" stroke="#cbd5e1" stroke-width="1" stroke-linejoin="round"/>
30
30
  <line x1="290" y1="62" x2="290" y2="80" stroke="#64748b" stroke-width="1" stroke-dasharray="3 3"/>
31
- <text class="mono" x="290" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">LOOP</tspan><tspan fill="#94a3b8">)</tspan></text>
31
+ <text class="mono" x="290" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">YOUR PRODUCT</tspan><tspan fill="#94a3b8">)</tspan></text>
32
32
  </g>
33
- <g class="body b2" style="animation-delay:6.4s">
33
+ <g class="body b2" style="animation-delay:3.2s">
34
34
  <path d="M 90 150 L 90 100 Q 90 84 106 84 L 340 84 Q 352 84 358 96 L 380 118 L 462 124 Q 478 126 478 140 L 478 150 Z" fill="#cbd5e1" fill-opacity="0.04" stroke="#cbd5e1" stroke-width="1.75" stroke-linejoin="round"/>
35
35
  <path d="M 110 96 L 166 96 L 166 124 L 110 124 Z M 176 96 L 232 96 L 232 124 L 176 124 Z M 242 96 L 298 96 L 298 124 L 242 124 Z M 308 96 L 342 96 L 366 118 L 308 118 Z" fill="#cbd5e1" fill-opacity="0.08" stroke="#cbd5e1" stroke-width="1" stroke-linejoin="round"/>
36
36
  <line x1="240" y1="62" x2="240" y2="80" stroke="#64748b" stroke-width="1" stroke-dasharray="3 3"/>
37
- <text class="mono" x="240" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">LOOP</tspan><tspan fill="#94a3b8">)</tspan></text>
37
+ <text class="mono" x="240" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">YOUR PRODUCT</tspan><tspan fill="#94a3b8">)</tspan></text>
38
38
  </g>
39
39
  <g class="body b3" style="animation-delay:9.6s">
40
40
  <path d="M 290 150 L 290 100 Q 292 84 308 82 L 352 82 Q 364 82 370 92 L 384 114 L 462 120 Q 478 122 478 136 L 478 150 Z M 90 150 L 90 110 L 100 110 L 104 140 L 270 140 L 274 110 L 284 110 L 284 150 Z" fill="#cbd5e1" fill-opacity="0.04" stroke="#cbd5e1" stroke-width="1.75" stroke-linejoin="round"/>
41
41
  <path d="M 302 92 L 348 92 L 372 114 L 302 114 Z" fill="#cbd5e1" fill-opacity="0.08" stroke="#cbd5e1" stroke-width="1" stroke-linejoin="round"/>
42
42
  <line x1="330" y1="62" x2="330" y2="78" stroke="#64748b" stroke-width="1" stroke-dasharray="3 3"/>
43
- <text class="mono" x="330" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">LOOP</tspan><tspan fill="#94a3b8">)</tspan></text>
43
+ <text class="mono" x="330" y="54" text-anchor="middle" font-size="11" letter-spacing="1.2" fill="#cbd5e1">BODY<tspan fill="#94a3b8"> (</tspan><tspan fill="#f8fafc">YOUR PRODUCT</tspan><tspan fill="#94a3b8">)</tspan></text>
44
44
  </g>
45
45
  <g>
46
46
  <rect class="motor" x="394" y="122" width="66" height="26" rx="4" fill="#ffffff" fill-opacity="0.06" stroke="#cbd5e1" stroke-width="1.5"/>
@@ -70,10 +70,10 @@
70
70
  <line x1="0" y1="-8" x2="0" y2="-20" stroke="#64748b" stroke-width="2" transform="rotate(288)"/>
71
71
  </g><circle r="8" fill="#0B0E14" stroke="#cbd5e1" stroke-width="1.5"/></g>
72
72
  <line x1="280" y1="172" x2="280" y2="232" stroke="#64748b" stroke-width="1" stroke-dasharray="3 3"/>
73
- <text class="mono" x="280" y="248" text-anchor="middle" font-size="11" letter-spacing="1.2" font-weight="700" fill="#C06CF0">CHASSIS<tspan fill="#94a3b8"> (</tspan><tspan fill="#e9d5ff">HARNESS</tspan><tspan fill="#94a3b8">)</tspan></text></g>
73
+ <text class="mono" x="280" y="248" text-anchor="middle" font-size="11" letter-spacing="1.2" font-weight="700" fill="#C06CF0">CHASSIS<tspan fill="#94a3b8"> (</tspan><tspan fill="#e9d5ff">OPENLOOPS</tspan><tspan fill="#94a3b8">)</tspan></text></g>
74
74
  <text class="mono role b0" x="280" y="278" text-anchor="middle" font-size="13" fill="#f8fafc" style="animation-delay:0s">Personal assistant</text>
75
- <text class="mono role b1" x="280" y="278" text-anchor="middle" font-size="13" fill="#f8fafc" style="animation-delay:3.2s">Analyst</text>
76
- <text class="mono role b2" x="280" y="278" text-anchor="middle" font-size="13" fill="#f8fafc" style="animation-delay:6.4s">Customer support</text>
77
- <text class="mono role b3" x="280" y="278" text-anchor="middle" font-size="13" fill="#f8fafc" style="animation-delay:9.6s">Programmer</text>
75
+ <text class="mono role b1" x="280" y="278" text-anchor="middle" font-size="13" fill="#f8fafc" style="animation-delay:6.4s">Meeting copilot</text>
76
+ <text class="mono role b2" x="280" y="278" text-anchor="middle" font-size="13" fill="#f8fafc" style="animation-delay:3.2s">Customer support</text>
77
+ <text class="mono role b3" x="280" y="278" text-anchor="middle" font-size="13" fill="#f8fafc" style="animation-delay:9.6s">Your incredible idea</text>
78
78
  <text class="mono" x="280" y="298" text-anchor="middle" font-size="11" fill="#94a3b8">Same engine. Same chassis. A different body, a different agent.</text>
79
79
  </svg>
package/docs/chats.md CHANGED
@@ -74,7 +74,7 @@ The first call renames the chat, and the agent keeps that title from then on. Th
74
74
 
75
75
  ## Migrating to 0.8.0
76
76
 
77
- Chats saved with a version before 0.8.0 have no title. **Run `migrateChatTitles` once per database when you update.** It gives each chat without a title its first message of the user, on one line and cut to 80 characters. Without it those chats stay untitled until they receive another message, and a history that lists with `select` has nothing to show for them, because it does not read the messages.
77
+ Chats saved with a version before 0.8.0 have no title. **Run `migrateChatTitles` once per database when you update.** It gives each chat without a title its first message of the user, on one line, without HTML tags and cut to 80 characters. Without it those chats stay untitled until they receive another message, and a history that lists with `select` has nothing to show for them, because it does not read the messages.
78
78
 
79
79
  1. **Take a backup**, and run it with `dryRun` first. It only counts.
80
80
 
@@ -19,7 +19,7 @@
19
19
  | `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). |
20
20
  | `LLM_CALL_TIMEOUT_MS` | no | Longest time to wait for one attempt of a model call, in milliseconds. Defaults to `60000`, and calls with the `high` thinking effort get twice as much. See [Timeouts](#timeouts). |
21
21
  | `MCP_TOOL_TIMEOUT_MS` | no | Longest time to wait for a tool of an MCP server, in milliseconds. Defaults to `60000`. See [Timeouts](#timeouts). |
22
- | `SENTRY_DSN` | no | Errors are reported to Sentry when set, unless `IS_LOCAL` is `true` or `NODE_ENV` is `development`. |
22
+ | `SENTRY_DSN` | no | **Deprecated.** Errors are reported to Sentry when set and no reporter is registered, unless `IS_LOCAL` is `true` or `NODE_ENV` is `development`. It needs `@sentry/node` installed in your project. Use [`setErrorReporter`](error-reporting.md) instead. |
23
23
  | `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL` | no | Traces every LLM call in Langfuse when all three are set. |
24
24
  | `IS_LOCAL`, `NODE_ENV` | no | Local development switches. With `IS_LOCAL` set to `true`, or `NODE_ENV` set to `development`, the logger prints colored logs if `pino-pretty` is installed in your project (it is a dev dependency of this package, so install it yourself: `yarn add -D pino-pretty`), and plain JSON otherwise. |
25
25
 
@@ -95,6 +95,10 @@ await client.close()
95
95
 
96
96
  It covers `llm_calls`, `chats`, `agent_tasks`, `agent_actions`, `agent_traces`, `workspace_items`, `mcp_servers`, `automations` and `automation_runs`. It is safe to run again: an index that already exists is left as it is. Collections of your own application are not included.
97
97
 
98
+ ## Reporting errors
99
+
100
+ The package does not choose a tool to report errors: you declare one function, once, and it receives the errors that the package catches. Read [reporting errors](error-reporting.md).
101
+
98
102
  ## What is recorded
99
103
 
100
104
  - Every LLM call, with its response, tokens and cost. See [usage](usage.md).
@@ -0,0 +1,219 @@
1
+ # Reporting errors
2
+
3
+ `openloops` does not choose a tool to report errors. You declare one function, once, and the package calls it every time it catches an error that would otherwise only be written in the log. What the function does is up to you: Sentry, Datadog, Slack, a file.
4
+
5
+ - [Declaring the reporter](#declaring-the-reporter)
6
+ - [What you do not have to do](#what-you-do-not-have-to-do)
7
+ - [A run that fails](#a-run-that-fails)
8
+ - [What the reporter receives](#what-the-reporter-receives)
9
+ - [What is reported and what is not](#what-is-reported-and-what-is-not)
10
+ - [Rules of the reporter](#rules-of-the-reporter)
11
+ - [Filtering and adding context](#filtering-and-adding-context)
12
+ - [Lambdas and other serverless deployments](#lambdas-and-other-serverless-deployments)
13
+ - [Tests](#tests)
14
+ - [Moving from `SENTRY_DSN`](#moving-from-sentry_dsn)
15
+
16
+ ## Declaring the reporter
17
+
18
+ ```typescript
19
+ import * as Sentry from '@sentry/node'
20
+ import { setErrorReporter } from 'openloops/common'
21
+
22
+ Sentry.init({ dsn: process.env.MY_SENTRY_DSN })
23
+
24
+ setErrorReporter((error, details) => {
25
+ Sentry.withScope(scope => {
26
+ scope.setTag('source', details.source)
27
+ scope.setExtras(details)
28
+ Sentry.captureException(error)
29
+ })
30
+ })
31
+ ```
32
+
33
+ **Declare it once.** Do it when the process starts, before the first request: at the top of the file that starts your server, or in a file of its own that your server imports first. That is all the setup there is.
34
+
35
+ - It is global to the process. Every `Agent`, every use case and the runner of the [automations](automations.md) that run in that process use it, with nothing to pass to them.
36
+ - Do not declare it inside a request, a use case or next to each `Agent`. It would work, but it would be a function replaced on every request for nothing.
37
+ - If you declare it twice, the second one replaces the first. There is only one reporter at a time.
38
+ - `setErrorReporter(undefined)` removes it. Without a reporter, the errors only go to the log, unless you still use the deprecated [`SENTRY_DSN`](#moving-from-sentry_dsn).
39
+ - A deployment with several processes (several servers, or lambdas) needs the declaration in each process. See [lambdas](#lambdas-and-other-serverless-deployments).
40
+
41
+ ## What you do not have to do
42
+
43
+ After the declaration the rest of your code stays as it was. There is no option in the `Agent`, no wrapper around the use cases and no `try/catch` added only to report.
44
+
45
+ ```typescript
46
+ import './error-reporting'
47
+ import { Agent } from 'openloops/core'
48
+ import { AgiLoop } from 'openloops/loops'
49
+
50
+ const agent = new Agent({ loop: new AgiLoop() })
51
+
52
+ const result = await agent.run({ input: { message: 'hi, how are you?' }, currentUser })
53
+ ```
54
+
55
+ The first line is the file that declares the reporter. If this run fails, the reporter is called without anything else in this code. The [example](../examples/errors/error-reporting.ts) has the declaration at the top and the code that runs below it, in one file.
56
+
57
+ ## A run that fails
58
+
59
+ Take a run whose provider rejects the API key. `agent.run` does not throw: it saves the chat as `failed`, returns the message for the user in `result.error` and calls the reporter. Your reporter receives something like this (the `code` depends on what the provider answers):
60
+
61
+ ```typescript
62
+ error // the LLMError, with the message of the provider
63
+ details // { source: 'agent', code: 'LLM_AUTH_FAILED', chatId: '6abc454162624f9e01929cd8', userId: '6ab56894eb20887d1ef7942c' }
64
+ ```
65
+
66
+ The chat is saved before the reporter is called, so a slow reporter never delays that. A run that goes well never calls the reporter.
67
+
68
+ ## What the reporter receives
69
+
70
+ The function has two parameters:
71
+
72
+ | Parameter | Meaning |
73
+ | --- | --- |
74
+ | `error` | The `Error` that was caught, or an `HttpError` if the code threw one. A text becomes an `Error`. |
75
+ | `details` | An object that tells where it happened. It always has `source`. The other fields appear when they exist. |
76
+
77
+ The fields of `details`:
78
+
79
+ | Field | Meaning |
80
+ | --- | --- |
81
+ | `source` | Where the error was caught: `agent`, `automations`, `mongo` or `openloops`. See the next table. |
82
+ | `code` | For a failure of the model, the code that is also saved in `state.lastError.code`, such as `LLM_RATE_LIMITED` or `LLM_CONTEXT_TOO_LONG`. See [error handling](agent.md#error-handling). |
83
+ | `chatId`, `userId` | The chat and the user of the run, when there is one. |
84
+ | `collection` | In `mongo`, the collection of the call that failed. |
85
+ | `stage` | Where in the process it failed, in `agent` and in `automations`. See the next table. |
86
+ | `guard` | In `agent`, the name of the guard that threw. |
87
+ | `automationId`, `runId` | In `automations`, the automation and the run. |
88
+ | `listener` | In `agent`, `activity` when a listener of `onActivity` threw. |
89
+
90
+ The values of `source`:
91
+
92
+ | `source` | What happened | Extra fields |
93
+ | --- | --- | --- |
94
+ | `agent` | A run failed, a listener of `onActivity` threw, a [guard](guardrails.md) threw, or the agent could not save the traces or the failed state of the chat. `stage` is `guard`, `traces` or `persist` in the last three, and it is missing when the run itself failed. | `chatId`, `userId`, `code` if the model failed, `stage`, `guard` and `listener` as they apply. |
95
+ | `automations` | The runner of the [automations](automations.md#the-runner) caught an error. `stage` is `sync` (checking the open runs), `tick` (looking for what is due), `run` (a run threw) or `onRunFinished` (your own callback threw). | `stage`, and `automationId` and `runId` in `run`. |
96
+ | `mongo` | A call to the database failed, or the connection did. | `collection` in a call. |
97
+ | `openloops` | Any other error that is reported without more detail. | |
98
+
99
+ ## What is reported and what is not
100
+
101
+ The reporter gets what the package catches **by itself**: places where, if it did not report, nobody would ever know.
102
+
103
+ - **A failed run.** `agent.run` returns the error instead of throwing it, so without the reporter you would only see it if you read `result.error`.
104
+ - **A listener of `onActivity` that throws.** The run goes on, so the error would be lost.
105
+ - **A guard that throws.** The request is closed with a generic reply, so the real error would only be in the log.
106
+ - **Traces or the failed state that cannot be saved.** The run does not stop for them, so you would lose them without knowing.
107
+ - **The runner of the automations.** It runs in the background, with nobody waiting for an answer.
108
+ - **A failed call to the database.** The repository reports it and then throws it. You receive it in both places, see below.
109
+
110
+ What is not reported are the errors that the use cases throw, such as a missing resource (`404`), a conflict (`409`) or invalid data (`400`). Those reach the code that called the use case, and that code answers your client and decides whether it is worth reporting.
111
+
112
+ ```typescript
113
+ try {
114
+ await updateChat({ id, payload: { title }, currentUser })
115
+ } catch (error) {
116
+ res.status(error.statusCode ?? 500).json({ message: error.errorMessage })
117
+ }
118
+ ```
119
+
120
+ **A failure of the database arrives twice** if you report it in your own `catch` too: once from the repository, with `source: 'mongo'`, and once from your code. Choose one. The simplest is to report in the reporter only, and in your `catch` only answer your client.
121
+
122
+ ## Rules of the reporter
123
+
124
+ - **It is awaited.** `openloops` waits for the function to finish, so an `async` reporter that sends the event to a service holds the caller until it ends. Keep it quick, or do not `await` the slow part if you do not need to.
125
+ - **It is protected.** An error thrown by the reporter, synchronous or not, is written in the log and ignored. A reporter that fails never breaks a run or a use case.
126
+ - **It receives only `error` and `details`.** The package does not pass the request, the messages of the user or the arguments of the tools.
127
+ - **It receives more than you may want.** Failures that are not a problem of yours, such as `LLM_RATE_LIMITED` or `LLM_QUOTA_EXCEEDED`, arrive too. Filter them, see the next section.
128
+
129
+ ## Filtering and adding context
130
+
131
+ Because the reporter is a plain function, filtering is an `if`:
132
+
133
+ ```typescript
134
+ setErrorReporter((error, details) => {
135
+ if (details.code === 'LLM_RATE_LIMITED' || details.code === 'LLM_QUOTA_EXCEEDED') return
136
+ if (details.source === 'automations' && details.stage === 'onRunFinished') return
137
+
138
+ Sentry.withScope(scope => {
139
+ scope.setTag('source', details.source)
140
+ if (details.userId) scope.setUser({ id: details.userId })
141
+ scope.setExtras(details)
142
+ Sentry.captureException(error)
143
+ })
144
+ })
145
+ ```
146
+
147
+ Send `userId` and `chatId` if your privacy rules allow it: they are the way to find the chat that failed. `details` never carries the messages of the user or the arguments of the tools.
148
+
149
+ ## Lambdas and other serverless deployments
150
+
151
+ Every function is its own process and does not share memory with the others. A declaration in one of them does not reach the rest, so each handler that uses `openloops` must run the declaration.
152
+
153
+ The simple way is a file of its own that declares the reporter, `error-reporting-lambda.ts`:
154
+
155
+ ```typescript
156
+ import * as Sentry from '@sentry/node'
157
+ import { setErrorReporter } from 'openloops/common'
158
+
159
+ Sentry.init({ dsn: process.env.MY_SENTRY_DSN })
160
+
161
+ setErrorReporter(async (error, details) => {
162
+ Sentry.withScope(scope => {
163
+ scope.setTag('source', details.source)
164
+ scope.setExtras(details)
165
+ Sentry.captureException(error)
166
+ })
167
+
168
+ await Sentry.flush(2000)
169
+ })
170
+ ```
171
+
172
+ Imported at the top of every handler:
173
+
174
+ ```typescript
175
+ import './error-reporting-lambda'
176
+ import { listChatsByUser } from 'openloops/chats'
177
+
178
+ export const handler = async (event: any) => {
179
+ const result = await listChatsByUser({ options: { page: 1, limit: 10 }, currentUser })
180
+
181
+ return { statusCode: 200, body: JSON.stringify(result) }
182
+ }
183
+ ```
184
+
185
+ - Importing the same file from many handlers is fine: it runs once in each process.
186
+ - Put the import in a module that every file that calls `openloops` already imports, if you have one (a helper that builds the current user, for example), and you will not forget it in a new handler.
187
+ - A lambda can be frozen as soon as the handler returns. Wait for your tool to send the event inside the reporter (with Sentry, `await Sentry.flush(2000)`), because `openloops` awaits the reporter and that keeps the handler alive until then.
188
+
189
+ ## Tests
190
+
191
+ The reporter lives in the process, so a test that declares one must remove it:
192
+
193
+ ```typescript
194
+ const reporter = jest.fn()
195
+
196
+ beforeEach(() => setErrorReporter(reporter))
197
+ afterEach(() => setErrorReporter(undefined))
198
+
199
+ it('reports a failed run', async () => {
200
+ await agent.run({ input: { message: 'hi' }, currentUser })
201
+
202
+ expect(reporter).toHaveBeenCalledWith(expect.any(Error), expect.objectContaining({ source: 'agent' }))
203
+ })
204
+ ```
205
+
206
+ ## Moving from `SENTRY_DSN`
207
+
208
+ Reporting to Sentry with `SENTRY_DSN` still works, but it is deprecated and will be removed in a future version. Two things changed:
209
+
210
+ - `@sentry/node` is no longer installed with the package. It is an optional peer dependency, loaded only when `SENTRY_DSN` is set and no reporter is registered. If you rely on `SENTRY_DSN`, install it in your project: `yarn add @sentry/node`.
211
+ - The package no longer starts Sentry when it is imported. It starts it the first time it has an error to report, and it warns once in the log that this way is deprecated.
212
+
213
+ To move to the reporter:
214
+
215
+ 1. Install `@sentry/node` in your project and call `Sentry.init` yourself.
216
+ 2. Declare the reporter as shown [above](#declaring-the-reporter).
217
+ 3. Remove `SENTRY_DSN` from the environment of `openloops`.
218
+
219
+ A registered reporter turns the old way off, so nothing is sent twice while you move. If your application already starts Sentry by itself, this also ends the second start that `openloops` made when `SENTRY_DSN` was set.
@@ -88,6 +88,10 @@ Show `data.messages`, and look at `data.state.status`:
88
88
 
89
89
  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).
90
90
 
91
+ ## Reporting errors
92
+
93
+ Register one reporter when the process starts, before the first request, with `setErrorReporter` from `openloops/common`, and send what it receives to Sentry or to the tool you use. A failed run, a failed database call and the errors of the automations runner come to it. In a serverless deployment, import it at the top of each handler that uses `openloops`. Read [reporting errors](error-reporting.md).
94
+
91
95
  ## MCP servers
92
96
 
93
97
  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).
package/docs/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # openloops
2
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.
3
+ > An open source harness for building multitenant AI agents for your SaaS: a TypeScript runtime that runs 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
4
 
5
5
  Start with the integration guide, then read only the pages you need. All pages are in this folder.
6
6
 
@@ -14,6 +14,7 @@ Start with the integration guide, then read only the pages you need. All pages a
14
14
 
15
15
  - [The Agent](agent.md): options, running a turn, statuses, confirmations, autonomous mode
16
16
  - [Configuration](configuration.md): environment variables, default model, timeouts
17
+ - [Reporting errors](error-reporting.md): `setErrorReporter`, what it receives, what is reported, serverless and moving from `SENTRY_DSN`
17
18
  - [Chats](chats.md): the chat record, its title, message source, listing, searching and deleting, and the migration to 0.8.0
18
19
 
19
20
  ## Shape the agent
package/docs/loops.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Building an `AgentLoop`
2
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.
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 works out of the box, so most products never need to write a loop. This page is for the advanced case where you do.
4
4
 
5
5
  ```typescript
6
6
  import { AgentLoop, AgentStatus, Harness, RunContext } from 'openloops/core'
@@ -0,0 +1,75 @@
1
+ import * as Sentry from '@sentry/node'
2
+ import { Agent } from 'openloops/core'
3
+ import { Logger, setErrorReporter } from 'openloops/common'
4
+ import { CurrentUser } from 'openloops/base'
5
+ import { AgiLoop } from 'openloops/loops'
6
+ import { listChatsByUser } from 'openloops/chats'
7
+
8
+ /**
9
+ * 1. DECLARE THE REPORTER, ONCE.
10
+ *
11
+ * Do it when the process starts and before the first request: at the top of the file that starts your server, or in a file that
12
+ * your server imports first. It is global to the process, so there is nothing to pass to the `Agent`, to the use cases or to the
13
+ * runner of the automations: they find the reporter by themselves. If you declare it twice, the second replaces the first.
14
+ *
15
+ * The reporter receives the error and `details`. `details.source` is always there (`agent`, `mongo`, `automations` or
16
+ * `openloops`), and `code`, `chatId` and `userId` come when they exist.
17
+ */
18
+ Sentry.init({ dsn: process.env.MY_SENTRY_DSN })
19
+
20
+ setErrorReporter((error, details) => {
21
+ if (details.code === 'LLM_RATE_LIMITED' || details.code === 'LLM_QUOTA_EXCEEDED') return
22
+
23
+ Sentry.withScope(scope => {
24
+ scope.setTag('source', details.source)
25
+ if (details.userId) scope.setUser({ id: details.userId })
26
+ scope.setExtras(details)
27
+ Sentry.captureException(error)
28
+ })
29
+ })
30
+
31
+ /**
32
+ * 2. RUN YOUR CODE AS ALWAYS.
33
+ *
34
+ * Nothing below mentions the reporter. There is no option in the `Agent`, no wrapper around the use case and no try/catch added
35
+ * to report.
36
+ */
37
+ async function main () {
38
+ const logger = new Logger()
39
+ const currentUser = await CurrentUser.asyncFromDB('6ab56894eb20887d1ef7942c')
40
+
41
+ if (!currentUser) throw new Error('[Demo] current user is not defined')
42
+
43
+ const agent = new Agent({ loop: new AgiLoop() })
44
+
45
+ const result = await agent.run({
46
+ input: {
47
+ message: 'hi, how are you?',
48
+ },
49
+ currentUser,
50
+ })
51
+
52
+ /**
53
+ * `agent.run` does not throw. If the run fails, for example because the provider rejects the API key, openloops saves the
54
+ * chat as `failed`, returns the message for the user in `result.error` and calls the reporter above with
55
+ * `{ source: 'agent', code: 'LLM_AUTH_FAILED', chatId, userId }` (the code depends on what the provider answers).
56
+ * A run that goes well never calls the reporter.
57
+ */
58
+ logger.info({ error: result.error, status: result.data?.state?.status }, '[Demo] Run')
59
+
60
+ /**
61
+ * A use case throws its errors and they reach this `catch`: you decide what to answer to your client. What the reporter
62
+ * receives is what openloops catches by itself. A failed call to the database is one of those cases: the repository calls
63
+ * the reporter with `{ source: 'mongo', collection: 'chats' }` and then throws the error. If this `catch` reported it too,
64
+ * Sentry would get it twice, so report the errors of the database in one of the two places.
65
+ */
66
+ try {
67
+ const chats = await listChatsByUser({ options: { page: 1, limit: 10 }, currentUser })
68
+
69
+ logger.info(chats.items.map(chat => ({ id: chat._id, status: chat.state?.status })), '[Demo] Chats')
70
+ } catch (error: any) {
71
+ logger.error(error, '[Demo] The list could not be read')
72
+ }
73
+ }
74
+
75
+ main()