@exulu/backend 5.5.1 → 5.6.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
@@ -162,11 +162,11 @@ async function postgresClient() {
162
162
  // Log pool events to help debug connection issues
163
163
  afterCreate: (conn, done) => {
164
164
  console.log("[EXULU] New database connection created");
165
- conn.query("SET statement_timeout = 1800000; SET hnsw.ef_search = 20", (err3) => {
166
- if (err3) {
167
- console.error("[EXULU] Error setting connection parameters:", err3);
165
+ conn.query("SET statement_timeout = 1800000; SET hnsw.ef_search = 20", (err4) => {
166
+ if (err4) {
167
+ console.error("[EXULU] Error setting connection parameters:", err4);
168
168
  }
169
- done(err3, conn);
169
+ done(err4, conn);
170
170
  });
171
171
  }
172
172
  }
@@ -525,7 +525,7 @@ function sanitizeMetadata(metadata) {
525
525
  }
526
526
  return sanitized;
527
527
  }
528
- var import_express, import_client_s3, import_s3_request_presigner, import_client_sts, import_node_crypto, expiresIn, s3Client, getPresignedUrl, addGeneralPrefixToKey, addUserPrefixToKey, addBucketPrefixToKey, uploadFile, listS3ObjectsByPrefix, copyS3Object, getS3ObjectContent, getS3ObjectEtag, getS3ObjectBytes, deleteS3Object, getS3SignedUploadUrl, createUppyRoutes;
528
+ var import_express, import_client_s3, import_s3_request_presigner, import_client_sts, import_node_crypto, expiresIn, s3Client, getPresignedUrl, addGeneralPrefixToKey, addUserPrefixToKey, addBucketPrefixToKey, uploadFile, listS3ObjectsByPrefix, copyS3Object, getS3ObjectContent, getS3ObjectStream, getS3ObjectEtag, getS3ObjectBytes, deleteS3Object, getS3SignedUploadUrl, createUppyRoutes;
529
529
  var init_uppy = __esm({
530
530
  "src/uppy/index.ts"() {
531
531
  "use strict";
@@ -684,6 +684,19 @@ var init_uppy = __esm({
684
684
  }
685
685
  return response.Body.transformToString("utf-8");
686
686
  };
687
+ getS3ObjectStream = async (key, config) => {
688
+ if (!config.fileUploads) {
689
+ throw new Error("File uploads are not configured");
690
+ }
691
+ const client2 = getS3Client(config);
692
+ const bucket = config.fileUploads.s3Bucket;
693
+ const command = new import_client_s3.GetObjectCommand({ Bucket: bucket, Key: key });
694
+ const response = await client2.send(command);
695
+ if (!response.Body) {
696
+ throw new Error(`Empty body for S3 key: ${key}`);
697
+ }
698
+ return response.Body;
699
+ };
687
700
  getS3ObjectEtag = async (key, config) => {
688
701
  if (!config.fileUploads) {
689
702
  throw new Error("File uploads are not configured");
@@ -866,8 +879,8 @@ var init_uppy = __esm({
866
879
  const url = await getPresignedUrl(bucket, key, config);
867
880
  res.setHeader("Access-Control-Allow-Origin", "*");
868
881
  res.json({ url, method: "GET", expiresIn });
869
- } catch (err3) {
870
- next(err3);
882
+ } catch (err4) {
883
+ next(err4);
871
884
  }
872
885
  });
873
886
  app.post("/s3/object", async (req, res) => {
@@ -1135,9 +1148,9 @@ var init_uppy = __esm({
1135
1148
  Metadata: sanitizeMetadata(metadata)
1136
1149
  };
1137
1150
  const command = new import_client_s3.CreateMultipartUploadCommand(params);
1138
- return client2.send(command, (err3, data) => {
1139
- if (err3) {
1140
- next(err3);
1151
+ return client2.send(command, (err4, data) => {
1152
+ if (err4) {
1153
+ next(err4);
1141
1154
  return;
1142
1155
  }
1143
1156
  res.setHeader("Access-Control-Allow-Origin", "*");
@@ -1207,9 +1220,9 @@ var init_uppy = __esm({
1207
1220
  UploadId: uploadId,
1208
1221
  PartNumberMarker: startAt
1209
1222
  }),
1210
- (err3, data) => {
1211
- if (err3) {
1212
- next(err3);
1223
+ (err4, data) => {
1224
+ if (err4) {
1225
+ next(err4);
1213
1226
  return;
1214
1227
  }
1215
1228
  parts.push(...data?.Parts ?? []);
@@ -1251,9 +1264,9 @@ var init_uppy = __esm({
1251
1264
  Parts: parts
1252
1265
  }
1253
1266
  }),
1254
- (err3, data) => {
1255
- if (err3) {
1256
- next(err3);
1267
+ (err4, data) => {
1268
+ if (err4) {
1269
+ next(err4);
1257
1270
  return;
1258
1271
  }
1259
1272
  res.setHeader("Access-Control-Allow-Origin", "*");
@@ -1282,9 +1295,9 @@ var init_uppy = __esm({
1282
1295
  Key: key,
1283
1296
  UploadId: uploadId
1284
1297
  }),
1285
- (err3) => {
1286
- if (err3) {
1287
- next(err3);
1298
+ (err4) => {
1299
+ if (err4) {
1300
+ next(err4);
1288
1301
  return;
1289
1302
  }
1290
1303
  res.json({
@@ -2224,8 +2237,8 @@ var init_supervisor = __esm({
2224
2237
  pollHealth(cfg.host, cfg.port).then(() => "ready"),
2225
2238
  exitPromise.then((code2) => ({ exited: code2 }))
2226
2239
  ]);
2227
- } catch (err3) {
2228
- log2(`Readiness probe failed: ${err3.message}`);
2240
+ } catch (err4) {
2241
+ log2(`Readiness probe failed: ${err4.message}`);
2229
2242
  try {
2230
2243
  internal.child?.kill("SIGTERM");
2231
2244
  } catch {
@@ -2322,9 +2335,9 @@ var init_supervisor = __esm({
2322
2335
  let res;
2323
2336
  try {
2324
2337
  res = await fetch(url, { method: "GET", headers: remote ? authHeaders : {} });
2325
- } catch (err3) {
2338
+ } catch (err4) {
2326
2339
  throw new Error(
2327
- `LiteLLM proxy not reachable at ${url} (is the Exulu server process running?): ${err3.message}`
2340
+ `LiteLLM proxy not reachable at ${url} (is the Exulu server process running?): ${err4.message}`
2328
2341
  );
2329
2342
  }
2330
2343
  if (!res.ok) {
@@ -2499,8 +2512,8 @@ function createTaggedFetch(tags) {
2499
2512
  headers: stripContentLengthHeader(init.headers)
2500
2513
  };
2501
2514
  return globalThis.fetch(input, nextInit);
2502
- } catch (err3) {
2503
- console.warn("[vertex-labels] label injection failed, forwarding unchanged", err3);
2515
+ } catch (err4) {
2516
+ console.warn("[vertex-labels] label injection failed, forwarding unchanged", err4);
2504
2517
  return globalThis.fetch(input, init);
2505
2518
  }
2506
2519
  };
@@ -2620,11 +2633,11 @@ async function tagInfo(names) {
2620
2633
  let json;
2621
2634
  try {
2622
2635
  json = await call("/tag/info", { names });
2623
- } catch (err3) {
2624
- if (err3 instanceof LiteLLMAdminError && /not found/i.test(err3.message)) {
2636
+ } catch (err4) {
2637
+ if (err4 instanceof LiteLLMAdminError && /not found/i.test(err4.message)) {
2625
2638
  return out;
2626
2639
  }
2627
- throw err3;
2640
+ throw err4;
2628
2641
  }
2629
2642
  for (const name of names) {
2630
2643
  const raw = json?.[name];
@@ -2838,8 +2851,8 @@ async function enrichSpendFromActivity(map) {
2838
2851
  map[name].spend = spend;
2839
2852
  }
2840
2853
  }
2841
- } catch (err3) {
2842
- console.warn("[EXULU] enrichSpendFromActivity failed", err3);
2854
+ } catch (err4) {
2855
+ console.warn("[EXULU] enrichSpendFromActivity failed", err4);
2843
2856
  }
2844
2857
  }
2845
2858
  function isEnabled() {
@@ -2925,8 +2938,8 @@ async function getTagBudgetMap() {
2925
2938
  await enrichSpendFromActivity(map);
2926
2939
  tagMapCache = { expiry: Date.now() + TAG_MAP_TTL_MS, map };
2927
2940
  return map;
2928
- } catch (err3) {
2929
- console.warn("[EXULU] getTagBudgetMap failed", err3);
2941
+ } catch (err4) {
2942
+ console.warn("[EXULU] getTagBudgetMap failed", err4);
2930
2943
  return {};
2931
2944
  } finally {
2932
2945
  tagMapInflight = void 0;
@@ -2957,8 +2970,8 @@ async function provisionDefaultUserBudget(userId) {
2957
2970
  budget_duration: g.budget_duration
2958
2971
  });
2959
2972
  provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
2960
- } catch (err3) {
2961
- console.warn("[EXULU] ensureUserBudget failed", err3);
2973
+ } catch (err4) {
2974
+ console.warn("[EXULU] ensureUserBudget failed", err4);
2962
2975
  }
2963
2976
  }
2964
2977
  async function getUserBudgetView(userId) {
@@ -2988,8 +3001,8 @@ async function getUserBudgetView(userId) {
2988
3001
  } : null;
2989
3002
  readCache.set(tag, { expiry: Date.now() + READ_TTL_MS, view });
2990
3003
  return view;
2991
- } catch (err3) {
2992
- console.warn("[EXULU] getUserBudgetView failed", err3);
3004
+ } catch (err4) {
3005
+ console.warn("[EXULU] getUserBudgetView failed", err4);
2993
3006
  return null;
2994
3007
  }
2995
3008
  }
@@ -3028,10 +3041,10 @@ async function resolveEmbedder(input) {
3028
3041
  }
3029
3042
  try {
3030
3043
  await waitForLiteLLMReady();
3031
- } catch (err3) {
3044
+ } catch (err4) {
3032
3045
  throw new ResolveEmbedderError(
3033
3046
  "LITELLM_NOT_READY",
3034
- `LiteLLM is not ready: ${err3.message}`
3047
+ `LiteLLM is not ready: ${err4.message}`
3035
3048
  );
3036
3049
  }
3037
3050
  const { baseUrl, authHeaders } = resolveLiteLLMTarget();
@@ -3585,10 +3598,10 @@ var init_embedder_settings = __esm({
3585
3598
  model: model.trim(),
3586
3599
  queue: typeof queue === "string" && queue.trim() ? queue.trim() : null
3587
3600
  };
3588
- } catch (err3) {
3601
+ } catch (err4) {
3589
3602
  console.warn(
3590
3603
  `[EXULU] Could not read the embedder setting for "${contextId}":`,
3591
- err3.message
3604
+ err4.message
3592
3605
  );
3593
3606
  return null;
3594
3607
  }
@@ -3671,9 +3684,9 @@ var init_hydrate_embedders = __esm({
3671
3684
  }
3672
3685
  try {
3673
3686
  modelInfo(info.databaseModel);
3674
- } catch (err3) {
3687
+ } catch (err4) {
3675
3688
  console.error(
3676
- `[EXULU] Context "${context.id}" has a stored embedder "${info.databaseModel}" that is not a usable embedding model (${err3.message.split("\n")[0]}). Ignoring the override and falling back to the model declared in code${info.codeModel ? ` ("${info.codeModel}")` : " (none)"}.`
3689
+ `[EXULU] Context "${context.id}" has a stored embedder "${info.databaseModel}" that is not a usable embedding model (${err4.message.split("\n")[0]}). Ignoring the override and falling back to the model declared in code${info.codeModel ? ` ("${info.codeModel}")` : " (none)"}.`
3677
3690
  );
3678
3691
  context.embedder = codeEmbedder;
3679
3692
  continue;
@@ -3692,10 +3705,10 @@ var init_hydrate_embedders = __esm({
3692
3705
  }
3693
3706
  }
3694
3707
  context.embedder = { model: info.databaseModel, queue };
3695
- } catch (err3) {
3708
+ } catch (err4) {
3696
3709
  console.error(
3697
3710
  `[EXULU] Could not hydrate the embedder for context "${context.id}":`,
3698
- err3.message
3711
+ err4.message
3699
3712
  );
3700
3713
  }
3701
3714
  }
@@ -4790,7 +4803,7 @@ CREATE TABLE IF NOT EXISTS user_credentials (
4790
4803
  );
4791
4804
  `;
4792
4805
  }
4793
- var agentMessagesSchema, agentSessionsSchema, skillsSchema, variablesSchema, projectsSchema, agentsSchema, modelsSchema, usersSchema, platformConfigurationsSchema, entityTypeSettingsSchema, promptLibrarySchema, promptFavoritesSchema, memoryUsagesSchema, memoryConflictsSchema, memoryJudgementsSchema, memoryConflictScansSchema, contextProjectionsSchema, contextMapTopicsSchema, transcriptionJobsSchema, imageGenerationsSchema, sharedArtifactsSchema, contextPresetsSchema, addCoreFields, otpSendAttemptsSchema, coreSchemas;
4806
+ var agentMessagesSchema, agentSessionsSchema, skillsSchema, variablesSchema, projectsSchema, agentsSchema, modelsSchema, usersSchema, platformConfigurationsSchema, entityTypeSettingsSchema, promptLibrarySchema, promptFavoritesSchema, memoryUsagesSchema, memoryConflictsSchema, memoryJudgementsSchema, memoryConflictScansSchema, contextProjectionsSchema, contextMapTopicsSchema, transcriptionJobsSchema, imageGenerationsSchema, sharedArtifactsSchema, contextPresetsSchema, contextFoldersSchema, addCoreFields, otpSendAttemptsSchema, coreSchemas;
4794
4807
  var init_core_schema = __esm({
4795
4808
  "src/postgres/core-schema.ts"() {
4796
4809
  "use strict";
@@ -5745,6 +5758,58 @@ var init_core_schema = __esm({
5745
5758
  }
5746
5759
  ]
5747
5760
  };
5761
+ contextFoldersSchema = {
5762
+ type: "context_folders",
5763
+ name: {
5764
+ plural: "context_folders",
5765
+ singular: "context_folder"
5766
+ },
5767
+ RBAC: false,
5768
+ apiWrites: "super_admin",
5769
+ fields: [
5770
+ {
5771
+ // `index: true` is advisory here, not a DB index: init-exulu-db.ts's
5772
+ // mapType call for core tables only forwards `unique`, never `index`,
5773
+ // to knex. Kept on the field because it documents intent (and other,
5774
+ // non-core-table callers of mapType do read it) and the schema test
5775
+ // asserts it, but creating this table does not add a Postgres index.
5776
+ name: "name",
5777
+ type: "text",
5778
+ required: true,
5779
+ index: true
5780
+ },
5781
+ {
5782
+ name: "description",
5783
+ type: "text"
5784
+ },
5785
+ {
5786
+ name: "icon",
5787
+ type: "text"
5788
+ },
5789
+ {
5790
+ // `default: 0` is advisory here, not a DB default: map-types.ts's
5791
+ // json/number branches only call `.defaultTo(defaultValue)` when
5792
+ // defaultValue is truthy, and 0 is falsy, so no column default is ever
5793
+ // emitted for this field. New rows rely on the GraphQL input/resolver
5794
+ // defaulting sort_order, not a Postgres-level default.
5795
+ name: "sort_order",
5796
+ type: "number",
5797
+ default: 0
5798
+ },
5799
+ {
5800
+ // Unlike sort_order's `0`, "[]" is a truthy string, so map-types.ts's
5801
+ // json branch does emit `.defaultTo("[]")`: a CreateOne that omits
5802
+ // context_ids stores an empty array instead of NULL. That matters
5803
+ // because the generated GraphQL output type is JSON! (non-null) —
5804
+ // without this default a bare NULL would break context_foldersPagination
5805
+ // for every reader, not just the row that omitted the field.
5806
+ name: "context_ids",
5807
+ type: "json",
5808
+ required: true,
5809
+ default: "[]"
5810
+ }
5811
+ ]
5812
+ };
5748
5813
  addCoreFields = (schema7) => {
5749
5814
  schema7.fields.forEach((field) => {
5750
5815
  if (field.type === "file") {
@@ -5829,6 +5894,7 @@ var init_core_schema = __esm({
5829
5894
  contextProjectionsSchema: () => addCoreFields(contextProjectionsSchema),
5830
5895
  contextMapTopicsSchema: () => addCoreFields(contextMapTopicsSchema),
5831
5896
  contextPresetsSchema: () => addCoreFields(contextPresetsSchema),
5897
+ contextFoldersSchema: () => addCoreFields(contextFoldersSchema),
5832
5898
  sharedArtifactsSchema: () => addCoreFields(sharedArtifactsSchema),
5833
5899
  transcriptionJobsSchema: () => addCoreFields(transcriptionJobsSchema),
5834
5900
  imageGenerationsSchema: () => addCoreFields(imageGenerationsSchema),
@@ -5965,7 +6031,7 @@ var init_embedder_not_configured = __esm({
5965
6031
  this.contextId = contextId;
5966
6032
  }
5967
6033
  };
5968
- isEmbedderNotConfigured = (err3) => !!err3 && err3.name === "ContextEmbedderNotConfiguredError";
6034
+ isEmbedderNotConfigured = (err4) => !!err4 && err4.name === "ContextEmbedderNotConfiguredError";
5969
6035
  }
5970
6036
  });
5971
6037
 
@@ -6006,8 +6072,8 @@ var init_config = __esm({
6006
6072
  description: row.description || ""
6007
6073
  });
6008
6074
  }
6009
- } catch (err3) {
6010
- console.warn("[EXULU] Could not read entity_type_settings:", err3.message);
6075
+ } catch (err4) {
6076
+ console.warn("[EXULU] Could not read entity_type_settings:", err4.message);
6011
6077
  }
6012
6078
  return Array.from(byName.values());
6013
6079
  };
@@ -6036,10 +6102,10 @@ var init_config = __esm({
6036
6102
  if (rows.length) {
6037
6103
  await db2.from("entity_type_settings").insert(rows);
6038
6104
  }
6039
- } catch (err3) {
6105
+ } catch (err4) {
6040
6106
  console.warn(
6041
6107
  "[EXULU] Could not persist entity suggestions:",
6042
- err3.message
6108
+ err4.message
6043
6109
  );
6044
6110
  }
6045
6111
  };
@@ -6059,8 +6125,8 @@ var init_config = __esm({
6059
6125
  }
6060
6126
  }
6061
6127
  return typeof value === "string" && value.trim() ? value.trim() : null;
6062
- } catch (err3) {
6063
- console.warn("[EXULU] Could not read entity model setting:", err3.message);
6128
+ } catch (err4) {
6129
+ console.warn("[EXULU] Could not read entity model setting:", err4.message);
6064
6130
  return null;
6065
6131
  }
6066
6132
  };
@@ -6104,10 +6170,10 @@ async function resolveModel(input) {
6104
6170
  }
6105
6171
  try {
6106
6172
  await waitForLiteLLMReady();
6107
- } catch (err3) {
6173
+ } catch (err4) {
6108
6174
  throw new ResolveModelError(
6109
6175
  "LITELLM_NOT_READY",
6110
- `LiteLLM is not ready: ${err3.message}`
6176
+ `LiteLLM is not ready: ${err4.message}`
6111
6177
  );
6112
6178
  }
6113
6179
  if (user?.id) await provisionDefaultUserBudget(user.id);
@@ -6303,10 +6369,10 @@ ${c.content}`).join("\n\n");
6303
6369
  rbacBypass: true
6304
6370
  });
6305
6371
  languageModel = resolved.languageModel;
6306
- } catch (err3) {
6372
+ } catch (err4) {
6307
6373
  console.error(
6308
6374
  `[EXULU] Entity extraction skipped for context ${context.id}: could not resolve model ${modelId}:`,
6309
- err3.message
6375
+ err4.message
6310
6376
  );
6311
6377
  return empty;
6312
6378
  }
@@ -6371,10 +6437,10 @@ ${c.content}`).join("\n\n");
6371
6437
  });
6372
6438
  }
6373
6439
  }
6374
- } catch (err3) {
6440
+ } catch (err4) {
6375
6441
  console.error(
6376
6442
  `[EXULU] Entity extraction batch failed for context ${context.id} (continuing):`,
6377
- err3.message
6443
+ err4.message
6378
6444
  );
6379
6445
  }
6380
6446
  }
@@ -6763,8 +6829,8 @@ var init_entities = __esm({
6763
6829
  try {
6764
6830
  if (!await chunkEntitiesTableExists(context)) return [];
6765
6831
  return await getEntityIdsForItem(context, itemId);
6766
- } catch (err3) {
6767
- console.error("[EXULU] captureEntitiesBeforeReembed failed (continuing):", err3.message);
6832
+ } catch (err4) {
6833
+ console.error("[EXULU] captureEntitiesBeforeReembed failed (continuing):", err4.message);
6768
6834
  return [];
6769
6835
  }
6770
6836
  };
@@ -6794,10 +6860,10 @@ var init_entities = __esm({
6794
6860
  `[EXULU] Entity ingestion complete for item ${itemId} in context ${context.id}: ${mentions.length} mentions.`
6795
6861
  );
6796
6862
  return mentions.length;
6797
- } catch (err3) {
6863
+ } catch (err4) {
6798
6864
  console.error(
6799
6865
  `[EXULU] Entity ingestion failed for item ${itemId} in context ${context.id} (non-fatal):`,
6800
- err3.message
6866
+ err4.message
6801
6867
  );
6802
6868
  return 0;
6803
6869
  }
@@ -7200,8 +7266,8 @@ var init_vector_search = __esm({
7200
7266
  return { r, score: base + boost };
7201
7267
  }).sort((a, b) => b.score - a.score).map((x) => x.r);
7202
7268
  }
7203
- } catch (err3) {
7204
- console.error("[EXULU] Entity boost step failed (continuing):", err3.message);
7269
+ } catch (err4) {
7270
+ console.error("[EXULU] Entity boost step failed (continuing):", err4.message);
7205
7271
  }
7206
7272
  }
7207
7273
  results = results.slice(0, limit);
@@ -7228,8 +7294,8 @@ var init_vector_search = __esm({
7228
7294
  results = results.map((r) => ({ ...r, chunk_entities: entMap.get(r.chunk_id) || [] }));
7229
7295
  }
7230
7296
  entityInsights = queryEntities.length ? await buildEntityInsights(context, queryEntities, finalIds) : { queryEntities: [] };
7231
- } catch (err3) {
7232
- console.error("[EXULU] Entity insights step failed (continuing):", err3.message);
7297
+ } catch (err4) {
7298
+ console.error("[EXULU] Entity insights step failed (continuing):", err4.message);
7233
7299
  }
7234
7300
  }
7235
7301
  await updateStatistic({
@@ -7394,22 +7460,61 @@ async function maybePruneJobResults(db2) {
7394
7460
  sinceLastPrune = 0;
7395
7461
  pruning = true;
7396
7462
  try {
7397
- const boundary = await db2("job_results").whereIn("state", TERMINAL_JOB_STATES).orderBy("createdAt", "desc").offset(MAX_TERMINAL).limit(1).first();
7463
+ await pruneGenericJobResults(db2);
7464
+ await pruneImportJobResults(db2);
7465
+ } finally {
7466
+ pruning = false;
7467
+ }
7468
+ }
7469
+ function excludeImportType(builder) {
7470
+ return builder.where(function() {
7471
+ this.whereNot({ type: "import" }).orWhereNull("type");
7472
+ });
7473
+ }
7474
+ async function pruneGenericJobResults(db2) {
7475
+ try {
7476
+ const boundary = await excludeImportType(
7477
+ db2("job_results").whereIn("state", TERMINAL_JOB_STATES)
7478
+ ).orderBy("createdAt", "desc").offset(MAX_TERMINAL).limit(1).first();
7398
7479
  if (boundary?.createdAt) {
7399
- const deleted = await db2("job_results").whereIn("state", TERMINAL_JOB_STATES).where("createdAt", "<=", boundary.createdAt).del();
7480
+ const deleted = await excludeImportType(
7481
+ db2("job_results").whereIn("state", TERMINAL_JOB_STATES)
7482
+ ).where("createdAt", "<=", boundary.createdAt).del();
7400
7483
  if (deleted) {
7401
7484
  console.log(
7402
7485
  `[EXULU] pruned ${deleted} terminal job_results rows (cap ${MAX_TERMINAL}).`
7403
7486
  );
7404
7487
  }
7405
7488
  }
7406
- } catch (err3) {
7407
- console.error("[EXULU] job_results prune failed", err3);
7408
- } finally {
7409
- pruning = false;
7489
+ } catch (err4) {
7490
+ console.error("[EXULU] job_results prune failed", err4);
7491
+ }
7492
+ }
7493
+ async function pruneImportJobResults(db2) {
7494
+ if (db2.client?.config?.client !== "pg") return;
7495
+ try {
7496
+ const statePlaceholders = TERMINAL_JOB_STATES.map(() => "?").join(", ");
7497
+ const deleted = await db2("job_results").where({ type: "import" }).whereRaw(
7498
+ `id in (
7499
+ select id from (
7500
+ select id, row_number() over (partition by context order by "createdAt" desc) as rn
7501
+ from job_results
7502
+ where type = 'import' and state in (${statePlaceholders})
7503
+ ) ranked
7504
+ where rn > ?
7505
+ )`,
7506
+ [...TERMINAL_JOB_STATES, MAX_IMPORT_PER_CONTEXT]
7507
+ ).del();
7508
+ if (deleted) {
7509
+ console.log(
7510
+ `[EXULU] pruned ${deleted} terminal import job_results rows (cap ${MAX_IMPORT_PER_CONTEXT}/context).`
7511
+ );
7512
+ }
7513
+ } catch (err4) {
7514
+ console.error("[EXULU] import job_results prune failed", err4);
7410
7515
  }
7411
7516
  }
7412
- var MAX_TERMINAL, PRUNE_EVERY, sinceLastPrune, pruning;
7517
+ var MAX_TERMINAL, PRUNE_EVERY, MAX_IMPORT_PER_CONTEXT, sinceLastPrune, pruning;
7413
7518
  var init_prune_job_results = __esm({
7414
7519
  "ee/queues/prune-job-results.ts"() {
7415
7520
  "use strict";
@@ -7417,6 +7522,7 @@ var init_prune_job_results = __esm({
7417
7522
  init_jobs();
7418
7523
  MAX_TERMINAL = 1e4;
7419
7524
  PRUNE_EVERY = 100;
7525
+ MAX_IMPORT_PER_CONTEXT = 200;
7420
7526
  sinceLastPrune = 0;
7421
7527
  pruning = false;
7422
7528
  }
@@ -7500,8 +7606,8 @@ var init_decorator = __esm({
7500
7606
  metadata: {}
7501
7607
  });
7502
7608
  void maybePruneJobResults(db2);
7503
- } catch (err3) {
7504
- console.error("[EXULU] enqueue job_results insert failed", err3);
7609
+ } catch (err4) {
7610
+ console.error("[EXULU] enqueue job_results insert failed", err4);
7505
7611
  }
7506
7612
  }
7507
7613
  const job = await queue.add(`${embedder || workflow || processor || evaluation}`, jobData, {
@@ -9128,11 +9234,11 @@ var init_session_items_retrieval_tool = __esm({
9128
9234
  limit: 10,
9129
9235
  page: 1
9130
9236
  });
9131
- } catch (err3) {
9132
- if (isEmbedderNotConfigured(err3)) {
9133
- return err3.message;
9237
+ } catch (err4) {
9238
+ if (isEmbedderNotConfigured(err4)) {
9239
+ return err4.message;
9134
9240
  }
9135
- throw err3;
9241
+ throw err4;
9136
9242
  }
9137
9243
  })
9138
9244
  );
@@ -11195,10 +11301,10 @@ var init_os_environ_names = __esm({
11195
11301
  try {
11196
11302
  if (!(0, import_node_fs5.existsSync)(configPath)) return [];
11197
11303
  return parseOsEnvironNames((0, import_node_fs5.readFileSync)(configPath, "utf8"));
11198
- } catch (err3) {
11304
+ } catch (err4) {
11199
11305
  console.warn(
11200
11306
  `[SKILLS] Could not read LiteLLM config at ${configPath} to collect os.environ/ credential names; the skill environment falls back to the static secret inventory.`,
11201
- err3
11307
+ err4
11202
11308
  );
11203
11309
  return [];
11204
11310
  }
@@ -11623,7 +11729,7 @@ var init_tool_call = __esm({
11623
11729
  ctx.tool.id
11624
11730
  );
11625
11731
  }
11626
- const err3 = ctx.error;
11732
+ const err4 = ctx.error;
11627
11733
  return {
11628
11734
  v: 1,
11629
11735
  ts: nowIso(),
@@ -11645,7 +11751,7 @@ var init_tool_call = __esm({
11645
11751
  ...ctx.client ? { client: ctx.client } : {},
11646
11752
  ...credential ? { credential } : {},
11647
11753
  status,
11648
- ...status === "error" ? { error: { name: err3?.name, message: String(err3?.message ?? err3 ?? "unknown error") } } : {},
11754
+ ...status === "error" ? { error: { name: err4?.name, message: String(err4?.message ?? err4 ?? "unknown error") } } : {},
11649
11755
  data,
11650
11756
  durationMs: ctx.durationMs,
11651
11757
  ...Object.keys(truncated).length ? { truncated } : {}
@@ -12042,8 +12148,8 @@ function probeSandboxSupport() {
12042
12148
  child.stderr.on("data", (chunk2) => {
12043
12149
  stderr += chunk2.toString();
12044
12150
  });
12045
- child.on("error", (err3) => {
12046
- resolve8({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
12151
+ child.on("error", (err4) => {
12152
+ resolve8({ canSandbox: false, reason: `bwrap not executable: ${err4.message}` });
12047
12153
  });
12048
12154
  child.on("exit", (code) => {
12049
12155
  if (code === 0) resolve8({ canSandbox: true });
@@ -12118,10 +12224,10 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
12118
12224
  let objects;
12119
12225
  try {
12120
12226
  objects = await listS3ObjectsByPrefix(userPrefix, config);
12121
- } catch (err3) {
12227
+ } catch (err4) {
12122
12228
  console.error(
12123
12229
  `[SKILLS] Failed to list S3 artifacts for session ${sessionId} (user ${userId}); proceeding with empty session dir.`,
12124
- err3
12230
+ err4
12125
12231
  );
12126
12232
  return;
12127
12233
  }
@@ -12148,10 +12254,10 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
12148
12254
  const bytes = await getS3ObjectBytes(obj.key, config);
12149
12255
  await (0, import_promises2.mkdir)((0, import_node_path5.dirname)(localPath), { recursive: true });
12150
12256
  await (0, import_promises2.writeFile)(localPath, bytes);
12151
- } catch (err3) {
12257
+ } catch (err4) {
12152
12258
  console.error(
12153
12259
  `[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
12154
- err3
12260
+ err4
12155
12261
  );
12156
12262
  }
12157
12263
  }
@@ -12181,8 +12287,8 @@ async function resolvePythonVenvPath() {
12181
12287
  try {
12182
12288
  const { getPythonVenvPath: getPythonVenvPath2 } = await Promise.resolve().then(() => (init_python_setup(), python_setup_exports));
12183
12289
  return getPythonVenvPath2();
12184
- } catch (err3) {
12185
- console.warn("[SKILLS] Could not resolve the Python venv for the session sandbox; skill scripts fall back to the system python.", err3);
12290
+ } catch (err4) {
12291
+ console.warn("[SKILLS] Could not resolve the Python venv for the session sandbox; skill scripts fall back to the system python.", err4);
12186
12292
  return void 0;
12187
12293
  }
12188
12294
  }
@@ -12215,8 +12321,8 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent) {
12215
12321
  if (userId && config.fileUploads) {
12216
12322
  try {
12217
12323
  await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, { onlyMissing: true });
12218
- } catch (err3) {
12219
- console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err3);
12324
+ } catch (err4) {
12325
+ console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err4);
12220
12326
  }
12221
12327
  }
12222
12328
  return cached.handle;
@@ -12305,10 +12411,10 @@ Probe error: ${probe.reason ?? "(no detail)"}`
12305
12411
  const loaded = await getAllExuluVariables();
12306
12412
  configuredVariables = loaded.granted;
12307
12413
  withheldNames = loaded.withheldNames;
12308
- } catch (err3) {
12414
+ } catch (err4) {
12309
12415
  console.error(
12310
12416
  `[SKILLS] Failed to load configured variables for session ${sessionId}; bash env will not include them.`,
12311
- err3
12417
+ err4
12312
12418
  );
12313
12419
  }
12314
12420
  const { env: sandboxedExecEnv, strippedSecretNames, grantedNames, skippedNames } = buildSkillEnv({
@@ -12341,10 +12447,10 @@ Probe error: ${probe.reason ?? "(no detail)"}`
12341
12447
  degradedSandbox: useDirectExec
12342
12448
  })
12343
12449
  );
12344
- } catch (err3) {
12450
+ } catch (err4) {
12345
12451
  console.error(
12346
12452
  `[SKILLS] audit: skill-sandbox emit failed for session ${sessionId}; continuing.`,
12347
- err3
12453
+ err4
12348
12454
  );
12349
12455
  }
12350
12456
  }
@@ -12417,17 +12523,17 @@ Probe error: ${probe.reason ?? "(no detail)"}`
12417
12523
  const keyOnly = fullKey.slice(slashIdx + 1);
12418
12524
  try {
12419
12525
  out.url = await getPresignedUrl(bucket, keyOnly, config);
12420
- } catch (err3) {
12526
+ } catch (err4) {
12421
12527
  console.error(
12422
12528
  `[SKILLS] Upload succeeded but presign failed for ${fullKey}; continuing without URL.`,
12423
- err3
12529
+ err4
12424
12530
  );
12425
12531
  }
12426
12532
  }
12427
- } catch (err3) {
12533
+ } catch (err4) {
12428
12534
  console.error(
12429
12535
  `[SKILLS] Failed to upload artifact ${s3Key} for session ${sessionId} (user ${userId}); continuing.`,
12430
- err3
12536
+ err4
12431
12537
  );
12432
12538
  }
12433
12539
  return out;
@@ -12563,10 +12669,10 @@ Probe error: ${probe.reason ?? "(no detail)"}`
12563
12669
  key: persisted.key,
12564
12670
  url: persisted.url
12565
12671
  });
12566
- } catch (err3) {
12672
+ } catch (err4) {
12567
12673
  console.error(
12568
12674
  `[SKILLS] Failed to mirror bash-produced artifact ${path4} to S3; continuing.`,
12569
- err3
12675
+ err4
12570
12676
  );
12571
12677
  }
12572
12678
  }
@@ -12644,10 +12750,10 @@ var init_create_sandbox = __esm({
12644
12750
  try {
12645
12751
  const bytes = import_crypto_js3.default.AES.decrypt(value, process.env.NEXTAUTH_SECRET);
12646
12752
  value = bytes.toString(import_crypto_js3.default.enc.Utf8);
12647
- } catch (err3) {
12753
+ } catch (err4) {
12648
12754
  console.error(
12649
12755
  `[VARIABLES] Failed to decrypt variable "${row.name}"; skipping.`,
12650
- err3
12756
+ err4
12651
12757
  );
12652
12758
  continue;
12653
12759
  }
@@ -12843,8 +12949,8 @@ var init_tool_output_offload = __esm({
12843
12949
  ctx.user?.id
12844
12950
  );
12845
12951
  return name;
12846
- } catch (err3) {
12847
- console.error("[EXULU] Failed to offload oversized tool output to session files.", err3);
12952
+ } catch (err4) {
12953
+ console.error("[EXULU] Failed to offload oversized tool output to session files.", err4);
12848
12954
  return void 0;
12849
12955
  }
12850
12956
  };
@@ -12970,8 +13076,8 @@ var init_session_file_read_tool = __esm({
12970
13076
  offset: start + 1,
12971
13077
  linesReturned
12972
13078
  };
12973
- } catch (err3) {
12974
- return { error: `Failed to read session file "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
13079
+ } catch (err4) {
13080
+ return { error: `Failed to read session file "${safeName}": ${err4 instanceof Error ? err4.message : "unknown error"}` };
12975
13081
  }
12976
13082
  };
12977
13083
  return ExuluTool.internal({
@@ -13015,9 +13121,9 @@ async function convertLegacyOfficeToModern(bytes, ext) {
13015
13121
  ["--headless", "--convert-to", target, inputPath, "--outdir", dir],
13016
13122
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
13017
13123
  );
13018
- } catch (err3) {
13124
+ } catch (err4) {
13019
13125
  throw new Error(
13020
- `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err3 instanceof Error ? err3.message : String(err3))
13126
+ `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err4 instanceof Error ? err4.message : String(err4))
13021
13127
  );
13022
13128
  }
13023
13129
  const outputPath = (0, import_node_path6.join)(dir, `input.${target}`);
@@ -13054,9 +13160,9 @@ async function renderPdfPageToPng(pdf, page, scaleTo) {
13054
13160
  ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, (0, import_node_path6.join)(dir, "page")],
13055
13161
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
13056
13162
  );
13057
- } catch (err3) {
13058
- if (err3?.code === 99) return null;
13059
- throw err3;
13163
+ } catch (err4) {
13164
+ if (err4?.code === 99) return null;
13165
+ throw err4;
13060
13166
  }
13061
13167
  const produced = (await (0, import_promises3.readdir)(dir)).find((f) => f.startsWith("page") && f.endsWith(".png"));
13062
13168
  if (!produced) return null;
@@ -13235,8 +13341,8 @@ ${text.trim()}`).join("\n");
13235
13341
  offset: start + 1,
13236
13342
  linesReturned
13237
13343
  };
13238
- } catch (err3) {
13239
- return { error: `Failed to parse "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
13344
+ } catch (err4) {
13345
+ return { error: `Failed to parse "${safeName}": ${err4 instanceof Error ? err4.message : "unknown error"}` };
13240
13346
  }
13241
13347
  };
13242
13348
  return ExuluTool.internal({
@@ -13293,9 +13399,9 @@ async function getPdfPreviewBytes(opts) {
13293
13399
  `soffice --headless --convert-to pdf "${inputPath}" --outdir "${CACHE_OUT}"`,
13294
13400
  { timeout: 6e4, maxBuffer: 16 * 1024 * 1024 }
13295
13401
  );
13296
- } catch (err3) {
13402
+ } catch (err4) {
13297
13403
  throw new PreviewRenderError(
13298
- `LibreOffice conversion failed for ${sourceKey} (etag ${etag}): ${err3?.stderr ?? err3?.message ?? "unknown error"}`
13404
+ `LibreOffice conversion failed for ${sourceKey} (etag ${etag}): ${err4?.stderr ?? err4?.message ?? "unknown error"}`
13299
13405
  );
13300
13406
  }
13301
13407
  if (!(0, import_node_fs8.existsSync)(outputPath)) {
@@ -13417,8 +13523,8 @@ var init_catalog = __esm({
13417
13523
  const uniqueItems = Array.from(map.values());
13418
13524
  _cache = { expiresAt: Date.now() + CACHE_TTL_MS, items: uniqueItems };
13419
13525
  return uniqueItems;
13420
- } catch (err3) {
13421
- console.error("[EXULU] litellmCatalog: failed to fetch /model/info:", err3);
13526
+ } catch (err4) {
13527
+ console.error("[EXULU] litellmCatalog: failed to fetch /model/info:", err4);
13422
13528
  return [];
13423
13529
  }
13424
13530
  };
@@ -13644,8 +13750,8 @@ var init_view_document_page_tool = __esm({
13644
13750
  page: pageNumber,
13645
13751
  note: "The rendered image follows this tool result as an attached user message \u2014 analyze it there. If no image message follows, the attachment has expired; call this tool again to re-render it."
13646
13752
  };
13647
- } catch (err3) {
13648
- return { error: `Failed to render "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
13753
+ } catch (err4) {
13754
+ return { error: `Failed to render "${safeName}": ${err4 instanceof Error ? err4.message : "unknown error"}` };
13649
13755
  }
13650
13756
  };
13651
13757
  return ExuluTool.internal({
@@ -13825,10 +13931,10 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
13825
13931
  }
13826
13932
  try {
13827
13933
  toolConfig.value = JSON.parse(toolConfig.variable.toString());
13828
- } catch (err3) {
13934
+ } catch (err4) {
13829
13935
  console.warn(
13830
13936
  `[EXULU] Config option "${toolConfig.name}" holds invalid JSON \u2014 falling back to the tool's declared default.`,
13831
- err3
13937
+ err4
13832
13938
  );
13833
13939
  toolConfig.value = void 0;
13834
13940
  }
@@ -13873,10 +13979,10 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
13873
13979
  // skill.sandbox.created event can be joined to the agent that caused it.
13874
13980
  agent ? { id: agent.id, name: agent.name, slug: agent.slug } : void 0
13875
13981
  );
13876
- } catch (err3) {
13982
+ } catch (err4) {
13877
13983
  console.error(
13878
13984
  "[EXULU] Failed to eagerly create shared skill sandbox; outer agent will not have readFile/writeFile available.",
13879
- err3
13985
+ err4
13880
13986
  );
13881
13987
  }
13882
13988
  }
@@ -14443,10 +14549,10 @@ async function resolveReranker(input) {
14443
14549
  }
14444
14550
  try {
14445
14551
  await waitForLiteLLMReady();
14446
- } catch (err3) {
14552
+ } catch (err4) {
14447
14553
  throw new ResolveRerankerError(
14448
14554
  "LITELLM_NOT_READY",
14449
- `LiteLLM is not ready: ${err3.message}`
14555
+ `LiteLLM is not ready: ${err4.message}`
14450
14556
  );
14451
14557
  }
14452
14558
  const { baseUrl, authHeaders } = resolveLiteLLMTarget();
@@ -14513,8 +14619,8 @@ async function resolveReranker(input) {
14513
14619
  }));
14514
14620
  reranked.sort((a, b) => b.rerank_score - a.rerank_score);
14515
14621
  return reranked;
14516
- } catch (err3) {
14517
- console.error("[EXULU] Error reranking:", err3);
14622
+ } catch (err4) {
14623
+ console.error("[EXULU] Error reranking:", err4);
14518
14624
  return [];
14519
14625
  }
14520
14626
  };
@@ -14562,8 +14668,8 @@ function jsonVal(name, schema7, v) {
14562
14668
  if (typeof v === "string" && v.trim().length > 0) {
14563
14669
  try {
14564
14670
  candidate = JSON.parse(v);
14565
- } catch (err3) {
14566
- console.warn(`[EXULU pipeline] config "${name}" is not valid JSON \u2014 using defaults.`, err3);
14671
+ } catch (err4) {
14672
+ console.warn(`[EXULU pipeline] config "${name}" is not valid JSON \u2014 using defaults.`, err4);
14567
14673
  candidate = void 0;
14568
14674
  }
14569
14675
  } else if (typeof v !== "object" || v === null) {
@@ -14576,8 +14682,8 @@ function jsonVal(name, schema7, v) {
14576
14682
  }
14577
14683
  try {
14578
14684
  return schema7.parse(defaultFor(name));
14579
- } catch (err3) {
14580
- console.warn(`[EXULU pipeline] failed to parse fallback for option "${name}" \u2014 falling back to schema.parse(undefined).`, err3);
14685
+ } catch (err4) {
14686
+ console.warn(`[EXULU pipeline] failed to parse fallback for option "${name}" \u2014 falling back to schema.parse(undefined).`, err4);
14581
14687
  try {
14582
14688
  return schema7.parse(void 0);
14583
14689
  } catch {
@@ -15127,10 +15233,10 @@ async function resolveIdentifierPins({
15127
15233
  });
15128
15234
  })
15129
15235
  );
15130
- } catch (err3) {
15236
+ } catch (err4) {
15131
15237
  console.warn(
15132
15238
  `[EXULU pipeline] identifier extraction for "${set.name}" failed \u2014 skipping.`,
15133
- err3
15239
+ err4
15134
15240
  );
15135
15241
  }
15136
15242
  })
@@ -15285,8 +15391,8 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
15285
15391
  enabledContexts,
15286
15392
  routingRules: wantsClassification ? routingRules : [],
15287
15393
  extraInstructions
15288
- }).catch((err3) => {
15289
- console.warn("[EXULU pipeline] merged routing call failed \u2014 falling back to the v1 hops.", err3);
15394
+ }).catch((err4) => {
15395
+ console.warn("[EXULU pipeline] merged routing call failed \u2014 falling back to the v1 hops.", err4);
15290
15396
  return null;
15291
15397
  })
15292
15398
  ) : null;
@@ -15304,7 +15410,7 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
15304
15410
  pageNumber: import_zod14.z.number().int().nullable().optional()
15305
15411
  })
15306
15412
  });
15307
- } catch (err3) {
15413
+ } catch (err4) {
15308
15414
  steps.push({ text: "Doc/page detection failed \u2014 skipping filename and page hints." });
15309
15415
  return {
15310
15416
  output: {
@@ -15328,7 +15434,7 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
15328
15434
  }),
15329
15435
  messages: [{ role: "user", content: question }]
15330
15436
  });
15331
- } catch (err3) {
15437
+ } catch (err4) {
15332
15438
  return { output: { explicitlyRequestedKnowledgeBases: [] } };
15333
15439
  }
15334
15440
  })()
@@ -15370,8 +15476,8 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
15370
15476
  text: totalMatched > 0 ? `User referenced specific document(s); pinning ${totalMatched} file(s): ${matchedNames.join(", ")}` : `User referenced document(s) ${hints.join(", ")} but no matching file was found.`
15371
15477
  });
15372
15478
  }
15373
- } catch (err3) {
15374
- console.warn("[EXULU pipeline] Document reference resolution failed:", err3);
15479
+ } catch (err4) {
15480
+ console.warn("[EXULU pipeline] Document reference resolution failed:", err4);
15375
15481
  steps.push({ text: "Document reference resolution failed \u2014 continuing without file pins." });
15376
15482
  }
15377
15483
  }
@@ -15440,7 +15546,7 @@ ${extraInstructions}
15440
15546
  text: "Classification returned unknown rule \u2014 using implicit all-main rule."
15441
15547
  });
15442
15548
  }
15443
- } catch (err3) {
15549
+ } catch (err4) {
15444
15550
  mainContexts = enabledContexts.map((c) => c.id);
15445
15551
  fallbackContexts = [];
15446
15552
  steps.push({
@@ -15459,8 +15565,8 @@ ${extraInstructions}
15459
15565
  hasExplicitDocAndPage,
15460
15566
  steps
15461
15567
  };
15462
- } catch (err3) {
15463
- console.warn("[EXULU pipeline] runRoutingPhase failed:", err3);
15568
+ } catch (err4) {
15569
+ console.warn("[EXULU pipeline] runRoutingPhase failed:", err4);
15464
15570
  return {
15465
15571
  mainContexts: enabledContexts.map((c) => c.id),
15466
15572
  fallbackContexts: [],
@@ -15922,8 +16028,8 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
15922
16028
  updatedImportantKeyword,
15923
16029
  steps
15924
16030
  };
15925
- } catch (err3) {
15926
- console.warn("[EXULU pipeline] memory phase failed \u2014 continuing without memory.", err3);
16031
+ } catch (err4) {
16032
+ console.warn("[EXULU pipeline] memory phase failed \u2014 continuing without memory.", err4);
15927
16033
  return neutralResult(question, keywords, importantKeyword);
15928
16034
  }
15929
16035
  }
@@ -16225,13 +16331,13 @@ async function searchContexts(opts) {
16225
16331
  return tagContext(await singleSearch({ query: keywordQuery, config: searchConfig, user, role, pinnedItemIds, context: ctx }), ctx);
16226
16332
  }
16227
16333
  return [];
16228
- } catch (err3) {
16229
- if (isEmbedderNotConfigured(err3)) {
16334
+ } catch (err4) {
16335
+ if (isEmbedderNotConfigured(err4)) {
16230
16336
  console.warn(
16231
- `[EXULU pipeline] context "${ctxId}" is not searchable: ${err3.message}`
16337
+ `[EXULU pipeline] context "${ctxId}" is not searchable: ${err4.message}`
16232
16338
  );
16233
16339
  } else {
16234
- console.warn(`[EXULU pipeline] searchContexts failed for context "${ctxId}":`, err3);
16340
+ console.warn(`[EXULU pipeline] searchContexts failed for context "${ctxId}":`, err4);
16235
16341
  }
16236
16342
  return [];
16237
16343
  }
@@ -16384,8 +16490,8 @@ async function rerankResults(opts) {
16384
16490
  duplicateOf.set(a, [...duplicateOf.get(a) ?? [], b]);
16385
16491
  duplicateOf.set(b, [...duplicateOf.get(b) ?? [], a]);
16386
16492
  }
16387
- } catch (err3) {
16388
- console.warn("[EXULU pipeline] near-duplicate lookup failed \u2014 selecting without suppression:", err3);
16493
+ } catch (err4) {
16494
+ console.warn("[EXULU pipeline] near-duplicate lookup failed \u2014 selecting without suppression:", err4);
16389
16495
  duplicateOf = /* @__PURE__ */ new Map();
16390
16496
  }
16391
16497
  }
@@ -16471,15 +16577,15 @@ function makeNearDuplicateFinder(opts) {
16471
16577
  [ids, ids, threshold]
16472
16578
  );
16473
16579
  return (res.rows ?? []).map((r) => [r.a, r.b]);
16474
- } catch (err3) {
16475
- console.warn(`[EXULU pipeline] near-duplicate query failed for "${ctxId}":`, err3);
16580
+ } catch (err4) {
16581
+ console.warn(`[EXULU pipeline] near-duplicate query failed for "${ctxId}":`, err4);
16476
16582
  return [];
16477
16583
  }
16478
16584
  })
16479
16585
  );
16480
16586
  return results.flat();
16481
- } catch (err3) {
16482
- console.warn("[EXULU pipeline] near-duplicate lookup failed to acquire a database connection:", err3);
16587
+ } catch (err4) {
16588
+ console.warn("[EXULU pipeline] near-duplicate lookup failed to acquire a database connection:", err4);
16483
16589
  return [];
16484
16590
  }
16485
16591
  };
@@ -16837,10 +16943,10 @@ function createAgenticRetrievalTool(opts) {
16837
16943
  if (rerankerId && rerankerId !== "none") {
16838
16944
  try {
16839
16945
  reranker = await resolveReranker({ model: rerankerId, user, roleId: role });
16840
- } catch (err3) {
16946
+ } catch (err4) {
16841
16947
  console.warn(
16842
16948
  `[EXULU pipeline] could not resolve reranker "${rerankerId}", continuing without reranking:`,
16843
- err3
16949
+ err4
16844
16950
  );
16845
16951
  }
16846
16952
  }
@@ -16853,10 +16959,10 @@ function createAgenticRetrievalTool(opts) {
16853
16959
  rbacBypass: true
16854
16960
  });
16855
16961
  utilityModel = resolved.languageModel ?? model;
16856
- } catch (err3) {
16962
+ } catch (err4) {
16857
16963
  console.warn(
16858
16964
  `[EXULU pipeline] could not resolve utility model "${cfg.utilityModel}", falling back to agent model:`,
16859
- err3
16965
+ err4
16860
16966
  );
16861
16967
  }
16862
16968
  }
@@ -17196,8 +17302,8 @@ Verified answer:
17196
17302
  }
17197
17303
  yield { result: serializeOutput(result, hideSources) };
17198
17304
  return { result: serializeOutput(result, hideSources) };
