@exulu/backend 5.12.0 → 5.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -584,6 +584,13 @@ var ExuluTool = class _ExuluTool {
584
584
  * the boolean and never applies the "Allow for this chat" shortcut.
585
585
  */
586
586
  needsApprovalFn;
587
+ /**
588
+ * Calls for which approval is ALWAYS asked, even when the user allowed the tool for this
589
+ * chat (e.g. save_to_project with overwrite: true). Only narrows the shortcut: a call whose
590
+ * approval was already answered is still honoured by the approval wiring.
591
+ * Ignored for tools that set `needsApprovalFn` (that check decides every call on its own).
592
+ */
593
+ alwaysAskWhen;
587
594
  authentication;
588
595
  config;
589
596
  constructor({
@@ -597,6 +604,7 @@ var ExuluTool = class _ExuluTool {
597
604
  config,
598
605
  needsApproval,
599
606
  needsApprovalFn,
607
+ alwaysAskWhen,
600
608
  authentication: authentication2
601
609
  }) {
602
610
  if (!PUBLIC_TOOL_TYPES.includes(type)) {
@@ -615,6 +623,7 @@ var ExuluTool = class _ExuluTool {
615
623
  this.config = config;
616
624
  this.needsApproval = needsApproval ?? true;
617
625
  this.needsApprovalFn = needsApprovalFn;
626
+ this.alwaysAskWhen = alwaysAskWhen;
618
627
  this.category = category || "default";
619
628
  this.name = name;
620
629
  this.description = description;
@@ -659,7 +668,7 @@ var ExuluTool = class _ExuluTool {
659
668
  if (!agent) {
660
669
  throw new Error("Agent not found.");
661
670
  }
662
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-WEC42QHZ.js");
671
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-IYEO2RV6.js");
663
672
  const tools = await convertExuluToolsToAiSdkTools2(
664
673
  [this],
665
674
  [],
@@ -4174,6 +4183,115 @@ import {
4174
4183
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
4175
4184
  import { STSClient, GetFederationTokenCommand } from "@aws-sdk/client-sts";
4176
4185
  import { randomUUID as randomUUID2 } from "crypto";
4186
+
4187
+ // src/exulu/session-files.ts
4188
+ function sessionFilePrefix(ownerId, sessionId, s3prefix) {
4189
+ const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
4190
+ return `${general}user_${ownerId}/sessions/${sessionId}/`;
4191
+ }
4192
+ function sanitizeFilename(name) {
4193
+ const trimmed = name.trim();
4194
+ if (!trimmed) return "";
4195
+ if (trimmed.includes("..")) return "";
4196
+ if (trimmed.startsWith("/") || trimmed.startsWith("\\")) return "";
4197
+ return trimmed.replace(/[\\/]/g, "_");
4198
+ }
4199
+
4200
+ // src/exulu/project-files.ts
4201
+ var MAX_PROJECT_FILES = 200;
4202
+ var MAX_PROMOTE_KEYS = 20;
4203
+ var PROJECT_DIR = "project";
4204
+ var generalPrefix = (s3prefix) => s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
4205
+ function projectFilePrefix(projectId, s3prefix) {
4206
+ const projectPrefix = `projects/${projectId}/files/`;
4207
+ return { projectPrefix, fullProjectPrefix: `${generalPrefix(s3prefix)}${projectPrefix}` };
4208
+ }
4209
+ function isProjectKey(key, s3prefix) {
4210
+ return key.replace(/^\/+/, "").startsWith(`${generalPrefix(s3prefix)}projects/`);
4211
+ }
4212
+ function parseProjectFilename(filename) {
4213
+ const marker = `${PROJECT_DIR}/`;
4214
+ if (!filename.startsWith(marker)) return { scope: "session", name: filename };
4215
+ const rest = filename.slice(marker.length);
4216
+ if (!rest) return { error: "Project filename is empty." };
4217
+ if (rest.includes("..")) return { error: "Project filename must not contain '..'." };
4218
+ if (rest.includes("/") || rest.includes("\\")) {
4219
+ return { error: "Project files are flat; subdirectories are not allowed." };
4220
+ }
4221
+ const name = sanitizeFilename(rest);
4222
+ if (!name) return { error: "Project filename is not valid." };
4223
+ return { scope: "project", name };
4224
+ }
4225
+ function planPromote(args) {
4226
+ const { keys, fullSessionPrefix, fullProjectPrefix, existingNames, overwrite } = args;
4227
+ if (keys.length > MAX_PROMOTE_KEYS) {
4228
+ return {
4229
+ accepted: [],
4230
+ rejected: keys.map((key) => ({
4231
+ key: String(key),
4232
+ reason: `Batch exceeds the ${MAX_PROMOTE_KEYS}-key promote limit.`
4233
+ })),
4234
+ clashes: []
4235
+ };
4236
+ }
4237
+ const accepted = [];
4238
+ const rejected = [];
4239
+ const clashes = [];
4240
+ const existing = new Set(existingNames);
4241
+ const owners = /* @__PURE__ */ new Map();
4242
+ for (const raw of keys) {
4243
+ if (typeof raw !== "string" || !raw.trim()) {
4244
+ rejected.push({ key: String(raw), reason: "Key must be a non-empty string." });
4245
+ continue;
4246
+ }
4247
+ const key = raw.replace(/^\/+/, "");
4248
+ if (key.includes("..")) {
4249
+ rejected.push({ key: raw, reason: "Key contains a path traversal segment." });
4250
+ continue;
4251
+ }
4252
+ if (!key.startsWith(fullSessionPrefix)) {
4253
+ rejected.push({ key: raw, reason: "Key is not a file of this session." });
4254
+ continue;
4255
+ }
4256
+ const name = sanitizeFilename(key.slice(fullSessionPrefix.length));
4257
+ if (!name) {
4258
+ rejected.push({ key: raw, reason: "Could not derive a safe filename." });
4259
+ continue;
4260
+ }
4261
+ if (owners.has(name)) {
4262
+ const first = owners.get(name);
4263
+ if (first) {
4264
+ const idx = accepted.indexOf(first);
4265
+ if (idx !== -1) accepted.splice(idx, 1);
4266
+ rejected.push({ key: first.sourceKey, reason: "Filename collides with another key in this batch." });
4267
+ owners.set(name, null);
4268
+ }
4269
+ rejected.push({ key: raw, reason: "Filename collides with another key in this batch." });
4270
+ continue;
4271
+ }
4272
+ if (existing.has(name) && !overwrite) {
4273
+ clashes.push(name);
4274
+ owners.set(name, null);
4275
+ continue;
4276
+ }
4277
+ const entry = { sourceKey: key, name, destKey: `${fullProjectPrefix}${name}` };
4278
+ accepted.push(entry);
4279
+ owners.set(name, entry);
4280
+ }
4281
+ const newCount = accepted.filter((a) => !existing.has(a.name)).length;
4282
+ if (existing.size + newCount > MAX_PROJECT_FILES) {
4283
+ for (const a of accepted) {
4284
+ rejected.push({
4285
+ key: a.sourceKey,
4286
+ reason: `A project holds at most ${MAX_PROJECT_FILES} files.`
4287
+ });
4288
+ }
4289
+ return { accepted: [], rejected, clashes };
4290
+ }
4291
+ return { accepted, rejected, clashes };
4292
+ }
4293
+
4294
+ // src/uppy/index.ts
4177
4295
  var expiresIn = 60 * 60 * 24 * 1;
4178
4296
  var s3Client;
4179
4297
  function getS3Client(config) {
@@ -4285,7 +4403,7 @@ var uploadFile = async (file, fileName, config, options = {}, user, customBucket
4285
4403
  if (error.name === "SignatureDoesNotMatch" || error.name === "InvalidAccessKeyId" || error.name === "AccessDenied") {
4286
4404
  if (attempt < maxRetries) {
4287
4405
  const backoffMs = Math.pow(2, attempt) * 1e3;
4288
- await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
4406
+ await new Promise((resolve4) => setTimeout(resolve4, backoffMs));
4289
4407
  s3Client = void 0;
4290
4408
  getS3Client(config);
4291
4409
  continue;
@@ -4339,7 +4457,10 @@ var copyS3Object = async (sourceKey, destKey, config) => {
4339
4457
  const command = new CopyObjectCommand({
4340
4458
  Bucket: bucket,
4341
4459
  CopySource: `${bucket}/${encodeS3KeyForCopySource(sourceKey)}`,
4342
- Key: destKey
4460
+ Key: destKey,
4461
+ // Explicit so the origin marker (exulu-origin) survives a copy; promoting a
4462
+ // file into a project must not turn an agent file into a "user" file.
4463
+ MetadataDirective: "COPY"
4343
4464
  });
4344
4465
  await client.send(command);
4345
4466
  };
@@ -4384,6 +4505,72 @@ var getS3ObjectEtag = async (key, config) => {
4384
4505
  return null;
4385
4506
  }
4386
4507
  };
4508
+ function isS3NotFound(err3) {
4509
+ const e = err3;
4510
+ return e?.$metadata?.httpStatusCode === 404 || e?.name === "NotFound" || e?.name === "NoSuchKey" || e?.Code === "NotFound" || e?.Code === "NoSuchKey";
4511
+ }
4512
+ var getS3ObjectMetadataStrict = async (key, config) => {
4513
+ if (!config.fileUploads) {
4514
+ throw new Error("File uploads are not configured");
4515
+ }
4516
+ const client = getS3Client(config);
4517
+ try {
4518
+ const response = await client.send(
4519
+ new HeadObjectCommand({ Bucket: config.fileUploads.s3Bucket, Key: key })
4520
+ );
4521
+ return response.Metadata;
4522
+ } catch (err3) {
4523
+ if (isS3NotFound(err3)) return void 0;
4524
+ throw err3;
4525
+ }
4526
+ };
4527
+ function mayUseGenericS3Route(key, user, s3prefix) {
4528
+ if (user.type === "api" || user.super_admin) return true;
4529
+ return !isProjectKey(key, s3prefix);
4530
+ }
4531
+ function genericKeyDirectories(key, s3prefix) {
4532
+ const segments = key.split("/");
4533
+ if (segments.some((s) => s === "" || s === "." || s === "..")) return null;
4534
+ const general = (s3prefix ?? "").replace(/^\/+|\/+$/g, "");
4535
+ const prefixSegments = general ? general.split("/") : [];
4536
+ const hasPrefix = prefixSegments.length > 0 && prefixSegments.every((p, i) => segments[i] === p);
4537
+ return segments.slice(hasPrefix ? prefixSegments.length : 0, -1);
4538
+ }
4539
+ function mayReadGenericS3Key(key, user, s3prefix) {
4540
+ if (user.type === "api" || user.super_admin) return true;
4541
+ const directories = genericKeyDirectories(key, s3prefix);
4542
+ if (directories === null) return false;
4543
+ return directories.every((d) => !d.startsWith("user_") || d === `user_${user.id}`);
4544
+ }
4545
+ function mayDeleteGenericS3Key(key, user, s3prefix) {
4546
+ if (user.type === "api" || user.super_admin) return true;
4547
+ if (!mayReadGenericS3Key(key, user, s3prefix)) return false;
4548
+ return (genericKeyDirectories(key, s3prefix) ?? []).includes(`user_${user.id}`);
4549
+ }
4550
+ function multipartKeyBelongsTo(key, user, s3prefix) {
4551
+ if (!key || key.split("/").includes("..")) return false;
4552
+ let rest = key;
4553
+ const general = (s3prefix ?? "").replace(/\/+$/, "");
4554
+ if (general) {
4555
+ if (!rest.startsWith(`${general}/`)) return false;
4556
+ rest = rest.slice(general.length + 1);
4557
+ }
4558
+ const own = user.type === "api" ? "user_api/" : `user_${user.id}/`;
4559
+ return rest.startsWith(own) || rest.startsWith("global/");
4560
+ }
4561
+ function buildStsPolicy(bucket, userId, s3prefix) {
4562
+ const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
4563
+ return {
4564
+ Version: "2012-10-17",
4565
+ Statement: [
4566
+ {
4567
+ Effect: "Allow",
4568
+ Action: ["s3:PutObject"],
4569
+ Resource: [`arn:aws:s3:::${bucket}/${general}user_${userId}/*`]
4570
+ }
4571
+ ]
4572
+ };
4573
+ }
4387
4574
  var getS3ObjectSize = async (key, config) => {
4388
4575
  if (!config.fileUploads) {
4389
4576
  throw new Error("File uploads are not configured");
@@ -4422,7 +4609,7 @@ var deleteS3Object = async (key, config) => {
4422
4609
  const command = new DeleteObjectCommand({ Bucket: bucket, Key: key });
4423
4610
  await client.send(command);
4424
4611
  };
4425
- var getS3SignedUploadUrl = async (key, contentType, config) => {
4612
+ var getS3SignedUploadUrl = async (key, contentType, config, opts = {}) => {
4426
4613
  if (!config.fileUploads) {
4427
4614
  throw new Error("File uploads are not configured");
4428
4615
  }
@@ -4435,7 +4622,7 @@ var getS3SignedUploadUrl = async (key, contentType, config) => {
4435
4622
  Key: key,
4436
4623
  ContentType: contentType
4437
4624
  }),
4438
- { expiresIn }
4625
+ { expiresIn: opts.expiresIn ?? expiresIn }
4439
4626
  );
4440
4627
  return url;
4441
4628
  };
@@ -4443,19 +4630,6 @@ var createUppyRoutes = async (app, config) => {
4443
4630
  if (!config.fileUploads) {
4444
4631
  throw new Error("File uploads are not configured");
4445
4632
  }
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
4633
  let stsClient;
4460
4634
  function getSTSClient() {
4461
4635
  if (!config.fileUploads) {
@@ -4499,7 +4673,11 @@ var createUppyRoutes = async (app, config) => {
4499
4673
  return;
4500
4674
  }
4501
4675
  let bucket = key.split("/")[0];
4502
- if (user.type !== "api" && !key.includes(`/user_${user.id}/`) && !user.super_admin) {
4676
+ if (!mayUseGenericS3Route(key.replace(`${bucket}/`, ""), user, config.fileUploads.s3prefix)) {
4677
+ res.status(403).json({ error: "Project files cannot be deleted through this route." });
4678
+ return;
4679
+ }
4680
+ if (!mayDeleteGenericS3Key(key.slice((bucket ?? "").length + 1), user, config.fileUploads.s3prefix)) {
4503
4681
  res.status(405).json({
4504
4682
  error: "Not allowed to access the files in the folder based on authenticated user."
4505
4683
  });
@@ -4554,11 +4732,11 @@ var createUppyRoutes = async (app, config) => {
4554
4732
  res.status(400).json({ error: "Missing or invalid `key` query parameter." });
4555
4733
  return;
4556
4734
  }
4557
- let allowed = false;
4558
- if (user.type === "api" || user.super_admin || !key.includes(`user_`) || key.includes(`user_${user.id}/`)) {
4559
- allowed = true;
4735
+ if (!mayUseGenericS3Route(key, user, config.fileUploads?.s3prefix)) {
4736
+ res.status(403).json({ error: "Project files cannot be downloaded through this route." });
4737
+ return;
4560
4738
  }
4561
- if (!allowed) {
4739
+ if (!mayReadGenericS3Key(key, user, config.fileUploads?.s3prefix)) {
4562
4740
  res.status(405).json({ error: "Not allowed to access the file based on authenticated user." });
4563
4741
  return;
4564
4742
  }
@@ -4591,17 +4769,30 @@ var createUppyRoutes = async (app, config) => {
4591
4769
  res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
4592
4770
  return;
4593
4771
  }
4594
- let { key } = req.body;
4772
+ let { key } = req.body ?? {};
4773
+ if (typeof key !== "string" || key.trim() === "") {
4774
+ res.status(400).json({ error: "Missing or invalid `key` in the request body." });
4775
+ return;
4776
+ }
4595
4777
  let bucket = key.split("/")[0];
4596
- if (!bucket || typeof bucket !== "string" || bucket.trim() === "") {
4778
+ if (!bucket || bucket.trim() === "") {
4597
4779
  res.status(400).json({
4598
4780
  error: "Missing or invalid `bucket` (should be the first part of the key before the first slash)."
4599
4781
  });
4600
4782
  return;
4601
4783
  }
4602
4784
  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." });
4785
+ if (!key || key.trim() === "") {
4786
+ res.status(400).json({ error: "Missing or invalid `key` in the request body." });
4787
+ return;
4788
+ }
4789
+ const user = authenticationResult.user;
4790
+ if (!mayUseGenericS3Route(key, user, config.fileUploads.s3prefix)) {
4791
+ res.status(403).json({ error: "Project files cannot be read through this route." });
4792
+ return;
4793
+ }
4794
+ if (!mayReadGenericS3Key(key, user, config.fileUploads?.s3prefix)) {
4795
+ res.status(403).json({ error: "Not allowed to access the file based on authenticated user." });
4605
4796
  return;
4606
4797
  }
4607
4798
  const client = getS3Client(config);
@@ -4609,9 +4800,23 @@ var createUppyRoutes = async (app, config) => {
4609
4800
  Bucket: bucket,
4610
4801
  Key: key
4611
4802
  });
4612
- const response = await client.send(command);
4613
- res.json(response);
4614
- res.end();
4803
+ let response;
4804
+ try {
4805
+ response = await client.send(command);
4806
+ } catch (err3) {
4807
+ if (err3?.name === "NotFound" || err3?.name === "NoSuchKey" || err3?.$metadata?.httpStatusCode === 404) {
4808
+ res.status(404).json({ error: "Object not found." });
4809
+ return;
4810
+ }
4811
+ throw err3;
4812
+ }
4813
+ res.json({
4814
+ ContentLength: response.ContentLength,
4815
+ ContentType: response.ContentType,
4816
+ LastModified: response.LastModified,
4817
+ ETag: response.ETag,
4818
+ Metadata: response.Metadata
4819
+ });
4615
4820
  });
4616
4821
  app.get("/s3/list", async (req, res) => {
4617
4822
  if (!config.fileUploads) {
@@ -4637,9 +4842,9 @@ var createUppyRoutes = async (app, config) => {
4637
4842
  const client = getS3Client(config);
4638
4843
  let prefix = `${config.fileUploads.s3prefix ? config.fileUploads.s3prefix.replace(/\/$/, "") + "/" : ""}`;
4639
4844
  if (!req.headers.global) {
4640
- prefix += `user_${authenticationResult.user.id}`;
4845
+ prefix += `user_${authenticationResult.user.id}/`;
4641
4846
  } else {
4642
- prefix += "global";
4847
+ prefix += "global/";
4643
4848
  }
4644
4849
  console.log("[EXULU] bucket", config.fileUploads.s3Bucket);
4645
4850
  console.log("[EXULU] prefix", prefix);
@@ -4694,10 +4899,28 @@ var createUppyRoutes = async (app, config) => {
4694
4899
  });
4695
4900
  res.end();
4696
4901
  });
4697
- app.get("/s3/sts", (req, res, next) => {
4902
+ app.get("/s3/sts", async (req, res, next) => {
4698
4903
  if (!config.fileUploads) {
4699
4904
  throw new Error("File uploads are not configured");
4700
4905
  }
4906
+ const apikey = req.headers["exulu-api-key"] || null;
4907
+ const internalkey = req.headers["internal-key"] || null;
4908
+ const { db } = await postgresClient();
4909
+ let authtoken = null;
4910
+ if (typeof apikey !== "string" && typeof internalkey !== "string") {
4911
+ authtoken = await getToken(req.headers.authorization ?? "");
4912
+ }
4913
+ const authenticationResult = await authentication({ authtoken, apikey, internalkey, db });
4914
+ if (!authenticationResult.user?.id) {
4915
+ res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
4916
+ return;
4917
+ }
4918
+ const user = authenticationResult.user;
4919
+ const policy = buildStsPolicy(
4920
+ config.fileUploads.s3Bucket,
4921
+ user.type === "api" ? "api" : user.id,
4922
+ config.fileUploads.s3prefix
4923
+ );
4701
4924
  getSTSClient().send(
4702
4925
  new GetFederationTokenCommand({
4703
4926
  Name: "Exulu",
@@ -4709,7 +4932,7 @@ var createUppyRoutes = async (app, config) => {
4709
4932
  })
4710
4933
  ).then((response) => {
4711
4934
  res.setHeader("Access-Control-Allow-Origin", "*");
4712
- res.setHeader("Cache-Control", `public,max-age=${expiresIn}`);
4935
+ res.setHeader("Cache-Control", `private,max-age=${expiresIn}`);
4713
4936
  res.json({
4714
4937
  credentials: response.Credentials,
4715
4938
  bucket: config.fileUploads?.s3Bucket,
@@ -4852,24 +5075,45 @@ var createUppyRoutes = async (app, config) => {
4852
5075
  });
4853
5076
  });
4854
5077
  });
5078
+ const authorizeMultipartKey = async (req, res) => {
5079
+ const apikey = req.headers["exulu-api-key"] || null;
5080
+ const { db } = await postgresClient();
5081
+ let authtoken = null;
5082
+ if (typeof apikey !== "string") {
5083
+ authtoken = await getToken(req.headers.authorization ?? "");
5084
+ }
5085
+ const authenticationResult = await authentication({ authtoken, apikey, db });
5086
+ if (!authenticationResult.user?.id) {
5087
+ res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
5088
+ return null;
5089
+ }
5090
+ const { key } = req.query;
5091
+ if (typeof key !== "string") {
5092
+ res.status(400).json({
5093
+ error: 's3: the object key must be passed as a query parameter. For example: "?key=abc.jpg"'
5094
+ });
5095
+ return null;
5096
+ }
5097
+ if (!multipartKeyBelongsTo(key, authenticationResult.user, config.fileUploads?.s3prefix)) {
5098
+ res.status(403).json({ error: "s3: this upload does not belong to the authenticated user." });
5099
+ return null;
5100
+ }
5101
+ return key;
5102
+ };
4855
5103
  function validatePartNumber(partNumber) {
4856
5104
  partNumber = Number(partNumber);
4857
5105
  return Number.isInteger(partNumber) && partNumber >= 1 && partNumber <= 1e4;
4858
5106
  }
4859
- app.get("/s3/multipart/:uploadId/:partNumber", (req, res, next) => {
5107
+ app.get("/s3/multipart/:uploadId/:partNumber", async (req, res, next) => {
4860
5108
  if (!config.fileUploads) {
4861
5109
  throw new Error("File uploads are not configured");
4862
5110
  }
4863
5111
  const { uploadId, partNumber } = req.params;
4864
- const { key } = req.query;
4865
5112
  if (!validatePartNumber(partNumber)) {
4866
5113
  return res.status(400).json({ error: "s3: the part number must be an integer between 1 and 10000." });
4867
5114
  }
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
- }
5115
+ const key = await authorizeMultipartKey(req, res);
5116
+ if (key === null) return;
4873
5117
  return getSignedUrl(
4874
5118
  getS3Client(config),
4875
5119
  new UploadPartCommand({
@@ -4885,16 +5129,12 @@ var createUppyRoutes = async (app, config) => {
4885
5129
  res.json({ url, expires: expiresIn });
4886
5130
  }, next);
4887
5131
  });
4888
- app.get("/s3/multipart/:uploadId", (req, res, next) => {
5132
+ app.get("/s3/multipart/:uploadId", async (req, res, next) => {
5133
+ const authorizedKey = await authorizeMultipartKey(req, res);
5134
+ if (authorizedKey === null) return;
5135
+ const key = authorizedKey;
4889
5136
  const client = getS3Client(config);
4890
5137
  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
5138
  const parts = [];
4899
5139
  function listPartsPage(startAt) {
4900
5140
  if (!config.fileUploads) {
@@ -4926,19 +5166,15 @@ var createUppyRoutes = async (app, config) => {
4926
5166
  function isValidPart(part) {
4927
5167
  return part && typeof part === "object" && Number(part.PartNumber) && typeof part.ETag === "string";
4928
5168
  }
4929
- app.post("/s3/multipart/:uploadId/complete", (req, res, next) => {
5169
+ app.post("/s3/multipart/:uploadId/complete", async (req, res, next) => {
4930
5170
  if (!config.fileUploads) {
4931
5171
  throw new Error("File uploads are not configured");
4932
5172
  }
5173
+ const key = await authorizeMultipartKey(req, res);
5174
+ if (key === null) return;
4933
5175
  const client = getS3Client(config);
4934
5176
  const { uploadId } = req.params;
4935
- const { key } = req.query;
4936
5177
  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
5178
  if (!Array.isArray(parts) || !parts.every(isValidPart)) {
4943
5179
  return res.status(400).json({ error: "s3: `parts` must be an array of {ETag, PartNumber} objects." });
4944
5180
  }
@@ -4964,18 +5200,14 @@ var createUppyRoutes = async (app, config) => {
4964
5200
  }
4965
5201
  );
4966
5202
  });
4967
- app.delete("/s3/multipart/:uploadId", (req, res, next) => {
5203
+ app.delete("/s3/multipart/:uploadId", async (req, res, next) => {
4968
5204
  if (!config.fileUploads) {
4969
5205
  throw new Error("File uploads are not configured");
4970
5206
  }
5207
+ const key = await authorizeMultipartKey(req, res);
5208
+ if (key === null) return;
4971
5209
  const client = getS3Client(config);
4972
5210
  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
5211
  return client.send(
4980
5212
  new AbortMultipartUploadCommand({
4981
5213
  Bucket: config.fileUploads.s3Bucket,
@@ -6167,14 +6399,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
6167
6399
  for (const row of rows) {
6168
6400
  const centered = new Float64Array(dims);
6169
6401
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
6170
- const z20 = new Float64Array(basis.length);
6402
+ const z21 = new Float64Array(basis.length);
6171
6403
  for (const [b, vec] of basis.entries()) {
6172
6404
  let dot = 0;
6173
6405
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
6174
- z20[b] = dot;
6406
+ z21[b] = dot;
6175
6407
  }
6176
6408
  for (const [b, target] of next.entries()) {
6177
- const scale = z20[b] ?? 0;
6409
+ const scale = z21[b] ?? 0;
6178
6410
  if (scale === 0) continue;
6179
6411
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
6180
6412
  }
@@ -6272,12 +6504,12 @@ function ridgeFit(Z, Y, lambda) {
6272
6504
  });
6273
6505
  return { map, intercept };
6274
6506
  }
6275
- function applyMap(z20, map, intercept) {
6507
+ function applyMap(z21, map, intercept) {
6276
6508
  const out = [];
6277
6509
  for (let j = 0; j < 3; j += 1) {
6278
6510
  let v = intercept[j] ?? 0;
6279
6511
  const row = map[j] ?? [];
6280
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z20[d] ?? 0);
6512
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z21[d] ?? 0);
6281
6513
  out.push(Number.isFinite(v) ? v : 0);
6282
6514
  }
6283
6515
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -6300,8 +6532,8 @@ function fitResidual(Z, Y, map, intercept) {
6300
6532
  for (let i = 0; i < Z.length; i += 1) {
6301
6533
  const zi = Z[i] ?? [];
6302
6534
  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]));
6535
+ const [x, y, z21] = applyMap(zi, map, intercept);
6536
+ total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z21 - finite(yi[2]));
6305
6537
  }
6306
6538
  return finite(total / Z.length);
6307
6539
  }
@@ -6441,8 +6673,8 @@ async function chunkCoordinates({
6441
6673
  }
6442
6674
  return null;
6443
6675
  }
6444
- const [x, y, z20] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6445
- return { x, y, z: z20 };
6676
+ const [x, y, z21] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6677
+ return { x, y, z: z21 };
6446
6678
  });
6447
6679
  } catch (e) {
6448
6680
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -6528,8 +6760,8 @@ var captureCodeEmbedder = (context) => {
6528
6760
  };
6529
6761
  var codeEmbedderFor = (context) => codeEmbedders.has(context) ? codeEmbedders.get(context) : context.embedder;
6530
6762
  var contextEmbedderInfoFor = async (context, deps = {}) => {
6531
- const resolve3 = deps.resolve ?? resolveContextEmbedder;
6532
- return resolve3({ id: context.id, embedder: codeEmbedderFor(context) });
6763
+ const resolve4 = deps.resolve ?? resolveContextEmbedder;
6764
+ return resolve4({ id: context.id, embedder: codeEmbedderFor(context) });
6533
6765
  };
6534
6766
  var willEmbedOnQueue = async (context, overrideQueue) => {
6535
6767
  if (overrideQueue) {
@@ -6538,11 +6770,11 @@ var willEmbedOnQueue = async (context, overrideQueue) => {
6538
6770
  return Boolean(await codeEmbedderFor(context)?.queue);
6539
6771
  };
6540
6772
  var hydrateContextEmbedders = async (contexts, deps = {}) => {
6541
- const { resolve: resolve3, modelInfo, queues } = { ...defaultDeps(), ...deps };
6773
+ const { resolve: resolve4, modelInfo, queues } = { ...defaultDeps(), ...deps };
6542
6774
  for (const context of contexts) {
6543
6775
  try {
6544
6776
  const codeEmbedder = captureCodeEmbedder(context);
6545
- const info = await resolve3({ id: context.id, embedder: codeEmbedder });
6777
+ const info = await resolve4({ id: context.id, embedder: codeEmbedder });
6546
6778
  if (info.source !== "database" || !info.databaseModel) {
6547
6779
  context.embedder = codeEmbedder;
6548
6780
  continue;
@@ -11416,19 +11648,6 @@ function collectMemoryDecisions(messages) {
11416
11648
  import { z as z13 } from "zod";
11417
11649
  import { randomUUID as randomUUID3 } from "crypto";
11418
11650
 
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
11651
  // src/utils/check-item-write-access.ts
11433
11652
  var checkItemWriteAccess = async (context, record, user) => {
11434
11653
  if (!user) {
@@ -12311,86 +12530,644 @@ var collectKbWriteTools = (agent, contexts, deps = {}) => {
12311
12530
  return tools;
12312
12531
  };
12313
12532
 
12314
- // src/templates/tools/skill-author-tools.ts
12315
- import { randomUUID as randomUUID4 } from "crypto";
12533
+ // src/templates/tools/save-to-project-tool.ts
12316
12534
  import { z as z14 } from "zod";
12317
12535
 
12318
- // ee/rbac-resolver.ts
12319
- var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
12320
- const license = checkLicense();
12321
- if (!license.rbac) {
12322
- return {
12323
- type: "public",
12324
- users: [],
12325
- roles: [],
12326
- teams: []
12327
- };
12536
+ // src/exulu/shared-artifacts.ts
12537
+ import bcrypt2 from "bcryptjs";
12538
+ var normalizeS3Key = (key, bucket) => {
12539
+ const segments = key.split("/").filter((s, i) => !(i === 0 && s === "")).map((s) => decodeURIComponent(s));
12540
+ if (segments[0] === bucket) segments.shift();
12541
+ return segments.join("/");
12542
+ };
12543
+ var isHtmlKey = (key) => /\.html?$/i.test(key);
12544
+ var deriveFilename = (key) => {
12545
+ const base = key.split("/").pop() ?? key;
12546
+ return base.split("_EXULU_").pop() ?? base;
12547
+ };
12548
+ var slugifyShareName = (input) => deriveFilename(input).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
12549
+ var isExpired = (expiresAt, now) => {
12550
+ if (!expiresAt) return false;
12551
+ return new Date(expiresAt).getTime() <= now.getTime();
12552
+ };
12553
+ var validateCreateInput = (input, now) => {
12554
+ if (!input.s3key) return { ok: false, message: "s3key is required." };
12555
+ if (!input.name) return { ok: false, message: "name is required." };
12556
+ const mode = input.auth_mode;
12557
+ if (mode !== "public" && mode !== "password" && mode !== "regular") {
12558
+ return { ok: false, message: "auth_mode must be public, password, or regular." };
12328
12559
  }
12329
- const rbacRecords = await db.from("rbac").where({
12330
- entity: entityName,
12331
- target_resource_id: resourceId
12332
- }).select("*");
12333
- const users = rbacRecords.filter((r) => r.access_type === "User")?.map((r) => ({ id: r.user_id, rights: r.rights }));
12334
- const roles = rbacRecords.filter((r) => r.access_type === "Role")?.map((r) => ({ id: r.role_id, rights: r.rights }));
12335
- const teams = rbacRecords.filter((r) => r.access_type === "Team")?.map((r) => ({ id: r.team_id, rights: r.rights }));
12336
- let type = rights_mode || "private";
12337
- if (type === "users" && users.length === 0) type = "private";
12338
- if (type === "roles" && roles.length === 0) type = "private";
12339
- if (type === "teams" && teams.length === 0) type = "private";
12340
- return {
12341
- type,
12342
- users,
12343
- roles,
12344
- teams
12345
- };
12560
+ if (mode === "password" && !input.password) {
12561
+ return { ok: false, message: "A password is required for password mode." };
12562
+ }
12563
+ if (input.expires_at && Number.isNaN(new Date(input.expires_at).getTime())) {
12564
+ return { ok: false, message: "expires_at is not a valid date." };
12565
+ }
12566
+ if (input.expires_at && isExpired(input.expires_at, now)) {
12567
+ return { ok: false, message: "expires_at must be in the future." };
12568
+ }
12569
+ return { ok: true };
12346
12570
  };
12347
-
12348
- // src/skills/skill-access.ts
12349
- async function resolveSkillByName(db, name) {
12350
- const row = await db("skills").where({ name }).first();
12351
- return row ?? null;
12352
- }
12353
- async function canAccessSkill(db, skill, action, user) {
12354
- const rbac = await RBACResolver(db, "skill", skill.id, skill.rights_mode || "private");
12355
- return checkRecordAccess({ ...skill, RBAC: rbac }, action, user);
12356
- }
12357
- async function filterReadableSkills(db, skills, user) {
12358
- const out = [];
12359
- for (const s of skills) {
12360
- if (await canAccessSkill(db, s, "read", user)) out.push(s);
12571
+ var validateAgentSlots = (value) => {
12572
+ if (!Array.isArray(value)) {
12573
+ return { ok: false, message: "agent_slots must be an array." };
12361
12574
  }
12362
- return out;
12363
- }
12364
-
12365
- // src/skills/frontmatter.ts
12366
- import JSZip from "jszip";
12367
- function parseFrontmatter(md) {
12368
- const match = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(md);
12369
- if (!match) return {};
12370
- const block = match[1];
12371
- const out = {};
12372
- for (const line of block.split(/\r?\n/)) {
12373
- const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
12374
- if (!m) continue;
12375
- const key = m[1];
12376
- let v = m[2].trim();
12377
- if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) {
12378
- v = v.slice(1, -1);
12575
+ const slots = [];
12576
+ const seenKeys = /* @__PURE__ */ new Set();
12577
+ for (const entry of value) {
12578
+ if (typeof entry !== "object" || entry === null) {
12579
+ return { ok: false, message: "Each agent slot must be an object." };
12379
12580
  }
12380
- out[key] = v;
12581
+ const { key, agentId } = entry;
12582
+ if (typeof key !== "string" || !key.trim()) {
12583
+ return { ok: false, message: "Each agent slot needs a non-empty key." };
12584
+ }
12585
+ if (typeof agentId !== "string" || !agentId.trim()) {
12586
+ return { ok: false, message: "Each agent slot needs a non-empty agentId." };
12587
+ }
12588
+ const trimmedKey = key.trim();
12589
+ if (seenKeys.has(trimmedKey)) {
12590
+ return { ok: false, message: "agent_slots keys must be unique." };
12591
+ }
12592
+ seenKeys.add(trimmedKey);
12593
+ slots.push({ key: trimmedKey, agentId });
12381
12594
  }
12382
- return out;
12383
- }
12384
- async function parseSkillFrontmatter(zipBytes) {
12385
- let zip;
12386
- try {
12387
- zip = await JSZip.loadAsync(zipBytes);
12388
- } catch {
12389
- return {};
12595
+ return { ok: true, slots };
12596
+ };
12597
+ var readAgentSlots = (value) => {
12598
+ const parsed = typeof value === "string" ? (() => {
12599
+ try {
12600
+ return JSON.parse(value);
12601
+ } catch {
12602
+ return null;
12603
+ }
12604
+ })() : value;
12605
+ return Array.isArray(parsed) ? parsed : [];
12606
+ };
12607
+ var RIGHTS_MODES = /* @__PURE__ */ new Set(["private", "users", "roles", "teams", "public"]);
12608
+ var canManageShare = (row, user) => user.super_admin === true || row.created_by != null && String(row.created_by) === String(user.id);
12609
+ var validateUpdateInput = (input, row, now) => {
12610
+ if (input.name !== void 0 && !slugifyShareName(input.name)) {
12611
+ return { ok: false, message: "name must contain url-safe characters." };
12390
12612
  }
12391
- const paths = [];
12392
- zip.forEach((p, entry) => {
12393
- if (!entry.dir) paths.push(p);
12613
+ const mode = input.auth_mode ?? row.auth_mode;
12614
+ if (mode !== "public" && mode !== "password" && mode !== "regular") {
12615
+ return { ok: false, message: "auth_mode must be public, password, or regular." };
12616
+ }
12617
+ const keepsPassword = row.auth_mode === "password" && !!row.password_hash;
12618
+ if (mode === "password" && !input.password && !keepsPassword) {
12619
+ return { ok: false, message: "A password is required for password mode." };
12620
+ }
12621
+ if (input.expires_at && Number.isNaN(new Date(input.expires_at).getTime())) {
12622
+ return { ok: false, message: "expires_at is not a valid date." };
12623
+ }
12624
+ if (input.expires_at && isExpired(input.expires_at, now)) {
12625
+ return { ok: false, message: "expires_at must be in the future." };
12626
+ }
12627
+ if (input.rights_mode !== void 0 && !RIGHTS_MODES.has(input.rights_mode)) {
12628
+ return { ok: false, message: "rights_mode must be private, users, roles, teams, or public." };
12629
+ }
12630
+ if (input.s3key !== void 0 && (typeof input.s3key !== "string" || !input.s3key.trim())) {
12631
+ return { ok: false, message: "s3key must be a non-empty string." };
12632
+ }
12633
+ if (input.agent_slots !== void 0) {
12634
+ const slotsResult = validateAgentSlots(input.agent_slots);
12635
+ if (!slotsResult.ok) return { ok: false, message: slotsResult.message };
12636
+ }
12637
+ return { ok: true };
12638
+ };
12639
+ var ownsObjectKey = (key, user, s3prefix) => {
12640
+ if (user.super_admin === true) return true;
12641
+ let k = key.replace(/^\/+/, "");
12642
+ const prefix = (s3prefix ?? "").replace(/\/+$/, "");
12643
+ if (prefix && k.startsWith(prefix + "/")) k = k.slice(prefix.length + 1);
12644
+ const owner = user.type === "api" ? "api" : String(user.id);
12645
+ return k.startsWith(`user_${owner}/`);
12646
+ };
12647
+ var planShareUpdate = (input, row, newPasswordHash, now) => {
12648
+ const mode = input.auth_mode ?? row.auth_mode;
12649
+ const patch = { auth_mode: mode, updatedAt: now };
12650
+ if (input.name !== void 0) patch.name = slugifyShareName(input.name);
12651
+ if (input.s3key !== void 0) patch.s3key = input.s3key;
12652
+ if (input.content_type !== void 0) patch.content_type = input.content_type;
12653
+ patch.password_hash = mode === "password" ? newPasswordHash ?? row.password_hash : null;
12654
+ if (input.expires_at !== void 0) patch.expires_at = input.expires_at;
12655
+ if (mode === "regular") {
12656
+ patch.rights_mode = input.rights_mode ?? (row.auth_mode === "regular" ? row.rights_mode ?? "private" : "private");
12657
+ } else {
12658
+ patch.rights_mode = "public";
12659
+ }
12660
+ if (input.agent_slots !== void 0) {
12661
+ const slotsResult = validateAgentSlots(input.agent_slots);
12662
+ if (slotsResult.ok) patch.agent_slots = slotsResult.slots;
12663
+ }
12664
+ return patch;
12665
+ };
12666
+ var hashSharePassword = (password) => bcrypt2.hash(password, 10);
12667
+ var verifySharePassword = (password, hash) => bcrypt2.compare(password, hash);
12668
+ var contentHeadersFor = (key, contentType, filename) => {
12669
+ if (isHtmlKey(key)) return { contentType: "text/html; charset=utf-8" };
12670
+ return {
12671
+ contentType: contentType || "application/octet-stream",
12672
+ disposition: `attachment; filename="${filename.replace(/"/g, "")}"`
12673
+ };
12674
+ };
12675
+ var publicMetaFor = (row) => ({
12676
+ auth_mode: row.auth_mode,
12677
+ expires_at: row.expires_at ?? null,
12678
+ filename: deriveFilename(row.s3key),
12679
+ content_type: row.content_type ?? null,
12680
+ is_html: isHtmlKey(row.s3key)
12681
+ });
12682
+ var getSharedArtifactByName = (db, name) => db("shared_artifacts").where({ name }).first();
12683
+
12684
+ // src/exulu/session-file-adopt.ts
12685
+ var MAX_ADOPT_KEYS = 20;
12686
+ var MAX_ADOPT_UPLOAD_BYTES = 50 * 1024 * 1024;
12687
+ var ownsAdoptKey = (key, user, s3prefix) => {
12688
+ const prefix = (s3prefix ?? "").replace(/\/+$/, "");
12689
+ const stripped = prefix && key.startsWith(`${prefix}/`) ? key.slice(prefix.length + 1) : key;
12690
+ const owner = user.type === "api" ? "api" : String(user.id);
12691
+ return stripped.startsWith(`user_${owner}/`);
12692
+ };
12693
+ var planAdoptKeys = (keys, user, s3prefix, bucket) => {
12694
+ if (!Array.isArray(keys)) {
12695
+ return { accepted: [], rejected: [] };
12696
+ }
12697
+ if (keys.length > MAX_ADOPT_KEYS) {
12698
+ return {
12699
+ accepted: [],
12700
+ rejected: keys.map((k) => ({
12701
+ key: typeof k === "string" ? k : String(k),
12702
+ reason: `Batch exceeds the ${MAX_ADOPT_KEYS}-key adopt limit.`
12703
+ }))
12704
+ };
12705
+ }
12706
+ const accepted = [];
12707
+ const rejected = [];
12708
+ const filenameOwners = /* @__PURE__ */ new Map();
12709
+ for (const raw of keys) {
12710
+ if (typeof raw !== "string" || !raw.trim()) {
12711
+ rejected.push({
12712
+ key: typeof raw === "string" ? raw : String(raw),
12713
+ reason: "Key must be a non-empty string."
12714
+ });
12715
+ continue;
12716
+ }
12717
+ let normalized;
12718
+ try {
12719
+ normalized = normalizeS3Key(raw, bucket).replace(/^\/+/, "");
12720
+ } catch {
12721
+ rejected.push({ key: raw, reason: "Key is not a valid S3 key." });
12722
+ continue;
12723
+ }
12724
+ if (normalized.includes("..")) {
12725
+ rejected.push({ key: raw, reason: "Key contains a path traversal segment." });
12726
+ continue;
12727
+ }
12728
+ if (!ownsAdoptKey(normalized, user, s3prefix)) {
12729
+ rejected.push({ key: raw, reason: "You do not own this object." });
12730
+ continue;
12731
+ }
12732
+ const filename = sanitizeFilename(deriveFilename(normalized));
12733
+ if (!filename) {
12734
+ rejected.push({ key: raw, reason: "Could not derive a safe filename." });
12735
+ continue;
12736
+ }
12737
+ if (filenameOwners.has(filename)) {
12738
+ const existing = filenameOwners.get(filename);
12739
+ if (existing) {
12740
+ const idx = accepted.indexOf(existing);
12741
+ if (idx !== -1) accepted.splice(idx, 1);
12742
+ rejected.push({ key: existing.key, reason: "Filename collides with another key in this batch." });
12743
+ filenameOwners.set(filename, null);
12744
+ }
12745
+ rejected.push({ key: raw, reason: "Filename collides with another key in this batch." });
12746
+ continue;
12747
+ }
12748
+ const entry = { source: normalized, filename, key: raw };
12749
+ accepted.push(entry);
12750
+ filenameOwners.set(filename, entry);
12751
+ }
12752
+ return { accepted, rejected };
12753
+ };
12754
+ var planAdoptSizeCheck = (checks, maxBytes) => {
12755
+ const rejected = [];
12756
+ for (const { entry, size } of checks) {
12757
+ if (size === null) {
12758
+ rejected.push({ key: entry.key, reason: "Source object not found." });
12759
+ } else if (size > maxBytes) {
12760
+ rejected.push({
12761
+ key: entry.key,
12762
+ reason: `File exceeds the ${Math.floor(maxBytes / (1024 * 1024))}MB upload limit.`
12763
+ });
12764
+ }
12765
+ }
12766
+ if (rejected.length > 0) return { proceed: false, rejected };
12767
+ return { proceed: true };
12768
+ };
12769
+
12770
+ // src/exulu/project-files-promote.ts
12771
+ var COPY_FAILED_REASON = "Copying the file into the project failed.";
12772
+ async function promoteSessionFiles(args) {
12773
+ const { projectPrefix, fullProjectPrefix } = projectFilePrefix(args.projectId, args.s3prefix);
12774
+ const existingNames = await args.s3.listProjectNames(projectPrefix);
12775
+ const plan = planPromote({
12776
+ keys: args.keys,
12777
+ fullSessionPrefix: args.fullSessionPrefix,
12778
+ fullProjectPrefix,
12779
+ existingNames,
12780
+ overwrite: args.overwrite
12781
+ });
12782
+ const rejected = [...plan.rejected];
12783
+ if (plan.clashes.length > 0 || plan.accepted.length === 0) {
12784
+ return { promoted: [], rejected, clashes: plan.clashes };
12785
+ }
12786
+ const sizes = [];
12787
+ for (const a of plan.accepted) sizes.push({ key: a.sourceKey, size: await args.s3.sizeOf(a.sourceKey) });
12788
+ const perFile = planAdoptSizeCheck(
12789
+ plan.accepted.map((a, i) => ({
12790
+ entry: { key: a.sourceKey, source: a.sourceKey, filename: a.name },
12791
+ size: sizes[i].size
12792
+ })),
12793
+ MAX_ADOPT_UPLOAD_BYTES
12794
+ );
12795
+ const total = sizes.reduce((sum, s) => sum + (s.size ?? 0), 0);
12796
+ if (!perFile.proceed || total > MAX_ADOPT_UPLOAD_BYTES) {
12797
+ const reasons = !perFile.proceed ? perFile.rejected : [];
12798
+ const byKey = new Map(reasons.map((r) => [r.key, r.reason]));
12799
+ for (const a of plan.accepted) {
12800
+ rejected.push({
12801
+ key: a.sourceKey,
12802
+ reason: byKey.get(a.sourceKey) ?? "The batch exceeds the 50MB total limit."
12803
+ });
12804
+ }
12805
+ return { promoted: [], rejected, clashes: [] };
12806
+ }
12807
+ const promoted = [];
12808
+ for (const a of plan.accepted) {
12809
+ try {
12810
+ await args.s3.copy(a.sourceKey, a.destKey);
12811
+ promoted.push({ key: a.destKey, name: a.name });
12812
+ } catch (err3) {
12813
+ console.error("[PROJECT-FILES] copy failed", a.sourceKey, err3);
12814
+ rejected.push({ key: a.sourceKey, reason: COPY_FAILED_REASON });
12815
+ }
12816
+ }
12817
+ return { promoted, rejected, clashes: [] };
12818
+ }
12819
+
12820
+ // ee/invoke-skills/artifact-filter.ts
12821
+ var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
12822
+ "venv",
12823
+ ".venv",
12824
+ "env",
12825
+ "node_modules",
12826
+ "__pycache__",
12827
+ "site-packages",
12828
+ "dist-packages",
12829
+ ".cache",
12830
+ ".git",
12831
+ ".pytest_cache",
12832
+ ".mypy_cache",
12833
+ ".ipynb_checkpoints"
12834
+ ]);
12835
+ function isIgnoredArtifactPath(relativePath) {
12836
+ return relativePath.split(/[\\/]+/).some((segment) => IGNORED_SEGMENTS.has(segment));
12837
+ }
12838
+ var DEFAULT_ARTIFACT_CAP = 50;
12839
+ function capArtifacts(artifacts, max = DEFAULT_ARTIFACT_CAP) {
12840
+ if (artifacts.length <= max) return { kept: artifacts, omitted: 0 };
12841
+ return { kept: artifacts.slice(0, max), omitted: artifacts.length - max };
12842
+ }
12843
+ function needsDownload(localSize, remoteSize) {
12844
+ return localSize === void 0 || localSize !== remoteSize;
12845
+ }
12846
+
12847
+ // src/exulu/session-file-listing.ts
12848
+ var DEFAULT_MAX = 25;
12849
+ function formatSize(bytes) {
12850
+ if (bytes < 1024) return `${bytes} B`;
12851
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
12852
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
12853
+ }
12854
+ function formatAge(then, now) {
12855
+ const minutes = Math.max(0, Math.round((now.getTime() - then.getTime()) / 6e4));
12856
+ if (minutes < 1) return "just now";
12857
+ if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
12858
+ const hours = Math.round(minutes / 60);
12859
+ if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
12860
+ const days = Math.round(hours / 24);
12861
+ return `${days} day${days === 1 ? "" : "s"} ago`;
12862
+ }
12863
+ function describeSessionFiles(files, opts = {}) {
12864
+ const now = opts.now ?? /* @__PURE__ */ new Date();
12865
+ const max = opts.max ?? DEFAULT_MAX;
12866
+ const usable = files.filter((f) => f.name && !f.name.endsWith("/") && !isIgnoredArtifactPath(f.name)).sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
12867
+ if (usable.length === 0) return "";
12868
+ const shown = usable.slice(0, max);
12869
+ const lines = shown.map((f) => {
12870
+ const isNew = opts.lastTurnAt ? f.lastModified.getTime() > opts.lastTurnAt.getTime() : false;
12871
+ return `- ${f.name} (${formatSize(f.size)}, ${formatAge(f.lastModified, now)})${isNew ? " [NEW since your last answer]" : ""}`;
12872
+ });
12873
+ const omitted = usable.length - shown.length;
12874
+ if (omitted > 0) lines.push(`\u2026 and ${omitted} more file${omitted === 1 ? "" : "s"} (list them with \`ls\`).`);
12875
+ 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.';
12876
+ }
12877
+ function listingLines(files, opts) {
12878
+ const now = opts.now ?? /* @__PURE__ */ new Date();
12879
+ const max = opts.max ?? DEFAULT_MAX;
12880
+ const usable = files.filter((f) => f.name && !f.name.endsWith("/") && !isIgnoredArtifactPath(f.name)).sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
12881
+ const shown = usable.slice(0, max);
12882
+ const lines = shown.map((f) => {
12883
+ const isNew = opts.lastTurnAt ? f.lastModified.getTime() > opts.lastTurnAt.getTime() : false;
12884
+ return `- ${f.name} (${formatSize(f.size)}, ${formatAge(f.lastModified, now)})${isNew ? " [NEW since your last answer]" : ""}`;
12885
+ });
12886
+ return { lines, omitted: usable.length - shown.length, total: usable.length };
12887
+ }
12888
+ var MAX_PROMPT_NAME = 80;
12889
+ function promptSafeProjectName(name) {
12890
+ return name.replace(/\s+/g, " ").trim().slice(0, MAX_PROMPT_NAME);
12891
+ }
12892
+ function describeProjectFiles(files, projectName, opts = {}) {
12893
+ const { lines, omitted, total } = listingLines(files, opts);
12894
+ if (total === 0) return "";
12895
+ if (omitted > 0) lines.push(`+${omitted} more (list them with \`ls project/\`).`);
12896
+ const name = promptSafeProjectName(projectName);
12897
+ return `Project files (shared with everyone on project ${name}):
12898
+ ` + lines.join("\n") + `
12899
+ Read them by passing \`${PROJECT_DIR}/<name>\` as the filename to parse_document, view_document_page or read_session_file. They are read-only.`;
12900
+ }
12901
+ function sessionFilesScopeSentence(projectName, canSaveToProject = false) {
12902
+ if (!projectName) {
12903
+ return "These files are scoped to\n this single session; they are NOT visible in other sessions, projects, or knowledge bases.";
12904
+ }
12905
+ const name = promptSafeProjectName(projectName);
12906
+ const route = canSaveToProject ? "A session file gets into the project with the save_to_project tool (the user approves each save) or by the user in the sidebar." : "You cannot add files to the project: only someone with write access can, by adding a session file to it in the sidebar.";
12907
+ return `Files you see by their plain name are private to this session. Project files are shared with everyone on project ${name} and appear under \`${PROJECT_DIR}/\`; they are read-only for you \u2014 do not write into \`${PROJECT_DIR}/\`, changes there are discarded. ` + route;
12908
+ }
12909
+ async function loadSessionFileListing(opts) {
12910
+ const uploads = opts.exuluConfig?.fileUploads;
12911
+ if (!uploads?.s3Bucket) return "";
12912
+ const prefix = sessionFilePrefix(opts.ownerId, opts.sessionID, uploads.s3prefix);
12913
+ let sessionBlock = "";
12914
+ try {
12915
+ const objects = await listS3ObjectsByPrefix(prefix, opts.exuluConfig);
12916
+ const files = objects.map((o) => ({
12917
+ name: o.key.slice(o.key.indexOf(prefix) + prefix.length),
12918
+ size: o.size,
12919
+ lastModified: new Date(o.lastModified)
12920
+ }));
12921
+ sessionBlock = describeSessionFiles(files, { lastTurnAt: opts.lastTurnAt });
12922
+ } catch (err3) {
12923
+ console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`, err3);
12924
+ }
12925
+ if (!opts.project) return sessionBlock;
12926
+ let projectBlock = "";
12927
+ try {
12928
+ const { projectPrefix } = projectFilePrefix(opts.project.id);
12929
+ const objects = await listS3ObjectsByPrefix(projectPrefix, opts.exuluConfig);
12930
+ const files = objects.map((o) => ({
12931
+ name: o.key.slice(o.key.indexOf(projectPrefix) + projectPrefix.length),
12932
+ size: o.size,
12933
+ lastModified: new Date(o.lastModified)
12934
+ }));
12935
+ projectBlock = describeProjectFiles(
12936
+ files.filter((f) => !f.name.includes("/")),
12937
+ opts.project.name,
12938
+ { lastTurnAt: opts.lastTurnAt }
12939
+ );
12940
+ } catch (err3) {
12941
+ console.warn(`[EXULU] could not list project files for prompt (session ${opts.sessionID}):`, err3);
12942
+ }
12943
+ return [sessionBlock, projectBlock].filter(Boolean).join("\n\n");
12944
+ }
12945
+
12946
+ // src/exulu/file-origin.ts
12947
+ var ORIGIN_METADATA_KEY = "exulu-origin";
12948
+ function originFromMetadata(metadata) {
12949
+ return metadata?.[ORIGIN_METADATA_KEY] === "agent" ? "agent" : "user";
12950
+ }
12951
+ function createOriginResolver(head) {
12952
+ const cache2 = /* @__PURE__ */ new Map();
12953
+ return async (file) => {
12954
+ const stamp = file.lastModified instanceof Date ? file.lastModified.toISOString() : String(file.lastModified);
12955
+ const id = `${file.key}\0${stamp}`;
12956
+ const hit = cache2.get(id);
12957
+ if (hit) return hit;
12958
+ try {
12959
+ const origin = originFromMetadata(await head(file.key));
12960
+ cache2.set(id, origin);
12961
+ return origin;
12962
+ } catch {
12963
+ return "user";
12964
+ }
12965
+ };
12966
+ }
12967
+
12968
+ // src/exulu/project-files-s3.ts
12969
+ var resolvers = /* @__PURE__ */ new WeakMap();
12970
+ function getOriginResolver(config) {
12971
+ let r = resolvers.get(config);
12972
+ if (!r) {
12973
+ r = createOriginResolver((key) => getS3ObjectMetadataStrict(key, config));
12974
+ resolvers.set(config, r);
12975
+ }
12976
+ return r;
12977
+ }
12978
+ function createPromoteS3(config) {
12979
+ return {
12980
+ listProjectNames: async (projectPrefix) => (await listS3ObjectsByPrefix(projectPrefix, config)).filter((o) => !o.key.endsWith("/")).map((o) => o.key.split("/").pop() ?? o.key),
12981
+ sizeOf: (key) => getS3ObjectSize(key, config),
12982
+ copy: (src, dest) => copyS3Object(src, dest, config)
12983
+ };
12984
+ }
12985
+
12986
+ // src/templates/tools/save-to-project-tool.ts
12987
+ var SAVE_TO_PROJECT_TOOL_NAME = "save_to_project";
12988
+ var SAVE_TO_PROJECT_TOOL_ID = "save_to_project";
12989
+ function canRegisterSaveToProject(args) {
12990
+ if (!args.sessionID || !args.exuluConfig?.fileUploads?.s3Bucket) return false;
12991
+ if (!args.project?.speakerCanWrite) return false;
12992
+ if (treatAsGuest(args.req, args.user)) return false;
12993
+ const disabled = args.disabled instanceof Set ? args.disabled : new Set(args.disabled ?? []);
12994
+ return !disabled.has(SAVE_TO_PROJECT_TOOL_ID);
12995
+ }
12996
+ var createSaveToProjectTool = ({
12997
+ sessionID,
12998
+ user,
12999
+ req,
13000
+ exuluConfig,
13001
+ ownerId,
13002
+ project,
13003
+ disabled,
13004
+ deps
13005
+ }) => {
13006
+ if (!canRegisterSaveToProject({ sessionID, exuluConfig, project, req, user, disabled })) return void 0;
13007
+ if (!sessionID || !exuluConfig || !project) return void 0;
13008
+ const uploads = exuluConfig.fileUploads;
13009
+ if (!uploads) return void 0;
13010
+ const projectLabel = promptSafeProjectName(project.name);
13011
+ const resolvedDeps = deps ?? {
13012
+ promote: promoteSessionFiles,
13013
+ s3: createPromoteS3(exuluConfig),
13014
+ projectModified: async (name) => {
13015
+ const { projectPrefix } = projectFilePrefix(project.id, uploads.s3prefix);
13016
+ const objects = await listS3ObjectsByPrefix(projectPrefix, exuluConfig);
13017
+ const hit = objects.find((o) => o.key.split("/").pop() === name);
13018
+ return hit ? new Date(hit.lastModified) : void 0;
13019
+ }
13020
+ };
13021
+ const execute = async ({ filename, overwrite }) => {
13022
+ const name = String(filename ?? "").trim();
13023
+ if (name.startsWith(`${PROJECT_DIR}/`)) {
13024
+ return {
13025
+ result: `"${name}" is already in the project. Pass the name of a session file, without the "${PROJECT_DIR}/" prefix.`
13026
+ };
13027
+ }
13028
+ if (!name || name.includes("/") || name.includes("\\") || name.includes("..")) {
13029
+ return {
13030
+ result: "Invalid filename. Pass the bare name of a session file, exactly as listed (session files are flat: no paths, no '..')."
13031
+ };
13032
+ }
13033
+ const ownerPrefix = sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix);
13034
+ let outcome;
13035
+ try {
13036
+ outcome = await resolvedDeps.promote({
13037
+ projectId: project.id,
13038
+ s3prefix: uploads.s3prefix,
13039
+ keys: [`${ownerPrefix}${name}`],
13040
+ fullSessionPrefix: ownerPrefix,
13041
+ overwrite: overwrite === true,
13042
+ s3: resolvedDeps.s3
13043
+ });
13044
+ } catch (err3) {
13045
+ console.error("[PROJECT-FILES] save_to_project failed", err3);
13046
+ return { result: "Saving to the project failed. Try again; if it keeps failing, tell the user." };
13047
+ }
13048
+ if (outcome.promoted.length > 0) {
13049
+ return {
13050
+ result: `Saved "${name}" to project ${projectLabel}. It will be visible to you as ${PROJECT_DIR}/${name} from the next turn.`
13051
+ };
13052
+ }
13053
+ if (outcome.clashes.length > 0) {
13054
+ let changed = "";
13055
+ try {
13056
+ const at = await resolvedDeps.projectModified(name);
13057
+ if (at) changed = ` (changed ${at.toISOString().slice(0, 10)})`;
13058
+ } catch {
13059
+ }
13060
+ return {
13061
+ result: `"${name}" already exists in the project${changed}. Call again with overwrite: true only if the user confirms.`
13062
+ };
13063
+ }
13064
+ const reason = outcome.rejected[0]?.reason ?? "Unknown reason.";
13065
+ if (reason.includes(`at most ${MAX_PROJECT_FILES} files`)) {
13066
+ return { result: `The project already holds ${MAX_PROJECT_FILES} files.` };
13067
+ }
13068
+ if (reason.includes("not found")) {
13069
+ return { result: `No session file named "${name}".` };
13070
+ }
13071
+ return { result: `Could not save "${name}" to the project: ${reason}` };
13072
+ };
13073
+ return ExuluTool.internal({
13074
+ id: "save_to_project",
13075
+ name: SAVE_TO_PROJECT_TOOL_NAME,
13076
+ needsApproval: true,
13077
+ // Replacing a shared file always needs a fresh yes, "allow for this chat" or not.
13078
+ alwaysAskWhen: (input) => input?.overwrite === true,
13079
+ description: `Copy one file from this session's files into the project's shared folder (${projectLabel}), where everyone on the project can read it. The \`project/\` directory is read-only for you, so this is the only way to add a file to the project. Pass the bare name of the session file. If the name already exists in the project the call changes nothing and tells you; call again with overwrite: true only after the user has confirmed replacing it.`,
13080
+ inputSchema: z14.object({
13081
+ filename: z14.string().describe("Bare name of the session file to save, exactly as listed in the session files (no path)."),
13082
+ overwrite: z14.boolean().optional().describe("Replace a project file of the same name. Only set after the user confirmed.")
13083
+ }),
13084
+ type: "function",
13085
+ category: "session",
13086
+ config: [],
13087
+ execute
13088
+ });
13089
+ };
13090
+
13091
+ // src/templates/tools/skill-author-tools.ts
13092
+ import { randomUUID as randomUUID4 } from "crypto";
13093
+ import { z as z15 } from "zod";
13094
+
13095
+ // ee/rbac-resolver.ts
13096
+ var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
13097
+ const license = checkLicense();
13098
+ if (!license.rbac) {
13099
+ return {
13100
+ type: "public",
13101
+ users: [],
13102
+ roles: [],
13103
+ teams: []
13104
+ };
13105
+ }
13106
+ const rbacRecords = await db.from("rbac").where({
13107
+ entity: entityName,
13108
+ target_resource_id: resourceId
13109
+ }).select("*");
13110
+ const users = rbacRecords.filter((r) => r.access_type === "User")?.map((r) => ({ id: r.user_id, rights: r.rights }));
13111
+ const roles = rbacRecords.filter((r) => r.access_type === "Role")?.map((r) => ({ id: r.role_id, rights: r.rights }));
13112
+ const teams = rbacRecords.filter((r) => r.access_type === "Team")?.map((r) => ({ id: r.team_id, rights: r.rights }));
13113
+ let type = rights_mode || "private";
13114
+ if (type === "users" && users.length === 0) type = "private";
13115
+ if (type === "roles" && roles.length === 0) type = "private";
13116
+ if (type === "teams" && teams.length === 0) type = "private";
13117
+ return {
13118
+ type,
13119
+ users,
13120
+ roles,
13121
+ teams
13122
+ };
13123
+ };
13124
+
13125
+ // src/skills/skill-access.ts
13126
+ async function resolveSkillByName(db, name) {
13127
+ const row = await db("skills").where({ name }).first();
13128
+ return row ?? null;
13129
+ }
13130
+ async function canAccessSkill(db, skill, action, user) {
13131
+ const rbac = await RBACResolver(db, "skill", skill.id, skill.rights_mode || "private");
13132
+ return checkRecordAccess({ ...skill, RBAC: rbac }, action, user);
13133
+ }
13134
+ async function filterReadableSkills(db, skills, user) {
13135
+ const out = [];
13136
+ for (const s of skills) {
13137
+ if (await canAccessSkill(db, s, "read", user)) out.push(s);
13138
+ }
13139
+ return out;
13140
+ }
13141
+
13142
+ // src/skills/frontmatter.ts
13143
+ import JSZip from "jszip";
13144
+ function parseFrontmatter(md) {
13145
+ const match = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(md);
13146
+ if (!match) return {};
13147
+ const block = match[1];
13148
+ const out = {};
13149
+ for (const line of block.split(/\r?\n/)) {
13150
+ const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
13151
+ if (!m) continue;
13152
+ const key = m[1];
13153
+ let v = m[2].trim();
13154
+ if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) {
13155
+ v = v.slice(1, -1);
13156
+ }
13157
+ out[key] = v;
13158
+ }
13159
+ return out;
13160
+ }
13161
+ async function parseSkillFrontmatter(zipBytes) {
13162
+ let zip;
13163
+ try {
13164
+ zip = await JSZip.loadAsync(zipBytes);
13165
+ } catch {
13166
+ return {};
13167
+ }
13168
+ const paths = [];
13169
+ zip.forEach((p, entry) => {
13170
+ if (!entry.dir) paths.push(p);
12394
13171
  });
12395
13172
  const heads = new Set(paths.map((p) => p.split("/")[0]).filter(Boolean));
12396
13173
  let strip = (p) => p;
@@ -12493,8 +13270,8 @@ description: ${yamlString(description)}
12493
13270
 
12494
13271
  ${content.replace(/^\s+/, "")}`;
12495
13272
  };
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("/"));
13273
+ var generalPrefix2 = (config) => config?.fileUploads?.s3prefix ? `${String(config.fileUploads.s3prefix).replace(/\/+$/, "")}/` : "";
13274
+ var relativePaths = (keys, config, prefix) => keys.map((f) => f.key.replace(generalPrefix2(config) + prefix, "")).filter((p) => p && !p.endsWith("/"));
12498
13275
  async function resolveSkill(db, ref) {
12499
13276
  const value = String(ref ?? "").trim();
12500
13277
  if (!value) return null;
@@ -12533,7 +13310,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12533
13310
  config: [],
12534
13311
  needsApproval: false,
12535
13312
  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") }),
13313
+ inputSchema: z15.object({ query: z15.string().optional().describe("Optional substring to filter by name or description") }),
12537
13314
  execute: async (params) => {
12538
13315
  const { user } = params;
12539
13316
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -12559,9 +13336,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12559
13336
  config: [],
12560
13337
  needsApproval: false,
12561
13338
  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")
13339
+ inputSchema: z15.object({
13340
+ skill: z15.string().describe("The skill's name or id"),
13341
+ path: z15.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
12565
13342
  }),
12566
13343
  execute: async (params) => {
12567
13344
  const { user, exuluConfig } = params;
@@ -12577,7 +13354,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12577
13354
  const path3 = params.path ? safeSkillPath(params.path) : "SKILL.md";
12578
13355
  if (!path3) return err2(`"${params.path}" is not a valid path inside the skill.`);
12579
13356
  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);
13357
+ let content = await io.read(generalPrefix2(exuluConfig) + prefix + path3, exuluConfig);
12581
13358
  if (Buffer.byteLength(content, "utf8") > MAX_READ_BYTES) content = content.slice(0, MAX_READ_BYTES) + "\n\u2026(truncated)";
12582
13359
  return {
12583
13360
  type: "skill_read",
@@ -12606,10 +13383,10 @@ ${content}`
12606
13383
  needsApproval: !config.skipApproval,
12607
13384
  needsApprovalFn: approvalFn,
12608
13385
  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")
13386
+ inputSchema: z15.object({
13387
+ name: z15.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
13388
+ description: z15.string().describe("One line: what the skill does and when to use it"),
13389
+ files: z15.array(z15.object({ path: z15.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z15.string() })).min(1).describe("The skill's files; SKILL.md is required")
12613
13390
  }),
12614
13391
  execute: async (params) => {
12615
13392
  const { user, exuluConfig } = params;
@@ -12675,12 +13452,12 @@ ${content}`
12675
13452
  needsApproval: !config.skipApproval,
12676
13453
  needsApprovalFn: approvalFn,
12677
13454
  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'")
13455
+ inputSchema: z15.object({
13456
+ skill: z15.string().describe("The skill's name or id"),
13457
+ files: z15.array(z15.object({ path: z15.string(), content: z15.string() })).optional().describe("Files to add or replace, full content each"),
13458
+ deletePaths: z15.array(z15.string()).optional().describe("Paths to remove in the new version"),
13459
+ description: z15.string().optional().describe("A new one-line description, if it changed"),
13460
+ label: z15.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
12684
13461
  }),
12685
13462
  execute: async (params) => {
12686
13463
  const { user, exuluConfig } = params;
@@ -12712,7 +13489,7 @@ ${content}`
12712
13489
  const newVersion = currentVersion + 1;
12713
13490
  const currentPrefix = `skills/${skill.id}/v${currentVersion}/`;
12714
13491
  const newPrefix = `skills/${skill.id}/v${newVersion}/`;
12715
- const gp = generalPrefix(exuluConfig);
13492
+ const gp = generalPrefix2(exuluConfig);
12716
13493
  const existing = await io.list(currentPrefix, exuluConfig);
12717
13494
  const changedPaths = new Set(changes.map((f) => f.path));
12718
13495
  const removedSet = new Set(removals);
@@ -12757,7 +13534,7 @@ var createSkillAuthorPickerTool = () => new ExuluTool({
12757
13534
  category: "default",
12758
13535
  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
13536
  type: "function",
12760
- inputSchema: z14.object({}),
13537
+ inputSchema: z15.object({}),
12761
13538
  config: [
12762
13539
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
12763
13540
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -12774,38 +13551,11 @@ var collectSkillAuthorTools = (agent, deps = {}) => {
12774
13551
  import {
12775
13552
  SandboxManager
12776
13553
  } from "@anthropic-ai/sandbox-runtime";
12777
- import { mkdir, rm, writeFile, readFile as fsReadFile, readdir, stat } from "fs/promises";
13554
+ import { mkdir as mkdir3, rm as rm2, readdir as readdir2, stat, lstat as lstat3 } from "fs/promises";
12778
13555
  import { existsSync as existsSync4 } from "fs";
12779
- import { join as join2, dirname, resolve as resolve2, relative, posix } from "path";
13556
+ import { join as join4, dirname as dirname3, resolve as resolve3, relative, posix } from "path";
12780
13557
  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
- }
13558
+ import { promisify as promisify3 } from "util";
12809
13559
 
12810
13560
  // src/exulu/system-dependencies.ts
12811
13561
  import { exec } from "child_process";
@@ -13726,8 +14476,372 @@ var buildSkillSandboxEvent = (ctx, opts = {}) => {
13726
14476
  // ee/invoke-skills/create-sandbox.ts
13727
14477
  import { createBashTool } from "bash-tool";
13728
14478
  import { tool as tool2 } from "ai";
13729
- import { z as z15 } from "zod";
14479
+ import { z as z16 } from "zod";
13730
14480
  import CryptoJS3 from "crypto-js";
14481
+
14482
+ // ee/invoke-skills/project-sync.ts
14483
+ import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "fs/promises";
14484
+ import { randomBytes as randomBytes2 } from "crypto";
14485
+ import { basename, dirname, join as join2, resolve as resolve2, sep } from "path";
14486
+ import { execFile } from "child_process";
14487
+ import { promisify as promisify2 } from "util";
14488
+
14489
+ // src/exulu/project-access.ts
14490
+ var idOf = (v) => typeof v === "object" && v ? v.id : v;
14491
+ function hasProjectAccess(args) {
14492
+ const { project, rbac, user, want } = args;
14493
+ if (user.super_admin) return true;
14494
+ if (user.type === "api" && (!user.scope_mode || user.scope_mode === "admin")) return true;
14495
+ if (project.rights_mode === "public" || rbac.type === "public") return true;
14496
+ if (project.created_by != null && String(project.created_by) === String(user.id)) return true;
14497
+ const satisfies = (rights) => rights === "write" || rights === "read" && want === "read";
14498
+ const granted = (grants, subject) => subject != null && (grants ?? []).some((g) => String(g.id) === String(subject) && satisfies(g.rights));
14499
+ switch (rbac.type) {
14500
+ case "users":
14501
+ return granted(rbac.users, user.id);
14502
+ case "roles":
14503
+ return granted(rbac.roles, idOf(user.role));
14504
+ case "teams":
14505
+ return granted(rbac.teams, idOf(user.team));
14506
+ default:
14507
+ return false;
14508
+ }
14509
+ }
14510
+
14511
+ // ee/invoke-skills/project-sync.ts
14512
+ function planProjectSync(remote, local) {
14513
+ const localSizes = new Map(local.map((e) => [e.name, e.size]));
14514
+ const remoteNames = new Set(remote.map((e) => e.name));
14515
+ return {
14516
+ download: remote.filter((e) => localSizes.get(e.name) !== e.size).map((e) => e.name),
14517
+ remove: local.filter((e) => !remoteNames.has(e.name)).map((e) => e.name)
14518
+ };
14519
+ }
14520
+ function projectSyncMarkerPath(sessionDir) {
14521
+ return join2(dirname(sessionDir), ".project-sync", basename(sessionDir));
14522
+ }
14523
+ async function readMarker(sessionDir) {
14524
+ try {
14525
+ return (await readFile(projectSyncMarkerPath(sessionDir), "utf8")).trim() || null;
14526
+ } catch {
14527
+ return null;
14528
+ }
14529
+ }
14530
+ async function clearProjectSyncMarker(sessionDir) {
14531
+ await rm(projectSyncMarkerPath(sessionDir), { force: true });
14532
+ }
14533
+ var isFlatName = (name) => !!name && !name.includes("/") && !name.includes("\\") && name !== "." && name !== "..";
14534
+ var HELPER_KINDS = [".project-staging", ".project-trash"];
14535
+ var helperRoot = (sessionDir, kind) => join2(dirname(sessionDir), kind);
14536
+ var helperPath = (sessionDir, kind) => join2(helperRoot(sessionDir, kind), `${basename(sessionDir)}-${randomBytes2(8).toString("hex")}`);
14537
+ var execFileAsync = promisify2(execFile);
14538
+ async function removeTreeSafely(path3, sessionDir) {
14539
+ const target = resolve2(path3);
14540
+ const inside = HELPER_KINDS.some((kind) => {
14541
+ const root = resolve2(helperRoot(sessionDir, kind));
14542
+ return target.startsWith(root + sep) && !target.slice(root.length + 1).includes(sep);
14543
+ });
14544
+ if (!inside) {
14545
+ console.error(`[SKILLS] Refusing to remove ${path3}: not a project staging or trash directory.`);
14546
+ return false;
14547
+ }
14548
+ try {
14549
+ await execFileAsync("rm", ["-rf", "--", target]);
14550
+ return true;
14551
+ } catch (err3) {
14552
+ console.error(`[SKILLS] Failed to remove ${target}; leaving it for a later sweep.`, err3);
14553
+ return false;
14554
+ }
14555
+ }
14556
+ var DAY_MS = 24 * 60 * 60 * 1e3;
14557
+ async function sweepStaleHelpers(sessionDir) {
14558
+ const prefix = `${basename(sessionDir)}-`;
14559
+ for (const kind of HELPER_KINDS) {
14560
+ const root = helperRoot(sessionDir, kind);
14561
+ let names;
14562
+ try {
14563
+ names = await readdir(root);
14564
+ } catch {
14565
+ continue;
14566
+ }
14567
+ for (const name of names) {
14568
+ if (!name.startsWith(prefix)) continue;
14569
+ const st = await lstat(join2(root, name)).catch(() => null);
14570
+ if (st && Date.now() - st.mtimeMs > DAY_MS) await removeTreeSafely(join2(root, name), sessionDir);
14571
+ }
14572
+ }
14573
+ }
14574
+ var errCode = (err3) => err3?.code;
14575
+ async function moveAway(dir, sessionDir) {
14576
+ const trash = helperPath(sessionDir, ".project-trash");
14577
+ await mkdir(dirname(trash), { recursive: true });
14578
+ try {
14579
+ await rename(dir, trash);
14580
+ return trash;
14581
+ } catch (err3) {
14582
+ if (errCode(err3) === "ENOENT") return null;
14583
+ throw err3;
14584
+ }
14585
+ }
14586
+ async function discard(path3, sessionDir) {
14587
+ if (path3) await removeTreeSafely(path3, sessionDir);
14588
+ }
14589
+ async function discardEntry(path3, sessionDir) {
14590
+ await discard(await moveAway(path3, sessionDir), sessionDir);
14591
+ }
14592
+ async function syncProjectDir(args) {
14593
+ const { sessionDir, projectId, config } = args;
14594
+ const dir = join2(sessionDir, PROJECT_DIR);
14595
+ const previous = await readMarker(sessionDir);
14596
+ if (!projectId) {
14597
+ if (previous !== null) {
14598
+ await discard(await moveAway(dir, sessionDir), sessionDir);
14599
+ await clearProjectSyncMarker(sessionDir);
14600
+ }
14601
+ return;
14602
+ }
14603
+ if (!config.fileUploads) {
14604
+ console.warn(`[SKILLS] File uploads are not configured; project files are not synced into ${sessionDir}.`);
14605
+ return;
14606
+ }
14607
+ const { projectPrefix } = projectFilePrefix(projectId);
14608
+ const remote = /* @__PURE__ */ new Map();
14609
+ try {
14610
+ for (const obj of await listS3ObjectsByPrefix(projectPrefix, config)) {
14611
+ const idx = obj.key.indexOf(projectPrefix);
14612
+ const name = idx >= 0 ? obj.key.slice(idx + projectPrefix.length) : "";
14613
+ if (!isFlatName(name)) continue;
14614
+ remote.set(name, { size: obj.size, key: obj.key });
14615
+ }
14616
+ } catch (err3) {
14617
+ console.error(`[SKILLS] Failed to list project files for project ${projectId}; keeping the local copy.`, err3);
14618
+ return;
14619
+ }
14620
+ await sweepStaleHelpers(sessionDir);
14621
+ await mkdir(dirname(projectSyncMarkerPath(sessionDir)), { recursive: true });
14622
+ await writeFile(projectSyncMarkerPath(sessionDir), projectId);
14623
+ const trashes = [];
14624
+ const staging = helperPath(sessionDir, ".project-staging");
14625
+ let installed = false;
14626
+ try {
14627
+ const old = await moveAway(dir, sessionDir);
14628
+ trashes.push(old);
14629
+ await mkdir(dirname(staging), { recursive: true });
14630
+ await mkdir(staging);
14631
+ const local = [];
14632
+ const oldStat = old && previous === projectId ? await lstat(old).catch(() => null) : null;
14633
+ if (old && oldStat?.isDirectory()) {
14634
+ for (const name of await readdir(old)) {
14635
+ const st = await lstat(join2(old, name)).catch(() => null);
14636
+ if (!st?.isFile() || remote.get(name)?.size !== st.size) continue;
14637
+ await rename(join2(old, name), join2(staging, name));
14638
+ const moved = await lstat(join2(staging, name)).catch(() => null);
14639
+ if (!moved?.isFile()) {
14640
+ await rename(join2(staging, name), join2(old, `.rejected-${randomBytes2(4).toString("hex")}`)).catch(() => {
14641
+ });
14642
+ continue;
14643
+ }
14644
+ local.push({ name, size: moved.size });
14645
+ }
14646
+ }
14647
+ const plan = planProjectSync(
14648
+ [...remote].map(([name, r]) => ({ name, size: r.size })),
14649
+ local
14650
+ );
14651
+ for (const name of plan.download) {
14652
+ try {
14653
+ const bytes = await getS3ObjectBytes(remote.get(name).key, config);
14654
+ await writeFile(join2(staging, name), bytes, { flag: "wx" });
14655
+ } catch (err3) {
14656
+ console.error(`[SKILLS] Failed to sync project file ${name} (project ${projectId}); continuing.`, err3);
14657
+ }
14658
+ }
14659
+ for (let attempt = 0; attempt < 2 && !installed; attempt++) {
14660
+ try {
14661
+ await rename(staging, dir);
14662
+ installed = true;
14663
+ } catch (err3) {
14664
+ const code = errCode(err3);
14665
+ if (attempt === 0 && (code === "EEXIST" || code === "ENOTEMPTY" || code === "ENOTDIR" || code === "EISDIR")) {
14666
+ trashes.push(await moveAway(dir, sessionDir));
14667
+ continue;
14668
+ }
14669
+ console.error(`[SKILLS] Could not install the project folder for session ${sessionDir}; skipping this turn.`, err3);
14670
+ break;
14671
+ }
14672
+ }
14673
+ } catch (err3) {
14674
+ console.error(`[SKILLS] Project sync failed for project ${projectId}; continuing.`, err3);
14675
+ } finally {
14676
+ if (!installed) await discard(staging, sessionDir);
14677
+ for (const t of trashes) await discard(t, sessionDir);
14678
+ }
14679
+ }
14680
+ async function resolveSandboxProjectId(args, deps) {
14681
+ const { projectId, ownerId } = args;
14682
+ if (!projectId || ownerId == null) return null;
14683
+ try {
14684
+ const project = await deps.getProject(projectId);
14685
+ if (!project) return null;
14686
+ const owner = args.owner && String(args.owner.id) === String(ownerId) ? args.owner : await deps.getUser(ownerId);
14687
+ if (!owner) return null;
14688
+ const rbac = await deps.getRbac(project);
14689
+ const allowed = hasProjectAccess({ project, rbac, user: owner, want: "read" });
14690
+ return allowed ? String(project.id) : null;
14691
+ } catch (err3) {
14692
+ console.error(`[SKILLS] Failed to resolve project ${projectId} for the session sandbox; continuing without project files.`, err3);
14693
+ return null;
14694
+ }
14695
+ }
14696
+
14697
+ // ee/invoke-skills/safe-fs.ts
14698
+ import { constants } from "fs";
14699
+ import { lstat as lstat2, mkdir as mkdir2, open, readlink, realpath, rename as rename2, unlink, writeFile as writeFile2 } from "fs/promises";
14700
+ import { randomBytes as randomBytes3 } from "crypto";
14701
+ import { dirname as dirname2, isAbsolute, join as join3, sep as sep2 } from "path";
14702
+ var UnsafeSessionPathError = class extends Error {
14703
+ constructor(message) {
14704
+ super(message);
14705
+ this.name = "UnsafeSessionPathError";
14706
+ }
14707
+ };
14708
+ var errCode2 = (err3) => err3?.code;
14709
+ var isInside = (root, path3) => path3 === root || path3.startsWith(root + sep2);
14710
+ async function readRegularFileInside(sessionDir, path3) {
14711
+ const skip = (why) => {
14712
+ console.warn(`[SKILLS] Not reading ${path3} back from the sandbox: ${why}.`);
14713
+ return null;
14714
+ };
14715
+ let root;
14716
+ let parent;
14717
+ try {
14718
+ root = await realpath(sessionDir);
14719
+ parent = await realpath(dirname2(path3));
14720
+ } catch {
14721
+ return skip("path does not resolve");
14722
+ }
14723
+ if (!isInside(root, parent)) return skip("it resolves outside the session directory");
14724
+ let handle;
14725
+ try {
14726
+ handle = await open(
14727
+ path3,
14728
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | constants.O_NOCTTY
14729
+ );
14730
+ } catch (err3) {
14731
+ return skip(errCode2(err3) === "ELOOP" ? "it is a symbolic link" : `open failed (${errCode2(err3) ?? "unknown"})`);
14732
+ }
14733
+ try {
14734
+ const st = await handle.stat();
14735
+ if (!st.isFile()) return skip("it is not a regular file");
14736
+ if (st.size > MAX_ADOPT_UPLOAD_BYTES) {
14737
+ return skip(`it is larger than the ${MAX_ADOPT_UPLOAD_BYTES / (1024 * 1024)}MB upload limit (${st.size} bytes)`);
14738
+ }
14739
+ const fdPath = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => null);
14740
+ if (fdPath !== null) {
14741
+ if (!isInside(root, fdPath)) return skip("it resolves outside the session directory");
14742
+ } else {
14743
+ const again = await realpath(dirname2(path3)).catch(() => null);
14744
+ if (again === null || !isInside(root, again)) return skip("it resolves outside the session directory");
14745
+ }
14746
+ const chunks = [];
14747
+ let total = 0;
14748
+ const chunkSize = Math.min(Math.max(st.size + 1, 64 * 1024), 1024 * 1024);
14749
+ for (; ; ) {
14750
+ const chunk = Buffer.allocUnsafe(chunkSize);
14751
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
14752
+ if (bytesRead === 0) break;
14753
+ total += bytesRead;
14754
+ if (total > MAX_ADOPT_UPLOAD_BYTES) return skip("it grew past the upload limit while being read");
14755
+ chunks.push(chunk.subarray(0, bytesRead));
14756
+ }
14757
+ return Buffer.concat(chunks, total);
14758
+ } finally {
14759
+ await handle.close().catch(() => {
14760
+ });
14761
+ }
14762
+ }
14763
+ function safeSegments(relativePath) {
14764
+ if (!relativePath || isAbsolute(relativePath) || relativePath.includes("\\")) {
14765
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": not a plain relative path.`);
14766
+ }
14767
+ const segments = relativePath.split("/").filter((s) => s !== "" && s !== ".");
14768
+ if (segments.length === 0 || segments.includes("..")) {
14769
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": it contains a ".." segment or no file name.`);
14770
+ }
14771
+ return segments;
14772
+ }
14773
+ async function ensureDirInside(sessionDir, segments) {
14774
+ const root = await realpath(sessionDir);
14775
+ let current = sessionDir;
14776
+ for (const segment of segments) {
14777
+ current = join3(current, segment);
14778
+ let st = await lstat2(current).catch((err3) => errCode2(err3) === "ENOENT" ? null : Promise.reject(err3));
14779
+ if (!st) {
14780
+ try {
14781
+ await mkdir2(current);
14782
+ } catch (err3) {
14783
+ if (errCode2(err3) !== "EEXIST") throw err3;
14784
+ }
14785
+ st = await lstat2(current);
14786
+ }
14787
+ if (!st.isDirectory()) {
14788
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it is not a real directory.`);
14789
+ }
14790
+ }
14791
+ const real = await realpath(current);
14792
+ if (!isInside(root, real)) {
14793
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it resolves outside the session directory.`);
14794
+ }
14795
+ return current;
14796
+ }
14797
+ async function writeFileInside(sessionDir, relativePath, bytes) {
14798
+ const segments = safeSegments(relativePath);
14799
+ const name = segments[segments.length - 1];
14800
+ const parent = await ensureDirInside(sessionDir, segments.slice(0, -1));
14801
+ const destination = join3(parent, name);
14802
+ const temp = join3(parent, `.exulu-write-${randomBytes3(8).toString("hex")}`);
14803
+ await writeFile2(temp, bytes, { flag: "wx" });
14804
+ try {
14805
+ await rename2(temp, destination);
14806
+ } catch (err3) {
14807
+ await unlink(temp).catch(() => {
14808
+ });
14809
+ throw err3;
14810
+ }
14811
+ return destination;
14812
+ }
14813
+ async function ensureRealDirectory(sessionDir, relativeDir) {
14814
+ const segments = safeSegments(relativeDir);
14815
+ let current = sessionDir;
14816
+ for (const segment of segments) {
14817
+ current = join3(current, segment);
14818
+ const st = await lstat2(current).catch(() => null);
14819
+ if (st && !st.isDirectory()) {
14820
+ console.warn(`[SKILLS] ${current} is not a real directory; replacing it.`);
14821
+ await unlink(current);
14822
+ }
14823
+ }
14824
+ return ensureDirInside(sessionDir, segments);
14825
+ }
14826
+ async function removeEntryInside(sessionDir, relativePath) {
14827
+ const segments = safeSegments(relativePath);
14828
+ const target = join3(sessionDir, ...segments);
14829
+ const root = await realpath(sessionDir);
14830
+ const parentReal = await realpath(dirname2(target)).catch(() => null);
14831
+ if (parentReal === null) return;
14832
+ if (!isInside(root, parentReal)) {
14833
+ throw new UnsafeSessionPathError(`Refusing to remove ${target}: its parent resolves outside the session directory.`);
14834
+ }
14835
+ const st = await lstat2(target).catch(() => null);
14836
+ if (!st) return;
14837
+ if (!st.isDirectory()) {
14838
+ await unlink(target);
14839
+ return;
14840
+ }
14841
+ await discardEntry(target, sessionDir);
14842
+ }
14843
+
14844
+ // ee/invoke-skills/create-sandbox.ts
13731
14845
  var getAllExuluVariables = async () => {
13732
14846
  const { db } = await postgresClient();
13733
14847
  const rows = await db.from("variables").select("*");
@@ -13751,14 +14865,14 @@ var getAllExuluVariables = async () => {
13751
14865
  const granted = selectGrantedVariables(decrypted);
13752
14866
  return { granted, withheldNames: deriveWithheldNames(rows, granted) };
13753
14867
  };
13754
- var execAsync2 = promisify2(exec2);
14868
+ var execAsync2 = promisify3(exec2);
13755
14869
  var backendSecretFiles = () => {
13756
14870
  const cwd = process.cwd();
13757
14871
  const names = [".env", ".env.local", ".env.production", ".env.production.local"];
13758
14872
  const paths = /* @__PURE__ */ new Set();
13759
14873
  for (const name of names) {
13760
- paths.add(join2(cwd, name));
13761
- paths.add(join2("/app", name));
14874
+ paths.add(join4(cwd, name));
14875
+ paths.add(join4("/app", name));
13762
14876
  }
13763
14877
  return [...paths];
13764
14878
  };
@@ -13783,18 +14897,18 @@ function probeSandboxSupport() {
13783
14897
  if (process.platform !== "linux") {
13784
14898
  return { canSandbox: false, reason: `Unsupported platform: ${process.platform}` };
13785
14899
  }
13786
- return await new Promise((resolve3) => {
14900
+ return await new Promise((resolve4) => {
13787
14901
  const child = spawn("bwrap", ["--dev-bind", "/", "/", "--", "/bin/true"], { env: {} });
13788
14902
  let stderr = "";
13789
14903
  child.stderr.on("data", (chunk) => {
13790
14904
  stderr += chunk.toString();
13791
14905
  });
13792
14906
  child.on("error", (err3) => {
13793
- resolve3({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
14907
+ resolve4({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
13794
14908
  });
13795
14909
  child.on("exit", (code) => {
13796
- if (code === 0) resolve3({ canSandbox: true });
13797
- else resolve3({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
14910
+ if (code === 0) resolve4({ canSandbox: true });
14911
+ else resolve4({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
13798
14912
  });
13799
14913
  });
13800
14914
  })();
@@ -13829,23 +14943,46 @@ async function downloadSkill(skill, skillsDirectory, config) {
13829
14943
  `[SKILLS] No files found for skill "${skill.name}" at prefix "${versionPrefix}". Check that current_version matches what was uploaded to S3.`
13830
14944
  );
13831
14945
  }
14946
+ const sessionDir = dirname3(skillsDirectory);
14947
+ await ensureRealDirectory(sessionDir, `skills/${skill.name}`);
13832
14948
  for (const file of files) {
13833
14949
  const prefixIndex = file.key.indexOf(versionPrefix);
13834
14950
  const relativePath = prefixIndex >= 0 ? file.key.slice(prefixIndex + versionPrefix.length) : file.key;
13835
14951
  if (!relativePath) continue;
13836
- const localPath = join2(skillsDirectory, skill.name, relativePath);
13837
- await mkdir(dirname(localPath), { recursive: true });
13838
14952
  const bytes = await getS3ObjectBytes(file.key, config);
13839
- await writeFile(localPath, bytes);
14953
+ try {
14954
+ await writeFileInside(sessionDir, `skills/${skill.name}/${relativePath}`, bytes);
14955
+ } catch (err3) {
14956
+ if (!(err3 instanceof UnsafeSessionPathError)) throw err3;
14957
+ console.error(`[SKILLS] Skipping skill file ${file.key}: ${err3.message}`);
14958
+ }
13840
14959
  }
13841
14960
  }
13842
- function isArtifactPath(absPath, sessionDir) {
13843
- const resolved = resolve2(absPath);
14961
+ async function removeInstalledSkill(skillsDirectory, skillName) {
14962
+ const sessionDir = dirname3(skillsDirectory);
14963
+ await ensureRealDirectory(sessionDir, "skills");
14964
+ await removeEntryInside(sessionDir, `skills/${skillName}`);
14965
+ }
14966
+ function isArtifactPath(absPath, sessionDir, opts = {}) {
14967
+ const resolved = resolve3(absPath);
13844
14968
  const rel = relative(sessionDir, resolved);
13845
14969
  if (!rel || rel.startsWith("..")) return false;
13846
14970
  const first = rel.split("/")[0];
14971
+ if (opts.hasProject && first === PROJECT_DIR) return false;
13847
14972
  return first !== "skills";
13848
14973
  }
14974
+ async function uploadAgentArtifact(content, s3Key, config, userId) {
14975
+ return uploadFile(
14976
+ content,
14977
+ s3Key,
14978
+ config,
14979
+ { metadata: { [ORIGIN_METADATA_KEY]: "agent" } },
14980
+ // uploadFile's user param is typed as number, but the
14981
+ // addUserPrefixToKey helper it delegates to accepts
14982
+ // number | string at runtime — pass through as-is.
14983
+ userId
14984
+ );
14985
+ }
13849
14986
  function artifactS3Key(sessionId, relPath) {
13850
14987
  return `sessions/${sessionId}/${relPath}`;
13851
14988
  }
@@ -13884,11 +15021,13 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13884
15021
  const relativePath = idx >= 0 ? obj.key.slice(idx + userPrefix.length) : "";
13885
15022
  if (!relativePath) continue;
13886
15023
  if (isIgnoredArtifactPath(relativePath)) continue;
13887
- const localPath = join2(sessionDir, relativePath);
15024
+ if (opts.skipProjectDir && relativePath.split("/")[0] === PROJECT_DIR) continue;
15025
+ const localPath = join4(sessionDir, relativePath);
13888
15026
  if (opts.onlyMissing) {
13889
15027
  let localSize;
13890
15028
  try {
13891
- localSize = (await stat(localPath)).size;
15029
+ const st = await lstat3(localPath);
15030
+ localSize = st.isFile() ? st.size : void 0;
13892
15031
  } catch {
13893
15032
  localSize = void 0;
13894
15033
  }
@@ -13896,8 +15035,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13896
15035
  }
13897
15036
  try {
13898
15037
  const bytes = await getS3ObjectBytes(obj.key, config);
13899
- await mkdir(dirname(localPath), { recursive: true });
13900
- await writeFile(localPath, bytes);
15038
+ await writeFileInside(sessionDir, relativePath, bytes);
13901
15039
  } catch (err3) {
13902
15040
  console.error(
13903
15041
  `[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
@@ -13908,7 +15046,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13908
15046
  }
13909
15047
  async function downloadKeyIntoSandbox(opts) {
13910
15048
  const { sessionId, userId, fullS3Key, config } = opts;
13911
- const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
15049
+ const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
13912
15050
  if (!existsSync4(sessionDir)) {
13913
15051
  return { written: false };
13914
15052
  }
@@ -13921,10 +15059,8 @@ async function downloadKeyIntoSandbox(opts) {
13921
15059
  }
13922
15060
  const relativePath = fullS3Key.slice(idx + userPrefix.length);
13923
15061
  if (!relativePath) return { written: false };
13924
- const localPath = join2(sessionDir, relativePath);
13925
15062
  const bytes = await getS3ObjectBytes(fullS3Key, config);
13926
- await mkdir(dirname(localPath), { recursive: true });
13927
- await writeFile(localPath, bytes);
15063
+ const localPath = await writeFileInside(sessionDir, relativePath, bytes);
13928
15064
  return { written: true, localPath };
13929
15065
  }
13930
15066
  async function resolvePythonVenvPath() {
@@ -13939,42 +15075,55 @@ async function resolvePythonVenvPath() {
13939
15075
  async function refreshSessionSkills(sessionId, skills, config) {
13940
15076
  const cached = sandboxCache.get(sessionId);
13941
15077
  if (!cached) return { refreshed: 0, sandbox: false };
13942
- const skillsDirectory = join2(cached.handle.sessionDir, "skills");
15078
+ const skillsDirectory = join4(cached.handle.sessionDir, "skills");
13943
15079
  let refreshed = 0;
13944
15080
  for (const skill of skills) {
13945
- await rm(join2(skillsDirectory, skill.name), { recursive: true, force: true });
15081
+ await removeInstalledSkill(skillsDirectory, skill.name);
13946
15082
  await downloadSkill(skill, skillsDirectory, config);
13947
15083
  cached.installedSkills.set(skill.id, skill.current_version);
13948
15084
  refreshed++;
13949
15085
  }
13950
15086
  return { refreshed, sandbox: true };
13951
15087
  }
13952
- async function createSessionSandbox(sessionId, skills, config, userId, agent) {
15088
+ async function createSessionSandbox(sessionId, skills, config, userId, agent, opts = {}) {
13953
15089
  const cached = sandboxCache.get(sessionId);
15090
+ const projectId = opts.projectId ?? null;
15091
+ const syncProject = async (dir) => {
15092
+ try {
15093
+ await syncProjectDir({ sessionDir: dir, projectId, config });
15094
+ } catch (err3) {
15095
+ console.error(`[SKILLS] Failed to sync project files into session ${sessionId}; continuing.`, err3);
15096
+ }
15097
+ };
13954
15098
  if (cached) {
13955
- const skillsDirectory2 = join2(cached.handle.sessionDir, "skills");
15099
+ cached.projectState.projectId = projectId;
15100
+ const skillsDirectory2 = join4(cached.handle.sessionDir, "skills");
13956
15101
  for (const skill of skills) {
13957
15102
  const installedVersion = cached.installedSkills.get(skill.id);
13958
15103
  if (installedVersion === skill.current_version) continue;
13959
15104
  if (installedVersion !== void 0) {
13960
- await rm(join2(skillsDirectory2, skill.name), { recursive: true, force: true });
15105
+ await removeInstalledSkill(skillsDirectory2, skill.name);
13961
15106
  }
13962
15107
  await downloadSkill(skill, skillsDirectory2, config);
13963
15108
  cached.installedSkills.set(skill.id, skill.current_version);
13964
15109
  }
13965
15110
  if (userId && config.fileUploads) {
13966
15111
  try {
13967
- await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, { onlyMissing: true });
15112
+ await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, {
15113
+ onlyMissing: true,
15114
+ skipProjectDir: projectId !== null
15115
+ });
13968
15116
  } catch (err3) {
13969
15117
  console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err3);
13970
15118
  }
13971
15119
  }
15120
+ await syncProject(cached.handle.sessionDir);
13972
15121
  return cached.handle;
13973
15122
  }
13974
- const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
15123
+ const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
13975
15124
  const dirExisted = existsSync4(sessionDir);
13976
- await mkdir(sessionDir, { recursive: true });
13977
- const skillsDirectory = join2(sessionDir, "skills");
15125
+ await mkdir3(sessionDir, { recursive: true });
15126
+ const skillsDirectory = join4(sessionDir, "skills");
13978
15127
  const installedSkills = /* @__PURE__ */ new Map();
13979
15128
  for (const skill of skills) {
13980
15129
  await downloadSkill(skill, skillsDirectory, config);
@@ -13987,8 +15136,13 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent) {
13987
15136
  );
13988
15137
  }
13989
15138
  if (userId && config.fileUploads) {
13990
- await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, { onlyMissing: dirExisted });
15139
+ await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, {
15140
+ onlyMissing: dirExisted,
15141
+ skipProjectDir: projectId !== null
15142
+ });
13991
15143
  }
15144
+ await syncProject(sessionDir);
15145
+ const projectState = { projectId };
13992
15146
  const probe = await probeSandboxSupport();
13993
15147
  const useDirectExec = !probe.canSandbox;
13994
15148
  if (useDirectExec) {
@@ -14067,7 +15221,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14067
15221
  extraSecretNames: litellmConfigSecretNames(),
14068
15222
  overrides: {
14069
15223
  ...npmGlobalRoot ? { NODE_PATH: npmGlobalRoot } : {},
14070
- ...pythonVenvPath ? { PATH: `${join2(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
15224
+ ...pythonVenvPath ? { PATH: `${join4(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
14071
15225
  }
14072
15226
  });
14073
15227
  if (skippedNames.length) {
@@ -14142,24 +15296,16 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14142
15296
  await writeFilesInternal(files);
14143
15297
  }
14144
15298
  };
14145
- async function persistArtifactToS3(absPath, content) {
14146
- if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir)) {
15299
+ const hasProjectNow = () => projectState.projectId !== null;
15300
+ async function persistArtifactToS3(absPath, content, hasProject) {
15301
+ if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir, { hasProject })) {
14147
15302
  return {};
14148
15303
  }
14149
- const rel = relative(sessionDir, resolve2(absPath));
15304
+ const rel = relative(sessionDir, resolve3(absPath));
14150
15305
  const s3Key = artifactS3Key(sessionId, rel);
14151
15306
  const out = {};
14152
15307
  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
- );
15308
+ const fullKey = await uploadAgentArtifact(content, s3Key, config, userId);
14163
15309
  out.key = fullKey;
14164
15310
  const slashIdx = fullKey.indexOf("/");
14165
15311
  if (slashIdx > 0) {
@@ -14182,11 +15328,11 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14182
15328
  }
14183
15329
  return out;
14184
15330
  }
14185
- async function writeFilesInternal(files) {
15331
+ async function writeFilesInternal(files, hasProject = hasProjectNow()) {
14186
15332
  const results = [];
14187
15333
  for (const file of files) {
14188
15334
  const wrapped = await wrapIfNeeded(
14189
- `mkdir -p ${shellQuote(dirname(file.path))} && cat > ${shellQuote(file.path)}`
15335
+ `mkdir -p ${shellQuote(dirname3(file.path))} && cat > ${shellQuote(file.path)}`
14190
15336
  );
14191
15337
  await new Promise((resolveSpawn, rejectSpawn) => {
14192
15338
  const child = spawn("/bin/bash", ["-c", wrapped], { env: sandboxedExecEnv });
@@ -14205,7 +15351,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14205
15351
  const result = { path: file.path };
14206
15352
  const persisted = await persistArtifactToS3(
14207
15353
  file.path,
14208
- Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content)
15354
+ Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content),
15355
+ hasProject || hasProjectNow()
14209
15356
  );
14210
15357
  if (persisted.key) result.key = persisted.key;
14211
15358
  if (persisted.url) result.url = persisted.url;
@@ -14213,19 +15360,21 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14213
15360
  }
14214
15361
  return results;
14215
15362
  }
14216
- async function snapshotSessionArtifacts() {
15363
+ async function snapshotSessionArtifacts(hasProject) {
14217
15364
  const map = /* @__PURE__ */ new Map();
14218
- const skillsDir = join2(sessionDir, "skills");
15365
+ const skillsDir = join4(sessionDir, "skills");
15366
+ const projectDir = hasProject ? join4(sessionDir, PROJECT_DIR) : null;
14219
15367
  const walk = async (dir) => {
14220
15368
  let entries;
14221
15369
  try {
14222
- entries = await readdir(dir, { withFileTypes: true });
15370
+ entries = await readdir2(dir, { withFileTypes: true });
14223
15371
  } catch {
14224
15372
  return;
14225
15373
  }
14226
15374
  for (const entry of entries) {
14227
- const full = join2(dir, entry.name);
15375
+ const full = join4(dir, entry.name);
14228
15376
  if (full === skillsDir) continue;
15377
+ if (projectDir !== null && full === projectDir) continue;
14229
15378
  if (isIgnoredArtifactPath(relative(sessionDir, full))) continue;
14230
15379
  if (entry.isDirectory()) {
14231
15380
  await walk(full);
@@ -14250,13 +15399,14 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14250
15399
  });
14251
15400
  const writeFileTool = tool2({
14252
15401
  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")
15402
+ inputSchema: z16.object({
15403
+ path: z16.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
15404
+ content: z16.string().describe("The content to write to the file")
14256
15405
  }),
14257
15406
  execute: async ({ path: path3, content }) => {
15407
+ const hasProject = hasProjectNow();
14258
15408
  const resolvedPath = resolveSessionPath(path3, sessionDir);
14259
- const results = await writeFilesInternal([{ path: resolvedPath, content }]);
15409
+ const results = await writeFilesInternal([{ path: resolvedPath, content }], hasProject);
14260
15410
  const result = results[0];
14261
15411
  if (!result) {
14262
15412
  throw new Error(`writeFile ${resolvedPath} produced no result`);
@@ -14271,8 +15421,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14271
15421
  });
14272
15422
  const readFileTool = tool2({
14273
15423
  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.")
15424
+ inputSchema: z16.object({
15425
+ path: z16.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
14276
15426
  }),
14277
15427
  execute: async ({ path: path3 }) => {
14278
15428
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -14289,19 +15439,21 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14289
15439
  const originalBashTool = tools.bash;
14290
15440
  const bashTool = tool2({
14291
15441
  description: originalBashTool.description ?? "",
14292
- inputSchema: z15.object({
14293
- command: z15.string().describe("The bash command to execute.")
15442
+ inputSchema: z16.object({
15443
+ command: z16.string().describe("The bash command to execute.")
14294
15444
  }),
14295
- execute: async (args, opts) => {
14296
- const before = persistenceEnabled ? await snapshotSessionArtifacts() : null;
15445
+ execute: async (args, opts2) => {
15446
+ const hasProject = hasProjectNow();
15447
+ const before = persistenceEnabled ? await snapshotSessionArtifacts(hasProject) : null;
14297
15448
  const originalExecute = originalBashTool.execute;
14298
15449
  if (!originalExecute) {
14299
15450
  throw new Error("bash tool execute is undefined");
14300
15451
  }
14301
- const result = await originalExecute(args, opts);
15452
+ const result = await originalExecute(args, opts2);
14302
15453
  const artifacts = [];
14303
15454
  if (persistenceEnabled && before) {
14304
- const after = await snapshotSessionArtifacts();
15455
+ const skipProject = hasProject || hasProjectNow();
15456
+ const after = await snapshotSessionArtifacts(skipProject);
14305
15457
  const changedPaths = [];
14306
15458
  for (const [path3, mtime] of after) {
14307
15459
  const beforeMtime = before.get(path3);
@@ -14311,8 +15463,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14311
15463
  }
14312
15464
  for (const path3 of changedPaths) {
14313
15465
  try {
14314
- const content = await fsReadFile(path3);
14315
- const persisted = await persistArtifactToS3(path3, content);
15466
+ const content = await readRegularFileInside(sessionDir, path3);
15467
+ if (content === null) continue;
15468
+ const persisted = await persistArtifactToS3(path3, content, skipProject);
14316
15469
  artifacts.push({
14317
15470
  path: path3,
14318
15471
  relativePath: relative(sessionDir, path3),
@@ -14359,15 +15512,53 @@ ${lines.join("\n")}`;
14359
15512
  if (!useDirectExec) {
14360
15513
  await SandboxManager.reset();
14361
15514
  }
14362
- await rm(sessionDir, { recursive: true, force: true });
15515
+ await rm2(sessionDir, { recursive: true, force: true });
15516
+ await clearProjectSyncMarker(sessionDir);
14363
15517
  }
14364
15518
  };
14365
- sandboxCache.set(sessionId, { handle, installedSkills });
15519
+ sandboxCache.set(sessionId, { handle, installedSkills, projectState });
14366
15520
  return handle;
14367
15521
  }
14368
15522
 
15523
+ // src/exulu/resolve-session-project.ts
15524
+ async function resolveSessionProject(args) {
15525
+ if (!args.projectId || args.ownerId == null) return null;
15526
+ let row;
15527
+ let rbac;
15528
+ const id = await resolveSandboxProjectId(
15529
+ { projectId: args.projectId, ownerId: args.ownerId, owner: args.owner },
15530
+ {
15531
+ getProject: async (pid) => {
15532
+ const { db } = await postgresClient();
15533
+ row = await db.from("projects").where({ id: pid }).first();
15534
+ return row;
15535
+ },
15536
+ // The rbac table stores the SINGULAR entity name for projects.
15537
+ getRbac: async (p) => {
15538
+ const { db } = await postgresClient();
15539
+ rbac = await RBACResolver(db, "project", p.id, p.rights_mode || "private");
15540
+ return rbac;
15541
+ },
15542
+ getUser: async (uid) => {
15543
+ const { db } = await postgresClient();
15544
+ return db.from("users").where({ id: uid }).first();
15545
+ }
15546
+ }
15547
+ );
15548
+ if (!id) return null;
15549
+ let speakerCanWrite = false;
15550
+ if (args.speaker?.id != null && row && rbac) {
15551
+ try {
15552
+ speakerCanWrite = hasProjectAccess({ project: row, rbac, user: args.speaker, want: "write" });
15553
+ } catch {
15554
+ speakerCanWrite = false;
15555
+ }
15556
+ }
15557
+ return { id, name: row?.name?.trim() || "(unnamed)", speakerCanWrite };
15558
+ }
15559
+
14369
15560
  // src/templates/tools/routine-status-tool.ts
14370
- import { z as z16 } from "zod";
15561
+ import { z as z17 } from "zod";
14371
15562
  var SET_ROUTINE_STATUS_TOOL_ID = "set_routine_status";
14372
15563
  function createRoutineStatusTool(handle) {
14373
15564
  if (!handle || handle.statuses.length === 0) return void 0;
@@ -14380,8 +15571,8 @@ function createRoutineStatusTool(handle) {
14380
15571
  category: "routines",
14381
15572
  type: "function",
14382
15573
  needsApproval: false,
14383
- inputSchema: z16.object({
14384
- status: z16.enum(keys).describe("The work status key to set.")
15574
+ inputSchema: z17.object({
15575
+ status: z17.enum(keys).describe("The work status key to set.")
14385
15576
  }),
14386
15577
  config: [],
14387
15578
  execute: async ({ status }) => {
@@ -14593,7 +15784,30 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
14593
15784
  };
14594
15785
 
14595
15786
  // src/templates/tools/session-file-read-tool.ts
14596
- import { z as z17 } from "zod";
15787
+ import { z as z18 } from "zod";
15788
+
15789
+ // src/templates/tools/resolve-file-key.ts
15790
+ var NO_PROJECT_FILES_ERROR = "This session has no project files.";
15791
+ var INVALID_SESSION_FILENAME_ERROR = "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths).";
15792
+ function resolveFileKey(args) {
15793
+ const filename = String(args.filename ?? "").trim();
15794
+ const parsed = parseProjectFilename(filename);
15795
+ if ("error" in parsed) return parsed;
15796
+ if (parsed.scope === "project") {
15797
+ if (!args.projectId) return { error: NO_PROJECT_FILES_ERROR };
15798
+ const { fullProjectPrefix } = projectFilePrefix(args.projectId, args.s3prefix);
15799
+ return { key: `${fullProjectPrefix}${parsed.name}`, scope: "project" };
15800
+ }
15801
+ if (!filename || filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
15802
+ return { error: INVALID_SESSION_FILENAME_ERROR };
15803
+ }
15804
+ return {
15805
+ key: `${sessionFilePrefix(args.ownerId, args.sessionId, args.s3prefix ?? void 0)}${filename}`,
15806
+ scope: "session"
15807
+ };
15808
+ }
15809
+
15810
+ // src/templates/tools/session-file-read-tool.ts
14597
15811
  var DEFAULT_LIMIT = 250;
14598
15812
  var MAX_CONTENT_CHARS = 16e3;
14599
15813
  var SESSION_FILE_READ_TOOL_NAME = "read_session_file";
@@ -14601,18 +15815,22 @@ var createSessionFileReadTool = ({
14601
15815
  sessionID,
14602
15816
  user,
14603
15817
  exuluConfig,
14604
- ownerId
15818
+ ownerId,
15819
+ projectId
14605
15820
  }) => {
14606
15821
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
14607
15822
  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
15823
  const uploads = exuluConfig.fileUploads;
14615
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
15824
+ const resolved = resolveFileKey({
15825
+ filename,
15826
+ ownerId: ownerId ?? user?.id ?? "api",
15827
+ sessionId: sessionID,
15828
+ projectId: projectId ?? null,
15829
+ s3prefix: uploads.s3prefix
15830
+ });
15831
+ if ("error" in resolved) return { error: resolved.error };
15832
+ const key = resolved.key;
15833
+ const safeName = String(filename).trim();
14616
15834
  try {
14617
15835
  const url = await getPresignedUrl(uploads.s3Bucket, key, exuluConfig);
14618
15836
  const res = await fetch(url);
@@ -14645,11 +15863,11 @@ var createSessionFileReadTool = ({
14645
15863
  id: "read_session_file",
14646
15864
  name: SESSION_FILE_READ_TOOL_NAME,
14647
15865
  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})`)
15866
+ description: "Read a line range from a file stored in this session's files \u2014 including offloaded tool outputs (tool-output-*.txt) and uploaded documents. Use offset (1-based line number) and limit to page through large files instead of reading everything at once. Files of the session's project are addressed as `project/<name>` and are read-only.",
15867
+ inputSchema: z18.object({
15868
+ filename: z18.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
15869
+ offset: z18.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
15870
+ limit: z18.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
14653
15871
  }),
14654
15872
  type: "function",
14655
15873
  category: "session",
@@ -14662,18 +15880,18 @@ var createSessionFileReadTool = ({
14662
15880
  };
14663
15881
 
14664
15882
  // src/templates/tools/parse-document-tool.ts
14665
- import { z as z18 } from "zod";
15883
+ import { z as z19 } from "zod";
14666
15884
  import { extname } from "path";
14667
15885
  import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
14668
15886
 
14669
15887
  // src/templates/tools/document-render-helpers.ts
14670
- import { execFile } from "child_process";
14671
- import { promisify as promisify3 } from "util";
15888
+ import { execFile as execFile2 } from "child_process";
15889
+ import { promisify as promisify4 } from "util";
14672
15890
  import { existsSync as existsSync5 } from "fs";
14673
- import { mkdtemp, readdir as readdir2, readFile, rm as rm2, writeFile as writeFile2 } from "fs/promises";
15891
+ import { mkdtemp, readdir as readdir3, readFile as readFile2, rm as rm3, writeFile as writeFile3 } from "fs/promises";
14674
15892
  import { tmpdir } from "os";
14675
- import { join as join3 } from "path";
14676
- var execFileAsync = promisify3(execFile);
15893
+ import { join as join5 } from "path";
15894
+ var execFileAsync2 = promisify4(execFile2);
14677
15895
  var MAX_STDOUT_BYTES = 64 * 1024 * 1024;
14678
15896
  var LEGACY_OFFICE_CONVERSION_TARGETS = {
14679
15897
  ".doc": "docx",
@@ -14689,12 +15907,12 @@ async function convertLegacyOfficeToModern(bytes, ext) {
14689
15907
  if (!target) {
14690
15908
  throw new Error(`No modern-format conversion target registered for "${ext}"`);
14691
15909
  }
14692
- const dir = await mkdtemp(join3(tmpdir(), "exulu-officeconv-"));
15910
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-officeconv-"));
14693
15911
  try {
14694
- const inputPath = join3(dir, `input${ext}`);
14695
- await writeFile2(inputPath, bytes);
15912
+ const inputPath = join5(dir, `input${ext}`);
15913
+ await writeFile3(inputPath, bytes);
14696
15914
  try {
14697
- await execFileAsync(
15915
+ await execFileAsync2(
14698
15916
  "soffice",
14699
15917
  ["--headless", "--convert-to", target, inputPath, "--outdir", dir],
14700
15918
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
@@ -14704,62 +15922,62 @@ async function convertLegacyOfficeToModern(bytes, ext) {
14704
15922
  `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err3 instanceof Error ? err3.message : String(err3))
14705
15923
  );
14706
15924
  }
14707
- const outputPath = join3(dir, `input.${target}`);
15925
+ const outputPath = join5(dir, `input.${target}`);
14708
15926
  if (!existsSync5(outputPath)) {
14709
15927
  throw new Error(`LibreOffice produced no output converting "${ext}" to ${target}`);
14710
15928
  }
14711
- return await readFile(outputPath);
15929
+ return await readFile2(outputPath);
14712
15930
  } finally {
14713
- await rm2(dir, { recursive: true, force: true });
15931
+ await rm3(dir, { recursive: true, force: true });
14714
15932
  }
14715
15933
  }
14716
15934
  async function pdfToText(pdf) {
14717
- const dir = await mkdtemp(join3(tmpdir(), "exulu-parse-"));
15935
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-parse-"));
14718
15936
  try {
14719
- const inputPath = join3(dir, "input.pdf");
14720
- await writeFile2(inputPath, pdf);
14721
- const { stdout } = await execFileAsync("pdftotext", ["-layout", inputPath, "-"], {
15937
+ const inputPath = join5(dir, "input.pdf");
15938
+ await writeFile3(inputPath, pdf);
15939
+ const { stdout } = await execFileAsync2("pdftotext", ["-layout", inputPath, "-"], {
14722
15940
  timeout: 6e4,
14723
15941
  maxBuffer: MAX_STDOUT_BYTES
14724
15942
  });
14725
15943
  return stdout;
14726
15944
  } finally {
14727
- await rm2(dir, { recursive: true, force: true });
15945
+ await rm3(dir, { recursive: true, force: true });
14728
15946
  }
14729
15947
  }
14730
15948
  async function pdfPageCount(pdf) {
14731
- const dir = await mkdtemp(join3(tmpdir(), "exulu-pdfinfo-"));
15949
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-pdfinfo-"));
14732
15950
  try {
14733
- const inputPath = join3(dir, "input.pdf");
14734
- await writeFile2(inputPath, pdf);
14735
- const { stdout } = await execFileAsync("pdfinfo", [inputPath], { timeout: 3e4, maxBuffer: 1e6 });
15951
+ const inputPath = join5(dir, "input.pdf");
15952
+ await writeFile3(inputPath, pdf);
15953
+ const { stdout } = await execFileAsync2("pdfinfo", [inputPath], { timeout: 3e4, maxBuffer: 1e6 });
14736
15954
  const match = /^Pages:\s+(\d+)/m.exec(stdout);
14737
15955
  if (!match) throw new Error("pdfinfo did not report a page count");
14738
15956
  return Number(match[1]);
14739
15957
  } finally {
14740
- await rm2(dir, { recursive: true, force: true });
15958
+ await rm3(dir, { recursive: true, force: true });
14741
15959
  }
14742
15960
  }
14743
15961
  async function renderPdfPageToPng(pdf, page, scaleTo) {
14744
- const dir = await mkdtemp(join3(tmpdir(), "exulu-render-"));
15962
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-render-"));
14745
15963
  try {
14746
- const inputPath = join3(dir, "input.pdf");
14747
- await writeFile2(inputPath, pdf);
15964
+ const inputPath = join5(dir, "input.pdf");
15965
+ await writeFile3(inputPath, pdf);
14748
15966
  try {
14749
- await execFileAsync(
15967
+ await execFileAsync2(
14750
15968
  "pdftoppm",
14751
- ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, join3(dir, "page")],
15969
+ ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, join5(dir, "page")],
14752
15970
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
14753
15971
  );
14754
15972
  } catch (err3) {
14755
15973
  if (err3?.code === 99) return null;
14756
15974
  throw err3;
14757
15975
  }
14758
- const produced = (await readdir2(dir)).find((f) => f.startsWith("page") && f.endsWith(".png"));
15976
+ const produced = (await readdir3(dir)).find((f) => f.startsWith("page") && f.endsWith(".png"));
14759
15977
  if (!produced) return null;
14760
- return await readFile(join3(dir, produced));
15978
+ return await readFile2(join5(dir, produced));
14761
15979
  } finally {
14762
- await rm2(dir, { recursive: true, force: true });
15980
+ await rm3(dir, { recursive: true, force: true });
14763
15981
  }
14764
15982
  }
14765
15983
 
@@ -14928,7 +16146,8 @@ var createParseDocumentTool = ({
14928
16146
  sessionID,
14929
16147
  user,
14930
16148
  exuluConfig,
14931
- ownerId
16149
+ ownerId,
16150
+ projectId
14932
16151
  }) => {
14933
16152
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
14934
16153
  const parseDocumentExecute = async ({
@@ -14937,12 +16156,16 @@ var createParseDocumentTool = ({
14937
16156
  offset,
14938
16157
  limit
14939
16158
  }) => {
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
- }
16159
+ const resolvedKey = resolveFileKey({
16160
+ filename,
16161
+ ownerId: ownerId ?? user?.id ?? "api",
16162
+ sessionId: sessionID,
16163
+ projectId: projectId ?? null,
16164
+ s3prefix: exuluConfig.fileUploads.s3prefix
16165
+ });
16166
+ if ("error" in resolvedKey) return { error: resolvedKey.error };
16167
+ const key = resolvedKey.key;
16168
+ const safeName = String(filename).trim();
14946
16169
  const ext = extname(safeName).toLowerCase();
14947
16170
  if (ext !== ".pdf" && !OFFICE_EXTENSIONS.has(ext)) {
14948
16171
  return {
@@ -14953,7 +16176,6 @@ var createParseDocumentTool = ({
14953
16176
  return { error: `The pages option is only supported for PDF files \u2014 "${ext}" documents are extracted whole.` };
14954
16177
  }
14955
16178
  const uploads = exuluConfig.fileUploads;
14956
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
14957
16179
  try {
14958
16180
  const url = await getPresignedUrl(uploads.s3Bucket, key, exuluConfig);
14959
16181
  const res = await fetch(url);
@@ -15030,12 +16252,12 @@ ${text.trim()}`).join("\n");
15030
16252
  id: "parse_document",
15031
16253
  name: PARSE_DOCUMENT_TOOL_NAME,
15032
16254
  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})`)
16255
+ description: "Extract the text of an uploaded PDF or Office document from this session's files, with \"--- page N ---\" markers for PDFs so you can locate content by page. Free and fast (no OCR): works only on documents with a real text layer. To SEE a page or an image inside a document, use view_document_page. Files of the session's project are addressed as `project/<name>` and are read-only.",
16256
+ inputSchema: z19.object({
16257
+ filename: z19.string().describe('Exact session file name, e.g. "report.pdf"'),
16258
+ pages: z19.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
16259
+ offset: z19.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
16260
+ limit: z19.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
15039
16261
  }),
15040
16262
  type: "function",
15041
16263
  category: "session",
@@ -15048,19 +16270,19 @@ ${text.trim()}`).join("\n");
15048
16270
  };
15049
16271
 
15050
16272
  // src/templates/tools/view-document-page-tool.ts
15051
- import { z as z19 } from "zod";
16273
+ import { z as z20 } from "zod";
15052
16274
  import { extname as extname3 } from "path";
15053
16275
 
15054
16276
  // src/sessions/pdf-preview-cache.ts
15055
16277
  import { exec as exec3 } from "child_process";
15056
16278
  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);
16279
+ import { mkdir as mkdir4, readFile as readFile3, rename as rename3, rm as rm4, writeFile as writeFile4 } from "fs/promises";
16280
+ import { extname as extname2, join as join6 } from "path";
16281
+ import { promisify as promisify5 } from "util";
16282
+ var execAsync3 = promisify5(exec3);
15061
16283
  var CACHE_ROOT = "/tmp/exulu-pdf-cache";
15062
- var CACHE_IN = join4(CACHE_ROOT, "_in");
15063
- var CACHE_OUT = join4(CACHE_ROOT, "_out");
16284
+ var CACHE_IN = join6(CACHE_ROOT, "_in");
16285
+ var CACHE_OUT = join6(CACHE_ROOT, "_out");
15064
16286
  var inFlight = /* @__PURE__ */ new Map();
15065
16287
  var PreviewRenderError = class extends Error {
15066
16288
  constructor(message) {
@@ -15077,22 +16299,22 @@ async function getPdfPreviewBytes(opts) {
15077
16299
  if (!safeEtag) {
15078
16300
  throw new PreviewRenderError(`Invalid ETag for ${sourceKey}`);
15079
16301
  }
15080
- const cachedPath = join4(CACHE_ROOT, `${safeEtag}.pdf`);
16302
+ const cachedPath = join6(CACHE_ROOT, `${safeEtag}.pdf`);
15081
16303
  if (existsSync6(cachedPath)) {
15082
- return readFile2(cachedPath);
16304
+ return readFile3(cachedPath);
15083
16305
  }
15084
16306
  const existing = inFlight.get(safeEtag);
15085
16307
  if (existing) return existing;
15086
16308
  const promise = (async () => {
15087
16309
  try {
15088
- await mkdir2(CACHE_IN, { recursive: true });
15089
- await mkdir2(CACHE_OUT, { recursive: true });
16310
+ await mkdir4(CACHE_IN, { recursive: true });
16311
+ await mkdir4(CACHE_OUT, { recursive: true });
15090
16312
  const ext = (extname2(sourceKey) || ".docx").toLowerCase();
15091
- const inputPath = join4(CACHE_IN, `${safeEtag}${ext}`);
15092
- const outputPath = join4(CACHE_OUT, `${safeEtag}.pdf`);
16313
+ const inputPath = join6(CACHE_IN, `${safeEtag}${ext}`);
16314
+ const outputPath = join6(CACHE_OUT, `${safeEtag}.pdf`);
15093
16315
  try {
15094
16316
  const bytes = await getS3ObjectBytes(sourceKey, config);
15095
- await writeFile3(inputPath, bytes);
16317
+ await writeFile4(inputPath, bytes);
15096
16318
  try {
15097
16319
  await execAsync3(
15098
16320
  `soffice --headless --convert-to pdf "${inputPath}" --outdir "${CACHE_OUT}"`,
@@ -15108,10 +16330,10 @@ async function getPdfPreviewBytes(opts) {
15108
16330
  `LibreOffice produced no output for ${sourceKey} (etag ${etag})`
15109
16331
  );
15110
16332
  }
15111
- await rename(outputPath, cachedPath);
15112
- return await readFile2(cachedPath);
16333
+ await rename3(outputPath, cachedPath);
16334
+ return await readFile3(cachedPath);
15113
16335
  } finally {
15114
- await rm3(inputPath, { force: true });
16336
+ await rm4(inputPath, { force: true });
15115
16337
  }
15116
16338
  } finally {
15117
16339
  inFlight.delete(safeEtag);
@@ -15227,16 +16449,21 @@ var createViewDocumentPageTool = ({
15227
16449
  sessionID,
15228
16450
  user,
15229
16451
  exuluConfig,
15230
- ownerId
16452
+ ownerId,
16453
+ projectId
15231
16454
  }) => {
15232
16455
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
15233
16456
  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
- }
16457
+ const resolvedKey = resolveFileKey({
16458
+ filename,
16459
+ ownerId: ownerId ?? user?.id ?? "api",
16460
+ sessionId: sessionID,
16461
+ projectId: projectId ?? null,
16462
+ s3prefix: exuluConfig.fileUploads.s3prefix
16463
+ });
16464
+ if ("error" in resolvedKey) return { error: resolvedKey.error };
16465
+ const key = resolvedKey.key;
16466
+ const safeName = String(filename).trim();
15240
16467
  const ext = extname3(safeName).toLowerCase();
15241
16468
  const isImage = ext in IMAGE_MEDIA_TYPES;
15242
16469
  const isPdf = ext === ".pdf";
@@ -15259,8 +16486,6 @@ var createViewDocumentPageTool = ({
15259
16486
  } catch {
15260
16487
  }
15261
16488
  }
15262
- const uploads = exuluConfig.fileUploads;
15263
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
15264
16489
  const pageNumber = page ?? 1;
15265
16490
  try {
15266
16491
  let imageBytes;
@@ -15318,10 +16543,10 @@ var createViewDocumentPageTool = ({
15318
16543
  id: "view_document_page",
15319
16544
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
15320
16545
  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)")
16546
+ description: "LOOK at a page of an uploaded PDF/Office document, or at an uploaded image, from this session's files. The rendered image is attached as a user message directly after this tool result so you can visually analyze photos, charts, scans, and layouts. Use parse_document first to find which page you need. Requires a vision-capable model. Files of the session's project are addressed as `project/<name>` and are read-only.",
16547
+ inputSchema: z20.object({
16548
+ filename: z20.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
16549
+ page: z20.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
15325
16550
  }),
15326
16551
  type: "function",
15327
16552
  category: "session",
@@ -15463,7 +16688,7 @@ var hydrateVariables = async (tool3) => {
15463
16688
  await Promise.all(promises);
15464
16689
  return tool3;
15465
16690
  };
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) => {
16691
+ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions, skillDecisions, routineHandleFactory, resolvedProject) => {
15467
16692
  if (!currentTools) return {};
15468
16693
  if (!allExuluTools) {
15469
16694
  allExuluTools = [];
@@ -15473,6 +16698,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15473
16698
  }
15474
16699
  const budget = deriveContextBudget(contextWindow);
15475
16700
  const toolOutputCharLimit = budget.toolOutputCapTokens * 4;
16701
+ const turnProject = resolvedProject !== void 0 ? resolvedProject : sessionID ? await resolveSessionProject({ projectId: project, ownerId: sessionOwnerId ?? user?.id, owner: user, speaker: user }) : null;
16702
+ const sandboxProjectId = turnProject?.id ?? null;
15476
16703
  let sharedSessionSandbox;
15477
16704
  if (sessionID && exuluConfig && agent?.sandbox_enabled === true) {
15478
16705
  try {
@@ -15483,7 +16710,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15483
16710
  sessionOwnerId ?? user?.id,
15484
16711
  // Same agent descriptor the tool-call audit emitter uses below, so a
15485
16712
  // 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
16713
+ agent ? { id: agent.id, name: agent.name, slug: agent.slug } : void 0,
16714
+ { projectId: sandboxProjectId }
15487
16715
  );
15488
16716
  } catch (err3) {
15489
16717
  console.error(
@@ -15560,11 +16788,11 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15560
16788
  currentTools.push(sessionItemsRetrievalTool);
15561
16789
  }
15562
16790
  }
15563
- const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
16791
+ const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
15564
16792
  if (sessionFileReadTool && !disabled.has(sessionFileReadTool.id)) {
15565
16793
  currentTools.push(sessionFileReadTool);
15566
16794
  }
15567
- const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
16795
+ const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
15568
16796
  if (parseDocumentTool && !disabled.has(parseDocumentTool.id)) {
15569
16797
  currentTools.push(parseDocumentTool);
15570
16798
  }
@@ -15572,7 +16800,19 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15572
16800
  if (routineStatusTool && !disabled.has(routineStatusTool.id)) {
15573
16801
  currentTools.push(routineStatusTool);
15574
16802
  }
15575
- const viewDocumentPageTool = createViewDocumentPageTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
16803
+ const saveToProjectTool = createSaveToProjectTool({
16804
+ sessionID,
16805
+ user,
16806
+ req,
16807
+ exuluConfig,
16808
+ ownerId: sessionOwnerId,
16809
+ project: turnProject,
16810
+ disabled
16811
+ });
16812
+ if (saveToProjectTool) {
16813
+ currentTools.push(saveToProjectTool);
16814
+ }
16815
+ const viewDocumentPageTool = createViewDocumentPageTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
15576
16816
  if (viewDocumentPageTool && !disabled.has(viewDocumentPageTool.id)) {
15577
16817
  currentTools.push(viewDocumentPageTool);
15578
16818
  }
@@ -15710,10 +16950,12 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15710
16950
  // Never a plain `false` for a tool the user allowed for this chat: the
15711
16951
  // SDK re-validates an ANSWERED approval by calling needsApproval again
15712
16952
  // 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({
16953
+ needsApproval: cur.needsApprovalFn ? (input, opts) => cur.needsApprovalFn(input, opts) : isMemoryToolId(cur.id) ? true : (input, opts) => needsApprovalForCall({
15714
16954
  toolCallId: opts.toolCallId,
15715
16955
  messages: opts.messages,
15716
- approvedForSession,
16956
+ // alwaysAskWhen only removes the "allowed for this chat" shortcut for
16957
+ // that call; an answered approval still reads as true, so no denial loop.
16958
+ approvedForSession: approvedForSession && !cur.alwaysAskWhen?.(input),
15717
16959
  requiresApproval: !!cur.needsApproval
15718
16960
  // todo make configurable
15719
16961
  }),
@@ -15907,6 +17149,9 @@ export {
15907
17149
  resolveLiteLLMConfigPath,
15908
17150
  parseEmbeddingModels,
15909
17151
  getEmbeddingModelInfo,
17152
+ sanitizeFilename,
17153
+ MAX_PROJECT_FILES,
17154
+ projectFilePrefix,
15910
17155
  getPresignedUrl,
15911
17156
  uploadFile,
15912
17157
  listS3ObjectsByPrefix,
@@ -16023,12 +17268,35 @@ export {
16023
17268
  buildMemoryPromptBlock,
16024
17269
  normalizeRbac,
16025
17270
  collectMemoryDecisions,
16026
- sessionFilePrefix,
16027
- sanitizeFilename,
16028
17271
  isPublicSurface,
16029
17272
  treatAsGuest,
16030
17273
  KB_EDITOR_TOOL_ID,
16031
17274
  createKbEditorPickerTool,
17275
+ normalizeS3Key,
17276
+ deriveFilename,
17277
+ slugifyShareName,
17278
+ isExpired,
17279
+ validateCreateInput,
17280
+ readAgentSlots,
17281
+ canManageShare,
17282
+ validateUpdateInput,
17283
+ ownsObjectKey,
17284
+ planShareUpdate,
17285
+ hashSharePassword,
17286
+ verifySharePassword,
17287
+ contentHeadersFor,
17288
+ publicMetaFor,
17289
+ getSharedArtifactByName,
17290
+ MAX_ADOPT_UPLOAD_BYTES,
17291
+ planAdoptKeys,
17292
+ planAdoptSizeCheck,
17293
+ COPY_FAILED_REASON,
17294
+ promoteSessionFiles,
17295
+ sessionFilesScopeSentence,
17296
+ loadSessionFileListing,
17297
+ getOriginResolver,
17298
+ createPromoteS3,
17299
+ canRegisterSaveToProject,
16032
17300
  RBACResolver,
16033
17301
  resolveSkillByName,
16034
17302
  canAccessSkill,
@@ -16039,13 +17307,14 @@ export {
16039
17307
  parseSkillAuthorConfig,
16040
17308
  SKILL_AUTHOR_PROMPT,
16041
17309
  createSkillAuthorPickerTool,
16042
- isIgnoredArtifactPath,
16043
17310
  reportSystemDependencies,
16044
17311
  findUnclassifiedSecretShaped,
16045
17312
  getAuditLogger,
16046
17313
  initAudit,
17314
+ hasProjectAccess,
16047
17315
  downloadKeyIntoSandbox,
16048
17316
  refreshSessionSkills,
17317
+ resolveSessionProject,
16049
17318
  truncateToolOutput,
16050
17319
  DEFAULT_CONTEXT_WINDOW,
16051
17320
  deriveContextBudget,