@exulu/backend 1.32.0 → 1.33.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/dist/index.cjs CHANGED
@@ -48,7 +48,7 @@ __export(index_exports, {
48
48
  ExuluUtils: () => ExuluUtils,
49
49
  ExuluVariables: () => ExuluVariables,
50
50
  db: () => db2,
51
- logMetadata: () => logMetadata
51
+ logMetadata: () => logMetadata2
52
52
  });
53
53
  module.exports = __toCommonJS(index_exports);
54
54
  var import_config = require("dotenv/config");
@@ -58,10 +58,10 @@ var import_redis = require("redis");
58
58
 
59
59
  // src/bullmq/server.ts
60
60
  var redisServer = {
61
- host: `${process.env.REDIS_HOST}`,
62
- port: process.env.REDIS_PORT,
61
+ host: process.env.REDIS_HOST ?? "",
62
+ port: process.env.REDIS_PORT ?? "",
63
63
  password: process.env.REDIS_PASSWORD || void 0,
64
- username: process.env.REDIS_USER || void 0
64
+ username: process.env.REDIS_USER || ""
65
65
  };
66
66
 
67
67
  // src/redis/client.ts
@@ -74,7 +74,7 @@ async function redisClient() {
74
74
  if (!client["exulu"]) {
75
75
  try {
76
76
  let url = "";
77
- if (redisServer.username) {
77
+ if (redisServer.password) {
78
78
  url = `redis://${redisServer.username}:${redisServer.password}@${redisServer.host}:${redisServer.port}`;
79
79
  } else {
80
80
  url = `redis://${redisServer.host}:${redisServer.port}`;
@@ -434,7 +434,7 @@ var mapType = (t, type, name, defaultValue, unique) => {
434
434
  if (unique) t.unique(name);
435
435
  return;
436
436
  }
437
- throw new Error("Invalid type: " + type);
437
+ throw new Error("Invalid field type for database: " + type);
438
438
  };
439
439
 
440
440
  // src/registry/utils/sanitize-name.ts
@@ -824,6 +824,10 @@ var agentSessionsSchema = {
824
824
  name: "project",
825
825
  type: "uuid",
826
826
  required: false
827
+ },
828
+ {
829
+ name: "metadata",
830
+ type: "json"
827
831
  }
828
832
  ]
829
833
  };
@@ -1481,11 +1485,11 @@ var bullmq = {
1481
1485
  if (!data.inputs) {
1482
1486
  throw new Error(`Missing property "inputs" in data for job ${id}.`);
1483
1487
  }
1484
- if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function") {
1485
- throw new Error(`Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run" or "eval_function".`);
1488
+ if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function" && data.type !== "source") {
1489
+ throw new Error(`Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run", "eval_function" or "source".`);
1486
1490
  }
1487
- if (!data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length) {
1488
- throw new Error(`Either a workflow, embedder, processor, eval_run or eval_functions must be set for job ${id}.`);
1491
+ if (!data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length && !data.source) {
1492
+ throw new Error(`Either a workflow, embedder, processor, eval_run, eval_functions or source must be set for job ${id}.`);
1489
1493
  }
1490
1494
  }
1491
1495
  };
@@ -1991,6 +1995,7 @@ var handleRBACUpdate = async (db3, entityName, resourceId, rbacData, existingRba
1991
1995
  };
1992
1996
  function createMutations(table, agents, contexts, tools, config) {
1993
1997
  const tableNamePlural = table.name.plural.toLowerCase();
1998
+ const tableNameSingular = table.name.singular.toLowerCase();
1994
1999
  const validateWriteAccess = async (id, context) => {
1995
2000
  try {
1996
2001
  const { db: db3, req, user } = context;
@@ -2302,56 +2307,120 @@ function createMutations(table, agents, contexts, tools, config) {
2302
2307
  return finalizeRequestedFields({ table, requestedFields, agents, contexts, tools, result, user: context.user.id });
2303
2308
  }
2304
2309
  };
2305
- if (table.type === "items" && table.fields.some((field) => field.processor?.execute)) {
2306
- mutations[`${tableNamePlural}ProcessItemField`] = async (_, args, context, info) => {
2310
+ if (table.type === "items") {
2311
+ if (table.fields.some((field) => field.processor?.execute)) {
2312
+ mutations[`${tableNameSingular}ProcessItemField`] = async (_, args, context, info) => {
2313
+ if (!context.user?.super_admin) {
2314
+ throw new Error("You are not authorized to process fields via API, user must be super admin.");
2315
+ }
2316
+ const exists = contexts.find((context2) => context2.id === table.id);
2317
+ if (!exists) {
2318
+ throw new Error(`Context ${table.id} not found.`);
2319
+ }
2320
+ if (!args.field) {
2321
+ throw new Error("Field argument missing, the field argument is required.");
2322
+ }
2323
+ if (!args.item) {
2324
+ throw new Error("Item argument missing, the item argument is required.");
2325
+ }
2326
+ const name = args.field?.replace("_s3key", "");
2327
+ console.log("[EXULU] name", name);
2328
+ console.log("[EXULU] fields", exists.fields.map((field2) => field2.name));
2329
+ const field = exists.fields.find((field2) => field2.name === name);
2330
+ if (!field) {
2331
+ throw new Error(`Field ${name} not found in context ${exists.id}.`);
2332
+ }
2333
+ if (!field.processor) {
2334
+ throw new Error(`Processor not set for field ${args.field} in context ${exists.id}.`);
2335
+ }
2336
+ const { db: db3 } = context;
2337
+ let query = db3.from(tableNamePlural).select("*").where({ id: args.item });
2338
+ query = applyAccessControl(table, context.user, query);
2339
+ const item = await query.first();
2340
+ if (!item) {
2341
+ throw new Error("Item not found, or your user does not have access to it.");
2342
+ }
2343
+ const { job, result } = await exists.processField(
2344
+ "api",
2345
+ context.user.id,
2346
+ context.user.role?.id,
2347
+ {
2348
+ ...item,
2349
+ field: args.field
2350
+ },
2351
+ config
2352
+ );
2353
+ return {
2354
+ message: job ? "Processing job scheduled." : "Item processed successfully.",
2355
+ result,
2356
+ job
2357
+ };
2358
+ };
2359
+ }
2360
+ mutations[`${tableNameSingular}ExecuteSource`] = async (_, args, context, info) => {
2361
+ console.log("[EXULU] Executing source", args);
2307
2362
  if (!context.user?.super_admin) {
2308
- throw new Error("You are not authorized to process fields via API, user must be super admin.");
2363
+ throw new Error("You are not authorized to execute sources via API, user must be super admin.");
2364
+ }
2365
+ if (!args.source) {
2366
+ throw new Error("Source argument missing, the source argument is required.");
2309
2367
  }
2310
2368
  const exists = contexts.find((context2) => context2.id === table.id);
2311
2369
  if (!exists) {
2312
2370
  throw new Error(`Context ${table.id} not found.`);
2313
2371
  }
2314
- if (!args.field) {
2315
- throw new Error("Field argument missing, the field argument is required.");
2316
- }
2317
- if (!args.item) {
2318
- throw new Error("Item argument missing, the item argument is required.");
2372
+ const source = exists.sources.find((source2) => source2.id === args.source);
2373
+ if (!source) {
2374
+ throw new Error(`Source ${args.source} not found in context ${exists.id}.`);
2319
2375
  }
2320
- const name = args.field?.replace("_s3key", "");
2321
- console.log("[EXULU] name", name);
2322
- console.log("[EXULU] fields", exists.fields.map((field2) => field2.name));
2323
- const field = exists.fields.find((field2) => field2.name === name);
2324
- if (!field) {
2325
- throw new Error(`Field ${name} not found in context ${exists.id}.`);
2326
- }
2327
- if (!field.processor) {
2328
- throw new Error(`Processor not set for field ${args.field} in context ${exists.id}.`);
2376
+ if (source?.config?.queue) {
2377
+ console.log("[EXULU] Executing source function in queue mode");
2378
+ const queue = await source.config.queue;
2379
+ if (!queue) {
2380
+ throw new Error(`Queue not found for source ${source.id}.`);
2381
+ }
2382
+ const job = await queue.queue?.add(source.id, {
2383
+ source: source.id,
2384
+ context: exists.id,
2385
+ type: "source",
2386
+ inputs: args.inputs
2387
+ });
2388
+ console.log("[EXULU] Source function job scheduled", job.id);
2389
+ return {
2390
+ message: "Job scheduled for source execution.",
2391
+ jobs: [job?.id],
2392
+ items: []
2393
+ };
2329
2394
  }
2330
- const { db: db3 } = context;
2331
- let query = db3.from(tableNamePlural).select("*").where({ id: args.item });
2332
- query = applyAccessControl(table, context.user, query);
2333
- const item = await query.first();
2334
- if (!item) {
2335
- throw new Error("Item not found, or your user does not have access to it.");
2395
+ console.log("[EXULU] Executing source function directly");
2396
+ const result = await source.execute(args.inputs);
2397
+ let jobs = [];
2398
+ let items = [];
2399
+ for (const item of result) {
2400
+ const { item: createdItem, job } = await exists.createItem(
2401
+ item,
2402
+ config,
2403
+ context.user.id,
2404
+ context.user.role?.id
2405
+ );
2406
+ if (job) {
2407
+ jobs.push(job);
2408
+ console.log(`[EXULU] Scheduled job through source update job for item ${createdItem.id} (Job ID: ${job})`);
2409
+ }
2410
+ if (createdItem.id) {
2411
+ items.push(createdItem.id);
2412
+ console.log(`[EXULU] created item through source update job ${createdItem.id}`);
2413
+ }
2336
2414
  }
2337
- const { job, result } = await exists.processField(
2338
- "api",
2339
- context.user.id,
2340
- context.user.role?.id,
2341
- {
2342
- ...item,
2343
- field: args.field
2344
- },
2345
- config
2346
- );
2347
2415
  return {
2348
- message: job ? "Processing job scheduled." : "Item processed successfully.",
2349
- result,
2350
- job
2416
+ message: "Items created successfully.",
2417
+ jobs,
2418
+ items
2351
2419
  };
2352
- }, mutations[`${tableNamePlural}GenerateChunks`] = async (_, args, context, info) => {
2420
+ };
2421
+ mutations[`${tableNameSingular}GenerateChunks`] = async (_, args, context, info) => {
2353
2422
  if (!context.user?.super_admin) {
2354
- throw new Error("You are not authorized to delete chunks via API, user must be super admin.");
2423
+ throw new Error("You are not authorized to generate chunks via API, user must be super admin.");
2355
2424
  }
2356
2425
  const { db: db3 } = await postgresClient();
2357
2426
  const exists = contexts.find((context2) => context2.id === table.id);
@@ -2396,11 +2465,12 @@ function createMutations(table, agents, contexts, tools, config) {
2396
2465
  }
2397
2466
  }
2398
2467
  return {
2399
- message: "Chunks deleted successfully.",
2468
+ message: "Chunks generated successfully.",
2400
2469
  items: items.length,
2401
2470
  jobs: jobs.slice(0, 100)
2402
2471
  };
2403
- }, mutations[`${tableNamePlural}DeleteChunks`] = async (_, args, context, info) => {
2472
+ };
2473
+ mutations[`${tableNameSingular}DeleteChunks`] = async (_, args, context, info) => {
2404
2474
  if (!context.user?.super_admin) {
2405
2475
  throw new Error("You are not authorized to delete chunks via API, user must be super admin.");
2406
2476
  }
@@ -3372,6 +3442,7 @@ function createSDL(tables, contexts, agents, tools, config, evals, queues2) {
3372
3442
  if (table.type === "items") {
3373
3443
  mutationDefs += `
3374
3444
  ${tableNameSingular}GenerateChunks(where: [Filter${tableNameSingularUpperCaseFirst}]): ${tableNameSingular}GenerateChunksReturnPayload
3445
+ ${tableNameSingular}ExecuteSource(source: ID!, inputs: JSON!): ${tableNameSingular}ExecuteSourceReturnPayload
3375
3446
  ${tableNameSingular}DeleteChunks(where: [Filter${tableNameSingularUpperCaseFirst}]): ${tableNameSingular}DeleteChunksReturnPayload
3376
3447
  `;
3377
3448
  if (processorFields?.length > 0) {
@@ -3386,6 +3457,12 @@ function createSDL(tables, contexts, agents, tools, config, evals, queues2) {
3386
3457
  jobs: [String!]
3387
3458
  }
3388
3459
 
3460
+ type ${tableNameSingular}ExecuteSourceReturnPayload {
3461
+ message: String!
3462
+ jobs: [String!]
3463
+ items: [String!]
3464
+ }
3465
+
3389
3466
  type ${tableNameSingular}ProcessItemFieldReturnPayload {
3390
3467
  message: String!
3391
3468
  result: String!
@@ -3497,7 +3574,7 @@ type PageInfo {
3497
3574
  toolCategories: [String!]!
3498
3575
  `;
3499
3576
  typeDefs += `
3500
- jobs(queue: QueueEnum!, statusses: [JobStateEnum!]): JobPaginationResult
3577
+ jobs(queue: QueueEnum!, statusses: [JobStateEnum!], page: Int, limit: Int): JobPaginationResult
3501
3578
  `;
3502
3579
  resolvers.Query["providers"] = async (_, args, context, info) => {
3503
3580
  const requestedFields = getRequestedFields(info);
@@ -3696,6 +3773,7 @@ type PageInfo {
3696
3773
  if (!client2) {
3697
3774
  throw new Error("Redis client not created properly");
3698
3775
  }
3776
+ console.log("[EXULU] Jobs pagination args", args);
3699
3777
  const {
3700
3778
  jobs,
3701
3779
  count
@@ -3728,25 +3806,46 @@ type PageInfo {
3728
3806
  itemCount: count,
3729
3807
  currentPage: args.page || 1,
3730
3808
  hasPreviousPage: args.page && args.page > 1 ? true : false,
3731
- hasNextPage: args.page && args.page < Math.ceil(jobs.length / (args.limit || 100)) ? true : false
3809
+ hasNextPage: args.page && args.page < Math.ceil(count / (args.limit || 100)) ? true : false
3732
3810
  }
3733
3811
  };
3734
3812
  };
3735
3813
  resolvers.Query["contexts"] = async (_, args, context, info) => {
3736
- const data = contexts.map((context2) => ({
3737
- id: context2.id,
3738
- name: context2.name,
3739
- description: context2.description,
3740
- embedder: context2.embedder?.name || void 0,
3741
- slug: "/contexts/" + context2.id,
3742
- active: context2.active,
3743
- fields: context2.fields.map((field) => {
3814
+ const data = await Promise.all(contexts.map(async (context2) => {
3815
+ const sources = await Promise.all(context2.sources.map(async (source) => {
3816
+ let queueName = void 0;
3817
+ if (source.config) {
3818
+ const config2 = await source.config.queue;
3819
+ queueName = config2?.queue?.name || void 0;
3820
+ }
3744
3821
  return {
3745
- ...field,
3746
- name: sanitizeName(field.name),
3747
- label: field.name?.replace("_s3key", "")
3822
+ id: source.id,
3823
+ name: source.name,
3824
+ description: source.description,
3825
+ config: {
3826
+ schedule: source.config?.schedule,
3827
+ queue: queueName,
3828
+ retries: source.config?.retries,
3829
+ backoff: source.config?.backoff
3830
+ }
3748
3831
  };
3749
- })
3832
+ }));
3833
+ return {
3834
+ id: context2.id,
3835
+ name: context2.name,
3836
+ description: context2.description,
3837
+ embedder: context2.embedder?.name || void 0,
3838
+ slug: "/contexts/" + context2.id,
3839
+ active: context2.active,
3840
+ sources,
3841
+ fields: context2.fields.map((field) => {
3842
+ return {
3843
+ ...field,
3844
+ name: sanitizeName(field.name),
3845
+ label: field.name?.replace("_s3key", "")
3846
+ };
3847
+ })
3848
+ };
3750
3849
  }));
3751
3850
  const requestedFields = getRequestedFields(info);
3752
3851
  return {
@@ -3764,6 +3863,24 @@ type PageInfo {
3764
3863
  if (!data) {
3765
3864
  return null;
3766
3865
  }
3866
+ const sources = await Promise.all(data.sources.map(async (source) => {
3867
+ let queueName = void 0;
3868
+ if (source.config) {
3869
+ const config2 = await source.config.queue;
3870
+ queueName = config2?.queue?.name || void 0;
3871
+ }
3872
+ return {
3873
+ id: source.id,
3874
+ name: source.name,
3875
+ description: source.description,
3876
+ config: {
3877
+ schedule: source.config?.schedule,
3878
+ queue: queueName,
3879
+ retries: source.config?.retries,
3880
+ backoff: source.config?.backoff
3881
+ }
3882
+ };
3883
+ }));
3767
3884
  const clean = {
3768
3885
  id: data.id,
3769
3886
  name: data.name,
@@ -3771,6 +3888,7 @@ type PageInfo {
3771
3888
  embedder: data.embedder?.name || void 0,
3772
3889
  slug: "/contexts/" + data.id,
3773
3890
  active: data.active,
3891
+ sources,
3774
3892
  fields: await Promise.all(data.fields.map(async (field) => {
3775
3893
  const label = field.name?.replace("_s3key", "");
3776
3894
  if (field.type === "file" && !field.name.endsWith("_s3key")) {
@@ -3987,6 +4105,26 @@ type Context {
3987
4105
  active: Boolean
3988
4106
  fields: JSON
3989
4107
  configuration: JSON
4108
+ sources: [ContextSource!]
4109
+ }
4110
+
4111
+ type ContextSource {
4112
+ id: String!
4113
+ name: String!
4114
+ description: String!
4115
+ config: ContextSourceConfig!
4116
+ }
4117
+
4118
+ type ContextSourceConfig {
4119
+ schedule: String
4120
+ queue: String
4121
+ retries: Int
4122
+ backoff: ContextSourceBackoff
4123
+ }
4124
+
4125
+ type ContextSourceBackoff {
4126
+ type: String
4127
+ delay: Int
3990
4128
  }
3991
4129
 
3992
4130
  type RunEvalReturnPayload {
@@ -4079,8 +4217,11 @@ async function getJobsByQueueAndName(queueName, statusses, page, limit) {
4079
4217
  }
4080
4218
  const config = await queue.use();
4081
4219
  const startIndex = (page || 1) - 1;
4082
- const endIndex = startIndex + (limit || 100);
4220
+ const endIndex = startIndex - 1 + (limit || 100);
4221
+ console.log("[EXULU] Jobs pagination startIndex", startIndex);
4222
+ console.log("[EXULU] Jobs pagination endIndex", endIndex);
4083
4223
  const jobs = await config.queue.getJobs(statusses || [], startIndex, endIndex, false);
4224
+ console.log("[EXULU] Jobs pagination jobs", jobs?.length);
4084
4225
  const counts = await config.queue.getJobCounts(...statusses || []);
4085
4226
  let total = 0;
4086
4227
  if (counts) {
@@ -4651,7 +4792,7 @@ function sanitizeToolName(name) {
4651
4792
  }
4652
4793
  return sanitized;
4653
4794
  }
4654
- var convertToolsArrayToObject = (currentTools, allExuluTools, configs, providerapikey, contexts, user, exuluConfig) => {
4795
+ var convertToolsArrayToObject = (currentTools, allExuluTools, configs, providerapikey, contexts, user, exuluConfig, sessionID) => {
4655
4796
  if (!currentTools) return {};
4656
4797
  if (!allExuluTools) return {};
4657
4798
  const sanitizedTools = currentTools ? currentTools.map((tool2) => ({
@@ -4661,101 +4802,109 @@ var convertToolsArrayToObject = (currentTools, allExuluTools, configs, providera
4661
4802
  console.log("[EXULU] Sanitized tools", sanitizedTools.map((x) => x.name + " (" + x.id + ")"));
4662
4803
  return {
4663
4804
  ...sanitizedTools?.reduce(
4664
- (prev, cur) => ({
4665
- ...prev,
4666
- [cur.name]: {
4667
- ...cur.tool,
4668
- async *execute(inputs, options) {
4669
- if (!cur.tool?.execute) {
4670
- console.error("[EXULU] Tool execute function is undefined.", cur.tool);
4671
- throw new Error("Tool execute function is undefined.");
4672
- }
4673
- let config = configs?.find((config2) => config2.id === cur.id);
4674
- if (config) {
4675
- config = await hydrateVariables(config || []);
4676
- }
4677
- let upload = void 0;
4678
- if (exuluConfig?.fileUploads?.s3endpoint && exuluConfig?.fileUploads?.s3key && exuluConfig?.fileUploads?.s3secret && exuluConfig?.fileUploads?.s3Bucket) {
4679
- s3Client2 ??= new import_client_s32.S3Client({
4680
- region: exuluConfig?.fileUploads?.s3region,
4681
- ...exuluConfig?.fileUploads?.s3endpoint && {
4682
- forcePathStyle: true,
4683
- endpoint: exuluConfig?.fileUploads?.s3endpoint
4684
- },
4685
- credentials: {
4686
- accessKeyId: exuluConfig?.fileUploads?.s3key ?? "",
4687
- secretAccessKey: exuluConfig?.fileUploads?.s3secret ?? ""
4688
- }
4689
- });
4690
- upload = async ({
4691
- name,
4692
- data,
4693
- type,
4694
- tags
4695
- }) => {
4696
- const mime = getMimeType(type);
4697
- const prefix = exuluConfig?.fileUploads?.s3prefix ? `${exuluConfig.fileUploads.s3prefix.replace(/\/$/, "")}/` : "";
4698
- const key = `${prefix}${user}/${generateS3Key(name)}${type}`;
4699
- const command = new import_client_s32.PutObjectCommand({
4700
- Bucket: exuluConfig?.fileUploads?.s3Bucket,
4701
- Key: key,
4702
- Body: data,
4703
- ContentType: mime
4805
+ (prev, cur) => {
4806
+ let config = configs?.find((config2) => config2.id === cur.id);
4807
+ const userDefinedConfigDescription = config?.config.find((config2) => config2.name === "description")?.value;
4808
+ const defaultConfigDescription = config?.config.find((config2) => config2.name === "description")?.default;
4809
+ const toolDescription = cur.description;
4810
+ const description = userDefinedConfigDescription || defaultConfigDescription || toolDescription;
4811
+ return {
4812
+ ...prev,
4813
+ [cur.name]: {
4814
+ ...cur.tool,
4815
+ description,
4816
+ async *execute(inputs, options) {
4817
+ if (!cur.tool?.execute) {
4818
+ console.error("[EXULU] Tool execute function is undefined.", cur.tool);
4819
+ throw new Error("Tool execute function is undefined.");
4820
+ }
4821
+ if (config) {
4822
+ config = await hydrateVariables(config || []);
4823
+ }
4824
+ let upload = void 0;
4825
+ if (exuluConfig?.fileUploads?.s3endpoint && exuluConfig?.fileUploads?.s3key && exuluConfig?.fileUploads?.s3secret && exuluConfig?.fileUploads?.s3Bucket) {
4826
+ s3Client2 ??= new import_client_s32.S3Client({
4827
+ region: exuluConfig?.fileUploads?.s3region,
4828
+ ...exuluConfig?.fileUploads?.s3endpoint && {
4829
+ forcePathStyle: true,
4830
+ endpoint: exuluConfig?.fileUploads?.s3endpoint
4831
+ },
4832
+ credentials: {
4833
+ accessKeyId: exuluConfig?.fileUploads?.s3key ?? "",
4834
+ secretAccessKey: exuluConfig?.fileUploads?.s3secret ?? ""
4835
+ }
4704
4836
  });
4705
- try {
4706
- const response2 = await s3Client2.send(command);
4707
- console.log(response2);
4708
- return response2;
4709
- } catch (caught) {
4710
- if (caught instanceof import_client_s32.S3ServiceException && caught.name === "EntityTooLarge") {
4711
- console.error(
4712
- `Error from S3 while uploading object to ${exuluConfig?.fileUploads?.s3Bucket}. The object was too large. To upload objects larger than 5GB, use the S3 console (160GB max) or the multipart upload API (5TB max).`
4713
- );
4714
- } else if (caught instanceof import_client_s32.S3ServiceException) {
4715
- console.error(
4716
- `Error from S3 while uploading object to ${exuluConfig?.fileUploads?.s3Bucket}. ${caught.name}: ${caught.message}`
4717
- );
4718
- } else {
4719
- throw caught;
4837
+ upload = async ({
4838
+ name,
4839
+ data,
4840
+ type,
4841
+ tags
4842
+ }) => {
4843
+ const mime = getMimeType(type);
4844
+ const prefix = exuluConfig?.fileUploads?.s3prefix ? `${exuluConfig.fileUploads.s3prefix.replace(/\/$/, "")}/` : "";
4845
+ const key = `${prefix}${user}/${generateS3Key(name)}${type}`;
4846
+ const command = new import_client_s32.PutObjectCommand({
4847
+ Bucket: exuluConfig?.fileUploads?.s3Bucket,
4848
+ Key: key,
4849
+ Body: data,
4850
+ ContentType: mime
4851
+ });
4852
+ try {
4853
+ const response2 = await s3Client2.send(command);
4854
+ console.log(response2);
4855
+ return response2;
4856
+ } catch (caught) {
4857
+ if (caught instanceof import_client_s32.S3ServiceException && caught.name === "EntityTooLarge") {
4858
+ console.error(
4859
+ `[EXULU] Error from S3 while uploading object to ${exuluConfig?.fileUploads?.s3Bucket}. The object was too large. To upload objects larger than 5GB, use the S3 console (160GB max) or the multipart upload API (5TB max).`
4860
+ );
4861
+ } else if (caught instanceof import_client_s32.S3ServiceException) {
4862
+ console.error(
4863
+ `[EXULU] Error from S3 while uploading object to ${exuluConfig?.fileUploads?.s3Bucket}. ${caught.name}: ${caught.message}`
4864
+ );
4865
+ } else {
4866
+ throw caught;
4867
+ }
4720
4868
  }
4721
- }
4722
- };
4723
- }
4724
- const contextsMap = contexts?.reduce((acc, curr) => {
4725
- acc[curr.id] = curr;
4726
- return acc;
4727
- }, {});
4728
- console.log("[EXULU] Config", config);
4729
- const response = await cur.tool.execute({
4730
- ...inputs,
4731
- // Convert config to object format if a config object
4732
- // is available, after we added the .value property
4733
- // by hydrating it from the variables table.
4734
- providerapikey,
4735
- allExuluTools,
4736
- currentTools,
4737
- user,
4738
- contexts: contextsMap,
4739
- upload,
4740
- config: config ? config.config.reduce((acc, curr) => {
4741
- acc[curr.name] = curr.value;
4869
+ };
4870
+ }
4871
+ const contextsMap = contexts?.reduce((acc, curr) => {
4872
+ acc[curr.id] = curr;
4742
4873
  return acc;
4743
- }, {}) : {}
4744
- }, options);
4745
- await updateStatistic({
4746
- name: "count",
4747
- label: cur.name,
4748
- type: STATISTICS_TYPE_ENUM.TOOL_CALL,
4749
- trigger: "agent",
4750
- count: 1,
4751
- user: user?.id,
4752
- role: user?.role?.id
4753
- });
4754
- yield response;
4755
- return response;
4874
+ }, {});
4875
+ console.log("[EXULU] Config", config);
4876
+ const response = await cur.tool.execute({
4877
+ ...inputs,
4878
+ sessionID,
4879
+ // Convert config to object format if a config object
4880
+ // is available, after we added the .value property
4881
+ // by hydrating it from the variables table.
4882
+ providerapikey,
4883
+ allExuluTools,
4884
+ currentTools,
4885
+ user,
4886
+ contexts: contextsMap,
4887
+ upload,
4888
+ config: config ? config.config.reduce((acc, curr) => {
4889
+ acc[curr.name] = curr.value;
4890
+ return acc;
4891
+ }, {}) : {}
4892
+ }, options);
4893
+ await updateStatistic({
4894
+ name: "count",
4895
+ label: cur.name,
4896
+ type: STATISTICS_TYPE_ENUM.TOOL_CALL,
4897
+ trigger: "agent",
4898
+ count: 1,
4899
+ user: user?.id,
4900
+ role: user?.role?.id
4901
+ });
4902
+ yield response;
4903
+ return response;
4904
+ }
4756
4905
  }
4757
- }
4758
- }),
4906
+ };
4907
+ },
4759
4908
  {}
4760
4909
  )
4761
4910
  // askForConfirmation
@@ -4764,6 +4913,9 @@ var convertToolsArrayToObject = (currentTools, allExuluTools, configs, providera
4764
4913
  var hydrateVariables = async (tool2) => {
4765
4914
  const { db: db3 } = await postgresClient();
4766
4915
  const promises = tool2.config.map(async (toolConfig) => {
4916
+ if (!toolConfig.variable) {
4917
+ return toolConfig;
4918
+ }
4767
4919
  const variableName = toolConfig.variable;
4768
4920
  const variable = await db3.from("variables").where({ name: variableName }).first();
4769
4921
  if (!variable) {
@@ -4776,6 +4928,7 @@ var hydrateVariables = async (tool2) => {
4776
4928
  value = bytes.toString(import_crypto_js2.default.enc.Utf8);
4777
4929
  }
4778
4930
  toolConfig.value = value;
4931
+ return toolConfig;
4779
4932
  });
4780
4933
  await Promise.all(promises);
4781
4934
  console.log("[EXULU] Variable values retrieved and added to tool config.");
@@ -5033,7 +5186,8 @@ var ExuluAgent2 = class {
5033
5186
  providerapikey,
5034
5187
  contexts,
5035
5188
  user,
5036
- exuluConfig
5189
+ exuluConfig,
5190
+ session
5037
5191
  ),
5038
5192
  stopWhen: [(0, import_ai.stepCountIs)(2)]
5039
5193
  });
@@ -5091,7 +5245,8 @@ var ExuluAgent2 = class {
5091
5245
  providerapikey,
5092
5246
  contexts,
5093
5247
  user,
5094
- exuluConfig
5248
+ exuluConfig,
5249
+ session
5095
5250
  ),
5096
5251
  stopWhen: [(0, import_ai.stepCountIs)(2)]
5097
5252
  });
@@ -5204,7 +5359,8 @@ var ExuluAgent2 = class {
5204
5359
  providerapikey,
5205
5360
  contexts,
5206
5361
  user,
5207
- exuluConfig
5362
+ exuluConfig,
5363
+ session
5208
5364
  ),
5209
5365
  onError: (error) => {
5210
5366
  console.error("[EXULU] chat stream error.", error);
@@ -5229,6 +5385,15 @@ var getAgentMessages = async ({ session, user, limit, page }) => {
5229
5385
  const messages = await query;
5230
5386
  return messages;
5231
5387
  };
5388
+ var getSession = async ({ sessionID }) => {
5389
+ const { db: db3 } = await postgresClient();
5390
+ console.log("[EXULU] getting session for session ID: " + sessionID);
5391
+ const session = await db3.from("agent_sessions").where({ id: sessionID }).first();
5392
+ if (!session) {
5393
+ throw new Error("Session not found for session ID: " + sessionID);
5394
+ }
5395
+ return session;
5396
+ };
5232
5397
  var saveChat = async ({ session, user, messages }) => {
5233
5398
  const { db: db3 } = await postgresClient();
5234
5399
  const promises = messages.map((message) => {
@@ -5996,25 +6161,13 @@ var createExpressRoutes = async (app, agents, tools, contexts, config, evals, tr
5996
6161
  import_express3.default.json({ limit: REQUEST_SIZE_LIMIT }),
5997
6162
  (0, import_express5.expressMiddleware)(server, {
5998
6163
  context: async ({ req }) => {
5999
- console.info("[EXULU] Incoming graphql request", {
6000
- message: "Incoming Request",
6001
- method: req.method,
6002
- path: req.path,
6003
- requestId: "req-" + Date.now(),
6004
- ipAddress: req.ip,
6005
- userAgent: req.get("User-Agent"),
6006
- headers: {
6007
- "authorization": req.headers["authorization"],
6008
- "exulu-api-key": req.headers["exulu-api-key"],
6009
- "origin": req.headers["origin"],
6010
- "...": "..."
6011
- }
6012
- });
6013
6164
  const authenticationResult = await requestValidators.authenticate(req);
6014
6165
  if (!authenticationResult.user?.id) {
6166
+ console.error("[EXULU] Authentication failed", authenticationResult);
6015
6167
  throw new Error(authenticationResult.message);
6016
6168
  }
6017
6169
  const { db: db3 } = await postgresClient();
6170
+ console.log("[EXULU] Graphql call");
6018
6171
  return {
6019
6172
  req,
6020
6173
  db: db3,
@@ -6628,7 +6781,7 @@ var import_ai3 = require("ai");
6628
6781
  var import_crypto_js4 = __toESM(require("crypto-js"), 1);
6629
6782
 
6630
6783
  // src/registry/log-metadata.ts
6631
- function logMetadata(id, additionalMetadata) {
6784
+ function logMetadata2(id, additionalMetadata) {
6632
6785
  return {
6633
6786
  __logMetadata: true,
6634
6787
  id,
@@ -6639,16 +6792,6 @@ function logMetadata(id, additionalMetadata) {
6639
6792
  // src/registry/workers.ts
6640
6793
  var redisConnection;
6641
6794
  var createWorkers = async (agents, queues2, config, contexts, evals, tools, tracer) => {
6642
- console.log(`
6643
- \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
6644
- \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
6645
- \u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
6646
- \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
6647
- \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D
6648
- \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D
6649
- Intelligence Management Platform - Workers
6650
-
6651
- `);
6652
6795
  console.log("[EXULU] creating workers for " + queues2?.length + " queues.");
6653
6796
  console.log("[EXULU] queues", queues2.map((q) => q.queue.name));
6654
6797
  if (!redisServer.host || !redisServer.port) {
@@ -6675,7 +6818,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6675
6818
  const worker = new import_bullmq4.Worker(
6676
6819
  `${queue.queue.name}`,
6677
6820
  async (bullmqJob) => {
6678
- console.log("[EXULU] starting execution for job", logMetadata(bullmqJob.name, {
6821
+ console.log("[EXULU] starting execution for job", logMetadata2(bullmqJob.name, {
6679
6822
  name: bullmqJob.name,
6680
6823
  status: await bullmqJob.getState(),
6681
6824
  type: bullmqJob.data.type
@@ -6692,7 +6835,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6692
6835
  try {
6693
6836
  bullmq.validate(bullmqJob.id, data);
6694
6837
  if (data.type === "embedder") {
6695
- console.log("[EXULU] running an embedder job.", logMetadata(bullmqJob.name));
6838
+ console.log("[EXULU] running an embedder job.", logMetadata2(bullmqJob.name));
6696
6839
  const label = `embedder-${bullmqJob.name}`;
6697
6840
  await db3.from("job_results").insert({
6698
6841
  job_id: bullmqJob.id,
@@ -6722,7 +6865,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6722
6865
  };
6723
6866
  }
6724
6867
  if (data.type === "processor") {
6725
- console.log("[EXULU] running a processor job.", logMetadata(bullmqJob.name));
6868
+ console.log("[EXULU] running a processor job.", logMetadata2(bullmqJob.name));
6726
6869
  const label = `processor-${bullmqJob.name}`;
6727
6870
  await db3.from("job_results").insert({
6728
6871
  job_id: bullmqJob.id,
@@ -6769,7 +6912,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6769
6912
  };
6770
6913
  }
6771
6914
  if (data.type === "eval_run") {
6772
- console.log("[EXULU] running an eval run job.", logMetadata(bullmqJob.name));
6915
+ console.log("[EXULU] running an eval run job.", logMetadata2(bullmqJob.name));
6773
6916
  const label = `eval-run-${data.eval_run_id}-${data.test_case_id}`;
6774
6917
  const existingResult = await db3.from("job_results").where({ label }).first();
6775
6918
  if (existingResult) {
@@ -6817,7 +6960,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6817
6960
  resolve(messages2);
6818
6961
  break;
6819
6962
  } catch (error) {
6820
- console.error(`[EXULU] error processing UI messages flow for agent ${agentInstance.name} (${agentInstance.id}).`, logMetadata(bullmqJob.name, {
6963
+ console.error(`[EXULU] error processing UI messages flow for agent ${agentInstance.name} (${agentInstance.id}).`, logMetadata2(bullmqJob.name, {
6821
6964
  error: error instanceof Error ? error.message : String(error)
6822
6965
  }));
6823
6966
  attempts++;
@@ -6876,7 +7019,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6876
7019
  eval_function_id: evalFunction.id,
6877
7020
  result: result2 || 0
6878
7021
  };
6879
- console.log(`[EXULU] eval function ${evalFunction.id} result: ${result2}`, logMetadata(bullmqJob.name, {
7022
+ console.log(`[EXULU] eval function ${evalFunction.id} result: ${result2}`, logMetadata2(bullmqJob.name, {
6880
7023
  result: result2 || 0
6881
7024
  }));
6882
7025
  evalFunctionResults.push(evalFunctionResult);
@@ -6895,7 +7038,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6895
7038
  result: result2 || 0
6896
7039
  };
6897
7040
  evalFunctionResults.push(evalFunctionResult);
6898
- console.log(`[EXULU] eval function ${evalFunction.id} result: ${result2}`, logMetadata(bullmqJob.name, {
7041
+ console.log(`[EXULU] eval function ${evalFunction.id} result: ${result2}`, logMetadata2(bullmqJob.name, {
6899
7042
  result: result2 || 0
6900
7043
  }));
6901
7044
  }
@@ -6922,7 +7065,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6922
7065
  };
6923
7066
  }
6924
7067
  if (data.type === "eval_function") {
6925
- console.log("[EXULU] running an eval function job.", logMetadata(bullmqJob.name));
7068
+ console.log("[EXULU] running an eval function job.", logMetadata2(bullmqJob.name));
6926
7069
  if (data.eval_functions?.length !== 1) {
6927
7070
  throw new Error(`Expected 1 eval function for eval function job, got ${data.eval_functions?.length}.`);
6928
7071
  }
@@ -6968,7 +7111,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6968
7111
  inputMessages,
6969
7112
  evalFunction.config || {}
6970
7113
  );
6971
- console.log(`[EXULU] eval function ${evalFunction.id} result: ${result}`, logMetadata(bullmqJob.name, {
7114
+ console.log(`[EXULU] eval function ${evalFunction.id} result: ${result}`, logMetadata2(bullmqJob.name, {
6972
7115
  result: result || 0
6973
7116
  }));
6974
7117
  }
@@ -6978,7 +7121,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
6978
7121
  };
6979
7122
  }
6980
7123
  if (data.type === "source") {
6981
- console.log("[EXULU] running a source job.", logMetadata(bullmqJob.name));
7124
+ console.log("[EXULU] running a source job.", logMetadata2(bullmqJob.name));
6982
7125
  if (!data.source) {
6983
7126
  throw new Error(`No source id set for source job.`);
6984
7127
  }
@@ -7000,14 +7143,14 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
7000
7143
  const { item: createdItem, job } = await context.createItem(item, config, data.user, data.role);
7001
7144
  if (job) {
7002
7145
  jobs.push(job);
7003
- console.log(`[EXULU] Scheduled job through source update job for item ${createdItem.id} (Job ID: ${job})`, logMetadata(bullmqJob.name, {
7146
+ console.log(`[EXULU] Scheduled job through source update job for item ${createdItem.id} (Job ID: ${job})`, logMetadata2(bullmqJob.name, {
7004
7147
  item: createdItem,
7005
7148
  job
7006
7149
  }));
7007
7150
  }
7008
7151
  if (createdItem.id) {
7009
7152
  items.push(createdItem.id);
7010
- console.log(`[EXULU] created item through source update job ${createdItem.id}`, logMetadata(bullmqJob.name, {
7153
+ console.log(`[EXULU] created item through source update job ${createdItem.id}`, logMetadata2(bullmqJob.name, {
7011
7154
  item: createdItem
7012
7155
  }));
7013
7156
  }
@@ -7042,7 +7185,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
7042
7185
  }
7043
7186
  );
7044
7187
  worker.on("completed", async (job, returnvalue) => {
7045
- console.log(`[EXULU] completed job ${job.id}.`, logMetadata(job.name, {
7188
+ console.log(`[EXULU] completed job ${job.id}.`, logMetadata2(job.name, {
7046
7189
  result: returnvalue
7047
7190
  }));
7048
7191
  const { db: db3 } = await postgresClient();
@@ -7062,7 +7205,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
7062
7205
  });
7063
7206
  return;
7064
7207
  }
7065
- console.error(`[EXULU] job failed.`, job?.name ? logMetadata(job.name, {
7208
+ console.error(`[EXULU] job failed.`, job?.name ? logMetadata2(job.name, {
7066
7209
  error: error instanceof Error ? error.message : String(error)
7067
7210
  }) : error);
7068
7211
  });
@@ -7070,7 +7213,7 @@ var createWorkers = async (agents, queues2, config, contexts, evals, tools, trac
7070
7213
  console.error(`[EXULU] worker error.`, error);
7071
7214
  });
7072
7215
  worker.on("progress", (job, progress) => {
7073
- console.log(`[EXULU] job progress ${job.id}.`, logMetadata(job.name, {
7216
+ console.log(`[EXULU] job progress ${job.id}.`, logMetadata2(job.name, {
7074
7217
  progress
7075
7218
  }));
7076
7219
  });
@@ -8722,6 +8865,280 @@ var mathTools = [
8722
8865
  degreesToRadiansTool
8723
8866
  ];
8724
8867
 
8868
+ // src/templates/tools/todo/todowrite.txt
8869
+ var todowrite_default = `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
8870
+ It also helps the user understand the progress of the task and overall progress of their requests.
8871
+
8872
+ ## When to Use This Tool
8873
+ Use this tool proactively in these scenarios:
8874
+
8875
+ 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
8876
+ 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
8877
+ 3. User explicitly requests todo list - When the user directly asks you to use the todo list
8878
+ 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
8879
+ 5. After receiving new instructions - Immediately capture user requirements as todos. Feel free to edit the todo list based on new information.
8880
+ 6. After completing a task - Mark it complete and add any new follow-up tasks
8881
+ 7. When you start working on a new task, mark the todo as in_progress. Ideally you should only have one todo as in_progress at a time. Complete existing tasks before starting new ones.
8882
+
8883
+ ## When NOT to Use This Tool
8884
+
8885
+ Skip using this tool when:
8886
+ 1. There is only a single, straightforward task
8887
+ 2. The task is trivial and tracking it provides no organizational benefit
8888
+ 3. The task can be completed in less than 3 trivial steps
8889
+ 4. The task is purely conversational or informational
8890
+
8891
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
8892
+
8893
+ ## Examples of When to Use the Todo List
8894
+
8895
+ <example>
8896
+ User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!
8897
+ Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.
8898
+ *Creates todo list with the following items:*
8899
+ 1. Create dark mode toggle component in Settings page
8900
+ 2. Add dark mode state management (context/store)
8901
+ 3. Implement CSS-in-JS styles for dark theme
8902
+ 4. Update existing components to support theme switching
8903
+ 5. Run tests and build process, addressing any failures or errors that occur
8904
+ *Begins working on the first task*
8905
+
8906
+ <reasoning>
8907
+ The assistant used the todo list because:
8908
+ 1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes
8909
+ 2. The user explicitly requested tests and build be run afterward
8910
+ 3. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task
8911
+ </reasoning>
8912
+ </example>
8913
+
8914
+ <example>
8915
+ User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project
8916
+ Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'.
8917
+ *Uses grep or search tools to locate all instances of getCwd in the codebase*
8918
+ Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.
8919
+ *Creates todo list with specific items for each file that needs updating*
8920
+
8921
+ <reasoning>
8922
+ The assistant used the todo list because:
8923
+ 1. First, the assistant searched to understand the scope of the task
8924
+ 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps
8925
+ 3. The todo list helps ensure every instance is tracked and updated systematically
8926
+ 4. This approach prevents missing any occurrences and maintains code consistency
8927
+ </reasoning>
8928
+ </example>
8929
+
8930
+
8931
+ <example>
8932
+ User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
8933
+ Assistant: I'll help implement these features. First, let's add all the features to the todo list.
8934
+ *Creates a todo list breaking down each feature into specific tasks based on the project architecture*
8935
+ Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
8936
+
8937
+ <reasoning>
8938
+ The assistant used the todo list because:
8939
+ 1. The user provided multiple complex features to implement in a comma separated list
8940
+ 2. The todo list helps organize these large features into manageable tasks
8941
+ 3. This approach allows for tracking progress across the entire implementation
8942
+ </reasoning>
8943
+ </example>
8944
+
8945
+ <example>
8946
+ User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
8947
+ Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
8948
+ *Reviews component structure, render patterns, state management, and data fetching*
8949
+ Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
8950
+ *Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
8951
+ Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
8952
+
8953
+ <reasoning>
8954
+ The assistant used the todo list because:
8955
+ 1. First, the assistant examined the codebase to identify specific performance issues
8956
+ 2. Based on this analysis, it identified multiple optimization opportunities
8957
+ 3. Performance optimization is a non-trivial task requiring multiple steps
8958
+ 4. The todo list helps methodically track improvements across different components
8959
+ 5. This systematic approach ensures all performance bottlenecks are addressed
8960
+ </reasoning>
8961
+ </example>
8962
+
8963
+ ## Examples of When NOT to Use the Todo List
8964
+
8965
+ <example>
8966
+ User: How do I print 'Hello World' in Python?
8967
+ Assistant: In Python, you can print "Hello World" with this simple code:
8968
+
8969
+ python
8970
+ print("Hello World")
8971
+
8972
+ This will output the text "Hello World" to the console when executed.</assistant>
8973
+
8974
+ <reasoning>
8975
+ The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
8976
+ </reasoning>
8977
+ </example>
8978
+
8979
+ <example>
8980
+ User: What does the git status command do?
8981
+ Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
8982
+
8983
+ <reasoning>
8984
+ The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
8985
+ </reasoning>
8986
+ </example>
8987
+
8988
+ <example>
8989
+ User: Can you add a comment to the calculateTotal function to explain what it does?
8990
+ Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does.
8991
+ * Uses the Edit tool to add a comment to the calculateTotal function *
8992
+
8993
+ <reasoning>
8994
+ The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.
8995
+ </reasoning>
8996
+ </example>
8997
+
8998
+ <example>
8999
+ User: Run npm install for me and tell me what happens.
9000
+ Assistant: I'll run the npm install command for you.
9001
+
9002
+ *Executes: npm install*
9003
+
9004
+ The command completed successfully. Here's the output:
9005
+ [Output of npm install command]
9006
+
9007
+ All dependencies have been installed according to your package.json file.
9008
+
9009
+ <reasoning>
9010
+ The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.
9011
+ </reasoning>
9012
+ </example>
9013
+
9014
+ ## Task States and Management
9015
+
9016
+ 1. **Task States**: Use these states to track progress:
9017
+ - pending: Task not yet started
9018
+ - in_progress: Currently working on (limit to ONE task at a time)
9019
+ - completed: Task finished successfully
9020
+ - cancelled: Task no longer needed
9021
+
9022
+ 2. **Task Management**:
9023
+ - Update task status in real-time as you work
9024
+ - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
9025
+ - Only have ONE task in_progress at any time
9026
+ - Complete current tasks before starting new ones
9027
+ - Cancel tasks that become irrelevant
9028
+
9029
+ 3. **Task Breakdown**:
9030
+ - Create specific, actionable items
9031
+ - Break complex tasks into smaller, manageable steps
9032
+ - Use clear, descriptive task names
9033
+
9034
+ When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
9035
+ `;
9036
+
9037
+ // src/templates/tools/todo/todoread.txt
9038
+ var todoread_default = `Use this tool to read the current to-do list for the session. This tool should be used proactively and frequently to ensure that you are aware of
9039
+ the status of the current task list. You should make use of this tool as often as possible, especially in the following situations:
9040
+ - At the beginning of conversations to see what's pending
9041
+ - Before starting new tasks to prioritize work
9042
+ - When the user asks about previous tasks or plans
9043
+ - Whenever you're uncertain about what to do next
9044
+ - After completing tasks to update your understanding of remaining work
9045
+ - After every few messages to ensure you're on track
9046
+
9047
+ Usage:
9048
+ - This tool takes in no parameters. So leave the input blank or empty. DO NOT include a dummy object, placeholder string or a key like "input" or "empty". LEAVE IT BLANK.
9049
+ - Returns a list of todo items with their status, priority, and content
9050
+ - Use this information to track progress and plan next steps
9051
+ - If no todos exist yet, an empty list will be returned`;
9052
+
9053
+ // src/templates/tools/todo/todo.ts
9054
+ var import_zod5 = __toESM(require("zod"), 1);
9055
+ var TodoSchema = import_zod5.default.object({
9056
+ content: import_zod5.default.string().describe("Brief description of the task"),
9057
+ status: import_zod5.default.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),
9058
+ priority: import_zod5.default.string().describe("Priority level of the task: high, medium, low"),
9059
+ id: import_zod5.default.string().describe("Unique identifier for the todo item")
9060
+ });
9061
+ var TodoWriteTool = new ExuluTool2({
9062
+ id: "todo_write",
9063
+ name: "Todo Write",
9064
+ description: "Use this tool to write your todo list",
9065
+ type: "function",
9066
+ category: "todo",
9067
+ config: [{
9068
+ name: "description",
9069
+ description: "The description of the todo list, if set overwrites the default description.",
9070
+ default: todowrite_default
9071
+ }],
9072
+ inputSchema: import_zod5.default.object({
9073
+ todos: import_zod5.default.array(TodoSchema).describe("The updated todo list")
9074
+ }),
9075
+ execute: async (inputs) => {
9076
+ const { sessionID, todos, user } = inputs;
9077
+ if (!user) {
9078
+ throw new Error("No authenticated user available, a user is required for the todo write tool, this likely means the tool was called outside a session like in an MCP or API call instead of as part of an authenticated session.");
9079
+ }
9080
+ if (!sessionID) {
9081
+ throw new Error("Session ID is required for the todo write tool, this likely means the tool was called outside a session like in an MCP or API call instead of as part of a conversation.");
9082
+ }
9083
+ const session = await getSession({ sessionID });
9084
+ if (!session?.id) {
9085
+ throw new Error("Session with ID " + sessionID + " not found in the todo write tool.");
9086
+ }
9087
+ const hasAccessToSession = await checkRecordAccess(session, "read", user);
9088
+ if (!hasAccessToSession) {
9089
+ throw new Error("You don't have access to this session " + session.id + ".");
9090
+ }
9091
+ await updateTodos({
9092
+ session,
9093
+ todos
9094
+ });
9095
+ return {
9096
+ result: JSON.stringify(todos, null, 2)
9097
+ };
9098
+ }
9099
+ });
9100
+ var TodoReadTool = new ExuluTool2({
9101
+ id: "todo_read",
9102
+ name: "Todo Read",
9103
+ description: "Use this tool to read your todo list",
9104
+ inputSchema: import_zod5.default.object({}),
9105
+ type: "function",
9106
+ category: "todo",
9107
+ config: [{
9108
+ name: "description",
9109
+ description: "The description of the todo list, if set overwrites the default description.",
9110
+ default: todoread_default
9111
+ }],
9112
+ execute: async (inputs) => {
9113
+ const { sessionID } = inputs;
9114
+ let todos = await getTodos(sessionID);
9115
+ return {
9116
+ result: JSON.stringify(todos, null, 2)
9117
+ };
9118
+ }
9119
+ });
9120
+ async function updateTodos(input) {
9121
+ const metadata = input.session.metadata || {};
9122
+ metadata["todos"] = input.todos;
9123
+ const { db: db3 } = await postgresClient();
9124
+ await db3.from("agent_sessions").where({ id: input.session.id }).update({
9125
+ metadata
9126
+ });
9127
+ return input.session;
9128
+ }
9129
+ async function getTodos(sessionID) {
9130
+ const { db: db3 } = await postgresClient();
9131
+ const session = await db3.from("agent_sessions").where({ id: sessionID }).first();
9132
+ if (!session) {
9133
+ throw new Error("Session not found for session ID: " + sessionID);
9134
+ }
9135
+ return session.metadata?.todos || [];
9136
+ }
9137
+ var todoTools = [
9138
+ TodoWriteTool,
9139
+ TodoReadTool
9140
+ ];
9141
+
8725
9142
  // src/registry/index.ts
8726
9143
  var isDev = process.env.NODE_ENV !== "production";
8727
9144
  var consoleTransport = new import_winston2.default.transports.Console({
@@ -8794,6 +9211,7 @@ var ExuluApp = class {
8794
9211
  this._tools = [
8795
9212
  ...tools ?? [],
8796
9213
  ...mathTools,
9214
+ ...todoTools,
8797
9215
  // Add contexts as tools
8798
9216
  ...Object.values(contexts || {}).map((context) => context.tool())
8799
9217
  // Because agents are stored in the database, we add those as tools
@@ -8905,6 +9323,16 @@ var ExuluApp = class {
8905
9323
  bullmq = {
8906
9324
  workers: {
8907
9325
  create: async (queues2) => {
9326
+ console.log(`
9327
+ \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557
9328
+ \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
9329
+ \u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
9330
+ \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551
9331
+ \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D
9332
+ \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D
9333
+ Intelligence Management Platform - Workers
9334
+
9335
+ `);
8908
9336
  if (!this._config) {
8909
9337
  throw new Error("Config not initialized, make sure to call await ExuluApp.create() first when starting your server.");
8910
9338
  }
@@ -8926,16 +9354,26 @@ var ExuluApp = class {
8926
9354
  if (queues2) {
8927
9355
  filteredQueues = filteredQueues.filter((q) => queues2.includes(q.queue.name));
8928
9356
  }
8929
- const sources = Object.values(this._contexts ?? {}).flatMap((context) => ({
8930
- ...context.sources,
8931
- context: context.id
8932
- }));
9357
+ const contexts = Object.values(this._contexts ?? {});
9358
+ let sources = [];
9359
+ for (const context of contexts) {
9360
+ for (const source of context.sources) {
9361
+ sources.push({
9362
+ ...source,
9363
+ context: context.id
9364
+ });
9365
+ }
9366
+ }
8933
9367
  if (sources.length > 0) {
8934
9368
  console.log("[EXULU] Creating ContextSource schedulers for", sources.length, "sources.");
8935
9369
  for (const source of sources) {
8936
9370
  const queue = await source.config?.queue;
9371
+ if (!queue) {
9372
+ console.warn("[EXULU] No queue configured for source", source.name);
9373
+ continue;
9374
+ }
8937
9375
  if (queue) {
8938
- if (!source.config.schedule) {
9376
+ if (!source.config?.schedule) {
8939
9377
  throw new Error("Schedule is required for source when configuring a queue: " + source.name);
8940
9378
  }
8941
9379
  console.log("[EXULU] Creating ContextSource scheduler for", source.name, "in queue", queue.queue?.name);
@@ -8947,7 +9385,8 @@ var ExuluApp = class {
8947
9385
  data: {
8948
9386
  source: source.id,
8949
9387
  context: source.context,
8950
- type: "source"
9388
+ type: "source",
9389
+ inputs: {}
8951
9390
  },
8952
9391
  opts: {
8953
9392
  backoff: {
@@ -10370,20 +10809,39 @@ var execute = async ({ contexts }) => {
10370
10809
  await up(db3);
10371
10810
  await contextDatabases(contexts);
10372
10811
  console.log("[EXULU] Inserting default user and admin role.");
10373
- const existingRole = await db3.from("roles").where({ name: "admin" }).first();
10374
- let roleId;
10375
- if (!existingRole) {
10376
- console.log("[EXULU] Creating default admin role.");
10812
+ const existingAdminRole = await db3.from("roles").where({ name: "admin" }).first();
10813
+ const existingDefaultRole = await db3.from("roles").where({ name: "default" }).first();
10814
+ let adminRoleId;
10815
+ let defaultRoleId;
10816
+ if (!existingAdminRole) {
10817
+ console.log("[EXULU] Creating admin role.");
10377
10818
  const role = await db3.from("roles").insert({
10378
10819
  name: "admin",
10379
10820
  agents: "write",
10821
+ api: "write",
10380
10822
  workflows: "write",
10381
10823
  variables: "write",
10382
- users: "write"
10824
+ users: "write",
10825
+ evals: "write"
10383
10826
  }).returning("id");
10384
- roleId = role[0].id;
10827
+ adminRoleId = role[0].id;
10385
10828
  } else {
10386
- roleId = existingRole.id;
10829
+ adminRoleId = existingAdminRole.id;
10830
+ }
10831
+ if (!existingDefaultRole) {
10832
+ console.log("[EXULU] Creating default role.");
10833
+ const role = await db3.from("roles").insert({
10834
+ name: "default",
10835
+ agents: "write",
10836
+ api: "read",
10837
+ workflows: "read",
10838
+ variables: "read",
10839
+ users: "read",
10840
+ evals: "read"
10841
+ }).returning("id");
10842
+ defaultRoleId = role[0].id;
10843
+ } else {
10844
+ defaultRoleId = existingDefaultRole.id;
10387
10845
  }
10388
10846
  const existingUser = await db3.from("users").where({ email: "admin@exulu.com" }).first();
10389
10847
  if (!existingUser) {
@@ -10398,7 +10856,7 @@ var execute = async ({ contexts }) => {
10398
10856
  updatedAt: /* @__PURE__ */ new Date(),
10399
10857
  password,
10400
10858
  type: "user",
10401
- role: roleId
10859
+ role: adminRoleId
10402
10860
  });
10403
10861
  }
10404
10862
  const { key } = await generateApiKey("exulu", "api@exulu.com");