@exulu/backend 5.18.0 → 5.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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-4NYSMZ6F.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";
@@ -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;
@@ -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);
@@ -6971,7 +6976,7 @@ function detectPayloadFormat(contentType) {
6971
6976
  }
6972
6977
  var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
6973
6978
  function extractMultipartMimePart(rawBody, contentType) {
6974
- return new Promise((resolve3, reject) => {
6979
+ return new Promise((resolve4, reject) => {
6975
6980
  let found = null;
6976
6981
  const bb = Busboy({ headers: { "content-type": contentType }, defCharset: "latin1" });
6977
6982
  bb.on("field", (name, value) => {
@@ -6980,7 +6985,7 @@ function extractMultipartMimePart(rawBody, contentType) {
6980
6985
  }
6981
6986
  });
6982
6987
  bb.on("close", () => {
6983
- if (found) resolve3(found);
6988
+ if (found) resolve4(found);
6984
6989
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
6985
6990
  });
6986
6991
  bb.on("error", (err2) => reject(err2 instanceof Error ? err2 : new Error(String(err2))));
@@ -8371,7 +8376,7 @@ function createSniffer(onFirstLine) {
8371
8376
  const head = [];
8372
8377
  let headBytes = 0;
8373
8378
  let resolved = false;
8374
- const resolve3 = (line) => {
8379
+ const resolve4 = (line) => {
8375
8380
  if (resolved) return;
8376
8381
  resolved = true;
8377
8382
  onFirstLine(line);
@@ -8386,15 +8391,15 @@ function createSniffer(onFirstLine) {
8386
8391
  const text = Buffer.concat(head).toString("utf-8");
8387
8392
  const eol = /\r|\n/.exec(text);
8388
8393
  if (eol) {
8389
- resolve3(text.slice(0, eol.index));
8394
+ resolve4(text.slice(0, eol.index));
8390
8395
  } else if (headBytes >= MAX_HEADER_BYTES) {
8391
- resolve3(text);
8396
+ resolve4(text);
8392
8397
  }
8393
8398
  }
8394
8399
  callback(null, chunk2);
8395
8400
  },
8396
8401
  flush(callback) {
8397
- resolve3(Buffer.concat(head).toString("utf-8"));
8402
+ resolve4(Buffer.concat(head).toString("utf-8"));
8398
8403
  callback();
8399
8404
  }
8400
8405
  });
@@ -8402,8 +8407,8 @@ function createSniffer(onFirstLine) {
8402
8407
  async function streamCsvRows(input, handlers, opts) {
8403
8408
  let resolveFirstLine = () => {
8404
8409
  };
8405
- const firstLine = new Promise((resolve3) => {
8406
- resolveFirstLine = resolve3;
8410
+ const firstLine = new Promise((resolve4) => {
8411
+ resolveFirstLine = resolve4;
8407
8412
  });
8408
8413
  const sniffer = createSniffer((line) => resolveFirstLine(line));
8409
8414
  let parser;
@@ -8897,7 +8902,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
8897
8902
  );
8898
8903
  if (attempt < retries) {
8899
8904
  const backoffMs = 500 * Math.pow(2, attempt - 1);
8900
- await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
8905
+ await new Promise((resolve4) => setTimeout(resolve4, backoffMs));
8901
8906
  }
8902
8907
  }
8903
8908
  }
@@ -9115,7 +9120,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9115
9120
  async (sessionId) => {
9116
9121
  const retries2 = 3;
9117
9122
  let attempts = 0;
9118
- const promise = new Promise(async (resolve3, reject) => {
9123
+ const promise = new Promise(async (resolve4, reject) => {
9119
9124
  while (attempts < retries2) {
9120
9125
  try {
9121
9126
  const messages2 = await processUiMessagesFlow({
@@ -9135,7 +9140,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9135
9140
  // back into blanket pre-approval (spec §5.2).
9136
9141
  respectToolApprovals: workflow.auto_approve_tools !== true
9137
9142
  });
9138
- resolve3(messages2);
9143
+ resolve4(messages2);
9139
9144
  break;
9140
9145
  } catch (error) {
9141
9146
  console.error(
@@ -9162,7 +9167,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9162
9167
  }
9163
9168
  reject(new Error(error instanceof Error ? error.message : String(error)));
9164
9169
  }
9165
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
9170
+ await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
9166
9171
  }
9167
9172
  }
9168
9173
  });
@@ -9262,7 +9267,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9262
9267
  } = await validateEvalPayload(data);
9263
9268
  const retries2 = 3;
9264
9269
  let attempts = 0;
9265
- const promise = new Promise(async (resolve3, reject) => {
9270
+ const promise = new Promise(async (resolve4, reject) => {
9266
9271
  while (attempts < retries2) {
9267
9272
  try {
9268
9273
  const messages2 = await processUiMessagesFlow({
@@ -9273,7 +9278,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9273
9278
  tools,
9274
9279
  config
9275
9280
  });
9276
- resolve3(messages2);
9281
+ resolve4(messages2);
9277
9282
  break;
9278
9283
  } catch (error) {
9279
9284
  console.error(
@@ -9284,7 +9289,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9284
9289
  if (attempts >= retries2) {
9285
9290
  reject(new Error(error instanceof Error ? error.message : String(error)));
9286
9291
  }
9287
- await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
9292
+ await new Promise((resolve5) => setTimeout((resolve6) => resolve6(true), 2e3));
9288
9293
  }
9289
9294
  }
9290
9295
  });
@@ -9867,7 +9872,7 @@ var pollJobResult = async ({
9867
9872
  attempts++;
9868
9873
  const job = await Job.fromId(queue.queue, jobId);
9869
9874
  if (!job) {
9870
- await new Promise((resolve3) => setTimeout((resolve4) => resolve4(true), 2e3));
9875
+ await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
9871
9876
  continue;
9872
9877
  }
9873
9878
  const elapsedTime = Date.now() - startTime;
@@ -9897,7 +9902,7 @@ var pollJobResult = async ({
9897
9902
  console.log(`[EXULU] eval function ${job.id} result: ${result}`);
9898
9903
  break;
9899
9904
  }
9900
- await new Promise((resolve3) => setTimeout(() => resolve3(true), 2e3));
9905
+ await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
9901
9906
  }
9902
9907
  return result;
9903
9908
  };
@@ -10001,7 +10006,7 @@ var processUiMessagesFlow = async ({
10001
10006
  trigger: "agent"
10002
10007
  };
10003
10008
  try {
10004
- messageHistory = await new Promise(async (resolve3, reject) => {
10009
+ messageHistory = await new Promise(async (resolve4, reject) => {
10005
10010
  const startTime = Date.now();
10006
10011
  try {
10007
10012
  const result = await generateStream({
@@ -10092,7 +10097,7 @@ var processUiMessagesFlow = async ({
10092
10097
  })
10093
10098
  ] : []
10094
10099
  ]);
10095
- resolve3({
10100
+ resolve4({
10096
10101
  messages,
10097
10102
  metadata: {
10098
10103
  tokens: {
@@ -10340,7 +10345,7 @@ async function fetch_with_retry(args) {
10340
10345
  console.log(
10341
10346
  `[EXULU-RECALL] fetch error from ${url} (${err2.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
10342
10347
  );
10343
- await new Promise((resolve3) => setTimeout(resolve3, 5e3 + jitterMs()));
10348
+ await new Promise((resolve4) => setTimeout(resolve4, 5e3 + jitterMs()));
10344
10349
  continue;
10345
10350
  }
10346
10351
  let wait_for = null;
@@ -10360,7 +10365,7 @@ async function fetch_with_retry(args) {
10360
10365
  `[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
10361
10366
  );
10362
10367
  await new Promise(
10363
- (resolve3) => setTimeout(resolve3, 1e3 * wait_for + jitterMs())
10368
+ (resolve4) => setTimeout(resolve4, 1e3 * wait_for + jitterMs())
10364
10369
  );
10365
10370
  continue;
10366
10371
  }
@@ -14692,7 +14697,7 @@ type EmbeddingModelOption {
14692
14697
  await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
14693
14698
  const retries = 3;
14694
14699
  let attempts = 0;
14695
- const promise = new Promise(async (resolve3, reject) => {
14700
+ const promise = new Promise(async (resolve4, reject) => {
14696
14701
  while (attempts < retries) {
14697
14702
  try {
14698
14703
  const messages2 = await processUiMessagesFlow({
@@ -14710,7 +14715,7 @@ type EmbeddingModelOption {
14710
14715
  // (never overriding a person), not as a chat continuation.
14711
14716
  jobResultId
14712
14717
  });
14713
- resolve3(messages2);
14718
+ resolve4(messages2);
14714
14719
  break;
14715
14720
  } catch (error) {
14716
14721
  console.error(
@@ -14724,7 +14729,7 @@ type EmbeddingModelOption {
14724
14729
  if (attempts >= retries) {
14725
14730
  reject(error instanceof Error ? error : new Error(String(error)));
14726
14731
  }
14727
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
14732
+ await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
14728
14733
  }
14729
14734
  }
14730
14735
  });
@@ -15239,10 +15244,10 @@ type EmbeddingModelOption {
15239
15244
  contexts.map(async (context2) => {
15240
15245
  let processor = null;
15241
15246
  if (context2.processor) {
15242
- processor = await new Promise(async (resolve3, reject) => {
15247
+ processor = await new Promise(async (resolve4, reject) => {
15243
15248
  const config2 = context2.processor?.config;
15244
15249
  const queue = await config2?.queue;
15245
- resolve3({
15250
+ resolve4({
15246
15251
  name: context2.processor.name,
15247
15252
  description: context2.processor.description,
15248
15253
  queue: queue?.queue?.name || void 0,
@@ -15324,10 +15329,10 @@ type EmbeddingModelOption {
15324
15329
  }
15325
15330
  let processor = null;
15326
15331
  if (data.processor) {
15327
- processor = await new Promise(async (resolve3, reject) => {
15332
+ processor = await new Promise(async (resolve4, reject) => {
15328
15333
  const config2 = data.processor?.config;
15329
15334
  const queue = await config2?.queue;
15330
- resolve3({
15335
+ resolve4({
15331
15336
  name: data.processor.name,
15332
15337
  description: data.processor.description,
15333
15338
  queue: queue?.queue?.name || void 0,
@@ -15872,7 +15877,7 @@ import bodyParser from "body-parser";
15872
15877
  import "crypto-js";
15873
15878
  import "openai";
15874
15879
  import fs2 from "fs";
15875
- import { randomUUID as randomUUID9 } from "crypto";
15880
+ import { randomUUID as randomUUID10 } from "crypto";
15876
15881
  import "@opentelemetry/api";
15877
15882
  import JSZip3 from "jszip";
15878
15883
 
@@ -16464,7 +16469,7 @@ var internetSearchTool = new ExuluTool({
16464
16469
  } catch (error) {
16465
16470
  if (error instanceof Perplexity.RateLimitError && attempt < maxRetries - 1) {
16466
16471
  const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
16467
- await new Promise((resolve3) => setTimeout(resolve3, delay));
16472
+ await new Promise((resolve4) => setTimeout(resolve4, delay));
16468
16473
  continue;
16469
16474
  }
16470
16475
  throw error;
@@ -17375,6 +17380,106 @@ function registerViewerIdentityRoutes(app, deps) {
17375
17380
  });
17376
17381
  }
17377
17382
 
17383
+ // src/exulu/tool-api-route.ts
17384
+ import { randomUUID as randomUUID9 } from "crypto";
17385
+ var TOOL_API_ROUTE_PATH = "/tools/:id";
17386
+ var toolConfigDefaults = (tool3) => Object.fromEntries(
17387
+ (tool3.config ?? []).filter((c) => c.default !== void 0).map((c) => [c.name, c.default])
17388
+ );
17389
+ var isAsyncIterable = (value) => !!value && typeof value === "object" && Symbol.asyncIterator in value;
17390
+ function registerToolApiRoutes(app, deps) {
17391
+ app.post(TOOL_API_ROUTE_PATH, async (req, res) => {
17392
+ const tool3 = deps.tools.find((t) => t.id === req.params.id);
17393
+ if (!tool3 || tool3.api?.enabled !== true) {
17394
+ res.status(404).json({ detail: "Tool not found." });
17395
+ return;
17396
+ }
17397
+ const auth = await deps.authenticate(req);
17398
+ const user = auth.user;
17399
+ if (!user?.id) {
17400
+ res.status(auth.code ?? 401).json({ detail: auth.message ?? "Authentication required." });
17401
+ return;
17402
+ }
17403
+ if (user.type === "api" && user.scope_mode && user.scope_mode !== "admin") {
17404
+ res.status(403).json({ detail: "This API key is scoped to agents and cannot call tools directly." });
17405
+ return;
17406
+ }
17407
+ let input = {};
17408
+ if (tool3.inputSchema) {
17409
+ const parsed = await tool3.inputSchema.safeParseAsync(req.body ?? {});
17410
+ if (!parsed.success) {
17411
+ res.status(400).json({
17412
+ detail: "The request body does not match the tool's input schema.",
17413
+ issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message }))
17414
+ });
17415
+ return;
17416
+ }
17417
+ input = parsed.data ?? {};
17418
+ }
17419
+ const execute2 = tool3.tool?.execute;
17420
+ if (!execute2) {
17421
+ res.status(500).json({ detail: "Tool has no execute function." });
17422
+ return;
17423
+ }
17424
+ const toolCallId = `${tool3.id}_${randomUUID9()}`;
17425
+ const started = Date.now();
17426
+ let output;
17427
+ let status = "ok";
17428
+ let failure;
17429
+ try {
17430
+ const response = await execute2(
17431
+ {
17432
+ ...input,
17433
+ user,
17434
+ req,
17435
+ contexts: Object.fromEntries((deps.contexts ?? []).map((c) => [c.id, c])),
17436
+ exuluConfig: deps.config,
17437
+ upload: deps.buildUpload?.(deps.config, user),
17438
+ toolVariablesConfig: toolConfigDefaults(tool3),
17439
+ allExuluTools: deps.tools,
17440
+ currentTools: [tool3]
17441
+ },
17442
+ { toolCallId, messages: [] }
17443
+ );
17444
+ if (isAsyncIterable(response)) {
17445
+ for await (const value of response) {
17446
+ if (!isInterimToolStatus(value)) output = value;
17447
+ }
17448
+ } else {
17449
+ output = response;
17450
+ }
17451
+ } catch (error) {
17452
+ status = "error";
17453
+ failure = error;
17454
+ }
17455
+ try {
17456
+ await deps.onCall?.({
17457
+ tool: tool3,
17458
+ user,
17459
+ req,
17460
+ toolCallId,
17461
+ input,
17462
+ output,
17463
+ status,
17464
+ error: failure,
17465
+ durationMs: Date.now() - started
17466
+ });
17467
+ } catch (error) {
17468
+ console.error(`[EXULU] tool api: recording the call to "${tool3.id}" failed:`, error);
17469
+ res.status(500).json({ detail: "The tool call could not be recorded." });
17470
+ return;
17471
+ }
17472
+ if (status === "error") {
17473
+ console.error(`[EXULU] tool api: "${tool3.id}" threw:`, failure);
17474
+ res.status(500).json({
17475
+ detail: failure instanceof Error ? failure.message : "The tool failed."
17476
+ });
17477
+ return;
17478
+ }
17479
+ res.status(200).json(output ?? {});
17480
+ });
17481
+ }
17482
+
17378
17483
  // src/exulu/shared-artifact-create-route.ts
17379
17484
  function registerCreateShareRoute(app, deps) {
17380
17485
  app.post("/shared-artifacts", async (req, res) => {
@@ -19685,8 +19790,8 @@ var settleWithin = async (tasks, ms) => {
19685
19790
  try {
19686
19791
  return await Promise.race([
19687
19792
  Promise.allSettled(tasks),
19688
- new Promise((resolve3) => {
19689
- timer3 = setTimeout(() => resolve3(null), ms);
19793
+ new Promise((resolve4) => {
19794
+ timer3 = setTimeout(() => resolve4(null), ms);
19690
19795
  })
19691
19796
  ]);
19692
19797
  } finally {
@@ -20534,7 +20639,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
20534
20639
  inputs: payload
20535
20640
  };
20536
20641
  await queue.queue.add("email-intake", jobData, {
20537
- jobId: randomUUID9(),
20642
+ jobId: randomUUID10(),
20538
20643
  attempts: 3,
20539
20644
  removeOnComplete: 5e3,
20540
20645
  removeOnFail: 1e4,
@@ -20942,7 +21047,7 @@ ${customInstructions}` : agent.instructions,
20942
21047
  contextId: agent.memory,
20943
21048
  agentId: agent.id,
20944
21049
  session: headers.session ?? null,
20945
- messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID9(),
21050
+ messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID10(),
20946
21051
  userId: user?.id ?? null
20947
21052
  });
20948
21053
  }
@@ -21635,7 +21740,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21635
21740
  const keys = [];
21636
21741
  const revisedPrompts = [];
21637
21742
  for (const img of images) {
21638
- const filename = `${randomUUID9()}.${img.extension}`;
21743
+ const filename = `${randomUUID10()}.${img.extension}`;
21639
21744
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
21640
21745
  const fullKey = await uploadFile(
21641
21746
  img.buffer,
@@ -21923,7 +22028,7 @@ ${style.markdown}` : params.prompt;
21923
22028
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
21924
22029
  );
21925
22030
  const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
21926
- const messageId = randomUUID9();
22031
+ const messageId = randomUUID10();
21927
22032
  const uiMessage = {
21928
22033
  id: messageId,
21929
22034
  role: "system",
@@ -23020,7 +23125,7 @@ ${style.markdown}` : params.prompt;
23020
23125
  return;
23021
23126
  }
23022
23127
  const meta = await parseSkillFrontmatter(bytes);
23023
- const skillId = randomUUID9();
23128
+ const skillId = randomUUID10();
23024
23129
  try {
23025
23130
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
23026
23131
  } catch (err2) {
@@ -23143,7 +23248,7 @@ ${style.markdown}` : params.prompt;
23143
23248
  return;
23144
23249
  }
23145
23250
  if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
23146
- const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID9()}${extension}`;
23251
+ const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID10()}${extension}`;
23147
23252
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
23148
23253
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
23149
23254
  res.json({ uploadUrl, stagingKey });
@@ -24237,6 +24342,39 @@ ${style.markdown}` : params.prompt;
24237
24342
  RBACResolver,
24238
24343
  checkRecordAccess
24239
24344
  });
24345
+ registerToolApiRoutes(app, {
24346
+ authenticate: (req) => requestValidators.authenticate(req),
24347
+ tools,
24348
+ contexts,
24349
+ config,
24350
+ buildUpload: (cfg, user) => buildToolUpload(cfg, user),
24351
+ onCall: async ({ tool: tool3, user, req, toolCallId, input, output, status, error, durationMs }) => {
24352
+ await updateStatistic({
24353
+ name: "count",
24354
+ label: tool3.name,
24355
+ type: STATISTICS_TYPE_ENUM.TOOL_CALL,
24356
+ trigger: "api",
24357
+ count: 1,
24358
+ user: user.id,
24359
+ role: user.role?.id
24360
+ });
24361
+ const auditLogger = getAuditLogger(config ?? {});
24362
+ await emitToolCallAudit(auditLogger, {
24363
+ durationMs,
24364
+ agent: void 0,
24365
+ tool: { id: tool3.id, name: tool3.name, category: tool3.category, authentication: tool3.authentication },
24366
+ user,
24367
+ projectId: void 0,
24368
+ sessionID: void 0,
24369
+ toolCallId,
24370
+ input,
24371
+ output,
24372
+ status,
24373
+ error,
24374
+ client: extractClientInfo(req)
24375
+ });
24376
+ }
24377
+ });
24240
24378
  registerClaimCheckRoutes(app, {
24241
24379
  authenticate: (req) => requestValidators.authenticate(req),
24242
24380
  checkApiKeyScope,
@@ -24539,7 +24677,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
24539
24677
 
24540
24678
  // src/mcp/index.ts
24541
24679
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
24542
- import { randomUUID as randomUUID10 } from "crypto";
24680
+ import { randomUUID as randomUUID11 } from "crypto";
24543
24681
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
24544
24682
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
24545
24683
  import "express";
@@ -24633,7 +24771,7 @@ var ExuluMCP = class {
24633
24771
  throw new Error("Tool not found in converted tools array.");
24634
24772
  }
24635
24773
  const iterator = await convertedTool.execute(inputs, {
24636
- toolCallId: tool3.id + "_" + randomUUID10(),
24774
+ toolCallId: tool3.id + "_" + randomUUID11(),
24637
24775
  messages: []
24638
24776
  });
24639
24777
  let result;
@@ -24823,7 +24961,7 @@ var ExuluMCP = class {
24823
24961
  transport = this.transports[sessionId];
24824
24962
  } else if (!sessionId && isInitializeRequest(req.body)) {
24825
24963
  transport = new StreamableHTTPServerTransport({
24826
- sessionIdGenerator: () => randomUUID10(),
24964
+ sessionIdGenerator: () => randomUUID11(),
24827
24965
  onsessioninitialized: (sessionId2) => {
24828
24966
  this.transports[sessionId2] = transport;
24829
24967
  }
@@ -25404,7 +25542,7 @@ After asking a question, use the Question Read tool to check if the user has ans
25404
25542
 
25405
25543
  // src/templates/tools/question/question-ask.ts
25406
25544
  import z15 from "zod";
25407
- import { randomUUID as randomUUID11 } from "crypto";
25545
+ import { randomUUID as randomUUID12 } from "crypto";
25408
25546
  var AnswerOptionSchema = z15.object({
25409
25547
  id: z15.string().describe("Unique identifier for the answer option"),
25410
25548
  text: z15.string().describe("The text of the answer option")
@@ -25458,15 +25596,15 @@ var QuestionAskTool = new ExuluTool({
25458
25596
  throw new Error("You don't have access to this session " + session.id + ".");
25459
25597
  }
25460
25598
  const answerOptionsWithIds = answerOptions.map((text) => ({
25461
- id: randomUUID11(),
25599
+ id: randomUUID12(),
25462
25600
  text
25463
25601
  }));
25464
25602
  answerOptionsWithIds.push({
25465
- id: randomUUID11(),
25603
+ id: randomUUID12(),
25466
25604
  text: "None of the above..."
25467
25605
  });
25468
25606
  const newQuestion = {
25469
- id: randomUUID11(),
25607
+ id: randomUUID12(),
25470
25608
  question,
25471
25609
  answerOptions: answerOptionsWithIds,
25472
25610
  status: "pending"
@@ -27755,8 +27893,8 @@ var execute = async ({ contexts }) => {
27755
27893
  };
27756
27894
 
27757
27895
  // src/exulu/litellm/db-init.ts
27758
- import { existsSync as existsSync4, readdirSync } from "fs";
27759
- import { resolve as resolve2 } from "path";
27896
+ import { existsSync as existsSync5, readdirSync } from "fs";
27897
+ import { resolve as resolve3 } from "path";
27760
27898
  import { spawnSync } from "child_process";
27761
27899
  import { Client } from "pg";
27762
27900
 
@@ -27813,6 +27951,67 @@ var checkLiteLLMDatabaseSafety = (configPath) => {
27813
27951
  return { ok: true, reason: "isolated", litellmTarget };
27814
27952
  };
27815
27953
 
27954
+ // src/exulu/litellm/pre-push-migrations.ts
27955
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
27956
+ import { resolve as resolve2 } from "path";
27957
+ var tableExists = async (client2, table) => {
27958
+ const res = await client2.query(
27959
+ `SELECT 1 AS exists FROM information_schema.tables
27960
+ WHERE table_schema = 'public' AND table_name = $1`,
27961
+ [table]
27962
+ );
27963
+ return res.rows.length > 0;
27964
+ };
27965
+ var columnExists = async (client2, table, column) => {
27966
+ const res = await client2.query(
27967
+ `SELECT 1 AS exists FROM information_schema.columns
27968
+ WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2`,
27969
+ [table, column]
27970
+ );
27971
+ return res.rows.length > 0;
27972
+ };
27973
+ var JWT_KEY_MAPPING_ISSUER_MIGRATION = "20260915000000_scope_jwt_key_mapping_by_issuer";
27974
+ var MIGRATIONS = [
27975
+ {
27976
+ name: JWT_KEY_MAPPING_ISSUER_MIGRATION,
27977
+ isNeeded: async (client2) => (
27978
+ // A fresh database has no table yet; the push creates it in its final
27979
+ // shape, and the migration's ALTER TABLE would fail on a missing table.
27980
+ await tableExists(client2, "LiteLLM_JWTKeyMapping") && !await columnExists(client2, "LiteLLM_JWTKeyMapping", "jwt_issuer")
27981
+ )
27982
+ }
27983
+ ];
27984
+ var applyPrePushMigrations = async (args) => {
27985
+ const { client: client2, migrationsDir, log: log6 } = args;
27986
+ const result = { applied: [], failed: [] };
27987
+ for (const migration of MIGRATIONS) {
27988
+ const file = resolve2(migrationsDir, migration.name, "migration.sql");
27989
+ if (!existsSync4(file)) continue;
27990
+ try {
27991
+ if (!await migration.isNeeded(client2)) continue;
27992
+ } catch (err2) {
27993
+ result.failed.push({ name: migration.name, error: errorMessage(err2) });
27994
+ continue;
27995
+ }
27996
+ const sql = readFileSync4(file, "utf8");
27997
+ try {
27998
+ await client2.query("BEGIN");
27999
+ await client2.query(sql);
28000
+ await client2.query("COMMIT");
28001
+ result.applied.push(migration.name);
28002
+ log6(`Applied LiteLLM migration ${migration.name} ahead of the schema push.`);
28003
+ } catch (err2) {
28004
+ try {
28005
+ await client2.query("ROLLBACK");
28006
+ } catch {
28007
+ }
28008
+ result.failed.push({ name: migration.name, error: errorMessage(err2) });
28009
+ }
28010
+ }
28011
+ return result;
28012
+ };
28013
+ var errorMessage = (err2) => err2 instanceof Error ? err2.message : String(err2);
28014
+
27816
28015
  // src/exulu/litellm/db-init.ts
27817
28016
  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
28017
  var warn2 = (lines) => {
@@ -27824,8 +28023,14 @@ ${WARNING_BANNER}`);
27824
28023
  `);
27825
28024
  };
27826
28025
  var log5 = (line) => console.log(`[EXULU-LITELLM] ${line}`);
28026
+ var LiteLLMSchemaPushError = class extends Error {
28027
+ constructor(message) {
28028
+ super(message);
28029
+ this.name = "LiteLLMSchemaPushError";
28030
+ }
28031
+ };
27827
28032
  var initLiteLLMDatabase = async (packageRoot) => {
27828
- const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve2(process.cwd(), "./config.litellm.yaml");
28033
+ const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve3(process.cwd(), "./config.litellm.yaml");
27829
28034
  const safety = checkLiteLLMDatabaseSafety(configPath);
27830
28035
  if (safety.ok && safety.reason === "no-litellm-db-mode") return;
27831
28036
  if (!safety.ok && safety.reason === "unparseable-url") {
@@ -27963,10 +28168,10 @@ var initLiteLLMDatabase = async (packageRoot) => {
27963
28168
  ]);
27964
28169
  return;
27965
28170
  }
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;
28171
+ const venvBin = resolve3(packageRoot, "ee/python/.venv/bin");
28172
+ const prismaCli = resolve3(venvBin, "prisma");
28173
+ const venvLibDir = resolve3(packageRoot, "ee/python/.venv/lib");
28174
+ const pythonVersionDir = existsSync5(venvLibDir) ? readdirSync(venvLibDir).find((entry) => /^python3\.\d+$/.test(entry)) : void 0;
27970
28175
  if (!pythonVersionDir) {
27971
28176
  warn2([
27972
28177
  `Could not find a python3.* directory under ${venvLibDir}.`,
@@ -27975,13 +28180,13 @@ var initLiteLLMDatabase = async (packageRoot) => {
27975
28180
  ]);
27976
28181
  return;
27977
28182
  }
27978
- const litellmProxyDir = resolve2(
28183
+ const litellmProxyDir = resolve3(
27979
28184
  venvLibDir,
27980
28185
  pythonVersionDir,
27981
28186
  "site-packages/litellm/proxy"
27982
28187
  );
27983
- const schemaPath = resolve2(litellmProxyDir, "schema.prisma");
27984
- if (!existsSync4(prismaCli)) {
28188
+ const schemaPath = resolve3(litellmProxyDir, "schema.prisma");
28189
+ if (!existsSync5(prismaCli)) {
27985
28190
  warn2([
27986
28191
  `Prisma CLI not found at ${prismaCli}.`,
27987
28192
  `Run \`npm run python:setup\` to create the venv and install prisma.`,
@@ -27989,13 +28194,45 @@ var initLiteLLMDatabase = async (packageRoot) => {
27989
28194
  ]);
27990
28195
  return;
27991
28196
  }
27992
- if (!existsSync4(schemaPath)) {
28197
+ if (!existsSync5(schemaPath)) {
27993
28198
  warn2([
27994
28199
  `LiteLLM Prisma schema not found at ${schemaPath}.`,
27995
28200
  `Re-run \`npm run python:setup\`. Skipping LiteLLM database setup.`
27996
28201
  ]);
27997
28202
  return;
27998
28203
  }
28204
+ const prePushClient = new Client({ connectionString: litellmUrl });
28205
+ try {
28206
+ await prePushClient.connect();
28207
+ const prePush = await applyPrePushMigrations({
28208
+ client: prePushClient,
28209
+ migrationsDir: resolve3(
28210
+ venvLibDir,
28211
+ pythonVersionDir,
28212
+ "site-packages/litellm_proxy_extras/migrations"
28213
+ ),
28214
+ log: log5
28215
+ });
28216
+ if (prePush.failed.length > 0) {
28217
+ warn2([
28218
+ `Could not prepare LiteLLM's database for the schema push:`,
28219
+ ...prePush.failed.map((f) => ` ${f.name}: ${f.error}`),
28220
+ ``,
28221
+ `Continuing with prisma db push, which will likely refuse and name`,
28222
+ `the change it cannot make.`
28223
+ ]);
28224
+ }
28225
+ } catch (err2) {
28226
+ warn2([
28227
+ `Could not connect to LiteLLM's database to prepare the schema push:`,
28228
+ ` ${err2 instanceof Error ? err2.message : String(err2)}`
28229
+ ]);
28230
+ } finally {
28231
+ try {
28232
+ await prePushClient.end();
28233
+ } catch {
28234
+ }
28235
+ }
27999
28236
  log5("Running `prisma db push` against LiteLLM's schema\u2026");
28000
28237
  const result = spawnSync(prismaCli, ["db", "push", "--skip-generate"], {
28001
28238
  cwd: litellmProxyDir,
@@ -28012,9 +28249,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
28012
28249
  if (result.error) {
28013
28250
  warn2([
28014
28251
  `Failed to launch prisma: ${result.error.message}`,
28015
- `Skipping LiteLLM database setup.`
28252
+ `LiteLLM's database schema was NOT updated.`
28016
28253
  ]);
28017
- return;
28254
+ throw new LiteLLMSchemaPushError(
28255
+ `Could not launch prisma to update LiteLLM's database schema: ${result.error.message}`
28256
+ );
28018
28257
  }
28019
28258
  if (result.status !== 0) {
28020
28259
  warn2([
@@ -28022,9 +28261,16 @@ var initLiteLLMDatabase = async (packageRoot) => {
28022
28261
  `stdout:`,
28023
28262
  ...(result.stdout || "(empty)").split("\n").map((l) => ` ${l}`),
28024
28263
  `stderr:`,
28025
- ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`)
28264
+ ...(result.stderr || "(empty)").split("\n").map((l) => ` ${l}`),
28265
+ ``,
28266
+ `LiteLLM's database schema was NOT updated. Starting the proxy on it`,
28267
+ `would break tag budgets and spend tracking while chat keeps working.`,
28268
+ `If prisma asks for --accept-data-loss, a LiteLLM upgrade changed a`,
28269
+ `constraint it will not alter on its own: see pre-push-migrations.ts.`
28026
28270
  ]);
28027
- return;
28271
+ throw new LiteLLMSchemaPushError(
28272
+ `prisma db push against LiteLLM's database exited with status ${result.status}: ` + (result.stderr || result.stdout || "no output").trim().split("\n").slice(-3).join(" ")
28273
+ );
28028
28274
  }
28029
28275
  log5("\u2713 LiteLLM database ready.");
28030
28276
  };
@@ -28066,7 +28312,7 @@ var create = ({
28066
28312
  });
28067
28313
  const sdk = new NodeSDK({
28068
28314
  traceExporter,
28069
- logRecordProcessors: [new BatchLogRecordProcessor(logExporter)],
28315
+ logRecordProcessors: [new BatchLogRecordProcessor({ exporter: logExporter })],
28070
28316
  instrumentations: [getNodeAutoInstrumentations()],
28071
28317
  resource: resourceFromAttributes({
28072
28318
  [ATTR_SERVICE_NAME]: "Exulu"