17199
- } catch (err3) {
17200
- console.warn("[EXULU pipeline] retrieval pipeline failed:", err3);
17305
+ } catch (err4) {
17306
+ console.warn("[EXULU pipeline] retrieval pipeline failed:", err4);
17201
17307
  result.steps.push({
17202
17308
  stepNumber: 1,
17203
17309
  text: "Retrieval degraded due to an internal error \u2014 returning partial results.",
@@ -17308,11 +17414,11 @@ var describeError = (e) => {
17308
17414
  function logRedisErrors(source, label) {
17309
17415
  let count = 0;
17310
17416
  let lastLoggedAt = 0;
17311
- source.on("error", (err3) => {
17417
+ source.on("error", (err4) => {
17312
17418
  count += 1;
17313
17419
  const now = Date.now();
17314
17420
  if (count === 1 || now - lastLoggedAt >= ERROR_LOG_THROTTLE_MS) {
17315
- errorLog(`${label} connection error (${redisAddress()}): ${describeError(err3)}${count > 1 ? ` (x${count})` : ""}`);
17421
+ errorLog(`${label} connection error (${redisAddress()}): ${describeError(err4)}${count > 1 ? ` (x${count})` : ""}`);
17316
17422
  lastLoggedAt = now;
17317
17423
  }
17318
17424
  });
@@ -17322,8 +17428,8 @@ async function guardRedisStartup(label, run, source) {
17322
17428
  log(`Connecting to Redis (${addr}) for ${label}\u2026`);
17323
17429
  const startedAt = Date.now();
17324
17430
  let lastError;
17325
- const onError = (err3) => {
17326
- lastError = err3;
17431
+ const onError = (err4) => {
17432
+ lastError = err4;
17327
17433
  };
17328
17434
  source?.on("error", onError);
17329
17435
  const watchdog = setInterval(() => {
@@ -17686,7 +17792,8 @@ var import_bullmq_otel = require("bullmq-otel");
17686
17792
  init_entitlements();
17687
17793
  var global_queues = {
17688
17794
  eval_runs: "eval_runs",
17689
- email_intake: "email_intake"
17795
+ email_intake: "email_intake",
17796
+ import: "import"
17690
17797
  };
17691
17798
  var ExuluQueues = class {
17692
17799
  queues;
@@ -17748,10 +17855,10 @@ var ExuluQueues = class {
17748
17855
  logRedisErrors(newQueue, `queue "${name}"`);
17749
17856
  try {
17750
17857
  await guardRedisStartup(`queue "${name}"`, () => newQueue.waitUntilReady(), newQueue);
17751
- } catch (err3) {
17858
+ } catch (err4) {
17752
17859
  void newQueue.close().catch(() => {
17753
17860
  });
17754
- throw err3;
17861
+ throw err4;
17755
17862
  }
17756
17863
  await newQueue.setGlobalConcurrency(queueConcurrency);
17757
17864
  this.queues.push({
@@ -18960,6 +19067,507 @@ async function deleteRoutineRunRow(db2, row, queues2) {
18960
19067
  await db2.from("job_results").where({ id: row.id }).del();
18961
19068
  }
18962
19069
 
19070
+ // ee/queues/import-queue.ts
19071
+ init_cjs_shims();
19072
+ var IMPORT_QUEUE_CONCURRENCY = { worker: 1, queue: 1 };
19073
+ var IMPORT_QUEUE_RATELIMIT = 1;
19074
+ var IMPORT_QUEUE_TIMEOUT_SECONDS = 6 * 3600;
19075
+ function registerImportQueue() {
19076
+ return queues.register(
19077
+ global_queues.import,
19078
+ IMPORT_QUEUE_CONCURRENCY,
19079
+ IMPORT_QUEUE_RATELIMIT,
19080
+ IMPORT_QUEUE_TIMEOUT_SECONDS
19081
+ );
19082
+ }
19083
+
19084
+ // src/exulu/import/start-import.ts
19085
+ init_cjs_shims();
19086
+ var import_node_crypto8 = require("crypto");
19087
+
19088
+ // src/utils/serialize-error.ts
19089
+ init_cjs_shims();
19090
+ var MAX_CAUSE_DEPTH = 3;
19091
+ function serializeError(err4, depth = 0) {
19092
+ if (err4 instanceof Error) {
19093
+ const out = { name: err4.name, message: err4.message };
19094
+ if (err4.stack) out.stack = err4.stack;
19095
+ for (const [key, value] of Object.entries(err4)) {
19096
+ if (key !== "cause") out[key] = value;
19097
+ }
19098
+ const cause = err4.cause;
19099
+ if (cause !== void 0 && depth < MAX_CAUSE_DEPTH) {
19100
+ out.cause = serializeError(cause, depth + 1);
19101
+ }
19102
+ return out;
19103
+ }
19104
+ if (typeof err4 === "string") {
19105
+ return { message: err4 };
19106
+ }
19107
+ if (err4 !== null && typeof err4 === "object") {
19108
+ let message;
19109
+ try {
19110
+ message = JSON.stringify(err4);
19111
+ } catch {
19112
+ message = "[unserializable error object]";
19113
+ }
19114
+ return { ...err4, message };
19115
+ }
19116
+ return { message: String(err4) };
19117
+ }
19118
+
19119
+ // src/exulu/import/rows.ts
19120
+ init_cjs_shims();
19121
+
19122
+ // src/exulu/import/coerce.ts
19123
+ init_cjs_shims();
19124
+ var TEXTUAL = /* @__PURE__ */ new Set(["text", "longText", "shortText", "markdown", "code"]);
19125
+ function err3(raw, code, params) {
19126
+ return { raw, value: null, error: { code, params } };
19127
+ }
19128
+ function coerceValue(field, raw) {
19129
+ const trimmed = raw.trim();
19130
+ if (trimmed === "") {
19131
+ return { raw, value: TEXTUAL.has(field.type) ? "" : null };
19132
+ }
19133
+ switch (field.type) {
19134
+ case "number": {
19135
+ const hasComma = trimmed.includes(",");
19136
+ const hasDot = trimmed.includes(".");
19137
+ if (hasComma && hasDot) return err3(raw, "number");
19138
+ let candidate = trimmed;
19139
+ if (hasComma) {
19140
+ const parts = trimmed.split(",");
19141
+ if (parts.length !== 2 || (parts[1]?.length ?? 0) === 3) return err3(raw, "numberAmbiguous");
19142
+ candidate = parts.join(".");
19143
+ }
19144
+ const n = Number(candidate);
19145
+ if (!Number.isFinite(n)) return err3(raw, "number");
19146
+ return { raw, value: n };
19147
+ }
19148
+ case "boolean": {
19149
+ const v = trimmed.toLowerCase();
19150
+ if (["true", "yes", "ja", "1"].includes(v)) return { raw, value: true };
19151
+ if (["false", "no", "nein", "0"].includes(v)) return { raw, value: false };
19152
+ return err3(raw, "boolean");
19153
+ }
19154
+ case "enum": {
19155
+ const match = (field.enumValues ?? []).find((e) => e.toLowerCase() === trimmed.toLowerCase());
19156
+ if (!match) return err3(raw, "enum", { values: (field.enumValues ?? []).join(", ") });
19157
+ return { raw, value: match };
19158
+ }
19159
+ case "date": {
19160
+ if (/^\d{4}-\d{2}-\d{2}(T[\d:.]+(Z|[+-]\d{2}:?\d{2})?)?$/.test(trimmed)) {
19161
+ return Number.isNaN(Date.parse(trimmed)) ? err3(raw, "date") : { raw, value: trimmed };
19162
+ }
19163
+ if (trimmed.includes("/")) return err3(raw, "date");
19164
+ return Number.isNaN(Date.parse(trimmed)) ? err3(raw, "date") : { raw, value: new Date(trimmed).toISOString() };
19165
+ }
19166
+ case "json": {
19167
+ try {
19168
+ JSON.parse(trimmed);
19169
+ return { raw, value: trimmed };
19170
+ } catch {
19171
+ return err3(raw, "json");
19172
+ }
19173
+ }
19174
+ case "uuid": {
19175
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed) ? { raw, value: trimmed } : err3(raw, "uuid");
19176
+ }
19177
+ default:
19178
+ return { raw, value: raw };
19179
+ }
19180
+ }
19181
+
19182
+ // src/exulu/import/rows.ts
19183
+ function tentativeAction(cells) {
19184
+ const id = cells.id?.value;
19185
+ if (typeof id === "string" && id !== "") return "update";
19186
+ const externalId = cells.external_id?.value;
19187
+ if (typeof externalId === "string" && externalId !== "") return "update";
19188
+ return "create";
19189
+ }
19190
+ function buildRow(index, cells, byIndex, fields) {
19191
+ const byName = new Map(fields.map((f) => [f.name, f]));
19192
+ const rowCells = {};
19193
+ for (let i = 0; i < byIndex.length; i++) {
19194
+ const fieldName = byIndex[i];
19195
+ if (!fieldName) continue;
19196
+ const field = byName.get(fieldName);
19197
+ if (!field) continue;
19198
+ rowCells[fieldName] = coerceValue(field, cells[i] ?? "");
19199
+ }
19200
+ const action = tentativeAction(rowCells);
19201
+ const errors = [];
19202
+ for (const f of fields) {
19203
+ const cell = rowCells[f.name];
19204
+ const mustHaveValue = action === "create" || cell !== void 0;
19205
+ if (f.required && mustHaveValue && (cell === void 0 || cell.raw.trim() === "")) {
19206
+ errors.push(`required:${f.name}`);
19207
+ continue;
19208
+ }
19209
+ if (cell?.error) {
19210
+ errors.push(`${f.name}:${cell.error.code}`);
19211
+ }
19212
+ }
19213
+ return { index, cells: rowCells, errors };
19214
+ }
19215
+ function rowIsValid(row) {
19216
+ return row.errors.length === 0;
19217
+ }
19218
+ function rowAction(row) {
19219
+ const id = row.cells.id?.value;
19220
+ if (typeof id === "string" && id !== "") {
19221
+ return { action: "update", by: "id", key: id };
19222
+ }
19223
+ const externalId = row.cells.external_id?.value;
19224
+ if (typeof externalId === "string" && externalId !== "") {
19225
+ return { action: "update", by: "external_id", key: externalId };
19226
+ }
19227
+ return { action: "create" };
19228
+ }
19229
+ function cellValues(row) {
19230
+ const input = {};
19231
+ for (const [name, cell] of Object.entries(row.cells)) {
19232
+ if (name === "id") continue;
19233
+ if (name === "external_id" && (cell.value == null || cell.value === "")) continue;
19234
+ input[name] = cell.value;
19235
+ }
19236
+ return input;
19237
+ }
19238
+ function asGrantList(value) {
19239
+ return Array.isArray(value) ? value : [];
19240
+ }
19241
+ function rbacGrantsFor(access) {
19242
+ const hasGrants = access.rights_mode === "users" || access.rights_mode === "roles" || access.rights_mode === "teams";
19243
+ if (!hasGrants) return void 0;
19244
+ return {
19245
+ users: asGrantList(access.users),
19246
+ roles: asGrantList(access.roles),
19247
+ teams: asGrantList(access.teams)
19248
+ };
19249
+ }
19250
+ function buildCreateInput(row, access) {
19251
+ const input = cellValues(row);
19252
+ input.rights_mode = access.rights_mode;
19253
+ return input;
19254
+ }
19255
+ function buildUpdateInput(row) {
19256
+ return cellValues(row);
19257
+ }
19258
+
19259
+ // src/exulu/import/worker-deps.ts
19260
+ init_cjs_shims();
19261
+ init_table_names();
19262
+ init_uppy();
19263
+ init_rbac_update();
19264
+ init_jobs();
19265
+ function grantsOf(existing) {
19266
+ const raw = existing.RBAC;
19267
+ return Array.isArray(raw) ? raw : [];
19268
+ }
19269
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19270
+ function isUuid(value) {
19271
+ return UUID_RE.test(value);
19272
+ }
19273
+ function idOf(value) {
19274
+ if (typeof value === "string") return value;
19275
+ if (value != null && typeof value === "object" && "id" in value) {
19276
+ const id = value.id;
19277
+ if (typeof id === "string") return id;
19278
+ if (typeof id === "number") return String(id);
19279
+ }
19280
+ return void 0;
19281
+ }
19282
+ function canWrite(existing, user) {
19283
+ if (user.super_admin === true) return true;
19284
+ if (existing.rights_mode === "public") return true;
19285
+ const isCreator = existing.created_by != null && String(existing.created_by) === String(user.id);
19286
+ if (existing.rights_mode === "private") return isCreator;
19287
+ if (isCreator) return true;
19288
+ if (existing.rights_mode === "users") {
19289
+ return grantsOf(existing).some(
19290
+ (g) => g.access_type === "User" && String(g.user_id) === String(user.id) && g.rights === "write"
19291
+ );
19292
+ }
19293
+ if (existing.rights_mode === "roles") {
19294
+ const roleId = idOf(user.role);
19295
+ if (!roleId) return false;
19296
+ return grantsOf(existing).some(
19297
+ (g) => g.access_type === "Role" && String(g.role_id) === roleId && g.rights === "write"
19298
+ );
19299
+ }
19300
+ if (existing.rights_mode === "teams") {
19301
+ const teamId = idOf(user.team);
19302
+ if (!teamId) return false;
19303
+ return grantsOf(existing).some(
19304
+ (g) => g.access_type === "Team" && String(g.team_id) === teamId && g.rights === "write"
19305
+ );
19306
+ }
19307
+ return false;
19308
+ }
19309
+ async function selectItemsBy(db2, tableName, column, values) {
19310
+ if (values.length === 0) return [];
19311
+ return db2(tableName).select("id", "external_id", "rights_mode", "created_by").whereIn(column, values);
19312
+ }
19313
+ async function lookupExisting(db2, tableName, ids, externalIds) {
19314
+ const [byId, byExternalId] = await Promise.all([
19315
+ selectItemsBy(db2, tableName, "id", ids.filter(isUuid)),
19316
+ selectItemsBy(db2, tableName, "external_id", externalIds)
19317
+ ]);
19318
+ const merged = /* @__PURE__ */ new Map();
19319
+ for (const row of [...byId, ...byExternalId]) merged.set(row.id, row);
19320
+ const rows = [...merged.values()];
19321
+ if (rows.length === 0) return [];
19322
+ const needsGrants = rows.some(
19323
+ (r) => r.rights_mode === "users" || r.rights_mode === "roles" || r.rights_mode === "teams"
19324
+ );
19325
+ if (!needsGrants) {
19326
+ return rows.map((r) => ({ ...r, RBAC: [] }));
19327
+ }
19328
+ const grants = await db2("rbac").select("target_resource_id", "access_type", "user_id", "role_id", "team_id", "rights").where({ entity: tableName }).whereIn(
19329
+ "target_resource_id",
19330
+ rows.map((r) => r.id)
19331
+ );
19332
+ const grantsByItem = /* @__PURE__ */ new Map();
19333
+ for (const g of grants) {
19334
+ const list = grantsByItem.get(g.target_resource_id) ?? [];
19335
+ list.push(g);
19336
+ grantsByItem.set(g.target_resource_id, list);
19337
+ }
19338
+ return rows.map((r) => ({ ...r, RBAC: grantsByItem.get(r.id) ?? [] }));
19339
+ }
19340
+ function parseMetadata(value) {
19341
+ if (value == null) return {};
19342
+ let parsed = value;
19343
+ if (typeof value === "string") {
19344
+ try {
19345
+ parsed = JSON.parse(value);
19346
+ } catch {
19347
+ return {};
19348
+ }
19349
+ }
19350
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
19351
+ }
19352
+ function mergeMetadataRaw(db2, patch) {
19353
+ return db2.raw("coalesce(metadata, '{}'::jsonb) || ?::jsonb", [JSON.stringify(patch)]);
19354
+ }
19355
+ async function writeProgress(db2, jobResultId, m) {
19356
+ await db2("job_results").where({ id: jobResultId }).update({ metadata: mergeMetadataRaw(db2, m) });
19357
+ }
19358
+ async function isCancelRequested(db2, jobResultId) {
19359
+ const row = await db2("job_results").where({ id: jobResultId }).select("metadata").first();
19360
+ return parseMetadata(row?.metadata).cancelRequested === true;
19361
+ }
19362
+ async function finalizeCancelled(db2, jobResultId, result) {
19363
+ await db2("job_results").where({ id: jobResultId }).whereIn("state", [JOB_STATUS_ENUM.active]).update({
19364
+ state: JOB_STATUS_ENUM.cancelled,
19365
+ result: JSON.stringify(result),
19366
+ metadata: mergeMetadataRaw(db2, result)
19367
+ });
19368
+ }
19369
+ async function uploadErrorReport(csv, contextId, jobResultId, config, user) {
19370
+ const buffer = Buffer.from(csv, "utf-8");
19371
+ const fileName = `imports/${contextId}/${jobResultId}-errors.csv`;
19372
+ return uploadFile(buffer, fileName, config, { contentType: "text/csv" }, user, void 0, true);
19373
+ }
19374
+ function buildWorkerDeps(input) {
19375
+ const { db: db2, config, context, contextId, jobResultId, stream, fields, mapping, access, options, user, log: log7 } = input;
19376
+ const tableName = getTableName(contextId);
19377
+ const roleId = idOf(user.role);
19378
+ const generateEmbeddingsOverwrite = options.skipEmbeddings ? false : void 0;
19379
+ const rbac = rbacGrantsFor(access);
19380
+ const total = typeof input.total === "number" && input.total > 0 ? input.total : void 0;
19381
+ return {
19382
+ stream,
19383
+ fields,
19384
+ mapping,
19385
+ access,
19386
+ options,
19387
+ user,
19388
+ log: log7,
19389
+ total,
19390
+ lookupExisting: (ids, externalIds) => lookupExisting(db2, tableName, ids, externalIds),
19391
+ canWrite: (existing) => canWrite(existing, user),
19392
+ createItem: async (itemInput) => {
19393
+ const { RBAC: _droppedRbacColumn, ...columns } = itemInput;
19394
+ const created = await context.createItem(
19395
+ { ...columns, created_by: user.id },
19396
+ config,
19397
+ user.id,
19398
+ roleId,
19399
+ false,
19400
+ generateEmbeddingsOverwrite
19401
+ );
19402
+ const createdId = created?.item?.id;
19403
+ if (rbac && typeof createdId === "string") {
19404
+ await handleRBACUpdate(db2, tableName, createdId, rbac, []);
19405
+ }
19406
+ },
19407
+ // buildUpdateInput (rows.ts) never carries an id/rights_mode/RBAC -- the
19408
+ // target's id is threaded in here, same as the GraphQL updateOne path.
19409
+ // `created_by` is deliberately left untouched on an update.
19410
+ updateItem: async (id, itemInput) => {
19411
+ await context.updateItem({ id, ...itemInput }, config, user.id, roleId, generateEmbeddingsOverwrite);
19412
+ },
19413
+ writeProgress: (m) => writeProgress(db2, jobResultId, m),
19414
+ isCancelRequested: () => isCancelRequested(db2, jobResultId),
19415
+ uploadErrorReport: (csv) => uploadErrorReport(csv, contextId, jobResultId, config, user.id)
19416
+ };
19417
+ }
19418
+
19419
+ // src/exulu/import/start-import.ts
19420
+ function idOrSelf(value) {
19421
+ if (value != null && typeof value === "object" && "id" in value) {
19422
+ return value.id;
19423
+ }
19424
+ return value;
19425
+ }
19426
+ var VALID_RIGHTS_MODES2 = ["private", "users", "roles", "teams", "public"];
19427
+ var StartImportError = class extends Error {
19428
+ constructor(code) {
19429
+ super(code);
19430
+ this.code = code;
19431
+ this.name = "StartImportError";
19432
+ }
19433
+ };
19434
+ async function startImport(deps, args) {
19435
+ const { db: db2, config, queue, user, contextExists, uuid } = deps;
19436
+ if (!contextExists(args.contextId)) {
19437
+ throw new StartImportError("CONTEXT_NOT_FOUND");
19438
+ }
19439
+ if (!VALID_RIGHTS_MODES2.includes(args.access.rights_mode)) {
19440
+ throw new StartImportError("INVALID_RIGHTS_MODE");
19441
+ }
19442
+ const access = {
19443
+ ...args.access,
19444
+ users: asGrantList(args.access.users),
19445
+ roles: asGrantList(args.access.roles),
19446
+ teams: asGrantList(args.access.teams)
19447
+ };
19448
+ if (args.options?.delimiter != null && args.options.delimiter.length !== 1) {
19449
+ throw new StartImportError("INVALID_DELIMITER");
19450
+ }
19451
+ const bucket = args.s3Key.split("/")[0];
19452
+ if (bucket !== config.fileUploads?.s3Bucket) {
19453
+ throw new StartImportError("IMPORT_S3_KEY_OUTSIDE_BUCKET");
19454
+ }
19455
+ const keyWithoutBucket = args.s3Key.split("/").slice(1).join("/");
19456
+ const prefixAllowed = user.type === "api" || user.super_admin === true || !keyWithoutBucket.includes("user_") || keyWithoutBucket.includes(`user_${user.id}/`);
19457
+ if (!prefixAllowed) {
19458
+ throw new StartImportError("IMPORT_S3_KEY_NOT_ALLOWED");
19459
+ }
19460
+ const running = await db2("job_results").where({ context: args.contextId, type: "import" }).whereIn("state", ["waiting", "active"]).first();
19461
+ if (running) {
19462
+ throw new StartImportError("IMPORT_ALREADY_RUNNING");
19463
+ }
19464
+ const id = (uuid ?? import_node_crypto8.randomUUID)();
19465
+ const label = `Import ${args.fileName}`;
19466
+ const userSnapshot = {
19467
+ id: user.id,
19468
+ super_admin: user.super_admin === true,
19469
+ role: idOrSelf(user.role),
19470
+ team: idOrSelf(user.team)
19471
+ };
19472
+ await db2("job_results").insert({
19473
+ id,
19474
+ job_id: id,
19475
+ type: "import",
19476
+ context: args.contextId,
19477
+ label,
19478
+ state: "waiting",
19479
+ trigger: args.trigger,
19480
+ trigger_metadata: JSON.stringify({
19481
+ s3Key: args.s3Key,
19482
+ fileName: args.fileName,
19483
+ mapping: args.mapping,
19484
+ access,
19485
+ options: args.options,
19486
+ user: userSnapshot
19487
+ }),
19488
+ metadata: JSON.stringify({
19489
+ total: args.totalRows ?? 0,
19490
+ processed: 0,
19491
+ created: 0,
19492
+ updated: 0,
19493
+ failed: 0,
19494
+ invalid: 0
19495
+ })
19496
+ });
19497
+ try {
19498
+ await queue.add(
19499
+ "import",
19500
+ {
19501
+ label,
19502
+ type: "import",
19503
+ // BullMqJobData.trigger is a STATISTICS_LABELS value, which has no
19504
+ // "ui" member -- "api" here is just that field's required value for
19505
+ // this queue path, unrelated to the job_results row's own ui|api
19506
+ // `trigger` column above (which records real run provenance).
19507
+ trigger: "api",
19508
+ timeoutInSeconds: 6 * 3600,
19509
+ // Required: bullmq.validate (src/validators/bullmq.ts) throws without
19510
+ // an `inputs` key, even though the import branch ignores it (its
19511
+ // inputs live on the job_results row's trigger_metadata instead).
19512
+ inputs: {},
19513
+ jobResultId: id,
19514
+ context: args.contextId,
19515
+ user: user.id,
19516
+ role: idOrSelf(user.role)
19517
+ },
19518
+ {
19519
+ jobId: id,
19520
+ attempts: 1,
19521
+ removeOnComplete: 5e3,
19522
+ removeOnFail: 5e3
19523
+ }
19524
+ );
19525
+ } catch (error) {
19526
+ await db2("job_results").where({ id }).update({ state: "failed", error: JSON.stringify(serializeError(error)) });
19527
+ throw error;
19528
+ }
19529
+ return { jobResultId: id };
19530
+ }
19531
+ async function cancelImport(deps, jobResultId) {
19532
+ const { db: db2, queue, user } = deps;
19533
+ const row = await db2("job_results").where({ id: jobResultId }).first();
19534
+ if (!row) {
19535
+ throw new StartImportError("IMPORT_NOT_FOUND");
19536
+ }
19537
+ if (row.type !== "import") {
19538
+ throw new StartImportError("IMPORT_NOT_FOUND");
19539
+ }
19540
+ if (row.state !== "waiting" && row.state !== "active") {
19541
+ return { ok: true };
19542
+ }
19543
+ const meta = parseMetadata(row.trigger_metadata);
19544
+ const starterId = idOrSelf(meta.user);
19545
+ const isStarter = starterId != null && Number(starterId) === user.id;
19546
+ if (!isStarter && user.super_admin !== true) {
19547
+ throw new StartImportError("NOT_AUTHORIZED");
19548
+ }
19549
+ await db2("job_results").where({ id: jobResultId }).update({ metadata: mergeMetadataRaw(db2, { cancelRequested: true }) });
19550
+ if (row.state === "waiting") {
19551
+ try {
19552
+ const job = await queue.getJob?.(jobResultId);
19553
+ await job?.remove();
19554
+ } catch (error) {
19555
+ console.error("[EXULU] failed to remove queued import job after cancel", error);
19556
+ }
19557
+ await db2("job_results").where({ id: jobResultId }).whereIn("state", ["waiting"]).update({ state: "cancelled" });
19558
+ } else {
19559
+ try {
19560
+ const job = await queue.getJob?.(jobResultId);
19561
+ if (!job) {
19562
+ await db2("job_results").where({ id: jobResultId }).whereIn("state", ["active"]).update({ state: "cancelled" });
19563
+ }
19564
+ } catch (error) {
19565
+ console.error("[EXULU] failed to inspect the running import job after cancel", error);
19566
+ }
19567
+ }
19568
+ return { ok: true };
19569
+ }
19570
+
18963
19571
  // src/graphql/mutations/index.ts
18964
19572
  init_rbac_update();
18965
19573
 
@@ -19172,10 +19780,10 @@ var currentChunksDimensionality = async (contextId) => {
19172
19780
  [getChunksTableName(contextId)]
19173
19781
  );
19174
19782
  return parseVectorDimensionality(result?.rows?.[0]?.type ?? null);
19175
- } catch (err3) {
19783
+ } catch (err4) {
19176
19784
  console.warn(
19177
19785
  `[EXULU] Could not read the chunk vector dimensionality for "${contextId}":`,
19178
- err3.message
19786
+ err4.message
19179
19787
  );
19180
19788
  return null;
19181
19789
  }
@@ -19295,10 +19903,10 @@ var getTranscriptsSettings = async () => {
19295
19903
  const { db: db2 } = await postgresClient();
19296
19904
  const row = await db2.from("platform_configurations").where({ config_key: TRANSCRIPTS_SETTINGS_KEY }).first();
19297
19905
  return { ...EMPTY, ...parseStoredSettings(row) ?? {} };
19298
- } catch (err3) {
19906
+ } catch (err4) {
19299
19907
  console.warn(
19300
19908
  "[EXULU] Could not read the Transcripts settings:",
19301
- err3.message
19909
+ err4.message
19302
19910
  );
19303
19911
  return { ...EMPTY };
19304
19912
  }
@@ -19413,7 +20021,7 @@ var parseSettingsInput = (input) => {
19413
20021
  };
19414
20022
 
19415
20023
  // src/graphql/mutations/index.ts
19416
- var VALID_RIGHTS_MODES2 = ["private", "users", "roles", "teams", "public"];
20024
+ var VALID_RIGHTS_MODES3 = ["private", "users", "roles", "teams", "public"];
19417
20025
  var postprocessDeletion = async ({
19418
20026
  table,
19419
20027
  requestedFields,
@@ -19555,10 +20163,10 @@ var buildTranscriptsSettingsInfo = async () => {
19555
20163
  const { db: db2 } = await postgresClient();
19556
20164
  const promptRows = await db2.from("prompt_library").select("id");
19557
20165
  livePromptIds = new Set(promptRows.map((row) => String(row.id)));
19558
- } catch (err3) {
20166
+ } catch (err4) {
19559
20167
  console.warn(
19560
20168
  "[EXULU] Could not read prompt_library for the Transcripts settings page:",
19561
- err3.message
20169
+ err4.message
19562
20170
  );
19563
20171
  }
19564
20172
  let liveAgentIds = null;
@@ -19566,10 +20174,10 @@ var buildTranscriptsSettingsInfo = async () => {
19566
20174
  const { db: db2 } = await postgresClient();
19567
20175
  const agentRows = await db2.from("agents").select("id");
19568
20176
  liveAgentIds = new Set(agentRows.map((row) => String(row.id)));
19569
- } catch (err3) {
20177
+ } catch (err4) {
19570
20178
  console.warn(
19571
20179
  "[EXULU] Could not read agents for the Transcripts settings page:",
19572
- err3.message
20180
+ err4.message
19573
20181
  );
19574
20182
  }
19575
20183
  const { live, stale } = livePromptIds && liveAgentIds ? filterLivePresets(resolved.summaryPresets.value, livePromptIds, liveAgentIds) : { live: resolved.summaryPresets.value, stale: [] };
@@ -19782,9 +20390,9 @@ function createMutations(table, contexts, tools, config) {
19782
20390
  input.id = db2.fn.uuid();
19783
20391
  }
19784
20392
  }
19785
- if (table.RBAC && input.rights_mode != null && !VALID_RIGHTS_MODES2.includes(input.rights_mode)) {
20393
+ if (table.RBAC && input.rights_mode != null && !VALID_RIGHTS_MODES3.includes(input.rights_mode)) {
19786
20394
  throw new Error(
19787
- `Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES2.join(", ")}`
20395
+ `Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES3.join(", ")}`
19788
20396
  );
19789
20397
  }
19790
20398
  const columns = await db2(tableNamePlural).columnInfo();
@@ -20192,6 +20800,89 @@ function createMutations(table, contexts, tools, config) {
20192
20800
  items
20193
20801
  };
20194
20802
  };
20803
+ const getImportQueue = async () => {
20804
+ let registered;
20805
+ try {
20806
+ registered = registerImportQueue();
20807
+ } catch (error) {
20808
+ throw new Error("QUEUES_NOT_LICENSED");
20809
+ }
20810
+ let importQueue;
20811
+ try {
20812
+ importQueue = await registered.use();
20813
+ } catch (error) {
20814
+ console.error("[EXULU] import queue unavailable", error);
20815
+ throw error;
20816
+ }
20817
+ return {
20818
+ add: (name, data, opts) => importQueue.queue.add(name, data, opts),
20819
+ getJob: (id) => importQueue.queue.getJob(id)
20820
+ };
20821
+ };
20822
+ mutations[`${tableNameSingular}StartImport`] = async (_, args, context, info) => {
20823
+ if (!context.user) {
20824
+ throw new Error("NOT_AUTHORIZED");
20825
+ }
20826
+ if (!table.id) {
20827
+ throw new Error("CONTEXT_NOT_FOUND");
20828
+ }
20829
+ const queue = await getImportQueue();
20830
+ try {
20831
+ return await startImport(
20832
+ {
20833
+ db: context.db,
20834
+ config,
20835
+ queue,
20836
+ user: context.user,
20837
+ // Mirrors ExecuteSource's own `exists` lookup above, as a
20838
+ // predicate rather than a one-shot find (start-import.ts needs
20839
+ // it before it knows the id is even valid).
20840
+ contextExists: (id) => contexts.some((c) => c.id === id)
20841
+ },
20842
+ {
20843
+ contextId: table.id,
20844
+ s3Key: args.input.s3Key,
20845
+ fileName: args.input.fileName,
20846
+ mapping: args.input.mapping,
20847
+ access: args.input.access,
20848
+ options: args.input.options,
20849
+ // Runs-view provenance (same rule as the workflow-run resolver
20850
+ // at src/graphql/schemas/index.ts:1964): API-key callers get
20851
+ // "api", everyone else (UI session) gets "ui".
20852
+ trigger: context.user.type === "api" ? "api" : "ui",
20853
+ totalRows: args.input.totalRows
20854
+ }
20855
+ );
20856
+ } catch (error) {
20857
+ if (error instanceof StartImportError) {
20858
+ throw new Error(error.code);
20859
+ }
20860
+ throw error;
20861
+ }
20862
+ };
20863
+ mutations[`${tableNameSingular}CancelImport`] = async (_, args, context, info) => {
20864
+ if (!context.user) {
20865
+ throw new Error("NOT_AUTHORIZED");
20866
+ }
20867
+ const queue = await getImportQueue();
20868
+ try {
20869
+ return await cancelImport(
20870
+ {
20871
+ db: context.db,
20872
+ config,
20873
+ queue,
20874
+ user: context.user,
20875
+ contextExists: (id) => contexts.some((c) => c.id === id)
20876
+ },
20877
+ args.jobResultId
20878
+ );
20879
+ } catch (error) {
20880
+ if (error instanceof StartImportError) {
20881
+ throw new Error(error.code);
20882
+ }
20883
+ throw error;
20884
+ }
20885
+ };
20195
20886
  mutations[`${tableNameSingular}GenerateChunks`] = async (_, args, context, info) => {
20196
20887
  const { db: db2 } = await postgresClient();
20197
20888
  const exists = contexts.find((context2) => context2.id === table.id);
@@ -20394,9 +21085,9 @@ function createMutations(table, contexts, tools, config) {
20394
21085
  rebuild: result.case,
20395
21086
  itemsQueued: result.items
20396
21087
  };
20397
- } catch (err3) {
21088
+ } catch (err4) {
20398
21089
  ctx.embedder = previous;
20399
- throw err3;
21090
+ throw err4;
20400
21091
  }
20401
21092
  };
20402
21093
  mutations[`${tableNameSingular}ExtractEntities`] = async (_, args, context) => {
@@ -20432,9 +21123,9 @@ function createMutations(table, contexts, tools, config) {
20432
21123
  if (!Array.isArray(ids) || ids.length === 0) {
20433
21124
  throw new Error("ids is required and must be a non-empty array.");
20434
21125
  }
20435
- if (!VALID_RIGHTS_MODES2.includes(rights_mode)) {
21126
+ if (!VALID_RIGHTS_MODES3.includes(rights_mode)) {
20436
21127
  throw new Error(
20437
- `Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES2.join(", ")}`
21128
+ `Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES3.join(", ")}`
20438
21129
  );
20439
21130
  }
20440
21131
  for (const id of ids) {
@@ -20484,9 +21175,7 @@ function createMutations(table, contexts, tools, config) {
20484
21175
  if (!inner) continue;
20485
21176
  mutations[key] = async (parent, args, context, info) => {
20486
21177
  if (context?.user?.super_admin !== true) {
20487
- throw new Error(
20488
- `${table.name.plural} rows are changed through their own API; the generic mutation is reserved for super admins.`
20489
- );
21178
+ throw new Error(`${table.name.plural} rows may only be changed by super admins through this API.`);
20490
21179
  }
20491
21180
  return inner(parent, args, context, info);
20492
21181
  };
@@ -20516,12 +21205,12 @@ var bullmq = {
20516
21205
  if (!data.inputs) {
20517
21206
  throw new Error(`Missing property "inputs" in data for job ${id}.`);
20518
21207
  }
20519
- if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function" && data.type !== "source" && data.type !== "email_intake") {
21208
+ if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function" && data.type !== "source" && data.type !== "email_intake" && data.type !== "import") {
20520
21209
  throw new Error(
20521
- `Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run", "eval_function", "source" or "email_intake".`
21210
+ `Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run", "eval_function", "source", "email_intake" or "import".`
20522
21211
  );
20523
21212
  }
20524
- if (data.type !== "email_intake" && !data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length && !data.source) {
21213
+ if (data.type !== "email_intake" && data.type !== "import" && !data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length && !data.source) {
20525
21214
  throw new Error(
20526
21215
  `Either a workflow, embedder, processor, eval_run, eval_functions or source must be set for job ${id}.`
20527
21216
  );
@@ -20529,37 +21218,6 @@ var bullmq = {
20529
21218
  }
20530
21219
  };
20531
21220
 
20532
- // src/utils/serialize-error.ts
20533
- init_cjs_shims();
20534
- var MAX_CAUSE_DEPTH = 3;
20535
- function serializeError(err3, depth = 0) {
20536
- if (err3 instanceof Error) {
20537
- const out = { name: err3.name, message: err3.message };
20538
- if (err3.stack) out.stack = err3.stack;
20539
- for (const [key, value] of Object.entries(err3)) {
20540
- if (key !== "cause") out[key] = value;
20541
- }
20542
- const cause = err3.cause;
20543
- if (cause !== void 0 && depth < MAX_CAUSE_DEPTH) {
20544
- out.cause = serializeError(cause, depth + 1);
20545
- }
20546
- return out;
20547
- }
20548
- if (typeof err3 === "string") {
20549
- return { message: err3 };
20550
- }
20551
- if (err3 !== null && typeof err3 === "object") {
20552
- let message;
20553
- try {
20554
- message = JSON.stringify(err3);
20555
- } catch {
20556
- message = "[unserializable error object]";
20557
- }
20558
- return { ...err3, message };
20559
- }
20560
- return { message: String(err3) };
20561
- }
20562
-
20563
21221
  // src/exulu/turn-metadata.ts
20564
21222
  init_cjs_shims();
20565
21223
  function finishTurnMetadata(opts) {
@@ -20695,8 +21353,8 @@ async function resolveFreshFileUrl(url, opts) {
20695
21353
  if (!location) return url;
20696
21354
  try {
20697
21355
  return await opts.sign(location.bucket, location.key);
20698
- } catch (err3) {
20699
- console.warn(`[EXULU] could not re-sign stored file URL for key "${location.key}":`, err3);
21356
+ } catch (err4) {
21357
+ console.warn(`[EXULU] could not re-sign stored file URL for key "${location.key}":`, err4);
20700
21358
  return url;
20701
21359
  }
20702
21360
  }
@@ -20747,8 +21405,8 @@ async function loadSessionFileListing(opts) {
20747
21405
  lastModified: new Date(o.lastModified)
20748
21406
  }));
20749
21407
  return describeSessionFiles(files, { lastTurnAt: opts.lastTurnAt });
20750
- } catch (err3) {
20751
- console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`, err3);
21408
+ } catch (err4) {
21409
+ console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`, err4);
20752
21410
  return "";
20753
21411
  }
20754
21412
  }
@@ -21230,7 +21888,7 @@ async function recordMemoryUsage(input) {
21230
21888
  }
21231
21889
 
21232
21890
  // src/exulu/generate-stream.ts
21233
- var import_node_crypto8 = require("crypto");
21891
+ var import_node_crypto9 = require("crypto");
21234
21892
  var processFilePartsInMessages = async (messages, offloadCtx) => {
21235
21893
  const processedMessages = await Promise.all(
21236
21894
  messages.map(async (message) => {
@@ -21633,7 +22291,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
21633
22291
  contextId: agent.memory,
21634
22292
  agentId: agent.id,
21635
22293
  session: session ?? null,
21636
- messageId: output.response?.id ?? (0, import_node_crypto8.randomUUID)(),
22294
+ messageId: output.response?.id ?? (0, import_node_crypto9.randomUUID)(),
21637
22295
  userId: user?.id ?? null
21638
22296
  });
21639
22297
  }
@@ -21708,7 +22366,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
21708
22366
  contextId: agent.memory,
21709
22367
  agentId: agent.id,
21710
22368
  session: session ?? null,
21711
- messageId: response?.id ?? (0, import_node_crypto8.randomUUID)(),
22369
+ messageId: response?.id ?? (0, import_node_crypto9.randomUUID)(),
21712
22370
  userId: user?.id ?? null
21713
22371
  });
21714
22372
  }
@@ -22024,10 +22682,10 @@ function extractGlossaryFromAgentTools(tools) {
22024
22682
  return glossary.filter(
22025
22683
  (g) => !!g && typeof g.term === "string" && typeof g.meaning === "string" && g.term.trim().length > 0
22026
22684
  );
22027
- } catch (err3) {
22685
+ } catch (err4) {
22028
22686
  console.warn(
22029
22687
  "[EXULU] Failed to parse the agentic_context_search vocabulary config while building agent instructions.",
22030
- err3
22688
+ err4
22031
22689
  );
22032
22690
  return [];
22033
22691
  }
@@ -22225,14 +22883,14 @@ init_singleton();
22225
22883
 
22226
22884
  // src/exulu/email-inbound/intake.ts
22227
22885
  init_cjs_shims();
22228
- var import_node_crypto11 = require("crypto");
22886
+ var import_node_crypto12 = require("crypto");
22229
22887
  init_client();
22230
22888
  init_uppy();
22231
22889
  init_singleton();
22232
22890
 
22233
22891
  // src/exulu/email-inbound/normalize.ts
22234
22892
  init_cjs_shims();
22235
- var import_node_crypto9 = require("crypto");
22893
+ var import_node_crypto10 = require("crypto");
22236
22894
  var import_mailparser = require("mailparser");
22237
22895
  var htmlToText = (html) => html.replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&amp;/gi, "&").replace(/\s+/g, " ").trim();
22238
22896
  var headerValueToString = (value) => {
@@ -22273,7 +22931,7 @@ async function parseRawMime(raw) {
22273
22931
  return {
22274
22932
  // Message-ID is the dedup key (spec §4.4.5). A missing header gets a
22275
22933
  // deterministic content hash so webhook/job retries still dedup.
22276
- messageId: parsed.messageId ?? `generated-${(0, import_node_crypto9.createHash)("sha256").update(raw).digest("hex")}`,
22934
+ messageId: parsed.messageId ?? `generated-${(0, import_node_crypto10.createHash)("sha256").update(raw).digest("hex")}`,
22277
22935
  from: {
22278
22936
  address: fromEntry.address.toLowerCase(),
22279
22937
  ...fromEntry.name ? { name: fromEntry.name } : {}
@@ -22293,7 +22951,7 @@ async function parseRawMime(raw) {
22293
22951
 
22294
22952
  // src/exulu/email-inbound/adapters.ts
22295
22953
  init_cjs_shims();
22296
- var import_node_crypto10 = require("crypto");
22954
+ var import_node_crypto11 = require("crypto");
22297
22955
  var import_node_stream = require("stream");
22298
22956
  var import_busboy = __toESM(require("busboy"), 1);
22299
22957
  var htmlToText2 = (html) => html.replace(/<\s*(script|style)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, "").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/\s+/g, " ").trim();
@@ -22338,7 +22996,7 @@ function extractMultipartMimePart(rawBody, contentType) {
22338
22996
  if (found) resolve8(found);
22339
22997
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
22340
22998
  });
22341
- bb.on("error", (err3) => reject(err3 instanceof Error ? err3 : new Error(String(err3))));
22999
+ bb.on("error", (err4) => reject(err4 instanceof Error ? err4 : new Error(String(err4))));
22342
23000
  import_node_stream.Readable.from(rawBody).pipe(bb);
22343
23001
  });
22344
23002
  }
@@ -22351,7 +23009,7 @@ function jsonToInboundEmail(raw) {
22351
23009
  const subject = typeof obj.subject === "string" ? obj.subject : "";
22352
23010
  const html = typeof obj.html === "string" ? obj.html : void 0;
22353
23011
  const text = typeof obj.text === "string" && obj.text ? obj.text : html ? htmlToText2(html) : "";
22354
- const messageId = typeof obj.message_id === "string" && obj.message_id ? obj.message_id : `<${(0, import_node_crypto10.randomUUID)()}@webhook.local>`;
23012
+ const messageId = typeof obj.message_id === "string" && obj.message_id ? obj.message_id : `<${(0, import_node_crypto11.randomUUID)()}@webhook.local>`;
22355
23013
  const attachments = Array.isArray(obj.attachments) ? obj.attachments.map(decodeAttachment) : [];
22356
23014
  const headers = /* @__PURE__ */ new Map([["message-id", messageId]]);
22357
23015
  return {
@@ -22434,10 +23092,10 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
22434
23092
  const elapsedFraction = now % HOUR_MS / HOUR_MS;
22435
23093
  const weighted = count + previous * (1 - elapsedFraction);
22436
23094
  return weighted <= limitPerHour;
22437
- } catch (err3) {
23095
+ } catch (err4) {
22438
23096
  console.error(
22439
23097
  "[EXULU] email-inbound rate limit: redis unavailable, allowing (best-effort)",
22440
- err3 instanceof Error ? err3.message : String(err3)
23098
+ err4 instanceof Error ? err4.message : String(err4)
22441
23099
  );
22442
23100
  return true;
22443
23101
  }
@@ -22589,7 +23247,7 @@ var fireRun = async (opts) => {
22589
23247
  }
22590
23248
  const fromDisplay = email.from.name ? `"${email.from.name}" <${email.from.address}>` : `<${email.from.address}>`;
22591
23249
  const initialMessage = {
22592
- id: (0, import_node_crypto11.randomUUID)(),
23250
+ id: (0, import_node_crypto12.randomUUID)(),
22593
23251
  role: "user",
22594
23252
  parts: [
22595
23253
  {
@@ -22773,6 +23431,426 @@ function computeRunCostUsd(inputTokens, outputTokens, price) {
22773
23431
  return inTok / 1e6 * inPrice + outTok / 1e6 * outPrice;
22774
23432
  }
22775
23433
 
23434
+ // ee/workers.ts
23435
+ init_uppy();
23436
+
23437
+ // src/exulu/import/run-import.ts
23438
+ init_cjs_shims();
23439
+
23440
+ // src/exulu/import/csv-stream.ts
23441
+ init_cjs_shims();
23442
+ var import_node_stream2 = require("stream");
23443
+ var import_csv_parse = require("csv-parse");
23444
+ var CANDIDATE_DELIMITERS = [",", ";", " ", "|"];
23445
+ var MAX_HEADER_BYTES = 64 * 1024;
23446
+ function sniffDelimiter(headerLine) {
23447
+ const counts = new Map(CANDIDATE_DELIMITERS.map((d) => [d, 0]));
23448
+ let inQuotes = false;
23449
+ for (const char of headerLine) {
23450
+ if (char === '"') {
23451
+ inQuotes = !inQuotes;
23452
+ continue;
23453
+ }
23454
+ if (inQuotes) continue;
23455
+ const seen = counts.get(char);
23456
+ if (seen !== void 0) counts.set(char, seen + 1);
23457
+ }
23458
+ let best = CANDIDATE_DELIMITERS[0];
23459
+ let bestCount = 0;
23460
+ for (const candidate of CANDIDATE_DELIMITERS) {
23461
+ const count = counts.get(candidate) ?? 0;
23462
+ if (count > bestCount) {
23463
+ best = candidate;
23464
+ bestCount = count;
23465
+ }
23466
+ }
23467
+ return best;
23468
+ }
23469
+ function createSniffer(onFirstLine) {
23470
+ const head = [];
23471
+ let headBytes = 0;
23472
+ let resolved = false;
23473
+ const resolve8 = (line) => {
23474
+ if (resolved) return;
23475
+ resolved = true;
23476
+ onFirstLine(line);
23477
+ };
23478
+ return new import_node_stream2.Transform({
23479
+ readableHighWaterMark: 4 * MAX_HEADER_BYTES,
23480
+ transform(chunk2, _encoding, callback) {
23481
+ if (!resolved) {
23482
+ const buffer = Buffer.isBuffer(chunk2) ? chunk2 : Buffer.from(String(chunk2));
23483
+ head.push(buffer);
23484
+ headBytes += buffer.length;
23485
+ const text = Buffer.concat(head).toString("utf-8");
23486
+ const eol = /\r|\n/.exec(text);
23487
+ if (eol) {
23488
+ resolve8(text.slice(0, eol.index));
23489
+ } else if (headBytes >= MAX_HEADER_BYTES) {
23490
+ resolve8(text);
23491
+ }
23492
+ }
23493
+ callback(null, chunk2);
23494
+ },
23495
+ flush(callback) {
23496
+ resolve8(Buffer.concat(head).toString("utf-8"));
23497
+ callback();
23498
+ }
23499
+ });
23500
+ }
23501
+ async function streamCsvRows(input, handlers, opts) {
23502
+ let resolveFirstLine = () => {
23503
+ };
23504
+ const firstLine = new Promise((resolve8) => {
23505
+ resolveFirstLine = resolve8;
23506
+ });
23507
+ const sniffer = createSniffer((line) => resolveFirstLine(line));
23508
+ let parser;
23509
+ let earlyError;
23510
+ input.on("error", (err4) => sniffer.destroy(err4));
23511
+ sniffer.on("error", (err4) => {
23512
+ if (parser) parser.destroy(err4);
23513
+ else {
23514
+ earlyError = err4;
23515
+ resolveFirstLine("");
23516
+ }
23517
+ });
23518
+ input.pipe(sniffer);
23519
+ const headerLine = await firstLine;
23520
+ if (earlyError) throw earlyError;
23521
+ const delimiter = opts?.delimiter ?? sniffDelimiter(headerLine);
23522
+ parser = (0, import_csv_parse.parse)({
23523
+ bom: true,
23524
+ relax_quotes: true,
23525
+ relax_column_count: true,
23526
+ skip_empty_lines: true,
23527
+ columns: false,
23528
+ delimiter,
23529
+ // csv-parse's auto record-delimiter discovery locks onto the first
23530
+ // line ending it sees (outside quotes) and never reconsiders -- a file
23531
+ // whose header ends in "\n" but has later rows ending in "\r\n" (or
23532
+ // vice versa) would then have the "\r" leak into field content instead
23533
+ // of being recognized as part of the delimiter. Listing all three EOL
23534
+ // styles up front avoids that trap for real-world, possibly
23535
+ // inconsistently-terminated uploads.
23536
+ record_delimiter: ["\r\n", "\n", "\r"]
23537
+ });
23538
+ sniffer.pipe(parser);
23539
+ let sawHeader = false;
23540
+ let index = 0;
23541
+ for await (const record of parser) {
23542
+ if (!sawHeader) {
23543
+ sawHeader = true;
23544
+ await handlers.onHeader(record.map((cell) => cell.trim()));
23545
+ continue;
23546
+ }
23547
+ if (record.every((cell) => cell.trim() === "")) continue;
23548
+ await handlers.onRow(record, index);
23549
+ index++;
23550
+ }
23551
+ return { rows: index };
23552
+ }
23553
+
23554
+ // src/exulu/import/mapping.ts
23555
+ init_cjs_shims();
23556
+ init_sanitize_name();
23557
+ function normalizeHeader(value) {
23558
+ return value.trim().toLowerCase().replace(/[\s-]+/g, "_");
23559
+ }
23560
+ function headerMatchesField(field, normalizedHeader) {
23561
+ if (normalizeHeader(field.name) === normalizedHeader) return true;
23562
+ return field.label != null && normalizeHeader(field.label) === normalizedHeader;
23563
+ }
23564
+ function autoMapColumns(headers, fields) {
23565
+ const used = /* @__PURE__ */ new Set();
23566
+ return headers.map((header2) => {
23567
+ const normalized = normalizeHeader(header2);
23568
+ const match = fields.find((f) => !used.has(f.name) && headerMatchesField(f, normalized));
23569
+ if (!match) return { header: header2, fieldName: null };
23570
+ used.add(match.name);
23571
+ return { header: header2, fieldName: match.name };
23572
+ });
23573
+ }
23574
+ var CORE_FIELDS = [
23575
+ { name: "id", type: "text", core: true },
23576
+ { name: "external_id", type: "text", core: true },
23577
+ { name: "name", type: "shortText", required: true, core: true },
23578
+ { name: "description", type: "longText", core: true },
23579
+ { name: "tags", type: "text", core: true }
23580
+ ];
23581
+ function importFieldsFor(fields) {
23582
+ const custom = fields.filter((f) => !f.calculated && !f.hidden && f.type !== "file").map((f) => ({
23583
+ name: sanitizeName(f.name),
23584
+ label: f.name,
23585
+ type: f.type,
23586
+ required: f.required === true,
23587
+ core: false,
23588
+ enumValues: f.enumValues
23589
+ }));
23590
+ return [...CORE_FIELDS, ...custom];
23591
+ }
23592
+ function resolveMapping(headers, fields, given) {
23593
+ if (!given) {
23594
+ return { byIndex: autoMapColumns(headers, fields).map((m) => m.fieldName), unknownFields: [] };
23595
+ }
23596
+ const fieldNames = new Set(fields.map((f) => f.name));
23597
+ const byHeader = new Map(given.map((g) => [normalizeHeader(g.header), g.fieldName]));
23598
+ const unknownFields = /* @__PURE__ */ new Set();
23599
+ const byIndex = headers.map((header2) => {
23600
+ const fieldName = byHeader.get(normalizeHeader(header2));
23601
+ if (fieldName == null) return null;
23602
+ if (!fieldNames.has(fieldName)) {
23603
+ unknownFields.add(fieldName);
23604
+ return null;
23605
+ }
23606
+ return fieldName;
23607
+ });
23608
+ return { byIndex, unknownFields: [...unknownFields] };
23609
+ }
23610
+
23611
+ // src/exulu/import/run-import.ts
23612
+ var ABORT_MESSAGES = {
23613
+ NO_MAPPABLE_COLUMNS: "No column in the file maps to a usable field (name, id, or external_id).",
23614
+ EMPTY_FILE: "The file has no header row."
23615
+ };
23616
+ var ImportAbort = class extends Error {
23617
+ constructor(code) {
23618
+ super(ABORT_MESSAGES[code]);
23619
+ this.code = code;
23620
+ this.name = "ImportAbort";
23621
+ }
23622
+ };
23623
+ var DEFAULT_CHUNK_ROWS = 500;
23624
+ var DEFAULT_CONCURRENCY = 8;
23625
+ var DEFAULT_PROGRESS_INTERVAL_MS = 1e4;
23626
+ var IMPORT_MAX_ERROR_LINES = 5e4;
23627
+ var RunCancelled = class extends Error {
23628
+ };
23629
+ function csvField(value) {
23630
+ return /["\n\r,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
23631
+ }
23632
+ function csvLine(cells) {
23633
+ return cells.map(csvField).join(",");
23634
+ }
23635
+ async function runPool(items, concurrency, worker) {
23636
+ let next = 0;
23637
+ const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
23638
+ while (next < items.length) {
23639
+ const index = next;
23640
+ next += 1;
23641
+ await worker(items[index]);
23642
+ }
23643
+ });
23644
+ await Promise.all(runners);
23645
+ }
23646
+ async function runImport(deps) {
23647
+ const now = deps.now ?? Date.now;
23648
+ const log7 = deps.log ?? (() => {
23649
+ });
23650
+ const chunkRows = deps.chunkRows ?? DEFAULT_CHUNK_ROWS;
23651
+ const concurrency = deps.concurrency ?? DEFAULT_CONCURRENCY;
23652
+ const progressIntervalMs = deps.progressIntervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS;
23653
+ const maxErrorLines = deps.maxErrorLines ?? IMPORT_MAX_ERROR_LINES;
23654
+ const startedAt = now();
23655
+ const metadata = {
23656
+ total: deps.total ?? null,
23657
+ processed: 0,
23658
+ created: 0,
23659
+ updated: 0,
23660
+ failed: 0,
23661
+ invalid: 0
23662
+ };
23663
+ let cancelled = false;
23664
+ let headerSeen = false;
23665
+ let headerCells = [];
23666
+ let byIndex = [];
23667
+ const errorLines = [];
23668
+ let truncatedErrorCount = 0;
23669
+ const seenIds = /* @__PURE__ */ new Set();
23670
+ const seenExternalIds = /* @__PURE__ */ new Set();
23671
+ let buffer = [];
23672
+ let lastTickAt = startedAt;
23673
+ function pushErrorLine(cells, message) {
23674
+ if (errorLines.length < maxErrorLines) {
23675
+ errorLines.push(csvLine([...cells, message]));
23676
+ } else {
23677
+ truncatedErrorCount++;
23678
+ }
23679
+ }
23680
+ async function runCreate(row, cells) {
23681
+ try {
23682
+ await deps.createItem(buildCreateInput(row, deps.access));
23683
+ metadata.created++;
23684
+ } catch (e) {
23685
+ metadata.failed++;
23686
+ pushErrorLine(cells, e instanceof Error ? e.message : String(e));
23687
+ }
23688
+ }
23689
+ async function runUpdate(existing, row, cells) {
23690
+ let allowed;
23691
+ try {
23692
+ allowed = deps.canWrite(existing);
23693
+ } catch (e) {
23694
+ metadata.failed++;
23695
+ pushErrorLine(cells, e instanceof Error ? e.message : String(e));
23696
+ return;
23697
+ }
23698
+ if (!allowed) {
23699
+ metadata.failed++;
23700
+ pushErrorLine(cells, "no write access");
23701
+ return;
23702
+ }
23703
+ try {
23704
+ await deps.updateItem(existing.id, buildUpdateInput(row));
23705
+ metadata.updated++;
23706
+ } catch (e) {
23707
+ metadata.failed++;
23708
+ pushErrorLine(cells, e instanceof Error ? e.message : String(e));
23709
+ }
23710
+ }
23711
+ async function processChunk(chunk2) {
23712
+ if (chunk2.length === 0) return;
23713
+ const toCreate = [];
23714
+ const toUpdate = [];
23715
+ for (const { index, cells } of chunk2) {
23716
+ metadata.processed++;
23717
+ try {
23718
+ const row = buildRow(index, cells, byIndex, deps.fields);
23719
+ if (!rowIsValid(row)) {
23720
+ metadata.invalid++;
23721
+ pushErrorLine(cells, row.errors.join("; "));
23722
+ continue;
23723
+ }
23724
+ const action = rowAction(row);
23725
+ if (action.action === "create") {
23726
+ toCreate.push({ row, cells });
23727
+ continue;
23728
+ }
23729
+ const seen = action.by === "id" ? seenIds : seenExternalIds;
23730
+ if (seen.has(action.key)) {
23731
+ metadata.invalid++;
23732
+ pushErrorLine(cells, `duplicateKey:${action.by}`);
23733
+ continue;
23734
+ }
23735
+ seen.add(action.key);
23736
+ toUpdate.push({ row, by: action.by, key: action.key, cells });
23737
+ } catch (e) {
23738
+ metadata.failed++;
23739
+ pushErrorLine(cells, e instanceof Error ? e.message : String(e));
23740
+ }
23741
+ }
23742
+ const ids = toUpdate.filter((u) => u.by === "id").map((u) => u.key);
23743
+ const externalIds = toUpdate.filter((u) => u.by === "external_id").map((u) => u.key);
23744
+ let existingRows;
23745
+ try {
23746
+ existingRows = ids.length > 0 || externalIds.length > 0 ? await deps.lookupExisting(ids, externalIds) : [];
23747
+ } catch (e) {
23748
+ const message = e instanceof Error ? e.message : String(e);
23749
+ for (const { cells } of toCreate) {
23750
+ metadata.failed++;
23751
+ pushErrorLine(cells, message);
23752
+ }
23753
+ for (const u of toUpdate) {
23754
+ metadata.failed++;
23755
+ pushErrorLine(u.cells, message);
23756
+ }
23757
+ return;
23758
+ }
23759
+ const byId = new Map(existingRows.map((r) => [r.id, r]));
23760
+ const byExternalId = new Map(
23761
+ existingRows.filter((r) => r.external_id != null).map((r) => [r.external_id, r])
23762
+ );
23763
+ const tasks = [];
23764
+ for (const { row, cells } of toCreate) {
23765
+ tasks.push(() => runCreate(row, cells));
23766
+ }
23767
+ for (const u of toUpdate) {
23768
+ const existing = u.by === "id" ? byId.get(u.key) : byExternalId.get(u.key);
23769
+ if (existing) {
23770
+ tasks.push(() => runUpdate(existing, u.row, u.cells));
23771
+ continue;
23772
+ }
23773
+ if (u.by === "id") {
23774
+ metadata.failed++;
23775
+ pushErrorLine(u.cells, "id not found");
23776
+ continue;
23777
+ }
23778
+ tasks.push(() => runCreate(u.row, u.cells));
23779
+ }
23780
+ await runPool(tasks, concurrency, (task) => task());
23781
+ }
23782
+ async function tick3() {
23783
+ lastTickAt = now();
23784
+ await deps.writeProgress({ ...metadata });
23785
+ }
23786
+ try {
23787
+ await streamCsvRows(
23788
+ deps.stream,
23789
+ {
23790
+ onHeader: (headers) => {
23791
+ headerSeen = true;
23792
+ headerCells = headers;
23793
+ const resolved = resolveMapping(headers, deps.fields, deps.mapping);
23794
+ byIndex = resolved.byIndex;
23795
+ const nameMapped = byIndex.includes("name");
23796
+ const keyMapped = byIndex.includes("id") || byIndex.includes("external_id");
23797
+ const allUnmapped = byIndex.every((f) => f === null);
23798
+ if (allUnmapped || !nameMapped && !keyMapped) {
23799
+ throw new ImportAbort("NO_MAPPABLE_COLUMNS");
23800
+ }
23801
+ },
23802
+ onRow: async (cells, index) => {
23803
+ buffer.push({ index, cells });
23804
+ const intervalElapsed = now() - lastTickAt >= progressIntervalMs;
23805
+ if (buffer.length < chunkRows && !intervalElapsed) return;
23806
+ const chunk2 = buffer;
23807
+ buffer = [];
23808
+ await processChunk(chunk2);
23809
+ await tick3();
23810
+ if (await deps.isCancelRequested()) {
23811
+ cancelled = true;
23812
+ log7(`import: cancelled after ${metadata.processed} rows`);
23813
+ throw new RunCancelled();
23814
+ }
23815
+ }
23816
+ },
23817
+ { delimiter: deps.options.delimiter }
23818
+ );
23819
+ } catch (e) {
23820
+ if (!(e instanceof RunCancelled)) throw e;
23821
+ }
23822
+ if (!headerSeen) {
23823
+ throw new ImportAbort("EMPTY_FILE");
23824
+ }
23825
+ if (!cancelled && buffer.length > 0) {
23826
+ const chunk2 = buffer;
23827
+ buffer = [];
23828
+ await processChunk(chunk2);
23829
+ await tick3();
23830
+ }
23831
+ const errorReportTruncated = truncatedErrorCount > 0;
23832
+ let errorReportKey = null;
23833
+ if (errorLines.length > 0 || errorReportTruncated) {
23834
+ const lines = [csvLine([...headerCells, "import_error"]), ...errorLines];
23835
+ if (errorReportTruncated) {
23836
+ const markerPadding = Array(Math.max(headerCells.length - 1, 0)).fill("");
23837
+ lines.push(csvLine(["\u2026", ...markerPadding, `truncated: ${truncatedErrorCount} more rows not listed`]));
23838
+ }
23839
+ const csv = "\uFEFF" + lines.join("\n");
23840
+ errorReportKey = await deps.uploadErrorReport(csv);
23841
+ }
23842
+ log7(
23843
+ `import: completed -- processed ${metadata.processed}, created ${metadata.created}, updated ${metadata.updated}, failed ${metadata.failed}, invalid ${metadata.invalid}`
23844
+ );
23845
+ return {
23846
+ ...metadata,
23847
+ durationMs: now() - startedAt,
23848
+ errorReportKey,
23849
+ cancelled,
23850
+ errorReportTruncated
23851
+ };
23852
+ }
23853
+
22776
23854
  // ee/workers.ts
22777
23855
  var FlowStepError = class extends Error {
22778
23856
  stepIndex;
@@ -22883,7 +23961,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
22883
23961
  type: bullmqJob.data.type
22884
23962
  });
22885
23963
  let progressInterval;
22886
- if (bullmqJob.data.type === "processor") {
23964
+ if (bullmqJob.data.type === "processor" || bullmqJob.data.type === "import") {
22887
23965
  progressInterval = setInterval(async () => {
22888
23966
  try {
22889
23967
  await bullmqJob.updateProgress({
@@ -23537,6 +24615,97 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
23537
24615
  }
23538
24616
  };
23539
24617
  }
24618
+ if (data.type === "import") {
24619
+ console.log("[EXULU] running a server-side bulk import job.", bullmqJob.name);
24620
+ if (!data.jobResultId) {
24621
+ throw new Error(`No jobResultId set for import job ${bullmqJob.id}.`);
24622
+ }
24623
+ if (!data.context) {
24624
+ throw new Error(`No context id set for import job ${bullmqJob.id}.`);
24625
+ }
24626
+ const importData = {
24627
+ type: "import",
24628
+ jobResultId: data.jobResultId,
24629
+ context: data.context,
24630
+ user: data.user,
24631
+ role: data.role
24632
+ };
24633
+ const jobResultId = importData.jobResultId;
24634
+ const row = await db2.from("job_results").where({ id: jobResultId }).first();
24635
+ if (!row) {
24636
+ throw new Error(
24637
+ `job_results row ${jobResultId} not found for import job ${bullmqJob.id}.`
24638
+ );
24639
+ }
24640
+ const priorMetadata = parseMetadata(row.metadata);
24641
+ const priorProcessed = Number(priorMetadata.processed ?? 0);
24642
+ if (row.state === JOB_STATUS_ENUM.active || priorProcessed > 0) {
24643
+ throw new Error(
24644
+ `IMPORT_RESTARTED_AFTER_STALL: import ${jobResultId} was already running; partial rows are kept, start a new import`
24645
+ );
24646
+ }
24647
+ await upsertJobStart(db2, bullmqJob, row.label, "import");
24648
+ const context = contexts.find((c) => c.id === importData.context);
24649
+ if (!context) {
24650
+ throw new Error(`Context ${importData.context} not found in the registry.`);
24651
+ }
24652
+ const triggerMetadata = parseRunMetadata(row.trigger_metadata);
24653
+ if (!triggerMetadata.s3Key) {
24654
+ throw new Error(
24655
+ `No s3Key recorded on job_results row ${jobResultId} for import job.`
24656
+ );
24657
+ }
24658
+ if (!triggerMetadata.access) {
24659
+ throw new Error(
24660
+ `No batch access recorded on job_results row ${jobResultId} for import job.`
24661
+ );
24662
+ }
24663
+ const snap = triggerMetadata.user;
24664
+ const importUser = snap && typeof snap === "object" ? {
24665
+ id: Number(snap.id),
24666
+ super_admin: snap.super_admin === true,
24667
+ role: snap.role,
24668
+ team: snap.team
24669
+ } : { id: Number(snap ?? importData.user), role: importData.role };
24670
+ if (!importUser.id) {
24671
+ throw new Error(`No acting user recorded for import job ${bullmqJob.id}.`);
24672
+ }
24673
+ const bareS3Key = triggerMetadata.s3Key.slice(triggerMetadata.s3Key.indexOf("/") + 1);
24674
+ const stream = await getS3ObjectStream(bareS3Key, config);
24675
+ try {
24676
+ const deps = buildWorkerDeps({
24677
+ db: db2,
24678
+ config,
24679
+ context,
24680
+ contextId: importData.context,
24681
+ jobResultId,
24682
+ stream,
24683
+ fields: importFieldsFor(context.fields),
24684
+ mapping: triggerMetadata.mapping,
24685
+ access: triggerMetadata.access,
24686
+ options: triggerMetadata.options ?? {},
24687
+ user: importUser,
24688
+ log: (m) => console.log(`[EXULU] import ${jobResultId}: ${m}`),
24689
+ // The row count StartImport seeded into metadata.total
24690
+ // (from the caller's `totalRows`); buildWorkerDeps treats a
24691
+ // 0/absent value as "unknown" so the progress patch does
24692
+ // not overwrite it with null on the first tick.
24693
+ total: priorMetadata.total
24694
+ });
24695
+ const result = await runImport(deps);
24696
+ if (result.cancelled) {
24697
+ await finalizeCancelled(db2, row.id, result);
24698
+ }
24699
+ return { result, metadata: result };
24700
+ } catch (error) {
24701
+ if (error instanceof ImportAbort) {
24702
+ console.error(`[EXULU] import ${jobResultId} aborted: ${error.code}`);
24703
+ }
24704
+ throw error;
24705
+ } finally {
24706
+ stream.destroy();
24707
+ }
24708
+ }
23540
24709
  if (data.type === "email_intake") {
23541
24710
  console.log("[EXULU] running a routine webhook intake job.", bullmqJob.name);
23542
24711
  if (!data.inputs?.s3Key || !data.inputs?.triggerId) {
@@ -23870,8 +25039,8 @@ var processUiMessagesFlow = async ({
23870
25039
  let contextWindow;
23871
25040
  try {
23872
25041
  contextWindow = await resolveContextWindow({ modelId: resolved.model.id });
23873
- } catch (err3) {
23874
- console.warn(`[EXULU] Could not resolve the context window for routine model "${resolved.model.id}"; using the default.`, err3);
25042
+ } catch (err4) {
25043
+ console.warn(`[EXULU] Could not resolve the context window for routine model "${resolved.model.id}"; using the default.`, err4);
23875
25044
  }
23876
25045
  const messagesWithoutPlaceholder = inputMessages.filter(
23877
25046
  (message) => message.metadata?.type !== "placeholder"
@@ -24226,10 +25395,10 @@ async function fetch_with_retry(args) {
24226
25395
  url,
24227
25396
  timeout_ms ? { ...options, signal: AbortSignal.timeout(timeout_ms) } : options
24228
25397
  );
24229
- } catch (err3) {
24230
- if (!retry_on_reject || attempt === max_attempts) throw err3;
25398
+ } catch (err4) {
25399
+ if (!retry_on_reject || attempt === max_attempts) throw err4;
24231
25400
  console.log(
24232
- `[EXULU-RECALL] fetch error from ${url} (${err3.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
25401
+ `[EXULU-RECALL] fetch error from ${url} (${err4.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
24233
25402
  );
24234
25403
  await new Promise((resolve8) => setTimeout(resolve8, 5e3 + jitterMs()));
24235
25404
  continue;
@@ -24566,13 +25735,13 @@ var recallService = {
24566
25735
  });
24567
25736
  const [updated] = await db2(TABLE2).where({ id: inserted.id }).update({ recall_bot_id: bot.id, updatedAt: /* @__PURE__ */ new Date() }).returning("*");
24568
25737
  return this._row(updated);
24569
- } catch (err3) {
25738
+ } catch (err4) {
24570
25739
  const [failed] = await db2(TABLE2).where({ id: inserted.id }).update({
24571
25740
  status: "failed",
24572
- error: err3.message,
25741
+ error: err4.message,
24573
25742
  updatedAt: /* @__PURE__ */ new Date()
24574
25743
  }).returning("*");
24575
- log3(`createBot failed for job ${inserted.id}: ${err3.message}`);
25744
+ log3(`createBot failed for job ${inserted.id}: ${err4.message}`);
24576
25745
  return this._row(failed);
24577
25746
  }
24578
25747
  },
@@ -24643,8 +25812,8 @@ var recallService = {
24643
25812
  row?.language || "auto"
24644
25813
  );
24645
25814
  await this._update(jobId, { recall_transcript_id: transcript.id ?? null });
24646
- } catch (err3) {
24647
- await this._fail(jobId, `create transcript failed: ${err3.message}`);
25815
+ } catch (err4) {
25816
+ await this._fail(jobId, `create transcript failed: ${err4.message}`);
24648
25817
  }
24649
25818
  },
24650
25819
  async _onTranscriptDone(jobId, transcriptId, recordingId) {
@@ -24680,12 +25849,12 @@ var recallService = {
24680
25849
  jobId,
24681
25850
  exuluApp.get().config
24682
25851
  );
24683
- } catch (err3) {
24684
- log3(`could not store video locally for job ${jobId}: ${err3.message}`);
25852
+ } catch (err4) {
25853
+ log3(`could not store video locally for job ${jobId}: ${err4.message}`);
24685
25854
  }
24686
25855
  }
24687
- } catch (err3) {
24688
- log3(`could not fetch recording duration for job ${jobId}: ${err3.message}`);
25856
+ } catch (err4) {
25857
+ log3(`could not fetch recording duration for job ${jobId}: ${err4.message}`);
24689
25858
  }
24690
25859
  }
24691
25860
  await this._update(jobId, {
@@ -24695,8 +25864,8 @@ var recallService = {
24695
25864
  ...videoS3Key ? { video_s3key: videoS3Key } : {},
24696
25865
  status: "awaiting_review"
24697
25866
  });
24698
- } catch (err3) {
24699
- await this._fail(jobId, `transcript download failed: ${err3.message}`);
25867
+ } catch (err4) {
25868
+ await this._fail(jobId, `transcript download failed: ${err4.message}`);
24700
25869
  return;
24701
25870
  }
24702
25871
  await this.runPostProcessing(jobId);
@@ -24728,9 +25897,9 @@ var recallService = {
24728
25897
  if (!video) return null;
24729
25898
  if (video.status?.code && video.status.code !== "done") return null;
24730
25899
  return video.data?.download_url ?? null;
24731
- } catch (err3) {
25900
+ } catch (err4) {
24732
25901
  log3(
24733
- `could not resolve video url for recording ${recordingId}: ${err3.message}`
25902
+ `could not resolve video url for recording ${recordingId}: ${err4.message}`
24734
25903
  );
24735
25904
  return null;
24736
25905
  }
@@ -24867,15 +26036,15 @@ ${transcriptText}`,
24867
26036
  error: null,
24868
26037
  ran_at: ranAt
24869
26038
  };
24870
- } catch (err3) {
24871
- log3(`post-processing prompt ${promptId} failed for job ${job.id}: ${err3.message}`);
26039
+ } catch (err4) {
26040
+ log3(`post-processing prompt ${promptId} failed for job ${job.id}: ${err4.message}`);
24872
26041
  return {
24873
26042
  prompt_id: promptId,
24874
26043
  agent_id: agentId,
24875
26044
  prompt_name: promptName,
24876
26045
  status: "failed",
24877
26046
  output: null,
24878
- error: err3.message,
26047
+ error: err4.message,
24879
26048
  ran_at: ranAt
24880
26049
  };
24881
26050
  }
@@ -24905,8 +26074,8 @@ ${transcriptText}`,
24905
26074
  const job = this._row(dbRow);
24906
26075
  try {
24907
26076
  if (await this._reconcileStuckJob(job)) acted++;
24908
- } catch (err3) {
24909
- if (await this._reconcileError(job, err3)) acted++;
26077
+ } catch (err4) {
26078
+ if (await this._reconcileError(job, err4)) acted++;
24910
26079
  }
24911
26080
  }
24912
26081
  for (const dbRow of redo) {
@@ -24914,9 +26083,9 @@ ${transcriptText}`,
24914
26083
  log3(`reconcile: re-running lost post-processing for job ${dbRow.id}`);
24915
26084
  const outputs = await this.runPostProcessing(dbRow.id);
24916
26085
  if (outputs.length > 0) acted++;
24917
- } catch (err3) {
26086
+ } catch (err4) {
24918
26087
  log3(
24919
- `post-processing redo failed for job ${dbRow.id}: ${err3.message}`
26088
+ `post-processing redo failed for job ${dbRow.id}: ${err4.message}`
24920
26089
  );
24921
26090
  }
24922
26091
  }
@@ -24936,9 +26105,9 @@ ${transcriptText}`,
24936
26105
  * Otherwise apply the 24h give-up (API errors must not defer it forever),
24937
26106
  * and touch the row so it rotates to the back of the sweep window.
24938
26107
  */
24939
- async _reconcileError(job, err3) {
24940
- const message = err3.message ?? String(err3);
24941
- if (err3.status === 404) {
26108
+ async _reconcileError(job, err4) {
26109
+ const message = err4.message ?? String(err4);
26110
+ if (err4.status === 404) {
24942
26111
  await this._fail(
24943
26112
  job.id,
24944
26113
  `Recall no longer knows this recording: ${message}`
@@ -25134,15 +26303,15 @@ var request2 = async (path4, init = {}) => {
25134
26303
  let res;
25135
26304
  try {
25136
26305
  res = await fetch(url, init);
25137
- } catch (err3) {
26306
+ } catch (err4) {
25138
26307
  throw new TranscriptionServerUnavailable(
25139
- `Unable to reach whisper server at ${url}: ${err3.message}`
26308
+ `Unable to reach whisper server at ${url}: ${err4.message}`
25140
26309
  );
25141
26310
  }
25142
26311
  if (res.status === 404) {
25143
- const err3 = new Error(`whisper server returned 404 for ${path4}`);
25144
- err3.code = "JOB_NOT_FOUND";
25145
- throw err3;
26312
+ const err4 = new Error(`whisper server returned 404 for ${path4}`);
26313
+ err4.code = "JOB_NOT_FOUND";
26314
+ throw err4;
25146
26315
  }
25147
26316
  if (!res.ok) {
25148
26317
  throw new Error(
@@ -25293,13 +26462,13 @@ var transcriptionService = {
25293
26462
  updatedAt: /* @__PURE__ */ new Date()
25294
26463
  }).returning("*");
25295
26464
  return this._rowFromDb(updated);
25296
- } catch (err3) {
26465
+ } catch (err4) {
25297
26466
  const [failed] = await db2(TABLE3).where({ id: row.id }).update({
25298
26467
  status: "failed",
25299
- error: err3.message,
26468
+ error: err4.message,
25300
26469
  updatedAt: /* @__PURE__ */ new Date()
25301
26470
  }).returning("*");
25302
- log4(`Failed to dispatch job ${row.id}: ${err3.message}`);
26471
+ log4(`Failed to dispatch job ${row.id}: ${err4.message}`);
25303
26472
  return this._rowFromDb(failed);
25304
26473
  }
25305
26474
  },
@@ -25318,18 +26487,18 @@ var transcriptionService = {
25318
26487
  try {
25319
26488
  const job = await transcriptionClient.getJob(row.whisper_job_id);
25320
26489
  await this._applyJobUpdate(row, job);
25321
- } catch (err3) {
25322
- const code = err3.code;
26490
+ } catch (err4) {
26491
+ const code = err4.code;
25323
26492
  if (code === "JOB_NOT_FOUND") {
25324
26493
  await db2(TABLE3).where({ id: row.id }).update({
25325
26494
  status: "failed",
25326
26495
  error: "lost on server restart",
25327
26496
  updatedAt: /* @__PURE__ */ new Date()
25328
26497
  });
25329
- } else if (err3 instanceof TranscriptionServerUnavailable) {
26498
+ } else if (err4 instanceof TranscriptionServerUnavailable) {
25330
26499
  log4(`Whisper server unreachable while polling ${row.id}; will retry`);
25331
26500
  } else {
25332
- log4(`Error polling job ${row.id}: ${err3.message}`);
26501
+ log4(`Error polling job ${row.id}: ${err4.message}`);
25333
26502
  }
25334
26503
  }
25335
26504
  }
@@ -25356,8 +26525,8 @@ var transcriptionService = {
25356
26525
  row.post_processing_prompts,
25357
26526
  row.post_processing_outputs
25358
26527
  )) {
25359
- void recallService.runPostProcessing(row.id).catch((err3) => {
25360
- log4(`post-processing for upload ${row.id} failed: ${err3.message}`);
26528
+ void recallService.runPostProcessing(row.id).catch((err4) => {
26529
+ log4(`post-processing for upload ${row.id} failed: ${err4.message}`);
25361
26530
  });
25362
26531
  }
25363
26532
  return;
@@ -25385,10 +26554,10 @@ var transcriptionService = {
25385
26554
  if (row.whisper_job_id && transcriptionClient.isConfigured()) {
25386
26555
  try {
25387
26556
  await transcriptionClient.cancelJob(row.whisper_job_id);
25388
- } catch (err3) {
25389
- const code = err3.code;
26557
+ } catch (err4) {
26558
+ const code = err4.code;
25390
26559
  if (code !== "JOB_NOT_FOUND") {
25391
- log4(`Best-effort cancel of whisper job failed: ${err3.message}`);
26560
+ log4(`Best-effort cancel of whisper job failed: ${err4.message}`);
25392
26561
  }
25393
26562
  }
25394
26563
  }
@@ -25498,13 +26667,13 @@ var transcriptionService = {
25498
26667
  // upsert when re-saving
25499
26668
  );
25500
26669
  item = result.item;
25501
- } catch (err3) {
26670
+ } catch (err4) {
25502
26671
  await db2(TABLE3).where({ id }).update({
25503
26672
  speakers: JSON.stringify(input.speakers),
25504
- error: `Failed to save: ${err3.message}`,
26673
+ error: `Failed to save: ${err4.message}`,
25505
26674
  updatedAt: /* @__PURE__ */ new Date()
25506
26675
  });
25507
- throw err3;
26676
+ throw err4;
25508
26677
  }
25509
26678
  const itemId = item.id ?? row.saved_item_id ?? "";
25510
26679
  const users = input.target_rbac_users ?? row.target_rbac_users ?? [];
@@ -25518,8 +26687,8 @@ var transcriptionService = {
25518
26687
  { users, roles },
25519
26688
  []
25520
26689
  );
25521
- } catch (err3) {
25522
- log4(`RBAC update failed for item ${itemId}: ${err3.message}`);
26690
+ } catch (err4) {
26691
+ log4(`RBAC update failed for item ${itemId}: ${err4.message}`);
25523
26692
  }
25524
26693
  }
25525
26694
  const projectId = input.project_id ?? row.project_id ?? null;
@@ -25540,8 +26709,8 @@ var transcriptionService = {
25540
26709
  });
25541
26710
  }
25542
26711
  }
25543
- } catch (err3) {
25544
- projectWarning = err3.message;
26712
+ } catch (err4) {
26713
+ projectWarning = err4.message;
25545
26714
  }
25546
26715
  }
25547
26716
  const nextCorrectedSegments = input.corrected_segments !== void 0 ? input.corrected_segments : row.corrected_segments;
@@ -25582,9 +26751,9 @@ var transcriptionService = {
25582
26751
  const { db: db2 } = await postgresClient();
25583
26752
  try {
25584
26753
  await assertOwnsTranscriptionJob(db2, user, jobId);
25585
- } catch (err3) {
25586
- if (err3 instanceof TranscriptionJobAccessError) return void 0;
25587
- throw err3;
26754
+ } catch (err4) {
26755
+ if (err4 instanceof TranscriptionJobAccessError) return void 0;
26756
+ throw err4;
25588
26757
  }
25589
26758
  const dbRow = await db2(TABLE3).where({ id: jobId }).first();
25590
26759
  if (!dbRow) return void 0;
@@ -25718,8 +26887,8 @@ var liveRecordingService = {
25718
26887
  );
25719
26888
  }
25720
26889
  log5(`live recording ${id} stopped \u2192 awaiting_review`);
25721
- void recallService.runPostProcessing(id).catch((err3) => {
25722
- log5(`post-processing for job ${id} failed: ${err3.message}`);
26890
+ void recallService.runPostProcessing(id).catch((err4) => {
26891
+ log5(`post-processing for job ${id} failed: ${err4.message}`);
25723
26892
  });
25724
26893
  return rowFromDb(updated);
25725
26894
  }
@@ -25727,7 +26896,7 @@ var liveRecordingService = {
25727
26896
 
25728
26897
  // src/exulu/email-inbound/trigger-config.ts
25729
26898
  init_cjs_shims();
25730
- var import_node_crypto12 = require("crypto");
26899
+ var import_node_crypto13 = require("crypto");
25731
26900
  var import_safe_regex = __toESM(require("safe-regex"), 1);
25732
26901
  var MAX_FILTER_PATTERN_LENGTH = 200;
25733
26902
  var FILTER_FIELDS = [
@@ -25821,10 +26990,10 @@ function validateEmailTriggerConfig(raw) {
25821
26990
  return config;
25822
26991
  }
25823
26992
  function generateTriggerSecret() {
25824
- return (0, import_node_crypto12.randomBytes)(32).toString("base64url");
26993
+ return (0, import_node_crypto13.randomBytes)(32).toString("base64url");
25825
26994
  }
25826
26995
  function generateSigningSecret() {
25827
- return (0, import_node_crypto12.randomBytes)(32).toString("base64url");
26996
+ return (0, import_node_crypto13.randomBytes)(32).toString("base64url");
25828
26997
  }
25829
26998
 
25830
26999
  // src/graphql/schemas/index.ts
@@ -25854,9 +27023,9 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
25854
27023
  for (let attempt = 0; attempt < 5; attempt++) {
25855
27024
  try {
25856
27025
  return await insertFn({ ...baseRow, secret: generateTriggerSecret() });
25857
- } catch (err3) {
25858
- if (err3?.code === "23505") continue;
25859
- throw err3;
27026
+ } catch (err4) {
27027
+ if (err4?.code === "23505") continue;
27028
+ throw err4;
25860
27029
  }
25861
27030
  }
25862
27031
  throw new Error("Could not generate a unique trigger secret.");
@@ -25864,11 +27033,11 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
25864
27033
 
25865
27034
  // src/exulu/email-inbound/webhook.ts
25866
27035
  init_cjs_shims();
25867
- var import_node_crypto14 = require("crypto");
27036
+ var import_node_crypto15 = require("crypto");
25868
27037
 
25869
27038
  // src/exulu/email-inbound/verify-signature.ts
25870
27039
  init_cjs_shims();
25871
- var import_node_crypto13 = require("crypto");
27040
+ var import_node_crypto14 = require("crypto");
25872
27041
  var SIGNATURE_REPLAY_WINDOW_SECONDS = 300;
25873
27042
  var REPLAY_TTL_SECONDS = 900;
25874
27043
  function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secret) {
@@ -25877,11 +27046,11 @@ function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secre
25877
27046
  const provided = signatureHeader.slice("sha256=".length);
25878
27047
  if (!/^[0-9a-f]+$/i.test(provided)) return false;
25879
27048
  const message = timestampHeader ? Buffer.concat([Buffer.from(`${timestampHeader}.`), rawBody]) : rawBody;
25880
- const expected = (0, import_node_crypto13.createHmac)("sha256", secret).update(message).digest("hex");
27049
+ const expected = (0, import_node_crypto14.createHmac)("sha256", secret).update(message).digest("hex");
25881
27050
  const expectedBuf = Buffer.from(expected, "utf8");
25882
27051
  const providedBuf = Buffer.from(provided.toLowerCase(), "utf8");
25883
27052
  if (expectedBuf.length !== providedBuf.length) return false;
25884
- return (0, import_node_crypto13.timingSafeEqual)(expectedBuf, providedBuf);
27053
+ return (0, import_node_crypto14.timingSafeEqual)(expectedBuf, providedBuf);
25885
27054
  }
25886
27055
  async function isReplay(redis, signature, timestamp) {
25887
27056
  const ts = Number(timestamp);
@@ -25894,10 +27063,10 @@ async function isReplay(redis, signature, timestamp) {
25894
27063
  EX: REPLAY_TTL_SECONDS
25895
27064
  });
25896
27065
  return result === null;
25897
- } catch (err3) {
27066
+ } catch (err4) {
25898
27067
  console.error(
25899
27068
  "[EXULU] routine-webhook replay guard: redis unavailable, degrading to window-only",
25900
- err3 instanceof Error ? err3.message : String(err3)
27069
+ err4 instanceof Error ? err4.message : String(err4)
25901
27070
  );
25902
27071
  return false;
25903
27072
  }
@@ -25970,8 +27139,8 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
25970
27139
  payloadBytes = rawBody;
25971
27140
  format = "eml";
25972
27141
  }
25973
- } catch (err3) {
25974
- res.status(400).json({ detail: err3 instanceof Error ? err3.message : "bad payload" });
27142
+ } catch (err4) {
27143
+ res.status(400).json({ detail: err4 instanceof Error ? err4.message : "bad payload" });
25975
27144
  return;
25976
27145
  }
25977
27146
  void deps.stampLastFiredAt(db2, trigger.id).catch(
@@ -25979,7 +27148,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
25979
27148
  );
25980
27149
  try {
25981
27150
  const ext = format === "json" ? "json" : "eml";
25982
- const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${(0, import_node_crypto14.randomUUID)()}.${ext}`, payloadBytes);
27151
+ const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${(0, import_node_crypto15.randomUUID)()}.${ext}`, payloadBytes);
25983
27152
  await deps.enqueueIntake({ s3Key, triggerId: trigger.id, format });
25984
27153
  } catch (error) {
25985
27154
  console.error("[EXULU-WEBHOOK] persist/enqueue failed", error);
@@ -25991,7 +27160,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
25991
27160
 
25992
27161
  // src/graphql/schemas/index.ts
25993
27162
  init_uppy();
25994
- var import_node_crypto15 = require("crypto");
27163
+ var import_node_crypto16 = require("crypto");
25995
27164
  init_memory_base();
25996
27165
 
25997
27166
  // src/graphql/resolvers/memory-base-stats.ts
@@ -27535,6 +28704,8 @@ function createSDL(tables, contexts, tools, config, evals) {
27535
28704
  mutationDefs += `
27536
28705
  ${tableNameSingular}GenerateChunks(where: [Filter${tableNameSingularUpperCaseFirst}], limit: Int): ${tableNameSingular}GenerateChunksReturnPayload
27537
28706
  ${tableNameSingular}ExecuteSource(source: ID!, inputs: JSON!): ${tableNameSingular}ExecuteSourceReturnPayload
28707
+ ${tableNameSingular}StartImport(input: StartImportInput!): StartImportPayload
28708
+ ${tableNameSingular}CancelImport(jobResultId: ID!): CancelImportPayload
27538
28709
  ${tableNameSingular}DeleteChunks(where: [Filter${tableNameSingularUpperCaseFirst}], limit: Int): ${tableNameSingular}DeleteChunksReturnPayload
27539
28710
  ${tableNameSingular}BackfillEntities(onlyStale: Boolean, limit: Int): ${tableNameSingular}EntityBackfillPayload
27540
28711
  ${tableNameSingular}PurgeEntityType(type: String!): ${tableNameSingular}EntityPurgePayload
@@ -27573,6 +28744,40 @@ function createSDL(tables, contexts, tools, config, evals) {
27573
28744
  items: [String!]
27574
28745
  }
27575
28746
 
28747
+ input StartImportMappingInput {
28748
+ header: String!
28749
+ fieldName: String
28750
+ }
28751
+
28752
+ input StartImportAccessInput {
28753
+ rights_mode: String!
28754
+ users: JSON
28755
+ roles: JSON
28756
+ teams: JSON
28757
+ }
28758
+
28759
+ input StartImportOptionsInput {
28760
+ skipEmbeddings: Boolean
28761
+ delimiter: String
28762
+ }
28763
+
28764
+ input StartImportInput {
28765
+ s3Key: String!
28766
+ fileName: String!
28767
+ mapping: [StartImportMappingInput!]
28768
+ access: StartImportAccessInput!
28769
+ options: StartImportOptionsInput
28770
+ totalRows: Int
28771
+ }
28772
+
28773
+ type StartImportPayload {
28774
+ jobResultId: ID!
28775
+ }
28776
+
28777
+ type CancelImportPayload {
28778
+ ok: Boolean!
28779
+ }
28780
+
27576
28781
  type ${tableNameSingular}ProcessItemFieldReturnPayload {
27577
28782
  message: String!
27578
28783
  results: [String]
@@ -28107,8 +29312,8 @@ type EmbeddingModelOption {
28107
29312
  maxChunkSize: m.maxChunkSize,
28108
29313
  maxBatchSize: m.maxBatchSize
28109
29314
  }));
28110
- } catch (err3) {
28111
- console.warn("[EXULU] Could not read embedding models:", err3.message);
29315
+ } catch (err4) {
29316
+ console.warn("[EXULU] Could not read embedding models:", err4.message);
28112
29317
  return [];
28113
29318
  }
28114
29319
  };
@@ -28301,9 +29506,9 @@ type EmbeddingModelOption {
28301
29506
  throw new Error("You don't have access to this workflow template.");
28302
29507
  }
28303
29508
  const hasWorkflowsWriteRole = user?.super_admin || user?.role?.workflows === "write";
28304
- const canWrite = hasWorkflowsWriteRole && await checkRecordAccess(workflowTemplate, "write", user);
29509
+ const canWrite2 = hasWorkflowsWriteRole && await checkRecordAccess(workflowTemplate, "write", user);
28305
29510
  const rows = await db2.from("workflow_triggers").where({ workflow: args.workflow }).orderBy("createdAt", "asc");
28306
- return rows.map((r) => toWorkflowTriggerPayload(r, { canWrite }));
29511
+ return rows.map((r) => toWorkflowTriggerPayload(r, { canWrite: canWrite2 }));
28307
29512
  };
28308
29513
  resolvers.Mutation["upsertWorkflowEmailTrigger"] = async (_, args, context) => {
28309
29514
  if (!args.workflow) {
@@ -28384,9 +29589,9 @@ type EmbeddingModelOption {
28384
29589
  const rows = await db2.from("workflow_triggers").where({ id: args.id }).update({ secret: generateTriggerSecret(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).returning("*");
28385
29590
  updated = rows[0];
28386
29591
  break;
28387
- } catch (err3) {
28388
- if (err3?.code === "23505") continue;
28389
- throw err3;
29592
+ } catch (err4) {
29593
+ if (err4?.code === "23505") continue;
29594
+ throw err4;
28390
29595
  }
28391
29596
  }
28392
29597
  if (!updated) throw new Error("Could not generate a unique trigger secret.");
@@ -28432,13 +29637,13 @@ type EmbeddingModelOption {
28432
29637
  bytes = Buffer.from(args.payload, "latin1");
28433
29638
  format = "eml";
28434
29639
  }
28435
- } catch (err3) {
28436
- return { outcome: "error", error: err3 instanceof Error ? err3.message : "bad payload" };
29640
+ } catch (err4) {
29641
+ return { outcome: "error", error: err4 instanceof Error ? err4.message : "bad payload" };
28437
29642
  }
28438
29643
  const ext = format === "json" ? "json" : "eml";
28439
29644
  const fullKey = await uploadFile(
28440
29645
  bytes,
28441
- `${EMAIL_INBOUND_S3_PREFIX}${(0, import_node_crypto15.randomUUID)()}.${ext}`,
29646
+ `${EMAIL_INBOUND_S3_PREFIX}${(0, import_node_crypto16.randomUUID)()}.${ext}`,
28442
29647
  config,
28443
29648
  { contentType: "application/octet-stream" },
28444
29649
  void 0,
@@ -28623,11 +29828,11 @@ type EmbeddingModelOption {
28623
29828
  user
28624
29829
  );
28625
29830
  return new Map(rows.map((row) => [row.id, row]));
28626
- } catch (err3) {
28627
- if (err3 instanceof Error && err3.message.startsWith("Access control error")) {
29831
+ } catch (err4) {
29832
+ if (err4 instanceof Error && err4.message.startsWith("Access control error")) {
28628
29833
  return /* @__PURE__ */ new Map();
28629
29834
  }
28630
- throw err3;
29835
+ throw err4;
28631
29836
  }
28632
29837
  };
28633
29838
  const loadRoutineRunForWrite = async (db2, user, id) => {
@@ -29141,8 +30346,8 @@ type EmbeddingModelOption {
29141
30346
  stuck_count: num7(stuckRow?.c),
29142
30347
  stale_count: num7(staleRow?.c)
29143
30348
  };
29144
- } catch (err3) {
29145
- console.error("[EXULU] computeContextAggregates failed for", contextId, err3);
30349
+ } catch (err4) {
30350
+ console.error("[EXULU] computeContextAggregates failed for", contextId, err4);
29146
30351
  return empty;
29147
30352
  }
29148
30353
  };
@@ -29688,9 +30893,9 @@ async function extractZipToPrefix(bytes, prefix, config) {
29688
30893
  let zip;
29689
30894
  try {
29690
30895
  zip = await import_jszip2.default.loadAsync(bytes);
29691
- } catch (err3) {
30896
+ } catch (err4) {
29692
30897
  throw new BundleValidationError(
29693
- `Could not parse zip file: ${err3?.message ?? "unknown error"}`
30898
+ `Could not parse zip file: ${err4?.message ?? "unknown error"}`
29694
30899
  );
29695
30900
  }
29696
30901
  const entries = [];
@@ -29794,7 +30999,7 @@ var import_body_parser = __toESM(require("body-parser"), 1);
29794
30999
  var import_crypto_js7 = require("crypto-js");
29795
31000
  var import_openai = require("openai");
29796
31001
  var import_fs4 = __toESM(require("fs"), 1);
29797
- var import_node_crypto19 = require("crypto");
31002
+ var import_node_crypto20 = require("crypto");
29798
31003
  var import_api2 = require("@opentelemetry/api");
29799
31004
  init_check_record_access();
29800
31005
  var import_jszip4 = __toESM(require("jszip"), 1);
@@ -29802,7 +31007,7 @@ var import_jszip4 = __toESM(require("jszip"), 1);
29802
31007
  // src/skills/bundled.ts
29803
31008
  init_cjs_shims();
29804
31009
  var import_jszip3 = __toESM(require("jszip"), 1);
29805
- var import_node_crypto16 = require("crypto");
31010
+ var import_node_crypto17 = require("crypto");
29806
31011
 
29807
31012
  // src/skills/bundled.generated.ts
29808
31013
  init_cjs_shims();
@@ -29826,7 +31031,7 @@ var BUNDLED_SKILLS = [
29826
31031
  init_frontmatter();
29827
31032
  var BUNDLED_LABEL = "Bundled with the IMP";
29828
31033
  function bundledSkillHash(skill) {
29829
- const h = (0, import_node_crypto16.createHash)("sha256");
31034
+ const h = (0, import_node_crypto17.createHash)("sha256");
29830
31035
  for (const path4 of Object.keys(skill.files).sort()) {
29831
31036
  h.update(path4).update("\0").update(skill.files[path4]).update("\0");
29832
31037
  }
@@ -29887,7 +31092,7 @@ async function seedBundledSkills({
29887
31092
  log7(`"${skill.name}" updated to v${nextVersion}`);
29888
31093
  continue;
29889
31094
  }
29890
- const skillId = (0, import_node_crypto16.randomUUID)();
31095
+ const skillId = (0, import_node_crypto17.randomUUID)();
29891
31096
  await extractBundleToVersion({ bytes: await bundledSkillZip(skill), skillId, version: 1, config });
29892
31097
  await db2("skills").insert({
29893
31098
  id: skillId,
@@ -29989,7 +31194,7 @@ init_context_budget();
29989
31194
 
29990
31195
  // src/exulu/compact-session.ts
29991
31196
  init_cjs_shims();
29992
- var import_node_crypto17 = require("crypto");
31197
+ var import_node_crypto18 = require("crypto");
29993
31198
  var import_ai11 = require("ai");
29994
31199
  init_truncate_tool_output();
29995
31200
  init_context_budget();
@@ -30094,7 +31299,7 @@ Focus especially on: ${steer.trim()}` : SUMMARY_SYSTEM;
30094
31299
  ...steer?.trim() ? { steer: steer.trim() } : {}
30095
31300
  };
30096
31301
  const checkpoint = {
30097
- id: `compaction_${(0, import_node_crypto17.randomUUID)()}`,
31302
+ id: `compaction_${(0, import_node_crypto18.randomUUID)()}`,
30098
31303
  role: "user",
30099
31304
  parts: [{ type: "text", text: `[Conversation summary \u2014 earlier messages were compacted]
30100
31305
 
@@ -30109,19 +31314,19 @@ ${summary}` }],
30109
31314
  init_cjs_shims();
30110
31315
  var import_ai12 = require("ai");
30111
31316
  init_context_budget();
30112
- function describeRequestError(err3) {
30113
- if (err3 instanceof ContextCompactionRequiredError) {
30114
- return { status: 413, body: err3.message };
31317
+ function describeRequestError(err4) {
31318
+ if (err4 instanceof ContextCompactionRequiredError) {
31319
+ return { status: 413, body: err4.message };
30115
31320
  }
30116
- if (import_ai12.TypeValidationError.isInstance(err3)) {
30117
- const cause = err3.cause;
31321
+ if (import_ai12.TypeValidationError.isInstance(err4)) {
31322
+ const cause = err4.cause;
30118
31323
  const detail = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
30119
31324
  return {
30120
31325
  status: 422,
30121
31326
  body: `The stored conversation could not be loaded: ${detail.slice(0, 400) || "type validation failed"}`
30122
31327
  };
30123
31328
  }
30124
- return { status: 500, body: err3 instanceof Error ? err3.message : String(err3) };
31329
+ return { status: 500, body: err4 instanceof Error ? err4.message : String(err4) };
30125
31330
  }
30126
31331
 
30127
31332
  // src/exulu/memory/recalled-metadata.ts
@@ -30576,12 +31781,12 @@ function registerLiveRecordingChunkRoute(app, deps) {
30576
31781
  const db2 = await deps.getDb();
30577
31782
  try {
30578
31783
  await deps.assertOwns(db2, user, jobId);
30579
- } catch (err3) {
30580
- if (err3 instanceof TranscriptionJobAccessError) {
30581
- res.status(err3.code).json({ detail: err3.message });
31784
+ } catch (err4) {
31785
+ if (err4 instanceof TranscriptionJobAccessError) {
31786
+ res.status(err4.code).json({ detail: err4.message });
30582
31787
  return;
30583
31788
  }
30584
- throw err3;
31789
+ throw err4;
30585
31790
  }
30586
31791
  const row = await db2.from("transcription_jobs").select(["status", "raw_segments", "project_id"]).where({ id: jobId }).first();
30587
31792
  if (!row) {
@@ -30636,14 +31841,14 @@ function registerLiveRecordingChunkRoute(app, deps) {
30636
31841
  priorText: LIVE_PRIOR_TEXT_ENABLED ? priorTextFrom(row.raw_segments) : void 0,
30637
31842
  tags
30638
31843
  }));
30639
- } catch (err3) {
30640
- if (err3 instanceof TranscriptionError) {
30641
- const code = err3.upstreamStatus >= 500 ? 502 : err3.upstreamStatus;
30642
- res.status(code).json({ detail: err3.message });
31844
+ } catch (err4) {
31845
+ if (err4 instanceof TranscriptionError) {
31846
+ const code = err4.upstreamStatus >= 500 ? 502 : err4.upstreamStatus;
31847
+ res.status(code).json({ detail: err4.message });
30643
31848
  return;
30644
31849
  }
30645
- console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`, err3);
30646
- res.status(500).json({ detail: err3 instanceof Error ? err3.message : "Transcription failed." });
31850
+ console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`, err4);
31851
+ res.status(500).json({ detail: err4 instanceof Error ? err4.message : "Transcription failed." });
30647
31852
  return;
30648
31853
  }
30649
31854
  }
@@ -30737,7 +31942,7 @@ var formatSrtTime = (seconds) => {
30737
31942
  const ms = String(totalMs % 1e3).padStart(3, "0");
30738
31943
  return `${formatCsvTime(wholeSeconds)},${ms}`;
30739
31944
  };
30740
- var csvField = (value, isTextField = false) => {
31945
+ var csvField2 = (value, isTextField = false) => {
30741
31946
  const needsQuote = /["\n\r,]/.test(value) || isTextField;
30742
31947
  return needsQuote ? `"${value.replace(/"/g, '""')}"` : value;
30743
31948
  };
@@ -30751,7 +31956,7 @@ function buildTranscriptCsv(item, options) {
30751
31956
  const label = resolveLabel(item, segment.speaker, options.speakers);
30752
31957
  const text = (segment.text ?? "").trim();
30753
31958
  const cells = options.timestamps ? [formatCsvTime(segment.start), formatCsvTime(segment.end), label, text] : [label, text];
30754
- return cells.map((value, i) => csvField(value, i === cells.length - 1)).join(",");
31959
+ return cells.map((value, i) => csvField2(value, i === cells.length - 1)).join(",");
30755
31960
  });
30756
31961
  return [header2, ...rows].join("\n") + "\n";
30757
31962
  }
@@ -30811,8 +32016,8 @@ function registerTranscriptExportRoute(app, deps) {
30811
32016
  `attachment; filename="${encodeURIComponent(filename)}"`
30812
32017
  );
30813
32018
  res.send(body);
30814
- } catch (err3) {
30815
- console.error("[EXULU] transcript export failed", err3);
32019
+ } catch (err4) {
32020
+ console.error("[EXULU] transcript export failed", err4);
30816
32021
  res.status(500).json({ detail: "Export failed." });
30817
32022
  }
30818
32023
  });
@@ -30862,8 +32067,8 @@ function registerTranscriptExportRoute(app, deps) {
30862
32067
  `attachment; filename="${encodeURIComponent(filename)}"`
30863
32068
  );
30864
32069
  res.send(body);
30865
- } catch (err3) {
30866
- console.error("[EXULU] transcript job export failed", err3);
32070
+ } catch (err4) {
32071
+ console.error("[EXULU] transcript job export failed", err4);
30867
32072
  res.status(500).json({ detail: "Export failed." });
30868
32073
  }
30869
32074
  });
@@ -30936,7 +32141,7 @@ function pipelineConfigFor(agent) {
30936
32141
  // ee/claim-check/routes.ts
30937
32142
  var CLAIM_CHECK_PATH = "/claims/check";
30938
32143
  var CLAIM_CHECK_SESSION_PATH = "/claims/check/:session";
30939
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
32144
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
30940
32145
  function hasNumericUserId(user) {
30941
32146
  return Boolean(user?.id) && Number.isFinite(Number(user?.id));
30942
32147
  }
@@ -31097,9 +32302,9 @@ function registerClaimCheckRoutes(app, deps) {
31097
32302
  }
31098
32303
  try {
31099
32304
  agent = await deps.getAgent(body.agent);
31100
- } catch (err3) {
32305
+ } catch (err4) {
31101
32306
  console.warn(
31102
- `[EXULU] claim check: agent lookup for "${body.agent}" failed: ${err3 instanceof Error ? err3.message : String(err3)}`
32307
+ `[EXULU] claim check: agent lookup for "${body.agent}" failed: ${err4 instanceof Error ? err4.message : String(err4)}`
31103
32308
  );
31104
32309
  }
31105
32310
  if (!agent) {
@@ -31124,7 +32329,7 @@ function registerClaimCheckRoutes(app, deps) {
31124
32329
  });
31125
32330
  return;
31126
32331
  }
31127
- if (deps.findClaimCheck && body.session && body.messageId && UUID_RE.test(body.session)) {
32332
+ if (deps.findClaimCheck && body.session && body.messageId && UUID_RE2.test(body.session)) {
31128
32333
  try {
31129
32334
  const stored = await deps.findClaimCheck({
31130
32335
  session: body.session,
@@ -31135,10 +32340,10 @@ function registerClaimCheckRoutes(app, deps) {
31135
32340
  res.status(200).json(stored);
31136
32341
  return;
31137
32342
  }
31138
- } catch (err3) {
32343
+ } catch (err4) {
31139
32344
  console.warn(
31140
32345
  "[EXULU claim-check] could not read the stored check for this message; running the check.",
31141
- err3
32346
+ err4
31142
32347
  );
31143
32348
  }
31144
32349
  }
@@ -31164,10 +32369,10 @@ function registerClaimCheckRoutes(app, deps) {
31164
32369
  model = resolved.languageModel;
31165
32370
  break;
31166
32371
  }
31167
- } catch (err3) {
31168
- lastError = err3;
32372
+ } catch (err4) {
32373
+ lastError = err4;
31169
32374
  console.warn(
31170
- `[EXULU] claim check: model "${modelId}" failed to resolve: ${err3 instanceof Error ? err3.message : String(err3)}`
32375
+ `[EXULU] claim check: model "${modelId}" failed to resolve: ${err4 instanceof Error ? err4.message : String(err4)}`
31171
32376
  );
31172
32377
  }
31173
32378
  }
@@ -31231,21 +32436,21 @@ function registerClaimCheckRoutes(app, deps) {
31231
32436
  ]);
31232
32437
  completedResult = result;
31233
32438
  res.status(200).json(result);
31234
- } catch (err3) {
31235
- if (err3 instanceof ClaimCheckTimeoutError) {
32439
+ } catch (err4) {
32440
+ if (err4 instanceof ClaimCheckTimeoutError) {
31236
32441
  console.warn(`[EXULU] claim check exceeded the ${timeoutMs} ms deadline.`);
31237
32442
  res.status(504).json({
31238
32443
  detail: `The claim check did not finish within ${timeoutMs / 1e3} seconds and was cancelled.`
31239
32444
  });
31240
32445
  } else {
31241
- console.error("[EXULU] claim check failed.", err3);
32446
+ console.error("[EXULU] claim check failed.", err4);
31242
32447
  res.status(500).json({ detail: "The claim check failed." });
31243
32448
  }
31244
32449
  } finally {
31245
32450
  if (deadline) clearTimeout(deadline);
31246
32451
  deps.limiter.release();
31247
32452
  }
31248
- if (completedResult && body.session && body.messageId && UUID_RE.test(body.session)) {
32453
+ if (completedResult && body.session && body.messageId && UUID_RE2.test(body.session)) {
31249
32454
  if (!deps.saveClaimCheck) {
31250
32455
  console.error(
31251
32456
  "[EXULU claim-check] saveClaimCheck is not wired; this check cannot survive a reload."
@@ -31258,8 +32463,8 @@ function registerClaimCheckRoutes(app, deps) {
31258
32463
  userId: Number(user.id),
31259
32464
  result: completedResult
31260
32465
  });
31261
- } catch (err3) {
31262
- console.warn("[EXULU claim-check] could not store the check for this message.", err3);
32466
+ } catch (err4) {
32467
+ console.warn("[EXULU claim-check] could not store the check for this message.", err4);
31263
32468
  }
31264
32469
  }
31265
32470
  }
@@ -31270,7 +32475,7 @@ function registerClaimCheckRoutes(app, deps) {
31270
32475
  return;
31271
32476
  }
31272
32477
  const session = req.params.session ?? "";
31273
- if (!UUID_RE.test(session)) {
32478
+ if (!UUID_RE2.test(session)) {
31274
32479
  res.status(400).json({ detail: "session must be a uuid." });
31275
32480
  return;
31276
32481
  }
@@ -31287,8 +32492,8 @@ function registerClaimCheckRoutes(app, deps) {
31287
32492
  try {
31288
32493
  const checks = await deps.listClaimChecks({ session, userId: Number(auth.user.id) });
31289
32494
  res.status(200).json({ checks });
31290
- } catch (err3) {
31291
- console.error("[EXULU claim-check] could not read stored checks.", err3);
32495
+ } catch (err4) {
32496
+ console.error("[EXULU claim-check] could not read stored checks.", err4);
31292
32497
  res.status(500).json({ detail: "Could not read stored checks." });
31293
32498
  }
31294
32499
  });
@@ -32634,9 +33839,9 @@ async function runClaimCheck(args) {
32634
33839
  limits: { truncated: skipped.length > 0 || truncation.sources > 0, sentencesSkipped: skipped.length },
32635
33840
  notes: state.notes
32636
33841
  };
32637
- } catch (err3) {
33842
+ } catch (err4) {
32638
33843
  timings.totalMs = Date.now() - startedAt;
32639
- const message = err3 instanceof Error ? err3.message : String(err3);
33844
+ const message = err4 instanceof Error ? err4.message : String(err4);
32640
33845
  return {
32641
33846
  status: "partial",
32642
33847
  score: scoreClaims([], options.thresholds),
@@ -32698,8 +33903,8 @@ function makeSecondChance(args) {
32698
33903
  }))
32699
33904
  );
32700
33905
  return selectEvidence([claimText], index, MAX_SNIPPETS_PER_CLAIM);
32701
- } catch (err3) {
32702
- console.warn("[EXULU claim-check] second-chance retrieval failed:", err3);
33906
+ } catch (err4) {
33907
+ console.warn("[EXULU claim-check] second-chance retrieval failed:", err4);
32703
33908
  return [];
32704
33909
  }
32705
33910
  };
@@ -32747,8 +33952,8 @@ async function testSource(source, deps) {
32747
33952
  try {
32748
33953
  await entry.ping();
32749
33954
  return { ok: true };
32750
- } catch (err3) {
32751
- return { ok: false, reason: "unreachable", message: err3.message };
33955
+ } catch (err4) {
33956
+ return { ok: false, reason: "unreachable", message: err4.message };
32752
33957
  }
32753
33958
  }
32754
33959
 
@@ -33447,7 +34652,7 @@ init_flow();
33447
34652
 
33448
34653
  // src/exulu/recall/verify.ts
33449
34654
  init_cjs_shims();
33450
- var import_node_crypto18 = require("crypto");
34655
+ var import_node_crypto19 = require("crypto");
33451
34656
  var TOLERANCE_SECONDS = 5 * 60;
33452
34657
  var header = (headers, ...names) => {
33453
34658
  for (const name of names) {
@@ -33465,7 +34670,7 @@ var safeEqual = (a, b) => {
33465
34670
  const bufA = Buffer.from(a);
33466
34671
  const bufB = Buffer.from(b);
33467
34672
  if (bufA.length !== bufB.length) return false;
33468
- return (0, import_node_crypto18.timingSafeEqual)(bufA, bufB);
34673
+ return (0, import_node_crypto19.timingSafeEqual)(bufA, bufB);
33469
34674
  };
33470
34675
  var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
33471
34676
  if (!secret) {
@@ -33487,7 +34692,7 @@ var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()
33487
34692
  }
33488
34693
  const body = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
33489
34694
  const signedContent = `${id}.${timestamp}.${body}`;
33490
- const expected = (0, import_node_crypto18.createHmac)("sha256", secretKey(secret)).update(signedContent).digest("base64");
34695
+ const expected = (0, import_node_crypto19.createHmac)("sha256", secretKey(secret)).update(signedContent).digest("base64");
33491
34696
  const passed = signatureHeader.split(" ").some((entry) => {
33492
34697
  const [, sig] = entry.split(",");
33493
34698
  return !!sig && safeEqual(sig, expected);
@@ -33852,6 +35057,7 @@ var {
33852
35057
  rbacSchema: rbacSchema2,
33853
35058
  promptLibrarySchema: promptLibrarySchema2,
33854
35059
  contextPresetsSchema: contextPresetsSchema2,
35060
+ contextFoldersSchema: contextFoldersSchema2,
33855
35061
  teamsSchema: teamsSchema2,
33856
35062
  entityTypeSettingsSchema: entityTypeSettingsSchema2,
33857
35063
  promptFavoritesSchema: promptFavoritesSchema2,
@@ -33914,6 +35120,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
33914
35120
  jobResultsSchema2(),
33915
35121
  promptLibrarySchema2(),
33916
35122
  contextPresetsSchema2(),
35123
+ // Knowledge folders (2026-10): UI-only grouping of knowledge contexts
35124
+ // for the IMP's folder view. apiWrites: "super_admin" (core-schema.ts)
35125
+ // reserves the generic CreateOne/UpdateOne*/RemoveOne*/CopyOneById
35126
+ // mutations for super admins; reads stay generic for every
35127
+ // authenticated user, same split as sharedArtifactsSchema below.
35128
+ contextFoldersSchema2(),
33917
35129
  teamsSchema2(),
33918
35130
  entityTypeSettingsSchema2(),
33919
35131
  promptFavoritesSchema2(),
@@ -34066,8 +35278,8 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
34066
35278
  }
34067
35279
  const event = req.body;
34068
35280
  res.status(200).json({ ok: true });
34069
- void recallService.handleWebhookEvent(event).catch((err3) => {
34070
- console.error("[EXULU-RECALL] webhook processing failed", err3);
35281
+ void recallService.handleWebhookEvent(event).catch((err4) => {
35282
+ console.error("[EXULU-RECALL] webhook processing failed", err4);
34071
35283
  });
34072
35284
  });
34073
35285
  const routineWebhookHandler = createRoutineWebhookHandler({
@@ -34098,7 +35310,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
34098
35310
  inputs: payload
34099
35311
  };
34100
35312
  await queue.queue.add("email-intake", jobData, {
34101
- jobId: (0, import_node_crypto19.randomUUID)(),
35313
+ jobId: (0, import_node_crypto20.randomUUID)(),
34102
35314
  attempts: 3,
34103
35315
  removeOnComplete: 5e3,
34104
35316
  removeOnFail: 1e4,
@@ -34294,13 +35506,13 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
34294
35506
  user,
34295
35507
  agent
34296
35508
  });
34297
- } catch (err3) {
34298
- if (err3 instanceof ResolveModelError) {
34299
- const status = err3.code === "MODEL_FORBIDDEN" ? 403 : 400;
34300
- res.status(status).json({ message: err3.message, code: err3.code });
35509
+ } catch (err4) {
35510
+ if (err4 instanceof ResolveModelError) {
35511
+ const status = err4.code === "MODEL_FORBIDDEN" ? 403 : 400;
35512
+ res.status(status).json({ message: err4.message, code: err4.code });
34301
35513
  return;
34302
35514
  }
34303
- throw err3;
35515
+ throw err4;
34304
35516
  }
34305
35517
  const resolvedLanguageModel = resolved.languageModel;
34306
35518
  const resolvedModelId = resolved.model.id;
@@ -34351,13 +35563,13 @@ ${customInstructions}` : agent.instructions,
34351
35563
  contextWindow,
34352
35564
  disabledTools
34353
35565
  });
34354
- } catch (err3) {
35566
+ } catch (err4) {
34355
35567
  if (headers.session) clearStreamActive(headers.session);
34356
35568
  console.error(
34357
35569
  "[EXULU] chat request failed before streaming.",
34358
- err3 instanceof Error ? err3.message.slice(0, 500) : err3
35570
+ err4 instanceof Error ? err4.message.slice(0, 500) : err4
34359
35571
  );
34360
- const { status, body } = describeRequestError(err3);
35572
+ const { status, body } = describeRequestError(err4);
34361
35573
  res.status(status).send(body);
34362
35574
  return;
34363
35575
  }
@@ -34469,7 +35681,7 @@ ${customInstructions}` : agent.instructions,
34469
35681
  contextId: agent.memory,
34470
35682
  agentId: agent.id,
34471
35683
  session: headers.session ?? null,
34472
- messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0, import_node_crypto19.randomUUID)(),
35684
+ messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0, import_node_crypto20.randomUUID)(),
34473
35685
  userId: user?.id ?? null
34474
35686
  });
34475
35687
  }
@@ -34548,12 +35760,12 @@ ${customInstructions}` : agent.instructions,
34548
35760
  onTokenUsage: async ({ inputTokens, outputTokens }) => {
34549
35761
  }
34550
35762
  });
34551
- } catch (err3) {
35763
+ } catch (err4) {
34552
35764
  console.error(
34553
35765
  "[EXULU] run request failed.",
34554
- err3 instanceof Error ? err3.message.slice(0, 500) : err3
35766
+ err4 instanceof Error ? err4.message.slice(0, 500) : err4
34555
35767
  );
34556
- const { status, body } = describeRequestError(err3);
35768
+ const { status, body } = describeRequestError(err4);
34557
35769
  res.status(status).send(body);
34558
35770
  return;
34559
35771
  }
@@ -34620,13 +35832,13 @@ ${customInstructions}` : agent.instructions,
34620
35832
  let resolved;
34621
35833
  try {
34622
35834
  resolved = await resolveModel({ modelId, user, agent });
34623
- } catch (err3) {
34624
- if (err3 instanceof ResolveModelError) {
34625
- const status = err3.code === "MODEL_FORBIDDEN" ? 403 : 400;
34626
- res.status(status).json({ message: err3.message, code: err3.code });
35835
+ } catch (err4) {
35836
+ if (err4 instanceof ResolveModelError) {
35837
+ const status = err4.code === "MODEL_FORBIDDEN" ? 403 : 400;
35838
+ res.status(status).json({ message: err4.message, code: err4.code });
34627
35839
  return;
34628
35840
  }
34629
- throw err3;
35841
+ throw err4;
34630
35842
  }
34631
35843
  const contextWindow = await resolveContextWindow({
34632
35844
  modelId: resolved.model.id
@@ -34642,13 +35854,13 @@ ${customInstructions}` : agent.instructions,
34642
35854
  modelId: resolved.model.id
34643
35855
  });
34644
35856
  res.json(result);
34645
- } catch (err3) {
34646
- if (err3 instanceof CompactionInsufficientError) {
34647
- res.status(422).send(err3.message);
35857
+ } catch (err4) {
35858
+ if (err4 instanceof CompactionInsufficientError) {
35859
+ res.status(422).send(err4.message);
34648
35860
  return;
34649
35861
  }
34650
- console.error("[EXULU] compactSession failed.", err3);
34651
- res.status(500).json({ message: err3 instanceof Error ? err3.message : "Compaction failed." });
35862
+ console.error("[EXULU] compactSession failed.", err4);
35863
+ res.status(500).json({ message: err4 instanceof Error ? err4.message : "Compaction failed." });
34652
35864
  }
34653
35865
  });
34654
35866
  };
@@ -34713,13 +35925,13 @@ ${customInstructions}` : agent.instructions,
34713
35925
  user,
34714
35926
  agent
34715
35927
  });
34716
- } catch (err3) {
34717
- if (err3 instanceof ResolveModelError) {
34718
- const status = err3.code === "MODEL_FORBIDDEN" ? 403 : 400;
34719
- res.status(status).json({ detail: err3.message, code: err3.code });
35928
+ } catch (err4) {
35929
+ if (err4 instanceof ResolveModelError) {
35930
+ const status = err4.code === "MODEL_FORBIDDEN" ? 403 : 400;
35931
+ res.status(status).json({ detail: err4.message, code: err4.code });
34720
35932
  return;
34721
35933
  }
34722
- throw err3;
35934
+ throw err4;
34723
35935
  }
34724
35936
  try {
34725
35937
  const { suggestions, usage } = await generateSuggestions({
@@ -34759,10 +35971,10 @@ ${customInstructions}` : agent.instructions,
34759
35971
  ] : []
34760
35972
  ]);
34761
35973
  res.status(200).json({ suggestions });
34762
- } catch (err3) {
34763
- console.error("[EXULU] suggestions generation failed", err3);
35974
+ } catch (err4) {
35975
+ console.error("[EXULU] suggestions generation failed", err4);
34764
35976
  res.status(500).json({
34765
- detail: err3 instanceof Error ? err3.message : "Failed to generate suggestions."
35977
+ detail: err4 instanceof Error ? err4.message : "Failed to generate suggestions."
34766
35978
  });
34767
35979
  }
34768
35980
  });
@@ -34772,14 +35984,14 @@ ${customInstructions}` : agent.instructions,
34772
35984
  limits: { fileSize: MAX_TRANSCRIBE_BYTES }
34773
35985
  });
34774
35986
  const transcribeUploadMiddleware = (req, res, next) => {
34775
- transcribeUpload.single("file")(req, res, (err3) => {
34776
- if (!err3) return next();
34777
- const code = err3?.code;
35987
+ transcribeUpload.single("file")(req, res, (err4) => {
35988
+ if (!err4) return next();
35989
+ const code = err4?.code;
34778
35990
  if (code === "LIMIT_FILE_SIZE") {
34779
35991
  res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
34780
35992
  return;
34781
35993
  }
34782
- res.status(400).json({ detail: err3 instanceof Error ? err3.message : "Upload failed." });
35994
+ res.status(400).json({ detail: err4 instanceof Error ? err4.message : "Upload failed." });
34783
35995
  });
34784
35996
  };
34785
35997
  app.post(
@@ -34823,15 +36035,15 @@ ${customInstructions}` : agent.instructions,
34823
36035
  try {
34824
36036
  const { text } = await transcribeAudio({ file, language });
34825
36037
  res.status(200).json({ text });
34826
- } catch (err3) {
34827
- if (err3 instanceof TranscriptionError) {
34828
- const code = err3.upstreamStatus >= 500 ? 502 : err3.upstreamStatus;
34829
- res.status(code).json({ detail: err3.message });
36038
+ } catch (err4) {
36039
+ if (err4 instanceof TranscriptionError) {
36040
+ const code = err4.upstreamStatus >= 500 ? 502 : err4.upstreamStatus;
36041
+ res.status(code).json({ detail: err4.message });
34830
36042
  return;
34831
36043
  }
34832
- console.error("[EXULU] /transcribe failed", err3);
36044
+ console.error("[EXULU] /transcribe failed", err4);
34833
36045
  res.status(500).json({
34834
- detail: err3 instanceof Error ? err3.message : "Transcription failed."
36046
+ detail: err4 instanceof Error ? err4.message : "Transcription failed."
34835
36047
  });
34836
36048
  }
34837
36049
  }
@@ -34910,8 +36122,8 @@ ${customInstructions}` : agent.instructions,
34910
36122
  const response = await fetch(url, {
34911
36123
  headers: { Authorization: recallApiKey(), accept: "application/json" },
34912
36124
  signal: AbortSignal.timeout(1e4)
34913
- }).catch((err3) => {
34914
- throw new Error(`Unable to reach the Recall API: ${err3.message}`);
36125
+ }).catch((err4) => {
36126
+ throw new Error(`Unable to reach the Recall API: ${err4.message}`);
34915
36127
  });
34916
36128
  if (!response.ok) {
34917
36129
  const body = await response.text();
@@ -34935,8 +36147,8 @@ ${customInstructions}` : agent.instructions,
34935
36147
  }
34936
36148
  });
34937
36149
  res.status(200).json(result);
34938
- } catch (err3) {
34939
- res.status(400).json({ detail: err3.message });
36150
+ } catch (err4) {
36151
+ res.status(400).json({ detail: err4.message });
34940
36152
  }
34941
36153
  });
34942
36154
  const MAX_TTS_INPUT_CHARS = 4e3;
@@ -34984,15 +36196,15 @@ ${customInstructions}` : agent.instructions,
34984
36196
  res.setHeader("Content-Length", String(audio.length));
34985
36197
  res.setHeader("Cache-Control", "no-store");
34986
36198
  res.send(audio);
34987
- } catch (err3) {
34988
- if (err3 instanceof SpeechError) {
34989
- const code = err3.upstreamStatus >= 500 ? 502 : err3.upstreamStatus;
34990
- res.status(code).json({ detail: err3.message });
36199
+ } catch (err4) {
36200
+ if (err4 instanceof SpeechError) {
36201
+ const code = err4.upstreamStatus >= 500 ? 502 : err4.upstreamStatus;
36202
+ res.status(code).json({ detail: err4.message });
34991
36203
  return;
34992
36204
  }
34993
- console.error("[EXULU] /speech failed", err3);
36205
+ console.error("[EXULU] /speech failed", err4);
34994
36206
  res.status(500).json({
34995
- detail: err3 instanceof Error ? err3.message : "Speech generation failed."
36207
+ detail: err4 instanceof Error ? err4.message : "Speech generation failed."
34996
36208
  });
34997
36209
  }
34998
36210
  }
@@ -35003,10 +36215,10 @@ ${customInstructions}` : agent.instructions,
35003
36215
  const configPath = process.env.LITELLM_CONFIG_PATH ?? (0, import_node_path10.resolve)(process.cwd(), "./config.litellm.yaml");
35004
36216
  const models2 = parseImageGenerationModels(configPath);
35005
36217
  return new Map(models2.map((m) => [m.model_name, m]));
35006
- } catch (err3) {
36218
+ } catch (err4) {
35007
36219
  console.error(
35008
36220
  "[EXULU] Skipping /images/* routes due to config.litellm.yaml error:",
35009
- err3.message
36221
+ err4.message
35010
36222
  );
35011
36223
  return /* @__PURE__ */ new Map();
35012
36224
  }
@@ -35118,7 +36330,7 @@ ${customInstructions}` : agent.instructions,
35118
36330
  const keys = [];
35119
36331
  const revisedPrompts = [];
35120
36332
  for (const img of images) {
35121
- const filename = `${(0, import_node_crypto19.randomUUID)()}.${img.extension}`;
36333
+ const filename = `${(0, import_node_crypto20.randomUUID)()}.${img.extension}`;
35122
36334
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
35123
36335
  const fullKey = await uploadFile(
35124
36336
  img.buffer,
@@ -35208,16 +36420,16 @@ ${style.markdown}` : params.prompt;
35208
36420
  revisedPrompt: revisedPrompts[i]
35209
36421
  }))
35210
36422
  });
35211
- } catch (err3) {
36423
+ } catch (err4) {
35212
36424
  if (abortController.signal.aborted) return;
35213
- if (err3 instanceof ImageGenerationError) {
35214
- const code = err3.upstreamStatus >= 500 ? 502 : err3.upstreamStatus;
35215
- res.status(code).json({ detail: err3.message });
36425
+ if (err4 instanceof ImageGenerationError) {
36426
+ const code = err4.upstreamStatus >= 500 ? 502 : err4.upstreamStatus;
36427
+ res.status(code).json({ detail: err4.message });
35216
36428
  return;
35217
36429
  }
35218
- console.error("[EXULU] /images/generate failed", err3);
36430
+ console.error("[EXULU] /images/generate failed", err4);
35219
36431
  res.status(500).json({
35220
- detail: err3 instanceof Error ? err3.message : "Image generation failed."
36432
+ detail: err4 instanceof Error ? err4.message : "Image generation failed."
35221
36433
  });
35222
36434
  }
35223
36435
  });
@@ -35325,16 +36537,16 @@ ${style.markdown}` : params.prompt;
35325
36537
  revisedPrompt: revisedPrompts[i]
35326
36538
  }))
35327
36539
  });
35328
- } catch (err3) {
36540
+ } catch (err4) {
35329
36541
  if (abortController.signal.aborted) return;
35330
- if (err3 instanceof ImageGenerationError) {
35331
- const code = err3.upstreamStatus >= 500 ? 502 : err3.upstreamStatus;
35332
- res.status(code).json({ detail: err3.message });
36542
+ if (err4 instanceof ImageGenerationError) {
36543
+ const code = err4.upstreamStatus >= 500 ? 502 : err4.upstreamStatus;
36544
+ res.status(code).json({ detail: err4.message });
35333
36545
  return;
35334
36546
  }
35335
- console.error("[EXULU] /images/edit failed", err3);
36547
+ console.error("[EXULU] /images/edit failed", err4);
35336
36548
  res.status(500).json({
35337
- detail: err3 instanceof Error ? err3.message : "Image edit failed."
36549
+ detail: err4 instanceof Error ? err4.message : "Image edit failed."
35338
36550
  });
35339
36551
  }
35340
36552
  });
@@ -35406,7 +36618,7 @@ ${style.markdown}` : params.prompt;
35406
36618
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
35407
36619
  );
35408
36620
  const messageText = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
35409
- const messageId = (0, import_node_crypto19.randomUUID)();
36621
+ const messageId = (0, import_node_crypto20.randomUUID)();
35410
36622
  const uiMessage = {
35411
36623
  id: messageId,
35412
36624
  role: "system",
@@ -35539,11 +36751,11 @@ ${style.markdown}` : params.prompt;
35539
36751
  reader.releaseLock();
35540
36752
  }
35541
36753
  res.end();
35542
- } catch (err3) {
35543
- console.error("[EXULU] LiteLLM UI proxy failed", err3);
36754
+ } catch (err4) {
36755
+ console.error("[EXULU] LiteLLM UI proxy failed", err4);
35544
36756
  if (!res.headersSent) {
35545
36757
  res.status(502).json({
35546
- detail: err3 instanceof Error ? err3.message : "LiteLLM UI proxy failed."
36758
+ detail: err4 instanceof Error ? err4.message : "LiteLLM UI proxy failed."
35547
36759
  });
35548
36760
  } else {
35549
36761
  res.end();
@@ -35668,11 +36880,11 @@ ${style.markdown}` : params.prompt;
35668
36880
  reader.releaseLock();
35669
36881
  }
35670
36882
  res.end();
35671
- } catch (err3) {
35672
- console.error("[EXULU] /litellm proxy failed", err3);
36883
+ } catch (err4) {
36884
+ console.error("[EXULU] /litellm proxy failed", err4);
35673
36885
  if (!res.headersSent) {
35674
36886
  res.status(502).json({
35675
- detail: err3 instanceof Error ? err3.message : "LiteLLM proxy failed."
36887
+ detail: err4 instanceof Error ? err4.message : "LiteLLM proxy failed."
35676
36888
  });
35677
36889
  } else {
35678
36890
  res.end();
@@ -35729,8 +36941,8 @@ ${style.markdown}` : params.prompt;
35729
36941
  `attachment; filename="${encodeURIComponent(filename)}"`
35730
36942
  );
35731
36943
  res.send(bytes);
35732
- } catch (err3) {
35733
- console.error("[EXULU] markdown export failed", err3);
36944
+ } catch (err4) {
36945
+ console.error("[EXULU] markdown export failed", err4);
35734
36946
  res.status(500).json({ detail: "Export failed." });
35735
36947
  }
35736
36948
  });
@@ -35828,14 +37040,14 @@ ${style.markdown}` : params.prompt;
35828
37040
  }
35829
37041
  try {
35830
37042
  res.status(200).json({ usage: await getMyUsageView(authResult.user.id, window) });
35831
- } catch (err3) {
35832
- if (err3 instanceof LiteLLMAdminError) {
35833
- res.status(502).json({ detail: err3.message });
37043
+ } catch (err4) {
37044
+ if (err4 instanceof LiteLLMAdminError) {
37045
+ res.status(502).json({ detail: err4.message });
35834
37046
  return;
35835
37047
  }
35836
- console.error("[EXULU] /me/usage failed", err3);
37048
+ console.error("[EXULU] /me/usage failed", err4);
35837
37049
  res.status(500).json({
35838
- detail: err3 instanceof Error ? err3.message : "Usage query failed."
37050
+ detail: err4 instanceof Error ? err4.message : "Usage query failed."
35839
37051
  });
35840
37052
  }
35841
37053
  });
@@ -35865,11 +37077,11 @@ ${style.markdown}` : params.prompt;
35865
37077
  try {
35866
37078
  await upsertBudget(tag, body.max_budget, body.budget_duration, body.budget_reset_at);
35867
37079
  results.push({ entityId: String(id), ok: true });
35868
- } catch (err3) {
37080
+ } catch (err4) {
35869
37081
  results.push({
35870
37082
  entityId: String(id),
35871
37083
  ok: false,
35872
- error: err3 instanceof Error ? err3.message : "Failed."
37084
+ error: err4 instanceof Error ? err4.message : "Failed."
35873
37085
  });
35874
37086
  }
35875
37087
  }
@@ -35896,9 +37108,9 @@ ${style.markdown}` : params.prompt;
35896
37108
  await upsertBudget(tag, body.max_budget, body.budget_duration, body.budget_reset_at);
35897
37109
  const info = await tagInfo([tag]);
35898
37110
  res.status(200).json({ budget: info[tag] ?? null });
35899
- } catch (err3) {
37111
+ } catch (err4) {
35900
37112
  res.status(502).json({
35901
- detail: err3 instanceof Error ? err3.message : "Failed to save budget."
37113
+ detail: err4 instanceof Error ? err4.message : "Failed to save budget."
35902
37114
  });
35903
37115
  }
35904
37116
  }
@@ -35918,9 +37130,9 @@ ${style.markdown}` : params.prompt;
35918
37130
  await tagDelete(tag);
35919
37131
  invalidateBudgetCaches(tag);
35920
37132
  res.status(204).end();
35921
- } catch (err3) {
37133
+ } catch (err4) {
35922
37134
  res.status(502).json({
35923
- detail: err3 instanceof Error ? err3.message : "Failed to delete budget."
37135
+ detail: err4 instanceof Error ? err4.message : "Failed to delete budget."
35924
37136
  });
35925
37137
  }
35926
37138
  }
@@ -36291,14 +37503,14 @@ ${style.markdown}` : params.prompt;
36291
37503
  echoedPrefix
36292
37504
  );
36293
37505
  res.status(200).json(projected);
36294
- } catch (err3) {
36295
- if (err3 instanceof LiteLLMAdminError) {
36296
- res.status(502).json({ detail: err3.message });
37506
+ } catch (err4) {
37507
+ if (err4 instanceof LiteLLMAdminError) {
37508
+ res.status(502).json({ detail: err4.message });
36297
37509
  return;
36298
37510
  }
36299
- console.error("[EXULU] /admin/litellm/tag-activity failed", err3);
37511
+ console.error("[EXULU] /admin/litellm/tag-activity failed", err4);
36300
37512
  res.status(500).json({
36301
- detail: err3 instanceof Error ? err3.message : "Analytics query failed."
37513
+ detail: err4 instanceof Error ? err4.message : "Analytics query failed."
36302
37514
  });
36303
37515
  }
36304
37516
  }
@@ -36359,7 +37571,7 @@ ${style.markdown}` : params.prompt;
36359
37571
  void (async () => {
36360
37572
  const { db: db2 } = await postgresClient();
36361
37573
  await seedBundledSkills({ db: db2, config });
36362
- })().catch((err3) => console.error("[SKILLS] seeding the bundled skills failed", err3));
37574
+ })().catch((err4) => console.error("[SKILLS] seeding the bundled skills failed", err4));
36363
37575
  app.get("/skills/agent/bootstrap", async (_req, res) => {
36364
37576
  try {
36365
37577
  const zip = new import_jszip4.default();
@@ -36375,8 +37587,8 @@ ${style.markdown}` : params.prompt;
36375
37587
  res.setHeader("Content-Type", "application/zip");
36376
37588
  res.setHeader("Content-Disposition", 'attachment; filename="imp-skills.zip"');
36377
37589
  res.send(buffer);
36378
- } catch (err3) {
36379
- console.error("[SKILLS] Failed to build bootstrap zip", err3);
37590
+ } catch (err4) {
37591
+ console.error("[SKILLS] Failed to build bootstrap zip", err4);
36380
37592
  res.status(500).json({ detail: "Failed to build bootstrap skill." });
36381
37593
  }
36382
37594
  });
@@ -36460,17 +37672,17 @@ ${style.markdown}` : params.prompt;
36460
37672
  const { db: db2 } = await postgresClient();
36461
37673
  const existing = await resolveSkillByName(db2, name);
36462
37674
  if (existing) {
36463
- const canWrite = await canAccessSkill(db2, existing, "write", authResult.user);
36464
- if (canWrite) {
37675
+ const canWrite2 = await canAccessSkill(db2, existing, "write", authResult.user);
37676
+ if (canWrite2) {
36465
37677
  const nextVersion = (existing.current_version ?? 1) + 1;
36466
37678
  try {
36467
37679
  await extractBundleToVersion({ bytes, skillId: existing.id, version: nextVersion, config });
36468
- } catch (err3) {
36469
- if (err3 instanceof BundleValidationError) {
36470
- res.status(400).json({ detail: err3.message });
37680
+ } catch (err4) {
37681
+ if (err4 instanceof BundleValidationError) {
37682
+ res.status(400).json({ detail: err4.message });
36471
37683
  return;
36472
37684
  }
36473
- console.error("[SKILLS] publish (new version) failed", err3);
37685
+ console.error("[SKILLS] publish (new version) failed", err4);
36474
37686
  res.status(500).json({ detail: "Failed to publish new version." });
36475
37687
  return;
36476
37688
  }
@@ -36503,15 +37715,15 @@ ${style.markdown}` : params.prompt;
36503
37715
  return;
36504
37716
  }
36505
37717
  const meta = await parseSkillFrontmatter(bytes);
36506
- const skillId = (0, import_node_crypto19.randomUUID)();
37718
+ const skillId = (0, import_node_crypto20.randomUUID)();
36507
37719
  try {
36508
37720
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
36509
- } catch (err3) {
36510
- if (err3 instanceof BundleValidationError) {
36511
- res.status(400).json({ detail: err3.message });
37721
+ } catch (err4) {
37722
+ if (err4 instanceof BundleValidationError) {
37723
+ res.status(400).json({ detail: err4.message });
36512
37724
  return;
36513
37725
  }
36514
- console.error("[SKILLS] publish (create) failed", err3);
37726
+ console.error("[SKILLS] publish (create) failed", err4);
36515
37727
  res.status(500).json({ detail: "Failed to publish skill." });
36516
37728
  return;
36517
37729
  }
@@ -36531,7 +37743,7 @@ ${style.markdown}` : params.prompt;
36531
37743
  rights_mode: visibility,
36532
37744
  created_by: authResult.user.id
36533
37745
  });
36534
- } catch (err3) {
37746
+ } catch (err4) {
36535
37747
  res.status(409).json({ detail: "That name is unavailable." });
36536
37748
  return;
36537
37749
  }
@@ -36585,8 +37797,8 @@ ${style.markdown}` : params.prompt;
36585
37797
  const s3Key = `skills/${skillId}/v1/SKILL.md`;
36586
37798
  try {
36587
37799
  await uploadFile(Buffer.from(skillMdContent, "utf-8"), s3Key, config, { contentType: "text/markdown" }, void 0, void 0, true);
36588
- } catch (err3) {
36589
- console.error("[SKILLS] Failed to create SKILL.md in S3", err3);
37800
+ } catch (err4) {
37801
+ console.error("[SKILLS] Failed to create SKILL.md in S3", err4);
36590
37802
  res.status(500).json({ detail: "Failed to initialise skill folder in S3." });
36591
37803
  return;
36592
37804
  }
@@ -36623,7 +37835,7 @@ ${style.markdown}` : params.prompt;
36623
37835
  res.status(404).json({ detail: "Skill not found." });
36624
37836
  return;
36625
37837
  }
36626
- const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0, import_node_crypto19.randomUUID)()}${extension}`;
37838
+ const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0, import_node_crypto20.randomUUID)()}${extension}`;
36627
37839
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
36628
37840
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
36629
37841
  res.json({ uploadUrl, stagingKey });
@@ -36663,15 +37875,15 @@ ${style.markdown}` : params.prompt;
36663
37875
  let bytes;
36664
37876
  try {
36665
37877
  bytes = await getS3ObjectBytes(fullStagingKey, config);
36666
- } catch (err3) {
36667
- console.error("[SKILLS] Failed to fetch staged bundle", err3);
37878
+ } catch (err4) {
37879
+ console.error("[SKILLS] Failed to fetch staged bundle", err4);
36668
37880
  res.status(500).json({ detail: "Failed to fetch staged bundle from S3." });
36669
37881
  return;
36670
37882
  }
36671
37883
  let result;
36672
37884
  try {
36673
37885
  result = await extractBundleToS3({ bytes, skillId, isZip, config });
36674
- } catch (err3) {
37886
+ } catch (err4) {
36675
37887
  try {
36676
37888
  await db2("skills").where({ id: skillId }).delete();
36677
37889
  } catch (cleanupErr) {
@@ -36688,11 +37900,11 @@ ${style.markdown}` : params.prompt;
36688
37900
  cleanupErr
36689
37901
  );
