@exulu/backend 5.17.2 → 5.19.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
@@ -677,11 +677,11 @@ function extractorFingerprint(args) {
677
677
  const vlm = processorConfig.vlm?.model ? `vlm:${processorConfig.vlm.model}` : "vlm:off";
678
678
  const extension = (0, import_node_path3.extname)(args.filename).toLowerCase() || "-";
679
679
  const chunk2 = processorConfig.processor.maxPagesPerChunk ?? 25;
680
- label = `document-processor/${name}/${ocrModel}/${vlm}/${extension}/chunk:${chunk2}@${EXTRACTOR_VERSION}`;
680
+ label = `document-processor/${name}/${ocrModel}/${vlm}/${extension}/chunk:${chunk2}@${name === "officeparser" ? OFFICEPARSER_VERSION : EXTRACTOR_VERSION}`;
681
681
  } else if (args.filename.toLowerCase().endsWith(".pdf")) {
682
682
  label = `pdftotext@${EXTRACTOR_VERSION}`;
683
683
  } else {
684
- label = `officeparser@${EXTRACTOR_VERSION}`;
684
+ label = `officeparser@${OFFICEPARSER_VERSION}`;
685
685
  }
686
686
  return { id: sha256(label).slice(0, 16), label };
687
687
  }
@@ -697,7 +697,7 @@ function documentMaxPages(env = process.env) {
697
697
  const n = Number(raw);
698
698
  return Number.isInteger(n) && n > 0 ? n : 300;
699
699
  }
