openloops 0.7.6 → 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 (86) hide show
  1. package/CHANGELOG.md +66 -11
  2. package/README.md +5 -8
  3. package/dist/clients/llm/llm-error.d.ts +1 -1
  4. package/dist/clients/llm/llm-error.js +12 -0
  5. package/dist/clients/llm/llm-error.mjs +12 -0
  6. package/dist/common/error/error-reporter.d.ts +11 -0
  7. package/dist/common/error/error-reporter.js +36 -0
  8. package/dist/common/error/error-reporter.mjs +11 -0
  9. package/dist/common/error/index.d.ts +1 -0
  10. package/dist/common/error/index.js +3 -1
  11. package/dist/common/error/index.mjs +1 -0
  12. package/dist/common/error/reportError.js +10 -0
  13. package/dist/common/error/reportError.mjs +10 -0
  14. package/dist/common/error/sentry-client.d.ts +2 -2
  15. package/dist/common/error/sentry-client.js +19 -24
  16. package/dist/common/error/sentry-client.mjs +19 -14
  17. package/dist/common/helpers/index.d.ts +1 -0
  18. package/dist/common/helpers/index.js +3 -1
  19. package/dist/common/helpers/index.mjs +1 -0
  20. package/dist/common/helpers/sanitize-string.js +5 -15
  21. package/dist/common/helpers/sanitize-string.mjs +5 -5
  22. package/dist/common/helpers/strip-blocks.d.ts +1 -0
  23. package/dist/common/helpers/strip-blocks.js +45 -0
  24. package/dist/common/helpers/strip-blocks.mjs +21 -0
  25. package/dist/common/index.d.ts +2 -0
  26. package/dist/common/index.js +9 -0
  27. package/dist/common/index.mjs +4 -0
  28. package/dist/common/logger/pino.js +12 -3
  29. package/dist/common/logger/pino.mjs +12 -3
  30. package/dist/common/repositories/mongo-db.client.js +1 -1
  31. package/dist/common/repositories/mongo-db.client.mjs +1 -1
  32. package/dist/common/repositories/mongo-db.repository.js +1 -1
  33. package/dist/common/repositories/mongo-db.repository.mjs +1 -1
  34. package/dist/common/utils/secret-manager.js +1 -1
  35. package/dist/common/utils/secret-manager.mjs +1 -1
  36. package/dist/db/index.d.ts +1 -0
  37. package/dist/db/index.js +3 -1
  38. package/dist/db/index.mjs +1 -0
  39. package/dist/db/migrations/chat-titles.d.ts +10 -0
  40. package/dist/db/migrations/chat-titles.js +55 -0
  41. package/dist/db/migrations/chat-titles.mjs +31 -0
  42. package/dist/harness/agent-state.d.ts +0 -1
  43. package/dist/harness/agent.d.ts +1 -0
  44. package/dist/harness/agent.js +9 -0
  45. package/dist/harness/agent.mjs +9 -0
  46. package/dist/loops/agi/loop.js +4 -2
  47. package/dist/loops/agi/loop.mjs +4 -2
  48. package/dist/loops/shared/skills/fast-responder.d.ts +1 -0
  49. package/dist/loops/shared/skills/fast-responder.js +4 -2
  50. package/dist/loops/shared/skills/fast-responder.mjs +4 -2
  51. package/dist/services/automations/runner/automation-runner.js +6 -1
  52. package/dist/services/automations/runner/automation-runner.mjs +6 -1
  53. package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.d.ts +2 -1
  54. package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.js +2 -2
  55. package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.mjs +2 -2
  56. package/dist/services/automations/use-cases/sync-automation-run.use-case.d.ts +1 -0
  57. package/dist/services/automations/use-cases/sync-automation-run.use-case.js +6 -2
  58. package/dist/services/automations/use-cases/sync-automation-run.use-case.mjs +5 -2
  59. package/dist/services/chats/entities/chat.entity.d.ts +3 -0
  60. package/dist/services/chats/entities/chat.entity.js +8 -0
  61. package/dist/services/chats/entities/chat.entity.mjs +8 -0
  62. package/dist/services/chats/use-cases/get-chat-by-id.use-case.js +1 -5
  63. package/dist/services/chats/use-cases/get-chat-by-id.use-case.mjs +1 -5
  64. package/dist/services/chats/use-cases/list-chats-by-user.use-case.d.ts +2 -1
  65. package/dist/services/chats/use-cases/list-chats-by-user.use-case.js +3 -2
  66. package/dist/services/chats/use-cases/list-chats-by-user.use-case.mjs +3 -2
  67. package/dist/services/chats/utils/title.d.ts +2 -0
  68. package/dist/services/chats/utils/title.js +37 -0
  69. package/dist/services/chats/utils/title.mjs +12 -0
  70. package/dist/tools/core/fetch-url/html-to-text.js +3 -20
  71. package/dist/tools/core/fetch-url/html-to-text.mjs +3 -20
  72. package/docs/README.md +2 -1
  73. package/docs/agent.md +20 -3
  74. package/docs/automations.md +3 -3
  75. package/docs/chats.md +41 -8
  76. package/docs/configuration.md +6 -2
  77. package/docs/error-reporting.md +219 -0
  78. package/docs/integration-guide.md +6 -2
  79. package/docs/llms.txt +2 -1
  80. package/docs/loops.md +1 -1
  81. package/examples/chats/search-chats.ts +30 -0
  82. package/examples/errors/error-reporting.ts +75 -0
  83. package/package.json +23 -12
  84. package/dist/services/chats/utils/deprecated-activity.d.ts +0 -1
  85. package/dist/services/chats/utils/deprecated-activity.js +0 -60
  86. package/dist/services/chats/utils/deprecated-activity.mjs +0 -36
package/CHANGELOG.md CHANGED
@@ -2,33 +2,88 @@
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
5
+ ## 0.8.1
6
6
 
7
- This version breaks the API of the internal MCP servers in automations. Before, the runner sent one token for the whole deployment, from `INTERNAL_MCP_TOKEN`. Now each internal server declares its own. To migrate: delete `INTERNAL_MCP_TOKEN` and, in each internal server that used `{{token}}` in automations, add `autonomousToken: process.env.<YOUR_VARIABLE>` with the token of the service account that it needs. Read [automations](docs/automations.md#internal-mcp-servers-in-an-automation).
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
+
18
+ ## 0.8.0
19
+
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.
8
21
 
9
22
  ### Added
10
23
 
11
- - `fetchUrlTool` in `openloops/tools`, a basic `curl` for the model: GET to an `http` or `https` URL, HTML converted to text with no dependencies. It refuses private and internal addresses, has fixed limits and does not run JavaScript. Opt-in with `agent.addTool(fetchUrlTool)`. Read [tools](docs/tools.md#fetchurltool).
12
- - **Internal MCP servers stored in the database**, managed from a back office. `createInternalMcp`, `updateInternalMcp`, `getInternalMcpById`, `listInternalMcps` and `deleteInternalMcp` in the new entry point `openloops/mcps/admin`, all for admins only. The agent loads the enabled ones in every run next to the ones declared in code, with the same rules: trusted, no manifest review, destructive tools still ask. `{{token}}` in a header uses the token of the run, a token written in the header is sent as it is. Read [MCP servers](docs/mcp-servers.md#internal-servers-stored-in-the-database).
13
- - `internal` and `enabled` in `McpServerProps`. A record without them is a normal server, so no migration is needed.
14
- - A unique index on the name of the internal servers: run `ensureIndexes`.
15
- - `autonomousToken` in the internal MCP servers declared in code (`InternalMcp`), not in the stored ones. It is the token of a service account, used for `{{token}}` only in an autonomous run that brings no token for that server, and then the agent sends the id of the user in `X-User-Id`. An interactive run never uses it. It is temporary, until the integrations give the runner the token of the owner.
16
- - `environment` in `McpServerProps`, an optional text for every MCP server, internal or not, to say which environment it belongs to. It is only a label. The functions of `openloops/mcps` and of `openloops/mcps/admin` accept it, and a blank text removes it.
24
+ - `status` in `listAutomationRunsByAutomation`, as `listAutomationRunsByUser` already had, so a page of runs is filtered before it is paginated.
25
+ - Four codes for the failures of the model, saved in `state.lastError.code` with their own message: `LLM_AUTH_FAILED`, `LLM_CONTEXT_TOO_LONG`, `LLM_CONTENT_FILTERED` and `LLM_INCOMPLETE_RESPONSE`. They used to end in `LLM_FAILED`, so a client that compared `lastError.code` with it to show a generic message must handle the new ones. The first three are not retryable. Read [agent](docs/agent.md#error-handling).
26
+ - `title` in `ChatProps`, a short text that names the chat. In an interactive run the `fast_responder` writes it in the first message of a chat that has none, in the language of the user, and it never replaces a title that exists. Rename a chat with `updateChat({ payload: { title } })` and remove the title with `unset: { title: '' }`. A chat that comes back without a title (the model returned nothing usable) is asked again in its next message. An autonomous run skips the `fast_responder`, so its chat has no title unless you set one. Read [chats](docs/chats.md#the-title).
27
+ - `migrateChatTitles(db, { dryRun })` in `openloops/db`, which gives each chat without a title its first message of the user, on one line and cut to 80 characters. It can be run again without changing anything. In a checkout of this repository: `yarn migrate:chat-titles --dry-run` and `yarn migrate:chat-titles`. **Run it once when you update from an earlier version**: read [the migration to 0.8.0](docs/chats.md#migrating-to-080).
28
+ - `select` in `listChatsByUser`, to get only some fields of each chat, such as `{ title: 1, updatedAt: 1 }` for a history list. Without it the chats come complete, as before. `search` still looks in the messages when they are not returned.
29
+
30
+ ### Changed
31
+
32
+ - A paused run of an automation whose chat was deleted is closed as `failed` with the code `CHAT_DELETED`, when the runner syncs it, and the automation runs again on its next occurrence.
33
+ - `search` in `listChatsByUser` also matches the title of the chat, not only the content of its messages.
34
+ - The `fast_responder` skill is now 2.5.0 and returns an optional `title`, and the AgiLoop is now 1.10.0. The context that the loop sends to the skill has `needs_title: true` while the chat has no title.
35
+ - `sanitizeString`, which cleans every text field of the entities and the email of a user, no longer uses `sanitize-html`, so that package and its dependencies are gone. It still removes tags, scripts, styles and comments and keeps the text, but now `&` stays as it is (before it was saved as `&amp;`) HTML entities are no longer decoded (`&copy;` stays `&copy;`, before it became `©`), and a `<` or `>` that does not belong to a tag is saved as `&lt;` or `&gt;` (before the text that followed a lone `<` was lost). Values already saved do not change.
36
+ - `pino-pretty` moved from `dependencies` to `devDependencies`, so it is no longer installed with the package. The logger loads it only when `IS_LOCAL` is `true` or `NODE_ENV` is `development`, and falls back to plain JSON logs if it is not installed. If you want the colored logs in your own local environment, install it: `yarn add -D pino-pretty`.
17
37
 
18
38
  ### Removed
19
39
 
20
- - `INTERNAL_MCP_TOKEN` and the `serviceToken` parameter of `Agent.run`. Use `autonomousToken` in each internal MCP server.
40
+ - `state.currentActivity`, deprecated since 0.3.0. `AgentStateProps` no longer has it, and `getChatById` no longer adds a generic word (`Thinking...`, `Cooking...`) to it while a run is `processing`. The helper `deprecatedActivity` is gone too. A client that polls the chat and reads that field gets nothing now: move it to [`agent.onActivity`](docs/agent.md#activity-updates), which tells the real activity of the run as it happens, and use `state.status` to know whether the run is in progress. The versions of your app that still poll the chat need to be updated before you update `openloops`. A chat saved before 0.3.0 can still carry the old field in the database, ignore it. `AgentState.setCurrentActivity` and `AgentState.currentActivity` stay as the in-memory value that feeds the listener, they are not saved.
41
+
42
+ ## 0.7.6
43
+
44
+ ### Changed
45
+
46
+ - The description of `fetchUrlTool` tells the model to prefer a source that returns plain text or JSON and needs no key, such as a public API it knows, over a regular web page, and to search when it knows none instead of guessing a URL.
47
+
48
+ ## 0.7.4
49
+
50
+ ### Added
51
+
52
+ - `fetchUrlTool` in `openloops/tools`, a basic `curl` for the model: GET to an `http` or `https` URL, HTML converted to text with no dependencies. It refuses private and internal addresses, has fixed limits and does not run JavaScript. Opt-in with `agent.addTool(fetchUrlTool)`. Read [tools](docs/tools.md#fetchurltool).
21
53
 
22
54
  ### Changed
23
55
 
24
56
  - The `notice` of a tool now goes in every observation of its results, next to `output`, in the turns that follow and in failed calls too, so the model sees it as long as the content is in its context. Before, it only showed when a tool was described by `search_tools`, and a local tool never showed it. The agent saves it in the new `notice` field of `AgentAction` when it runs the tool, an action saved earlier has none. The AgiLoop is now 1.9.0. Read [tools](docs/tools.md#notice).
25
57
  - The notice of the tools of external MCP servers, of `webSearchTool` and of `fetchUrlTool` is shorter, because it repeats in every observation.
26
58
  - `webSearchTool` tells the model that its results are snippets that can be outdated and use many tokens, and to read a source it already knows first when it has a tool to read pages. It also carries a `notice`, because the results come from the internet.
59
+ - `CurrentUser.isFreePlan()` always returned `false`, now it is `true` for a user that is not premium.
60
+ - `login` and `issuePasswordResetToken` find the user whatever the case of the email or the username, and ignore spaces around it.
61
+
62
+ ## 0.7.3
63
+
64
+ ### Changed
65
+
66
+ - `autonomousToken` is only accepted by the internal MCP servers declared in code (`InternalMcp`). The stored ones (`createInternalMcp` and `updateInternalMcp`) no longer take it, so the token never goes in the database.
67
+
68
+ ## 0.7.1
69
+
70
+ ### Added
71
+
72
+ - **Internal MCP servers stored in the database**, managed from a back office. `createInternalMcp`, `updateInternalMcp`, `getInternalMcpById`, `listInternalMcps` and `deleteInternalMcp` in the new entry point `openloops/mcps/admin`, all for admins only. The agent loads the enabled ones in every run next to the ones declared in code, with the same rules: trusted, no manifest review, destructive tools still ask. `{{token}}` in a header uses the token of the run, a token written in the header is sent as it is. Read [MCP servers](docs/mcp-servers.md#internal-servers-stored-in-the-database).
73
+ - `internal` and `enabled` in `McpServerProps`. A record without them is a normal server, so no migration is needed.
74
+ - A unique index on the name of the internal servers: run `ensureIndexes`.
75
+ - `autonomousToken` in the internal MCP servers, declared in code (`InternalMcp`) or stored (`createInternalMcp` and `updateInternalMcp`). It is the token of a service account, used for `{{token}}` only in an autonomous run that brings no token for that server, and then the agent sends the id of the user in `X-User-Id`. An interactive run never uses it. It is temporary, until the integrations give the runner the token of the owner.
76
+ - `environment` in `McpServerProps`, an optional text for every MCP server, internal or not, to say which environment it belongs to. It is only a label. The functions of `openloops/mcps` and of `openloops/mcps/admin` accept it, and a blank text removes it.
77
+
78
+ ### Changed
79
+
27
80
  - The functions of `openloops/mcps` never see an internal server, not even for an admin, and ignore `internal` and `enabled` in the payload of a user.
28
81
  - `listMcpServersByUser` failed because it sent no scope to the repository, now it lists the servers of the user.
29
82
  - The connection errors of an internal server mask the values of its headers in the logs.
30
- - `CurrentUser.isFreePlan()` always returned `false`, now it is `true` for a user that is not premium.
31
- - `login` and `issuePasswordResetToken` find the user whatever the case of the email or the username, and ignore spaces around it.
83
+
84
+ ### Removed
85
+
86
+ - `INTERNAL_MCP_TOKEN` and the `serviceToken` parameter of `Agent.run`. Use `autonomousToken` in each internal MCP server.
32
87
 
33
88
  ## 0.7.0
34
89
 
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
 
@@ -1,4 +1,4 @@
1
- export type LLMErrorCode = 'LLM_RATE_LIMITED' | 'LLM_QUOTA_EXCEEDED' | 'LLM_UNAVAILABLE' | 'LLM_TIMEOUT' | 'LLM_UNSUPPORTED_PARAMETER' | 'LLM_FAILED';
1
+ export type LLMErrorCode = 'LLM_RATE_LIMITED' | 'LLM_QUOTA_EXCEEDED' | 'LLM_UNAVAILABLE' | 'LLM_TIMEOUT' | 'LLM_UNSUPPORTED_PARAMETER' | 'LLM_AUTH_FAILED' | 'LLM_CONTEXT_TOO_LONG' | 'LLM_CONTENT_FILTERED' | 'LLM_INCOMPLETE_RESPONSE' | 'LLM_FAILED';
2
2
  export declare class LLMError extends Error {
3
3
  readonly code: LLMErrorCode;
4
4
  readonly isRetryable: boolean;
@@ -29,6 +29,10 @@ const USER_MESSAGES = {
29
29
  LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
30
30
  LLM_TIMEOUT: "The model did not answer in time. Please try again.",
31
31
  LLM_UNSUPPORTED_PARAMETER: "The model does not accept one of the request settings. Please try again.",
32
+ LLM_AUTH_FAILED: "The credentials of the model provider were rejected. Please check the configuration of the provider.",
33
+ LLM_CONTEXT_TOO_LONG: "The conversation is too long for the model. Please start a new chat or shorten the message.",
34
+ LLM_CONTENT_FILTERED: "The model provider blocked this request or its answer. Please rephrase the message.",
35
+ LLM_INCOMPLETE_RESPONSE: "The model stopped before it finished its answer. Please try again.",
32
36
  LLM_FAILED: "The model request failed. Please try again."
33
37
  };
34
38
  const RETRYABLE = {
@@ -37,6 +41,10 @@ const RETRYABLE = {
37
41
  LLM_UNAVAILABLE: true,
38
42
  LLM_TIMEOUT: true,
39
43
  LLM_UNSUPPORTED_PARAMETER: true,
44
+ LLM_AUTH_FAILED: false,
45
+ LLM_CONTEXT_TOO_LONG: false,
46
+ LLM_CONTENT_FILTERED: false,
47
+ LLM_INCOMPLETE_RESPONSE: true,
40
48
  LLM_FAILED: true
41
49
  };
42
50
  const MAX_WAIT_MS = 6e4;
@@ -63,6 +71,10 @@ function classify(detail) {
63
71
  if (rejectsSamplingParameter(detail)) return "LLM_UNSUPPORTED_PARAMETER";
64
72
  if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
65
73
  if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
74
+ if (/context.?(length|window)|prompt is too long|too many tokens|input.{0,40}exceeds|maximum.{0,20}tokens.{0,40}(input|prompt|context)/i.test(detail)) return "LLM_CONTEXT_TOO_LONG";
75
+ if (/content.?(filter|policy)|safety|responsible.?ai|blocked.{0,30}(policy|safety)/i.test(detail)) return "LLM_CONTENT_FILTERED";
76
+ if (/\b40[13]\b|unauthorized|forbidden|invalid.{0,10}api.?key|authentication|permission.?denied/i.test(detail)) return "LLM_AUTH_FAILED";
77
+ if (/incomplete|truncated|max.?tokens|finish.?reason.{0,10}length|stop.?reason.{0,10}(length|max)/i.test(detail)) return "LLM_INCOMPLETE_RESPONSE";
66
78
  if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
67
79
  return "LLM_FAILED";
68
80
  }
@@ -4,6 +4,10 @@ const USER_MESSAGES = {
4
4
  LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
5
5
  LLM_TIMEOUT: "The model did not answer in time. Please try again.",
6
6
  LLM_UNSUPPORTED_PARAMETER: "The model does not accept one of the request settings. Please try again.",
7
+ LLM_AUTH_FAILED: "The credentials of the model provider were rejected. Please check the configuration of the provider.",
8
+ LLM_CONTEXT_TOO_LONG: "The conversation is too long for the model. Please start a new chat or shorten the message.",
9
+ LLM_CONTENT_FILTERED: "The model provider blocked this request or its answer. Please rephrase the message.",
10
+ LLM_INCOMPLETE_RESPONSE: "The model stopped before it finished its answer. Please try again.",
7
11
  LLM_FAILED: "The model request failed. Please try again."
8
12
  };
9
13
  const RETRYABLE = {
@@ -12,6 +16,10 @@ const RETRYABLE = {
12
16
  LLM_UNAVAILABLE: true,
13
17
  LLM_TIMEOUT: true,
14
18
  LLM_UNSUPPORTED_PARAMETER: true,
19
+ LLM_AUTH_FAILED: false,
20
+ LLM_CONTEXT_TOO_LONG: false,
21
+ LLM_CONTENT_FILTERED: false,
22
+ LLM_INCOMPLETE_RESPONSE: true,
15
23
  LLM_FAILED: true
16
24
  };
17
25
  const MAX_WAIT_MS = 6e4;
@@ -38,6 +46,10 @@ function classify(detail) {
38
46
  if (rejectsSamplingParameter(detail)) return "LLM_UNSUPPORTED_PARAMETER";
39
47
  if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
40
48
  if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
49
+ if (/context.?(length|window)|prompt is too long|too many tokens|input.{0,40}exceeds|maximum.{0,20}tokens.{0,40}(input|prompt|context)/i.test(detail)) return "LLM_CONTEXT_TOO_LONG";
50
+ if (/content.?(filter|policy)|safety|responsible.?ai|blocked.{0,30}(policy|safety)/i.test(detail)) return "LLM_CONTENT_FILTERED";
51
+ if (/\b40[13]\b|unauthorized|forbidden|invalid.{0,10}api.?key|authentication|permission.?denied/i.test(detail)) return "LLM_AUTH_FAILED";
52
+ if (/incomplete|truncated|max.?tokens|finish.?reason.{0,10}length|stop.?reason.{0,10}(length|max)/i.test(detail)) return "LLM_INCOMPLETE_RESPONSE";
41
53
  if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
42
54
  return "LLM_FAILED";
43
55
  }
@@ -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,3 +1,4 @@
1
1
  export * from './escape-regex';
2
2
  export * from './extract-json-from-text';
3
3
  export * from './sanitize-string';
4
+ export * from './strip-blocks';
@@ -18,9 +18,11 @@ module.exports = __toCommonJS(helpers_exports);
18
18
  __reExport(helpers_exports, require("./escape-regex"), module.exports);
19
19
  __reExport(helpers_exports, require("./extract-json-from-text"), module.exports);
20
20
  __reExport(helpers_exports, require("./sanitize-string"), module.exports);
21
+ __reExport(helpers_exports, require("./strip-blocks"), module.exports);
21
22
  // Annotate the CommonJS export names for ESM import in node:
22
23
  0 && (module.exports = {
23
24
  ...require("./escape-regex"),
24
25
  ...require("./extract-json-from-text"),
25
- ...require("./sanitize-string")
26
+ ...require("./sanitize-string"),
27
+ ...require("./strip-blocks")
26
28
  });
@@ -1,3 +1,4 @@
1
1
  export * from "./escape-regex";
2
2
  export * from "./extract-json-from-text";
3
3
  export * from "./sanitize-string";
4
+ export * from "./strip-blocks";
@@ -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,27 +15,19 @@ 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 sanitize_string_exports = {};
30
20
  __export(sanitize_string_exports, {
31
21
  sanitizeString: () => sanitizeString
32
22
  });
33
23
  module.exports = __toCommonJS(sanitize_string_exports);
34
- var import_sanitize_html = __toESM(require("sanitize-html"));
24
+ var import_strip_blocks = require("./strip-blocks");
35
25
  function sanitizeString(input = "") {
36
26
  if (!input) return void 0;
37
- return (0, import_sanitize_html.default)(input, {
38
- allowedTags: [],
39
- allowedAttributes: {}
40
- });
27
+ let text = (0, import_strip_blocks.stripBlocks)(input, "<!--", "-->", "-->", false);
28
+ text = (0, import_strip_blocks.stripBlocks)(text, "<script", "</script", ">", true);
29
+ text = (0, import_strip_blocks.stripBlocks)(text, "<style", "</style", ">", true);
30
+ return text.replace(/<[/!?]?[a-zA-Z][^<>]*>/g, "").replace(/</g, "&lt;").replace(/>/g, "&gt;");
41
31
  }
42
32
  // Annotate the CommonJS export names for ESM import in node:
43
33
  0 && (module.exports = {
@@ -1,10 +1,10 @@
1
- import sanitizeHtml from "sanitize-html";
1
+ import { stripBlocks } from "./strip-blocks";
2
2
  function sanitizeString(input = "") {
3
3
  if (!input) return void 0;
4
- return sanitizeHtml(input, {
5
- allowedTags: [],
6
- allowedAttributes: {}
7
- });
4
+ let text = stripBlocks(input, "<!--", "-->", "-->", false);
5
+ text = stripBlocks(text, "<script", "</script", ">", true);
6
+ text = stripBlocks(text, "<style", "</style", ">", true);
7
+ return text.replace(/<[/!?]?[a-zA-Z][^<>]*>/g, "").replace(/</g, "&lt;").replace(/>/g, "&gt;");
8
8
  }
9
9
  export {
10
10
  sanitizeString
@@ -0,0 +1 @@
1
+ export declare function stripBlocks(html: string, open: string, close: string, end: string, isElement: boolean): string;