@exulu/backend 5.22.0 → 5.24.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,7 +1,7 @@
1
1
  import "dotenv/config";
2
2
  import {
3
3
  documentProcessor
4
- } from "./chunk-Q4DFJFUI.js";
4
+ } from "./chunk-DAVYWGEE.js";
5
5
  import {
6
6
  getPackageRoot,
7
7
  getPythonSetupInstructions,
@@ -29,6 +29,7 @@ import {
29
29
  EDGE_LIMIT_DEFAULT,
30
30
  EDGE_LIMIT_MAX,
31
31
  EDGE_QUERY_TERMS,
32
+ EXTERNAL_SUPER_ADMIN_ONLY,
32
33
  ExuluContext,
33
34
  ExuluStorage,
34
35
  ExuluTokenizer,
@@ -138,6 +139,8 @@ import {
138
139
  estimateMessageTokens,
139
140
  estimateTokens,
140
141
  exchangeCodeForTokens,
142
+ externalAccessCheckApplies,
143
+ externalAccessNeedsTeams,
141
144
  extractClientInfo,
142
145
  extractDocument,
143
146
  exuluApp,
@@ -171,6 +174,7 @@ import {
171
174
  handleRBACUpdate,
172
175
  hasAgentsReadAccess,
173
176
  hasAgentsWriteAccess,
177
+ hasCompanionWriteGrant,
174
178
  hasProjectAccess,
175
179
  hashSharePassword,
176
180
  hydrateContextEmbedders,
@@ -190,11 +194,13 @@ import {
190
194
  loadSessionFileListing,
191
195
  mapStreamErrorMessage,
192
196
  mapType,
197
+ mayChangeExternalRelease,
193
198
  mayReadGenericS3Key,
194
199
  mayResignStoredFileKey,
195
200
  mayUseGenericS3Route,
196
201
  maybePruneJobResults,
197
202
  meanVector,
203
+ memoryPromptLine,
198
204
  microCall,
199
205
  microCallProviderOptions,
200
206
  normalizeLayout,
@@ -254,6 +260,7 @@ import {
254
260
  shouldShowSourcesToUser,
255
261
  sliceHistoryAtCheckpoint,
256
262
  slugifyShareName,
263
+ teamNamesByIds,
257
264
  treatAsGuest,
258
265
  truncateToolOutput,
259
266
  updateStatistic,
@@ -262,6 +269,8 @@ import {
262
269
  userIdOf,
263
270
  validateAttachmentsConfig,
264
271
  validateCreateInput,
272
+ validateExternalAccess,
273
+ validateExternalAccessUpdate,
265
274
  validateUpdateInput,
266
275
  vectorSearch,
267
276
  verifyCredentialNonce,
@@ -271,7 +280,7 @@ import {
271
280
  willEmbedOnQueue,
272
281
  withRunSession,
273
282
  workflowTemplatesSchema
274
- } from "./chunk-6OAYOFEY.js";
283
+ } from "./chunk-6HADZYCD.js";
275
284
  import {
276
285
  LITELLM_UI_PATH,
277
286
  ResolveModelError,
@@ -298,7 +307,7 @@ import {
298
307
  tagInfo,
299
308
  upsertBudget,
300
309
  waitForLiteLLMReady
301
- } from "./chunk-43QIPMLT.js";
310
+ } from "./chunk-BFIDSFRQ.js";
302
311
  import {
303
312
  findLiteLLMModel
304
313
  } from "./chunk-F534XOQR.js";
@@ -420,6 +429,151 @@ async function redisClient() {
420
429
  // src/exulu/app/index.ts
421
430
  import "express";
422
431
 
432
+ // src/exulu/companion/operation-guard.ts
433
+ import {
434
+ GraphQLError,
435
+ Kind
436
+ } from "graphql";
437
+ var companionAllowedOperations = (tables) => {
438
+ const allowed = /* @__PURE__ */ new Set();
439
+ for (const table of tables) {
440
+ const plural = table.name.plural.toLowerCase();
441
+ const singular = table.name.singular.toLowerCase();
442
+ allowed.add(`${plural}Pagination`);
443
+ allowed.add(`${singular}ById`);
444
+ allowed.add(`${plural}UpdateOneById`);
445
+ }
446
+ return allowed;
447
+ };
448
+ var fieldNamesOf = (operation, document) => {
449
+ const fragments = /* @__PURE__ */ new Map();
450
+ for (const def of document.definitions) {
451
+ if (def.kind === Kind.FRAGMENT_DEFINITION) fragments.set(def.name.value, def.selectionSet);
452
+ }
453
+ const names = [];
454
+ const seen = /* @__PURE__ */ new Set();
455
+ const walk = (set) => {
456
+ for (const selection of set.selections) {
457
+ if (selection.kind === Kind.FIELD) names.push(selection.name.value);
458
+ else if (selection.kind === Kind.INLINE_FRAGMENT) walk(selection.selectionSet);
459
+ else {
460
+ const name = selection.name.value;
461
+ const fragment = fragments.get(name);
462
+ if (fragment && !seen.has(name)) {
463
+ seen.add(name);
464
+ walk(fragment);
465
+ }
466
+ }
467
+ }
468
+ };
469
+ walk(operation.selectionSet);
470
+ return names;
471
+ };
472
+ var companionOperationGuard = (allowed) => ({
473
+ async requestDidStart() {
474
+ return {
475
+ async didResolveOperation({ contextValue, document, operation }) {
476
+ if (!contextValue?.user?.via_companion) return;
477
+ const names = operation ? fieldNamesOf(operation, document) : [];
478
+ const permitted = names.length > 0 && names.every((name) => name === "__typename" || allowed.has(name));
479
+ if (!permitted) {
480
+ throw new GraphQLError("This operation is not available through the companion server.", {
481
+ extensions: { code: "FORBIDDEN", http: { status: 403 } }
482
+ });
483
+ }
484
+ }
485
+ };
486
+ }
487
+ });
488
+
489
+ // src/exulu/companion/request.ts
490
+ import { timingSafeEqual } from "crypto";
491
+ import { GraphQLError as GraphQLError2 } from "graphql";
492
+
493
+ // src/exulu/external-rate-limit.ts
494
+ var MINUTE_MS = 6e4;
495
+ var HOUR_MS = 36e5;
496
+ var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
497
+ var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
498
+ var windows = /* @__PURE__ */ new Map();
499
+ var externalRateLimitExceeded = (userId, now = Date.now()) => {
500
+ const state = windows.get(userId) ?? {
501
+ minuteStart: now,
502
+ minuteCount: 0,
503
+ hourStart: now,
504
+ hourCount: 0,
505
+ lastSeen: now
506
+ };
507
+ if (now - state.minuteStart >= MINUTE_MS) {
508
+ state.minuteStart = now;
509
+ state.minuteCount = 0;
510
+ }
511
+ if (now - state.hourStart >= HOUR_MS) {
512
+ state.hourStart = now;
513
+ state.hourCount = 0;
514
+ }
515
+ state.minuteCount += 1;
516
+ state.hourCount += 1;
517
+ state.lastSeen = now;
518
+ windows.set(userId, state);
519
+ if (windows.size > 1e4) {
520
+ for (const [key, value] of windows) {
521
+ if (now - value.lastSeen >= HOUR_MS) windows.delete(key);
522
+ }
523
+ if (windows.size > 1e4) {
524
+ const sorted = [...windows.entries()].sort(
525
+ (a, b) => a[1].lastSeen - b[1].lastSeen
526
+ );
527
+ for (const [key] of sorted) {
528
+ if (windows.size <= 1e4) break;
529
+ windows.delete(key);
530
+ }
531
+ }
532
+ }
533
+ const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
534
+ const hourLimitExceeded = state.hourCount > perHourLimit();
535
+ const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
536
+ if (limitExceeded) {
537
+ const limits = {
538
+ perMinute: perMinuteLimit(),
539
+ perHour: perHourLimit()
540
+ };
541
+ const current = {
542
+ minute: state.minuteCount,
543
+ hour: state.hourCount
544
+ };
545
+ console.warn(
546
+ `[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
547
+ );
548
+ }
549
+ return limitExceeded;
550
+ };
551
+ var isExternalUser = (user) => {
552
+ return user?.role?.name === "external";
553
+ };
554
+
555
+ // src/exulu/companion/request.ts
556
+ var COMPANION_HEADER = "x-exulu-companion";
557
+ var companionRequestState = (headers, env = process.env) => {
558
+ const received = headers[COMPANION_HEADER];
559
+ if (received === void 0) return "absent";
560
+ const expected = env.EXULU_COMPANION_KEY;
561
+ if (typeof received !== "string" || received === "" || !expected) return "invalid";
562
+ const a = Buffer.from(received);
563
+ const b = Buffer.from(expected);
564
+ if (a.length !== b.length) return "invalid";
565
+ return timingSafeEqual(a, b) ? "valid" : "invalid";
566
+ };
567
+ var forbidden = (message) => new GraphQLError2(message, { extensions: { code: "FORBIDDEN", http: { status: 403 } } });
568
+ var admitCompanionUser = (state, user) => {
569
+ if (state === "absent") return user;
570
+ if (state === "invalid") throw forbidden("Companion key rejected.");
571
+ if (user.super_admin || !isExternalUser(user)) {
572
+ throw forbidden("This account cannot be used through the companion server.");
573
+ }
574
+ return { ...user, via_companion: true };
575
+ };
576
+
423
577
  // src/exulu/routes.ts
424
578
  import "express";
425
579
 
@@ -1006,7 +1160,7 @@ function createQueueMutationResolvers(deps) {
1006
1160
  import { v4 as uuidv43 } from "uuid";
1007
1161
 
1008
1162
  // src/graphql/types/index.ts
1009
- import { GraphQLScalarType, Kind } from "graphql";
1163
+ import { GraphQLScalarType, Kind as Kind2 } from "graphql";
1010
1164
  var GraphQLDate = new GraphQLScalarType({
1011
1165
  name: "Date",
1012
1166
  description: "Date custom scalar type",
@@ -1032,10 +1186,10 @@ var GraphQLDate = new GraphQLScalarType({
1032
1186
  return value;
1033
1187
  },
1034
1188
  parseLiteral(ast) {
1035
- if (ast.kind === Kind.STRING) {
1189
+ if (ast.kind === Kind2.STRING) {
1036
1190
  return new Date(ast.value);
1037
1191
  }
1038
- if (ast.kind === Kind.INT) {
1192
+ if (ast.kind === Kind2.INT) {
1039
1193
  return new Date(parseInt(ast.value, 10));
1040
1194
  }
1041
1195
  return null;
@@ -1107,6 +1261,12 @@ var contextItemsProcessorHandler = async (context, config, items, user, role) =>
1107
1261
  };
1108
1262
  };
1109
1263
 
1264
+ // src/graphql/schemas/rbac-field.ts
1265
+ var resolveRbacField = async (table, parent, context) => {
1266
+ if (context.user?.via_companion === true) return null;
1267
+ return RBACResolver(context.db, table.name.singular, parent.id, parent.rights_mode);
1268
+ };
1269
+
1110
1270
  // src/graphql/utilities/provider-fields.ts
1111
1271
  var exuluProviderFields = [
1112
1272
  "providerName",
@@ -4272,6 +4432,12 @@ function createMutations(table, contexts, tools, config) {
4272
4432
  const validateWriteAccess = async (id, context) => {
4273
4433
  try {
4274
4434
  const { db, user } = context;
4435
+ if (user.via_companion === true) {
4436
+ const row = table.RBAC === true ? await db.from(tableNamePlural).select(["rights_mode"]).where({ id }).first() : void 0;
4437
+ const grant = !!row && await hasCompanionWriteGrant(db, table.name.singular, id, user, row.rights_mode);
4438
+ if (grant) return true;
4439
+ throw new Error("Insufficient permissions to edit this record");
4440
+ }
4275
4441
  if (user.super_admin === true) {
4276
4442
  return true;
4277
4443
  }
@@ -4622,6 +4788,14 @@ function createMutations(table, contexts, tools, config) {
4622
4788
  [`${tableNamePlural}UpdateOneById`]: async (_, args, context, info) => {
4623
4789
  const { db, req } = context;
4624
4790
  let { id, input } = args;
4791
+ if (context.user?.via_companion === true && ["rights_mode", "RBAC", "created_by", "id"].some(
4792
+ (key) => Object.prototype.hasOwnProperty.call(input ?? {}, key)
4793
+ )) {
4794
+ throw new Error("Access rights of a row cannot be changed through the companion server.");
4795
+ }
4796
+ if (context.user?.via_companion === true && args.generateEmbeddings === true) {
4797
+ throw new Error("Embedding generation cannot be requested through the companion server.");
4798
+ }
4625
4799
  await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
4626
4800
  await validateWriteAccess(id, context);
4627
4801
  if (table.type === "items") {
@@ -5838,6 +6012,7 @@ function previousUserTexts(messages) {
5838
6012
  }
5839
6013
 
5840
6014
  // src/exulu/memory/recall.ts
6015
+ var FOLLOW_UP_MAX_NEW = 5;
5841
6016
  var EMPTY3 = { collector: void 0, memoryItems: void 0, promptBlock: "" };
5842
6017
  async function recallMemories({ agent, contexts, query, user, db, previousUserTurns }) {
5843
6018
  if (!agent?.memory || !query) return { ...EMPTY3 };
@@ -5849,29 +6024,110 @@ async function recallMemories({ agent, contexts, query, user, db, previousUserTu
5849
6024
  const config = resolveMemoryConfig(agent.memory_config);
5850
6025
  const collector = createRecallCollector(context, user, db);
5851
6026
  if (!config.retrieval.enabled) return { collector, memoryItems: void 0, promptBlock: "" };
6027
+ const search = (text) => context.search({
6028
+ query: text,
6029
+ itemFilters: [],
6030
+ chunkFilters: [],
6031
+ method: "hybridSearch",
6032
+ sort: { field: "updatedAt", direction: "desc" },
6033
+ trigger: "agent",
6034
+ limit: config.retrieval.limit,
6035
+ page: 1,
6036
+ user,
6037
+ role: user?.role?.id
6038
+ });
6039
+ const memoryItems = [];
6040
+ const followUp = async (text) => {
6041
+ const q = (text ?? "").trim().slice(0, MAX_QUERY_CHARS);
6042
+ if (!q) return [];
6043
+ try {
6044
+ const known = new Set(collector.list().map((m) => m.id));
6045
+ const freshIds = /* @__PURE__ */ new Set();
6046
+ const fresh = ((await search(q))?.chunks ?? []).filter((c) => {
6047
+ if (!c.item_id || known.has(c.item_id)) return false;
6048
+ if (!freshIds.has(c.item_id) && freshIds.size >= FOLLOW_UP_MAX_NEW) return false;
6049
+ freshIds.add(c.item_id);
6050
+ return true;
6051
+ });
6052
+ if (fresh.length === 0) return [];
6053
+ await collector.addFromChunks(fresh, "follow_up");
6054
+ const added = collector.list().filter((m) => !known.has(m.id));
6055
+ const addedIds = new Set(added.map((m) => m.id));
6056
+ memoryItems.push(...fresh.filter((c) => addedIds.has(c.item_id)));
6057
+ return added;
6058
+ } catch (e) {
6059
+ console.warn(`[EXULU] memory: follow-up recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
6060
+ return [];
6061
+ }
6062
+ };
5852
6063
  let result;
5853
6064
  try {
5854
- result = await context.search({
5855
- query: buildRecallQuery(query, previousUserTurns ?? []),
5856
- itemFilters: [],
5857
- chunkFilters: [],
5858
- method: "hybridSearch",
5859
- sort: { field: "updatedAt", direction: "desc" },
5860
- trigger: "agent",
5861
- limit: config.retrieval.limit,
5862
- page: 1,
5863
- user,
5864
- role: user?.role?.id
5865
- });
6065
+ result = await search(buildRecallQuery(query, previousUserTurns ?? []));
5866
6066
  } catch (e) {
5867
6067
  console.warn(`[EXULU] memory: recall failed for context "${context.id}"`, e instanceof Error ? e.message : e);
5868
- return { collector, memoryItems: void 0, promptBlock: "" };
6068
+ return { collector, memoryItems, promptBlock: "", followUp };
5869
6069
  }
5870
6070
  const chunks = result?.chunks ?? [];
5871
- if (chunks.length === 0) return { collector, memoryItems: void 0, promptBlock: "" };
6071
+ if (chunks.length === 0) return { collector, memoryItems, promptBlock: "", followUp };
5872
6072
  await collector.addFromChunks(chunks, "prefetch");
5873
- return { collector, memoryItems: chunks, promptBlock: buildMemoryPromptBlock(collector.list()) };
6073
+ memoryItems.push(...chunks);
6074
+ return { collector, memoryItems, promptBlock: buildMemoryPromptBlock(collector.list()), followUp };
6075
+ }
6076
+
6077
+ // src/exulu/memory/recall-step.ts
6078
+ var MAX_FOLLOW_UP_RECALLS = 4;
6079
+ var MAX_VALUE_CHARS = 200;
6080
+ function memoryRecallStep(recall, system) {
6081
+ if (!recall.followUp) return () => void 0;
6082
+ const followUp = recall.followUp;
6083
+ const found = [];
6084
+ const asked = /* @__PURE__ */ new Set();
6085
+ let lastStepSeen = 0;
6086
+ return async ({ steps }) => {
6087
+ const all = steps ?? [];
6088
+ for (let i = lastStepSeen; i < all.length; i++) {
6089
+ if (asked.size >= MAX_FOLLOW_UP_RECALLS) break;
6090
+ const query = toolCallQuery(all[i]?.toolCalls);
6091
+ if (!query || asked.has(query.toLowerCase())) continue;
6092
+ asked.add(query.toLowerCase());
6093
+ found.push(...await followUp(query));
6094
+ }
6095
+ lastStepSeen = all.length;
6096
+ return found.length > 0 ? { system: system + "\n\n" + buildFollowUpBlock(found) } : void 0;
6097
+ };
6098
+ }
6099
+ function buildFollowUpBlock(memories) {
6100
+ return [
6101
+ "More memories, found for what you looked up while working on this answer. They count like the memories above:",
6102
+ "use them where relevant, cite them the same way, and where one of them corrects or narrows another memory for the",
6103
+ "exact product or case at hand, follow the more specific one.",
6104
+ ...memories.map(memoryPromptLine)
6105
+ ].join("\n");
6106
+ }
6107
+ function toolCallQuery(toolCalls) {
6108
+ const words = [];
6109
+ const seen = /* @__PURE__ */ new Set();
6110
+ const add = (value) => {
6111
+ const v = value.trim();
6112
+ if (v.length < 2 || v.length > MAX_VALUE_CHARS || v.includes("\n")) return;
6113
+ if (UUID.test(v) || PATH.test(v)) return;
6114
+ for (const w of v.split(/\s+/)) {
6115
+ const key = w.toLowerCase();
6116
+ if (!w || seen.has(key)) continue;
6117
+ seen.add(key);
6118
+ words.push(w);
6119
+ }
6120
+ };
6121
+ const walk = (value, depth) => {
6122
+ if (typeof value === "string") add(value);
6123
+ else if (depth < 3 && Array.isArray(value)) value.forEach((v) => walk(v, depth + 1));
6124
+ else if (depth < 3 && value && typeof value === "object") Object.values(value).forEach((v) => walk(v, depth + 1));
6125
+ };
6126
+ for (const call of toolCalls ?? []) walk(call?.input, 0);
6127
+ return words.join(" ").slice(0, MAX_QUERY_CHARS).trim();
5874
6128
  }
6129
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6130
+ var PATH = /^\S*\/\S*$|^\S+\.[a-z0-9]{1,5}$/i;
5875
6131
 
5876
6132
  // src/exulu/message-language.ts
5877
6133
  import { francAll } from "franc";
@@ -6560,7 +6816,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
6560
6816
  // Stop after the image_generation tool fires — the widget IS the
6561
6817
  // assistant's response, no follow-up text turn is wanted (same
6562
6818
  // reasoning as question_ask: the UI artifact is the message).
6563
- prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
6819
+ prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
6564
6820
  stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
6565
6821
  });
6566
6822
  console.log("[EXULU] Output: " + JSON.stringify(output, null, 2));
@@ -6639,7 +6895,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
6639
6895
  }),
6640
6896
  maxRetries: 2,
6641
6897
  tools,
6642
- prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
6898
+ prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
6643
6899
  stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
6644
6900
  });
6645
6901
  if (statistics) {
@@ -7008,7 +7264,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
7008
7264
  // Log only — throwing here crashed the process (see stream-error.ts).
7009
7265
  onError: onChatStreamError,
7010
7266
  // todo allow configuring the step budget per skill
7011
- prepareStep: composePrepareSteps(contextGuard(contextWindow), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
7267
+ prepareStep: composePrepareSteps(contextGuard(contextWindow), memoryRecallStep(memoryRecall, system), retrievalGuard, finalAnswerGuard(turnBudget), imageAttachmentGuard()),
7012
7268
  stopWhen: [stepCountIs(turnBudget), hasToolCall("image_generation")]
7013
7269
  });
7014
7270
  return {
@@ -7411,7 +7667,7 @@ var DEFAULT_SENDER_RATE_LIMIT_PER_HOUR = 10;
7411
7667
  var DEFAULT_FILTERED_RUN_RETENTION = 200;
7412
7668
  var FILTER_BODY_BYTE_CAP = 10 * 1024;
7413
7669
  var AUTO_REPLY_PRECEDENCE = /* @__PURE__ */ new Set(["bulk", "junk", "list"]);
7414
- var HOUR_MS = 60 * 60 * 1e3;
7670
+ var HOUR_MS2 = 60 * 60 * 1e3;
7415
7671
  var isAutoReply = (email) => {
7416
7672
  const autoSubmitted = email.headers.get("auto-submitted");
7417
7673
  if (autoSubmitted !== void 0 && autoSubmitted.trim().toLowerCase() !== "no") {
@@ -7443,7 +7699,7 @@ var senderAllowed = (address, allowedSenders) => {
7443
7699
  var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
7444
7700
  if (!redis) return true;
7445
7701
  try {
7446
- const currentBucket = Math.floor(now / HOUR_MS);
7702
+ const currentBucket = Math.floor(now / HOUR_MS2);
7447
7703
  const currentKey = `${key}:${currentBucket}`;
7448
7704
  const previousKey = `${key}:${currentBucket - 1}`;
7449
7705
  const count2 = await redis.incr(currentKey);
@@ -7452,7 +7708,7 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
7452
7708
  }
7453
7709
  const previousRaw = await redis.get(previousKey);
7454
7710
  const previous = previousRaw ? Number(previousRaw) : 0;
7455
- const elapsedFraction = now % HOUR_MS / HOUR_MS;
7711
+ const elapsedFraction = now % HOUR_MS2 / HOUR_MS2;
7456
7712
  const weighted = count2 + previous * (1 - elapsedFraction);
7457
7713
  return weighted <= limitPerHour;
7458
7714
  } catch (err2) {
@@ -8424,68 +8680,6 @@ var createRunLock = (redis) => ({
8424
8680
  }
8425
8681
  });
8426
8682
 
8427
- // src/exulu/external-rate-limit.ts
8428
- var MINUTE_MS = 6e4;
8429
- var HOUR_MS2 = 36e5;
8430
- var perMinuteLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_MINUTE || "30", 10);
8431
- var perHourLimit = () => parseInt(process.env.EXULU_EXTERNAL_RATE_PER_HOUR || "300", 10);
8432
- var windows = /* @__PURE__ */ new Map();
8433
- var externalRateLimitExceeded = (userId, now = Date.now()) => {
8434
- const state = windows.get(userId) ?? {
8435
- minuteStart: now,
8436
- minuteCount: 0,
8437
- hourStart: now,
8438
- hourCount: 0,
8439
- lastSeen: now
8440
- };
8441
- if (now - state.minuteStart >= MINUTE_MS) {
8442
- state.minuteStart = now;
8443
- state.minuteCount = 0;
8444
- }
8445
- if (now - state.hourStart >= HOUR_MS2) {
8446
- state.hourStart = now;
8447
- state.hourCount = 0;
8448
- }
8449
- state.minuteCount += 1;
8450
- state.hourCount += 1;
8451
- state.lastSeen = now;
8452
- windows.set(userId, state);
8453
- if (windows.size > 1e4) {
8454
- for (const [key, value] of windows) {
8455
- if (now - value.lastSeen >= HOUR_MS2) windows.delete(key);
8456
- }
8457
- if (windows.size > 1e4) {
8458
- const sorted = [...windows.entries()].sort(
8459
- (a, b) => a[1].lastSeen - b[1].lastSeen
8460
- );
8461
- for (const [key] of sorted) {
8462
- if (windows.size <= 1e4) break;
8463
- windows.delete(key);
8464
- }
8465
- }
8466
- }
8467
- const minuteLimitExceeded = state.minuteCount > perMinuteLimit();
8468
- const hourLimitExceeded = state.hourCount > perHourLimit();
8469
- const limitExceeded = minuteLimitExceeded || hourLimitExceeded;
8470
- if (limitExceeded) {
8471
- const limits = {
8472
- perMinute: perMinuteLimit(),
8473
- perHour: perHourLimit()
8474
- };
8475
- const current = {
8476
- minute: state.minuteCount,
8477
- hour: state.hourCount
8478
- };
8479
- console.warn(
8480
- `[EXULU] Rate limit exceeded for user ${userId}${minuteLimitExceeded ? ` per-minute (${current.minute}/${limits.perMinute})` : ""}${minuteLimitExceeded && hourLimitExceeded ? " and" : ""}${hourLimitExceeded ? ` per-hour (${current.hour}/${limits.perHour})` : ""}`
8481
- );
8482
- }
8483
- return limitExceeded;
8484
- };
8485
- var isExternalUser = (user) => {
8486
- return user?.role?.name === "external";
8487
- };
8488
-
8489
8683
  // src/exulu/channels/wiring.ts
8490
8684
  var channelStoreFromRedis = (client2) => ({
8491
8685
  set: (key, value, opts) => client2.set(key, value, opts.NX ? { EX: opts.EX, NX: true } : { EX: opts.EX }),
@@ -10429,6 +10623,18 @@ var processUiMessagesFlow = async ({
10429
10623
  },
10430
10624
  onFinish: async ({ messages }) => {
10431
10625
  const metadata = messages[messages.length - 1]?.metadata;
10626
+ if (agent.memory && messages[messages.length - 1]?.id) {
10627
+ const { db: usageDb } = await postgresClient();
10628
+ await recordMemoryUsage({
10629
+ db: usageDb,
10630
+ recall: result.recall,
10631
+ contextId: agent.memory,
10632
+ agentId: agent.id,
10633
+ session: sessionId ?? null,
10634
+ messageId: messages[messages.length - 1].id,
10635
+ userId: typeof user?.id === "number" ? user.id : null
10636
+ });
10637
+ }
10432
10638
  console.log("[EXULU] Stream finished with messages:", messages);
10433
10639
  console.log("[EXULU] Stream metadata", metadata);
10434
10640
  await Promise.all([
@@ -12330,7 +12536,7 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
12330
12536
  import { randomUUID as randomUUID5 } from "crypto";
12331
12537
 
12332
12538
  // src/exulu/email-inbound/verify-signature.ts
12333
- import { createHmac, timingSafeEqual } from "crypto";
12539
+ import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
12334
12540
  var SIGNATURE_REPLAY_WINDOW_SECONDS = 300;
12335
12541
  var REPLAY_TTL_SECONDS = 900;
12336
12542
  function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secret) {
@@ -12343,7 +12549,7 @@ function verifyPayloadSignature(rawBody, signatureHeader, timestampHeader, secre
12343
12549
  const expectedBuf = Buffer.from(expected, "utf8");
12344
12550
  const providedBuf = Buffer.from(provided.toLowerCase(), "utf8");
12345
12551
  if (expectedBuf.length !== providedBuf.length) return false;
12346
- return timingSafeEqual(expectedBuf, providedBuf);
12552
+ return timingSafeEqual2(expectedBuf, providedBuf);
12347
12553
  }
12348
12554
  async function isReplay(redis, signature, timestamp) {
12349
12555
  const ts = Number(timestamp);
@@ -12745,7 +12951,7 @@ var epochMs = (d) => {
12745
12951
  const date = d instanceof Date ? d : typeof d === "string" || typeof d === "number" ? new Date(d) : null;
12746
12952
  return date && Number.isFinite(date.getTime()) ? date.getTime() : null;
12747
12953
  };
12748
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12954
+ var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12749
12955
  var clamp = (limit, fallback, max) => {
12750
12956
  const asked = limit == null ? NaN : Number(limit);
12751
12957
  return Math.max(1, Math.min(Number.isFinite(asked) ? asked : fallback, max));
@@ -12874,7 +13080,7 @@ async function contextMapItem({
12874
13080
  user,
12875
13081
  itemId
12876
13082
  }) {
12877
- if (!UUID.test(itemId)) return null;
13083
+ if (!UUID2.test(itemId)) return null;
12878
13084
  const items = getTableName(context.id);
12879
13085
  const table = convertContextToTableDefinition(context);
12880
13086
  let q = db(`${items} as items`).where("items.id", itemId).whereRaw("items.archived IS NOT TRUE");
@@ -12913,7 +13119,7 @@ async function contextMapEdges({
12913
13119
  mode = "DOCUMENTS",
12914
13120
  limit
12915
13121
  }) {
12916
- if (!UUID.test(String(nodeId ?? ""))) return [];
13122
+ if (!UUID2.test(String(nodeId ?? ""))) return [];
12917
13123
  const chunks = getChunksTableName(context.id);
12918
13124
  const items = getTableName(context.id);
12919
13125
  if (!await db.schema.hasTable(chunks)) return [];
@@ -14247,13 +14453,7 @@ type PageInfo {
14247
14453
  if (!resolvers[rbacResolverName]) {
14248
14454
  resolvers[rbacResolverName] = {};
14249
14455
  }
14250
- resolvers[rbacResolverName].RBAC = async (parent, args, context) => {
14251
- const { db } = context;
14252
- const resourceId = parent.id;
14253
- const entityName = table.name.singular;
14254
- const rights_mode = parent.rights_mode;
14255
- return RBACResolver(db, entityName, resourceId, rights_mode);
14256
- };
14456
+ resolvers[rbacResolverName].RBAC = async (parent, args, context) => resolveRbacField(table, parent, context);
14257
14457
  }
14258
14458
  }
14259
14459
  typeDefs += `
@@ -17752,6 +17952,133 @@ function registerViewerIdentityRoutes(app, deps) {
17752
17952
  });
17753
17953
  }
17754
17954
 
17955
+ // src/exulu/companion/external-share-route.ts
17956
+ var SHARED_ARTIFACT_EXTERNAL_PATH = "/shared-artifacts/:name/external";
17957
+ function registerExternalShareRoute(app, deps) {
17958
+ app.get(SHARED_ARTIFACT_EXTERNAL_PATH, async (req, res) => {
17959
+ const notFound = () => res.status(404).json({ detail: "Not found." });
17960
+ try {
17961
+ if (companionRequestState(req.headers, deps.env ?? process.env) !== "valid") {
17962
+ notFound();
17963
+ return;
17964
+ }
17965
+ const db = await deps.getDb();
17966
+ const row = await getSharedArtifactByName(db, req.params.name ?? "");
17967
+ if (!row || isExpired(row.expires_at, /* @__PURE__ */ new Date()) || row.auth_mode !== "regular" || row.external_access !== true) {
17968
+ notFound();
17969
+ return;
17970
+ }
17971
+ const grants = await db("rbac").where({ entity: "shared_artifact", target_resource_id: row.id, access_type: "Team" }).select("team_id");
17972
+ const teams = await teamNamesByIds(db, grants.map((g) => g.team_id));
17973
+ if (validateExternalAccess({
17974
+ external_access: true,
17975
+ auth_mode: row.auth_mode,
17976
+ rights_mode: row.rights_mode,
17977
+ teams
17978
+ }) !== null) {
17979
+ notFound();
17980
+ return;
17981
+ }
17982
+ res.status(204).end();
17983
+ } catch (e) {
17984
+ console.error("[EXULU] companion external check failed", e);
17985
+ notFound();
17986
+ }
17987
+ });
17988
+ }
17989
+
17990
+ // src/exulu/companion/status.ts
17991
+ var HEALTH_TIMEOUT_MS = 5e3;
17992
+ var CACHE_TTL_MS = 3e4;
17993
+ var VERSION_RE = /^[\w.+-]{1,32}$/;
17994
+ var HOST_RE = /^[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?(:\d{1,5})?$/;
17995
+ var checkCompanion = async (deps) => {
17996
+ const host = deps.env.EXULU_COMPANION_HOST;
17997
+ const key = deps.env.EXULU_COMPANION_KEY;
17998
+ if (!host || !key || !HOST_RE.test(host)) return { state: "not_configured" };
17999
+ const checkedAt = deps.now().toISOString();
18000
+ const unreachable = { state: "unreachable", host, checkedAt };
18001
+ try {
18002
+ const res = await deps.fetch(`https://${host}/_companion/health`, {
18003
+ method: "GET",
18004
+ headers: { [COMPANION_HEADER]: key },
18005
+ redirect: "error",
18006
+ signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS)
18007
+ });
18008
+ if (res.status !== 200) return unreachable;
18009
+ const body = await res.json();
18010
+ if (!body || typeof body !== "object" || typeof body.version !== "string" || !VERSION_RE.test(body.version) || typeof body.upstream !== "boolean") {
18011
+ return unreachable;
18012
+ }
18013
+ const { version, upstream } = body;
18014
+ if (version.includes(key)) return unreachable;
18015
+ return { state: upstream ? "connected" : "no_tunnel", host, version, checkedAt };
18016
+ } catch {
18017
+ return unreachable;
18018
+ }
18019
+ };
18020
+ var createCompanionStatusCache = (deps) => {
18021
+ let cached = null;
18022
+ return {
18023
+ get: async (refresh = false) => {
18024
+ const t = deps.now().getTime();
18025
+ if (!refresh && cached && t - cached.at < CACHE_TTL_MS && t >= cached.at) return cached.value;
18026
+ const value = await checkCompanion(deps);
18027
+ cached = { at: t, value };
18028
+ return value;
18029
+ }
18030
+ };
18031
+ };
18032
+ var cachedCompanionStatus = createCompanionStatusCache({
18033
+ env: process.env,
18034
+ fetch: globalThis.fetch,
18035
+ now: () => /* @__PURE__ */ new Date()
18036
+ });
18037
+
18038
+ // src/exulu/companion/status-routes.ts
18039
+ function registerCompanionStatusRoutes(app, deps) {
18040
+ const status = deps.status ?? cachedCompanionStatus;
18041
+ const requireSuperAdmin = async (req, res) => {
18042
+ const auth = await deps.authenticate(req);
18043
+ if (!auth.user?.id) {
18044
+ res.status(auth.code ?? 401).json({ detail: auth.message });
18045
+ return false;
18046
+ }
18047
+ if (auth.user.super_admin !== true) {
18048
+ res.status(403).json({ detail: "Only a super admin can view the companion server." });
18049
+ return false;
18050
+ }
18051
+ return true;
18052
+ };
18053
+ app.get("/companion/status", async (req, res) => {
18054
+ if (!await requireSuperAdmin(req, res)) return;
18055
+ res.json(await status.get(req.query.refresh === "1"));
18056
+ });
18057
+ app.get("/companion/released", async (req, res) => {
18058
+ if (!await requireSuperAdmin(req, res)) return;
18059
+ try {
18060
+ const db = await deps.getDb();
18061
+ const shares = await db("shared_artifacts").where({ external_access: true }).select("id", "name");
18062
+ const grants = shares.length ? await db("rbac").where({ entity: "shared_artifact", access_type: "Team" }).whereIn("target_resource_id", shares.map((s) => s.id)).select("target_resource_id", "team_id") : [];
18063
+ const teamIds = [...new Set(grants.map((g) => g.team_id).filter(Boolean))];
18064
+ const teams = teamIds.length ? await db("teams").whereIn("id", teamIds).select("id", "name") : [];
18065
+ const users = teamIds.length ? await db("users").where({ type: "external" }).whereIn("team", teamIds).select("team") : [];
18066
+ const counts = /* @__PURE__ */ new Map();
18067
+ for (const u of users) counts.set(u.team, (counts.get(u.team) ?? 0) + 1);
18068
+ const teamName = new Map(teams.map((t) => [t.id, t.name]));
18069
+ res.json({
18070
+ items: shares.map((s) => ({
18071
+ name: s.name,
18072
+ teams: [...new Set(grants.filter((g) => g.target_resource_id === s.id).map((g) => g.team_id))].filter((id) => teamName.has(id)).map((id) => ({ id, name: teamName.get(id), users: counts.get(id) ?? 0 }))
18073
+ }))
18074
+ });
18075
+ } catch (e) {
18076
+ console.error("[EXULU] companion released listing failed", e);
18077
+ res.status(500).json({ detail: "Failed to list released artifacts." });
18078
+ }
18079
+ });
18080
+ }
18081
+
17755
18082
  // src/exulu/tool-api-route.ts
17756
18083
  import { randomUUID as randomUUID9 } from "crypto";
17757
18084
  var TOOL_API_ROUTE_PATH = "/tools/:id";
@@ -17868,6 +18195,23 @@ function registerCreateShareRoute(app, deps) {
17868
18195
  res.status(400).json({ detail: valid.message });
17869
18196
  return;
17870
18197
  }
18198
+ if (!mayChangeExternalRelease(auth.user, req.body.external_access, false)) {
18199
+ res.status(403).json({ detail: EXTERNAL_SUPER_ADMIN_ONLY });
18200
+ return;
18201
+ }
18202
+ if (req.body.external_access !== void 0) {
18203
+ const teamIds = req.body.external_access === true && Array.isArray(req.body.rbac?.teams) ? req.body.rbac.teams.map((t) => t?.id) : [];
18204
+ const externalError = validateExternalAccess({
18205
+ external_access: req.body.external_access,
18206
+ auth_mode: req.body.auth_mode,
18207
+ rights_mode: req.body.rights_mode ?? "private",
18208
+ teams: await teamNamesByIds(db, teamIds)
18209
+ });
18210
+ if (externalError) {
18211
+ res.status(400).json({ detail: externalError });
18212
+ return;
18213
+ }
18214
+ }
17871
18215
  const details = planDetails({ ...req.body, archived: void 0 }, now);
17872
18216
  if (!details.ok) {
17873
18217
  res.status(400).json({ detail: details.message });
@@ -17898,6 +18242,7 @@ function registerCreateShareRoute(app, deps) {
17898
18242
  password_hash,
17899
18243
  expires_at: req.body.expires_at ?? null,
17900
18244
  content_type: req.body.content_type ?? null,
18245
+ external_access: req.body.external_access === true,
17901
18246
  rights_mode,
17902
18247
  created_by: auth.user.id,
17903
18248
  ...details.patch,
@@ -20290,7 +20635,7 @@ import multer from "multer";
20290
20635
  // src/exulu/channels/webhook.ts
20291
20636
  var WEBHOOK_BACKGROUND_WAIT_MS = 8e3;
20292
20637
  var LOG_PREFIX3 = "[EXULU-CHANNEL]";
20293
- var UUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20638
+ var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20294
20639
  var RATE_WINDOW_MS2 = 6e4;
20295
20640
  var RATE_MAX_REQUESTS2 = 300;
20296
20641
  var rateWindowStart2 = 0;
@@ -20348,7 +20693,7 @@ var createChannelWebhookHandler = (deps) => async (req, res) => {
20348
20693
  return;
20349
20694
  }
20350
20695
  const channelId = String(req.params?.channelId ?? "");
20351
- if (!UUID2.test(channelId)) {
20696
+ if (!UUID3.test(channelId)) {
20352
20697
  res.status(404).json({ detail: "not found" });
20353
20698
  return;
20354
20699
  }
@@ -20620,7 +20965,7 @@ var handleCredentialDelete = async (req, res) => {
20620
20965
  };
20621
20966
 
20622
20967
  // src/exulu/recall/verify.ts
20623
- import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual2 } from "crypto";
20968
+ import { createHmac as createHmac2, timingSafeEqual as timingSafeEqual3 } from "crypto";
20624
20969
  var TOLERANCE_SECONDS = 5 * 60;
20625
20970
  var header = (headers, ...names) => {
20626
20971
  for (const name of names) {
@@ -20638,7 +20983,7 @@ var safeEqual = (a, b) => {
20638
20983
  const bufA = Buffer.from(a);
20639
20984
  const bufB = Buffer.from(b);
20640
20985
  if (bufA.length !== bufB.length) return false;
20641
- return timingSafeEqual2(bufA, bufB);
20986
+ return timingSafeEqual3(bufA, bufB);
20642
20987
  };
20643
20988
  var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()) => {
20644
20989
  if (!secret) {
@@ -21017,7 +21362,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
21017
21362
  const server = new ApolloServer({
21018
21363
  cache: new InMemoryLRUCache(),
21019
21364
  schema: schema7,
21020
- introspection: true
21365
+ introspection: true,
21366
+ plugins: [
21367
+ companionOperationGuard(
21368
+ companionAllowedOperations((contexts ?? []).map(convertContextToTableDefinition))
21369
+ )
21370
+ ]
21021
21371
  });
21022
21372
  await server.start();
21023
21373
  app.use(
@@ -21036,7 +21386,10 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
21036
21386
  return {
21037
21387
  req,
21038
21388
  db,
21039
- user: authenticationResult.user
21389
+ user: admitCompanionUser(
21390
+ companionRequestState(req.headers),
21391
+ authenticationResult.user
21392
+ )
21040
21393
  };
21041
21394
  }
21042
21395
  })
@@ -24783,6 +25136,7 @@ ${style.markdown}` : params.prompt;
24783
25136
  // Coerced, not `?? []`: see readAgentSlots on why a stored non-array is
24784
25137
  // a real possibility and why a reader has to survive one.
24785
25138
  agent_slots: readAgentSlots(row.agent_slots),
25139
+ external_access: row.external_access === true,
24786
25140
  ...detailsOf(row),
24787
25141
  // Older files, newest first; at most MAX_OLDER_VERSIONS (artifact-library.ts).
24788
25142
  versions: versions.map((v) => ({
@@ -24822,6 +25176,28 @@ ${style.markdown}` : params.prompt;
24822
25176
  res.status(400).json({ detail: valid.message });
24823
25177
  return;
24824
25178
  }
25179
+ if (!mayChangeExternalRelease(auth.user, input.external_access, row.external_access)) {
25180
+ res.status(403).json({ detail: EXTERNAL_SUPER_ADMIN_ONLY });
25181
+ return;
25182
+ }
25183
+ if (externalAccessCheckApplies(input, row)) {
25184
+ let teams = [];
25185
+ if (externalAccessNeedsTeams(input, row)) {
25186
+ let teamIds;
25187
+ if (input.rbac && typeof input.rbac === "object") {
25188
+ teamIds = Array.isArray(input.rbac.teams) ? input.rbac.teams.map((t) => t?.id) : [];
25189
+ } else {
25190
+ const stored = await db("rbac").where({ entity: "shared_artifact", target_resource_id: row.id, access_type: "Team" }).select("team_id");
25191
+ teamIds = stored.map((r) => r.team_id);
25192
+ }
25193
+ teams = await teamNamesByIds(db, teamIds);
25194
+ }
25195
+ const externalError = validateExternalAccessUpdate(input, row, teams);
25196
+ if (externalError) {
25197
+ res.status(400).json({ detail: externalError });
25198
+ return;
25199
+ }
25200
+ }
24825
25201
  const details = planDetails(input, now);
24826
25202
  if (!details.ok) {
24827
25203
  res.status(400).json({ detail: details.message });
@@ -24866,6 +25242,7 @@ ${style.markdown}` : params.prompt;
24866
25242
  expires_at: updated.expires_at ?? null,
24867
25243
  rights_mode: updated.rights_mode ?? null,
24868
25244
  agent_slots: readAgentSlots(updated.agent_slots),
25245
+ external_access: updated.external_access === true,
24869
25246
  ...detailsOf(updated),
24870
25247
  version_count: readVersions(updated.versions).length
24871
25248
  });
@@ -24935,6 +25312,13 @@ ${style.markdown}` : params.prompt;
24935
25312
  RBACResolver,
24936
25313
  checkRecordAccess
24937
25314
  });
25315
+ registerExternalShareRoute(app, {
25316
+ getDb: async () => (await postgresClient()).db
25317
+ });
25318
+ registerCompanionStatusRoutes(app, {
25319
+ authenticate: (req) => requestValidators.authenticate(req),
25320
+ getDb: async () => (await postgresClient()).db
25321
+ });
24938
25322
  registerToolApiRoutes(app, {
24939
25323
  authenticate: (req) => requestValidators.authenticate(req),
24940
25324
  tools,