@exulu/backend 5.12.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";
@@ -584,6 +585,13 @@ var ExuluTool = class _ExuluTool {
584
585
  * the boolean and never applies the "Allow for this chat" shortcut.
585
586
  */
586
587
  needsApprovalFn;
588
+ /**
589
+ * Calls for which approval is ALWAYS asked, even when the user allowed the tool for this
590
+ * chat (e.g. save_to_project with overwrite: true). Only narrows the shortcut: a call whose
591
+ * approval was already answered is still honoured by the approval wiring.
592
+ * Ignored for tools that set `needsApprovalFn` (that check decides every call on its own).
593
+ */
594
+ alwaysAskWhen;
587
595
  authentication;
588
596
  config;
589
597
  constructor({
@@ -597,6 +605,7 @@ var ExuluTool = class _ExuluTool {
597
605
  config,
598
606
  needsApproval,
599
607
  needsApprovalFn,
608
+ alwaysAskWhen,
600
609
  authentication: authentication2
601
610
  }) {
602
611
  if (!PUBLIC_TOOL_TYPES.includes(type)) {
@@ -615,6 +624,7 @@ var ExuluTool = class _ExuluTool {
615
624
  this.config = config;
616
625
  this.needsApproval = needsApproval ?? true;
617
626
  this.needsApprovalFn = needsApprovalFn;
627
+ this.alwaysAskWhen = alwaysAskWhen;
618
628
  this.category = category || "default";
619
629
  this.name = name;
620
630
  this.description = description;
@@ -659,7 +669,7 @@ var ExuluTool = class _ExuluTool {
659
669
  if (!agent) {
660
670
  throw new Error("Agent not found.");
661
671
  }
662
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-WEC42QHZ.js");
672
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-UT7TOLLD.js");
663
673
  const tools = await convertExuluToolsToAiSdkTools2(
664
674
  [this],
665
675
  [],
@@ -2535,24 +2545,28 @@ function requiresPlainObject(schema) {
2535
2545
  function preserveDescription(original, rebuilt) {
2536
2546
  return original.description ? rebuilt.describe(original.description) : rebuilt;
2537
2547
  }
2538
- function loosenForTransport(schema) {
2548
+ function loosenForTransport(schema, options = {}) {
2549
+ return loosen(schema, options.nullableEntries === true);
2550
+ }
2551
+ function loosen(schema, nullEntries) {
2539
2552
  const def = schema.def;
2540
2553
  switch (def.type) {
2541
2554
  case "optional":
2542
- return preserveDescription(schema, z7.optional(loosenForTransport(def.innerType)));
2555
+ return preserveDescription(schema, z7.optional(loosen(def.innerType, nullEntries)));
2543
2556
  case "nullable":
2544
- return preserveDescription(schema, z7.nullable(loosenForTransport(def.innerType)));
2557
+ return preserveDescription(schema, z7.nullable(loosen(def.innerType, nullEntries)));
2545
2558
  case "default":
2546
2559
  return preserveDescription(
2547
2560
  schema,
2548
- loosenForTransport(def.innerType).default(
2561
+ loosen(def.innerType, nullEntries).default(
2549
2562
  def.defaultValue
2550
2563
  )
2551
2564
  );
2552
2565
  case "array":
2553
- return preserveDescription(schema, z7.array(loosenForTransport(def.element)));
2566
+ return preserveDescription(schema, z7.array(loosen(def.element, false)));
2554
2567
  case "record": {
2555
- const loosenedValue = loosenForTransport(def.valueType);
2568
+ const innerValue = loosen(def.valueType, false);
2569
+ const loosenedValue = nullEntries ? z7.nullable(innerValue) : innerValue;
2556
2570
  return preserveDescription(
2557
2571
  schema,
2558
2572
  schema.clone({ ...def, valueType: loosenedValue })
@@ -2561,7 +2575,7 @@ function loosenForTransport(schema) {
2561
2575
  case "union":
2562
2576
  return preserveDescription(
2563
2577
  schema,
2564
- z7.union(def.options.map((option) => loosenForTransport(option)))
2578
+ z7.union(def.options.map((option) => loosen(option, false)))
2565
2579
  );
2566
2580
  case "object": {
2567
2581
  const shape = def.shape;
@@ -2569,7 +2583,8 @@ function loosenForTransport(schema) {
2569
2583
  for (const key of Object.keys(shape)) {
2570
2584
  const child = shape[key];
2571
2585
  if (!child) continue;
2572
- loosenedShape[key] = loosenForTransport(child);
2586
+ const loosenedChild = loosen(child, false);
2587
+ loosenedShape[key] = nullEntries ? preserveDescription(child, z7.nullable(loosenedChild)) : loosenedChild;
2573
2588
  }
2574
2589
  return preserveDescription(
2575
2590
  schema,
@@ -3930,7 +3945,7 @@ function sanitizeToolName(name) {
3930
3945
  }
3931
3946
 
3932
3947
  // src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts
3933
- import { randomUUID as randomUUID7 } from "crypto";
3948
+ import { randomUUID as randomUUID8 } from "crypto";
3934
3949
 
3935
3950
  // types/enums/statistics.ts
3936
3951
  var STATISTICS_TYPE_ENUM = {
@@ -4169,11 +4184,170 @@ import {
4169
4184
  UploadPartCommand,
4170
4185
  ListObjectsV2Command,
4171
4186
  HeadObjectCommand,
4172
- DeleteObjectCommand
4187
+ DeleteObjectCommand,
4188
+ DeleteObjectsCommand
4173
4189
  } from "@aws-sdk/client-s3";
4174
4190
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
4175
4191
  import { STSClient, GetFederationTokenCommand } from "@aws-sdk/client-sts";
4176
4192
  import { randomUUID as randomUUID2 } from "crypto";
4193
+
4194
+ // src/exulu/session-files.ts
4195
+ function sessionFilePrefix(ownerId, sessionId, s3prefix) {
4196
+ const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
4197
+ return `${general}user_${ownerId}/sessions/${sessionId}/`;
4198
+ }
4199
+ function sanitizeFilename(name) {
4200
+ const trimmed = name.trim();
4201
+ if (!trimmed) return "";
4202
+ if (trimmed.includes("..")) return "";
4203
+ if (trimmed.startsWith("/") || trimmed.startsWith("\\")) return "";
4204
+ return trimmed.replace(/[\\/]/g, "_");
4205
+ }
4206
+
4207
+ // src/exulu/project-files.ts
4208
+ var MAX_PROJECT_FILES = 200;
4209
+ var MAX_PROMOTE_KEYS = 20;
4210
+ var PROJECT_DIR = "project";
4211
+ var generalPrefix = (s3prefix) => s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
4212
+ function projectFilePrefix(projectId, s3prefix) {
4213
+ const projectPrefix = `projects/${projectId}/files/`;
4214
+ return { projectPrefix, fullProjectPrefix: `${generalPrefix(s3prefix)}${projectPrefix}` };
4215
+ }
4216
+ function isProjectKey(key, s3prefix) {
4217
+ return key.replace(/^\/+/, "").startsWith(`${generalPrefix(s3prefix)}projects/`);
4218
+ }
4219
+ function parseProjectFilename(filename) {
4220
+ const marker = `${PROJECT_DIR}/`;
4221
+ if (!filename.startsWith(marker)) return { scope: "session", name: filename };
4222
+ const rest = filename.slice(marker.length);
4223
+ if (!rest) return { error: "Project filename is empty." };
4224
+ if (rest.includes("..")) return { error: "Project filename must not contain '..'." };
4225
+ if (rest.includes("/") || rest.includes("\\")) {
4226
+ return { error: "Project files are flat; subdirectories are not allowed." };
4227
+ }
4228
+ const name = sanitizeFilename(rest);
4229
+ if (!name) return { error: "Project filename is not valid." };
4230
+ return { scope: "project", name };
4231
+ }
4232
+ function planPromote(args) {
4233
+ const { keys, fullSessionPrefix, fullProjectPrefix, existingNames, overwrite } = args;
4234
+ if (keys.length > MAX_PROMOTE_KEYS) {
4235
+ return {
4236
+ accepted: [],
4237
+ rejected: keys.map((key) => ({
4238
+ key: String(key),
4239
+ reason: `Batch exceeds the ${MAX_PROMOTE_KEYS}-key promote limit.`
4240
+ })),
4241
+ clashes: []
4242
+ };
4243
+ }
4244
+ const accepted = [];
4245
+ const rejected = [];
4246
+ const clashes = [];
4247
+ const existing = new Set(existingNames);
4248
+ const owners = /* @__PURE__ */ new Map();
4249
+ for (const raw of keys) {
4250
+ if (typeof raw !== "string" || !raw.trim()) {
4251
+ rejected.push({ key: String(raw), reason: "Key must be a non-empty string." });
4252
+ continue;
4253
+ }
4254
+ const key = raw.replace(/^\/+/, "");
4255
+ if (key.includes("..")) {
4256
+ rejected.push({ key: raw, reason: "Key contains a path traversal segment." });
4257
+ continue;
4258
+ }
4259
+ if (!key.startsWith(fullSessionPrefix)) {
4260
+ rejected.push({ key: raw, reason: "Key is not a file of this session." });
4261
+ continue;
4262
+ }
4263
+ const name = sanitizeFilename(key.slice(fullSessionPrefix.length));
4264
+ if (!name) {
4265
+ rejected.push({ key: raw, reason: "Could not derive a safe filename." });
4266
+ continue;
4267
+ }
4268
+ if (owners.has(name)) {
4269
+ const first = owners.get(name);
4270
+ if (first) {
4271
+ const idx = accepted.indexOf(first);
4272
+ if (idx !== -1) accepted.splice(idx, 1);
4273
+ rejected.push({ key: first.sourceKey, reason: "Filename collides with another key in this batch." });
4274
+ owners.set(name, null);
4275
+ }
4276
+ rejected.push({ key: raw, reason: "Filename collides with another key in this batch." });
4277
+ continue;
4278
+ }
4279
+ if (existing.has(name) && !overwrite) {
4280
+ clashes.push(name);
4281
+ owners.set(name, null);
4282
+ continue;
4283
+ }
4284
+ const entry = { sourceKey: key, name, destKey: `${fullProjectPrefix}${name}` };
4285
+ accepted.push(entry);
4286
+ owners.set(name, entry);
4287
+ }
4288
+ const newCount = accepted.filter((a) => !existing.has(a.name)).length;
4289
+ if (existing.size + newCount > MAX_PROJECT_FILES) {
4290
+ for (const a of accepted) {
4291
+ rejected.push({
4292
+ key: a.sourceKey,
4293
+ reason: `A project holds at most ${MAX_PROJECT_FILES} files.`
4294
+ });
4295
+ }
4296
+ return { accepted: [], rejected, clashes };
4297
+ }
4298
+ return { accepted, rejected, clashes };
4299
+ }
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
+
4350
+ // src/uppy/index.ts
4177
4351
  var expiresIn = 60 * 60 * 24 * 1;
4178
4352
  var s3Client;
4179
4353
  function getS3Client(config) {
@@ -4285,7 +4459,7 @@ var uploadFile = async (file, fileName, config, options = {}, user, customBucket
4285
4459
  if (error.name === "SignatureDoesNotMatch" || error.name === "InvalidAccessKeyId" || error.name === "AccessDenied") {
4286
4460
  if (attempt < maxRetries) {
4287
4461
  const backoffMs = Math.pow(2, attempt) * 1e3;
4288
- await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
4462
+ await new Promise((resolve4) => setTimeout(resolve4, backoffMs));
4289
4463
  s3Client = void 0;
4290
4464
  getS3Client(config);
4291
4465
  continue;
@@ -4339,7 +4513,10 @@ var copyS3Object = async (sourceKey, destKey, config) => {
4339
4513
  const command = new CopyObjectCommand({
4340
4514
  Bucket: bucket,
4341
4515
  CopySource: `${bucket}/${encodeS3KeyForCopySource(sourceKey)}`,
4342
- Key: destKey
4516
+ Key: destKey,
4517
+ // Explicit so the origin marker (exulu-origin) survives a copy; promoting a
4518
+ // file into a project must not turn an agent file into a "user" file.
4519
+ MetadataDirective: "COPY"
4343
4520
  });
4344
4521
  await client.send(command);
4345
4522
  };
@@ -4384,6 +4561,73 @@ var getS3ObjectEtag = async (key, config) => {
4384
4561
  return null;
4385
4562
  }
4386
4563
  };
4564
+ function isS3NotFound(err3) {
4565
+ const e = err3;
4566
+ return e?.$metadata?.httpStatusCode === 404 || e?.name === "NotFound" || e?.name === "NoSuchKey" || e?.Code === "NotFound" || e?.Code === "NoSuchKey";
4567
+ }
4568
+ var getS3ObjectMetadataStrict = async (key, config) => {
4569
+ if (!config.fileUploads) {
4570
+ throw new Error("File uploads are not configured");
4571
+ }
4572
+ const client = getS3Client(config);
4573
+ try {
4574
+ const response = await client.send(
4575
+ new HeadObjectCommand({ Bucket: config.fileUploads.s3Bucket, Key: key })
4576
+ );
4577
+ return response.Metadata;
4578
+ } catch (err3) {
4579
+ if (isS3NotFound(err3)) return void 0;
4580
+ throw err3;
4581
+ }
4582
+ };
4583
+ function mayUseGenericS3Route(key, user, s3prefix) {
4584
+ if (isDerivedKey(key, s3prefix)) return false;
4585
+ if (user.type === "api" || user.super_admin) return true;
4586
+ return !isProjectKey(key, s3prefix);
4587
+ }
4588
+ function genericKeyDirectories(key, s3prefix) {
4589
+ const segments = key.split("/");
4590
+ if (segments.some((s) => s === "" || s === "." || s === "..")) return null;
4591
+ const general = (s3prefix ?? "").replace(/^\/+|\/+$/g, "");
4592
+ const prefixSegments = general ? general.split("/") : [];
4593
+ const hasPrefix = prefixSegments.length > 0 && prefixSegments.every((p, i) => segments[i] === p);
4594
+ return segments.slice(hasPrefix ? prefixSegments.length : 0, -1);
4595
+ }
4596
+ function mayReadGenericS3Key(key, user, s3prefix) {
4597
+ if (user.type === "api" || user.super_admin) return true;
4598
+ const directories = genericKeyDirectories(key, s3prefix);
4599
+ if (directories === null) return false;
4600
+ return directories.every((d) => !d.startsWith("user_") || d === `user_${user.id}`);
4601
+ }
4602
+ function mayDeleteGenericS3Key(key, user, s3prefix) {
4603
+ if (user.type === "api" || user.super_admin) return true;
4604
+ if (!mayReadGenericS3Key(key, user, s3prefix)) return false;
4605
+ return (genericKeyDirectories(key, s3prefix) ?? []).includes(`user_${user.id}`);
4606
+ }
4607
+ function multipartKeyBelongsTo(key, user, s3prefix) {
4608
+ if (!key || key.split("/").includes("..")) return false;
4609
+ let rest = key;
4610
+ const general = (s3prefix ?? "").replace(/\/+$/, "");
4611
+ if (general) {
4612
+ if (!rest.startsWith(`${general}/`)) return false;
4613
+ rest = rest.slice(general.length + 1);
4614
+ }
4615
+ const own = user.type === "api" ? "user_api/" : `user_${user.id}/`;
4616
+ return rest.startsWith(own) || rest.startsWith("global/");
4617
+ }
4618
+ function buildStsPolicy(bucket, userId, s3prefix) {
4619
+ const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
4620
+ return {
4621
+ Version: "2012-10-17",
4622
+ Statement: [
4623
+ {
4624
+ Effect: "Allow",
4625
+ Action: ["s3:PutObject"],
4626
+ Resource: [`arn:aws:s3:::${bucket}/${general}user_${userId}/*`]
4627
+ }
4628
+ ]
4629
+ };
4630
+ }
4387
4631
  var getS3ObjectSize = async (key, config) => {
4388
4632
  if (!config.fileUploads) {
4389
4633
  throw new Error("File uploads are not configured");
@@ -4413,6 +4657,85 @@ var getS3ObjectBytes = async (key, config) => {
4413
4657
  const byteArray = await response.Body.transformToByteArray();
4414
4658
  return Buffer.from(byteArray);
4415
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
+ };
4416
4739
  var deleteS3Object = async (key, config) => {
4417
4740
  if (!config.fileUploads) {
4418
4741
  throw new Error("File uploads are not configured");
@@ -4422,7 +4745,42 @@ var deleteS3Object = async (key, config) => {
4422
4745
  const command = new DeleteObjectCommand({ Bucket: bucket, Key: key });
4423
4746
  await client.send(command);
4424
4747
  };
4425
- var getS3SignedUploadUrl = async (key, contentType, config) => {
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
+ };
4783
+ var getS3SignedUploadUrl = async (key, contentType, config, opts = {}) => {
4426
4784
  if (!config.fileUploads) {
4427
4785
  throw new Error("File uploads are not configured");
4428
4786
  }
@@ -4435,7 +4793,7 @@ var getS3SignedUploadUrl = async (key, contentType, config) => {
4435
4793
  Key: key,
4436
4794
  ContentType: contentType
4437
4795
  }),
4438
- { expiresIn }
4796
+ { expiresIn: opts.expiresIn ?? expiresIn }
4439
4797
  );
4440
4798
  return url;
4441
4799
  };
@@ -4443,19 +4801,6 @@ var createUppyRoutes = async (app, config) => {
4443
4801
  if (!config.fileUploads) {
4444
4802
  throw new Error("File uploads are not configured");
4445
4803
  }
4446
- const policy = {
4447
- Version: "2012-10-17",
4448
- Statement: [
4449
- {
4450
- Effect: "Allow",
4451
- Action: ["s3:PutObject"],
4452
- Resource: [
4453
- `arn:aws:s3:::${config.fileUploads.s3Bucket}/*`,
4454
- `arn:aws:s3:::${config.fileUploads.s3Bucket}`
4455
- ]
4456
- }
4457
- ]
4458
- };
4459
4804
  let stsClient;
4460
4805
  function getSTSClient() {
4461
4806
  if (!config.fileUploads) {
@@ -4499,7 +4844,11 @@ var createUppyRoutes = async (app, config) => {
4499
4844
  return;
4500
4845
  }
4501
4846
  let bucket = key.split("/")[0];
4502
- if (user.type !== "api" && !key.includes(`/user_${user.id}/`) && !user.super_admin) {
4847
+ if (!mayUseGenericS3Route(key.replace(`${bucket}/`, ""), user, config.fileUploads.s3prefix)) {
4848
+ res.status(403).json({ error: "Project files cannot be deleted through this route." });
4849
+ return;
4850
+ }
4851
+ if (!mayDeleteGenericS3Key(key.slice((bucket ?? "").length + 1), user, config.fileUploads.s3prefix)) {
4503
4852
  res.status(405).json({
4504
4853
  error: "Not allowed to access the files in the folder based on authenticated user."
4505
4854
  });
@@ -4554,11 +4903,11 @@ var createUppyRoutes = async (app, config) => {
4554
4903
  res.status(400).json({ error: "Missing or invalid `key` query parameter." });
4555
4904
  return;
4556
4905
  }
4557
- let allowed = false;
4558
- if (user.type === "api" || user.super_admin || !key.includes(`user_`) || key.includes(`user_${user.id}/`)) {
4559
- allowed = true;
4906
+ if (!mayUseGenericS3Route(key, user, config.fileUploads?.s3prefix)) {
4907
+ res.status(403).json({ error: "Project files cannot be downloaded through this route." });
4908
+ return;
4560
4909
  }
4561
- if (!allowed) {
4910
+ if (!mayReadGenericS3Key(key, user, config.fileUploads?.s3prefix)) {
4562
4911
  res.status(405).json({ error: "Not allowed to access the file based on authenticated user." });
4563
4912
  return;
4564
4913
  }
@@ -4591,17 +4940,30 @@ var createUppyRoutes = async (app, config) => {
4591
4940
  res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
4592
4941
  return;
4593
4942
  }
4594
- let { key } = req.body;
4943
+ let { key } = req.body ?? {};
4944
+ if (typeof key !== "string" || key.trim() === "") {
4945
+ res.status(400).json({ error: "Missing or invalid `key` in the request body." });
4946
+ return;
4947
+ }
4595
4948
  let bucket = key.split("/")[0];
4596
- if (!bucket || typeof bucket !== "string" || bucket.trim() === "") {
4949
+ if (!bucket || bucket.trim() === "") {
4597
4950
  res.status(400).json({
4598
4951
  error: "Missing or invalid `bucket` (should be the first part of the key before the first slash)."
4599
4952
  });
4600
4953
  return;
4601
4954
  }
4602
4955
  key = key.split("/").slice(1).join("/");
4603
- if (!key || typeof key !== "string" || key.trim() === "") {
4604
- res.status(400).json({ error: "Missing or invalid `key` query parameter." });
4956
+ if (!key || key.trim() === "") {
4957
+ res.status(400).json({ error: "Missing or invalid `key` in the request body." });
4958
+ return;
4959
+ }
4960
+ const user = authenticationResult.user;
4961
+ if (!mayUseGenericS3Route(key, user, config.fileUploads.s3prefix)) {
4962
+ res.status(403).json({ error: "Project files cannot be read through this route." });
4963
+ return;
4964
+ }
4965
+ if (!mayReadGenericS3Key(key, user, config.fileUploads?.s3prefix)) {
4966
+ res.status(403).json({ error: "Not allowed to access the file based on authenticated user." });
4605
4967
  return;
4606
4968
  }
4607
4969
  const client = getS3Client(config);
@@ -4609,9 +4971,23 @@ var createUppyRoutes = async (app, config) => {
4609
4971
  Bucket: bucket,
4610
4972
  Key: key
4611
4973
  });
4612
- const response = await client.send(command);
4613
- res.json(response);
4614
- res.end();
4974
+ let response;
4975
+ try {
4976
+ response = await client.send(command);
4977
+ } catch (err3) {
4978
+ if (err3?.name === "NotFound" || err3?.name === "NoSuchKey" || err3?.$metadata?.httpStatusCode === 404) {
4979
+ res.status(404).json({ error: "Object not found." });
4980
+ return;
4981
+ }
4982
+ throw err3;
4983
+ }
4984
+ res.json({
4985
+ ContentLength: response.ContentLength,
4986
+ ContentType: response.ContentType,
4987
+ LastModified: response.LastModified,
4988
+ ETag: response.ETag,
4989
+ Metadata: response.Metadata
4990
+ });
4615
4991
  });
4616
4992
  app.get("/s3/list", async (req, res) => {
4617
4993
  if (!config.fileUploads) {
@@ -4637,9 +5013,9 @@ var createUppyRoutes = async (app, config) => {
4637
5013
  const client = getS3Client(config);
4638
5014
  let prefix = `${config.fileUploads.s3prefix ? config.fileUploads.s3prefix.replace(/\/$/, "") + "/" : ""}`;
4639
5015
  if (!req.headers.global) {
4640
- prefix += `user_${authenticationResult.user.id}`;
5016
+ prefix += `user_${authenticationResult.user.id}/`;
4641
5017
  } else {
4642
- prefix += "global";
5018
+ prefix += "global/";
4643
5019
  }
4644
5020
  console.log("[EXULU] bucket", config.fileUploads.s3Bucket);
4645
5021
  console.log("[EXULU] prefix", prefix);
@@ -4694,10 +5070,28 @@ var createUppyRoutes = async (app, config) => {
4694
5070
  });
4695
5071
  res.end();
4696
5072
  });
4697
- app.get("/s3/sts", (req, res, next) => {
5073
+ app.get("/s3/sts", async (req, res, next) => {
4698
5074
  if (!config.fileUploads) {
4699
5075
  throw new Error("File uploads are not configured");
4700
5076
  }
5077
+ const apikey = req.headers["exulu-api-key"] || null;
5078
+ const internalkey = req.headers["internal-key"] || null;
5079
+ const { db } = await postgresClient();
5080
+ let authtoken = null;
5081
+ if (typeof apikey !== "string" && typeof internalkey !== "string") {
5082
+ authtoken = await getToken(req.headers.authorization ?? "");
5083
+ }
5084
+ const authenticationResult = await authentication({ authtoken, apikey, internalkey, db });
5085
+ if (!authenticationResult.user?.id) {
5086
+ res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
5087
+ return;
5088
+ }
5089
+ const user = authenticationResult.user;
5090
+ const policy = buildStsPolicy(
5091
+ config.fileUploads.s3Bucket,
5092
+ user.type === "api" ? "api" : user.id,
5093
+ config.fileUploads.s3prefix
5094
+ );
4701
5095
  getSTSClient().send(
4702
5096
  new GetFederationTokenCommand({
4703
5097
  Name: "Exulu",
@@ -4709,7 +5103,7 @@ var createUppyRoutes = async (app, config) => {
4709
5103
  })
4710
5104
  ).then((response) => {
4711
5105
  res.setHeader("Access-Control-Allow-Origin", "*");
4712
- res.setHeader("Cache-Control", `public,max-age=${expiresIn}`);
5106
+ res.setHeader("Cache-Control", `private,max-age=${expiresIn}`);
4713
5107
  res.json({
4714
5108
  credentials: response.Credentials,
4715
5109
  bucket: config.fileUploads?.s3Bucket,
@@ -4852,24 +5246,45 @@ var createUppyRoutes = async (app, config) => {
4852
5246
  });
4853
5247
  });
4854
5248
  });
5249
+ const authorizeMultipartKey = async (req, res) => {
5250
+ const apikey = req.headers["exulu-api-key"] || null;
5251
+ const { db } = await postgresClient();
5252
+ let authtoken = null;
5253
+ if (typeof apikey !== "string") {
5254
+ authtoken = await getToken(req.headers.authorization ?? "");
5255
+ }
5256
+ const authenticationResult = await authentication({ authtoken, apikey, db });
5257
+ if (!authenticationResult.user?.id) {
5258
+ res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
5259
+ return null;
5260
+ }
5261
+ const { key } = req.query;
5262
+ if (typeof key !== "string") {
5263
+ res.status(400).json({
5264
+ error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"'
5265
+ });
5266
+ return null;
5267
+ }
5268
+ if (!multipartKeyBelongsTo(key, authenticationResult.user, config.fileUploads?.s3prefix)) {
5269
+ res.status(403).json({ error: "s3: this upload does not belong to the authenticated user." });
5270
+ return null;
5271
+ }
5272
+ return key;
5273
+ };
4855
5274
  function validatePartNumber(partNumber) {
4856
5275
  partNumber = Number(partNumber);
4857
5276
  return Number.isInteger(partNumber) && partNumber >= 1 && partNumber <= 1e4;
4858
5277
  }
4859
- app.get("/s3/multipart/:uploadId/:partNumber", (req, res, next) => {
5278
+ app.get("/s3/multipart/:uploadId/:partNumber", async (req, res, next) => {
4860
5279
  if (!config.fileUploads) {
4861
5280
  throw new Error("File uploads are not configured");
4862
5281
  }
4863
5282
  const { uploadId, partNumber } = req.params;
4864
- const { key } = req.query;
4865
5283
  if (!validatePartNumber(partNumber)) {
4866
5284
  return res.status(400).json({ error: "s3: the part number must be an integer between 1 and 10000." });
4867
5285
  }
4868
- if (typeof key !== "string") {
4869
- return res.status(400).json({
4870
- error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"'
4871
- });
4872
- }
5286
+ const key = await authorizeMultipartKey(req, res);
5287
+ if (key === null) return;
4873
5288
  return getSignedUrl(
4874
5289
  getS3Client(config),
4875
5290
  new UploadPartCommand({
@@ -4885,16 +5300,12 @@ var createUppyRoutes = async (app, config) => {
4885
5300
  res.json({ url, expires: expiresIn });
4886
5301
  }, next);
4887
5302
  });
4888
- app.get("/s3/multipart/:uploadId", (req, res, next) => {
5303
+ app.get("/s3/multipart/:uploadId", async (req, res, next) => {
5304
+ const authorizedKey = await authorizeMultipartKey(req, res);
5305
+ if (authorizedKey === null) return;
5306
+ const key = authorizedKey;
4889
5307
  const client = getS3Client(config);
4890
5308
  const { uploadId } = req.params;
4891
- const { key } = req.query;
4892
- if (typeof key !== "string") {
4893
- res.status(400).json({
4894
- error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"'
4895
- });
4896
- return;
4897
- }
4898
5309
  const parts = [];
4899
5310
  function listPartsPage(startAt) {
4900
5311
  if (!config.fileUploads) {
@@ -4926,19 +5337,15 @@ var createUppyRoutes = async (app, config) => {
4926
5337
  function isValidPart(part) {
4927
5338
  return part && typeof part === "object" && Number(part.PartNumber) && typeof part.ETag === "string";
4928
5339
  }
4929
- app.post("/s3/multipart/:uploadId/complete", (req, res, next) => {
5340
+ app.post("/s3/multipart/:uploadId/complete", async (req, res, next) => {
4930
5341
  if (!config.fileUploads) {
4931
5342
  throw new Error("File uploads are not configured");
4932
5343
  }
5344
+ const key = await authorizeMultipartKey(req, res);
5345
+ if (key === null) return;
4933
5346
  const client = getS3Client(config);
4934
5347
  const { uploadId } = req.params;
4935
- const { key } = req.query;
4936
5348
  const { parts } = req.body;
4937
- if (typeof key !== "string") {
4938
- return res.status(400).json({
4939
- error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"'
4940
- });
4941
- }
4942
5349
  if (!Array.isArray(parts) || !parts.every(isValidPart)) {
4943
5350
  return res.status(400).json({ error: "s3: `parts` must be an array of {ETag, PartNumber} objects." });
4944
5351
  }
@@ -4964,18 +5371,14 @@ var createUppyRoutes = async (app, config) => {
4964
5371
  }
4965
5372
  );
4966
5373
  });
4967
- app.delete("/s3/multipart/:uploadId", (req, res, next) => {
5374
+ app.delete("/s3/multipart/:uploadId", async (req, res, next) => {
4968
5375
  if (!config.fileUploads) {
4969
5376
  throw new Error("File uploads are not configured");
4970
5377
  }
5378
+ const key = await authorizeMultipartKey(req, res);
5379
+ if (key === null) return;
4971
5380
  const client = getS3Client(config);
4972
5381
  const { uploadId } = req.params;
4973
- const { key } = req.query;
4974
- if (typeof key !== "string") {
4975
- return res.status(400).json({
4976
- error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"'
4977
- });
4978
- }
4979
5382
  return client.send(
4980
5383
  new AbortMultipartUploadCommand({
4981
5384
  Bucket: config.fileUploads.s3Bucket,
@@ -6167,14 +6570,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
6167
6570
  for (const row of rows) {
6168
6571
  const centered = new Float64Array(dims);
6169
6572
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
6170
- const z20 = new Float64Array(basis.length);
6573
+ const z22 = new Float64Array(basis.length);
6171
6574
  for (const [b, vec] of basis.entries()) {
6172
6575
  let dot = 0;
6173
6576
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
6174
- z20[b] = dot;
6577
+ z22[b] = dot;
6175
6578
  }
6176
6579
  for (const [b, target] of next.entries()) {
6177
- const scale = z20[b] ?? 0;
6580
+ const scale = z22[b] ?? 0;
6178
6581
  if (scale === 0) continue;
6179
6582
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
6180
6583
  }
@@ -6272,12 +6675,12 @@ function ridgeFit(Z, Y, lambda) {
6272
6675
  });
6273
6676
  return { map, intercept };
6274
6677
  }
6275
- function applyMap(z20, map, intercept) {
6678
+ function applyMap(z22, map, intercept) {
6276
6679
  const out = [];
6277
6680
  for (let j = 0; j < 3; j += 1) {
6278
6681
  let v = intercept[j] ?? 0;
6279
6682
  const row = map[j] ?? [];
6280
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z20[d] ?? 0);
6683
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z22[d] ?? 0);
6281
6684
  out.push(Number.isFinite(v) ? v : 0);
6282
6685
  }
6283
6686
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -6300,8 +6703,8 @@ function fitResidual(Z, Y, map, intercept) {
6300
6703
  for (let i = 0; i < Z.length; i += 1) {
6301
6704
  const zi = Z[i] ?? [];
6302
6705
  const yi = Y[i] ?? [];
6303
- const [x, y, z20] = applyMap(zi, map, intercept);
6304
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z20 - 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]));
6305
6708
  }
6306
6709
  return finite(total / Z.length);
6307
6710
  }
@@ -6441,8 +6844,8 @@ async function chunkCoordinates({
6441
6844
  }
6442
6845
  return null;
6443
6846
  }
6444
- const [x, y, z20] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6445
- return { x, y, z: z20 };
6847
+ const [x, y, z22] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6848
+ return { x, y, z: z22 };
6446
6849
  });
6447
6850
  } catch (e) {
6448
6851
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -6528,8 +6931,8 @@ var captureCodeEmbedder = (context) => {
6528
6931
  };
6529
6932
  var codeEmbedderFor = (context) => codeEmbedders.has(context) ? codeEmbedders.get(context) : context.embedder;
6530
6933
  var contextEmbedderInfoFor = async (context, deps = {}) => {
6531
- const resolve3 = deps.resolve ?? resolveContextEmbedder;
6532
- return resolve3({ id: context.id, embedder: codeEmbedderFor(context) });
6934
+ const resolve4 = deps.resolve ?? resolveContextEmbedder;
6935
+ return resolve4({ id: context.id, embedder: codeEmbedderFor(context) });
6533
6936
  };
6534
6937
  var willEmbedOnQueue = async (context, overrideQueue) => {
6535
6938
  if (overrideQueue) {
@@ -6538,11 +6941,11 @@ var willEmbedOnQueue = async (context, overrideQueue) => {
6538
6941
  return Boolean(await codeEmbedderFor(context)?.queue);
6539
6942
  };
6540
6943
  var hydrateContextEmbedders = async (contexts, deps = {}) => {
6541
- const { resolve: resolve3, modelInfo, queues } = { ...defaultDeps(), ...deps };
6944
+ const { resolve: resolve4, modelInfo, queues } = { ...defaultDeps(), ...deps };
6542
6945
  for (const context of contexts) {
6543
6946
  try {
6544
6947
  const codeEmbedder = captureCodeEmbedder(context);
6545
- const info = await resolve3({ id: context.id, embedder: codeEmbedder });
6948
+ const info = await resolve4({ id: context.id, embedder: codeEmbedder });
6546
6949
  if (info.source !== "database" || !info.databaseModel) {
6547
6950
  context.embedder = codeEmbedder;
6548
6951
  continue;
@@ -7229,13 +7632,13 @@ var extractEntitiesForItem = async ({
7229
7632
  };
7230
7633
 
7231
7634
  // src/exulu/entities/normalize.ts
7232
- import { createHash as createHash2 } from "crypto";
7635
+ import { createHash as createHash3 } from "crypto";
7233
7636
  var normalizeCanonicalKey = (name) => {
7234
7637
  return name.toLowerCase().normalize("NFKC").replace(/\s+/g, " ").trim().replace(/^[\s\p{P}]+|[\s\p{P}]+$/gu, "").trim();
7235
7638
  };
7236
7639
  var computeTypesSignature = (types) => {
7237
7640
  const names = Array.from(new Set(types.map((t) => t.name.toLowerCase().trim()))).sort().join("|");
7238
- return createHash2("sha1").update(names).digest("hex").slice(0, 16);
7641
+ return createHash3("sha1").update(names).digest("hex").slice(0, 16);
7239
7642
  };
7240
7643
 
7241
7644
  // src/exulu/entities/types.ts
@@ -11416,19 +11819,6 @@ function collectMemoryDecisions(messages) {
11416
11819
  import { z as z13 } from "zod";
11417
11820
  import { randomUUID as randomUUID3 } from "crypto";
11418
11821
 
11419
- // src/exulu/session-files.ts
11420
- function sessionFilePrefix(ownerId, sessionId, s3prefix) {
11421
- const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
11422
- return `${general}user_${ownerId}/sessions/${sessionId}/`;
11423
- }
11424
- function sanitizeFilename(name) {
11425
- const trimmed = name.trim();
11426
- if (!trimmed) return "";
11427
- if (trimmed.includes("..")) return "";
11428
- if (trimmed.startsWith("/") || trimmed.startsWith("\\")) return "";
11429
- return trimmed.replace(/[\\/]/g, "_");
11430
- }
11431
-
11432
11822
  // src/utils/check-item-write-access.ts
11433
11823
  var checkItemWriteAccess = async (context, record, user) => {
11434
11824
  if (!user) {
@@ -12043,7 +12433,7 @@ var buildWriteSchema = (context, mode) => {
12043
12433
  break;
12044
12434
  case "json":
12045
12435
  jsonFieldNames.push(field.name);
12046
- 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.`);
12047
12437
  break;
12048
12438
  case "markdown":
12049
12439
  schema = z13.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
@@ -12311,10 +12701,44 @@ var collectKbWriteTools = (agent, contexts, deps = {}) => {
12311
12701
  return tools;
12312
12702
  };
12313
12703
 
12314
- // src/templates/tools/skill-author-tools.ts
12315
- import { randomUUID as randomUUID4 } from "crypto";
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
12316
12714
  import { z as z14 } from "zod";
12317
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
+
12318
12742
  // ee/rbac-resolver.ts
12319
12743
  var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
12320
12744
  const license = checkLicense();
@@ -12345,6 +12769,1172 @@ var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
12345
12769
  };
12346
12770
  };
12347
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
+
12799
+ // src/exulu/shared-artifacts.ts
12800
+ import bcrypt2 from "bcryptjs";
12801
+ var normalizeS3Key = (key, bucket) => {
12802
+ const segments = key.split("/").filter((s, i) => !(i === 0 && s === "")).map((s) => decodeURIComponent(s));
12803
+ if (segments[0] === bucket) segments.shift();
12804
+ return segments.join("/");
12805
+ };
12806
+ var isHtmlKey = (key) => /\.html?$/i.test(key);
12807
+ var deriveFilename = (key) => {
12808
+ const base = key.split("/").pop() ?? key;
12809
+ return base.split("_EXULU_").pop() ?? base;
12810
+ };
12811
+ var slugifyShareName = (input) => deriveFilename(input).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
12812
+ var isExpired = (expiresAt, now) => {
12813
+ if (!expiresAt) return false;
12814
+ return new Date(expiresAt).getTime() <= now.getTime();
12815
+ };
12816
+ var validateCreateInput = (input, now) => {
12817
+ if (!input.s3key) return { ok: false, message: "s3key is required." };
12818
+ if (!input.name) return { ok: false, message: "name is required." };
12819
+ const mode = input.auth_mode;
12820
+ if (mode !== "public" && mode !== "password" && mode !== "regular") {
12821
+ return { ok: false, message: "auth_mode must be public, password, or regular." };
12822
+ }
12823
+ if (mode === "password" && !input.password) {
12824
+ return { ok: false, message: "A password is required for password mode." };
12825
+ }
12826
+ if (input.expires_at && Number.isNaN(new Date(input.expires_at).getTime())) {
12827
+ return { ok: false, message: "expires_at is not a valid date." };
12828
+ }
12829
+ if (input.expires_at && isExpired(input.expires_at, now)) {
12830
+ return { ok: false, message: "expires_at must be in the future." };
12831
+ }
12832
+ return { ok: true };
12833
+ };
12834
+ var validateAgentSlots = (value) => {
12835
+ if (!Array.isArray(value)) {
12836
+ return { ok: false, message: "agent_slots must be an array." };
12837
+ }
12838
+ const slots = [];
12839
+ const seenKeys = /* @__PURE__ */ new Set();
12840
+ for (const entry of value) {
12841
+ if (typeof entry !== "object" || entry === null) {
12842
+ return { ok: false, message: "Each agent slot must be an object." };
12843
+ }
12844
+ const { key, agentId } = entry;
12845
+ if (typeof key !== "string" || !key.trim()) {
12846
+ return { ok: false, message: "Each agent slot needs a non-empty key." };
12847
+ }
12848
+ if (typeof agentId !== "string" || !agentId.trim()) {
12849
+ return { ok: false, message: "Each agent slot needs a non-empty agentId." };
12850
+ }
12851
+ const trimmedKey = key.trim();
12852
+ if (seenKeys.has(trimmedKey)) {
12853
+ return { ok: false, message: "agent_slots keys must be unique." };
12854
+ }
12855
+ seenKeys.add(trimmedKey);
12856
+ slots.push({ key: trimmedKey, agentId });
12857
+ }
12858
+ return { ok: true, slots };
12859
+ };
12860
+ var readAgentSlots = (value) => {
12861
+ const parsed = typeof value === "string" ? (() => {
12862
+ try {
12863
+ return JSON.parse(value);
12864
+ } catch {
12865
+ return null;
12866
+ }
12867
+ })() : value;
12868
+ return Array.isArray(parsed) ? parsed : [];
12869
+ };
12870
+ var RIGHTS_MODES = /* @__PURE__ */ new Set(["private", "users", "roles", "teams", "public"]);
12871
+ var canManageShare = (row, user) => user.super_admin === true || row.created_by != null && String(row.created_by) === String(user.id);
12872
+ var validateUpdateInput = (input, row, now) => {
12873
+ if (input.name !== void 0 && !slugifyShareName(input.name)) {
12874
+ return { ok: false, message: "name must contain url-safe characters." };
12875
+ }
12876
+ const mode = input.auth_mode ?? row.auth_mode;
12877
+ if (mode !== "public" && mode !== "password" && mode !== "regular") {
12878
+ return { ok: false, message: "auth_mode must be public, password, or regular." };
12879
+ }
12880
+ const keepsPassword = row.auth_mode === "password" && !!row.password_hash;
12881
+ if (mode === "password" && !input.password && !keepsPassword) {
12882
+ return { ok: false, message: "A password is required for password mode." };
12883
+ }
12884
+ if (input.expires_at && Number.isNaN(new Date(input.expires_at).getTime())) {
12885
+ return { ok: false, message: "expires_at is not a valid date." };
12886
+ }
12887
+ if (input.expires_at && isExpired(input.expires_at, now)) {
12888
+ return { ok: false, message: "expires_at must be in the future." };
12889
+ }
12890
+ if (input.rights_mode !== void 0 && !RIGHTS_MODES.has(input.rights_mode)) {
12891
+ return { ok: false, message: "rights_mode must be private, users, roles, teams, or public." };
12892
+ }
12893
+ if (input.s3key !== void 0 && (typeof input.s3key !== "string" || !input.s3key.trim())) {
12894
+ return { ok: false, message: "s3key must be a non-empty string." };
12895
+ }
12896
+ if (input.agent_slots !== void 0) {
12897
+ const slotsResult = validateAgentSlots(input.agent_slots);
12898
+ if (!slotsResult.ok) return { ok: false, message: slotsResult.message };
12899
+ }
12900
+ return { ok: true };
12901
+ };
12902
+ var ownsObjectKey = (key, user, s3prefix) => {
12903
+ if (user.super_admin === true) return true;
12904
+ let k = key.replace(/^\/+/, "");
12905
+ const prefix = (s3prefix ?? "").replace(/\/+$/, "");
12906
+ if (prefix && k.startsWith(prefix + "/")) k = k.slice(prefix.length + 1);
12907
+ const owner = user.type === "api" ? "api" : String(user.id);
12908
+ return k.startsWith(`user_${owner}/`);
12909
+ };
12910
+ var planShareUpdate = (input, row, newPasswordHash, now) => {
12911
+ const mode = input.auth_mode ?? row.auth_mode;
12912
+ const patch = { auth_mode: mode, updatedAt: now };
12913
+ if (input.name !== void 0) patch.name = slugifyShareName(input.name);
12914
+ if (input.s3key !== void 0) patch.s3key = input.s3key;
12915
+ if (input.content_type !== void 0) patch.content_type = input.content_type;
12916
+ patch.password_hash = mode === "password" ? newPasswordHash ?? row.password_hash : null;
12917
+ if (input.expires_at !== void 0) patch.expires_at = input.expires_at;
12918
+ if (mode === "regular") {
12919
+ patch.rights_mode = input.rights_mode ?? (row.auth_mode === "regular" ? row.rights_mode ?? "private" : "private");
12920
+ } else {
12921
+ patch.rights_mode = "public";
12922
+ }
12923
+ if (input.agent_slots !== void 0) {
12924
+ const slotsResult = validateAgentSlots(input.agent_slots);
12925
+ if (slotsResult.ok) patch.agent_slots = slotsResult.slots;
12926
+ }
12927
+ return patch;
12928
+ };
12929
+ var hashSharePassword = (password) => bcrypt2.hash(password, 10);
12930
+ var verifySharePassword = (password, hash) => bcrypt2.compare(password, hash);
12931
+ var contentHeadersFor = (key, contentType, filename) => {
12932
+ if (isHtmlKey(key)) return { contentType: "text/html; charset=utf-8" };
12933
+ return {
12934
+ contentType: contentType || "application/octet-stream",
12935
+ disposition: `attachment; filename="${filename.replace(/"/g, "")}"`
12936
+ };
12937
+ };
12938
+ var publicMetaFor = (row) => ({
12939
+ auth_mode: row.auth_mode,
12940
+ expires_at: row.expires_at ?? null,
12941
+ filename: deriveFilename(row.s3key),
12942
+ content_type: row.content_type ?? null,
12943
+ is_html: isHtmlKey(row.s3key)
12944
+ });
12945
+ var getSharedArtifactByName = (db, name) => db("shared_artifacts").where({ name }).first();
12946
+
12947
+ // src/exulu/session-file-adopt.ts
12948
+ var MAX_ADOPT_KEYS = 20;
12949
+ var MAX_ADOPT_UPLOAD_BYTES = 50 * 1024 * 1024;
12950
+ var ownsAdoptKey = (key, user, s3prefix) => {
12951
+ const prefix = (s3prefix ?? "").replace(/\/+$/, "");
12952
+ const stripped = prefix && key.startsWith(`${prefix}/`) ? key.slice(prefix.length + 1) : key;
12953
+ const owner = user.type === "api" ? "api" : String(user.id);
12954
+ return stripped.startsWith(`user_${owner}/`);
12955
+ };
12956
+ var planAdoptKeys = (keys, user, s3prefix, bucket) => {
12957
+ if (!Array.isArray(keys)) {
12958
+ return { accepted: [], rejected: [] };
12959
+ }
12960
+ if (keys.length > MAX_ADOPT_KEYS) {
12961
+ return {
12962
+ accepted: [],
12963
+ rejected: keys.map((k) => ({
12964
+ key: typeof k === "string" ? k : String(k),
12965
+ reason: `Batch exceeds the ${MAX_ADOPT_KEYS}-key adopt limit.`
12966
+ }))
12967
+ };
12968
+ }
12969
+ const accepted = [];
12970
+ const rejected = [];
12971
+ const filenameOwners = /* @__PURE__ */ new Map();
12972
+ for (const raw of keys) {
12973
+ if (typeof raw !== "string" || !raw.trim()) {
12974
+ rejected.push({
12975
+ key: typeof raw === "string" ? raw : String(raw),
12976
+ reason: "Key must be a non-empty string."
12977
+ });
12978
+ continue;
12979
+ }
12980
+ let normalized;
12981
+ try {
12982
+ normalized = normalizeS3Key(raw, bucket).replace(/^\/+/, "");
12983
+ } catch {
12984
+ rejected.push({ key: raw, reason: "Key is not a valid S3 key." });
12985
+ continue;
12986
+ }
12987
+ if (normalized.includes("..")) {
12988
+ rejected.push({ key: raw, reason: "Key contains a path traversal segment." });
12989
+ continue;
12990
+ }
12991
+ if (!ownsAdoptKey(normalized, user, s3prefix)) {
12992
+ rejected.push({ key: raw, reason: "You do not own this object." });
12993
+ continue;
12994
+ }
12995
+ const filename = sanitizeFilename(deriveFilename(normalized));
12996
+ if (!filename) {
12997
+ rejected.push({ key: raw, reason: "Could not derive a safe filename." });
12998
+ continue;
12999
+ }
13000
+ if (filenameOwners.has(filename)) {
13001
+ const existing = filenameOwners.get(filename);
13002
+ if (existing) {
13003
+ const idx = accepted.indexOf(existing);
13004
+ if (idx !== -1) accepted.splice(idx, 1);
13005
+ rejected.push({ key: existing.key, reason: "Filename collides with another key in this batch." });
13006
+ filenameOwners.set(filename, null);
13007
+ }
13008
+ rejected.push({ key: raw, reason: "Filename collides with another key in this batch." });
13009
+ continue;
13010
+ }
13011
+ const entry = { source: normalized, filename, key: raw };
13012
+ accepted.push(entry);
13013
+ filenameOwners.set(filename, entry);
13014
+ }
13015
+ return { accepted, rejected };
13016
+ };
13017
+ var planAdoptSizeCheck = (checks, maxBytes) => {
13018
+ const rejected = [];
13019
+ for (const { entry, size } of checks) {
13020
+ if (size === null) {
13021
+ rejected.push({ key: entry.key, reason: "Source object not found." });
13022
+ } else if (size > maxBytes) {
13023
+ rejected.push({
13024
+ key: entry.key,
13025
+ reason: `File exceeds the ${Math.floor(maxBytes / (1024 * 1024))}MB upload limit.`
13026
+ });
13027
+ }
13028
+ }
13029
+ if (rejected.length > 0) return { proceed: false, rejected };
13030
+ return { proceed: true };
13031
+ };
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
+
13162
+ // src/exulu/project-files-promote.ts
13163
+ var COPY_FAILED_REASON = "Copying the file into the project failed.";
13164
+ async function promoteSessionFiles(args) {
13165
+ const { projectPrefix, fullProjectPrefix } = projectFilePrefix(args.projectId, args.s3prefix);
13166
+ const existingNames = await args.s3.listProjectNames(projectPrefix);
13167
+ const plan = planPromote({
13168
+ keys: args.keys,
13169
+ fullSessionPrefix: args.fullSessionPrefix,
13170
+ fullProjectPrefix,
13171
+ existingNames,
13172
+ overwrite: args.overwrite
13173
+ });
13174
+ const rejected = [...plan.rejected];
13175
+ if (plan.clashes.length > 0 || plan.accepted.length === 0) {
13176
+ return { promoted: [], rejected, clashes: plan.clashes };
13177
+ }
13178
+ const sizes = [];
13179
+ for (const a of plan.accepted) sizes.push({ key: a.sourceKey, size: await args.s3.sizeOf(a.sourceKey) });
13180
+ const perFile = planAdoptSizeCheck(
13181
+ plan.accepted.map((a, i) => ({
13182
+ entry: { key: a.sourceKey, source: a.sourceKey, filename: a.name },
13183
+ size: sizes[i].size
13184
+ })),
13185
+ MAX_ADOPT_UPLOAD_BYTES
13186
+ );
13187
+ const total = sizes.reduce((sum, s) => sum + (s.size ?? 0), 0);
13188
+ if (!perFile.proceed || total > MAX_ADOPT_UPLOAD_BYTES) {
13189
+ const reasons = !perFile.proceed ? perFile.rejected : [];
13190
+ const byKey = new Map(reasons.map((r) => [r.key, r.reason]));
13191
+ for (const a of plan.accepted) {
13192
+ rejected.push({
13193
+ key: a.sourceKey,
13194
+ reason: byKey.get(a.sourceKey) ?? "The batch exceeds the 50MB total limit."
13195
+ });
13196
+ }
13197
+ return { promoted: [], rejected, clashes: [] };
13198
+ }
13199
+ const promoted = [];
13200
+ for (const a of plan.accepted) {
13201
+ try {
13202
+ await args.s3.copy(a.sourceKey, a.destKey);
13203
+ promoted.push({ key: a.destKey, name: a.name, sourceKey: a.sourceKey });
13204
+ } catch (err3) {
13205
+ console.error("[PROJECT-FILES] copy failed", a.sourceKey, err3);
13206
+ rejected.push({ key: a.sourceKey, reason: COPY_FAILED_REASON });
13207
+ }
13208
+ }
13209
+ return { promoted, rejected, clashes: [] };
13210
+ }
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;
13255
+ }
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";
13261
+ }
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
+ };
13277
+ }
13278
+
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`;
13380
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
13381
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
13382
+ }
13383
+ function formatAge(then, now) {
13384
+ const minutes = Math.max(0, Math.round((now.getTime() - then.getTime()) / 6e4));
13385
+ if (minutes < 1) return "just now";
13386
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
13387
+ const hours = Math.round(minutes / 60);
13388
+ if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
13389
+ const days = Math.round(hours / 24);
13390
+ return `${days} day${days === 1 ? "" : "s"} ago`;
13391
+ }
13392
+ function describeSessionFiles(files, opts = {}) {
13393
+ const now = opts.now ?? /* @__PURE__ */ new Date();
13394
+ const max = opts.max ?? DEFAULT_MAX;
13395
+ const usable = files.filter((f) => f.name && !f.name.endsWith("/") && !isIgnoredArtifactPath(f.name)).sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
13396
+ if (usable.length === 0) return "";
13397
+ const shown = usable.slice(0, max);
13398
+ const lines = shown.map((f) => {
13399
+ const isNew = opts.lastTurnAt ? f.lastModified.getTime() > opts.lastTurnAt.getTime() : false;
13400
+ return `- ${f.name} (${formatSize(f.size)}, ${formatAge(f.lastModified, now)})${isNew ? " [NEW since your last answer]" : ""}`;
13401
+ });
13402
+ const omitted = usable.length - shown.length;
13403
+ if (omitted > 0) lines.push(`\u2026 and ${omitted} more file${omitted === 1 ? "" : "s"} (list them with \`ls\`).`);
13404
+ return "Files currently in this session (newest first):\n" + lines.join("\n") + '\nThese files are available to you. When the user refers to one of these files, to "the document" or "the attachment", or asks something only such a file can answer, read it with parse_document, view_document_page or read_session_file. Otherwise proceed as usual, e.g. with the knowledge bases.';
13405
+ }
13406
+ function listingLines(files, opts) {
13407
+ const now = opts.now ?? /* @__PURE__ */ new Date();
13408
+ const max = opts.max ?? DEFAULT_MAX;
13409
+ const usable = files.filter((f) => f.name && !f.name.endsWith("/") && !isIgnoredArtifactPath(f.name)).sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
13410
+ const shown = usable.slice(0, max);
13411
+ const lines = shown.map((f) => {
13412
+ const isNew = opts.lastTurnAt ? f.lastModified.getTime() > opts.lastTurnAt.getTime() : false;
13413
+ return `- ${f.name} (${formatSize(f.size)}, ${formatAge(f.lastModified, now)})${isNew ? " [NEW since your last answer]" : ""}`;
13414
+ });
13415
+ return { lines, omitted: usable.length - shown.length, total: usable.length };
13416
+ }
13417
+ var MAX_PROMPT_NAME = 80;
13418
+ function promptSafeProjectName(name) {
13419
+ return name.replace(/\s+/g, " ").trim().slice(0, MAX_PROMPT_NAME);
13420
+ }
13421
+ function projectLabel(project) {
13422
+ return `${promptSafeProjectName(project.name)} (id ${project.id})`;
13423
+ }
13424
+ function describeProjectFiles(files, project, opts = {}) {
13425
+ const { lines, omitted, total } = listingLines(files, opts);
13426
+ if (total === 0) return "";
13427
+ if (omitted > 0) lines.push(`+${omitted} more (list them with \`ls project/\`).`);
13428
+ return `Project files (shared with everyone on project ${projectLabel(project)}):
13429
+ ` + lines.join("\n") + `
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.`;
13431
+ }
13432
+ function sessionFilesScopeSentence(project, canSaveToProject = false) {
13433
+ if (!project) {
13434
+ return "These files are scoped to\n this single session; they are NOT visible in other sessions, projects, or knowledge bases.";
13435
+ }
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.";
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;
13438
+ }
13439
+ async function loadSessionFileListing(opts) {
13440
+ const uploads = opts.exuluConfig?.fileUploads;
13441
+ if (!uploads?.s3Bucket) return "";
13442
+ const prefix = sessionFilePrefix(opts.ownerId, opts.sessionID, uploads.s3prefix);
13443
+ let sessionBlock = "";
13444
+ try {
13445
+ const objects = await listS3ObjectsByPrefix(prefix, opts.exuluConfig);
13446
+ const files = objects.map((o) => ({
13447
+ name: o.key.slice(o.key.indexOf(prefix) + prefix.length),
13448
+ size: o.size,
13449
+ lastModified: new Date(o.lastModified)
13450
+ }));
13451
+ sessionBlock = describeSessionFiles(files, { lastTurnAt: opts.lastTurnAt });
13452
+ } catch (err3) {
13453
+ console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`, err3);
13454
+ }
13455
+ if (!opts.project) return sessionBlock;
13456
+ let projectBlock = "";
13457
+ try {
13458
+ const { projectPrefix } = projectFilePrefix(opts.project.id);
13459
+ const objects = await listS3ObjectsByPrefix(projectPrefix, opts.exuluConfig);
13460
+ const files = objects.map((o) => ({
13461
+ name: o.key.slice(o.key.indexOf(projectPrefix) + projectPrefix.length),
13462
+ size: o.size,
13463
+ lastModified: new Date(o.lastModified)
13464
+ }));
13465
+ projectBlock = describeProjectFiles(
13466
+ files.filter((f) => !f.name.includes("/")),
13467
+ opts.project,
13468
+ { lastTurnAt: opts.lastTurnAt }
13469
+ );
13470
+ } catch (err3) {
13471
+ console.warn(`[EXULU] could not list project files for prompt (session ${opts.sessionID}):`, err3);
13472
+ }
13473
+ return [sessionBlock, projectBlock].filter(Boolean).join("\n\n");
13474
+ }
13475
+
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;
13515
+ }
13516
+ var isRunSessionMetadata = (metadata) => {
13517
+ if (metadata == null) {
13518
+ return false;
13519
+ }
13520
+ let parsed = metadata;
13521
+ if (typeof metadata === "string") {
13522
+ try {
13523
+ parsed = JSON.parse(metadata);
13524
+ } catch {
13525
+ return false;
13526
+ }
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);
13582
+ }
13583
+
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
+ }
13596
+ }
13597
+ return Array.isArray(entries) && entries.some((t) => t?.id === CREATE_PROJECT_TOOL_ID);
13598
+ }
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");
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
+ });
13826
+
13827
+ // src/templates/tools/save-to-project-tool.ts
13828
+ import { z as z15 } from "zod";
13829
+ var SAVE_TO_PROJECT_TOOL_NAME = "save_to_project";
13830
+ var SAVE_TO_PROJECT_TOOL_ID = "save_to_project";
13831
+ function canRegisterSaveToProject(args) {
13832
+ if (!args.sessionID || !args.exuluConfig?.fileUploads?.s3Bucket) return false;
13833
+ if (!args.project?.speakerCanWrite) return false;
13834
+ if (treatAsGuest(args.req, args.user)) return false;
13835
+ const disabled = args.disabled instanceof Set ? args.disabled : new Set(args.disabled ?? []);
13836
+ return !disabled.has(SAVE_TO_PROJECT_TOOL_ID);
13837
+ }
13838
+ var createSaveToProjectTool = ({
13839
+ sessionID,
13840
+ user,
13841
+ req,
13842
+ exuluConfig,
13843
+ ownerId,
13844
+ project,
13845
+ disabled,
13846
+ deps,
13847
+ turnProject
13848
+ }) => {
13849
+ if (!canRegisterSaveToProject({ sessionID, exuluConfig, project, req, user, disabled })) return void 0;
13850
+ if (!sessionID || !exuluConfig || !project) return void 0;
13851
+ const uploads = exuluConfig.fileUploads;
13852
+ if (!uploads) return void 0;
13853
+ const projectLabel2 = promptSafeProjectName(project.name);
13854
+ const resolvedDeps = deps ?? {
13855
+ promote: promoteSessionFiles,
13856
+ s3: createPromoteS3(exuluConfig),
13857
+ projectModified: async (name) => {
13858
+ const { projectPrefix } = projectFilePrefix(currentProjectId(turnProject, project.id) ?? project.id, uploads.s3prefix);
13859
+ const objects = await listS3ObjectsByPrefix(projectPrefix, exuluConfig);
13860
+ const hit = objects.find((o) => o.key.split("/").pop() === name);
13861
+ return hit ? new Date(hit.lastModified) : void 0;
13862
+ }
13863
+ };
13864
+ const execute = async ({ filename, overwrite }) => {
13865
+ const name = String(filename ?? "").trim();
13866
+ if (name.startsWith(`${PROJECT_DIR}/`)) {
13867
+ return {
13868
+ result: `"${name}" is already in the project. Pass the name of a session file, without the "${PROJECT_DIR}/" prefix.`
13869
+ };
13870
+ }
13871
+ if (!name || name.includes("/") || name.includes("\\") || name.includes("..")) {
13872
+ return {
13873
+ result: "Invalid filename. Pass the bare name of a session file, exactly as listed (session files are flat: no paths, no '..')."
13874
+ };
13875
+ }
13876
+ const ownerPrefix = sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix);
13877
+ let outcome;
13878
+ try {
13879
+ outcome = await resolvedDeps.promote({
13880
+ projectId: currentProjectId(turnProject, project.id) ?? project.id,
13881
+ s3prefix: uploads.s3prefix,
13882
+ keys: [`${ownerPrefix}${name}`],
13883
+ fullSessionPrefix: ownerPrefix,
13884
+ overwrite: overwrite === true,
13885
+ s3: resolvedDeps.s3
13886
+ });
13887
+ } catch (err3) {
13888
+ console.error("[PROJECT-FILES] save_to_project failed", err3);
13889
+ return { result: "Saving to the project failed. Try again; if it keeps failing, tell the user." };
13890
+ }
13891
+ if (outcome.promoted.length > 0) {
13892
+ return {
13893
+ result: `Saved "${name}" to project ${projectLabel2}. It will be visible to you as ${PROJECT_DIR}/${name} from the next turn.`
13894
+ };
13895
+ }
13896
+ if (outcome.clashes.length > 0) {
13897
+ let changed = "";
13898
+ try {
13899
+ const at = await resolvedDeps.projectModified(name);
13900
+ if (at) changed = ` (changed ${at.toISOString().slice(0, 10)})`;
13901
+ } catch {
13902
+ }
13903
+ return {
13904
+ result: `"${name}" already exists in the project${changed}. Call again with overwrite: true only if the user confirms.`
13905
+ };
13906
+ }
13907
+ const reason = outcome.rejected[0]?.reason ?? "Unknown reason.";
13908
+ if (reason.includes(`at most ${MAX_PROJECT_FILES} files`)) {
13909
+ return { result: `The project already holds ${MAX_PROJECT_FILES} files.` };
13910
+ }
13911
+ if (reason.includes("not found")) {
13912
+ return { result: `No session file named "${name}".` };
13913
+ }
13914
+ return { result: `Could not save "${name}" to the project: ${reason}` };
13915
+ };
13916
+ return ExuluTool.internal({
13917
+ id: "save_to_project",
13918
+ name: SAVE_TO_PROJECT_TOOL_NAME,
13919
+ needsApproval: true,
13920
+ // Replacing a shared file always needs a fresh yes, "allow for this chat" or not.
13921
+ alwaysAskWhen: (input) => input?.overwrite === true,
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.")
13926
+ }),
13927
+ type: "function",
13928
+ category: "session",
13929
+ config: [],
13930
+ execute
13931
+ });
13932
+ };
13933
+
13934
+ // src/templates/tools/skill-author-tools.ts
13935
+ import { randomUUID as randomUUID5 } from "crypto";
13936
+ import { z as z16 } from "zod";
13937
+
12348
13938
  // src/skills/skill-access.ts
12349
13939
  async function resolveSkillByName(db, name) {
12350
13940
  const row = await db("skills").where({ name }).first();
@@ -12493,8 +14083,8 @@ description: ${yamlString(description)}
12493
14083
 
12494
14084
  ${content.replace(/^\s+/, "")}`;
12495
14085
  };
12496
- var generalPrefix = (config) => config?.fileUploads?.s3prefix ? `${String(config.fileUploads.s3prefix).replace(/\/+$/, "")}/` : "";
12497
- var relativePaths = (keys, config, prefix) => keys.map((f) => f.key.replace(generalPrefix(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("/"));
12498
14088
  async function resolveSkill(db, ref) {
12499
14089
  const value = String(ref ?? "").trim();
12500
14090
  if (!value) return null;
@@ -12533,7 +14123,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12533
14123
  config: [],
12534
14124
  needsApproval: false,
12535
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.",
12536
- inputSchema: z14.object({ query: z14.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") }),
12537
14127
  execute: async (params) => {
12538
14128
  const { user } = params;
12539
14129
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -12559,9 +14149,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12559
14149
  config: [],
12560
14150
  needsApproval: false,
12561
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.",
12562
- inputSchema: z14.object({
12563
- skill: z14.string().describe("The skill's name or id"),
12564
- path: z14.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")
12565
14155
  }),
12566
14156
  execute: async (params) => {
12567
14157
  const { user, exuluConfig } = params;
@@ -12577,7 +14167,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12577
14167
  const path3 = params.path ? safeSkillPath(params.path) : "SKILL.md";
12578
14168
  if (!path3) return err2(`"${params.path}" is not a valid path inside the skill.`);
12579
14169
  if (!files.includes(path3)) return err2(`The skill has no file "${path3}". Files: ${files.join(", ") || "(none)"}`);
12580
- let content = await io.read(generalPrefix(exuluConfig) + prefix + path3, exuluConfig);
14170
+ let content = await io.read(generalPrefix3(exuluConfig) + prefix + path3, exuluConfig);
12581
14171
  if (Buffer.byteLength(content, "utf8") > MAX_READ_BYTES) content = content.slice(0, MAX_READ_BYTES) + "\n\u2026(truncated)";
12582
14172
  return {
12583
14173
  type: "skill_read",
@@ -12606,10 +14196,10 @@ ${content}`
12606
14196
  needsApproval: !config.skipApproval,
12607
14197
  needsApprovalFn: approvalFn,
12608
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.",
12609
- inputSchema: z14.object({
12610
- name: z14.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
12611
- description: z14.string().describe("One line: what the skill does and when to use it"),
12612
- files: z14.array(z14.object({ path: z14.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z14.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")
12613
14203
  }),
12614
14204
  execute: async (params) => {
12615
14205
  const { user, exuluConfig } = params;
@@ -12628,7 +14218,7 @@ ${content}`
12628
14218
  const db = await getDb();
12629
14219
  if (await resolveSkillByName(db, name)) return err2(`A skill named "${name}" already exists. Use skill_update to change it, or choose another name.`);
12630
14220
  const rights_mode = decision?.rights_mode ?? "private";
12631
- const skillId = randomUUID4();
14221
+ const skillId = randomUUID5();
12632
14222
  const stamp = now().toISOString();
12633
14223
  for (const f of files) {
12634
14224
  await io.upload(Buffer.from(f.content, "utf8"), `skills/${skillId}/v1/${f.path}`, exuluConfig, contentTypeFor(f.path));
@@ -12675,12 +14265,12 @@ ${content}`
12675
14265
  needsApproval: !config.skipApproval,
12676
14266
  needsApprovalFn: approvalFn,
12677
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.",
12678
- inputSchema: z14.object({
12679
- skill: z14.string().describe("The skill's name or id"),
12680
- files: z14.array(z14.object({ path: z14.string(), content: z14.string() })).optional().describe("Files to add or replace, full content each"),
12681
- deletePaths: z14.array(z14.string()).optional().describe("Paths to remove in the new version"),
12682
- description: z14.string().optional().describe("A new one-line description, if it changed"),
12683
- label: z14.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'")
12684
14274
  }),
12685
14275
  execute: async (params) => {
12686
14276
  const { user, exuluConfig } = params;
@@ -12712,7 +14302,7 @@ ${content}`
12712
14302
  const newVersion = currentVersion + 1;
12713
14303
  const currentPrefix = `skills/${skill.id}/v${currentVersion}/`;
12714
14304
  const newPrefix = `skills/${skill.id}/v${newVersion}/`;
12715
- const gp = generalPrefix(exuluConfig);
14305
+ const gp = generalPrefix3(exuluConfig);
12716
14306
  const existing = await io.list(currentPrefix, exuluConfig);
12717
14307
  const changedPaths = new Set(changes.map((f) => f.path));
12718
14308
  const removedSet = new Set(removals);
@@ -12757,7 +14347,7 @@ var createSkillAuthorPickerTool = () => new ExuluTool({
12757
14347
  category: "default",
12758
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.",
12759
14349
  type: "function",
12760
- inputSchema: z14.object({}),
14350
+ inputSchema: z16.object({}),
12761
14351
  config: [
12762
14352
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
12763
14353
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -12774,38 +14364,11 @@ var collectSkillAuthorTools = (agent, deps = {}) => {
12774
14364
  import {
12775
14365
  SandboxManager
12776
14366
  } from "@anthropic-ai/sandbox-runtime";
12777
- import { mkdir, rm, writeFile, readFile as fsReadFile, readdir, stat } from "fs/promises";
14367
+ import { mkdir as mkdir3, rm as rm2, readdir as readdir2, stat, lstat as lstat3 } from "fs/promises";
12778
14368
  import { existsSync as existsSync4 } from "fs";
12779
- import { join as join2, dirname, resolve as resolve2, relative, posix } from "path";
14369
+ import { join as join4, dirname as dirname3, resolve as resolve3, relative, posix } from "path";
12780
14370
  import { exec as exec2, spawn } from "child_process";
12781
- import { promisify as promisify2 } from "util";
12782
-
12783
- // ee/invoke-skills/artifact-filter.ts
12784
- var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
12785
- "venv",
12786
- ".venv",
12787
- "env",
12788
- "node_modules",
12789
- "__pycache__",
12790
- "site-packages",
12791
- "dist-packages",
12792
- ".cache",
12793
- ".git",
12794
- ".pytest_cache",
12795
- ".mypy_cache",
12796
- ".ipynb_checkpoints"
12797
- ]);
12798
- function isIgnoredArtifactPath(relativePath) {
12799
- return relativePath.split(/[\\/]+/).some((segment) => IGNORED_SEGMENTS.has(segment));
12800
- }
12801
- var DEFAULT_ARTIFACT_CAP = 50;
12802
- function capArtifacts(artifacts, max = DEFAULT_ARTIFACT_CAP) {
12803
- if (artifacts.length <= max) return { kept: artifacts, omitted: 0 };
12804
- return { kept: artifacts.slice(0, max), omitted: artifacts.length - max };
12805
- }
12806
- function needsDownload(localSize, remoteSize) {
12807
- return localSize === void 0 || localSize !== remoteSize;
12808
- }
14371
+ import { promisify as promisify3 } from "util";
12809
14372
 
12810
14373
  // src/exulu/system-dependencies.ts
12811
14374
  import { exec } from "child_process";
@@ -13346,7 +14909,7 @@ ${JSON.stringify(config, null, 2)}`
13346
14909
  };
13347
14910
 
13348
14911
  // src/exulu/audit/sink.ts
13349
- import { randomUUID as randomUUID5 } from "crypto";
14912
+ import { randomUUID as randomUUID6 } from "crypto";
13350
14913
  import { promises as fs } from "fs";
13351
14914
  import path2 from "path";
13352
14915
  var createFsSpoolStore = (dir) => ({
@@ -13380,7 +14943,7 @@ var AuditSink = class {
13380
14943
  objectKey() {
13381
14944
  const d = this.now();
13382
14945
  const dt = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
13383
- 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`;
13384
14947
  }
13385
14948
  serialize(events) {
13386
14949
  return events.map((e) => JSON.stringify(e)).join("\n") + "\n";
@@ -13407,7 +14970,7 @@ var AuditSink = class {
13407
14970
  await this.writer.putNdjson(this.objectKey(), body);
13408
14971
  await this.drainSpool();
13409
14972
  } catch (error) {
13410
- const name = `${Date.now()}-${randomUUID5()}.ndjson`;
14973
+ const name = `${Date.now()}-${randomUUID6()}.ndjson`;
13411
14974
  try {
13412
14975
  await this.spool.write(name, body);
13413
14976
  console.warn(`[EXULU] audit: S3 write failed, spooled ${batch.length} record(s) to disk (${name}).`, error);
@@ -13726,8 +15289,348 @@ var buildSkillSandboxEvent = (ctx, opts = {}) => {
13726
15289
  // ee/invoke-skills/create-sandbox.ts
13727
15290
  import { createBashTool } from "bash-tool";
13728
15291
  import { tool as tool2 } from "ai";
13729
- import { z as z15 } from "zod";
15292
+ import { z as z17 } from "zod";
13730
15293
  import CryptoJS3 from "crypto-js";
15294
+
15295
+ // ee/invoke-skills/project-sync.ts
15296
+ import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "fs/promises";
15297
+ import { randomBytes as randomBytes2 } from "crypto";
15298
+ import { basename, dirname, join as join2, resolve as resolve2, sep } from "path";
15299
+ import { execFile } from "child_process";
15300
+ import { promisify as promisify2 } from "util";
15301
+ function planProjectSync(remote, local) {
15302
+ const localSizes = new Map(local.map((e) => [e.name, e.size]));
15303
+ const remoteNames = new Set(remote.map((e) => e.name));
15304
+ return {
15305
+ download: remote.filter((e) => localSizes.get(e.name) !== e.size).map((e) => e.name),
15306
+ remove: local.filter((e) => !remoteNames.has(e.name)).map((e) => e.name)
15307
+ };
15308
+ }
15309
+ function projectSyncMarkerPath(sessionDir) {
15310
+ return join2(dirname(sessionDir), ".project-sync", basename(sessionDir));
15311
+ }
15312
+ async function readMarker(sessionDir) {
15313
+ try {
15314
+ return (await readFile(projectSyncMarkerPath(sessionDir), "utf8")).trim() || null;
15315
+ } catch {
15316
+ return null;
15317
+ }
15318
+ }
15319
+ async function clearProjectSyncMarker(sessionDir) {
15320
+ await rm(projectSyncMarkerPath(sessionDir), { force: true });
15321
+ }
15322
+ var isFlatName = (name) => !!name && !name.includes("/") && !name.includes("\\") && name !== "." && name !== "..";
15323
+ var HELPER_KINDS = [".project-staging", ".project-trash"];
15324
+ var helperRoot = (sessionDir, kind) => join2(dirname(sessionDir), kind);
15325
+ var helperPath = (sessionDir, kind) => join2(helperRoot(sessionDir, kind), `${basename(sessionDir)}-${randomBytes2(8).toString("hex")}`);
15326
+ var execFileAsync = promisify2(execFile);
15327
+ async function removeTreeSafely(path3, sessionDir) {
15328
+ const target = resolve2(path3);
15329
+ const inside = HELPER_KINDS.some((kind) => {
15330
+ const root = resolve2(helperRoot(sessionDir, kind));
15331
+ return target.startsWith(root + sep) && !target.slice(root.length + 1).includes(sep);
15332
+ });
15333
+ if (!inside) {
15334
+ console.error(`[SKILLS] Refusing to remove ${path3}: not a project staging or trash directory.`);
15335
+ return false;
15336
+ }
15337
+ try {
15338
+ await execFileAsync("rm", ["-rf", "--", target]);
15339
+ return true;
15340
+ } catch (err3) {
15341
+ console.error(`[SKILLS] Failed to remove ${target}; leaving it for a later sweep.`, err3);
15342
+ return false;
15343
+ }
15344
+ }
15345
+ var DAY_MS = 24 * 60 * 60 * 1e3;
15346
+ async function sweepStaleHelpers(sessionDir) {
15347
+ const prefix = `${basename(sessionDir)}-`;
15348
+ for (const kind of HELPER_KINDS) {
15349
+ const root = helperRoot(sessionDir, kind);
15350
+ let names;
15351
+ try {
15352
+ names = await readdir(root);
15353
+ } catch {
15354
+ continue;
15355
+ }
15356
+ for (const name of names) {
15357
+ if (!name.startsWith(prefix)) continue;
15358
+ const st = await lstat(join2(root, name)).catch(() => null);
15359
+ if (st && Date.now() - st.mtimeMs > DAY_MS) await removeTreeSafely(join2(root, name), sessionDir);
15360
+ }
15361
+ }
15362
+ }
15363
+ var errCode = (err3) => err3?.code;
15364
+ async function moveAway(dir, sessionDir) {
15365
+ const trash = helperPath(sessionDir, ".project-trash");
15366
+ await mkdir(dirname(trash), { recursive: true });
15367
+ try {
15368
+ await rename(dir, trash);
15369
+ return trash;
15370
+ } catch (err3) {
15371
+ if (errCode(err3) === "ENOENT") return null;
15372
+ throw err3;
15373
+ }
15374
+ }
15375
+ async function discard(path3, sessionDir) {
15376
+ if (path3) await removeTreeSafely(path3, sessionDir);
15377
+ }
15378
+ async function discardEntry(path3, sessionDir) {
15379
+ await discard(await moveAway(path3, sessionDir), sessionDir);
15380
+ }
15381
+ async function syncProjectDir(args) {
15382
+ const { sessionDir, projectId, config } = args;
15383
+ const dir = join2(sessionDir, PROJECT_DIR);
15384
+ const previous = await readMarker(sessionDir);
15385
+ if (!projectId) {
15386
+ if (previous !== null) {
15387
+ await discard(await moveAway(dir, sessionDir), sessionDir);
15388
+ await clearProjectSyncMarker(sessionDir);
15389
+ }
15390
+ return;
15391
+ }
15392
+ if (!config.fileUploads) {
15393
+ console.warn(`[SKILLS] File uploads are not configured; project files are not synced into ${sessionDir}.`);
15394
+ return;
15395
+ }
15396
+ const { projectPrefix } = projectFilePrefix(projectId);
15397
+ const remote = /* @__PURE__ */ new Map();
15398
+ try {
15399
+ for (const obj of await listS3ObjectsByPrefix(projectPrefix, config)) {
15400
+ const idx = obj.key.indexOf(projectPrefix);
15401
+ const name = idx >= 0 ? obj.key.slice(idx + projectPrefix.length) : "";
15402
+ if (!isFlatName(name)) continue;
15403
+ remote.set(name, { size: obj.size, key: obj.key });
15404
+ }
15405
+ } catch (err3) {
15406
+ console.error(`[SKILLS] Failed to list project files for project ${projectId}; keeping the local copy.`, err3);
15407
+ return;
15408
+ }
15409
+ await sweepStaleHelpers(sessionDir);
15410
+ await mkdir(dirname(projectSyncMarkerPath(sessionDir)), { recursive: true });
15411
+ await writeFile(projectSyncMarkerPath(sessionDir), projectId);
15412
+ const trashes = [];
15413
+ const staging = helperPath(sessionDir, ".project-staging");
15414
+ let installed = false;
15415
+ try {
15416
+ const old = await moveAway(dir, sessionDir);
15417
+ trashes.push(old);
15418
+ await mkdir(dirname(staging), { recursive: true });
15419
+ await mkdir(staging);
15420
+ const local = [];
15421
+ const oldStat = old && previous === projectId ? await lstat(old).catch(() => null) : null;
15422
+ if (old && oldStat?.isDirectory()) {
15423
+ for (const name of await readdir(old)) {
15424
+ const st = await lstat(join2(old, name)).catch(() => null);
15425
+ if (!st?.isFile() || remote.get(name)?.size !== st.size) continue;
15426
+ await rename(join2(old, name), join2(staging, name));
15427
+ const moved = await lstat(join2(staging, name)).catch(() => null);
15428
+ if (!moved?.isFile()) {
15429
+ await rename(join2(staging, name), join2(old, `.rejected-${randomBytes2(4).toString("hex")}`)).catch(() => {
15430
+ });
15431
+ continue;
15432
+ }
15433
+ local.push({ name, size: moved.size });
15434
+ }
15435
+ }
15436
+ const plan = planProjectSync(
15437
+ [...remote].map(([name, r]) => ({ name, size: r.size })),
15438
+ local
15439
+ );
15440
+ for (const name of plan.download) {
15441
+ try {
15442
+ const bytes = await getS3ObjectBytes(remote.get(name).key, config);
15443
+ await writeFile(join2(staging, name), bytes, { flag: "wx" });
15444
+ } catch (err3) {
15445
+ console.error(`[SKILLS] Failed to sync project file ${name} (project ${projectId}); continuing.`, err3);
15446
+ }
15447
+ }
15448
+ for (let attempt = 0; attempt < 2 && !installed; attempt++) {
15449
+ try {
15450
+ await rename(staging, dir);
15451
+ installed = true;
15452
+ } catch (err3) {
15453
+ const code = errCode(err3);
15454
+ if (attempt === 0 && (code === "EEXIST" || code === "ENOTEMPTY" || code === "ENOTDIR" || code === "EISDIR")) {
15455
+ trashes.push(await moveAway(dir, sessionDir));
15456
+ continue;
15457
+ }
15458
+ console.error(`[SKILLS] Could not install the project folder for session ${sessionDir}; skipping this turn.`, err3);
15459
+ break;
15460
+ }
15461
+ }
15462
+ } catch (err3) {
15463
+ console.error(`[SKILLS] Project sync failed for project ${projectId}; continuing.`, err3);
15464
+ } finally {
15465
+ if (!installed) await discard(staging, sessionDir);
15466
+ for (const t of trashes) await discard(t, sessionDir);
15467
+ }
15468
+ }
15469
+ async function resolveSandboxProjectId(args, deps) {
15470
+ const { projectId, ownerId } = args;
15471
+ if (!projectId || ownerId == null) return null;
15472
+ try {
15473
+ const project = await deps.getProject(projectId);
15474
+ if (!project) return null;
15475
+ const owner = args.owner && String(args.owner.id) === String(ownerId) ? args.owner : await deps.getUser(ownerId);
15476
+ if (!owner) return null;
15477
+ const rbac = await deps.getRbac(project);
15478
+ const allowed = hasProjectAccess({ project, rbac, user: owner, want: "read" });
15479
+ return allowed ? String(project.id) : null;
15480
+ } catch (err3) {
15481
+ console.error(`[SKILLS] Failed to resolve project ${projectId} for the session sandbox; continuing without project files.`, err3);
15482
+ return null;
15483
+ }
15484
+ }
15485
+
15486
+ // ee/invoke-skills/safe-fs.ts
15487
+ import { constants } from "fs";
15488
+ import { lstat as lstat2, mkdir as mkdir2, open, readlink, realpath, rename as rename2, unlink, writeFile as writeFile2 } from "fs/promises";
15489
+ import { randomBytes as randomBytes3 } from "crypto";
15490
+ import { dirname as dirname2, isAbsolute, join as join3, sep as sep2 } from "path";
15491
+ var UnsafeSessionPathError = class extends Error {
15492
+ constructor(message) {
15493
+ super(message);
15494
+ this.name = "UnsafeSessionPathError";
15495
+ }
15496
+ };
15497
+ var errCode2 = (err3) => err3?.code;
15498
+ var isInside = (root, path3) => path3 === root || path3.startsWith(root + sep2);
15499
+ async function readRegularFileInside(sessionDir, path3) {
15500
+ const skip = (why) => {
15501
+ console.warn(`[SKILLS] Not reading ${path3} back from the sandbox: ${why}.`);
15502
+ return null;
15503
+ };
15504
+ let root;
15505
+ let parent;
15506
+ try {
15507
+ root = await realpath(sessionDir);
15508
+ parent = await realpath(dirname2(path3));
15509
+ } catch {
15510
+ return skip("path does not resolve");
15511
+ }
15512
+ if (!isInside(root, parent)) return skip("it resolves outside the session directory");
15513
+ let handle;
15514
+ try {
15515
+ handle = await open(
15516
+ path3,
15517
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | constants.O_NOCTTY
15518
+ );
15519
+ } catch (err3) {
15520
+ return skip(errCode2(err3) === "ELOOP" ? "it is a symbolic link" : `open failed (${errCode2(err3) ?? "unknown"})`);
15521
+ }
15522
+ try {
15523
+ const st = await handle.stat();
15524
+ if (!st.isFile()) return skip("it is not a regular file");
15525
+ if (st.size > MAX_ADOPT_UPLOAD_BYTES) {
15526
+ return skip(`it is larger than the ${MAX_ADOPT_UPLOAD_BYTES / (1024 * 1024)}MB upload limit (${st.size} bytes)`);
15527
+ }
15528
+ const fdPath = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => null);
15529
+ if (fdPath !== null) {
15530
+ if (!isInside(root, fdPath)) return skip("it resolves outside the session directory");
15531
+ } else {
15532
+ const again = await realpath(dirname2(path3)).catch(() => null);
15533
+ if (again === null || !isInside(root, again)) return skip("it resolves outside the session directory");
15534
+ }
15535
+ const chunks = [];
15536
+ let total = 0;
15537
+ const chunkSize = Math.min(Math.max(st.size + 1, 64 * 1024), 1024 * 1024);
15538
+ for (; ; ) {
15539
+ const chunk = Buffer.allocUnsafe(chunkSize);
15540
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
15541
+ if (bytesRead === 0) break;
15542
+ total += bytesRead;
15543
+ if (total > MAX_ADOPT_UPLOAD_BYTES) return skip("it grew past the upload limit while being read");
15544
+ chunks.push(chunk.subarray(0, bytesRead));
15545
+ }
15546
+ return Buffer.concat(chunks, total);
15547
+ } finally {
15548
+ await handle.close().catch(() => {
15549
+ });
15550
+ }
15551
+ }
15552
+ function safeSegments(relativePath) {
15553
+ if (!relativePath || isAbsolute(relativePath) || relativePath.includes("\\")) {
15554
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": not a plain relative path.`);
15555
+ }
15556
+ const segments = relativePath.split("/").filter((s) => s !== "" && s !== ".");
15557
+ if (segments.length === 0 || segments.includes("..")) {
15558
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": it contains a ".." segment or no file name.`);
15559
+ }
15560
+ return segments;
15561
+ }
15562
+ async function ensureDirInside(sessionDir, segments) {
15563
+ const root = await realpath(sessionDir);
15564
+ let current = sessionDir;
15565
+ for (const segment of segments) {
15566
+ current = join3(current, segment);
15567
+ let st = await lstat2(current).catch((err3) => errCode2(err3) === "ENOENT" ? null : Promise.reject(err3));
15568
+ if (!st) {
15569
+ try {
15570
+ await mkdir2(current);
15571
+ } catch (err3) {
15572
+ if (errCode2(err3) !== "EEXIST") throw err3;
15573
+ }
15574
+ st = await lstat2(current);
15575
+ }
15576
+ if (!st.isDirectory()) {
15577
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it is not a real directory.`);
15578
+ }
15579
+ }
15580
+ const real = await realpath(current);
15581
+ if (!isInside(root, real)) {
15582
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it resolves outside the session directory.`);
15583
+ }
15584
+ return current;
15585
+ }
15586
+ async function writeFileInside(sessionDir, relativePath, bytes) {
15587
+ const segments = safeSegments(relativePath);
15588
+ const name = segments[segments.length - 1];
15589
+ const parent = await ensureDirInside(sessionDir, segments.slice(0, -1));
15590
+ const destination = join3(parent, name);
15591
+ const temp = join3(parent, `.exulu-write-${randomBytes3(8).toString("hex")}`);
15592
+ await writeFile2(temp, bytes, { flag: "wx" });
15593
+ try {
15594
+ await rename2(temp, destination);
15595
+ } catch (err3) {
15596
+ await unlink(temp).catch(() => {
15597
+ });
15598
+ throw err3;
15599
+ }
15600
+ return destination;
15601
+ }
15602
+ async function ensureRealDirectory(sessionDir, relativeDir) {
15603
+ const segments = safeSegments(relativeDir);
15604
+ let current = sessionDir;
15605
+ for (const segment of segments) {
15606
+ current = join3(current, segment);
15607
+ const st = await lstat2(current).catch(() => null);
15608
+ if (st && !st.isDirectory()) {
15609
+ console.warn(`[SKILLS] ${current} is not a real directory; replacing it.`);
15610
+ await unlink(current);
15611
+ }
15612
+ }
15613
+ return ensureDirInside(sessionDir, segments);
15614
+ }
15615
+ async function removeEntryInside(sessionDir, relativePath) {
15616
+ const segments = safeSegments(relativePath);
15617
+ const target = join3(sessionDir, ...segments);
15618
+ const root = await realpath(sessionDir);
15619
+ const parentReal = await realpath(dirname2(target)).catch(() => null);
15620
+ if (parentReal === null) return;
15621
+ if (!isInside(root, parentReal)) {
15622
+ throw new UnsafeSessionPathError(`Refusing to remove ${target}: its parent resolves outside the session directory.`);
15623
+ }
15624
+ const st = await lstat2(target).catch(() => null);
15625
+ if (!st) return;
15626
+ if (!st.isDirectory()) {
15627
+ await unlink(target);
15628
+ return;
15629
+ }
15630
+ await discardEntry(target, sessionDir);
15631
+ }
15632
+
15633
+ // ee/invoke-skills/create-sandbox.ts
13731
15634
  var getAllExuluVariables = async () => {
13732
15635
  const { db } = await postgresClient();
13733
15636
  const rows = await db.from("variables").select("*");
@@ -13751,14 +15654,14 @@ var getAllExuluVariables = async () => {
13751
15654
  const granted = selectGrantedVariables(decrypted);
13752
15655
  return { granted, withheldNames: deriveWithheldNames(rows, granted) };
13753
15656
  };
13754
- var execAsync2 = promisify2(exec2);
15657
+ var execAsync2 = promisify3(exec2);
13755
15658
  var backendSecretFiles = () => {
13756
15659
  const cwd = process.cwd();
13757
15660
  const names = [".env", ".env.local", ".env.production", ".env.production.local"];
13758
15661
  const paths = /* @__PURE__ */ new Set();
13759
15662
  for (const name of names) {
13760
- paths.add(join2(cwd, name));
13761
- paths.add(join2("/app", name));
15663
+ paths.add(join4(cwd, name));
15664
+ paths.add(join4("/app", name));
13762
15665
  }
13763
15666
  return [...paths];
13764
15667
  };
@@ -13783,18 +15686,18 @@ function probeSandboxSupport() {
13783
15686
  if (process.platform !== "linux") {
13784
15687
  return { canSandbox: false, reason: `Unsupported platform: ${process.platform}` };
13785
15688
  }
13786
- return await new Promise((resolve3) => {
15689
+ return await new Promise((resolve4) => {
13787
15690
  const child = spawn("bwrap", ["--dev-bind", "/", "/", "--", "/bin/true"], { env: {} });
13788
15691
  let stderr = "";
13789
15692
  child.stderr.on("data", (chunk) => {
13790
15693
  stderr += chunk.toString();
13791
15694
  });
13792
15695
  child.on("error", (err3) => {
13793
- resolve3({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
15696
+ resolve4({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
13794
15697
  });
13795
15698
  child.on("exit", (code) => {
13796
- if (code === 0) resolve3({ canSandbox: true });
13797
- else resolve3({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
15699
+ if (code === 0) resolve4({ canSandbox: true });
15700
+ else resolve4({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
13798
15701
  });
13799
15702
  });
13800
15703
  })();
@@ -13829,23 +15732,46 @@ async function downloadSkill(skill, skillsDirectory, config) {
13829
15732
  `[SKILLS] No files found for skill "${skill.name}" at prefix "${versionPrefix}". Check that current_version matches what was uploaded to S3.`
13830
15733
  );
13831
15734
  }
15735
+ const sessionDir = dirname3(skillsDirectory);
15736
+ await ensureRealDirectory(sessionDir, `skills/${skill.name}`);
13832
15737
  for (const file of files) {
13833
15738
  const prefixIndex = file.key.indexOf(versionPrefix);
13834
15739
  const relativePath = prefixIndex >= 0 ? file.key.slice(prefixIndex + versionPrefix.length) : file.key;
13835
15740
  if (!relativePath) continue;
13836
- const localPath = join2(skillsDirectory, skill.name, relativePath);
13837
- await mkdir(dirname(localPath), { recursive: true });
13838
15741
  const bytes = await getS3ObjectBytes(file.key, config);
13839
- await writeFile(localPath, bytes);
15742
+ try {
15743
+ await writeFileInside(sessionDir, `skills/${skill.name}/${relativePath}`, bytes);
15744
+ } catch (err3) {
15745
+ if (!(err3 instanceof UnsafeSessionPathError)) throw err3;
15746
+ console.error(`[SKILLS] Skipping skill file ${file.key}: ${err3.message}`);
15747
+ }
13840
15748
  }
13841
15749
  }
13842
- function isArtifactPath(absPath, sessionDir) {
13843
- const resolved = resolve2(absPath);
15750
+ async function removeInstalledSkill(skillsDirectory, skillName) {
15751
+ const sessionDir = dirname3(skillsDirectory);
15752
+ await ensureRealDirectory(sessionDir, "skills");
15753
+ await removeEntryInside(sessionDir, `skills/${skillName}`);
15754
+ }
15755
+ function isArtifactPath(absPath, sessionDir, opts = {}) {
15756
+ const resolved = resolve3(absPath);
13844
15757
  const rel = relative(sessionDir, resolved);
13845
15758
  if (!rel || rel.startsWith("..")) return false;
13846
15759
  const first = rel.split("/")[0];
15760
+ if (opts.hasProject && first === PROJECT_DIR) return false;
13847
15761
  return first !== "skills";
13848
15762
  }
15763
+ async function uploadAgentArtifact(content, s3Key, config, userId) {
15764
+ return uploadFile(
15765
+ content,
15766
+ s3Key,
15767
+ config,
15768
+ { metadata: { [ORIGIN_METADATA_KEY]: "agent" } },
15769
+ // uploadFile's user param is typed as number, but the
15770
+ // addUserPrefixToKey helper it delegates to accepts
15771
+ // number | string at runtime — pass through as-is.
15772
+ userId
15773
+ );
15774
+ }
13849
15775
  function artifactS3Key(sessionId, relPath) {
13850
15776
  return `sessions/${sessionId}/${relPath}`;
13851
15777
  }
@@ -13884,11 +15810,13 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13884
15810
  const relativePath = idx >= 0 ? obj.key.slice(idx + userPrefix.length) : "";
13885
15811
  if (!relativePath) continue;
13886
15812
  if (isIgnoredArtifactPath(relativePath)) continue;
13887
- const localPath = join2(sessionDir, relativePath);
15813
+ if (opts.skipProjectDir && relativePath.split("/")[0] === PROJECT_DIR) continue;
15814
+ const localPath = join4(sessionDir, relativePath);
13888
15815
  if (opts.onlyMissing) {
13889
15816
  let localSize;
13890
15817
  try {
13891
- localSize = (await stat(localPath)).size;
15818
+ const st = await lstat3(localPath);
15819
+ localSize = st.isFile() ? st.size : void 0;
13892
15820
  } catch {
13893
15821
  localSize = void 0;
13894
15822
  }
@@ -13896,8 +15824,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13896
15824
  }
13897
15825
  try {
13898
15826
  const bytes = await getS3ObjectBytes(obj.key, config);
13899
- await mkdir(dirname(localPath), { recursive: true });
13900
- await writeFile(localPath, bytes);
15827
+ await writeFileInside(sessionDir, relativePath, bytes);
13901
15828
  } catch (err3) {
13902
15829
  console.error(
13903
15830
  `[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
@@ -13908,7 +15835,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13908
15835
  }
13909
15836
  async function downloadKeyIntoSandbox(opts) {
13910
15837
  const { sessionId, userId, fullS3Key, config } = opts;
13911
- const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
15838
+ const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
13912
15839
  if (!existsSync4(sessionDir)) {
13913
15840
  return { written: false };
13914
15841
  }
@@ -13921,10 +15848,8 @@ async function downloadKeyIntoSandbox(opts) {
13921
15848
  }
13922
15849
  const relativePath = fullS3Key.slice(idx + userPrefix.length);
13923
15850
  if (!relativePath) return { written: false };
13924
- const localPath = join2(sessionDir, relativePath);
13925
15851
  const bytes = await getS3ObjectBytes(fullS3Key, config);
13926
- await mkdir(dirname(localPath), { recursive: true });
13927
- await writeFile(localPath, bytes);
15852
+ const localPath = await writeFileInside(sessionDir, relativePath, bytes);
13928
15853
  return { written: true, localPath };
13929
15854
  }
13930
15855
  async function resolvePythonVenvPath() {
@@ -13939,42 +15864,55 @@ async function resolvePythonVenvPath() {
13939
15864
  async function refreshSessionSkills(sessionId, skills, config) {
13940
15865
  const cached = sandboxCache.get(sessionId);
13941
15866
  if (!cached) return { refreshed: 0, sandbox: false };
13942
- const skillsDirectory = join2(cached.handle.sessionDir, "skills");
15867
+ const skillsDirectory = join4(cached.handle.sessionDir, "skills");
13943
15868
  let refreshed = 0;
13944
15869
  for (const skill of skills) {
13945
- await rm(join2(skillsDirectory, skill.name), { recursive: true, force: true });
15870
+ await removeInstalledSkill(skillsDirectory, skill.name);
13946
15871
  await downloadSkill(skill, skillsDirectory, config);
13947
15872
  cached.installedSkills.set(skill.id, skill.current_version);
13948
15873
  refreshed++;
13949
15874
  }
13950
15875
  return { refreshed, sandbox: true };
13951
15876
  }
13952
- async function createSessionSandbox(sessionId, skills, config, userId, agent) {
15877
+ async function createSessionSandbox(sessionId, skills, config, userId, agent, opts = {}) {
13953
15878
  const cached = sandboxCache.get(sessionId);
15879
+ const projectId = opts.projectId ?? null;
15880
+ const syncProject = async (dir) => {
15881
+ try {
15882
+ await syncProjectDir({ sessionDir: dir, projectId, config });
15883
+ } catch (err3) {
15884
+ console.error(`[SKILLS] Failed to sync project files into session ${sessionId}; continuing.`, err3);
15885
+ }
15886
+ };
13954
15887
  if (cached) {
13955
- const skillsDirectory2 = join2(cached.handle.sessionDir, "skills");
15888
+ cached.projectState.projectId = projectId;
15889
+ const skillsDirectory2 = join4(cached.handle.sessionDir, "skills");
13956
15890
  for (const skill of skills) {
13957
15891
  const installedVersion = cached.installedSkills.get(skill.id);
13958
15892
  if (installedVersion === skill.current_version) continue;
13959
15893
  if (installedVersion !== void 0) {
13960
- await rm(join2(skillsDirectory2, skill.name), { recursive: true, force: true });
15894
+ await removeInstalledSkill(skillsDirectory2, skill.name);
13961
15895
  }
13962
15896
  await downloadSkill(skill, skillsDirectory2, config);
13963
15897
  cached.installedSkills.set(skill.id, skill.current_version);
13964
15898
  }
13965
15899
  if (userId && config.fileUploads) {
13966
15900
  try {
13967
- await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, { onlyMissing: true });
15901
+ await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, {
15902
+ onlyMissing: true,
15903
+ skipProjectDir: projectId !== null
15904
+ });
13968
15905
  } catch (err3) {
13969
15906
  console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err3);
13970
15907
  }
13971
15908
  }
15909
+ await syncProject(cached.handle.sessionDir);
13972
15910
  return cached.handle;
13973
15911
  }
13974
- const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
15912
+ const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
13975
15913
  const dirExisted = existsSync4(sessionDir);
13976
- await mkdir(sessionDir, { recursive: true });
13977
- const skillsDirectory = join2(sessionDir, "skills");
15914
+ await mkdir3(sessionDir, { recursive: true });
15915
+ const skillsDirectory = join4(sessionDir, "skills");
13978
15916
  const installedSkills = /* @__PURE__ */ new Map();
13979
15917
  for (const skill of skills) {
13980
15918
  await downloadSkill(skill, skillsDirectory, config);
@@ -13987,8 +15925,13 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent) {
13987
15925
  );
13988
15926
  }
13989
15927
  if (userId && config.fileUploads) {
13990
- await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, { onlyMissing: dirExisted });
15928
+ await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, {
15929
+ onlyMissing: dirExisted,
15930
+ skipProjectDir: projectId !== null
15931
+ });
13991
15932
  }
15933
+ await syncProject(sessionDir);
15934
+ const projectState = { projectId };
13992
15935
  const probe = await probeSandboxSupport();
13993
15936
  const useDirectExec = !probe.canSandbox;
13994
15937
  if (useDirectExec) {
@@ -14067,7 +16010,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14067
16010
  extraSecretNames: litellmConfigSecretNames(),
14068
16011
  overrides: {
14069
16012
  ...npmGlobalRoot ? { NODE_PATH: npmGlobalRoot } : {},
14070
- ...pythonVenvPath ? { PATH: `${join2(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
16013
+ ...pythonVenvPath ? { PATH: `${join4(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
14071
16014
  }
14072
16015
  });
14073
16016
  if (skippedNames.length) {
@@ -14142,24 +16085,16 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14142
16085
  await writeFilesInternal(files);
14143
16086
  }
14144
16087
  };
14145
- async function persistArtifactToS3(absPath, content) {
14146
- if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir)) {
16088
+ const hasProjectNow = () => projectState.projectId !== null;
16089
+ async function persistArtifactToS3(absPath, content, hasProject) {
16090
+ if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir, { hasProject })) {
14147
16091
  return {};
14148
16092
  }
14149
- const rel = relative(sessionDir, resolve2(absPath));
16093
+ const rel = relative(sessionDir, resolve3(absPath));
14150
16094
  const s3Key = artifactS3Key(sessionId, rel);
14151
16095
  const out = {};
14152
16096
  try {
14153
- const fullKey = await uploadFile(
14154
- content,
14155
- s3Key,
14156
- config,
14157
- {},
14158
- // uploadFile's user param is typed as number, but the
14159
- // addUserPrefixToKey helper it delegates to accepts
14160
- // number | string at runtime — pass through as-is.
14161
- userId
14162
- );
16097
+ const fullKey = await uploadAgentArtifact(content, s3Key, config, userId);
14163
16098
  out.key = fullKey;
14164
16099
  const slashIdx = fullKey.indexOf("/");
14165
16100
  if (slashIdx > 0) {
@@ -14182,11 +16117,11 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14182
16117
  }
14183
16118
  return out;
14184
16119
  }
14185
- async function writeFilesInternal(files) {
16120
+ async function writeFilesInternal(files, hasProject = hasProjectNow()) {
14186
16121
  const results = [];
14187
16122
  for (const file of files) {
14188
16123
  const wrapped = await wrapIfNeeded(
14189
- `mkdir -p ${shellQuote(dirname(file.path))} && cat > ${shellQuote(file.path)}`
16124
+ `mkdir -p ${shellQuote(dirname3(file.path))} && cat > ${shellQuote(file.path)}`
14190
16125
  );
14191
16126
  await new Promise((resolveSpawn, rejectSpawn) => {
14192
16127
  const child = spawn("/bin/bash", ["-c", wrapped], { env: sandboxedExecEnv });
@@ -14205,7 +16140,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14205
16140
  const result = { path: file.path };
14206
16141
  const persisted = await persistArtifactToS3(
14207
16142
  file.path,
14208
- Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content)
16143
+ Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content),
16144
+ hasProject || hasProjectNow()
14209
16145
  );
14210
16146
  if (persisted.key) result.key = persisted.key;
14211
16147
  if (persisted.url) result.url = persisted.url;
@@ -14213,19 +16149,21 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14213
16149
  }
14214
16150
  return results;
14215
16151
  }
14216
- async function snapshotSessionArtifacts() {
16152
+ async function snapshotSessionArtifacts(hasProject) {
14217
16153
  const map = /* @__PURE__ */ new Map();
14218
- const skillsDir = join2(sessionDir, "skills");
16154
+ const skillsDir = join4(sessionDir, "skills");
16155
+ const projectDir = hasProject ? join4(sessionDir, PROJECT_DIR) : null;
14219
16156
  const walk = async (dir) => {
14220
16157
  let entries;
14221
16158
  try {
14222
- entries = await readdir(dir, { withFileTypes: true });
16159
+ entries = await readdir2(dir, { withFileTypes: true });
14223
16160
  } catch {
14224
16161
  return;
14225
16162
  }
14226
16163
  for (const entry of entries) {
14227
- const full = join2(dir, entry.name);
16164
+ const full = join4(dir, entry.name);
14228
16165
  if (full === skillsDir) continue;
16166
+ if (projectDir !== null && full === projectDir) continue;
14229
16167
  if (isIgnoredArtifactPath(relative(sessionDir, full))) continue;
14230
16168
  if (entry.isDirectory()) {
14231
16169
  await walk(full);
@@ -14250,13 +16188,14 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14250
16188
  });
14251
16189
  const writeFileTool = tool2({
14252
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.',
14253
- inputSchema: z15.object({
14254
- path: z15.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
14255
- content: z15.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")
14256
16194
  }),
14257
16195
  execute: async ({ path: path3, content }) => {
16196
+ const hasProject = hasProjectNow();
14258
16197
  const resolvedPath = resolveSessionPath(path3, sessionDir);
14259
- const results = await writeFilesInternal([{ path: resolvedPath, content }]);
16198
+ const results = await writeFilesInternal([{ path: resolvedPath, content }], hasProject);
14260
16199
  const result = results[0];
14261
16200
  if (!result) {
14262
16201
  throw new Error(`writeFile ${resolvedPath} produced no result`);
@@ -14271,8 +16210,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14271
16210
  });
14272
16211
  const readFileTool = tool2({
14273
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.',
14274
- inputSchema: z15.object({
14275
- path: z15.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.")
14276
16215
  }),
14277
16216
  execute: async ({ path: path3 }) => {
14278
16217
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -14289,19 +16228,21 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14289
16228
  const originalBashTool = tools.bash;
14290
16229
  const bashTool = tool2({
14291
16230
  description: originalBashTool.description ?? "",
14292
- inputSchema: z15.object({
14293
- command: z15.string().describe("The bash command to execute.")
16231
+ inputSchema: z17.object({
16232
+ command: z17.string().describe("The bash command to execute.")
14294
16233
  }),
14295
- execute: async (args, opts) => {
14296
- const before = persistenceEnabled ? await snapshotSessionArtifacts() : null;
16234
+ execute: async (args, opts2) => {
16235
+ const hasProject = hasProjectNow();
16236
+ const before = persistenceEnabled ? await snapshotSessionArtifacts(hasProject) : null;
14297
16237
  const originalExecute = originalBashTool.execute;
14298
16238
  if (!originalExecute) {
14299
16239
  throw new Error("bash tool execute is undefined");
14300
16240
  }
14301
- const result = await originalExecute(args, opts);
16241
+ const result = await originalExecute(args, opts2);
14302
16242
  const artifacts = [];
14303
16243
  if (persistenceEnabled && before) {
14304
- const after = await snapshotSessionArtifacts();
16244
+ const skipProject = hasProject || hasProjectNow();
16245
+ const after = await snapshotSessionArtifacts(skipProject);
14305
16246
  const changedPaths = [];
14306
16247
  for (const [path3, mtime] of after) {
14307
16248
  const beforeMtime = before.get(path3);
@@ -14311,8 +16252,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14311
16252
  }
14312
16253
  for (const path3 of changedPaths) {
14313
16254
  try {
14314
- const content = await fsReadFile(path3);
14315
- const persisted = await persistArtifactToS3(path3, content);
16255
+ const content = await readRegularFileInside(sessionDir, path3);
16256
+ if (content === null) continue;
16257
+ const persisted = await persistArtifactToS3(path3, content, skipProject);
14316
16258
  artifacts.push({
14317
16259
  path: path3,
14318
16260
  relativePath: relative(sessionDir, path3),
@@ -14349,25 +16291,153 @@ ${lines.join("\n")}`;
14349
16291
  };
14350
16292
  }
14351
16293
  });
14352
- const wrappedTools = { ...tools, bash: bashTool, readFile: readFileTool, writeFile: writeFileTool };
14353
- const handle = {
14354
- sessionDir,
14355
- tools: wrappedTools,
14356
- wrapCommand: (command) => wrapIfNeeded(command),
14357
- cleanup: async () => {
14358
- sandboxCache.delete(sessionId);
14359
- if (!useDirectExec) {
14360
- await SandboxManager.reset();
14361
- }
14362
- await rm(sessionDir, { recursive: true, force: true });
14363
- }
14364
- };
14365
- sandboxCache.set(sessionId, { handle, installedSkills });
14366
- return handle;
16294
+ const wrappedTools = { ...tools, bash: bashTool, readFile: readFileTool, writeFile: writeFileTool };
16295
+ const handle = {
16296
+ sessionDir,
16297
+ tools: wrappedTools,
16298
+ wrapCommand: (command) => wrapIfNeeded(command),
16299
+ cleanup: async () => {
16300
+ sandboxCache.delete(sessionId);
16301
+ if (!useDirectExec) {
16302
+ await SandboxManager.reset();
16303
+ }
16304
+ await rm2(sessionDir, { recursive: true, force: true });
16305
+ await clearProjectSyncMarker(sessionDir);
16306
+ }
16307
+ };
16308
+ sandboxCache.set(sessionId, { handle, installedSkills, projectState });
16309
+ return handle;
16310
+ }
16311
+
16312
+ // src/exulu/resolve-session-project.ts
16313
+ async function resolveSessionProject(args) {
16314
+ if (!args.projectId || args.ownerId == null) return null;
16315
+ let row;
16316
+ let rbac;
16317
+ const id = await resolveSandboxProjectId(
16318
+ { projectId: args.projectId, ownerId: args.ownerId, owner: args.owner },
16319
+ {
16320
+ getProject: async (pid) => {
16321
+ const { db } = await postgresClient();
16322
+ row = await db.from("projects").where({ id: pid }).first();
16323
+ return row;
16324
+ },
16325
+ // The rbac table stores the SINGULAR entity name for projects.
16326
+ getRbac: async (p) => {
16327
+ const { db } = await postgresClient();
16328
+ rbac = await RBACResolver(db, "project", p.id, p.rights_mode || "private");
16329
+ return rbac;
16330
+ },
16331
+ getUser: async (uid) => {
16332
+ const { db } = await postgresClient();
16333
+ return db.from("users").where({ id: uid }).first();
16334
+ }
16335
+ }
16336
+ );
16337
+ if (!id) return null;
16338
+ let speakerCanWrite = false;
16339
+ if (args.speaker?.id != null && row && rbac) {
16340
+ try {
16341
+ speakerCanWrite = hasProjectAccess({ project: row, rbac, user: args.speaker, want: "write" });
16342
+ } catch {
16343
+ speakerCanWrite = false;
16344
+ }
16345
+ }
16346
+ return { id, name: row?.name?.trim() || "(unnamed)", speakerCanWrite };
16347
+ }
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
+ });
14367
16437
  }
14368
16438
 
14369
16439
  // src/templates/tools/routine-status-tool.ts
14370
- import { z as z16 } from "zod";
16440
+ import { z as z18 } from "zod";
14371
16441
  var SET_ROUTINE_STATUS_TOOL_ID = "set_routine_status";
14372
16442
  function createRoutineStatusTool(handle) {
14373
16443
  if (!handle || handle.statuses.length === 0) return void 0;
@@ -14380,8 +16450,8 @@ function createRoutineStatusTool(handle) {
14380
16450
  category: "routines",
14381
16451
  type: "function",
14382
16452
  needsApproval: false,
14383
- inputSchema: z16.object({
14384
- status: z16.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.")
14385
16455
  }),
14386
16456
  config: [],
14387
16457
  execute: async ({ status }) => {
@@ -14421,7 +16491,7 @@ var truncateToolOutput = (output, maxContextLength, toolName, tailFraction = 0.1
14421
16491
  };
14422
16492
 
14423
16493
  // src/exulu/tool-output-offload.ts
14424
- import { randomUUID as randomUUID6 } from "crypto";
16494
+ import { randomUUID as randomUUID7 } from "crypto";
14425
16495
 
14426
16496
  // src/exulu/context-budget.ts
14427
16497
  var DEFAULT_CONTEXT_WINDOW = 128e3;
@@ -14525,7 +16595,7 @@ var PREVIEW_CHARS = 4e3;
14525
16595
  var storeAsSessionFile = async (serialized, ctx) => {
14526
16596
  if (!ctx.sessionID || !ctx.exuluConfig?.fileUploads) return void 0;
14527
16597
  const safeTool = ctx.toolName.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
14528
- const name = `tool-output-${safeTool}-${randomUUID6().slice(0, 8)}.txt`;
16598
+ const name = `tool-output-${safeTool}-${randomUUID7().slice(0, 8)}.txt`;
14529
16599
  try {
14530
16600
  await uploadFile(
14531
16601
  Buffer.from(serialized, "utf-8"),
@@ -14593,7 +16663,30 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
14593
16663
  };
14594
16664
 
14595
16665
  // src/templates/tools/session-file-read-tool.ts
14596
- import { z as z17 } from "zod";
16666
+ import { z as z19 } from "zod";
16667
+
16668
+ // src/templates/tools/resolve-file-key.ts
16669
+ var NO_PROJECT_FILES_ERROR = "This session has no project files.";
16670
+ var INVALID_SESSION_FILENAME_ERROR = "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths).";
16671
+ function resolveFileKey(args) {
16672
+ const filename = String(args.filename ?? "").trim();
16673
+ const parsed = parseProjectFilename(filename);
16674
+ if ("error" in parsed) return parsed;
16675
+ if (parsed.scope === "project") {
16676
+ if (!args.projectId) return { error: NO_PROJECT_FILES_ERROR };
16677
+ const { fullProjectPrefix } = projectFilePrefix(args.projectId, args.s3prefix);
16678
+ return { key: `${fullProjectPrefix}${parsed.name}`, scope: "project" };
16679
+ }
16680
+ if (!filename || filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
16681
+ return { error: INVALID_SESSION_FILENAME_ERROR };
16682
+ }
16683
+ return {
16684
+ key: `${sessionFilePrefix(args.ownerId, args.sessionId, args.s3prefix ?? void 0)}${filename}`,
16685
+ scope: "session"
16686
+ };
16687
+ }
16688
+
16689
+ // src/templates/tools/session-file-read-tool.ts
14597
16690
  var DEFAULT_LIMIT = 250;
14598
16691
  var MAX_CONTENT_CHARS = 16e3;
14599
16692
  var SESSION_FILE_READ_TOOL_NAME = "read_session_file";
@@ -14601,18 +16694,23 @@ var createSessionFileReadTool = ({
14601
16694
  sessionID,
14602
16695
  user,
14603
16696
  exuluConfig,
14604
- ownerId
16697
+ ownerId,
16698
+ projectId,
16699
+ turnProject
14605
16700
  }) => {
14606
16701
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
14607
16702
  const readSessionFileExecute = async ({ filename, offset, limit }) => {
14608
- const safeName = String(filename ?? "").trim();
14609
- if (!safeName || safeName.includes("..") || safeName.includes("/") || safeName.includes("\\")) {
14610
- return {
14611
- error: "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths)."
14612
- };
14613
- }
14614
16703
  const uploads = exuluConfig.fileUploads;
14615
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
16704
+ const resolved = resolveFileKey({
16705
+ filename,
16706
+ ownerId: ownerId ?? user?.id ?? "api",
16707
+ sessionId: sessionID,
16708
+ projectId: currentProjectId(turnProject, projectId),
16709
+ s3prefix: uploads.s3prefix
16710
+ });
16711
+ if ("error" in resolved) return { error: resolved.error };
16712
+ const key = resolved.key;
16713
+ const safeName = String(filename).trim();
14616
16714
  try {
14617
16715
  const url = await getPresignedUrl(uploads.s3Bucket, key, exuluConfig);
14618
16716
  const res = await fetch(url);
@@ -14645,11 +16743,11 @@ var createSessionFileReadTool = ({
14645
16743
  id: "read_session_file",
14646
16744
  name: SESSION_FILE_READ_TOOL_NAME,
14647
16745
  needsApproval: false,
14648
- 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.",
14649
- inputSchema: z17.object({
14650
- filename: z17.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
14651
- offset: z17.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
14652
- limit: z17.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
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.",
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})`)
14653
16751
  }),
14654
16752
  type: "function",
14655
16753
  category: "session",
@@ -14662,18 +16760,18 @@ var createSessionFileReadTool = ({
14662
16760
  };
14663
16761
 
14664
16762
  // src/templates/tools/parse-document-tool.ts
14665
- import { z as z18 } from "zod";
14666
- import { extname } from "path";
16763
+ import { z as z20 } from "zod";
16764
+ import { extname as extname2 } from "path";
14667
16765
  import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
14668
16766
 
14669
16767
  // src/templates/tools/document-render-helpers.ts
14670
- import { execFile } from "child_process";
14671
- import { promisify as promisify3 } from "util";
16768
+ import { execFile as execFile2 } from "child_process";
16769
+ import { promisify as promisify4 } from "util";
14672
16770
  import { existsSync as existsSync5 } from "fs";
14673
- import { mkdtemp, readdir as readdir2, readFile, rm as rm2, writeFile as writeFile2 } from "fs/promises";
16771
+ import { mkdtemp, readdir as readdir3, readFile as readFile2, rm as rm3, writeFile as writeFile3 } from "fs/promises";
14674
16772
  import { tmpdir } from "os";
14675
- import { join as join3 } from "path";
14676
- var execFileAsync = promisify3(execFile);
16773
+ import { join as join5 } from "path";
16774
+ var execFileAsync2 = promisify4(execFile2);
14677
16775
  var MAX_STDOUT_BYTES = 64 * 1024 * 1024;
14678
16776
  var LEGACY_OFFICE_CONVERSION_TARGETS = {
14679
16777
  ".doc": "docx",
@@ -14689,12 +16787,12 @@ async function convertLegacyOfficeToModern(bytes, ext) {
14689
16787
  if (!target) {
14690
16788
  throw new Error(`No modern-format conversion target registered for "${ext}"`);
14691
16789
  }
14692
- const dir = await mkdtemp(join3(tmpdir(), "exulu-officeconv-"));
16790
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-officeconv-"));
14693
16791
  try {
14694
- const inputPath = join3(dir, `input${ext}`);
14695
- await writeFile2(inputPath, bytes);
16792
+ const inputPath = join5(dir, `input${ext}`);
16793
+ await writeFile3(inputPath, bytes);
14696
16794
  try {
14697
- await execFileAsync(
16795
+ await execFileAsync2(
14698
16796
  "soffice",
14699
16797
  ["--headless", "--convert-to", target, inputPath, "--outdir", dir],
14700
16798
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
@@ -14704,62 +16802,62 @@ async function convertLegacyOfficeToModern(bytes, ext) {
14704
16802
  `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err3 instanceof Error ? err3.message : String(err3))
14705
16803
  );
14706
16804
  }
14707
- const outputPath = join3(dir, `input.${target}`);
16805
+ const outputPath = join5(dir, `input.${target}`);
14708
16806
  if (!existsSync5(outputPath)) {
14709
16807
  throw new Error(`LibreOffice produced no output converting "${ext}" to ${target}`);
14710
16808
  }
14711
- return await readFile(outputPath);
16809
+ return await readFile2(outputPath);
14712
16810
  } finally {
14713
- await rm2(dir, { recursive: true, force: true });
16811
+ await rm3(dir, { recursive: true, force: true });
14714
16812
  }
14715
16813
  }
14716
16814
  async function pdfToText(pdf) {
14717
- const dir = await mkdtemp(join3(tmpdir(), "exulu-parse-"));
16815
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-parse-"));
14718
16816
  try {
14719
- const inputPath = join3(dir, "input.pdf");
14720
- await writeFile2(inputPath, pdf);
14721
- const { stdout } = await execFileAsync("pdftotext", ["-layout", inputPath, "-"], {
16817
+ const inputPath = join5(dir, "input.pdf");
16818
+ await writeFile3(inputPath, pdf);
16819
+ const { stdout } = await execFileAsync2("pdftotext", ["-layout", inputPath, "-"], {
14722
16820
  timeout: 6e4,
14723
16821
  maxBuffer: MAX_STDOUT_BYTES
14724
16822
  });
14725
16823
  return stdout;
14726
16824
  } finally {
14727
- await rm2(dir, { recursive: true, force: true });
16825
+ await rm3(dir, { recursive: true, force: true });
14728
16826
  }
14729
16827
  }
14730
16828
  async function pdfPageCount(pdf) {
14731
- const dir = await mkdtemp(join3(tmpdir(), "exulu-pdfinfo-"));
16829
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-pdfinfo-"));
14732
16830
  try {
14733
- const inputPath = join3(dir, "input.pdf");
14734
- await writeFile2(inputPath, pdf);
14735
- const { stdout } = await execFileAsync("pdfinfo", [inputPath], { timeout: 3e4, maxBuffer: 1e6 });
16831
+ const inputPath = join5(dir, "input.pdf");
16832
+ await writeFile3(inputPath, pdf);
16833
+ const { stdout } = await execFileAsync2("pdfinfo", [inputPath], { timeout: 3e4, maxBuffer: 1e6 });
14736
16834
  const match = /^Pages:\s+(\d+)/m.exec(stdout);
14737
16835
  if (!match) throw new Error("pdfinfo did not report a page count");
14738
16836
  return Number(match[1]);
14739
16837
  } finally {
14740
- await rm2(dir, { recursive: true, force: true });
16838
+ await rm3(dir, { recursive: true, force: true });
14741
16839
  }
14742
16840
  }
14743
16841
  async function renderPdfPageToPng(pdf, page, scaleTo) {
14744
- const dir = await mkdtemp(join3(tmpdir(), "exulu-render-"));
16842
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-render-"));
14745
16843
  try {
14746
- const inputPath = join3(dir, "input.pdf");
14747
- await writeFile2(inputPath, pdf);
16844
+ const inputPath = join5(dir, "input.pdf");
16845
+ await writeFile3(inputPath, pdf);
14748
16846
  try {
14749
- await execFileAsync(
16847
+ await execFileAsync2(
14750
16848
  "pdftoppm",
14751
- ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, join3(dir, "page")],
16849
+ ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, join5(dir, "page")],
14752
16850
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
14753
16851
  );
14754
16852
  } catch (err3) {
14755
16853
  if (err3?.code === 99) return null;
14756
16854
  throw err3;
14757
16855
  }
14758
- const produced = (await readdir2(dir)).find((f) => f.startsWith("page") && f.endsWith(".png"));
16856
+ const produced = (await readdir3(dir)).find((f) => f.startsWith("page") && f.endsWith(".png"));
14759
16857
  if (!produced) return null;
14760
- return await readFile(join3(dir, produced));
16858
+ return await readFile2(join5(dir, produced));
14761
16859
  } finally {
14762
- await rm2(dir, { recursive: true, force: true });
16860
+ await rm3(dir, { recursive: true, force: true });
14763
16861
  }
14764
16862
  }
14765
16863
 
@@ -14779,8 +16877,11 @@ function attachmentMaxPages(env = process.env) {
14779
16877
  function tooLongNotice(filename, pageCount, maxPages) {
14780
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.]`;
14781
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
+ }
14782
16883
  var loadDocumentProcessor = async () => {
14783
- const mod = await import("./doc_processor-E5GCE2ZT.js");
16884
+ const mod = await import("./doc_processor-SVOSOVOY.js");
14784
16885
  return mod.documentProcessor;
14785
16886
  };
14786
16887
  function pagesToText(pages) {
@@ -14795,12 +16896,16 @@ function pagesFromProcessor(result) {
14795
16896
  text: (p.vlm_corrected_text ?? p.content ?? "").trim()
14796
16897
  }));
14797
16898
  }
16899
+ function degradedPagesOf(result) {
16900
+ return (result ?? []).filter((p) => p.vlm_failed).map((p) => p.page);
16901
+ }
14798
16902
  var defaultOfficeParse = async (bytes) => String(await parseOfficeAsync(bytes, { outputErrorToConsole: false, newlineDelimiter: "\n" }));
14799
16903
  async function extractDocument(input) {
14800
16904
  const config = input.exuluConfig?.attachments?.documentProcessor;
14801
16905
  if (config) {
14802
16906
  if (input.filename.toLowerCase().endsWith(".pdf")) {
14803
- const maxPages = attachmentMaxPages();
16907
+ const forTool = input.maxPages !== void 0;
16908
+ const maxPages = input.maxPages ?? attachmentMaxPages();
14804
16909
  let pageCount;
14805
16910
  try {
14806
16911
  pageCount = await (input.countPages ?? pdfPageCount)(input.bytes);
@@ -14808,10 +16913,10 @@ async function extractDocument(input) {
14808
16913
  console.warn(`[EXULU] Could not count pages of ${input.filename}:`, error instanceof Error ? error.message : String(error));
14809
16914
  }
14810
16915
  if (pageCount !== void 0 && pageCount > maxPages) {
14811
- 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.`);
14812
16917
  return {
14813
16918
  pages: [],
14814
- text: tooLongNotice(input.filename, pageCount, maxPages),
16919
+ text: (forTool ? tooLongForToolNotice : tooLongNotice)(input.filename, pageCount, maxPages),
14815
16920
  engine: "document-processor",
14816
16921
  tooLong: { pageCount, maxPages }
14817
16922
  };
@@ -14822,11 +16927,22 @@ async function extractDocument(input) {
14822
16927
  const result = await process2({
14823
16928
  file: input.bytes,
14824
16929
  name: input.filename,
14825
- 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
14826
16936
  });
14827
16937
  const pages = pagesFromProcessor(result);
14828
16938
  if (pages.some((p) => p.text.length > 0)) {
14829
- 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
+ };
14830
16946
  }
14831
16947
  console.warn(`[EXULU] Document processor returned no text for ${input.filename}; falling back to officeparser.`);
14832
16948
  } catch (error) {
@@ -14841,9 +16957,17 @@ async function extractDocument(input) {
14841
16957
  }
14842
16958
  var PROCESSOR_NAMES = /* @__PURE__ */ new Set(["liteparse", "mistral", "officeparser"]);
14843
16959
  function validateAttachmentsConfig(config, license) {
14844
- const processorConfig = config?.attachments?.documentProcessor;
14845
- if (!processorConfig) return [];
14846
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;
14847
16971
  const name = processorConfig.processor?.name;
14848
16972
  if (!name || !PROCESSOR_NAMES.has(name)) {
14849
16973
  problems.push(`attachments.documentProcessor.processor.name must be one of ${[...PROCESSOR_NAMES].join(", ")} (got ${JSON.stringify(name)})`);
@@ -14859,6 +16983,10 @@ function validateAttachmentsConfig(config, license) {
14859
16983
  problems.push("attachments.documentProcessor.vlm.concurrency must be a positive integer");
14860
16984
  }
14861
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
+ }
14862
16990
  if (!license["advanced-document-processing"]) {
14863
16991
  problems.push("attachments.documentProcessor needs the enterprise licence (advanced-document-processing); set EXULU_ENTERPRISE_LICENSE or remove the attachments config");
14864
16992
  }
@@ -14869,6 +16997,149 @@ function validateAttachmentsConfig(config, license) {
14869
16997
  return problems;
14870
16998
  }
14871
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
+
14872
17143
  // src/templates/tools/parse-document-tool.ts
14873
17144
  var DEFAULT_LIMIT2 = 250;
14874
17145
  var MAX_CONTENT_CHARS2 = 16e3;
@@ -14898,6 +17169,50 @@ var OFFICE_EXTENSIONS = /* @__PURE__ */ new Set([
14898
17169
  ".odp",
14899
17170
  ".rtf"
14900
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
+ }
14901
17216
  var pagesPattern = /^(\d+)(?:-(\d+))?$/;
14902
17217
  function resolvePageRange(pages, totalPages, safeName) {
14903
17218
  if (!pages) return [1, totalPages];
@@ -14928,7 +17243,9 @@ var createParseDocumentTool = ({
14928
17243
  sessionID,
14929
17244
  user,
14930
17245
  exuluConfig,
14931
- ownerId
17246
+ ownerId,
17247
+ projectId,
17248
+ turnProject
14932
17249
  }) => {
14933
17250
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
14934
17251
  const parseDocumentExecute = async ({
@@ -14936,14 +17253,18 @@ var createParseDocumentTool = ({
14936
17253
  pages,
14937
17254
  offset,
14938
17255
  limit
14939
- }) => {
14940
- const safeName = String(filename ?? "").trim();
14941
- if (!safeName || safeName.includes("..") || safeName.includes("/") || safeName.includes("\\")) {
14942
- return {
14943
- error: "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths)."
14944
- };
14945
- }
14946
- const ext = extname(safeName).toLowerCase();
17256
+ }, onProgress) => {
17257
+ const resolvedKey = resolveFileKey({
17258
+ filename,
17259
+ ownerId: ownerId ?? user?.id ?? "api",
17260
+ sessionId: sessionID,
17261
+ projectId: currentProjectId(turnProject, projectId),
17262
+ s3prefix: exuluConfig.fileUploads.s3prefix
17263
+ });
17264
+ if ("error" in resolvedKey) return { error: resolvedKey.error };
17265
+ const key = resolvedKey.key;
17266
+ const safeName = String(filename).trim();
17267
+ const ext = extname2(safeName).toLowerCase();
14947
17268
  if (ext !== ".pdf" && !OFFICE_EXTENSIONS.has(ext)) {
14948
17269
  return {
14949
17270
  error: `Unsupported extension "${ext}" \u2014 parse_document handles PDF and Office formats. For plain-text files use read_session_file.`
@@ -14953,56 +17274,93 @@ var createParseDocumentTool = ({
14953
17274
  return { error: `The pages option is only supported for PDF files \u2014 "${ext}" documents are extracted whole.` };
14954
17275
  }
14955
17276
  const uploads = exuluConfig.fileUploads;
14956
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
14957
17277
  try {
14958
- const url = await getPresignedUrl(uploads.s3Bucket, key, exuluConfig);
14959
- const res = await fetch(url);
14960
- if (!res.ok) {
14961
- return { error: `Could not read session file "${safeName}" (status ${res.status}). Check the exact file name.` };
14962
- }
14963
- const bytes = Buffer.from(await res.arrayBuffer());
14964
- let fullText;
14965
- let totalPages;
14966
- if (exuluConfig.attachments?.documentProcessor) {
14967
- const extracted = await extractDocument({ bytes, filename: safeName, exuluConfig, attribution: { user } });
14968
- if (extracted.tooLong) {
14969
- return { error: extracted.text };
14970
- }
14971
- if (extracted.engine === "document-processor") {
14972
- totalPages = extracted.pages.length;
14973
- const range = resolvePageRange(pages, totalPages, safeName);
14974
- if (!Array.isArray(range)) return range;
14975
- const multiPage = totalPages > 1;
14976
- fullText = extracted.pages.filter(({ page }) => page >= range[0] && page <= range[1]).map(({ page, text }) => multiPage ? `--- page ${page} ---
14977
- ${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
+ }
14978
17289
  }
14979
- }
14980
- if (fullText === void 0 && ext === ".pdf") {
14981
- const raw = await pdfToText(bytes);
14982
- const pageTexts = raw.replace(/\f$/, "").split("\f");
14983
- totalPages = pageTexts.length;
14984
- const nonWhitespace = raw.replace(/\s/g, "").length;
14985
- if (looksLikeGarbledTextLayer(raw)) {
14986
- return {
14987
- 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.`
14988
- };
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";
14989
17318
  }
14990
- 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
+ }
14991
17330
  return {
14992
- 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")
14993
17335
  };
14994
17336
  }
14995
- const range = resolvePageRange(pages, totalPages, safeName);
14996
- if (!Array.isArray(range)) return range;
14997
- fullText = pageTexts.map((text, i) => ({ page: i + 1, text })).filter(({ page }) => page >= range[0] && page <= range[1]).map(({ page, text }) => `--- page ${page} ---
14998
- ${text.trim()}`).join("\n");
14999
- } else if (fullText === void 0) {
15000
17337
  const officeBytes = isLegacyOfficeFormat(ext) ? await convertLegacyOfficeToModern(bytes, ext) : bytes;
15001
- const extracted = await parseOfficeAsync2(officeBytes, {
17338
+ const parsed = await parseOfficeAsync2(officeBytes, {
15002
17339
  outputErrorToConsole: false,
15003
17340
  newlineDelimiter: "\n"
15004
17341
  });
15005
- 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 ?? [];
15006
17364
  }
15007
17365
  const lines = (fullText ?? "").split("\n");
15008
17366
  const start = (offset ?? 1) - 1;
@@ -15015,27 +17373,68 @@ ${text.trim()}`).join("\n");
15015
17373
  linesReturned = Math.max(1, content.split("\n").length - 1);
15016
17374
  content = content + "\n[slice truncated \u2014 request fewer lines]";
15017
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
+ }
15018
17380
  return {
15019
17381
  content,
15020
17382
  ...totalPages !== void 0 ? { totalPages } : {},
15021
17383
  totalLines: lines.length,
15022
17384
  offset: start + 1,
15023
- 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 } : {}
15024
17389
  };
15025
17390
  } catch (err3) {
17391
+ if (err3 instanceof ExtractionRefusal) return { error: refusalMessage2(err3.info, safeName) };
15026
17392
  return { error: `Failed to parse "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
15027
17393
  }
15028
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
+ }
15029
17426
  return ExuluTool.internal({
15030
17427
  id: "parse_document",
15031
17428
  name: PARSE_DOCUMENT_TOOL_NAME,
15032
17429
  needsApproval: false,
15033
- 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.`,
15034
- inputSchema: z18.object({
15035
- filename: z18.string().describe('Exact session file name, e.g. "report.pdf"'),
15036
- pages: z18.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
15037
- offset: z18.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
15038
- limit: z18.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})`)
15039
17438
  }),
15040
17439
  type: "function",
15041
17440
  category: "session",
@@ -15043,25 +17442,25 @@ ${text.trim()}`).join("\n");
15043
17442
  // Same shape mismatch as read_session_file / memory-tool: internal utility
15044
17443
  // tools return richer objects than ExuluTool's retrieval-flavored execute
15045
17444
  // type; the AI SDK passes the object through verbatim.
15046
- execute: parseDocumentExecute
17445
+ execute: parseDocumentStream
15047
17446
  });
15048
17447
  };
15049
17448
 
15050
17449
  // src/templates/tools/view-document-page-tool.ts
15051
- import { z as z19 } from "zod";
15052
- import { extname as extname3 } from "path";
17450
+ import { z as z21 } from "zod";
17451
+ import { extname as extname4 } from "path";
15053
17452
 
15054
17453
  // src/sessions/pdf-preview-cache.ts
15055
17454
  import { exec as exec3 } from "child_process";
15056
17455
  import { existsSync as existsSync6 } from "fs";
15057
- import { mkdir as mkdir2, readFile as readFile2, rename, rm as rm3, writeFile as writeFile3 } from "fs/promises";
15058
- import { extname as extname2, join as join4 } from "path";
15059
- import { promisify as promisify4 } from "util";
15060
- var execAsync3 = promisify4(exec3);
17456
+ import { mkdir as mkdir4, readFile as readFile3, rename as rename3, rm as rm4, writeFile as writeFile4 } from "fs/promises";
17457
+ import { extname as extname3, join as join6 } from "path";
17458
+ import { promisify as promisify5 } from "util";
17459
+ var execAsync3 = promisify5(exec3);
15061
17460
  var CACHE_ROOT = "/tmp/exulu-pdf-cache";
15062
- var CACHE_IN = join4(CACHE_ROOT, "_in");
15063
- var CACHE_OUT = join4(CACHE_ROOT, "_out");
15064
- var inFlight = /* @__PURE__ */ new Map();
17461
+ var CACHE_IN = join6(CACHE_ROOT, "_in");
17462
+ var CACHE_OUT = join6(CACHE_ROOT, "_out");
17463
+ var inFlight2 = /* @__PURE__ */ new Map();
15065
17464
  var PreviewRenderError = class extends Error {
15066
17465
  constructor(message) {
15067
17466
  super(message);
@@ -15077,22 +17476,22 @@ async function getPdfPreviewBytes(opts) {
15077
17476
  if (!safeEtag) {
15078
17477
  throw new PreviewRenderError(`Invalid ETag for ${sourceKey}`);
15079
17478
  }
15080
- const cachedPath = join4(CACHE_ROOT, `${safeEtag}.pdf`);
17479
+ const cachedPath = join6(CACHE_ROOT, `${safeEtag}.pdf`);
15081
17480
  if (existsSync6(cachedPath)) {
15082
- return readFile2(cachedPath);
17481
+ return readFile3(cachedPath);
15083
17482
  }
15084
- const existing = inFlight.get(safeEtag);
17483
+ const existing = inFlight2.get(safeEtag);
15085
17484
  if (existing) return existing;
15086
17485
  const promise = (async () => {
15087
17486
  try {
15088
- await mkdir2(CACHE_IN, { recursive: true });
15089
- await mkdir2(CACHE_OUT, { recursive: true });
15090
- const ext = (extname2(sourceKey) || ".docx").toLowerCase();
15091
- const inputPath = join4(CACHE_IN, `${safeEtag}${ext}`);
15092
- const outputPath = join4(CACHE_OUT, `${safeEtag}.pdf`);
17487
+ await mkdir4(CACHE_IN, { recursive: true });
17488
+ await mkdir4(CACHE_OUT, { recursive: true });
17489
+ const ext = (extname3(sourceKey) || ".docx").toLowerCase();
17490
+ const inputPath = join6(CACHE_IN, `${safeEtag}${ext}`);
17491
+ const outputPath = join6(CACHE_OUT, `${safeEtag}.pdf`);
15093
17492
  try {
15094
17493
  const bytes = await getS3ObjectBytes(sourceKey, config);
15095
- await writeFile3(inputPath, bytes);
17494
+ await writeFile4(inputPath, bytes);
15096
17495
  try {
15097
17496
  await execAsync3(
15098
17497
  `soffice --headless --convert-to pdf "${inputPath}" --outdir "${CACHE_OUT}"`,
@@ -15108,16 +17507,16 @@ async function getPdfPreviewBytes(opts) {
15108
17507
  `LibreOffice produced no output for ${sourceKey} (etag ${etag})`
15109
17508
  );
15110
17509
  }
15111
- await rename(outputPath, cachedPath);
15112
- return await readFile2(cachedPath);
17510
+ await rename3(outputPath, cachedPath);
17511
+ return await readFile3(cachedPath);
15113
17512
  } finally {
15114
- await rm3(inputPath, { force: true });
17513
+ await rm4(inputPath, { force: true });
15115
17514
  }
15116
17515
  } finally {
15117
- inFlight.delete(safeEtag);
17516
+ inFlight2.delete(safeEtag);
15118
17517
  }
15119
17518
  })();
15120
- inFlight.set(safeEtag, promise);
17519
+ inFlight2.set(safeEtag, promise);
15121
17520
  return promise;
15122
17521
  }
15123
17522
 
@@ -15227,17 +17626,23 @@ var createViewDocumentPageTool = ({
15227
17626
  sessionID,
15228
17627
  user,
15229
17628
  exuluConfig,
15230
- ownerId
17629
+ ownerId,
17630
+ projectId,
17631
+ turnProject
15231
17632
  }) => {
15232
17633
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
15233
17634
  const viewDocumentPageExecute = async ({ filename, page, model }, options) => {
15234
- const safeName = String(filename ?? "").trim();
15235
- if (!safeName || safeName.includes("..") || safeName.includes("/") || safeName.includes("\\")) {
15236
- return {
15237
- error: "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths)."
15238
- };
15239
- }
15240
- const ext = extname3(safeName).toLowerCase();
17635
+ const resolvedKey = resolveFileKey({
17636
+ filename,
17637
+ ownerId: ownerId ?? user?.id ?? "api",
17638
+ sessionId: sessionID,
17639
+ projectId: currentProjectId(turnProject, projectId),
17640
+ s3prefix: exuluConfig.fileUploads.s3prefix
17641
+ });
17642
+ if ("error" in resolvedKey) return { error: resolvedKey.error };
17643
+ const key = resolvedKey.key;
17644
+ const safeName = String(filename).trim();
17645
+ const ext = extname4(safeName).toLowerCase();
15241
17646
  const isImage = ext in IMAGE_MEDIA_TYPES;
15242
17647
  const isPdf = ext === ".pdf";
15243
17648
  const isOffice = OFFICE_EXTENSIONS2.has(ext);
@@ -15259,8 +17664,6 @@ var createViewDocumentPageTool = ({
15259
17664
  } catch {
15260
17665
  }
15261
17666
  }
15262
- const uploads = exuluConfig.fileUploads;
15263
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
15264
17667
  const pageNumber = page ?? 1;
15265
17668
  try {
15266
17669
  let imageBytes;
@@ -15318,10 +17721,10 @@ var createViewDocumentPageTool = ({
15318
17721
  id: "view_document_page",
15319
17722
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
15320
17723
  needsApproval: false,
15321
- 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.",
15322
- inputSchema: z19.object({
15323
- filename: z19.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
15324
- page: z19.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
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.",
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)")
15325
17728
  }),
15326
17729
  type: "function",
15327
17730
  category: "session",
@@ -15364,55 +17767,14 @@ function extractClientInfo(req) {
15364
17767
  }
15365
17768
 
15366
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
+ };
15367
17775
  var OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
15368
- var generateS3Key = (filename) => `${randomUUID7()}-${filename}`;
17776
+ var generateS3Key = (filename) => `${randomUUID8()}-${filename}`;
15369
17777
  var s3Client2;
15370
- var getMimeType = (type) => {
15371
- switch (type) {
15372
- case ".png":
15373
- return "image/png";
15374
- case ".jpg":
15375
- return "image/jpg";
15376
- case ".jpeg":
15377
- return "image/jpeg";
15378
- case ".gif":
15379
- return "image/gif";
15380
- case ".webp":
15381
- return "image/webp";
15382
- case ".pdf":
15383
- return "application/pdf";
15384
- case ".docx":
15385
- return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
15386
- case ".xlsx":
15387
- return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
15388
- case ".xls":
15389
- return "application/vnd.ms-excel";
15390
- case ".csv":
15391
- return "text/csv";
15392
- case ".pptx":
15393
- return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
15394
- case ".ppt":
15395
- return "application/vnd.ms-powerpoint";
15396
- case ".m4a":
15397
- return "audio/mp4";
15398
- case ".mp4":
15399
- return "audio/mp4";
15400
- case ".mpeg":
15401
- return "audio/mpeg";
15402
- case ".mp3":
15403
- return "audio/mp3";
15404
- case ".wav":
15405
- return "audio/wav";
15406
- case ".txt":
15407
- return "text/plain";
15408
- case ".md":
15409
- return "text/markdown";
15410
- case ".json":
15411
- return "application/json";
15412
- default:
15413
- return "";
15414
- }
15415
- };
15416
17778
  var hydrateVariables = async (tool3) => {
15417
17779
  const { db } = await postgresClient();
15418
17780
  const promises = tool3.config.map(async (toolConfig) => {
@@ -15463,7 +17825,7 @@ var hydrateVariables = async (tool3) => {
15463
17825
  await Promise.all(promises);
15464
17826
  return tool3;
15465
17827
  };
15466
- var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions, skillDecisions, routineHandleFactory) => {
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) => {
15467
17829
  if (!currentTools) return {};
15468
17830
  if (!allExuluTools) {
15469
17831
  allExuluTools = [];
@@ -15473,6 +17835,9 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15473
17835
  }
15474
17836
  const budget = deriveContextBudget(contextWindow);
15475
17837
  const toolOutputCharLimit = budget.toolOutputCapTokens * 4;
17838
+ const turnProject = resolvedProject !== void 0 ? resolvedProject : sessionID ? await resolveSessionProject({ projectId: project, ownerId: sessionOwnerId ?? user?.id, owner: user, speaker: user }) : null;
17839
+ const sandboxProjectId = turnProject?.id ?? null;
17840
+ const turnProjectHolder = createTurnProject(turnProject);
15476
17841
  let sharedSessionSandbox;
15477
17842
  if (sessionID && exuluConfig && agent?.sandbox_enabled === true) {
15478
17843
  try {
@@ -15483,7 +17848,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15483
17848
  sessionOwnerId ?? user?.id,
15484
17849
  // Same agent descriptor the tool-call audit emitter uses below, so a
15485
17850
  // skill.sandbox.created event can be joined to the agent that caused it.
15486
- agent ? { id: agent.id, name: agent.name, slug: agent.slug } : void 0
17851
+ agent ? { id: agent.id, name: agent.name, slug: agent.slug } : void 0,
17852
+ { projectId: sandboxProjectId }
15487
17853
  );
15488
17854
  } catch (err3) {
15489
17855
  console.error(
@@ -15560,11 +17926,11 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15560
17926
  currentTools.push(sessionItemsRetrievalTool);
15561
17927
  }
15562
17928
  }
15563
- const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
17929
+ const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId, turnProject: turnProjectHolder });
15564
17930
  if (sessionFileReadTool && !disabled.has(sessionFileReadTool.id)) {
15565
17931
  currentTools.push(sessionFileReadTool);
15566
17932
  }
15567
- const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
17933
+ const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId, turnProject: turnProjectHolder });
15568
17934
  if (parseDocumentTool && !disabled.has(parseDocumentTool.id)) {
15569
17935
  currentTools.push(parseDocumentTool);
15570
17936
  }
@@ -15572,7 +17938,36 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15572
17938
  if (routineStatusTool && !disabled.has(routineStatusTool.id)) {
15573
17939
  currentTools.push(routineStatusTool);
15574
17940
  }
15575
- const viewDocumentPageTool = createViewDocumentPageTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
17941
+ const saveToProjectTool = createSaveToProjectTool({
17942
+ sessionID,
17943
+ user,
17944
+ req,
17945
+ exuluConfig,
17946
+ ownerId: sessionOwnerId,
17947
+ project: turnProject,
17948
+ disabled,
17949
+ turnProject: turnProjectHolder
17950
+ });
17951
+ if (saveToProjectTool) {
17952
+ currentTools.push(saveToProjectTool);
17953
+ }
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 });
15576
17971
  if (viewDocumentPageTool && !disabled.has(viewDocumentPageTool.id)) {
15577
17972
  currentTools.push(viewDocumentPageTool);
15578
17973
  }
@@ -15710,10 +18105,12 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15710
18105
  // Never a plain `false` for a tool the user allowed for this chat: the
15711
18106
  // SDK re-validates an ANSWERED approval by calling needsApproval again
15712
18107
  // and reads `false` as "deny" — see approval-revalidation.ts.
15713
- needsApproval: cur.needsApprovalFn ? (input, opts) => cur.needsApprovalFn(input, opts) : isMemoryToolId(cur.id) ? true : (_input, opts) => needsApprovalForCall({
18108
+ needsApproval: cur.needsApprovalFn ? (input, opts) => cur.needsApprovalFn(input, opts) : isMemoryToolId(cur.id) ? true : (input, opts) => needsApprovalForCall({
15714
18109
  toolCallId: opts.toolCallId,
15715
18110
  messages: opts.messages,
15716
- approvedForSession,
18111
+ // alwaysAskWhen only removes the "allowed for this chat" shortcut for
18112
+ // that call; an answered approval still reads as true, so no denial loop.
18113
+ approvedForSession: approvedForSession && !cur.alwaysAskWhen?.(input),
15717
18114
  requiresApproval: !!cur.needsApproval
15718
18115
  // todo make configurable
15719
18116
  }),
@@ -15816,6 +18213,15 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15816
18213
  user,
15817
18214
  contexts: contextsMap,
15818
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
+ }),
15819
18225
  exuluConfig,
15820
18226
  toolVariablesConfig: toolVariablesConfigData,
15821
18227
  // Present only inside a routine run: routine.runs.current.update({ status }).
@@ -15842,16 +18248,19 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15842
18248
  const offloadExempt = OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS.has(cur.id);
15843
18249
  if (response && typeof response === "object" && Symbol.asyncIterator in response) {
15844
18250
  let lastValue;
18251
+ let lastYieldWasInterim = false;
15845
18252
  for await (const value of response) {
15846
18253
  yield value;
15847
- lastValue = value;
18254
+ lastYieldWasInterim = isReadingProgress(value);
18255
+ if (!lastYieldWasInterim) lastValue = value;
15848
18256
  }
15849
18257
  if (offloadExempt) {
15850
18258
  __auditOutput = lastValue;
18259
+ if (lastYieldWasInterim) yield lastValue;
15851
18260
  return lastValue;
15852
18261
  }
15853
18262
  const guarded = await guardToolOutput(lastValue, guardCtx);
15854
- if (guarded !== lastValue) {
18263
+ if (guarded !== lastValue || lastYieldWasInterim) {
15855
18264
  yield guarded;
15856
18265
  }
15857
18266
  __auditOutput = guarded;
@@ -15907,6 +18316,12 @@ export {
15907
18316
  resolveLiteLLMConfigPath,
15908
18317
  parseEmbeddingModels,
15909
18318
  getEmbeddingModelInfo,
18319
+ sanitizeFilename,
18320
+ MAX_PROJECT_FILES,
18321
+ projectFilePrefix,
18322
+ DERIVED_ROOT,
18323
+ isDerivedKey,
18324
+ documentCacheDays,
15910
18325
  getPresignedUrl,
15911
18326
  uploadFile,
15912
18327
  listS3ObjectsByPrefix,
@@ -15917,6 +18332,8 @@ export {
15917
18332
  getS3ObjectSize,
15918
18333
  getS3ObjectBytes,
15919
18334
  deleteS3Object,
18335
+ listS3ObjectsExact,
18336
+ deleteS3ObjectsExact,
15920
18337
  getS3SignedUploadUrl,
15921
18338
  createUppyRoutes,
15922
18339
  ExuluStorage,
@@ -16023,13 +18440,50 @@ export {
16023
18440
  buildMemoryPromptBlock,
16024
18441
  normalizeRbac,
16025
18442
  collectMemoryDecisions,
16026
- sessionFilePrefix,
16027
- sanitizeFilename,
16028
18443
  isPublicSurface,
16029
18444
  treatAsGuest,
16030
18445
  KB_EDITOR_TOOL_ID,
16031
18446
  createKbEditorPickerTool,
18447
+ hasProjectAccess,
16032
18448
  RBACResolver,
18449
+ normalizeS3Key,
18450
+ deriveFilename,
18451
+ slugifyShareName,
18452
+ isExpired,
18453
+ validateCreateInput,
18454
+ readAgentSlots,
18455
+ canManageShare,
18456
+ validateUpdateInput,
18457
+ ownsObjectKey,
18458
+ planShareUpdate,
18459
+ hashSharePassword,
18460
+ verifySharePassword,
18461
+ contentHeadersFor,
18462
+ publicMetaFor,
18463
+ getSharedArtifactByName,
18464
+ MAX_ADOPT_UPLOAD_BYTES,
18465
+ planAdoptKeys,
18466
+ planAdoptSizeCheck,
18467
+ createProjectForUser,
18468
+ SKIP_TOO_LARGE,
18469
+ SKIP_PROJECT_FULL,
18470
+ COPY_FAILED_REASON,
18471
+ promoteSessionFiles,
18472
+ getOriginResolver,
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,
18486
+ canRegisterSaveToProject,
16033
18487
  resolveSkillByName,
16034
18488
  canAccessSkill,
16035
18489
  filterReadableSkills,
@@ -16039,13 +18493,17 @@ export {
16039
18493
  parseSkillAuthorConfig,
16040
18494
  SKILL_AUTHOR_PROMPT,
16041
18495
  createSkillAuthorPickerTool,
16042
- isIgnoredArtifactPath,
16043
18496
  reportSystemDependencies,
16044
18497
  findUnclassifiedSecretShaped,
16045
18498
  getAuditLogger,
16046
18499
  initAudit,
16047
18500
  downloadKeyIntoSandbox,
16048
18501
  refreshSessionSkills,
18502
+ resolveSessionProject,
18503
+ contentTypeFor2 as contentTypeFor,
18504
+ SAVE_INVALID_NAME,
18505
+ SAVE_EMPTY,
18506
+ SAVE_FAILED,
16049
18507
  truncateToolOutput,
16050
18508
  DEFAULT_CONTEXT_WINDOW,
16051
18509
  deriveContextBudget,