openloops 0.7.6 → 0.8.0

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 (58) hide show
  1. package/CHANGELOG.md +53 -11
  2. package/dist/clients/llm/llm-error.d.ts +1 -1
  3. package/dist/clients/llm/llm-error.js +12 -0
  4. package/dist/clients/llm/llm-error.mjs +12 -0
  5. package/dist/common/helpers/index.d.ts +1 -0
  6. package/dist/common/helpers/index.js +3 -1
  7. package/dist/common/helpers/index.mjs +1 -0
  8. package/dist/common/helpers/sanitize-string.js +5 -15
  9. package/dist/common/helpers/sanitize-string.mjs +5 -5
  10. package/dist/common/helpers/strip-blocks.d.ts +1 -0
  11. package/dist/common/helpers/strip-blocks.js +45 -0
  12. package/dist/common/helpers/strip-blocks.mjs +21 -0
  13. package/dist/common/logger/pino.js +12 -3
  14. package/dist/common/logger/pino.mjs +12 -3
  15. package/dist/db/index.d.ts +1 -0
  16. package/dist/db/index.js +3 -1
  17. package/dist/db/index.mjs +1 -0
  18. package/dist/db/migrations/chat-titles.d.ts +10 -0
  19. package/dist/db/migrations/chat-titles.js +55 -0
  20. package/dist/db/migrations/chat-titles.mjs +31 -0
  21. package/dist/harness/agent-state.d.ts +0 -1
  22. package/dist/loops/agi/loop.js +4 -2
  23. package/dist/loops/agi/loop.mjs +4 -2
  24. package/dist/loops/shared/skills/fast-responder.d.ts +1 -0
  25. package/dist/loops/shared/skills/fast-responder.js +4 -2
  26. package/dist/loops/shared/skills/fast-responder.mjs +4 -2
  27. package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.d.ts +2 -1
  28. package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.js +2 -2
  29. package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.mjs +2 -2
  30. package/dist/services/automations/use-cases/sync-automation-run.use-case.d.ts +1 -0
  31. package/dist/services/automations/use-cases/sync-automation-run.use-case.js +6 -2
  32. package/dist/services/automations/use-cases/sync-automation-run.use-case.mjs +5 -2
  33. package/dist/services/chats/entities/chat.entity.d.ts +3 -0
  34. package/dist/services/chats/entities/chat.entity.js +8 -0
  35. package/dist/services/chats/entities/chat.entity.mjs +8 -0
  36. package/dist/services/chats/use-cases/get-chat-by-id.use-case.js +1 -5
  37. package/dist/services/chats/use-cases/get-chat-by-id.use-case.mjs +1 -5
  38. package/dist/services/chats/use-cases/list-chats-by-user.use-case.d.ts +2 -1
  39. package/dist/services/chats/use-cases/list-chats-by-user.use-case.js +3 -2
  40. package/dist/services/chats/use-cases/list-chats-by-user.use-case.mjs +3 -2
  41. package/dist/services/chats/utils/title.d.ts +2 -0
  42. package/dist/services/chats/utils/title.js +35 -0
  43. package/dist/services/chats/utils/title.mjs +10 -0
  44. package/dist/tools/core/fetch-url/html-to-text.js +3 -20
  45. package/dist/tools/core/fetch-url/html-to-text.mjs +3 -20
  46. package/docs/README.md +1 -1
  47. package/docs/agent.md +18 -3
  48. package/docs/automations.md +3 -3
  49. package/docs/chats.md +41 -8
  50. package/docs/configuration.md +1 -1
  51. package/docs/integration-guide.md +2 -2
  52. package/docs/llms.txt +1 -1
  53. package/docs/loops.md +1 -1
  54. package/examples/chats/search-chats.ts +30 -0
  55. package/package.json +7 -8
  56. package/dist/services/chats/utils/deprecated-activity.d.ts +0 -1
  57. package/dist/services/chats/utils/deprecated-activity.js +0 -60
  58. package/dist/services/chats/utils/deprecated-activity.mjs +0 -36
package/CHANGELOG.md CHANGED
@@ -2,33 +2,75 @@
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.0
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
+ 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
8
 
9
9
  ### Added
