openloops 0.9.0 → 0.10.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 +19 -0
  2. package/README.md +2 -0
  3. package/dist/clients/llm/llm-client.d.ts +1 -0
  4. package/dist/clients/llm/llm-client.js +6 -3
  5. package/dist/clients/llm/llm-client.mjs +6 -3
  6. package/dist/common/base/current-user.js +2 -1
  7. package/dist/common/base/current-user.mjs +2 -1
  8. package/dist/common/index.d.ts +3 -0
  9. package/dist/common/index.js +6 -0
  10. package/dist/common/index.mjs +4 -0
  11. package/dist/common/repositories/mongo-db.client.d.ts +1 -1
  12. package/dist/common/repositories/mongo-db.client.js +7 -6
  13. package/dist/common/repositories/mongo-db.client.mjs +7 -6
  14. package/dist/common/repositories/mongo-db.repository.d.ts +3 -2
  15. package/dist/common/repositories/mongo-db.repository.js +20 -16
  16. package/dist/common/repositories/mongo-db.repository.mjs +20 -16
  17. package/dist/common/utils/config-context.d.ts +3 -0
  18. package/dist/common/utils/config-context.js +33 -0
  19. package/dist/common/utils/config-context.mjs +8 -0
  20. package/dist/common/utils/secret-manager.d.ts +7 -5
  21. package/dist/common/utils/secret-manager.js +41 -28
  22. package/dist/common/utils/secret-manager.mjs +41 -28
  23. package/dist/harness/agent-state.d.ts +1 -1
  24. package/dist/harness/agent.d.ts +1 -0
  25. package/dist/harness/agent.js +17 -1
  26. package/dist/harness/agent.mjs +17 -1
  27. package/dist/services/authentication/repositories/refresh-token.repository.js +1 -1
  28. package/dist/services/authentication/repositories/refresh-token.repository.mjs +1 -1
  29. package/dist/services/authentication/repositories/revoked-token.repository.js +1 -1
  30. package/dist/services/authentication/repositories/revoked-token.repository.mjs +1 -1
  31. package/dist/services/automations/repositories/automation-run.repository.js +1 -1
  32. package/dist/services/automations/repositories/automation-run.repository.mjs +1 -1
  33. package/dist/services/automations/repositories/automation.repository.js +1 -1
  34. package/dist/services/automations/repositories/automation.repository.mjs +1 -1
  35. package/dist/services/chats/repositories/chat.repository.js +1 -1
  36. package/dist/services/chats/repositories/chat.repository.mjs +1 -1
  37. package/dist/services/llmcalls/repositories/llmcall.repository.js +1 -1
  38. package/dist/services/llmcalls/repositories/llmcall.repository.mjs +1 -1
  39. package/dist/services/mcp-servers/repositories/mcpserver.repository.js +1 -1
  40. package/dist/services/mcp-servers/repositories/mcpserver.repository.mjs +1 -1
  41. package/dist/services/tasks/repositories/agent-action.repository.js +1 -1
  42. package/dist/services/tasks/repositories/agent-action.repository.mjs +1 -1
  43. package/dist/services/tasks/repositories/agent-task.repository.js +1 -1
  44. package/dist/services/tasks/repositories/agent-task.repository.mjs +1 -1
  45. package/dist/services/traces/repositories/agent-trace.repository.js +1 -1
  46. package/dist/services/traces/repositories/agent-trace.repository.mjs +1 -1
  47. package/dist/services/users/repositories/user.repository.js +1 -1
  48. package/dist/services/users/repositories/user.repository.mjs +1 -1
  49. package/dist/services/workspaces/repositories/workspace-item.repository.js +1 -1
  50. package/dist/services/workspaces/repositories/workspace-item.repository.mjs +1 -1
  51. package/docs/README.md +1 -1
  52. package/docs/agent.md +3 -2
  53. package/docs/configuration.md +30 -1
  54. package/docs/integration-guide.md +1 -1
  55. package/docs/llms.txt +1 -1
  56. package/examples/run-agent/run-agent-multi-tenant.ts +52 -0
  57. package/examples/run-agent/run-agent-with-usage-limit.ts +5 -4
  58. package/package.json +1 -1
@@ -35,43 +35,65 @@ module.exports = __toCommonJS(secret_manager_exports);
35
35
  var import_config = require("dotenv/config");
36
36
  var import_cryptr = __toESM(require("cryptr"));
37
37
  var import_logger = require("../logger/index.js");
