@exulu/backend 5.13.0 → 5.14.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.
@@ -4,11 +4,12 @@ import {
4
4
  checkLicense,
5
5
  isLiteLLMEnabled,
6
6
  postgresClient,
7
+ processWideLimiters,
7
8
  provisionDefaultUserBudget,
8
9
  resolveModel,
9
10
  waitForLiteLLMReady,
10
11
  withRetry
11
- } from "./chunk-4W3V7IHR.js";
12
+ } from "./chunk-NBDSN45T.js";
12
13
  import {
13
14
  findLiteLLMModel
14
15
  } from "./chunk-F534XOQR.js";
@@ -668,7 +669,7 @@ var ExuluTool = class _ExuluTool {
668
669
  if (!agent) {
669
670
  throw new Error("Agent not found.");
670
671
  }
671
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-IYEO2RV6.js");
672
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-UT7TOLLD.js");
672
673
  const tools = await convertExuluToolsToAiSdkTools2(
673
674
  [this],
674
675
  [],
@@ -2544,24 +2545,28 @@ function requiresPlainObject(schema) {
2544
2545
  function preserveDescription(original, rebuilt) {
2545
2546
  return original.description ? rebuilt.describe(original.description) : rebuilt;
2546
2547
  }
2547
- function loosenForTransport(schema) {
2548
+ function loosenForTransport(schema, options = {}) {
2549
+ return loosen(schema, options.nullableEntries === true);
2550
+ }
2551
+ function loosen(schema, nullEntries) {
2548
2552
  const def = schema.def;
2549
2553
  switch (def.type) {
2550
2554
  case "optional":
2551
- return preserveDescription(schema, z7.optional(loosenForTransport(def.innerType)));
2555
+ return preserveDescription(schema, z7.optional(loosen(def.innerType, nullEntries)));
2552
2556
  case "nullable":
2553
- return preserveDescription(schema, z7.nullable(loosenForTransport(def.innerType)));
2557
+ return preserveDescription(schema, z7.nullable(loosen(def.innerType, nullEntries)));
2554
2558
  case "default":
2555
2559
  return preserveDescription(
2556
2560
  schema,
2557
- loosenForTransport(def.innerType).default(
2561
+ loosen(def.innerType, nullEntries).default(
2558
2562
  def.defaultValue
2559
2563
  )
2560
2564
  );
2561
2565
  case "array":
2562
- return preserveDescription(schema, z7.array(loosenForTransport(def.element)));
2566
+ return preserveDescription(schema, z7.array(loosen(def.element, false)));
2563
2567
  case "record": {
2564
- const loosenedValue = loosenForTransport(def.valueType);
2568
+ const innerValue = loosen(def.valueType, false);
2569
+ const loosenedValue = nullEntries ? z7.nullable(innerValue) : innerValue;
2565
2570
  return preserveDescription(
2566
2571
  schema,
2567
2572
  schema.clone({ ...def, valueType: loosenedValue })
@@ -2570,7 +2575,7 @@ function loosenForTransport(schema) {
2570
2575
  case "union":
2571
2576
  return preserveDescription(
2572
2577
  schema,
2573
- z7.union(def.options.map((option) => loosenForTransport(option)))
2578
+ z7.union(def.options.map((option) => loosen(option, false)))
2574
2579
  );
2575
2580
  case "object": {
2576
2581
  const shape = def.shape;
@@ -2578,7 +2583,8 @@ function loosenForTransport(schema) {
2578
2583
  for (const key of Object.keys(shape)) {
2579
2584
  const child = shape[key];
2580
2585
  if (!child) continue;
2581
- loosenedShape[key] = loosenForTransport(child);
2586
+ const loosenedChild = loosen(child, false);
2587
+ loosenedShape[key] = nullEntries ? preserveDescription(child, z7.nullable(loosenedChild)) : loosenedChild;
2582
2588
  }
2583
2589
  return preserveDescription(
2584
2590
  schema,
@@ -3939,7 +3945,7 @@ function sanitizeToolName(name) {
3939
3945
  }
3940
3946
 
3941
3947
  // src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts
3942
- import { randomUUID as randomUUID7 } from "crypto";
3948
+ import { randomUUID as randomUUID8 } from "crypto";
3943
3949
 
3944
3950
  // types/enums/statistics.ts
3945
3951
  var STATISTICS_TYPE_ENUM = {
@@ -4178,7 +4184,8 @@ import {
4178
4184
  UploadPartCommand,
4179
4185
  ListObjectsV2Command,
4180
4186
  HeadObjectCommand,
4181
- DeleteObjectCommand
4187
+ DeleteObjectCommand,
4188
+ DeleteObjectsCommand
4182
4189
  } from "@aws-sdk/client-s3";
4183
4190
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
4184
4191
  import { STSClient, GetFederationTokenCommand } from "@aws-sdk/client-sts";
@@ -4291,6 +4298,55 @@ function planPromote(args) {
4291
4298
  return { accepted, rejected, clashes };
4292
4299
  }
4293
4300
 
4301
+ // src/exulu/document-cache/keys.ts
4302
+ import { createHash as createHash2 } from "crypto";
4303
+ import { extname } from "path";
4304
+ var DERIVED_ROOT = "derived";
4305
+ var EXTRACTOR_VERSION = 1;
4306
+ var generalPrefix2 = (s3prefix) => {
4307
+ const trimmed = (s3prefix ?? "").replace(/^\/+|\/+$/g, "");
4308
+ return trimmed ? `${trimmed}/` : "";
4309
+ };
4310
+ var sha256 = (value) => createHash2("sha256").update(value).digest("hex");
4311
+ function isDerivedKey(key, s3prefix) {
4312
+ return key.replace(/^\/+/, "").startsWith(`${generalPrefix2(s3prefix)}${DERIVED_ROOT}/`);
4313
+ }
4314
+ function contentKey(sha256Hex2, fingerprintId, s3prefix) {
4315
+ return `${generalPrefix2(s3prefix)}${DERIVED_ROOT}/content/${sha256Hex2}/${fingerprintId}.md`;
4316
+ }
4317
+ function pointerKey(bucket, fullKey, s3prefix) {
4318
+ return `${generalPrefix2(s3prefix)}${DERIVED_ROOT}/pointers/${sha256(`${bucket}/${fullKey}`)}.json`;
4319
+ }
4320
+ function extractorFingerprint(args) {
4321
+ const processorConfig = args.exuluConfig?.attachments?.documentProcessor;
4322
+ let label;
4323
+ if (processorConfig?.processor) {
4324
+ const { name, model } = processorConfig.processor;
4325
+ const ocrModel = model?.trim() || (name === "mistral" ? "mistral-ocr" : "-");
4326
+ const vlm = processorConfig.vlm?.model ? `vlm:${processorConfig.vlm.model}` : "vlm:off";
4327
+ const extension = extname(args.filename).toLowerCase() || "-";
4328
+ const chunk = processorConfig.processor.maxPagesPerChunk ?? 25;
4329
+ label = `document-processor/${name}/${ocrModel}/${vlm}/${extension}/chunk:${chunk}@${EXTRACTOR_VERSION}`;
4330
+ } else if (args.filename.toLowerCase().endsWith(".pdf")) {
4331
+ label = `pdftotext@${EXTRACTOR_VERSION}`;
4332
+ } else {
4333
+ label = `officeparser@${EXTRACTOR_VERSION}`;
4334
+ }
4335
+ return { id: sha256(label).slice(0, 16), label };
4336
+ }
4337
+ function documentCacheDays(env = process.env) {
4338
+ const raw = env.EXULU_DOCUMENT_CACHE_DAYS;
4339
+ if (raw === void 0 || raw.trim() === "") return 365;
4340
+ const n = Number(raw);
4341
+ return Number.isInteger(n) && n >= 0 ? n : 365;
4342
+ }
4343
+ function documentMaxPages(env = process.env) {
4344
+ const raw = env.EXULU_DOCUMENT_MAX_PAGES;
4345
+ if (raw === void 0 || raw.trim() === "") return 300;
4346
+ const n = Number(raw);
4347
+ return Number.isInteger(n) && n > 0 ? n : 300;
4348
+ }
4349
+
4294
4350
  // src/uppy/index.ts
4295
4351
  var expiresIn = 60 * 60 * 24 * 1;
4296
4352
  var s3Client;
@@ -4525,6 +4581,7 @@ var getS3ObjectMetadataStrict = async (key, config) => {
4525
4581
  }
4526
4582
  };
4527
4583
  function mayUseGenericS3Route(key, user, s3prefix) {
4584
+ if (isDerivedKey(key, s3prefix)) return false;
4528
4585
  if (user.type === "api" || user.super_admin) return true;
4529
4586
  return !isProjectKey(key, s3prefix);
4530
4587
  }
@@ -4600,6 +4657,85 @@ var getS3ObjectBytes = async (key, config) => {
4600
4657
  const byteArray = await response.Body.transformToByteArray();
4601
4658
  return Buffer.from(byteArray);
4602
4659
  };
4660
+ var getS3ObjectTextExact = async (key, config) => {
4661
+ if (!config.fileUploads) {
4662
+ throw new Error("File uploads are not configured");
4663
+ }
4664
+ const client = getS3Client(config);
4665
+ try {
4666
+ const response = await client.send(
4667
+ new GetObjectCommand({ Bucket: config.fileUploads.s3Bucket, Key: key })
4668
+ );
4669
+ if (!response.Body) return null;
4670
+ return {
4671
+ text: await response.Body.transformToString("utf-8"),
4672
+ lastModified: response.LastModified ?? /* @__PURE__ */ new Date(0),
4673
+ metadata: response.Metadata ?? {}
4674
+ };
4675
+ } catch (err3) {
4676
+ if (isS3NotFound(err3)) return null;
4677
+ throw err3;
4678
+ }
4679
+ };
4680
+ var getS3ObjectBytesWithInfo = async (key, config) => {
4681
+ if (!config.fileUploads) {
4682
+ throw new Error("File uploads are not configured");
4683
+ }
4684
+ const client = getS3Client(config);
4685
+ const response = await client.send(
4686
+ new GetObjectCommand({ Bucket: config.fileUploads.s3Bucket, Key: key })
4687
+ );
4688
+ if (!response.Body) {
4689
+ throw new Error(`Empty body for S3 key: ${key}`);
4690
+ }
4691
+ const bytes = Buffer.from(await response.Body.transformToByteArray());
4692
+ return {
4693
+ bytes,
4694
+ etag: response.ETag ?? null,
4695
+ lastModified: response.LastModified ?? null,
4696
+ size: response.ContentLength ?? bytes.length
4697
+ };
4698
+ };
4699
+ var headS3ObjectExact = async (key, config) => {
4700
+ if (!config.fileUploads) {
4701
+ throw new Error("File uploads are not configured");
4702
+ }
4703
+ const client = getS3Client(config);
4704
+ try {
4705
+ const response = await client.send(
4706
+ new HeadObjectCommand({ Bucket: config.fileUploads.s3Bucket, Key: key })
4707
+ );
4708
+ return {
4709
+ etag: response.ETag ?? null,
4710
+ lastModified: response.LastModified ?? null,
4711
+ size: response.ContentLength ?? null
4712
+ };
4713
+ } catch (err3) {
4714
+ if (isS3NotFound(err3)) return null;
4715
+ throw err3;
4716
+ }
4717
+ };
4718
+ var putS3ObjectTextExact = async (key, text, metadata, config, contentType = "text/markdown; charset=utf-8") => {
4719
+ if (!config.fileUploads) {
4720
+ throw new Error("File uploads are not configured");
4721
+ }
4722
+ const client = getS3Client(config);
4723
+ const body = Buffer.from(text, "utf-8");
4724
+ const safeMetadata = {};
4725
+ for (const [k, v] of Object.entries(metadata)) {
4726
+ safeMetadata[k] = /^[\x20-\x7e]*$/.test(v) ? v : encodeURIComponent(v);
4727
+ }
4728
+ await client.send(
4729
+ new PutObjectCommand({
4730
+ Bucket: config.fileUploads.s3Bucket,
4731
+ Key: key,
4732
+ Body: body,
4733
+ ContentType: contentType,
4734
+ ContentLength: body.byteLength,
4735
+ Metadata: safeMetadata
4736
+ })
4737
+ );
4738
+ };
4603
4739
  var deleteS3Object = async (key, config) => {
4604
4740
  if (!config.fileUploads) {
4605
4741
  throw new Error("File uploads are not configured");
@@ -4609,6 +4745,41 @@ var deleteS3Object = async (key, config) => {
4609
4745
  const command = new DeleteObjectCommand({ Bucket: bucket, Key: key });
4610
4746
  await client.send(command);
4611
4747
  };
4748
+ var listS3ObjectsExact = async (prefix, token, config) => {
4749
+ if (!config.fileUploads) {
4750
+ throw new Error("File uploads are not configured");
4751
+ }
4752
+ const client = getS3Client(config);
4753
+ const response = await client.send(
4754
+ new ListObjectsV2Command({
4755
+ Bucket: config.fileUploads.s3Bucket,
4756
+ Prefix: prefix,
4757
+ ...token && { ContinuationToken: token }
4758
+ })
4759
+ );
4760
+ const items = [];
4761
+ for (const obj of response.Contents ?? []) {
4762
+ if (obj.Key && obj.LastModified) items.push({ key: obj.Key, lastModified: obj.LastModified });
4763
+ }
4764
+ return { items, next: response.IsTruncated ? response.NextContinuationToken : void 0 };
4765
+ };
4766
+ var deleteS3ObjectsExact = async (keys, config) => {
4767
+ if (!config.fileUploads) {
4768
+ throw new Error("File uploads are not configured");
4769
+ }
4770
+ const client = getS3Client(config);
4771
+ for (let i = 0; i < keys.length; i += 1e3) {
4772
+ const response = await client.send(
4773
+ new DeleteObjectsCommand({
4774
+ Bucket: config.fileUploads.s3Bucket,
4775
+ Delete: { Objects: keys.slice(i, i + 1e3).map((Key) => ({ Key })), Quiet: true }
4776
+ })
4777
+ );
4778
+ if (response?.Errors?.length) {
4779
+ throw new Error(`S3 refused to delete ${response.Errors.length} object(s): ${response.Errors[0]?.Message}`);
4780
+ }
4781
+ }
4782
+ };
4612
4783
  var getS3SignedUploadUrl = async (key, contentType, config, opts = {}) => {
4613
4784
  if (!config.fileUploads) {
4614
4785
  throw new Error("File uploads are not configured");
@@ -6399,14 +6570,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
6399
6570
  for (const row of rows) {
6400
6571
  const centered = new Float64Array(dims);
6401
6572
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
6402
- const z21 = new Float64Array(basis.length);
6573
+ const z22 = new Float64Array(basis.length);
6403
6574
  for (const [b, vec] of basis.entries()) {
6404
6575
  let dot = 0;
6405
6576
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
6406
- z21[b] = dot;
6577
+ z22[b] = dot;
6407
6578
  }
6408
6579
  for (const [b, target] of next.entries()) {
6409
- const scale = z21[b] ?? 0;
6580
+ const scale = z22[b] ?? 0;
6410
6581
  if (scale === 0) continue;
6411
6582
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
6412
6583
  }
@@ -6504,12 +6675,12 @@ function ridgeFit(Z, Y, lambda) {
6504
6675
  });
6505
6676
  return { map, intercept };
6506
6677
  }
6507
- function applyMap(z21, map, intercept) {
6678
+ function applyMap(z22, map, intercept) {
6508
6679
  const out = [];
6509
6680
  for (let j = 0; j < 3; j += 1) {
6510
6681
  let v = intercept[j] ?? 0;
6511
6682
  const row = map[j] ?? [];
6512
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z21[d] ?? 0);
6683
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z22[d] ?? 0);
6513
6684
  out.push(Number.isFinite(v) ? v : 0);
6514
6685
  }
6515
6686
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -6532,8 +6703,8 @@ function fitResidual(Z, Y, map, intercept) {
6532
6703
  for (let i = 0; i < Z.length; i += 1) {
6533
6704
  const zi = Z[i] ?? [];
6534
6705
  const yi = Y[i] ?? [];
6535
- const [x, y, z21] = applyMap(zi, map, intercept);
6536
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z21 - finite(yi[2]));
6706
+ const [x, y, z22] = applyMap(zi, map, intercept);
6707
+ total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z22 - finite(yi[2]));
6537
6708
  }
6538
6709
  return finite(total / Z.length);
6539
6710
  }
@@ -6673,8 +6844,8 @@ async function chunkCoordinates({
6673
6844
  }
6674
6845
  return null;
6675
6846
  }
6676
- const [x, y, z21] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6677
- return { x, y, z: z21 };
6847
+ const [x, y, z22] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6848
+ return { x, y, z: z22 };
6678
6849
  });
6679
6850
  } catch (e) {
6680
6851
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -7461,13 +7632,13 @@ var extractEntitiesForItem = async ({
7461
7632
  };
7462
7633
 
7463
7634
  // src/exulu/entities/normalize.ts
7464
- import { createHash as createHash2 } from "crypto";
7635
+ import { createHash as createHash3 } from "crypto";
7465
7636
  var normalizeCanonicalKey = (name) => {
7466
7637
  return name.toLowerCase().normalize("NFKC").replace(/\s+/g, " ").trim().replace(/^[\s\p{P}]+|[\s\p{P}]+$/gu, "").trim();
7467
7638
  };
7468
7639
  var computeTypesSignature = (types) => {
7469
7640
  const names = Array.from(new Set(types.map((t) => t.name.toLowerCase().trim()))).sort().join("|");
7470
- return createHash2("sha1").update(names).digest("hex").slice(0, 16);
7641
+ return createHash3("sha1").update(names).digest("hex").slice(0, 16);
7471
7642
  };
7472
7643
 
7473
7644
  // src/exulu/entities/types.ts
@@ -12262,7 +12433,7 @@ var buildWriteSchema = (context, mode) => {
12262
12433
  break;
12263
12434
  case "json":
12264
12435
  jsonFieldNames.push(field.name);
12265
- schema = field.schema ? loosenForTransport(field.schema).describe(`The ${field.name} of the item.`) : z13.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
12436
+ schema = field.schema ? loosenForTransport(field.schema, { nullableEntries: mode === "update" }).describe(`The ${field.name} of the item.`) : z13.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
12266
12437
  break;
12267
12438
  case "markdown":
12268
12439
  schema = z13.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
@@ -12530,9 +12701,101 @@ var collectKbWriteTools = (agent, contexts, deps = {}) => {
12530
12701
  return tools;
12531
12702
  };
12532
12703
 
12533
- // src/templates/tools/save-to-project-tool.ts
12704
+ // src/exulu/turn-project.ts
12705
+ function createTurnProject(initial) {
12706
+ return { current: initial ? { ...initial } : null };
12707
+ }
12708
+ function currentProjectId(holder, fallback) {
12709
+ if (holder) return holder.current?.id ?? null;
12710
+ return fallback ?? null;
12711
+ }
12712
+
12713
+ // src/templates/tools/create-project-tool.ts
12534
12714
  import { z as z14 } from "zod";
12535
12715
 
12716
+ // src/exulu/project-access.ts
12717
+ var sameEntityId = (a, b) => a != null && b != null && a !== "" && b !== "" && String(a) === String(b);
12718
+ var idOf = (v) => typeof v === "object" && v ? v.id : v;
12719
+ function hasProjectAccess(args) {
12720
+ const { project, rbac, user, want } = args;
12721
+ if (user.super_admin) return true;
12722
+ if (user.type === "api" && (!user.scope_mode || user.scope_mode === "admin")) return true;
12723
+ if (project.rights_mode === "public" || rbac.type === "public") return true;
12724
+ if (project.created_by != null && String(project.created_by) === String(user.id)) return true;
12725
+ const satisfies = (rights) => rights === "write" || rights === "read" && want === "read";
12726
+ const granted = (grants, subject) => subject != null && (grants ?? []).some((g) => String(g.id) === String(subject) && satisfies(g.rights));
12727
+ switch (rbac.type) {
12728
+ case "users":
12729
+ return granted(rbac.users, user.id);
12730
+ case "roles":
12731
+ return granted(rbac.roles, idOf(user.role));
12732
+ case "teams":
12733
+ return granted(rbac.teams, idOf(user.team));
12734
+ default:
12735
+ return false;
12736
+ }
12737
+ }
12738
+
12739
+ // src/exulu/project-create.ts
12740
+ import { randomUUID as randomUUID4 } from "crypto";
12741
+
12742
+ // ee/rbac-resolver.ts
12743
+ var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
12744
+ const license = checkLicense();
12745
+ if (!license.rbac) {
12746
+ return {
12747
+ type: "public",
12748
+ users: [],
12749
+ roles: [],
12750
+ teams: []
12751
+ };
12752
+ }
12753
+ const rbacRecords = await db.from("rbac").where({
12754
+ entity: entityName,
12755
+ target_resource_id: resourceId
12756
+ }).select("*");
12757
+ const users = rbacRecords.filter((r) => r.access_type === "User")?.map((r) => ({ id: r.user_id, rights: r.rights }));
12758
+ const roles = rbacRecords.filter((r) => r.access_type === "Role")?.map((r) => ({ id: r.role_id, rights: r.rights }));
12759
+ const teams = rbacRecords.filter((r) => r.access_type === "Team")?.map((r) => ({ id: r.team_id, rights: r.rights }));
12760
+ let type = rights_mode || "private";
12761
+ if (type === "users" && users.length === 0) type = "private";
12762
+ if (type === "roles" && roles.length === 0) type = "private";
12763
+ if (type === "teams" && teams.length === 0) type = "private";
12764
+ return {
12765
+ type,
12766
+ users,
12767
+ roles,
12768
+ teams
12769
+ };
12770
+ };
12771
+
12772
+ // ee/invoke-skills/artifact-filter.ts
12773
+ var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
12774
+ "venv",
12775
+ ".venv",
12776
+ "env",
12777
+ "node_modules",
12778
+ "__pycache__",
12779
+ "site-packages",
12780
+ "dist-packages",
12781
+ ".cache",
12782
+ ".git",
12783
+ ".pytest_cache",
12784
+ ".mypy_cache",
12785
+ ".ipynb_checkpoints"
12786
+ ]);
12787
+ function isIgnoredArtifactPath(relativePath) {
12788
+ return relativePath.split(/[\\/]+/).some((segment) => IGNORED_SEGMENTS.has(segment));
12789
+ }
12790
+ var DEFAULT_ARTIFACT_CAP = 50;
12791
+ function capArtifacts(artifacts, max = DEFAULT_ARTIFACT_CAP) {
12792
+ if (artifacts.length <= max) return { kept: artifacts, omitted: 0 };
12793
+ return { kept: artifacts.slice(0, max), omitted: artifacts.length - max };
12794
+ }
12795
+ function needsDownload(localSize, remoteSize) {
12796
+ return localSize === void 0 || localSize !== remoteSize;
12797
+ }
12798
+
12536
12799
  // src/exulu/shared-artifacts.ts
12537
12800
  import bcrypt2 from "bcryptjs";
12538
12801
  var normalizeS3Key = (key, bucket) => {
@@ -12767,6 +13030,135 @@ var planAdoptSizeCheck = (checks, maxBytes) => {
12767
13030
  return { proceed: true };
12768
13031
  };
12769
13032
 
13033
+ // src/exulu/project-create.ts
13034
+ var MAX_PROJECT_NAME_LENGTH = 120;
13035
+ var MAX_PROJECT_DESCRIPTION_LENGTH = 2e3;
13036
+ var TOOL_OUTPUT_PREFIX = "tool-output-";
13037
+ var cachedProjectFields;
13038
+ var projectFields = () => {
13039
+ if (!cachedProjectFields) {
13040
+ cachedProjectFields = coreSchemas.get().projectsSchema().fields;
13041
+ }
13042
+ return cachedProjectFields;
13043
+ };
13044
+ async function createProjectForUser(db, user, input) {
13045
+ const name = String(input?.name ?? "").trim();
13046
+ if (!name || name.length > MAX_PROJECT_NAME_LENGTH) {
13047
+ throw new Error(`Project name must be 1 to ${MAX_PROJECT_NAME_LENGTH} characters.`);
13048
+ }
13049
+ const description = input.description == null ? void 0 : String(input.description).trim();
13050
+ if (description && description.length > MAX_PROJECT_DESCRIPTION_LENGTH) {
13051
+ throw new Error(`Project description must be at most ${MAX_PROJECT_DESCRIPTION_LENGTH} characters.`);
13052
+ }
13053
+ if (user?.id == null || user.id === "") throw new Error("A project needs a signed-in creator.");
13054
+ const values = { name, ...description ? { description } : {} };
13055
+ const validation = prepareItemWrite({ fields: projectFields(), existing: null, input: values });
13056
+ if (!validation.ok) throw new Error(validation.message);
13057
+ const row = { ...values, id: randomUUID4(), created_by: user.id, rights_mode: "private" };
13058
+ const [created] = await db("projects").insert(row).returning(["id", "name"]);
13059
+ if (!created?.id) throw new Error("The project could not be created.");
13060
+ return { id: String(created.id), name: String(created.name ?? name) };
13061
+ }
13062
+ var bareId = (v) => typeof v === "object" && v ? v.id : v;
13063
+ function canWriteSession(session, rbac, user) {
13064
+ if (sameEntityId(session.user, user.id)) return true;
13065
+ if (user.type === "api" && (!user.scope_mode || user.scope_mode === "admin")) return true;
13066
+ const grant = (list, subject) => subject != null && (list ?? []).some((g) => sameEntityId(g.id, subject) && g.rights === "write");
13067
+ switch (rbac.type) {
13068
+ case "users":
13069
+ return grant(rbac.users, user.id);
13070
+ case "roles":
13071
+ return grant(rbac.roles, bareId(user.role));
13072
+ case "teams":
13073
+ return grant(rbac.teams, bareId(user.team));
13074
+ default:
13075
+ return false;
13076
+ }
13077
+ }
13078
+ async function attachSessionToProject(db, args) {
13079
+ const { sessionId, projectId, user } = args;
13080
+ const session = await db.from("agent_sessions").where({ id: sessionId }).first();
13081
+ if (!session) throw new Error("Session not found.");
13082
+ if (session.project) throw new Error("This session already belongs to a project.");
13083
+ const sessionRbac = await RBACResolver(db, "agent_session", session.id, session.rights_mode || "private");
13084
+ if (!canWriteSession(session, sessionRbac, user)) {
13085
+ throw new Error("No write access to this session.");
13086
+ }
13087
+ const project = await db.from("projects").where({ id: projectId }).first();
13088
+ if (!project) throw new Error("Project not found.");
13089
+ const projectRbac = await RBACResolver(db, "project", project.id, project.rights_mode || "private");
13090
+ if (!hasProjectAccess({ project, rbac: projectRbac, user, want: "read" })) {
13091
+ throw new Error("No read access to this project.");
13092
+ }
13093
+ const updated = await db("agent_sessions").where({ id: sessionId }).whereNull("project").update({ project: projectId });
13094
+ if (!updated) throw new Error("This session already belongs to a project.");
13095
+ }
13096
+ async function createProjectAndAttach(db, user, input) {
13097
+ return db.transaction(async (trx) => {
13098
+ const created = await createProjectForUser(trx, user, { name: input.name, description: input.description });
13099
+ await attachSessionToProject(trx, { sessionId: input.sessionId, projectId: created.id, user });
13100
+ return created;
13101
+ });
13102
+ }
13103
+ var SKIP_CLASH = "Its name clashes with another file once sanitised.";
13104
+ var SKIP_UNKNOWN = "No session file with this name.";
13105
+ var SKIP_NESTED = "Only top-level session files can be moved.";
13106
+ var SKIP_TOO_LARGE = "It is larger than 50 MB.";
13107
+ var SKIP_PROJECT_FULL = `A project holds at most ${MAX_PROJECT_FILES} files.`;
13108
+ var isDefaultMoveCandidate = (name) => !name.includes("/") && !name.includes("\\") && !name.startsWith(TOOL_OUTPUT_PREFIX) && !isIgnoredArtifactPath(name);
13109
+ function planMove(args) {
13110
+ const skipped = [];
13111
+ let pool;
13112
+ if (args.requested) {
13113
+ const byName = new Map(args.files.map((f) => [f.name, f]));
13114
+ pool = [];
13115
+ const seen = /* @__PURE__ */ new Set();
13116
+ for (const raw of args.requested) {
13117
+ const name = String(raw ?? "").trim();
13118
+ if (!name || seen.has(name)) continue;
13119
+ seen.add(name);
13120
+ if (name.includes("/") || name.includes("\\")) {
13121
+ skipped.push({ name, reason: SKIP_NESTED });
13122
+ continue;
13123
+ }
13124
+ const hit = byName.get(name);
13125
+ if (!hit) skipped.push({ name, reason: SKIP_UNKNOWN });
13126
+ else pool.push(hit);
13127
+ }
13128
+ } else {
13129
+ pool = args.files.filter((f) => isDefaultMoveCandidate(f.name));
13130
+ }
13131
+ const groups = /* @__PURE__ */ new Map();
13132
+ for (const f of pool) {
13133
+ const safe = sanitizeFilename(f.name);
13134
+ groups.set(safe, [...groups.get(safe) ?? [], f]);
13135
+ }
13136
+ const usable = [];
13137
+ for (const f of pool) {
13138
+ const safe = sanitizeFilename(f.name);
13139
+ if (!safe) skipped.push({ name: f.name, reason: "Could not derive a safe filename." });
13140
+ else if ((groups.get(safe) ?? []).length > 1) skipped.push({ name: f.name, reason: SKIP_CLASH });
13141
+ else if (f.size > MAX_ADOPT_UPLOAD_BYTES) skipped.push({ name: f.name, reason: SKIP_TOO_LARGE });
13142
+ else usable.push(f);
13143
+ }
13144
+ const kept = usable.slice(0, MAX_PROJECT_FILES);
13145
+ for (const f of usable.slice(MAX_PROJECT_FILES)) skipped.push({ name: f.name, reason: SKIP_PROJECT_FULL });
13146
+ const batches = [];
13147
+ let batch = [];
13148
+ let bytes = 0;
13149
+ for (const f of kept) {
13150
+ if (batch.length >= MAX_PROMOTE_KEYS || batch.length > 0 && bytes + f.size > MAX_ADOPT_UPLOAD_BYTES) {
13151
+ batches.push(batch);
13152
+ batch = [];
13153
+ bytes = 0;
13154
+ }
13155
+ batch.push({ key: f.key, name: f.name });
13156
+ bytes += f.size;
13157
+ }
13158
+ if (batch.length > 0) batches.push(batch);
13159
+ return { batches, skipped };
13160
+ }
13161
+
12770
13162
  // src/exulu/project-files-promote.ts
12771
13163
  var COPY_FAILED_REASON = "Copying the file into the project failed.";
12772
13164
  async function promoteSessionFiles(args) {
@@ -12808,7 +13200,7 @@ async function promoteSessionFiles(args) {
12808
13200
  for (const a of plan.accepted) {
12809
13201
  try {
12810
13202
  await args.s3.copy(a.sourceKey, a.destKey);
12811
- promoted.push({ key: a.destKey, name: a.name });
13203
+ promoted.push({ key: a.destKey, name: a.name, sourceKey: a.sourceKey });
12812
13204
  } catch (err3) {
12813
13205
  console.error("[PROJECT-FILES] copy failed", a.sourceKey, err3);
12814
13206
  rejected.push({ key: a.sourceKey, reason: COPY_FAILED_REASON });
@@ -12816,38 +13208,175 @@ async function promoteSessionFiles(args) {
12816
13208
  }
12817
13209
  return { promoted, rejected, clashes: [] };
12818
13210
  }
12819
-
12820
- // ee/invoke-skills/artifact-filter.ts
12821
- var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
12822
- "venv",
12823
- ".venv",
12824
- "env",
12825
- "node_modules",
12826
- "__pycache__",
12827
- "site-packages",
12828
- "dist-packages",
12829
- ".cache",
12830
- ".git",
12831
- ".pytest_cache",
12832
- ".mypy_cache",
12833
- ".ipynb_checkpoints"
12834
- ]);
12835
- function isIgnoredArtifactPath(relativePath) {
12836
- return relativePath.split(/[\\/]+/).some((segment) => IGNORED_SEGMENTS.has(segment));
13211
+ async function moveSessionFiles(args) {
13212
+ const result = { moved: [], notMoved: [], originalsKept: [], keptForHistory: [] };
13213
+ const bare = (key) => key.replace(/^\/+/, "");
13214
+ const keep = new Set([...args.keepOriginalKeys ?? []].map(bare));
13215
+ for (const batch of args.batches) {
13216
+ let outcome;
13217
+ try {
13218
+ outcome = await promoteSessionFiles({
13219
+ projectId: args.projectId,
13220
+ s3prefix: args.s3prefix,
13221
+ keys: batch.map((f) => f.key),
13222
+ fullSessionPrefix: args.fullSessionPrefix,
13223
+ overwrite: false,
13224
+ s3: args.s3
13225
+ });
13226
+ } catch (err3) {
13227
+ console.error("[PROJECT-FILES] move batch failed", err3);
13228
+ for (const f of batch) result.notMoved.push({ name: f.name, reason: COPY_FAILED_REASON });
13229
+ continue;
13230
+ }
13231
+ const copied = new Set(outcome.promoted.map((p) => p.sourceKey));
13232
+ const rejectedBy = new Map(outcome.rejected.map((r) => [r.key, r.reason]));
13233
+ for (const f of batch) {
13234
+ if (!copied.has(f.key.replace(/^\/+/, ""))) {
13235
+ result.notMoved.push({
13236
+ name: f.name,
13237
+ reason: rejectedBy.get(f.key) ?? "A file with this name is already in the project."
13238
+ });
13239
+ continue;
13240
+ }
13241
+ if (keep.has(bare(f.key))) {
13242
+ result.keptForHistory.push(f.name);
13243
+ continue;
13244
+ }
13245
+ try {
13246
+ await args.s3.remove(f.key);
13247
+ result.moved.push(f.name);
13248
+ } catch (err3) {
13249
+ console.error("[PROJECT-FILES] could not delete session original after copy", f.key, err3);
13250
+ result.originalsKept.push(f.name);
13251
+ }
13252
+ }
13253
+ }
13254
+ return result;
12837
13255
  }
12838
- var DEFAULT_ARTIFACT_CAP = 50;
12839
- function capArtifacts(artifacts, max = DEFAULT_ARTIFACT_CAP) {
12840
- if (artifacts.length <= max) return { kept: artifacts, omitted: 0 };
12841
- return { kept: artifacts.slice(0, max), omitted: artifacts.length - max };
13256
+
13257
+ // src/exulu/file-origin.ts
13258
+ var ORIGIN_METADATA_KEY = "exulu-origin";
13259
+ function originFromMetadata(metadata) {
13260
+ return metadata?.[ORIGIN_METADATA_KEY] === "agent" ? "agent" : "user";
12842
13261
  }
12843
- function needsDownload(localSize, remoteSize) {
12844
- return localSize === void 0 || localSize !== remoteSize;
13262
+ function createOriginResolver(head) {
13263
+ const cache2 = /* @__PURE__ */ new Map();
13264
+ return async (file) => {
13265
+ const stamp = file.lastModified instanceof Date ? file.lastModified.toISOString() : String(file.lastModified);
13266
+ const id = `${file.key}\0${stamp}`;
13267
+ const hit = cache2.get(id);
13268
+ if (hit) return hit;
13269
+ try {
13270
+ const origin = originFromMetadata(await head(file.key));
13271
+ cache2.set(id, origin);
13272
+ return origin;
13273
+ } catch {
13274
+ return "user";
13275
+ }
13276
+ };
12845
13277
  }
12846
13278
 
12847
- // src/exulu/session-file-listing.ts
12848
- var DEFAULT_MAX = 25;
12849
- function formatSize(bytes) {
12850
- if (bytes < 1024) return `${bytes} B`;
13279
+ // src/exulu/project-files-s3.ts
13280
+ var resolvers = /* @__PURE__ */ new WeakMap();
13281
+ function getOriginResolver(config) {
13282
+ let r = resolvers.get(config);
13283
+ if (!r) {
13284
+ r = createOriginResolver((key) => getS3ObjectMetadataStrict(key, config));
13285
+ resolvers.set(config, r);
13286
+ }
13287
+ return r;
13288
+ }
13289
+ function createPromoteS3(config) {
13290
+ return {
13291
+ listProjectNames: async (projectPrefix) => (await listS3ObjectsByPrefix(projectPrefix, config)).filter((o) => !o.key.endsWith("/")).map((o) => o.key.split("/").pop() ?? o.key),
13292
+ sizeOf: (key) => getS3ObjectSize(key, config),
13293
+ copy: (src, dest) => copyS3Object(src, dest, config)
13294
+ };
13295
+ }
13296
+ function createMoveS3(config) {
13297
+ return { ...createPromoteS3(config), remove: (key) => deleteS3Object(key, config) };
13298
+ }
13299
+
13300
+ // src/exulu/stored-file-url.ts
13301
+ var stripTrailingSlash = (s) => s.replace(/\/+$/, "");
13302
+ var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13303
+ function decodeKey(rawPath) {
13304
+ const key = rawPath.replace(/^\/+/, "");
13305
+ try {
13306
+ return decodeURIComponent(key);
13307
+ } catch {
13308
+ return key;
13309
+ }
13310
+ }
13311
+ function parseStoredFileUrl(url, store) {
13312
+ if (!url || !store.bucket) return void 0;
13313
+ let parsed;
13314
+ try {
13315
+ parsed = new URL(url);
13316
+ } catch {
13317
+ return void 0;
13318
+ }
13319
+ if (store.endpoint) {
13320
+ let endpoint;
13321
+ try {
13322
+ endpoint = new URL(store.endpoint);
13323
+ } catch {
13324
+ return void 0;
13325
+ }
13326
+ if (parsed.protocol !== endpoint.protocol || parsed.host !== endpoint.host) return void 0;
13327
+ const base = stripTrailingSlash(endpoint.pathname);
13328
+ const prefix = `${base}/${store.bucket}/`;
13329
+ if (!parsed.pathname.startsWith(prefix)) return void 0;
13330
+ const key = decodeKey(parsed.pathname.slice(prefix.length));
13331
+ return key ? { bucket: store.bucket, key } : void 0;
13332
+ }
13333
+ if (parsed.protocol !== "https:") return void 0;
13334
+ const region = "(?:\\.dualstack)?(?:[.-](?:[a-z]{2}(?:-gov)?-[a-z]+-\\d|accelerate|external-1))?";
13335
+ if (new RegExp(`^${escapeRegExp(store.bucket)}\\.s3${region}\\.amazonaws\\.com$`).test(parsed.host)) {
13336
+ const key = decodeKey(parsed.pathname);
13337
+ return key ? { bucket: store.bucket, key } : void 0;
13338
+ }
13339
+ if (new RegExp(`^s3${region}\\.amazonaws\\.com$`).test(parsed.host)) {
13340
+ const prefix = `/${store.bucket}/`;
13341
+ if (!parsed.pathname.startsWith(prefix)) return void 0;
13342
+ const key = decodeKey(parsed.pathname.slice(prefix.length));
13343
+ return key ? { bucket: store.bucket, key } : void 0;
13344
+ }
13345
+ return void 0;
13346
+ }
13347
+ function mayResignStoredFileKey(key, ctx) {
13348
+ if (key.split("/").includes("..")) return false;
13349
+ let rest = key.replace(/^\/+/, "");
13350
+ const general = (ctx.s3prefix ?? "").replace(/\/+$/, "");
13351
+ if (general) {
13352
+ if (!rest.startsWith(`${general}/`)) return false;
13353
+ rest = rest.slice(general.length + 1);
13354
+ }
13355
+ const allowed = ["global/"];
13356
+ if (ctx.ownerId != null && ctx.ownerId !== "") allowed.push(`user_${ctx.ownerId}/`);
13357
+ if (ctx.speaker?.type === "api") allowed.push("user_api/");
13358
+ else if (ctx.speaker?.id != null && ctx.speaker.id !== "") allowed.push(`user_${ctx.speaker.id}/`);
13359
+ return allowed.some((p) => rest.startsWith(p));
13360
+ }
13361
+ async function resolveFreshFileUrl(url, opts) {
13362
+ const location = parseStoredFileUrl(url, opts);
13363
+ if (!location) return url;
13364
+ if (!opts.mayResign(location.key)) {
13365
+ console.warn(`[EXULU] not re-signing stored file URL outside the session's own files: "${location.key}"`);
13366
+ return url;
13367
+ }
13368
+ try {
13369
+ return await opts.sign(location.bucket, location.key);
13370
+ } catch (err3) {
13371
+ console.warn(`[EXULU] could not re-sign stored file URL for key "${location.key}":`, err3);
13372
+ return url;
13373
+ }
13374
+ }
13375
+
13376
+ // src/exulu/session-file-listing.ts
13377
+ var DEFAULT_MAX = 25;
13378
+ function formatSize(bytes) {
13379
+ if (bytes < 1024) return `${bytes} B`;
12851
13380
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
12852
13381
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12853
13382
  }
@@ -12889,22 +13418,23 @@ var MAX_PROMPT_NAME = 80;
12889
13418
  function promptSafeProjectName(name) {
12890
13419
  return name.replace(/\s+/g, " ").trim().slice(0, MAX_PROMPT_NAME);
12891
13420
  }
12892
- function describeProjectFiles(files, projectName, opts = {}) {
13421
+ function projectLabel(project) {
13422
+ return `${promptSafeProjectName(project.name)} (id ${project.id})`;
13423
+ }
13424
+ function describeProjectFiles(files, project, opts = {}) {
12893
13425
  const { lines, omitted, total } = listingLines(files, opts);
12894
13426
  if (total === 0) return "";
12895
13427
  if (omitted > 0) lines.push(`+${omitted} more (list them with \`ls project/\`).`);
12896
- const name = promptSafeProjectName(projectName);
12897
- return `Project files (shared with everyone on project ${name}):
13428
+ return `Project files (shared with everyone on project ${projectLabel(project)}):
12898
13429
  ` + lines.join("\n") + `
12899
13430
  Read them by passing \`${PROJECT_DIR}/<name>\` as the filename to parse_document, view_document_page or read_session_file. They are read-only.`;
12900
13431
  }
12901
- function sessionFilesScopeSentence(projectName, canSaveToProject = false) {
12902
- if (!projectName) {
13432
+ function sessionFilesScopeSentence(project, canSaveToProject = false) {
13433
+ if (!project) {
12903
13434
  return "These files are scoped to\n this single session; they are NOT visible in other sessions, projects, or knowledge bases.";
12904
13435
  }
12905
- const name = promptSafeProjectName(projectName);
12906
13436
  const route = canSaveToProject ? "A session file gets into the project with the save_to_project tool (the user approves each save) or by the user in the sidebar." : "You cannot add files to the project: only someone with write access can, by adding a session file to it in the sidebar.";
12907
- return `Files you see by their plain name are private to this session. Project files are shared with everyone on project ${name} and appear under \`${PROJECT_DIR}/\`; they are read-only for you \u2014 do not write into \`${PROJECT_DIR}/\`, changes there are discarded. ` + route;
13437
+ return `Files you see by their plain name are private to this session. Project files are shared with everyone on project ${projectLabel(project)} and appear under \`${PROJECT_DIR}/\`; they are read-only for you \u2014 do not write into \`${PROJECT_DIR}/\`, changes there are discarded. ` + route;
12908
13438
  }
12909
13439
  async function loadSessionFileListing(opts) {
12910
13440
  const uploads = opts.exuluConfig?.fileUploads;
@@ -12934,7 +13464,7 @@ async function loadSessionFileListing(opts) {
12934
13464
  }));
12935
13465
  projectBlock = describeProjectFiles(
12936
13466
  files.filter((f) => !f.name.includes("/")),
12937
- opts.project.name,
13467
+ opts.project,
12938
13468
  { lastTurnAt: opts.lastTurnAt }
12939
13469
  );
12940
13470
  } catch (err3) {
@@ -12943,47 +13473,359 @@ async function loadSessionFileListing(opts) {
12943
13473
  return [sessionBlock, projectBlock].filter(Boolean).join("\n\n");
12944
13474
  }
12945
13475
 
12946
- // src/exulu/file-origin.ts
12947
- var ORIGIN_METADATA_KEY = "exulu-origin";
12948
- function originFromMetadata(metadata) {
12949
- return metadata?.[ORIGIN_METADATA_KEY] === "agent" ? "agent" : "user";
13476
+ // src/exulu/routines/run-session.ts
13477
+ async function createRunSession(opts) {
13478
+ const { db, workflow, userId, title, trigger, jobResultId } = opts;
13479
+ const inserted = await db.from("agent_sessions").insert({
13480
+ agent: workflow.agent,
13481
+ user: userId,
13482
+ created_by: userId,
13483
+ title,
13484
+ rights_mode: workflow.rights_mode ?? "private",
13485
+ // The routine/workflow this session is a run of; null for user chats.
13486
+ // Chat history filters run = null so run sessions do not appear there.
13487
+ run: workflow.id,
13488
+ // Session ⇄ run cross-link; the agent-run route uses job_result_id to
13489
+ // resume a paused run after an approval turn (spec §5.5).
13490
+ metadata: {
13491
+ routine_id: workflow.id,
13492
+ job_result_id: jobResultId ?? null,
13493
+ trigger
13494
+ }
13495
+ }).returning("id");
13496
+ const sessionId = inserted[0].id;
13497
+ const routineRbacRows = await db.from("rbac").where({ entity: "workflow_template", target_resource_id: workflow.id }).select("*");
13498
+ if (routineRbacRows.length > 0) {
13499
+ const now = /* @__PURE__ */ new Date();
13500
+ await db.from("rbac").insert(
13501
+ routineRbacRows.map((row) => ({
13502
+ entity: "agent_session",
13503
+ access_type: row.access_type,
13504
+ target_resource_id: sessionId,
13505
+ user_id: row.user_id ?? null,
13506
+ role_id: row.role_id ?? null,
13507
+ team_id: row.team_id ?? null,
13508
+ rights: row.rights,
13509
+ createdAt: now,
13510
+ updatedAt: now
13511
+ }))
13512
+ );
13513
+ }
13514
+ return sessionId;
12950
13515
  }
12951
- function createOriginResolver(head) {
12952
- const cache2 = /* @__PURE__ */ new Map();
12953
- return async (file) => {
12954
- const stamp = file.lastModified instanceof Date ? file.lastModified.toISOString() : String(file.lastModified);
12955
- const id = `${file.key}\0${stamp}`;
12956
- const hit = cache2.get(id);
12957
- if (hit) return hit;
13516
+ var isRunSessionMetadata = (metadata) => {
13517
+ if (metadata == null) {
13518
+ return false;
13519
+ }
13520
+ let parsed = metadata;
13521
+ if (typeof metadata === "string") {
12958
13522
  try {
12959
- const origin = originFromMetadata(await head(file.key));
12960
- cache2.set(id, origin);
12961
- return origin;
13523
+ parsed = JSON.parse(metadata);
12962
13524
  } catch {
12963
- return "user";
13525
+ return false;
12964
13526
  }
12965
- };
13527
+ }
13528
+ return typeof parsed === "object" && parsed !== null && !!parsed.job_result_id;
13529
+ };
13530
+ var parseMetadata = (metadata) => {
13531
+ if (metadata == null) return null;
13532
+ if (typeof metadata === "string") {
13533
+ try {
13534
+ const parsed = JSON.parse(metadata);
13535
+ return parsed && typeof parsed === "object" ? parsed : null;
13536
+ } catch {
13537
+ return null;
13538
+ }
13539
+ }
13540
+ return typeof metadata === "object" ? metadata : null;
13541
+ };
13542
+ async function verifyRunSessionOwnership(db, opts) {
13543
+ const { sessionId, workflowId, runUser } = opts;
13544
+ const session = await db.from("agent_sessions").where({ id: sessionId }).first();
13545
+ if (!session) {
13546
+ throw new Error(`Run session ${sessionId} not found; refusing to run routine ${workflowId}.`);
13547
+ }
13548
+ const markers = [session.run, parseMetadata(session.metadata)?.routine_id].filter(
13549
+ (m) => m != null && m !== ""
13550
+ );
13551
+ const belongs = markers.length > 0 ? markers.every((m) => String(m) === String(workflowId)) : await checkRecordAccess(session, "write", runUser);
13552
+ if (!belongs) {
13553
+ throw new Error(`Session ${sessionId} does not belong to routine ${workflowId}; refusing to run.`);
13554
+ }
13555
+ }
13556
+ async function withRunSession(db, opts, generate) {
13557
+ const { existingSession, jobResultId, workflow, runUser, trigger } = opts;
13558
+ let sessionId;
13559
+ if (existingSession) {
13560
+ try {
13561
+ await verifyRunSessionOwnership(db, { sessionId: existingSession, workflowId: workflow.id, runUser });
13562
+ } catch (error) {
13563
+ await Promise.resolve(
13564
+ db.from("job_results").where({ id: jobResultId, session: existingSession }).update({ session: null })
13565
+ ).catch(() => {
13566
+ });
13567
+ throw error;
13568
+ }
13569
+ sessionId = existingSession;
13570
+ } else {
13571
+ sessionId = await createRunSession({
13572
+ db,
13573
+ workflow,
13574
+ userId: runUser.id,
13575
+ title: `${workflow.name} \u2014 ${(/* @__PURE__ */ new Date()).toISOString()}`,
13576
+ trigger,
13577
+ jobResultId
13578
+ });
13579
+ await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
13580
+ }
13581
+ return generate(sessionId);
12966
13582
  }
12967
13583
 
12968
- // src/exulu/project-files-s3.ts
12969
- var resolvers = /* @__PURE__ */ new WeakMap();
12970
- function getOriginResolver(config) {
12971
- let r = resolvers.get(config);
12972
- if (!r) {
12973
- r = createOriginResolver((key) => getS3ObjectMetadataStrict(key, config));
12974
- resolvers.set(config, r);
13584
+ // src/templates/tools/create-project-tool.ts
13585
+ var CREATE_PROJECT_TOOL_NAME = "create_project";
13586
+ var CREATE_PROJECT_TOOL_ID = "create_project";
13587
+ var PRIVATE_PROJECT_SENTENCE = "Only you can see this project. Invite colleagues on the project page.";
13588
+ function isCreateProjectEnabledOnAgent(tools) {
13589
+ let entries = tools;
13590
+ if (typeof entries === "string") {
13591
+ try {
13592
+ entries = JSON.parse(entries);
13593
+ } catch {
13594
+ return false;
13595
+ }
12975
13596
  }
12976
- return r;
13597
+ return Array.isArray(entries) && entries.some((t) => t?.id === CREATE_PROJECT_TOOL_ID);
12977
13598
  }
12978
- function createPromoteS3(config) {
12979
- return {
12980
- listProjectNames: async (projectPrefix) => (await listS3ObjectsByPrefix(projectPrefix, config)).filter((o) => !o.key.endsWith("/")).map((o) => o.key.split("/").pop() ?? o.key),
12981
- sizeOf: (key) => getS3ObjectSize(key, config),
12982
- copy: (src, dest) => copyS3Object(src, dest, config)
12983
- };
13599
+ function canRegisterCreateProject(args) {
13600
+ if (args.routineRun) return false;
13601
+ if (!checkLicense().rbac) return false;
13602
+ if (!args.sessionID || !args.exuluConfig?.fileUploads?.s3Bucket) return false;
13603
+ if (treatAsGuest(args.req, args.user)) return false;
13604
+ if (!isCreateProjectEnabledOnAgent(args.agentTools)) return false;
13605
+ if (args.project || args.sessionProjectId) return false;
13606
+ if (!sameEntityId(args.ownerId, args.user?.id)) return false;
13607
+ const disabled = args.disabled instanceof Set ? args.disabled : new Set(args.disabled ?? []);
13608
+ return !disabled.has(CREATE_PROJECT_TOOL_ID);
13609
+ }
13610
+ var CREATE_PROJECT_PROMPT = "Projects: this conversation does not belong to a project yet. When the user wants to keep working on this topic over time, or to share the work with colleagues later, you can offer to turn the conversation into a project with the create_project tool: agree a short project name with the user first, then call it with `files` listing exactly the session files (from the listing above) that should move into the project. The user approves the call and sees that list; the project is private to them; unlisted files stay in the session.";
13611
+ function sessionKeyLikePattern(sessionPrefix) {
13612
+ return `${sessionPrefix.replace(/^\/+/, "").replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
13613
+ }
13614
+ var FILE_PART_PATTERN = '"type"[[:space:]]*:[[:space:]]*"file"';
13615
+ function referencedFileKeys(rows, store) {
13616
+ const keys = /* @__PURE__ */ new Set();
13617
+ for (const row of rows) {
13618
+ let message;
13619
+ try {
13620
+ message = JSON.parse(row.content);
13621
+ } catch {
13622
+ throw new Error("A stored message could not be parsed.");
13623
+ }
13624
+ for (const part of message?.parts ?? []) {
13625
+ if (part?.type !== "file") continue;
13626
+ const at = parseStoredFileUrl(part.url, store);
13627
+ if (at) keys.add(at.key);
13628
+ }
13629
+ }
13630
+ return keys;
13631
+ }
13632
+ var MAX_LISTED_NAMES = 20;
13633
+ var listNames = (names) => names.slice(0, MAX_LISTED_NAMES).join(", ") + (names.length > MAX_LISTED_NAMES ? ` (+${names.length - MAX_LISTED_NAMES} more)` : "");
13634
+ function formatCreateProjectResult(args) {
13635
+ const { name, id, moved, skipped, leftInSession, interrupted } = args;
13636
+ const notMoved = [...skipped, ...moved.notMoved];
13637
+ const lines = [
13638
+ `Created project "${promptSafeProjectName(name)}" (id ${id}) and attached this conversation to it.`,
13639
+ interrupted ? "Moving the files was interrupted by an error, so it is not known which of them reached the project. Tell the user to check the project's files and this conversation's file list." : moved.moved.length > 0 ? `Moved ${moved.moved.length} file${moved.moved.length === 1 ? "" : "s"} into the project: ${listNames(moved.moved)}.` : "Moved 0 files into the project."
13640
+ ];
13641
+ if (notMoved.length > 0) {
13642
+ lines.push(
13643
+ `Not moved (they stay in this session): ${notMoved.slice(0, MAX_LISTED_NAMES).map((s) => `${s.name} (${s.reason})`).join("; ")}${notMoved.length > MAX_LISTED_NAMES ? ` (+${notMoved.length - MAX_LISTED_NAMES} more)` : ""}.`
13644
+ );
13645
+ }
13646
+ if (moved.keptForHistory.length > 0) {
13647
+ lines.push(
13648
+ `Copied into the project and also kept in the session, because an earlier message in this conversation or a share link refers to them: ${listNames(moved.keptForHistory)}.`
13649
+ );
13650
+ }
13651
+ if (moved.originalsKept.length > 0) {
13652
+ lines.push(
13653
+ `These files were copied into the project but their session originals could not be removed, so they exist in both places: ${listNames(moved.originalsKept)}.`
13654
+ );
13655
+ }
13656
+ if (leftInSession > 0) {
13657
+ lines.push(
13658
+ `${leftInSession} other session file${leftInSession === 1 ? "" : "s"} not on the approved list stayed in the session.`
13659
+ );
13660
+ }
13661
+ lines.push(
13662
+ PRIVATE_PROJECT_SENTENCE,
13663
+ `Project page: /projects/${id}`,
13664
+ `The moved files can be read in this turn as ${PROJECT_DIR}/<name>; the sandbox ${PROJECT_DIR}/ folder appears from the next message.`
13665
+ );
13666
+ return lines.join("\n");
12984
13667
  }
13668
+ var createCreateProjectTool = ({
13669
+ sessionID,
13670
+ user,
13671
+ req,
13672
+ exuluConfig,
13673
+ ownerId,
13674
+ agentTools,
13675
+ project,
13676
+ sessionProjectId,
13677
+ routineRun,
13678
+ disabled,
13679
+ turnProject,
13680
+ deps
13681
+ }) => {
13682
+ const gate = (liveOwner, liveProject, liveSessionProject) => canRegisterCreateProject({
13683
+ sessionID,
13684
+ exuluConfig,
13685
+ agentTools,
13686
+ project: liveProject,
13687
+ sessionProjectId: liveSessionProject,
13688
+ ownerId: liveOwner,
13689
+ routineRun,
13690
+ req,
13691
+ user,
13692
+ disabled
13693
+ });
13694
+ if (!gate(ownerId, project, sessionProjectId)) return void 0;
13695
+ if (!sessionID || !exuluConfig || !user) return void 0;
13696
+ const uploads = exuluConfig.fileUploads;
13697
+ if (!uploads?.s3Bucket) return void 0;
13698
+ const resolvedDeps = {
13699
+ loadSession: async (id) => {
13700
+ const { db } = await postgresClient();
13701
+ return db.from("agent_sessions").where({ id }).first();
13702
+ },
13703
+ createAndAttach: createProjectAndAttach,
13704
+ referencedKeys: async (id, sessionPrefix) => {
13705
+ const { db } = await postgresClient();
13706
+ const rows = await db.from("agent_messages").where({ session: id }).whereRaw("content ~ ?", [FILE_PART_PATTERN]).select("content");
13707
+ const keys = referencedFileKeys(rows, { endpoint: uploads.s3endpoint, bucket: uploads.s3Bucket });
13708
+ const shares = await db.from("shared_artifacts").whereRaw("s3key LIKE ? ESCAPE '\\'", [sessionKeyLikePattern(sessionPrefix)]).select("s3key");
13709
+ for (const share of shares) if (share?.s3key) keys.add(String(share.s3key).replace(/^\/+/, ""));
13710
+ return keys;
13711
+ },
13712
+ listSessionFiles: async (prefix) => {
13713
+ const objects = await listS3ObjectsByPrefix(prefix, exuluConfig);
13714
+ return objects.filter((o) => !o.key.endsWith("/")).map((o) => ({ key: o.key, name: o.key.slice(o.key.indexOf(prefix) + prefix.length), size: o.size }));
13715
+ },
13716
+ move: moveSessionFiles,
13717
+ s3: createMoveS3(exuluConfig),
13718
+ db: async () => (await postgresClient()).db,
13719
+ ...deps
13720
+ };
13721
+ const execute = async ({ name, description, files }) => {
13722
+ const requested = Array.isArray(files) ? files : [];
13723
+ let session;
13724
+ try {
13725
+ session = await resolvedDeps.loadSession(sessionID);
13726
+ } catch (err3) {
13727
+ console.error("[PROJECT-CREATE] could not load the session", err3);
13728
+ return { result: "Creating the project failed. Try again; if it keeps failing, tell the user." };
13729
+ }
13730
+ if (!session) return { result: "This conversation has no saved session yet, so it cannot become a project." };
13731
+ if (session.project) return { result: "This conversation already belongs to a project." };
13732
+ if (isRunSessionMetadata(session.metadata)) {
13733
+ return { result: "A routine run cannot be turned into a project." };
13734
+ }
13735
+ if (!checkLicense().rbac) {
13736
+ return { result: "Projects are private only where access control is licensed, so this conversation cannot be turned into a project here." };
13737
+ }
13738
+ if (!gate(session.user, turnProject?.current ?? null, null)) {
13739
+ return { result: "Only the owner of this conversation can turn it into a project, and only where this agent has the tool enabled." };
13740
+ }
13741
+ const ownerPrefix = sessionFilePrefix(session.user, sessionID, uploads.s3prefix);
13742
+ let candidates;
13743
+ try {
13744
+ candidates = await resolvedDeps.listSessionFiles(ownerPrefix);
13745
+ } catch (err3) {
13746
+ console.error("[PROJECT-CREATE] could not list the session files", err3);
13747
+ return { result: "Creating the project failed. Try again; if it keeps failing, tell the user." };
13748
+ }
13749
+ const plan = planMove({ files: candidates, requested });
13750
+ let created;
13751
+ try {
13752
+ created = await resolvedDeps.createAndAttach(await resolvedDeps.db(), user, { sessionId: sessionID, name, description });
13753
+ } catch (err3) {
13754
+ console.error("[PROJECT-CREATE] create/attach failed", err3);
13755
+ const message = err3 instanceof Error ? err3.message : "";
13756
+ const ours = /^Project (name|description) must be/.test(message);
13757
+ return {
13758
+ result: ours ? message : "The project could not be created and attached to this conversation, so nothing was created or moved."
13759
+ };
13760
+ }
13761
+ if (turnProject) turnProject.current = { id: created.id, name: created.name, speakerCanWrite: true };
13762
+ let keepOriginalKeys;
13763
+ try {
13764
+ keepOriginalKeys = await resolvedDeps.referencedKeys(sessionID, ownerPrefix);
13765
+ } catch (err3) {
13766
+ console.error("[PROJECT-CREATE] could not read the references to the session's files", err3);
13767
+ keepOriginalKeys = new Set(plan.batches.flat().map((f) => f.key));
13768
+ }
13769
+ let moved = { moved: [], notMoved: [], originalsKept: [], keptForHistory: [] };
13770
+ let interrupted = false;
13771
+ try {
13772
+ moved = await resolvedDeps.move({
13773
+ projectId: created.id,
13774
+ s3prefix: uploads.s3prefix,
13775
+ fullSessionPrefix: ownerPrefix,
13776
+ batches: plan.batches,
13777
+ s3: resolvedDeps.s3,
13778
+ keepOriginalKeys
13779
+ });
13780
+ } catch (err3) {
13781
+ console.error("[PROJECT-CREATE] moving files failed", err3);
13782
+ interrupted = true;
13783
+ }
13784
+ const asked = new Set(requested.map((n) => String(n ?? "").trim()));
13785
+ const leftInSession = candidates.filter((c) => !asked.has(c.name)).length;
13786
+ return {
13787
+ result: formatCreateProjectResult({
13788
+ name: created.name,
13789
+ id: created.id,
13790
+ moved,
13791
+ skipped: plan.skipped,
13792
+ leftInSession,
13793
+ interrupted
13794
+ })
13795
+ };
13796
+ };
13797
+ return ExuluTool.internal({
13798
+ id: CREATE_PROJECT_TOOL_ID,
13799
+ name: CREATE_PROJECT_TOOL_NAME,
13800
+ needsApproval: true,
13801
+ // The project and the file move are not undone by a later "no": every call asks, even in a chat
13802
+ // where the user allowed other tools.
13803
+ alwaysAskWhen: () => true,
13804
+ description: "Turn this conversation into a project: creates a new private project owned by the user, attaches this conversation to it and moves the listed session files into the project's shared folder. Only offer this when the user wants to keep working on this topic over time or share it later; agree a short project name first. `files` is REQUIRED and must list exactly the files to move, as bare names taken from the session file listing in the system prompt (an empty list creates the project without moving files). The user sees this list on the approval card; every session file not on it stays in the session. Do not list tool-output-* files, generated artifacts or files in subfolders unless the user asked for them. Nobody else gets access.",
13805
+ inputSchema: z14.object({
13806
+ name: z14.string().min(1).max(MAX_PROJECT_NAME_LENGTH).describe("The project's name."),
13807
+ description: z14.string().max(MAX_PROJECT_DESCRIPTION_LENGTH).optional().describe("One or two sentences about what the project is for."),
13808
+ files: z14.array(z14.string()).describe("Bare names of the session files to move, exactly as listed. [] to move none.")
13809
+ }),
13810
+ type: "function",
13811
+ category: "session",
13812
+ config: [],
13813
+ execute
13814
+ });
13815
+ };
13816
+ var createCreateProjectPickerTool = () => new ExuluTool({
13817
+ id: CREATE_PROJECT_TOOL_ID,
13818
+ name: "Create project from chat",
13819
+ category: "default",
13820
+ description: "Let this agent offer to turn a conversation into a project: after the user approves, it creates a private project, attaches the conversation and moves the listed session files into the project's shared folder. Off unless added here; always asks for approval; not offered in routine runs or to guests.",
13821
+ type: "function",
13822
+ inputSchema: z14.object({}),
13823
+ config: [],
13824
+ execute: async () => ({ result: "This entry is configuration-only; Exulu builds the create_project tool per conversation at runtime." })
13825
+ });
12985
13826
 
12986
13827
  // src/templates/tools/save-to-project-tool.ts
13828
+ import { z as z15 } from "zod";
12987
13829
  var SAVE_TO_PROJECT_TOOL_NAME = "save_to_project";
12988
13830
  var SAVE_TO_PROJECT_TOOL_ID = "save_to_project";
12989
13831
  function canRegisterSaveToProject(args) {
@@ -13001,18 +13843,19 @@ var createSaveToProjectTool = ({
13001
13843
  ownerId,
13002
13844
  project,
13003
13845
  disabled,
13004
- deps
13846
+ deps,
13847
+ turnProject
13005
13848
  }) => {
13006
13849
  if (!canRegisterSaveToProject({ sessionID, exuluConfig, project, req, user, disabled })) return void 0;
13007
13850
  if (!sessionID || !exuluConfig || !project) return void 0;
13008
13851
  const uploads = exuluConfig.fileUploads;
13009
13852
  if (!uploads) return void 0;
13010
- const projectLabel = promptSafeProjectName(project.name);
13853
+ const projectLabel2 = promptSafeProjectName(project.name);
13011
13854
  const resolvedDeps = deps ?? {
13012
13855
  promote: promoteSessionFiles,
13013
13856
  s3: createPromoteS3(exuluConfig),
13014
13857
  projectModified: async (name) => {
13015
- const { projectPrefix } = projectFilePrefix(project.id, uploads.s3prefix);
13858
+ const { projectPrefix } = projectFilePrefix(currentProjectId(turnProject, project.id) ?? project.id, uploads.s3prefix);
13016
13859
  const objects = await listS3ObjectsByPrefix(projectPrefix, exuluConfig);
13017
13860
  const hit = objects.find((o) => o.key.split("/").pop() === name);
13018
13861
  return hit ? new Date(hit.lastModified) : void 0;
@@ -13034,7 +13877,7 @@ var createSaveToProjectTool = ({
13034
13877
  let outcome;
13035
13878
  try {
13036
13879
  outcome = await resolvedDeps.promote({
13037
- projectId: project.id,
13880
+ projectId: currentProjectId(turnProject, project.id) ?? project.id,
13038
13881
  s3prefix: uploads.s3prefix,
13039
13882
  keys: [`${ownerPrefix}${name}`],
13040
13883
  fullSessionPrefix: ownerPrefix,
@@ -13047,7 +13890,7 @@ var createSaveToProjectTool = ({
13047
13890
  }
13048
13891
  if (outcome.promoted.length > 0) {
13049
13892
  return {
13050
- result: `Saved "${name}" to project ${projectLabel}. It will be visible to you as ${PROJECT_DIR}/${name} from the next turn.`
13893
+ result: `Saved "${name}" to project ${projectLabel2}. It will be visible to you as ${PROJECT_DIR}/${name} from the next turn.`
13051
13894
  };
13052
13895
  }
13053
13896
  if (outcome.clashes.length > 0) {
@@ -13076,10 +13919,10 @@ var createSaveToProjectTool = ({
13076
13919
  needsApproval: true,
13077
13920
  // Replacing a shared file always needs a fresh yes, "allow for this chat" or not.
13078
13921
  alwaysAskWhen: (input) => input?.overwrite === true,
13079
- description: `Copy one file from this session's files into the project's shared folder (${projectLabel}), where everyone on the project can read it. The \`project/\` directory is read-only for you, so this is the only way to add a file to the project. Pass the bare name of the session file. If the name already exists in the project the call changes nothing and tells you; call again with overwrite: true only after the user has confirmed replacing it.`,
13080
- inputSchema: z14.object({
13081
- filename: z14.string().describe("Bare name of the session file to save, exactly as listed in the session files (no path)."),
13082
- overwrite: z14.boolean().optional().describe("Replace a project file of the same name. Only set after the user confirmed.")
13922
+ description: `Copy one file from this session's files into the project's shared folder (${projectLabel2}), where everyone on the project can read it. The \`project/\` directory is read-only for you, so this is the only way to add a file to the project. Pass the bare name of the session file. If the name already exists in the project the call changes nothing and tells you; call again with overwrite: true only after the user has confirmed replacing it.`,
13923
+ inputSchema: z15.object({
13924
+ filename: z15.string().describe("Bare name of the session file to save, exactly as listed in the session files (no path)."),
13925
+ overwrite: z15.boolean().optional().describe("Replace a project file of the same name. Only set after the user confirmed.")
13083
13926
  }),
13084
13927
  type: "function",
13085
13928
  category: "session",
@@ -13089,38 +13932,8 @@ var createSaveToProjectTool = ({
13089
13932
  };
13090
13933
 
13091
13934
  // src/templates/tools/skill-author-tools.ts
13092
- import { randomUUID as randomUUID4 } from "crypto";
13093
- import { z as z15 } from "zod";
13094
-
13095
- // ee/rbac-resolver.ts
13096
- var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
13097
- const license = checkLicense();
13098
- if (!license.rbac) {
13099
- return {
13100
- type: "public",
13101
- users: [],
13102
- roles: [],
13103
- teams: []
13104
- };
13105
- }
13106
- const rbacRecords = await db.from("rbac").where({
13107
- entity: entityName,
13108
- target_resource_id: resourceId
13109
- }).select("*");
13110
- const users = rbacRecords.filter((r) => r.access_type === "User")?.map((r) => ({ id: r.user_id, rights: r.rights }));
13111
- const roles = rbacRecords.filter((r) => r.access_type === "Role")?.map((r) => ({ id: r.role_id, rights: r.rights }));
13112
- const teams = rbacRecords.filter((r) => r.access_type === "Team")?.map((r) => ({ id: r.team_id, rights: r.rights }));
13113
- let type = rights_mode || "private";
13114
- if (type === "users" && users.length === 0) type = "private";
13115
- if (type === "roles" && roles.length === 0) type = "private";
13116
- if (type === "teams" && teams.length === 0) type = "private";
13117
- return {
13118
- type,
13119
- users,
13120
- roles,
13121
- teams
13122
- };
13123
- };
13935
+ import { randomUUID as randomUUID5 } from "crypto";
13936
+ import { z as z16 } from "zod";
13124
13937
 
13125
13938
  // src/skills/skill-access.ts
13126
13939
  async function resolveSkillByName(db, name) {
@@ -13270,8 +14083,8 @@ description: ${yamlString(description)}
13270
14083
 
13271
14084
  ${content.replace(/^\s+/, "")}`;
13272
14085
  };
13273
- var generalPrefix2 = (config) => config?.fileUploads?.s3prefix ? `${String(config.fileUploads.s3prefix).replace(/\/+$/, "")}/` : "";
13274
- var relativePaths = (keys, config, prefix) => keys.map((f) => f.key.replace(generalPrefix2(config) + prefix, "")).filter((p) => p && !p.endsWith("/"));
14086
+ var generalPrefix3 = (config) => config?.fileUploads?.s3prefix ? `${String(config.fileUploads.s3prefix).replace(/\/+$/, "")}/` : "";
14087
+ var relativePaths = (keys, config, prefix) => keys.map((f) => f.key.replace(generalPrefix3(config) + prefix, "")).filter((p) => p && !p.endsWith("/"));
13275
14088
  async function resolveSkill(db, ref) {
13276
14089
  const value = String(ref ?? "").trim();
13277
14090
  if (!value) return null;
@@ -13310,7 +14123,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
13310
14123
  config: [],
13311
14124
  needsApproval: false,
13312
14125
  description: "List the skills in this instance's library that the current user may read: name, description and current version. Use it before creating a skill to avoid duplicates, and before updating one.",
13313
- inputSchema: z15.object({ query: z15.string().optional().describe("Optional substring to filter by name or description") }),
14126
+ inputSchema: z16.object({ query: z16.string().optional().describe("Optional substring to filter by name or description") }),
13314
14127
  execute: async (params) => {
13315
14128
  const { user } = params;
13316
14129
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -13336,9 +14149,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
13336
14149
  config: [],
13337
14150
  needsApproval: false,
13338
14151
  description: "Read a skill the user may access: its file list and the content of SKILL.md, or of one file by path. Use it before updating a skill so you change only what must change.",
13339
- inputSchema: z15.object({
13340
- skill: z15.string().describe("The skill's name or id"),
13341
- path: z15.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
14152
+ inputSchema: z16.object({
14153
+ skill: z16.string().describe("The skill's name or id"),
14154
+ path: z16.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
13342
14155
  }),
13343
14156
  execute: async (params) => {
13344
14157
  const { user, exuluConfig } = params;
@@ -13354,7 +14167,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
13354
14167
  const path3 = params.path ? safeSkillPath(params.path) : "SKILL.md";
13355
14168
  if (!path3) return err2(`"${params.path}" is not a valid path inside the skill.`);
13356
14169
  if (!files.includes(path3)) return err2(`The skill has no file "${path3}". Files: ${files.join(", ") || "(none)"}`);
13357
- let content = await io.read(generalPrefix2(exuluConfig) + prefix + path3, exuluConfig);
14170
+ let content = await io.read(generalPrefix3(exuluConfig) + prefix + path3, exuluConfig);
13358
14171
  if (Buffer.byteLength(content, "utf8") > MAX_READ_BYTES) content = content.slice(0, MAX_READ_BYTES) + "\n\u2026(truncated)";
13359
14172
  return {
13360
14173
  type: "skill_read",
@@ -13383,10 +14196,10 @@ ${content}`
13383
14196
  needsApproval: !config.skipApproval,
13384
14197
  needsApprovalFn: approvalFn,
13385
14198
  description: "Propose a NEW skill from a procedure the user just completed. Give it a short name, a one-line description, and its files: a SKILL.md with frontmatter and clear steps, plus reference files only where useful. The user confirms name, description and visibility on a card before anything is created; never claim it exists until this tool returns skill_created.",
13386
- inputSchema: z15.object({
13387
- name: z15.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
13388
- description: z15.string().describe("One line: what the skill does and when to use it"),
13389
- files: z15.array(z15.object({ path: z15.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z15.string() })).min(1).describe("The skill's files; SKILL.md is required")
14199
+ inputSchema: z16.object({
14200
+ name: z16.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
14201
+ description: z16.string().describe("One line: what the skill does and when to use it"),
14202
+ files: z16.array(z16.object({ path: z16.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z16.string() })).min(1).describe("The skill's files; SKILL.md is required")
13390
14203
  }),
13391
14204
  execute: async (params) => {
13392
14205
  const { user, exuluConfig } = params;
@@ -13405,7 +14218,7 @@ ${content}`
13405
14218
  const db = await getDb();
13406
14219
  if (await resolveSkillByName(db, name)) return err2(`A skill named "${name}" already exists. Use skill_update to change it, or choose another name.`);
13407
14220
  const rights_mode = decision?.rights_mode ?? "private";
13408
- const skillId = randomUUID4();
14221
+ const skillId = randomUUID5();
13409
14222
  const stamp = now().toISOString();
13410
14223
  for (const f of files) {
13411
14224
  await io.upload(Buffer.from(f.content, "utf8"), `skills/${skillId}/v1/${f.path}`, exuluConfig, contentTypeFor(f.path));
@@ -13452,12 +14265,12 @@ ${content}`
13452
14265
  needsApproval: !config.skipApproval,
13453
14266
  needsApprovalFn: approvalFn,
13454
14267
  description: "Publish a new version of an existing skill the user may write: pass only the files to add or replace (full content each) and, optionally, paths to remove. Unchanged files carry over. Read the skill first with skill_read. The user confirms on a card; never claim the change happened until this tool returns skill_updated.",
13455
- inputSchema: z15.object({
13456
- skill: z15.string().describe("The skill's name or id"),
13457
- files: z15.array(z15.object({ path: z15.string(), content: z15.string() })).optional().describe("Files to add or replace, full content each"),
13458
- deletePaths: z15.array(z15.string()).optional().describe("Paths to remove in the new version"),
13459
- description: z15.string().optional().describe("A new one-line description, if it changed"),
13460
- label: z15.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
14268
+ inputSchema: z16.object({
14269
+ skill: z16.string().describe("The skill's name or id"),
14270
+ files: z16.array(z16.object({ path: z16.string(), content: z16.string() })).optional().describe("Files to add or replace, full content each"),
14271
+ deletePaths: z16.array(z16.string()).optional().describe("Paths to remove in the new version"),
14272
+ description: z16.string().optional().describe("A new one-line description, if it changed"),
14273
+ label: z16.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
13461
14274
  }),
13462
14275
  execute: async (params) => {
13463
14276
  const { user, exuluConfig } = params;
@@ -13489,7 +14302,7 @@ ${content}`
13489
14302
  const newVersion = currentVersion + 1;
13490
14303
  const currentPrefix = `skills/${skill.id}/v${currentVersion}/`;
13491
14304
  const newPrefix = `skills/${skill.id}/v${newVersion}/`;
13492
- const gp = generalPrefix2(exuluConfig);
14305
+ const gp = generalPrefix3(exuluConfig);
13493
14306
  const existing = await io.list(currentPrefix, exuluConfig);
13494
14307
  const changedPaths = new Set(changes.map((f) => f.path));
13495
14308
  const removedSet = new Set(removals);
@@ -13534,7 +14347,7 @@ var createSkillAuthorPickerTool = () => new ExuluTool({
13534
14347
  category: "default",
13535
14348
  description: "Let this agent create skills and publish new versions of existing ones from the chat, with the user's consent on a card. Adds a system-prompt hint to offer a skill only after complex, recurring, multi-step work \u2014 never for a single question or correction.",
13536
14349
  type: "function",
13537
- inputSchema: z15.object({}),
14350
+ inputSchema: z16.object({}),
13538
14351
  config: [
13539
14352
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
13540
14353
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -14096,7 +14909,7 @@ ${JSON.stringify(config, null, 2)}`
14096
14909
  };
14097
14910
 
14098
14911
  // src/exulu/audit/sink.ts
14099
- import { randomUUID as randomUUID5 } from "crypto";
14912
+ import { randomUUID as randomUUID6 } from "crypto";
14100
14913
  import { promises as fs } from "fs";
14101
14914
  import path2 from "path";
14102
14915
  var createFsSpoolStore = (dir) => ({
@@ -14130,7 +14943,7 @@ var AuditSink = class {
14130
14943
  objectKey() {
14131
14944
  const d = this.now();
14132
14945
  const dt = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
14133
- return `${this.cfg.target.s3prefix}dt=${dt}/${pad(d.getUTCHours())}/${d.getTime()}-${randomUUID5()}.ndjson`;
14946
+ return `${this.cfg.target.s3prefix}dt=${dt}/${pad(d.getUTCHours())}/${d.getTime()}-${randomUUID6()}.ndjson`;
14134
14947
  }
14135
14948
  serialize(events) {
14136
14949
  return events.map((e) => JSON.stringify(e)).join("\n") + "\n";
@@ -14157,7 +14970,7 @@ var AuditSink = class {
14157
14970
  await this.writer.putNdjson(this.objectKey(), body);
14158
14971
  await this.drainSpool();
14159
14972
  } catch (error) {
14160
- const name = `${Date.now()}-${randomUUID5()}.ndjson`;
14973
+ const name = `${Date.now()}-${randomUUID6()}.ndjson`;
14161
14974
  try {
14162
14975
  await this.spool.write(name, body);
14163
14976
  console.warn(`[EXULU] audit: S3 write failed, spooled ${batch.length} record(s) to disk (${name}).`, error);
@@ -14476,7 +15289,7 @@ var buildSkillSandboxEvent = (ctx, opts = {}) => {
14476
15289
  // ee/invoke-skills/create-sandbox.ts
14477
15290
  import { createBashTool } from "bash-tool";
14478
15291
  import { tool as tool2 } from "ai";
14479
- import { z as z16 } from "zod";
15292
+ import { z as z17 } from "zod";
14480
15293
  import CryptoJS3 from "crypto-js";
14481
15294
 
14482
15295
  // ee/invoke-skills/project-sync.ts
@@ -14485,30 +15298,6 @@ import { randomBytes as randomBytes2 } from "crypto";
14485
15298
  import { basename, dirname, join as join2, resolve as resolve2, sep } from "path";
14486
15299
  import { execFile } from "child_process";
14487
15300
  import { promisify as promisify2 } from "util";
14488
-
14489
- // src/exulu/project-access.ts
14490
- var idOf = (v) => typeof v === "object" && v ? v.id : v;
14491
- function hasProjectAccess(args) {
14492
- const { project, rbac, user, want } = args;
14493
- if (user.super_admin) return true;
14494
- if (user.type === "api" && (!user.scope_mode || user.scope_mode === "admin")) return true;
14495
- if (project.rights_mode === "public" || rbac.type === "public") return true;
14496
- if (project.created_by != null && String(project.created_by) === String(user.id)) return true;
14497
- const satisfies = (rights) => rights === "write" || rights === "read" && want === "read";
14498
- const granted = (grants, subject) => subject != null && (grants ?? []).some((g) => String(g.id) === String(subject) && satisfies(g.rights));
14499
- switch (rbac.type) {
14500
- case "users":
14501
- return granted(rbac.users, user.id);
14502
- case "roles":
14503
- return granted(rbac.roles, idOf(user.role));
14504
- case "teams":
14505
- return granted(rbac.teams, idOf(user.team));
14506
- default:
14507
- return false;
14508
- }
14509
- }
14510
-
14511
- // ee/invoke-skills/project-sync.ts
14512
15301
  function planProjectSync(remote, local) {
14513
15302
  const localSizes = new Map(local.map((e) => [e.name, e.size]));
14514
15303
  const remoteNames = new Set(remote.map((e) => e.name));
@@ -15399,9 +16188,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
15399
16188
  });
15400
16189
  const writeFileTool = tool2({
15401
16190
  description: 'Write content to a file in the sandbox. Creates parent directories if needed. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/<Skill name>/SKILL.md") and leading-slash paths ("/skills/<Skill name>/SKILL.md") work and reach the same file. When the path is under the session artifact tree, the file is also uploaded to S3 and a short-lived presigned URL is returned in the tool output.',
15402
- inputSchema: z16.object({
15403
- path: z16.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
15404
- content: z16.string().describe("The content to write to the file")
16191
+ inputSchema: z17.object({
16192
+ path: z17.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
16193
+ content: z17.string().describe("The content to write to the file")
15405
16194
  }),
15406
16195
  execute: async ({ path: path3, content }) => {
15407
16196
  const hasProject = hasProjectNow();
@@ -15421,8 +16210,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
15421
16210
  });
15422
16211
  const readFileTool = tool2({
15423
16212
  description: 'Read the contents of a file from the sandbox. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/<Skill name>/SKILL.md") and leading-slash paths ("/skills/<Skill name>/SKILL.md") work and reach the same file. Skills live in a folder per skill: "skills/<Skill name>/SKILL.md", never "skills/<Skill name>.md". If the file does not exist, the error message is surfaced verbatim.',
15424
- inputSchema: z16.object({
15425
- path: z16.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
16213
+ inputSchema: z17.object({
16214
+ path: z17.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
15426
16215
  }),
15427
16216
  execute: async ({ path: path3 }) => {
15428
16217
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -15439,8 +16228,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
15439
16228
  const originalBashTool = tools.bash;
15440
16229
  const bashTool = tool2({
15441
16230
  description: originalBashTool.description ?? "",
15442
- inputSchema: z16.object({
15443
- command: z16.string().describe("The bash command to execute.")
16231
+ inputSchema: z17.object({
16232
+ command: z17.string().describe("The bash command to execute.")
15444
16233
  }),
15445
16234
  execute: async (args, opts2) => {
15446
16235
  const hasProject = hasProjectNow();
@@ -15557,8 +16346,98 @@ async function resolveSessionProject(args) {
15557
16346
  return { id, name: row?.name?.trim() || "(unnamed)", speakerCanWrite };
15558
16347
  }
15559
16348
 
16349
+ // src/exulu/session-file-write.ts
16350
+ var getMimeType = (type) => {
16351
+ switch (type) {
16352
+ case ".png":
16353
+ return "image/png";
16354
+ case ".jpg":
16355
+ return "image/jpg";
16356
+ case ".jpeg":
16357
+ return "image/jpeg";
16358
+ case ".gif":
16359
+ return "image/gif";
16360
+ case ".webp":
16361
+ return "image/webp";
16362
+ case ".pdf":
16363
+ return "application/pdf";
16364
+ case ".docx":
16365
+ return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
16366
+ case ".xlsx":
16367
+ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
16368
+ case ".xls":
16369
+ return "application/vnd.ms-excel";
16370
+ case ".csv":
16371
+ return "text/csv";
16372
+ case ".pptx":
16373
+ return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
16374
+ case ".ppt":
16375
+ return "application/vnd.ms-powerpoint";
16376
+ case ".m4a":
16377
+ return "audio/mp4";
16378
+ case ".mp4":
16379
+ return "audio/mp4";
16380
+ case ".mpeg":
16381
+ return "audio/mpeg";
16382
+ case ".mp3":
16383
+ return "audio/mp3";
16384
+ case ".wav":
16385
+ return "audio/wav";
16386
+ case ".txt":
16387
+ return "text/plain";
16388
+ case ".md":
16389
+ return "text/markdown";
16390
+ case ".json":
16391
+ return "application/json";
16392
+ default:
16393
+ return "";
16394
+ }
16395
+ };
16396
+ function contentTypeFor2(name) {
16397
+ const dot = name.lastIndexOf(".");
16398
+ if (dot < 0) return "application/octet-stream";
16399
+ const ext = name.slice(dot).toLowerCase();
16400
+ return getMimeType(ext) || "application/octet-stream";
16401
+ }
16402
+ var SAVE_INVALID_NAME = "Invalid filename (no path separators, no '..').";
16403
+ var SAVE_EMPTY = "The file is empty.";
16404
+ var SAVE_TOO_LARGE = "It is larger than 50 MB.";
16405
+ var SAVE_FAILED = "Saving the file failed.";
16406
+ async function writeSessionFile(args) {
16407
+ const name = sanitizeFilename(args.file.name);
16408
+ if (!name) return { error: SAVE_INVALID_NAME };
16409
+ if (args.file.data.length === 0) return { error: SAVE_EMPTY };
16410
+ if (args.file.data.length > MAX_ADOPT_UPLOAD_BYTES) return { error: SAVE_TOO_LARGE };
16411
+ const key = sessionFilePrefix(args.ownerId, args.sessionId, void 0) + name;
16412
+ try {
16413
+ await args.put(key, args.file.data, contentTypeFor2(name));
16414
+ } catch (err3) {
16415
+ console.error("[EXULU] saveSessionFile failed", err3);
16416
+ return { error: SAVE_FAILED };
16417
+ }
16418
+ return { name };
16419
+ }
16420
+ function buildSaveSessionFile(args) {
16421
+ const { sessionID, exuluConfig } = args;
16422
+ const uploads = exuluConfig?.fileUploads;
16423
+ if (!sessionID || !exuluConfig) return void 0;
16424
+ if (!uploads?.s3endpoint || !uploads.s3key || !uploads.s3secret || !uploads.s3Bucket) {
16425
+ return void 0;
16426
+ }
16427
+ if (args.inRoutineRun || treatAsGuest(args.req, args.user)) return void 0;
16428
+ const ownerId = args.ownerId ?? args.user?.id;
16429
+ return (file) => writeSessionFile({
16430
+ ownerId,
16431
+ sessionId: sessionID,
16432
+ file,
16433
+ put: async (key, data, contentType) => {
16434
+ await uploadFile(data, key, exuluConfig, { contentType }, void 0, void 0, true);
16435
+ }
16436
+ });
16437
+ }
16438
+
15560
16439
  // src/templates/tools/routine-status-tool.ts
15561
- import { z as z17 } from "zod";
16440
+ import { z as z18 } from "zod";
15562
16441
  var SET_ROUTINE_STATUS_TOOL_ID = "set_routine_status";
15563
16442
  function createRoutineStatusTool(handle) {
15564
16443
  if (!handle || handle.statuses.length === 0) return void 0;
@@ -15571,8 +16450,8 @@ function createRoutineStatusTool(handle) {
15571
16450
  category: "routines",
15572
16451
  type: "function",
15573
16452
  needsApproval: false,
15574
- inputSchema: z17.object({
15575
- status: z17.enum(keys).describe("The work status key to set.")
16453
+ inputSchema: z18.object({
16454
+ status: z18.enum(keys).describe("The work status key to set.")
15576
16455
  }),
15577
16456
  config: [],
15578
16457
  execute: async ({ status }) => {
@@ -15612,7 +16491,7 @@ var truncateToolOutput = (output, maxContextLength, toolName, tailFraction = 0.1
15612
16491
  };
15613
16492
 
15614
16493
  // src/exulu/tool-output-offload.ts
15615
- import { randomUUID as randomUUID6 } from "crypto";
16494
+ import { randomUUID as randomUUID7 } from "crypto";
15616
16495
 
15617
16496
  // src/exulu/context-budget.ts
15618
16497
  var DEFAULT_CONTEXT_WINDOW = 128e3;
@@ -15716,7 +16595,7 @@ var PREVIEW_CHARS = 4e3;
15716
16595
  var storeAsSessionFile = async (serialized, ctx) => {
15717
16596
  if (!ctx.sessionID || !ctx.exuluConfig?.fileUploads) return void 0;
15718
16597
  const safeTool = ctx.toolName.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
15719
- const name = `tool-output-${safeTool}-${randomUUID6().slice(0, 8)}.txt`;
16598
+ const name = `tool-output-${safeTool}-${randomUUID7().slice(0, 8)}.txt`;
15720
16599
  try {
15721
16600
  await uploadFile(
15722
16601
  Buffer.from(serialized, "utf-8"),
@@ -15784,7 +16663,7 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
15784
16663
  };
15785
16664
 
15786
16665
  // src/templates/tools/session-file-read-tool.ts
15787
- import { z as z18 } from "zod";
16666
+ import { z as z19 } from "zod";
15788
16667
 
15789
16668
  // src/templates/tools/resolve-file-key.ts
15790
16669
  var NO_PROJECT_FILES_ERROR = "This session has no project files.";
@@ -15816,7 +16695,8 @@ var createSessionFileReadTool = ({
15816
16695
  user,
15817
16696
  exuluConfig,
15818
16697
  ownerId,
15819
- projectId
16698
+ projectId,
16699
+ turnProject
15820
16700
  }) => {
15821
16701
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
15822
16702
  const readSessionFileExecute = async ({ filename, offset, limit }) => {
@@ -15825,7 +16705,7 @@ var createSessionFileReadTool = ({
15825
16705
  filename,
15826
16706
  ownerId: ownerId ?? user?.id ?? "api",
15827
16707
  sessionId: sessionID,
15828
- projectId: projectId ?? null,
16708
+ projectId: currentProjectId(turnProject, projectId),
15829
16709
  s3prefix: uploads.s3prefix
15830
16710
  });
15831
16711
  if ("error" in resolved) return { error: resolved.error };
@@ -15864,10 +16744,10 @@ var createSessionFileReadTool = ({
15864
16744
  name: SESSION_FILE_READ_TOOL_NAME,
15865
16745
  needsApproval: false,
15866
16746
  description: "Read a line range from a file stored in this session's files \u2014 including offloaded tool outputs (tool-output-*.txt) and uploaded documents. Use offset (1-based line number) and limit to page through large files instead of reading everything at once. Files of the session's project are addressed as `project/<name>` and are read-only.",
15867
- inputSchema: z18.object({
15868
- filename: z18.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
15869
- offset: z18.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
15870
- limit: z18.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
16747
+ inputSchema: z19.object({
16748
+ filename: z19.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
16749
+ offset: z19.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
16750
+ limit: z19.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
15871
16751
  }),
15872
16752
  type: "function",
15873
16753
  category: "session",
@@ -15880,8 +16760,8 @@ var createSessionFileReadTool = ({
15880
16760
  };
15881
16761
 
15882
16762
  // src/templates/tools/parse-document-tool.ts
15883
- import { z as z19 } from "zod";
15884
- import { extname } from "path";
16763
+ import { z as z20 } from "zod";
16764
+ import { extname as extname2 } from "path";
15885
16765
  import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
15886
16766
 
15887
16767
  // src/templates/tools/document-render-helpers.ts
@@ -15997,8 +16877,11 @@ function attachmentMaxPages(env = process.env) {
15997
16877
  function tooLongNotice(filename, pageCount, maxPages) {
15998
16878
  return `[Document too long: "${filename}" has ${pageCount} pages, the limit for attachments is ${maxPages} pages (EXULU_ATTACHMENT_MAX_PAGES). The document was NOT read. Tell the user plainly that the document is too long and ask for a shorter document or an excerpt with the relevant pages.]`;
15999
16879
  }
16880
+ function tooLongForToolNotice(filename, pageCount, maxPages) {
16881
+ return `[Document too long: "${filename}" has ${pageCount} pages, the limit for reading a document is ${maxPages} pages (EXULU_DOCUMENT_MAX_PAGES). The document was NOT read. Tell the user plainly and suggest splitting the file.]`;
16882
+ }
16000
16883
  var loadDocumentProcessor = async () => {
16001
- const mod = await import("./doc_processor-E5GCE2ZT.js");
16884
+ const mod = await import("./doc_processor-SVOSOVOY.js");
16002
16885
  return mod.documentProcessor;
16003
16886
  };
16004
16887
  function pagesToText(pages) {
@@ -16013,12 +16896,16 @@ function pagesFromProcessor(result) {
16013
16896
  text: (p.vlm_corrected_text ?? p.content ?? "").trim()
16014
16897
  }));
16015
16898
  }
16899
+ function degradedPagesOf(result) {
16900
+ return (result ?? []).filter((p) => p.vlm_failed).map((p) => p.page);
16901
+ }
16016
16902
  var defaultOfficeParse = async (bytes) => String(await parseOfficeAsync(bytes, { outputErrorToConsole: false, newlineDelimiter: "\n" }));
16017
16903
  async function extractDocument(input) {
16018
16904
  const config = input.exuluConfig?.attachments?.documentProcessor;
16019
16905
  if (config) {
16020
16906
  if (input.filename.toLowerCase().endsWith(".pdf")) {
16021
- const maxPages = attachmentMaxPages();
16907
+ const forTool = input.maxPages !== void 0;
16908
+ const maxPages = input.maxPages ?? attachmentMaxPages();
16022
16909
  let pageCount;
16023
16910
  try {
16024
16911
  pageCount = await (input.countPages ?? pdfPageCount)(input.bytes);
@@ -16026,10 +16913,10 @@ async function extractDocument(input) {
16026
16913
  console.warn(`[EXULU] Could not count pages of ${input.filename}:`, error instanceof Error ? error.message : String(error));
16027
16914
  }
16028
16915
  if (pageCount !== void 0 && pageCount > maxPages) {
16029
- console.warn(`[EXULU] ${input.filename} has ${pageCount} pages, over the attachment cap of ${maxPages}; not read.`);
16916
+ console.warn(`[EXULU] ${input.filename} has ${pageCount} pages, over the ${forTool ? "document" : "attachment"} cap of ${maxPages}; not read.`);
16030
16917
  return {
16031
16918
  pages: [],
16032
- text: tooLongNotice(input.filename, pageCount, maxPages),
16919
+ text: (forTool ? tooLongForToolNotice : tooLongNotice)(input.filename, pageCount, maxPages),
16033
16920
  engine: "document-processor",
16034
16921
  tooLong: { pageCount, maxPages }
16035
16922
  };
@@ -16040,11 +16927,22 @@ async function extractDocument(input) {
16040
16927
  const result = await process2({
16041
16928
  file: input.bytes,
16042
16929
  name: input.filename,
16043
- config: { ...config, attribution: { ...config.attribution, ...input.attribution } }
16930
+ config: { ...config, attribution: { ...config.attribution, ...input.attribution } },
16931
+ ...input.tolerateVisionFailures ? { tolerateVisionFailures: true } : {},
16932
+ ...input.onProgress ? { onProgress: input.onProgress } : {},
16933
+ // Chat reads (parse_document, inline attachments) share the process-wide OCR/vision
16934
+ // ceilings; knowledge-base processing calls the processor directly without them.
16935
+ limiters: processWideLimiters
16044
16936
  });
16045
16937
  const pages = pagesFromProcessor(result);
16046
16938
  if (pages.some((p) => p.text.length > 0)) {
16047
- return { pages, text: pagesToText(pages), engine: "document-processor" };
16939
+ const degradedPages = input.tolerateVisionFailures ? degradedPagesOf(result) : [];
16940
+ return {
16941
+ pages,
16942
+ text: pagesToText(pages),
16943
+ engine: "document-processor",
16944
+ ...degradedPages.length > 0 ? { degradedPages } : {}
16945
+ };
16048
16946
  }
16049
16947
  console.warn(`[EXULU] Document processor returned no text for ${input.filename}; falling back to officeparser.`);
16050
16948
  } catch (error) {
@@ -16059,9 +16957,17 @@ async function extractDocument(input) {
16059
16957
  }
16060
16958
  var PROCESSOR_NAMES = /* @__PURE__ */ new Set(["liteparse", "mistral", "officeparser"]);
16061
16959
  function validateAttachmentsConfig(config, license) {
16062
- const processorConfig = config?.attachments?.documentProcessor;
16063
- if (!processorConfig) return [];
16064
16960
  const problems = [];
16961
+ const rawDays = process.env.EXULU_DOCUMENT_CACHE_DAYS;
16962
+ if (rawDays !== void 0 && rawDays.trim() !== "" && !(Number.isInteger(Number(rawDays)) && Number(rawDays) >= 0)) {
16963
+ problems.push(`EXULU_DOCUMENT_CACHE_DAYS must be a non-negative integer, 0 disables the cache (got ${JSON.stringify(rawDays)}; default 365)`);
16964
+ }
16965
+ const rawDocPages = process.env.EXULU_DOCUMENT_MAX_PAGES;
16966
+ if (rawDocPages !== void 0 && rawDocPages.trim() !== "" && !(Number.isInteger(Number(rawDocPages)) && Number(rawDocPages) > 0)) {
16967
+ problems.push(`EXULU_DOCUMENT_MAX_PAGES must be a positive integer (got ${JSON.stringify(rawDocPages)}; default 300)`);
16968
+ }
16969
+ const processorConfig = config?.attachments?.documentProcessor;
16970
+ if (!processorConfig) return problems;
16065
16971
  const name = processorConfig.processor?.name;
16066
16972
  if (!name || !PROCESSOR_NAMES.has(name)) {
16067
16973
  problems.push(`attachments.documentProcessor.processor.name must be one of ${[...PROCESSOR_NAMES].join(", ")} (got ${JSON.stringify(name)})`);
@@ -16077,6 +16983,10 @@ function validateAttachmentsConfig(config, license) {
16077
16983
  problems.push("attachments.documentProcessor.vlm.concurrency must be a positive integer");
16078
16984
  }
16079
16985
  }
16986
+ const ocrConcurrencySetting = processorConfig.ocr?.concurrency;
16987
+ if (ocrConcurrencySetting !== void 0 && !(Number.isInteger(ocrConcurrencySetting) && ocrConcurrencySetting >= 1 && ocrConcurrencySetting <= 8)) {
16988
+ problems.push("attachments.documentProcessor.ocr.concurrency must be an integer from 1 to 8");
16989
+ }
16080
16990
  if (!license["advanced-document-processing"]) {
16081
16991
  problems.push("attachments.documentProcessor needs the enterprise licence (advanced-document-processing); set EXULU_ENTERPRISE_LICENSE or remove the attachments config");
16082
16992
  }
@@ -16087,6 +16997,149 @@ function validateAttachmentsConfig(config, license) {
16087
16997
  return problems;
16088
16998
  }
16089
16999
 
17000
+ // src/exulu/document-cache/progress.ts
17001
+ function isInterimToolStatus(value) {
17002
+ return typeof value === "object" && value !== null && value.status === "reading";
17003
+ }
17004
+ function throttleProgress(fn, ms = 1e3, now = Date.now) {
17005
+ let last;
17006
+ let lastPhase;
17007
+ return (p) => {
17008
+ const isFinal = p.pagesTotal > 0 && p.pagesDone === p.pagesTotal;
17009
+ const t = now();
17010
+ if (last !== void 0 && p.phase === lastPhase && !isFinal && t - last < ms) return;
17011
+ last = t;
17012
+ lastPhase = p.phase;
17013
+ fn(p);
17014
+ };
17015
+ }
17016
+
17017
+ // src/exulu/document-cache/store.ts
17018
+ import { createHash as createHash4 } from "crypto";
17019
+ var inFlight = /* @__PURE__ */ new Map();
17020
+ var DAY_MS2 = 24 * 60 * 60 * 1e3;
17021
+ var sha256Hex = (bytes) => createHash4("sha256").update(bytes).digest("hex");
17022
+ var PAGES_METADATA_KEY = "exulu-pages";
17023
+ function countPageMarkers(text) {
17024
+ const count = (text.match(/^--- page \d+ ---$/gm) ?? []).length;
17025
+ return count > 0 ? count : void 0;
17026
+ }
17027
+ var warn = (what, err3) => console.warn(`[EXULU] document store: ${what}:`, err3 instanceof Error ? err3.message : String(err3));
17028
+ async function readThroughDocument(args) {
17029
+ const { io, bucket, sourceKey, s3prefix, fingerprint, cacheDays, extract, onProgress } = args;
17030
+ const now = args.now ?? (() => /* @__PURE__ */ new Date());
17031
+ const useStore = cacheDays > 0;
17032
+ const pointerAt = pointerKey(bucket, sourceKey, s3prefix);
17033
+ const fromStoredText = (stored) => {
17034
+ if (!stored) return null;
17035
+ if (now().getTime() - stored.lastModified.getTime() > cacheDays * DAY_MS2) return null;
17036
+ const pages = Number(stored.metadata?.[PAGES_METADATA_KEY]);
17037
+ const totalPages = Number.isInteger(pages) && pages > 0 ? pages : countPageMarkers(stored.text);
17038
+ return { text: stored.text, totalPages, fromStore: true };
17039
+ };
17040
+ const readText = async (key) => {
17041
+ try {
17042
+ return await io.getText(key);
17043
+ } catch (err3) {
17044
+ warn(`could not read ${key}`, err3);
17045
+ return null;
17046
+ }
17047
+ };
17048
+ if (useStore) {
17049
+ let head = null;
17050
+ try {
17051
+ head = await io.head(sourceKey);
17052
+ } catch (err3) {
17053
+ warn(`could not head ${sourceKey}`, err3);
17054
+ }
17055
+ if (head && head.etag && head.lastModified && head.size !== null) {
17056
+ const pointerRaw = await readText(pointerAt);
17057
+ let pointer = null;
17058
+ try {
17059
+ pointer = pointerRaw ? JSON.parse(pointerRaw.text) : null;
17060
+ } catch {
17061
+ pointer = null;
17062
+ }
17063
+ if (pointer && pointer.etag === head.etag && pointer.lastModified === head.lastModified.toISOString() && pointer.size === head.size && typeof pointer.sha256 === "string") {
17064
+ const hit = fromStoredText(await readText(contentKey(pointer.sha256, fingerprint.id, s3prefix)));
17065
+ if (hit) return hit;
17066
+ }
17067
+ }
17068
+ }
17069
+ const got = await io.getBytes(sourceKey);
17070
+ const bytes = got.bytes;
17071
+ const sha = sha256Hex(bytes);
17072
+ const textKey = contentKey(sha, fingerprint.id, s3prefix);
17073
+ const writePointer = async () => {
17074
+ if (!got.etag || !got.lastModified || got.size === null) return;
17075
+ await io.putText(
17076
+ pointerAt,
17077
+ JSON.stringify({ etag: got.etag, lastModified: got.lastModified.toISOString(), size: got.size, sha256: sha }),
17078
+ {}
17079
+ );
17080
+ };
17081
+ if (useStore) {
17082
+ const hit = fromStoredText(await readText(textKey));
17083
+ if (hit) {
17084
+ try {
17085
+ await writePointer();
17086
+ } catch (err3) {
17087
+ warn("could not write pointer", err3);
17088
+ }
17089
+ return hit;
17090
+ }
17091
+ }
17092
+ const flightKey = `${sha}/${fingerprint.id}`;
17093
+ const existing = inFlight.get(flightKey);
17094
+ if (existing) {
17095
+ if (onProgress) existing.listeners.add(onProgress);
17096
+ return existing.promise;
17097
+ }
17098
+ const listeners = /* @__PURE__ */ new Set();
17099
+ if (onProgress) listeners.add(onProgress);
17100
+ const emit = (p) => {
17101
+ for (const listener of listeners) {
17102
+ try {
17103
+ listener(p);
17104
+ } catch {
17105
+ }
17106
+ }
17107
+ };
17108
+ const promise = (async () => {
17109
+ const extracted = await extract(bytes, emit);
17110
+ if (useStore && extracted.storable) {
17111
+ try {
17112
+ emit({ phase: "storing", pagesDone: extracted.totalPages ?? 0, pagesTotal: extracted.totalPages ?? 0 });
17113
+ await io.putText(textKey, extracted.text, {
17114
+ "exulu-extractor": fingerprint.label,
17115
+ ...extracted.totalPages ? { [PAGES_METADATA_KEY]: String(extracted.totalPages) } : {}
17116
+ });
17117
+ await writePointer();
17118
+ } catch (err3) {
17119
+ warn("could not store extracted text", err3);
17120
+ }
17121
+ }
17122
+ return {
17123
+ text: extracted.text,
17124
+ totalPages: extracted.totalPages,
17125
+ fromStore: false,
17126
+ ...extracted.degradedPages?.length ? { degradedPages: extracted.degradedPages } : {}
17127
+ };
17128
+ })().finally(() => {
17129
+ inFlight.delete(flightKey);
17130
+ });
17131
+ inFlight.set(flightKey, { promise, listeners });
17132
+ return promise;
17133
+ }
17134
+ function createStoreIo(exuluConfig) {
17135
+ return {
17136
+ head: (key) => headS3ObjectExact(key, exuluConfig),
17137
+ getBytes: (key) => getS3ObjectBytesWithInfo(key, exuluConfig),
17138
+ getText: (key) => getS3ObjectTextExact(key, exuluConfig),
17139
+ putText: (key, text, metadata) => putS3ObjectTextExact(key, text, metadata, exuluConfig, key.endsWith(".json") ? "application/json" : void 0)
17140
+ };
17141
+ }
17142
+
16090
17143
  // src/templates/tools/parse-document-tool.ts
16091
17144
  var DEFAULT_LIMIT2 = 250;
16092
17145
  var MAX_CONTENT_CHARS2 = 16e3;
@@ -16116,6 +17169,50 @@ var OFFICE_EXTENSIONS = /* @__PURE__ */ new Set([
16116
17169
  ".odp",
16117
17170
  ".rtf"
16118
17171
  ]);
17172
+ var ExtractionRefusal = class extends Error {
17173
+ constructor(info) {
17174
+ super(info.kind);
17175
+ this.info = info;
17176
+ }
17177
+ };
17178
+ function refusalMessage2(info, name) {
17179
+ switch (info.kind) {
17180
+ case "tooLong":
17181
+ return tooLongForToolNotice(name, info.pageCount, info.maxPages);
17182
+ case "garbledTextLayer":
17183
+ return `"${name}" has a text layer that is unreadable (its font encoding maps glyphs to the wrong characters, so words and especially numbers come out wrong or vanish). Do not use extracted text from this file. Use view_document_page to read the pages visually, or suggest the user add the document to a knowledge base with a document processor for full OCR.`;
17184
+ case "noTextLayer":
17185
+ return `"${name}" has no extractable text layer (likely a scan or image-based PDF). Use view_document_page to look at pages visually, or suggest the user add the document to a knowledge base with a document processor for full OCR.`;
17186
+ case "notFound":
17187
+ return `Could not read session file "${name}" (status 404). Check the exact file name.`;
17188
+ case "readFailed":
17189
+ return `Could not read "${name}". Try again; if it keeps failing, tell the user.`;
17190
+ }
17191
+ }
17192
+ function collapsePageList(pages) {
17193
+ const sorted = [...new Set(pages)].sort((a, b) => a - b);
17194
+ const parts = [];
17195
+ for (let i = 0; i < sorted.length; ) {
17196
+ let j = i;
17197
+ while (j + 1 < sorted.length && sorted[j + 1] === sorted[j] + 1) j++;
17198
+ parts.push(j > i ? `${sorted[i]}-${sorted[j]}` : String(sorted[i]));
17199
+ i = j + 1;
17200
+ }
17201
+ return parts.join(", ");
17202
+ }
17203
+ function selectPages(fullText, range) {
17204
+ const parts = fullText.split(/^(?=--- page \d+ ---$)/m);
17205
+ if (parts.length < 2 && !/^--- page \d+ ---$/m.test(fullText)) return fullText;
17206
+ const kept = [];
17207
+ parts.forEach((part, i) => {
17208
+ const m = /^--- page (\d+) ---$/m.exec(part);
17209
+ if (!m) return;
17210
+ const page = Number(m[1]);
17211
+ if (page < range[0] || page > range[1]) return;
17212
+ kept.push(i < parts.length - 1 ? part.replace(/\n$/, "") : part);
17213
+ });
17214
+ return kept.join("\n");
17215
+ }
16119
17216
  var pagesPattern = /^(\d+)(?:-(\d+))?$/;
16120
17217
  function resolvePageRange(pages, totalPages, safeName) {
16121
17218
  if (!pages) return [1, totalPages];
@@ -16147,7 +17244,8 @@ var createParseDocumentTool = ({
16147
17244
  user,
16148
17245
  exuluConfig,
16149
17246
  ownerId,
16150
- projectId
17247
+ projectId,
17248
+ turnProject
16151
17249
  }) => {
16152
17250
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
16153
17251
  const parseDocumentExecute = async ({
@@ -16155,18 +17253,18 @@ var createParseDocumentTool = ({
16155
17253
  pages,
16156
17254
  offset,
16157
17255
  limit
16158
- }) => {
17256
+ }, onProgress) => {
16159
17257
  const resolvedKey = resolveFileKey({
16160
17258
  filename,
16161
17259
  ownerId: ownerId ?? user?.id ?? "api",
16162
17260
  sessionId: sessionID,
16163
- projectId: projectId ?? null,
17261
+ projectId: currentProjectId(turnProject, projectId),
16164
17262
  s3prefix: exuluConfig.fileUploads.s3prefix
16165
17263
  });
16166
17264
  if ("error" in resolvedKey) return { error: resolvedKey.error };
16167
17265
  const key = resolvedKey.key;
16168
17266
  const safeName = String(filename).trim();
16169
- const ext = extname(safeName).toLowerCase();
17267
+ const ext = extname2(safeName).toLowerCase();
16170
17268
  if (ext !== ".pdf" && !OFFICE_EXTENSIONS.has(ext)) {
16171
17269
  return {
16172
17270
  error: `Unsupported extension "${ext}" \u2014 parse_document handles PDF and Office formats. For plain-text files use read_session_file.`
@@ -16177,54 +17275,92 @@ var createParseDocumentTool = ({
16177
17275
  }
16178
17276
  const uploads = exuluConfig.fileUploads;
16179
17277
  try {
16180
- const url = await getPresignedUrl(uploads.s3Bucket, key, exuluConfig);
16181
- const res = await fetch(url);
16182
- if (!res.ok) {
16183
- return { error: `Could not read session file "${safeName}" (status ${res.status}). Check the exact file name.` };
16184
- }
16185
- const bytes = Buffer.from(await res.arrayBuffer());
16186
- let fullText;
16187
- let totalPages;
16188
- if (exuluConfig.attachments?.documentProcessor) {
16189
- const extracted = await extractDocument({ bytes, filename: safeName, exuluConfig, attribution: { user } });
16190
- if (extracted.tooLong) {
16191
- return { error: extracted.text };
16192
- }
16193
- if (extracted.engine === "document-processor") {
16194
- totalPages = extracted.pages.length;
16195
- const range = resolvePageRange(pages, totalPages, safeName);
16196
- if (!Array.isArray(range)) return range;
16197
- const multiPage = totalPages > 1;
16198
- fullText = extracted.pages.filter(({ page }) => page >= range[0] && page <= range[1]).map(({ page, text }) => multiPage ? `--- page ${page} ---
16199
- ${text.trim()}` : text.trim()).join("\n");
17278
+ const baseIo = createStoreIo(exuluConfig);
17279
+ const io = {
17280
+ ...baseIo,
17281
+ getBytes: async (sourceKey) => {
17282
+ try {
17283
+ return await baseIo.getBytes(sourceKey);
17284
+ } catch (err3) {
17285
+ if (isS3NotFound(err3)) throw new ExtractionRefusal({ kind: "notFound" });
17286
+ console.error(`[EXULU] parse_document: could not read ${sourceKey}:`, err3 instanceof Error ? err3.message : String(err3));
17287
+ throw new ExtractionRefusal({ kind: "readFailed" });
17288
+ }
16200
17289
  }
16201
- }
16202
- if (fullText === void 0 && ext === ".pdf") {
16203
- const raw = await pdfToText(bytes);
16204
- const pageTexts = raw.replace(/\f$/, "").split("\f");
16205
- totalPages = pageTexts.length;
16206
- const nonWhitespace = raw.replace(/\s/g, "").length;
16207
- if (looksLikeGarbledTextLayer(raw)) {
16208
- return {
16209
- error: `"${safeName}" has a text layer that is unreadable (its font encoding maps glyphs to the wrong characters, so words and especially numbers come out wrong or vanish). Do not use extracted text from this file. Use view_document_page to read the pages visually, or suggest the user add the document to a knowledge base with a document processor for full OCR.`
16210
- };
17290
+ };
17291
+ const extractFull = async (bytes, onProgress2) => {
17292
+ let processorFellBack = false;
17293
+ if (exuluConfig.attachments?.documentProcessor) {
17294
+ const extracted = await extractDocument({
17295
+ bytes,
17296
+ filename: safeName,
17297
+ exuluConfig,
17298
+ attribution: { user },
17299
+ maxPages: documentMaxPages(),
17300
+ tolerateVisionFailures: true,
17301
+ onProgress: onProgress2
17302
+ });
17303
+ if (extracted.tooLong) {
17304
+ throw new ExtractionRefusal({ kind: "tooLong", ...extracted.tooLong });
17305
+ }
17306
+ if (extracted.engine === "document-processor") {
17307
+ const multiPage = extracted.pages.length > 1;
17308
+ const degraded = extracted.degradedPages ?? [];
17309
+ return {
17310
+ totalPages: extracted.pages.length,
17311
+ storable: degraded.length === 0,
17312
+ ...degraded.length > 0 ? { degradedPages: degraded } : {},
17313
+ text: extracted.pages.map(({ page, text }) => multiPage ? `--- page ${page} ---
17314
+ ${text.trim()}` : text.trim()).join("\n")
17315
+ };
17316
+ }
17317
+ processorFellBack = extracted.engine === "officeparser";
16211
17318
  }
16212
- if (nonWhitespace < totalPages * MIN_CHARS_PER_PAGE) {
17319
+ if (ext === ".pdf") {
17320
+ const raw = await pdfToText(bytes);
17321
+ const pageTexts = raw.replace(/\f$/, "").split("\f");
17322
+ const pageCount = pageTexts.length;
17323
+ const nonWhitespace = raw.replace(/\s/g, "").length;
17324
+ if (looksLikeGarbledTextLayer(raw)) {
17325
+ throw new ExtractionRefusal({ kind: "garbledTextLayer" });
17326
+ }
17327
+ if (nonWhitespace < pageCount * MIN_CHARS_PER_PAGE) {
17328
+ throw new ExtractionRefusal({ kind: "noTextLayer" });
17329
+ }
16213
17330
  return {
16214
- error: `"${safeName}" has no extractable text layer (likely a scan or image-based PDF). Use view_document_page to look at pages visually, or suggest the user add the document to a knowledge base with a document processor for full OCR.`
17331
+ totalPages: pageCount,
17332
+ storable: !processorFellBack,
17333
+ text: pageTexts.map((text, i) => `--- page ${i + 1} ---
17334
+ ${text.trim()}`).join("\n")
16215
17335
  };
16216
17336
  }
16217
- const range = resolvePageRange(pages, totalPages, safeName);
16218
- if (!Array.isArray(range)) return range;
16219
- fullText = pageTexts.map((text, i) => ({ page: i + 1, text })).filter(({ page }) => page >= range[0] && page <= range[1]).map(({ page, text }) => `--- page ${page} ---
16220
- ${text.trim()}`).join("\n");
16221
- } else if (fullText === void 0) {
16222
17337
  const officeBytes = isLegacyOfficeFormat(ext) ? await convertLegacyOfficeToModern(bytes, ext) : bytes;
16223
- const extracted = await parseOfficeAsync2(officeBytes, {
17338
+ const parsed = await parseOfficeAsync2(officeBytes, {
16224
17339
  outputErrorToConsole: false,
16225
17340
  newlineDelimiter: "\n"
16226
17341
  });
16227
- fullText = String(extracted);
17342
+ return { text: String(parsed), storable: !processorFellBack };
17343
+ };
17344
+ const stored = await readThroughDocument({
17345
+ io,
17346
+ bucket: uploads.s3Bucket,
17347
+ sourceKey: key,
17348
+ s3prefix: uploads.s3prefix,
17349
+ fingerprint: extractorFingerprint({ filename: safeName, exuluConfig }),
17350
+ cacheDays: documentCacheDays(),
17351
+ extract: extractFull,
17352
+ ...onProgress ? { onProgress } : {}
17353
+ });
17354
+ let fullText = stored.text;
17355
+ let degradedInRange = [];
17356
+ const totalPages = stored.totalPages ?? (ext === ".pdf" ? 1 : void 0);
17357
+ if (ext === ".pdf" && totalPages !== void 0) {
17358
+ const range = resolvePageRange(pages, totalPages, safeName);
17359
+ if (!Array.isArray(range)) return range;
17360
+ if (pages) fullText = selectPages(fullText, range);
17361
+ degradedInRange = (stored.degradedPages ?? []).filter((p) => p >= range[0] && p <= range[1]);
17362
+ } else {
17363
+ degradedInRange = stored.degradedPages ?? [];
16228
17364
  }
16229
17365
  const lines = (fullText ?? "").split("\n");
16230
17366
  const start = (offset ?? 1) - 1;
@@ -16237,27 +17373,68 @@ ${text.trim()}`).join("\n");
16237
17373
  linesReturned = Math.max(1, content.split("\n").length - 1);
16238
17374
  content = content + "\n[slice truncated \u2014 request fewer lines]";
16239
17375
  }
17376
+ if (degradedInRange.length > 0) {
17377
+ content += `
17378
+ [Note: figures and tables on page(s) ${collapsePageList(degradedInRange)} could not be verified; the text for those pages is OCR only.]`;
17379
+ }
16240
17380
  return {
16241
17381
  content,
16242
17382
  ...totalPages !== void 0 ? { totalPages } : {},
16243
17383
  totalLines: lines.length,
16244
17384
  offset: start + 1,
16245
- linesReturned
17385
+ linesReturned,
17386
+ // Only when the text came from the store; the key is absent otherwise, so results of
17387
+ // uncached reads stay byte-identical to what they were.
17388
+ ...stored.fromStore ? { fromStore: true } : {}
16246
17389
  };
16247
17390
  } catch (err3) {
17391
+ if (err3 instanceof ExtractionRefusal) return { error: refusalMessage2(err3.info, safeName) };
16248
17392
  return { error: `Failed to parse "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
16249
17393
  }
16250
17394
  };
17395
+ async function* parseDocumentStream(args) {
17396
+ const filename = String(args.filename).trim();
17397
+ const queue = [];
17398
+ let wake;
17399
+ let finished = false;
17400
+ let closed = false;
17401
+ const onProgress = throttleProgress((p) => {
17402
+ if (closed) return;
17403
+ queue.push({ status: "reading", filename, ...p });
17404
+ wake?.();
17405
+ });
17406
+ const run = parseDocumentExecute(args, onProgress).finally(() => {
17407
+ finished = true;
17408
+ wake?.();
17409
+ });
17410
+ run.catch(() => void 0);
17411
+ try {
17412
+ while (true) {
17413
+ while (queue.length > 0) yield queue.shift();
17414
+ if (finished) break;
17415
+ await new Promise((resolve4) => {
17416
+ wake = resolve4;
17417
+ });
17418
+ wake = void 0;
17419
+ }
17420
+ yield await run;
17421
+ } finally {
17422
+ closed = true;
17423
+ queue.length = 0;
17424
+ }
17425
+ }
16251
17426
  return ExuluTool.internal({
16252
17427
  id: "parse_document",
16253
17428
  name: PARSE_DOCUMENT_TOOL_NAME,
16254
17429
  needsApproval: false,
16255
- description: "Extract the text of an uploaded PDF or Office document from this session's files, with \"--- page N ---\" markers for PDFs so you can locate content by page. Free and fast (no OCR): works only on documents with a real text layer. To SEE a page or an image inside a document, use view_document_page. Files of the session's project are addressed as `project/<name>` and are read-only.",
16256
- inputSchema: z19.object({
16257
- filename: z19.string().describe('Exact session file name, e.g. "report.pdf"'),
16258
- pages: z19.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
16259
- offset: z19.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
16260
- limit: z19.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
17430
+ // Without a document processor the tool reads the text layer only: say so, and keep the
17431
+ // original wording so existing deployments see no change beyond the reuse sentence.
17432
+ description: exuluConfig.attachments?.documentProcessor ? "Extract the text of an uploaded PDF or Office document from this session's files, with \"--- page N ---\" markers for PDFs so you can locate content by page. Results are stored and reused, so reading the same document again is fast, but the first read of a long document can take minutes. To SEE a page or an image inside a document, use view_document_page. Files of the session's project are addressed as `project/<name>` and are read-only." : "Extract the text of an uploaded PDF or Office document from this session's files, with \"--- page N ---\" markers for PDFs so you can locate content by page. Free and fast (no OCR): works only on documents with a real text layer. To SEE a page or an image inside a document, use view_document_page. Extracted text is stored and reused, so reading the same document again is fast. Files of the session's project are addressed as `project/<name>` and are read-only.",
17433
+ inputSchema: z20.object({
17434
+ filename: z20.string().describe('Exact session file name, e.g. "report.pdf"'),
17435
+ pages: z20.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
17436
+ offset: z20.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
17437
+ limit: z20.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
16261
17438
  }),
16262
17439
  type: "function",
16263
17440
  category: "session",
@@ -16265,25 +17442,25 @@ ${text.trim()}`).join("\n");
16265
17442
  // Same shape mismatch as read_session_file / memory-tool: internal utility
16266
17443
  // tools return richer objects than ExuluTool's retrieval-flavored execute
16267
17444
  // type; the AI SDK passes the object through verbatim.
16268
- execute: parseDocumentExecute
17445
+ execute: parseDocumentStream
16269
17446
  });
16270
17447
  };
16271
17448
 
16272
17449
  // src/templates/tools/view-document-page-tool.ts
16273
- import { z as z20 } from "zod";
16274
- import { extname as extname3 } from "path";
17450
+ import { z as z21 } from "zod";
17451
+ import { extname as extname4 } from "path";
16275
17452
 
16276
17453
  // src/sessions/pdf-preview-cache.ts
16277
17454
  import { exec as exec3 } from "child_process";
16278
17455
  import { existsSync as existsSync6 } from "fs";
16279
17456
  import { mkdir as mkdir4, readFile as readFile3, rename as rename3, rm as rm4, writeFile as writeFile4 } from "fs/promises";
16280
- import { extname as extname2, join as join6 } from "path";
17457
+ import { extname as extname3, join as join6 } from "path";
16281
17458
  import { promisify as promisify5 } from "util";
16282
17459
  var execAsync3 = promisify5(exec3);
16283
17460
  var CACHE_ROOT = "/tmp/exulu-pdf-cache";
16284
17461
  var CACHE_IN = join6(CACHE_ROOT, "_in");
16285
17462
  var CACHE_OUT = join6(CACHE_ROOT, "_out");
16286
- var inFlight = /* @__PURE__ */ new Map();
17463
+ var inFlight2 = /* @__PURE__ */ new Map();
16287
17464
  var PreviewRenderError = class extends Error {
16288
17465
  constructor(message) {
16289
17466
  super(message);
@@ -16303,13 +17480,13 @@ async function getPdfPreviewBytes(opts) {
16303
17480
  if (existsSync6(cachedPath)) {
16304
17481
  return readFile3(cachedPath);
16305
17482
  }
16306
- const existing = inFlight.get(safeEtag);
17483
+ const existing = inFlight2.get(safeEtag);
16307
17484
  if (existing) return existing;
16308
17485
  const promise = (async () => {
16309
17486
  try {
16310
17487
  await mkdir4(CACHE_IN, { recursive: true });
16311
17488
  await mkdir4(CACHE_OUT, { recursive: true });
16312
- const ext = (extname2(sourceKey) || ".docx").toLowerCase();
17489
+ const ext = (extname3(sourceKey) || ".docx").toLowerCase();
16313
17490
  const inputPath = join6(CACHE_IN, `${safeEtag}${ext}`);
16314
17491
  const outputPath = join6(CACHE_OUT, `${safeEtag}.pdf`);
16315
17492
  try {
@@ -16336,10 +17513,10 @@ async function getPdfPreviewBytes(opts) {
16336
17513
  await rm4(inputPath, { force: true });
16337
17514
  }
16338
17515
  } finally {
16339
- inFlight.delete(safeEtag);
17516
+ inFlight2.delete(safeEtag);
16340
17517
  }
16341
17518
  })();
16342
- inFlight.set(safeEtag, promise);
17519
+ inFlight2.set(safeEtag, promise);
16343
17520
  return promise;
16344
17521
  }
16345
17522
 
@@ -16450,7 +17627,8 @@ var createViewDocumentPageTool = ({
16450
17627
  user,
16451
17628
  exuluConfig,
16452
17629
  ownerId,
16453
- projectId
17630
+ projectId,
17631
+ turnProject
16454
17632
  }) => {
16455
17633
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
16456
17634
  const viewDocumentPageExecute = async ({ filename, page, model }, options) => {
@@ -16458,13 +17636,13 @@ var createViewDocumentPageTool = ({
16458
17636
  filename,
16459
17637
  ownerId: ownerId ?? user?.id ?? "api",
16460
17638
  sessionId: sessionID,
16461
- projectId: projectId ?? null,
17639
+ projectId: currentProjectId(turnProject, projectId),
16462
17640
  s3prefix: exuluConfig.fileUploads.s3prefix
16463
17641
  });
16464
17642
  if ("error" in resolvedKey) return { error: resolvedKey.error };
16465
17643
  const key = resolvedKey.key;
16466
17644
  const safeName = String(filename).trim();
16467
- const ext = extname3(safeName).toLowerCase();
17645
+ const ext = extname4(safeName).toLowerCase();
16468
17646
  const isImage = ext in IMAGE_MEDIA_TYPES;
16469
17647
  const isPdf = ext === ".pdf";
16470
17648
  const isOffice = OFFICE_EXTENSIONS2.has(ext);
@@ -16544,9 +17722,9 @@ var createViewDocumentPageTool = ({
16544
17722
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
16545
17723
  needsApproval: false,
16546
17724
  description: "LOOK at a page of an uploaded PDF/Office document, or at an uploaded image, from this session's files. The rendered image is attached as a user message directly after this tool result so you can visually analyze photos, charts, scans, and layouts. Use parse_document first to find which page you need. Requires a vision-capable model. Files of the session's project are addressed as `project/<name>` and are read-only.",
16547
- inputSchema: z20.object({
16548
- filename: z20.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
16549
- page: z20.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
17725
+ inputSchema: z21.object({
17726
+ filename: z21.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
17727
+ page: z21.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
16550
17728
  }),
16551
17729
  type: "function",
16552
17730
  category: "session",
@@ -16589,55 +17767,14 @@ function extractClientInfo(req) {
16589
17767
  }
16590
17768
 
16591
17769
  // src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts
17770
+ var isReadingProgress = (value) => {
17771
+ if (!isInterimToolStatus(value)) return false;
17772
+ const v = value;
17773
+ return typeof v.filename === "string" && typeof v.pagesDone === "number" && typeof v.pagesTotal === "number";
17774
+ };
16592
17775
  var OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
16593
- var generateS3Key = (filename) => `${randomUUID7()}-${filename}`;
17776
+ var generateS3Key = (filename) => `${randomUUID8()}-${filename}`;
16594
17777
  var s3Client2;
16595
- var getMimeType = (type) => {
16596
- switch (type) {
16597
- case ".png":
16598
- return "image/png";
16599
- case ".jpg":
16600
- return "image/jpg";
16601
- case ".jpeg":
16602
- return "image/jpeg";
16603
- case ".gif":
16604
- return "image/gif";
16605
- case ".webp":
16606
- return "image/webp";
16607
- case ".pdf":
16608
- return "application/pdf";
16609
- case ".docx":
16610
- return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
16611
- case ".xlsx":
16612
- return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
16613
- case ".xls":
16614
- return "application/vnd.ms-excel";
16615
- case ".csv":
16616
- return "text/csv";
16617
- case ".pptx":
16618
- return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
16619
- case ".ppt":
16620
- return "application/vnd.ms-powerpoint";
16621
- case ".m4a":
16622
- return "audio/mp4";
16623
- case ".mp4":
16624
- return "audio/mp4";
16625
- case ".mpeg":
16626
- return "audio/mpeg";
16627
- case ".mp3":
16628
- return "audio/mp3";
16629
- case ".wav":
16630
- return "audio/wav";
16631
- case ".txt":
16632
- return "text/plain";
16633
- case ".md":
16634
- return "text/markdown";
16635
- case ".json":
16636
- return "application/json";
16637
- default:
16638
- return "";
16639
- }
16640
- };
16641
17778
  var hydrateVariables = async (tool3) => {
16642
17779
  const { db } = await postgresClient();
16643
17780
  const promises = tool3.config.map(async (toolConfig) => {
@@ -16688,7 +17825,7 @@ var hydrateVariables = async (tool3) => {
16688
17825
  await Promise.all(promises);
16689
17826
  return tool3;
16690
17827
  };
16691
- var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions, skillDecisions, routineHandleFactory, resolvedProject) => {
17828
+ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions, skillDecisions, routineHandleFactory, resolvedProject, inRoutineRun) => {
16692
17829
  if (!currentTools) return {};
16693
17830
  if (!allExuluTools) {
16694
17831
  allExuluTools = [];
@@ -16700,6 +17837,7 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
16700
17837
  const toolOutputCharLimit = budget.toolOutputCapTokens * 4;
16701
17838
  const turnProject = resolvedProject !== void 0 ? resolvedProject : sessionID ? await resolveSessionProject({ projectId: project, ownerId: sessionOwnerId ?? user?.id, owner: user, speaker: user }) : null;
16702
17839
  const sandboxProjectId = turnProject?.id ?? null;
17840
+ const turnProjectHolder = createTurnProject(turnProject);
16703
17841
  let sharedSessionSandbox;
16704
17842
  if (sessionID && exuluConfig && agent?.sandbox_enabled === true) {
16705
17843
  try {
@@ -16788,11 +17926,11 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
16788
17926
  currentTools.push(sessionItemsRetrievalTool);
16789
17927
  }
16790
17928
  }
16791
- const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
17929
+ const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId, turnProject: turnProjectHolder });
16792
17930
  if (sessionFileReadTool && !disabled.has(sessionFileReadTool.id)) {
16793
17931
  currentTools.push(sessionFileReadTool);
16794
17932
  }
16795
- const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
17933
+ const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId, turnProject: turnProjectHolder });
16796
17934
  if (parseDocumentTool && !disabled.has(parseDocumentTool.id)) {
16797
17935
  currentTools.push(parseDocumentTool);
16798
17936
  }
@@ -16807,12 +17945,29 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
16807
17945
  exuluConfig,
16808
17946
  ownerId: sessionOwnerId,
16809
17947
  project: turnProject,
16810
- disabled
17948
+ disabled,
17949
+ turnProject: turnProjectHolder
16811
17950
  });
16812
17951
  if (saveToProjectTool) {
16813
17952
  currentTools.push(saveToProjectTool);
16814
17953
  }
16815
- const viewDocumentPageTool = createViewDocumentPageTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
17954
+ const createProjectTool = createCreateProjectTool({
17955
+ sessionID,
17956
+ user,
17957
+ req,
17958
+ exuluConfig,
17959
+ ownerId: sessionOwnerId,
17960
+ agentTools: agent?.tools,
17961
+ project: turnProject,
17962
+ sessionProjectId: project,
17963
+ routineRun: inRoutineRun ?? Boolean(routineHandleFactory),
17964
+ disabled,
17965
+ turnProject: turnProjectHolder
17966
+ });
17967
+ if (createProjectTool) {
17968
+ currentTools.push(createProjectTool);
17969
+ }
17970
+ const viewDocumentPageTool = createViewDocumentPageTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId, turnProject: turnProjectHolder });
16816
17971
  if (viewDocumentPageTool && !disabled.has(viewDocumentPageTool.id)) {
16817
17972
  currentTools.push(viewDocumentPageTool);
16818
17973
  }
@@ -17058,6 +18213,15 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
17058
18213
  user,
17059
18214
  contexts: contextsMap,
17060
18215
  upload,
18216
+ // Writes a file into this session's folder (undefined without a session, uploads, a signed-in user, or outside routines/public surface).
18217
+ saveSessionFile: buildSaveSessionFile({
18218
+ sessionID,
18219
+ ownerId: sessionOwnerId,
18220
+ user,
18221
+ req,
18222
+ exuluConfig,
18223
+ inRoutineRun: inRoutineRun ?? Boolean(routineHandleFactory)
18224
+ }),
17061
18225
  exuluConfig,
17062
18226
  toolVariablesConfig: toolVariablesConfigData,
17063
18227
  // Present only inside a routine run: routine.runs.current.update({ status }).
@@ -17084,16 +18248,19 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
17084
18248
  const offloadExempt = OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS.has(cur.id);
17085
18249
  if (response && typeof response === "object" && Symbol.asyncIterator in response) {
17086
18250
  let lastValue;
18251
+ let lastYieldWasInterim = false;
17087
18252
  for await (const value of response) {
17088
18253
  yield value;
17089
- lastValue = value;
18254
+ lastYieldWasInterim = isReadingProgress(value);
18255
+ if (!lastYieldWasInterim) lastValue = value;
17090
18256
  }
17091
18257
  if (offloadExempt) {
17092
18258
  __auditOutput = lastValue;
18259
+ if (lastYieldWasInterim) yield lastValue;
17093
18260
  return lastValue;
17094
18261
  }
17095
18262
  const guarded = await guardToolOutput(lastValue, guardCtx);
17096
- if (guarded !== lastValue) {
18263
+ if (guarded !== lastValue || lastYieldWasInterim) {
17097
18264
  yield guarded;
17098
18265
  }
17099
18266
  __auditOutput = guarded;
@@ -17152,6 +18319,9 @@ export {
17152
18319
  sanitizeFilename,
17153
18320
  MAX_PROJECT_FILES,
17154
18321
  projectFilePrefix,
18322
+ DERIVED_ROOT,
18323
+ isDerivedKey,
18324
+ documentCacheDays,
17155
18325
  getPresignedUrl,
17156
18326
  uploadFile,
17157
18327
  listS3ObjectsByPrefix,
@@ -17162,6 +18332,8 @@ export {
17162
18332
  getS3ObjectSize,
17163
18333
  getS3ObjectBytes,
17164
18334
  deleteS3Object,
18335
+ listS3ObjectsExact,
18336
+ deleteS3ObjectsExact,
17165
18337
  getS3SignedUploadUrl,
17166
18338
  createUppyRoutes,
17167
18339
  ExuluStorage,
@@ -17272,6 +18444,8 @@ export {
17272
18444
  treatAsGuest,
17273
18445
  KB_EDITOR_TOOL_ID,
17274
18446
  createKbEditorPickerTool,
18447
+ hasProjectAccess,
18448
+ RBACResolver,
17275
18449
  normalizeS3Key,
17276
18450
  deriveFilename,
17277
18451
  slugifyShareName,
@@ -17290,14 +18464,26 @@ export {
17290
18464
  MAX_ADOPT_UPLOAD_BYTES,
17291
18465
  planAdoptKeys,
17292
18466
  planAdoptSizeCheck,
18467
+ createProjectForUser,
18468
+ SKIP_TOO_LARGE,
18469
+ SKIP_PROJECT_FULL,
17293
18470
  COPY_FAILED_REASON,
17294
18471
  promoteSessionFiles,
17295
- sessionFilesScopeSentence,
17296
- loadSessionFileListing,
17297
18472
  getOriginResolver,
17298
18473
  createPromoteS3,
18474
+ parseStoredFileUrl,
18475
+ mayResignStoredFileKey,
18476
+ resolveFreshFileUrl,
18477
+ sessionFilesScopeSentence,
18478
+ loadSessionFileListing,
18479
+ createRunSession,
18480
+ isRunSessionMetadata,
18481
+ withRunSession,
18482
+ CREATE_PROJECT_TOOL_ID,
18483
+ canRegisterCreateProject,
18484
+ CREATE_PROJECT_PROMPT,
18485
+ createCreateProjectPickerTool,
17299
18486
  canRegisterSaveToProject,
17300
- RBACResolver,
17301
18487
  resolveSkillByName,
17302
18488
  canAccessSkill,
17303
18489
  filterReadableSkills,
@@ -17311,10 +18497,13 @@ export {
17311
18497
  findUnclassifiedSecretShaped,
17312
18498
  getAuditLogger,
17313
18499
  initAudit,
17314
- hasProjectAccess,
17315
18500
  downloadKeyIntoSandbox,
17316
18501
  refreshSessionSkills,
17317
18502
  resolveSessionProject,
18503
+ contentTypeFor2 as contentTypeFor,
18504
+ SAVE_INVALID_NAME,
18505
+ SAVE_EMPTY,
18506
+ SAVE_FAILED,
17318
18507
  truncateToolOutput,
17319
18508
  DEFAULT_CONTEXT_WINDOW,
17320
18509
  deriveContextBudget,