36690
37902
  }
36691
- if (err3 instanceof BundleValidationError) {
36692
- res.status(400).json({ detail: err3.message });
37903
+ if (err4 instanceof BundleValidationError) {
37904
+ res.status(400).json({ detail: err4.message });
36693
37905
  return;
36694
37906
  }
36695
- console.error("[SKILLS] Failed to extract bundle", err3);
37907
+ console.error("[SKILLS] Failed to extract bundle", err4);
36696
37908
  res.status(500).json({ detail: "Failed to extract bundle." });
36697
37909
  return;
36698
37910
  }
@@ -36706,8 +37918,8 @@ ${style.markdown}` : params.prompt;
36706
37918
  });
36707
37919
  try {
36708
37920
  await deleteS3Object(fullStagingKey, config);
36709
- } catch (err3) {
36710
- console.warn(`[SKILLS] Failed to delete staging key ${fullStagingKey}; continuing.`, err3);
37921
+ } catch (err4) {
37922
+ console.warn(`[SKILLS] Failed to delete staging key ${fullStagingKey}; continuing.`, err4);
36711
37923
  }
36712
37924
  res.json({ version: 1, filesCount: result.filesCount });
36713
37925
  });
@@ -37115,8 +38327,8 @@ ${style.markdown}` : params.prompt;
37115
38327
  const skills = await getEnabledSkills(agent, []);
