@exulu/backend 5.17.2 → 5.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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;
@@ -2965,12 +2970,12 @@ var channelView = (row) => ({
2965
2970
  needsCredentials: readSecrets(row) === null
2966
2971
  });
2967
2972
  var maskIdentity = (identity) => identity.length < 4 ? "\u2022\u2022\u2022\u2022" : `\u2022\u2022\u2022\u2022 ${identity.slice(-4)}`;
2968
- var linkPageUrl = (agentId) => {
2973
+ var linkPageUrl = (agentId, locale) => {
2969
2974
  const base = [process.env.CHANNEL_LINK_BASE_URL, process.env.FRONTEND, process.env.NEXTAUTH_URL].map((v) => (v ?? "").trim()).find((v) => v !== "");
2970
2975
  if (!base) {
2971
2976
  throw new ChannelSetupError("None of CHANNEL_LINK_BASE_URL, FRONTEND and NEXTAUTH_URL is set; the channel link page has no URL");
2972
2977
  }
2973
- return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp`;
2978
+ return `${base.replace(/\/+$/, "")}/public/agents/${encodeURIComponent(agentId)}/link/whatsapp${locale ? `?lang=${locale}` : ""}`;
2974
2979
  };
2975
2980
 
2976
2981
  // src/exulu/channels/link-codes.ts
@@ -3478,11 +3483,19 @@ var registerChannelApi = (app, deps) => {
3478
3483
  if (!row) return void res.json({ links: [] });
3479
3484
  const at = now();
3480
3485
  const links = await createLinkStore(db).listForChannel(row.id);
3486
+ const mayReadUsers = gate.user.super_admin === true || gate.user.role?.users === "read" || gate.user.role?.users === "write";
3487
+ const emails = /* @__PURE__ */ new Map();
3488
+ const ids = [...new Set(links.map((l) => l.user))];
3489
+ if (mayReadUsers && ids.length > 0) {
3490
+ const owners = await db("users").whereIn("id", ids).select("id", "email");
3491
+ for (const o of owners) emails.set(o.id, o.email ?? null);
3492
+ }
3481
3493
  res.json({
3482
3494
  links: links.map((l) => ({
3483
3495
  id: l.id,
3484
3496
  identityMasked: maskIdentity(l.identity),
3485
3497
  userId: l.user,
3498
+ userEmail: emails.get(l.user) ?? null,
3486
3499
  linked_at: l.linked_at,
3487
3500
  expires_at: l.expires_at,
3488
3501
  last_seen_at: l.last_seen_at,
@@ -3491,6 +3504,19 @@ var registerChannelApi = (app, deps) => {
3491
3504
  });
3492
3505
  })
3493
3506
  );
3507
+ app.post(
3508
+ `${base}/verify-token`,
3509
+ route("rotate verify token", async (req, res) => {
3510
+ const gate = await adminAgent(req, res);
3511
+ if (!gate) return;
3512
+ const db = await deps.getDb();
3513
+ const row = await loadChannel(db, gate.agent.id);
3514
+ if (!row) return void res.status(404).json({ detail: "Channel not found." });
3515
+ const verifyToken = randomBytes(24).toString("base64url");
3516
+ await db(TABLE3).where({ id: row.id }).update({ verify_token: verifyToken, updatedAt: now() });
3517
+ res.json({ verifyToken });
3518
+ })
3519
+ );
3494
3520
  app.delete(
3495
3521
  `${base}/links/:linkId`,
3496
3522
  route("revoke link", async (req, res) => {
@@ -3511,24 +3537,53 @@ var registerChannelApi = (app, deps) => {
3511
3537
  res.status(204).end();
3512
3538
  })
3513
3539
  );
3514
- const customerChannel = async (req, opts) => {
3540
+ const customerChannel = async (req) => {
3515
3541
  const agent = await loadAgent(String(req.params.id ?? ""));
3516
3542
  if (!agent) return null;
3517
3543
  const db = await deps.getDb();
3518
3544
  const row = await loadChannel(db, agent.id);
3519
3545
  if (!row) return null;
3520
- if (opts.requireEnabled && !row.enabled) return null;
3521
3546
  return { db, agent, row };
3522
3547
  };
3548
+ const linkableConfig = (agent, row) => {
3549
+ if (!deps.entitled() || !row.enabled) return null;
3550
+ const config = tryParseConfig(row.config);
3551
+ return config && canEnableChannel(agent).ok ? config : null;
3552
+ };
3553
+ app.get(
3554
+ "/public-agents/:id/channels/whatsapp/links",
3555
+ route("customer links", async (req, res) => {
3556
+ const user = await signedIn(req, res);
3557
+ if (!user) return;
3558
+ const none = { available: false, links: [] };
3559
+ if (!deps.entitled()) return void res.json(none);
3560
+ const agent = await loadAgent(String(req.params.id ?? ""));
3561
+ if (!agent) return void res.json(none);
3562
+ const db = await deps.getDb();
3563
+ const row = await loadChannel(db, agent.id);
3564
+ const links = row ? await createLinkStore(db).listForUser(row.id, user.id) : [];
3565
+ const available = !!row && linkableConfig(agent, row) !== null && await channelAccessAllowed({
3566
+ db,
3567
+ loadAgent: (id) => loadAgent(id),
3568
+ agentId: agent.id,
3569
+ channelId: row.id,
3570
+ userId: user.id
3571
+ });
3572
+ res.json({
3573
+ available,
3574
+ links: links.filter((l) => !l.revoked_at).map((l) => ({ id: l.id, identityMasked: maskIdentity(l.identity), expires_at: l.expires_at }))
3575
+ });
3576
+ })
3577
+ );
3523
3578
  app.post(
3524
3579
  "/public-agents/:id/channels/whatsapp/link-code",
3525
3580
  route("issue link code", async (req, res) => {
3526
3581
  const user = await signedIn(req, res);
3527
3582
  if (!user) return;
3528
3583
  if (!deps.entitled()) return void res.status(404).json(NOT_FOUND);
3529
- const found = await customerChannel(req, { requireEnabled: true });
3530
- const config = found ? tryParseConfig(found.row.config) : null;
3531
- if (!found || !config || !canEnableChannel(found.agent).ok) return void res.status(404).json(NOT_FOUND);
3584
+ const found = await customerChannel(req);
3585
+ const config = found ? linkableConfig(found.agent, found.row) : null;
3586
+ if (!found || !config) return void res.status(404).json(NOT_FOUND);
3532
3587
  const { db, agent, row } = found;
3533
3588
  const allowed = await channelAccessAllowed({
3534
3589
  db,
@@ -3573,7 +3628,7 @@ var registerChannelApi = (app, deps) => {
3573
3628
  if (!user) return;
3574
3629
  const linkId = String(req.params.linkId ?? "");
3575
3630
  if (!UUID_RE2.test(linkId)) return void res.status(404).json(NOT_FOUND);
3576
- const found = await customerChannel(req, { requireEnabled: false });
3631
+ const found = await customerChannel(req);
3577
3632
  if (!found) return void res.status(404).json(NOT_FOUND);
3578
3633
  const { db, row } = found;
3579
3634
  const link = await db("channel_links").where({ id: linkId, channel: row.id, user: user.id }).first();
@@ -3600,16 +3655,16 @@ var shouldGenerateEmbeddings = ({
3600
3655
 
3601
3656
  // src/exulu/embedder-change.ts
3602
3657
  var MAX_INLINE_REGENERATION_ITEMS = 2e3;
3603
- var decideRebuildCase = (existing, next, tableExists) => {
3604
- if (!tableExists) return "create";
3658
+ var decideRebuildCase = (existing, next, tableExists2) => {
3659
+ if (!tableExists2) return "create";
3605
3660
  if (existing === null) return "recreate";
3606
3661
  return existing === next ? "truncate" : "recreate";
3607
3662
  };
3608
3663
  var changeContextEmbedder = async (context, model, queue, deps) => {
3609
- const tableExists = await deps.chunksTableExists(context);
3664
+ const tableExists2 = await deps.chunksTableExists(context);
3610
3665
  const target = model ?? deps.codeModel(context);
3611
3666
  if (!target) {
3612
- if (tableExists) await deps.dropChunksTable(context);
3667
+ if (tableExists2) await deps.dropChunksTable(context);
3613
3668
  await deps.persist(context.id, null, null);
3614
3669
  await deps.hydrate([context]);
3615
3670
  return { case: "cleared", items: 0, jobs: [] };
@@ -3624,7 +3679,7 @@ var changeContextEmbedder = async (context, model, queue, deps) => {
3624
3679
  }
3625
3680
  }
3626
3681
  const existing = await deps.currentDimensionality(context.id);
3627
- const rebuild = decideRebuildCase(existing, dimensionality, tableExists);
3682
+ const rebuild = decideRebuildCase(existing, dimensionality, tableExists2);
3628
3683
  if (rebuild === "recreate") {
3629
3684
  await deps.dropChunksTable(context);
3630
3685
  await deps.createChunksTable(context);
@@ -6921,7 +6976,7 @@ function detectPayloadFormat(contentType) {
6921
6976
  }
6922
6977
  var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
6923
6978
  function extractMultipartMimePart(rawBody, contentType) {
6924
- return new Promise((resolve3, reject) => {
6979
+ return new Promise((resolve4, reject) => {
6925
6980
  let found = null;
6926
6981
  const bb = Busboy({ headers: { "content-type": contentType }, defCharset: "latin1" });
6927
6982
  bb.on("field", (name, value) => {
@@ -6930,7 +6985,7 @@ function extractMultipartMimePart(rawBody, contentType) {
6930
6985
  }
6931
6986
  });
6932
6987
  bb.on("close", () => {
6933
- if (found) resolve3(found);
6988
+ if (found) resolve4(found);
6934
6989
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
6935
6990
  });
6936
6991
  bb.on("error", (err2) => reject(err2 instanceof Error ? err2 : new Error(String(err2))));
@@ -8087,7 +8142,7 @@ var createDecideDeps = (p) => {
8087
8142
  now: env.now ?? (() => /* @__PURE__ */ new Date()),
8088
8143
  config,
8089
8144
  // lazily: a missing URL variable must only affect the link reply, never linked users
8090
- linkUrl: () => linkPageUrl(row.agent),
8145
+ linkUrl: () => linkPageUrl(row.agent, config.locale),
8091
8146
  links: createLinkStore(db),
8092
8147
  consumeCode: (code) => consumeCode(store, code),
8093
8148
  codeAttemptsExceeded: (identity) => codeAttemptsExceeded(store, row.id, identity),
@@ -8321,7 +8376,7 @@ function createSniffer(onFirstLine) {
8321
8376
  const head = [];
8322
8377
  let headBytes = 0;
8323
8378
  let resolved = false;
8324
- const resolve3 = (line) => {
8379
+ const resolve4 = (line) => {
8325
8380
  if (resolved) return;
8326
8381
  resolved = true;
8327
8382
  onFirstLine(line);
@@ -8336,15 +8391,15 @@ function createSniffer(onFirstLine) {
8336
8391
  const text = Buffer.concat(head).toString("utf-8");
8337
8392
  const eol = /\r|\n/.exec(text);
8338
8393
  if (eol) {
8339
- resolve3(text.slice(0, eol.index));
8394
+ resolve4(text.slice(0, eol.index));
8340
8395
  } else if (headBytes >= MAX_HEADER_BYTES) {
8341
- resolve3(text);
8396
+ resolve4(text);
8342
8397
  }
8343
8398
  }
8344
8399
  callback(null, chunk2);
8345
8400
  },
8346
8401
  flush(callback) {
8347
- resolve3(Buffer.concat(head).toString("utf-8"));
8402
+ resolve4(Buffer.concat(head).toString("utf-8"));
8348
8403
  callback();
8349
8404
  }
8350
8405
  });
@@ -8352,8 +8407,8 @@ function createSniffer(onFirstLine) {
8352
8407
  async function streamCsvRows(input, handlers, opts) {
8353
8408
  let resolveFirstLine = () => {
8354
8409
  };
8355
- const firstLine = new Promise((resolve3) => {
8356
- resolveFirstLine = resolve3;
8410
+ const firstLine = new Promise((resolve4) => {
8411
+ resolveFirstLine = resolve4;
8357
8412
  });
8358
8413
  const sniffer = createSniffer((line) => resolveFirstLine(line));
8359
8414
  let parser;
@@ -8847,7 +8902,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
8847
8902
  );
8848
8903
  if (attempt < retries) {
8849
8904
  const backoffMs = 500 * Math.pow(2, attempt - 1);
8850
- await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
8905
+ await new Promise((resolve4) => setTimeout(resolve4, backoffMs));
8851
8906
  }
8852
8907
  }
8853
8908
  }
@@ -9065,7 +9120,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9065
9120
  async (sessionId) => {
9066
9121
  const retries2 = 3;
9067
9122
  let attempts = 0;
9068
- const promise = new Promise(async (resolve3, reject) => {
9123
+ const promise = new Promise(async (resolve4, reject) => {
9069
9124
  while (attempts < retries2) {
9070
9125
  try {
9071
9126
  const messages2 = await processUiMessagesFlow({
@@ -9085,7 +9140,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9085
9140
  // back into blanket pre-approval (spec §5.2).
9086
9141
  respectToolApprovals: workflow.auto_approve_tools !== true
9087
9142
  });
9088
- resolve3(messages2);
9143
+ resolve4(messages2);
9089
9144
  break;
9090
9145
  } catch (error) {
9091
9146
  console.error(
@@ -9112,7 +9167,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9112
9167
  }
9113
9168
  reject(new Error(error instanceof Error ? error.message : String(error)));
9114
9169
  }
9115
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
9170
+ await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
9116
9171
  }
9117
9172
  }
9118
9173
  });
@@ -9212,7 +9267,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9212
9267
  } = await validateEvalPayload(data);
9213
9268
  const retries2 = 3;
9214
9269
  let attempts = 0;
9215
- const promise = new Promise(async (resolve3, reject) => {
9270
+ const promise = new Promise(async (resolve4, reject) => {
9216
9271
  while (attempts < retries2) {
9217
9272
  try {
9218
9273
  const messages2 = await processUiMessagesFlow({
@@ -9223,7 +9278,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9223
9278
  tools,
9224
9279
  config
9225
9280
  });
9226
- resolve3(messages2);
9281
+ resolve4(messages2);
9227
9282
  break;
9228
9283
  } catch (error) {
9229
9284
  console.error(
@@ -9234,7 +9289,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
9234
9289
  if (attempts >= retries2) {
9235
9290
  reject(new Error(error instanceof Error ? error.message : String(error)));
9236
9291
  }
9237
- await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
9292
+ await new Promise((resolve5) => setTimeout((resolve6) => resolve6(true), 2e3));
9238
9293
  }
9239
9294
  }
9240
9295
  });
@@ -9817,7 +9872,7 @@ var pollJobResult = async ({
9817
9872
  attempts++;
9818
9873
  const job = await Job.fromId(queue.queue, jobId);
9819
9874
  if (!job) {
9820
- await new Promise((resolve3) => setTimeout((resolve4) => resolve4(true), 2e3));
9875
+ await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
9821
9876
  continue;
9822
9877
  }
9823
9878
  const elapsedTime = Date.now() - startTime;
@@ -9847,7 +9902,7 @@ var pollJobResult = async ({
9847
9902
  console.log(`[EXULU] eval function ${job.id} result: ${result}`);
9848
9903
  break;
9849
9904
  }
9850
- await new Promise((resolve3) => setTimeout(() => resolve3(true), 2e3));
9905
+ await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
9851
9906
  }
9852
9907
  return result;
9853
9908
  };
@@ -9951,7 +10006,7 @@ var processUiMessagesFlow = async ({
9951
10006
  trigger: "agent"
9952
10007
  };
9953
10008
  try {
9954
- messageHistory = await new Promise(async (resolve3, reject) => {
10009
+ messageHistory = await new Promise(async (resolve4, reject) => {
9955
10010
  const startTime = Date.now();
9956
10011
  try {
9957
10012
  const result = await generateStream({
@@ -10042,7 +10097,7 @@ var processUiMessagesFlow = async ({
10042
10097
  })
10043
10098
  ] : []
10044
10099
  ]);
10045
- resolve3({
10100
+ resolve4({
10046
10101
  messages,
10047
10102
  metadata: {
10048
10103
  tokens: {
@@ -10290,7 +10345,7 @@ async function fetch_with_retry(args) {
10290
10345
  console.log(
10291
10346
  `[EXULU-RECALL] fetch error from ${url} (${err2.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
10292
10347
  );
10293
- await new Promise((resolve3) => setTimeout(resolve3, 5e3 + jitterMs()));
10348
+ await new Promise((resolve4) => setTimeout(resolve4, 5e3 + jitterMs()));
10294
10349
  continue;
10295
10350
  }
10296
10351
  let wait_for = null;
@@ -10310,7 +10365,7 @@ async function fetch_with_retry(args) {
10310
10365
  `[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
10311
10366
  );
10312
10367
  await new Promise(
10313
- (resolve3) => setTimeout(resolve3, 1e3 * wait_for + jitterMs())
10368
+ (resolve4) => setTimeout(resolve4, 1e3 * wait_for + jitterMs())
10314
10369
  );
10315
10370
  continue;
10316
10371
  }
@@ -14642,7 +14697,7 @@ type EmbeddingModelOption {
14642
14697
  await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
14643
14698
  const retries = 3;
14644
14699
  let attempts = 0;
14645
- const promise = new Promise(async (resolve3, reject) => {
14700
+ const promise = new Promise(async (resolve4, reject) => {
14646
14701
  while (attempts < retries) {
14647
14702
  try {
14648
14703
  const messages2 = await processUiMessagesFlow({
@@ -14660,7 +14715,7 @@ type EmbeddingModelOption {
14660
14715
  // (never overriding a person), not as a chat continuation.
14661
14716
  jobResultId
14662
14717
  });
14663
- resolve3(messages2);
14718
+ resolve4(messages2);
14664
14719
  break;
14665
14720
  } catch (error) {
14666
14721
  console.error(
@@ -14674,7 +14729,7 @@ type EmbeddingModelOption {
14674
14729
  if (attempts >= retries) {
14675
14730
  reject(error instanceof Error ? error : new Error(String(error)));
14676
14731
  }
14677
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
14732
+ await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
14678
14733
  }
14679
14734
  }
14680
14735
  });
@@ -15189,10 +15244,10 @@ type EmbeddingModelOption {
15189
15244
  contexts.map(async (context2) => {
15190
15245
  let processor = null;
15191
15246
  if (context2.processor) {
15192
- processor = await new Promise(async (resolve3, reject) => {
15247
+ processor = await new Promise(async (resolve4, reject) => {
15193
15248
  const config2 = context2.processor?.config;
15194
15249
  const queue = await config2?.queue;
15195
- resolve3({
15250
+ resolve4({
15196
15251
  name: context2.processor.name,
15197
15252
  description: context2.processor.description,
15198
15253
  queue: queue?.queue?.name || void 0,
@@ -15274,10 +15329,10 @@ type EmbeddingModelOption {
15274
15329
  }
15275
15330
  let processor = null;
15276
15331
  if (data.processor) {
15277
- processor = await new Promise(async (resolve3, reject) => {
15332
+ processor = await new Promise(async (resolve4, reject) => {
15278
15333
  const config2 = data.processor?.config;
15279
15334
  const queue = await config2?.queue;
15280
- resolve3({
15335
+ resolve4({
15281
15336
  name: data.processor.name,
15282
15337
  description: data.processor.description,
15283
15338
  queue: queue?.queue?.name || void 0,
@@ -15822,7 +15877,7 @@ import bodyParser from "body-parser";
15822
15877
  import "crypto-js";
15823
15878
  import "openai";
15824
15879
  import fs2 from "fs";
15825
- import { randomUUID as randomUUID9 } from "crypto";
15880
+ import { randomUUID as randomUUID10 } from "crypto";
15826
15881
  import "@opentelemetry/api";
15827
15882
  import JSZip3 from "jszip";
15828
15883
 
@@ -16414,7 +16469,7 @@ var internetSearchTool = new ExuluTool({
16414
16469
  } catch (error) {
16415
16470
  if (error instanceof Perplexity.RateLimitError && attempt < maxRetries - 1) {
16416
16471
  const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
16417
- await new Promise((resolve3) => setTimeout(resolve3, delay));
16472
+ await new Promise((resolve4) => setTimeout(resolve4, delay));
16418
16473
  continue;
16419
16474
  }
16420
16475
  throw error;
@@ -17325,6 +17380,106 @@ function registerViewerIdentityRoutes(app, deps) {
17325
17380
  });
17326
17381
  }
17327
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
+
17328
17483
  // src/exulu/shared-artifact-create-route.ts
17329
17484
  function registerCreateShareRoute(app, deps) {
17330
17485
  app.post("/shared-artifacts", async (req, res) => {
@@ -19463,6 +19618,20 @@ See docs/superpowers/specs/2026-05-31-in-chat-image-generation-design.md for the
19463
19618
  // src/exulu/routes.ts
19464
19619
  import { resolve as resolvePath } from "path";
19465
19620
 
19621
+ // src/exulu/session-access.ts
19622
+ var SESSION_RBAC_ENTITY = "agent_session";
19623
+ async function hasSessionAccess(db, session, rights, user) {
19624
+ const rbac = await RBACResolver(
19625
+ db,
19626
+ SESSION_RBAC_ENTITY,
19627
+ session.id,
19628
+ session.rights_mode || "private"
19629
+ );
19630
+ const record = { ...session, RBAC: rbac };
19631
+ if (await checkRecordAccess(record, rights, user)) return true;
19632
+ return rights === "read" ? checkRecordAccess(record, "write", user) : false;
19633
+ }
19634
+
19466
19635
  // src/exulu/litellm/passthrough-allowlist.ts
19467
19636
  var isLiteLLMPassthroughPathAllowed = (path) => path.startsWith("/v1/") || path === "/model/info";
19468
19637
 
@@ -19621,8 +19790,8 @@ var settleWithin = async (tasks, ms) => {
19621
19790
  try {
19622
19791
  return await Promise.race([
19623
19792
  Promise.allSettled(tasks),
19624
- new Promise((resolve3) => {
19625
- timer3 = setTimeout(() => resolve3(null), ms);
19793
+ new Promise((resolve4) => {
19794
+ timer3 = setTimeout(() => resolve4(null), ms);
19626
19795
  })
19627
19796
  ]);
19628
19797
  } finally {
@@ -20470,7 +20639,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
20470
20639
  inputs: payload
20471
20640
  };
20472
20641
  await queue.queue.add("email-intake", jobData, {
20473
- jobId: randomUUID9(),
20642
+ jobId: randomUUID10(),
20474
20643
  attempts: 3,
20475
20644
  removeOnComplete: 5e3,
20476
20645
  removeOnFail: 1e4,
@@ -20878,7 +21047,7 @@ ${customInstructions}` : agent.instructions,
20878
21047
  contextId: agent.memory,
20879
21048
  agentId: agent.id,
20880
21049
  session: headers.session ?? null,
20881
- messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID9(),
21050
+ messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID10(),
20882
21051
  userId: user?.id ?? null
20883
21052
  });
20884
21053
  }
