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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,25 @@
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
+ ## Unreleased
6
+
7
+ ### Changed
8
+
9
+ - The description of the package, the README and the docs index present `openloops` as the harness for building multitenant AI agents for your SaaS, where the model is the engine, `openloops` the chassis and your product the body. The README no longer shows the `CustomerSupportLoop` and `CodeSpecialistLoop` examples, which the package does not ship, and links to the live demo at openloops.xyz.
10
+
11
+ ## 0.8.1
12
+
13
+ ### Added
14
+
15
+ - `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).
16
+ - 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`.
17
+
18
+ ### Changed
19
+
20
+ - The error that the secret manager throws when `SECRET_MANAGER_KEY` is missing now names that variable. It said `SSUID`.
21
+ - `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.
22
+ - 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.
23
+
5
24
  ## 0.8.0
6
25
 
7
26
  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
@@ -1,11 +1,13 @@
1
1
  # openloops
2
2
 
3
- **Build production-grade enterprise agents in minutes, not days, weeks, or months.** · [openloops.xyz](https://openloops.xyz)
3
+ **Build enterprise multitenant AI agents for your SaaS in minutes, not days, weeks, or months.** · [openloops.xyz](https://openloops.xyz)
4
4
 
5
- `openloops` is an open source **harness** for AI agents. An agent is three things: a **model** that thinks (the engine), a **harness** that gives it hands, memory and rules (the chassis), and a **loop** that decides what it is for (the body). `openloops` is the harness, and it ships the loop. Change the model, or the loop, and the rest stays the same.
5
+ Openloops is an open source **harness** for building AI agents. An agent is three things: a **model** that thinks (the engine), a **harness** that gives it hands, memory and rules (the chassis), and the **product** you build around it (the body). Anthropic and OpenAI give you the engine, Openloops is the chassis, with the AGI loop, the tools and everything an agent needs in production, and you build the body: a customer support agent, a financial auditor, a meeting copilot. Change the model, or the product, and the rest stays the same.
6
+
7
+ **Want to see it working?** [Try the live demo](https://openloops.xyz/#demo), a real agent running on Openloops, with nothing to install.
6
8
 
7
9
  <p align="center">
8
- <img src="https://raw.githubusercontent.com/jbarcosdev/openloops/main/docs/assets/harness-car.svg" alt="A car made of an engine (the AI model), a chassis (the harness) and a body (the loop). The body changes between a personal assistant, an analyst, customer support and a programmer, while the engine and the chassis stay the same." width="560">
10
+ <img src="https://raw.githubusercontent.com/jbarcosdev/openloops/main/docs/assets/harness-car.svg" alt="A car made of an engine (the AI model), a chassis (Openloops) and a body (your product). The body changes between a personal assistant, customer support, a meeting copilot and your own idea, while the engine and the chassis stay the same." width="560">
9
11
  </p>
10
12
 
11
13
  ```typescript
@@ -13,13 +15,13 @@ import { Agent } from 'openloops/core'
13
15
  import { Logger } from 'openloops/common'
14
16
  import { CurrentUser } from 'openloops/base'
15
17
  import { AgiLoop } from 'openloops/loops'
16
- import { webSearchTool } from 'openloops/tools'
18
+ import { fetchUrlTool } from 'openloops/tools'
17
19
 
18
20
  const logger = new Logger()
19
21
  const currentUser = await CurrentUser.asyncFromDB(userId)
20
22
  const agent = new Agent({ loop: new AgiLoop() })
21
23
 
22
- agent.addTool(webSearchTool) // needs SERPER_API_KEY, see "Web search" below
24
+ agent.addTool(fetchUrlTool) // reads web pages as text, it needs no key
23
25
 