37116
38328
  const outcome = await refreshSessionSkills(sessionId, skills, config);
37117
38329
  res.json({ ...outcome, skills: skills.map((s) => ({ id: s.id, name: s.name, version: s.current_version })) });
37118
- } catch (err3) {
37119
- console.error("[SKILLS] reload failed", err3);
38330
+ } catch (err4) {
38331
+ console.error("[SKILLS] reload failed", err4);
37120
38332
  res.status(500).json({ detail: "Could not reload the skills." });
37121
38333
  }
37122
38334
  });
@@ -37136,8 +38348,8 @@ ${style.markdown}` : params.prompt;
37136
38348
  let objects;
37137
38349
  try {
37138
38350
  objects = await listS3ObjectsByPrefix(userSessionPrefix, config);
37139
- } catch (err3) {
37140
- console.error("[SESSION-FILES] Failed to list S3 objects", err3);
38351
+ } catch (err4) {
38352
+ console.error("[SESSION-FILES] Failed to list S3 objects", err4);
37141
38353
  res.status(500).json({ detail: "Failed to list session files." });
37142
38354
  return;
37143
38355
  }
@@ -37219,8 +38431,8 @@ ${style.markdown}` : params.prompt;
37219
38431
  config
37220
38432
  });
37221
38433
  res.json(result);
