openloops 0.8.0 → 0.8.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 (38) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +5 -8
  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/chats.md +1 -1
  33. package/docs/configuration.md +5 -1
  34. package/docs/error-reporting.md +219 -0
  35. package/docs/integration-guide.md +4 -0
  36. package/docs/llms.txt +1 -0
  37. package/examples/errors/error-reporting.ts +75 -0
  38. package/package.json +18 -6
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to `openloops` are written here, newest first. The format follows [Keep a Changelog](https://keepachangelog.com) and the versions follow [semantic versioning](https://semver.org), where a minor version can still break the API while the package is in beta. Changes before 0.4.0 are not recorded here, see the commits and the tags.
4
4
 
5
+ ## 0.8.1
6
+
7
+ ### Added
8
+
9
+ - `setErrorReporter(callback)` in `openloops/common`, to receive the errors that the package catches and send them to the tool you use. The callback gets the error and `details`, with a `source` (`agent`, `mongo`, `automations` or `openloops`) and, when they exist, `code`, `chatId` and `userId`. It is global to the process, it is awaited, and an error in it is ignored. Read [reporting errors](docs/error-reporting.md) and the [example](examples/errors/error-reporting.ts).
10
+ - The `Agent` reports a failed run, an `onActivity` listener that throws, a guard that throws, and the traces or the failed state of the chat that it cannot save, and the automations runner reports the errors it catches (`sync`, `tick`, `run` and `onRunFinished`). Before, those only went to the log. A reporter also receives the failures of the model that are not a problem of yours, such as `LLM_RATE_LIMITED`: filter them by `code`.
11
+
12
+ ### Changed
13
+
14
+ - The error that the secret manager throws when `SECRET_MANAGER_KEY` is missing now names that variable. It said `SSUID`.
15
+ - `migrateChatTitles` removes the HTML tags of the message it takes as a title, as the entities do with any text. Before, the title kept them.
16
+ - Reporting errors to Sentry with `SENTRY_DSN` is deprecated and will be removed in a future version. `@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, and the package no longer starts Sentry when it is imported. If you rely on `SENTRY_DSN`, install `@sentry/node` in your project, or move to `setErrorReporter`: read [moving from `SENTRY_DSN`](docs/error-reporting.md#moving-from-sentry_dsn). Registering a reporter turns the old path off.
17
+
5
18
  ## 0.8.0
6
19
 
7
20
  This version removes `state.currentActivity` from the chat and needs a migration of the chats that were saved before. Follow the [migration steps](docs/chats.md#migrating-to-080) when you update.
package/README.md CHANGED
@@ -109,7 +109,7 @@ You know the pattern: before you write a single line of what your agent actually
109
109
  - **Usage and cost tracking.** Every LLM call is recorded. Get the tokens and cost of a chat or an answer, and per-user statistics by model and by period. See [usage](docs/usage.md).
110
110
  - **Users and authentication included.** User management and login with tokens, so you don't need a parallel system just to have an identity to hand the `Agent`.
111
111
  - **Any LLM provider, including local ones.** Built on [`@earendil-works/pi-ai`](https://www.npmjs.com/package/@earendil-works/pi-ai), so OpenAI, Anthropic, Google, and self-hosted models (e.g. via Ollama) all work the same way, chosen per chat.
112
- - **Observability without ceremony.** Sentry and Langfuse are built in. Set the environment variables and they turn on, no SDK wiring required. Every node, skill and guard also writes a trace you can read back.
112
+ - **Observability without ceremony.** Langfuse is built in: set the environment variables and every LLM call is traced. Errors go to one function that you register, so you report them to Sentry or to whatever tool you use. Every node, skill and guard also writes a trace you can read back.
113
113
 
114
114
  On the roadmap: **sub-agent orchestration**, where an agent launches and coordinates other agents to split up a problem. A guide will come with it.
115
115
 
@@ -173,7 +173,7 @@ This is a comparison against the self-hosted, open-source versions of LangGraph
173
173
  | MCP support | Native: servers are a per-user record, tools load on demand, and every server goes through an approval flow | A separate package (`langchain-mcp-adapters`) with a client that you wire into the graph | Native `mcps` field on agents, or `MCPServerAdapter`. Servers are declared in code, not loaded per user |
174
174
  | User management | Included (`openloops/users`, `openloops/authentication`) | Not included, you build your own | Not included, you build your own |
175
175
  | LLM usage/cost tracking | Included (`openloops/llmcalls`): per answer, per chat, and per-user statistics | Not included in OSS, available via paid LangSmith | Third-party integrations such as OpenLIT report token usage and cost |
176
- | Observability | Sentry + Langfuse, enabled via env vars, plus traces stored per chat | Your own tracing setup, or paid LangSmith | Third-party integrations (Langfuse, OpenLIT, Arize Phoenix, Opik, Weave) that you set up |
176
+ | Observability | Langfuse via env vars, a hook to report errors to the tool you use, and traces stored per chat | Your own tracing setup, or paid LangSmith | Third-party integrations (Langfuse, OpenLIT, Arize Phoenix, Opik, Weave) that you set up |
177
177
  | What you write | Node functions (plain async functions) | Nodes and the graph's edges, explicitly | Agents, tasks, and crew orchestration, declared per role |
178
178
  | Mental model | A state machine your loop drives itself | A graph you declare and compile ahead of time | A crew of role-based agents coordinated for you |
179
179
 
@@ -229,7 +229,6 @@ MCP_TOOL_TIMEOUT_MS=
229
229
  OPENLOOPS_MONGO_MAX_POOL_SIZE=
230
230
 
231
231
  # Optional, see "Observability" below
232
- SENTRY_DSN=
233
232
  LANGFUSE_SECRET_KEY=
234
233
  LANGFUSE_PUBLIC_KEY=
235
234
  LANGFUSE_BASE_URL=
@@ -255,14 +254,12 @@ The built-in `sendSlackMessageTool` posts a message to a channel. Create a Slack
255
254
 
256
255
  ### Observability
257
256
 
258
- - **Sentry**: set `SENTRY_DSN` and error tracking turns on automatically.
259
- - **Langfuse**: set `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, and `LANGFUSE_BASE_URL` and every LLM call is traced automatically.
260
-
261
- Neither requires any code changes. They're opt-in purely through environment variables.
257
+ - **Errors**: register one function with `setErrorReporter` and send them to Sentry or to the tool you use. See [reporting errors](docs/error-reporting.md). Reporting with `SENTRY_DSN` still works but is deprecated.
258
+ - **Langfuse**: set `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, and `LANGFUSE_BASE_URL` and every LLM call is traced automatically, with no code changes.
262
259
 
263
260
  ## More examples
264
261
 
265
- Every pattern above, and a lot more, lives as a runnable example in [`examples/`](examples), organized by domain: `run-agent`, `loops`, `tools`, `guardrails`, `automations`, `mcps`, `chats`, `usage`, `users`, and `authentication`.
262
+ Every pattern above, and a lot more, lives as a runnable example in [`examples/`](examples), organized by domain: `run-agent`, `loops`, `tools`, `guardrails`, `automations`, `mcps`, `chats`, `usage`, `users`, `errors`, and `authentication`.
266
263
 
267
264
  ## Package structure
268
265
 
@@ -0,0 +1,11 @@
1
+ import type { HttpError } from './http-error';
2
+ export interface ErrorReportDetails {
3
+ source: string;
4
+ code?: string;
5
+ chatId?: string;
6
+ userId?: string;
7
+ [key: string]: unknown;
8
+ }
9
+ export type ErrorReporter = (error: Error | HttpError, details: ErrorReportDetails) => void | Promise<void>;
10
+ export declare function setErrorReporter(callback?: ErrorReporter): void;
11
+ export declare function getErrorReporter(): ErrorReporter | undefined;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var error_reporter_exports = {};
20
+ __export(error_reporter_exports, {
21
+ getErrorReporter: () => getErrorReporter,
22
+ setErrorReporter: () => setErrorReporter
23
+ });
24
+ module.exports = __toCommonJS(error_reporter_exports);
25
+ let reporter;
26
+ function setErrorReporter(callback) {
27
+ reporter = callback;
28
+ }
29
+ function getErrorReporter() {
30
+ return reporter;
31
+ }
32
+ // Annotate the CommonJS export names for ESM import in node:
33
+ 0 && (module.exports = {
34
+ getErrorReporter,
35
+ setErrorReporter
36
+ });
@@ -0,0 +1,11 @@
1
+ let reporter;
2
+ function setErrorReporter(callback) {
3
+ reporter = callback;
4
+ }
5
+ function getErrorReporter() {
6
+ return reporter;
7
+ }
8
+ export {
9
+ getErrorReporter,
10
+ setErrorReporter
11
+ };
@@ -1,2 +1,3 @@
1
1
  export * from './reportError';
2
2
  export * from './http-error';
3
+ export * from './error-reporter';
@@ -17,8 +17,10 @@ var error_exports = {};
17
17
  module.exports = __toCommonJS(error_exports);
18
18
  __reExport(error_exports, require("./reportError"), module.exports);
19
19
  __reExport(error_exports, require("./http-error"), module.exports);
20
+ __reExport(error_exports, require("./error-reporter"), module.exports);
20
21
  // Annotate the CommonJS export names for ESM import in node:
21
22
  0 && (module.exports = {
22
23
  ...require("./reportError"),
23
- ...require("./http-error")
24
+ ...require("./http-error"),
25
+ ...require("./error-reporter")
24
26
  });
@@ -1,2 +1,3 @@
1
1
  export * from "./reportError";
2
2
  export * from "./http-error";
3
+ export * from "./error-reporter";
@@ -22,6 +22,7 @@ __export(reportError_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(reportError_exports);
24
24
  var import_sentry_client = require("./sentry-client");
25
+ var import_error_reporter = require("./error-reporter");
25
26
  var import_http_error = require("./http-error");
26
27
  var import_logger = require("../logger");
27
28
  const reportError = async (error, details) => {
@@ -33,6 +34,15 @@ const reportError = async (error, details) => {
33
34
  error: details,
34
35
  message: errorMessage
35
36
  }, "[Report Error] Reporting new error");
37
+ const reporter = (0, import_error_reporter.getErrorReporter)();
38
+ if (reporter) {
39
+ try {
40
+ await reporter(error, { source: "openloops", ...details });
41
+ } catch (failure) {
42
+ import_logger.logger.error({ error: failure }, "[Report Error] The error reporter failed");
43
+ }
44
+ return;
45
+ }
36
46
  const isLocal = process.env.IS_LOCAL === "true" || process.env.NODE_ENV === "development";
37
47
  try {
38
48
  !isLocal && await import_sentry_client.sentryClient?.captureError(error, {
@@ -1,4 +1,5 @@
1
1
  import { sentryClient } from "./sentry-client";
2
+ import { getErrorReporter } from "./error-reporter";
2
3
  import { HttpError } from "./http-error";
3
4
  import { logger } from "../logger";
4
5
  const reportError = async (error, details) => {
@@ -10,6 +11,15 @@ const reportError = async (error, details) => {
10
11
  error: details,
11
12
  message: errorMessage
12
13
  }, "[Report Error] Reporting new error");
14
+ const reporter = getErrorReporter();
15
+ if (reporter) {
16
+ try {
17
+ await reporter(error, { source: "openloops", ...details });
18
+ } catch (failure) {
19
+ logger.error({ error: failure }, "[Report Error] The error reporter failed");
20
+ }
21
+ return;
22
+ }
13
23
  const isLocal = process.env.IS_LOCAL === "true" || process.env.NODE_ENV === "development";
14
24
  try {
15
25
  !isLocal && await sentryClient?.captureError(error, {
@@ -1,10 +1,10 @@
1
1
  export declare class SentryClient {
2
2
  private static instance;
3
- private readonly enabled;
3
+ private sdk?;
4
4
  static getInstance(): SentryClient;
5
5
  private constructor();
6
6
  captureError(error: unknown, contextData?: Record<string, any>): Promise<void>;
7
- setUser(userId: string): void;
7
+ private load;
8
8
  private resolveDsn;
9
9
  }
10
10
  export declare const sentryClient: SentryClient;
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
  var sentry_client_exports = {};
30
20
  __export(sentry_client_exports, {
@@ -32,12 +22,11 @@ __export(sentry_client_exports, {
32
22
  sentryClient: () => sentryClient
33
23
  });
34
24
  module.exports = __toCommonJS(sentry_client_exports);
35
- var Sentry = __toESM(require("@sentry/node"));
36
25
  var import_logger = require("../logger");
37
26
  var import_secret_manager = require("../utils/secret-manager.js");
38
27
  class SentryClient {
39
28
  static instance;
40
- enabled;
29
+ sdk;
41
30
  static getInstance() {
42
31
  if (!SentryClient.instance) {
43
32
  SentryClient.instance = new SentryClient();
@@ -45,17 +34,10 @@ class SentryClient {
45
34
  return SentryClient.instance;
46
35
  }
47
36
  constructor() {
48
- const dsn = this.resolveDsn();
49
- this.enabled = !!dsn;
50
- if (!dsn) {
51
- import_logger.logger.warn("[Sentry Client] Sentry DSN is not configured. Skipping error reporting.");
52
- return;
53
- }
54
- Sentry.init({ dsn, environment: process.env.NODE_ENV || "production", tracesSampleRate: 0 });
55
- import_logger.logger.debug("[Sentry Client] Sentry client initialized");
56
37
  }
57
38
  async captureError(error, contextData) {
58
- if (!this.enabled) return;
39
+ const Sentry = this.load();
40
+ if (!Sentry) return;
59
41
  Sentry.withScope((scope) => {
60
42
  if (contextData) scope.setExtras(contextData);
61
43
  Sentry.captureException(error);
@@ -67,9 +49,22 @@ class SentryClient {
67
49
  import_logger.logger.error(e, "[Sentry Client] Failed to flush Sentry events");
68
50
  }
69
51
  }
70
- setUser(userId) {
71
- if (!this.enabled) return;
72
- Sentry.setUser({ id: userId });
52
+ load() {
53
+ if (this.sdk !== void 0) return this.sdk;
54
+ const dsn = this.resolveDsn();
55
+ if (!dsn) {
56
+ import_logger.logger.warn("[Sentry Client] Sentry DSN is not configured. Skipping error reporting.");
57
+ return this.sdk = null;
58
+ }
59
+ try {
60
+ const Sentry = require("@sentry/node");
61
+ Sentry.init({ dsn, environment: process.env.NODE_ENV || "production", tracesSampleRate: 0 });
62
+ import_logger.logger.warn("[Sentry Client] Reporting to Sentry with SENTRY_DSN is deprecated and will be removed in a future version. Register your own reporter with setErrorReporter.");
63
+ return this.sdk = Sentry;
64
+ } catch {
65
+ import_logger.logger.warn("[Sentry Client] SENTRY_DSN is set but @sentry/node is not installed. Install it, or register your own reporter with setErrorReporter.");
66
+ return this.sdk = null;
67
+ }
73
68
  }
74
69
  resolveDsn() {
75
70
  try {
@@ -1,9 +1,8 @@
1
- import * as Sentry from "@sentry/node";
2
1
  import { logger } from "../logger";
3
2
  import { secretManager } from "../utils/secret-manager.js";
4
3
  class SentryClient {
5
4
  static instance;
6
- enabled;
5
+ sdk;
7
6
  static getInstance() {
8
7
  if (!SentryClient.instance) {
9
8
  SentryClient.instance = new SentryClient();
@@ -11,17 +10,10 @@ class SentryClient {
11
10
  return SentryClient.instance;
12
11
  }
13
12
  constructor() {
14
- const dsn = this.resolveDsn();
15
- this.enabled = !!dsn;
16
- if (!dsn) {
17
- logger.warn("[Sentry Client] Sentry DSN is not configured. Skipping error reporting.");
18
- return;
19
- }
20
- Sentry.init({ dsn, environment: process.env.NODE_ENV || "production", tracesSampleRate: 0 });
21
- logger.debug("[Sentry Client] Sentry client initialized");
22
13
  }
23
14
  async captureError(error, contextData) {
24
- if (!this.enabled) return;
15
+ const Sentry = this.load();
16
+ if (!Sentry) return;
25
17
  Sentry.withScope((scope) => {
26
18
  if (contextData) scope.setExtras(contextData);
27
19
  Sentry.captureException(error);
@@ -33,9 +25,22 @@ class SentryClient {
33
25
  logger.error(e, "[Sentry Client] Failed to flush Sentry events");
34
26
  }
35
27
  }
36
- setUser(userId) {
37
- if (!this.enabled) return;
38
- Sentry.setUser({ id: userId });
28
+ load() {
29
+ if (this.sdk !== void 0) return this.sdk;
30
+ const dsn = this.resolveDsn();
31
+ if (!dsn) {
32
+ logger.warn("[Sentry Client] Sentry DSN is not configured. Skipping error reporting.");
33
+ return this.sdk = null;
34
+ }
35
+ try {
36
+ const Sentry = require("@sentry/node");
37
+ Sentry.init({ dsn, environment: process.env.NODE_ENV || "production", tracesSampleRate: 0 });
38
+ logger.warn("[Sentry Client] Reporting to Sentry with SENTRY_DSN is deprecated and will be removed in a future version. Register your own reporter with setErrorReporter.");
39
+ return this.sdk = Sentry;
40
+ } catch {
41
+ logger.warn("[Sentry Client] SENTRY_DSN is set but @sentry/node is not installed. Install it, or register your own reporter with setErrorReporter.");
42
+ return this.sdk = null;
43
+ }
39
44
  }
40
45
  resolveDsn() {
41
46
  try {
@@ -1 +1,3 @@
1
1
  export * from './logger';
2
+ export { setErrorReporter } from './error/error-reporter';
3
+ export type { ErrorReporter, ErrorReportDetails } from './error/error-reporter';
@@ -3,6 +3,10 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
6
10
  var __copyProps = (to, from, except, desc) => {
7
11
  if (from && typeof from === "object" || typeof from === "function") {
8
12
  for (let key of __getOwnPropNames(from))
@@ -14,9 +18,14 @@ var __copyProps = (to, from, except, desc) => {
14
18
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
20
  var common_exports = {};
21
+ __export(common_exports, {
22
+ setErrorReporter: () => import_error_reporter.setErrorReporter
23
+ });
17
24
  module.exports = __toCommonJS(common_exports);
18
25
  __reExport(common_exports, require("./logger"), module.exports);
26
+ var import_error_reporter = require("./error/error-reporter");
19
27
  // Annotate the CommonJS export names for ESM import in node:
20
28
  0 && (module.exports = {
29
+ setErrorReporter,
21
30
  ...require("./logger")
22
31
  });
@@ -1 +1,5 @@
1
1
  export * from "./logger";
2
+ import { setErrorReporter } from "./error/error-reporter";
3
+ export {
4
+ setErrorReporter
5
+ };
@@ -59,7 +59,7 @@ class MongoClient {
59
59
  await this.connect();
60
60
  } catch (error) {
61
61
  this.logger.error("[Mongo Client]: Error connecting to MongoDB");
62
- await (0, import_error.reportError)(`Error connecting to MongoDB: ${error.message}`, { error });
62
+ await (0, import_error.reportError)(`Error connecting to MongoDB: ${error.message}`, { source: "mongo", error });
63
63
  throw error;
64
64
  }
65
65
  return this.client.db(dbName, options);
@@ -37,7 +37,7 @@ class MongoClient {
37
37
  await this.connect();
38
38
  } catch (error) {
39
39
  this.logger.error("[Mongo Client]: Error connecting to MongoDB");
40
- await reportError(`Error connecting to MongoDB: ${error.message}`, { error });
40
+ await reportError(`Error connecting to MongoDB: ${error.message}`, { source: "mongo", error });
41
41
  throw error;
42
42
  }
43
43
  return this.client.db(dbName, options);
@@ -44,7 +44,7 @@ class MongoRepository {
44
44
  scoped;
45
45
  ownerField;
46
46
  protectedFields;
47
- report = import_error.reportError;
47
+ report = (error) => (0, import_error.reportError)(error, { source: "mongo", collection: this.collection });
48
48
  constructor(props) {
49
49
  const { database, collection, envvar, scoped = false, ownerField = "ownerId", protectedFields = [] } = props || {};
50
50
  if (!database) throw new Error("[Mongo Repository] Database name is required");
@@ -20,7 +20,7 @@ class MongoRepository {
20
20
  scoped;
21
21
  ownerField;
22
22
  protectedFields;
23
- report = reportError;
23
+ report = (error) => reportError(error, { source: "mongo", collection: this.collection });
24
24
  constructor(props) {
25
25
  const { database, collection, envvar, scoped = false, ownerField = "ownerId", protectedFields = [] } = props || {};
26
26
  if (!database) throw new Error("[Mongo Repository] Database name is required");
@@ -52,7 +52,7 @@ class SecretManager {
52
52
  constructor() {
53
53
  const secretKey = process.env.SECRET_MANAGER_KEY;
54
54
  if (!secretKey) {
55
- throw new Error("[Secret manager] SSUID environment variable is not set");
55
+ throw new Error("[Secret manager] SECRET_MANAGER_KEY environment variable is not set");
56
56
  }
57
57
  this.cryptr = new import_cryptr.default(secretKey, {
58
58
  pbkdf2Iterations: 1e3,
@@ -18,7 +18,7 @@ class SecretManager {
18
18
  constructor() {
19
19
  const secretKey = process.env.SECRET_MANAGER_KEY;
20
20
  if (!secretKey) {
21
- throw new Error("[Secret manager] SSUID environment variable is not set");
21
+ throw new Error("[Secret manager] SECRET_MANAGER_KEY environment variable is not set");
22
22
  }
23
23
  this.cryptr = new Cryptr(secretKey, {
24
24
  pbkdf2Iterations: 1e3,
@@ -111,6 +111,7 @@ export declare class Agent {
111
111
  private requestApproval;
112
112
  private resolveConfirmation;
113
113
  private postRunner;
114
+ private reportFailure;
114
115
  private failRun;
115
116
  private fingerprint;
116
117
  private loadTasks;
@@ -24,6 +24,7 @@ __export(agent_exports, {
24
24
  module.exports = __toCommonJS(agent_exports);
25
25
  var import_mongodb = require("mongodb");
26
26
  var import_logger = require("../common/logger/index.js");
27
+ var import_error = require("../common/error/index.js");
27
28
  var import_entities = require("../services/mcp-servers/entities/index.js");
28
29
  var import_chats = require("../services/chats/index.js");
29
30
  var import_chat = require("../services/chats/entities/chat.entity.js");
@@ -191,6 +192,7 @@ class Agent {
191
192
  const llmError = error instanceof import_llm_error.LLMError ? error : void 0;
192
193
  const reported = llmError?.userMessage ?? message;
193
194
  await this.failRun(reported, llmError);
195
+ await this.reportFailure(error, llmError ? { code: llmError.code } : {});
194
196
  return { data: this.currentChat?._id ? this.currentChat : void 0, error: reported };
195
197
  }
196
198
  }
@@ -221,6 +223,7 @@ class Agent {
221
223
  listener(activity);
222
224
  } catch (error) {
223
225
  this.logger.warn({ error: error?.message ?? error }, "[AGENT] An activity listener failed");
226
+ void this.reportFailure(error, { listener: "activity" });
224
227
  }
225
228
  }
226
229
  }
@@ -294,6 +297,7 @@ class Agent {
294
297
  result = await guard.run(context);
295
298
  } catch (error) {
296
299
  this.logger.error({ error: error?.message ?? error, guard: guard.name }, "[AGENT] Guard failed");
300
+ await this.reportFailure(error, { stage: "guard", guard: guard.name });
297
301
  failed = true;
298
302
  result = { passed: false, reason: `Guard failed: ${error?.message ?? error}` };
299
303
  }
@@ -378,6 +382,9 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
378
382
  await this.persist();
379
383
  await this.disconnectMcpServers();
380
384
  }
385
+ async reportFailure(error, details = {}) {
386
+ await (0, import_error.reportError)(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
387
+ }
381
388
  async failRun(message, llmError) {
382
389
  try {
383
390
  this.currentChat.state?.setStatus(import_agent_state.AgentStatus.FAILED);
@@ -387,6 +394,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
387
394
  await this.persist();
388
395
  } catch (saveError) {
389
396
  this.logger.error({ error: saveError?.message ?? saveError }, "[AGENT] Failed to persist failed run state");
397
+ await this.reportFailure(saveError, { stage: "persist" });
390
398
  } finally {
391
399
  await this.disconnectMcpServers();
392
400
  }
@@ -474,6 +482,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
474
482
  });
475
483
  } catch (error) {
476
484
  this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to persist traces");
485
+ await this.reportFailure(error, { stage: "traces" });
477
486
  }
478
487
  }
479
488
  async persist(props) {
@@ -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).
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
@@ -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
@@ -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()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openloops",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "Open source harness for AI agents: a TypeScript runtime with persistence, tools, MCP trust, approvals and autonomous automations, where the loop is pluggable",
5
5
  "author": {
6
6
  "name": "Jose Barcos",
@@ -8,6 +8,14 @@
8
8
  "url": "https://github.com/jbarcosdev"
9
9
  },
10
10
  "license": "Apache-2.0",
11
+ "homepage": "https://openloops.xyz",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/jbarcosdev/openloops.git"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/jbarcosdev/openloops/issues"
18
+ },
11
19
  "main": "dist/index.js",
12
20
  "types": "dist/index.d.ts",
13
21
  "exports": {
@@ -109,7 +117,6 @@
109
117
  "dependencies": {
110
118
  "@earendil-works/pi-ai": "^1.5.0",
111
119
  "@modelcontextprotocol/sdk": "^1.32.2",
112
- "@sentry/node": "^11.11.0",
113
120
  "bcryptjs": "^3.0.3",
114
121
  "croner": "^11.0.0",
115
122
  "cryptr": "^6.4.0",
@@ -121,6 +128,7 @@
121
128
  "pino": "^10.4.0"
122
129
  },
123
130
  "devDependencies": {
131
+ "@sentry/node": "^11.11.0",
124
132
  "@types/jest": "^30.0.0",
125
133
  "@types/node": "^26.6.6",
126
134
  "jest": "^30.5.2",
@@ -131,13 +139,17 @@
131
139
  "tsup": "^9.0.0",
132
140
  "typescript": "^6.0.3"
133
141
  },
142
+ "peerDependencies": {
143
+ "@sentry/node": "^11.11.0"
144
+ },
145
+ "peerDependenciesMeta": {
146
+ "@sentry/node": {
147
+ "optional": true
148
+ }
149
+ },
134
150
  "engines": {
135
151
  "node": ">=22.0.0"
136
152
  },
137
- "repository": {
138
- "type": "git",
139
- "url": "git+https://github.com/jbarcosdev/openloops.git"
140
- },
141
153
  "keywords": [
142
154
  "ai-agent",
143
155
  "ai-agents",