10
10
 
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.
11
+ - `status` in `listAutomationRunsByAutomation`, as `listAutomationRunsByUser` already had, so a page of runs is filtered before it is paginated.
12
+ - 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).
13
+ - `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).
14
+ - `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).
15
+ - `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.
16
+
17
+ ### Changed
18
+
19
+ - 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.
20
+ - `search` in `listChatsByUser` also matches the title of the chat, not only the content of its messages.
21
+ - 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.
22
+ - `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.
23
+ - `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
24
 
18
25
  ### Removed
19
26
 
20
- - `INTERNAL_MCP_TOKEN` and the `serviceToken` parameter of `Agent.run`. Use `autonomousToken` in each internal MCP server.
27
+ - `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.
28
+
29
+ ## 0.7.6
30
+
31
+ ### Changed
32
+
33
+ - 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.
34
+
35
+ ## 0.7.4
36
+
37
+ ### Added
38
+
39
+ - `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
40
 
22
41
  ### Changed
23
42
 
24
43
  - 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
44
  - The notice of the tools of external MCP servers, of `webSearchTool` and of `fetchUrlTool` is shorter, because it repeats in every observation.
26
45
  - `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.
46
+ - `CurrentUser.isFreePlan()` always returned `false`, now it is `true` for a user that is not premium.
47
+ - `login` and `issuePasswordResetToken` find the user whatever the case of the email or the username, and ignore spaces around it.
48
+
49
+ ## 0.7.3
50
+
51
+ ### Changed
52
+
53
+ - `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.
54
+
55
+ ## 0.7.1
56
+
57
+ ### Added
58
+
59
+ - **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).
60
+ - `internal` and `enabled` in `McpServerProps`. A record without them is a normal server, so no migration is needed.
61
+ - A unique index on the name of the internal servers: run `ensureIndexes`.
62
+ - `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.
63
+ - `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.
64
+
65
+ ### Changed
66
+
27
67
  - 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
68
  - `listMcpServersByUser` failed because it sent no scope to the repository, now it lists the servers of the user.
29
69
  - 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.
70
+
71
+ ### Removed
72
+
73
+ - `INTERNAL_MCP_TOKEN` and the `serviceToken` parameter of `Agent.run`. Use `autonomousToken` in each internal MCP server.
32
74
 
33
75
  ## 0.7.0
34
76
 
@@ -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
  }
@@ -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;
@@ -0,0 +1,45 @@
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 strip_blocks_exports = {};
20
+ __export(strip_blocks_exports, {
21
+ stripBlocks: () => stripBlocks
22
+ });
23
+ module.exports = __toCommonJS(strip_blocks_exports);
24
+ function asciiLower(text) {
25
+ return text.replace(/[A-Z]/g, (char) => String.fromCharCode(char.charCodeAt(0) + 32));
26
+ }
27
+ function stripBlocks(html, open, close, end, isElement) {
28
+ const lower = asciiLower(html);
29
+ let result = "";
30
+ let cursor = 0;
31
+ while (cursor < html.length) {
32
+ let start = lower.indexOf(open, cursor);
33
+ while (isElement && start !== -1 && /[a-z0-9]/.test(lower.charAt(start + open.length))) start = lower.indexOf(open, start + 1);
34
+ if (start === -1) break;
35
+ result += html.slice(cursor, start);
36
+ const closing = lower.indexOf(close, start + open.length);
37
+ const stop = closing === -1 ? -1 : lower.indexOf(end, closing);
38
+ cursor = stop === -1 ? html.length : stop + end.length;
39
+ }
40
+ return result + html.slice(cursor);
41
+ }
42
+ // Annotate the CommonJS export names for ESM import in node:
43
+ 0 && (module.exports = {
44
+ stripBlocks
45
+ });
@@ -0,0 +1,21 @@
1
+ function asciiLower(text) {
2
+ return text.replace(/[A-Z]/g, (char) => String.fromCharCode(char.charCodeAt(0) + 32));
3
+ }
4
+ function stripBlocks(html, open, close, end, isElement) {
5
+ const lower = asciiLower(html);
6
+ let result = "";
7
+ let cursor = 0;
8
+ while (cursor < html.length) {
9
+ let start = lower.indexOf(open, cursor);
10
+ while (isElement && start !== -1 && /[a-z0-9]/.test(lower.charAt(start + open.length))) start = lower.indexOf(open, start + 1);
11
+ if (start === -1) break;
12
+ result += html.slice(cursor, start);
13
+ const closing = lower.indexOf(close, start + open.length);
14
+ const stop = closing === -1 ? -1 : lower.indexOf(end, closing);
15
+ cursor = stop === -1 ? html.length : stop + end.length;
16
+ }
17
+ return result + html.slice(cursor);
18
+ }
19
+ export {
20
+ stripBlocks
21
+ };
@@ -34,11 +34,20 @@ __export(pino_exports, {
34
34
  module.exports = __toCommonJS(pino_exports);
35
35
  var import_config = require("dotenv/config");
36
36
  var import_pino = __toESM(require("pino"));
37
- var import_pino_pretty = __toESM(require("pino-pretty"));
38
- const stream = (0, import_pino_pretty.default)({ colorize: true });
37
+ let prettyStream;
38
+ function localStream() {
39
+ if (prettyStream === void 0) {
40
+ try {
41
+ prettyStream = require("pino-pretty")({ colorize: true });
42
+ } catch {
43
+ prettyStream = null;
44
+ }
45
+ }
46
+ return prettyStream ?? void 0;
47
+ }
39
48
  class Logger {
40
49
  IS_LOCAL = process.env.IS_LOCAL === "true" || process.env.NODE_ENV === "development";
41
- logger = this.IS_LOCAL ? (0, import_pino.default)({ level: "debug" }, stream) : (0, import_pino.default)({ level: "info" });
50
+ logger = this.IS_LOCAL ? (0, import_pino.default)({ level: "debug" }, localStream()) : (0, import_pino.default)({ level: "info" });
42
51
  log(level, obj, msg) {
43
52
  if (typeof obj === "string") {
44
53
  msg = obj;
@@ -1,10 +1,19 @@
1
1
  import "dotenv/config";
2
2
  import pino from "pino";
3
- import pretty from "pino-pretty";
4
- const stream = pretty({ colorize: true });
3
+ let prettyStream;
4
+ function localStream() {
5
+ if (prettyStream === void 0) {
6
+ try {
7
+ prettyStream = require("pino-pretty")({ colorize: true });
8
+ } catch {
9
+ prettyStream = null;
10
+ }
11
+ }
12
+ return prettyStream ?? void 0;
13
+ }
5
14
  class Logger {
6
15
  IS_LOCAL = process.env.IS_LOCAL === "true" || process.env.NODE_ENV === "development";
7
- logger = this.IS_LOCAL ? pino({ level: "debug" }, stream) : pino({ level: "info" });
16
+ logger = this.IS_LOCAL ? pino({ level: "debug" }, localStream()) : pino({ level: "info" });
8
17
  log(level, obj, msg) {
9
18
  if (typeof obj === "string") {
10
19
  msg = obj;
@@ -1,2 +1,3 @@
1
1
  export * from './indexes';
2
2
  export * from './migrations/automations';
3
+ export * from './migrations/chat-titles';
package/dist/db/index.js CHANGED
@@ -17,8 +17,10 @@ var db_exports = {};
17
17
  module.exports = __toCommonJS(db_exports);
18
18
  __reExport(db_exports, require("./indexes"), module.exports);
19
19
  __reExport(db_exports, require("./migrations/automations"), module.exports);
20
+ __reExport(db_exports, require("./migrations/chat-titles"), module.exports);
20
21
  // Annotate the CommonJS export names for ESM import in node:
21
22
  0 && (module.exports = {
22
23
  ...require("./indexes"),
23
- ...require("./migrations/automations")
24
+ ...require("./migrations/automations"),
25
+ ...require("./migrations/chat-titles")
24
26
  });
package/dist/db/index.mjs CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from "./indexes";
2
2
  export * from "./migrations/automations";
3
+ export * from "./migrations/chat-titles";
@@ -0,0 +1,10 @@
1
+ import { Db } from 'mongodb';
2
+ export interface ChatTitlesMigrationOptions {
3
+ dryRun?: boolean;
4
+ }
5
+ export interface ChatTitlesMigrationReport {
6
+ dryRun: boolean;
7
+ titled: number;
8
+ skipped: number;
9
+ }
10
+ export declare function migrateChatTitles(db: Db, options?: ChatTitlesMigrationOptions): Promise<ChatTitlesMigrationReport>;
@@ -0,0 +1,55 @@
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 chat_titles_exports = {};
20
+ __export(chat_titles_exports, {
21
+ migrateChatTitles: () => migrateChatTitles
22
+ });
23
+ module.exports = __toCommonJS(chat_titles_exports);
24
+ var import_title = require("../../services/chats/utils/title");
25
+ const BATCH_SIZE = 500;
26
+ const withoutTitle = { $or: [{ title: { $exists: false } }, { title: null }, { title: "" }] };
27
+ const firstUserMessage = { role: "user", source: { $ne: "harness" }, excludeFromContext: { $ne: true } };
28
+ async function migrateChatTitles(db, options = {}) {
29
+ const dryRun = Boolean(options.dryRun);
30
+ const report = { dryRun, titled: 0, skipped: 0 };
31
+ const chats = db.collection("chats");
32
+ let operations = [];
33
+ const flush = async () => {
34
+ if (!operations.length) return;
35
+ if (!dryRun) await chats.bulkWrite(operations, { ordered: false });
36
+ operations = [];
37
+ };
38
+ const cursor = chats.find({ ...withoutTitle, deletedAt: null }, { projection: { messages: { $elemMatch: firstUserMessage } } });
39
+ for await (const chat of cursor) {
40
+ const title = (0, import_title.normalizeTitle)(chat.messages?.[0]?.content);
41
+ if (!title) {
42
+ report.skipped++;
43
+ continue;
44
+ }
45
+ report.titled++;
46
+ operations.push({ updateOne: { filter: { _id: chat._id, ...withoutTitle }, update: { $set: { title } } } });
47
+ if (operations.length >= BATCH_SIZE) await flush();
48
+ }
49
+ await flush();
50
+ return report;
51
+ }
52
+ // Annotate the CommonJS export names for ESM import in node:
53
+ 0 && (module.exports = {
54
+ migrateChatTitles
55
+ });
@@ -0,0 +1,31 @@
1
+ import { normalizeTitle } from "../../services/chats/utils/title";
2
+ const BATCH_SIZE = 500;
3
+ const withoutTitle = { $or: [{ title: { $exists: false } }, { title: null }, { title: "" }] };
4
+ const firstUserMessage = { role: "user", source: { $ne: "harness" }, excludeFromContext: { $ne: true } };
5
+ async function migrateChatTitles(db, options = {}) {
6
+ const dryRun = Boolean(options.dryRun);
7
+ const report = { dryRun, titled: 0, skipped: 0 };
8
+ const chats = db.collection("chats");
9
+ let operations = [];
10
+ const flush = async () => {
11
+ if (!operations.length) return;
12
+ if (!dryRun) await chats.bulkWrite(operations, { ordered: false });
13
+ operations = [];
14
+ };
15
+ const cursor = chats.find({ ...withoutTitle, deletedAt: null }, { projection: { messages: { $elemMatch: firstUserMessage } } });
16
+ for await (const chat of cursor) {
17
+ const title = normalizeTitle(chat.messages?.[0]?.content);
18
+ if (!title) {
19
+ report.skipped++;
20
+ continue;
21
+ }
22
+ report.titled++;
23
+ operations.push({ updateOne: { filter: { _id: chat._id, ...withoutTitle }, update: { $set: { title } } } });
24
+ if (operations.length >= BATCH_SIZE) await flush();
25
+ }
26
+ await flush();
27
+ return report;
28
+ }
29
+ export {
30
+ migrateChatTitles
31
+ };
@@ -19,7 +19,6 @@ export interface AgentStateProps {
19
19
  lastError?: AgentError;
20
20
  activeTaskId?: string;
21
21
  stopRequested?: boolean;
22
- currentActivity?: CurrentActivity;
23
22
  }
24
23
  export declare class AgentState {
25
24
  status?: AgentStatus | undefined;
@@ -50,7 +50,7 @@ class AgiLoop extends import_harness.AgentLoop {
50
50
  return "agi";
51
51
  }
52
52
  get version() {
53
- return "1.9.0";
53
+ return "1.10.0";
54
54
  }
55
55
  get author() {
56
56
  return {
@@ -78,10 +78,12 @@ class AgiLoop extends import_harness.AgentLoop {
78
78
  ...ctx.skillParams,
79
79
  contextInjection: {
80
80
  ...agentIdentity && Object.keys(agentIdentity)?.length ? { agentIdentity } : {},
81
- ...chat_history?.length ? { chat_history } : {}
81
+ ...chat_history?.length ? { chat_history } : {},
82
+ ...ctx.chat.title ? {} : { needs_title: true }
82
83
  }
83
84
  });
84
85
  ctx.chat.state?.setLanguage(result.detected_language);
86
+ ctx.chat.setTitle(result.title);
85
87
  if (!result.can_answer) {
86
88
  const activity = (0, import_activity.cleanActivity)(result.activity);
87
89
  if (activity) ctx.chat.state?.setCurrentActivity(activity);
@@ -27,7 +27,7 @@ class AgiLoop extends AgentLoop {
27
27
  return "agi";
28
28
  }
29
29
  get version() {
30
- return "1.9.0";
30
+ return "1.10.0";
31
31
  }
32
32
  get author() {
33
33
  return {
@@ -55,10 +55,12 @@ class AgiLoop extends AgentLoop {
55
55
  ...ctx.skillParams,
56
56
  contextInjection: {
57
57
  ...agentIdentity && Object.keys(agentIdentity)?.length ? { agentIdentity } : {},
58
- ...chat_history?.length ? { chat_history } : {}
58
+ ...chat_history?.length ? { chat_history } : {},
59
+ ...ctx.chat.title ? {} : { needs_title: true }
59
60
  }
60
61
  });
61
62
  ctx.chat.state?.setLanguage(result.detected_language);
63
+ ctx.chat.setTitle(result.title);
62
64
  if (!result.can_answer) {
63
65
  const activity = cleanActivity(result.activity);
64
66
  if (activity) ctx.chat.state?.setCurrentActivity(activity);
@@ -5,6 +5,7 @@ type ResponseSchema = {
5
5
  reasoning: string;
6
6
  detected_language: string;
7
7
  activity?: string;
8
+ title?: string;
8
9
  };
9
10
  export declare const fastResponder: Skill<ResponseSchema>;
10
11
  export {};
@@ -25,7 +25,7 @@ var import_skill = require("../../../skills/skill.js");
25
25
  var import_shared_rules = require("../../../skills/shared/shared-rules.js");
26
26
  const fastResponder = new import_skill.Skill({
27
27
  name: "fast_responder",
28
- version: "2.4.3",
28
+ version: "2.5.0",
29
29
  description: "Handles general conversations and multipurpose user assistance.",
30
30
  temperature: 0.7,
31
31
  thinking: "low",
@@ -43,6 +43,7 @@ const fastResponder = new import_skill.Skill({
43
43
  "MEMORY_AND_PERSONAL_DATA_CHECK: Do NOT assume, pretend, or hallucinate remembering past events, meetings, notes, or specific user context. If the user asks about something mentioned in the past (e.g., 'recuerdas la reuni\xF3n...?', 'qu\xE9 te dije de...?'), set 'can_answer' to false UNLESS the exact details are explicitly provided inside 'context_injection'. Never fake memory.",
44
44
  "CAPABILITY_CHECK: Set 'can_answer' to false if: 1) The query involves creating, registering, updating, or deleting data or non-text resources (e.g., expenses, records, reminders, calendar entries), 2) The query refers to personal memory, past events, meetings, or stored notes not present in 'context_injection', 3) The query requires specialized skills or tools (e.g., searching databases, calendar lookup, external integrations), 4) The query requires live internet access (news, weather, live data), 5) The query is a correction, rejection, or negative feedback regarding a previously executed task or tool response (e.g., 'no era esa fecha', 'te equivocaste', 'busca otra opci\xF3n', 'eso no sirvi\xF3'). When 'can_answer' is false, leave 'answer' minimal or empty for the fallback engine.",
45
45
  "ACTIVITY: When 'can_answer' is false, always write in 'activity' one short sentence of at most 60 characters: a verb in the present or progressive form followed by what you will look up or do, taken from the user's request. It must be in 'detected_language' and match the language of the message of the user, never the language of these instructions. Never mention tool names or technical terms, never include personal data, and do not promise a result. Leave it empty when 'can_answer' is true.",
46
+ "TITLE: Only when 'context_injection.needs_title' is true, write in 'title' a short title for this conversation, of at most 50 characters, taken from the topic of INPUT.user_message, in 'detected_language', as a noun phrase with no quotes, no final period and no personal data. Write it whether 'can_answer' is true or false. Leave it empty when 'context_injection.needs_title' is not present.",
46
47
  "REASONING: Always generate the 'reasoning' field with a short explanation in English of the decision-making process, regardless of whether 'can_answer' is true or false.",
47
48
  import_shared_rules.FORMATTING,
48
49
  import_shared_rules.LATEX_FORMATTING,
@@ -57,7 +58,8 @@ const fastResponder = new import_skill.Skill({
57
58
  answer: "string",
58
59
  reasoning: "string",
59
60
  detected_language: "string",
60
- activity: "string"
61
+ activity: "string",
62
+ title: "string"
61
63
  }
62
64
  }
63
65
  }
@@ -2,7 +2,7 @@ import { Skill } from "../../../skills/skill.js";
2
2
  import { FORMATTING, LATEX_FORMATTING, CITATION_FORMATTING, POLICY_RESTRICTIONS } from "../../../skills/shared/shared-rules.js";
3
3
  const fastResponder = new Skill({
4
4
  name: "fast_responder",
5
- version: "2.4.3",
5
+ version: "2.5.0",
6
6
  description: "Handles general conversations and multipurpose user assistance.",
7
7
  temperature: 0.7,
8
8
  thinking: "low",
@@ -20,6 +20,7 @@ const fastResponder = new Skill({
20
20
  "MEMORY_AND_PERSONAL_DATA_CHECK: Do NOT assume, pretend, or hallucinate remembering past events, meetings, notes, or specific user context. If the user asks about something mentioned in the past (e.g., 'recuerdas la reuni\xF3n...?', 'qu\xE9 te dije de...?'), set 'can_answer' to false UNLESS the exact details are explicitly provided inside 'context_injection'. Never fake memory.",
21
21
  "CAPABILITY_CHECK: Set 'can_answer' to false if: 1) The query involves creating, registering, updating, or deleting data or non-text resources (e.g., expenses, records, reminders, calendar entries), 2) The query refers to personal memory, past events, meetings, or stored notes not present in 'context_injection', 3) The query requires specialized skills or tools (e.g., searching databases, calendar lookup, external integrations), 4) The query requires live internet access (news, weather, live data), 5) The query is a correction, rejection, or negative feedback regarding a previously executed task or tool response (e.g., 'no era esa fecha', 'te equivocaste', 'busca otra opci\xF3n', 'eso no sirvi\xF3'). When 'can_answer' is false, leave 'answer' minimal or empty for the fallback engine.",
22
22
  "ACTIVITY: When 'can_answer' is false, always write in 'activity' one short sentence of at most 60 characters: a verb in the present or progressive form followed by what you will look up or do, taken from the user's request. It must be in 'detected_language' and match the language of the message of the user, never the language of these instructions. Never mention tool names or technical terms, never include personal data, and do not promise a result. Leave it empty when 'can_answer' is true.",
23
+ "TITLE: Only when 'context_injection.needs_title' is true, write in 'title' a short title for this conversation, of at most 50 characters, taken from the topic of INPUT.user_message, in 'detected_language', as a noun phrase with no quotes, no final period and no personal data. Write it whether 'can_answer' is true or false. Leave it empty when 'context_injection.needs_title' is not present.",
23
24
  "REASONING: Always generate the 'reasoning' field with a short explanation in English of the decision-making process, regardless of whether 'can_answer' is true or false.",
24
25
  FORMATTING,
25
26
  LATEX_FORMATTING,
@@ -34,7 +35,8 @@ const fastResponder = new Skill({
34
35
  answer: "string",
35
36
  reasoning: "string",
36
37
  detected_language: "string",
37
- activity: "string"
38
+ activity: "string",
39
+ title: "string"
38
40
  }
39
41
  }
40
42
  }