37222
- } catch (err3) {
37223
- console.error("[SESSION-FILES] sync-to-sandbox failed", err3);
38434
+ } catch (err4) {
38435
+ console.error("[SESSION-FILES] sync-to-sandbox failed", err4);
37224
38436
  res.status(500).json({ detail: "Failed to sync file into sandbox." });
37225
38437
  }
37226
38438
  }
@@ -37247,8 +38459,8 @@ ${style.markdown}` : params.prompt;
37247
38459
  try {
37248
38460
  await deleteS3Object(key, config);
37249
38461
  res.json({ deleted: true });
37250
- } catch (err3) {
37251
- console.error("[SESSION-FILES] delete failed", err3);
38462
+ } catch (err4) {
38463
+ console.error("[SESSION-FILES] delete failed", err4);
37252
38464
  res.status(500).json({ detail: "Failed to delete session file." });
37253
38465
  }
37254
38466
  }
@@ -37289,13 +38501,13 @@ ${style.markdown}` : params.prompt;
37289
38501
  res.setHeader("Content-Type", "application/pdf");
37290
38502
  res.setHeader("Cache-Control", "private, max-age=300");
37291
38503
  res.send(pdfBytes);
37292
- } catch (err3) {
37293
- if (err3 instanceof PreviewRenderError) {
37294
- console.error("[SESSION-FILES] preview render failed", err3);
37295
- res.status(500).json({ detail: err3.message });
38504
+ } catch (err4) {
38505
+ if (err4 instanceof PreviewRenderError) {
38506
+ console.error("[SESSION-FILES] preview render failed", err4);
38507
+ res.status(500).json({ detail: err4.message });
37296
38508
  return;
37297
38509
  }
37298
- console.error("[SESSION-FILES] preview unexpected error", err3);
38510
+ console.error("[SESSION-FILES] preview unexpected error", err4);
37299
38511
  res.status(500).json({ detail: "Failed to render preview." });
37300
38512
  }
37301
38513
  }
