@exulu/backend 5.12.0 → 5.13.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
@@ -17,6 +17,7 @@ import {
17
17
  CLAIM_CHECK_MAX_OUTPUT_TOKENS,
18
18
  COMPACTION_INSUFFICIENT,
19
19
  COMPONENTS,
20
+ COPY_FAILED_REASON,
20
21
  Chunk,
21
22
  ContextCompactionRequiredError,
22
23
  CredentialInvalidError,
@@ -31,6 +32,8 @@ import {
31
32
  FIT_SAMPLE,
32
33
  JOB_STATUS_ENUM,
33
34
  KB_EDITOR_TOOL_ID,
35
+ MAX_ADOPT_UPLOAD_BYTES,
36
+ MAX_PROJECT_FILES,
34
37
  MEMORY_REQUIRED_FIELDS,
35
38
  OAUTH_CALLBACK_PATH,
36
39
  PARSE_DOCUMENT_TOOL_NAME,
@@ -72,6 +75,8 @@ import {
72
75
  buildMemoryPromptBlock,
73
76
  canAccessSkill,
74
77
  canEditMemory,
78
+ canManageShare,
79
+ canRegisterSaveToProject,
75
80
  captureCodeEmbedder,
76
81
  checkMemoryBase,
77
82
  checkRecordAccess,
@@ -79,6 +84,7 @@ import {
79
84
  clearEmbedderSetting,
80
85
  codeEmbedderFor,
81
86
  collectMemoryDecisions,
87
+ contentHeadersFor,
82
88
  contextEmbedderInfoFor,
83
89
  contextOccupancy,
84
90
  convertContextToTableDefinition,
@@ -87,6 +93,7 @@ import {
87
93
  coreSchemas,
88
94
  createAgenticRetrievalTool,
89
95
  createKbEditorPickerTool,
96
+ createPromoteS3,
90
97
  createRecallCollector,
91
98
  createSkillAuthorPickerTool,
92
99
  createUppyRoutes,
@@ -97,6 +104,7 @@ import {
97
104
  defaultChunker,
98
105
  deleteS3Object,
99
106
  deriveContextBudget,
107
+ deriveFilename,
100
108
  displayName,
101
109
  downloadKeyIntoSandbox,
102
110
  dropProjection,
@@ -118,6 +126,7 @@ import {
118
126
  getEmbeddingModelInfo,
119
127
  getEntitiesForItem,
120
128
  getEntitiesTableName,
129
+ getOriginResolver,
121
130
  getPdfPreviewBytes,
122
131
  getPresignedUrl,
123
132
  getS3ObjectBytes,
@@ -126,20 +135,24 @@ import {
126
135
  getS3ObjectSize,
127
136
  getS3ObjectStream,
128
137
  getS3SignedUploadUrl,
138
+ getSharedArtifactByName,
129
139
  getTableName,
130
140
  getToken,
131
141
  guardExtractedFileText,
132
142
  handleRBACUpdate,
133
143
  hasAgentsReadAccess,
134
144
  hasAgentsWriteAccess,
145
+ hasProjectAccess,
146
+ hashSharePassword,
135
147
  hydrateContextEmbedders,
136
148
  imageAttachmentGuard,
137
149
  initAudit,
150
+ isExpired,
138
151
  isExternalOrAnonymousUser,
139
- isIgnoredArtifactPath,
140
152
  isPublicSurface,
141
153
  l2normalize,
142
154
  listS3ObjectsByPrefix,
155
+ loadSessionFileListing,
143
156
  mapStreamErrorMessage,
144
157
  mapType,
145
158
  maybePruneJobResults,
@@ -148,16 +161,25 @@ import {
148
161
  microCallProviderOptions,
149
162
  normalizeLayout,
150
163
  normalizeRbac,
164
+ normalizeS3Key,
165
+ ownsObjectKey,
151
166
  parseEmbeddingModels,
152
167
  parseFrontmatter,
153
168
  parsePipelineConfig,
154
169
  parseSkillAuthorConfig,
155
170
  parseSkillFrontmatter,
171
+ planAdoptKeys,
172
+ planAdoptSizeCheck,
173
+ planShareUpdate,
156
174
  prepareItemWrite,
157
175
  preprocessQuery,
158
176
  principalRotation,
159
177
  projectComponents,
178
+ projectFilePrefix,
179
+ promoteSessionFiles,
180
+ publicMetaFor,
160
181
  randomizedPCA,
182
+ readAgentSlots,
161
183
  readProjectionRow,
162
184
  refreshContextEmbeddersIfStale,
163
185
  refreshSessionSkills,
@@ -168,6 +190,7 @@ import {
168
190
  resolveReranker,
169
191
  resolveRetrievalCallBudget,
170
192
  resolveSearchQueryTexts,
193
+ resolveSessionProject,
171
194
  resolveSkillByName,
172
195
  resolveTurnStepBudget,
173
196
  retrievalBudgetGuard,
@@ -178,22 +201,26 @@ import {
178
201
  sanitizeName,
179
202
  sanitizeToolName,
180
203
  searchContexts,
181
- sessionFilePrefix,
204
+ sessionFilesScopeSentence,
182
205
  setEmbedderSetting,
183
206
  setEntityModelSetting,
184
207
  shouldShowSourcesToUser,
185
208
  sliceHistoryAtCheckpoint,
209
+ slugifyShareName,
186
210
  treatAsGuest,
187
211
  truncateToolOutput,
188
212
  updateStatistic,
189
213
  uploadFile,
190
214
  userCredentialsSchema,
191
215
  validateAttachmentsConfig,
216
+ validateCreateInput,
217
+ validateUpdateInput,
192
218
  vectorSearch,
193
219
  verifyCredentialNonce,
220
+ verifySharePassword,
194
221
  willEmbedOnQueue,
195
222
  workflowTemplatesSchema
196
- } from "./chunk-U4UIVZST.js";
223
+ } from "./chunk-URX7KJQV.js";
197
224
  import {
198
225
  LITELLM_UI_PATH,
199
226
  ResolveModelError,
@@ -716,6 +743,86 @@ var ExuluQueues = class {
716
743
  };
717
744
  var queues = new ExuluQueues();
718
745
 
746
+ // src/graphql/queue-access.ts
747
+ var has = (granted, level) => granted === "write" || level === "read" && granted === "read";
748
+ async function assertQueueAccess(opts, deps) {
749
+ const { user, queue, level } = opts;
750
+ if (user?.super_admin === true) return;
751
+ const role = user?.role;
752
+ const isGlobal = new Set(deps.globalQueueNames).has(queue);
753
+ let allowed = false;
754
+ if (role) {
755
+ if (isGlobal) {
756
+ allowed = queue === "eval_runs" && has(role.evals, level);
757
+ } else {
758
+ allowed = has(role.workflows, level) || has(role.agents, level) && (await deps.contextQueueNames()).has(queue);
759
+ }
760
+ }
761
+ if (!allowed) {
762
+ throw new Error(
763
+ `You don't have permission to ${level === "write" ? "manage" : "view"} the queue "${queue}". Required: super_admin or ${level} access to the page that owns it.`
764
+ );
765
+ }
766
+ }
767
+ function createQueueMutationResolvers(deps) {
768
+ const open = async (args, context) => {
769
+ if (!args.queue) {
770
+ throw new Error("Queue name is required");
771
+ }
772
+ await assertQueueAccess({ user: context?.user, queue: args.queue, level: "write" }, deps);
773
+ const queue = deps.getQueue(args.queue);
774
+ if (!queue) {
775
+ throw new Error("Queue not found");
776
+ }
777
+ return (await queue.use()).queue;
778
+ };
779
+ const requireId = (args) => {
780
+ if (!args.id) {
781
+ throw new Error("Job ID is required");
782
+ }
783
+ };
784
+ return {
785
+ /**
786
+ * Drains the queue, i.e., removes all jobs that are waiting
787
+ * or delayed, but not active, completed or failed.
788
+ */
789
+ drainQueue: async (_, args, context) => {
790
+ await (await open(args, context)).drain();
791
+ return { success: true };
792
+ },
793
+ pauseQueue: async (_, args, context) => {
794
+ await (await open(args, context)).pause();
795
+ return { success: true };
796
+ },
797
+ resumeQueue: async (_, args, context) => {
798
+ await (await open(args, context)).resume();
799
+ return { success: true };
800
+ },
801
+ deleteJob: async (_, args, context) => {
802
+ requireId(args);
803
+ await (await open(args, context)).remove(args.id);
804
+ return { success: true };
805
+ },
806
+ // KB-5: generic job retry. Re-enqueues a FRESH job with the same name +
807
+ // data (rather than BullMQ's job.retry(), which only works for failed jobs)
808
+ // so it's robust across states and leaves a clean audit trail. Optionally
809
+ // removes the original.
810
+ retryJob: async (_, args, context) => {
811
+ requireId(args);
812
+ const queue = await open(args, context);
813
+ const job = await queue.getJob(args.id);
814
+ if (!job) {
815
+ throw new Error("Job not found");
816
+ }
817
+ await queue.add(job.name, job.data);
818
+ if (args.deleteOriginal) {
819
+ await queue.remove(args.id);
820
+ }
821
+ return { success: true };
822
+ }
823
+ };
824
+ }
825
+
719
826
  // src/graphql/schemas/index.ts
720
827
  import { v4 as uuidv43 } from "uuid";
721
828
 
@@ -1622,7 +1729,7 @@ var encryptSensitiveFields = (input) => {
1622
1729
  };
1623
1730
 
1624
1731
  // src/graphql/mutations/index.ts
1625
- import bcrypt3 from "bcryptjs";
1732
+ import bcrypt2 from "bcryptjs";
1626
1733
 
1627
1734
  // src/exulu/routines/run-state.ts
1628
1735
  import { v4 as uuidv4 } from "uuid";
@@ -2494,154 +2601,6 @@ async function cancelImport(deps, jobResultId) {
2494
2601
  return { ok: true };
2495
2602
  }
2496
2603
 
2497
- // src/exulu/shared-artifacts.ts
2498
- import bcrypt2 from "bcryptjs";
2499
- var normalizeS3Key = (key, bucket) => {
2500
- const segments = key.split("/").filter((s, i) => !(i === 0 && s === "")).map((s) => decodeURIComponent(s));
2501
- if (segments[0] === bucket) segments.shift();
2502
- return segments.join("/");
2503
- };
2504
- var isHtmlKey = (key) => /\.html?$/i.test(key);
2505
- var deriveFilename = (key) => {
2506
- const base = key.split("/").pop() ?? key;
2507
- return base.split("_EXULU_").pop() ?? base;
2508
- };
2509
- var slugifyShareName = (input) => deriveFilename(input).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
2510
- var isExpired = (expiresAt, now) => {
2511
- if (!expiresAt) return false;
2512
- return new Date(expiresAt).getTime() <= now.getTime();
2513
- };
2514
- var validateCreateInput = (input, now) => {
2515
- if (!input.s3key) return { ok: false, message: "s3key is required." };
2516
- if (!input.name) return { ok: false, message: "name is required." };
2517
- const mode = input.auth_mode;
2518
- if (mode !== "public" && mode !== "password" && mode !== "regular") {
2519
- return { ok: false, message: "auth_mode must be public, password, or regular." };
2520
- }
2521
- if (mode === "password" && !input.password) {
2522
- return { ok: false, message: "A password is required for password mode." };
2523
- }
2524
- if (input.expires_at && Number.isNaN(new Date(input.expires_at).getTime())) {
2525
- return { ok: false, message: "expires_at is not a valid date." };
2526
- }
2527
- if (input.expires_at && isExpired(input.expires_at, now)) {
2528
- return { ok: false, message: "expires_at must be in the future." };
2529
- }
2530
- return { ok: true };
2531
- };
2532
- var validateAgentSlots = (value) => {
2533
- if (!Array.isArray(value)) {
2534
- return { ok: false, message: "agent_slots must be an array." };
2535
- }
2536
- const slots = [];
2537
- const seenKeys = /* @__PURE__ */ new Set();
2538
- for (const entry of value) {
2539
- if (typeof entry !== "object" || entry === null) {
2540
- return { ok: false, message: "Each agent slot must be an object." };
2541
- }
2542
- const { key, agentId } = entry;
2543
- if (typeof key !== "string" || !key.trim()) {
2544
- return { ok: false, message: "Each agent slot needs a non-empty key." };
2545
- }
2546
- if (typeof agentId !== "string" || !agentId.trim()) {
2547
- return { ok: false, message: "Each agent slot needs a non-empty agentId." };
2548
- }
2549
- const trimmedKey = key.trim();
2550
- if (seenKeys.has(trimmedKey)) {
2551
- return { ok: false, message: "agent_slots keys must be unique." };
2552
- }
2553
- seenKeys.add(trimmedKey);
2554
- slots.push({ key: trimmedKey, agentId });
2555
- }
2556
- return { ok: true, slots };
2557
- };
2558
- var readAgentSlots = (value) => {
2559
- const parsed = typeof value === "string" ? (() => {
2560
- try {
2561
- return JSON.parse(value);
2562
- } catch {
2563
- return null;
2564
- }
2565
- })() : value;
2566
- return Array.isArray(parsed) ? parsed : [];
2567
- };
2568
- var RIGHTS_MODES = /* @__PURE__ */ new Set(["private", "users", "roles", "teams", "public"]);
2569
- var canManageShare = (row, user) => user.super_admin === true || row.created_by != null && String(row.created_by) === String(user.id);
2570
- var validateUpdateInput = (input, row, now) => {
2571
- if (input.name !== void 0 && !slugifyShareName(input.name)) {
2572
- return { ok: false, message: "name must contain url-safe characters." };
2573
- }
2574
- const mode = input.auth_mode ?? row.auth_mode;
2575
- if (mode !== "public" && mode !== "password" && mode !== "regular") {
2576
- return { ok: false, message: "auth_mode must be public, password, or regular." };
2577
- }
2578
- const keepsPassword = row.auth_mode === "password" && !!row.password_hash;
2579
- if (mode === "password" && !input.password && !keepsPassword) {
2580
- return { ok: false, message: "A password is required for password mode." };
2581
- }
2582
- if (input.expires_at && Number.isNaN(new Date(input.expires_at).getTime())) {
2583
- return { ok: false, message: "expires_at is not a valid date." };
2584
- }
2585
- if (input.expires_at && isExpired(input.expires_at, now)) {
2586
- return { ok: false, message: "expires_at must be in the future." };
2587
- }
2588
- if (input.rights_mode !== void 0 && !RIGHTS_MODES.has(input.rights_mode)) {
2589
- return { ok: false, message: "rights_mode must be private, users, roles, teams, or public." };
2590
- }
2591
- if (input.s3key !== void 0 && (typeof input.s3key !== "string" || !input.s3key.trim())) {
2592
- return { ok: false, message: "s3key must be a non-empty string." };
2593
- }
2594
- if (input.agent_slots !== void 0) {
2595
- const slotsResult = validateAgentSlots(input.agent_slots);
2596
- if (!slotsResult.ok) return { ok: false, message: slotsResult.message };
2597
- }
2598
- return { ok: true };
2599
- };
2600
- var ownsObjectKey = (key, user, s3prefix) => {
2601
- if (user.super_admin === true) return true;
2602
- let k = key.replace(/^\/+/, "");
2603
- const prefix = (s3prefix ?? "").replace(/\/+$/, "");
2604
- if (prefix && k.startsWith(prefix + "/")) k = k.slice(prefix.length + 1);
2605
- const owner = user.type === "api" ? "api" : String(user.id);
2606
- return k.startsWith(`user_${owner}/`);
2607
- };
2608
- var planShareUpdate = (input, row, newPasswordHash, now) => {
2609
- const mode = input.auth_mode ?? row.auth_mode;
2610
- const patch = { auth_mode: mode, updatedAt: now };
2611
- if (input.name !== void 0) patch.name = slugifyShareName(input.name);
2612
- if (input.s3key !== void 0) patch.s3key = input.s3key;
2613
- if (input.content_type !== void 0) patch.content_type = input.content_type;
2614
- patch.password_hash = mode === "password" ? newPasswordHash ?? row.password_hash : null;
2615
- if (input.expires_at !== void 0) patch.expires_at = input.expires_at;
2616
- if (mode === "regular") {
2617
- patch.rights_mode = input.rights_mode ?? (row.auth_mode === "regular" ? row.rights_mode ?? "private" : "private");
2618
- } else {
2619
- patch.rights_mode = "public";
2620
- }
2621
- if (input.agent_slots !== void 0) {
2622
- const slotsResult = validateAgentSlots(input.agent_slots);
2623
- if (slotsResult.ok) patch.agent_slots = slotsResult.slots;
2624
- }
2625
- return patch;
2626
- };
2627
- var hashSharePassword = (password) => bcrypt2.hash(password, 10);
2628
- var verifySharePassword = (password, hash) => bcrypt2.compare(password, hash);
2629
- var contentHeadersFor = (key, contentType, filename) => {
2630
- if (isHtmlKey(key)) return { contentType: "text/html; charset=utf-8" };
2631
- return {
2632
- contentType: contentType || "application/octet-stream",
2633
- disposition: `attachment; filename="${filename.replace(/"/g, "")}"`
2634
- };
2635
- };
2636
- var publicMetaFor = (row) => ({
2637
- auth_mode: row.auth_mode,
2638
- expires_at: row.expires_at ?? null,
2639
- filename: deriveFilename(row.s3key),
2640
- content_type: row.content_type ?? null,
2641
- is_html: isHtmlKey(row.s3key)
2642
- });
2643
- var getSharedArtifactByName = (db, name) => db("shared_artifacts").where({ name }).first();
2644
-
2645
2604
  // src/graphql/utilities/agent-guest-fields.ts
2646
2605
  var VALID_GUEST_AUTH_MODES = /* @__PURE__ */ new Set(["public", "password", "regular"]);
2647
2606
  var applyAgentGuestFieldTransforms = async (input) => {
@@ -3352,7 +3311,7 @@ function createMutations(table, contexts, tools, config) {
3352
3311
  }
3353
3312
  if (table.name.singular === "user" && input.password) {
3354
3313
  console.log("[EXULU] Hashing password", input.password);
3355
- input.password = await bcrypt3.hash(input.password, SALT_ROUNDS);
3314
+ input.password = await bcrypt2.hash(input.password, SALT_ROUNDS);
3356
3315
  console.log("[EXULU] Hashed password", input.password);
3357
3316
  }
3358
3317
  if (table.name.singular === "agent") {
@@ -3431,7 +3390,7 @@ function createMutations(table, contexts, tools, config) {
3431
3390
  }
3432
3391
  if (table.name.singular === "user" && input.password) {
3433
3392
  console.log("[EXULU] Hashing password", input.password);
3434
- input.password = await bcrypt3.hash(input.password, SALT_ROUNDS);
3393
+ input.password = await bcrypt2.hash(input.password, SALT_ROUNDS);
3435
3394
  console.log("[EXULU] Hashed password", input.password);
3436
3395
  }
3437
3396
  if (table.name.singular === "agent") {
@@ -3518,7 +3477,7 @@ function createMutations(table, contexts, tools, config) {
3518
3477
  }
3519
3478
  if (table.name.singular === "user" && input.password) {
3520
3479
  console.log("[EXULU] Hashing password", input.password);
3521
- input.password = await bcrypt3.hash(input.password, SALT_ROUNDS);
3480
+ input.password = await bcrypt2.hash(input.password, SALT_ROUNDS);
3522
3481
  console.log("[EXULU] Hashed password", input.password);
3523
3482
  }
3524
3483
  if (table.name.singular === "agent") {
@@ -4306,6 +4265,7 @@ function dropEmptyMessages(messages) {
4306
4265
 
4307
4266
  // src/exulu/stored-file-url.ts
4308
4267
  var stripTrailingSlash = (s) => s.replace(/\/+$/, "");
4268
+ var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4309
4269
  function decodeKey(rawPath) {
4310
4270
  const key = rawPath.replace(/^\/+/, "");
4311
4271
  try {
@@ -4322,7 +4282,6 @@ function parseStoredFileUrl(url, store) {
4322
4282
  } catch {
4323
4283
  return void 0;
4324
4284
  }
4325
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return void 0;
4326
4285
  if (store.endpoint) {
4327
4286
  let endpoint;
4328
4287
  try {
@@ -4330,22 +4289,48 @@ function parseStoredFileUrl(url, store) {
4330
4289
  } catch {
4331
4290
  return void 0;
4332
4291
  }
4333
- if (parsed.host !== endpoint.host) return void 0;
4292
+ if (parsed.protocol !== endpoint.protocol || parsed.host !== endpoint.host) return void 0;
4334
4293
  const base = stripTrailingSlash(endpoint.pathname);
4335
4294
  const prefix = `${base}/${store.bucket}/`;
4336
4295
  if (!parsed.pathname.startsWith(prefix)) return void 0;
4337
- const key2 = decodeKey(parsed.pathname.slice(prefix.length));
4338
- return key2 ? { bucket: store.bucket, key: key2 } : void 0;
4296
+ const key = decodeKey(parsed.pathname.slice(prefix.length));
4297
+ return key ? { bucket: store.bucket, key } : void 0;
4339
4298
  }
4340
- if (!parsed.host.startsWith(`${store.bucket}.s3`) || !parsed.host.endsWith(".amazonaws.com")) {
4341
- return void 0;
4299
+ if (parsed.protocol !== "https:") return void 0;
4300
+ const region = "(?:\\.dualstack)?(?:[.-](?:[a-z]{2}(?:-gov)?-[a-z]+-\\d|accelerate|external-1))?";
4301
+ if (new RegExp(`^${escapeRegExp(store.bucket)}\\.s3${region}\\.amazonaws\\.com$`).test(parsed.host)) {
4302
+ const key = decodeKey(parsed.pathname);
4303
+ return key ? { bucket: store.bucket, key } : void 0;
4304
+ }
4305
+ if (new RegExp(`^s3${region}\\.amazonaws\\.com$`).test(parsed.host)) {
4306
+ const prefix = `/${store.bucket}/`;
4307
+ if (!parsed.pathname.startsWith(prefix)) return void 0;
4308
+ const key = decodeKey(parsed.pathname.slice(prefix.length));
4309
+ return key ? { bucket: store.bucket, key } : void 0;
4342
4310
  }
4343
- const key = decodeKey(parsed.pathname);
4344
- return key ? { bucket: store.bucket, key } : void 0;
4311
+ return void 0;
4312
+ }
4313
+ function mayResignStoredFileKey(key, ctx) {
4314
+ if (key.split("/").includes("..")) return false;
4315
+ let rest = key.replace(/^\/+/, "");
4316
+ const general = (ctx.s3prefix ?? "").replace(/\/+$/, "");
4317
+ if (general) {
4318
+ if (!rest.startsWith(`${general}/`)) return false;
4319
+ rest = rest.slice(general.length + 1);
4320
+ }
4321
+ const allowed = ["global/"];
4322
+ if (ctx.ownerId != null && ctx.ownerId !== "") allowed.push(`user_${ctx.ownerId}/`);
4323
+ if (ctx.speaker?.type === "api") allowed.push("user_api/");
4324
+ else if (ctx.speaker?.id != null && ctx.speaker.id !== "") allowed.push(`user_${ctx.speaker.id}/`);
4325
+ return allowed.some((p) => rest.startsWith(p));
4345
4326
  }
4346
4327
  async function resolveFreshFileUrl(url, opts) {
4347
4328
  const location = parseStoredFileUrl(url, opts);
4348
4329
  if (!location) return url;
4330
+ if (!opts.mayResign(location.key)) {
4331
+ console.warn(`[EXULU] not re-signing stored file URL outside the session's own files: "${location.key}"`);
4332
+ return url;
4333
+ }
4349
4334
  try {
4350
4335
  return await opts.sign(location.bucket, location.key);
4351
4336
  } catch (err2) {
@@ -4354,51 +4339,93 @@ async function resolveFreshFileUrl(url, opts) {
4354
4339
  }
4355
4340
  }
4356
4341
 
4357
- // src/exulu/session-file-listing.ts
4358
- var DEFAULT_MAX = 25;
4359
- function formatSize(bytes) {
4360
- if (bytes < 1024) return `${bytes} B`;
4361
- if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
4362
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
4363
- }
4364
- function formatAge(then, now) {
4365
- const minutes = Math.max(0, Math.round((now.getTime() - then.getTime()) / 6e4));
4366
- if (minutes < 1) return "just now";
4367
- if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
4368
- const hours = Math.round(minutes / 60);
4369
- if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
4370
- const days = Math.round(hours / 24);
4371
- return `${days} day${days === 1 ? "" : "s"} ago`;
4372
- }
4373
- function describeSessionFiles(files, opts = {}) {
4374
- const now = opts.now ?? /* @__PURE__ */ new Date();
4375
- const max = opts.max ?? DEFAULT_MAX;
4376
- const usable = files.filter((f) => f.name && !f.name.endsWith("/") && !isIgnoredArtifactPath(f.name)).sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
4377
- if (usable.length === 0) return "";
4378
- const shown = usable.slice(0, max);
4379
- const lines = shown.map((f) => {
4380
- const isNew = opts.lastTurnAt ? f.lastModified.getTime() > opts.lastTurnAt.getTime() : false;
4381
- return `- ${f.name} (${formatSize(f.size)}, ${formatAge(f.lastModified, now)})${isNew ? " [NEW since your last answer]" : ""}`;
4382
- });
4383
- const omitted = usable.length - shown.length;
4384
- if (omitted > 0) lines.push(`\u2026 and ${omitted} more file${omitted === 1 ? "" : "s"} (list them with \`ls\`).`);
4385
- return "Files currently in this session (newest first):\n" + lines.join("\n") + '\nThese files are available to you. When the user refers to one of these files, to "the document" or "the attachment", or asks something only such a file can answer, read it with parse_document, view_document_page or read_session_file. Otherwise proceed as usual, e.g. with the knowledge bases.';
4386
- }
4387
- async function loadSessionFileListing(opts) {
4388
- const uploads = opts.exuluConfig?.fileUploads;
4389
- if (!uploads?.s3Bucket) return "";
4390
- const prefix = sessionFilePrefix(opts.ownerId, opts.sessionID, uploads.s3prefix);
4342
+ // src/exulu/file-part-fetch.ts
4343
+ var MAX_FILE_PART_BYTES = MAX_ADOPT_UPLOAD_BYTES;
4344
+ var FILE_PART_FETCH_TIMEOUT_MS = 3e4;
4345
+ var mb = (bytes) => `${Math.floor(bytes / (1024 * 1024))}MB`;
4346
+ function decodeDataUrl(url) {
4347
+ const comma = url.indexOf(",");
4348
+ if (!url.startsWith("data:") || comma < 0) return void 0;
4349
+ const meta = url.slice(5, comma);
4350
+ const payload = url.slice(comma + 1);
4351
+ if (meta.split(";").includes("base64")) return Buffer.from(payload, "base64");
4391
4352
  try {
4392
- const objects = await listS3ObjectsByPrefix(prefix, opts.exuluConfig);
4393
- const files = objects.map((o) => ({
4394
- name: o.key.slice(o.key.indexOf(prefix) + prefix.length),
4395
- size: o.size,
4396
- lastModified: new Date(o.lastModified)
4397
- }));
4398
- return describeSessionFiles(files, { lastTurnAt: opts.lastTurnAt });
4399
- } catch (err2) {
4400
- console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`, err2);
4401
- return "";
4353
+ return Buffer.from(decodeURIComponent(payload), "utf8");
4354
+ } catch {
4355
+ return Buffer.from(payload, "utf8");
4356
+ }
4357
+ }
4358
+ async function readCapped(response, maxBytes) {
4359
+ const declared = Number(response.headers?.get?.("content-length") ?? NaN);
4360
+ if (Number.isFinite(declared) && declared > maxBytes) return void 0;
4361
+ if (!response.body) {
4362
+ const whole = Buffer.from(await response.arrayBuffer());
4363
+ return whole.length > maxBytes ? void 0 : whole;
4364
+ }
4365
+ const reader = response.body.getReader();
4366
+ const chunks = [];
4367
+ let total = 0;
4368
+ for (; ; ) {
4369
+ const { done, value } = await reader.read();
4370
+ if (done) break;
4371
+ total += value.byteLength;
4372
+ if (total > maxBytes) {
4373
+ await reader.cancel().catch(() => void 0);
4374
+ return void 0;
4375
+ }
4376
+ chunks.push(Buffer.from(value));
4377
+ }
4378
+ return Buffer.concat(chunks);
4379
+ }
4380
+ async function loadFilePartBytes(partUrl, filename, opts) {
4381
+ const maxBytes = opts.maxBytes ?? MAX_FILE_PART_BYTES;
4382
+ const tooLarge = `[Error: Could not load file ${filename}: the file is larger than the ${mb(maxBytes)} attachment limit.]`;
4383
+ if (typeof partUrl === "string" && partUrl.startsWith("data:")) {
4384
+ const bytes = decodeDataUrl(partUrl);
4385
+ if (!bytes) return { ok: false, error: `[Error: Could not load file ${filename}]` };
4386
+ if (bytes.length > maxBytes) return { ok: false, error: tooLarge };
4387
+ return { ok: true, bytes };
4388
+ }
4389
+ if (!opts.store || !parseStoredFileUrl(partUrl, opts.store)) {
4390
+ console.warn(`[EXULU] refusing to fetch file part "${filename}" from outside the configured storage`);
4391
+ return {
4392
+ ok: false,
4393
+ error: `[Error: Could not load file ${filename}: only files from this workspace's storage can be attached.]`
4394
+ };
4395
+ }
4396
+ const target = opts.fetchUrl ?? partUrl;
4397
+ if (!parseStoredFileUrl(target, opts.store)) {
4398
+ return {
4399
+ ok: false,
4400
+ error: `[Error: Could not load file ${filename}: only files from this workspace's storage can be attached.]`
4401
+ };
4402
+ }
4403
+ let response;
4404
+ try {
4405
+ response = await fetch(target, {
4406
+ // A redirect could point anywhere (internal addresses included); storage never needs one.
4407
+ redirect: "error",
4408
+ signal: AbortSignal.timeout(opts.timeoutMs ?? FILE_PART_FETCH_TIMEOUT_MS)
4409
+ });
4410
+ } catch (error) {
4411
+ const reason = error instanceof Error && error.name === "TimeoutError" ? "the download timed out" : "the download failed";
4412
+ console.error(`[EXULU] Failed to fetch file ${filename}:`, error);
4413
+ return { ok: false, error: `[Error: Could not load file ${filename}: ${reason}.]` };
4414
+ }
4415
+ if (response.status >= 300 && response.status < 400) {
4416
+ return { ok: false, error: `[Error: Could not load file ${filename}: redirects are not followed.]` };
4417
+ }
4418
+ if (!response.ok) {
4419
+ console.error(`[EXULU] Failed to fetch file: ${filename}, status: ${response.status} `);
4420
+ return { ok: false, error: `[Error: Could not load file ${filename}]` };
4421
+ }
4422
+ try {
4423
+ const bytes = await readCapped(response, maxBytes);
4424
+ if (!bytes) return { ok: false, error: tooLarge };
4425
+ return { ok: true, bytes };
4426
+ } catch (error) {
4427
+ console.error(`[EXULU] Failed to read file ${filename}:`, error);
4428
+ return { ok: false, error: `[Error: Could not load file ${filename}: the download failed.]` };
4402
4429
  }
4403
4430
  }
4404
4431
 
@@ -4517,6 +4544,59 @@ var isRunSessionMetadata = (metadata) => {
4517
4544
  }
4518
4545
  return typeof parsed === "object" && parsed !== null && !!parsed.job_result_id;
4519
4546
  };
4547
+ var parseMetadata2 = (metadata) => {
4548
+ if (metadata == null) return null;
4549
+ if (typeof metadata === "string") {
4550
+ try {
4551
+ const parsed = JSON.parse(metadata);
4552
+ return parsed && typeof parsed === "object" ? parsed : null;
4553
+ } catch {
4554
+ return null;
4555
+ }
4556
+ }
4557
+ return typeof metadata === "object" ? metadata : null;
4558
+ };
4559
+ async function verifyRunSessionOwnership(db, opts) {
4560
+ const { sessionId, workflowId, runUser } = opts;
4561
+ const session = await db.from("agent_sessions").where({ id: sessionId }).first();
4562
+ if (!session) {
4563
+ throw new Error(`Run session ${sessionId} not found; refusing to run routine ${workflowId}.`);
4564
+ }
4565
+ const markers = [session.run, parseMetadata2(session.metadata)?.routine_id].filter(
4566
+ (m) => m != null && m !== ""
4567
+ );
4568
+ const belongs = markers.length > 0 ? markers.every((m) => String(m) === String(workflowId)) : await checkRecordAccess(session, "write", runUser);
4569
+ if (!belongs) {
4570
+ throw new Error(`Session ${sessionId} does not belong to routine ${workflowId}; refusing to run.`);
4571
+ }
4572
+ }
4573
+ async function withRunSession(db, opts, generate) {
4574
+ const { existingSession, jobResultId, workflow, runUser, trigger } = opts;
4575
+ let sessionId;
4576
+ if (existingSession) {
4577
+ try {
4578
+ await verifyRunSessionOwnership(db, { sessionId: existingSession, workflowId: workflow.id, runUser });
4579
+ } catch (error) {
4580
+ await Promise.resolve(
4581
+ db.from("job_results").where({ id: jobResultId, session: existingSession }).update({ session: null })
4582
+ ).catch(() => {
4583
+ });
4584
+ throw error;
4585
+ }
4586
+ sessionId = existingSession;
4587
+ } else {
4588
+ sessionId = await createRunSession({
4589
+ db,
4590
+ workflow,
4591
+ userId: runUser.id,
4592
+ title: `${workflow.name} \u2014 ${(/* @__PURE__ */ new Date()).toISOString()}`,
4593
+ trigger,
4594
+ jobResultId
4595
+ });
4596
+ await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
4597
+ }
4598
+ return generate(sessionId);
4599
+ }
4520
4600
 
4521
4601
  // src/exulu/routines/routine-handle.ts
4522
4602
  var runIdFromSessionMetadata = (metadata) => {
@@ -4904,7 +4984,12 @@ var processFilePartsInMessages = async (messages, offloadCtx) => {
4904
4984
  const url = uploads?.s3Bucket ? await resolveFreshFileUrl(part.url, {
4905
4985
  endpoint: uploads.s3endpoint,
4906
4986
  bucket: uploads.s3Bucket,
4907
- sign: (bucket, key) => getPresignedUrl(bucket, key, offloadCtx.exuluConfig)
4987
+ sign: (bucket, key) => getPresignedUrl(bucket, key, offloadCtx.exuluConfig),
4988
+ mayResign: (key) => mayResignStoredFileKey(key, {
4989
+ s3prefix: uploads.s3prefix,
4990
+ ownerId: offloadCtx.sessionOwnerId ?? offloadCtx.user?.id,
4991
+ speaker: offloadCtx.user
4992
+ })
4908
4993
  }) : part.url;
4909
4994
  const classified = classifyFilePart(part);
4910
4995
  console.log(`[EXULU] File part classified as ${classified.kind}: ${classified.filename}`);
@@ -4920,17 +5005,14 @@ var processFilePartsInMessages = async (messages, offloadCtx) => {
4920
5005
  const filename = classified.filename;
4921
5006
  console.log(`[EXULU] Converting file part to text: ${filename}`);
4922
5007
  try {
4923
- const response = await fetch(url);
4924
- if (!response.ok) {
4925
- console.error(
4926
- `[EXULU] Failed to fetch file: ${filename}, status: ${response.status} `
4927
- );
4928
- return {
4929
- type: "text",
4930
- text: `[Error: Could not load file ${filename}]`
4931
- };
5008
+ const loaded = await loadFilePartBytes(part.url, filename, {
5009
+ store: uploads?.s3Bucket ? { endpoint: uploads.s3endpoint, bucket: uploads.s3Bucket } : void 0,
5010
+ fetchUrl: url
5011
+ });
5012
+ if (!loaded.ok) {
5013
+ return { type: "text", text: loaded.error };
4932
5014
  }
4933
- const bytes = Buffer.from(await response.arrayBuffer());
5015
+ const bytes = loaded.bytes;
4934
5016
  const extracted = await extractDocument({
4935
5017
  bytes,
4936
5018
  filename,
@@ -5052,11 +5134,18 @@ var generateSync = async ({
5052
5134
  let sessionItems;
5053
5135
  let sessionOwnerId;
5054
5136
  let lastTurnAt;
5137
+ let resolvedProject = null;
5055
5138
  if (session) {
5056
5139
  const sessionData = await getSession({ sessionID: session });
5057
5140
  sessionItems = sessionData.session_items;
5058
5141
  project = sessionData.project;
5059
5142
  sessionOwnerId = sessionData.user ?? void 0;
5143
+ resolvedProject = await resolveSessionProject({
5144
+ projectId: project,
5145
+ ownerId: sessionOwnerId ?? user?.id,
5146
+ owner: user,
5147
+ speaker: user
5148
+ });
5060
5149
  }
5061
5150
  const model = languageModel;
5062
5151
  console.log("[EXULU] Model created for generating sync.");
@@ -5140,7 +5229,12 @@ var generateSync = async ({
5140
5229
  memoryItems,
5141
5230
  contextWindow,
5142
5231
  disabledTools,
5143
- sessionOwnerId
5232
+ sessionOwnerId,
5233
+ void 0,
5234
+ void 0,
5235
+ void 0,
5236
+ // routineHandleFactory: the sync path is never part of a routine run
5237
+ resolvedProject
5144
5238
  );
5145
5239
  const agenticEntry = currentTools?.find((t) => t.id === "agentic_context_search");
5146
5240
  const agenticToolKey = agenticEntry ? sanitizeToolName(agenticEntry.name) : void 0;
@@ -5204,15 +5298,15 @@ var generateSync = async ({
5204
5298
  The user can upload files to this session through a side panel in the chat UI. Any such
5205
5299
  file appears in your working directory by its original filename \u2014 list them with \`ls\` or
5206
5300
  read them with the readFile tool. Files you produce yourself (via writeFile or via shell
5207
- commands like \`node create_doc.js\`) live in the same place. These files are scoped to
5208
- this single session; they are NOT visible in other sessions, projects, or knowledge bases.
5301
+ commands like \`node create_doc.js\`) live in the same place. ${sessionFilesScopeSentence(resolvedProject?.name, canRegisterSaveToProject({ sessionID: session, exuluConfig, project: resolvedProject, req, user, disabled: disabledTools }))}
5209
5302
  `;
5210
5303
  if (session) {
5211
5304
  const listing = await loadSessionFileListing({
5212
5305
  sessionID: session,
5213
5306
  ownerId: sessionOwnerId ?? user?.id ?? "api",
5214
5307
  exuluConfig,
5215
- lastTurnAt
5308
+ lastTurnAt,
5309
+ project: resolvedProject
5216
5310
  });
5217
5311
  if (listing) system += "\n\n" + listing;
5218
5312
  }
@@ -5410,12 +5504,19 @@ var generateStream = async ({
5410
5504
  let sessionOwnerId;
5411
5505
  let sessionMetadata;
5412
5506
  let lastTurnAt;
5507
+ let resolvedProject = null;
5413
5508
  if (session) {
5414
5509
  const sessionData = await getSession({ sessionID: session });
5415
5510
  project = sessionData.project;
5416
5511
  sessionItems = sessionData.session_items;
5417
5512
  sessionOwnerId = sessionData.user ?? void 0;
5418
5513
  sessionMetadata = sessionData.metadata;
5514
+ resolvedProject = await resolveSessionProject({
5515
+ projectId: project,
5516
+ ownerId: sessionOwnerId ?? user?.id,
5517
+ owner: user,
5518
+ speaker: user
5519
+ });
5419
5520
  console.log("[EXULU] loading previous messages from session: " + session);
5420
5521
  const previousMessages2 = await getAgentMessages({
5421
5522
  session,
@@ -5459,6 +5560,7 @@ var generateStream = async ({
5459
5560
  contextWindow,
5460
5561
  sessionID: session,
5461
5562
  user,
5563
+ sessionOwnerId,
5462
5564
  exuluConfig
5463
5565
  });
5464
5566
  const chronologicalMessages = messages;
@@ -5532,8 +5634,7 @@ ${skillsList}
5532
5634
  The user can upload files to this session through a side panel in the chat UI. Any such
5533
5635
  file appears in your working directory by its original filename \u2014 list them with \`ls\` or
5534
5636
  read them with the readFile tool. Files you produce yourself (via writeFile or via shell
5535
- commands like \`node create_doc.js\`) live in the same place. These files are scoped to
5536
- this single session; they are NOT visible in other sessions, projects, or knowledge bases.
5637
+ commands like \`node create_doc.js\`) live in the same place. ${sessionFilesScopeSentence(resolvedProject?.name, canRegisterSaveToProject({ sessionID: session, exuluConfig, project: resolvedProject, req, user, disabled: disabledTools }))}
5537
5638
 
5538
5639
  Note on large outputs: oversized tool outputs and large uploaded documents are automatically
5539
5640
  truncated in the conversation; the FULL content is saved as a session file (named in the
@@ -5545,7 +5646,8 @@ ${skillsList}
5545
5646
  sessionID: session,
5546
5647
  ownerId: sessionOwnerId ?? user?.id ?? "api",
5547
5648
  exuluConfig,
5548
- lastTurnAt
5649
+ lastTurnAt,
5650
+ project: resolvedProject
5549
5651
  });
5550
5652
  if (listing) system += "\n\n" + listing;
5551
5653
  }
@@ -5588,7 +5690,8 @@ When a tool execution is not approved by the user, do not retry it unless explic
5588
5690
  sessionOwnerId,
5589
5691
  memoryDecisions,
5590
5692
  skillDecisions,
5591
- routineHandleFactory
5693
+ routineHandleFactory,
5694
+ resolvedProject
5592
5695
  );
5593
5696
  console.log("[EXULU] Converted tools", Object.keys(tools));
5594
5697
  const includesContextSearchTool = currentTools?.some(
@@ -7227,77 +7330,77 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
7227
7330
  workflow,
7228
7331
  messages: inputMessages
7229
7332
  } = await validateWorkflowPayload(data);
7230
- let sessionId = started.session ?? void 0;
7231
- if (!sessionId) {
7232
- sessionId = await createRunSession({
7233
- db,
7333
+ const result = await withRunSession(
7334
+ db,
7335
+ {
7336
+ existingSession: started.session,
7337
+ jobResultId,
7234
7338
  workflow: {
7235
7339
  id: workflow.id,
7236
7340
  name: workflow.name,
7237
7341
  agent: workflow.agent,
7238
7342
  rights_mode: workflow.rights_mode
7239
7343
  },
7240
- userId: user.id,
7241
- title: `${workflow.name} \u2014 ${(/* @__PURE__ */ new Date()).toISOString()}`,
7242
- trigger: data.triggerSource ?? "api",
7243
- jobResultId
7244
- });
7245
- await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
7246
- }
7247
- const retries2 = 3;
7248
- let attempts = 0;
7249
- const promise = new Promise(async (resolve3, reject) => {
7250
- while (attempts < retries2) {
7251
- try {
7252
- const messages2 = await processUiMessagesFlow({
7253
- agent,
7254
- inputMessages: structuredClone(inputMessages),
7255
- contexts,
7256
- user,
7257
- tools,
7258
- config,
7259
- variables: data.inputs,
7260
- // Tag LLM spend to this routine (cron + ad-hoc share this path).
7261
- routine: { id: workflow.id, name: workflow.name },
7262
- jobResultId,
7263
- sessionId,
7264
- resumeFromIndex,
7265
- // Approval-gated tools pause unless the routine opted
7266
- // back into blanket pre-approval (spec §5.2).
7267
- respectToolApprovals: workflow.auto_approve_tools !== true
7268
- });
7269
- resolve3(messages2);
7270
- break;
7271
- } catch (error) {
7272
- console.error(
7273
- `[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
7274
- error instanceof Error ? error.message : String(error)
7275
- );
7276
- if (error instanceof FlowStepError) {
7277
- resumeFromIndex = error.stepIndex;
7278
- }
7279
- attempts++;
7280
- if (attempts >= retries2) {
7344
+ runUser: user,
7345
+ trigger: data.triggerSource ?? "api"
7346
+ },
7347
+ async (sessionId) => {
7348
+ const retries2 = 3;
7349
+ let attempts = 0;
7350
+ const promise = new Promise(async (resolve3, reject) => {
7351
+ while (attempts < retries2) {
7281
7352
  try {
7282
- await db.from("job_results").where({ id: jobResultId }).update({
7283
- metadata: JSON.stringify({
7284
- ...runBookkeeping,
7285
- current_step_index: resumeFromIndex
7286
- })
7353
+ const messages2 = await processUiMessagesFlow({
7354
+ agent,
7355
+ inputMessages: structuredClone(inputMessages),
7356
+ contexts,
7357
+ user,
7358
+ tools,
7359
+ config,
7360
+ variables: data.inputs,
7361
+ // Tag LLM spend to this routine (cron + ad-hoc share this path).
7362
+ routine: { id: workflow.id, name: workflow.name },
7363
+ jobResultId,
7364
+ sessionId,
7365
+ resumeFromIndex,
7366
+ // Approval-gated tools pause unless the routine opted
7367
+ // back into blanket pre-approval (spec §5.2).
7368
+ respectToolApprovals: workflow.auto_approve_tools !== true
7287
7369
  });
7288
- } catch (persistError) {
7370
+ resolve3(messages2);
7371
+ break;
7372
+ } catch (error) {
7289
7373
  console.error(
7290
- `[EXULU] failed to persist run progress for job ${bullmqJob.id}.`,
7291
- persistError
7374
+ `[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
7375
+ error instanceof Error ? error.message : String(error)
7292
7376
  );
7377
+ if (error instanceof FlowStepError) {
7378
+ resumeFromIndex = error.stepIndex;
7379
+ }
7380
+ attempts++;
7381
+ if (attempts >= retries2) {
7382
+ try {
7383
+ await db.from("job_results").where({ id: jobResultId }).update({
7384
+ metadata: JSON.stringify({
7385
+ ...runBookkeeping,
7386
+ current_step_index: resumeFromIndex
7387
+ })
7388
+ });
7389
+ } catch (persistError) {
7390
+ console.error(
7391
+ `[EXULU] failed to persist run progress for job ${bullmqJob.id}.`,
7392
+ persistError
7393
+ );
7394
+ }
7395
+ reject(new Error(error instanceof Error ? error.message : String(error)));
7396
+ }
7397
+ await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
7293
7398
  }
7294
- reject(new Error(error instanceof Error ? error.message : String(error)));
7295
7399
  }
7296
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
7297
- }
7400
+ });
7401
+ return await promise;
7298
7402
  }
7299
- });
7300
- const result = await promise;
7403
+ );
7301
7404
  const messages = result.messages;
7302
7405
  const metadata = result.metadata;
7303
7406
  const rowBeforeWrite = await db.from("job_results").where({ id: jobResultId }).first();
@@ -12379,6 +12482,24 @@ type EmbeddingModelOption {
12379
12482
  iteration: void 0
12380
12483
  };
12381
12484
  };
12485
+ const queueAccessDeps = {
12486
+ globalQueueNames: Object.values(global_queues),
12487
+ contextQueueNames: async () => {
12488
+ const names = /* @__PURE__ */ new Set();
12489
+ for (const ctx of contexts ?? []) {
12490
+ const pending = [
12491
+ ctx.processor?.config?.queue,
12492
+ ctx.embedder?.queue,
12493
+ ...(ctx.sources ?? []).map((source) => source.config?.queue)
12494
+ ];
12495
+ for (const queue of pending) {
12496
+ const config2 = await Promise.resolve(queue).catch(() => void 0);
12497
+ if (config2?.queue?.name) names.add(config2.queue.name);
12498
+ }
12499
+ }
12500
+ return names;
12501
+ }
12502
+ };
12382
12503
  resolvers.Query["queues"] = async () => resolveAvailableQueues(
12383
12504
  () => exuluApp.get().queues(),
12384
12505
  Object.values(global_queues)
@@ -12387,6 +12508,7 @@ type EmbeddingModelOption {
12387
12508
  if (!args.queue) {
12388
12509
  throw new Error("Queue name is required");
12389
12510
  }
12511
+ await assertQueueAccess({ user: context.user, queue: args.queue, level: "read" }, queueAccessDeps);
12390
12512
  const queue = queues.list.get(args.queue);
12391
12513
  if (!queue) {
12392
12514
  throw new Error("Queue not found");
@@ -13115,79 +13237,7 @@ type EmbeddingModelOption {
13115
13237
  });
13116
13238
  return mapped;
13117
13239
  };
13118
- resolvers.Mutation["drainQueue"] = async (_, args, context, info) => {
13119
- if (!args.queue) {
13120
- throw new Error("Queue name is required");
13121
- }
13122
- const queue = queues.list.get(args.queue);
13123
- if (!queue) {
13124
- throw new Error("Queue not found");
13125
- }
13126
- const config2 = await queue.use();
13127
- await config2.queue.drain();
13128
- return { success: true };
13129
- };
13130
- resolvers.Mutation["pauseQueue"] = async (_, args, context, info) => {
13131
- if (!args.queue) {
13132
- throw new Error("Queue name is required");
13133
- }
13134
- const queue = queues.list.get(args.queue);
13135
- if (!queue) {
13136
- throw new Error("Queue not found");
13137
- }
13138
- const config2 = await queue.use();
13139
- await config2.queue.pause();
13140
- return { success: true };
13141
- };
13142
- resolvers.Mutation["resumeQueue"] = async (_, args, context, info) => {
13143
- if (!args.queue) {
13144
- throw new Error("Queue name is required");
13145
- }
13146
- const queue = queues.list.get(args.queue);
13147
- if (!queue) {
13148
- throw new Error("Queue not found");
13149
- }
13150
- const config2 = await queue.use();
13151
- await config2.queue.resume();
13152
- return { success: true };
13153
- };
13154
- resolvers.Mutation["deleteJob"] = async (_, args, context, info) => {
13155
- if (!args.id) {
13156
- throw new Error("Job ID is required");
13157
- }
13158
- if (!args.queue) {
13159
- throw new Error("Queue name is required");
13160
- }
13161
- const queue = queues.list.get(args.queue);
13162
- if (!queue) {
13163
- throw new Error("Queue not found");
13164
- }
13165
- const config2 = await queue.use();
13166
- await config2.queue.remove(args.id);
13167
- return { success: true };
13168
- };
13169
- resolvers.Mutation["retryJob"] = async (_, args) => {
13170
- if (!args.id) {
13171
- throw new Error("Job ID is required");
13172
- }
13173
- if (!args.queue) {
13174
- throw new Error("Queue name is required");
13175
- }
13176
- const queue = queues.list.get(args.queue);
13177
- if (!queue) {
13178
- throw new Error("Queue not found");
13179
- }
13180
- const config2 = await queue.use();
13181
- const job = await config2.queue.getJob(args.id);
13182
- if (!job) {
13183
- throw new Error("Job not found");
13184
- }
13185
- await config2.queue.add(job.name, job.data);
13186
- if (args.deleteOriginal) {
13187
- await config2.queue.remove(args.id);
13188
- }
13189
- return { success: true };
13190
- };
13240
+ Object.assign(resolvers.Mutation, createQueueMutationResolvers({ ...queueAccessDeps, getQueue: (name) => queues.list.get(name) }));
13191
13241
  const assertOwnsTranscriptionJob2 = async (id, context) => assertOwnsTranscriptionJob(context.db, context.user, id);
13192
13242
  resolvers.Mutation["transcriptionJobStart"] = async (_, args, context) => {
13193
13243
  const { user } = context;
@@ -13322,6 +13372,7 @@ type EmbeddingModelOption {
13322
13372
  if (!args.queue) {
13323
13373
  throw new Error("Queue name is required");
13324
13374
  }
13375
+ await assertQueueAccess({ user: context.user, queue: args.queue, level: "read" }, queueAccessDeps);
13325
13376
  const { client: client2 } = await redisClient();
13326
13377
  if (!client2) {
13327
13378
  throw new Error("Redis client not created properly");
@@ -15096,6 +15147,249 @@ function registerTranscriptExportRoute(app, deps) {
15096
15147
  });
15097
15148
  }
15098
15149
 
15150
+ // src/exulu/project-file-handlers.ts
15151
+ var LIST_CONCURRENCY = 10;
15152
+ async function mapWithConcurrency(items, limit, fn) {
15153
+ const results = new Array(items.length);
15154
+ let next = 0;
15155
+ const worker = async () => {
15156
+ while (next < items.length) {
15157
+ const i = next++;
15158
+ results[i] = await fn(items[i]);
15159
+ }
15160
+ };
15161
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
15162
+ return results;
15163
+ }
15164
+ async function listFilesWithOrigin(args) {
15165
+ const files = await mapWithConcurrency(
15166
+ // Skip the directory marker (key ending with /).
15167
+ args.objects.filter((obj) => !obj.key.endsWith("/")),
15168
+ LIST_CONCURRENCY,
15169
+ async (obj) => {
15170
+ const name = obj.key.split("/").pop() ?? obj.key;
15171
+ const [presignedUrl, origin] = await Promise.all([
15172
+ args.presign(obj.key),
15173
+ args.resolveOrigin(obj).catch(() => "user")
15174
+ ]);
15175
+ return {
15176
+ key: obj.key,
15177
+ name,
15178
+ size: obj.size,
15179
+ lastModified: obj.lastModified.toISOString(),
15180
+ contentType: args.inferContentType(name),
15181
+ presignedUrl,
15182
+ origin
15183
+ };
15184
+ }
15185
+ );
15186
+ files.sort((a, b) => b.lastModified.localeCompare(a.lastModified));
15187
+ return files;
15188
+ }
15189
+ function decideUploadSign(args) {
15190
+ const hit = args.existing.find((f) => f.name === args.name);
15191
+ if (hit && !args.overwrite) {
15192
+ return { ok: false, status: 409, body: { error: "exists", lastModified: hit.lastModified.toISOString() } };
15193
+ }
15194
+ if (!hit && args.existing.length >= MAX_PROJECT_FILES) {
15195
+ return { ok: false, status: 400, body: { error: "project_full", max: MAX_PROJECT_FILES } };
15196
+ }
15197
+ return { ok: true };
15198
+ }
15199
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15200
+ function makeLoadAuthedProject(deps) {
15201
+ return async (req, res, projectId, want) => {
15202
+ const authResult = await deps.authenticate(req);
15203
+ if (!authResult.user?.id) {
15204
+ res.status(authResult.code || 401).json({ detail: authResult.message });
15205
+ return null;
15206
+ }
15207
+ if (!UUID_RE2.test(projectId)) {
15208
+ res.status(404).json({ detail: `Project ${projectId} not found.` });
15209
+ return null;
15210
+ }
15211
+ const project = await deps.getProject(projectId);
15212
+ if (!project) {
15213
+ res.status(404).json({ detail: `Project ${projectId} not found.` });
15214
+ return null;
15215
+ }
15216
+ const rbac = await deps.getRbac(project);
15217
+ if (!hasProjectAccess({ project, rbac, user: authResult.user, want })) {
15218
+ res.status(403).json({ detail: `You don't have ${want} access to this project.` });
15219
+ return null;
15220
+ }
15221
+ return { user: authResult.user, project };
15222
+ };
15223
+ }
15224
+
15225
+ // src/exulu/project-file-routes.ts
15226
+ var PROJECT_UPLOAD_URL_TTL_SECONDS = 5 * 60;
15227
+ function isInside(key, fullPrefix) {
15228
+ return key.startsWith(fullPrefix) && !key.includes("..");
15229
+ }
15230
+ function registerProjectFileRoutes(app, deps) {
15231
+ const idOf2 = (req) => String(req.params.projectId ?? "");
15232
+ const rowId = (authed) => String(authed.project.id);
15233
+ const listObjects = async (projectId) => (await deps.s3.list(projectFilePrefix(projectId, deps.s3prefix).projectPrefix)).filter(
15234
+ (o) => !o.key.endsWith("/")
15235
+ );
15236
+ app.get("/projects/:projectId/files", async (req, res) => {
15237
+ const projectId = idOf2(req);
15238
+ const authed = await deps.loadAuthedProject(req, res, projectId, "read");
15239
+ if (!authed) return;
15240
+ const canWrite2 = await deps.canWrite(authed.user, authed.project);
15241
+ let objects;
15242
+ try {
15243
+ objects = await listObjects(rowId(authed));
15244
+ } catch (err2) {
15245
+ console.error("[PROJECT-FILES] list failed", err2);
15246
+ res.status(500).json({ detail: "Failed to list project files." });
15247
+ return;
15248
+ }
15249
+ const files = await listFilesWithOrigin({
15250
+ objects,
15251
+ presign: deps.s3.presign,
15252
+ resolveOrigin: deps.resolveOrigin,
15253
+ inferContentType: deps.inferContentType
15254
+ });
15255
+ res.json({ canWrite: canWrite2, files });
15256
+ });
15257
+ app.post("/projects/:projectId/files/upload-sign", async (req, res) => {
15258
+ const projectId = idOf2(req);
15259
+ const authed = await deps.loadAuthedProject(req, res, projectId, "write");
15260
+ if (!authed) return;
15261
+ const { filename, contentType, overwrite } = req.body ?? {};
15262
+ if (!filename || typeof filename !== "string") {
15263
+ res.status(400).json({ detail: "Missing filename in request body." });
15264
+ return;
15265
+ }
15266
+ const safeName = sanitizeFilename(filename);
15267
+ if (!safeName) {
15268
+ res.status(400).json({ detail: "Invalid filename (no path separators, no '..')." });
15269
+ return;
15270
+ }
15271
+ if (!contentType || typeof contentType !== "string") {
15272
+ res.status(400).json({ detail: "Missing contentType in request body." });
15273
+ return;
15274
+ }
15275
+ try {
15276
+ const objects = await listObjects(rowId(authed));
15277
+ const decision = decideUploadSign({
15278
+ name: safeName,
15279
+ overwrite: overwrite === true,
15280
+ existing: objects.map((o) => ({
15281
+ name: o.key.split("/").pop() ?? o.key,
15282
+ lastModified: o.lastModified
15283
+ }))
15284
+ });
15285
+ if (!decision.ok) {
15286
+ res.status(decision.status).json(decision.body);
15287
+ return;
15288
+ }
15289
+ const { fullProjectPrefix } = projectFilePrefix(rowId(authed), deps.s3prefix);
15290
+ const key = `${fullProjectPrefix}${safeName}`;
15291
+ res.json({ uploadUrl: await deps.s3.signUpload(key, contentType, PROJECT_UPLOAD_URL_TTL_SECONDS), key });
15292
+ } catch (err2) {
15293
+ console.error("[PROJECT-FILES] upload-sign failed", err2);
15294
+ res.status(500).json({ detail: "Failed to sign the upload." });
15295
+ }
15296
+ });
15297
+ app.delete("/projects/:projectId/files", async (req, res) => {
15298
+ const projectId = idOf2(req);
15299
+ const key = req.query.key;
15300
+ if (!key || typeof key !== "string") {
15301
+ res.status(400).json({ detail: "Missing or invalid 'key' query parameter." });
15302
+ return;
15303
+ }
15304
+ const authed = await deps.loadAuthedProject(req, res, projectId, "write");
15305
+ if (!authed) return;
15306
+ const { fullProjectPrefix } = projectFilePrefix(rowId(authed), deps.s3prefix);
15307
+ if (!isInside(key, fullProjectPrefix)) {
15308
+ res.status(403).json({ detail: "Key does not belong to this project." });
15309
+ return;
15310
+ }
15311
+ try {
15312
+ await deps.s3.remove(key);
15313
+ res.json({ deleted: true });
15314
+ } catch (err2) {
15315
+ console.error("[PROJECT-FILES] delete failed", err2);
15316
+ res.status(500).json({ detail: "Failed to delete project file." });
15317
+ }
15318
+ });
15319
+ app.get("/projects/:projectId/file/preview-pdf", async (req, res) => {
15320
+ if (!req.headers.authorization && typeof req.query.auth === "string") {
15321
+ req.headers.authorization = `Bearer ${req.query.auth}`;
15322
+ }
15323
+ const projectId = idOf2(req);
15324
+ const key = req.query.key;
15325
+ if (!key || typeof key !== "string") {
15326
+ res.status(400).json({ detail: "Missing or invalid 'key' query parameter." });
15327
+ return;
15328
+ }
15329
+ const authed = await deps.loadAuthedProject(req, res, projectId, "read");
15330
+ if (!authed) return;
15331
+ const { fullProjectPrefix } = projectFilePrefix(rowId(authed), deps.s3prefix);
15332
+ if (!isInside(key, fullProjectPrefix)) {
15333
+ res.status(403).json({ detail: "Key does not belong to this project." });
15334
+ return;
15335
+ }
15336
+ const etag = await deps.s3.etag(key);
15337
+ if (!etag) {
15338
+ res.status(404).json({ detail: "Source file not found in S3." });
15339
+ return;
15340
+ }
15341
+ try {
15342
+ const bytes = await deps.previewPdf(key, etag);
15343
+ res.setHeader("Content-Type", "application/pdf");
15344
+ res.setHeader("Cache-Control", "private, max-age=300");
15345
+ res.send(bytes);
15346
+ } catch (err2) {
15347
+ console.error("[PROJECT-FILES] preview failed", err2);
15348
+ res.status(500).json({ detail: deps.isPreviewError(err2) ? err2.message : "Failed to render preview." });
15349
+ }
15350
+ });
15351
+ app.post("/projects/:projectId/files/promote", async (req, res) => {
15352
+ const projectId = idOf2(req);
15353
+ const { sessionId, keys, overwrite } = req.body ?? {};
15354
+ if (typeof sessionId !== "string" || !sessionId || !Array.isArray(keys)) {
15355
+ res.status(400).json({ detail: "sessionId (string) and keys (array) are required." });
15356
+ return;
15357
+ }
15358
+ const authed = await deps.loadAuthedProject(req, res, projectId, "write");
15359
+ if (!authed) return;
15360
+ const sessionAuthed = await deps.loadAuthedSession(req, res, sessionId, "write");
15361
+ if (!sessionAuthed) return;
15362
+ const ownerId = sessionAuthed.session.user ?? sessionAuthed.user.id;
15363
+ const { fullSessionPrefix } = deps.buildSessionPrefixes(ownerId, sessionId);
15364
+ try {
15365
+ const result = await promoteSessionFiles({
15366
+ projectId: rowId(authed),
15367
+ s3prefix: deps.s3prefix,
15368
+ keys,
15369
+ fullSessionPrefix,
15370
+ overwrite: overwrite === true,
15371
+ s3: deps.s3
15372
+ });
15373
+ const copyFailed = result.rejected.some((r) => r.reason === COPY_FAILED_REASON);
15374
+ const status = result.clashes.length > 0 ? 409 : copyFailed && result.promoted.length === 0 ? 500 : 200;
15375
+ res.status(status).json(result);
15376
+ } catch (err2) {
15377
+ console.error("[PROJECT-FILES] promote failed", err2);
15378
+ res.status(500).json({ detail: "Failed to copy files into the project." });
15379
+ }
15380
+ });
15381
+ }
15382
+ function registerProjectFileRoutesUnconfigured(app) {
15383
+ const handler = (_req, res) => {
15384
+ res.status(500).json({ detail: "File uploads are not configured." });
15385
+ };
15386
+ app.get("/projects/:projectId/files", handler);
15387
+ app.post("/projects/:projectId/files/upload-sign", handler);
15388
+ app.delete("/projects/:projectId/files", handler);
15389
+ app.get("/projects/:projectId/file/preview-pdf", handler);
15390
+ app.post("/projects/:projectId/files/promote", handler);
15391
+ }
15392
+
15099
15393
  // src/exulu/viewer-identity-routes.ts
15100
15394
  var SHARED_ARTIFACT_ACCESS_PATH = "/shared-artifacts/:name/access";
15101
15395
  function registerViewerIdentityRoutes(app, deps) {
@@ -15136,6 +15430,56 @@ function registerViewerIdentityRoutes(app, deps) {
15136
15430
  });
15137
15431
  }
15138
15432
 
15433
+ // src/exulu/shared-artifact-create-route.ts
15434
+ function registerCreateShareRoute(app, deps) {
15435
+ app.post("/shared-artifacts", async (req, res) => {
15436
+ const db = await deps.getDb();
15437
+ const auth = await deps.authenticate(req);
15438
+ if (!auth.user?.id) {
15439
+ res.status(401).json({ detail: "Authentication required." });
15440
+ return;
15441
+ }
15442
+ const now = /* @__PURE__ */ new Date();
15443
+ const valid = validateCreateInput(req.body, now);
15444
+ if (!valid.ok) {
15445
+ res.status(400).json({ detail: valid.message });
15446
+ return;
15447
+ }
15448
+ const s3key = normalizeS3Key(req.body.s3key, deps.bucket);
15449
+ if (!ownsObjectKey(s3key, auth.user, deps.s3prefix)) {
15450
+ res.status(403).json({ detail: "You can only share a file you uploaded yourself." });
15451
+ return;
15452
+ }
15453
+ const name = slugifyShareName(req.body.name);
15454
+ if (!name) {
15455
+ res.status(400).json({ detail: "name must contain url-safe characters." });
15456
+ return;
15457
+ }
15458
+ const existing = await getSharedArtifactByName(db, name);
15459
+ if (existing) {
15460
+ res.status(409).json({ detail: "That share name is already taken." });
15461
+ return;
15462
+ }
15463
+ const auth_mode = req.body.auth_mode;
15464
+ const password_hash = auth_mode === "password" ? await hashSharePassword(req.body.password) : null;
15465
+ const rights_mode = auth_mode === "regular" ? req.body.rights_mode ?? "private" : "public";
15466
+ const [row] = await db("shared_artifacts").insert({
15467
+ name,
15468
+ s3key,
15469
+ auth_mode,
15470
+ password_hash,
15471
+ expires_at: req.body.expires_at ?? null,
15472
+ content_type: req.body.content_type ?? null,
15473
+ rights_mode,
15474
+ created_by: auth.user.id
15475
+ }).returning("*");
15476
+ if (auth_mode === "regular" && req.body.rbac) {
15477
+ await deps.handleRBACUpdate(db, "shared_artifact", row.id, req.body.rbac, []);
15478
+ }
15479
+ res.status(201).json({ name: row.name });
15480
+ });
15481
+ }
15482
+
15139
15483
  // ee/claim-check/routes.ts
15140
15484
  import { z as z5 } from "zod";
15141
15485
 
@@ -15157,7 +15501,7 @@ function pipelineConfigFor(agent) {
15157
15501
  // ee/claim-check/routes.ts
15158
15502
  var CLAIM_CHECK_PATH = "/claims/check";
15159
15503
  var CLAIM_CHECK_SESSION_PATH = "/claims/check/:session";
15160
- var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15504
+ var UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15161
15505
  function hasNumericUserId(user) {
15162
15506
  return Boolean(user?.id) && Number.isFinite(Number(user?.id));
15163
15507
  }
@@ -15345,7 +15689,7 @@ function registerClaimCheckRoutes(app, deps) {
15345
15689
  });
15346
15690
  return;
15347
15691
  }
15348
- if (deps.findClaimCheck && body.session && body.messageId && UUID_RE2.test(body.session)) {
15692
+ if (deps.findClaimCheck && body.session && body.messageId && UUID_RE3.test(body.session)) {
15349
15693
  try {
15350
15694
  const stored = await deps.findClaimCheck({
15351
15695
  session: body.session,
@@ -15466,7 +15810,7 @@ function registerClaimCheckRoutes(app, deps) {
15466
15810
  if (deadline) clearTimeout(deadline);
15467
15811
  deps.limiter.release();
15468
15812
  }
15469
- if (completedResult && body.session && body.messageId && UUID_RE2.test(body.session)) {
15813
+ if (completedResult && body.session && body.messageId && UUID_RE3.test(body.session)) {
15470
15814
  if (!deps.saveClaimCheck) {
15471
15815
  console.error(
15472
15816
  "[EXULU claim-check] saveClaimCheck is not wired; this check cannot survive a reload."
@@ -15491,7 +15835,7 @@ function registerClaimCheckRoutes(app, deps) {
15491
15835
  return;
15492
15836
  }
15493
15837
  const session = req.params.session ?? "";
15494
- if (!UUID_RE2.test(session)) {
15838
+ if (!UUID_RE3.test(session)) {
15495
15839
  res.status(400).json({ detail: "session must be a uuid." });
15496
15840
  return;
15497
15841
  }
@@ -16362,7 +16706,7 @@ function buildSentenceResults(sentences, states, claims) {
16362
16706
  }
16363
16707
 
16364
16708
  // ee/claim-check/concurrency.ts
16365
- async function mapWithConcurrency(items, limit, fn) {
16709
+ async function mapWithConcurrency2(items, limit, fn) {
16366
16710
  const results = new Array(items.length);
16367
16711
  const bound = Math.max(1, Math.floor(limit));
16368
16712
  let next = 0;
@@ -16410,7 +16754,7 @@ async function runBatched(batches, label, state, call) {
16410
16754
  const good = [];
16411
16755
  let pending = batches;
16412
16756
  for (let round = 0; pending.length > 0; round += 1) {
16413
- const settled = await mapWithConcurrency(pending, MAX_IN_FLIGHT, async (windows3) => call(windows3));
16757
+ const settled = await mapWithConcurrency2(pending, MAX_IN_FLIGHT, async (windows3) => call(windows3));
16414
16758
  const failed = [];
16415
16759
  settled.forEach((outcome, i) => {
16416
16760
  if (outcome.status === "fulfilled") {
@@ -16712,7 +17056,7 @@ async function runClaimCheck(args) {
16712
17056
  bySentence.set(claim.sentenceIndex, list);
16713
17057
  }
16714
17058
  const groups = chunk([...bySentence.values()], BATCH.verifySentences).map((g) => g.flat());
16715
- const verified = await mapWithConcurrency(groups, MAX_IN_FLIGHT, async (group) => {
17059
+ const verified = await mapWithConcurrency2(groups, MAX_IN_FLIGHT, async (group) => {
16716
17060
  const evidence = selectGroupEvidence(group.map((c) => c.text), indexed);
16717
17061
  return runVerification({
16718
17062
  claims: group.map((c) => ({ id: c.id, text: c.text })),
@@ -16775,7 +17119,7 @@ async function runClaimCheck(args) {
16775
17119
  `maxReRetrievals (${options.caps.maxReRetrievals}) reached; ${candidates.length - budget.length} unsupported claim(s) were not re-retrieved`
16776
17120
  );
16777
17121
  }
16778
- await mapWithConcurrency(budget, MAX_IN_FLIGHT, async (claim) => {
17122
+ await mapWithConcurrency2(budget, MAX_IN_FLIGHT, async (claim) => {
16779
17123
  try {
16780
17124
  const extra = await args.secondChance(claim.text);
16781
17125
  if (extra.length === 0) return;
@@ -17611,92 +17955,6 @@ var verifyRecallRequest = (headers, rawBody, secret = recallVerificationSecret()
17611
17955
  return passed ? { ok: true } : { ok: false, reason: "signature mismatch" };
17612
17956
  };
17613
17957
 
17614
- // src/exulu/session-file-adopt.ts
17615
- var MAX_ADOPT_KEYS = 20;
17616
- var MAX_ADOPT_UPLOAD_BYTES = 50 * 1024 * 1024;
17617
- var ownsAdoptKey = (key, user, s3prefix) => {
17618
- const prefix = (s3prefix ?? "").replace(/\/+$/, "");
17619
- const stripped = prefix && key.startsWith(`${prefix}/`) ? key.slice(prefix.length + 1) : key;
17620
- const owner = user.type === "api" ? "api" : String(user.id);
17621
- return stripped.startsWith(`user_${owner}/`);
17622
- };
17623
- var planAdoptKeys = (keys, user, s3prefix, bucket) => {
17624
- if (!Array.isArray(keys)) {
17625
- return { accepted: [], rejected: [] };
17626
- }
17627
- if (keys.length > MAX_ADOPT_KEYS) {
17628
- return {
17629
- accepted: [],
17630
- rejected: keys.map((k) => ({
17631
- key: typeof k === "string" ? k : String(k),
17632
- reason: `Batch exceeds the ${MAX_ADOPT_KEYS}-key adopt limit.`
17633
- }))
17634
- };
17635
- }
17636
- const accepted = [];
17637
- const rejected = [];
17638
- const filenameOwners = /* @__PURE__ */ new Map();
17639
- for (const raw of keys) {
17640
- if (typeof raw !== "string" || !raw.trim()) {
17641
- rejected.push({
17642
- key: typeof raw === "string" ? raw : String(raw),
17643
- reason: "Key must be a non-empty string."
17644
- });
17645
- continue;
17646
- }
17647
- let normalized;
17648
- try {
17649
- normalized = normalizeS3Key(raw, bucket).replace(/^\/+/, "");
17650
- } catch {
17651
- rejected.push({ key: raw, reason: "Key is not a valid S3 key." });
17652
- continue;
17653
- }
17654
- if (normalized.includes("..")) {
17655
- rejected.push({ key: raw, reason: "Key contains a path traversal segment." });
17656
- continue;
17657
- }
17658
- if (!ownsAdoptKey(normalized, user, s3prefix)) {
17659
- rejected.push({ key: raw, reason: "You do not own this object." });
17660
- continue;
17661
- }
17662
- const filename = sanitizeFilename(deriveFilename(normalized));
17663
- if (!filename) {
17664
- rejected.push({ key: raw, reason: "Could not derive a safe filename." });
17665
- continue;
17666
- }
17667
- if (filenameOwners.has(filename)) {
17668
- const existing = filenameOwners.get(filename);
17669
- if (existing) {
17670
- const idx = accepted.indexOf(existing);
17671
- if (idx !== -1) accepted.splice(idx, 1);
17672
- rejected.push({ key: existing.key, reason: "Filename collides with another key in this batch." });
17673
- filenameOwners.set(filename, null);
17674
- }
17675
- rejected.push({ key: raw, reason: "Filename collides with another key in this batch." });
17676
- continue;
17677
- }
17678
- const entry = { source: normalized, filename, key: raw };
17679
- accepted.push(entry);
17680
- filenameOwners.set(filename, entry);
17681
- }
17682
- return { accepted, rejected };
17683
- };
17684
- var planAdoptSizeCheck = (checks, maxBytes) => {
17685
- const rejected = [];
17686
- for (const { entry, size } of checks) {
17687
- if (size === null) {
17688
- rejected.push({ key: entry.key, reason: "Source object not found." });
17689
- } else if (size > maxBytes) {
17690
- rejected.push({
17691
- key: entry.key,
17692
- reason: `File exceeds the ${Math.floor(maxBytes / (1024 * 1024))}MB upload limit.`
17693
- });
17694
- }
17695
- }
17696
- if (rejected.length > 0) return { proceed: false, rejected };
17697
- return { proceed: true };
17698
- };
17699
-
17700
17958
  // src/exulu/public-agents.ts
17701
17959
  var publicAgentView = (row, slug) => ({
17702
17960
  id: row.id,
@@ -19259,6 +19517,18 @@ ${customInstructions}` : agent.instructions,
19259
19517
  }
19260
19518
  return { user: authResult.user, session, db };
19261
19519
  };
19520
+ const projectRbac = async (project) => {
19521
+ const { db } = await postgresClient();
19522
+ return RBACResolver(db, "project", project.id, project.rights_mode || "private");
19523
+ };
19524
+ const loadAuthedProject = makeLoadAuthedProject({
19525
+ authenticate: (req) => requestValidators.authenticate(req),
19526
+ getProject: async (id) => {
19527
+ const { db } = await postgresClient();
19528
+ return db.from("projects").where({ id }).first();
19529
+ },
19530
+ getRbac: projectRbac
19531
+ });
19262
19532
  const loadStyle = async (db, styleId, user, res) => {
19263
19533
  if (!styleId) return { markdown: null, id: null };
19264
19534
  const row = await db.from("platform_configurations").where({ id: styleId }).first();
@@ -20336,8 +20606,8 @@ ${style.markdown}` : params.prompt;
20336
20606
  }
20337
20607
  const modelsBreakdown = breakdown?.models ?? row?.models ?? {};
20338
20608
  if (modelsBreakdown && typeof modelsBreakdown === "object") {
20339
- for (const [modelName, mb] of Object.entries(modelsBreakdown)) {
20340
- const mm = mb?.metrics ?? mb;
20609
+ for (const [modelName, mb2] of Object.entries(modelsBreakdown)) {
20610
+ const mm = mb2?.metrics ?? mb2;
20341
20611
  addToModel(modelName, mm);
20342
20612
  }
20343
20613
  }
@@ -21348,21 +21618,12 @@ ${style.markdown}` : params.prompt;
21348
21618
  return;
21349
21619
  }
21350
21620
  const bucket = config.fileUploads.s3Bucket;
21351
- const files = await Promise.all(
21352
- objects.filter((obj) => !obj.key.endsWith("/")).map(async (obj) => {
21353
- const name = obj.key.split("/").pop() ?? obj.key;
21354
- const presignedUrl = await getPresignedUrl(bucket, obj.key, config);
21355
- return {
21356
- key: obj.key,
21357
- name,
21358
- size: obj.size,
21359
- lastModified: obj.lastModified.toISOString(),
21360
- contentType: inferContentType(name),
21361
- presignedUrl
21362
- };
21363
- })
21364
- );
21365
- files.sort((a, b) => b.lastModified.localeCompare(a.lastModified));
21621
+ const files = await listFilesWithOrigin({
21622
+ objects,
21623
+ presign: (key) => getPresignedUrl(bucket, key, config),
21624
+ resolveOrigin: getOriginResolver(config),
21625
+ inferContentType
21626
+ });
21366
21627
  res.json({ files });
21367
21628
  });
21368
21629
  app.post(
@@ -21571,6 +21832,30 @@ ${style.markdown}` : params.prompt;
21571
21832
  res.json({ adopted, rejected: [] });
21572
21833
  }
21573
21834
  );
21835
+ if (config.fileUploads) {
21836
+ const fileConfig = config;
21837
+ registerProjectFileRoutes(app, {
21838
+ s3prefix: config.fileUploads.s3prefix,
21839
+ loadAuthedProject,
21840
+ canWrite: async (user, project) => hasProjectAccess({ project, rbac: await projectRbac(project), user, want: "write" }),
21841
+ loadAuthedSession,
21842
+ buildSessionPrefixes,
21843
+ s3: {
21844
+ ...createPromoteS3(fileConfig),
21845
+ list: (prefix) => listS3ObjectsByPrefix(prefix, fileConfig),
21846
+ presign: (key) => getPresignedUrl(fileConfig.fileUploads.s3Bucket, key, fileConfig),
21847
+ signUpload: (key, contentType, expiresIn) => getS3SignedUploadUrl(key, contentType, fileConfig, { expiresIn }),
21848
+ remove: (key) => deleteS3Object(key, fileConfig),
21849
+ etag: (key) => getS3ObjectEtag(key, fileConfig)
21850
+ },
21851
+ resolveOrigin: getOriginResolver(fileConfig),
21852
+ inferContentType,
21853
+ previewPdf: (key, etag) => getPdfPreviewBytes({ sourceKey: key, etag, config: fileConfig }),
21854
+ isPreviewError: (err2) => err2 instanceof PreviewRenderError
21855
+ });
21856
+ } else {
21857
+ registerProjectFileRoutesUnconfigured(app);
21858
+ }
21574
21859
  async function resolveTargetUser(req, res, opts) {
21575
21860
  const authResult = await requestValidators.authenticate(req);
21576
21861
  if (!authResult.user?.id) {
@@ -21874,48 +22159,12 @@ ${style.markdown}` : params.prompt;
21874
22159
  }
21875
22160
  res.json({ agent_slots: readAgentSlots(row.agent_slots) });
21876
22161
  });
21877
- app.post("/shared-artifacts", async (req, res) => {
21878
- const { db } = await postgresClient();
21879
- const auth = await requestValidators.authenticate(req);
21880
- if (!auth.user?.id) {
21881
- res.status(401).json({ detail: "Authentication required." });
21882
- return;
21883
- }
21884
- const now = /* @__PURE__ */ new Date();
21885
- const valid = validateCreateInput(req.body, now);
21886
- if (!valid.ok) {
21887
- res.status(400).json({ detail: valid.message });
21888
- return;
21889
- }
21890
- const bucket = config.fileUploads?.s3Bucket ?? "";
21891
- const s3key = normalizeS3Key(req.body.s3key, bucket);
21892
- const name = slugifyShareName(req.body.name);
21893
- if (!name) {
21894
- res.status(400).json({ detail: "name must contain url-safe characters." });
21895
- return;
21896
- }
21897
- const existing = await getSharedArtifactByName(db, name);
21898
- if (existing) {
21899
- res.status(409).json({ detail: "That share name is already taken." });
21900
- return;
21901
- }
21902
- const auth_mode = req.body.auth_mode;
21903
- const password_hash = auth_mode === "password" ? await hashSharePassword(req.body.password) : null;
21904
- const rights_mode = auth_mode === "regular" ? req.body.rights_mode ?? "private" : "public";
21905
- const [row] = await db("shared_artifacts").insert({
21906
- name,
21907
- s3key,
21908
- auth_mode,
21909
- password_hash,
21910
- expires_at: req.body.expires_at ?? null,
21911
- content_type: req.body.content_type ?? null,
21912
- rights_mode,
21913
- created_by: auth.user.id
21914
- }).returning("*");
21915
- if (auth_mode === "regular" && req.body.rbac) {
21916
- await handleRBACUpdate(db, "shared_artifact", row.id, req.body.rbac, []);
21917
- }
21918
- res.status(201).json({ name: row.name });
22162
+ registerCreateShareRoute(app, {
22163
+ authenticate: (req) => requestValidators.authenticate(req),
22164
+ getDb: async () => (await postgresClient()).db,
22165
+ bucket: config.fileUploads?.s3Bucket ?? "",
22166
+ s3prefix: config.fileUploads?.s3prefix,
22167
+ handleRBACUpdate
21919
22168
  });
21920
22169
  app.get("/shared-artifacts/:name/meta", async (req, res) => {
21921
22170
  const { db } = await postgresClient();
@@ -22035,13 +22284,13 @@ ${style.markdown}` : params.prompt;
22035
22284
  if (!agentModel) return "";
22036
22285
  return "";
22037
22286
  };
22038
- const UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22287
+ const UUID_RE4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22039
22288
  const stripBucketPrefix = (key, cfg) => {
22040
22289
  const bucket = cfg.fileUploads?.s3Bucket;
22041
22290
  return bucket ? key.replace(`${bucket}/`, "") : key;
22042
22291
  };
22043
22292
  const getGuestAgentById = async (id) => {
22044
- if (!UUID_RE3.test(id)) return void 0;
22293
+ if (!UUID_RE4.test(id)) return void 0;
22045
22294
  const { db } = await postgresClient();
22046
22295
  return db.from("agents").where({ id, guest_access: true, active: true }).first();
22047
22296
  };