700
- var import_crypto, import_node_path3, DERIVED_ROOT, EXTRACTOR_VERSION, generalPrefix2, sha256;
700
+ var import_crypto, import_node_path3, DERIVED_ROOT, EXTRACTOR_VERSION, OFFICEPARSER_VERSION, generalPrefix2, sha256;
701
701
  var init_keys = __esm({
702
702
  "src/exulu/document-cache/keys.ts"() {
703
703
  "use strict";
@@ -706,6 +706,7 @@ var init_keys = __esm({
706
706
  import_node_path3 = require("path");
707
707
  DERIVED_ROOT = "derived";
708
708
  EXTRACTOR_VERSION = 1;
709
+ OFFICEPARSER_VERSION = 2;
709
710
  generalPrefix2 = (s3prefix) => {
710
711
  const trimmed = (s3prefix ?? "").replace(/^\/+|\/+$/g, "");
711
712
  return trimmed ? `${trimmed}/` : "";
@@ -892,7 +893,7 @@ var init_uppy = __esm({
892
893
  if (error.name === "SignatureDoesNotMatch" || error.name === "InvalidAccessKeyId" || error.name === "AccessDenied") {
893
894
  if (attempt < maxRetries) {
894
895
  const backoffMs = Math.pow(2, attempt) * 1e3;
895
- await new Promise((resolve10) => setTimeout(resolve10, backoffMs));
896
+ await new Promise((resolve11) => setTimeout(resolve11, backoffMs));
896
897
  s3Client = void 0;
897
898
  getS3Client(config);
898
899
  continue;
@@ -3066,7 +3067,7 @@ var init_supervisor = __esm({
3066
3067
  MAX_CRASHES = 5;
3067
3068
  INITIAL_BACKOFF_MS = 1e3;
3068
3069
  MAX_BACKOFF_MS = 3e4;
3069
- READY_TIMEOUT_MS = 9e4;
3070
+ READY_TIMEOUT_MS = 15e4;
3070
3071
  WAIT_TIMEOUT_MS = 6e4;
3071
3072
  READY_POLL_INTERVAL_MS = 200;
3072
3073
  SHUTDOWN_GRACE_MS = 5e3;
@@ -4581,8 +4582,8 @@ var init_hydrate_embedders = __esm({
4581
4582
  };
4582
4583
  codeEmbedderFor = (context) => codeEmbedders.has(context) ? codeEmbedders.get(context) : context.embedder;
4583
4584
  contextEmbedderInfoFor = async (context, deps = {}) => {
4584
- const resolve10 = deps.resolve ?? resolveContextEmbedder;
4585
- return resolve10({ id: context.id, embedder: codeEmbedderFor(context) });
4585
+ const resolve11 = deps.resolve ?? resolveContextEmbedder;
4586
+ return resolve11({ id: context.id, embedder: codeEmbedderFor(context) });
4586
4587
  };
4587
4588
  willEmbedOnQueue = async (context, overrideQueue) => {
4588
4589
  if (overrideQueue) {
@@ -4591,11 +4592,11 @@ var init_hydrate_embedders = __esm({
4591
4592
  return Boolean(await codeEmbedderFor(context)?.queue);
4592
4593
  };
4593
4594
  hydrateContextEmbedders = async (contexts, deps = {}) => {
4594
- const { resolve: resolve10, modelInfo, queues: queues2 } = { ...defaultDeps(), ...deps };
4595
+ const { resolve: resolve11, modelInfo, queues: queues2 } = { ...defaultDeps(), ...deps };
4595
4596
  for (const context of contexts) {
4596
4597
  try {
4597
4598
  const codeEmbedder = captureCodeEmbedder(context);
4598
- const info = await resolve10({ id: context.id, embedder: codeEmbedder });
4599
+ const info = await resolve11({ id: context.id, embedder: codeEmbedder });
4599
4600
  if (info.source !== "database" || !info.databaseModel) {
4600
4601
  context.embedder = codeEmbedder;
4601
4602
  continue;
@@ -8916,8 +8917,8 @@ var init_context = __esm({
8916
8917
  const { db: db2 } = await postgresClient();
8917
8918
  const tableName = getTableName(this.id);
8918
8919
  console.log("[EXULU] checking if table exists.", tableName);
8919
- const tableExists = await db2.schema.hasTable(tableName);
8920
- return tableExists;
8920
+ const tableExists2 = await db2.schema.hasTable(tableName);
8921
+ return tableExists2;
8921
8922
  };
8922
8923
  chunksTableExists = async () => {
8923
8924
  const { db: db2 } = await postgresClient();
@@ -15827,8 +15828,8 @@ async function setupPythonEnvironment(options = {}) {
15827
15828
  packageRoot = getPackageRoot(),
15828
15829
  force = false,
15829
15830
  verbose = false,
15830
- timeout = 6e5
15831
- // 10 minutes
15831
+ timeout = 18e5
15832
+ // 30 minutes
15832
15833
  } = options;
15833
15834
  const alreadyExisted = isPythonEnvironmentSetup(packageRoot);
15834
15835
  if (verbose) {
@@ -15994,18 +15995,18 @@ function probeSandboxSupport() {
15994
15995
  if (process.platform !== "linux") {
15995
15996
  return { canSandbox: false, reason: `Unsupported platform: ${process.platform}` };
15996
15997
  }
15997
- return await new Promise((resolve10) => {
15998
+ return await new Promise((resolve11) => {
15998
15999
  const child = (0, import_node_child_process5.spawn)("bwrap", ["--dev-bind", "/", "/", "--", "/bin/true"], { env: {} });
15999
16000
  let stderr = "";
16000
16001
  child.stderr.on("data", (chunk2) => {
16001
16002
  stderr += chunk2.toString();
16002
16003
  });
16003
16004
  child.on("error", (err4) => {
16004
- resolve10({ canSandbox: false, reason: `bwrap not executable: ${err4.message}` });
16005
+ resolve11({ canSandbox: false, reason: `bwrap not executable: ${err4.message}` });
16005
16006
  });
16006
16007
  child.on("exit", (code) => {
16007
- if (code === 0) resolve10({ canSandbox: true });
16008
- else resolve10({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
16008
+ if (code === 0) resolve11({ canSandbox: true });
16009
+ else resolve11({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
16009
16010
  });
16010
16011
  });
16011
16012
  })();
@@ -16973,6 +16974,63 @@ var init_routine_status_tool = __esm({
16973
16974
  }
16974
16975
  });
16975
16976
 
16977
+ // src/templates/tools/tool-upload.ts
16978
+ var import_client_s33, import_node_crypto9, generateS3Key, s3Client2, buildToolUpload;
16979
+ var init_tool_upload = __esm({
16980
+ "src/templates/tools/tool-upload.ts"() {
16981
+ "use strict";
16982
+ init_cjs_shims();
16983
+ import_client_s33 = require("@aws-sdk/client-s3");
16984
+ import_node_crypto9 = require("crypto");
16985
+ init_session_file_write();
16986
+ init_uppy();
16987
+ generateS3Key = (filename) => `${(0, import_node_crypto9.randomUUID)()}-${filename}`;
16988
+ buildToolUpload = (exuluConfig, user) => {
16989
+ const uploads = exuluConfig?.fileUploads;
16990
+ if (!uploads?.s3endpoint || !uploads?.s3key || !uploads?.s3secret || !uploads?.s3Bucket) {
16991
+ return void 0;
16992
+ }
16993
+ s3Client2 ??= new import_client_s33.S3Client({
16994
+ region: uploads.s3region,
16995
+ forcePathStyle: true,
16996
+ endpoint: uploads.s3endpoint,
16997
+ credentials: {
16998
+ accessKeyId: uploads.s3key ?? "",
16999
+ secretAccessKey: uploads.s3secret ?? ""
17000
+ }
17001
+ });
17002
+ const client2 = s3Client2;
17003
+ return async ({ name, data, type }) => {
17004
+ const mime = getMimeType(type);
17005
+ const prefix = uploads.s3prefix ? `${uploads.s3prefix.replace(/\/$/, "")}/` : "";
17006
+ const key = `${prefix}${user?.id}/${generateS3Key(name)}${type}`;
17007
+ const command = new import_client_s33.PutObjectCommand({
17008
+ Bucket: uploads.s3Bucket,
17009
+ Key: key,
17010
+ Body: data,
17011
+ ContentType: mime
17012
+ });
17013
+ try {
17014
+ await client2.send(command);
17015
+ const bucket = uploads.s3Bucket ?? "";
17016
+ const presignedUrl = await getPresignedUrl(bucket, key, exuluConfig);
17017
+ return { url: presignedUrl, key: `${bucket}/${key}` };
17018
+ } catch (caught) {
17019
+ if (caught instanceof import_client_s33.S3ServiceException && caught.name === "EntityTooLarge") {
17020
+ throw new Error(`[EXULU] Error from S3 while uploading object to ${uploads.s3Bucket}. The object was too large. To upload objects larger than 5GB, use the S3 console (160GB max) or the multipart upload API (5TB max).`);
17021
+ } else if (caught instanceof import_client_s33.S3ServiceException) {
17022
+ throw new Error(
17023
+ `[EXULU] Error from S3 while uploading object to ${uploads.s3Bucket}. ${caught.name}: ${caught.message}`
17024
+ );
17025
+ } else {
17026
+ throw caught;
17027
+ }
17028
+ }
17029
+ };
17030
+ };
17031
+ }
17032
+ });
17033
+
16976
17034
  // src/utils/truncate-tool-output.ts
16977
17035
  var truncateToolOutput;
16978
17036
  var init_truncate_tool_output = __esm({
@@ -17108,19 +17166,19 @@ var init_context_budget = __esm({
17108
17166
  });
17109
17167
 
17110
17168
  // src/exulu/tool-output-offload.ts
17111
- var import_node_crypto9, PREVIEW_CHARS, storeAsSessionFile, buildNotice, guardToolOutput, guardExtractedFileText;
17169
+ var import_node_crypto10, PREVIEW_CHARS, storeAsSessionFile, buildNotice, guardToolOutput, guardExtractedFileText;
17112
17170
  var init_tool_output_offload = __esm({
17113
17171
  "src/exulu/tool-output-offload.ts"() {
17114
17172
  "use strict";
17115
17173
  init_cjs_shims();
17116
- import_node_crypto9 = require("crypto");
17174
+ import_node_crypto10 = require("crypto");
17117
17175
  init_uppy();
17118
17176
  init_context_budget();
17119
17177
  PREVIEW_CHARS = 4e3;
17120
17178
  storeAsSessionFile = async (serialized, ctx) => {
17121
17179
  if (!ctx.sessionID || !ctx.exuluConfig?.fileUploads) return void 0;
17122
17180
  const safeTool = ctx.toolName.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
17123
- const name = `tool-output-${safeTool}-${(0, import_node_crypto9.randomUUID)().slice(0, 8)}.txt`;
17181
+ const name = `tool-output-${safeTool}-${(0, import_node_crypto10.randomUUID)().slice(0, 8)}.txt`;
17124
17182
  try {
17125
17183
  await uploadFile(
17126
17184
  Buffer.from(serialized, "utf-8"),
@@ -17319,6 +17377,24 @@ var init_session_file_read_tool = __esm({
17319
17377
  }
17320
17378
  });
17321
17379
 
17380
+ // src/utils/office-text.ts
17381
+ var import_officeparser, officeToText;
17382
+ var init_office_text = __esm({
17383
+ "src/utils/office-text.ts"() {
17384
+ "use strict";
17385
+ init_cjs_shims();
17386
+ import_officeparser = require("officeparser");
17387
+ officeToText = async (bytes) => {
17388
+ const ast = await (0, import_officeparser.parseOffice)(bytes, { newlineDelimiter: "\n" });
17389
+ const { value } = await ast.to("text", {
17390
+ includeImages: false,
17391
+ textConfig: { preserveLayout: false }
17392
+ });
17393
+ return String(value);
17394
+ };
17395
+ }
17396
+ });
17397
+
17322
17398
  // src/templates/tools/document-render-helpers.ts
17323
17399
  function isLegacyOfficeFormat(ext) {
17324
17400
  return ext in LEGACY_OFFICE_CONVERSION_TARGETS;
@@ -17463,7 +17539,7 @@ async function withRetry(generateFn, maxRetries = 3, opts = {}) {
17463
17539
  if (attempt === maxRetries || shouldRetry && !shouldRetry(error)) {
17464
17540
  throw error;
17465
17541
  }
17466
- await new Promise((resolve10) => setTimeout(resolve10, Math.pow(2, attempt) * baseDelayMs));
17542
+ await new Promise((resolve11) => setTimeout(resolve11, Math.pow(2, attempt) * baseDelayMs));
17467
17543
  }
17468
17544
  }
17469
17545
  throw lastError;
@@ -17565,25 +17641,25 @@ async function executePythonScript(config) {
17565
17641
  const stdout = error.stdout?.toString() ?? "";
17566
17642
  const stderr = error.stderr?.toString() ?? "";
17567
17643
  const exitCode = error.code ?? 1;
17568
- let errorMessage = `Python script execution failed: ${error.message}`;
17644
+ let errorMessage2 = `Python script execution failed: ${error.message}`;
17569
17645
  if (stderr) {
17570
- errorMessage += `
17646
+ errorMessage2 += `
17571
17647
 
17572
17648
  Stderr:
17573
17649
  ${stderr}`;
17574
17650
  }
17575
17651
  if (stdout) {
17576
- errorMessage += `
17652
+ errorMessage2 += `
17577
17653
 
17578
17654
  Stdout:
17579
17655
  ${stdout}`;
17580
17656
  }
17581
- errorMessage += `
17657
+ errorMessage2 += `
17582
17658
 
17583
17659
  Command executed:
17584
17660
  ${command}`;
17585
17661
  throw new PythonExecutionError(
17586
- errorMessage,
17662
+ errorMessage2,
17587
17663
  stdout,
17588
17664
  stderr,
17589
17665
  exitCode
@@ -18055,7 +18131,7 @@ async function validateWithVLM(document2, model, verbose = false, concurrency =
18055
18131
  let correctedCount = 0;
18056
18132
  const validationTasks = document2.map(
18057
18133
  (page) => limit(async () => {
18058
- await new Promise((resolve10) => setImmediate(resolve10));
18134
+ await new Promise((resolve11) => setImmediate(resolve11));
18059
18135
  const imagePath = page.image;
18060
18136
  if (!imagePath) {
18061
18137
  console.warn(`[EXULU] Page ${page.page}: No image found, skipping validation`);
@@ -18186,14 +18262,21 @@ async function processDocument(filePath, fileType, buffer, tempDir, config, verb
18186
18262
  }
18187
18263
  };
18188
18264
  }
18265
+ async function saveScreenshots(screenshots, dir) {
18266
+ await fs2.promises.mkdir(dir, { recursive: true });
18267
+ const saved = /* @__PURE__ */ new Map();
18268
+ for (const screenshot of screenshots) {
18269
+ const file = path3.join(dir, `${screenshot.pageNum}.png`);
18270
+ await fs2.promises.writeFile(file, screenshot.imageBuffer);
18271
+ saved.set(screenshot.pageNum, file);
18272
+ }
18273
+ return saved;
18274
+ }
18189
18275
  async function processPdf(buffer, paths, config, verbose = false, tolerateVisionFailures = false, onProgress, limiters) {
18190
18276
  try {
18191
18277
  let json = [];
18192
18278
  if (config?.processor.name === "officeparser") {
18193
- const text = await (0, import_officeparser.parseOfficeAsync)(buffer, {
18194
- outputErrorToConsole: false,
18195
- newlineDelimiter: "\n"
18196
- });
18279
+ const text = await officeToText(buffer);
18197
18280
  json = [{
18198
18281
  page: 1,
18199
18282
  content: text,
@@ -18230,8 +18313,8 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
18230
18313
  const chunkResults = await Promise.all(
18231
18314
  pdfChunks.map(
18232
18315
  (chunk2, i) => chunkLimit(async () => {
18233
- await new Promise((resolve10) => setImmediate(resolve10));
18234
- await new Promise((resolve10) => setTimeout(resolve10, Math.floor(Math.random() * 1e3) + 200));
18316
+ await new Promise((resolve11) => setImmediate(resolve11));
18317
+ await new Promise((resolve11) => setTimeout(resolve11, Math.floor(Math.random() * 1e3) + 200));
18235
18318
  console.log(`[EXULU] OCR chunk ${i + 1}/${pdfChunks.length}: pages ${chunk2.start_page}\u2013${chunk2.end_page - 1}`);
18236
18319
  const chunkBuffer = await fs2.promises.readFile(chunk2.path);
18237
18320
  const chunkBase64 = chunkBuffer.toString("base64");
@@ -18251,40 +18334,25 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
18251
18334
  const mergedPages = chunkResults.sort((a, b) => a.offset - b.offset).flatMap(
18252
18335
  ({ pages, offset }) => pages.map((p) => ({ ...p, index: p.index + offset }))
18253
18336
  );
18254
- const parser = new import_liteparse.LiteParse();
18337
+ const parser = new import_liteparse.LiteParse({ quiet: true });
18255
18338
  const screenshots = await parser.screenshot(paths.source, void 0);
18256
- await fs2.promises.mkdir(paths.images, { recursive: true });
18257
- for (const screenshot of screenshots) {
18258
- await fs2.promises.writeFile(
18259
- path3.join(
18260
- paths.images,
18261
- `${screenshot.pageNum}.png`
18262
- ),
18263
- screenshot.imageBuffer
18264
- );
18265
- screenshot.imagePath = path3.join(paths.images, `${screenshot.pageNum}.png`);
18266
- }
18339
+ const imagePaths = await saveScreenshots(screenshots, paths.images);
18267
18340
  json = mergedPages.map((page) => ({
18268
18341
  page: page.index + 1,
18269
18342
  content: page.markdown,
18270
- image: screenshots.find((s) => s.pageNum === page.index + 1)?.imagePath,
18343
+ image: imagePaths.get(page.index + 1),
18271
18344
  headings: []
18272
18345
  }));
18273
18346
  fs2.writeFileSync(paths.json, JSON.stringify(json, null, 2));
18274
18347
  } else if (config?.processor.name === "liteparse") {
18275
- const parser = new import_liteparse.LiteParse();
18348
+ const parser = new import_liteparse.LiteParse({ quiet: true });
18276
18349
  const result = await parser.parse(paths.source);
18277
18350
  const screenshots = await parser.screenshot(paths.source, void 0);
18278
- console.log(`[EXULU] Liteparse screenshots: ${JSON.stringify(screenshots)}`);
18279
- await fs2.promises.mkdir(paths.images, { recursive: true });
18280
- for (const screenshot of screenshots) {
18281
- await fs2.promises.writeFile(path3.join(paths.images, `${screenshot.pageNum}.png`), screenshot.imageBuffer);
18282
- screenshot.imagePath = path3.join(paths.images, `${screenshot.pageNum}.png`);
18283
- }
18351
+ const imagePaths = await saveScreenshots(screenshots, paths.images);
18284
18352
  json = result.pages.map((page) => ({
18285
18353
  page: page.pageNum,
18286
18354
  content: page.text,
18287
- image: screenshots.find((s) => s.pageNum === page.pageNum)?.imagePath
18355
+ image: imagePaths.get(page.pageNum)
18288
18356
  }));
18289
18357
  fs2.writeFileSync(paths.json, JSON.stringify(json, null, 2));
18290
18358
  } else {
@@ -18339,8 +18407,8 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
18339
18407
  markdownStream.write("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
18340
18408
  }
18341
18409
  }
18342
- await new Promise((resolve10, reject) => {
18343
- markdownStream.end(() => resolve10());
18410
+ await new Promise((resolve11, reject) => {
18411
+ markdownStream.end(() => resolve11());
18344
18412
  markdownStream.on("error", reject);
18345
18413
  });
18346
18414
  console.log(`[EXULU] Validated output saved to: ${paths.json}`);
@@ -18436,7 +18504,7 @@ async function documentProcessor({
18436
18504
  }
18437
18505
  }
18438
18506
  }
18439
- var fs2, path3, import_ai3, import_zod16, import_p_limit2, import_crypto4, mammoth, import_turndown, import_word_extractor, import_officeparser, import_liteparse, loadFile;
18507
+ var fs2, path3, import_ai3, import_zod16, import_p_limit2, import_crypto4, mammoth, import_turndown, import_word_extractor, import_liteparse, loadFile;
18440
18508
  var init_doc_processor = __esm({
18441
18509
  "ee/python/documents/processing/doc_processor.ts"() {
18442
18510
  "use strict";
@@ -18451,7 +18519,7 @@ var init_doc_processor = __esm({
18451
18519
  mammoth = __toESM(require("mammoth"), 1);
18452
18520
  import_turndown = __toESM(require("turndown"), 1);
18453
18521
  import_word_extractor = __toESM(require("word-extractor"), 1);
18454
- import_officeparser = require("officeparser");
18522
+ init_office_text();
18455
18523
  init_entitlements();
18456
18524
  init_python_executor();
18457
18525
  import_liteparse = require("@llamaindex/liteparse");
@@ -18615,12 +18683,12 @@ function validateAttachmentsConfig(config, license) {
18615
18683
  }
18616
18684
  return problems;
18617
18685
  }
18618
- var import_officeparser2, DEFAULT_ATTACHMENT_MAX_PAGES, loadDocumentProcessor, defaultOfficeParse, PROCESSOR_NAMES;
18686
+ var DEFAULT_ATTACHMENT_MAX_PAGES, loadDocumentProcessor, defaultOfficeParse, PROCESSOR_NAMES;
18619
18687
  var init_attachment_text = __esm({
18620
18688
  "src/exulu/attachment-text.ts"() {
18621
18689
  "use strict";
18622
18690
  init_cjs_shims();
18623
- import_officeparser2 = require("officeparser");
18691
+ init_office_text();
18624
18692
  init_document_render_helpers();
18625
18693
  init_limits();
18626
18694
  DEFAULT_ATTACHMENT_MAX_PAGES = 50;
@@ -18628,7 +18696,7 @@ var init_attachment_text = __esm({
18628
18696
  const mod = await Promise.resolve().then(() => (init_doc_processor(), doc_processor_exports));
18629
18697
  return mod.documentProcessor;
18630
18698
  };
18631
- defaultOfficeParse = async (bytes) => String(await (0, import_officeparser2.parseOfficeAsync)(bytes, { outputErrorToConsole: false, newlineDelimiter: "\n" }));
18699
+ defaultOfficeParse = (bytes) => officeToText(bytes);
18632
18700
  PROCESSOR_NAMES = /* @__PURE__ */ new Set(["liteparse", "mistral", "officeparser"]);
18633
18701
  }
18634
18702
  });
@@ -18863,7 +18931,7 @@ function binaryDocumentBashHint(command, stdout, stderr) {
18863
18931
  const [, file] = match;
18864
18932
  return `Note: "${file}" is a binary document \u2014 grep/cat/text tools cannot read the text inside it, so a silent or garbled result does not mean the content isn't there. Use parse_document to extract its text first, then search or read within that extracted text instead of the original file.`;
18865
18933
  }
18866
- var import_zod17, import_node_path12, import_officeparser3, DEFAULT_LIMIT2, MAX_CONTENT_CHARS2, PARSE_DOCUMENT_TOOL_NAME, MIN_CHARS_PER_PAGE, OFFICE_EXTENSIONS, ExtractionRefusal, pagesPattern, BINARY_DOCUMENT_EXTENSION_PATTERN, createParseDocumentTool;
18934
+ var import_zod17, import_node_path12, DEFAULT_LIMIT2, MAX_CONTENT_CHARS2, PARSE_DOCUMENT_TOOL_NAME, MIN_CHARS_PER_PAGE, OFFICE_EXTENSIONS, ExtractionRefusal, pagesPattern, BINARY_DOCUMENT_EXTENSION_PATTERN, createParseDocumentTool;
18867
18935
  var init_parse_document_tool = __esm({
18868
18936
  "src/templates/tools/parse-document-tool.ts"() {
18869
18937
  "use strict";
@@ -18871,7 +18939,7 @@ var init_parse_document_tool = __esm({
18871
18939
  init_turn_project();
18872
18940
  import_zod17 = require("zod");
18873
18941
  import_node_path12 = require("path");
18874
- import_officeparser3 = require("officeparser");
18942
+ init_office_text();
18875
18943
  init_tool2();
18876
18944
  init_uppy();
18877
18945
  init_document_render_helpers();
@@ -19003,11 +19071,8 @@ ${text.trim()}`).join("\n")
19003
19071
  };
19004
19072
  }
19005
19073
  const officeBytes = isLegacyOfficeFormat(ext) ? await convertLegacyOfficeToModern(bytes, ext) : bytes;
19006
- const parsed = await (0, import_officeparser3.parseOfficeAsync)(officeBytes, {
19007
- outputErrorToConsole: false,
19008
- newlineDelimiter: "\n"
19009
- });
19010
- return { text: String(parsed), storable: !processorFellBack };
19074
+ const parsed = await officeToText(officeBytes);
19075
+ return { text: parsed, storable: !processorFellBack };
19011
19076
  };
19012
19077
  const stored = await readThroughDocument({
19013
19078
  io,
@@ -19080,8 +19145,8 @@ ${text.trim()}`).join("\n")
19080
19145
  while (true) {
19081
19146
  while (queue.length > 0) yield queue.shift();
19082
19147
  if (finished) break;
19083
- await new Promise((resolve10) => {
19084
- wake = resolve10;
19148
+ await new Promise((resolve11) => {
19149
+ wake = resolve11;
19085
19150
  });
19086
19151
  wake = void 0;
19087
19152
  }
@@ -19579,12 +19644,11 @@ __export(convert_exulu_tools_to_ai_sdk_tools_exports, {
19579
19644
  convertExuluToolsToAiSdkTools: () => convertExuluToolsToAiSdkTools,
19580
19645
  hydrateVariables: () => hydrateVariables
19581
19646
  });
19582
- var import_client_s33, import_crypto_js4, import_node_crypto10, isReadingProgress, OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS, generateS3Key, s3Client2, hydrateVariables, convertExuluToolsToAiSdkTools;
19647
+ var import_crypto_js4, isReadingProgress, OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS, hydrateVariables, convertExuluToolsToAiSdkTools;
19583
19648
  var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19584
19649
  "src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts"() {
19585
19650
  "use strict";
19586
19651
  init_cjs_shims();
19587
- import_client_s33 = require("@aws-sdk/client-s3");
19588
19652
  init_tool2();
19589
19653
  init_statistics2();
19590
19654
  init_client();
@@ -19594,7 +19658,6 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19594
19658
  init_pipeline();
19595
19659
  init_project_scope();
19596
19660
  init_sanitize_tool_name();
19597
- import_node_crypto10 = require("crypto");
19598
19661
  init_statistics();
19599
19662
  init_tools();
19600
19663
  init_memory_base();
@@ -19611,7 +19674,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19611
19674
  init_resolve_session_project();
19612
19675
  init_session_file_write();
19613
19676
  init_routine_status_tool();
19614
- init_uppy();
19677
+ init_tool_upload();
19615
19678
  init_truncate_tool_output();
19616
19679
  init_tool_output_offload();
19617
19680
  init_auth_tool_model_output();
@@ -19629,7 +19692,6 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19629
19692
  return typeof v.filename === "string" && typeof v.pagesDone === "number" && typeof v.pagesTotal === "number";
19630
19693
  };
19631
19694
  OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
19632
- generateS3Key = (filename) => `${(0, import_node_crypto10.randomUUID)()}-${filename}`;
19633
19695
  hydrateVariables = async (tool5) => {
19634
19696
  const { db: db2 } = await postgresClient();
19635
19697
  const promises2 = tool5.config.map(async (toolConfig) => {
@@ -20030,54 +20092,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
20030
20092
  if (toolVariableConfig) {
20031
20093
  toolVariableConfig = await hydrateVariables(toolVariableConfig || []);
20032
20094
  }
20033
- let upload = void 0;
20034
- if (exuluConfig?.fileUploads?.s3endpoint && exuluConfig?.fileUploads?.s3key && exuluConfig?.fileUploads?.s3secret && exuluConfig?.fileUploads?.s3Bucket) {
20035
- s3Client2 ??= new import_client_s33.S3Client({
20036
- region: exuluConfig?.fileUploads?.s3region,
20037
- ...exuluConfig?.fileUploads?.s3endpoint && {
20038
- forcePathStyle: true,
20039
- endpoint: exuluConfig?.fileUploads?.s3endpoint
20040
- },
20041
- credentials: {
20042
- accessKeyId: exuluConfig?.fileUploads?.s3key ?? "",
20043
- secretAccessKey: exuluConfig?.fileUploads?.s3secret ?? ""
20044
- }
20045
- });
20046
- upload = async ({
20047
- name,
20048
- data,
20049
- type
20050
- }) => {
20051
- const mime = getMimeType(type);
20052
- const prefix = exuluConfig?.fileUploads?.s3prefix ? `${exuluConfig.fileUploads.s3prefix.replace(/\/$/, "")}/` : "";
20053
- const key = `${prefix}${user?.id}/${generateS3Key(name)}${type}`;
20054
- const command = new import_client_s33.PutObjectCommand({
20055
- Bucket: exuluConfig?.fileUploads?.s3Bucket,
20056
- Key: key,
20057
- Body: data,
20058
- ContentType: mime
20059
- });
20060
- try {
20061
- if (!s3Client2) {
20062
- throw new Error("S3 client not initialized");
20063
- }
20064
- await s3Client2.send(command);
20065
- const bucket = exuluConfig?.fileUploads?.s3Bucket ?? "";
20066
- const presignedUrl = await getPresignedUrl(bucket, key, exuluConfig);
20067
- return { url: presignedUrl, key: `${bucket}/${key}` };
20068
- } catch (caught) {
20069
- if (caught instanceof import_client_s33.S3ServiceException && caught.name === "EntityTooLarge") {
20070
- throw new Error(`[EXULU] Error from S3 while uploading object to ${exuluConfig?.fileUploads?.s3Bucket}. The object was too large. To upload objects larger than 5GB, use the S3 console (160GB max) or the multipart upload API (5TB max).`);
20071
- } else if (caught instanceof import_client_s33.S3ServiceException) {
20072
- throw new Error(
20073
- `[EXULU] Error from S3 while uploading object to ${exuluConfig?.fileUploads?.s3Bucket}. ${caught.name}: ${caught.message}`
20074
- );
20075
- } else {
20076
- throw caught;
20077
- }
20078
- }
20079
- };
20080
- }
20095
+ const upload = buildToolUpload(exuluConfig, user);
20081
20096
  const contextsMap = contexts?.reduce((acc, curr) => {
20082
20097
  acc[curr.id] = curr;
20083
20098
  return acc;
@@ -20244,6 +20259,8 @@ var init_tool2 = __esm({
20244
20259
  */
20245
20260
  alwaysAskWhen;
20246
20261
  authentication;
20262
+ /** Always set; `{ enabled: false }` unless the tool opted in. See ExuluToolApiConfig. */
20263
+ api;
20247
20264
  config;
20248
20265
  constructor({
20249
20266
  id,
@@ -20257,7 +20274,8 @@ var init_tool2 = __esm({
20257
20274
  needsApproval,
20258
20275
  needsApprovalFn,
20259
20276
  alwaysAskWhen,
20260
- authentication: authentication2
20277
+ authentication: authentication2,
20278
+ api
20261
20279
  }) {
20262
20280
  if (!PUBLIC_TOOL_TYPES.includes(type)) {
20263
20281
  throw new Error(
@@ -20270,6 +20288,17 @@ var init_tool2 = __esm({
20270
20288
  validateAuthConfig(id, authentication2);
20271
20289
  authRegistry.register(id, authentication2);
20272
20290
  }
20291
+ this.api = { enabled: api?.enabled === true };
20292
+ if (this.api.enabled) {
20293
+ const variables = config.filter((c) => c.type === "variable").map((c) => c.name);
20294
+ if (variables.length > 0) {
20295
+ throw new Error(
20296
+ `ExuluTool "${id}": api.enabled is not possible with "variable" config params (${variables.join(
20297
+ ", "
20298
+ )}). Their values come from an agent's tool configuration, and a call to /tools/${id} has no agent.`
20299
+ );
20300
+ }
20301
+ }
20273
20302
  this.authentication = authentication2;
20274
20303
  this.id = id;
20275
20304
  this.config = config;
@@ -24268,7 +24297,8 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
24268
24297
  name: hydrated?.name || "",
24269
24298
  description: hydrated?.description || "",
24270
24299
  category: tool5?.category || "default",
24271
- needsApproval: true
24300
+ needsApproval: true,
24301
+ api: hydrated?.api ?? { enabled: false }
24272
24302
  };
24273
24303
  console.log("[EXULU] hydratedTool", hydratedTool);
24274
24304
  return hydratedTool;
@@ -26073,12 +26103,12 @@ var channelView = (row) => ({
26073
26103
  needsCredentials: readSecrets(row) === null
26074
26104
  });
26075
26105
  var maskIdentity = (identity) => identity.length < 4 ? "\u2022\u2022\u2022\u2022" : `\u2022\u2022\u2022\u2022 ${identity.slice(-4)}`;
26076
- var linkPageUrl = (agentId) => {
26106
+ var linkPageUrl = (agentId, locale) => {
26077
26107
  const base = [process.env.CHANNEL_LINK_BASE_URL, process.env.FRONTEND, process.env.NEXTAUTH_URL].map((v) => (v ?? "").trim()).find((v) => v !== "");
26078
26108
  if (!base) {
26079
26109
  throw new ChannelSetupError("None of CHANNEL_LINK_BASE_URL, FRONTEND and NEXTAUTH_URL is set; the channel link page has no URL");
26080
26110
  }
26081
- return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp`;
26111
+ return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp${locale ? `?lang=${locale}` : ""}`;
26082
26112
  };
26083
26113
 
26084
26114
  // src/exulu/channels/decide.ts
@@ -26592,11 +26622,19 @@ var registerChannelApi = (app, deps) => {
26592
26622
  if (!row) return void res.json({ links: [] });
26593
26623
  const at = now();
26594
26624
  const links = await createLinkStore(db2).listForChannel(row.id);
26625
+ const mayReadUsers = gate.user.super_admin === true || gate.user.role?.users === "read" || gate.user.role?.users === "write";
26626
+ const emails = /* @__PURE__ */ new Map();
26627
+ const ids = [...new Set(links.map((l) => l.user))];
26628
+ if (mayReadUsers && ids.length > 0) {
26629
+ const owners = await db2("users").whereIn("id", ids).select("id", "email");
26630
+ for (const o of owners) emails.set(o.id, o.email ?? null);
26631
+ }
26595
26632
  res.json({
26596
26633
  links: links.map((l) => ({
26597
26634
  id: l.id,
26598
26635
  identityMasked: maskIdentity(l.identity),
26599
26636
  userId: l.user,
26637
+ userEmail: emails.get(l.user) ?? null,
26600
26638
  linked_at: l.linked_at,
26601
26639
  expires_at: l.expires_at,
26602
26640
  last_seen_at: l.last_seen_at,
@@ -26605,6 +26643,19 @@ var registerChannelApi = (app, deps) => {
26605
26643
  });
26606
26644
  })
26607
26645
  );
26646
+ app.post(
26647
+ `${base}/verify-token`,
26648
+ route("rotate verify token", async (req, res) => {
26649
+ const gate = await adminAgent(req, res);
26650
+ if (!gate) return;
26651
+ const db2 = await deps.getDb();
26652
+ const row = await loadChannel(db2, gate.agent.id);
26653
+ if (!row) return void res.status(404).json({ detail: "Channel not found." });
26654
+ const verifyToken = (0, import_crypto7.randomBytes)(24).toString("base64url");
26655
+ await db2(TABLE4).where({ id: row.id }).update({ verify_token: verifyToken, updatedAt: now() });
26656
+ res.json({ verifyToken });
26657
+ })
26658
+ );
26608
26659
  app.delete(
26609
26660
  `${base}/links/:linkId`,
26610
26661
  route("revoke link", async (req, res) => {
@@ -26625,24 +26676,53 @@ var registerChannelApi = (app, deps) => {
26625
26676
  res.status(204).end();
26626
26677
  })
26627
26678
  );
26628
- const customerChannel = async (req, opts) => {
26679
+ const customerChannel = async (req) => {
26629
26680
  const agent = await loadAgent(String(req.params.id ?? ""));
26630
26681
  if (!agent) return null;
26631
26682
  const db2 = await deps.getDb();
26632
26683
  const row = await loadChannel(db2, agent.id);
26633
26684
  if (!row) return null;
26634
- if (opts.requireEnabled && !row.enabled) return null;
26635
26685
  return { db: db2, agent, row };
26636
26686
  };
26687
+ const linkableConfig = (agent, row) => {
26688
+ if (!deps.entitled() || !row.enabled) return null;
26689
+ const config = tryParseConfig(row.config);
26690
+ return config && canEnableChannel(agent).ok ? config : null;
26691
+ };
26692
+ app.get(
26693
+ "/public-agents/:id/channels/whatsapp/links",
26694
+ route("customer links", async (req, res) => {
26695
+ const user = await signedIn(req, res);
26696
+ if (!user) return;
26697
+ const none = { available: false, links: [] };
26698
+ if (!deps.entitled()) return void res.json(none);
26699
+ const agent = await loadAgent(String(req.params.id ?? ""));
26700
+ if (!agent) return void res.json(none);
26701
+ const db2 = await deps.getDb();
26702
+ const row = await loadChannel(db2, agent.id);
26703
+ const links = row ? await createLinkStore(db2).listForUser(row.id, user.id) : [];
26704
+ const available = !!row && linkableConfig(agent, row) !== null && await channelAccessAllowed({
26705
+ db: db2,
26706
+ loadAgent: (id) => loadAgent(id),
26707
+ agentId: agent.id,
26708
+ channelId: row.id,
26709
+ userId: user.id
26710
+ });
26711
+ res.json({
26712
+ available,
26713
+ links: links.filter((l) => !l.revoked_at).map((l) => ({ id: l.id, identityMasked: maskIdentity(l.identity), expires_at: l.expires_at }))
26714
+ });
26715
+ })
26716
+ );
26637
26717
  app.post(
26638
26718
  "/public-agents/:id/channels/whatsapp/link-code",
26639
26719
  route("issue link code", async (req, res) => {
26640
26720
  const user = await signedIn(req, res);
26641
26721
  if (!user) return;
26642
26722
  if (!deps.entitled()) return void res.status(404).json(NOT_FOUND);
26643
- const found = await customerChannel(req, { requireEnabled: true });
26644
- const config = found ? tryParseConfig(found.row.config) : null;
26645
- if (!found || !config || !canEnableChannel(found.agent).ok) return void res.status(404).json(NOT_FOUND);
26723
+ const found = await customerChannel(req);
26724
+ const config = found ? linkableConfig(found.agent, found.row) : null;
26725
+ if (!found || !config) return void res.status(404).json(NOT_FOUND);
26646
26726
  const { db: db2, agent, row } = found;
26647
26727
  const allowed = await channelAccessAllowed({
26648
26728
  db: db2,
@@ -26687,7 +26767,7 @@ var registerChannelApi = (app, deps) => {
26687
26767
  if (!user) return;
26688
26768
  const linkId = String(req.params.linkId ?? "");
26689
26769
  if (!UUID_RE2.test(linkId)) return void res.status(404).json(NOT_FOUND);
26690
- const found = await customerChannel(req, { requireEnabled: false });
26770
+ const found = await customerChannel(req);
26691
26771
  if (!found) return void res.status(404).json(NOT_FOUND);
26692
26772
  const { db: db2, row } = found;
26693
26773
  const link = await db2("channel_links").where({ id: linkId, channel: row.id, user: user.id }).first();
@@ -26716,16 +26796,16 @@ var shouldGenerateEmbeddings = ({
26716
26796
  // src/exulu/embedder-change.ts
26717
26797
  init_cjs_shims();
26718
26798
  var MAX_INLINE_REGENERATION_ITEMS = 2e3;
26719
- var decideRebuildCase = (existing, next, tableExists) => {
26720
- if (!tableExists) return "create";
26799
+ var decideRebuildCase = (existing, next, tableExists2) => {
26800
+ if (!tableExists2) return "create";
26721
26801
  if (existing === null) return "recreate";
26722
26802
  return existing === next ? "truncate" : "recreate";
26723
26803
  };
26724
26804
  var changeContextEmbedder = async (context, model, queue, deps) => {
26725
- const tableExists = await deps.chunksTableExists(context);
26805
+ const tableExists2 = await deps.chunksTableExists(context);
26726
26806
  const target = model ?? deps.codeModel(context);
26727
26807
  if (!target) {
26728
- if (tableExists) await deps.dropChunksTable(context);
26808
+ if (tableExists2) await deps.dropChunksTable(context);
26729
26809
  await deps.persist(context.id, null, null);
26730
26810
  await deps.hydrate([context]);
26731
26811
  return { case: "cleared", items: 0, jobs: [] };
@@ -26740,7 +26820,7 @@ var changeContextEmbedder = async (context, model, queue, deps) => {
26740
26820
  }
26741
26821
  }
26742
26822
  const existing = await deps.currentDimensionality(context.id);
26743
- const rebuild = decideRebuildCase(existing, dimensionality, tableExists);
26823
+ const rebuild = decideRebuildCase(existing, dimensionality, tableExists2);
26744
26824
  if (rebuild === "recreate") {
26745
26825
  await deps.dropChunksTable(context);
26746
26826
  await deps.createChunksTable(context);
@@ -30172,7 +30252,7 @@ function detectPayloadFormat(contentType) {
30172
30252
  }
30173
30253
  var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
30174
30254
  function extractMultipartMimePart(rawBody, contentType) {
30175
- return new Promise((resolve10, reject) => {
30255
+ return new Promise((resolve11, reject) => {
30176
30256
  let found = null;
30177
30257
  const bb = (0, import_busboy.default)({ headers: { "content-type": contentType }, defCharset: "latin1" });
30178
30258
  bb.on("field", (name, value) => {
@@ -30181,7 +30261,7 @@ function extractMultipartMimePart(rawBody, contentType) {
30181
30261
  }
30182
30262
  });
30183
30263
  bb.on("close", () => {
30184
- if (found) resolve10(found);
30264
+ if (found) resolve11(found);
30185
30265
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
30186
30266
  });
30187
30267
  bb.on("error", (err4) => reject(err4 instanceof Error ? err4 : new Error(String(err4))));
@@ -31365,7 +31445,7 @@ var createDecideDeps = (p) => {
31365
31445
  now: env.now ?? (() => /* @__PURE__ */ new Date()),
31366
31446
  config,
31367
31447
  // lazily: a missing URL variable must only affect the link reply, never linked users
31368
- linkUrl: () => linkPageUrl(row.agent),
31448
+ linkUrl: () => linkPageUrl(row.agent, config.locale),
31369
31449
  links: createLinkStore(db2),
31370
31450
  consumeCode: (code) => consumeCode(store, code),
31371
31451
  codeAttemptsExceeded: (identity) => codeAttemptsExceeded(store, row.id, identity),
@@ -31612,7 +31692,7 @@ function createSniffer(onFirstLine) {
31612
31692
  const head = [];
31613
31693
  let headBytes = 0;
31614
31694
  let resolved = false;
31615
- const resolve10 = (line) => {
31695
+ const resolve11 = (line) => {
31616
31696
  if (resolved) return;
31617
31697
  resolved = true;
31618
31698
  onFirstLine(line);
@@ -31627,15 +31707,15 @@ function createSniffer(onFirstLine) {
31627
31707
  const text = Buffer.concat(head).toString("utf-8");
31628
31708
  const eol = /\r|\n/.exec(text);
31629
31709
  if (eol) {
31630
- resolve10(text.slice(0, eol.index));
31710
+ resolve11(text.slice(0, eol.index));
31631
31711
  } else if (headBytes >= MAX_HEADER_BYTES) {
31632
- resolve10(text);
31712
+ resolve11(text);
31633
31713
  }
31634
31714
  }
31635
31715
  callback(null, chunk2);
31636
31716
  },
31637
31717
  flush(callback) {
31638
- resolve10(Buffer.concat(head).toString("utf-8"));
31718
+ resolve11(Buffer.concat(head).toString("utf-8"));
31639
31719
  callback();
31640
31720
  }
31641
31721
  });
@@ -31643,8 +31723,8 @@ function createSniffer(onFirstLine) {
31643
31723
  async function streamCsvRows(input, handlers, opts) {
31644
31724
  let resolveFirstLine = () => {
31645
31725
  };
31646
- const firstLine = new Promise((resolve10) => {
31647
- resolveFirstLine = resolve10;
31726
+ const firstLine = new Promise((resolve11) => {
31727
+ resolveFirstLine = resolve11;
31648
31728
  });
31649
31729
  const sniffer = createSniffer((line) => resolveFirstLine(line));
31650
31730
  let parser;
@@ -32140,7 +32220,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32140
32220
  );
32141
32221
  if (attempt < retries) {
32142
32222
  const backoffMs = 500 * Math.pow(2, attempt - 1);
32143
- await new Promise((resolve10) => setTimeout(resolve10, backoffMs));
32223
+ await new Promise((resolve11) => setTimeout(resolve11, backoffMs));
32144
32224
  }
32145
32225
  }
32146
32226
  }
@@ -32358,7 +32438,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32358
32438
  async (sessionId) => {
32359
32439
  const retries2 = 3;
32360
32440
  let attempts = 0;
32361
- const promise = new Promise(async (resolve10, reject) => {
32441
+ const promise = new Promise(async (resolve11, reject) => {
32362
32442
  while (attempts < retries2) {
32363
32443
  try {
32364
32444
  const messages2 = await processUiMessagesFlow({
@@ -32378,7 +32458,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32378
32458
  // back into blanket pre-approval (spec §5.2).
32379
32459
  respectToolApprovals: workflow.auto_approve_tools !== true
32380
32460
  });
32381
- resolve10(messages2);
32461
+ resolve11(messages2);
32382
32462
  break;
32383
32463
  } catch (error) {
32384
32464
  console.error(
@@ -32405,7 +32485,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32405
32485
  }
32406
32486
  reject(new Error(error instanceof Error ? error.message : String(error)));
32407
32487
  }
32408
- await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
32488
+ await new Promise((resolve12) => setTimeout(() => resolve12(true), 2e3));
32409
32489
  }
32410
32490
  }
32411
32491
  });
@@ -32505,7 +32585,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32505
32585
  } = await validateEvalPayload(data);
32506
32586
  const retries2 = 3;
32507
32587
  let attempts = 0;
32508
- const promise = new Promise(async (resolve10, reject) => {
32588
+ const promise = new Promise(async (resolve11, reject) => {
32509
32589
  while (attempts < retries2) {
32510
32590
  try {
32511
32591
  const messages2 = await processUiMessagesFlow({
@@ -32516,7 +32596,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32516
32596
  tools,
32517
32597
  config
32518
32598
  });
32519
- resolve10(messages2);
32599
+ resolve11(messages2);
32520
32600
  break;
32521
32601
  } catch (error) {
32522
32602
  console.error(
@@ -32527,7 +32607,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32527
32607
  if (attempts >= retries2) {
32528
32608
  reject(new Error(error instanceof Error ? error.message : String(error)));
32529
32609
  }
32530
- await new Promise((resolve11) => setTimeout((resolve12) => resolve12(true), 2e3));
32610
+ await new Promise((resolve12) => setTimeout((resolve13) => resolve13(true), 2e3));
32531
32611
  }
32532
32612
  }
32533
32613
  });
@@ -33110,7 +33190,7 @@ var pollJobResult = async ({
33110
33190
  attempts++;
33111
33191
  const job = await import_bullmq3.Job.fromId(queue.queue, jobId);
33112
33192
  if (!job) {
33113
- await new Promise((resolve10) => setTimeout((resolve11) => resolve11(true), 2e3));
33193
+ await new Promise((resolve11) => setTimeout((resolve12) => resolve12(true), 2e3));
33114
33194
  continue;
33115
33195
  }
33116
33196
  const elapsedTime = Date.now() - startTime;
@@ -33140,7 +33220,7 @@ var pollJobResult = async ({
33140
33220
  console.log(`[EXULU] eval function ${job.id} result: ${result}`);
33141
33221
  break;
33142
33222
  }
33143
- await new Promise((resolve10) => setTimeout(() => resolve10(true), 2e3));
33223
+ await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
33144
33224
  }
33145
33225
  return result;
33146
33226
  };
@@ -33244,7 +33324,7 @@ var processUiMessagesFlow = async ({
33244
33324
  trigger: "agent"
33245
33325
  };
33246
33326
  try {
33247
- messageHistory = await new Promise(async (resolve10, reject) => {
33327
+ messageHistory = await new Promise(async (resolve11, reject) => {
33248
33328
  const startTime = Date.now();
33249
33329
  try {
33250
33330
  const result = await generateStream({
@@ -33335,7 +33415,7 @@ var processUiMessagesFlow = async ({
33335
33415
  })
33336
33416
  ] : []
33337
33417
  ]);
33338
- resolve10({
33418
+ resolve11({
33339
33419
  messages,
33340
33420
  metadata: {
33341
33421
  tokens: {
@@ -33604,7 +33684,7 @@ async function fetch_with_retry(args) {
33604
33684
  console.log(
33605
33685
  `[EXULU-RECALL] fetch error from ${url} (${err4.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
33606
33686
  );
33607
- await new Promise((resolve10) => setTimeout(resolve10, 5e3 + jitterMs()));
33687
+ await new Promise((resolve11) => setTimeout(resolve11, 5e3 + jitterMs()));
33608
33688
  continue;
33609
33689
  }
33610
33690
  let wait_for = null;
@@ -33624,7 +33704,7 @@ async function fetch_with_retry(args) {
33624
33704
  `[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
33625
33705
  );
33626
33706
  await new Promise(
33627
- (resolve10) => setTimeout(resolve10, 1e3 * wait_for + jitterMs())
33707
+ (resolve11) => setTimeout(resolve11, 1e3 * wait_for + jitterMs())
33628
33708
  );
33629
33709
  continue;
33630
33710
  }
@@ -38024,7 +38104,7 @@ type EmbeddingModelOption {
38024
38104
  await db2.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
38025
38105
  const retries = 3;
38026
38106
  let attempts = 0;
38027
- const promise = new Promise(async (resolve10, reject) => {
38107
+ const promise = new Promise(async (resolve11, reject) => {
38028
38108
  while (attempts < retries) {
38029
38109
  try {
38030
38110
  const messages2 = await processUiMessagesFlow({
@@ -38042,7 +38122,7 @@ type EmbeddingModelOption {
38042
38122
  // (never overriding a person), not as a chat continuation.
38043
38123
  jobResultId
38044
38124
  });
38045
- resolve10(messages2);
38125
+ resolve11(messages2);
38046
38126
  break;
38047
38127
  } catch (error) {
38048
38128
  console.error(
@@ -38056,7 +38136,7 @@ type EmbeddingModelOption {
38056
38136
  if (attempts >= retries) {
38057
38137
  reject(error instanceof Error ? error : new Error(String(error)));
38058
38138
  }
38059
- await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
38139
+ await new Promise((resolve12) => setTimeout(() => resolve12(true), 2e3));
38060
38140
  }
38061
38141
  }
38062
38142
  });
@@ -38571,10 +38651,10 @@ type EmbeddingModelOption {
38571
38651
  contexts.map(async (context2) => {
38572
38652
  let processor = null;
38573
38653
  if (context2.processor) {
38574
- processor = await new Promise(async (resolve10, reject) => {
38654
+ processor = await new Promise(async (resolve11, reject) => {
38575
38655
  const config2 = context2.processor?.config;
38576
38656
  const queue = await config2?.queue;
38577
- resolve10({
38657
+ resolve11({
38578
38658
  name: context2.processor.name,
38579
38659
  description: context2.processor.description,
38580
38660
  queue: queue?.queue?.name || void 0,
@@ -38656,10 +38736,10 @@ type EmbeddingModelOption {
38656
38736
  }
38657
38737
  let processor = null;
38658
38738
  if (data.processor) {
38659
- processor = await new Promise(async (resolve10, reject) => {
38739
+ processor = await new Promise(async (resolve11, reject) => {
38660
38740
  const config2 = data.processor?.config;
38661
38741
  const queue = await config2?.queue;
38662
- resolve10({
38742
+ resolve11({
38663
38743
  name: data.processor.name,
38664
38744
  description: data.processor.description,
38665
38745
  queue: queue?.queue?.name || void 0,
@@ -39213,7 +39293,7 @@ var import_body_parser = __toESM(require("body-parser"), 1);
39213
39293
  var import_crypto_js7 = require("crypto-js");
39214
39294
  var import_openai = require("openai");
39215
39295
  var import_fs5 = __toESM(require("fs"), 1);
39216
- var import_node_crypto24 = require("crypto");
39296
+ var import_node_crypto25 = require("crypto");
39217
39297
  var import_api3 = require("@opentelemetry/api");
39218
39298
  init_check_record_access();
39219
39299
  var import_jszip4 = __toESM(require("jszip"), 1);
@@ -39831,7 +39911,7 @@ var internetSearchTool = new ExuluTool({
39831
39911
  } catch (error) {
39832
39912
  if (error instanceof import_perplexity_ai.default.RateLimitError && attempt < maxRetries - 1) {
39833
39913
  const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
39834
- await new Promise((resolve10) => setTimeout(resolve10, delay));
39914
+ await new Promise((resolve11) => setTimeout(resolve11, delay));
39835
39915
  continue;
39836
39916
  }
39837
39917
  throw error;
@@ -40769,6 +40849,114 @@ function registerViewerIdentityRoutes(app, deps) {
40769
40849
  });
40770
40850
  }
40771
40851
 
40852
+ // src/exulu/tool-api-route.ts
40853
+ init_cjs_shims();
40854
+ var import_node_crypto23 = require("crypto");
40855
+ init_progress();
40856
+ var TOOL_API_ROUTE_PATH = "/tools/:id";
40857
+ var toolConfigDefaults = (tool5) => Object.fromEntries(
40858
+ (tool5.config ?? []).filter((c) => c.default !== void 0).map((c) => [c.name, c.default])
40859
+ );
40860
+ var isAsyncIterable = (value) => !!value && typeof value === "object" && Symbol.asyncIterator in value;
40861
+ function registerToolApiRoutes(app, deps) {
40862
+ app.post(TOOL_API_ROUTE_PATH, async (req, res) => {
40863
+ const tool5 = deps.tools.find((t) => t.id === req.params.id);
40864
+ if (!tool5 || tool5.api?.enabled !== true) {
40865
+ res.status(404).json({ detail: "Tool not found." });
40866
+ return;
40867
+ }
40868
+ const auth = await deps.authenticate(req);
40869
+ const user = auth.user;
40870
+ if (!user?.id) {
40871
+ res.status(auth.code ?? 401).json({ detail: auth.message ?? "Authentication required." });
40872
+ return;
40873
+ }
40874
+ if (user.type === "api" && user.scope_mode && user.scope_mode !== "admin") {
40875
+ res.status(403).json({ detail: "This API key is scoped to agents and cannot call tools directly." });
40876
+ return;
40877
+ }
40878
+ let input = {};
40879
+ if (tool5.inputSchema) {
40880
+ const parsed = await tool5.inputSchema.safeParseAsync(req.body ?? {});
40881
+ if (!parsed.success) {
40882
+ res.status(400).json({
40883
+ detail: "The request body does not match the tool's input schema.",
40884
+ issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message }))
40885
+ });
40886
+ return;
40887
+ }
40888
+ input = parsed.data ?? {};
40889
+ }
40890
+ const execute2 = tool5.tool?.execute;
40891
+ if (!execute2) {
40892
+ res.status(500).json({ detail: "Tool has no execute function." });
40893
+ return;
40894
+ }
40895
+ const toolCallId = `${tool5.id}_${(0, import_node_crypto23.randomUUID)()}`;
40896
+ const started = Date.now();
40897
+ let output;
40898
+ let status = "ok";
40899
+ let failure;
40900
+ try {
40901
+ const response = await execute2(
40902
+ {
40903
+ ...input,
40904
+ user,
40905
+ req,
40906
+ contexts: Object.fromEntries((deps.contexts ?? []).map((c) => [c.id, c])),
40907
+ exuluConfig: deps.config,
40908
+ upload: deps.buildUpload?.(deps.config, user),
40909
+ toolVariablesConfig: toolConfigDefaults(tool5),
40910
+ allExuluTools: deps.tools,
40911
+ currentTools: [tool5]
40912
+ },
40913
+ { toolCallId, messages: [] }
40914
+ );
40915
+ if (isAsyncIterable(response)) {
40916
+ for await (const value of response) {
40917
+ if (!isInterimToolStatus(value)) output = value;
40918
+ }
40919
+ } else {
40920
+ output = response;
40921
+ }
40922
+ } catch (error) {
40923
+ status = "error";
40924
+ failure = error;
40925
+ }
40926
+ try {
40927
+ await deps.onCall?.({
40928
+ tool: tool5,
40929
+ user,
40930
+ req,
40931
+ toolCallId,
40932
+ input,
40933
+ output,
40934
+ status,
40935
+ error: failure,
40936
+ durationMs: Date.now() - started
40937
+ });
40938
+ } catch (error) {
40939
+ console.error(`[EXULU] tool api: recording the call to "${tool5.id}" failed:`, error);
40940
+ res.status(500).json({ detail: "The tool call could not be recorded." });
40941
+ return;
40942
+ }
40943
+ if (status === "error") {
40944
+ console.error(`[EXULU] tool api: "${tool5.id}" threw:`, failure);
40945
+ res.status(500).json({
40946
+ detail: failure instanceof Error ? failure.message : "The tool failed."
40947
+ });
40948
+ return;
40949
+ }
40950
+ res.status(200).json(output ?? {});
40951
+ });
40952
+ }
40953
+
40954
+ // src/exulu/routes.ts
40955
+ init_logger();
40956
+ init_emit_tool_call();
40957
+ init_client_info();
40958
+ init_tool_upload();
40959
+
40772
40960
  // src/exulu/shared-artifact-create-route.ts
40773
40961
  init_cjs_shims();
40774
40962
  init_shared_artifacts();
@@ -42965,6 +43153,25 @@ See docs/superpowers/specs/2026-05-31-in-chat-image-generation-design.md for the
42965
43153
  // src/exulu/routes.ts
42966
43154
  var import_node_path15 = require("path");
42967
43155
  init_rbac_resolver();
43156
+
43157
+ // src/exulu/session-access.ts
43158
+ init_cjs_shims();
43159
+ init_rbac_resolver();
43160
+ init_check_record_access();
43161
+ var SESSION_RBAC_ENTITY = "agent_session";
43162
+ async function hasSessionAccess(db2, session, rights, user) {
43163
+ const rbac = await RBACResolver(
43164
+ db2,
43165
+ SESSION_RBAC_ENTITY,
43166
+ session.id,
43167
+ session.rights_mode || "private"
43168
+ );
43169
+ const record = { ...session, RBAC: rbac };
43170
+ if (await checkRecordAccess(record, rights, user)) return true;
43171
+ return rights === "read" ? checkRecordAccess(record, "write", user) : false;
43172
+ }
43173
+
43174
+ // src/exulu/routes.ts
42968
43175
  init_tags();
42969
43176
  init_admin_client();
42970
43177
  init_env();
@@ -43137,8 +43344,8 @@ var settleWithin = async (tasks, ms) => {
43137
43344
  try {
43138
43345
  return await Promise.race([
43139
43346
  Promise.allSettled(tasks),
43140
- new Promise((resolve10) => {
43141
- timer3 = setTimeout(() => resolve10(null), ms);
43347
+ new Promise((resolve11) => {
43348
+ timer3 = setTimeout(() => resolve11(null), ms);
43142
43349
  })
43143
43350
  ]);
43144
43351
  } finally {
@@ -43456,7 +43663,7 @@ init_flow();
43456
43663
 
43457
43664
  // src/exulu/recall/verify.ts
43458
43665
  init_cjs_shims();
43459
- var import_node_crypto23 = require("crypto");
43666
+ var import_node_crypto24 = require("crypto");
43460
43667
  var TOLERANCE_SECONDS = 5 * 60;
43461
43668
  var header = (headers, ...names) => {
43462
43669
  for (const name of names) {
@@ -43474,7 +43681,7 @@ var safeEqual = (a, b) => {
43474
43681
  const bufA = Buffer.from(a);
43475
43682
  const bufB = Buffer.from(b);
43476
43683
  if (bufA.length !== bufB.length) return false;
43477
- return (0, import_node_crypto23.timingSafeEqual)(bufA, bufB);
43684
+ return (0, import_node_crypto24.timingSafeEqual)(bufA, bufB);
43478
43685
  };
43479
43686
  var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
43480
43687
  if (!secret) {
@@ -43496,7 +43703,7 @@ var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()
43496
43703
  }
43497
43704
  const body = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
43498
43705
  const signedContent = `${id}.${timestamp}.${body}`;
43499
- const expected = (0, import_node_crypto23.createHmac)("sha256", secretKey(secret)).update(signedContent).digest("base64");
43706
+ const expected = (0, import_node_crypto24.createHmac)("sha256", secretKey(secret)).update(signedContent).digest("base64");
43500
43707
  const passed = signatureHeader.split(" ").some((entry) => {
43501
43708
  const [, sig] = entry.split(",");
43502
43709
  return !!sig && safeEqual(sig, expected);
@@ -44022,7 +44229,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
44022
44229
  inputs: payload
44023
44230
  };
44024
44231
  await queue.queue.add("email-intake", jobData, {
44025
- jobId: (0, import_node_crypto24.randomUUID)(),
44232
+ jobId: (0, import_node_crypto25.randomUUID)(),
44026
44233
  attempts: 3,
44027
44234
  removeOnComplete: 5e3,
44028
44235
  removeOnFail: 1e4,
@@ -44430,7 +44637,7 @@ ${customInstructions}` : agent.instructions,
44430
44637
  contextId: agent.memory,
44431
44638
  agentId: agent.id,
44432
44639
  session: headers.session ?? null,
44433
- messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0, import_node_crypto24.randomUUID)(),
44640
+ messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0, import_node_crypto25.randomUUID)(),
44434
44641
  userId: user?.id ?? null
44435
44642
  });
44436
44643
  }
@@ -45032,17 +45239,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
45032
45239
  res.status(404).json({ detail: `Session ${sessionId} not found.` });
45033
45240
  return null;
45034
45241
  }
45035
- const sessionRbac = await RBACResolver(
45036
- db2,
45037
- "agent_sessions",
45038
- session.id,
45039
- session.rights_mode || "private"
45040
- );
45041
- const allowed = await checkRecordAccess(
45042
- { ...session, RBAC: sessionRbac },
45043
- rights,
45044
- authResult.user
45045
- );
45242
+ const allowed = await hasSessionAccess(db2, session, rights, authResult.user);
45046
45243
  if (!allowed) {
45047
45244
  res.status(403).json({ detail: `You don't have ${rights} access to this session.` });
45048
45245
  return null;
@@ -45070,7 +45267,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
45070
45267
  }
45071
45268
  const rbac = await RBACResolver(
45072
45269
  db2,
45073
- "platform_configurations",
45270
+ "platform_configuration",
45074
45271
  row.id,
45075
45272
  row.rights_mode || "private"
45076
45273
  );
@@ -45133,7 +45330,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
45133
45330
  const keys = [];
45134
45331
  const revisedPrompts = [];
45135
45332
  for (const img of images) {
45136
- const filename = `${(0, import_node_crypto24.randomUUID)()}.${img.extension}`;
45333
+ const filename = `${(0, import_node_crypto25.randomUUID)()}.${img.extension}`;
45137
45334
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
45138
45335
  const fullKey = await uploadFile(
45139
45336
  img.buffer,
@@ -45421,7 +45618,7 @@ ${style.markdown}` : params.prompt;
45421
45618
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
45422
45619
  );
45423
45620
  const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
45424
- const messageId = (0, import_node_crypto24.randomUUID)();
45621
+ const messageId = (0, import_node_crypto25.randomUUID)();
45425
45622
  const uiMessage = {
45426
45623
  id: messageId,
45427
45624
  role: "system",
@@ -46518,7 +46715,7 @@ ${style.markdown}` : params.prompt;
46518
46715
  return;
46519
46716
  }
46520
46717
  const meta = await parseSkillFrontmatter(bytes);
46521
- const skillId = (0, import_node_crypto24.randomUUID)();
46718
+ const skillId = (0, import_node_crypto25.randomUUID)();
46522
46719
  try {
46523
46720
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
46524
46721
  } catch (err4) {
@@ -46641,7 +46838,7 @@ ${style.markdown}` : params.prompt;
46641
46838
  return;
46642
46839
  }
46643
46840
  if (!await ensureSkillWrite(db2, skill, authResult.user, res)) return;
46644
- const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0, import_node_crypto24.randomUUID)()}${extension}`;
46841
+ const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0, import_node_crypto25.randomUUID)()}${extension}`;
46645
46842
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
46646
46843
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
46647
46844
  res.json({ uploadUrl, stagingKey });
@@ -47735,6 +47932,39 @@ ${style.markdown}` : params.prompt;
47735
47932
  RBACResolver,
47736
47933
  checkRecordAccess
47737
47934
  });
47935
+ registerToolApiRoutes(app, {
47936
+ authenticate: (req) => requestValidators.authenticate(req),
47937
+ tools,
47938
+ contexts,
47939
+ config,
47940
+ buildUpload: (cfg, user) => buildToolUpload(cfg, user),
47941
+ onCall: async ({ tool: tool5, user, req, toolCallId, input, output, status, error, durationMs }) => {
47942
+ await updateStatistic({
47943
+ name: "count",
47944
+ label: tool5.name,
47945
+ type: STATISTICS_TYPE_ENUM.TOOL_CALL,
47946
+ trigger: "api",
47947
+ count: 1,
47948
+ user: user.id,
47949
+ role: user.role?.id
47950
+ });
47951
+ const auditLogger = getAuditLogger(config ?? {});
47952
+ await emitToolCallAudit(auditLogger, {
47953
+ durationMs,
47954
+ agent: void 0,
47955
+ tool: { id: tool5.id, name: tool5.name, category: tool5.category, authentication: tool5.authentication },
47956
+ user,
47957
+ projectId: void 0,
47958
+ sessionID: void 0,
47959
+ toolCallId,
47960
+ input,
47961
+ output,
47962
+ status,
47963
+ error,
47964
+ client: extractClientInfo(req)
47965
+ });
47966
+ }
47967
+ });
47738
47968
  registerClaimCheckRoutes(app, {
47739
47969
  authenticate: (req) => requestValidators.authenticate(req),
47740
47970
  checkApiKeyScope,
@@ -48038,7 +48268,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
48038
48268
  // src/mcp/index.ts
48039
48269
  init_cjs_shims();
48040
48270
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
48041
- var import_node_crypto25 = require("crypto");
48271
+ var import_node_crypto26 = require("crypto");
48042
48272
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
48043
48273
  var import_types14 = require("@modelcontextprotocol/sdk/types.js");
48044
48274
  init_sanitize_tool_name();
@@ -48139,7 +48369,7 @@ var ExuluMCP = class {
48139
48369
  throw new Error("Tool not found in converted tools array.");
48140
48370
  }
48141
48371
  const iterator = await convertedTool.execute(inputs, {
48142
- toolCallId: tool5.id + "_" + (0, import_node_crypto25.randomUUID)(),
48372
+ toolCallId: tool5.id + "_" + (0, import_node_crypto26.randomUUID)(),
48143
48373
  messages: []
48144
48374
  });
48145
48375
  let result;
@@ -48329,7 +48559,7 @@ var ExuluMCP = class {
48329
48559
  transport = this.transports[sessionId];
48330
48560
  } else if (!sessionId && (0, import_types14.isInitializeRequest)(req.body)) {
48331
48561
  transport = new import_streamableHttp.StreamableHTTPServerTransport({
48332
- sessionIdGenerator: () => (0, import_node_crypto25.randomUUID)(),
48562
+ sessionIdGenerator: () => (0, import_node_crypto26.randomUUID)(),
48333
48563
  onsessioninitialized: (sessionId2) => {
48334
48564
  this.transports[sessionId2] = transport;
48335
48565
  }
@@ -48935,7 +49165,7 @@ var import_zod39 = __toESM(require("zod"), 1);
48935
49165
  init_tool2();
48936
49166
  init_check_record_access();
48937
49167
  init_client();
48938
- var import_node_crypto26 = require("crypto");
49168
+ var import_node_crypto27 = require("crypto");
48939
49169
  var AnswerOptionSchema = import_zod39.default.object({
48940
49170
  id: import_zod39.default.string().describe("Unique identifier for the answer option"),
48941
49171
  text: import_zod39.default.string().describe("The text of the answer option")
@@ -48989,15 +49219,15 @@ var QuestionAskTool = new ExuluTool({
48989
49219
  throw new Error("You don't have access to this session " + session.id + ".");
48990
49220
  }
48991
49221
  const answerOptionsWithIds = answerOptions.map((text) => ({
48992
- id: (0, import_node_crypto26.randomUUID)(),
49222
+ id: (0, import_node_crypto27.randomUUID)(),
48993
49223
  text
48994
49224
  }));
48995
49225
  answerOptionsWithIds.push({
48996
- id: (0, import_node_crypto26.randomUUID)(),
49226
+ id: (0, import_node_crypto27.randomUUID)(),
48997
49227
  text: "None of the above..."
48998
49228
  });
48999
49229
  const newQuestion = {
49000
- id: (0, import_node_crypto26.randomUUID)(),
49230
+ id: (0, import_node_crypto27.randomUUID)(),
49001
49231
  question,
49002
49232
  answerOptions: answerOptionsWithIds,
49003
49233
  status: "pending"
@@ -49195,7 +49425,7 @@ var loadAvailableStyles = async (user) => {
49195
49425
  for (const row of rows) {
49196
49426
  const rbac = await RBACResolver(
49197
49427
  db2,
49198
- "platform_configurations",
49428
+ "platform_configuration",
49199
49429
  row.id,
49200
49430
  row.rights_mode || "private"
49201
49431
  );
@@ -51379,8 +51609,8 @@ init_cjs_shims();
51379
51609
 
51380
51610
  // src/exulu/litellm/db-init.ts
51381
51611
  init_cjs_shims();
51382
- var import_node_fs12 = require("fs");
51383
- var import_node_path17 = require("path");
51612
+ var import_node_fs13 = require("fs");
51613
+ var import_node_path18 = require("path");
51384
51614
  var import_node_child_process8 = require("child_process");
51385
51615
  var import_pg3 = require("pg");
51386
51616
 
@@ -51438,6 +51668,68 @@ var checkLiteLLMDatabaseSafety = (configPath) => {
51438
51668
  return { ok: true, reason: "isolated", litellmTarget };
51439
51669
  };
51440
51670
 
51671
+ // src/exulu/litellm/pre-push-migrations.ts
51672
+ init_cjs_shims();
51673
+ var import_node_fs12 = require("fs");
51674
+ var import_node_path17 = require("path");
51675
+ var tableExists = async (client2, table) => {
51676
+ const res = await client2.query(
51677
+ `SELECT 1 AS exists FROM information_schema.tables
51678
+ WHERE table_schema = 'public' AND table_name = $1`,
51679
+ [table]
51680
+ );
51681
+ return res.rows.length > 0;
51682
+ };
51683
+ var columnExists = async (client2, table, column) => {
51684
+ const res = await client2.query(
51685
+ `SELECT 1 AS exists FROM information_schema.columns
51686
+ WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`,
51687
+ [table, column]
51688
+ );
51689
+ return res.rows.length > 0;
51690
+ };
51691
+ var JWT_KEY_MAPPING_ISSUER_MIGRATION = "20260915000000_scope_jwt_key_mapping_by_issuer";
51692
+ var MIGRATIONS = [
51693
+ {
51694
+ name: JWT_KEY_MAPPING_ISSUER_MIGRATION,
51695
+ isNeeded: async (client2) => (
51696
+ // A fresh database has no table yet; the push creates it in its final
51697
+ // shape, and the migration's ALTER TABLE would fail on a missing table.
51698
+ await tableExists(client2, "LiteLLM_JWTKeyMapping") && !await columnExists(client2, "LiteLLM_JWTKeyMapping", "jwt_issuer")
51699
+ )
51700
+ }
51701
+ ];
51702
+ var applyPrePushMigrations = async (args) => {
51703
+ const { client: client2, migrationsDir, log: log7 } = args;
51704
+ const result = { applied: [], failed: [] };
51705
+ for (const migration of MIGRATIONS) {
51706
+ const file = (0, import_node_path17.resolve)(migrationsDir, migration.name, "migration.sql");
51707
+ if (!(0, import_node_fs12.existsSync)(file)) continue;
51708
+ try {
51709
+ if (!await migration.isNeeded(client2)) continue;
51710
+ } catch (err4) {
51711
+ result.failed.push({ name: migration.name, error: errorMessage(err4) });
51712
+ continue;
51713
+ }
51714
+ const sql = (0, import_node_fs12.readFileSync)(file, "utf8");
51715
+ try {
51716
+ await client2.query("BEGIN");
51717
+ await client2.query(sql);
51718
+ await client2.query("COMMIT");
51719
+ result.applied.push(migration.name);
51720
+ log7(`Applied LiteLLM migration ${migration.name} ahead of the schema push.`);
51721
+ } catch (err4) {
51722
+ try {
51723
+ await client2.query("ROLLBACK");
51724
+ } catch {
51725
+ }
51726
+ result.failed.push({ name: migration.name, error: errorMessage(err4) });
51727
+ }
51728
+ }
51729
+ return result;
51730
+ };
51731
+ var errorMessage = (err4) => err4 instanceof Error ? err4.message : String(err4);
51732
+
51441
51733
  // src/exulu/litellm/db-init.ts
51442
51734
  var WARNING_BANNER = "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550";
51443
51735
  var warn3 = (lines) => {
@@ -51449,8 +51741,14 @@ ${WARNING_BANNER}`);
51449
51741
  `);
51450
51742
  };
51451
51743
  var log6 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
51744
+ var LiteLLMSchemaPushError = class extends Error {
51745
+ constructor(message) {
51746
+ super(message);
51747
+ this.name = "LiteLLMSchemaPushError";
51748
+ }
51749
+ };
51452
51750
  var initLiteLLMDatabase = async (packageRoot) => {
51453
- const configPath = process.env.LITELLM_CONFIG_PATH ?? (0, import_node_path17.resolve)(process.cwd(), "./config.litellm.yaml");
51751
+ const configPath = process.env.LITELLM_CONFIG_PATH ?? (0, import_node_path18.resolve)(process.cwd(), "./config.litellm.yaml");
51454
51752
  const safety = checkLiteLLMDatabaseSafety(configPath);
51455
51753
  if (safety.ok && safety.reason === "no-litellm-db-mode") return;
51456
51754
  if (!safety.ok && safety.reason === "unparseable-url") {
@@ -51588,10 +51886,10 @@ var initLiteLLMDatabase = async (packageRoot) => {
51588
51886
  ]);
51589
51887
  return;
51590
51888
  }
51591
- const venvBin = (0, import_node_path17.resolve)(packageRoot, "ee/python/.venv/bin");
51592
- const prismaCli = (0, import_node_path17.resolve)(venvBin, "prisma");
51593
- const venvLibDir = (0, import_node_path17.resolve)(packageRoot, "ee/python/.venv/lib");
51594
- const pythonVersionDir = (0, import_node_fs12.existsSync)(venvLibDir) ? (0, import_node_fs12.readdirSync)(venvLibDir).find((entry) => /^python3\.\d+$/.test(entry)) : void 0;
51889
+ const venvBin = (0, import_node_path18.resolve)(packageRoot, "ee/python/.venv/bin");
51890
+ const prismaCli = (0, import_node_path18.resolve)(venvBin, "prisma");
51891
+ const venvLibDir = (0, import_node_path18.resolve)(packageRoot, "ee/python/.venv/lib");
51892
+ const pythonVersionDir = (0, import_node_fs13.existsSync)(venvLibDir) ? (0, import_node_fs13.readdirSync)(venvLibDir).find((entry) => /^python3\.\d+$/.test(entry)) : void 0;
51595
51893
  if (!pythonVersionDir) {
51596
51894
  warn3([
51597
51895
  `Could not find a python3.* directory under ${venvLibDir}.`,
@@ -51600,13 +51898,13 @@ var initLiteLLMDatabase = async (packageRoot) => {
51600
51898
  ]);
51601
51899
  return;
51602
51900
  }
51603
- const litellmProxyDir = (0, import_node_path17.resolve)(
51901
+ const litellmProxyDir = (0, import_node_path18.resolve)(
51604
51902
  venvLibDir,
51605
51903
  pythonVersionDir,
51606
51904
  "site-packages/litellm/proxy"
51607
51905
  );
51608
- const schemaPath = (0, import_node_path17.resolve)(litellmProxyDir, "schema.prisma");
51609
- if (!(0, import_node_fs12.existsSync)(prismaCli)) {
51906
+ const schemaPath = (0, import_node_path18.resolve)(litellmProxyDir, "schema.prisma");
51907
+ if (!(0, import_node_fs13.existsSync)(prismaCli)) {
51610
51908
  warn3([
51611
51909
  `Prisma CLI not found at ${prismaCli}.`,
51612
51910
  `Run \`npm run python:setup\` to create the venv and install prisma.`,
@@ -51614,13 +51912,45 @@ var initLiteLLMDatabase = async (packageRoot) => {
51614
51912
  ]);
51615
51913
  return;
51616
51914
  }
51617
- if (!(0, import_node_fs12.existsSync)(schemaPath)) {
51915
+ if (!(0, import_node_fs13.existsSync)(schemaPath)) {
51618
51916
  warn3([
51619
51917
  `LiteLLM Prisma schema not found at ${schemaPath}.`,
51620
51918
  `Re-run \`npm run python:setup\`. Skipping LiteLLM database setup.`
51621
51919
  ]);
51622
51920
  return;
51623
51921
  }
51922
+ const prePushClient = new import_pg3.Client({ connectionString: litellmUrl });
51923
+ try {
51924
+ await prePushClient.connect();
51925
+ const prePush = await applyPrePushMigrations({
51926
+ client: prePushClient,
51927
+ migrationsDir: (0, import_node_path18.resolve)(
51928
+ venvLibDir,
51929
+ pythonVersionDir,
51930
+ "site-packages/litellm_proxy_extras/migrations"
51931
+ ),
51932
+ log: log6
51933
+ });
51934
+ if (prePush.failed.length > 0) {
51935
+ warn3([
51936
+ `Could not prepare LiteLLM's database for the schema push:`,
51937
+ ...prePush.failed.map((f) => ` ${f.name}: ${f.error}`),
51938
+ ``,
51939
+ `Continuing with prisma db push, which will likely refuse and name`,
51940
+ `the change it cannot make.`
51941
+ ]);
51942
+ }
51943
+ } catch (err4) {
51944
+ warn3([
51945
+ `Could not connect to LiteLLM's database to prepare the schema push:`,
51946
+ ` ${err4 instanceof Error ? err4.message : String(err4)}`
51947
+ ]);
51948
+ } finally {
51949
+ try {
51950
+ await prePushClient.end();
51951
+ } catch {
51952
+ }
51953
+ }
51624
51954
  log6("Running `prisma db push` against LiteLLM's schema\u2026");
51625
51955
  const result = (0, import_node_child_process8.spawnSync)(prismaCli, ["db", "push", "--skip-generate"], {
51626
51956
  cwd: litellmProxyDir,
@@ -51637,9 +51967,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
51637
51967
  if (result.error) {
51638
51968
  warn3([
51639
51969
  `Failed to launch prisma: ${result.error.message}`,
51640
- `Skipping LiteLLM database setup.`
51970
+ `LiteLLM's database schema was NOT updated.`
51641
51971
  ]);
51642
- return;
51972
+ throw new LiteLLMSchemaPushError(
51973
+ `Could not launch prisma to update LiteLLM's database schema: ${result.error.message}`
51974
+ );
51643
51975
  }
51644
51976
  if (result.status !== 0) {
51645
51977
  warn3([
@@ -51647,9 +51979,16 @@ var initLiteLLMDatabase = async (packageRoot) => {
51647
51979
  `stdout:`,
51648
51980
  ...(result.stdout || "(empty)").split("\n").map((l) => ` ${l}`),
51649
51981
  `stderr:`,
51650
- ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`)
51982
+ ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`),
51983
+ ``,
51984
+ `LiteLLM's database schema was NOT updated. Starting the proxy on it`,
51985
+ `would break tag budgets and spend tracking while chat keeps working.`,
51986
+ `If prisma asks for --accept-data-loss, a LiteLLM upgrade changed a`,
51987
+ `constraint it will not alter on its own: see pre-push-migrations.ts.`
51651
51988
  ]);
51652
- return;
51989
+ throw new LiteLLMSchemaPushError(
51990
+ `prisma db push against LiteLLM's database exited with status ${result.status}: ` + (result.stderr || result.stdout || "no output").trim().split("\n").slice(-3).join(" ")
51991
+ );
51653
51992
  }
51654
51993
  log6("\u2713 LiteLLM database ready.");
51655
51994
  };
@@ -51693,7 +52032,7 @@ var create = ({
51693
52032
  });
51694
52033
  const sdk = new import_sdk_node.NodeSDK({
51695
52034
  traceExporter,
51696
- logRecordProcessors: [new import_sdk_logs.BatchLogRecordProcessor(logExporter)],
52035
+ logRecordProcessors: [new import_sdk_logs.BatchLogRecordProcessor({ exporter: logExporter })],
51697
52036
  instrumentations: [(0, import_auto_instrumentations_node.getNodeAutoInstrumentations)()],
51698
52037
  resource: (0, import_resources.resourceFromAttributes)({
51699
52038
  [import_semantic_conventions.ATTR_SERVICE_NAME]: "Exulu"