@@ -37400,8 +38612,8 @@ ${style.markdown}` : params.prompt;
37400
38612
  `attachment; filename="${filename}"`
37401
38613
  );
37402
38614
  res.send(buffer);
37403
- } catch (err3) {
37404
- console.error("[GDPR] Failed to build data export", err3);
38615
+ } catch (err4) {
38616
+ console.error("[GDPR] Failed to build data export", err4);
37405
38617
  res.status(500).json({ detail: "Failed to build data export." });
37406
38618
  }
37407
38619
  });
@@ -37422,8 +38634,8 @@ ${style.markdown}` : params.prompt;
37422
38634
  await trx("rbac").where({ user_id: targetUser.id }).delete();
37423
38635
  await trx("users").where({ id: targetUser.id }).delete();
37424
38636
  });
37425
- } catch (err3) {
37426
- console.error("[GDPR] Failed to delete user", err3);
38637
+ } catch (err4) {
38638
+ console.error("[GDPR] Failed to delete user", err4);
37427
38639
  res.status(500).json({ detail: "Failed to delete user." });
37428
38640
  return;
37429
38641
  }
@@ -37431,8 +38643,8 @@ ${style.markdown}` : params.prompt;
37431
38643
  const prefix = `user_${targetUser.id}/`;
37432
38644
  const files = await listS3ObjectsByPrefix(prefix, config);
37433
38645
  await Promise.all(files.map((f) => deleteS3Object(f.key, config)));
37434
- } catch (err3) {
37435
- console.error("[GDPR] DB delete succeeded but S3 cleanup failed", err3);
38646
+ } catch (err4) {
38647
+ console.error("[GDPR] DB delete succeeded but S3 cleanup failed", err4);
37436
38648
  }
37437
38649
  res.status(204).send();
37438
38650
  });
@@ -37726,9 +38938,9 @@ ${style.markdown}` : params.prompt;
37726
38938
  if (!agentModel) return "";