24
26
  const result = await agent.run({
25
27
  input: { message: 'what is the current price of Bitcoin?' },
@@ -67,27 +69,9 @@ This project uses the `openloops` package. Before writing code that uses it, rea
67
69
  The package has no controllers: the authorization of every endpoint is the responsibility of this backend.
68
70
  ```
69
71
 
70
- ## Pick a loop, or write your own
71
-
72
- The logic that makes your agent *your* agent (how it reasons, when it asks for confirmation, whether it answers in one shot or works through a sequence of tools) lives in an `AgentLoop`. `openloops` ships `AgiLoop`, a reasoning loop that answers directly when it can and otherwise works in cycles of think, act and observe until it has a final answer. Any loop, yours or someone else's, is interchangeable.
73
-
74
- Want a customer support agent?
75
-
76
- ```typescript
77
- const agent = new Agent({ loop: new CustomerSupportLoop() })
78
- ```
79
-
80
- Want a software development agent?
72
+ ## Built for your SaaS, not for one person
81
73
 
82
- ```typescript
83
- const agent = new Agent({ loop: new CodeSpecialistLoop() })
84
- ```
85
-
86
- A loop is a single file with a handful of node functions, so writing your own is a matter of an afternoon, not a sprint. See [Building an `AgentLoop`](docs/loops.md).
87
-
88
- ## Built for products, not for one person
89
-
90
- If you've stood up [OpenClaw](https://github.com/openclaw/openclaw), [Hermes Agent](https://github.com/NousResearch/hermes-agent), or [ZeroClaw](https://github.com/zeroclaw-labs/zeroclaw), you already know how good a single, always-on personal agent can feel. You also know what happens the moment you try to make it serve more than one person: there's no clean boundary between "my agent" and "your agent." Conversations, memory, and connected tools were never designed to be scoped per user in the first place.
74
+ If you've stood up [OpenClaw](https://github.com/openclaw/openclaw), [Hermes Agent](https://github.com/NousResearch/hermes-agent), or [ZeroClaw](https://github.com/zeroclaw-labs/zeroclaw), you already know how good a single, always-on personal agent can feel. You also know what happens the moment you try to make it serve every customer of a product: there's no clean boundary between "my agent" and "your agent." Conversations, memory, and connected tools were never designed to be scoped per user in the first place.
91
75
 
92
76
  `openloops` starts from the opposite assumption. Every chat, every task, every piece of context, and every connected MCP server is scoped to a `currentUser` from the ground up, not bolted on later. Two users, same deployment, completely separate agents, with zero risk of one seeing the other's history or tools.
93
77
 
@@ -95,11 +79,11 @@ If you've stood up [OpenClaw](https://github.com/openclaw/openclaw), [Hermes Age
95
79
 
96
80
  You know the pattern: before you write a single line of what your agent actually *does*, you're declaring a graph, wiring a checkpointer, and figuring out how tool retries and error states are supposed to work. Weeks in, you have an agent that technically runs, and a mental model of *why* it does what it does that only lives in your head, because the framework itself is a black box the moment something goes wrong in production.
97
81
 
98
- `openloops` gives you one file to read to understand your agent's behavior: the loop itself. Persistence and tracing aren't something you configure. They're just already there. See the full comparison further down.
82
+ `openloops` gives you a ready-made chassis: you add your tools and your MCP servers, embed the agent in your app, and the rest is already there. Persistence and tracing aren't something you configure. See the full comparison further down.
99
83
 
100
84
  ## What you get out of the box
101
85
 
102
- - **Multi-user by design.** Chat history, task state, and MCP server configuration are all scoped per user, so the same deployment safely serves every one of your customers.
86
+ - **Multitenant by design.** Chat history, task state, and MCP server configuration are all scoped per user, so the same deployment safely serves every one of your customers.
103
87
  - **Zero-boilerplate persistence.** Messages, tasks, and every tool call your agent makes are saved automatically to MongoDB, and a conversation resumes exactly where it stopped, including in the middle of a confirmation or a question. You never write a `save()` call.
104
88
  - **Safe tool execution.** Arguments are validated against the tool's schema, destructive tools wait for the user's confirmation, identical failing calls are blocked, identifiers the model invented are rejected before they reach a real system, and large outputs are kept out of the prompt. LLM calls retry with backoff and wait out rate limits.
105
89
  - **Native MCP support with a trust flow.** Connect any MCP server and its tools become regular tools. Each server must be approved by the user before its first tool runs, and a server that changes its tools is reviewed again, so a third party cannot quietly change what your agent does.
@@ -109,7 +93,7 @@ You know the pattern: before you write a single line of what your agent actually
109
93
  - **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
94
  - **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
95
  - **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.
96
+ - **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
97
 
114
98
  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
99
 
@@ -173,9 +157,9 @@ This is a comparison against the self-hosted, open-source versions of LangGraph
173
157
  | 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
158
  | User management | Included (`openloops/users`, `openloops/authentication`) | Not included, you build your own | Not included, you build your own |
175
159
  | 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 |
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
- | 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 |
160
+ | 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 |
161
+ | What you write | Your tools and MCP servers, and the product you build on top. The loop is included, and you can write your own | Nodes and the graph's edges, explicitly | Agents, tasks, and crew orchestration, declared per role |
162
+ | Mental model | A ready-made chassis: you connect your tools and embed the agent in your app | A graph you declare and compile ahead of time | A crew of role-based agents coordinated for you |
179
163
 
180
164
  Neither approach is "wrong." LangGraph's explicit graph declaration is a deliberate design choice that gives you visual tooling (LangGraph Studio) and fine-grained control over parallel execution, and CrewAI's role-based model is a natural fit for problems that map cleanly onto a team of specialists. `openloops` trades some of that explicitness for a much shorter path from "I have an idea for an agent" to "it's running in production, for all my users."
181
165
 
@@ -229,7 +213,6 @@ MCP_TOOL_TIMEOUT_MS=
229
213
  OPENLOOPS_MONGO_MAX_POOL_SIZE=
230
214
 
231
215
  # Optional, see "Observability" below
232
- SENTRY_DSN=
233
216
  LANGFUSE_SECRET_KEY=
234
217
  LANGFUSE_PUBLIC_KEY=
235
218
  LANGFUSE_BASE_URL=
@@ -255,14 +238,18 @@ The built-in `sendSlackMessageTool` posts a message to a channel. Create a Slack
255
238
 
256
239
  ### Observability
257
240
 
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.
241
+ - **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.
242
+ - **Langfuse**: set `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, and `LANGFUSE_BASE_URL` and every LLM call is traced automatically, with no code changes.
243
+
244
+ ## The AGI loop, and your own if you need it
245
+
246
+ The logic that makes your agent *your* agent (how it reasons, when it asks for confirmation, whether it answers in one shot or works through a sequence of tools) lives in an `AgentLoop`. Most products never need to write one: `openloops` ships `AgiLoop`, a reasoning loop that answers directly when it can and otherwise works in cycles of think, act and observe until it has a final answer. What you add is your tools and your MCP servers.
260
247
 
261
- Neither requires any code changes. They're opt-in purely through environment variables.
248
+ If you need full control, a loop is a single file with a handful of node functions, so writing your own is a matter of an afternoon, not a sprint. See [Building an `AgentLoop`](docs/loops.md).
262
249
 
263
250
  ## More examples
264
251
 
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`.
252
+ 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
253
 
267
254
  ## Package structure
268
255
 
@@ -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) {