@@ -21480,17 +21649,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21480
21649
  res.status(404).json({ detail: `Session ${sessionId} not found.` });
21481
21650
  return null;
21482
21651
  }
21483
- const sessionRbac = await RBACResolver(
21484
- db,
21485
- "agent_sessions",
21486
- session.id,
21487
- session.rights_mode || "private"
21488
- );
21489
- const allowed = await checkRecordAccess(
21490
- { ...session, RBAC: sessionRbac },
21491
- rights,
21492
- authResult.user
21493
- );
21652
+ const allowed = await hasSessionAccess(db, session, rights, authResult.user);
21494
21653
  if (!allowed) {
21495
21654
  res.status(403).json({ detail: `You don't have ${rights} access to this session.` });
21496
21655
  return null;
@@ -21518,7 +21677,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21518
21677
  }
21519
21678
  const rbac = await RBACResolver(
21520
21679
  db,
21521
- "platform_configurations",
21680
+ "platform_configuration",
21522
21681
  row.id,
21523
21682
  row.rights_mode || "private"
21524
21683
  );
@@ -21581,7 +21740,7 @@ ${outputSchemaInstructions(outputSchema)}` : baseInstructions;
21581
21740
  const keys = [];
21582
21741
  const revisedPrompts = [];
21583
21742
  for (const img of images) {
21584
- const filename = `${randomUUID9()}.${img.extension}`;
21743
+ const filename = `${randomUUID10()}.${img.extension}`;
21585
21744
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
21586
21745
  const fullKey = await uploadFile(
21587
21746
  img.buffer,
@@ -21869,7 +22028,7 @@ ${style.markdown}` : params.prompt;
21869
22028
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
21870
22029
  );