37727
38939
  return "";
37728
38940
  };
37729
- const UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
38941
+ const UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
37730
38942
  const getGuestAgentById = async (id) => {
37731
- if (!UUID_RE2.test(id)) return void 0;
38943
+ if (!UUID_RE3.test(id)) return void 0;
37732
38944
  const { db: db2 } = await postgresClient();
37733
38945
  return db2.from("agents").where({ id, guest_access: true, active: true }).first();
37734
38946
  };
@@ -37872,7 +39084,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
37872
39084
  // src/mcp/index.ts
37873
39085
  init_cjs_shims();
37874
39086
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
37875
- var import_node_crypto20 = require("crypto");
39087
+ var import_node_crypto21 = require("crypto");
37876
39088
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
37877
39089
  var import_types13 = require("@modelcontextprotocol/sdk/types.js");
37878
39090
  init_sanitize_tool_name();
@@ -37973,7 +39185,7 @@ var ExuluMCP = class {
37973
39185
  throw new Error("Tool not found in converted tools array.");
37974
39186
  }
37975
39187
  const iterator = await convertedTool.execute(inputs, {
37976
- toolCallId: tool4.id + "_" + (0, import_node_crypto20.randomUUID)(),
39188
+ toolCallId: tool4.id + "_" + (0, import_node_crypto21.randomUUID)(),
37977
39189
  messages: []
37978
39190
  });
37979
39191
  let result;
@@ -38163,7 +39375,7 @@ var ExuluMCP = class {
38163
39375
  transport = this.transports[sessionId];
38164
39376
  } else if (!sessionId && (0, import_types13.isInitializeRequest)(req.body)) {
38165
39377
  transport = new import_streamableHttp.StreamableHTTPServerTransport({
38166
- sessionIdGenerator: () => (0, import_node_crypto20.randomUUID)(),
39378
+ sessionIdGenerator: () => (0, import_node_crypto21.randomUUID)(),
38167
39379
  onsessioninitialized: (sessionId2) => {
38168
39380
  this.transports[sessionId2] = transport;
38169
39381
  }
@@ -38769,7 +39981,7 @@ var import_zod31 = __toESM(require("zod"), 1);
38769
39981
  init_tool();
38770
39982
  init_check_record_access();
38771
39983
  init_client();
38772
- var import_node_crypto21 = require("crypto");
39984
+ var import_node_crypto22 = require("crypto");
38773
39985
  var AnswerOptionSchema = import_zod31.default.object({
38774
39986
  id: import_zod31.default.string().describe("Unique identifier for the answer option"),
38775
39987
  text: import_zod31.default.string().describe("The text of the answer option")
@@ -38823,15 +40035,15 @@ var QuestionAskTool = new ExuluTool({
38823
40035
  throw new Error("You don't have access to this session " + session.id + ".");
38824
40036
  }
38825
40037
  const answerOptionsWithIds = answerOptions.map((text) => ({
38826
- id: (0, import_node_crypto21.randomUUID)(),
40038
+ id: (0, import_node_crypto22.randomUUID)(),
38827
40039
  text
38828
40040
  }));
38829
40041
  answerOptionsWithIds.push({
38830
- id: (0, import_node_crypto21.randomUUID)(),
40042
+ id: (0, import_node_crypto22.randomUUID)(),
38831
40043
  text: "None of the above..."
38832
40044
  });
38833
40045
  const newQuestion = {
38834
- id: (0, import_node_crypto21.randomUUID)(),
40046
+ id: (0, import_node_crypto22.randomUUID)(),
38835
40047
  question,
38836
40048
  answerOptions: answerOptionsWithIds,
38837
40049
  status: "pending"
@@ -39192,8 +40404,8 @@ var tick = async () => {
39192
40404
  if (stopped) return;
39193
40405
  try {
39194
40406
  await transcriptionService.pollOnce(MAX_PER_TICK);
39195
- } catch (err3) {
39196
- console.error(`[EXULU-TRANSCRIPTION] polling tick failed: ${err3.message}`);
40407
+ } catch (err4) {
40408
+ console.error(`[EXULU-TRANSCRIPTION] polling tick failed: ${err4.message}`);
39197
40409
  } finally {
39198
40410
  if (!stopped) {
39199
40411
  timer = setTimeout(tick, POLL_INTERVAL_MS);
@@ -39227,9 +40439,9 @@ var tick2 = async () => {
39227
40439
  if (acted > 0) {
39228
40440
  console.log(`[EXULU-RECALL] reconcile tick recovered ${acted} job(s)`);
39229
40441
  }
39230
- } catch (err3) {
40442
+ } catch (err4) {
39231
40443
  console.error(
39232
- `[EXULU-RECALL] reconcile tick failed: ${err3.message}`
40444
+ `[EXULU-RECALL] reconcile tick failed: ${err4.message}`
39233
40445
  );
39234
40446
  } finally {
39235
40447
  if (!stopped2) {
@@ -39429,6 +40641,7 @@ var ExuluApp = class {
39429
40641
  5,
39430
40642
  300
39431
40643
  );
40644
+ registerImportQueue();
39432
40645
  if (queues2?.length) {
39433
40646
  for (const queue of queues2) {
39434
40647
  queueSet.add(await queue);
@@ -39477,10 +40690,10 @@ var ExuluApp = class {
39477
40690
  setLiteLLMPackageRoot(packageRoot);
39478
40691
  try {
39479
40692
  await startLiteLLMSupervisor();
39480
- } catch (err3) {
40693
+ } catch (err4) {
39481
40694
  console.error(
39482
40695
  "[EXULU] LiteLLM supervisor failed to start:",
39483
- err3.message
40696
+ err4.message
39484
40697
  );
39485
40698
  }
39486
40699
  }
@@ -39491,9 +40704,9 @@ var ExuluApp = class {
39491
40704
  console.log(
39492
40705
  `[EXULU] Transcription: enabled (server=${process.env.TRANSCRIPTION_SERVER}, device=${health.device}, GPU=${health.gpu.available ? "enabled" : "disabled"}, diarization=${health.diarization ? "enabled" : "disabled"})`
39493
40706
  );
39494
- } catch (err3) {
40707
+ } catch (err4) {
39495
40708
  console.warn(
39496
- `[EXULU] TRANSCRIPTION_SERVER set but not reachable yet: ${err3.message}. Polling loop is running; jobs will reconcile once the server is up.`
40709
+ `[EXULU] TRANSCRIPTION_SERVER set but not reachable yet: ${err4.message}. Polling loop is running; jobs will reconcile once the server is up.`
39497
40710
  );
39498
40711
  }
39499
40712
  } else {
@@ -40591,6 +41804,7 @@ var {
40591
41804
  jobResultsSchema: jobResultsSchema3,
40592
41805
  promptLibrarySchema: promptLibrarySchema3,
40593
41806
  contextPresetsSchema: contextPresetsSchema3,
41807
+ contextFoldersSchema: contextFoldersSchema3,
40594
41808
  contextProjectionsSchema: contextProjectionsSchema2,
40595
41809
  contextMapTopicsSchema: contextMapTopicsSchema2,
40596
41810
  entityTypeSettingsSchema: entityTypeSettingsSchema3,
@@ -40654,6 +41868,7 @@ var up = async function(knex) {
40654
41868
  jobResultsSchema3(),
40655
41869
  promptLibrarySchema3(),
40656
41870
  contextPresetsSchema3(),
41871
+ contextFoldersSchema3(),
40657
41872
  contextProjectionsSchema2(),
40658
41873
  contextMapTopicsSchema2(),
40659
41874
  entityTypeSettingsSchema3(),
@@ -41060,12 +42275,12 @@ var initLiteLLMDatabase = async (packageRoot) => {
41060
42275
  await probe.connect();
41061
42276
  await probe.end();
41062
42277
  return true;
41063
- } catch (err3) {
41064
- const code = err3?.code;
42278
+ } catch (err4) {
42279
+ const code = err4?.code;
41065
42280
  if (code !== "3D000") {
41066
42281
  warn2([
41067
42282
  `Could not connect to LiteLLM's target database:`,
41068
- ` ${err3 instanceof Error ? err3.message : String(err3)}`,
42283
+ ` ${err4 instanceof Error ? err4.message : String(err4)}`,
41069
42284
  ``,
41070
42285
  `Skipping LiteLLM database setup. LiteLLM features that depend on`,
41071
42286
  `the database will fail at runtime until this is resolved.`
@@ -41129,11 +42344,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
41129
42344
  ORDER BY table_name;`
41130
42345
  );
41131
42346
  foreignTables = res.rows.map((r) => r.table_name);
41132
- } catch (err3) {
42347
+ } catch (err4) {
41133
42348
  warn2([
41134
42349
  `Could not query LiteLLM's target database to verify it is safe`,
41135
42350
  `to push into:`,
41136
- ` ${err3 instanceof Error ? err3.message : String(err3)}`,
42351
+ ` ${err4 instanceof Error ? err4.message : String(err4)}`,
41137
42352
  ``,
41138
42353
  `Skipping LiteLLM database setup. LiteLLM features that depend on the`,
41139
42354
  `database will fail at runtime until this is resolved.`
@@ -41947,10 +43162,10 @@ async function resolveOcr(input) {
41947
43162
  }
41948
43163
  try {
41949
43164
  await waitForLiteLLMReady();
41950
- } catch (err3) {
43165
+ } catch (err4) {
41951
43166
  throw new ResolveOcrError(
41952
43167
  "LITELLM_NOT_READY",
41953
- `LiteLLM is not ready: ${err3.message}`
43168
+ `LiteLLM is not ready: ${err4.message}`
41954
43169
  );
41955
43170
  }
41956
43171
  const { baseUrl, authHeaders } = resolveLiteLLMTarget();
@@ -42468,9 +43683,9 @@ async function processPdf(buffer, paths, config, verbose = false) {
42468
43683
  let pdfChunks;
42469
43684
  try {
42470
43685
  pdfChunks = JSON.parse(splitResult.stdout);
42471
- } catch (err3) {
43686
+ } catch (err4) {
42472
43687
  throw new Error(
42473
- `[EXULU] split_pdf.py returned invalid JSON on stdout: ${err3.message}
43688
+ `[EXULU] split_pdf.py returned invalid JSON on stdout: ${err4.message}
42474
43689
  stdout: ${splitResult.stdout.slice(0, 500)}
42475
43690
  stderr: ${splitResult.stderr.slice(-1e3)}`
42476
43691
  );