38
+ var import_config_context = require("./config-context");
39
+ const VERSIONED = /^ENC:v(\d+):/;
38
40
  class SecretManager {
39
41
  static instance;
40
- cache = /* @__PURE__ */ new Map();
41
- cryptr;
42
+ envCache = /* @__PURE__ */ new Map();
43
+ contextCache = /* @__PURE__ */ new WeakMap();
44
+ cryptrs = /* @__PURE__ */ new Map();
42
45
  static getInstance() {
43
46
  if (!SecretManager.instance) {
44
47
  SecretManager.instance = new SecretManager();
45
48
  }
46
49
  return SecretManager.instance;
47
50
  }
48
- static encrypt(value) {
51
+ static encrypt(value, version) {
49
52
  if (!value) throw new Error("[Secret manager] Value to encrypt cannot be empty");
50
- return `ENC:${SecretManager.getInstance().cryptr.encrypt(value)}`;
53
+ const manager = SecretManager.getInstance();
54
+ if (!version) return `ENC:${manager.cryptr().encrypt(value)}`;
55
+ return `ENC:v${version}:${manager.cryptr(version).encrypt(value)}`;
51
56
  }
52
57
  constructor() {
53
- const secretKey = process.env.SECRET_MANAGER_KEY;
58
+ this.cryptr();
59
+ }
60
+ cryptr(version) {
61
+ const envName = version ? `SECRET_MANAGER_KEY_V${version}` : "SECRET_MANAGER_KEY";
62
+ const cached = this.cryptrs.get(envName);
63
+ if (cached) return cached;
64
+ const secretKey = process.env[envName];
54
65
  if (!secretKey) {
55
- throw new Error("[Secret manager] SECRET_MANAGER_KEY environment variable is not set");
66
+ throw new Error(`[Secret manager] ${envName} environment variable is not set`);
56
67
  }
57
- this.cryptr = new import_cryptr.default(secretKey, {
68
+ const cryptr = new import_cryptr.default(secretKey, {
58
69
  pbkdf2Iterations: 1e3,
59
70
  saltLength: 16
60
71
  });
72
+ this.cryptrs.set(envName, cryptr);
73
+ return cryptr;
61
74
  }
62
75
  get(key) {
63
76
  const startTime = process.hrtime.bigint();
64
- if (this.cache.has(key)) {
65
- const decryptedValue2 = this.cache.get(key);
77
+ const configs = (0, import_config_context.getContextConfigs)();
78
+ const cache = configs ? this.cacheOf(configs) : this.envCache;
79
+ if (cache.has(key)) {
66
80
  this.logElapsed(key, startTime, true);
67
- return decryptedValue2;
81
+ return cache.get(key);
68
82
  }
69
- const encryptedValue = this.getEnvVar(key);
70
- const decryptedValue = this.decryptEnvVar(encryptedValue);
71
- this.cache.set(key, decryptedValue);
83
+ const raw = configs ? configs[key] : this.getEnvVar(key);
84
+ const decryptedValue = this.decrypt(raw);
85
+ cache.set(key, decryptedValue);
72
86
  this.logElapsed(key, startTime, false);
73
87
  return decryptedValue;
74
88
  }
89
+ cacheOf(configs) {
90
+ let cache = this.contextCache.get(configs);
91
+ if (!cache) {
92
+ cache = /* @__PURE__ */ new Map();
93
+ this.contextCache.set(configs, cache);
94
+ }
95
+ return cache;
96
+ }
75
97
  getEnvVar(key) {
76
98
  const value = process.env[key];
77
99
  if (!value) {
@@ -80,21 +102,12 @@ class SecretManager {
80
102
  }
81
103
  return value;
82
104
  }
83
- decryptEnvVar(encryptedValue) {
84
- if (!encryptedValue) {
85
- import_logger.logger.debug("[Secret manager] Encrypted value cannot be empty");
86
- return "";
87
- }
88
- if (!this.isStringEncrypted(encryptedValue)) {
89
- import_logger.logger.debug("[Secret Manager] Value is not encrypted");
90
- return encryptedValue;
91
- }
92
- const valueWithoutPrefix = encryptedValue.replace(/^ENC:/, "");
93
- return this.cryptr.decrypt(valueWithoutPrefix);
94
- }
95
- isStringEncrypted(value) {
96
- if (!value) return false;
97
- return value.startsWith("ENC:");
105
+ decrypt(value) {
106
+ if (!value) return "";
107
+ if (!value.startsWith("ENC:")) return value;
108
+ const versioned = VERSIONED.exec(value);
109
+ if (versioned) return this.cryptr(Number(versioned[1])).decrypt(value.slice(versioned[0].length));
110
+ return this.cryptr().decrypt(value.replace(/^ENC:/, ""));
98
111
  }
99
112
  logElapsed(key, startTime, cached) {
100
113
  const endTime = process.hrtime.bigint();
@@ -1,43 +1,65 @@
1
1
  import "dotenv/config";
2
2
  import Cryptr from "cryptr";
3
3
  import { logger } from "../logger/index.js";
4
+ import { getContextConfigs } from "./config-context";
5
+ const VERSIONED = /^ENC:v(\d+):/;
4
6
  class SecretManager {
5
7
  static instance;
6
- cache = /* @__PURE__ */ new Map();
7
- cryptr;
8
+ envCache = /* @__PURE__ */ new Map();
9
+ contextCache = /* @__PURE__ */ new WeakMap();
10
+ cryptrs = /* @__PURE__ */ new Map();
8
11
  static getInstance() {
9
12
  if (!SecretManager.instance) {
10
13
  SecretManager.instance = new SecretManager();
11
14
  }
12
15
  return SecretManager.instance;
13
16
  }
14
- static encrypt(value) {
17
+ static encrypt(value, version) {
15
18
  if (!value) throw new Error("[Secret manager] Value to encrypt cannot be empty");
16
- return `ENC:${SecretManager.getInstance().cryptr.encrypt(value)}`;
19
+ const manager = SecretManager.getInstance();
20
+ if (!version) return `ENC:${manager.cryptr().encrypt(value)}`;
21
+ return `ENC:v${version}:${manager.cryptr(version).encrypt(value)}`;
17
22
  }
18
23
  constructor() {
19
- const secretKey = process.env.SECRET_MANAGER_KEY;
24
+ this.cryptr();
25
+ }
26
+ cryptr(version) {
27
+ const envName = version ? `SECRET_MANAGER_KEY_V${version}` : "SECRET_MANAGER_KEY";
28
+ const cached = this.cryptrs.get(envName);
29
+ if (cached) return cached;
30
+ const secretKey = process.env[envName];
20
31
  if (!secretKey) {
21
- throw new Error("[Secret manager] SECRET_MANAGER_KEY environment variable is not set");
32
+ throw new Error(`[Secret manager] ${envName} environment variable is not set`);
22
33
  }
23
- this.cryptr = new Cryptr(secretKey, {
34
+ const cryptr = new Cryptr(secretKey, {
24
35
  pbkdf2Iterations: 1e3,
25
36
  saltLength: 16
26
37
  });
38
+ this.cryptrs.set(envName, cryptr);
39
+ return cryptr;
27
40
  }
28
41
  get(key) {
29
42
  const startTime = process.hrtime.bigint();
30
- if (this.cache.has(key)) {
31
- const decryptedValue2 = this.cache.get(key);
43
+ const configs = getContextConfigs();
44
+ const cache = configs ? this.cacheOf(configs) : this.envCache;
45
+ if (cache.has(key)) {
32
46
  this.logElapsed(key, startTime, true);
33
- return decryptedValue2;
47
+ return cache.get(key);
34
48
  }
35
- const encryptedValue = this.getEnvVar(key);
36
- const decryptedValue = this.decryptEnvVar(encryptedValue);
37
- this.cache.set(key, decryptedValue);
49
+ const raw = configs ? configs[key] : this.getEnvVar(key);
50
+ const decryptedValue = this.decrypt(raw);
51
+ cache.set(key, decryptedValue);
38
52
  this.logElapsed(key, startTime, false);
39
53
  return decryptedValue;
40
54
  }
55
+ cacheOf(configs) {
56
+ let cache = this.contextCache.get(configs);
57
+ if (!cache) {
58
+ cache = /* @__PURE__ */ new Map();
59
+ this.contextCache.set(configs, cache);
60
+ }
61
+ return cache;
62
+ }
41
63
  getEnvVar(key) {
42
64
  const value = process.env[key];
43
65
  if (!value) {
@@ -46,21 +68,12 @@ class SecretManager {
46
68
  }
47
69
  return value;
48
70
  }
49
- decryptEnvVar(encryptedValue) {
50
- if (!encryptedValue) {
51
- logger.debug("[Secret manager] Encrypted value cannot be empty");
52
- return "";
53
- }
54
- if (!this.isStringEncrypted(encryptedValue)) {
55
- logger.debug("[Secret Manager] Value is not encrypted");
56
- return encryptedValue;
57
- }
58
- const valueWithoutPrefix = encryptedValue.replace(/^ENC:/, "");
59
- return this.cryptr.decrypt(valueWithoutPrefix);
60
- }
61
- isStringEncrypted(value) {
62
- if (!value) return false;
63
- return value.startsWith("ENC:");
71
+ decrypt(value) {
72
+ if (!value) return "";
73
+ if (!value.startsWith("ENC:")) return value;
74
+ const versioned = VERSIONED.exec(value);
75
+ if (versioned) return this.cryptr(Number(versioned[1])).decrypt(value.slice(versioned[0].length));
76
+ return this.cryptr().decrypt(value.replace(/^ENC:/, ""));
64
77
  }
65
78
  logElapsed(key, startTime, cached) {
66
79
  const endTime = process.hrtime.bigint();
@@ -11,7 +11,7 @@ export interface AgentError {
11
11
  isRetryable: boolean;
12
12
  timestamp: Date;
13
13
  }
14
- type CurrentActivity = 'running' | 'stopped' | (string & {});
14
+ type CurrentActivity = string;
15
15
  export type ActivityListener = (activity: string) => void;
16
16
  export interface AgentStateProps {
17
17
  status?: AgentStatus;
@@ -119,6 +119,7 @@ export declare class Agent {
119
119
  private resolveConfirmation;
120
120
  private postRunner;
121
121
  private reportFailure;
122
+ private saveBlockedMessage;
122
123
  private usageLimitResult;
123
124
  private failRun;
124
125
  private fingerprint;
@@ -191,7 +191,7 @@ class Agent {
191
191
  try {
192
192
  await (0, import_usage_limit.checkUsageLimit)(usageLimit, currentUser);
193
193
  } catch (error) {
194
- if (error instanceof import_usage_limit.UsageLimitError) return this.usageLimitResult(error);
194
+ if (error instanceof import_usage_limit.UsageLimitError) return this.usageLimitResult(error, await this.saveBlockedMessage(chatId));
195
195
  throw error;
196
196
  }
197
197
  }
@@ -405,6 +405,22 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
405
405
  async reportFailure(error, details = {}) {
406
406
  await (0, import_error.reportError)(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
407
407
  }
408
+ async saveBlockedMessage(chatId) {
409
+ if (!chatId) return void 0;
410
+ try {
411
+ const data = await (0, import_chats.getChatById)({ id: chatId, currentUser: this.currentUser });
412
+ if (!data?._id) return void 0;
413
+ this.currentChat = import_chat.Chat.fromJSON(data);
414
+ if (!this.currentChat.messages?.length) this.currentChat.setTitle(this.currentMessage);
415
+ this.currentChat.pushMessage({ role: "user", content: this.currentMessage, source: "user" });
416
+ await this.saveChat({ resetStop: true });
417
+ return this.currentChat;
418
+ } catch (error) {
419
+ this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to save the message of a run blocked by the usage limit");
420
+ await this.reportFailure(error, { stage: "blocked-message" });
421
+ return void 0;
422
+ }
423
+ }
408
424
  usageLimitResult(error, data) {
409
425
  return { data, error: error.userMessage, errorCode: error.code, usageLimit: { used: error.used, limit: error.limit, period: error.period } };
410
426
  }
@@ -175,7 +175,7 @@ class Agent {
175
175
  try {
176
176
  await checkUsageLimit(usageLimit, currentUser);
177
177
  } catch (error) {
178
- if (error instanceof UsageLimitError) return this.usageLimitResult(error);
178
+ if (error instanceof UsageLimitError) return this.usageLimitResult(error, await this.saveBlockedMessage(chatId));
179
179
  throw error;
180
180
  }
181
181
  }
@@ -389,6 +389,22 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
389
389
  async reportFailure(error, details = {}) {
390
390
  await reportError(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
391
391
  }
392
+ async saveBlockedMessage(chatId) {
393
+ if (!chatId) return void 0;
394
+ try {
395
+ const data = await getChatById({ id: chatId, currentUser: this.currentUser });
396
+ if (!data?._id) return void 0;
397
+ this.currentChat = Chat.fromJSON(data);
398
+ if (!this.currentChat.messages?.length) this.currentChat.setTitle(this.currentMessage);
399
+ this.currentChat.pushMessage({ role: "user", content: this.currentMessage, source: "user" });
400
+ await this.saveChat({ resetStop: true });
401
+ return this.currentChat;
402
+ } catch (error) {
403
+ this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to save the message of a run blocked by the usage limit");
404
+ await this.reportFailure(error, { stage: "blocked-message" });
405
+ return void 0;
406
+ }
407
+ }
392
408
  usageLimitResult(error, data) {
393
409
  return { data, error: error.userMessage, errorCode: error.code, usageLimit: { used: error.used, limit: error.limit, period: error.period } };
394
410
  }
@@ -25,7 +25,7 @@ var import_repositories = require("../../../common/repositories/index.js");
25
25
  var import_database_name = require("../../../common/utils/database-name.js");
26
26
  class RefreshTokenRepository {
27
27
  _ = new import_repositories.MongoRepository({
28
- database: (0, import_database_name.getDatabaseName)(),
28
+ database: import_database_name.getDatabaseName,
29
29
  collection: "refresh_tokens",
30
30
  scoped: true,
31
31
  ownerField: "userId"
@@ -2,7 +2,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
2
2
  import { getDatabaseName } from "../../../common/utils/database-name.js";
3
3
  class RefreshTokenRepository {
4
4
  _ = new MongoRepository({
5
- database: getDatabaseName(),
5
+ database: getDatabaseName,
6
6
  collection: "refresh_tokens",
7
7
  scoped: true,
8
8
  ownerField: "userId"
@@ -25,7 +25,7 @@ var import_repositories = require("../../../common/repositories/index.js");
25
25
  var import_database_name = require("../../../common/utils/database-name.js");
26
26
  class RevokedTokenRepository {
27
27
  _ = new import_repositories.MongoRepository({
28
- database: (0, import_database_name.getDatabaseName)(),
28
+ database: import_database_name.getDatabaseName,
29
29
  collection: "revoked_tokens",
30
30
  scoped: true
31
31
  });
@@ -2,7 +2,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
2
2
  import { getDatabaseName } from "../../../common/utils/database-name.js";
3
3
  class RevokedTokenRepository {
4
4
  _ = new MongoRepository({
5
- database: getDatabaseName(),
5
+ database: getDatabaseName,
6
6
  collection: "revoked_tokens",
7
7
  scoped: true
8
8
  });
@@ -27,7 +27,7 @@ var import_repositories = require("../../../common/repositories/index.js");
27
27
  var import_database_name = require("../../../common/utils/database-name.js");
28
28
  class AutomationRunRepository {
29
29
  _ = new import_repositories.MongoRepository({
30
- database: (0, import_database_name.getDatabaseName)(),
30
+ database: import_database_name.getDatabaseName,
31
31
  collection: "automation_runs",
32
32
  scoped: true
33
33
  });
@@ -4,7 +4,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
4
4
  import { getDatabaseName } from "../../../common/utils/database-name.js";
5
5
  class AutomationRunRepository {
6
6
  _ = new MongoRepository({
7
- database: getDatabaseName(),
7
+ database: getDatabaseName,
8
8
  collection: "automation_runs",
9
9
  scoped: true
10
10
  });
@@ -27,7 +27,7 @@ var import_repositories = require("../../../common/repositories/index.js");
27
27
  var import_database_name = require("../../../common/utils/database-name.js");
28
28
  class AutomationRepository {
29
29
  _ = new import_repositories.MongoRepository({
30
- database: (0, import_database_name.getDatabaseName)(),
30
+ database: import_database_name.getDatabaseName,
31
31
  collection: "automations",
32
32
  scoped: true
33
33
  });
@@ -4,7 +4,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
4
4
  import { getDatabaseName } from "../../../common/utils/database-name.js";
5
5
  class AutomationRepository {
6
6
  _ = new MongoRepository({
7
- database: getDatabaseName(),
7
+ database: getDatabaseName,
8
8
  collection: "automations",
9
9
  scoped: true
10
10
  });
@@ -26,7 +26,7 @@ var import_repositories = require("../../../common/repositories/index.js");
26
26
  var import_database_name = require("../../../common/utils/database-name.js");
27
27
  class ChatRepository {
28
28
  _ = new import_repositories.MongoRepository({
29
- database: (0, import_database_name.getDatabaseName)(),
29
+ database: import_database_name.getDatabaseName,
30
30
  collection: "chats",
31
31
  scoped: true
32
32
  });
@@ -3,7 +3,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
3
3
  import { getDatabaseName } from "../../../common/utils/database-name.js";
4
4
  class ChatRepository {
5
5
  _ = new MongoRepository({
6
- database: getDatabaseName(),
6
+ database: getDatabaseName,
7
7
  collection: "chats",
8
8
  scoped: true
9
9
  });
@@ -26,7 +26,7 @@ var import_repositories = require("../../../common/repositories/index.js");
26
26
  var import_database_name = require("../../../common/utils/database-name.js");
27
27
  class LLMCallRepository {
28
28
  _ = new import_repositories.MongoRepository({
29
- database: (0, import_database_name.getDatabaseName)(),
29
+ database: import_database_name.getDatabaseName,
30
30
  collection: "llm_calls",
31
31
  scoped: true
32
32
  });
@@ -3,7 +3,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
3
3
  import { getDatabaseName } from "../../../common/utils/database-name.js";
4
4
  class LLMCallRepository {
5
5
  _ = new MongoRepository({
6
- database: getDatabaseName(),
6
+ database: getDatabaseName,
7
7
  collection: "llm_calls",
8
8
  scoped: true
9
9
  });
@@ -28,7 +28,7 @@ var import_database_name = require("../../../common/utils/database-name.js");
28
28
  const external = (where) => ({ ...where, internal: { $ne: true } });
29
29
  class McpServerRepository {
30
30
  _ = new import_repositories.MongoRepository({
31
- database: (0, import_database_name.getDatabaseName)(),
31
+ database: import_database_name.getDatabaseName,
32
32
  collection: "mcp_servers",
33
33
  scoped: true
34
34
  });
@@ -5,7 +5,7 @@ import { getDatabaseName } from "../../../common/utils/database-name.js";
5
5
  const external = (where) => ({ ...where, internal: { $ne: true } });
6
6
  class McpServerRepository {
7
7
  _ = new MongoRepository({
8
- database: getDatabaseName(),
8
+ database: getDatabaseName,
9
9
  collection: "mcp_servers",
10
10
  scoped: true
11
11
  });
@@ -26,7 +26,7 @@ var import_repositories = require("../../../common/repositories/index.js");
26
26
  var import_database_name = require("../../../common/utils/database-name.js");
27
27
  class AgentActionRepository {
28
28
  _ = new import_repositories.MongoRepository({
29
- database: (0, import_database_name.getDatabaseName)(),
29
+ database: import_database_name.getDatabaseName,
30
30
  collection: "agent_actions",
31
31
  scoped: true
32
32
  });
@@ -3,7 +3,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
3
3
  import { getDatabaseName } from "../../../common/utils/database-name.js";
4
4
  class AgentActionRepository {
5
5
  _ = new MongoRepository({
6
- database: getDatabaseName(),
6
+ database: getDatabaseName,
7
7
  collection: "agent_actions",
8
8
  scoped: true
9
9
  });
@@ -26,7 +26,7 @@ var import_repositories = require("../../../common/repositories/index.js");
26
26
  var import_database_name = require("../../../common/utils/database-name.js");
27
27
  class AgentTaskRepository {
28
28
  _ = new import_repositories.MongoRepository({
29
- database: (0, import_database_name.getDatabaseName)(),
29
+ database: import_database_name.getDatabaseName,
30
30
  collection: "agent_tasks",
31
31
  scoped: true
32
32
  });
@@ -3,7 +3,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
3
3
  import { getDatabaseName } from "../../../common/utils/database-name.js";
4
4
  class AgentTaskRepository {
5
5
  _ = new MongoRepository({
6
- database: getDatabaseName(),
6
+ database: getDatabaseName,
7
7
  collection: "agent_tasks",
8
8
  scoped: true
9
9
  });
@@ -25,7 +25,7 @@ var import_repositories = require("../../../common/repositories/index.js");
25
25
  var import_database_name = require("../../../common/utils/database-name.js");
26
26
  class AgentTraceRepository {
27
27
  _ = new import_repositories.MongoRepository({
28
- database: (0, import_database_name.getDatabaseName)(),
28
+ database: import_database_name.getDatabaseName,
29
29
  collection: "agent_traces",
30
30
  scoped: true
31
31
  });
@@ -2,7 +2,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
2
2
  import { getDatabaseName } from "../../../common/utils/database-name.js";
3
3
  class AgentTraceRepository {
4
4
  _ = new MongoRepository({
5
- database: getDatabaseName(),
5
+ database: getDatabaseName,
6
6
  collection: "agent_traces",
7
7
  scoped: true
8
8
  });
@@ -27,7 +27,7 @@ var import_database_name = require("../../../common/utils/database-name.js");
27
27
  var import_entities = require("../entities");
28
28
  class UserRepository {
29
29
  _ = new import_repositories.MongoRepository({
30
- database: (0, import_database_name.getDatabaseName)(),
30
+ database: import_database_name.getDatabaseName,
31
31
  collection: "users",
32
32
  scoped: true,
33
33
  ownerField: "_id",
@@ -4,7 +4,7 @@ import { getDatabaseName } from "../../../common/utils/database-name.js";
4
4
  import { User } from "../entities";
5
5
  class UserRepository {
6
6
  _ = new MongoRepository({
7
- database: getDatabaseName(),
7
+ database: getDatabaseName,
8
8
  collection: "users",
9
9
  scoped: true,
10
10
  ownerField: "_id",
@@ -26,7 +26,7 @@ var import_repositories = require("../../../common/repositories/index.js");
26
26
  var import_database_name = require("../../../common/utils/database-name.js");
27
27
  class WorkspaceItemRepository {
28
28
  _ = new import_repositories.MongoRepository({
29
- database: (0, import_database_name.getDatabaseName)(),
29
+ database: import_database_name.getDatabaseName,
30
30
  collection: "workspace_items",
31
31
  scoped: true
32
32
  });
@@ -3,7 +3,7 @@ import { MongoRepository } from "../../../common/repositories/index.js";
3
3
  import { getDatabaseName } from "../../../common/utils/database-name.js";
4
4
  class WorkspaceItemRepository {
5
5
  _ = new MongoRepository({
6
- database: getDatabaseName(),
6
+ database: getDatabaseName,
7
7
  collection: "workspace_items",
8
8
  scoped: true
9
9
  });
package/docs/README.md CHANGED
@@ -14,7 +14,7 @@ Start with the [README](../README.md) for what `openloops` is and how to run it.
14
14
  | Page | What it covers |
15
15
  | --- | --- |
16
16
  | [The `Agent`](agent.md) | Options, running a turn, the result and its statuses, confirmations, autonomous mode, hooks and interruption. |
17
- | [Configuration](configuration.md) | Environment variables, choosing the model and what is recorded. |
17
+ | [Configuration](configuration.md) | Environment variables, encrypted values, several agents in one process, choosing the model and what is recorded. |
18
18
  | [Reporting errors](error-reporting.md) | Declare one function, once, to send the errors that the package catches to Sentry or to the tool you use: what it receives, what is reported, serverless and moving from `SENTRY_DSN`. |
19
19
  | [Automations](automations.md) | Tasks that the agent runs by itself, on a schedule, when an event arrives or both: triggers, tokens, the queue, the history of runs and the runner that executes them. If you used `agentic-jobs`, read [the migration steps](automations.md#migrating-from-agentic-jobs). Updating to 0.5.0 breaks the shape of the triggers, read [the migration to 0.5.0](automations.md#migrating-to-050). |
20
20
  | [Chats](chats.md) | The chat record, its title and messages and their `source`, listing and searching chats, reading and deleting them. Updating to 0.8.0 needs [a migration of the titles](chats.md#migrating-to-080). |
package/docs/agent.md CHANGED
@@ -90,15 +90,16 @@ const result = await agent.run({
90
90
 
91
91
  `period` is required and can be `day`, `week` (Monday to Sunday) or `month`. The period is calculated in the time zone of the user (UTC when it has none) and the spend is the cost of all the model calls of that user in it, from any chat and of any kind. The limit itself belongs to your application: `openloops` only checks it.
92
92
 
93
- Before the run starts, if the spend is equal to or greater than `maxCostUsd`, the run does not start and nothing is saved. The result has no `data` and carries the details:
93
+ Before the run starts, if the spend is equal to or greater than `maxCostUsd`, the run does not start: no guard, no model call and no loop run. When the run continues an existing chat (`chatId`), the message of the user is saved in it with no answer, the status of the chat does not change, and the chat is returned in `data`. A chat with no messages takes that message as its title. With no `chatId`, or with one that does not exist, nothing is saved and `data` is `undefined`. The result carries the details:
94
94
 
95
95
  ```typescript
96
+ result.data
96
97
  result.error
97
98
  result.errorCode
98
99
  result.usageLimit
99
100
  ```
100
101
 
101
- `errorCode` is `USAGE_LIMIT_REACHED` and `usageLimit` is `{ used, limit, period }`. This is an expected rejection, so it is not sent to the [error reporter](error-reporting.md).
102
+ `errorCode` is `USAGE_LIMIT_REACHED` and `usageLimit` is `{ used, limit, period }`. This is an expected rejection, so it is not sent to the [error reporter](error-reporting.md). The message that was saved is part of the history of the chat, so when the limit is lifted the next run reads it and the user can just say `continue`.
102
103
 
103
104
  A run that starts under the limit finishes even if it goes over it, so the last run of a period can spend a little more than `maxCostUsd`. To stop a run between the iterations of the loop, create the agent with `stopOnUsageLimit: true`. The chat is then marked as `failed` with `USAGE_LIMIT_REACHED` (not retryable) in `data.state.lastError`, and the result carries the same `errorCode` and `usageLimit`. It costs one query per iteration.
104
105
 
@@ -8,6 +8,7 @@
8
8
  | `OPENLOOPS_DB_NAME` | no | Database name. Defaults to `openloops`. |
9
9
  | `OPENLOOPS_MONGO_MAX_POOL_SIZE` | no | Most connections each process keeps open to MongoDB. Defaults to `3`, which suits serverless functions, where every instance handles one request at a time. Raise it for a long-running server. |
10
10
  | `SECRET_MANAGER_KEY` | yes | Key used to decrypt values that start with `ENC:`. The library throws when it loads without it. |
11
+ | `SECRET_MANAGER_KEY_V<N>` | only if you use `ENC:v<N>:` values | Key of version `N` of the [versioned encrypted values](#encrypted-values). |
11
12
  | `ANTHROPIC_API_KEY` | for the default model | API key of the default provider, `anthropic`. |
12
13
  | `OPENAI_API_KEY`, `GEMINI_API_KEY` | for those providers | API keys of the other providers you choose per chat. |
13
14
  | `JWT_SECRET` | for `login` and for event automations | Secret that signs the tokens of the sessions, of the reset of a password and of [event automations](automations.md#the-token). See [authentication](authentication.md). |
@@ -23,7 +24,35 @@
23
24
  | `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL` | no | Traces every LLM call in Langfuse when all three are set. |
24
25
  | `IS_LOCAL`, `NODE_ENV` | no | Local development switches. With `IS_LOCAL` set to `true`, or `NODE_ENV` set to `development`, the logger prints colored logs if `pino-pretty` is installed in your project (it is a dev dependency of this package, so install it yourself: `yarn add -D pino-pretty`), and plain JSON otherwise. |
25
26
 
26
- Any value can be stored encrypted by prefixing it with `ENC:`. It is decrypted with `SECRET_MANAGER_KEY` when it is read.
27
+ ## Encrypted values
28
+
29
+ Any value can be stored encrypted. It is decrypted when it is read.
30
+
31
+ - `ENC:<payload>` is decrypted with `SECRET_MANAGER_KEY`.
32
+ - `ENC:v<N>:<payload>` is decrypted with `SECRET_MANAGER_KEY_V<N>`. Versions let you rotate the key: encrypt new values with the next version, keep the old key until nothing uses it, then remove it.
33
+
34
+ ```ts
35
+ import { SecretManager } from 'openloops/common'
36
+
37
+ SecretManager.encrypt('sk-ant-...')
38
+ SecretManager.encrypt('sk-ant-...', 2)
39
+ ```
40
+
41
+ ## One process, several agents
42
+
43
+ By default the configuration is read from the environment, which is one configuration per process. To serve several agents from the same process, for example one function that runs every agent of a platform, run each request with its own configuration:
44
+
45
+ ```ts
46
+ import { runWithConfigs } from 'openloops/common'
47
+
48
+ await runWithConfigs(configsOfThisAgent, () => handleRequest(event))
49
+ ```
50
+
51
+ `configsOfThisAgent` is an object with the same names as the variables of this page (`OPENLOOPS_DB_URI`, `OPENLOOPS_DB_NAME`, `JWT_SECRET`, `ANTHROPIC_API_KEY`...), and its values can be encrypted. Everything that runs inside the callback, including what it awaits, reads those values and never the environment, so a name that is missing from the object is empty and does not fall back to the environment. Outside of `runWithConfigs` nothing changes.
52
+
53
+ Each agent can use its own database, even in its own cluster: the repositories resolve the database name and the connection on every call, and the connections are shared by connection string. The API key of the provider is sent with each model call, so two agents never use each other's key. See the example [run-agent-multi-tenant](../examples/run-agent/run-agent-multi-tenant.ts).
54
+
55
+ Pass the configuration of a request to `runWithConfigs` before creating the `Agent` and before resolving the user, and do not keep the result of `secretManager.get` between requests.
27
56
 
28
57
  ## Which model a chat uses
29
58
 
@@ -130,7 +130,7 @@ runner.start()
130
130
  - Add input guards for what your product must never receive, such as card numbers.
131
131
  - Mark your own destructive tools with `destructive: true`. The agent asks for confirmation before running them. Do not rely on a tool being treated as destructive by default, because it is not.
132
132
  - Use `strictMode: true` in the agent when the tools of an MCP server must be reviewed by the user on every change.
133
- - Keep API keys and the secrets of [configuration](configuration.md) out of the code. Values can be stored encrypted with the `ENC:` prefix.
133
+ - Keep API keys and the secrets of [configuration](configuration.md) out of the code. Values can be stored encrypted with the `ENC:` prefix. To serve several agents from one process, see [one process, several agents](configuration.md#one-process-several-agents).
134
134
  - Set limits on how many automations and how often they run in your own layer, since `openloops` does not limit them yet.
135
135
 
136
136
  ## Common mistakes