21871
22030
  const messageText2 = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
21872
- const messageId = randomUUID9();
22031
+ const messageId = randomUUID10();
21873
22032
  const uiMessage = {
21874
22033
  id: messageId,
21875
22034
  role: "system",
@@ -22966,7 +23125,7 @@ ${style.markdown}` : params.prompt;
22966
23125
  return;
22967
23126
  }
22968
23127
  const meta = await parseSkillFrontmatter(bytes);
22969
- const skillId = randomUUID9();
23128
+ const skillId = randomUUID10();
22970
23129
  try {
22971
23130
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
22972
23131
  } catch (err2) {
@@ -23089,7 +23248,7 @@ ${style.markdown}` : params.prompt;
23089
23248
  return;
23090
23249
  }
23091
23250
  if (!await ensureSkillWrite(db, skill, authResult.user, res)) return;
23092
- const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID9()}${extension}`;
23251
+ const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID10()}${extension}`;
23093
23252
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
23094
23253
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
23095
23254
  res.json({ uploadUrl, stagingKey });
@@ -24183,6 +24342,39 @@ ${style.markdown}` : params.prompt;
24183
24342
  RBACResolver,
24184
24343
  checkRecordAccess
24185
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
+ });
24186
24378
  registerClaimCheckRoutes(app, {
24187
24379
  authenticate: (req) => requestValidators.authenticate(req),
24188
24380
  checkApiKeyScope,
@@ -24485,7 +24677,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
24485
24677
 
24486
24678
  // src/mcp/index.ts
24487
24679
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
24488
- import { randomUUID as randomUUID10 } from "crypto";
24680
+ import { randomUUID as randomUUID11 } from "crypto";
24489
24681
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
24490
24682
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
24491
24683
  import "express";
@@ -24579,7 +24771,7 @@ var ExuluMCP = class {
24579
24771
  throw new Error("Tool not found in converted tools array.");
24580
24772
  }
24581
24773
  const iterator = await convertedTool.execute(inputs, {
24582
- toolCallId: tool3.id + "_" + randomUUID10(),
24774
+ toolCallId: tool3.id + "_" + randomUUID11(),
24583
24775
  messages: []
24584
24776
  });
24585
24777
  let result;
@@ -24769,7 +24961,7 @@ var ExuluMCP = class {
24769
24961
  transport = this.transports[sessionId];
24770
24962
  } else if (!sessionId && isInitializeRequest(req.body)) {
24771
24963
  transport = new StreamableHTTPServerTransport({
24772
- sessionIdGenerator: () => randomUUID10(),
24964
+ sessionIdGenerator: () => randomUUID11(),
24773
24965
  onsessioninitialized: (sessionId2) => {
24774
24966
  this.transports[sessionId2] = transport;
24775
24967
  }
@@ -25350,7 +25542,7 @@ After asking a question, use the Question Read tool to check if the user has ans
25350
25542
 
25351
25543
  // src/templates/tools/question/question-ask.ts
25352
25544
  import z15 from "zod";
25353
- import { randomUUID as randomUUID11 } from "crypto";
25545
+ import { randomUUID as randomUUID12 } from "crypto";
25354
25546
  var AnswerOptionSchema = z15.object({
25355
25547
  id: z15.string().describe("Unique identifier for the answer option"),
25356
25548
  text: z15.string().describe("The text of the answer option")
@@ -25404,15 +25596,15 @@ var QuestionAskTool = new ExuluTool({
25404
25596
  throw new Error("You don't have access to this session " + session.id + ".");
25405
25597
  }
25406
25598
  const answerOptionsWithIds = answerOptions.map((text) => ({
25407
- id: randomUUID11(),
25599
+ id: randomUUID12(),
25408
25600
  text
25409
25601
  }));
25410
25602
  answerOptionsWithIds.push({
25411
- id: randomUUID11(),
25603
+ id: randomUUID12(),
25412
25604
  text: "None of the above..."
25413
25605
  });
25414
25606
  const newQuestion = {
25415
- id: randomUUID11(),
25607
+ id: randomUUID12(),
25416
25608
  question,
25417
25609
  answerOptions: answerOptionsWithIds,
25418
25610
  status: "pending"
@@ -25602,7 +25794,7 @@ var loadAvailableStyles = async (user) => {
25602
25794
  for (const row of rows) {
25603
25795
  const rbac = await RBACResolver(
25604
25796
  db,
25605
- "platform_configurations",
25797
+ "platform_configuration",
25606
25798
  row.id,
25607
25799
  row.rights_mode || "private"
25608
25800
  );
@@ -27701,8 +27893,8 @@ var execute = async ({ contexts }) => {
27701
27893
  };
27702
27894
 
27703
27895
  // src/exulu/litellm/db-init.ts
27704
- import { existsSync as existsSync4, readdirSync } from "fs";
27705
- import { resolve as resolve2 } from "path";
27896
+ import { existsSync as existsSync5, readdirSync } from "fs";
27897
+ import { resolve as resolve3 } from "path";
27706
27898
  import { spawnSync } from "child_process";
27707
27899
  import { Client } from "pg";
27708
27900
 
@@ -27759,6 +27951,67 @@ var checkLiteLLMDatabaseSafety = (configPath) => {
27759
27951
  return { ok: true, reason: "isolated", litellmTarget };
27760
27952
  };
27761
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
+
27762
28015
  // src/exulu/litellm/db-init.ts
27763
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";
27764
28017
  var warn2 = (lines) => {
@@ -27770,8 +28023,14 @@ ${WARNING_BANNER}`);
27770
28023
  `);
27771
28024
  };
27772
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
+ };
27773
28032
  var initLiteLLMDatabase = async (packageRoot) => {
27774
- 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");
27775
28034
  const safety = checkLiteLLMDatabaseSafety(configPath);
27776
28035
  if (safety.ok && safety.reason === "no-litellm-db-mode") return;
27777
28036
  if (!safety.ok && safety.reason === "unparseable-url") {
@@ -27909,10 +28168,10 @@ var initLiteLLMDatabase = async (packageRoot) => {
27909
28168
  ]);
27910
28169
  return;
27911
28170
  }
27912
- const venvBin = resolve2(packageRoot, "ee/python/.venv/bin");
27913
- const prismaCli = resolve2(venvBin, "prisma");
27914
- const venvLibDir = resolve2(packageRoot, "ee/python/.venv/lib");
27915
- 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;
27916
28175
  if (!pythonVersionDir) {
27917
28176
  warn2([
27918
28177
  `Could not find a python3.* directory under ${venvLibDir}.`,
@@ -27921,13 +28180,13 @@ var initLiteLLMDatabase = async (packageRoot) => {
27921
28180
  ]);
27922
28181
  return;
27923
28182
  }
27924
- const litellmProxyDir = resolve2(
28183
+ const litellmProxyDir = resolve3(
27925
28184
  venvLibDir,
27926
28185
  pythonVersionDir,
27927
28186
  "site-packages/litellm/proxy"
27928
28187
  );
27929
- const schemaPath = resolve2(litellmProxyDir, "schema.prisma");
27930
- if (!existsSync4(prismaCli)) {
28188
+ const schemaPath = resolve3(litellmProxyDir, "schema.prisma");
28189
+ if (!existsSync5(prismaCli)) {
27931
28190
  warn2([
27932
28191
  `Prisma CLI not found at ${prismaCli}.`,
27933
28192
  `Run \`npm run python:setup\` to create the venv and install prisma.`,
