openloops 0.9.1 → 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.
- package/CHANGELOG.md +12 -0
- package/README.md +2 -0
- package/dist/clients/llm/llm-client.d.ts +1 -0
- package/dist/clients/llm/llm-client.js +6 -3
- package/dist/clients/llm/llm-client.mjs +6 -3
- package/dist/common/base/current-user.js +2 -1
- package/dist/common/base/current-user.mjs +2 -1
- package/dist/common/index.d.ts +3 -0
- package/dist/common/index.js +6 -0
- package/dist/common/index.mjs +4 -0
- package/dist/common/repositories/mongo-db.client.d.ts +1 -1
- package/dist/common/repositories/mongo-db.client.js +7 -6
- package/dist/common/repositories/mongo-db.client.mjs +7 -6
- package/dist/common/repositories/mongo-db.repository.d.ts +3 -2
- package/dist/common/repositories/mongo-db.repository.js +20 -16
- package/dist/common/repositories/mongo-db.repository.mjs +20 -16
- package/dist/common/utils/config-context.d.ts +3 -0
- package/dist/common/utils/config-context.js +33 -0
- package/dist/common/utils/config-context.mjs +8 -0
- package/dist/common/utils/secret-manager.d.ts +7 -5
- package/dist/common/utils/secret-manager.js +41 -28
- package/dist/common/utils/secret-manager.mjs +41 -28
- package/dist/services/authentication/repositories/refresh-token.repository.js +1 -1
- package/dist/services/authentication/repositories/refresh-token.repository.mjs +1 -1
- package/dist/services/authentication/repositories/revoked-token.repository.js +1 -1
- package/dist/services/authentication/repositories/revoked-token.repository.mjs +1 -1
- package/dist/services/automations/repositories/automation-run.repository.js +1 -1
- package/dist/services/automations/repositories/automation-run.repository.mjs +1 -1
- package/dist/services/automations/repositories/automation.repository.js +1 -1
- package/dist/services/automations/repositories/automation.repository.mjs +1 -1
- package/dist/services/chats/repositories/chat.repository.js +1 -1
- package/dist/services/chats/repositories/chat.repository.mjs +1 -1
- package/dist/services/llmcalls/repositories/llmcall.repository.js +1 -1
- package/dist/services/llmcalls/repositories/llmcall.repository.mjs +1 -1
- package/dist/services/mcp-servers/repositories/mcpserver.repository.js +1 -1
- package/dist/services/mcp-servers/repositories/mcpserver.repository.mjs +1 -1
- package/dist/services/tasks/repositories/agent-action.repository.js +1 -1
- package/dist/services/tasks/repositories/agent-action.repository.mjs +1 -1
- package/dist/services/tasks/repositories/agent-task.repository.js +1 -1
- package/dist/services/tasks/repositories/agent-task.repository.mjs +1 -1
- package/dist/services/traces/repositories/agent-trace.repository.js +1 -1
- package/dist/services/traces/repositories/agent-trace.repository.mjs +1 -1
- package/dist/services/users/repositories/user.repository.js +1 -1
- package/dist/services/users/repositories/user.repository.mjs +1 -1
- package/dist/services/workspaces/repositories/workspace-item.repository.js +1 -1
- package/dist/services/workspaces/repositories/workspace-item.repository.mjs +1 -1
- package/docs/README.md +1 -1
- package/docs/configuration.md +30 -1
- package/docs/integration-guide.md +1 -1
- package/docs/llms.txt +1 -1
- package/examples/run-agent/run-agent-multi-tenant.ts +52 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `openloops` are written here, newest first. The format follows [Keep a Changelog](https://keepachangelog.com) and the versions follow [semantic versioning](https://semver.org), where a minor version can still break the API while the package is in beta. Changes before 0.4.0 are not recorded here, see the commits and the tags.
|
|
4
4
|
|
|
5
|
+
## 0.10.0
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `runWithConfigs(configs, fn)` (`openloops/common`) runs `fn` with its own configuration, so one process can serve several agents. `secretManager.get` reads the configs of the current context first (values can be `ENC:` or `ENC:v<N>:`) and the environment when there is no context.
|
|
10
|
+
- Versioned encrypted values, `ENC:v<N>:`, with the master key in `SECRET_MANAGER_KEY_V<N>`. `SecretManager.encrypt(value, version?)` writes them. `ENC:` values keep using `SECRET_MANAGER_KEY`.
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- The repositories resolve the database name and the Mongo client on every call, not when the module loads. Mongo clients are cached by connection string. `getMongoDBClient` returns `undefined` when the connection string is not configured.
|
|
15
|
+
- The LLM client sends the API key of the provider on each request (`apiKey`) and no longer writes `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` into `process.env`. When the key is not configured, the provider falls back to its own environment variable as before.
|
|
16
|
+
|
|
5
17
|
## 0.9.1
|
|
6
18
|
|
|
7
19
|
### Changed
|
package/README.md
CHANGED
|
@@ -187,6 +187,8 @@ OPENLOOPS_DB_URI="mongodb://localhost:27017/"
|
|
|
187
187
|
OPENLOOPS_DB_NAME='openloops'
|
|
188
188
|
|
|
189
189
|
SECRET_MANAGER_KEY=secret
|
|
190
|
+
# Only for ENC:v<N>: values, see docs/configuration.md
|
|
191
|
+
# SECRET_MANAGER_KEY_V1=
|
|
190
192
|
|
|
191
193
|
# Default model provider (anthropic, claude-haiku-5-5)
|
|
192
194
|
ANTHROPIC_API_KEY=
|
|
@@ -66,8 +66,6 @@ class LLMClient {
|
|
|
66
66
|
langfuseEnabled;
|
|
67
67
|
callTimeoutMs;
|
|
68
68
|
constructor() {
|
|
69
|
-
process.env.OPENAI_API_KEY = import_secret_manager.secretManager.get("OPENAI_API_KEY");
|
|
70
|
-
process.env.ANTHROPIC_API_KEY = import_secret_manager.secretManager.get("ANTHROPIC_API_KEY");
|
|
71
69
|
this.callTimeoutMs = (0, import_number_setting.numberSetting)("LLM_CALL_TIMEOUT_MS", DEFAULT_CALL_TIMEOUT_MS);
|
|
72
70
|
const publicKey = import_secret_manager.secretManager.get("LANGFUSE_PUBLIC_KEY");
|
|
73
71
|
const secretKey = import_secret_manager.secretManager.get("LANGFUSE_SECRET_KEY");
|
|
@@ -103,7 +101,8 @@ class LLMClient {
|
|
|
103
101
|
const reasoning = thinking && thinking !== "off" ? thinking : void 0;
|
|
104
102
|
const ruleOmitsTemperature = (0, import_sampling_rules.omitsTemperature)(provider, modelName, Boolean(reasoning));
|
|
105
103
|
const send = (omitTemperature) => this.withDeadline(thinking === "high" ? this.callTimeoutMs * HIGH_THINKING_TIMEOUT_FACTOR : this.callTimeoutMs, (signal) => {
|
|
106
|
-
const
|
|
104
|
+
const apiKey = this.apiKeyOf(provider);
|
|
105
|
+
const options = { ...apiKey ? { apiKey } : {}, ...omitTemperature || ruleOmitsTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
|
|
107
106
|
return resolvedChoice || thinking ? models.completeSimple(model, context, { ...options, ...resolvedChoice ? { toolChoice: resolvedChoice } : {}, ...reasoning ? { reasoning } : {} }) : models.complete(model, context, options);
|
|
108
107
|
});
|
|
109
108
|
const raw = await this.traced(
|
|
@@ -116,6 +115,10 @@ class LLMClient {
|
|
|
116
115
|
}
|
|
117
116
|
return (0, import_pi_ai_adapter.fromPiMessage)(raw);
|
|
118
117
|
}
|
|
118
|
+
apiKeyOf(provider) {
|
|
119
|
+
const name = provider === "google" ? "GEMINI_API_KEY" : `${provider.toUpperCase().replace(/-/g, "_")}_API_KEY`;
|
|
120
|
+
return import_secret_manager.secretManager.get(name) || void 0;
|
|
121
|
+
}
|
|
119
122
|
chooseModel(params) {
|
|
120
123
|
const { provider, modelName, currentUser } = params ?? {};
|
|
121
124
|
if (Boolean(provider) !== Boolean(modelName)) throw new Error("[LLM Client] provider and modelName must be given together");
|
|
@@ -33,8 +33,6 @@ class LLMClient {
|
|
|
33
33
|
langfuseEnabled;
|
|
34
34
|
callTimeoutMs;
|
|
35
35
|
constructor() {
|
|
36
|
-
process.env.OPENAI_API_KEY = secretManager.get("OPENAI_API_KEY");
|
|
37
|
-
process.env.ANTHROPIC_API_KEY = secretManager.get("ANTHROPIC_API_KEY");
|
|
38
36
|
this.callTimeoutMs = numberSetting("LLM_CALL_TIMEOUT_MS", DEFAULT_CALL_TIMEOUT_MS);
|
|
39
37
|
const publicKey = secretManager.get("LANGFUSE_PUBLIC_KEY");
|
|
40
38
|
const secretKey = secretManager.get("LANGFUSE_SECRET_KEY");
|
|
@@ -70,7 +68,8 @@ class LLMClient {
|
|
|
70
68
|
const reasoning = thinking && thinking !== "off" ? thinking : void 0;
|
|
71
69
|
const ruleOmitsTemperature = omitsTemperature(provider, modelName, Boolean(reasoning));
|
|
72
70
|
const send = (omitTemperature) => this.withDeadline(thinking === "high" ? this.callTimeoutMs * HIGH_THINKING_TIMEOUT_FACTOR : this.callTimeoutMs, (signal) => {
|
|
73
|
-
const
|
|
71
|
+
const apiKey = this.apiKeyOf(provider);
|
|
72
|
+
const options = { ...apiKey ? { apiKey } : {}, ...omitTemperature || ruleOmitsTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
|
|
74
73
|
return resolvedChoice || thinking ? models.completeSimple(model, context, { ...options, ...resolvedChoice ? { toolChoice: resolvedChoice } : {}, ...reasoning ? { reasoning } : {} }) : models.complete(model, context, options);
|
|
75
74
|
});
|
|
76
75
|
const raw = await this.traced(
|
|
@@ -83,6 +82,10 @@ class LLMClient {
|
|
|
83
82
|
}
|
|
84
83
|
return fromPiMessage(raw);
|
|
85
84
|
}
|
|
85
|
+
apiKeyOf(provider) {
|
|
86
|
+
const name = provider === "google" ? "GEMINI_API_KEY" : `${provider.toUpperCase().replace(/-/g, "_")}_API_KEY`;
|
|
87
|
+
return secretManager.get(name) || void 0;
|
|
88
|
+
}
|
|
86
89
|
chooseModel(params) {
|
|
87
90
|
const { provider, modelName, currentUser } = params ?? {};
|
|
88
91
|
if (Boolean(provider) !== Boolean(modelName)) throw new Error("[LLM Client] provider and modelName must be given together");
|
|
@@ -32,11 +32,12 @@ class CurrentUser extends import_user.User {
|
|
|
32
32
|
static async asyncFromDB(userId) {
|
|
33
33
|
if (!userId) return void 0;
|
|
34
34
|
const mongoDBClient = (0, import_mongo_db.getMongoDBClient)();
|
|
35
|
+
if (!mongoDBClient) throw new Error("[Current User] Database client not found");
|
|
35
36
|
const db = await mongoDBClient.db((0, import_database_name.getDatabaseName)());
|
|
36
37
|
let user;
|
|
37
38
|
try {
|
|
38
39
|
user = await db.collection("users").findOne(
|
|
39
|
-
{ _id: new import_mongodb.ObjectId(userId) },
|
|
40
|
+
{ _id: new import_mongodb.ObjectId(userId), deletedAt: null, archivedAt: null },
|
|
40
41
|
{ projection: { password: 0 } }
|
|
41
42
|
);
|
|
42
43
|
} catch (error) {
|
|
@@ -9,11 +9,12 @@ class CurrentUser extends User {
|
|
|
9
9
|
static async asyncFromDB(userId) {
|
|
10
10
|
if (!userId) return void 0;
|
|
11
11
|
const mongoDBClient = getMongoDBClient();
|
|
12
|
+
if (!mongoDBClient) throw new Error("[Current User] Database client not found");
|
|
12
13
|
const db = await mongoDBClient.db(getDatabaseName());
|
|
13
14
|
let user;
|
|
14
15
|
try {
|
|
15
16
|
user = await db.collection("users").findOne(
|
|
16
|
-
{ _id: new ObjectId(userId) },
|
|
17
|
+
{ _id: new ObjectId(userId), deletedAt: null, archivedAt: null },
|
|
17
18
|
{ projection: { password: 0 } }
|
|
18
19
|
);
|
|
19
20
|
} catch (error) {
|
package/dist/common/index.d.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
1
|
export * from './logger';
|
|
2
2
|
export { setErrorReporter } from './error/error-reporter';
|
|
3
3
|
export type { ErrorReporter, ErrorReportDetails } from './error/error-reporter';
|
|
4
|
+
export { runWithConfigs } from './utils/config-context';
|
|
5
|
+
export type { Configs } from './utils/config-context';
|
|
6
|
+
export { SecretManager } from './utils/secret-manager';
|
package/dist/common/index.js
CHANGED
|
@@ -19,13 +19,19 @@ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "defau
|
|
|
19
19
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
20
|
var common_exports = {};
|
|
21
21
|
__export(common_exports, {
|
|
22
|
+
SecretManager: () => import_secret_manager.SecretManager,
|
|
23
|
+
runWithConfigs: () => import_config_context.runWithConfigs,
|
|
22
24
|
setErrorReporter: () => import_error_reporter.setErrorReporter
|
|
23
25
|
});
|
|
24
26
|
module.exports = __toCommonJS(common_exports);
|
|
25
27
|
__reExport(common_exports, require("./logger"), module.exports);
|
|
26
28
|
var import_error_reporter = require("./error/error-reporter");
|
|
29
|
+
var import_config_context = require("./utils/config-context");
|
|
30
|
+
var import_secret_manager = require("./utils/secret-manager");
|
|
27
31
|
// Annotate the CommonJS export names for ESM import in node:
|
|
28
32
|
0 && (module.exports = {
|
|
33
|
+
SecretManager,
|
|
34
|
+
runWithConfigs,
|
|
29
35
|
setErrorReporter,
|
|
30
36
|
...require("./logger")
|
|
31
37
|
});
|
package/dist/common/index.mjs
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
export * from "./logger";
|
|
2
2
|
import { setErrorReporter } from "./error/error-reporter";
|
|
3
|
+
import { runWithConfigs } from "./utils/config-context";
|
|
4
|
+
import { SecretManager } from "./utils/secret-manager";
|
|
3
5
|
export {
|
|
6
|
+
SecretManager,
|
|
7
|
+
runWithConfigs,
|
|
4
8
|
setErrorReporter
|
|
5
9
|
};
|
|
@@ -8,4 +8,4 @@ export declare class MongoClient {
|
|
|
8
8
|
close(force?: boolean): Promise<void>;
|
|
9
9
|
db(dbName?: string, options?: DbOptions): Promise<Db>;
|
|
10
10
|
}
|
|
11
|
-
export declare function getMongoDBClient(envVarName?: string): MongoClient;
|
|
11
|
+
export declare function getMongoDBClient(envVarName?: string): MongoClient | undefined;
|
|
@@ -67,13 +67,14 @@ class MongoClient {
|
|
|
67
67
|
}
|
|
68
68
|
const mongoDBClients = /* @__PURE__ */ new Map();
|
|
69
69
|
function getMongoDBClient(envVarName = "OPENLOOPS_DB_URI") {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
70
|
+
const connString = import_secret_manager.secretManager.get(envVarName);
|
|
71
|
+
if (!connString) return void 0;
|
|
72
|
+
let client = mongoDBClients.get(connString);
|
|
73
|
+
if (!client) {
|
|
74
|
+
client = new MongoClient(connString, {});
|
|
75
|
+
mongoDBClients.set(connString, client);
|
|
75
76
|
}
|
|
76
|
-
return
|
|
77
|
+
return client;
|
|
77
78
|
}
|
|
78
79
|
// Annotate the CommonJS export names for ESM import in node:
|
|
79
80
|
0 && (module.exports = {
|
|
@@ -45,13 +45,14 @@ class MongoClient {
|
|
|
45
45
|
}
|
|
46
46
|
const mongoDBClients = /* @__PURE__ */ new Map();
|
|
47
47
|
function getMongoDBClient(envVarName = "OPENLOOPS_DB_URI") {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}
|
|
48
|
+
const connString = secretManager.get(envVarName);
|
|
49
|
+
if (!connString) return void 0;
|
|
50
|
+
let client = mongoDBClients.get(connString);
|
|
51
|
+
if (!client) {
|
|
52
|
+
client = new MongoClient(connString, {});
|
|
53
|
+
mongoDBClients.set(connString, client);
|
|
53
54
|
}
|
|
54
|
-
return
|
|
55
|
+
return client;
|
|
55
56
|
}
|
|
56
57
|
export {
|
|
57
58
|
MongoClient,
|
|
@@ -9,20 +9,21 @@ export declare class VersionConflictError extends Error {
|
|
|
9
9
|
export declare class MongoRepository<T> {
|
|
10
10
|
private readonly database;
|
|
11
11
|
private readonly collection;
|
|
12
|
-
private readonly
|
|
12
|
+
private readonly envvar?;
|
|
13
13
|
private readonly _where;
|
|
14
14
|
private readonly scoped;
|
|
15
15
|
private readonly ownerField;
|
|
16
16
|
private readonly protectedFields;
|
|
17
17
|
private readonly report;
|
|
18
18
|
constructor(props: {
|
|
19
|
-
database: string;
|
|
19
|
+
database: string | (() => string);
|
|
20
20
|
collection: string;
|
|
21
21
|
envvar?: string;
|
|
22
22
|
scoped?: boolean;
|
|
23
23
|
ownerField?: string;
|
|
24
24
|
protectedFields?: string[];
|
|
25
25
|
});
|
|
26
|
+
private db;
|
|
26
27
|
private assertScope;
|
|
27
28
|
private actorId;
|
|
28
29
|
private withScope;
|
|
@@ -39,7 +39,7 @@ class VersionConflictError extends Error {
|
|
|
39
39
|
class MongoRepository {
|
|
40
40
|
database;
|
|
41
41
|
collection;
|
|
42
|
-
|
|
42
|
+
envvar;
|
|
43
43
|
_where = { deletedAt: null, archivedAt: null };
|
|
44
44
|
scoped;
|
|
45
45
|
ownerField;
|
|
@@ -49,14 +49,18 @@ class MongoRepository {
|
|
|
49
49
|
const { database, collection, envvar, scoped = false, ownerField = "ownerId", protectedFields = [] } = props || {};
|
|
50
50
|
if (!database) throw new Error("[Mongo Repository] Database name is required");
|
|
51
51
|
if (!collection) throw new Error("[Mongo Repository] Collection name is required");
|
|
52
|
-
this.
|
|
53
|
-
if (!this.dbClient) throw new Error("[Mongo Repository] Database client not found");
|
|
52
|
+
this.envvar = envvar;
|
|
54
53
|
this.database = database;
|
|
55
54
|
this.collection = collection;
|
|
56
55
|
this.scoped = scoped;
|
|
57
56
|
this.ownerField = ownerField;
|
|
58
57
|
this.protectedFields = [...PROTECTED_FIELDS, ...protectedFields];
|
|
59
58
|
}
|
|
59
|
+
async db() {
|
|
60
|
+
const client = (0, import_mongo_db.getMongoDBClient)(this.envvar);
|
|
61
|
+
if (!client) throw new Error("[Mongo Repository] Database client not found");
|
|
62
|
+
return client.db(typeof this.database === "function" ? this.database() : this.database);
|
|
63
|
+
}
|
|
60
64
|
assertScope(scope) {
|
|
61
65
|
if (!scope && this.scoped) throw new Error(`[Mongo Repository] Scope is required in ${this.collection}`);
|
|
62
66
|
}
|
|
@@ -114,7 +118,7 @@ class MongoRepository {
|
|
|
114
118
|
async findOne({ where, select, options, scope }) {
|
|
115
119
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
116
120
|
try {
|
|
117
|
-
const db = await this.
|
|
121
|
+
const db = await this.db();
|
|
118
122
|
const collection = db.collection(this.collection);
|
|
119
123
|
const result = await collection.findOne(
|
|
120
124
|
filter,
|
|
@@ -141,7 +145,7 @@ class MongoRepository {
|
|
|
141
145
|
async query({ where, select, options, scope }, pageSize, fetchSize) {
|
|
142
146
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
143
147
|
try {
|
|
144
|
-
const db = await this.
|
|
148
|
+
const db = await this.db();
|
|
145
149
|
const collection = db.collection(this.collection);
|
|
146
150
|
const { page = 1 } = options || {};
|
|
147
151
|
const _skip = +page > 0 ? (+page - 1) * pageSize : 0;
|
|
@@ -155,7 +159,7 @@ class MongoRepository {
|
|
|
155
159
|
async findAll({ where, select, options, scope }) {
|
|
156
160
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
157
161
|
try {
|
|
158
|
-
const db = await this.
|
|
162
|
+
const db = await this.db();
|
|
159
163
|
const collection = db.collection(this.collection);
|
|
160
164
|
const cursor = collection.find(filter, { projection: select });
|
|
161
165
|
const result = await (options?.sortBy ? cursor.sort(options.sortBy) : cursor).toArray();
|
|
@@ -169,7 +173,7 @@ class MongoRepository {
|
|
|
169
173
|
if (!payload || Object.keys(payload).length === 0) throw new Error("[Mongo Repository] Payload is required for createOne operation");
|
|
170
174
|
const document = this.stampCreate(payload, scope);
|
|
171
175
|
try {
|
|
172
|
-
const db = await this.
|
|
176
|
+
const db = await this.db();
|
|
173
177
|
const collection = db.collection(this.collection);
|
|
174
178
|
const { insertedId } = await collection.insertOne({ ...document, __v: 1 }, { ignoreUndefined: true });
|
|
175
179
|
return { ...document, _id: insertedId, __v: 1 };
|
|
@@ -181,7 +185,7 @@ class MongoRepository {
|
|
|
181
185
|
async createMany({ payload, scope }) {
|
|
182
186
|
const documents = payload.map((item) => this.stampCreate(item, scope));
|
|
183
187
|
try {
|
|
184
|
-
const db = await this.
|
|
188
|
+
const db = await this.db();
|
|
185
189
|
const collection = db.collection(this.collection);
|
|
186
190
|
const { insertedIds } = await collection.insertMany(documents.map((document) => ({ ...document, __v: 1 })), { ignoreUndefined: true });
|
|
187
191
|
return insertedIds;
|
|
@@ -214,7 +218,7 @@ class MongoRepository {
|
|
|
214
218
|
async claimOne({ where, set, scope }) {
|
|
215
219
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
216
220
|
try {
|
|
217
|
-
const db = await this.
|
|
221
|
+
const db = await this.db();
|
|
218
222
|
const collection = db.collection(this.collection);
|
|
219
223
|
const result = await collection.findOneAndUpdate(
|
|
220
224
|
filter,
|
|
@@ -246,7 +250,7 @@ class MongoRepository {
|
|
|
246
250
|
const checkVersion = typeof expectedVersion === "number";
|
|
247
251
|
const filter = this.withScope({ ...where, ...checkVersion ? { __v: expectedVersion } : {}, ...this._where }, scope);
|
|
248
252
|
try {
|
|
249
|
-
const db = await this.
|
|
253
|
+
const db = await this.db();
|
|
250
254
|
const collection = db.collection(this.collection);
|
|
251
255
|
const result = await collection.findOneAndUpdate(
|
|
252
256
|
filter,
|
|
@@ -271,7 +275,7 @@ class MongoRepository {
|
|
|
271
275
|
...scope ? { updatedAt: /* @__PURE__ */ new Date(), ...actor ? { updatedBy: actor } : {} } : {}
|
|
272
276
|
};
|
|
273
277
|
try {
|
|
274
|
-
const db = await this.
|
|
278
|
+
const db = await this.db();
|
|
275
279
|
const collection = db.collection(this.collection);
|
|
276
280
|
const result = await collection.updateMany(
|
|
277
281
|
filter,
|
|
@@ -287,7 +291,7 @@ class MongoRepository {
|
|
|
287
291
|
async deleteOne({ where, scope }) {
|
|
288
292
|
const filter = this.withScope({ ...where }, scope);
|
|
289
293
|
try {
|
|
290
|
-
const db = await this.
|
|
294
|
+
const db = await this.db();
|
|
291
295
|
const collection = db.collection(this.collection);
|
|
292
296
|
const { deletedCount } = await collection.deleteOne(filter);
|
|
293
297
|
return deletedCount;
|
|
@@ -299,7 +303,7 @@ class MongoRepository {
|
|
|
299
303
|
async deleteMany({ where, scope }) {
|
|
300
304
|
const filter = this.withScope({ ...where }, scope);
|
|
301
305
|
try {
|
|
302
|
-
const db = await this.
|
|
306
|
+
const db = await this.db();
|
|
303
307
|
const collection = db.collection(this.collection);
|
|
304
308
|
const { deletedCount } = await collection.deleteMany(filter);
|
|
305
309
|
return deletedCount;
|
|
@@ -311,7 +315,7 @@ class MongoRepository {
|
|
|
311
315
|
async count({ where, options, scope }) {
|
|
312
316
|
const filter = this.withScope({ ...where, ...options?.includeDeleted ? {} : this._where }, scope);
|
|
313
317
|
try {
|
|
314
|
-
const db = await this.
|
|
318
|
+
const db = await this.db();
|
|
315
319
|
const collection = db.collection(this.collection);
|
|
316
320
|
const result = await collection.countDocuments(filter);
|
|
317
321
|
return result;
|
|
@@ -324,7 +328,7 @@ class MongoRepository {
|
|
|
324
328
|
const scopeFilter = this.withScope({}, scope);
|
|
325
329
|
const scopedPipeline = Object.keys(scopeFilter).length ? [{ $match: scopeFilter }, ...pipeline] : pipeline;
|
|
326
330
|
try {
|
|
327
|
-
const db = await this.
|
|
331
|
+
const db = await this.db();
|
|
328
332
|
const collection = db.collection(this.collection);
|
|
329
333
|
const result = await collection.aggregate(scopedPipeline).toArray();
|
|
330
334
|
return result;
|
|
@@ -336,7 +340,7 @@ class MongoRepository {
|
|
|
336
340
|
async distinct(field, where, scope) {
|
|
337
341
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
338
342
|
try {
|
|
339
|
-
const db = await this.
|
|
343
|
+
const db = await this.db();
|
|
340
344
|
const collection = db.collection(this.collection);
|
|
341
345
|
const result = await collection.distinct(field, filter);
|
|
342
346
|
return result;
|
|
@@ -15,7 +15,7 @@ class VersionConflictError extends Error {
|
|
|
15
15
|
class MongoRepository {
|
|
16
16
|
database;
|
|
17
17
|
collection;
|
|
18
|
-
|
|
18
|
+
envvar;
|
|
19
19
|
_where = { deletedAt: null, archivedAt: null };
|
|
20
20
|
scoped;
|
|
21
21
|
ownerField;
|
|
@@ -25,14 +25,18 @@ class MongoRepository {
|
|
|
25
25
|
const { database, collection, envvar, scoped = false, ownerField = "ownerId", protectedFields = [] } = props || {};
|
|
26
26
|
if (!database) throw new Error("[Mongo Repository] Database name is required");
|
|
27
27
|
if (!collection) throw new Error("[Mongo Repository] Collection name is required");
|
|
28
|
-
this.
|
|
29
|
-
if (!this.dbClient) throw new Error("[Mongo Repository] Database client not found");
|
|
28
|
+
this.envvar = envvar;
|
|
30
29
|
this.database = database;
|
|
31
30
|
this.collection = collection;
|
|
32
31
|
this.scoped = scoped;
|
|
33
32
|
this.ownerField = ownerField;
|
|
34
33
|
this.protectedFields = [...PROTECTED_FIELDS, ...protectedFields];
|
|
35
34
|
}
|
|
35
|
+
async db() {
|
|
36
|
+
const client = getMongoDBClient(this.envvar);
|
|
37
|
+
if (!client) throw new Error("[Mongo Repository] Database client not found");
|
|
38
|
+
return client.db(typeof this.database === "function" ? this.database() : this.database);
|
|
39
|
+
}
|
|
36
40
|
assertScope(scope) {
|
|
37
41
|
if (!scope && this.scoped) throw new Error(`[Mongo Repository] Scope is required in ${this.collection}`);
|
|
38
42
|
}
|
|
@@ -90,7 +94,7 @@ class MongoRepository {
|
|
|
90
94
|
async findOne({ where, select, options, scope }) {
|
|
91
95
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
92
96
|
try {
|
|
93
|
-
const db = await this.
|
|
97
|
+
const db = await this.db();
|
|
94
98
|
const collection = db.collection(this.collection);
|
|
95
99
|
const result = await collection.findOne(
|
|
96
100
|
filter,
|
|
@@ -117,7 +121,7 @@ class MongoRepository {
|
|
|
117
121
|
async query({ where, select, options, scope }, pageSize, fetchSize) {
|
|
118
122
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
119
123
|
try {
|
|
120
|
-
const db = await this.
|
|
124
|
+
const db = await this.db();
|
|
121
125
|
const collection = db.collection(this.collection);
|
|
122
126
|
const { page = 1 } = options || {};
|
|
123
127
|
const _skip = +page > 0 ? (+page - 1) * pageSize : 0;
|
|
@@ -131,7 +135,7 @@ class MongoRepository {
|
|
|
131
135
|
async findAll({ where, select, options, scope }) {
|
|
132
136
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
133
137
|
try {
|
|
134
|
-
const db = await this.
|
|
138
|
+
const db = await this.db();
|
|
135
139
|
const collection = db.collection(this.collection);
|
|
136
140
|
const cursor = collection.find(filter, { projection: select });
|
|
137
141
|
const result = await (options?.sortBy ? cursor.sort(options.sortBy) : cursor).toArray();
|
|
@@ -145,7 +149,7 @@ class MongoRepository {
|
|
|
145
149
|
if (!payload || Object.keys(payload).length === 0) throw new Error("[Mongo Repository] Payload is required for createOne operation");
|
|
146
150
|
const document = this.stampCreate(payload, scope);
|
|
147
151
|
try {
|
|
148
|
-
const db = await this.
|
|
152
|
+
const db = await this.db();
|
|
149
153
|
const collection = db.collection(this.collection);
|
|
150
154
|
const { insertedId } = await collection.insertOne({ ...document, __v: 1 }, { ignoreUndefined: true });
|
|
151
155
|
return { ...document, _id: insertedId, __v: 1 };
|
|
@@ -157,7 +161,7 @@ class MongoRepository {
|
|
|
157
161
|
async createMany({ payload, scope }) {
|
|
158
162
|
const documents = payload.map((item) => this.stampCreate(item, scope));
|
|
159
163
|
try {
|
|
160
|
-
const db = await this.
|
|
164
|
+
const db = await this.db();
|
|
161
165
|
const collection = db.collection(this.collection);
|
|
162
166
|
const { insertedIds } = await collection.insertMany(documents.map((document) => ({ ...document, __v: 1 })), { ignoreUndefined: true });
|
|
163
167
|
return insertedIds;
|
|
@@ -190,7 +194,7 @@ class MongoRepository {
|
|
|
190
194
|
async claimOne({ where, set, scope }) {
|
|
191
195
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
192
196
|
try {
|
|
193
|
-
const db = await this.
|
|
197
|
+
const db = await this.db();
|
|
194
198
|
const collection = db.collection(this.collection);
|
|
195
199
|
const result = await collection.findOneAndUpdate(
|
|
196
200
|
filter,
|
|
@@ -222,7 +226,7 @@ class MongoRepository {
|
|
|
222
226
|
const checkVersion = typeof expectedVersion === "number";
|
|
223
227
|
const filter = this.withScope({ ...where, ...checkVersion ? { __v: expectedVersion } : {}, ...this._where }, scope);
|
|
224
228
|
try {
|
|
225
|
-
const db = await this.
|
|
229
|
+
const db = await this.db();
|
|
226
230
|
const collection = db.collection(this.collection);
|
|
227
231
|
const result = await collection.findOneAndUpdate(
|
|
228
232
|
filter,
|
|
@@ -247,7 +251,7 @@ class MongoRepository {
|
|
|
247
251
|
...scope ? { updatedAt: /* @__PURE__ */ new Date(), ...actor ? { updatedBy: actor } : {} } : {}
|
|
248
252
|
};
|
|
249
253
|
try {
|
|
250
|
-
const db = await this.
|
|
254
|
+
const db = await this.db();
|
|
251
255
|
const collection = db.collection(this.collection);
|
|
252
256
|
const result = await collection.updateMany(
|
|
253
257
|
filter,
|
|
@@ -263,7 +267,7 @@ class MongoRepository {
|
|
|
263
267
|
async deleteOne({ where, scope }) {
|
|
264
268
|
const filter = this.withScope({ ...where }, scope);
|
|
265
269
|
try {
|
|
266
|
-
const db = await this.
|
|
270
|
+
const db = await this.db();
|
|
267
271
|
const collection = db.collection(this.collection);
|
|
268
272
|
const { deletedCount } = await collection.deleteOne(filter);
|
|
269
273
|
return deletedCount;
|
|
@@ -275,7 +279,7 @@ class MongoRepository {
|
|
|
275
279
|
async deleteMany({ where, scope }) {
|
|
276
280
|
const filter = this.withScope({ ...where }, scope);
|
|
277
281
|
try {
|
|
278
|
-
const db = await this.
|
|
282
|
+
const db = await this.db();
|
|
279
283
|
const collection = db.collection(this.collection);
|
|
280
284
|
const { deletedCount } = await collection.deleteMany(filter);
|
|
281
285
|
return deletedCount;
|
|
@@ -287,7 +291,7 @@ class MongoRepository {
|
|
|
287
291
|
async count({ where, options, scope }) {
|
|
288
292
|
const filter = this.withScope({ ...where, ...options?.includeDeleted ? {} : this._where }, scope);
|
|
289
293
|
try {
|
|
290
|
-
const db = await this.
|
|
294
|
+
const db = await this.db();
|
|
291
295
|
const collection = db.collection(this.collection);
|
|
292
296
|
const result = await collection.countDocuments(filter);
|
|
293
297
|
return result;
|
|
@@ -300,7 +304,7 @@ class MongoRepository {
|
|
|
300
304
|
const scopeFilter = this.withScope({}, scope);
|
|
301
305
|
const scopedPipeline = Object.keys(scopeFilter).length ? [{ $match: scopeFilter }, ...pipeline] : pipeline;
|
|
302
306
|
try {
|
|
303
|
-
const db = await this.
|
|
307
|
+
const db = await this.db();
|
|
304
308
|
const collection = db.collection(this.collection);
|
|
305
309
|
const result = await collection.aggregate(scopedPipeline).toArray();
|
|
306
310
|
return result;
|
|
@@ -312,7 +316,7 @@ class MongoRepository {
|
|
|
312
316
|
async distinct(field, where, scope) {
|
|
313
317
|
const filter = this.withScope({ ...where, ...this._where }, scope);
|
|
314
318
|
try {
|
|
315
|
-
const db = await this.
|
|
319
|
+
const db = await this.db();
|
|
316
320
|
const collection = db.collection(this.collection);
|
|
317
321
|
const result = await collection.distinct(field, filter);
|
|
318
322
|
return result;
|
|
@@ -0,0 +1,33 @@
|
|
|
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 config_context_exports = {};
|
|
20
|
+
__export(config_context_exports, {
|
|
21
|
+
getContextConfigs: () => getContextConfigs,
|
|
22
|
+
runWithConfigs: () => runWithConfigs
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(config_context_exports);
|
|
25
|
+
var import_node_async_hooks = require("node:async_hooks");
|
|
26
|
+
const storage = new import_node_async_hooks.AsyncLocalStorage();
|
|
27
|
+
const runWithConfigs = (configs, fn) => storage.run(configs, fn);
|
|
28
|
+
const getContextConfigs = () => storage.getStore();
|
|
29
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
30
|
+
0 && (module.exports = {
|
|
31
|
+
getContextConfigs,
|
|
32
|
+
runWithConfigs
|
|
33
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
const storage = new AsyncLocalStorage();
|
|
3
|
+
const runWithConfigs = (configs, fn) => storage.run(configs, fn);
|
|
4
|
+
const getContextConfigs = () => storage.getStore();
|
|
5
|
+
export {
|
|
6
|
+
getContextConfigs,
|
|
7
|
+
runWithConfigs
|
|
8
|
+
};
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import 'dotenv/config';
|
|
2
2
|
export declare class SecretManager {
|
|
3
3
|
private static instance;
|
|
4
|
-
private
|
|
5
|
-
private
|
|
4
|
+
private envCache;
|
|
5
|
+
private contextCache;
|
|
6
|
+
private cryptrs;
|
|
6
7
|
static getInstance(): SecretManager;
|
|
7
|
-
static encrypt(value: string): string;
|
|
8
|
+
static encrypt(value: string, version?: number): string;
|
|
8
9
|
private constructor();
|
|
10
|
+
private cryptr;
|
|
9
11
|
get(key: string): string;
|
|
12
|
+
private cacheOf;
|
|
10
13
|
private getEnvVar;
|
|
11
|
-
private
|
|
12
|
-
private isStringEncrypted;
|
|
14
|
+
private decrypt;
|
|
13
15
|
private logElapsed;
|
|
14
16
|
}
|
|
15
17
|
export declare const secretManager: SecretManager;
|
|
@@ -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
|
-
|
|
41
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
66
|
+
throw new Error(`[Secret manager] ${envName} environment variable is not set`);
|
|
56
67
|
}
|
|
57
|
-
|
|
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
|
-
|
|
65
|
-
|
|
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
|
|
81
|
+
return cache.get(key);
|
|
68
82
|
}
|
|
69
|
-
const
|
|
70
|
-
const decryptedValue = this.
|
|
71
|
-
|
|
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
|
-
|
|
84
|
-
if (!
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
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
|
-
|
|
7
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
32
|
+
throw new Error(`[Secret manager] ${envName} environment variable is not set`);
|
|
22
33
|
}
|
|
23
|
-
|
|
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
|
-
|
|
31
|
-
|
|
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
|
|
47
|
+
return cache.get(key);
|
|
34
48
|
}
|
|
35
|
-
const
|
|
36
|
-
const decryptedValue = this.
|
|
37
|
-
|
|
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
|
-
|
|
50
|
-
if (!
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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();
|
|
@@ -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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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/configuration.md
CHANGED
|
@@ -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
|
-
|
|
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
|
package/docs/llms.txt
CHANGED
|
@@ -13,7 +13,7 @@ Start with the integration guide, then read only the pages you need. All pages a
|
|
|
13
13
|
## Run an agent
|
|
14
14
|
|
|
15
15
|
- [The Agent](agent.md): options, running a turn, statuses, confirmations, autonomous mode
|
|
16
|
-
- [Configuration](configuration.md): environment variables, default model, timeouts
|
|
16
|
+
- [Configuration](configuration.md): environment variables, encrypted values, several agents in one process, default model, timeouts
|
|
17
17
|
- [Reporting errors](error-reporting.md): `setErrorReporter`, what it receives, what is reported, serverless and moving from `SENTRY_DSN`
|
|
18
18
|
- [Chats](chats.md): the chat record, its title, message source, listing, searching and deleting, and the migration to 0.8.0
|
|
19
19
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Agent } from 'openloops/core'
|
|
2
|
+
import { Logger, runWithConfigs, SecretManager } from 'openloops/common'
|
|
3
|
+
import { CurrentUser } from 'openloops/base'
|
|
4
|
+
import { AgiLoop } from 'openloops/loops'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Serves two agents from the same process. Each one has its own database, its own JWT secret and its own model key, and the
|
|
8
|
+
* values are stored encrypted. Everything inside `runWithConfigs` reads that configuration and never the environment.
|
|
9
|
+
*/
|
|
10
|
+
const agents: Record<string, Record<string, string>> = {
|
|
11
|
+
acme: {
|
|
12
|
+
OPENLOOPS_DB_URI: 'mongodb://localhost:27017',
|
|
13
|
+
OPENLOOPS_DB_NAME: 'agent_acme',
|
|
14
|
+
JWT_SECRET: SecretManager.encrypt('acme-jwt-secret', 1),
|
|
15
|
+
ANTHROPIC_API_KEY: SecretManager.encrypt(process.env.ACME_ANTHROPIC_API_KEY as string, 1),
|
|
16
|
+
},
|
|
17
|
+
globex: {
|
|
18
|
+
OPENLOOPS_DB_URI: 'mongodb://localhost:27017',
|
|
19
|
+
OPENLOOPS_DB_NAME: 'agent_globex',
|
|
20
|
+
JWT_SECRET: SecretManager.encrypt('globex-jwt-secret', 1),
|
|
21
|
+
ANTHROPIC_API_KEY: SecretManager.encrypt(process.env.GLOBEX_ANTHROPIC_API_KEY as string, 1),
|
|
22
|
+
},
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function handleRequest (agentName: string, userId: string, message: string) {
|
|
26
|
+
return runWithConfigs(agents[agentName], async () => {
|
|
27
|
+
const currentUser = await CurrentUser.asyncFromDB(userId)
|
|
28
|
+
|
|
29
|
+
if (!currentUser) throw new Error('[Demo] current user is not defined')
|
|
30
|
+
|
|
31
|
+
const agent = new Agent({ loop: new AgiLoop() })
|
|
32
|
+
|
|
33
|
+
return agent.run({ input: { message }, currentUser })
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function runMultiTenant () {
|
|
38
|
+
const logger = new Logger()
|
|
39
|
+
|
|
40
|
+
try {
|
|
41
|
+
const [acme, globex] = await Promise.all([
|
|
42
|
+
handleRequest('acme', '6ab56894eb20887d1ef7942c', 'hi from acme'),
|
|
43
|
+
handleRequest('globex', '6ab56894eb20887d1ef7942d', 'hi from globex'),
|
|
44
|
+
])
|
|
45
|
+
|
|
46
|
+
logger.info({ acme, globex }, '[Demo] Result')
|
|
47
|
+
} catch (error: any) {
|
|
48
|
+
logger.error(error, '[Demo] Error')
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
runMultiTenant()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openloops",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Open source harness for building multitenant AI agents for your SaaS: a TypeScript runtime with persistence, tools, MCP trust, approvals and autonomous automations",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Jose Barcos",
|