@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.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import "dotenv/config";
2
2
  import {
3
3
  documentProcessor
4
- } from "./chunk-7UDWQTFZ.js";
4
+ } from "./chunk-Q4DFJFUI.js";
5
5
  import {
6
6
  getPackageRoot,
7
7
  getPythonSetupInstructions,
8
8
  isPythonEnvironmentSetup,
9
9
  setupPythonEnvironment,
10
10
  validatePythonEnvironment
11
- } from "./chunk-JIZCKSJO.js";
11
+ } from "./chunk-NJWNOXLJ.js";
12
12
  import {
13
13
  AGENTIC_RETRIEVAL_TOOL_NAME,
14
14
  BACKFILL_BATCH,
@@ -82,6 +82,7 @@ import {
82
82
  authRegistry,
83
83
  authentication,
84
84
  buildMemoryPromptBlock,
85
+ buildToolUpload,
85
86
  canAccessSkill,
86
87
  canEditMemory,
87
88
  canManageShare,
@@ -125,6 +126,7 @@ import {
125
126
  documentCacheDays,
126
127
  downloadKeyIntoSandbox,
127
128
  dropProjection,
129
+ emitToolCallAudit,
128
130
  encrypt,
129
131
  ensureEntityTables,
130
132
  ensureSkillRead,
@@ -132,6 +134,7 @@ import {
132
134
  estimateMessageTokens,
133
135
  estimateTokens,
134
136
  exchangeCodeForTokens,
137
+ extractClientInfo,
135
138
  extractDocument,
136
139
  exuluApp,
137
140
  filterReadableSkills,
@@ -169,6 +172,7 @@ import {
169
172
  isDerivedKey,
170
173
  isExpired,
171
174
  isExternalOrAnonymousUser,
175
+ isInterimToolStatus,
172
176
  isPublicSurface,
173
177
  isRunSessionMetadata,
174
178
  l2normalize,
@@ -246,7 +250,7 @@ import {
246
250
  willEmbedOnQueue,
247
251
  withRunSession,
248
252
  workflowTemplatesSchema
249
- } from "./chunk-PNBVWUEA.js";
253
+ } from "./chunk-XVUJ3WIC.js";
250
254
  import {
251
255
  LITELLM_UI_PATH,
252
256
  ResolveModelError,
@@ -273,7 +277,7 @@ import {
273
277
  tagInfo,
274
278
  upsertBudget,
275
279
  waitForLiteLLMReady
276
- } from "./chunk-NBAFO66K.js";
280
+ } from "./chunk-43QIPMLT.js";
277
281
  import {
278
282
  findLiteLLMModel
279
283
  } from "./chunk-F534XOQR.js";
@@ -311,13 +315,13 @@ var describeError = (e) => {
311
315
  return head ?? String(e);
312
316
  };
313
317
  function logRedisErrors(source, label) {
314
- let count = 0;
318
+ let count2 = 0;
315
319
  let lastLoggedAt = 0;
316
320
  source.on("error", (err2) => {
317
- count += 1;
321
+ count2 += 1;
318
322
  const now = Date.now();
319
- if (count === 1 || now - lastLoggedAt >= ERROR_LOG_THROTTLE_MS) {
320
- errorLog(`${label} connection error (${redisAddress()}): ${describeError(err2)}${count > 1 ? ` (x${count})` : ""}`);
323
+ if (count2 === 1 || now - lastLoggedAt >= ERROR_LOG_THROTTLE_MS) {
324
+ errorLog(`${label} connection error (${redisAddress()}): ${describeError(err2)}${count2 > 1 ? ` (x${count2})` : ""}`);
321
325
  lastLoggedAt = now;
322
326
  }
323
327
  });
@@ -1226,7 +1230,8 @@ var addProviderFields = async (args, requestedFields, result, tools, user, conte
1226
1230
  name: hydrated?.name || "",
1227
1231
  description: hydrated?.description || "",
1228
1232
  category: tool3?.category || "default",
1229
- needsApproval: true
1233
+ needsApproval: true,
1234
+ api: hydrated?.api ?? { enabled: false }
1230
1235
  };
1231
1236
  console.log("[EXULU] hydratedTool", hydratedTool);
1232
1237
  return hydratedTool;
@@ -1642,19 +1647,19 @@ function createQueries(table, tools, contexts) {
1642
1647
  } else {
1643
1648
  if (tableNamePlural === "tracking") {
1644
1649
  query = query.sum("total as count");
1645
- const [{ count }] = await query.sum("total as count");
1650
+ const [{ count: count2 }] = await query.sum("total as count");
1646
1651
  return [
1647
1652
  {
1648
1653
  group: "total",
1649
- count: count ? Number(count) : 0
1654
+ count: count2 ? Number(count2) : 0
1650
1655
  }
1651
1656
  ];
1652
1657
  } else {
1653
- const [{ count }] = await query.count("* as count");
1658
+ const [{ count: count2 }] = await query.count("* as count");
1654
1659
  return [
1655
1660
  {
1656
1661
  group: "total",
1657
- count: count ? Number(count) : 0
1662
+ count: count2 ? Number(count2) : 0
1658
1663
  }
1659
1664
  ];
1660
1665
  }
@@ -3650,16 +3655,16 @@ var shouldGenerateEmbeddings = ({
3650
3655
 
3651
3656
  // src/exulu/embedder-change.ts
3652
3657
  var MAX_INLINE_REGENERATION_ITEMS = 2e3;
3653
- var decideRebuildCase = (existing, next, tableExists) => {
3654
- if (!tableExists) return "create";
3658
+ var decideRebuildCase = (existing, next, tableExists2) => {
3659
+ if (!tableExists2) return "create";
3655
3660
  if (existing === null) return "recreate";
3656
3661
  return existing === next ? "truncate" : "recreate";
3657
3662
  };
3658
3663
  var changeContextEmbedder = async (context, model, queue, deps) => {
3659
- const tableExists = await deps.chunksTableExists(context);
3664
+ const tableExists2 = await deps.chunksTableExists(context);
3660
3665
  const target = model ?? deps.codeModel(context);
3661
3666
  if (!target) {
3662
- if (tableExists) await deps.dropChunksTable(context);
3667
+ if (tableExists2) await deps.dropChunksTable(context);
3663
3668
  await deps.persist(context.id, null, null);
3664
3669
  await deps.hydrate([context]);
3665
3670
  return { case: "cleared", items: 0, jobs: [] };
@@ -3674,7 +3679,7 @@ var changeContextEmbedder = async (context, model, queue, deps) => {
3674
3679
  }
3675
3680
  }
3676
3681
  const existing = await deps.currentDimensionality(context.id);
3677
- const rebuild = decideRebuildCase(existing, dimensionality, tableExists);
3682
+ const rebuild = decideRebuildCase(existing, dimensionality, tableExists2);
3678
3683
  if (rebuild === "recreate") {
3679
3684
  await deps.dropChunksTable(context);
3680
3685
  await deps.createChunksTable(context);
@@ -4976,17 +4981,17 @@ function createMutations(table, contexts, tools, config) {
4976
4981
  "You are not authorized to delete all chunks via API, user must be super admin."
4977
4982
  );
4978
4983
  }
4979
- let count = 0;
4984
+ let count2 = 0;
4980
4985
  if (!args.limit) {
4981
4986
  const result = await db.from(getChunksTableName(id)).count();
4982
- count = parseInt(result[0].count);
4987
+ count2 = parseInt(result[0].count);
4983
4988
  await db.from(getChunksTableName(id)).truncate();
4984
4989
  } else {
4985
- count = await db.from(getChunksTableName(id)).limit(args.limit).delete();
4990
+ count2 = await db.from(getChunksTableName(id)).limit(args.limit).delete();
4986
4991
  }
4987
4992
  return {
4988
4993
  message: "Chunks deleted successfully.",
4989
- items: count,
4994
+ items: count2,
4990
4995
  jobs: []
4991
4996
  };
4992
4997
  }
@@ -5734,6 +5739,225 @@ async function recallMemories({ agent, contexts, query, user, db, previousUserTu
5734
5739
  return { collector, memoryItems: chunks, promptBlock: buildMemoryPromptBlock(collector.list()) };
5735
5740
  }
5736
5741
 
5742
+ // src/exulu/message-language.ts
5743
+ import { francAll } from "franc";
5744
+ var FUNCTION_WORDS = {
5745
+ en: `the and is are were be been am do does did have has had will would can could should may might must
5746
+ what which who whom whose when where why how many much this that these those there here it its you your yours
5747
+ 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
5748
+ 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`,
5749
+ de: `der die das den dem des ein eine einen einem einer eines und oder aber nicht kein keine ist sind war waren
5750
+ wird werden wurde wurden hat haben hatte hast kann k\xF6nnen konnte muss m\xFCssen soll sollen darf wie was wer wo
5751
+ wann warum wieso welche welcher welches viele viel ich du er sie es wir ihr mich mir dich dir uns euch mein
5752
+ 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
5753
+ durch wenn weil dass ob auch nur noch schon sehr bitte danke hallo ja nein man sich dieser diese dieses gibt
5754
+ als bis gegen zwischen damit dann bedeutet bedeuten hei\xDFt zeigt zeige kennst welche gibt wieviel kannst k\xF6nnt k\xF6nnte k\xF6nnten habt`,
5755
+ nl: `de het een en of maar niet geen is zijn was waren wordt worden werd heeft hebben had kan kunnen moet moeten
5756
+ zal zullen wat wie waar wanneer waarom hoe welke veel ik jij je hij zij ze wij we jullie mij me mijn jouw uw
5757
+ van naar bij met zonder voor op uit over onder in om door als omdat dat die deze dit ook nog al zeer erg
5758
+ alstublieft bedankt hoi ja nee er aan te betekent heet toont`,
5759
+ 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
5760
+ doit doivent que qui quoi quel quelle quels quelles o\xF9 quand pourquoi comment combien je tu il elle nous vous
5761
+ 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
5762
+ si parce ce cette ces aussi tr\xE8s bonjour merci plus`,
5763
+ 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
5764
+ 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
5765
+ 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
5766
+ estos estas tambi\xE9n muy hola gracias m\xE1s`,
5767
+ 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
5768
+ devono che chi cosa quale quali dove quando perch\xE9 come quanto quanti io tu lui lei noi voi loro mi ti si
5769
+ 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
5770
+ questo questa questi queste anche molto ciao grazie pi\xF9`,
5771
+ 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
5772
+ deve devem que quem qual quais onde quando porque como quanto quantos eu tu ele ela n\xF3s voc\xEAs eles elas me
5773
+ 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
5774
+ esta estes estas tamb\xE9m muito ol\xE1 obrigado obrigada mais`,
5775
+ 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
5776
+ tack hej ja nej finns blir vara detta dessa`,
5777
+ da: `og det et som p\xE5 af med til har ikke om jeg du han hun vi kan skal skulle hvad
5778
+ hvordan hvorn\xE5r hvorfor hvilken hvilke eller men fra efter uden over under ogs\xE5 meget her mig dig sig
5779
+ min din tak hej ja nej findes bliver v\xE6re dette disse`,
5780
+ 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
5781
+ din takk hei ja nei finnes blir v\xE6re dette disse`,
5782
+ 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
5783
+ 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
5784
+ 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`,
5785
+ 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
5786
+ 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
5787
+ ano tak\xE9 u\u017E jen velmi pros\xEDm d\u011Bkuji ahoj jak\xFD jak\xE1 jak\xE9`,
5788
+ 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
5789
+ onlar bana sana ona bize size gibi kadar ama veya \xE7ok daha evet hay\u0131r l\xFCtfen te\u015Fekk\xFCrler merhaba olarak
5790
+ olan ise ki her \u015Fey`,
5791
+ 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
5792
+ 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`,
5793
+ 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
5794
+ 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
5795
+ al ale lui`,
5796
+ 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
5797
+ csak nagyon igen k\xF6sz\xF6n\xF6m szia kell lehet tud meg el be ki fel le ez ezt azt ezek`
5798
+ };
5799
+ var LISTS = Object.entries(FUNCTION_WORDS).map(([language, list]) => [
5800
+ language,
5801
+ new Set(list.split(/\s+/).filter((word) => word.length > 1))
5802
+ ]);
5803
+ var FAMILY = { sv: "nordic", da: "nordic", nb: "nordic", cs: "west-slavic", pl: "west-slavic" };
5804
+ var family = (language) => FAMILY[language] ?? language;
5805
+ var MARGIN = 2;
5806
+ var MIN_SHARE = 0.2;
5807
+ var FRANC_MIN_LETTERS = 60;
5808
+ var FRANC_MIN_LEAD = 0.1;
5809
+ var FRANC_LATIN = {
5810
+ eng: "en",
5811
+ deu: "de",
5812
+ nld: "nl",
5813
+ fra: "fr",
5814
+ spa: "es",
5815
+ ita: "it",
5816
+ por: "pt",
5817
+ swe: "sv",
5818
+ dan: "da",
5819
+ nob: "nb",
5820
+ fin: "fi",
5821
+ pol: "pl",
5822
+ ces: "cs",
5823
+ slk: "sk",
5824
+ hun: "hu",
5825
+ ron: "ro",
5826
+ tur: "tr",
5827
+ hrv: "hr",
5828
+ slv: "sl",
5829
+ lit: "lt",
5830
+ lav: "lv",
5831
+ est: "et",
5832
+ ind: "id",
5833
+ vie: "vi",
5834
+ cat: "ca"
5835
+ };
5836
+ var FRANC_CYRILLIC = { rus: "ru", ukr: "uk", bul: "bg", srp: "sr", bel: "be", mkd: "mk" };
5837
+ var FRANC_ARABIC = { arb: "ar", pes: "fa", urd: "ur" };
5838
+ var SCRIPT_LANGUAGE = [
5839
+ [/[\p{Script=Hiragana}\p{Script=Katakana}]/gu, "ja"],
5840
+ [/\p{Script=Hangul}/gu, "ko"],
5841
+ [/\p{Script=Han}/gu, "zh"],
5842
+ [/\p{Script=Thai}/gu, "th"],
5843
+ [/\p{Script=Hebrew}/gu, "he"],
5844
+ [/\p{Script=Greek}/gu, "el"],
5845
+ [/\p{Script=Devanagari}/gu, "hi"]
5846
+ ];
5847
+ var NONE = { language: null, mixed: false };
5848
+ var MIXED = { language: null, mixed: true };
5849
+ var count = (text, pattern) => (text.match(pattern) ?? []).length;
5850
+ function franc(prose, only, minLetters) {
5851
+ if (count(prose, /\p{L}/gu) < minLetters) return null;
5852
+ const guesses = francAll(prose, { only: Object.keys(only), minLength: 3 });
5853
+ const best = guesses[0];
5854
+ if (!best || best[0] === "und") return null;
5855
+ if (best[1] - (guesses[1]?.[1] ?? 0) < FRANC_MIN_LEAD) return null;
5856
+ return only[best[0]] ?? null;
5857
+ }
5858
+ function readText(text) {
5859
+ const prose = text.replace(/```[\s\S]*?(```|$)/g, " ").replace(/`[^`\n]*`/g, " ").replace(/\b(https?:\/\/|www\.)\S+/gi, " ").toLowerCase();
5860
+ const letters = count(prose, /\p{L}/gu);
5861
+ if (letters === 0) return NONE;
5862
+ const latin = count(prose, /\p{Script=Latin}/gu);
5863
+ if (latin < letters / 2) {
5864
+ for (const [pattern, language] of SCRIPT_LANGUAGE) {
5865
+ if (count(prose, pattern) >= (letters - latin) / 3 && count(prose, pattern) >= 2) return { language, mixed: false };
5866
+ }
5867
+ if (count(prose, /\p{Script=Cyrillic}/gu) > letters / 2) {
5868
+ return { language: franc(prose, FRANC_CYRILLIC, 20), mixed: false };
5869
+ }
5870
+ if (count(prose, /\p{Script=Arabic}/gu) > letters / 2) {
5871
+ return { language: franc(prose, FRANC_ARABIC, 20), mixed: false };
5872
+ }
5873
+ return NONE;
5874
+ }
5875
+ const words = (prose.match(/\p{L}+/gu) ?? []).filter((word) => word.length > 1);
5876
+ if (words.length === 0) return NONE;
5877
+ 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);
5878
+ const guess = franc(prose, FRANC_LATIN, FRANC_MIN_LETTERS);
5879
+ const top = found[0];
5880
+ if (!top) return { language: guess, mixed: false };
5881
+ const against = (other) => {
5882
+ const mine = top.hits.filter((word) => !other.set.has(word)).length;
5883
+ const theirs = other.hits.filter((word) => !top.set.has(word)).length;
5884
+ if (mine >= 1 && mine >= MARGIN * theirs) return "wins";
5885
+ return theirs === 0 ? "open" : "mixed";
5886
+ };
5887
+ const others = found.filter((entry) => entry !== top);
5888
+ const rivals = others.filter((entry) => family(entry.language) !== family(top.language)).map(against);
5889
+ if (rivals.includes("mixed")) return MIXED;
5890
+ if (rivals.includes("open")) return NONE;
5891
+ const siblings = others.filter((entry) => family(entry.language) === family(top.language)).map(against);
5892
+ const words_say = siblings.every((verdict) => verdict === "wins") ? top.language : null;
5893
+ if (guess) {
5894
+ if (words_say) return words_say === guess ? { language: guess, mixed: false } : NONE;
5895
+ return family(guess) === family(top.language) ? { language: guess, mixed: false } : NONE;
5896
+ }
5897
+ if (!words_say) return NONE;
5898
+ const enough = top.hits.length >= 2 ? top.hits.length / words.length >= MIN_SHARE : words.length <= 2;
5899
+ return enough ? { language: words_say, mixed: false } : NONE;
5900
+ }
5901
+ function readMessageLanguage(text) {
5902
+ if (typeof text !== "string") return NONE;
5903
+ const whole = readText(text);
5904
+ if (!whole.language) return whole;
5905
+ const opening = text.trim().match(/^[^?!.:\n]{1,300}[?!.:\n]/)?.[0];
5906
+ if (!opening || opening.length > text.trim().length * 0.8) return whole;
5907
+ const first = readText(opening).language;
5908
+ return first && first !== whole.language ? MIXED : whole;
5909
+ }
5910
+
5911
+ // src/exulu/response-language.ts
5912
+ var LOCALE = /^[a-z]{2,3}(-[a-z0-9]{2,8}){0,2}$/i;
5913
+ var languageName = (locale) => {
5914
+ try {
5915
+ const name = new Intl.DisplayNames(["en"], { type: "language" }).of(locale);
5916
+ return name && name.toLowerCase() !== locale.toLowerCase() ? name : void 0;
5917
+ } catch {
5918
+ return void 0;
5919
+ }
5920
+ };
5921
+ function resolveResponseLanguageMode(agent) {
5922
+ const raw = agent?.response_language;
5923
+ if (typeof raw !== "string") return { kind: "off" };
5924
+ const value = raw.trim();
5925
+ if (!value || value.toLowerCase() === "off") return { kind: "off" };
5926
+ if (value.toLowerCase() === "auto") return { kind: "auto" };
5927
+ if (!LOCALE.test(value)) return { kind: "off" };
5928
+ const language = languageName(value);
5929
+ return language ? { kind: "fixed", language } : { kind: "off" };
5930
+ }
5931
+ var LANGUAGE_NAME_OVERRIDES = { nb: "Norwegian", zh: "Chinese" };
5932
+ var nameOf = (locale) => LANGUAGE_NAME_OVERRIDES[locale] ?? languageName(locale) ?? locale;
5933
+ 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.";
5934
+ 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.`;
5935
+ function responseLanguageInstruction({
5936
+ agent,
5937
+ current,
5938
+ previousUserTexts: previousUserTexts2
5939
+ }) {
5940
+ const mode = resolveResponseLanguageMode(agent);
5941
+ if (mode.kind === "off") return "";
5942
+ if (mode.kind === "fixed") {
5943
+ return `Response language: ${REPLY_IN(mode.language)} Only if the user explicitly asks for a translation into another language, follow that request instead.`;
5944
+ }
5945
+ const now = readMessageLanguage(current);
5946
+ if (now.language) {
5947
+ const language = nameOf(now.language);
5948
+ return `Response language: The user's latest message is written in ${language}. ${REPLY_IN(language)} ${EXCEPTION}`;
5949
+ }
5950
+ if (now.mixed) return "";
5951
+ for (let i = previousUserTexts2.length - 1; i >= 0; i--) {
5952
+ const earlier = readMessageLanguage(previousUserTexts2[i]).language;
5953
+ if (earlier) {
5954
+ const language = nameOf(earlier);
5955
+ return `Response language: The conversation so far has been in ${language}. ${REPLY_IN(language)} ${EXCEPTION}`;
5956
+ }
5957
+ }
5958
+ return "";
5959
+ }
5960
+
5737
5961
  // src/exulu/skills/decisions.ts
5738
5962
  var SKILL_TOOL_IDS = ["skill_create", "skill_update"];
5739
5963
  var isSkillToolId = (id) => SKILL_TOOL_IDS.includes(id);
@@ -6177,6 +6401,12 @@ When a tool execution is not approved by the user, do not retry it unless explic
6177
6401
  if (credentialGuardrail) {
6178
6402
  system += "\n\n" + credentialGuardrail;
6179
6403
  }
6404
+ const answerLanguage = responseLanguageInstruction({
6405
+ agent,
6406
+ current: query,
6407
+ previousUserTexts: previousUserTexts([...messages, currentAsUiMessage])
6408
+ });
6409
+ if (answerLanguage) system += "\n\n" + answerLanguage;
6180
6410
  if (prompt) {
6181
6411
  let result = { object: null, text: "" };
6182
6412
  let inputTokens = 0;
@@ -6606,6 +6836,12 @@ When a tool execution is not approved by the user, do not retry it unless explic
6606
6836
  Example: {url: https://www.google.com, title: Google, snippet: The result of the web search.}
6607
6837
  `;
6608
6838
  }
6839
+ const answerLanguage = responseLanguageInstruction({
6840
+ agent,
6841
+ current: query,
6842
+ previousUserTexts: previousUserTexts(messages)
6843
+ });
6844
+ if (answerLanguage) system += "\n\n" + answerLanguage;
6609
6845
  const agenticEntry = currentTools?.find((t) => t.id === "agentic_context_search");
6610
6846
  const agenticToolKey = agenticEntry ? sanitizeToolName(agenticEntry.name) : void 0;
6611
6847
  const retrievalGuard = retrievalBudgetGuard(
@@ -6971,7 +7207,7 @@ function detectPayloadFormat(contentType) {
6971
7207
  }
6972
7208
  var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
6973
7209
  function extractMultipartMimePart(rawBody, contentType) {
6974
- return new Promise((resolve3, reject) => {
7210
+ return new Promise((resolve4, reject) => {
6975
7211
  let found = null;
6976
7212
  const bb = Busboy({ headers: { "content-type": contentType }, defCharset: "latin1" });
6977
7213
  bb.on("field", (name, value) => {
@@ -6980,7 +7216,7 @@ function extractMultipartMimePart(rawBody, contentType) {
6980
7216
  }
6981
7217
  });
6982
7218
  bb.on("close", () => {
6983
- if (found) resolve3(found);
7219
+ if (found) resolve4(found);
6984
7220
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
6985
7221
  });
6986
7222
  bb.on("error", (err2) => reject(err2 instanceof Error ? err2 : new Error(String(err2))));
@@ -7076,14 +7312,14 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
7076
7312
  const currentBucket = Math.floor(now / HOUR_MS);
7077
7313
  const currentKey = `${key}:${currentBucket}`;
7078
7314
  const previousKey = `${key}:${currentBucket - 1}`;
7079
- const count = await redis.incr(currentKey);
7080
- if (count === 1) {
7315
+ const count2 = await redis.incr(currentKey);
7316
+ if (count2 === 1) {
7081
7317
  await redis.expire(currentKey, 2 * 60 * 60);
7082
7318
  }
7083
7319
  const previousRaw = await redis.get(previousKey);
7084
7320
  const previous = previousRaw ? Number(previousRaw) : 0;
7085
7321
  const elapsedFraction = now % HOUR_MS / HOUR_MS;
7086
- const weighted = count + previous * (1 - elapsedFraction);
7322
+ const weighted = count2 + previous * (1 - elapsedFraction);
7087
7323
  return weighted <= limitPerHour;
7088
7324
  } catch (err2) {
7089
7325
  console.error(
@@ -8359,10 +8595,10 @@ function sniffDelimiter(headerLine) {
8359
8595
  let best = CANDIDATE_DELIMITERS[0];
8360
8596
  let bestCount = 0;
8361
8597
  for (const candidate of CANDIDATE_DELIMITERS) {
8362
- const count = counts.get(candidate) ?? 0;
8363
- if (count > bestCount) {
8598
+ const count2 = counts.get(candidate) ?? 0;
8599
+ if (count2 > bestCount) {
8364
8600
  best = candidate;
8365
- bestCount = count;
8601
+ bestCount = count2;
8366
8602
  }
8367
8603
  }
8368
8604
  return best;
@@ -8371,7 +8607,7 @@ function createSniffer(onFirstLine) {
8371
8607
  const head = [];
8372
8608
  let headBytes = 0;
8373
8609
  let resolved = false;
8374
- const resolve3 = (line) => {
8610
+ const resolve4 = (line) => {
8375
8611
  if (resolved) return;
8376
8612
  resolved = true;
8377
8613
  onFirstLine(line);
@@ -8386,15 +8622,15 @@ function createSniffer(onFirstLine) {
8386
8622
  const text = Buffer.concat(head).toString("utf-8");
8387
8623
  const eol = /\r|\n/.exec(text);
8388
8624
  if (eol) {
8389
- resolve3(text.slice(0, eol.index));
8625
+ resolve4(text.slice(0, eol.index));
8390
8626
  } else if (headBytes >= MAX_HEADER_BYTES) {
8391
- resolve3(text);
8627
+ resolve4(text);
8392
8628
  }
8393
8629
  }
8394
8630
  callback(null, chunk2);
8395
8631
  },
8396
8632
  flush(callback) {
8397
- resolve3(Buffer.concat(head).toString("utf-8"));
8633
+ resolve4(Buffer.concat(head).toString("utf-8"));
8398
8634
  callback();
8399
8635
  }
8400
8636
  });
@@ -8402,8 +8638,8 @@ function createSniffer(onFirstLine) {
8402
8638
  async function streamCsvRows(input, handlers, opts) {
8403
8639
  let resolveFirstLine = () => {
8404
8640
  };
8405
- const firstLine = new Promise((resolve3) => {
8406
- resolveFirstLine = resolve3;
8641
+ const firstLine = new Promise((resolve4) => {
8642
+ resolveFirstLine = resolve4;
8407
8643
  });
8408
8644
  const sniffer = createSniffer((line) => resolveFirstLine(line));
8409
8645
  let parser;
@@ -8897,7 +9133,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
8897
9133
  );
8898
9134
  if (attempt < retries) {
8899
9135
  const backoffMs = 500 * Math.pow(2, attempt - 1);
8900
- await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
9136
+ await new Promise((resolve4) => setTimeout(resolve4, backoffMs));
8901
9137
  }
8902
9138
  }
8903
9139
  }
@@ -9115,7 +9351,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9115
9351
  async (sessionId) => {
9116
9352
  const retries2 = 3;
9117
9353
  let attempts = 0;
9118
- const promise = new Promise(async (resolve3, reject) => {
9354
+ const promise = new Promise(async (resolve4, reject) => {
9119
9355
  while (attempts < retries2) {
9120
9356
  try {
9121
9357
  const messages2 = await processUiMessagesFlow({
@@ -9135,7 +9371,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9135
9371
  // back into blanket pre-approval (spec §5.2).
9136
9372
  respectToolApprovals: workflow.auto_approve_tools !== true
9137
9373
  });
9138
- resolve3(messages2);
9374
+ resolve4(messages2);
9139
9375
  break;
9140
9376
  } catch (error) {
9141
9377
  console.error(
@@ -9162,7 +9398,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9162
9398
  }
9163
9399
  reject(new Error(error instanceof Error ? error.message : String(error)));
9164
9400
  }
9165
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
9401
+ await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
9166
9402
  }
9167
9403
  }
9168
9404
  });
@@ -9262,7 +9498,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9262
9498
  } = await validateEvalPayload(data);
9263
9499
  const retries2 = 3;
9264
9500
  let attempts = 0;
9265
- const promise = new Promise(async (resolve3, reject) => {
9501
+ const promise = new Promise(async (resolve4, reject) => {
9266
9502
  while (attempts < retries2) {
9267
9503
  try {
9268
9504
  const messages2 = await processUiMessagesFlow({
@@ -9273,7 +9509,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9273
9509
  tools,
9274
9510
  config
9275
9511
  });
9276
- resolve3(messages2);
9512
+ resolve4(messages2);
9277
9513
  break;
9278
9514
  } catch (error) {
9279
9515
  console.error(
@@ -9284,7 +9520,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9284
9520
  if (attempts >= retries2) {
9285
9521
  reject(new Error(error instanceof Error ? error.message : String(error)));
9286
9522
  }
9287
- await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
9523
+ await new Promise((resolve5) => setTimeout((resolve6) => resolve6(true), 2e3));
9288
9524
  }
9289
9525
  }
9290
9526
  });
@@ -9867,7 +10103,7 @@ var pollJobResult = async ({
9867
10103
  attempts++;
9868
10104
  const job = await Job.fromId(queue.queue, jobId);
9869
10105
  if (!job) {
9870
- await new Promise((resolve3) => setTimeout((resolve4) => resolve4(true), 2e3));
10106
+ await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
9871
10107
  continue;
9872
10108
  }
9873
10109
  const elapsedTime = Date.now() - startTime;
@@ -9897,7 +10133,7 @@ var pollJobResult = async ({
9897
10133
  console.log(`[EXULU] eval function ${job.id} result: ${result}`);
9898
10134
  break;
9899
10135
  }
9900
- await new Promise((resolve3) => setTimeout(() => resolve3(true), 2e3));
10136
+ await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
9901
10137
  }
9902
10138
  return result;
9903
10139
  };
@@ -10001,7 +10237,7 @@ var processUiMessagesFlow = async ({
10001
10237
  trigger: "agent"
10002
10238
  };
10003
10239
  try {
10004
- messageHistory = await new Promise(async (resolve3, reject) => {
10240
+ messageHistory = await new Promise(async (resolve4, reject) => {
10005
10241
  const startTime = Date.now();
10006
10242
  try {
10007
10243
  const result = await generateStream({
@@ -10092,7 +10328,7 @@ var processUiMessagesFlow = async ({
10092
10328
  })
10093
10329
  ] : []
10094
10330
  ]);
10095
- resolve3({
10331
+ resolve4({
10096
10332
  messages,
10097
10333
  metadata: {
10098
10334
  tokens: {
@@ -10340,7 +10576,7 @@ async function fetch_with_retry(args) {
10340
10576
  console.log(
10341
10577
  `[EXULU-RECALL] fetch error from ${url} (${err2.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
10342
10578
  );
10343
- await new Promise((resolve3) => setTimeout(resolve3, 5e3 + jitterMs()));
10579
+ await new Promise((resolve4) => setTimeout(resolve4, 5e3 + jitterMs()));
10344
10580
  continue;
10345
10581
  }
10346
10582
  let wait_for = null;
@@ -10360,7 +10596,7 @@ async function fetch_with_retry(args) {
10360
10596
  `[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
10361
10597
  );
10362
10598
  await new Promise(
10363
- (resolve3) => setTimeout(resolve3, 1e3 * wait_for + jitterMs())
10599
+ (resolve4) => setTimeout(resolve4, 1e3 * wait_for + jitterMs())
10364
10600
  );
10365
10601
  continue;
10366
10602
  }
@@ -14692,7 +14928,7 @@ type EmbeddingModelOption {
14692
14928
  await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
14693
14929
  const retries = 3;
14694
14930
  let attempts = 0;
14695
- const promise = new Promise(async (resolve3, reject) => {
14931
+ const promise = new Promise(async (resolve4, reject) => {
14696
14932
  while (attempts < retries) {
14697
14933
  try {
14698
14934
  const messages2 = await processUiMessagesFlow({
@@ -14710,7 +14946,7 @@ type EmbeddingModelOption {
14710
14946
  // (never overriding a person), not as a chat continuation.
14711
14947
  jobResultId
14712
14948
  });
14713
- resolve3(messages2);
14949
+ resolve4(messages2);
14714
14950
  break;
14715
14951
  } catch (error) {
14716
14952
  console.error(
@@ -14724,7 +14960,7 @@ type EmbeddingModelOption {
14724
14960
  if (attempts >= retries) {
14725
14961
  reject(error instanceof Error ? error : new Error(String(error)));
14726
14962
  }
14727
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
14963
+ await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
14728
14964
  }
14729
14965
  }
14730
14966
  });
@@ -15152,7 +15388,7 @@ type EmbeddingModelOption {
15152
15388
  if (!client2) {
15153
15389
  throw new Error("Redis client not created properly");
15154
15390
  }
15155
- const { jobs, count } = await getJobsByQueueName(
15391
+ const { jobs, count: count2 } = await getJobsByQueueName(
15156
15392
  args.queue,
15157
15393
  args.statusses,
15158
15394
  args.page || 1,
@@ -15178,11 +15414,11 @@ type EmbeddingModelOption {
15178
15414
  })
15179
15415
  ),
15180
15416
  pageInfo: {
15181
- pageCount: Math.ceil(count / (args.limit || 100)),
15182
- itemCount: count,
15417
+ pageCount: Math.ceil(count2 / (args.limit || 100)),
15418
+ itemCount: count2,
15183
15419
  currentPage: args.page || 1,
15184
15420
  hasPreviousPage: args.page && args.page > 1 ? true : false,
15185
- hasNextPage: args.page && args.page < Math.ceil(count / (args.limit || 100)) ? true : false
15421
+ hasNextPage: args.page && args.page < Math.ceil(count2 / (args.limit || 100)) ? true : false
15186
15422
  }
15187
15423
  };
15188
15424
  };
@@ -15239,10 +15475,10 @@ type EmbeddingModelOption {
15239
15475
  contexts.map(async (context2) => {
15240
15476
  let processor = null;
15241
15477
  if (context2.processor) {
15242
- processor = await new Promise(async (resolve3, reject) => {
15478
+ processor = await new Promise(async (resolve4, reject) => {
15243
15479
  const config2 = context2.processor?.config;
15244
15480
  const queue = await config2?.queue;
15245
- resolve3({
15481
+ resolve4({
15246
15482
  name: context2.processor.name,
15247
15483
  description: context2.processor.description,
15248
15484
  queue: queue?.queue?.name || void 0,
@@ -15324,10 +15560,10 @@ type EmbeddingModelOption {
15324
15560
  }
15325
15561
  let processor = null;
15326
15562
  if (data.processor) {
15327
- processor = await new Promise(async (resolve3, reject) => {
15563
+ processor = await new Promise(async (resolve4, reject) => {
15328
15564
  const config2 = data.processor?.config;
15329
15565
  const queue = await config2?.queue;
15330
- resolve3({
15566
+ resolve4({
15331
15567
  name: data.processor.name,
15332
15568
  description: data.processor.description,
15333
15569
  queue: queue?.queue?.name || void 0,
@@ -15872,7 +16108,7 @@ import bodyParser from "body-parser";
15872
16108
  import "crypto-js";
15873
16109
  import "openai";
15874
16110
  import fs2 from "fs";
15875
- import { randomUUID as randomUUID9 } from "crypto";
16111
+ import { randomUUID as randomUUID10 } from "crypto";
15876
16112
  import "@opentelemetry/api";
15877
16113
  import JSZip3 from "jszip";
15878
16114
 
@@ -16464,7 +16700,7 @@ var internetSearchTool = new ExuluTool({
16464
16700
  } catch (error) {
16465
16701
  if (error instanceof Perplexity.RateLimitError && attempt < maxRetries - 1) {
16466
16702
  const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
16467
- await new Promise((resolve3) => setTimeout(resolve3, delay));
16703
+ await new Promise((resolve4) => setTimeout(resolve4, delay));
16468
16704
  continue;
16469
16705
  }
16470
16706
  throw error;
@@ -17375,6 +17611,106 @@ function registerViewerIdentityRoutes(app, deps) {
17375
17611
  });
17376
17612
  }
17377
17613
 
17614
+ // src/exulu/tool-api-route.ts
17615
+ import { randomUUID as randomUUID9 } from "crypto";
17616
+ var TOOL_API_ROUTE_PATH = "/tools/:id";
17617
+ var toolConfigDefaults = (tool3) => Object.fromEntries(
17618
+ (tool3.config ?? []).filter((c) => c.default !== void 0).map((c) => [c.name, c.default])
17619
+ );
17620
+ var isAsyncIterable = (value) => !!value && typeof value === "object" && Symbol.asyncIterator in value;
17621
+ function registerToolApiRoutes(app, deps) {
17622
+ app.post(TOOL_API_ROUTE_PATH, async (req, res) => {
17623
+ const tool3 = deps.tools.find((t) => t.id === req.params.id);
17624
+ if (!tool3 || tool3.api?.enabled !== true) {
17625
+ res.status(404).json({ detail: "Tool not found." });
17626
+ return;
17627
+ }
17628
+ const auth = await deps.authenticate(req);
17629
+ const user = auth.user;
17630
+ if (!user?.id) {
17631
+ res.status(auth.code ?? 401).json({ detail: auth.message ?? "Authentication required." });
17632
+ return;
17633
+ }
17634
+ if (user.type === "api" && user.scope_mode && user.scope_mode !== "admin") {
17635
+ res.status(403).json({ detail: "This API key is scoped to agents and cannot call tools directly." });
17636
+ return;
17637
+ }
17638
+ let input = {};
17639
+ if (tool3.inputSchema) {
17640
+ const parsed = await tool3.inputSchema.safeParseAsync(req.body ?? {});
17641
+ if (!parsed.success) {
17642
+ res.status(400).json({
17643
+ detail: "The request body does not match the tool's input schema.",
17644
+ issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message }))
17645
+ });
17646
+ return;
17647
+ }
17648
+ input = parsed.data ?? {};
17649
+ }
17650
+ const execute2 = tool3.tool?.execute;
17651
+ if (!execute2) {
17652
+ res.status(500).json({ detail: "Tool has no execute function." });
17653
+ return;
17654
+ }
17655
+ const toolCallId = `${tool3.id}_${randomUUID9()}`;
17656
+ const started = Date.now();
17657
+ let output;
17658
+ let status = "ok";
17659
+ let failure;
17660
+ try {
17661
+ const response = await execute2(
17662
+ {
17663
+ ...input,
17664
+ user,
17665
+ req,
17666
+ contexts: Object.fromEntries((deps.contexts ?? []).map((c) => [c.id, c])),
17667
+ exuluConfig: deps.config,
17668
+ upload: deps.buildUpload?.(deps.config, user),
17669
+ toolVariablesConfig: toolConfigDefaults(tool3),
17670
+ allExuluTools: deps.tools,
17671
+ currentTools: [tool3]
17672
+ },
17673
+ { toolCallId, messages: [] }
17674
+ );
17675
+ if (isAsyncIterable(response)) {
17676
+ for await (const value of response) {
17677
+ if (!isInterimToolStatus(value)) output = value;
17678
+ }
17679
+ } else {
17680
+ output = response;
17681
+ }
17682
+ } catch (error) {
17683
+ status = "error";
17684
+ failure = error;
17685
+ }
17686
+ try {
17687
+ await deps.onCall?.({
17688
+ tool: tool3,
17689
+ user,
17690
+ req,
17691
+ toolCallId,
17692
+ input,
17693
+ output,
17694
+ status,
17695
+ error: failure,
17696
+ durationMs: Date.now() - started
17697
+ });
17698
+ } catch (error) {
17699
+ console.error(`[EXULU] tool api: recording the call to "${tool3.id}" failed:`, error);
17700
+ res.status(500).json({ detail: "The tool call could not be recorded." });
17701
+ return;
17702
+ }
17703
+ if (status === "error") {
17704
+ console.error(`[EXULU] tool api: "${tool3.id}" threw:`, failure);
17705
+ res.status(500).json({
17706
+ detail: failure instanceof Error ? failure.message : "The tool failed."
17707
+ });
17708
+ return;
17709
+ }
17710
+ res.status(200).json(output ?? {});
17711
+ });
17712
+ }
17713
+
17378
17714
  // src/exulu/shared-artifact-create-route.ts
17379
17715
  function registerCreateShareRoute(app, deps) {
17380
17716
  app.post("/shared-artifacts", async (req, res) => {
@@ -19685,8 +20021,8 @@ var settleWithin = async (tasks, ms) => {
19685
20021
  try {
19686
20022
  return await Promise.race([
19687
20023
  Promise.allSettled(tasks),
19688
- new Promise((resolve3) => {
19689
- timer3 = setTimeout(() => resolve3(null), ms);
20024
+ new Promise((resolve4) => {
20025
+ timer3 = setTimeout(() => resolve4(null), ms);
19690
20026
  })
19691
20027
  ]);
19692
20028
  } finally {
@@ -20534,7 +20870,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
20534
20870
  inputs: payload
20535
20871
  };
20536
20872
  await queue.queue.add("email-intake", jobData, {
20537
- jobId: randomUUID9(),
20873
+ jobId: randomUUID10(),
20538
20874
  attempts: 3,
20539
20875
  removeOnComplete: 5e3,
20540
20876
  removeOnFail: 1e4,
@@ -20942,7 +21278,7 @@ ${customInstructions}` : agent.instructions,
20942
21278
  contextId: agent.memory,
20943
21279
  agentId: agent.id,
20944
21280
  session: headers.session ?? null,
20945
- messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID9(),
21281
+ messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID10(),
20946
21282
  userId: user?.id ?? null
20947
21283
  });
20948
21284
  }
@@ -21047,13 +21383,13 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21047
21383
  [
21048
21384
  ["inputTokens", inputTokens],
21049
21385
  ["outputTokens", outputTokens]
21050
- ].filter(([, count]) => count > 0).map(
21051
- ([name, count]) => updateStatistic({
21386
+ ].filter(([, count2]) => count2 > 0).map(
21387
+ ([name, count2]) => updateStatistic({
21052
21388
  name,
21053
21389
  label: agent.name,
21054
21390
  type: STATISTICS_TYPE_ENUM.AGENT_RUN,
21055
21391
  trigger: "agent",
21056
- count,
21392
+ count: count2,
21057
21393
  user: user?.id,
21058
21394
  role: user?.role?.id
21059
21395
  })
@@ -21635,7 +21971,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21635
21971
  const keys = [];
21636
21972
  const revisedPrompts = [];
21637
21973
  for (const img of images) {
21638
- const filename = `${randomUUID9()}.${img.extension}`;
21974
+ const filename = `${randomUUID10()}.${img.extension}`;
21639
21975
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
21640
21976
  const fullKey = await uploadFile(
21641
21977
  img.buffer,
@@ -21923,7 +22259,7 @@ ${style.markdown}` : params.prompt;
21923
22259
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
21924
22260
  );
21925
22261
  const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
21926
- const messageId = randomUUID9();
22262
+ const messageId = randomUUID10();
21927
22263
  const uiMessage = {
21928
22264
  id: messageId,
21929
22265
  role: "system",
@@ -23020,7 +23356,7 @@ ${style.markdown}` : params.prompt;
23020
23356
  return;
23021
23357
  }
23022
23358
  const meta = await parseSkillFrontmatter(bytes);
23023
- const skillId = randomUUID9();
23359
+ const skillId = randomUUID10();
23024
23360
  try {
23025
23361
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
23026
23362
  } catch (err2) {
@@ -23143,7 +23479,7 @@ ${style.markdown}` : params.prompt;
23143
23479
  return;
23144
23480
  }
23145
23481
  if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
23146
- const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID9()}${extension}`;
23482
+ const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID10()}${extension}`;
23147
23483
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
23148
23484
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
23149
23485
  res.json({ uploadUrl, stagingKey });
@@ -24237,6 +24573,39 @@ ${style.markdown}` : params.prompt;
24237
24573
  RBACResolver,
24238
24574
  checkRecordAccess
24239
24575
  });
24576
+ registerToolApiRoutes(app, {
24577
+ authenticate: (req) => requestValidators.authenticate(req),
24578
+ tools,
24579
+ contexts,
24580
+ config,
24581
+ buildUpload: (cfg, user) => buildToolUpload(cfg, user),
24582
+ onCall: async ({ tool: tool3, user, req, toolCallId, input, output, status, error, durationMs }) => {
24583
+ await updateStatistic({
24584
+ name: "count",
24585
+ label: tool3.name,
24586
+ type: STATISTICS_TYPE_ENUM.TOOL_CALL,
24587
+ trigger: "api",
24588
+ count: 1,
24589
+ user: user.id,
24590
+ role: user.role?.id
24591
+ });
24592
+ const auditLogger = getAuditLogger(config ?? {});
24593
+ await emitToolCallAudit(auditLogger, {
24594
+ durationMs,
24595
+ agent: void 0,
24596
+ tool: { id: tool3.id, name: tool3.name, category: tool3.category, authentication: tool3.authentication },
24597
+ user,
24598
+ projectId: void 0,
24599
+ sessionID: void 0,
24600
+ toolCallId,
24601
+ input,
24602
+ output,
24603
+ status,
24604
+ error,
24605
+ client: extractClientInfo(req)
24606
+ });
24607
+ }
24608
+ });
24240
24609
  registerClaimCheckRoutes(app, {
24241
24610
  authenticate: (req) => requestValidators.authenticate(req),
24242
24611
  checkApiKeyScope,
@@ -24539,7 +24908,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
24539
24908
 
24540
24909
  // src/mcp/index.ts
24541
24910
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
24542
- import { randomUUID as randomUUID10 } from "crypto";
24911
+ import { randomUUID as randomUUID11 } from "crypto";
24543
24912
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
24544
24913
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
24545
24914
  import "express";
@@ -24633,7 +25002,7 @@ var ExuluMCP = class {
24633
25002
  throw new Error("Tool not found in converted tools array.");
24634
25003
  }
24635
25004
  const iterator = await convertedTool.execute(inputs, {
24636
- toolCallId: tool3.id + "_" + randomUUID10(),
25005
+ toolCallId: tool3.id + "_" + randomUUID11(),
24637
25006
  messages: []
24638
25007
  });
24639
25008
  let result;
@@ -24823,7 +25192,7 @@ var ExuluMCP = class {
24823
25192
  transport = this.transports[sessionId];
24824
25193
  } else if (!sessionId && isInitializeRequest(req.body)) {
24825
25194
  transport = new StreamableHTTPServerTransport({
24826
- sessionIdGenerator: () => randomUUID10(),
25195
+ sessionIdGenerator: () => randomUUID11(),
24827
25196
  onsessioninitialized: (sessionId2) => {
24828
25197
  this.transports[sessionId2] = transport;
24829
25198
  }
@@ -25404,7 +25773,7 @@ After asking a question, use the Question Read tool to check if the user has ans
25404
25773
 
25405
25774
  // src/templates/tools/question/question-ask.ts
25406
25775
  import z15 from "zod";
25407
- import { randomUUID as randomUUID11 } from "crypto";
25776
+ import { randomUUID as randomUUID12 } from "crypto";
25408
25777
  var AnswerOptionSchema = z15.object({
25409
25778
  id: z15.string().describe("Unique identifier for the answer option"),
25410
25779
  text: z15.string().describe("The text of the answer option")
@@ -25458,15 +25827,15 @@ var QuestionAskTool = new ExuluTool({
25458
25827
  throw new Error("You don't have access to this session " + session.id + ".");
25459
25828
  }
25460
25829
  const answerOptionsWithIds = answerOptions.map((text) => ({
25461
- id: randomUUID11(),
25830
+ id: randomUUID12(),
25462
25831
  text
25463
25832
  }));
25464
25833
  answerOptionsWithIds.push({
25465
- id: randomUUID11(),
25834
+ id: randomUUID12(),
25466
25835
  text: "None of the above..."
25467
25836
  });
25468
25837
  const newQuestion = {
25469
- id: randomUUID11(),
25838
+ id: randomUUID12(),
25470
25839
  question,
25471
25840
  answerOptions: answerOptionsWithIds,
25472
25841
  status: "pending"
@@ -27086,7 +27455,7 @@ var RecursiveChunker = class _RecursiveChunker extends BaseChunker {
27086
27455
  `Number of splits ${splits.length} does not match number of token counts ${tokenCounts.length}`
27087
27456
  );
27088
27457
  }
27089
- if (tokenCounts.every((count) => count > this.chunkSize)) {
27458
+ if (tokenCounts.every((count2) => count2 > this.chunkSize)) {
27090
27459
  return [splits, tokenCounts];
27091
27460
  }
27092
27461
  const merged = [];
@@ -27094,14 +27463,14 @@ var RecursiveChunker = class _RecursiveChunker extends BaseChunker {
27094
27463
  let sum = 0;
27095
27464
  if (combineWhitespace) {
27096
27465
  cumulativeTokenCounts.push(0);
27097
- for (const count of tokenCounts) {
27098
- sum += count + 1;
27466
+ for (const count2 of tokenCounts) {
27467
+ sum += count2 + 1;
27099
27468
  cumulativeTokenCounts.push(sum);
27100
27469
  }
27101
27470
  } else {
27102
27471
  cumulativeTokenCounts.push(0);
27103
- for (const count of tokenCounts) {
27104
- sum += count;
27472
+ for (const count2 of tokenCounts) {
27473
+ sum += count2;
27105
27474
  cumulativeTokenCounts.push(sum);
27106
27475
  }
27107
27476
  }
@@ -27755,8 +28124,8 @@ var execute = async ({ contexts }) => {
27755
28124
  };
27756
28125
 
27757
28126
  // src/exulu/litellm/db-init.ts
27758
- import { existsSync as existsSync4, readdirSync } from "fs";
27759
- import { resolve as resolve2 } from "path";
28127
+ import { existsSync as existsSync5, readdirSync } from "fs";
28128
+ import { resolve as resolve3 } from "path";
27760
28129
  import { spawnSync } from "child_process";
27761
28130
  import { Client } from "pg";
27762
28131
 
@@ -27813,6 +28182,67 @@ var checkLiteLLMDatabaseSafety = (configPath) => {
27813
28182
  return { ok: true, reason: "isolated", litellmTarget };
27814
28183
  };
27815
28184
 
28185
+ // src/exulu/litellm/pre-push-migrations.ts
28186
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
28187
+ import { resolve as resolve2 } from "path";
28188
+ var tableExists = async (client2, table) => {
28189
+ const res = await client2.query(
28190
+ `SELECT 1 AS exists FROM information_schema.tables
28191
+ WHERE table_schema = 'public' AND table_name = $1`,
28192
+ [table]
28193
+ );
28194
+ return res.rows.length > 0;
28195
+ };
28196
+ var columnExists = async (client2, table, column) => {
28197
+ const res = await client2.query(
28198
+ `SELECT 1 AS exists FROM information_schema.columns
28199
+ WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`,
28200
+ [table, column]
28201
+ );
28202
+ return res.rows.length > 0;
28203
+ };
28204
+ var JWT_KEY_MAPPING_ISSUER_MIGRATION = "20260915000000_scope_jwt_key_mapping_by_issuer";
28205
+ var MIGRATIONS = [
28206
+ {
28207
+ name: JWT_KEY_MAPPING_ISSUER_MIGRATION,
28208
+ isNeeded: async (client2) => (
28209
+ // A fresh database has no table yet; the push creates it in its final
28210
+ // shape, and the migration's ALTER TABLE would fail on a missing table.
28211
+ await tableExists(client2, "LiteLLM_JWTKeyMapping") && !await columnExists(client2, "LiteLLM_JWTKeyMapping", "jwt_issuer")
28212
+ )
28213
+ }
28214
+ ];
28215
+ var applyPrePushMigrations = async (args) => {
28216
+ const { client: client2, migrationsDir, log: log6 } = args;
28217
+ const result = { applied: [], failed: [] };
28218
+ for (const migration of MIGRATIONS) {
28219
+ const file = resolve2(migrationsDir, migration.name, "migration.sql");
28220
+ if (!existsSync4(file)) continue;
28221
+ try {
28222
+ if (!await migration.isNeeded(client2)) continue;
28223
+ } catch (err2) {
28224
+ result.failed.push({ name: migration.name, error: errorMessage(err2) });
28225
+ continue;
28226
+ }
28227
+ const sql = readFileSync4(file, "utf8");
28228
+ try {
28229
+ await client2.query("BEGIN");
28230
+ await client2.query(sql);
28231
+ await client2.query("COMMIT");
28232
+ result.applied.push(migration.name);
28233
+ log6(`Applied LiteLLM migration ${migration.name} ahead of the schema push.`);
28234
+ } catch (err2) {
28235
+ try {
28236
+ await client2.query("ROLLBACK");
28237
+ } catch {
28238
+ }
28239
+ result.failed.push({ name: migration.name, error: errorMessage(err2) });
28240
+ }
28241
+ }
28242
+ return result;
28243
+ };
28244
+ var errorMessage = (err2) => err2 instanceof Error ? err2.message : String(err2);
28245
+
27816
28246
  // src/exulu/litellm/db-init.ts
27817
28247
  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";
27818
28248
  var warn2 = (lines) => {
@@ -27824,8 +28254,14 @@ ${WARNING_BANNER}`);
27824
28254
  `);
27825
28255
  };
27826
28256
  var log5 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
28257
+ var LiteLLMSchemaPushError = class extends Error {
28258
+ constructor(message) {
28259
+ super(message);
28260
+ this.name = "LiteLLMSchemaPushError";
28261
+ }
28262
+ };
27827
28263
  var initLiteLLMDatabase = async (packageRoot) => {
27828
- const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve2(process.cwd(), "./config.litellm.yaml");
28264
+ const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve3(process.cwd(), "./config.litellm.yaml");
27829
28265
  const safety = checkLiteLLMDatabaseSafety(configPath);
27830
28266
  if (safety.ok && safety.reason === "no-litellm-db-mode") return;
27831
28267
  if (!safety.ok && safety.reason === "unparseable-url") {
@@ -27963,10 +28399,10 @@ var initLiteLLMDatabase = async (packageRoot) => {
27963
28399
  ]);
27964
28400
  return;
27965
28401
  }
27966
- const venvBin = resolve2(packageRoot, "ee/python/.venv/bin");
27967
- const prismaCli = resolve2(venvBin, "prisma");
27968
- const venvLibDir = resolve2(packageRoot, "ee/python/.venv/lib");
27969
- const pythonVersionDir = existsSync4(venvLibDir) ? readdirSync(venvLibDir).find((entry) => /^python3\.\d+$/.test(entry)) : void 0;
28402
+ const venvBin = resolve3(packageRoot, "ee/python/.venv/bin");
28403
+ const prismaCli = resolve3(venvBin, "prisma");
28404
+ const venvLibDir = resolve3(packageRoot, "ee/python/.venv/lib");
28405
+ const pythonVersionDir = existsSync5(venvLibDir) ? readdirSync(venvLibDir).find((entry) => /^python3\.\d+$/.test(entry)) : void 0;
27970
28406
  if (!pythonVersionDir) {
27971
28407
  warn2([
27972
28408
  `Could not find a python3.* directory under ${venvLibDir}.`,
@@ -27975,13 +28411,13 @@ var initLiteLLMDatabase = async (packageRoot) => {
27975
28411
  ]);
27976
28412
  return;
27977
28413
  }
27978
- const litellmProxyDir = resolve2(
28414
+ const litellmProxyDir = resolve3(
27979
28415
  venvLibDir,
27980
28416
  pythonVersionDir,
27981
28417
  "site-packages/litellm/proxy"
27982
28418
  );
27983
- const schemaPath = resolve2(litellmProxyDir, "schema.prisma");
27984
- if (!existsSync4(prismaCli)) {
28419
+ const schemaPath = resolve3(litellmProxyDir, "schema.prisma");
28420
+ if (!existsSync5(prismaCli)) {
27985
28421
  warn2([
27986
28422
  `Prisma CLI not found at ${prismaCli}.`,
27987
28423
  `Run \`npm run python:setup\` to create the venv and install prisma.`,
@@ -27989,13 +28425,45 @@ var initLiteLLMDatabase = async (packageRoot) => {
27989
28425
  ]);
27990
28426
  return;
27991
28427
  }
27992
- if (!existsSync4(schemaPath)) {
28428
+ if (!existsSync5(schemaPath)) {
27993
28429
  warn2([
27994
28430
  `LiteLLM Prisma schema not found at ${schemaPath}.`,
27995
28431
  `Re-run \`npm run python:setup\`. Skipping LiteLLM database setup.`
27996
28432
  ]);
27997
28433
  return;
27998
28434
  }
28435
+ const prePushClient = new Client({ connectionString: litellmUrl });
28436
+ try {
28437
+ await prePushClient.connect();
28438
+ const prePush = await applyPrePushMigrations({
28439
+ client: prePushClient,
28440
+ migrationsDir: resolve3(
28441
+ venvLibDir,
28442
+ pythonVersionDir,
28443
+ "site-packages/litellm_proxy_extras/migrations"
28444
+ ),
28445
+ log: log5
28446
+ });
28447
+ if (prePush.failed.length > 0) {
28448
+ warn2([
28449
+ `Could not prepare LiteLLM's database for the schema push:`,
28450
+ ...prePush.failed.map((f) => ` ${f.name}: ${f.error}`),
28451
+ ``,
28452
+ `Continuing with prisma db push, which will likely refuse and name`,
28453
+ `the change it cannot make.`
28454
+ ]);
28455
+ }
28456
+ } catch (err2) {
28457
+ warn2([
28458
+ `Could not connect to LiteLLM's database to prepare the schema push:`,
28459
+ ` ${err2 instanceof Error ? err2.message : String(err2)}`
28460
+ ]);
28461
+ } finally {
28462
+ try {
28463
+ await prePushClient.end();
28464
+ } catch {
28465
+ }
28466
+ }
27999
28467
  log5("Running `prisma db push` against LiteLLM's schema\u2026");
28000
28468
  const result = spawnSync(prismaCli, ["db", "push", "--skip-generate"], {
28001
28469
  cwd: litellmProxyDir,
@@ -28012,9 +28480,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
28012
28480
  if (result.error) {
28013
28481
  warn2([
28014
28482
  `Failed to launch prisma: ${result.error.message}`,
28015
- `Skipping LiteLLM database setup.`
28483
+ `LiteLLM's database schema was NOT updated.`
28016
28484
  ]);
28017
- return;
28485
+ throw new LiteLLMSchemaPushError(
28486
+ `Could not launch prisma to update LiteLLM's database schema: ${result.error.message}`
28487
+ );
28018
28488
  }
28019
28489
  if (result.status !== 0) {
28020
28490
  warn2([
@@ -28022,9 +28492,16 @@ var initLiteLLMDatabase = async (packageRoot) => {
28022
28492
  `stdout:`,
28023
28493
  ...(result.stdout || "(empty)").split("\n").map((l) => ` ${l}`),
28024
28494
  `stderr:`,
28025
- ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`)
28495
+ ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`),
28496
+ ``,
28497
+ `LiteLLM's database schema was NOT updated. Starting the proxy on it`,
28498
+ `would break tag budgets and spend tracking while chat keeps working.`,
28499
+ `If prisma asks for --accept-data-loss, a LiteLLM upgrade changed a`,
28500
+ `constraint it will not alter on its own: see pre-push-migrations.ts.`
28026
28501
  ]);
28027
- return;
28502
+ throw new LiteLLMSchemaPushError(
28503
+ `prisma db push against LiteLLM's database exited with status ${result.status}: ` + (result.stderr || result.stdout || "no output").trim().split("\n").slice(-3).join(" ")
28504
+ );
28028
28505
  }
28029
28506
  log5("\u2713 LiteLLM database ready.");
28030
28507
  };
@@ -28066,7 +28543,7 @@ var create = ({
28066
28543
  });
28067
28544
  const sdk = new NodeSDK({
28068
28545
  traceExporter,
28069
- logRecordProcessors: [new BatchLogRecordProcessor(logExporter)],
28546
+ logRecordProcessors: [new BatchLogRecordProcessor({ exporter: logExporter })],
28070
28547
  instrumentations: [getNodeAutoInstrumentations()],
28071
28548
  resource: resourceFromAttributes({
28072
28549
  [ATTR_SERVICE_NAME]: "Exulu"
@@ -28835,23 +29312,23 @@ async function computeTopics({
28835
29312
  const taken = /* @__PURE__ */ new Set();
28836
29313
  const labels = /* @__PURE__ */ new Map();
28837
29314
  const finalIndex = new Map(filtered.map((r, i) => [r.index, i]));
28838
- for (const { index: origIndex, count } of [...filtered].sort((a, b) => b.count - a.count)) {
29315
+ for (const { index: origIndex, count: count2 } of [...filtered].sort((a, b) => b.count - a.count)) {
28839
29316
  const label = pickLabel(
28840
29317
  counts.get(origIndex) ?? /* @__PURE__ */ new Map(),
28841
29318
  corpus,
28842
29319
  finalIndex.get(origIndex) ?? 0,
28843
- count,
29320
+ count2,
28844
29321
  ids.length,
28845
29322
  taken
28846
29323
  );
28847
29324
  labels.set(origIndex, label);
28848
29325
  for (const word of label.split(" & ")) taken.add(word.toLowerCase());
28849
29326
  }
28850
- const rows = filtered.map(({ centre, index: origIndex, count }, newIndex) => ({
29327
+ const rows = filtered.map(({ centre, index: origIndex, count: count2 }, newIndex) => ({
28851
29328
  context: sanitizeName(contextId),
28852
29329
  topic_index: newIndex,
28853
29330
  label: labels.get(origIndex) ?? `Topic ${newIndex + 1}`,
28854
- count,
29331
+ count: count2,
28855
29332
  x: centre[0] ?? 0,
28856
29333
  y: centre[1] ?? 0,
28857
29334
  z: centre[2] ?? 0,