@@ -27935,13 +28194,45 @@ var initLiteLLMDatabase = async (packageRoot) => {
27935
28194
  ]);
27936
28195
  return;
27937
28196
  }
27938
- if (!existsSync4(schemaPath)) {
28197
+ if (!existsSync5(schemaPath)) {
27939
28198
  warn2([
27940
28199
  `LiteLLM Prisma schema not found at ${schemaPath}.`,
27941
28200
  `Re-run \`npm run python:setup\`. Skipping LiteLLM database setup.`
27942
28201
  ]);
27943
28202
  return;
27944
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
+ }
27945
28236
  log5("Running `prisma db push` against LiteLLM's schema\u2026");
27946
28237
  const result = spawnSync(prismaCli, ["db", "push", "--skip-generate"], {
27947
28238
  cwd: litellmProxyDir,
@@ -27958,9 +28249,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
27958
28249
  if (result.error) {
27959
28250
  warn2([
27960
28251
  `Failed to launch prisma: ${result.error.message}`,
27961
- `Skipping LiteLLM database setup.`
28252
+ `LiteLLM's database schema was NOT updated.`
27962
28253
  ]);
27963
- return;
28254
+ throw new LiteLLMSchemaPushError(
28255
+ `Could not launch prisma to update LiteLLM's database schema: ${result.error.message}`
28256
+ );
27964
28257
  }
27965
28258
  if (result.status !== 0) {
27966
28259
  warn2([
@@ -27968,9 +28261,16 @@ var initLiteLLMDatabase = async (packageRoot) => {
27968
28261
  `stdout:`,
27969
28262
  ...(result.stdout || "(empty)").split("\n").map((l) => ` ${l}`),
27970
28263
  `stderr:`,
27971
- ...(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.`
27972
28270
  ]);
27973
- 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
+ );
27974
28274
  }
27975
28275
  log5("\u2713 LiteLLM database ready.");
27976
28276
  };
@@ -28012,7 +28312,7 @@ var create = ({
28012
28312
  });
28013
28313
  const sdk = new NodeSDK({
28014
28314
  traceExporter,
28015
- logRecordProcessors: [new BatchLogRecordProcessor(logExporter)],
28315
+ logRecordProcessors: [new BatchLogRecordProcessor({ exporter: logExporter })],
28016
28316
  instrumentations: [getNodeAutoInstrumentations()],
28017
28317
  resource: resourceFromAttributes({
28018
28318
  [ATTR_SERVICE_NAME]: "Exulu"