@exulu/backend 5.18.0 → 5.20.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;
@@ -1950,9 +1951,9 @@ var init_tokenizer = __esm({
1950
1951
  throw new Error("Tokenizer not initialized");
1951
1952
  }
1952
1953
  const tokens = this.encoder.encode(text);
1953
- const count = tokens.length;
1954
- console.log("[EXULU] Token count.", count);
1955
- return count;
1954
+ const count2 = tokens.length;
1955
+ console.log("[EXULU] Token count.", count2);
1956
+ return count2;
1956
1957
  }
1957
1958
  async free() {
1958
1959
  console.log("[EXULU] Freeing tokenizer.");
@@ -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;
@@ -6113,6 +6114,13 @@ var init_core_schema = __esm({
6113
6114
  name: "reasoning_effort",
6114
6115
  type: "text"
6115
6116
  },
6117
+ {
6118
+ // Language the agent answers in. null/"off" = nothing is added to the
6119
+ // prompt; "auto" = the language of the user's message; a locale ("en")
6120
+ // = always that language. See response-language.ts. Auto-ALTERed on boot.
6121
+ name: "response_language",
6122
+ type: "text"
6123
+ },
6116
6124
  {
6117
6125
  name: "guest_access",
6118
6126
  type: "boolean",
@@ -8916,8 +8924,8 @@ var init_context = __esm({
8916
8924
  const { db: db2 } = await postgresClient();
8917
8925
  const tableName = getTableName(this.id);
8918
8926
  console.log("[EXULU] checking if table exists.", tableName);
8919
- const tableExists = await db2.schema.hasTable(tableName);
8920
- return tableExists;
8927
+ const tableExists2 = await db2.schema.hasTable(tableName);
8928
+ return tableExists2;
8921
8929
  };
8922
8930
  chunksTableExists = async () => {
8923
8931
  const { db: db2 } = await postgresClient();
@@ -15827,8 +15835,8 @@ async function setupPythonEnvironment(options = {}) {
15827
15835
  packageRoot = getPackageRoot(),
15828
15836
  force = false,
15829
15837
  verbose = false,
15830
- timeout = 6e5
15831
- // 10 minutes
15838
+ timeout = 18e5
15839
+ // 30 minutes
15832
15840
  } = options;
15833
15841
  const alreadyExisted = isPythonEnvironmentSetup(packageRoot);
15834
15842
  if (verbose) {
@@ -15994,18 +16002,18 @@ function probeSandboxSupport() {
15994
16002
  if (process.platform !== "linux") {
15995
16003
  return { canSandbox: false, reason: `Unsupported platform: ${process.platform}` };
15996
16004
  }
15997
- return await new Promise((resolve10) => {
16005
+ return await new Promise((resolve11) => {
15998
16006
  const child = (0, import_node_child_process5.spawn)("bwrap", ["--dev-bind", "/", "/", "--", "/bin/true"], { env: {} });
15999
16007
  let stderr = "";
16000
16008
  child.stderr.on("data", (chunk2) => {
16001
16009
  stderr += chunk2.toString();
16002
16010
  });
16003
16011
  child.on("error", (err4) => {
16004
- resolve10({ canSandbox: false, reason: `bwrap not executable: ${err4.message}` });
16012
+ resolve11({ canSandbox: false, reason: `bwrap not executable: ${err4.message}` });
16005
16013
  });
16006
16014
  child.on("exit", (code) => {
16007
- if (code === 0) resolve10({ canSandbox: true });
16008
- else resolve10({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
16015
+ if (code === 0) resolve11({ canSandbox: true });
16016
+ else resolve11({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
16009
16017
  });
16010
16018
  });
16011
16019
  })();
@@ -16973,6 +16981,63 @@ var init_routine_status_tool = __esm({
16973
16981
  }
16974
16982
  });
16975
16983
 
16984
+ // src/templates/tools/tool-upload.ts
16985
+ var import_client_s33, import_node_crypto9, generateS3Key, s3Client2, buildToolUpload;
16986
+ var init_tool_upload = __esm({
16987
+ "src/templates/tools/tool-upload.ts"() {
16988
+ "use strict";
16989
+ init_cjs_shims();
16990
+ import_client_s33 = require("@aws-sdk/client-s3");
16991
+ import_node_crypto9 = require("crypto");
16992
+ init_session_file_write();
16993
+ init_uppy();
16994
+ generateS3Key = (filename) => `${(0, import_node_crypto9.randomUUID)()}-${filename}`;
16995
+ buildToolUpload = (exuluConfig, user) => {
16996
+ const uploads = exuluConfig?.fileUploads;
16997
+ if (!uploads?.s3endpoint || !uploads?.s3key || !uploads?.s3secret || !uploads?.s3Bucket) {
16998
+ return void 0;
16999
+ }
17000
+ s3Client2 ??= new import_client_s33.S3Client({
17001
+ region: uploads.s3region,
17002
+ forcePathStyle: true,
17003
+ endpoint: uploads.s3endpoint,
17004
+ credentials: {
17005
+ accessKeyId: uploads.s3key ?? "",
17006
+ secretAccessKey: uploads.s3secret ?? ""
17007
+ }
17008
+ });
17009
+ const client2 = s3Client2;
17010
+ return async ({ name, data, type }) => {
17011
+ const mime = getMimeType(type);
17012
+ const prefix = uploads.s3prefix ? `${uploads.s3prefix.replace(/\/$/, "")}/` : "";
17013
+ const key = `${prefix}${user?.id}/${generateS3Key(name)}${type}`;
17014
+ const command = new import_client_s33.PutObjectCommand({
17015
+ Bucket: uploads.s3Bucket,
17016
+ Key: key,
17017
+ Body: data,
17018
+ ContentType: mime
17019
+ });
17020
+ try {
17021
+ await client2.send(command);
17022
+ const bucket = uploads.s3Bucket ?? "";
17023
+ const presignedUrl = await getPresignedUrl(bucket, key, exuluConfig);
17024
+ return { url: presignedUrl, key: `${bucket}/${key}` };
17025
+ } catch (caught) {
17026
+ if (caught instanceof import_client_s33.S3ServiceException && caught.name === "EntityTooLarge") {
17027
+ 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).`);
17028
+ } else if (caught instanceof import_client_s33.S3ServiceException) {
17029
+ throw new Error(
17030
+ `[EXULU] Error from S3 while uploading object to ${uploads.s3Bucket}. ${caught.name}: ${caught.message}`
17031
+ );
17032
+ } else {
17033
+ throw caught;
17034
+ }
17035
+ }
17036
+ };
17037
+ };
17038
+ }
17039
+ });
17040
+
16976
17041
  // src/utils/truncate-tool-output.ts
16977
17042
  var truncateToolOutput;
16978
17043
  var init_truncate_tool_output = __esm({
@@ -17108,19 +17173,19 @@ var init_context_budget = __esm({
17108
17173
  });
17109
17174
 
17110
17175
  // src/exulu/tool-output-offload.ts
17111
- var import_node_crypto9, PREVIEW_CHARS, storeAsSessionFile, buildNotice, guardToolOutput, guardExtractedFileText;
17176
+ var import_node_crypto10, PREVIEW_CHARS, storeAsSessionFile, buildNotice, guardToolOutput, guardExtractedFileText;
17112
17177
  var init_tool_output_offload = __esm({
17113
17178
  "src/exulu/tool-output-offload.ts"() {
17114
17179
  "use strict";
17115
17180
  init_cjs_shims();
17116
- import_node_crypto9 = require("crypto");
17181
+ import_node_crypto10 = require("crypto");
17117
17182
  init_uppy();
17118
17183
  init_context_budget();
17119
17184
  PREVIEW_CHARS = 4e3;
17120
17185
  storeAsSessionFile = async (serialized, ctx) => {
17121
17186
  if (!ctx.sessionID || !ctx.exuluConfig?.fileUploads) return void 0;
17122
17187
  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`;
17188
+ const name = `tool-output-${safeTool}-${(0, import_node_crypto10.randomUUID)().slice(0, 8)}.txt`;
17124
17189
  try {
17125
17190
  await uploadFile(
17126
17191
  Buffer.from(serialized, "utf-8"),
@@ -17319,6 +17384,24 @@ var init_session_file_read_tool = __esm({
17319
17384
  }
17320
17385
  });
17321
17386
 
17387
+ // src/utils/office-text.ts
17388
+ var import_officeparser, officeToText;
17389
+ var init_office_text = __esm({
17390
+ "src/utils/office-text.ts"() {
17391
+ "use strict";
17392
+ init_cjs_shims();
17393
+ import_officeparser = require("officeparser");
17394
+ officeToText = async (bytes) => {
17395
+ const ast = await (0, import_officeparser.parseOffice)(bytes, { newlineDelimiter: "\n" });
17396
+ const { value } = await ast.to("text", {
17397
+ includeImages: false,
17398
+ textConfig: { preserveLayout: false }
17399
+ });
17400
+ return String(value);
17401
+ };
17402
+ }
17403
+ });
17404
+
17322
17405
  // src/templates/tools/document-render-helpers.ts
17323
17406
  function isLegacyOfficeFormat(ext) {
17324
17407
  return ext in LEGACY_OFFICE_CONVERSION_TARGETS;
@@ -17463,7 +17546,7 @@ async function withRetry(generateFn, maxRetries = 3, opts = {}) {
17463
17546
  if (attempt === maxRetries || shouldRetry && !shouldRetry(error)) {
17464
17547
  throw error;
17465
17548
  }
17466
- await new Promise((resolve10) => setTimeout(resolve10, Math.pow(2, attempt) * baseDelayMs));
17549
+ await new Promise((resolve11) => setTimeout(resolve11, Math.pow(2, attempt) * baseDelayMs));
17467
17550
  }
17468
17551
  }
17469
17552
  throw lastError;
@@ -17565,25 +17648,25 @@ async function executePythonScript(config) {
17565
17648
  const stdout = error.stdout?.toString() ?? "";
17566
17649
  const stderr = error.stderr?.toString() ?? "";
17567
17650
  const exitCode = error.code ?? 1;
17568
- let errorMessage = `Python script execution failed: ${error.message}`;
17651
+ let errorMessage2 = `Python script execution failed: ${error.message}`;
17569
17652
  if (stderr) {
17570
- errorMessage += `
17653
+ errorMessage2 += `
17571
17654
 
17572
17655
  Stderr:
17573
17656
  ${stderr}`;
17574
17657
  }
17575
17658
  if (stdout) {
17576
- errorMessage += `
17659
+ errorMessage2 += `
17577
17660
 
17578
17661
  Stdout:
17579
17662
  ${stdout}`;
17580
17663
  }
17581
- errorMessage += `
17664
+ errorMessage2 += `
17582
17665
 
17583
17666
  Command executed:
17584
17667
  ${command}`;
17585
17668
  throw new PythonExecutionError(
17586
- errorMessage,
17669
+ errorMessage2,
17587
17670
  stdout,
17588
17671
  stderr,
17589
17672
  exitCode
@@ -18055,7 +18138,7 @@ async function validateWithVLM(document2, model, verbose = false, concurrency =
18055
18138
  let correctedCount = 0;
18056
18139
  const validationTasks = document2.map(
18057
18140
  (page) => limit(async () => {
18058
- await new Promise((resolve10) => setImmediate(resolve10));
18141
+ await new Promise((resolve11) => setImmediate(resolve11));
18059
18142
  const imagePath = page.image;
18060
18143
  if (!imagePath) {
18061
18144
  console.warn(`[EXULU] Page ${page.page}: No image found, skipping validation`);
@@ -18186,14 +18269,21 @@ async function processDocument(filePath, fileType, buffer, tempDir, config, verb
18186
18269
  }
18187
18270
  };
18188
18271
  }
18272
+ async function saveScreenshots(screenshots, dir) {
18273
+ await fs2.promises.mkdir(dir, { recursive: true });
18274
+ const saved = /* @__PURE__ */ new Map();
18275
+ for (const screenshot of screenshots) {
18276
+ const file = path3.join(dir, `${screenshot.pageNum}.png`);
18277
+ await fs2.promises.writeFile(file, screenshot.imageBuffer);
18278
+ saved.set(screenshot.pageNum, file);
18279
+ }
18280
+ return saved;
18281
+ }
18189
18282
  async function processPdf(buffer, paths, config, verbose = false, tolerateVisionFailures = false, onProgress, limiters) {
18190
18283
  try {
18191
18284
  let json = [];
18192
18285
  if (config?.processor.name === "officeparser") {
18193
- const text = await (0, import_officeparser.parseOfficeAsync)(buffer, {
18194
- outputErrorToConsole: false,
18195
- newlineDelimiter: "\n"
18196
- });
18286
+ const text = await officeToText(buffer);
18197
18287
  json = [{
18198
18288
  page: 1,
18199
18289
  content: text,
@@ -18230,8 +18320,8 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
18230
18320
  const chunkResults = await Promise.all(
18231
18321
  pdfChunks.map(
18232
18322
  (chunk2, i) => chunkLimit(async () => {
18233
- await new Promise((resolve10) => setImmediate(resolve10));
18234
- await new Promise((resolve10) => setTimeout(resolve10, Math.floor(Math.random() * 1e3) + 200));
18323
+ await new Promise((resolve11) => setImmediate(resolve11));
18324
+ await new Promise((resolve11) => setTimeout(resolve11, Math.floor(Math.random() * 1e3) + 200));
18235
18325
  console.log(`[EXULU] OCR chunk ${i + 1}/${pdfChunks.length}: pages ${chunk2.start_page}\u2013${chunk2.end_page - 1}`);
18236
18326
  const chunkBuffer = await fs2.promises.readFile(chunk2.path);
18237
18327
  const chunkBase64 = chunkBuffer.toString("base64");
@@ -18251,40 +18341,25 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
18251
18341
  const mergedPages = chunkResults.sort((a, b) => a.offset - b.offset).flatMap(
18252
18342
  ({ pages, offset }) => pages.map((p) => ({ ...p, index: p.index + offset }))
18253
18343
  );
18254
- const parser = new import_liteparse.LiteParse();
18344
+ const parser = new import_liteparse.LiteParse({ quiet: true });
18255
18345
  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
- }
18346
+ const imagePaths = await saveScreenshots(screenshots, paths.images);
18267
18347
  json = mergedPages.map((page) => ({
18268
18348
  page: page.index + 1,
18269
18349
  content: page.markdown,
18270
- image: screenshots.find((s) => s.pageNum === page.index + 1)?.imagePath,
18350
+ image: imagePaths.get(page.index + 1),
18271
18351
  headings: []
18272
18352
  }));
18273
18353
  fs2.writeFileSync(paths.json, JSON.stringify(json, null, 2));
18274
18354
  } else if (config?.processor.name === "liteparse") {
18275
- const parser = new import_liteparse.LiteParse();
18355
+ const parser = new import_liteparse.LiteParse({ quiet: true });
18276
18356
  const result = await parser.parse(paths.source);
18277
18357
  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
- }
18358
+ const imagePaths = await saveScreenshots(screenshots, paths.images);
18284
18359
  json = result.pages.map((page) => ({
18285
18360
  page: page.pageNum,
18286
18361
  content: page.text,
18287
- image: screenshots.find((s) => s.pageNum === page.pageNum)?.imagePath
18362
+ image: imagePaths.get(page.pageNum)
18288
18363
  }));
18289
18364
  fs2.writeFileSync(paths.json, JSON.stringify(json, null, 2));
18290
18365
  } else {
@@ -18339,8 +18414,8 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
18339
18414
  markdownStream.write("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
18340
18415
  }
18341
18416
  }
18342
- await new Promise((resolve10, reject) => {
18343
- markdownStream.end(() => resolve10());
18417
+ await new Promise((resolve11, reject) => {
18418
+ markdownStream.end(() => resolve11());
18344
18419
  markdownStream.on("error", reject);
18345
18420
  });
18346
18421
  console.log(`[EXULU] Validated output saved to: ${paths.json}`);
@@ -18436,7 +18511,7 @@ async function documentProcessor({
18436
18511
  }
18437
18512
  }
18438
18513
  }
18439
- var fs2, path3, import_ai3, import_zod16, import_p_limit2, import_crypto4, mammoth, import_turndown, import_word_extractor, import_officeparser, import_liteparse, loadFile;
18514
+ var fs2, path3, import_ai3, import_zod16, import_p_limit2, import_crypto4, mammoth, import_turndown, import_word_extractor, import_liteparse, loadFile;
18440
18515
  var init_doc_processor = __esm({
18441
18516
  "ee/python/documents/processing/doc_processor.ts"() {
18442
18517
  "use strict";
@@ -18451,7 +18526,7 @@ var init_doc_processor = __esm({
18451
18526
  mammoth = __toESM(require("mammoth"), 1);
18452
18527
  import_turndown = __toESM(require("turndown"), 1);
18453
18528
  import_word_extractor = __toESM(require("word-extractor"), 1);
18454
- import_officeparser = require("officeparser");
18529
+ init_office_text();
18455
18530
  init_entitlements();
18456
18531
  init_python_executor();
18457
18532
  import_liteparse = require("@llamaindex/liteparse");
@@ -18615,12 +18690,12 @@ function validateAttachmentsConfig(config, license) {
18615
18690
  }
18616
18691
  return problems;
18617
18692
  }
18618
- var import_officeparser2, DEFAULT_ATTACHMENT_MAX_PAGES, loadDocumentProcessor, defaultOfficeParse, PROCESSOR_NAMES;
18693
+ var DEFAULT_ATTACHMENT_MAX_PAGES, loadDocumentProcessor, defaultOfficeParse, PROCESSOR_NAMES;
18619
18694
  var init_attachment_text = __esm({
18620
18695
  "src/exulu/attachment-text.ts"() {
18621
18696
  "use strict";
18622
18697
  init_cjs_shims();
18623
- import_officeparser2 = require("officeparser");
18698
+ init_office_text();
18624
18699
  init_document_render_helpers();
18625
18700
  init_limits();
18626
18701
  DEFAULT_ATTACHMENT_MAX_PAGES = 50;
@@ -18628,7 +18703,7 @@ var init_attachment_text = __esm({
18628
18703
  const mod = await Promise.resolve().then(() => (init_doc_processor(), doc_processor_exports));
18629
18704
  return mod.documentProcessor;
18630
18705
  };
18631
- defaultOfficeParse = async (bytes) => String(await (0, import_officeparser2.parseOfficeAsync)(bytes, { outputErrorToConsole: false, newlineDelimiter: "\n" }));
18706
+ defaultOfficeParse = (bytes) => officeToText(bytes);
18632
18707
  PROCESSOR_NAMES = /* @__PURE__ */ new Set(["liteparse", "mistral", "officeparser"]);
18633
18708
  }
18634
18709
  });
@@ -18658,8 +18733,8 @@ var init_progress = __esm({
18658
18733
 
18659
18734
  // src/exulu/document-cache/store.ts
18660
18735
  function countPageMarkers(text) {
18661
- const count = (text.match(/^--- page \d+ ---$/gm) ?? []).length;
18662
- return count > 0 ? count : void 0;
18736
+ const count2 = (text.match(/^--- page \d+ ---$/gm) ?? []).length;
18737
+ return count2 > 0 ? count2 : void 0;
18663
18738
  }
18664
18739
  async function readThroughDocument(args) {
18665
18740
  const { io, bucket, sourceKey, s3prefix, fingerprint, cacheDays, extract, onProgress } = args;
@@ -18673,7 +18748,7 @@ async function readThroughDocument(args) {
18673
18748
  const totalPages = Number.isInteger(pages) && pages > 0 ? pages : countPageMarkers(stored.text);
18674
18749
  return { text: stored.text, totalPages, fromStore: true };
18675
18750
  };
18676
- const readText = async (key) => {
18751
+ const readText2 = async (key) => {
18677
18752
  try {
18678
18753
  return await io.getText(key);
18679
18754
  } catch (err4) {
@@ -18689,7 +18764,7 @@ async function readThroughDocument(args) {
18689
18764
  warn2(`could not head ${sourceKey}`, err4);
18690
18765
  }
18691
18766
  if (head && head.etag && head.lastModified && head.size !== null) {
18692
- const pointerRaw = await readText(pointerAt);
18767
+ const pointerRaw = await readText2(pointerAt);
18693
18768
  let pointer = null;
18694
18769
  try {
18695
18770
  pointer = pointerRaw ? JSON.parse(pointerRaw.text) : null;
@@ -18697,7 +18772,7 @@ async function readThroughDocument(args) {
18697
18772
  pointer = null;
18698
18773
  }
18699
18774
  if (pointer && pointer.etag === head.etag && pointer.lastModified === head.lastModified.toISOString() && pointer.size === head.size && typeof pointer.sha256 === "string") {
18700
- const hit = fromStoredText(await readText(contentKey(pointer.sha256, fingerprint.id, s3prefix)));
18775
+ const hit = fromStoredText(await readText2(contentKey(pointer.sha256, fingerprint.id, s3prefix)));
18701
18776
  if (hit) return hit;
18702
18777
  }
18703
18778
  }
@@ -18715,7 +18790,7 @@ async function readThroughDocument(args) {
18715
18790
  );
18716
18791
  };
18717
18792
  if (useStore) {
18718
- const hit = fromStoredText(await readText(textKey));
18793
+ const hit = fromStoredText(await readText2(textKey));
18719
18794
  if (hit) {
18720
18795
  try {
18721
18796
  await writePointer();
@@ -18863,7 +18938,7 @@ function binaryDocumentBashHint(command, stdout, stderr) {
18863
18938
  const [, file] = match;
18864
18939
  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
18940
  }
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;
18941
+ 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
18942
  var init_parse_document_tool = __esm({
18868
18943
  "src/templates/tools/parse-document-tool.ts"() {
18869
18944
  "use strict";
@@ -18871,7 +18946,7 @@ var init_parse_document_tool = __esm({
18871
18946
  init_turn_project();
18872
18947
  import_zod17 = require("zod");
18873
18948
  import_node_path12 = require("path");
18874
- import_officeparser3 = require("officeparser");
18949
+ init_office_text();
18875
18950
  init_tool2();
18876
18951
  init_uppy();
18877
18952
  init_document_render_helpers();
@@ -19003,11 +19078,8 @@ ${text.trim()}`).join("\n")
19003
19078
  };
19004
19079
  }
19005
19080
  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 };
19081
+ const parsed = await officeToText(officeBytes);
19082
+ return { text: parsed, storable: !processorFellBack };
19011
19083
  };
19012
19084
  const stored = await readThroughDocument({
19013
19085
  io,
@@ -19080,8 +19152,8 @@ ${text.trim()}`).join("\n")
19080
19152
  while (true) {
19081
19153
  while (queue.length > 0) yield queue.shift();
19082
19154
  if (finished) break;
19083
- await new Promise((resolve10) => {
19084
- wake = resolve10;
19155
+ await new Promise((resolve11) => {
19156
+ wake = resolve11;
19085
19157
  });
19086
19158
  wake = void 0;
19087
19159
  }
@@ -19579,12 +19651,11 @@ __export(convert_exulu_tools_to_ai_sdk_tools_exports, {
19579
19651
  convertExuluToolsToAiSdkTools: () => convertExuluToolsToAiSdkTools,
19580
19652
  hydrateVariables: () => hydrateVariables
19581
19653
  });
19582
- var import_client_s33, import_crypto_js4, import_node_crypto10, isReadingProgress, OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS, generateS3Key, s3Client2, hydrateVariables, convertExuluToolsToAiSdkTools;
19654
+ var import_crypto_js4, isReadingProgress, OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS, hydrateVariables, convertExuluToolsToAiSdkTools;
19583
19655
  var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19584
19656
  "src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts"() {
19585
19657
  "use strict";
19586
19658
  init_cjs_shims();
19587
- import_client_s33 = require("@aws-sdk/client-s3");
19588
19659
  init_tool2();
19589
19660
  init_statistics2();
19590
19661
  init_client();
@@ -19594,7 +19665,6 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19594
19665
  init_pipeline();
19595
19666
  init_project_scope();
19596
19667
  init_sanitize_tool_name();
19597
- import_node_crypto10 = require("crypto");
19598
19668
  init_statistics();
19599
19669
  init_tools();
19600
19670
  init_memory_base();
@@ -19611,7 +19681,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19611
19681
  init_resolve_session_project();
19612
19682
  init_session_file_write();
19613
19683
  init_routine_status_tool();
19614
- init_uppy();
19684
+ init_tool_upload();
19615
19685
  init_truncate_tool_output();
19616
19686
  init_tool_output_offload();
19617
19687
  init_auth_tool_model_output();
@@ -19629,7 +19699,6 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
19629
19699
  return typeof v.filename === "string" && typeof v.pagesDone === "number" && typeof v.pagesTotal === "number";
19630
19700
  };
19631
19701
  OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
19632
- generateS3Key = (filename) => `${(0, import_node_crypto10.randomUUID)()}-${filename}`;
19633
19702
  hydrateVariables = async (tool5) => {
19634
19703
  const { db: db2 } = await postgresClient();
19635
19704
  const promises2 = tool5.config.map(async (toolConfig) => {
@@ -20030,54 +20099,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
20030
20099
  if (toolVariableConfig) {
20031
20100
  toolVariableConfig = await hydrateVariables(toolVariableConfig || []);
20032
20101
  }
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
- }
20102
+ const upload = buildToolUpload(exuluConfig, user);
20081
20103
  const contextsMap = contexts?.reduce((acc, curr) => {
20082
20104
  acc[curr.id] = curr;
20083
20105
  return acc;
@@ -20244,6 +20266,8 @@ var init_tool2 = __esm({
20244
20266
  */
20245
20267
  alwaysAskWhen;
20246
20268
  authentication;
20269
+ /** Always set; `{ enabled: false }` unless the tool opted in. See ExuluToolApiConfig. */
20270
+ api;
20247
20271
  config;
20248
20272
  constructor({
20249
20273
  id,
@@ -20257,7 +20281,8 @@ var init_tool2 = __esm({
20257
20281
  needsApproval,
20258
20282
  needsApprovalFn,
20259
20283
  alwaysAskWhen,
20260
- authentication: authentication2
20284
+ authentication: authentication2,
20285
+ api
20261
20286
  }) {
20262
20287
  if (!PUBLIC_TOOL_TYPES.includes(type)) {
20263
20288
  throw new Error(
@@ -20270,6 +20295,17 @@ var init_tool2 = __esm({
20270
20295
  validateAuthConfig(id, authentication2);
20271
20296
  authRegistry.register(id, authentication2);
20272
20297
  }
20298
+ this.api = { enabled: api?.enabled === true };
20299
+ if (this.api.enabled) {
20300
+ const variables = config.filter((c) => c.type === "variable").map((c) => c.name);
20301
+ if (variables.length > 0) {
20302
+ throw new Error(
20303
+ `ExuluTool "${id}": api.enabled is not possible with "variable" config params (${variables.join(
20304
+ ", "
20305
+ )}). Their values come from an agent's tool configuration, and a call to /tools/${id} has no agent.`
20306
+ );
20307
+ }
20308
+ }
20273
20309
  this.authentication = authentication2;
20274
20310
  this.id = id;
20275
20311
  this.config = config;
@@ -23284,13 +23320,13 @@ var describeError = (e) => {
23284
23320
  return head ?? String(e);
23285
23321
  };
23286
23322
  function logRedisErrors(source, label) {
23287
- let count = 0;
23323
+ let count2 = 0;
23288
23324
  let lastLoggedAt = 0;
23289
23325
  source.on("error", (err4) => {
23290
- count += 1;
23326
+ count2 += 1;
23291
23327
  const now = Date.now();
23292
- if (count === 1 || now - lastLoggedAt >= ERROR_LOG_THROTTLE_MS) {
23293
- errorLog(`${label} connection error (${redisAddress()}): ${describeError(err4)}${count > 1 ? ` (x${count})` : ""}`);
23328
+ if (count2 === 1 || now - lastLoggedAt >= ERROR_LOG_THROTTLE_MS) {
23329
+ errorLog(`${label} connection error (${redisAddress()}): ${describeError(err4)}${count2 > 1 ? ` (x${count2})` : ""}`);
23294
23330
  lastLoggedAt = now;
23295
23331
  }
23296
23332
  });
@@ -24268,7 +24304,8 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
24268
24304
  name: hydrated?.name || "",
24269
24305
  description: hydrated?.description || "",
24270
24306
  category: tool5?.category || "default",
24271
- needsApproval: true
24307
+ needsApproval: true,
24308
+ api: hydrated?.api ?? { enabled: false }
24272
24309
  };
24273
24310
  console.log("[EXULU] hydratedTool", hydratedTool);
24274
24311
  return hydratedTool;
@@ -24693,19 +24730,19 @@ function createQueries(table, tools, contexts) {
24693
24730
  } else {
24694
24731
  if (tableNamePlural === "tracking") {
24695
24732
  query = query.sum("total as count");
24696
- const [{ count }] = await query.sum("total as count");
24733
+ const [{ count: count2 }] = await query.sum("total as count");
24697
24734
  return [
24698
24735
  {
24699
24736
  group: "total",
24700
- count: count ? Number(count) : 0
24737
+ count: count2 ? Number(count2) : 0
24701
24738
  }
24702
24739
  ];
24703
24740
  } else {
24704
- const [{ count }] = await query.count("* as count");
24741
+ const [{ count: count2 }] = await query.count("* as count");
24705
24742
  return [
24706
24743
  {
24707
24744
  group: "total",
24708
- count: count ? Number(count) : 0
24745
+ count: count2 ? Number(count2) : 0
24709
24746
  }
24710
24747
  ];
24711
24748
  }
@@ -26766,16 +26803,16 @@ var shouldGenerateEmbeddings = ({
26766
26803
  // src/exulu/embedder-change.ts
26767
26804
  init_cjs_shims();
26768
26805
  var MAX_INLINE_REGENERATION_ITEMS = 2e3;
26769
- var decideRebuildCase = (existing, next, tableExists) => {
26770
- if (!tableExists) return "create";
26806
+ var decideRebuildCase = (existing, next, tableExists2) => {
26807
+ if (!tableExists2) return "create";
26771
26808
  if (existing === null) return "recreate";
26772
26809
  return existing === next ? "truncate" : "recreate";
26773
26810
  };
26774
26811
  var changeContextEmbedder = async (context, model, queue, deps) => {
26775
- const tableExists = await deps.chunksTableExists(context);
26812
+ const tableExists2 = await deps.chunksTableExists(context);
26776
26813
  const target = model ?? deps.codeModel(context);
26777
26814
  if (!target) {
26778
- if (tableExists) await deps.dropChunksTable(context);
26815
+ if (tableExists2) await deps.dropChunksTable(context);
26779
26816
  await deps.persist(context.id, null, null);
26780
26817
  await deps.hydrate([context]);
26781
26818
  return { case: "cleared", items: 0, jobs: [] };
@@ -26790,7 +26827,7 @@ var changeContextEmbedder = async (context, model, queue, deps) => {
26790
26827
  }
26791
26828
  }
26792
26829
  const existing = await deps.currentDimensionality(context.id);
26793
- const rebuild = decideRebuildCase(existing, dimensionality, tableExists);
26830
+ const rebuild = decideRebuildCase(existing, dimensionality, tableExists2);
26794
26831
  if (rebuild === "recreate") {
26795
26832
  await deps.dropChunksTable(context);
26796
26833
  await deps.createChunksTable(context);
@@ -28116,17 +28153,17 @@ function createMutations(table, contexts, tools, config) {
28116
28153
  "You are not authorized to delete all chunks via API, user must be super admin."
28117
28154
  );
28118
28155
  }
28119
- let count = 0;
28156
+ let count2 = 0;
28120
28157
  if (!args.limit) {
28121
28158
  const result = await db2.from(getChunksTableName(id)).count();
28122
- count = parseInt(result[0].count);
28159
+ count2 = parseInt(result[0].count);
28123
28160
  await db2.from(getChunksTableName(id)).truncate();
28124
28161
  } else {
28125
- count = await db2.from(getChunksTableName(id)).limit(args.limit).delete();
28162
+ count2 = await db2.from(getChunksTableName(id)).limit(args.limit).delete();
28126
28163
  }
28127
28164
  return {
28128
28165
  message: "Chunks deleted successfully.",
28129
- items: count,
28166
+ items: count2,
28130
28167
  jobs: []
28131
28168
  };
28132
28169
  }
@@ -28950,6 +28987,231 @@ async function recallMemories({ agent, contexts, query, user, db: db2, previousU
28950
28987
 
28951
28988
  // src/exulu/generate-stream.ts
28952
28989
  init_public_surface();
28990
+
28991
+ // src/exulu/response-language.ts
28992
+ init_cjs_shims();
28993
+
28994
+ // src/exulu/message-language.ts
28995
+ init_cjs_shims();
28996
+ var import_franc2 = require("franc");
28997
+ var FUNCTION_WORDS = {
28998
+ en: `the and is are were be been am do does did have has had will would can could should may might must
28999
+ what which who whom whose when where why how many much this that these those there here it its you your yours
29000
+ we our they their them he she his her me my of to in on at for from with without about into by as if or but not
29001
+ no yes any some all please thanks thank hello hi an than then so because while also only very just mean means show shows tell`,
29002
+ de: `der die das den dem des ein eine einen einem einer eines und oder aber nicht kein keine ist sind war waren
29003
+ wird werden wurde wurden hat haben hatte hast kann k\xF6nnen konnte muss m\xFCssen soll sollen darf wie was wer wo
29004
+ wann warum wieso welche welcher welches viele viel ich du er sie es wir ihr mich mir dich dir uns euch mein
29005
+ meine dein deine sein seine von zu zum zur bei beim mit ohne f\xFCr auf aus nach \xFCber unter vor im am an in um
29006
+ durch wenn weil dass ob auch nur noch schon sehr bitte danke hallo ja nein man sich dieser diese dieses gibt
29007
+ als bis gegen zwischen damit dann bedeutet bedeuten hei\xDFt zeigt zeige kennst welche gibt wieviel kannst k\xF6nnt k\xF6nnte k\xF6nnten habt`,
29008
+ nl: `de het een en of maar niet geen is zijn was waren wordt worden werd heeft hebben had kan kunnen moet moeten
29009
+ zal zullen wat wie waar wanneer waarom hoe welke veel ik jij je hij zij ze wij we jullie mij me mijn jouw uw
29010
+ van naar bij met zonder voor op uit over onder in om door als omdat dat die deze dit ook nog al zeer erg
29011
+ alstublieft bedankt hoi ja nee er aan te betekent heet toont`,
29012
+ fr: `le la les un une des du de et ou mais ne pas non oui est sont \xE9tait \xEAtre a ont avait avoir peut peuvent
29013
+ doit doivent que qui quoi quel quelle quels quelles o\xF9 quand pourquoi comment combien je tu il elle nous vous
29014
+ ils elles me te se mon ma mes ton ta tes son sa ses notre votre leur \xE0 au aux avec sans pour sur dans par en
29015
+ si parce ce cette ces aussi tr\xE8s bonjour merci plus`,
29016
+ es: `el la los las un una unos unas y o pero no s\xED es son era ser est\xE1 est\xE1n estar ha han hab\xEDa haber puede
29017
+ pueden debe deben que qui\xE9n qu\xE9 cu\xE1l cu\xE1les d\xF3nde cu\xE1ndo c\xF3mo cu\xE1nto cu\xE1ntos yo t\xFA \xE9l ella nosotros ustedes
29018
+ ellos ellas me te se mi mis tu tus su sus nuestro de del al a con sin para por en sobre si porque este esta
29019
+ estos estas tambi\xE9n muy hola gracias m\xE1s`,
29020
+ it: `il lo la i gli le un uno una e o ma non no s\xEC \xE8 sono era essere ha hanno aveva avere pu\xF2 possono deve
29021
+ devono che chi cosa quale quali dove quando perch\xE9 come quanto quanti io tu lui lei noi voi loro mi ti si
29022
+ mio mia tuo tua suo sua nostro di del della dei delle a al alla da dal dalla con senza per su in tra fra se
29023
+ questo questa questi queste anche molto ciao grazie pi\xF9`,
29024
+ pt: `o a os as um uma uns umas e ou mas n\xE3o sim \xE9 s\xE3o era ser est\xE1 est\xE3o estar tem t\xEAm tinha ter pode podem
29025
+ deve devem que quem qual quais onde quando porque como quanto quantos eu tu ele ela n\xF3s voc\xEAs eles elas me
29026
+ te se meu minha teu tua seu sua nosso de do da dos das ao \xE0 com sem para por em no na nos nas sobre este
29027
+ esta estes estas tamb\xE9m muito ol\xE1 obrigado obrigada mais`,
29028
+ sv: `och att det \xE4r ett som p\xE5 av f\xF6r med till har inte om jag du han hon vi ni kan ska skulle vad hur n\xE4r varf\xF6r vilken vilka eller men fr\xE5n efter utan \xF6ver under ocks\xE5 mycket h\xE4r d\xE4r mig dig sig min din
29029
+ tack hej ja nej finns blir vara detta dessa`,
29030
+ da: `og det et som p\xE5 af med til har ikke om jeg du han hun vi kan skal skulle hvad
29031
+ hvordan hvorn\xE5r hvorfor hvilken hvilke eller men fra efter uden over under ogs\xE5 meget her mig dig sig
29032
+ min din tak hej ja nej findes bliver v\xE6re dette disse`,
29033
+ nb: `og det et som p\xE5 av med til har ikke om jeg du han hun vi dere kan skal skulle hva hvordan n\xE5r hvorfor hvilken hvilke eller men fra etter uten over under ogs\xE5 mye her meg deg seg min
29034
+ din takk hei ja nei finnes blir v\xE6re dette disse`,
29035
+ pl: `i w na z do si\u0119 nie to jest \u017Ce jak co czy ale lub oraz dla od po przez przy za o s\u0105 by\u0142 by\u0142a by\u0142o by\u0107 ma
29036
+ maj\u0105 mo\u017Ce mog\u0119 mo\u017Cna ten ta te tego tej tym kt\xF3ry kt\xF3ra kt\xF3re gdzie kiedy dlaczego ile ja ty on ona my wy
29037
+ oni mi mnie ci go jej ich tak te\u017C ju\u017C tylko bardzo prosz\u0119 dzi\u0119kuj\u0119 cze\u015B\u0107 jaki jaka jakie`,
29038
+ cs: `a v na s z do se ne to je \u017Ee jak co ale nebo pro od po p\u0159i za o jsou byl byla bylo b\xFDt m\xE1 maj\xED m\u016F\u017Ee mohu
29039
+ lze ten ta to tento tato kter\xFD kter\xE1 kter\xE9 kde kdy pro\u010D kolik j\xE1 ty on ona my vy oni mi m\u011B ti ho j\xED jich
29040
+ ano tak\xE9 u\u017E jen velmi pros\xEDm d\u011Bkuji ahoj jak\xFD jak\xE1 jak\xE9`,
29041
+ tr: `ve bir bu \u015Fu i\xE7in ile mi m\u0131 mu m\xFC ne nas\u0131l neden nerede hangi ka\xE7 de\u011Fil var yok ben sen biz siz
29042
+ onlar bana sana ona bize size gibi kadar ama veya \xE7ok daha evet hay\u0131r l\xFCtfen te\u015Fekk\xFCrler merhaba olarak
29043
+ olan ise ki her \u015Fey`,
29044
+ fi: `ja on ei ett\xE4 se t\xE4m\xE4 tuo mik\xE4 mit\xE4 miten miksi miss\xE4 milloin kuka tai mutta jos kun niin my\xF6s vain hyvin
29045
+ min\xE4 sin\xE4 h\xE4n me te he minun sinun ovat oli olla voi voiko pit\xE4\xE4 kanssa ilman kyll\xE4 kiitos hei ole`,
29046
+ ro: `\u0219i \xEEn la de cu pe din pentru nu este sunt era fi are au poate pot trebuie ce cum c\xE2nd unde care c\xE2t eu tu
29047
+ el ea noi voi ei ele m\u0103 te se meu mea sau dar dac\u0103 acest aceast\u0103 aceste foarte mai da mul\u021Bumesc bun\u0103 un o
29048
+ al ale lui`,
29049
+ hu: `\xE9s a az egy nem van volt lesz hogy mi mit mi\xE9rt hol mikor hogyan melyik ki \xE9n te \u0151 mi ti \u0151k vagy de ha is
29050
+ csak nagyon igen k\xF6sz\xF6n\xF6m szia kell lehet tud meg el be ki fel le ez ezt azt ezek`
29051
+ };
29052
+ var LISTS = Object.entries(FUNCTION_WORDS).map(([language, list]) => [
29053
+ language,
29054
+ new Set(list.split(/\s+/).filter((word) => word.length > 1))
29055
+ ]);
29056
+ var FAMILY = { sv: "nordic", da: "nordic", nb: "nordic", cs: "west-slavic", pl: "west-slavic" };
29057
+ var family = (language) => FAMILY[language] ?? language;
29058
+ var MARGIN = 2;
29059
+ var MIN_SHARE = 0.2;
29060
+ var FRANC_MIN_LETTERS = 60;
29061
+ var FRANC_MIN_LEAD = 0.1;
29062
+ var FRANC_LATIN = {
29063
+ eng: "en",
29064
+ deu: "de",
29065
+ nld: "nl",
29066
+ fra: "fr",
29067
+ spa: "es",
29068
+ ita: "it",
29069
+ por: "pt",
29070
+ swe: "sv",
29071
+ dan: "da",
29072
+ nob: "nb",
29073
+ fin: "fi",
29074
+ pol: "pl",
29075
+ ces: "cs",
29076
+ slk: "sk",
29077
+ hun: "hu",
29078
+ ron: "ro",
29079
+ tur: "tr",
29080
+ hrv: "hr",
29081
+ slv: "sl",
29082
+ lit: "lt",
29083
+ lav: "lv",
29084
+ est: "et",
29085
+ ind: "id",
29086
+ vie: "vi",
29087
+ cat: "ca"
29088
+ };
29089
+ var FRANC_CYRILLIC = { rus: "ru", ukr: "uk", bul: "bg", srp: "sr", bel: "be", mkd: "mk" };
29090
+ var FRANC_ARABIC = { arb: "ar", pes: "fa", urd: "ur" };
29091
+ var SCRIPT_LANGUAGE = [
29092
+ [/[\p{Script=Hiragana}\p{Script=Katakana}]/gu, "ja"],
29093
+ [/\p{Script=Hangul}/gu, "ko"],
29094
+ [/\p{Script=Han}/gu, "zh"],
29095
+ [/\p{Script=Thai}/gu, "th"],
29096
+ [/\p{Script=Hebrew}/gu, "he"],
29097
+ [/\p{Script=Greek}/gu, "el"],
29098
+ [/\p{Script=Devanagari}/gu, "hi"]
29099
+ ];
29100
+ var NONE = { language: null, mixed: false };
29101
+ var MIXED = { language: null, mixed: true };
29102
+ var count = (text, pattern) => (text.match(pattern) ?? []).length;
29103
+ function franc2(prose, only, minLetters) {
29104
+ if (count(prose, /\p{L}/gu) < minLetters) return null;
29105
+ const guesses = (0, import_franc2.francAll)(prose, { only: Object.keys(only), minLength: 3 });
29106
+ const best = guesses[0];
29107
+ if (!best || best[0] === "und") return null;
29108
+ if (best[1] - (guesses[1]?.[1] ?? 0) < FRANC_MIN_LEAD) return null;
29109
+ return only[best[0]] ?? null;
29110
+ }
29111
+ function readText(text) {
29112
+ const prose = text.replace(/```[\s\S]*?(```|$)/g, " ").replace(/`[^`\n]*`/g, " ").replace(/\b(https?:\/\/|www\.)\S+/gi, " ").toLowerCase();
29113
+ const letters = count(prose, /\p{L}/gu);
29114
+ if (letters === 0) return NONE;
29115
+ const latin = count(prose, /\p{Script=Latin}/gu);
29116
+ if (latin < letters / 2) {
29117
+ for (const [pattern, language] of SCRIPT_LANGUAGE) {
29118
+ if (count(prose, pattern) >= (letters - latin) / 3 && count(prose, pattern) >= 2) return { language, mixed: false };
29119
+ }
29120
+ if (count(prose, /\p{Script=Cyrillic}/gu) > letters / 2) {
29121
+ return { language: franc2(prose, FRANC_CYRILLIC, 20), mixed: false };
29122
+ }
29123
+ if (count(prose, /\p{Script=Arabic}/gu) > letters / 2) {
29124
+ return { language: franc2(prose, FRANC_ARABIC, 20), mixed: false };
29125
+ }
29126
+ return NONE;
29127
+ }
29128
+ const words = (prose.match(/\p{L}+/gu) ?? []).filter((word) => word.length > 1);
29129
+ if (words.length === 0) return NONE;
29130
+ const found = LISTS.map(([language, set]) => ({ language, set, hits: words.filter((word) => set.has(word)) })).filter((entry) => entry.hits.length > 0).sort((a, b) => b.hits.length - a.hits.length);
29131
+ const guess = franc2(prose, FRANC_LATIN, FRANC_MIN_LETTERS);
29132
+ const top = found[0];
29133
+ if (!top) return { language: guess, mixed: false };
29134
+ const against = (other) => {
29135
+ const mine = top.hits.filter((word) => !other.set.has(word)).length;
29136
+ const theirs = other.hits.filter((word) => !top.set.has(word)).length;
29137
+ if (mine >= 1 && mine >= MARGIN * theirs) return "wins";
29138
+ return theirs === 0 ? "open" : "mixed";
29139
+ };
29140
+ const others = found.filter((entry) => entry !== top);
29141
+ const rivals = others.filter((entry) => family(entry.language) !== family(top.language)).map(against);
29142
+ if (rivals.includes("mixed")) return MIXED;
29143
+ if (rivals.includes("open")) return NONE;
29144
+ const siblings = others.filter((entry) => family(entry.language) === family(top.language)).map(against);
29145
+ const words_say = siblings.every((verdict) => verdict === "wins") ? top.language : null;
29146
+ if (guess) {
29147
+ if (words_say) return words_say === guess ? { language: guess, mixed: false } : NONE;
29148
+ return family(guess) === family(top.language) ? { language: guess, mixed: false } : NONE;
29149
+ }
29150
+ if (!words_say) return NONE;
29151
+ const enough = top.hits.length >= 2 ? top.hits.length / words.length >= MIN_SHARE : words.length <= 2;
29152
+ return enough ? { language: words_say, mixed: false } : NONE;
29153
+ }
29154
+ function readMessageLanguage(text) {
29155
+ if (typeof text !== "string") return NONE;
29156
+ const whole = readText(text);
29157
+ if (!whole.language) return whole;
29158
+ const opening = text.trim().match(/^[^?!.:\n]{1,300}[?!.:\n]/)?.[0];
29159
+ if (!opening || opening.length > text.trim().length * 0.8) return whole;
29160
+ const first = readText(opening).language;
29161
+ return first && first !== whole.language ? MIXED : whole;
29162
+ }
29163
+
29164
+ // src/exulu/response-language.ts
29165
+ var LOCALE = /^[a-z]{2,3}(-[a-z0-9]{2,8}){0,2}$/i;
29166
+ var languageName = (locale) => {
29167
+ try {
29168
+ const name = new Intl.DisplayNames(["en"], { type: "language" }).of(locale);
29169
+ return name && name.toLowerCase() !== locale.toLowerCase() ? name : void 0;
29170
+ } catch {
29171
+ return void 0;
29172
+ }
29173
+ };
29174
+ function resolveResponseLanguageMode(agent) {
29175
+ const raw = agent?.response_language;
29176
+ if (typeof raw !== "string") return { kind: "off" };
29177
+ const value = raw.trim();
29178
+ if (!value || value.toLowerCase() === "off") return { kind: "off" };
29179
+ if (value.toLowerCase() === "auto") return { kind: "auto" };
29180
+ if (!LOCALE.test(value)) return { kind: "off" };
29181
+ const language = languageName(value);
29182
+ return language ? { kind: "fixed", language } : { kind: "off" };
29183
+ }
29184
+ var LANGUAGE_NAME_OVERRIDES = { nb: "Norwegian", zh: "Chinese" };
29185
+ var nameOf = (locale) => LANGUAGE_NAME_OVERRIDES[locale] ?? languageName(locale) ?? locale;
29186
+ var EXCEPTION = "Only if the user explicitly asks for a different language or for a translation, in this message or in their stated preferences, follow that request instead.";
29187
+ var REPLY_IN = (language) => `Write your entire reply in ${language}, including headings, follow-up questions and refusals, even where your instructions and the knowledge sources are in another language.`;
29188
+ function responseLanguageInstruction({
29189
+ agent,
29190
+ current,
29191
+ previousUserTexts: previousUserTexts2
29192
+ }) {
29193
+ const mode = resolveResponseLanguageMode(agent);
29194
+ if (mode.kind === "off") return "";
29195
+ if (mode.kind === "fixed") {
29196
+ return `Response language: ${REPLY_IN(mode.language)} Only if the user explicitly asks for a translation into another language, follow that request instead.`;
29197
+ }
29198
+ const now = readMessageLanguage(current);
29199
+ if (now.language) {
29200
+ const language = nameOf(now.language);
29201
+ return `Response language: The user's latest message is written in ${language}. ${REPLY_IN(language)} ${EXCEPTION}`;
29202
+ }
29203
+ if (now.mixed) return "";
29204
+ for (let i = previousUserTexts2.length - 1; i >= 0; i--) {
29205
+ const earlier = readMessageLanguage(previousUserTexts2[i]).language;
29206
+ if (earlier) {
29207
+ const language = nameOf(earlier);
29208
+ return `Response language: The conversation so far has been in ${language}. ${REPLY_IN(language)} ${EXCEPTION}`;
29209
+ }
29210
+ }
29211
+ return "";
29212
+ }
29213
+
29214
+ // src/exulu/generate-stream.ts
28953
29215
  init_decisions();
28954
29216
 
28955
29217
  // src/exulu/skills/decisions.ts
@@ -29402,6 +29664,12 @@ When a tool execution is not approved by the user, do not retry it unless explic
29402
29664
  if (credentialGuardrail) {
29403
29665
  system += "\n\n" + credentialGuardrail;
29404
29666
  }
29667
+ const answerLanguage = responseLanguageInstruction({
29668
+ agent,
29669
+ current: query,
29670
+ previousUserTexts: previousUserTexts([...messages, currentAsUiMessage])
29671
+ });
29672
+ if (answerLanguage) system += "\n\n" + answerLanguage;
29405
29673
  if (prompt) {
29406
29674
  let result = { object: null, text: "" };
29407
29675
  let inputTokens = 0;
@@ -29831,6 +30099,12 @@ When a tool execution is not approved by the user, do not retry it unless explic
29831
30099
  Example: {url: https://www.google.com, title: Google, snippet: The result of the web search.}
29832
30100
  `;
29833
30101
  }
30102
+ const answerLanguage = responseLanguageInstruction({
30103
+ agent,
30104
+ current: query,
30105
+ previousUserTexts: previousUserTexts(messages)
30106
+ });
30107
+ if (answerLanguage) system += "\n\n" + answerLanguage;
29834
30108
  const agenticEntry = currentTools?.find((t) => t.id === "agentic_context_search");
29835
30109
  const agenticToolKey = agenticEntry ? sanitizeToolName(agenticEntry.name) : void 0;
29836
30110
  const retrievalGuard = retrievalBudgetGuard(
@@ -30222,7 +30496,7 @@ function detectPayloadFormat(contentType) {
30222
30496
  }
30223
30497
  var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
30224
30498
  function extractMultipartMimePart(rawBody, contentType) {
30225
- return new Promise((resolve10, reject) => {
30499
+ return new Promise((resolve11, reject) => {
30226
30500
  let found = null;
30227
30501
  const bb = (0, import_busboy.default)({ headers: { "content-type": contentType }, defCharset: "latin1" });
30228
30502
  bb.on("field", (name, value) => {
@@ -30231,7 +30505,7 @@ function extractMultipartMimePart(rawBody, contentType) {
30231
30505
  }
30232
30506
  });
30233
30507
  bb.on("close", () => {
30234
- if (found) resolve10(found);
30508
+ if (found) resolve11(found);
30235
30509
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
30236
30510
  });
30237
30511
  bb.on("error", (err4) => reject(err4 instanceof Error ? err4 : new Error(String(err4))));
@@ -30331,14 +30605,14 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
30331
30605
  const currentBucket = Math.floor(now / HOUR_MS);
30332
30606
  const currentKey = `${key}:${currentBucket}`;
30333
30607
  const previousKey = `${key}:${currentBucket - 1}`;
30334
- const count = await redis.incr(currentKey);
30335
- if (count === 1) {
30608
+ const count2 = await redis.incr(currentKey);
30609
+ if (count2 === 1) {
30336
30610
  await redis.expire(currentKey, 2 * 60 * 60);
30337
30611
  }
30338
30612
  const previousRaw = await redis.get(previousKey);
30339
30613
  const previous = previousRaw ? Number(previousRaw) : 0;
30340
30614
  const elapsedFraction = now % HOUR_MS / HOUR_MS;
30341
- const weighted = count + previous * (1 - elapsedFraction);
30615
+ const weighted = count2 + previous * (1 - elapsedFraction);
30342
30616
  return weighted <= limitPerHour;
30343
30617
  } catch (err4) {
30344
30618
  console.error(
@@ -31650,10 +31924,10 @@ function sniffDelimiter(headerLine) {
31650
31924
  let best = CANDIDATE_DELIMITERS[0];
31651
31925
  let bestCount = 0;
31652
31926
  for (const candidate of CANDIDATE_DELIMITERS) {
31653
- const count = counts.get(candidate) ?? 0;
31654
- if (count > bestCount) {
31927
+ const count2 = counts.get(candidate) ?? 0;
31928
+ if (count2 > bestCount) {
31655
31929
  best = candidate;
31656
- bestCount = count;
31930
+ bestCount = count2;
31657
31931
  }
31658
31932
  }
31659
31933
  return best;
@@ -31662,7 +31936,7 @@ function createSniffer(onFirstLine) {
31662
31936
  const head = [];
31663
31937
  let headBytes = 0;
31664
31938
  let resolved = false;
31665
- const resolve10 = (line) => {
31939
+ const resolve11 = (line) => {
31666
31940
  if (resolved) return;
31667
31941
  resolved = true;
31668
31942
  onFirstLine(line);
@@ -31677,15 +31951,15 @@ function createSniffer(onFirstLine) {
31677
31951
  const text = Buffer.concat(head).toString("utf-8");
31678
31952
  const eol = /\r|\n/.exec(text);
31679
31953
  if (eol) {
31680
- resolve10(text.slice(0, eol.index));
31954
+ resolve11(text.slice(0, eol.index));
31681
31955
  } else if (headBytes >= MAX_HEADER_BYTES) {
31682
- resolve10(text);
31956
+ resolve11(text);
31683
31957
  }
31684
31958
  }
31685
31959
  callback(null, chunk2);
31686
31960
  },
31687
31961
  flush(callback) {
31688
- resolve10(Buffer.concat(head).toString("utf-8"));
31962
+ resolve11(Buffer.concat(head).toString("utf-8"));
31689
31963
  callback();
31690
31964
  }
31691
31965
  });
@@ -31693,8 +31967,8 @@ function createSniffer(onFirstLine) {
31693
31967
  async function streamCsvRows(input, handlers, opts) {
31694
31968
  let resolveFirstLine = () => {
31695
31969
  };
31696
- const firstLine = new Promise((resolve10) => {
31697
- resolveFirstLine = resolve10;
31970
+ const firstLine = new Promise((resolve11) => {
31971
+ resolveFirstLine = resolve11;
31698
31972
  });
31699
31973
  const sniffer = createSniffer((line) => resolveFirstLine(line));
31700
31974
  let parser;
@@ -32190,7 +32464,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32190
32464
  );
32191
32465
  if (attempt < retries) {
32192
32466
  const backoffMs = 500 * Math.pow(2, attempt - 1);
32193
- await new Promise((resolve10) => setTimeout(resolve10, backoffMs));
32467
+ await new Promise((resolve11) => setTimeout(resolve11, backoffMs));
32194
32468
  }
32195
32469
  }
32196
32470
  }
@@ -32408,7 +32682,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32408
32682
  async (sessionId) => {
32409
32683
  const retries2 = 3;
32410
32684
  let attempts = 0;
32411
- const promise = new Promise(async (resolve10, reject) => {
32685
+ const promise = new Promise(async (resolve11, reject) => {
32412
32686
  while (attempts < retries2) {
32413
32687
  try {
32414
32688
  const messages2 = await processUiMessagesFlow({
@@ -32428,7 +32702,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32428
32702
  // back into blanket pre-approval (spec §5.2).
32429
32703
  respectToolApprovals: workflow.auto_approve_tools !== true
32430
32704
  });
32431
- resolve10(messages2);
32705
+ resolve11(messages2);
32432
32706
  break;
32433
32707
  } catch (error) {
32434
32708
  console.error(
@@ -32455,7 +32729,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32455
32729
  }
32456
32730
  reject(new Error(error instanceof Error ? error.message : String(error)));
32457
32731
  }
32458
- await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
32732
+ await new Promise((resolve12) => setTimeout(() => resolve12(true), 2e3));
32459
32733
  }
32460
32734
  }
32461
32735
  });
@@ -32555,7 +32829,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32555
32829
  } = await validateEvalPayload(data);
32556
32830
  const retries2 = 3;
32557
32831
  let attempts = 0;
32558
- const promise = new Promise(async (resolve10, reject) => {
32832
+ const promise = new Promise(async (resolve11, reject) => {
32559
32833
  while (attempts < retries2) {
32560
32834
  try {
32561
32835
  const messages2 = await processUiMessagesFlow({
@@ -32566,7 +32840,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32566
32840
  tools,
32567
32841
  config
32568
32842
  });
32569
- resolve10(messages2);
32843
+ resolve11(messages2);
32570
32844
  break;
32571
32845
  } catch (error) {
32572
32846
  console.error(
@@ -32577,7 +32851,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
32577
32851
  if (attempts >= retries2) {
32578
32852
  reject(new Error(error instanceof Error ? error.message : String(error)));
32579
32853
  }
32580
- await new Promise((resolve11) => setTimeout((resolve12) => resolve12(true), 2e3));
32854
+ await new Promise((resolve12) => setTimeout((resolve13) => resolve13(true), 2e3));
32581
32855
  }
32582
32856
  }
32583
32857
  });
@@ -33160,7 +33434,7 @@ var pollJobResult = async ({
33160
33434
  attempts++;
33161
33435
  const job = await import_bullmq3.Job.fromId(queue.queue, jobId);
33162
33436
  if (!job) {
33163
- await new Promise((resolve10) => setTimeout((resolve11) => resolve11(true), 2e3));
33437
+ await new Promise((resolve11) => setTimeout((resolve12) => resolve12(true), 2e3));
33164
33438
  continue;
33165
33439
  }
33166
33440
  const elapsedTime = Date.now() - startTime;
@@ -33190,7 +33464,7 @@ var pollJobResult = async ({
33190
33464
  console.log(`[EXULU] eval function ${job.id} result: ${result}`);
33191
33465
  break;
33192
33466
  }
33193
- await new Promise((resolve10) => setTimeout(() => resolve10(true), 2e3));
33467
+ await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
33194
33468
  }
33195
33469
  return result;
33196
33470
  };
@@ -33294,7 +33568,7 @@ var processUiMessagesFlow = async ({
33294
33568
  trigger: "agent"
33295
33569
  };
33296
33570
  try {
33297
- messageHistory = await new Promise(async (resolve10, reject) => {
33571
+ messageHistory = await new Promise(async (resolve11, reject) => {
33298
33572
  const startTime = Date.now();
33299
33573
  try {
33300
33574
  const result = await generateStream({
@@ -33385,7 +33659,7 @@ var processUiMessagesFlow = async ({
33385
33659
  })
33386
33660
  ] : []
33387
33661
  ]);
33388
- resolve10({
33662
+ resolve11({
33389
33663
  messages,
33390
33664
  metadata: {
33391
33665
  tokens: {
@@ -33654,7 +33928,7 @@ async function fetch_with_retry(args) {
33654
33928
  console.log(
33655
33929
  `[EXULU-RECALL] fetch error from ${url} (${err4.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
33656
33930
  );
33657
- await new Promise((resolve10) => setTimeout(resolve10, 5e3 + jitterMs()));
33931
+ await new Promise((resolve11) => setTimeout(resolve11, 5e3 + jitterMs()));
33658
33932
  continue;
33659
33933
  }
33660
33934
  let wait_for = null;
@@ -33674,7 +33948,7 @@ async function fetch_with_retry(args) {
33674
33948
  `[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
33675
33949
  );
33676
33950
  await new Promise(
33677
- (resolve10) => setTimeout(resolve10, 1e3 * wait_for + jitterMs())
33951
+ (resolve11) => setTimeout(resolve11, 1e3 * wait_for + jitterMs())
33678
33952
  );
33679
33953
  continue;
33680
33954
  }
@@ -38074,7 +38348,7 @@ type EmbeddingModelOption {
38074
38348
  await db2.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
38075
38349
  const retries = 3;
38076
38350
  let attempts = 0;
38077
- const promise = new Promise(async (resolve10, reject) => {
38351
+ const promise = new Promise(async (resolve11, reject) => {
38078
38352
  while (attempts < retries) {
38079
38353
  try {
38080
38354
  const messages2 = await processUiMessagesFlow({
@@ -38092,7 +38366,7 @@ type EmbeddingModelOption {
38092
38366
  // (never overriding a person), not as a chat continuation.
38093
38367
  jobResultId
38094
38368
  });
38095
- resolve10(messages2);
38369
+ resolve11(messages2);
38096
38370
  break;
38097
38371
  } catch (error) {
38098
38372
  console.error(
@@ -38106,7 +38380,7 @@ type EmbeddingModelOption {
38106
38380
  if (attempts >= retries) {
38107
38381
  reject(error instanceof Error ? error : new Error(String(error)));
38108
38382
  }
38109
- await new Promise((resolve11) => setTimeout(() => resolve11(true), 2e3));
38383
+ await new Promise((resolve12) => setTimeout(() => resolve12(true), 2e3));
38110
38384
  }
38111
38385
  }
38112
38386
  });
@@ -38534,7 +38808,7 @@ type EmbeddingModelOption {
38534
38808
  if (!client2) {
38535
38809
  throw new Error("Redis client not created properly");
38536
38810
  }
38537
- const { jobs, count } = await getJobsByQueueName(
38811
+ const { jobs, count: count2 } = await getJobsByQueueName(
38538
38812
  args.queue,
38539
38813
  args.statusses,
38540
38814
  args.page || 1,
@@ -38560,11 +38834,11 @@ type EmbeddingModelOption {
38560
38834
  })
38561
38835
  ),
38562
38836
  pageInfo: {
38563
- pageCount: Math.ceil(count / (args.limit || 100)),
38564
- itemCount: count,
38837
+ pageCount: Math.ceil(count2 / (args.limit || 100)),
38838
+ itemCount: count2,
38565
38839
  currentPage: args.page || 1,
38566
38840
  hasPreviousPage: args.page && args.page > 1 ? true : false,
38567
- hasNextPage: args.page && args.page < Math.ceil(count / (args.limit || 100)) ? true : false
38841
+ hasNextPage: args.page && args.page < Math.ceil(count2 / (args.limit || 100)) ? true : false
38568
38842
  }
38569
38843
  };
38570
38844
  };
@@ -38621,10 +38895,10 @@ type EmbeddingModelOption {
38621
38895
  contexts.map(async (context2) => {
38622
38896
  let processor = null;
38623
38897
  if (context2.processor) {
38624
- processor = await new Promise(async (resolve10, reject) => {
38898
+ processor = await new Promise(async (resolve11, reject) => {
38625
38899
  const config2 = context2.processor?.config;
38626
38900
  const queue = await config2?.queue;
38627
- resolve10({
38901
+ resolve11({
38628
38902
  name: context2.processor.name,
38629
38903
  description: context2.processor.description,
38630
38904
  queue: queue?.queue?.name || void 0,
@@ -38706,10 +38980,10 @@ type EmbeddingModelOption {
38706
38980
  }
38707
38981
  let processor = null;
38708
38982
  if (data.processor) {
38709
- processor = await new Promise(async (resolve10, reject) => {
38983
+ processor = await new Promise(async (resolve11, reject) => {
38710
38984
  const config2 = data.processor?.config;
38711
38985
  const queue = await config2?.queue;
38712
- resolve10({
38986
+ resolve11({
38713
38987
  name: data.processor.name,
38714
38988
  description: data.processor.description,
38715
38989
  queue: queue?.queue?.name || void 0,
@@ -39263,7 +39537,7 @@ var import_body_parser = __toESM(require("body-parser"), 1);
39263
39537
  var import_crypto_js7 = require("crypto-js");
39264
39538
  var import_openai = require("openai");
39265
39539
  var import_fs5 = __toESM(require("fs"), 1);
39266
- var import_node_crypto24 = require("crypto");
39540
+ var import_node_crypto25 = require("crypto");
39267
39541
  var import_api3 = require("@opentelemetry/api");
39268
39542
  init_check_record_access();
39269
39543
  var import_jszip4 = __toESM(require("jszip"), 1);
@@ -39881,7 +40155,7 @@ var internetSearchTool = new ExuluTool({
39881
40155
  } catch (error) {
39882
40156
  if (error instanceof import_perplexity_ai.default.RateLimitError && attempt < maxRetries - 1) {
39883
40157
  const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
39884
- await new Promise((resolve10) => setTimeout(resolve10, delay));
40158
+ await new Promise((resolve11) => setTimeout(resolve11, delay));
39885
40159
  continue;
39886
40160
  }
39887
40161
  throw error;
@@ -40819,6 +41093,114 @@ function registerViewerIdentityRoutes(app, deps) {
40819
41093
  });
40820
41094
  }
40821
41095
 
41096
+ // src/exulu/tool-api-route.ts
41097
+ init_cjs_shims();
41098
+ var import_node_crypto23 = require("crypto");
41099
+ init_progress();
41100
+ var TOOL_API_ROUTE_PATH = "/tools/:id";
41101
+ var toolConfigDefaults = (tool5) => Object.fromEntries(
41102
+ (tool5.config ?? []).filter((c) => c.default !== void 0).map((c) => [c.name, c.default])
41103
+ );
41104
+ var isAsyncIterable = (value) => !!value && typeof value === "object" && Symbol.asyncIterator in value;
41105
+ function registerToolApiRoutes(app, deps) {
41106
+ app.post(TOOL_API_ROUTE_PATH, async (req, res) => {
41107
+ const tool5 = deps.tools.find((t) => t.id === req.params.id);
41108
+ if (!tool5 || tool5.api?.enabled !== true) {
41109
+ res.status(404).json({ detail: "Tool not found." });
41110
+ return;
41111
+ }
41112
+ const auth = await deps.authenticate(req);
41113
+ const user = auth.user;
41114
+ if (!user?.id) {
41115
+ res.status(auth.code ?? 401).json({ detail: auth.message ?? "Authentication required." });
41116
+ return;
41117
+ }
41118
+ if (user.type === "api" && user.scope_mode && user.scope_mode !== "admin") {
41119
+ res.status(403).json({ detail: "This API key is scoped to agents and cannot call tools directly." });
41120
+ return;
41121
+ }
41122
+ let input = {};
41123
+ if (tool5.inputSchema) {
41124
+ const parsed = await tool5.inputSchema.safeParseAsync(req.body ?? {});
41125
+ if (!parsed.success) {
41126
+ res.status(400).json({
41127
+ detail: "The request body does not match the tool's input schema.",
41128
+ issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message }))
41129
+ });
41130
+ return;
41131
+ }
41132
+ input = parsed.data ?? {};
41133
+ }
41134
+ const execute2 = tool5.tool?.execute;
41135
+ if (!execute2) {
41136
+ res.status(500).json({ detail: "Tool has no execute function." });
41137
+ return;
41138
+ }
41139
+ const toolCallId = `${tool5.id}_${(0, import_node_crypto23.randomUUID)()}`;
41140
+ const started = Date.now();
41141
+ let output;
41142
+ let status = "ok";
41143
+ let failure;
41144
+ try {
41145
+ const response = await execute2(
41146
+ {
41147
+ ...input,
41148
+ user,
41149
+ req,
41150
+ contexts: Object.fromEntries((deps.contexts ?? []).map((c) => [c.id, c])),
41151
+ exuluConfig: deps.config,
41152
+ upload: deps.buildUpload?.(deps.config, user),
41153
+ toolVariablesConfig: toolConfigDefaults(tool5),
41154
+ allExuluTools: deps.tools,
41155
+ currentTools: [tool5]
41156
+ },
41157
+ { toolCallId, messages: [] }
41158
+ );
41159
+ if (isAsyncIterable(response)) {
41160
+ for await (const value of response) {
41161
+ if (!isInterimToolStatus(value)) output = value;
41162
+ }
41163
+ } else {
41164
+ output = response;
41165
+ }
41166
+ } catch (error) {
41167
+ status = "error";
41168
+ failure = error;
41169
+ }
41170
+ try {
41171
+ await deps.onCall?.({
41172
+ tool: tool5,
41173
+ user,
41174
+ req,
41175
+ toolCallId,
41176
+ input,
41177
+ output,
41178
+ status,
41179
+ error: failure,
41180
+ durationMs: Date.now() - started
41181
+ });
41182
+ } catch (error) {
41183
+ console.error(`[EXULU] tool api: recording the call to "${tool5.id}" failed:`, error);
41184
+ res.status(500).json({ detail: "The tool call could not be recorded." });
41185
+ return;
41186
+ }
41187
+ if (status === "error") {
41188
+ console.error(`[EXULU] tool api: "${tool5.id}" threw:`, failure);
41189
+ res.status(500).json({
41190
+ detail: failure instanceof Error ? failure.message : "The tool failed."
41191
+ });
41192
+ return;
41193
+ }
41194
+ res.status(200).json(output ?? {});
41195
+ });
41196
+ }
41197
+
41198
+ // src/exulu/routes.ts
41199
+ init_logger();
41200
+ init_emit_tool_call();
41201
+ init_client_info();
41202
+ init_tool_upload();
41203
+
40822
41204
  // src/exulu/shared-artifact-create-route.ts
40823
41205
  init_cjs_shims();
40824
41206
  init_shared_artifacts();
@@ -43206,8 +43588,8 @@ var settleWithin = async (tasks, ms) => {
43206
43588
  try {
43207
43589
  return await Promise.race([
43208
43590
  Promise.allSettled(tasks),
43209
- new Promise((resolve10) => {
43210
- timer3 = setTimeout(() => resolve10(null), ms);
43591
+ new Promise((resolve11) => {
43592
+ timer3 = setTimeout(() => resolve11(null), ms);
43211
43593
  })
43212
43594
  ]);
43213
43595
  } finally {
@@ -43525,7 +43907,7 @@ init_flow();
43525
43907
 
43526
43908
  // src/exulu/recall/verify.ts
43527
43909
  init_cjs_shims();
43528
- var import_node_crypto23 = require("crypto");
43910
+ var import_node_crypto24 = require("crypto");
43529
43911
  var TOLERANCE_SECONDS = 5 * 60;
43530
43912
  var header = (headers, ...names) => {
43531
43913
  for (const name of names) {
@@ -43543,7 +43925,7 @@ var safeEqual = (a, b) => {
43543
43925
  const bufA = Buffer.from(a);
43544
43926
  const bufB = Buffer.from(b);
43545
43927
  if (bufA.length !== bufB.length) return false;
43546
- return (0, import_node_crypto23.timingSafeEqual)(bufA, bufB);
43928
+ return (0, import_node_crypto24.timingSafeEqual)(bufA, bufB);
43547
43929
  };
43548
43930
  var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
43549
43931
  if (!secret) {
@@ -43565,7 +43947,7 @@ var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()
43565
43947
  }
43566
43948
  const body = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
43567
43949
  const signedContent = `${id}.${timestamp}.${body}`;
43568
- const expected = (0, import_node_crypto23.createHmac)("sha256", secretKey(secret)).update(signedContent).digest("base64");
43950
+ const expected = (0, import_node_crypto24.createHmac)("sha256", secretKey(secret)).update(signedContent).digest("base64");
43569
43951
  const passed = signatureHeader.split(" ").some((entry) => {
43570
43952
  const [, sig] = entry.split(",");
43571
43953
  return !!sig && safeEqual(sig, expected);
@@ -44091,7 +44473,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
44091
44473
  inputs: payload
44092
44474
  };
44093
44475
  await queue.queue.add("email-intake", jobData, {
44094
- jobId: (0, import_node_crypto24.randomUUID)(),
44476
+ jobId: (0, import_node_crypto25.randomUUID)(),
44095
44477
  attempts: 3,
44096
44478
  removeOnComplete: 5e3,
44097
44479
  removeOnFail: 1e4,
@@ -44499,7 +44881,7 @@ ${customInstructions}` : agent.instructions,
44499
44881
  contextId: agent.memory,
44500
44882
  agentId: agent.id,
44501
44883
  session: headers.session ?? null,
44502
- messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0, import_node_crypto24.randomUUID)(),
44884
+ messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? (0, import_node_crypto25.randomUUID)(),
44503
44885
  userId: user?.id ?? null
44504
44886
  });
44505
44887
  }
@@ -44604,13 +44986,13 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
44604
44986
  [
44605
44987
  ["inputTokens", inputTokens],
44606
44988
  ["outputTokens", outputTokens]
44607
- ].filter(([, count]) => count > 0).map(
44608
- ([name, count]) => updateStatistic({
44989
+ ].filter(([, count2]) => count2 > 0).map(
44990
+ ([name, count2]) => updateStatistic({
44609
44991
  name,
44610
44992
  label: agent.name,
44611
44993
  type: STATISTICS_TYPE_ENUM.AGENT_RUN,
44612
44994
  trigger: "agent",
44613
- count,
44995
+ count: count2,
44614
44996
  user: user?.id,
44615
44997
  role: user?.role?.id
44616
44998
  })
@@ -45192,7 +45574,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
45192
45574
  const keys = [];
45193
45575
  const revisedPrompts = [];
45194
45576
  for (const img of images) {
45195
- const filename = `${(0, import_node_crypto24.randomUUID)()}.${img.extension}`;
45577
+ const filename = `${(0, import_node_crypto25.randomUUID)()}.${img.extension}`;
45196
45578
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
45197
45579
  const fullKey = await uploadFile(
45198
45580
  img.buffer,
@@ -45480,7 +45862,7 @@ ${style.markdown}` : params.prompt;
45480
45862
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
45481
45863
  );
45482
45864
  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)();
45865
+ const messageId = (0, import_node_crypto25.randomUUID)();
45484
45866
  const uiMessage = {
45485
45867
  id: messageId,
45486
45868
  role: "system",
@@ -46577,7 +46959,7 @@ ${style.markdown}` : params.prompt;
46577
46959
  return;
46578
46960
  }
46579
46961
  const meta = await parseSkillFrontmatter(bytes);
46580
- const skillId = (0, import_node_crypto24.randomUUID)();
46962
+ const skillId = (0, import_node_crypto25.randomUUID)();
46581
46963
  try {
46582
46964
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
46583
46965
  } catch (err4) {
@@ -46700,7 +47082,7 @@ ${style.markdown}` : params.prompt;
46700
47082
  return;
46701
47083
  }
46702
47084
  if (!await ensureSkillWrite(db2, skill, authResult.user, res)) return;
46703
- const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0, import_node_crypto24.randomUUID)()}${extension}`;
47085
+ const stagingKey = `user_${authResult.user.id}/skills/_staging/${(0, import_node_crypto25.randomUUID)()}${extension}`;
46704
47086
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
46705
47087
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
46706
47088
  res.json({ uploadUrl, stagingKey });
@@ -47794,6 +48176,39 @@ ${style.markdown}` : params.prompt;
47794
48176
  RBACResolver,
47795
48177
  checkRecordAccess
47796
48178
  });
48179
+ registerToolApiRoutes(app, {
48180
+ authenticate: (req) => requestValidators.authenticate(req),
48181
+ tools,
48182
+ contexts,
48183
+ config,
48184
+ buildUpload: (cfg, user) => buildToolUpload(cfg, user),
48185
+ onCall: async ({ tool: tool5, user, req, toolCallId, input, output, status, error, durationMs }) => {
48186
+ await updateStatistic({
48187
+ name: "count",
48188
+ label: tool5.name,
48189
+ type: STATISTICS_TYPE_ENUM.TOOL_CALL,
48190
+ trigger: "api",
48191
+ count: 1,
48192
+ user: user.id,
48193
+ role: user.role?.id
48194
+ });
48195
+ const auditLogger = getAuditLogger(config ?? {});
48196
+ await emitToolCallAudit(auditLogger, {
48197
+ durationMs,
48198
+ agent: void 0,
48199
+ tool: { id: tool5.id, name: tool5.name, category: tool5.category, authentication: tool5.authentication },
48200
+ user,
48201
+ projectId: void 0,
48202
+ sessionID: void 0,
48203
+ toolCallId,
48204
+ input,
48205
+ output,
48206
+ status,
48207
+ error,
48208
+ client: extractClientInfo(req)
48209
+ });
48210
+ }
48211
+ });
47797
48212
  registerClaimCheckRoutes(app, {
47798
48213
  authenticate: (req) => requestValidators.authenticate(req),
47799
48214
  checkApiKeyScope,
@@ -48097,7 +48512,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
48097
48512
  // src/mcp/index.ts
48098
48513
  init_cjs_shims();
48099
48514
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
48100
- var import_node_crypto25 = require("crypto");
48515
+ var import_node_crypto26 = require("crypto");
48101
48516
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
48102
48517
  var import_types14 = require("@modelcontextprotocol/sdk/types.js");
48103
48518
  init_sanitize_tool_name();
@@ -48198,7 +48613,7 @@ var ExuluMCP = class {
48198
48613
  throw new Error("Tool not found in converted tools array.");
48199
48614
  }
48200
48615
  const iterator = await convertedTool.execute(inputs, {
48201
- toolCallId: tool5.id + "_" + (0, import_node_crypto25.randomUUID)(),
48616
+ toolCallId: tool5.id + "_" + (0, import_node_crypto26.randomUUID)(),
48202
48617
  messages: []
48203
48618
  });
48204
48619
  let result;
@@ -48388,7 +48803,7 @@ var ExuluMCP = class {
48388
48803
  transport = this.transports[sessionId];
48389
48804
  } else if (!sessionId && (0, import_types14.isInitializeRequest)(req.body)) {
48390
48805
  transport = new import_streamableHttp.StreamableHTTPServerTransport({
48391
- sessionIdGenerator: () => (0, import_node_crypto25.randomUUID)(),
48806
+ sessionIdGenerator: () => (0, import_node_crypto26.randomUUID)(),
48392
48807
  onsessioninitialized: (sessionId2) => {
48393
48808
  this.transports[sessionId2] = transport;
48394
48809
  }
@@ -48994,7 +49409,7 @@ var import_zod39 = __toESM(require("zod"), 1);
48994
49409
  init_tool2();
48995
49410
  init_check_record_access();
48996
49411
  init_client();
48997
- var import_node_crypto26 = require("crypto");
49412
+ var import_node_crypto27 = require("crypto");
48998
49413
  var AnswerOptionSchema = import_zod39.default.object({
48999
49414
  id: import_zod39.default.string().describe("Unique identifier for the answer option"),
49000
49415
  text: import_zod39.default.string().describe("The text of the answer option")
@@ -49048,15 +49463,15 @@ var QuestionAskTool = new ExuluTool({
49048
49463
  throw new Error("You don't have access to this session " + session.id + ".");
49049
49464
  }
49050
49465
  const answerOptionsWithIds = answerOptions.map((text) => ({
49051
- id: (0, import_node_crypto26.randomUUID)(),
49466
+ id: (0, import_node_crypto27.randomUUID)(),
49052
49467
  text
49053
49468
  }));
49054
49469
  answerOptionsWithIds.push({
49055
- id: (0, import_node_crypto26.randomUUID)(),
49470
+ id: (0, import_node_crypto27.randomUUID)(),
49056
49471
  text: "None of the above..."
49057
49472
  });
49058
49473
  const newQuestion = {
49059
- id: (0, import_node_crypto26.randomUUID)(),
49474
+ id: (0, import_node_crypto27.randomUUID)(),
49060
49475
  question,
49061
49476
  answerOptions: answerOptionsWithIds,
49062
49477
  status: "pending"
@@ -50736,7 +51151,7 @@ var RecursiveChunker = class _RecursiveChunker extends BaseChunker {
50736
51151
  `Number of splits ${splits.length} does not match number of token counts ${tokenCounts.length}`
50737
51152
  );
50738
51153
  }
50739
- if (tokenCounts.every((count) => count > this.chunkSize)) {
51154
+ if (tokenCounts.every((count2) => count2 > this.chunkSize)) {
50740
51155
  return [splits, tokenCounts];
50741
51156
  }
50742
51157
  const merged = [];
@@ -50744,14 +51159,14 @@ var RecursiveChunker = class _RecursiveChunker extends BaseChunker {
50744
51159
  let sum = 0;
50745
51160
  if (combineWhitespace) {
50746
51161
  cumulativeTokenCounts.push(0);
50747
- for (const count of tokenCounts) {
50748
- sum += count + 1;
51162
+ for (const count2 of tokenCounts) {
51163
+ sum += count2 + 1;
50749
51164
  cumulativeTokenCounts.push(sum);
50750
51165
  }
50751
51166
  } else {
50752
51167
  cumulativeTokenCounts.push(0);
50753
- for (const count of tokenCounts) {
50754
- sum += count;
51168
+ for (const count2 of tokenCounts) {
51169
+ sum += count2;
50755
51170
  cumulativeTokenCounts.push(sum);
50756
51171
  }
50757
51172
  }
@@ -51438,8 +51853,8 @@ init_cjs_shims();
51438
51853
 
51439
51854
  // src/exulu/litellm/db-init.ts
51440
51855
  init_cjs_shims();
51441
- var import_node_fs12 = require("fs");
51442
- var import_node_path17 = require("path");
51856
+ var import_node_fs13 = require("fs");
51857
+ var import_node_path18 = require("path");
51443
51858
  var import_node_child_process8 = require("child_process");
51444
51859
  var import_pg3 = require("pg");
51445
51860
 
@@ -51497,6 +51912,68 @@ var checkLiteLLMDatabaseSafety = (configPath) => {
51497
51912
  return { ok: true, reason: "isolated", litellmTarget };
51498
51913
  };
51499
51914
 
51915
+ // src/exulu/litellm/pre-push-migrations.ts
51916
+ init_cjs_shims();
51917
+ var import_node_fs12 = require("fs");
51918
+ var import_node_path17 = require("path");
51919
+ var tableExists = async (client2, table) => {
51920
+ const res = await client2.query(
51921
+ `SELECT 1 AS exists FROM information_schema.tables
51922
+ WHERE table_schema = 'public' AND table_name = $1`,
51923
+ [table]
51924
+ );
51925
+ return res.rows.length > 0;
51926
+ };
51927
+ var columnExists = async (client2, table, column) => {
51928
+ const res = await client2.query(
51929
+ `SELECT 1 AS exists FROM information_schema.columns
51930
+ WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`,
51931
+ [table, column]
51932
+ );
51933
+ return res.rows.length > 0;
51934
+ };
51935
+ var JWT_KEY_MAPPING_ISSUER_MIGRATION = "20260915000000_scope_jwt_key_mapping_by_issuer";
51936
+ var MIGRATIONS = [
51937
+ {
51938
+ name: JWT_KEY_MAPPING_ISSUER_MIGRATION,
51939
+ isNeeded: async (client2) => (
51940
+ // A fresh database has no table yet; the push creates it in its final
51941
+ // shape, and the migration's ALTER TABLE would fail on a missing table.
51942
+ await tableExists(client2, "LiteLLM_JWTKeyMapping") && !await columnExists(client2, "LiteLLM_JWTKeyMapping", "jwt_issuer")
51943
+ )
51944
+ }
51945
+ ];
51946
+ var applyPrePushMigrations = async (args) => {
51947
+ const { client: client2, migrationsDir, log: log7 } = args;
51948
+ const result = { applied: [], failed: [] };
51949
+ for (const migration of MIGRATIONS) {
51950
+ const file = (0, import_node_path17.resolve)(migrationsDir, migration.name, "migration.sql");
51951
+ if (!(0, import_node_fs12.existsSync)(file)) continue;
51952
+ try {
51953
+ if (!await migration.isNeeded(client2)) continue;
51954
+ } catch (err4) {
51955
+ result.failed.push({ name: migration.name, error: errorMessage(err4) });
51956
+ continue;
51957
+ }
51958
+ const sql = (0, import_node_fs12.readFileSync)(file, "utf8");
51959
+ try {
51960
+ await client2.query("BEGIN");
51961
+ await client2.query(sql);
51962
+ await client2.query("COMMIT");
51963
+ result.applied.push(migration.name);
51964
+ log7(`Applied LiteLLM migration ${migration.name} ahead of the schema push.`);
51965
+ } catch (err4) {
51966
+ try {
51967
+ await client2.query("ROLLBACK");
51968
+ } catch {
51969
+ }
51970
+ result.failed.push({ name: migration.name, error: errorMessage(err4) });
51971
+ }
51972
+ }
51973
+ return result;
51974
+ };
51975
+ var errorMessage = (err4) => err4 instanceof Error ? err4.message : String(err4);
51976
+
51500
51977
  // src/exulu/litellm/db-init.ts
51501
51978
  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
51979
  var warn3 = (lines) => {
@@ -51508,8 +51985,14 @@ ${WARNING_BANNER}`);
51508
51985
  `);
51509
51986
  };
51510
51987
  var log6 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
51988
+ var LiteLLMSchemaPushError = class extends Error {
51989
+ constructor(message) {
51990
+ super(message);
51991
+ this.name = "LiteLLMSchemaPushError";
51992
+ }
51993
+ };
51511
51994
  var initLiteLLMDatabase = async (packageRoot) => {
51512
- const configPath = process.env.LITELLM_CONFIG_PATH ?? (0, import_node_path17.resolve)(process.cwd(), "./config.litellm.yaml");
51995
+ const configPath = process.env.LITELLM_CONFIG_PATH ?? (0, import_node_path18.resolve)(process.cwd(), "./config.litellm.yaml");
51513
51996
  const safety = checkLiteLLMDatabaseSafety(configPath);
51514
51997
  if (safety.ok && safety.reason === "no-litellm-db-mode") return;
51515
51998
  if (!safety.ok && safety.reason === "unparseable-url") {
@@ -51647,10 +52130,10 @@ var initLiteLLMDatabase = async (packageRoot) => {
51647
52130
  ]);
51648
52131
  return;
51649
52132
  }
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;
52133
+ const venvBin = (0, import_node_path18.resolve)(packageRoot, "ee/python/.venv/bin");
52134
+ const prismaCli = (0, import_node_path18.resolve)(venvBin, "prisma");
52135
+ const venvLibDir = (0, import_node_path18.resolve)(packageRoot, "ee/python/.venv/lib");
52136
+ const pythonVersionDir = (0, import_node_fs13.existsSync)(venvLibDir) ? (0, import_node_fs13.readdirSync)(venvLibDir).find((entry) => /^python3\.\d+$/.test(entry)) : void 0;
51654
52137
  if (!pythonVersionDir) {
51655
52138
  warn3([
51656
52139
  `Could not find a python3.* directory under ${venvLibDir}.`,
@@ -51659,13 +52142,13 @@ var initLiteLLMDatabase = async (packageRoot) => {
51659
52142
  ]);
51660
52143
  return;
51661
52144
  }
51662
- const litellmProxyDir = (0, import_node_path17.resolve)(
52145
+ const litellmProxyDir = (0, import_node_path18.resolve)(
51663
52146
  venvLibDir,
51664
52147
  pythonVersionDir,
51665
52148
  "site-packages/litellm/proxy"
51666
52149
  );
51667
- const schemaPath = (0, import_node_path17.resolve)(litellmProxyDir, "schema.prisma");
51668
- if (!(0, import_node_fs12.existsSync)(prismaCli)) {
52150
+ const schemaPath = (0, import_node_path18.resolve)(litellmProxyDir, "schema.prisma");
52151
+ if (!(0, import_node_fs13.existsSync)(prismaCli)) {
51669
52152
  warn3([
51670
52153
  `Prisma CLI not found at ${prismaCli}.`,
51671
52154
  `Run \`npm run python:setup\` to create the venv and install prisma.`,
@@ -51673,13 +52156,45 @@ var initLiteLLMDatabase = async (packageRoot) => {
51673
52156
  ]);
51674
52157
  return;
51675
52158
  }
51676
- if (!(0, import_node_fs12.existsSync)(schemaPath)) {
52159
+ if (!(0, import_node_fs13.existsSync)(schemaPath)) {
51677
52160
  warn3([
51678
52161
  `LiteLLM Prisma schema not found at ${schemaPath}.`,
51679
52162
  `Re-run \`npm run python:setup\`. Skipping LiteLLM database setup.`
51680
52163
  ]);
51681
52164
  return;
51682
52165
  }
52166
+ const prePushClient = new import_pg3.Client({ connectionString: litellmUrl });
52167
+ try {
52168
+ await prePushClient.connect();
52169
+ const prePush = await applyPrePushMigrations({
52170
+ client: prePushClient,
52171
+ migrationsDir: (0, import_node_path18.resolve)(
52172
+ venvLibDir,
52173
+ pythonVersionDir,
52174
+ "site-packages/litellm_proxy_extras/migrations"
52175
+ ),
52176
+ log: log6
52177
+ });
52178
+ if (prePush.failed.length > 0) {
52179
+ warn3([
52180
+ `Could not prepare LiteLLM's database for the schema push:`,
52181
+ ...prePush.failed.map((f) => ` ${f.name}: ${f.error}`),
52182
+ ``,
52183
+ `Continuing with prisma db push, which will likely refuse and name`,
52184
+ `the change it cannot make.`
52185
+ ]);
52186
+ }
52187
+ } catch (err4) {
52188
+ warn3([
52189
+ `Could not connect to LiteLLM's database to prepare the schema push:`,
52190
+ ` ${err4 instanceof Error ? err4.message : String(err4)}`
52191
+ ]);
52192
+ } finally {
52193
+ try {
52194
+ await prePushClient.end();
52195
+ } catch {
52196
+ }
52197
+ }
51683
52198
  log6("Running `prisma db push` against LiteLLM's schema\u2026");
51684
52199
  const result = (0, import_node_child_process8.spawnSync)(prismaCli, ["db", "push", "--skip-generate"], {
51685
52200
  cwd: litellmProxyDir,
@@ -51696,9 +52211,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
51696
52211
  if (result.error) {
51697
52212
  warn3([
51698
52213
  `Failed to launch prisma: ${result.error.message}`,
51699
- `Skipping LiteLLM database setup.`
52214
+ `LiteLLM's database schema was NOT updated.`
51700
52215
  ]);
51701
- return;
52216
+ throw new LiteLLMSchemaPushError(
52217
+ `Could not launch prisma to update LiteLLM's database schema: ${result.error.message}`
52218
+ );
51702
52219
  }
51703
52220
  if (result.status !== 0) {
51704
52221
  warn3([
@@ -51706,9 +52223,16 @@ var initLiteLLMDatabase = async (packageRoot) => {
51706
52223
  `stdout:`,
51707
52224
  ...(result.stdout || "(empty)").split("\n").map((l) => ` ${l}`),
51708
52225
  `stderr:`,
51709
- ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`)
52226
+ ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`),
52227
+ ``,
52228
+ `LiteLLM's database schema was NOT updated. Starting the proxy on it`,
52229
+ `would break tag budgets and spend tracking while chat keeps working.`,
52230
+ `If prisma asks for --accept-data-loss, a LiteLLM upgrade changed a`,
52231
+ `constraint it will not alter on its own: see pre-push-migrations.ts.`
51710
52232
  ]);
51711
- return;
52233
+ throw new LiteLLMSchemaPushError(
52234
+ `prisma db push against LiteLLM's database exited with status ${result.status}: ` + (result.stderr || result.stdout || "no output").trim().split("\n").slice(-3).join(" ")
52235
+ );
51712
52236
  }
51713
52237
  log6("\u2713 LiteLLM database ready.");
51714
52238
  };
@@ -51752,7 +52276,7 @@ var create = ({
51752
52276
  });
51753
52277
  const sdk = new import_sdk_node.NodeSDK({
51754
52278
  traceExporter,
51755
- logRecordProcessors: [new import_sdk_logs.BatchLogRecordProcessor(logExporter)],
52279
+ logRecordProcessors: [new import_sdk_logs.BatchLogRecordProcessor({ exporter: logExporter })],
51756
52280
  instrumentations: [(0, import_auto_instrumentations_node.getNodeAutoInstrumentations)()],
51757
52281
  resource: (0, import_resources.resourceFromAttributes)({
51758
52282
  [import_semantic_conventions.ATTR_SERVICE_NAME]: "Exulu"
@@ -52556,23 +53080,23 @@ async function computeTopics({
52556
53080
  const taken = /* @__PURE__ */ new Set();
52557
53081
  const labels = /* @__PURE__ */ new Map();
52558
53082
  const finalIndex = new Map(filtered.map((r, i) => [r.index, i]));
52559
- for (const { index: origIndex, count } of [...filtered].sort((a, b) => b.count - a.count)) {
53083
+ for (const { index: origIndex, count: count2 } of [...filtered].sort((a, b) => b.count - a.count)) {
52560
53084
  const label = pickLabel(
52561
53085
  counts.get(origIndex) ?? /* @__PURE__ */ new Map(),
52562
53086
  corpus,
52563
53087
  finalIndex.get(origIndex) ?? 0,
52564
- count,
53088
+ count2,
52565
53089
  ids.length,
52566
53090
  taken
52567
53091
  );
52568
53092
  labels.set(origIndex, label);
52569
53093
  for (const word of label.split(" & ")) taken.add(word.toLowerCase());
52570
53094
  }
52571
- const rows = filtered.map(({ centre, index: origIndex, count }, newIndex) => ({
53095
+ const rows = filtered.map(({ centre, index: origIndex, count: count2 }, newIndex) => ({
52572
53096
  context: sanitizeName(contextId),
52573
53097
  topic_index: newIndex,
52574
53098
  label: labels.get(origIndex) ?? `Topic ${newIndex + 1}`,
52575
- count,
53099
+ count: count2,
52576
53100
  x: centre[0] ?? 0,
52577
53101
  y: centre[1] ?? 0,
52578
53102
  z: centre[2] ?? 0,