@exulu/backend 5.18.0 → 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;
@@ -26766,16 +26796,16 @@ var shouldGenerateEmbeddings = ({
26766
26796
  // src/exulu/embedder-change.ts
26767
26797
  init_cjs_shims();
26768
26798
  var MAX_INLINE_REGENERATION_ITEMS = 2e3;
26769
- var decideRebuildCase = (existing, next, tableExists) => {
26770
- if (!tableExists) return "create";
26799
+ var decideRebuildCase = (existing, next, tableExists2) => {
26800
+ if (!tableExists2) return "create";
26771
26801
  if (existing === null) return "recreate";
26772
26802
  return existing === next ? "truncate" : "recreate";
26773
26803
  };
26774
26804
  var changeContextEmbedder = async (context, model, queue, deps) => {
26775
- const tableExists = await deps.chunksTableExists(context);
26805
+ const tableExists2 = await deps.chunksTableExists(context);
26776
26806
  const target = model ?? deps.codeModel(context);
26777
26807
  if (!target) {
26778
- if (tableExists) await deps.dropChunksTable(context);
26808
+ if (tableExists2) await deps.dropChunksTable(context);
26779
26809
  await deps.persist(context.id, null, null);
26780
26810
  await deps.hydrate([context]);
26781
26811
  return { case: "cleared", items: 0, jobs: [] };
@@ -26790,7 +26820,7 @@ var changeContextEmbedder = async (context, model, queue, deps) => {
26790
26820
  }
26791
26821
  }
26792
26822
  const existing = await deps.currentDimensionality(context.id);
26793
- const rebuild = decideRebuildCase(existing, dimensionality, tableExists);
26823
+ const rebuild = decideRebuildCase(existing, dimensionality, tableExists2);
26794
26824
  if (rebuild === "recreate") {
26795
26825
  await deps.dropChunksTable(context);
26796
26826
  await deps.createChunksTable(context);
@@ -30222,7 +30252,7 @@ function detectPayloadFormat(contentType) {
30222
30252
  }
30223
30253
  var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
30224
30254
  function extractMultipartMimePart(rawBody, contentType) {
30225
- return new Promise((resolve10, reject) => {
30255
+ return new Promise((resolve11, reject) => {
30226
30256
  let found = null;
30227
30257
  const bb = (0, import_busboy.default)({ headers: { "content-type": contentType }, defCharset: "latin1" });
30228
30258
  bb.on("field", (name, value) => {
@@ -30231,7 +30261,7 @@ function extractMultipartMimePart(rawBody, contentType) {
30231
30261
  }
30232
30262
  });
30233
30263
  bb.on("close", () => {
30234
- if (found) resolve10(found);
30264
+ if (found) resolve11(found);
30235
30265
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
30236
30266
  });
30237
30267
  bb.on("error", (err4) => reject(err4 instanceof Error ? err4 : new Error(String(err4))));
@@ -31662,7 +31692,7 @@ function createSniffer(onFirstLine) {
31662
31692
  const head = [];
31663
31693
  let headBytes = 0;
31664
31694
  let resolved = false;
31665
- const resolve10 = (line) => {
31695
+ const resolve11 = (line) => {
31666
31696
  if (resolved) return;
31667
31697
  resolved = true;
31668
31698
  onFirstLine(line);
@@ -31677,15 +31707,15 @@ function createSniffer(onFirstLine) {
31677
31707
  const text = Buffer.concat(head).toString("utf-8");
31678
31708
  const eol = /\r|\n/.exec(text);
31679
31709
  if (eol) {
31680
- resolve10(text.slice(0, eol.index));
31710
+ resolve11(text.slice(0, eol.index));
31681
31711
  } else if (headBytes >= MAX_HEADER_BYTES) {
31682
- resolve10(text);
31712
+ resolve11(text);
31683
31713
  }
31684
31714
  }
31685
31715
  callback(null, chunk2);
31686
31716
  },
31687
31717
  flush(callback) {
31688
- resolve10(Buffer.concat(head).toString("utf-8"));
31718
+ resolve11(Buffer.concat(head).toString("utf-8"));
31689
31719
  callback();
31690
31720
  }
31691
31721
  });
@@ -31693,8 +31723,8 @@ function createSniffer(onFirstLine) {
31693
31723
  async function streamCsvRows(input, handlers, opts) {
31694
31724
  let resolveFirstLine = () => {
31695
31725
  };
31696
- const firstLine = new Promise((resolve10) => {
31697
- resolveFirstLine = resolve10;
31726
+ const firstLine = new Promise((resolve11) => {
31727
+ resolveFirstLine = resolve11;
31698
31728
  });
31699
31729
  const sniffer = createSniffer((line) => resolveFirstLine(line));
31700
31730
  let parser;
@@ -32190,7 +32220,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32190
32220
  );
32191
32221
  if (attempt < retries) {
32192
32222
  const backoffMs = 500 * Math.pow(2, attempt - 1);
32193
- await new Promise((resolve10) => setTimeout(resolve10, backoffMs));
32223
+ await new Promise((resolve11) => setTimeout(resolve11, backoffMs));
32194
32224
  }
32195
32225
  }
32196
32226
  }
@@ -32408,7 +32438,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32408
32438
  async (sessionId) => {
32409
32439
  const retries2 = 3;
32410
32440
  let attempts = 0;
32411
- const promise = new Promise(async (resolve10, reject) => {
32441
+ const promise = new Promise(async (resolve11, reject) => {
32412
32442
  while (attempts < retries2) {
32413
32443
  try {
32414
32444
  const messages2 = await processUiMessagesFlow({
@@ -32428,7 +32458,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32428
32458
  // back into blanket pre-approval (spec §5.2).
32429
32459
  respectToolApprovals: workflow.auto_approve_tools !== true
32430
32460
  });
32431
- resolve10(messages2);
32461
+ resolve11(messages2);
32432
32462
  break;
32433
32463
  } catch (error) {
32434
32464
  console.error(
@@ -32455,7 +32485,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32455
32485
  }
32456
32486
  reject(new Error(error instanceof Error ? error.message : String(error)));
32457
32487
  }
32458
- await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
32488
+ await new Promise((resolve12) => setTimeout(() => resolve12(true), 2e3));
32459
32489
  }
32460
32490
  }
32461
32491
  });
@@ -32555,7 +32585,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32555
32585
  } = await validateEvalPayload(data);
32556
32586
  const retries2 = 3;
32557
32587
  let attempts = 0;
32558
- const promise = new Promise(async (resolve10, reject) => {
32588
+ const promise = new Promise(async (resolve11, reject) => {
32559
32589
  while (attempts < retries2) {
32560
32590
  try {
32561
32591
  const messages2 = await processUiMessagesFlow({
@@ -32566,7 +32596,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32566
32596
  tools,
32567
32597
  config
32568
32598
  });
32569
- resolve10(messages2);
32599
+ resolve11(messages2);
32570
32600
  break;
32571
32601
  } catch (error) {
32572
32602
  console.error(
@@ -32577,7 +32607,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32577
32607
  if (attempts >= retries2) {
32578
32608
  reject(new Error(error instanceof Error ? error.message : String(error)));
32579
32609
  }
32580
- await new Promise((resolve11) => setTimeout((resolve12) => resolve12(true), 2e3));
32610
+ await new Promise((resolve12) => setTimeout((resolve13) => resolve13(true), 2e3));
32581
32611
  }
32582
32612
  }
32583
32613
  });
@@ -33160,7 +33190,7 @@ var pollJobResult = async ({
33160
33190
  attempts++;
33161
33191
  const job = await import_bullmq3.Job.fromId(queue.queue, jobId);
33162
33192
  if (!job) {
33163
- await new Promise((resolve10) => setTimeout((resolve11) => resolve11(true), 2e3));
33193
+ await new Promise((resolve11) => setTimeout((resolve12) => resolve12(true), 2e3));
33164
33194
  continue;
33165
33195
  }
33166
33196
  const elapsedTime = Date.now() - startTime;
@@ -33190,7 +33220,7 @@ var pollJobResult = async ({
33190
33220
  console.log(`[EXULU] eval function ${job.id} result: ${result}`);
33191
33221
  break;
33192
33222
  }
33193
- await new Promise((resolve10) => setTimeout(() => resolve10(true), 2e3));
33223
+ await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
33194
33224
  }
33195
33225
  return result;
33196
33226
  };
@@ -33294,7 +33324,7 @@ var processUiMessagesFlow = async ({
33294
33324
  trigger: "agent"
33295
33325
  };
33296
33326
  try {
33297
- messageHistory = await new Promise(async (resolve10, reject) => {
33327
+ messageHistory = await new Promise(async (resolve11, reject) => {
33298
33328
  const startTime = Date.now();
33299
33329
  try {
33300
33330
  const result = await generateStream({
@@ -33385,7 +33415,7 @@ var processUiMessagesFlow = async ({
33385
33415
  })
33386
33416
  ] : []
33387
33417
  ]);
33388
- resolve10({
33418
+ resolve11({
33389
33419
  messages,
33390
33420
  metadata: {
33391
33421
  tokens: {
@@ -33654,7 +33684,7 @@ async function fetch_with_retry(args) {
33654
33684
  console.log(
33655
33685
  `[EXULU-RECALL] fetch error from ${url} (${err4.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
33656
33686
  );
33657
- await new Promise((resolve10) => setTimeout(resolve10, 5e3 + jitterMs()));
33687
+ await new Promise((resolve11) => setTimeout(resolve11, 5e3 + jitterMs()));
33658
33688
  continue;
33659
33689
  }
33660
33690
  let wait_for = null;
@@ -33674,7 +33704,7 @@ async function fetch_with_retry(args) {
33674
33704
  `[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
33675
33705
  );
33676
33706
  await new Promise(
33677
- (resolve10) => setTimeout(resolve10, 1e3 * wait_for + jitterMs())
33707
+ (resolve11) => setTimeout(resolve11, 1e3 * wait_for + jitterMs())
33678
33708
  );
33679
33709
  continue;
33680
33710
  }
@@ -38074,7 +38104,7 @@ type EmbeddingModelOption {
38074
38104
  await db2.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
38075
38105
  const retries = 3;
38076
38106
  let attempts = 0;
38077
- const promise = new Promise(async (resolve10, reject) => {
38107
+ const promise = new Promise(async (resolve11, reject) => {
38078
38108
  while (attempts < retries) {
38079
38109
  try {
38080
38110
  const messages2 = await processUiMessagesFlow({
@@ -38092,7 +38122,7 @@ type EmbeddingModelOption {
38092
38122
  // (never overriding a person), not as a chat continuation.
38093
38123
  jobResultId
38094
38124
  });
38095
- resolve10(messages2);
38125
+ resolve11(messages2);
38096
38126
  break;
38097
38127
  } catch (error) {
38098
38128
  console.error(
@@ -38106,7 +38136,7 @@ type EmbeddingModelOption {
38106
38136
  if (attempts >= retries) {
38107
38137
  reject(error instanceof Error ? error : new Error(String(error)));
38108
38138
  }
38109
- await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
38139
+ await new Promise((resolve12) => setTimeout(() => resolve12(true), 2e3));
38110
38140
  }
38111
38141
  }
38112
38142
  });
@@ -38621,10 +38651,10 @@ type EmbeddingModelOption {
38621
38651
  contexts.map(async (context2) => {
38622
38652
  let processor = null;
38623
38653
  if (context2.processor) {
38624
- processor = await new Promise(async (resolve10, reject) => {
38654
+ processor = await new Promise(async (resolve11, reject) => {
38625
38655
  const config2 = context2.processor?.config;
38626
38656
  const queue = await config2?.queue;
38627
- resolve10({
38657
+ resolve11({
38628
38658
  name: context2.processor.name,
38629
38659
  description: context2.processor.description,
38630
38660
  queue: queue?.queue?.name || void 0,
@@ -38706,10 +38736,10 @@ type EmbeddingModelOption {
38706
38736
  }
38707
38737
  let processor = null;
38708
38738
  if (data.processor) {
38709
- processor = await new Promise(async (resolve10, reject) => {
38739
+ processor = await new Promise(async (resolve11, reject) => {
38710
38740
  const config2 = data.processor?.config;
38711
38741
  const queue = await config2?.queue;
38712
- resolve10({
38742
+ resolve11({
38713
38743
  name: data.processor.name,
38714
38744
  description: data.processor.description,
38715
38745
  queue: queue?.queue?.name || void 0,
@@ -39263,7 +39293,7 @@ var import_body_parser = __toESM(require("body-parser"), 1);
39263
39293
  var import_crypto_js7 = require("crypto-js");
39264
39294
  var import_openai = require("openai");
39265
39295
  var import_fs5 = __toESM(require("fs"), 1);
39266
- var import_node_crypto24 = require("crypto");
39296
+ var import_node_crypto25 = require("crypto");
39267
39297
  var import_api3 = require("@opentelemetry/api");
39268
39298
  init_check_record_access();
39269
39299
  var import_jszip4 = __toESM(require("jszip"), 1);
@@ -39881,7 +39911,7 @@ var internetSearchTool = new ExuluTool({
39881
39911
  } catch (error) {
39882
39912
  if (error instanceof import_perplexity_ai.default.RateLimitError && attempt < maxRetries - 1) {
39883
39913
  const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
39884
- await new Promise((resolve10) => setTimeout(resolve10, delay));
39914
+ await new Promise((resolve11) => setTimeout(resolve11, delay));
39885
39915
  continue;
39886
39916
  }
39887
39917
  throw error;
@@ -40819,6 +40849,114 @@ function registerViewerIdentityRoutes(app, deps) {
40819
40849
  });
40820
40850
  }
40821
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
+
40822
40960
  // src/exulu/shared-artifact-create-route.ts
40823
40961
  init_cjs_shims();
40824
40962
  init_shared_artifacts();
@@ -43206,8 +43344,8 @@ var settleWithin = async (tasks, ms) => {
43206
43344
  try {
43207
43345
  return await Promise.race([
43208
43346
  Promise.allSettled(tasks),
43209
- new Promise((resolve10) => {
43210
- timer3 = setTimeout(() => resolve10(null), ms);
43347
+ new Promise((resolve11) => {
43348
+ timer3 = setTimeout(() => resolve11(null), ms);
43211
43349
  })
43212
43350
  ]);
43213
43351
  } finally {
@@ -43525,7 +43663,7 @@ init_flow();
43525
43663
 
43526
43664
  // src/exulu/recall/verify.ts
43527
43665
  init_cjs_shims();
43528
- var import_node_crypto23 = require("crypto");
43666
+ var import_node_crypto24 = require("crypto");
43529
43667
  var TOLERANCE_SECONDS = 5 * 60;
43530
43668
  var header = (headers, ...names) => {
43531
43669
  for (const name of names) {
@@ -43543,7 +43681,7 @@ var safeEqual = (a, b) => {
43543
43681
  const bufA = Buffer.from(a);
43544
43682
  const bufB = Buffer.from(b);
43545
43683
  if (bufA.length !== bufB.length) return false;
43546
- return (0, import_node_crypto23.timingSafeEqual)(bufA, bufB);
43684
+ return (0, import_node_crypto24.timingSafeEqual)(bufA, bufB);
43547
43685
  };
43548
43686
  var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
43549
43687
  if (!secret) {
@@ -43565,7 +43703,7 @@ var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()
43565
43703
  }
43566
43704
  const body = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
43567
43705
  const signedContent = `${id}.${timestamp}.${body}`;
43568
- 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");
43569
43707
  const passed = signatureHeader.split(" ").some((entry) => {
43570
43708
  const [, sig] = entry.split(",");
43571
43709
  return !!sig && safeEqual(sig, expected);
@@ -44091,7 +44229,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
44091
44229
  inputs: payload
44092
44230
  };
44093
44231
  await queue.queue.add("email-intake", jobData, {
44094
- jobId: (0, import_node_crypto24.randomUUID)(),
44232
+ jobId: (0, import_node_crypto25.randomUUID)(),
44095
44233
  attempts: 3,
44096
44234
  removeOnComplete: 5e3,
44097
44235
  removeOnFail: 1e4,
@@ -44499,7 +44637,7 @@ ${customInstructions}` : agent.instructions,
44499
44637
  contextId: agent.memory,
44500
44638
  agentId: agent.id,
44501
44639
  session: headers.session ?? null,
44502
- 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)(),
44503
44641
  userId: user?.id ?? null
44504
44642
  });
44505
44643
  }
@@ -45192,7 +45330,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
45192
45330
  const keys = [];
45193
45331
  const revisedPrompts = [];
45194
45332
  for (const img of images) {
45195
- const filename = `${(0, import_node_crypto24.randomUUID)()}.${img.extension}`;
45333
+ const filename = `${(0, import_node_crypto25.randomUUID)()}.${img.extension}`;
45196
45334
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
45197
45335
  const fullKey = await uploadFile(
45198
45336
  img.buffer,
@@ -45480,7 +45618,7 @@ ${style.markdown}` : params.prompt;
45480
45618
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
45481
45619
  );
45482
45620
  const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
45483
- const messageId = (0, import_node_crypto24.randomUUID)();
45621
+ const messageId = (0, import_node_crypto25.randomUUID)();
45484
45622
  const uiMessage = {
45485
45623
  id: messageId,
45486
45624
  role: "system",
@@ -46577,7 +46715,7 @@ ${style.markdown}` : params.prompt;
46577
46715
  return;
46578
46716
  }
46579
46717
  const meta = await parseSkillFrontmatter(bytes);
46580
- const skillId = (0, import_node_crypto24.randomUUID)();
46718
+ const skillId = (0, import_node_crypto25.randomUUID)();
46581
46719
  try {
46582
46720
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
46583
46721
  } catch (err4) {
@@ -46700,7 +46838,7 @@ ${style.markdown}` : params.prompt;
46700
46838
  return;
46701
46839
  }
46702
46840
  if (!await ensureSkillWrite(db2, skill, authResult.user, res)) return;
46703
- 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}`;
46704
46842
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
46705
46843
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
46706
46844
  res.json({ uploadUrl, stagingKey });
@@ -47794,6 +47932,39 @@ ${style.markdown}` : params.prompt;
47794
47932
  RBACResolver,
47795
47933
  checkRecordAccess
47796
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
+ });
47797
47968
  registerClaimCheckRoutes(app, {
47798
47969
  authenticate: (req) => requestValidators.authenticate(req),
47799
47970
  checkApiKeyScope,
@@ -48097,7 +48268,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
48097
48268
  // src/mcp/index.ts
48098
48269
  init_cjs_shims();
48099
48270
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
48100
- var import_node_crypto25 = require("crypto");
48271
+ var import_node_crypto26 = require("crypto");
48101
48272
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
48102
48273
  var import_types14 = require("@modelcontextprotocol/sdk/types.js");
48103
48274
  init_sanitize_tool_name();
@@ -48198,7 +48369,7 @@ var ExuluMCP = class {
48198
48369
  throw new Error("Tool not found in converted tools array.");
48199
48370
  }
48200
48371
  const iterator = await convertedTool.execute(inputs, {
48201
- toolCallId: tool5.id + "_" + (0, import_node_crypto25.randomUUID)(),
48372
+ toolCallId: tool5.id + "_" + (0, import_node_crypto26.randomUUID)(),
48202
48373
  messages: []
48203
48374
  });
48204
48375
  let result;
@@ -48388,7 +48559,7 @@ var ExuluMCP = class {
48388
48559
  transport = this.transports[sessionId];
48389
48560
  } else if (!sessionId && (0, import_types14.isInitializeRequest)(req.body)) {
48390
48561
  transport = new import_streamableHttp.StreamableHTTPServerTransport({
48391
- sessionIdGenerator: () => (0, import_node_crypto25.randomUUID)(),
48562
+ sessionIdGenerator: () => (0, import_node_crypto26.randomUUID)(),
48392
48563
  onsessioninitialized: (sessionId2) => {
48393
48564
  this.transports[sessionId2] = transport;
48394
48565
  }
@@ -48994,7 +49165,7 @@ var import_zod39 = __toESM(require("zod"), 1);
48994
49165
  init_tool2();
48995
49166
  init_check_record_access();
48996
49167
  init_client();
48997
- var import_node_crypto26 = require("crypto");
49168
+ var import_node_crypto27 = require("crypto");
48998
49169
  var AnswerOptionSchema = import_zod39.default.object({
48999
49170
  id: import_zod39.default.string().describe("Unique identifier for the answer option"),
49000
49171
  text: import_zod39.default.string().describe("The text of the answer option")
@@ -49048,15 +49219,15 @@ var QuestionAskTool = new ExuluTool({
49048
49219
  throw new Error("You don't have access to this session " + session.id + ".");
49049
49220
  }
49050
49221
  const answerOptionsWithIds = answerOptions.map((text) => ({
49051
- id: (0, import_node_crypto26.randomUUID)(),
49222
+ id: (0, import_node_crypto27.randomUUID)(),
49052
49223
  text
49053
49224
  }));
49054
49225
  answerOptionsWithIds.push({
49055
- id: (0, import_node_crypto26.randomUUID)(),
49226
+ id: (0, import_node_crypto27.randomUUID)(),
49056
49227
  text: "None of the above..."
49057
49228
  });
49058
49229
  const newQuestion = {
49059
- id: (0, import_node_crypto26.randomUUID)(),
49230
+ id: (0, import_node_crypto27.randomUUID)(),
49060
49231
  question,
49061
49232
  answerOptions: answerOptionsWithIds,
49062
49233
  status: "pending"
@@ -51438,8 +51609,8 @@ init_cjs_shims();
51438
51609
 
51439
51610
  // src/exulu/litellm/db-init.ts
51440
51611
  init_cjs_shims();
51441
- var import_node_fs12 = require("fs");
51442
- var import_node_path17 = require("path");
51612
+ var import_node_fs13 = require("fs");
51613
+ var import_node_path18 = require("path");
51443
51614
  var import_node_child_process8 = require("child_process");
51444
51615
  var import_pg3 = require("pg");
51445
51616
 
@@ -51497,6 +51668,68 @@ var checkLiteLLMDatabaseSafety = (configPath) => {
51497
51668
  return { ok: true, reason: "isolated", litellmTarget };
51498
51669
  };
51499
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
+
51500
51733
  // src/exulu/litellm/db-init.ts
51501
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";
51502
51735
  var warn3 = (lines) => {
@@ -51508,8 +51741,14 @@ ${WARNING_BANNER}`);
51508
51741
  `);
51509
51742
  };
51510
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
+ };
51511
51750
  var initLiteLLMDatabase = async (packageRoot) => {
51512
- 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");
51513
51752
  const safety = checkLiteLLMDatabaseSafety(configPath);
51514
51753
  if (safety.ok && safety.reason === "no-litellm-db-mode") return;
51515
51754
  if (!safety.ok && safety.reason === "unparseable-url") {
@@ -51647,10 +51886,10 @@ var initLiteLLMDatabase = async (packageRoot) => {
51647
51886
  ]);
51648
51887
  return;
51649
51888
  }
51650
- const venvBin = (0, import_node_path17.resolve)(packageRoot, "ee/python/.venv/bin");
51651
- const prismaCli = (0, import_node_path17.resolve)(venvBin, "prisma");
51652
- const venvLibDir = (0, import_node_path17.resolve)(packageRoot, "ee/python/.venv/lib");
51653
- 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;
51654
51893
  if (!pythonVersionDir) {
51655
51894
  warn3([
51656
51895
  `Could not find a python3.* directory under ${venvLibDir}.`,
@@ -51659,13 +51898,13 @@ var initLiteLLMDatabase = async (packageRoot) => {
51659
51898
  ]);
51660
51899
  return;
51661
51900
  }
51662
- const litellmProxyDir = (0, import_node_path17.resolve)(
51901
+ const litellmProxyDir = (0, import_node_path18.resolve)(
51663
51902
  venvLibDir,
51664
51903
  pythonVersionDir,
51665
51904
  "site-packages/litellm/proxy"
51666
51905
  );
51667
- const schemaPath = (0, import_node_path17.resolve)(litellmProxyDir, "schema.prisma");
51668
- 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)) {
51669
51908
  warn3([
51670
51909
  `Prisma CLI not found at ${prismaCli}.`,
51671
51910
  `Run \`npm run python:setup\` to create the venv and install prisma.`,
@@ -51673,13 +51912,45 @@ var initLiteLLMDatabase = async (packageRoot) => {
51673
51912
  ]);
51674
51913
  return;
51675
51914
  }
51676
- if (!(0, import_node_fs12.existsSync)(schemaPath)) {
51915
+ if (!(0, import_node_fs13.existsSync)(schemaPath)) {
51677
51916
  warn3([
51678
51917
  `LiteLLM Prisma schema not found at ${schemaPath}.`,
51679
51918
  `Re-run \`npm run python:setup\`. Skipping LiteLLM database setup.`
51680
51919
  ]);
51681
51920
  return;
51682
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
+ }
51683
51954
  log6("Running `prisma db push` against LiteLLM's schema\u2026");
51684
51955
  const result = (0, import_node_child_process8.spawnSync)(prismaCli, ["db", "push", "--skip-generate"], {
51685
51956
  cwd: litellmProxyDir,
@@ -51696,9 +51967,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
51696
51967
  if (result.error) {
51697
51968
  warn3([
51698
51969
  `Failed to launch prisma: ${result.error.message}`,
51699
- `Skipping LiteLLM database setup.`
51970
+ `LiteLLM's database schema was NOT updated.`
51700
51971
  ]);
51701
- return;
51972
+ throw new LiteLLMSchemaPushError(
51973
+ `Could not launch prisma to update LiteLLM's database schema: ${result.error.message}`
51974
+ );
51702
51975
  }
51703
51976
  if (result.status !== 0) {
51704
51977
  warn3([
@@ -51706,9 +51979,16 @@ var initLiteLLMDatabase = async (packageRoot) => {
51706
51979
  `stdout:`,
51707
51980
  ...(result.stdout || "(empty)").split("\n").map((l) => ` ${l}`),
51708
51981
  `stderr:`,
51709
- ...(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.`
51710
51988
  ]);
51711
- 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
+ );
51712
51992
  }
51713
51993
  log6("\u2713 LiteLLM database ready.");
51714
51994
  };
@@ -51752,7 +52032,7 @@ var create = ({
51752
52032
  });
51753
52033
  const sdk = new import_sdk_node.NodeSDK({
51754
52034
  traceExporter,
51755
- logRecordProcessors: [new import_sdk_logs.BatchLogRecordProcessor(logExporter)],
52035
+ logRecordProcessors: [new import_sdk_logs.BatchLogRecordProcessor({ exporter: logExporter })],
51756
52036
  instrumentations: [(0, import_auto_instrumentations_node.getNodeAutoInstrumentations)()],
51757
52037
  resource: (0, import_resources.resourceFromAttributes)({
51758
52038
  [import_semantic_conventions.ATTR_SERVICE_NAME]: "Exulu"