@exulu/backend 5.11.1 → 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-FX6KTVPQ.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 z19 = 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
- z19[b] = dot;
6406
+ z21[b] = dot;
6175
6407
  }
6176
6408
  for (const [b, target] of next.entries()) {
6177
- const scale = z19[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(z19, 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) * (z19[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, z19] = applyMap(zi, map, intercept);
6304
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z19 - 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, z19] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6445
- return { x, y, z: z19 };
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;
@@ -9457,6 +9689,23 @@ var jobResultsSchema = {
9457
9689
  {
9458
9690
  name: "workflow",
9459
9691
  type: "text"
9692
+ },
9693
+ // Work status of a routine run — the fachliche status people work
9694
+ // with (spec 2026-11-16-routine-work-status-design), separate from
9695
+ // the technical `state`. A key from the routine's work_statuses.
9696
+ {
9697
+ name: "work_status",
9698
+ type: "text",
9699
+ index: true
9700
+ },
9701
+ {
9702
+ name: "work_status_updated_at",
9703
+ type: "date"
9704
+ },
9705
+ // { kind: "user" | "tool" | "agent" | "default", id?, user? }
9706
+ {
9707
+ name: "work_status_updated_by",
9708
+ type: "json"
9460
9709
  }
9461
9710
  ]
9462
9711
  };
@@ -9593,6 +9842,12 @@ var workflowTemplatesSchema = {
9593
9842
  type: "boolean",
9594
9843
  default: false
9595
9844
  },
9845
+ // Per-routine work statuses: { statuses: [{ key, label, color?, done? }], default }.
9846
+ // null / empty list = feature off for this routine.
9847
+ {
9848
+ name: "work_statuses",
9849
+ type: "json"
9850
+ },
9596
9851
  {
9597
9852
  name: "queue",
9598
9853
  type: "text"
@@ -11393,19 +11648,6 @@ function collectMemoryDecisions(messages) {
11393
11648
  import { z as z13 } from "zod";
11394
11649
  import { randomUUID as randomUUID3 } from "crypto";
11395
11650
 
11396
- // src/exulu/session-files.ts
11397
- function sessionFilePrefix(ownerId, sessionId, s3prefix) {
11398
- const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
11399
- return `${general}user_${ownerId}/sessions/${sessionId}/`;
11400
- }
11401
- function sanitizeFilename(name) {
11402
- const trimmed = name.trim();
11403
- if (!trimmed) return "";
11404
- if (trimmed.includes("..")) return "";
11405
- if (trimmed.startsWith("/") || trimmed.startsWith("\\")) return "";
11406
- return trimmed.replace(/[\\/]/g, "_");
11407
- }
11408
-
11409
11651
  // src/utils/check-item-write-access.ts
11410
11652
  var checkItemWriteAccess = async (context, record, user) => {
11411
11653
  if (!user) {
@@ -12288,77 +12530,635 @@ var collectKbWriteTools = (agent, contexts, deps = {}) => {
12288
12530
  return tools;
12289
12531
  };
12290
12532
 
12291
- // src/templates/tools/skill-author-tools.ts
12292
- import { randomUUID as randomUUID4 } from "crypto";
12533
+ // src/templates/tools/save-to-project-tool.ts
12293
12534
  import { z as z14 } from "zod";
12294
12535
 
12295
- // ee/rbac-resolver.ts
12296
- var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
12297
- const license = checkLicense();
12298
- if (!license.rbac) {
12299
- return {
12300
- type: "public",
12301
- users: [],
12302
- roles: [],
12303
- teams: []
12304
- };
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." };
12305
12559
  }
12306
- const rbacRecords = await db.from("rbac").where({
12307
- entity: entityName,
12308
- target_resource_id: resourceId
12309
- }).select("*");
12310
- const users = rbacRecords.filter((r) => r.access_type === "User")?.map((r) => ({ id: r.user_id, rights: r.rights }));
12311
- const roles = rbacRecords.filter((r) => r.access_type === "Role")?.map((r) => ({ id: r.role_id, rights: r.rights }));
12312
- const teams = rbacRecords.filter((r) => r.access_type === "Team")?.map((r) => ({ id: r.team_id, rights: r.rights }));
12313
- let type = rights_mode || "private";
12314
- if (type === "users" && users.length === 0) type = "private";
12315
- if (type === "roles" && roles.length === 0) type = "private";
12316
- if (type === "teams" && teams.length === 0) type = "private";
12317
- return {
12318
- type,
12319
- users,
12320
- roles,
12321
- teams
12322
- };
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 };
12323
12570
  };
12324
-
12325
- // src/skills/skill-access.ts
12326
- async function resolveSkillByName(db, name) {
12327
- const row = await db("skills").where({ name }).first();
12328
- return row ?? null;
12329
- }
12330
- async function canAccessSkill(db, skill, action, user) {
12331
- const rbac = await RBACResolver(db, "skill", skill.id, skill.rights_mode || "private");
12332
- return checkRecordAccess({ ...skill, RBAC: rbac }, action, user);
12333
- }
12334
- async function filterReadableSkills(db, skills, user) {
12335
- const out = [];
12336
- for (const s of skills) {
12337
- 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." };
12338
12574
  }
12339
- return out;
12340
- }
12341
-
12342
- // src/skills/frontmatter.ts
12343
- import JSZip from "jszip";
12344
- function parseFrontmatter(md) {
12345
- const match = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(md);
12346
- if (!match) return {};
12347
- const block = match[1];
12348
- const out = {};
12349
- for (const line of block.split(/\r?\n/)) {
12350
- const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
12351
- if (!m) continue;
12352
- const key = m[1];
12353
- let v = m[2].trim();
12354
- if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) {
12355
- 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." };
12356
12580
  }
12357
- 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 });
12358
12594
  }
12359
- return out;
12360
- }
12361
- async function parseSkillFrontmatter(zipBytes) {
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." };
12612
+ }
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) {
12362
13162
  let zip;
12363
13163
  try {
12364
13164
  zip = await JSZip.loadAsync(zipBytes);
@@ -12470,8 +13270,8 @@ description: ${yamlString(description)}
12470
13270
 
12471
13271
  ${content.replace(/^\s+/, "")}`;
12472
13272
  };
12473
- var generalPrefix = (config) => config?.fileUploads?.s3prefix ? `${String(config.fileUploads.s3prefix).replace(/\/+$/, "")}/` : "";
12474
- 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("/"));
12475
13275
  async function resolveSkill(db, ref) {
12476
13276
  const value = String(ref ?? "").trim();
12477
13277
  if (!value) return null;
@@ -12510,7 +13310,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12510
13310
  config: [],
12511
13311
  needsApproval: false,
12512
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.",
12513
- 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") }),
12514
13314
  execute: async (params) => {
12515
13315
  const { user } = params;
12516
13316
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -12536,9 +13336,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12536
13336
  config: [],
12537
13337
  needsApproval: false,
12538
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.",
12539
- inputSchema: z14.object({
12540
- skill: z14.string().describe("The skill's name or id"),
12541
- 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")
12542
13342
  }),
12543
13343
  execute: async (params) => {
12544
13344
  const { user, exuluConfig } = params;
@@ -12554,7 +13354,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12554
13354
  const path3 = params.path ? safeSkillPath(params.path) : "SKILL.md";
12555
13355
  if (!path3) return err2(`"${params.path}" is not a valid path inside the skill.`);
12556
13356
  if (!files.includes(path3)) return err2(`The skill has no file "${path3}". Files: ${files.join(", ") || "(none)"}`);
12557
- let content = await io.read(generalPrefix(exuluConfig) + prefix + path3, exuluConfig);
13357
+ let content = await io.read(generalPrefix2(exuluConfig) + prefix + path3, exuluConfig);
12558
13358
  if (Buffer.byteLength(content, "utf8") > MAX_READ_BYTES) content = content.slice(0, MAX_READ_BYTES) + "\n\u2026(truncated)";
12559
13359
  return {
12560
13360
  type: "skill_read",
@@ -12583,10 +13383,10 @@ ${content}`
12583
13383
  needsApproval: !config.skipApproval,
12584
13384
  needsApprovalFn: approvalFn,
12585
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.",
12586
- inputSchema: z14.object({
12587
- name: z14.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
12588
- description: z14.string().describe("One line: what the skill does and when to use it"),
12589
- 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")
12590
13390
  }),
12591
13391
  execute: async (params) => {
12592
13392
  const { user, exuluConfig } = params;
@@ -12652,12 +13452,12 @@ ${content}`
12652
13452
  needsApproval: !config.skipApproval,
12653
13453
  needsApprovalFn: approvalFn,
12654
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.",
12655
- inputSchema: z14.object({
12656
- skill: z14.string().describe("The skill's name or id"),
12657
- files: z14.array(z14.object({ path: z14.string(), content: z14.string() })).optional().describe("Files to add or replace, full content each"),
12658
- deletePaths: z14.array(z14.string()).optional().describe("Paths to remove in the new version"),
12659
- description: z14.string().optional().describe("A new one-line description, if it changed"),
12660
- 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'")
12661
13461
  }),
12662
13462
  execute: async (params) => {
12663
13463
  const { user, exuluConfig } = params;
@@ -12689,7 +13489,7 @@ ${content}`
12689
13489
  const newVersion = currentVersion + 1;
12690
13490
  const currentPrefix = `skills/${skill.id}/v${currentVersion}/`;
12691
13491
  const newPrefix = `skills/${skill.id}/v${newVersion}/`;
12692
- const gp = generalPrefix(exuluConfig);
13492
+ const gp = generalPrefix2(exuluConfig);
12693
13493
  const existing = await io.list(currentPrefix, exuluConfig);
12694
13494
  const changedPaths = new Set(changes.map((f) => f.path));
12695
13495
  const removedSet = new Set(removals);
@@ -12734,7 +13534,7 @@ var createSkillAuthorPickerTool = () => new ExuluTool({
12734
13534
  category: "default",
12735
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.",
12736
13536
  type: "function",
12737
- inputSchema: z14.object({}),
13537
+ inputSchema: z15.object({}),
12738
13538
  config: [
12739
13539
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
12740
13540
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -12751,38 +13551,11 @@ var collectSkillAuthorTools = (agent, deps = {}) => {
12751
13551
  import {
12752
13552
  SandboxManager
12753
13553
  } from "@anthropic-ai/sandbox-runtime";
12754
- 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";
12755
13555
  import { existsSync as existsSync4 } from "fs";
12756
- 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";
12757
13557
  import { exec as exec2, spawn } from "child_process";
12758
- import { promisify as promisify2 } from "util";
12759
-
12760
- // ee/invoke-skills/artifact-filter.ts
12761
- var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
12762
- "venv",
12763
- ".venv",
12764
- "env",
12765
- "node_modules",
12766
- "__pycache__",
12767
- "site-packages",
12768
- "dist-packages",
12769
- ".cache",
12770
- ".git",
12771
- ".pytest_cache",
12772
- ".mypy_cache",
12773
- ".ipynb_checkpoints"
12774
- ]);
12775
- function isIgnoredArtifactPath(relativePath) {
12776
- return relativePath.split(/[\\/]+/).some((segment) => IGNORED_SEGMENTS.has(segment));
12777
- }
12778
- var DEFAULT_ARTIFACT_CAP = 50;
12779
- function capArtifacts(artifacts, max = DEFAULT_ARTIFACT_CAP) {
12780
- if (artifacts.length <= max) return { kept: artifacts, omitted: 0 };
12781
- return { kept: artifacts.slice(0, max), omitted: artifacts.length - max };
12782
- }
12783
- function needsDownload(localSize, remoteSize) {
12784
- return localSize === void 0 || localSize !== remoteSize;
12785
- }
13558
+ import { promisify as promisify3 } from "util";
12786
13559
 
12787
13560
  // src/exulu/system-dependencies.ts
12788
13561
  import { exec } from "child_process";
@@ -13703,8 +14476,372 @@ var buildSkillSandboxEvent = (ctx, opts = {}) => {
13703
14476
  // ee/invoke-skills/create-sandbox.ts
13704
14477
  import { createBashTool } from "bash-tool";
13705
14478
  import { tool as tool2 } from "ai";
13706
- import { z as z15 } from "zod";
14479
+ import { z as z16 } from "zod";
13707
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
13708
14845
  var getAllExuluVariables = async () => {
13709
14846
  const { db } = await postgresClient();
13710
14847
  const rows = await db.from("variables").select("*");
@@ -13728,14 +14865,14 @@ var getAllExuluVariables = async () => {
13728
14865
  const granted = selectGrantedVariables(decrypted);
13729
14866
  return { granted, withheldNames: deriveWithheldNames(rows, granted) };
13730
14867
  };
13731
- var execAsync2 = promisify2(exec2);
14868
+ var execAsync2 = promisify3(exec2);
13732
14869
  var backendSecretFiles = () => {
13733
14870
  const cwd = process.cwd();
13734
14871
  const names = [".env", ".env.local", ".env.production", ".env.production.local"];
13735
14872
  const paths = /* @__PURE__ */ new Set();
13736
14873
  for (const name of names) {
13737
- paths.add(join2(cwd, name));
13738
- paths.add(join2("/app", name));
14874
+ paths.add(join4(cwd, name));
14875
+ paths.add(join4("/app", name));
13739
14876
  }
13740
14877
  return [...paths];
13741
14878
  };
@@ -13760,18 +14897,18 @@ function probeSandboxSupport() {
13760
14897
  if (process.platform !== "linux") {
13761
14898
  return { canSandbox: false, reason: `Unsupported platform: ${process.platform}` };
13762
14899
  }
13763
- return await new Promise((resolve3) => {
14900
+ return await new Promise((resolve4) => {
13764
14901
  const child = spawn("bwrap", ["--dev-bind", "/", "/", "--", "/bin/true"], { env: {} });
13765
14902
  let stderr = "";
13766
14903
  child.stderr.on("data", (chunk) => {
13767
14904
  stderr += chunk.toString();
13768
14905
  });
13769
14906
  child.on("error", (err3) => {
13770
- resolve3({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
14907
+ resolve4({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
13771
14908
  });
13772
14909
  child.on("exit", (code) => {
13773
- if (code === 0) resolve3({ canSandbox: true });
13774
- 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}` });
13775
14912
  });
13776
14913
  });
13777
14914
  })();
@@ -13806,23 +14943,46 @@ async function downloadSkill(skill, skillsDirectory, config) {
13806
14943
  `[SKILLS] No files found for skill "${skill.name}" at prefix "${versionPrefix}". Check that current_version matches what was uploaded to S3.`
13807
14944
  );
13808
14945
  }
14946
+ const sessionDir = dirname3(skillsDirectory);
14947
+ await ensureRealDirectory(sessionDir, `skills/${skill.name}`);
13809
14948
  for (const file of files) {
13810
14949
  const prefixIndex = file.key.indexOf(versionPrefix);
13811
14950
  const relativePath = prefixIndex >= 0 ? file.key.slice(prefixIndex + versionPrefix.length) : file.key;
13812
14951
  if (!relativePath) continue;
13813
- const localPath = join2(skillsDirectory, skill.name, relativePath);
13814
- await mkdir(dirname(localPath), { recursive: true });
13815
14952
  const bytes = await getS3ObjectBytes(file.key, config);
13816
- 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
+ }
13817
14959
  }
13818
14960
  }
13819
- function isArtifactPath(absPath, sessionDir) {
13820
- 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);
13821
14968
  const rel = relative(sessionDir, resolved);
13822
14969
  if (!rel || rel.startsWith("..")) return false;
13823
14970
  const first = rel.split("/")[0];
14971
+ if (opts.hasProject && first === PROJECT_DIR) return false;
13824
14972
  return first !== "skills";
13825
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
+ }
13826
14986
  function artifactS3Key(sessionId, relPath) {
13827
14987
  return `sessions/${sessionId}/${relPath}`;
13828
14988
  }
@@ -13861,11 +15021,13 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13861
15021
  const relativePath = idx >= 0 ? obj.key.slice(idx + userPrefix.length) : "";
13862
15022
  if (!relativePath) continue;
13863
15023
  if (isIgnoredArtifactPath(relativePath)) continue;
13864
- const localPath = join2(sessionDir, relativePath);
15024
+ if (opts.skipProjectDir && relativePath.split("/")[0] === PROJECT_DIR) continue;
15025
+ const localPath = join4(sessionDir, relativePath);
13865
15026
  if (opts.onlyMissing) {
13866
15027
  let localSize;
13867
15028
  try {
13868
- localSize = (await stat(localPath)).size;
15029
+ const st = await lstat3(localPath);
15030
+ localSize = st.isFile() ? st.size : void 0;
13869
15031
  } catch {
13870
15032
  localSize = void 0;
13871
15033
  }
@@ -13873,8 +15035,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13873
15035
  }
13874
15036
  try {
13875
15037
  const bytes = await getS3ObjectBytes(obj.key, config);
13876
- await mkdir(dirname(localPath), { recursive: true });
13877
- await writeFile(localPath, bytes);
15038
+ await writeFileInside(sessionDir, relativePath, bytes);
13878
15039
  } catch (err3) {
13879
15040
  console.error(
13880
15041
  `[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
@@ -13885,7 +15046,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13885
15046
  }
13886
15047
  async function downloadKeyIntoSandbox(opts) {
13887
15048
  const { sessionId, userId, fullS3Key, config } = opts;
13888
- const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
15049
+ const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
13889
15050
  if (!existsSync4(sessionDir)) {
13890
15051
  return { written: false };
13891
15052
  }
@@ -13898,10 +15059,8 @@ async function downloadKeyIntoSandbox(opts) {
13898
15059
  }
13899
15060
  const relativePath = fullS3Key.slice(idx + userPrefix.length);
13900
15061
  if (!relativePath) return { written: false };
13901
- const localPath = join2(sessionDir, relativePath);
13902
15062
  const bytes = await getS3ObjectBytes(fullS3Key, config);
13903
- await mkdir(dirname(localPath), { recursive: true });
13904
- await writeFile(localPath, bytes);
15063
+ const localPath = await writeFileInside(sessionDir, relativePath, bytes);
13905
15064
  return { written: true, localPath };
13906
15065
  }
13907
15066
  async function resolvePythonVenvPath() {
@@ -13916,42 +15075,55 @@ async function resolvePythonVenvPath() {
13916
15075
  async function refreshSessionSkills(sessionId, skills, config) {
13917
15076
  const cached = sandboxCache.get(sessionId);
13918
15077
  if (!cached) return { refreshed: 0, sandbox: false };
13919
- const skillsDirectory = join2(cached.handle.sessionDir, "skills");
15078
+ const skillsDirectory = join4(cached.handle.sessionDir, "skills");
13920
15079
  let refreshed = 0;
13921
15080
  for (const skill of skills) {
13922
- await rm(join2(skillsDirectory, skill.name), { recursive: true, force: true });
15081
+ await removeInstalledSkill(skillsDirectory, skill.name);
13923
15082
  await downloadSkill(skill, skillsDirectory, config);
13924
15083
  cached.installedSkills.set(skill.id, skill.current_version);
13925
15084
  refreshed++;
13926
15085
  }
13927
15086
  return { refreshed, sandbox: true };
13928
15087
  }
13929
- async function createSessionSandbox(sessionId, skills, config, userId, agent) {
15088
+ async function createSessionSandbox(sessionId, skills, config, userId, agent, opts = {}) {
13930
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
+ };
13931
15098
  if (cached) {
13932
- const skillsDirectory2 = join2(cached.handle.sessionDir, "skills");
15099
+ cached.projectState.projectId = projectId;
15100
+ const skillsDirectory2 = join4(cached.handle.sessionDir, "skills");
13933
15101
  for (const skill of skills) {
13934
15102
  const installedVersion = cached.installedSkills.get(skill.id);
13935
15103
  if (installedVersion === skill.current_version) continue;
13936
15104
  if (installedVersion !== void 0) {
13937
- await rm(join2(skillsDirectory2, skill.name), { recursive: true, force: true });
15105
+ await removeInstalledSkill(skillsDirectory2, skill.name);
13938
15106
  }
13939
15107
  await downloadSkill(skill, skillsDirectory2, config);
13940
15108
  cached.installedSkills.set(skill.id, skill.current_version);
13941
15109
  }
13942
15110
  if (userId && config.fileUploads) {
13943
15111
  try {
13944
- 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
+ });
13945
15116
  } catch (err3) {
13946
15117
  console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err3);
13947
15118
  }
13948
15119
  }
15120
+ await syncProject(cached.handle.sessionDir);
13949
15121
  return cached.handle;
13950
15122
  }
13951
- const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
15123
+ const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
13952
15124
  const dirExisted = existsSync4(sessionDir);
13953
- await mkdir(sessionDir, { recursive: true });
13954
- const skillsDirectory = join2(sessionDir, "skills");
15125
+ await mkdir3(sessionDir, { recursive: true });
15126
+ const skillsDirectory = join4(sessionDir, "skills");
13955
15127
  const installedSkills = /* @__PURE__ */ new Map();
13956
15128
  for (const skill of skills) {
13957
15129
  await downloadSkill(skill, skillsDirectory, config);
@@ -13964,8 +15136,13 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent) {
13964
15136
  );
13965
15137
  }
13966
15138
  if (userId && config.fileUploads) {
13967
- await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, { onlyMissing: dirExisted });
15139
+ await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, {
15140
+ onlyMissing: dirExisted,
15141
+ skipProjectDir: projectId !== null
15142
+ });
13968
15143
  }
15144
+ await syncProject(sessionDir);
15145
+ const projectState = { projectId };
13969
15146
  const probe = await probeSandboxSupport();
13970
15147
  const useDirectExec = !probe.canSandbox;
13971
15148
  if (useDirectExec) {
@@ -14044,7 +15221,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14044
15221
  extraSecretNames: litellmConfigSecretNames(),
14045
15222
  overrides: {
14046
15223
  ...npmGlobalRoot ? { NODE_PATH: npmGlobalRoot } : {},
14047
- ...pythonVenvPath ? { PATH: `${join2(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
15224
+ ...pythonVenvPath ? { PATH: `${join4(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
14048
15225
  }
14049
15226
  });
14050
15227
  if (skippedNames.length) {
@@ -14119,24 +15296,16 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14119
15296
  await writeFilesInternal(files);
14120
15297
  }
14121
15298
  };
14122
- async function persistArtifactToS3(absPath, content) {
14123
- 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 })) {
14124
15302
  return {};
14125
15303
  }
14126
- const rel = relative(sessionDir, resolve2(absPath));
15304
+ const rel = relative(sessionDir, resolve3(absPath));
14127
15305
  const s3Key = artifactS3Key(sessionId, rel);
14128
15306
  const out = {};
14129
15307
  try {
14130
- const fullKey = await uploadFile(
14131
- content,
14132
- s3Key,
14133
- config,
14134
- {},
14135
- // uploadFile's user param is typed as number, but the
14136
- // addUserPrefixToKey helper it delegates to accepts
14137
- // number | string at runtime — pass through as-is.
14138
- userId
14139
- );
15308
+ const fullKey = await uploadAgentArtifact(content, s3Key, config, userId);
14140
15309
  out.key = fullKey;
14141
15310
  const slashIdx = fullKey.indexOf("/");
14142
15311
  if (slashIdx > 0) {
@@ -14159,11 +15328,11 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14159
15328
  }
14160
15329
  return out;
14161
15330
  }
14162
- async function writeFilesInternal(files) {
15331
+ async function writeFilesInternal(files, hasProject = hasProjectNow()) {
14163
15332
  const results = [];
14164
15333
  for (const file of files) {
14165
15334
  const wrapped = await wrapIfNeeded(
14166
- `mkdir -p ${shellQuote(dirname(file.path))} && cat > ${shellQuote(file.path)}`
15335
+ `mkdir -p ${shellQuote(dirname3(file.path))} && cat > ${shellQuote(file.path)}`
14167
15336
  );
14168
15337
  await new Promise((resolveSpawn, rejectSpawn) => {
14169
15338
  const child = spawn("/bin/bash", ["-c", wrapped], { env: sandboxedExecEnv });
@@ -14182,7 +15351,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14182
15351
  const result = { path: file.path };
14183
15352
  const persisted = await persistArtifactToS3(
14184
15353
  file.path,
14185
- Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content)
15354
+ Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content),
15355
+ hasProject || hasProjectNow()
14186
15356
  );
14187
15357
  if (persisted.key) result.key = persisted.key;
14188
15358
  if (persisted.url) result.url = persisted.url;
@@ -14190,19 +15360,21 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14190
15360
  }
14191
15361
  return results;
14192
15362
  }
14193
- async function snapshotSessionArtifacts() {
15363
+ async function snapshotSessionArtifacts(hasProject) {
14194
15364
  const map = /* @__PURE__ */ new Map();
14195
- const skillsDir = join2(sessionDir, "skills");
15365
+ const skillsDir = join4(sessionDir, "skills");
15366
+ const projectDir = hasProject ? join4(sessionDir, PROJECT_DIR) : null;
14196
15367
  const walk = async (dir) => {
14197
15368
  let entries;
14198
15369
  try {
14199
- entries = await readdir(dir, { withFileTypes: true });
15370
+ entries = await readdir2(dir, { withFileTypes: true });
14200
15371
  } catch {
14201
15372
  return;
14202
15373
  }
14203
15374
  for (const entry of entries) {
14204
- const full = join2(dir, entry.name);
15375
+ const full = join4(dir, entry.name);
14205
15376
  if (full === skillsDir) continue;
15377
+ if (projectDir !== null && full === projectDir) continue;
14206
15378
  if (isIgnoredArtifactPath(relative(sessionDir, full))) continue;
14207
15379
  if (entry.isDirectory()) {
14208
15380
  await walk(full);
@@ -14227,13 +15399,14 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14227
15399
  });
14228
15400
  const writeFileTool = tool2({
14229
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.',
14230
- inputSchema: z15.object({
14231
- 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."),
14232
- 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")
14233
15405
  }),
14234
15406
  execute: async ({ path: path3, content }) => {
15407
+ const hasProject = hasProjectNow();
14235
15408
  const resolvedPath = resolveSessionPath(path3, sessionDir);
14236
- const results = await writeFilesInternal([{ path: resolvedPath, content }]);
15409
+ const results = await writeFilesInternal([{ path: resolvedPath, content }], hasProject);
14237
15410
  const result = results[0];
14238
15411
  if (!result) {
14239
15412
  throw new Error(`writeFile ${resolvedPath} produced no result`);
@@ -14248,8 +15421,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14248
15421
  });
14249
15422
  const readFileTool = tool2({
14250
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.',
14251
- inputSchema: z15.object({
14252
- 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.")
14253
15426
  }),
14254
15427
  execute: async ({ path: path3 }) => {
14255
15428
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -14266,19 +15439,21 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14266
15439
  const originalBashTool = tools.bash;
14267
15440
  const bashTool = tool2({
14268
15441
  description: originalBashTool.description ?? "",
14269
- inputSchema: z15.object({
14270
- command: z15.string().describe("The bash command to execute.")
15442
+ inputSchema: z16.object({
15443
+ command: z16.string().describe("The bash command to execute.")
14271
15444
  }),
14272
- execute: async (args, opts) => {
14273
- const before = persistenceEnabled ? await snapshotSessionArtifacts() : null;
15445
+ execute: async (args, opts2) => {
15446
+ const hasProject = hasProjectNow();
15447
+ const before = persistenceEnabled ? await snapshotSessionArtifacts(hasProject) : null;
14274
15448
  const originalExecute = originalBashTool.execute;
14275
15449
  if (!originalExecute) {
14276
15450
  throw new Error("bash tool execute is undefined");
14277
15451
  }
14278
- const result = await originalExecute(args, opts);
15452
+ const result = await originalExecute(args, opts2);
14279
15453
  const artifacts = [];
14280
15454
  if (persistenceEnabled && before) {
14281
- const after = await snapshotSessionArtifacts();
15455
+ const skipProject = hasProject || hasProjectNow();
15456
+ const after = await snapshotSessionArtifacts(skipProject);
14282
15457
  const changedPaths = [];
14283
15458
  for (const [path3, mtime] of after) {
14284
15459
  const beforeMtime = before.get(path3);
@@ -14288,8 +15463,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
14288
15463
  }
14289
15464
  for (const path3 of changedPaths) {
14290
15465
  try {
14291
- const content = await fsReadFile(path3);
14292
- 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);
14293
15469
  artifacts.push({
14294
15470
  path: path3,
14295
15471
  relativePath: relative(sessionDir, path3),
@@ -14336,13 +15512,82 @@ ${lines.join("\n")}`;
14336
15512
  if (!useDirectExec) {
14337
15513
  await SandboxManager.reset();
14338
15514
  }
14339
- await rm(sessionDir, { recursive: true, force: true });
15515
+ await rm2(sessionDir, { recursive: true, force: true });
15516
+ await clearProjectSyncMarker(sessionDir);
14340
15517
  }
14341
15518
  };
14342
- sandboxCache.set(sessionId, { handle, installedSkills });
15519
+ sandboxCache.set(sessionId, { handle, installedSkills, projectState });
14343
15520
  return handle;
14344
15521
  }
14345
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
+
15560
+ // src/templates/tools/routine-status-tool.ts
15561
+ import { z as z17 } from "zod";
15562
+ var SET_ROUTINE_STATUS_TOOL_ID = "set_routine_status";
15563
+ function createRoutineStatusTool(handle) {
15564
+ if (!handle || handle.statuses.length === 0) return void 0;
15565
+ const keys = handle.statuses.map((status) => status.key);
15566
+ const labelOf = (key) => handle.statuses.find((status) => status.key === key)?.label ?? key;
15567
+ return new ExuluTool({
15568
+ id: SET_ROUTINE_STATUS_TOOL_ID,
15569
+ name: "Set routine status",
15570
+ description: `Sets the work status of this run of the routine "${handle.name}" for the people working the run list. Use it when the step instructions tell you to, with exactly one of these values: ` + handle.statuses.map((status) => `${status.key} \u2014 ${status.label}`).join("; ") + ".",
15571
+ category: "routines",
15572
+ type: "function",
15573
+ needsApproval: false,
15574
+ inputSchema: z17.object({
15575
+ status: z17.enum(keys).describe("The work status key to set.")
15576
+ }),
15577
+ config: [],
15578
+ execute: async ({ status }) => {
15579
+ const decision = await handle.runs.current.updateWithResult({ status });
15580
+ if (decision?.action === "skip" && decision.reason === "human_set") {
15581
+ return {
15582
+ result: `A person already set the status to "${labelOf(handle.runs.current.status ?? "")}"; left unchanged.`
15583
+ };
15584
+ }
15585
+ if (decision?.action === "skip") return { result: `Status is already "${labelOf(status)}".` };
15586
+ return { result: `Status set to "${labelOf(status)}".` };
15587
+ }
15588
+ });
15589
+ }
15590
+
14346
15591
  // src/utils/truncate-tool-output.ts
14347
15592
  var truncateToolOutput = (output, maxContextLength, toolName, tailFraction = 0.1, charLimitOverride) => {
14348
15593
  const effectiveCtx = maxContextLength != null && maxContextLength > 0 ? maxContextLength : 128e3;
@@ -14539,7 +15784,30 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
14539
15784
  };
14540
15785
 
14541
15786
  // src/templates/tools/session-file-read-tool.ts
14542
- import { z as z16 } 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
14543
15811
  var DEFAULT_LIMIT = 250;
14544
15812
  var MAX_CONTENT_CHARS = 16e3;
14545
15813
  var SESSION_FILE_READ_TOOL_NAME = "read_session_file";
@@ -14547,18 +15815,22 @@ var createSessionFileReadTool = ({
14547
15815
  sessionID,
14548
15816
  user,
14549
15817
  exuluConfig,
14550
- ownerId
15818
+ ownerId,
15819
+ projectId
14551
15820
  }) => {
14552
15821
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
14553
15822
  const readSessionFileExecute = async ({ filename, offset, limit }) => {
14554
- const safeName = String(filename ?? "").trim();
14555
- if (!safeName || safeName.includes("..") || safeName.includes("/") || safeName.includes("\\")) {
14556
- return {
14557
- error: "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths)."
14558
- };
14559
- }
14560
15823
  const uploads = exuluConfig.fileUploads;
14561
- 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();
14562
15834
  try {
14563
15835
  const url = await getPresignedUrl(uploads.s3Bucket, key, exuluConfig);
14564
15836
  const res = await fetch(url);
@@ -14591,11 +15863,11 @@ var createSessionFileReadTool = ({
14591
15863
  id: "read_session_file",
14592
15864
  name: SESSION_FILE_READ_TOOL_NAME,
14593
15865
  needsApproval: false,
14594
- 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.",
14595
- inputSchema: z16.object({
14596
- filename: z16.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
14597
- offset: z16.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
14598
- limit: z16.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})`)
14599
15871
  }),
14600
15872
  type: "function",
14601
15873
  category: "session",
@@ -14608,18 +15880,18 @@ var createSessionFileReadTool = ({
14608
15880
  };
14609
15881
 
14610
15882
  // src/templates/tools/parse-document-tool.ts
14611
- import { z as z17 } from "zod";
15883
+ import { z as z19 } from "zod";
14612
15884
  import { extname } from "path";
14613
15885
  import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
14614
15886
 
14615
15887
  // src/templates/tools/document-render-helpers.ts
14616
- import { execFile } from "child_process";
14617
- import { promisify as promisify3 } from "util";
15888
+ import { execFile as execFile2 } from "child_process";
15889
+ import { promisify as promisify4 } from "util";
14618
15890
  import { existsSync as existsSync5 } from "fs";
14619
- 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";
14620
15892
  import { tmpdir } from "os";
14621
- import { join as join3 } from "path";
14622
- var execFileAsync = promisify3(execFile);
15893
+ import { join as join5 } from "path";
15894
+ var execFileAsync2 = promisify4(execFile2);
14623
15895
  var MAX_STDOUT_BYTES = 64 * 1024 * 1024;
14624
15896
  var LEGACY_OFFICE_CONVERSION_TARGETS = {
14625
15897
  ".doc": "docx",
@@ -14635,12 +15907,12 @@ async function convertLegacyOfficeToModern(bytes, ext) {
14635
15907
  if (!target) {
14636
15908
  throw new Error(`No modern-format conversion target registered for "${ext}"`);
14637
15909
  }
14638
- const dir = await mkdtemp(join3(tmpdir(), "exulu-officeconv-"));
15910
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-officeconv-"));
14639
15911
  try {
14640
- const inputPath = join3(dir, `input${ext}`);
14641
- await writeFile2(inputPath, bytes);
15912
+ const inputPath = join5(dir, `input${ext}`);
15913
+ await writeFile3(inputPath, bytes);
14642
15914
  try {
14643
- await execFileAsync(
15915
+ await execFileAsync2(
14644
15916
  "soffice",
14645
15917
  ["--headless", "--convert-to", target, inputPath, "--outdir", dir],
14646
15918
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
@@ -14650,62 +15922,62 @@ async function convertLegacyOfficeToModern(bytes, ext) {
14650
15922
  `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err3 instanceof Error ? err3.message : String(err3))
14651
15923
  );
14652
15924
  }
14653
- const outputPath = join3(dir, `input.${target}`);
15925
+ const outputPath = join5(dir, `input.${target}`);
14654
15926
  if (!existsSync5(outputPath)) {
14655
15927
  throw new Error(`LibreOffice produced no output converting "${ext}" to ${target}`);
14656
15928
  }
14657
- return await readFile(outputPath);
15929
+ return await readFile2(outputPath);
14658
15930
  } finally {
14659
- await rm2(dir, { recursive: true, force: true });
15931
+ await rm3(dir, { recursive: true, force: true });
14660
15932
  }
14661
15933
  }
14662
15934
  async function pdfToText(pdf) {
14663
- const dir = await mkdtemp(join3(tmpdir(), "exulu-parse-"));
15935
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-parse-"));
14664
15936
  try {
14665
- const inputPath = join3(dir, "input.pdf");
14666
- await writeFile2(inputPath, pdf);
14667
- 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, "-"], {
14668
15940
  timeout: 6e4,
14669
15941
  maxBuffer: MAX_STDOUT_BYTES
14670
15942
  });
14671
15943
  return stdout;
14672
15944
  } finally {
14673
- await rm2(dir, { recursive: true, force: true });
15945
+ await rm3(dir, { recursive: true, force: true });
14674
15946
  }
14675
15947
  }
14676
15948
  async function pdfPageCount(pdf) {
14677
- const dir = await mkdtemp(join3(tmpdir(), "exulu-pdfinfo-"));
15949
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-pdfinfo-"));
14678
15950
  try {
14679
- const inputPath = join3(dir, "input.pdf");
14680
- await writeFile2(inputPath, pdf);
14681
- 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 });
14682
15954
  const match = /^Pages:\s+(\d+)/m.exec(stdout);
14683
15955
  if (!match) throw new Error("pdfinfo did not report a page count");
14684
15956
  return Number(match[1]);
14685
15957
  } finally {
14686
- await rm2(dir, { recursive: true, force: true });
15958
+ await rm3(dir, { recursive: true, force: true });
14687
15959
  }
14688
15960
  }
14689
15961
  async function renderPdfPageToPng(pdf, page, scaleTo) {
14690
- const dir = await mkdtemp(join3(tmpdir(), "exulu-render-"));
15962
+ const dir = await mkdtemp(join5(tmpdir(), "exulu-render-"));
14691
15963
  try {
14692
- const inputPath = join3(dir, "input.pdf");
14693
- await writeFile2(inputPath, pdf);
15964
+ const inputPath = join5(dir, "input.pdf");
15965
+ await writeFile3(inputPath, pdf);
14694
15966
  try {
14695
- await execFileAsync(
15967
+ await execFileAsync2(
14696
15968
  "pdftoppm",
14697
- ["-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")],
14698
15970
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
14699
15971
  );
14700
15972
  } catch (err3) {
14701
15973
  if (err3?.code === 99) return null;
14702
15974
  throw err3;
14703
15975
  }
14704
- 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"));
14705
15977
  if (!produced) return null;
14706
- return await readFile(join3(dir, produced));
15978
+ return await readFile2(join5(dir, produced));
14707
15979
  } finally {
14708
- await rm2(dir, { recursive: true, force: true });
15980
+ await rm3(dir, { recursive: true, force: true });
14709
15981
  }
14710
15982
  }
14711
15983
 
@@ -14874,7 +16146,8 @@ var createParseDocumentTool = ({
14874
16146
  sessionID,
14875
16147
  user,
14876
16148
  exuluConfig,
14877
- ownerId
16149
+ ownerId,
16150
+ projectId
14878
16151
  }) => {
14879
16152
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
14880
16153
  const parseDocumentExecute = async ({
@@ -14883,12 +16156,16 @@ var createParseDocumentTool = ({
14883
16156
  offset,
14884
16157
  limit
14885
16158
  }) => {
14886
- const safeName = String(filename ?? "").trim();
14887
- if (!safeName || safeName.includes("..") || safeName.includes("/") || safeName.includes("\\")) {
14888
- return {
14889
- error: "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths)."
14890
- };
14891
- }
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();
14892
16169
  const ext = extname(safeName).toLowerCase();
14893
16170
  if (ext !== ".pdf" && !OFFICE_EXTENSIONS.has(ext)) {
14894
16171
  return {
@@ -14899,7 +16176,6 @@ var createParseDocumentTool = ({
14899
16176
  return { error: `The pages option is only supported for PDF files \u2014 "${ext}" documents are extracted whole.` };
14900
16177
  }
14901
16178
  const uploads = exuluConfig.fileUploads;
14902
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
14903
16179
  try {
14904
16180
  const url = await getPresignedUrl(uploads.s3Bucket, key, exuluConfig);
14905
16181
  const res = await fetch(url);
@@ -14976,12 +16252,12 @@ ${text.trim()}`).join("\n");
14976
16252
  id: "parse_document",
14977
16253
  name: PARSE_DOCUMENT_TOOL_NAME,
14978
16254
  needsApproval: false,
14979
- 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.`,
14980
- inputSchema: z17.object({
14981
- filename: z17.string().describe('Exact session file name, e.g. "report.pdf"'),
14982
- pages: z17.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14983
- offset: z17.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14984
- limit: z17.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})`)
14985
16261
  }),
14986
16262
  type: "function",
14987
16263
  category: "session",
@@ -14994,19 +16270,19 @@ ${text.trim()}`).join("\n");
14994
16270
  };
14995
16271
 
14996
16272
  // src/templates/tools/view-document-page-tool.ts
14997
- import { z as z18 } from "zod";
16273
+ import { z as z20 } from "zod";
14998
16274
  import { extname as extname3 } from "path";
14999
16275
 
15000
16276
  // src/sessions/pdf-preview-cache.ts
15001
16277
  import { exec as exec3 } from "child_process";
15002
16278
  import { existsSync as existsSync6 } from "fs";
15003
- import { mkdir as mkdir2, readFile as readFile2, rename, rm as rm3, writeFile as writeFile3 } from "fs/promises";
15004
- import { extname as extname2, join as join4 } from "path";
15005
- import { promisify as promisify4 } from "util";
15006
- 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);
15007
16283
  var CACHE_ROOT = "/tmp/exulu-pdf-cache";
15008
- var CACHE_IN = join4(CACHE_ROOT, "_in");
15009
- var CACHE_OUT = join4(CACHE_ROOT, "_out");
16284
+ var CACHE_IN = join6(CACHE_ROOT, "_in");
16285
+ var CACHE_OUT = join6(CACHE_ROOT, "_out");
15010
16286
  var inFlight = /* @__PURE__ */ new Map();
15011
16287
  var PreviewRenderError = class extends Error {
15012
16288
  constructor(message) {
@@ -15023,22 +16299,22 @@ async function getPdfPreviewBytes(opts) {
15023
16299
  if (!safeEtag) {
15024
16300
  throw new PreviewRenderError(`Invalid ETag for ${sourceKey}`);
15025
16301
  }
15026
- const cachedPath = join4(CACHE_ROOT, `${safeEtag}.pdf`);
16302
+ const cachedPath = join6(CACHE_ROOT, `${safeEtag}.pdf`);
15027
16303
  if (existsSync6(cachedPath)) {
15028
- return readFile2(cachedPath);
16304
+ return readFile3(cachedPath);
15029
16305
  }
15030
16306
  const existing = inFlight.get(safeEtag);
15031
16307
  if (existing) return existing;
15032
16308
  const promise = (async () => {
15033
16309
  try {
15034
- await mkdir2(CACHE_IN, { recursive: true });
15035
- await mkdir2(CACHE_OUT, { recursive: true });
16310
+ await mkdir4(CACHE_IN, { recursive: true });
16311
+ await mkdir4(CACHE_OUT, { recursive: true });
15036
16312
  const ext = (extname2(sourceKey) || ".docx").toLowerCase();
15037
- const inputPath = join4(CACHE_IN, `${safeEtag}${ext}`);
15038
- const outputPath = join4(CACHE_OUT, `${safeEtag}.pdf`);
16313
+ const inputPath = join6(CACHE_IN, `${safeEtag}${ext}`);
16314
+ const outputPath = join6(CACHE_OUT, `${safeEtag}.pdf`);
15039
16315
  try {
15040
16316
  const bytes = await getS3ObjectBytes(sourceKey, config);
15041
- await writeFile3(inputPath, bytes);
16317
+ await writeFile4(inputPath, bytes);
15042
16318
  try {
15043
16319
  await execAsync3(
15044
16320
  `soffice --headless --convert-to pdf "${inputPath}" --outdir "${CACHE_OUT}"`,
@@ -15054,10 +16330,10 @@ async function getPdfPreviewBytes(opts) {
15054
16330
  `LibreOffice produced no output for ${sourceKey} (etag ${etag})`
15055
16331
  );
15056
16332
  }
15057
- await rename(outputPath, cachedPath);
15058
- return await readFile2(cachedPath);
16333
+ await rename3(outputPath, cachedPath);
16334
+ return await readFile3(cachedPath);
15059
16335
  } finally {
15060
- await rm3(inputPath, { force: true });
16336
+ await rm4(inputPath, { force: true });
15061
16337
  }
15062
16338
  } finally {
15063
16339
  inFlight.delete(safeEtag);
@@ -15173,16 +16449,21 @@ var createViewDocumentPageTool = ({
15173
16449
  sessionID,
15174
16450
  user,
15175
16451
  exuluConfig,
15176
- ownerId
16452
+ ownerId,
16453
+ projectId
15177
16454
  }) => {
15178
16455
  if (!sessionID || !exuluConfig?.fileUploads?.s3Bucket) return void 0;
15179
16456
  const viewDocumentPageExecute = async ({ filename, page, model }, options) => {
15180
- const safeName = String(filename ?? "").trim();
15181
- if (!safeName || safeName.includes("..") || safeName.includes("/") || safeName.includes("\\")) {
15182
- return {
15183
- error: "Invalid filename \u2014 pass the bare file name exactly as listed in the session files (no paths)."
15184
- };
15185
- }
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();
15186
16467
  const ext = extname3(safeName).toLowerCase();
15187
16468
  const isImage = ext in IMAGE_MEDIA_TYPES;
15188
16469
  const isPdf = ext === ".pdf";
@@ -15205,8 +16486,6 @@ var createViewDocumentPageTool = ({
15205
16486
  } catch {
15206
16487
  }
15207
16488
  }
15208
- const uploads = exuluConfig.fileUploads;
15209
- const key = `${sessionFilePrefix(ownerId ?? user?.id ?? "api", sessionID, uploads.s3prefix)}${safeName}`;
15210
16489
  const pageNumber = page ?? 1;
15211
16490
  try {
15212
16491
  let imageBytes;
@@ -15264,10 +16543,10 @@ var createViewDocumentPageTool = ({
15264
16543
  id: "view_document_page",
15265
16544
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
15266
16545
  needsApproval: false,
15267
- 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.",
15268
- inputSchema: z18.object({
15269
- filename: z18.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
15270
- page: z18.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)")
15271
16550
  }),
15272
16551
  type: "function",
15273
16552
  category: "session",
@@ -15409,7 +16688,7 @@ var hydrateVariables = async (tool3) => {
15409
16688
  await Promise.all(promises);
15410
16689
  return tool3;
15411
16690
  };
15412
- var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions, skillDecisions) => {
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) => {
15413
16692
  if (!currentTools) return {};
15414
16693
  if (!allExuluTools) {
15415
16694
  allExuluTools = [];
@@ -15419,6 +16698,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15419
16698
  }
15420
16699
  const budget = deriveContextBudget(contextWindow);
15421
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;
15422
16703
  let sharedSessionSandbox;
15423
16704
  if (sessionID && exuluConfig && agent?.sandbox_enabled === true) {
15424
16705
  try {
@@ -15429,7 +16710,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15429
16710
  sessionOwnerId ?? user?.id,
15430
16711
  // Same agent descriptor the tool-call audit emitter uses below, so a
15431
16712
  // skill.sandbox.created event can be joined to the agent that caused it.
15432
- 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 }
15433
16715
  );
15434
16716
  } catch (err3) {
15435
16717
  console.error(
@@ -15506,15 +16788,31 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15506
16788
  currentTools.push(sessionItemsRetrievalTool);
15507
16789
  }
15508
16790
  }
15509
- const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
16791
+ const sessionFileReadTool = createSessionFileReadTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
15510
16792
  if (sessionFileReadTool && !disabled.has(sessionFileReadTool.id)) {
15511
16793
  currentTools.push(sessionFileReadTool);
15512
16794
  }
15513
- const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
16795
+ const parseDocumentTool = createParseDocumentTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId, projectId: sandboxProjectId });
15514
16796
  if (parseDocumentTool && !disabled.has(parseDocumentTool.id)) {
15515
16797
  currentTools.push(parseDocumentTool);
15516
16798
  }
15517
- const viewDocumentPageTool = createViewDocumentPageTool({ sessionID, user, exuluConfig, ownerId: sessionOwnerId });
16799
+ const routineStatusTool = createRoutineStatusTool(routineHandleFactory?.({ kind: "agent" }));
16800
+ if (routineStatusTool && !disabled.has(routineStatusTool.id)) {
16801
+ currentTools.push(routineStatusTool);
16802
+ }
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 });
15518
16816
  if (viewDocumentPageTool && !disabled.has(viewDocumentPageTool.id)) {
15519
16817
  currentTools.push(viewDocumentPageTool);
15520
16818
  }
@@ -15652,10 +16950,12 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15652
16950
  // Never a plain `false` for a tool the user allowed for this chat: the
15653
16951
  // SDK re-validates an ANSWERED approval by calling needsApproval again
15654
16952
  // and reads `false` as "deny" — see approval-revalidation.ts.
15655
- 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({
15656
16954
  toolCallId: opts.toolCallId,
15657
16955
  messages: opts.messages,
15658
- 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),
15659
16959
  requiresApproval: !!cur.needsApproval
15660
16960
  // todo make configurable
15661
16961
  }),
@@ -15759,7 +17059,9 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15759
17059
  contexts: contextsMap,
15760
17060
  upload,
15761
17061
  exuluConfig,
15762
- toolVariablesConfig: toolVariablesConfigData
17062
+ toolVariablesConfig: toolVariablesConfigData,
17063
+ // Present only inside a routine run: routine.runs.current.update({ status }).
17064
+ routine: routineHandleFactory?.({ kind: "tool", id: cur.id })
15763
17065
  },
15764
17066
  options
15765
17067
  );
@@ -15847,6 +17149,9 @@ export {
15847
17149
  resolveLiteLLMConfigPath,
15848
17150
  parseEmbeddingModels,
15849
17151
  getEmbeddingModelInfo,
17152
+ sanitizeFilename,
17153
+ MAX_PROJECT_FILES,
17154
+ projectFilePrefix,
15850
17155
  getPresignedUrl,
15851
17156
  uploadFile,
15852
17157
  listS3ObjectsByPrefix,
@@ -15963,12 +17268,35 @@ export {
15963
17268
  buildMemoryPromptBlock,
15964
17269
  normalizeRbac,
15965
17270
  collectMemoryDecisions,
15966
- sessionFilePrefix,
15967
- sanitizeFilename,
15968
17271
  isPublicSurface,
15969
17272
  treatAsGuest,
15970
17273
  KB_EDITOR_TOOL_ID,
15971
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,
15972
17300
  RBACResolver,
15973
17301
  resolveSkillByName,
15974
17302
  canAccessSkill,
@@ -15979,13 +17307,14 @@ export {
15979
17307
  parseSkillAuthorConfig,
15980
17308
  SKILL_AUTHOR_PROMPT,
15981
17309
  createSkillAuthorPickerTool,
15982
- isIgnoredArtifactPath,
15983
17310
  reportSystemDependencies,
15984
17311
  findUnclassifiedSecretShaped,
15985
17312
  getAuditLogger,
15986
17313
  initAudit,
17314
+ hasProjectAccess,
15987
17315
  downloadKeyIntoSandbox,
15988
17316
  refreshSessionSkills,
17317
+ resolveSessionProject,
15989
17318
  truncateToolOutput,
15990
17319
  DEFAULT_CONTEXT_WINDOW,
15991
17320
  deriveContextBudget,