@exulu/backend 5.21.0 → 5.22.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.
@@ -681,7 +681,7 @@ var ExuluTool = class _ExuluTool {
681
681
  if (!agent) {
682
682
  throw new Error("Agent not found.");
683
683
  }
684
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-4TT2M2JH.js");
684
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-DAC4VCWO.js");
685
685
  const tools = await convertExuluToolsToAiSdkTools2(
686
686
  [this],
687
687
  [],
@@ -17545,7 +17545,8 @@ function buildSaveSessionFile(args) {
17545
17545
  if (!uploads?.s3endpoint || !uploads.s3key || !uploads.s3secret || !uploads.s3Bucket) {
17546
17546
  return void 0;
17547
17547
  }
17548
- if (args.inRoutineRun || treatAsGuest(args.req, args.user)) return void 0;
17548
+ if (args.inRoutineRun) return void 0;
17549
+ if (treatAsGuest(args.req, args.user) && !(args.user?.id && args.guestFiles)) return void 0;
17549
17550
  const ownerId = args.ownerId ?? args.user?.id;
17550
17551
  return (file) => writeSessionFile({
17551
17552
  ownerId,
@@ -17557,6 +17558,30 @@ function buildSaveSessionFile(args) {
17557
17558
  });
17558
17559
  }
17559
17560
 
17561
+ // src/exulu/guest-session-files.ts
17562
+ function guestFilesEnabled(agent) {
17563
+ return agent?.sandbox_enabled === true && (agent.guest_auth_mode || "regular") === "regular";
17564
+ }
17565
+ function agentAllowsGuestFiles(agent) {
17566
+ return agent?.guest_access === true && agent.active !== false && guestFilesEnabled(agent);
17567
+ }
17568
+ var GUEST_MAX_FILE_BYTES = MAX_ADOPT_UPLOAD_BYTES;
17569
+ var GUEST_MAX_SESSION_FILES = 50;
17570
+ var GUEST_MAX_SESSION_BYTES = 250 * 1024 * 1024;
17571
+ function guestUploadRefusal(objects) {
17572
+ if (objects.length >= GUEST_MAX_SESSION_FILES) {
17573
+ return `This conversation already holds ${GUEST_MAX_SESSION_FILES} files. Remove one or start a new conversation.`;
17574
+ }
17575
+ const total = objects.reduce((sum, object) => sum + (object.size || 0), 0);
17576
+ if (total >= GUEST_MAX_SESSION_BYTES) {
17577
+ return "This conversation's file storage is full. Remove a file or start a new conversation.";
17578
+ }
17579
+ return void 0;
17580
+ }
17581
+ function guestFileTooLarge(size) {
17582
+ return typeof size === "number" && size > GUEST_MAX_FILE_BYTES;
17583
+ }
17584
+
17560
17585
  // src/templates/tools/routine-status-tool.ts
17561
17586
  import { z as z20 } from "zod";
17562
17587
  var SET_ROUTINE_STATUS_TOOL_ID = "set_routine_status";
@@ -19374,7 +19399,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
19374
19399
  user,
19375
19400
  req,
19376
19401
  exuluConfig,
19377
- inRoutineRun: inRoutineRun ?? Boolean(routineHandleFactory)
19402
+ inRoutineRun: inRoutineRun ?? Boolean(routineHandleFactory),
19403
+ guestFiles: agentAllowsGuestFiles(agent)
19378
19404
  }),
19379
19405
  exuluConfig,
19380
19406
  toolVariablesConfig: toolVariablesConfigData,
@@ -19473,6 +19499,7 @@ export {
19473
19499
  sanitizeFilename,
19474
19500
  MAX_PROJECT_FILES,
19475
19501
  projectFilePrefix,
19502
+ isProjectKey,
19476
19503
  DERIVED_ROOT,
19477
19504
  isDerivedKey,
19478
19505
  documentCacheDays,
@@ -19483,6 +19510,8 @@ export {
19483
19510
  getS3ObjectContent,
19484
19511
  getS3ObjectStream,
19485
19512
  getS3ObjectEtag,
19513
+ mayUseGenericS3Route,
19514
+ mayReadGenericS3Key,
19486
19515
  getS3ObjectSize,
19487
19516
  getS3ObjectBytes,
19488
19517
  deleteS3Object,
@@ -19676,6 +19705,10 @@ export {
19676
19705
  SAVE_INVALID_NAME,
19677
19706
  SAVE_EMPTY,
19678
19707
  SAVE_FAILED,
19708
+ guestFilesEnabled,
19709
+ agentAllowsGuestFiles,
19710
+ guestUploadRefusal,
19711
+ guestFileTooLarge,
19679
19712
  buildToolUpload,
19680
19713
  truncateToolOutput,
19681
19714
  DEFAULT_CONTEXT_WINDOW,
@@ -3,7 +3,7 @@ import {
3
3
  OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS,
4
4
  convertExuluToolsToAiSdkTools,
5
5
  hydrateVariables
6
- } from "./chunk-YTW26TUA.js";
6
+ } from "./chunk-6OAYOFEY.js";
7
7
  import "./chunk-43QIPMLT.js";
8
8
  import "./chunk-F534XOQR.js";
9
9
  import "./chunk-6URU62NI.js";
package/dist/index.cjs CHANGED
@@ -17201,7 +17201,8 @@ function buildSaveSessionFile(args) {
17201
17201
  if (!uploads?.s3endpoint || !uploads.s3key || !uploads.s3secret || !uploads.s3Bucket) {
17202
17202
  return void 0;
17203
17203
  }
17204
- if (args.inRoutineRun || treatAsGuest(args.req, args.user)) return void 0;
17204
+ if (args.inRoutineRun) return void 0;
17205
+ if (treatAsGuest(args.req, args.user) && !(args.user?.id && args.guestFiles)) return void 0;
17205
17206
  const ownerId = args.ownerId ?? args.user?.id;
17206
17207
  return (file) => writeSessionFile({
17207
17208
  ownerId,
@@ -17274,6 +17275,38 @@ var init_session_file_write = __esm({
17274
17275
  }
17275
17276
  });
17276
17277
 
17278
+ // src/exulu/guest-session-files.ts
17279
+ function guestFilesEnabled(agent) {
17280
+ return agent?.sandbox_enabled === true && (agent.guest_auth_mode || "regular") === "regular";
17281
+ }
17282
+ function agentAllowsGuestFiles(agent) {
17283
+ return agent?.guest_access === true && agent.active !== false && guestFilesEnabled(agent);
17284
+ }
17285
+ function guestUploadRefusal(objects) {
17286
+ if (objects.length >= GUEST_MAX_SESSION_FILES) {
17287
+ return `This conversation already holds ${GUEST_MAX_SESSION_FILES} files. Remove one or start a new conversation.`;
17288
+ }
17289
+ const total = objects.reduce((sum, object) => sum + (object.size || 0), 0);
17290
+ if (total >= GUEST_MAX_SESSION_BYTES) {
17291
+ return "This conversation's file storage is full. Remove a file or start a new conversation.";
17292
+ }
17293
+ return void 0;
17294
+ }
17295
+ function guestFileTooLarge(size) {
17296
+ return typeof size === "number" && size > GUEST_MAX_FILE_BYTES;
17297
+ }
17298
+ var GUEST_MAX_FILE_BYTES, GUEST_MAX_SESSION_FILES, GUEST_MAX_SESSION_BYTES;
17299
+ var init_guest_session_files = __esm({
17300
+ "src/exulu/guest-session-files.ts"() {
17301
+ "use strict";
17302
+ init_cjs_shims();
17303
+ init_session_file_adopt();
17304
+ GUEST_MAX_FILE_BYTES = MAX_ADOPT_UPLOAD_BYTES;
17305
+ GUEST_MAX_SESSION_FILES = 50;
17306
+ GUEST_MAX_SESSION_BYTES = 250 * 1024 * 1024;
17307
+ }
17308
+ });
17309
+
17277
17310
  // src/templates/tools/routine-status-tool.ts
17278
17311
  function createRoutineStatusTool(handle) {
17279
17312
  if (!handle || handle.statuses.length === 0) return void 0;
@@ -20013,6 +20046,7 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
20013
20046
  init_create_sandbox();
20014
20047
  init_resolve_session_project();
20015
20048
  init_session_file_write();
20049
+ init_guest_session_files();
20016
20050
  init_routine_status_tool();
20017
20051
  init_tool_upload();
20018
20052
  init_truncate_tool_output();
@@ -20468,7 +20502,8 @@ var init_convert_exulu_tools_to_ai_sdk_tools = __esm({
20468
20502
  user,
20469
20503
  req,
20470
20504
  exuluConfig,
20471
- inRoutineRun: inRoutineRun ?? Boolean(routineHandleFactory)
20505
+ inRoutineRun: inRoutineRun ?? Boolean(routineHandleFactory),
20506
+ guestFiles: agentAllowsGuestFiles(agent)
20472
20507
  }),
20473
20508
  exuluConfig,
20474
20509
  toolVariablesConfig: toolVariablesConfigData,
@@ -24496,6 +24531,72 @@ init_context();
24496
24531
  init_entities();
24497
24532
  init_vector_search();
24498
24533
 
24534
+ // src/graphql/resolvers/chunk-source-document.ts
24535
+ init_cjs_shims();
24536
+ init_context();
24537
+ init_keys();
24538
+ init_project_files();
24539
+ init_access_control();
24540
+ function chunkWithItemQuery(db2, table, contextId, user, chunkId, itemColumns = []) {
24541
+ const query = db2(getChunksTableName(contextId) + " as chunks").select([
24542
+ "chunks.id as chunk_id",
24543
+ "chunks.source as chunk_source",
24544
+ "chunks.content as chunk_content",
24545
+ "chunks.chunk_index",
24546
+ "chunks.metadata as chunk_metadata",
24547
+ db2.raw('chunks."createdAt" as chunk_created_at'),
24548
+ db2.raw('chunks."updatedAt" as chunk_updated_at'),
24549
+ "items.id as item_id",
24550
+ "items.name as item_name",
24551
+ "items.external_id as item_external_id",
24552
+ db2.raw('items."updatedAt" as item_updated_at'),
24553
+ db2.raw('items."createdAt" as item_created_at'),
24554
+ ...itemColumns.map((column) => `items.${column} as item_file_${column}`)
24555
+ ]).join(getTableName(contextId) + " as items", "chunks.source", "items.id").where("chunks.id", chunkId);
24556
+ return applyAccessControl(table, query, user, "items").first();
24557
+ }
24558
+ function fileKeyColumns(fields) {
24559
+ return (fields ?? []).filter((field) => field.type === "file").map((field) => field.name.endsWith("_s3key") ? field.name : `${field.name}_s3key`);
24560
+ }
24561
+ function pickSourceDocumentKey(metadata, itemFileKeys) {
24562
+ if (!metadata || typeof metadata !== "object") return void 0;
24563
+ const { pdf, document: document2 } = metadata;
24564
+ const stored = new Set(itemFileKeys.filter((k) => typeof k === "string" && k !== ""));
24565
+ return [pdf, document2].find((k) => typeof k === "string" && stored.has(k));
24566
+ }
24567
+ async function chunkSourceDocument(deps) {
24568
+ const columns = fileKeyColumns(deps.context.fields);
24569
+ if (columns.length === 0) return null;
24570
+ const row = await chunkWithItemQuery(
24571
+ deps.db,
24572
+ deps.table,
24573
+ deps.context.id,
24574
+ deps.user,
24575
+ deps.chunkId,
24576
+ columns
24577
+ );
24578
+ if (!row) return null;
24579
+ const stored = pickSourceDocumentKey(
24580
+ row.chunk_metadata,
24581
+ columns.map((column) => row[`item_file_${column}`])
24582
+ );
24583
+ if (!stored) return null;
24584
+ const slash = stored.indexOf("/");
24585
+ if (slash <= 0) return null;
24586
+ const bucket = stored.slice(0, slash);
24587
+ const key = stored.slice(slash + 1);
24588
+ if (!key || isDerivedKey(key, deps.s3prefix) || isProjectKey(key, deps.s3prefix)) return null;
24589
+ const page = Number.parseInt(String(row.chunk_metadata?.page ?? ""), 10);
24590
+ return {
24591
+ url: await deps.sign(bucket, key),
24592
+ filename: key.slice(key.lastIndexOf("/") + 1),
24593
+ page: Number.isFinite(page) && page > 0 ? page : null
24594
+ };
24595
+ }
24596
+
24597
+ // src/graphql/resolvers/index.ts
24598
+ init_uppy();
24599
+
24499
24600
  // src/graphql/utilities/sanitize-and-hydrate-fields.ts
24500
24601
  init_cjs_shims();
24501
24602
  init_context();
@@ -24916,7 +25017,7 @@ var sanitizeRequestedFields = (table, requestedFields) => {
24916
25017
  }
24917
25018
  return requestedFields;
24918
25019
  };
24919
- function createQueries(table, tools, contexts) {
25020
+ function createQueries(table, tools, contexts, config) {
24920
25021
  const tableNamePlural = table.name.plural.toLowerCase();
24921
25022
  const tableNameSingular = table.name.singular.toLowerCase();
24922
25023
  const queries = {
@@ -25165,23 +25266,7 @@ function createQueries(table, tools, contexts) {
25165
25266
  if (!exists) {
25166
25267
  throw new Error("Context " + table.id + " not found in registry.");
25167
25268
  }
25168
- const { db: db2 } = context;
25169
- const chunksTable = getChunksTableName(exists.id);
25170
- const mainTable = getTableName(exists.id);
25171
- const chunk2 = await db2(chunksTable + " as chunks").select([
25172
- "chunks.id as chunk_id",
25173
- "chunks.source as chunk_source",
25174
- "chunks.content as chunk_content",
25175
- "chunks.chunk_index",
25176
- "chunks.metadata as chunk_metadata",
25177
- db2.raw('chunks."createdAt" as chunk_created_at'),
25178
- db2.raw('chunks."updatedAt" as chunk_updated_at'),
25179
- "items.id as item_id",
25180
- "items.name as item_name",
25181
- "items.external_id as item_external_id",
25182
- db2.raw('items."updatedAt" as item_updated_at'),
25183
- db2.raw('items."createdAt" as item_created_at')
25184
- ]).leftJoin(mainTable + " as items", "chunks.source", "items.id").where("chunks.id", args.id).first();
25269
+ const chunk2 = await chunkWithItemQuery(context.db, table, exists.id, context.user, args.id);
25185
25270
  if (!chunk2) {
25186
25271
  return null;
25187
25272
  }
@@ -25200,6 +25285,24 @@ function createQueries(table, tools, contexts) {
25200
25285
  item_created_at: chunk2.item_created_at
25201
25286
  };
25202
25287
  };
25288
+ queries[`${tableNameSingular}ChunkSourceDocument`] = async (_, args, context) => {
25289
+ const exists = contexts.find((ctx) => ctx.id === table.id);
25290
+ if (!exists) {
25291
+ throw new Error("Context " + table.id + " not found in registry.");
25292
+ }
25293
+ if (!config?.fileUploads) {
25294
+ return null;
25295
+ }
25296
+ return await chunkSourceDocument({
25297
+ db: context.db,
25298
+ table,
25299
+ context: exists,
25300
+ user: context.user,
25301
+ chunkId: args.id,
25302
+ s3prefix: config.fileUploads.s3prefix,
25303
+ sign: (bucket, key) => getPresignedUrl(bucket, key, config)
25304
+ });
25305
+ };
25203
25306
  }
25204
25307
  return queries;
25205
25308
  }
@@ -25233,6 +25336,32 @@ async function getJobsByQueueName(queueName, statusses, page, limit) {
25233
25336
  init_cjs_shims();
25234
25337
  init_context();
25235
25338
  init_item_write();
25339
+
25340
+ // src/exulu/item-file-keys.ts
25341
+ init_cjs_shims();
25342
+ init_uppy();
25343
+ function unreadableFileKeyColumns(input, user, s3prefix) {
25344
+ const caller = user ?? {};
25345
+ return Object.entries(input).filter(([column, value]) => column.endsWith("_s3key") && typeof value === "string" && value !== "").filter(([, value]) => {
25346
+ const stored = value;
25347
+ const key = stored.slice(stored.indexOf("/") + 1);
25348
+ if (!stored.includes("/") || !key) return true;
25349
+ return !mayUseGenericS3Route(key, caller, s3prefix) || !mayReadGenericS3Key(key, caller, s3prefix);
25350
+ }).map(([column]) => column);
25351
+ }
25352
+ async function assertItemFileKeysReadable(deps) {
25353
+ const flagged = unreadableFileKeyColumns(deps.input, deps.user, deps.s3prefix);
25354
+ if (flagged.length === 0) return;
25355
+ const existing = await deps.loadExisting();
25356
+ const refused = flagged.filter((column) => existing?.[column] !== deps.input[column]);
25357
+ if (refused.length > 0) {
25358
+ throw new Error(
25359
+ `Not allowed to attach the file in ${refused.join(", ")}: it is not one of your own uploads or a shared file.`
25360
+ );
25361
+ }
25362
+ }
25363
+
25364
+ // src/graphql/mutations/index.ts
25236
25365
  init_entities();
25237
25366
  init_statistics2();
25238
25367
  init_access_control();
@@ -26253,6 +26382,7 @@ init_cjs_shims();
26253
26382
  // src/exulu/public-agents.ts
26254
26383
  init_cjs_shims();
26255
26384
  init_shared_artifacts();
26385
+ init_guest_session_files();
26256
26386
  var LOCALE_KEY = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})?$/;
26257
26387
  var welcomeTranslations = (raw) => {
26258
26388
  let value = raw;
@@ -26283,7 +26413,8 @@ var publicAgentView = (row, slug) => ({
26283
26413
  guest_auth_mode: row.guest_auth_mode || "regular",
26284
26414
  guest_has_cover: !!row.guest_cover_image,
26285
26415
  guest_has_idle_animation: !!row.animation_idle,
26286
- guest_has_responding_animation: !!row.animation_responding
26416
+ guest_has_responding_animation: !!row.animation_responding,
26417
+ guest_files_enabled: guestFilesEnabled(row)
26287
26418
  });
26288
26419
  var evaluateGuestChatAccess = async (agent, userId, guestPassword) => {
26289
26420
  if (agent.guest_access) {
@@ -27838,6 +27969,20 @@ function createMutations(table, contexts, tools, config) {
27838
27969
  if (table.name.singular === "user" && context.user?.super_admin !== true) {
27839
27970
  throw new Error("You are not authorized to create users");
27840
27971
  }
27972
+ if (table.type === "items") {
27973
+ await assertItemFileKeysReadable({
27974
+ input,
27975
+ user: context.user,
27976
+ s3prefix: config?.fileUploads?.s3prefix,
27977
+ // An upsert may land on an existing row, whose stored keys stay valid.
27978
+ loadExisting: async () => {
27979
+ if (!args.upsert) return null;
27980
+ if (input.id) return db2.from(tableNamePlural).where({ id: input.id }).first();
27981
+ if (input.external_id) return db2.from(tableNamePlural).where({ external_id: input.external_id }).first();
27982
+ return null;
27983
+ }
27984
+ });
27985
+ }
27841
27986
  if (table.name.singular === "user" && input.email) {
27842
27987
  input.email = String(input.email).trim().toLowerCase();
27843
27988
  }
@@ -27940,6 +28085,14 @@ function createMutations(table, contexts, tools, config) {
27940
28085
  throw new Error("Record not found");
27941
28086
  }
27942
28087
  await validateWriteAccess(item.id, context);
28088
+ if (table.type === "items") {
28089
+ await assertItemFileKeysReadable({
28090
+ input,
28091
+ user: context.user,
28092
+ s3prefix: config?.fileUploads?.s3prefix,
28093
+ loadExisting: () => db2.from(tableNamePlural).where({ id: item.id }).first()
28094
+ });
28095
+ }
27943
28096
  const existingRow = args.merge?.length ? await db2.from(tableNamePlural).where({ id: item.id }).first() : null;
27944
28097
  const prepared = prepareItemWrite({
27945
28098
  fields: table.fields,
@@ -28006,6 +28159,14 @@ function createMutations(table, contexts, tools, config) {
28006
28159
  let { id, input } = args;
28007
28160
  await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
28008
28161
  await validateWriteAccess(id, context);
28162
+ if (table.type === "items") {
28163
+ await assertItemFileKeysReadable({
28164
+ input,
28165
+ user: context.user,
28166
+ s3prefix: config?.fileUploads?.s3prefix,
28167
+ loadExisting: () => db2.from(tableNamePlural).where({ id }).first()
28168
+ });
28169
+ }
28009
28170
  const rbacData = input.RBAC;
28010
28171
  delete input.RBAC;
28011
28172
  delete input.created_by;
@@ -37456,6 +37617,12 @@ type StatisticsResult {
37456
37617
  group: String!
37457
37618
  count: Int!
37458
37619
  }
37620
+
37621
+ type ChunkSourceDocument {
37622
+ url: String!
37623
+ filename: String!
37624
+ page: Int
37625
+ }
37459
37626
  `;
37460
37627
  }
37461
37628
  function createSDL(tables, contexts, tools, config, evals) {
@@ -37556,6 +37723,7 @@ function createSDL(tables, contexts, tools, config, evals) {
37556
37723
  typeDefs += `
37557
37724
  ${tableNamePlural}VectorSearch(limit: Int, query: String!, method: VectorMethodEnum!, itemFilters: [Filter${tableNameSingularUpperCaseFirst}], cutoffs: SearchCutoffs, expand: SearchExpand, entityFilter: ${tableNameSingular}EntityFilterInput): ${tableNameSingular}VectorSearchResult
37558
37725
  ${tableNameSingular}ChunkById(id: ID!): ${tableNameSingular}VectorSearchChunk
37726
+ ${tableNameSingular}ChunkSourceDocument(id: ID!): ChunkSourceDocument
37559
37727
  ${tableNameSingular}StaleEntityCount: Int
37560
37728
  ${tableNameSingular}EntityModel: ${tableNameSingular}EntityModelInfo
37561
37729
  ${tableNameSingular}EntitiesForItem(item: ID!): [${tableNameSingular}ItemEntity!]
@@ -37852,7 +38020,7 @@ type PageInfo {
37852
38020
  hasNextPage: Boolean!
37853
38021
  }
37854
38022
  `;
37855
- Object.assign(resolvers2.Query, createQueries(table, tools, contexts));
38023
+ Object.assign(resolvers2.Query, createQueries(table, tools, contexts, config));
37856
38024
  Object.assign(
37857
38025
  resolvers2.Mutation,
37858
38026
  createMutations(table, contexts, tools, config)
@@ -44464,6 +44632,7 @@ init_rbac_update();
44464
44632
  init_shared_artifacts();
44465
44633
  init_session_files();
44466
44634
  init_session_file_adopt();
44635
+ init_guest_session_files();
44467
44636
 
44468
44637
  // src/exulu/guest-rate-limit.ts
44469
44638
  init_cjs_shims();
@@ -48055,6 +48224,14 @@ ${style.markdown}` : params.prompt;
48055
48224
  const loadSessionFilesAuth = async (req, res, sessionId, rights) => {
48056
48225
  const authed = await loadAuthedSession(req, res, sessionId, rights);
48057
48226
  if (!authed) return null;
48227
+ if (isExternalUser(authed.user)) {
48228
+ const agentId = authed.session?.agent;
48229
+ const agentRow = agentId ? await authed.db.from("agents").where({ id: agentId }).select("guest_access", "guest_auth_mode", "sandbox_enabled", "active").first() : null;
48230
+ if (!agentAllowsGuestFiles(agentRow)) {
48231
+ res.status(403).json({ detail: "Files are not available for this conversation." });
48232
+ return null;
48233
+ }
48234
+ }
48058
48235
  const ownerId = authed.session.user ?? authed.user.id;
48059
48236
  return { ...authed, ownerId, ...buildSessionPrefixes(ownerId, sessionId) };
48060
48237
  };
@@ -48143,6 +48320,15 @@ ${style.markdown}` : params.prompt;
48143
48320
  res.status(400).json({ detail: "Missing contentType in request body." });
48144
48321
  return;
48145
48322
  }
48323
+ if (isExternalUser(authed.user)) {
48324
+ const refusal = guestUploadRefusal(
48325
+ await listS3ObjectsByPrefix(authed.userSessionPrefix, config)
48326
+ );
48327
+ if (refusal) {
48328
+ res.status(413).json({ detail: refusal });
48329
+ return;
48330
+ }
48331
+ }
48146
48332
  const fullKey = `${authed.fullSessionPrefix}${safeName}`;
48147
48333
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
48148
48334
  res.json({ uploadUrl, key: fullKey });
@@ -48167,6 +48353,16 @@ ${style.markdown}` : params.prompt;
48167
48353
  res.status(403).json({ detail: "Key does not belong to this session." });
48168
48354
  return;
48169
48355
  }
48356
+ if (isExternalUser(authed.user)) {
48357
+ const uploaded = (await listS3ObjectsByPrefix(authed.userSessionPrefix, config)).find(
48358
+ (object) => object.key === key
48359
+ );
48360
+ if (guestFileTooLarge(uploaded?.size)) {
48361
+ await deleteS3Object(key, config);
48362
+ res.status(413).json({ detail: "This file is too large." });
48363
+ return;
48364
+ }
48365
+ }
48170
48366
  try {
48171
48367
  const result = await downloadKeyIntoSandbox({
48172
48368
  sessionId,
@@ -48894,7 +49090,9 @@ ${style.markdown}` : params.prompt;
48894
49090
  // Presence only — publicAgentView turns these into booleans and the
48895
49091
  // bytes are served by /public-agents/:id/animation/:kind.
48896
49092
  "animation_idle",
48897
- "animation_responding"
49093
+ "animation_responding",
49094
+ // Presence of the guest files feature, never the sandbox itself.
49095
+ "sandbox_enabled"
48898
49096
  );
48899
49097
  const views = await Promise.all(
48900
49098
  rows.map(
package/dist/index.js CHANGED
@@ -74,6 +74,7 @@ import {
74
74
  UMAP_NEIGHBORS,
75
75
  VALID_RIGHTS_MODES,
76
76
  VIEW_DOCUMENT_PAGE_TOOL_NAME,
77
+ agentAllowsGuestFiles,
77
78
  applyAccessControl,
78
79
  applyFilters,
79
80
  applyFiltersGrouped,
@@ -164,6 +165,9 @@ import {
164
165
  getTableName,
165
166
  getToken,
166
167
  guardExtractedFileText,
168
+ guestFileTooLarge,
169
+ guestFilesEnabled,
170
+ guestUploadRefusal,
167
171
  handleRBACUpdate,
168
172
  hasAgentsReadAccess,
169
173
  hasAgentsWriteAccess,
@@ -177,6 +181,7 @@ import {
177
181
  isExternalOrAnonymousUser,
178
182
  isInterimToolStatus,
179
183
  isPreviewRequest,
184
+ isProjectKey,
180
185
  isPublicSurface,
181
186
  isRunSessionMetadata,
182
187
  l2normalize,
@@ -185,7 +190,9 @@ import {
185
190
  loadSessionFileListing,
186
191
  mapStreamErrorMessage,
187
192
  mapType,
193
+ mayReadGenericS3Key,
188
194
  mayResignStoredFileKey,
195
+ mayUseGenericS3Route,
189
196
  maybePruneJobResults,
190
197
  meanVector,
191
198
  microCall,
@@ -264,7 +271,7 @@ import {
264
271
  willEmbedOnQueue,
265
272
  withRunSession,
266
273
  workflowTemplatesSchema
267
- } from "./chunk-YTW26TUA.js";
274
+ } from "./chunk-6OAYOFEY.js";
268
275
  import {
269
276
  LITELLM_UI_PATH,
270
277
  ResolveModelError,
@@ -1113,6 +1120,64 @@ var exuluProviderFields = [
1113
1120
  "systemInstructions"
1114
1121
  ];
1115
1122
 
1123
+ // src/graphql/resolvers/chunk-source-document.ts
1124
+ function chunkWithItemQuery(db, table, contextId, user, chunkId, itemColumns = []) {
1125
+ const query = db(getChunksTableName(contextId) + " as chunks").select([
1126
+ "chunks.id as chunk_id",
1127
+ "chunks.source as chunk_source",
1128
+ "chunks.content as chunk_content",
1129
+ "chunks.chunk_index",
1130
+ "chunks.metadata as chunk_metadata",
1131
+ db.raw('chunks."createdAt" as chunk_created_at'),
1132
+ db.raw('chunks."updatedAt" as chunk_updated_at'),
1133
+ "items.id as item_id",
1134
+ "items.name as item_name",
1135
+ "items.external_id as item_external_id",
1136
+ db.raw('items."updatedAt" as item_updated_at'),
1137
+ db.raw('items."createdAt" as item_created_at'),
1138
+ ...itemColumns.map((column) => `items.${column} as item_file_${column}`)
1139
+ ]).join(getTableName(contextId) + " as items", "chunks.source", "items.id").where("chunks.id", chunkId);
1140
+ return applyAccessControl(table, query, user, "items").first();
1141
+ }
1142
+ function fileKeyColumns(fields) {
1143
+ return (fields ?? []).filter((field) => field.type === "file").map((field) => field.name.endsWith("_s3key") ? field.name : `${field.name}_s3key`);
1144
+ }
1145
+ function pickSourceDocumentKey(metadata, itemFileKeys) {
1146
+ if (!metadata || typeof metadata !== "object") return void 0;
1147
+ const { pdf, document } = metadata;
1148
+ const stored = new Set(itemFileKeys.filter((k) => typeof k === "string" && k !== ""));
1149
+ return [pdf, document].find((k) => typeof k === "string" && stored.has(k));
1150
+ }
1151
+ async function chunkSourceDocument(deps) {
1152
+ const columns = fileKeyColumns(deps.context.fields);
1153
+ if (columns.length === 0) return null;
1154
+ const row = await chunkWithItemQuery(
1155
+ deps.db,
1156
+ deps.table,
1157
+ deps.context.id,
1158
+ deps.user,
1159
+ deps.chunkId,
1160
+ columns
1161
+ );
1162
+ if (!row) return null;
1163
+ const stored = pickSourceDocumentKey(
1164
+ row.chunk_metadata,
1165
+ columns.map((column) => row[`item_file_${column}`])
1166
+ );
1167
+ if (!stored) return null;
1168
+ const slash = stored.indexOf("/");
1169
+ if (slash <= 0) return null;
1170
+ const bucket = stored.slice(0, slash);
1171
+ const key = stored.slice(slash + 1);
1172
+ if (!key || isDerivedKey(key, deps.s3prefix) || isProjectKey(key, deps.s3prefix)) return null;
1173
+ const page = Number.parseInt(String(row.chunk_metadata?.page ?? ""), 10);
1174
+ return {
1175
+ url: await deps.sign(bucket, key),
1176
+ filename: key.slice(key.lastIndexOf("/") + 1),
1177
+ page: Number.isFinite(page) && page > 0 ? page : null
1178
+ };
1179
+ }
1180
+
1116
1181
  // src/graphql/utilities/budget-field.ts
1117
1182
  var BUDGET_ENTITY_SINGULARS = /* @__PURE__ */ new Set([
1118
1183
  "user",
@@ -1511,7 +1576,7 @@ var sanitizeRequestedFields = (table, requestedFields) => {
1511
1576
  }
1512
1577
  return requestedFields;
1513
1578
  };
1514
- function createQueries(table, tools, contexts) {
1579
+ function createQueries(table, tools, contexts, config) {
1515
1580
  const tableNamePlural = table.name.plural.toLowerCase();
1516
1581
  const tableNameSingular = table.name.singular.toLowerCase();
1517
1582
  const queries = {
@@ -1760,23 +1825,7 @@ function createQueries(table, tools, contexts) {
1760
1825
  if (!exists) {
1761
1826
  throw new Error("Context " + table.id + " not found in registry.");
1762
1827
  }
1763
- const { db } = context;
1764
- const chunksTable = getChunksTableName(exists.id);
1765
- const mainTable = getTableName(exists.id);
1766
- const chunk2 = await db(chunksTable + " as chunks").select([
1767
- "chunks.id as chunk_id",
1768
- "chunks.source as chunk_source",
1769
- "chunks.content as chunk_content",
1770
- "chunks.chunk_index",
1771
- "chunks.metadata as chunk_metadata",
1772
- db.raw('chunks."createdAt" as chunk_created_at'),
1773
- db.raw('chunks."updatedAt" as chunk_updated_at'),
1774
- "items.id as item_id",
1775
- "items.name as item_name",
1776
- "items.external_id as item_external_id",
1777
- db.raw('items."updatedAt" as item_updated_at'),
1778
- db.raw('items."createdAt" as item_created_at')
1779
- ]).leftJoin(mainTable + " as items", "chunks.source", "items.id").where("chunks.id", args.id).first();
1828
+ const chunk2 = await chunkWithItemQuery(context.db, table, exists.id, context.user, args.id);
1780
1829
  if (!chunk2) {
1781
1830
  return null;
1782
1831
  }
@@ -1795,6 +1844,24 @@ function createQueries(table, tools, contexts) {
1795
1844
  item_created_at: chunk2.item_created_at
1796
1845
  };
1797
1846
  };
1847
+ queries[`${tableNameSingular}ChunkSourceDocument`] = async (_, args, context) => {
1848
+ const exists = contexts.find((ctx) => ctx.id === table.id);
1849
+ if (!exists) {
1850
+ throw new Error("Context " + table.id + " not found in registry.");
1851
+ }
1852
+ if (!config?.fileUploads) {
1853
+ return null;
1854
+ }
1855
+ return await chunkSourceDocument({
1856
+ db: context.db,
1857
+ table,
1858
+ context: exists,
1859
+ user: context.user,
1860
+ chunkId: args.id,
1861
+ s3prefix: config.fileUploads.s3prefix,
1862
+ sign: (bucket, key) => getPresignedUrl(bucket, key, config)
1863
+ });
1864
+ };
1798
1865
  }
1799
1866
  return queries;
1800
1867
  }
@@ -1820,6 +1887,28 @@ async function getJobsByQueueName(queueName, statusses, page, limit) {
1820
1887
  };
1821
1888
  }
1822
1889
 
1890
+ // src/exulu/item-file-keys.ts
1891
+ function unreadableFileKeyColumns(input, user, s3prefix) {
1892
+ const caller = user ?? {};
1893
+ return Object.entries(input).filter(([column, value]) => column.endsWith("_s3key") && typeof value === "string" && value !== "").filter(([, value]) => {
1894
+ const stored = value;
1895
+ const key = stored.slice(stored.indexOf("/") + 1);
1896
+ if (!stored.includes("/") || !key) return true;
1897
+ return !mayUseGenericS3Route(key, caller, s3prefix) || !mayReadGenericS3Key(key, caller, s3prefix);
1898
+ }).map(([column]) => column);
1899
+ }
1900
+ async function assertItemFileKeysReadable(deps) {
1901
+ const flagged = unreadableFileKeyColumns(deps.input, deps.user, deps.s3prefix);
1902
+ if (flagged.length === 0) return;
1903
+ const existing = await deps.loadExisting();
1904
+ const refused = flagged.filter((column) => existing?.[column] !== deps.input[column]);
1905
+ if (refused.length > 0) {
1906
+ throw new Error(
1907
+ `Not allowed to attach the file in ${refused.join(", ")}: it is not one of your own uploads or a shared file.`
1908
+ );
1909
+ }
1910
+ }
1911
+
1823
1912
  // src/auth/generate-key.ts
1824
1913
  import bcrypt from "bcryptjs";
1825
1914
  var SALT_ROUNDS = 12;
@@ -2827,7 +2916,8 @@ var publicAgentView = (row, slug) => ({
2827
2916
  guest_auth_mode: row.guest_auth_mode || "regular",
2828
2917
  guest_has_cover: !!row.guest_cover_image,
2829
2918
  guest_has_idle_animation: !!row.animation_idle,
2830
- guest_has_responding_animation: !!row.animation_responding
2919
+ guest_has_responding_animation: !!row.animation_responding,
2920
+ guest_files_enabled: guestFilesEnabled(row)
2831
2921
  });
2832
2922
  var evaluateGuestChatAccess = async (agent, userId, guestPassword) => {
2833
2923
  if (agent.guest_access) {
@@ -4344,6 +4434,20 @@ function createMutations(table, contexts, tools, config) {
4344
4434
  if (table.name.singular === "user" && context.user?.super_admin !== true) {
4345
4435
  throw new Error("You are not authorized to create users");
4346
4436
  }
4437
+ if (table.type === "items") {
4438
+ await assertItemFileKeysReadable({
4439
+ input,
4440
+ user: context.user,
4441
+ s3prefix: config?.fileUploads?.s3prefix,
4442
+ // An upsert may land on an existing row, whose stored keys stay valid.
4443
+ loadExisting: async () => {
4444
+ if (!args.upsert) return null;
4445
+ if (input.id) return db.from(tableNamePlural).where({ id: input.id }).first();
4446
+ if (input.external_id) return db.from(tableNamePlural).where({ external_id: input.external_id }).first();
4447
+ return null;
4448
+ }
4449
+ });
4450
+ }
4347
4451
  if (table.name.singular === "user" && input.email) {
4348
4452
  input.email = String(input.email).trim().toLowerCase();
4349
4453
  }
@@ -4446,6 +4550,14 @@ function createMutations(table, contexts, tools, config) {
4446
4550
  throw new Error("Record not found");
4447
4551
  }
4448
4552
  await validateWriteAccess(item.id, context);
4553
+ if (table.type === "items") {
4554
+ await assertItemFileKeysReadable({
4555
+ input,
4556
+ user: context.user,
4557
+ s3prefix: config?.fileUploads?.s3prefix,
4558
+ loadExisting: () => db.from(tableNamePlural).where({ id: item.id }).first()
4559
+ });
4560
+ }
4449
4561
  const existingRow = args.merge?.length ? await db.from(tableNamePlural).where({ id: item.id }).first() : null;
4450
4562
  const prepared = prepareItemWrite({
4451
4563
  fields: table.fields,
@@ -4512,6 +4624,14 @@ function createMutations(table, contexts, tools, config) {
4512
4624
  let { id, input } = args;
4513
4625
  await validateCreateOrRemoveSuperAdminPermission(tableNamePlural, input, req);
4514
4626
  await validateWriteAccess(id, context);
4627
+ if (table.type === "items") {
4628
+ await assertItemFileKeysReadable({
4629
+ input,
4630
+ user: context.user,
4631
+ s3prefix: config?.fileUploads?.s3prefix,
4632
+ loadExisting: () => db.from(tableNamePlural).where({ id }).first()
4633
+ });
4634
+ }
4515
4635
  const rbacData = input.RBAC;
4516
4636
  delete input.RBAC;
4517
4637
  delete input.created_by;
@@ -13714,6 +13834,12 @@ type StatisticsResult {
13714
13834
  group: String!
13715
13835
  count: Int!
13716
13836
  }
13837
+
13838
+ type ChunkSourceDocument {
13839
+ url: String!
13840
+ filename: String!
13841
+ page: Int
13842
+ }
13717
13843
  `;
13718
13844
  }
13719
13845
  function createSDL(tables, contexts, tools, config, evals) {
@@ -13814,6 +13940,7 @@ function createSDL(tables, contexts, tools, config, evals) {
13814
13940
  typeDefs += `
13815
13941
  ${tableNamePlural}VectorSearch(limit: Int, query: String!, method: VectorMethodEnum!, itemFilters: [Filter${tableNameSingularUpperCaseFirst}], cutoffs: SearchCutoffs, expand: SearchExpand, entityFilter: ${tableNameSingular}EntityFilterInput): ${tableNameSingular}VectorSearchResult
13816
13942
  ${tableNameSingular}ChunkById(id: ID!): ${tableNameSingular}VectorSearchChunk
13943
+ ${tableNameSingular}ChunkSourceDocument(id: ID!): ChunkSourceDocument
13817
13944
  ${tableNameSingular}StaleEntityCount: Int
13818
13945
  ${tableNameSingular}EntityModel: ${tableNameSingular}EntityModelInfo
13819
13946
  ${tableNameSingular}EntitiesForItem(item: ID!): [${tableNameSingular}ItemEntity!]
@@ -14110,7 +14237,7 @@ type PageInfo {
14110
14237
  hasNextPage: Boolean!
14111
14238
  }
14112
14239
  `;
14113
- Object.assign(resolvers.Query, createQueries(table, tools, contexts));
14240
+ Object.assign(resolvers.Query, createQueries(table, tools, contexts, config));
14114
14241
  Object.assign(
14115
14242
  resolvers.Mutation,
14116
14243
  createMutations(table, contexts, tools, config)
@@ -24122,6 +24249,14 @@ ${style.markdown}` : params.prompt;
24122
24249
  const loadSessionFilesAuth = async (req, res, sessionId, rights) => {
24123
24250
  const authed = await loadAuthedSession(req, res, sessionId, rights);
24124
24251
  if (!authed) return null;
24252
+ if (isExternalUser(authed.user)) {
24253
+ const agentId = authed.session?.agent;
24254
+ const agentRow = agentId ? await authed.db.from("agents").where({ id: agentId }).select("guest_access", "guest_auth_mode", "sandbox_enabled", "active").first() : null;
24255
+ if (!agentAllowsGuestFiles(agentRow)) {
24256
+ res.status(403).json({ detail: "Files are not available for this conversation." });
24257
+ return null;
24258
+ }
24259
+ }
24125
24260
  const ownerId = authed.session.user ?? authed.user.id;
24126
24261
  return { ...authed, ownerId, ...buildSessionPrefixes(ownerId, sessionId) };
24127
24262
  };
@@ -24210,6 +24345,15 @@ ${style.markdown}` : params.prompt;
24210
24345
  res.status(400).json({ detail: "Missing contentType in request body." });
24211
24346
  return;
24212
24347
  }
24348
+ if (isExternalUser(authed.user)) {
24349
+ const refusal = guestUploadRefusal(
24350
+ await listS3ObjectsByPrefix(authed.userSessionPrefix, config)
24351
+ );
24352
+ if (refusal) {
24353
+ res.status(413).json({ detail: refusal });
24354
+ return;
24355
+ }
24356
+ }
24213
24357
  const fullKey = `${authed.fullSessionPrefix}${safeName}`;
24214
24358
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
24215
24359
  res.json({ uploadUrl, key: fullKey });
@@ -24234,6 +24378,16 @@ ${style.markdown}` : params.prompt;
24234
24378
  res.status(403).json({ detail: "Key does not belong to this session." });
24235
24379
  return;
24236
24380
  }
24381
+ if (isExternalUser(authed.user)) {
24382
+ const uploaded = (await listS3ObjectsByPrefix(authed.userSessionPrefix, config)).find(
24383
+ (object) => object.key === key
24384
+ );
24385
+ if (guestFileTooLarge(uploaded?.size)) {
24386
+ await deleteS3Object(key, config);
24387
+ res.status(413).json({ detail: "This file is too large." });
24388
+ return;
24389
+ }
24390
+ }
24237
24391
  try {
24238
24392
  const result = await downloadKeyIntoSandbox({
24239
24393
  sessionId,
@@ -24961,7 +25115,9 @@ ${style.markdown}` : params.prompt;
24961
25115
  // Presence only — publicAgentView turns these into booleans and the
24962
25116
  // bytes are served by /public-agents/:id/animation/:kind.
24963
25117
  "animation_idle",
24964
- "animation_responding"
25118
+ "animation_responding",
25119
+ // Presence of the guest files feature, never the sandbox itself.
25120
+ "sandbox_enabled"
24965
25121
  );
24966
25122
  const views = await Promise.all(
24967
25123
  rows.map(
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "5.21.0",
4
+ "version": "5.22.0",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {