@exulu/backend 5.14.0 → 5.15.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.
@@ -599,7 +599,7 @@ var ExuluTool = class _ExuluTool {
599
599
  name,
600
600
  description,
601
601
  category,
602
- inputSchema,
602
+ inputSchema: inputSchema2,
603
603
  type,
604
604
  execute,
605
605
  config,
@@ -628,11 +628,11 @@ var ExuluTool = class _ExuluTool {
628
628
  this.category = category || "default";
629
629
  this.name = name;
630
630
  this.description = description;
631
- this.inputSchema = inputSchema;
631
+ this.inputSchema = inputSchema2;
632
632
  this.type = type;
633
633
  this.tool = tool({
634
634
  description,
635
- inputSchema: inputSchema || z.object({}),
635
+ inputSchema: inputSchema2 || z.object({}),
636
636
  execute: authentication2 ? wrapExecuteWithAuth(id, authentication2, execute) : execute
637
637
  });
638
638
  }
@@ -669,7 +669,7 @@ var ExuluTool = class _ExuluTool {
669
669
  if (!agent) {
670
670
  throw new Error("Agent not found.");
671
671
  }
672
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-UT7TOLLD.js");
672
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-GLRM3PM6.js");
673
673
  const tools = await convertExuluToolsToAiSdkTools2(
674
674
  [this],
675
675
  [],
@@ -3945,7 +3945,7 @@ function sanitizeToolName(name) {
3945
3945
  }
3946
3946
 
3947
3947
  // src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts
3948
- import { randomUUID as randomUUID8 } from "crypto";
3948
+ import { randomUUID as randomUUID9 } from "crypto";
3949
3949
 
3950
3950
  // types/enums/statistics.ts
3951
3951
  var STATISTICS_TYPE_ENUM = {
@@ -4459,7 +4459,7 @@ var uploadFile = async (file, fileName, config, options = {}, user, customBucket
4459
4459
  if (error.name === "SignatureDoesNotMatch" || error.name === "InvalidAccessKeyId" || error.name === "AccessDenied") {
4460
4460
  if (attempt < maxRetries) {
4461
4461
  const backoffMs = Math.pow(2, attempt) * 1e3;
4462
- await new Promise((resolve4) => setTimeout(resolve4, backoffMs));
4462
+ await new Promise((resolve5) => setTimeout(resolve5, backoffMs));
4463
4463
  s3Client = void 0;
4464
4464
  getS3Client(config);
4465
4465
  continue;
@@ -6570,14 +6570,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
6570
6570
  for (const row of rows) {
6571
6571
  const centered = new Float64Array(dims);
6572
6572
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
6573
- const z22 = new Float64Array(basis.length);
6573
+ const z24 = new Float64Array(basis.length);
6574
6574
  for (const [b, vec] of basis.entries()) {
6575
6575
  let dot = 0;
6576
6576
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
6577
- z22[b] = dot;
6577
+ z24[b] = dot;
6578
6578
  }
6579
6579
  for (const [b, target] of next.entries()) {
6580
- const scale = z22[b] ?? 0;
6580
+ const scale = z24[b] ?? 0;
6581
6581
  if (scale === 0) continue;
6582
6582
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
6583
6583
  }
@@ -6675,12 +6675,12 @@ function ridgeFit(Z, Y, lambda) {
6675
6675
  });
6676
6676
  return { map, intercept };
6677
6677
  }
6678
- function applyMap(z22, map, intercept) {
6678
+ function applyMap(z24, map, intercept) {
6679
6679
  const out = [];
6680
6680
  for (let j = 0; j < 3; j += 1) {
6681
6681
  let v = intercept[j] ?? 0;
6682
6682
  const row = map[j] ?? [];
6683
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z22[d] ?? 0);
6683
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z24[d] ?? 0);
6684
6684
  out.push(Number.isFinite(v) ? v : 0);
6685
6685
  }
6686
6686
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -6703,8 +6703,8 @@ function fitResidual(Z, Y, map, intercept) {
6703
6703
  for (let i = 0; i < Z.length; i += 1) {
6704
6704
  const zi = Z[i] ?? [];
6705
6705
  const yi = Y[i] ?? [];
6706
- const [x, y, z22] = applyMap(zi, map, intercept);
6707
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z22 - finite(yi[2]));
6706
+ const [x, y, z24] = applyMap(zi, map, intercept);
6707
+ total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z24 - finite(yi[2]));
6708
6708
  }
6709
6709
  return finite(total / Z.length);
6710
6710
  }
@@ -6844,8 +6844,8 @@ async function chunkCoordinates({
6844
6844
  }
6845
6845
  return null;
6846
6846
  }
6847
- const [x, y, z22] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6848
- return { x, y, z: z22 };
6847
+ const [x, y, z24] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6848
+ return { x, y, z: z24 };
6849
6849
  });
6850
6850
  } catch (e) {
6851
6851
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -6931,8 +6931,8 @@ var captureCodeEmbedder = (context) => {
6931
6931
  };
6932
6932
  var codeEmbedderFor = (context) => codeEmbedders.has(context) ? codeEmbedders.get(context) : context.embedder;
6933
6933
  var contextEmbedderInfoFor = async (context, deps = {}) => {
6934
- const resolve4 = deps.resolve ?? resolveContextEmbedder;
6935
- return resolve4({ id: context.id, embedder: codeEmbedderFor(context) });
6934
+ const resolve5 = deps.resolve ?? resolveContextEmbedder;
6935
+ return resolve5({ id: context.id, embedder: codeEmbedderFor(context) });
6936
6936
  };
6937
6937
  var willEmbedOnQueue = async (context, overrideQueue) => {
6938
6938
  if (overrideQueue) {
@@ -6941,11 +6941,11 @@ var willEmbedOnQueue = async (context, overrideQueue) => {
6941
6941
  return Boolean(await codeEmbedderFor(context)?.queue);
6942
6942
  };
6943
6943
  var hydrateContextEmbedders = async (contexts, deps = {}) => {
6944
- const { resolve: resolve4, modelInfo, queues } = { ...defaultDeps(), ...deps };
6944
+ const { resolve: resolve5, modelInfo, queues } = { ...defaultDeps(), ...deps };
6945
6945
  for (const context of contexts) {
6946
6946
  try {
6947
6947
  const codeEmbedder = captureCodeEmbedder(context);
6948
- const info = await resolve4({ id: context.id, embedder: codeEmbedder });
6948
+ const info = await resolve5({ id: context.id, embedder: codeEmbedder });
6949
6949
  if (info.source !== "database" || !info.databaseModel) {
6950
6950
  context.embedder = codeEmbedder;
6951
6951
  continue;
@@ -12139,10 +12139,10 @@ var projectRow = (record, fields, explicit) => {
12139
12139
  }
12140
12140
  return out;
12141
12141
  };
12142
- var clampLimit = (raw) => {
12142
+ var clampLimit = (raw, max = FIND_MAX_LIMIT) => {
12143
12143
  const asNumber = typeof raw === "number" || typeof raw === "string" && raw.trim() !== "" ? Math.floor(Number(raw)) : Number.NaN;
12144
12144
  if (!Number.isFinite(asNumber) || asNumber <= 0) return FIND_DEFAULT_LIMIT;
12145
- return Math.min(asNumber, FIND_MAX_LIMIT);
12145
+ return Math.min(asNumber, max);
12146
12146
  };
12147
12147
  var validateWhere = (filterable, where, contextName) => {
12148
12148
  const names = new Set(filterable.map((f) => f.name));
@@ -12241,14 +12241,102 @@ var checkItemReadAccess = async (context, record, user) => {
12241
12241
  const grant = await db.from("rbac").where({ entity, target_resource_id: record.id, access_type: "Team", team_id: teamId }).first();
12242
12242
  return !!grant;
12243
12243
  };
12244
+ var readContextItem = async (context, args, caller, deps = {}) => {
12245
+ const { user } = caller;
12246
+ const NOT_FOUND = itemNotFoundMessage(context, "read");
12247
+ const checkAccess = deps.checkAccess ?? checkItemReadAccess;
12248
+ const readable = readableContextFields(context);
12249
+ if (treatAsGuest(caller.req, user)) {
12250
+ return { ok: false, message: NOT_FOUND };
12251
+ }
12252
+ if (!args.id && !args.external_id) {
12253
+ return { ok: false, message: "Provide the id or external_id of the item to read." };
12254
+ }
12255
+ const selection = resolveFields(readable, args.fields, context.name);
12256
+ if ("error" in selection) {
12257
+ return { ok: false, message: selection.error };
12258
+ }
12259
+ try {
12260
+ const record = await context.getItem({
12261
+ item: { id: args.id, external_id: args.external_id }
12262
+ });
12263
+ if (!record?.id) {
12264
+ return { ok: false, message: NOT_FOUND };
12265
+ }
12266
+ if (!await checkAccess(context, record, user)) {
12267
+ return { ok: false, message: NOT_FOUND };
12268
+ }
12269
+ const explicit = Array.isArray(args.fields) && args.fields.length > 0;
12270
+ return { ok: true, item: projectRow(record, selection.fields, explicit) };
12271
+ } catch (error) {
12272
+ console.error(`[EXULU] Error reading item in context ${context.id}`, error);
12273
+ return {
12274
+ ok: false,
12275
+ message: `Failed to read the item in "${context.name}": ${error instanceof Error ? error.message : String(error)}`
12276
+ };
12277
+ }
12278
+ };
12279
+ var runFind = async (context, args, caller, probeTruncation) => {
12280
+ const { user } = caller;
12281
+ const readable = readableContextFields(context);
12282
+ const filterable = readable.filter((field) => !field.isFile);
12283
+ const findDefaults = readable.filter((field) => field.findDefault);
12284
+ const limit = clampLimit(args.limit, args.maxLimit ?? FIND_MAX_LIMIT);
12285
+ if (treatAsGuest(caller.req, user)) {
12286
+ return { ok: true, items: [], limit, truncated: false };
12287
+ }
12288
+ const requested = Array.isArray(args.fields) && args.fields.length > 0 ? args.fields : void 0;
12289
+ const selection = resolveFields(requested ? readable : findDefaults, requested, context.name);
12290
+ if ("error" in selection) {
12291
+ return { ok: false, message: selection.error };
12292
+ }
12293
+ const where = args.where && typeof args.where === "object" && !Array.isArray(args.where) ? args.where : void 0;
12294
+ if (where && Object.keys(where).length > 0) {
12295
+ const whereError = validateWhere(filterable, where, context.name);
12296
+ if (whereError) {
12297
+ return { ok: false, message: whereError };
12298
+ }
12299
+ }
12300
+ try {
12301
+ const rows = await context.getItems({
12302
+ filters: where && Object.keys(where).length > 0 ? [whereByColumn(filterable, where)] : [],
12303
+ fields: selectList(selection.fields),
12304
+ user,
12305
+ // A user's role can be the bare id string as well as an object;
12306
+ // `user.role?.id` on a string silently yields undefined, which knex
12307
+ // then refuses as an undefined binding (fix round 1, F3).
12308
+ role: typeof user.role === "string" ? user.role : user.role?.id,
12309
+ // One extra row tells "exactly limit match" from "more match".
12310
+ limit: probeTruncation ? limit + 1 : limit
12311
+ });
12312
+ const truncated = probeTruncation && rows.length > limit;
12313
+ return { ok: true, items: truncated ? rows.slice(0, limit) : rows, limit, truncated };
12314
+ } catch (error) {
12315
+ if (error instanceof UnknownFilterPathError) {
12316
+ console.warn(
12317
+ `[EXULU] find_${contextToolSegment(context)}_items refused an unknown json filter path:`,
12318
+ error.message
12319
+ );
12320
+ const field = filterable.find((candidate) => candidate.column === error.field);
12321
+ return {
12322
+ ok: false,
12323
+ message: field && field.name !== error.field ? new UnknownFilterPathError(field.name, error.offendingPaths, error.validPaths).message : error.message
12324
+ };
12325
+ }
12326
+ console.error(`[EXULU] Error finding items in context ${context.id}`, error);
12327
+ return {
12328
+ ok: false,
12329
+ message: `Failed to find items in "${context.name}": ${error instanceof Error ? error.message : String(error)}`
12330
+ };
12331
+ }
12332
+ };
12333
+ var findContextItems = (context, args, caller) => runFind(context, args, caller, true);
12244
12334
  var createContextReadTools = (context, deps = {}) => {
12245
12335
  const segment = contextToolSegment(context);
12246
12336
  const contextLabel = context.description ? ` ${context.description}` : "";
12247
12337
  const readable = readableContextFields(context);
12248
12338
  const filterable = readable.filter((field) => !field.isFile);
12249
12339
  const findDefaults = readable.filter((field) => field.findDefault);
12250
- const NOT_FOUND = itemNotFoundMessage(context, "read");
12251
- const checkAccess = deps.checkAccess ?? checkItemReadAccess;
12252
12340
  const fieldsInput = (defaults) => z12.array(z12.string()).optional().describe(
12253
12341
  `Which fields to return \u2014 "id" is always returned whether you name it or not. Omitted, ${defaults}. Available: ${nameList(readable)}.`
12254
12342
  );
@@ -12266,37 +12354,13 @@ var createContextReadTools = (context, deps = {}) => {
12266
12354
  config: [],
12267
12355
  needsApproval: false,
12268
12356
  execute: async (params) => {
12269
- const { user } = params;
12270
- if (treatAsGuest(params.req, user)) {
12271
- return { result: NOT_FOUND };
12272
- }
12273
- if (!params.id && !params.external_id) {
12274
- return { result: "Provide the id or external_id of the item to read." };
12275
- }
12276
- const selection = resolveFields(readable, params.fields, context.name);
12277
- if ("error" in selection) {
12278
- return { result: selection.error };
12279
- }
12280
- try {
12281
- const record = await context.getItem({
12282
- item: { id: params.id, external_id: params.external_id }
12283
- });
12284
- if (!record?.id) {
12285
- return { result: NOT_FOUND };
12286
- }
12287
- if (!await checkAccess(context, record, user)) {
12288
- return { result: NOT_FOUND };
12289
- }
12290
- const explicit = Array.isArray(params.fields) && params.fields.length > 0;
12291
- return {
12292
- result: `Item: ${JSON.stringify(projectRow(record, selection.fields, explicit))}`
12293
- };
12294
- } catch (error) {
12295
- console.error(`[EXULU] Error reading item in context ${context.id}`, error);
12296
- return {
12297
- result: `Failed to read the item in "${context.name}": ${error instanceof Error ? error.message : String(error)}`
12298
- };
12299
- }
12357
+ const outcome = await readContextItem(
12358
+ context,
12359
+ { id: params.id, external_id: params.external_id, fields: params.fields },
12360
+ { user: params.user, req: params.req },
12361
+ deps
12362
+ );
12363
+ return { result: outcome.ok ? `Item: ${JSON.stringify(outcome.item)}` : outcome.message };
12300
12364
  }
12301
12365
  });
12302
12366
  const findTool = new ExuluTool({
@@ -12317,48 +12381,14 @@ var createContextReadTools = (context, deps = {}) => {
12317
12381
  config: [],
12318
12382
  needsApproval: false,
12319
12383
  execute: async (params) => {
12320
- const { user } = params;
12321
- const limit = clampLimit(params.limit);
12322
- if (treatAsGuest(params.req, user)) {
12323
- return { result: "Found 0 item(s): []" };
12324
- }
12325
- const requested = Array.isArray(params.fields) && params.fields.length > 0 ? params.fields : void 0;
12326
- const selection = resolveFields(requested ? readable : findDefaults, requested, context.name);
12327
- if ("error" in selection) {
12328
- return { result: selection.error };
12329
- }
12330
- const where = params.where && typeof params.where === "object" && !Array.isArray(params.where) ? params.where : void 0;
12331
- if (where && Object.keys(where).length > 0) {
12332
- const whereError = validateWhere(filterable, where, context.name);
12333
- if (whereError) {
12334
- return { result: whereError };
12335
- }
12336
- }
12337
- try {
12338
- const items = await context.getItems({
12339
- filters: where && Object.keys(where).length > 0 ? [whereByColumn(filterable, where)] : [],
12340
- fields: selectList(selection.fields),
12341
- user,
12342
- // A user's role can be the bare id string as well as an object;
12343
- // `user.role?.id` on a string silently yields undefined, which knex
12344
- // then refuses as an undefined binding (fix round 1, F3).
12345
- role: typeof user.role === "string" ? user.role : user.role?.id,
12346
- limit
12347
- });
12348
- return { result: `Found ${items.length} item(s): ${JSON.stringify(items)}` };
12349
- } catch (error) {
12350
- if (error instanceof UnknownFilterPathError) {
12351
- console.warn(`[EXULU] ${findTool.id} refused an unknown json filter path:`, error.message);
12352
- const field = filterable.find((candidate) => candidate.column === error.field);
12353
- return {
12354
- result: field && field.name !== error.field ? new UnknownFilterPathError(field.name, error.offendingPaths, error.validPaths).message : error.message
12355
- };
12356
- }
12357
- console.error(`[EXULU] Error finding items in context ${context.id}`, error);
12358
- return {
12359
- result: `Failed to find items in "${context.name}": ${error instanceof Error ? error.message : String(error)}`
12360
- };
12361
- }
12384
+ const outcome = await runFind(
12385
+ context,
12386
+ { where: params.where, limit: params.limit, fields: params.fields },
12387
+ { user: params.user, req: params.req },
12388
+ false
12389
+ );
12390
+ if (!outcome.ok) return { result: outcome.message };
12391
+ return { result: `Found ${outcome.items.length} item(s): ${JSON.stringify(outcome.items)}` };
12362
12392
  }
12363
12393
  });
12364
12394
  return [getTool, findTool];
@@ -12770,6 +12800,7 @@ var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
12770
12800
  };
12771
12801
 
12772
12802
  // ee/invoke-skills/artifact-filter.ts
12803
+ var ACTION_INPUTS_DIR = ".exulu-inputs";
12773
12804
  var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
12774
12805
  "venv",
12775
12806
  ".venv",
@@ -12782,11 +12813,16 @@ var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
12782
12813
  ".git",
12783
12814
  ".pytest_cache",
12784
12815
  ".mypy_cache",
12785
- ".ipynb_checkpoints"
12816
+ ".ipynb_checkpoints",
12817
+ // Input files the platform writes for a skill action run; never session artifacts.
12818
+ ACTION_INPUTS_DIR
12786
12819
  ]);
12787
12820
  function isIgnoredArtifactPath(relativePath) {
12788
12821
  return relativePath.split(/[\\/]+/).some((segment) => IGNORED_SEGMENTS.has(segment));
12789
12822
  }
12823
+ function isActionInputsPath(relativePath) {
12824
+ return relativePath.split(/[\\/]+/).some((segment) => segment === ACTION_INPUTS_DIR);
12825
+ }
12790
12826
  var DEFAULT_ARTIFACT_CAP = 50;
12791
12827
  function capArtifacts(artifacts, max = DEFAULT_ARTIFACT_CAP) {
12792
12828
  if (artifacts.length <= max) return { kept: artifacts, omitted: 0 };
@@ -12795,6 +12831,21 @@ function capArtifacts(artifacts, max = DEFAULT_ARTIFACT_CAP) {
12795
12831
  function needsDownload(localSize, remoteSize) {
12796
12832
  return localSize === void 0 || localSize !== remoteSize;
12797
12833
  }
12834
+ var ARTIFACTS_BLOCK_HEADER = "[exulu-artifacts]";
12835
+ var ARTIFACTS_BLOCK_SEPARATOR = `
12836
+
12837
+ ${ARTIFACTS_BLOCK_HEADER}
12838
+ `;
12839
+ function appendArtifactsBlock(stdout, entryLines) {
12840
+ if (entryLines.length === 0) return stdout;
12841
+ return `${stdout}${ARTIFACTS_BLOCK_SEPARATOR}${entryLines.join("\n")}`;
12842
+ }
12843
+ function splitArtifactsBlock(stdout, hasBlock) {
12844
+ if (!hasBlock) return { output: stdout, block: "" };
12845
+ const at = stdout.lastIndexOf(ARTIFACTS_BLOCK_SEPARATOR);
12846
+ if (at < 0) return { output: stdout, block: "" };
12847
+ return { output: stdout.slice(0, at), block: stdout.slice(at) };
12848
+ }
12798
12849
 
12799
12850
  // src/exulu/shared-artifacts.ts
12800
12851
  import bcrypt2 from "bcryptjs";
@@ -13933,16 +13984,42 @@ var createSaveToProjectTool = ({
13933
13984
 
13934
13985
  // src/templates/tools/skill-author-tools.ts
13935
13986
  import { randomUUID as randomUUID5 } from "crypto";
13936
- import { z as z16 } from "zod";
13987
+ import { z as z17 } from "zod";
13937
13988
 
13938
13989
  // src/skills/skill-access.ts
13939
13990
  async function resolveSkillByName(db, name) {
13940
13991
  const row = await db("skills").where({ name }).first();
13941
13992
  return row ?? null;
13942
13993
  }
13994
+ async function canWritePublicSkill(db, skill, user) {
13995
+ if (!user) return false;
13996
+ if (user.super_admin === true) return true;
13997
+ if (user.type === "api" && (!user.scope_mode || user.scope_mode === "admin")) return true;
13998
+ if (sameEntityId(skill.created_by, user.id)) return true;
13999
+ const rbac = await RBACResolver(db, "skill", skill.id, "public");
14000
+ const granted = (list, subject) => subject != null && (list ?? []).some((g) => sameEntityId(g.id, subject) && g.rights === "write");
14001
+ const role = user.role;
14002
+ const team = user.team;
14003
+ return granted(rbac.users, user.id) || granted(rbac.roles, role?.id ?? role) || granted(rbac.teams, team?.id ?? team);
14004
+ }
13943
14005
  async function canAccessSkill(db, skill, action, user) {
14006
+ if (action === "write" && skill.rights_mode === "public") {
14007
+ return canWritePublicSkill(db, skill, user);
14008
+ }
13944
14009
  const rbac = await RBACResolver(db, "skill", skill.id, skill.rights_mode || "private");
13945
- return checkRecordAccess({ ...skill, RBAC: rbac }, action, user);
14010
+ const allowed = await checkRecordAccess({ ...skill, RBAC: rbac }, action, user);
14011
+ if (allowed || action === "write") return allowed;
14012
+ return canAccessSkill(db, skill, "write", user);
14013
+ }
14014
+ async function ensureSkillWrite(db, skill, user, res) {
14015
+ if (await canAccessSkill(db, skill, "write", user)) return true;
14016
+ res.status(403).json({ detail: "You don't have write access to this skill." });
14017
+ return false;
14018
+ }
14019
+ async function ensureSkillRead(db, skill, user, res) {
14020
+ if (await canAccessSkill(db, skill, "read", user)) return true;
14021
+ res.status(404).json({ detail: "Skill not found." });
14022
+ return false;
13946
14023
  }
13947
14024
  async function filterReadableSkills(db, skills, user) {
13948
14025
  const out = [];
@@ -13995,6 +14072,169 @@ async function parseSkillFrontmatter(zipBytes) {
13995
14072
  return { name: fm.name, description: fm.description };
13996
14073
  }
13997
14074
 
14075
+ // src/skills/authoring-limits.ts
14076
+ var MAX_FILES = 100;
14077
+ var MAX_FILE_BYTES = 200 * 1024;
14078
+
14079
+ // ee/invoke-skills/skill-actions/schema.ts
14080
+ import { parse as parse2 } from "yaml";
14081
+ import { z as z16 } from "zod";
14082
+ var ACTIONS_FILE = "actions.yaml";
14083
+ var ACTIONS_MAX_BYTES = 64 * 1024;
14084
+ var MAX_ACTIONS = 20;
14085
+ var NAME = /^[a-z][a-z0-9_]{0,39}$/;
14086
+ var nameMessage = "must match ^[a-z][a-z0-9_]{0,39}$";
14087
+ var inputSchema = z16.discriminatedUnion("type", [
14088
+ z16.strictObject({
14089
+ type: z16.literal("item"),
14090
+ context: z16.string().min(1),
14091
+ fields: z16.array(z16.string()).optional(),
14092
+ description: z16.string().optional()
14093
+ }),
14094
+ z16.strictObject({
14095
+ type: z16.literal("items"),
14096
+ context: z16.string().min(1),
14097
+ fields: z16.array(z16.string()).optional(),
14098
+ where: z16.record(z16.string(), z16.unknown()).optional(),
14099
+ description: z16.string().optional()
14100
+ }),
14101
+ z16.strictObject({
14102
+ type: z16.literal("text"),
14103
+ required: z16.boolean().default(true),
14104
+ description: z16.string().optional()
14105
+ })
14106
+ ]);
14107
+ var actionSchema = z16.strictObject({
14108
+ description: z16.string().min(1),
14109
+ run: z16.string().min(1),
14110
+ timeout_seconds: z16.number().int().min(1).max(300).default(60),
14111
+ inputs: z16.record(z16.string().regex(NAME, nameMessage), inputSchema).default({})
14112
+ }).transform(({ timeout_seconds, ...rest }) => ({
14113
+ description: rest.description,
14114
+ run: rest.run,
14115
+ timeoutSeconds: timeout_seconds,
14116
+ inputs: rest.inputs
14117
+ }));
14118
+ var fileSchema = z16.strictObject({
14119
+ version: z16.literal(1),
14120
+ actions: z16.record(z16.string().regex(NAME, nameMessage), actionSchema).refine((a) => Object.keys(a).length <= MAX_ACTIONS, {
14121
+ message: `at most ${MAX_ACTIONS} actions per skill`
14122
+ })
14123
+ });
14124
+ var parseActionsYaml = (text) => {
14125
+ try {
14126
+ if (Buffer.byteLength(text, "utf8") > ACTIONS_MAX_BYTES) {
14127
+ return { ok: false, error: `${ACTIONS_FILE} exceeds ${ACTIONS_MAX_BYTES} bytes` };
14128
+ }
14129
+ let raw;
14130
+ try {
14131
+ raw = parse2(text);
14132
+ } catch (e) {
14133
+ return { ok: false, error: `invalid YAML: ${e?.message ?? String(e)}` };
14134
+ }
14135
+ const result = fileSchema.safeParse(raw);
14136
+ if (!result.success) {
14137
+ const issue = result.error.issues[0];
14138
+ const path3 = issue?.path.length ? issue.path.join(".") : "(root)";
14139
+ return { ok: false, error: `${path3}: ${issue?.message ?? "invalid"}` };
14140
+ }
14141
+ return { ok: true, actions: result.data.actions };
14142
+ } catch (e) {
14143
+ return { ok: false, error: e?.message ?? String(e) };
14144
+ }
14145
+ };
14146
+
14147
+ // src/skills/authoring-guide.ts
14148
+ var ACTIONS_EDIT_NO_EFFECT = "Editing, replacing or deleting `skills/<name>/" + ACTIONS_FILE + "` inside a running session has no effect on which actions exist or what they read.";
14149
+ var SKILL_FOLDER_READ_ONLY = "The skill's own folder `skills/<name>/` is read-only in a session: nothing run in the sandbox can create, change, delete or rename files there, so a script writes its output to the working directory (the session directory). A skill changes only when a new version is saved; the session picks it up on the next turn or a reload of the skills.";
14150
+ var SKILL_FOLDER_READ_ONLY_DEGRADED = "On a host where the platform runs commands without a kernel sandbox (degraded mode), only the writeFile tool refuses that folder; shell commands and actions are not confined there.";
14151
+ var SKILL_AUTHORING_GUIDE = `# Writing skills for this platform
14152
+
14153
+ A skill is a folder of files. The format is the standard Agent Skills format and stays portable; this guide covers only what differs here.
14154
+
14155
+ ## 1. What stays standard
14156
+ - \`SKILL.md\` starts with front matter that carries only \`name\` and \`description\`. Put no platform-specific keys there.
14157
+ - Instructions, reference files and scripts are ordinary files in the folder.
14158
+
14159
+ ## 2. Where scripts run
14160
+ - In the session sandbox, in the same working directory as the chat's other files (the session directory). The skill's own files are in \`skills/<name>/\` below it, so address scripts as \`skills/<name>/scripts/x.py\`.
14161
+ - ${SKILL_FOLDER_READ_ONLY} ${SKILL_FOLDER_READ_ONLY_DEGRADED}
14162
+ - The sandbox is configured to allow no network access. Do not write scripts that download or call anything.
14163
+ - Environment: the backend's declared secrets are removed from the environment and variables an administrator has explicitly granted to skills are added under their own name (skipped if the name is not a plain POSIX name or collides with an existing variable). The rest of the process environment passes through, so do not rely on any other variable being present or absent. Never hard-code credentials; tell the user which variable the skill expects.
14164
+ - Interpreters: \`python3\` resolves to the platform's Python virtual environment when one is available; when npm is found, globally installed npm packages can be \`require()\`d from CommonJS scripts (\`NODE_PATH\` is set; ES \`import\` ignores it). Do not assume any particular package: check with a quick import or \`npm ls -g\`, and say in SKILL.md what the skill needs.
14165
+
14166
+ ## 3. Files a script creates
14167
+ - When the session has a user and file uploads are configured, new or changed files under the session directory (not under \`skills/\`) are uploaded, and the command output ends with an \`${ARTIFACTS_BLOCK_HEADER}\` block listing each as \`path: URL\`.
14168
+ - Give the user exactly that URL. Never link a relative path or invent one.
14169
+ - At most 50 files are listed per command. Dependency and cache directories (e.g. \`venv\`, \`node_modules\`, \`__pycache__\`, \`.cache\`, \`.git\`) are not listed; do not install packages into the session directory. Never write output into \`$EXULU_INPUTS_DIR\`: it is deleted after the run and never uploaded.
14170
+
14171
+ ## 4. Platform data
14172
+ - A script cannot fetch knowledge-base data itself (no network, no credentials). Never copy item data into a file by retyping it; it gets corrupted and truncated.
14173
+ - A small lookup: the agent uses the read tools \`get_<context>_item\` and \`find_<context>_items\` directly and reasons over the result.
14174
+ - Anything a script must process: declare an action (next section). The platform reads the data with the current user's rights and hands it to the script as files.
14175
+
14176
+ ## 5. actions.yaml
14177
+ \`${ACTIONS_FILE}\` at the skill root (at most ${ACTIONS_MAX_BYTES} bytes) declares what the agent may start. The agent starts one with the tool \`run_skill_action\` and the arguments \`skill\`, \`action\` and \`inputs\` (an object keyed by input name).
14178
+
14179
+ Keys: \`version: 1\` (required); \`actions\` (required, at most ${MAX_ACTIONS}); per action \`description\` (required), \`run\` (required, the shell command, run from the session directory; the caller can never change it), \`timeout_seconds\` (1-300, default 60), \`inputs\`. Action and input names match \`^[a-z][a-z0-9_]{0,39}$\`. Unknown keys are errors.
14180
+
14181
+ Input types:
14182
+ - \`item\`: keys \`type\`, \`context\` (required, the exact context id; the tool-name segment in \`get_<context>_item\` is sanitised and shortened, so it can differ from the id), \`fields\` (optional list of field names to include), \`description\`. The caller passes an item id string or \`{ "external_id": "..." }\`. The script finds \`<name>.json\` with the item.
14183
+ - \`items\`: keys \`type\`, \`context\`, \`fields\`, \`where\` (optional fixed filter in the syntax of \`find_<context>_items\`: \`{ field: { operator: value } }\` with the operators eq, ne, in, contains, gte, lte; unknown fields or operators are refused, and per field type: \`contains\` is refused on number, boolean, date and uuid fields, \`gte\` and \`lte\` on json and uuid fields (so not on \`id\`); eq, ne and in are always allowed. It is combined with the caller's filter; a field filtered here cannot be filtered again by the caller), \`description\`. The caller passes \`{ "where": {...}, "limit": n }\` or nothing (default limit 50, maximum 500). The script finds \`<name>.json\` as \`{ "items": [...], "limit": n, "truncated": true|false }\`. Archived items are included unless the fixed \`where\` excludes them with \`archived: { eq: false }\`.
14184
+ - \`text\`: keys \`type\`, \`required\` (default true), \`description\`. The caller passes a string of at most 10000 characters. The text inputs that were given arrive together in \`args.json\` as an object by input name; the file is missing when none was given (an optional text input left out). Do not name an \`item\` or \`items\` input \`args\`: the action then cannot run.
14185
+
14186
+ About \`fields\`: an \`item\` input without it returns every readable field, including createdAt, rights_mode, archived and file fields; an \`items\` input returns only id, updatedAt, name, description, tags, external_id and the context's non-file fields (name any other field to get it). A \`file\` field arrives as its storage key, never its content, and the script cannot fetch it. Fields whose value is null are left out unless \`fields\` names them.
14187
+
14188
+ In the script: \`$EXULU_INPUTS_DIR\` is the directory holding those files (it exists only while the command runs); \`$EXULU_SKILL_DIR\` is the skill's own folder. Values from the caller never reach the shell command, only these files.
14189
+
14190
+ Which contexts an action may read: only those the agent could read with its own tools in the same turn. That is the knowledge bases whose read tools the agent has (the knowledge-base editor setup), the knowledge bases its context search covers (all except those switched off there), or otherwise, in a project, the knowledge bases of the project's items. The agent's memory is never readable. An action that names any other context is refused when started, with the message that the knowledge base is not connected to the agent.
14191
+
14192
+ When the file is read: the platform takes \`${ACTIONS_FILE}\` from the saved skill version, when that version is downloaded into the session (the first turn, the first turn after a new version is saved, or a reload of the skills). ${ACTIONS_EDIT_NO_EFFECT} Save a new version instead; it is picked up on the next turn. Scripts still run from the session copy in \`skills/<name>/\`.
14193
+
14194
+ Invalid file: a skill whose saved \`${ACTIONS_FILE}\` is invalid is ignored (its actions are not offered and the agent is shown the reason), and this authoring tool refuses to save one.
14195
+
14196
+ Example:
14197
+
14198
+ \`\`\`yaml
14199
+ version: 1
14200
+ actions:
14201
+ summarize_contract:
14202
+ description: Build a one-page summary of a contract and the recent amendments.
14203
+ run: python3 "$EXULU_SKILL_DIR/scripts/summarize.py"
14204
+ timeout_seconds: 120
14205
+ inputs:
14206
+ contract:
14207
+ type: item
14208
+ context: contracts
14209
+ fields: [name, content]
14210
+ description: The contract to summarize.
14211
+ amendments:
14212
+ type: items
14213
+ context: amendments
14214
+ where: { status: { eq: active }, archived: { eq: false } }
14215
+ focus:
14216
+ type: text
14217
+ required: false
14218
+ description: A topic to emphasise.
14219
+ \`\`\`
14220
+
14221
+ \`\`\`python
14222
+ import json, os
14223
+ d = os.environ["EXULU_INPUTS_DIR"]
14224
+ contract = json.load(open(os.path.join(d, "contract.json")))
14225
+ amendments = json.load(open(os.path.join(d, "amendments.json")))["items"]
14226
+ args_path = os.path.join(d, "args.json")
14227
+ focus = json.load(open(args_path)).get("focus") if os.path.exists(args_path) else None
14228
+ \`\`\`
14229
+
14230
+ ## 6. Stay usable elsewhere
14231
+ Describe in SKILL.md a manual path that works without actions (for example: read the item with the read tools and follow the same steps by hand). Other hosts ignore \`${ACTIONS_FILE}\`, and on this platform an agent may not have the action available (the agent has no sandbox or the file is invalid; an action whose knowledge base is not connected is listed but refused when called).
14232
+
14233
+ ## 7. Limits
14234
+ - At most ${MAX_FILES} files per call to the authoring tools, each at most ${MAX_FILE_BYTES / 1024} KB; the \`${ACTIONS_FILE}\` limit is ${ACTIONS_MAX_BYTES / 1024} KB.
14235
+ - A file path is relative, at most 200 characters, with no \`..\`, empty segments or control characters.
14236
+ `;
14237
+
13998
14238
  // src/templates/tools/skill-author-config.ts
13999
14239
  var SKILL_AUTHOR_TOOL_ID = "skill_author";
14000
14240
  var asBool = (v, fallback) => {
@@ -14034,12 +14274,11 @@ var SKILL_AUTHOR_PROMPT = [
14034
14274
  "Offer a skill only after the user has finished a complex, multi-step piece of work that is likely to recur \u2014 typically one that produced files, documents, code, a report or a structured analysis, or a multi-step retrieval they run regularly.",
14035
14275
  "Do not offer it for a single question against a knowledge base, a quick lookup, or a one-off correction; a correction or a preference belongs in memory, not in a skill.",
14036
14276
  "When you offer, say in one sentence what the skill would capture and ask. The user confirms the name, the description and who may see it on a card before anything is created; never ask about visibility yourself unless the user raised it, and never claim a skill exists or changed until the tool returns skill_created or skill_updated.",
14277
+ "Skills on this platform differ from other hosts (where scripts run, what they can reach, how they read knowledge-base data): call skill_guide before writing or changing a skill that contains scripts or needs platform data.",
14037
14278
  "Write a skill as a SKILL.md with frontmatter (name, description) and clear steps, plus reference files only where they add something the model would otherwise have to guess."
14038
14279
  ].join(" ");
14039
14280
 
14040
14281
  // src/templates/tools/skill-author-tools.ts
14041
- var MAX_FILES = 100;
14042
- var MAX_FILE_BYTES = 200 * 1024;
14043
14282
  var MAX_READ_BYTES = 60 * 1024;
14044
14283
  var defaultIo = () => ({
14045
14284
  upload: (bytes, key, config, contentType) => uploadFile(bytes, key, config, { contentType }, void 0, void 0, true),
@@ -14105,6 +14344,12 @@ var normalizeFiles = (raw) => {
14105
14344
  }
14106
14345
  return { files };
14107
14346
  };
14347
+ var actionsFileError = (files) => {
14348
+ const file = files.find((f) => f.path === ACTIONS_FILE);
14349
+ if (!file) return null;
14350
+ const parsed = parseActionsYaml(file.content);
14351
+ return parsed.ok ? null : err2(`${ACTIONS_FILE} is invalid: ${parsed.error}. Nothing was saved; fix the file and call the tool again (skill_guide describes the format).`);
14352
+ };
14108
14353
  var createSkillAuthorTools = (agent, deps = {}) => {
14109
14354
  const config = parseSkillAuthorConfig(agent.tools);
14110
14355
  if (!config.enabled) return [];
@@ -14123,7 +14368,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
14123
14368
  config: [],
14124
14369
  needsApproval: false,
14125
14370
  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.",
14126
- inputSchema: z16.object({ query: z16.string().optional().describe("Optional substring to filter by name or description") }),
14371
+ inputSchema: z17.object({ query: z17.string().optional().describe("Optional substring to filter by name or description") }),
14127
14372
  execute: async (params) => {
14128
14373
  const { user } = params;
14129
14374
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -14149,9 +14394,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
14149
14394
  config: [],
14150
14395
  needsApproval: false,
14151
14396
  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.",
14152
- inputSchema: z16.object({
14153
- skill: z16.string().describe("The skill's name or id"),
14154
- path: z16.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
14397
+ inputSchema: z17.object({
14398
+ skill: z17.string().describe("The skill's name or id"),
14399
+ path: z17.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
14155
14400
  }),
14156
14401
  execute: async (params) => {
14157
14402
  const { user, exuluConfig } = params;
@@ -14185,6 +14430,19 @@ ${content}`
14185
14430
  }
14186
14431
  })
14187
14432
  );
14433
+ tools.push(
14434
+ new ExuluTool({
14435
+ id: "skill_guide",
14436
+ name: "skill_guide",
14437
+ category,
14438
+ type: "function",
14439
+ config: [],
14440
+ needsApproval: false,
14441
+ description: "Read how skills on this platform differ from other hosts: where scripts run, what they can reach, how files come back, how to read knowledge-base data (actions.yaml). Call it before writing or changing a skill that contains scripts or needs platform data.",
14442
+ inputSchema: z17.object({}),
14443
+ execute: async () => ({ type: "skill_guide", result: SKILL_AUTHORING_GUIDE })
14444
+ })
14445
+ );
14188
14446
  if (config.create) {
14189
14447
  tools.push(
14190
14448
  new ExuluTool({
@@ -14196,10 +14454,10 @@ ${content}`
14196
14454
  needsApproval: !config.skipApproval,
14197
14455
  needsApprovalFn: approvalFn,
14198
14456
  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.",
14199
- inputSchema: z16.object({
14200
- name: z16.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
14201
- description: z16.string().describe("One line: what the skill does and when to use it"),
14202
- files: z16.array(z16.object({ path: z16.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z16.string() })).min(1).describe("The skill's files; SKILL.md is required")
14457
+ inputSchema: z17.object({
14458
+ name: z17.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
14459
+ description: z17.string().describe("One line: what the skill does and when to use it"),
14460
+ files: z17.array(z17.object({ path: z17.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z17.string() })).min(1).describe("The skill's files; SKILL.md is required")
14203
14461
  }),
14204
14462
  execute: async (params) => {
14205
14463
  const { user, exuluConfig } = params;
@@ -14212,6 +14470,8 @@ ${content}`
14212
14470
  const parsed = normalizeFiles(params.files);
14213
14471
  if ("error" in parsed) return err2(parsed.error);
14214
14472
  const files = parsed.files;
14473
+ const invalidActions = actionsFileError(files);
14474
+ if (invalidActions) return invalidActions;
14215
14475
  const skillMd = files.find((f) => f.path === "SKILL.md");
14216
14476
  if (!skillMd) return err2("A skill needs a SKILL.md at its root.");
14217
14477
  skillMd.content = ensureFrontmatter(skillMd.content, name, description);
@@ -14265,12 +14525,12 @@ ${content}`
14265
14525
  needsApproval: !config.skipApproval,
14266
14526
  needsApprovalFn: approvalFn,
14267
14527
  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.",
14268
- inputSchema: z16.object({
14269
- skill: z16.string().describe("The skill's name or id"),
14270
- files: z16.array(z16.object({ path: z16.string(), content: z16.string() })).optional().describe("Files to add or replace, full content each"),
14271
- deletePaths: z16.array(z16.string()).optional().describe("Paths to remove in the new version"),
14272
- description: z16.string().optional().describe("A new one-line description, if it changed"),
14273
- label: z16.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
14528
+ inputSchema: z17.object({
14529
+ skill: z17.string().describe("The skill's name or id"),
14530
+ files: z17.array(z17.object({ path: z17.string(), content: z17.string() })).optional().describe("Files to add or replace, full content each"),
14531
+ deletePaths: z17.array(z17.string()).optional().describe("Paths to remove in the new version"),
14532
+ description: z17.string().optional().describe("A new one-line description, if it changed"),
14533
+ label: z17.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
14274
14534
  }),
14275
14535
  execute: async (params) => {
14276
14536
  const { user, exuluConfig } = params;
@@ -14285,6 +14545,8 @@ ${content}`
14285
14545
  const parsed = normalizeFiles(params.files);
14286
14546
  if ("error" in parsed) return err2(parsed.error);
14287
14547
  const changes = parsed.files;
14548
+ const invalidActions = actionsFileError(changes);
14549
+ if (invalidActions) return invalidActions;
14288
14550
  const removals = [];
14289
14551
  for (const raw of Array.isArray(params.deletePaths) ? params.deletePaths : []) {
14290
14552
  const p = safeSkillPath(raw);
@@ -14347,7 +14609,7 @@ var createSkillAuthorPickerTool = () => new ExuluTool({
14347
14609
  category: "default",
14348
14610
  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.",
14349
14611
  type: "function",
14350
- inputSchema: z16.object({}),
14612
+ inputSchema: z17.object({}),
14351
14613
  config: [
14352
14614
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
14353
14615
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -14360,1277 +14622,1638 @@ var collectSkillAuthorTools = (agent, deps = {}) => {
14360
14622
  return createSkillAuthorTools(agent, deps);
14361
14623
  };
14362
14624
 
14363
- // ee/invoke-skills/create-sandbox.ts
14364
- import {
14365
- SandboxManager
14366
- } from "@anthropic-ai/sandbox-runtime";
14367
- import { mkdir as mkdir3, rm as rm2, readdir as readdir2, stat, lstat as lstat3 } from "fs/promises";
14368
- import { existsSync as existsSync4 } from "fs";
14369
- import { join as join4, dirname as dirname3, resolve as resolve3, relative, posix } from "path";
14370
- import { exec as exec2, spawn } from "child_process";
14371
- import { promisify as promisify3 } from "util";
14372
-
14373
- // src/exulu/system-dependencies.ts
14374
- import { exec } from "child_process";
14375
- import { existsSync as existsSync2 } from "fs";
14625
+ // ee/invoke-skills/skill-actions/load.ts
14376
14626
  import { join } from "path";
14377
- import { promisify } from "util";
14378
- var execAsync = promisify(exec);
14379
- var REQUIRED_SYSTEM_DEPENDENCIES = [
14380
- {
14381
- check: { kind: "binary", binary: "pandoc" },
14382
- displayName: "Pandoc",
14383
- purpose: "docx skill: text extraction and tracked-changes conversion",
14384
- installHints: {
14385
- debian: "apt-get install -y pandoc",
14386
- macos: "brew install pandoc"
14387
- }
14388
- },
14389
- {
14390
- check: { kind: "binary", binary: "soffice" },
14391
- displayName: "LibreOffice",
14392
- purpose: "docx skill: converting .docx documents to PDF for visual analysis",
14393
- installHints: {
14394
- debian: "apt-get install -y libreoffice",
14395
- macos: "brew install --cask libreoffice"
14627
+ var declarationFromBytes = (bytes) => {
14628
+ if (bytes === void 0) return { kind: "none" };
14629
+ try {
14630
+ if (bytes.length > ACTIONS_MAX_BYTES) {
14631
+ return { kind: "problem", error: `${ACTIONS_FILE} exceeds ${ACTIONS_MAX_BYTES} bytes` };
14396
14632
  }
14397
- },
14398
- {
14399
- check: { kind: "binary", binary: "pdftoppm" },
14400
- displayName: "Poppler (pdftoppm)",
14401
- purpose: "docx skill: converting PDF pages to images",
14402
- installHints: {
14403
- debian: "apt-get install -y poppler-utils",
14404
- macos: "brew install poppler"
14633
+ const parsed = parseActionsYaml(bytes.toString("utf8"));
14634
+ return parsed.ok ? { kind: "ok", actions: parsed.actions } : { kind: "problem", error: parsed.error };
14635
+ } catch (err3) {
14636
+ return {
14637
+ kind: "problem",
14638
+ error: `${ACTIONS_FILE} could not be loaded: ${err3 instanceof Error ? err3.message : String(err3)}`
14639
+ };
14640
+ }
14641
+ };
14642
+ var isPlainName = (name) => typeof name === "string" && name !== "" && name !== "." && name !== ".." && !name.includes("/") && !name.includes("\\") && !name.includes("\0") && !name.includes("..");
14643
+ var loadSkillActions = (sessionDir, skills, pinned) => {
14644
+ const result = { bySkill: {}, problems: [] };
14645
+ for (const skill of skills) {
14646
+ const pin = pinned.get(skill.id);
14647
+ if (!pin || pin.version !== skill.current_version || pin.name !== skill.name) continue;
14648
+ const { declaration } = pin;
14649
+ if (declaration.kind === "none") continue;
14650
+ if (!isPlainName(skill.name)) {
14651
+ result.problems.push({
14652
+ skill: String(skill.name),
14653
+ error: `the skill's name contains a path separator or "..", so it cannot declare actions`
14654
+ });
14655
+ continue;
14405
14656
  }
14406
- },
14407
- {
14408
- check: { kind: "binary", binary: "pdftotext" },
14409
- displayName: "Poppler (pdftotext)",
14410
- purpose: "parse_document tool: extracting page-marked text from PDFs",
14411
- installHints: {
14412
- debian: "apt-get install -y poppler-utils",
14413
- macos: "brew install poppler"
14657
+ if (declaration.kind === "problem") {
14658
+ result.problems.push({ skill: skill.name, error: declaration.error });
14659
+ continue;
14414
14660
  }
14415
- },
14416
- {
14417
- check: { kind: "npm-global", packageName: "docx" },
14418
- displayName: "docx (npm global)",
14419
- purpose: "docx skill: programmatically constructing new .docx documents",
14420
- installHints: {
14421
- debian: "npm install -g docx",
14422
- macos: "npm install -g docx"
14661
+ result.bySkill[skill.name] = { skillDir: join(sessionDir, "skills", skill.name), actions: declaration.actions };
14662
+ }
14663
+ return result;
14664
+ };
14665
+ var describeActions = (loaded) => {
14666
+ const lines = [];
14667
+ for (const [skill, { actions }] of Object.entries(loaded.bySkill)) {
14668
+ for (const [actionName, action] of Object.entries(actions)) {
14669
+ lines.push(`${skill} / ${actionName} \u2014 ${action.description}`);
14670
+ for (const [inputName, input] of Object.entries(action.inputs)) {
14671
+ let qualifiers = input.type;
14672
+ if (input.type === "item" || input.type === "items") qualifiers += `, context ${input.context}`;
14673
+ if (input.type === "text" && !input.required) qualifiers += ", optional";
14674
+ lines.push(` ${inputName} (${qualifiers})${input.description ? ` \u2014 ${input.description}` : ""}`);
14675
+ }
14423
14676
  }
14424
14677
  }
14425
- ];
14426
- var cachedNpmGlobalRoot;
14427
- async function getNpmGlobalRoot() {
14428
- if (cachedNpmGlobalRoot !== void 0) return cachedNpmGlobalRoot;
14678
+ for (const p of loaded.problems) lines.push(`skill "${p.skill}": actions.yaml ignored \u2014 ${p.error}`);
14679
+ return lines.join("\n");
14680
+ };
14681
+
14682
+ // ee/invoke-skills/skill-actions/tool.ts
14683
+ import { randomUUID as randomUUID6 } from "crypto";
14684
+ import { mkdir as mkdir3 } from "fs/promises";
14685
+ import { join as join4 } from "path";
14686
+ import { z as z18 } from "zod";
14687
+
14688
+ // ee/invoke-skills/safe-fs.ts
14689
+ import { constants } from "fs";
14690
+ import { lstat as lstat2, mkdir as mkdir2, open, readlink, realpath, rename as rename2, unlink, writeFile as writeFile2 } from "fs/promises";
14691
+ import { randomBytes as randomBytes3 } from "crypto";
14692
+
14693
+ // ee/invoke-skills/project-sync.ts
14694
+ import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "fs/promises";
14695
+ import { randomBytes as randomBytes2 } from "crypto";
14696
+ import { basename, dirname, join as join2, resolve as resolve2, sep } from "path";
14697
+ import { execFile } from "child_process";
14698
+ import { promisify } from "util";
14699
+ function planProjectSync(remote, local) {
14700
+ const localSizes = new Map(local.map((e) => [e.name, e.size]));
14701
+ const remoteNames = new Set(remote.map((e) => e.name));
14702
+ return {
14703
+ download: remote.filter((e) => localSizes.get(e.name) !== e.size).map((e) => e.name),
14704
+ remove: local.filter((e) => !remoteNames.has(e.name)).map((e) => e.name)
14705
+ };
14706
+ }
14707
+ function projectSyncMarkerPath(sessionDir) {
14708
+ return join2(dirname(sessionDir), ".project-sync", basename(sessionDir));
14709
+ }
14710
+ async function readMarker(sessionDir) {
14429
14711
  try {
14430
- const { stdout } = await execAsync("npm root -g", { shell: "/bin/sh" });
14431
- cachedNpmGlobalRoot = stdout.trim() || null;
14712
+ return (await readFile(projectSyncMarkerPath(sessionDir), "utf8")).trim() || null;
14432
14713
  } catch {
14433
- cachedNpmGlobalRoot = null;
14714
+ return null;
14434
14715
  }
14435
- return cachedNpmGlobalRoot;
14436
14716
  }
14437
- async function probeDependency(dep) {
14438
- switch (dep.check.kind) {
14439
- case "binary": {
14440
- try {
14441
- await execAsync(`command -v ${dep.check.binary}`, { shell: "/bin/sh" });
14442
- return true;
14443
- } catch {
14444
- return false;
14445
- }
14446
- }
14447
- case "npm-global": {
14448
- const root = await getNpmGlobalRoot();
14449
- if (!root) return false;
14450
- return existsSync2(join(root, dep.check.packageName));
14451
- }
14452
- }
14717
+ async function clearProjectSyncMarker(sessionDir) {
14718
+ await rm(projectSyncMarkerPath(sessionDir), { force: true });
14453
14719
  }
14454
- async function checkSystemDependencies() {
14455
- const probes = await Promise.all(
14456
- REQUIRED_SYSTEM_DEPENDENCIES.map(async (dep) => ({
14457
- dep,
14458
- present: await probeDependency(dep)
14459
- }))
14460
- );
14461
- return {
14462
- missing: probes.filter((p) => !p.present).map((p) => p.dep)
14463
- };
14720
+ var isFlatName = (name) => !!name && !name.includes("/") && !name.includes("\\") && name !== "." && name !== "..";
14721
+ var HELPER_KINDS = [".project-staging", ".project-trash"];
14722
+ var helperRoot = (sessionDir, kind) => join2(dirname(sessionDir), kind);
14723
+ var helperPath = (sessionDir, kind) => join2(helperRoot(sessionDir, kind), `${basename(sessionDir)}-${randomBytes2(8).toString("hex")}`);
14724
+ var execFileAsync = promisify(execFile);
14725
+ async function removeTreeSafely(path3, sessionDir) {
14726
+ const target = resolve2(path3);
14727
+ const inside = HELPER_KINDS.some((kind) => {
14728
+ const root = resolve2(helperRoot(sessionDir, kind));
14729
+ return target.startsWith(root + sep) && !target.slice(root.length + 1).includes(sep);
14730
+ });
14731
+ if (!inside) {
14732
+ console.error(`[SKILLS] Refusing to remove ${path3}: not a project staging or trash directory.`);
14733
+ return false;
14734
+ }
14735
+ try {
14736
+ await execFileAsync("rm", ["-rf", "--", target]);
14737
+ return true;
14738
+ } catch (err3) {
14739
+ console.error(`[SKILLS] Failed to remove ${target}; leaving it for a later sweep.`, err3);
14740
+ return false;
14741
+ }
14464
14742
  }
14465
- function formatMissing(dep) {
14466
- const probeLabel = dep.check.kind === "binary" ? dep.check.binary : `npm:${dep.check.packageName} (global)`;
14467
- return ` - ${dep.displayName} (${probeLabel}) \u2014 ${dep.purpose}
14468
- Debian/Ubuntu: ${dep.installHints.debian}
14469
- macOS: ${dep.installHints.macos}`;
14743
+ var DAY_MS = 24 * 60 * 60 * 1e3;
14744
+ async function sweepStaleHelpers(sessionDir) {
14745
+ const prefix = `${basename(sessionDir)}-`;
14746
+ for (const kind of HELPER_KINDS) {
14747
+ const root = helperRoot(sessionDir, kind);
14748
+ let names;
14749
+ try {
14750
+ names = await readdir(root);
14751
+ } catch {
14752
+ continue;
14753
+ }
14754
+ for (const name of names) {
14755
+ if (!name.startsWith(prefix)) continue;
14756
+ const st = await lstat(join2(root, name)).catch(() => null);
14757
+ if (st && Date.now() - st.mtimeMs > DAY_MS) await removeTreeSafely(join2(root, name), sessionDir);
14758
+ }
14759
+ }
14470
14760
  }
14471
- async function reportSystemDependencies(opts) {
14472
- const { missing } = await checkSystemDependencies();
14473
- if (missing.length === 0) return;
14474
- const body = `${missing.length} system dependency check(s) failed:
14475
- ` + missing.map(formatMissing).join("\n");
14476
- if (opts.requireSystemDependencies) {
14477
- throw new Error(
14478
- `[EXULU] Required system dependencies are missing. Install them and restart, or set requireSystemDependencies=false in ExuluConfig to downgrade to a warning.
14479
- ${body}`
14480
- );
14761
+ var errCode = (err3) => err3?.code;
14762
+ async function moveAway(dir, sessionDir) {
14763
+ const trash = helperPath(sessionDir, ".project-trash");
14764
+ await mkdir(dirname(trash), { recursive: true });
14765
+ try {
14766
+ await rename(dir, trash);
14767
+ return trash;
14768
+ } catch (err3) {
14769
+ if (errCode(err3) === "ENOENT") return null;
14770
+ throw err3;
14771
+ }
14772
+ }
14773
+ async function discard(path3, sessionDir) {
14774
+ if (path3) await removeTreeSafely(path3, sessionDir);
14775
+ }
14776
+ async function discardEntry(path3, sessionDir) {
14777
+ await discard(await moveAway(path3, sessionDir), sessionDir);
14778
+ }
14779
+ async function syncProjectDir(args) {
14780
+ const { sessionDir, projectId, config } = args;
14781
+ const dir = join2(sessionDir, PROJECT_DIR);
14782
+ const previous = await readMarker(sessionDir);
14783
+ if (!projectId) {
14784
+ if (previous !== null) {
14785
+ await discard(await moveAway(dir, sessionDir), sessionDir);
14786
+ await clearProjectSyncMarker(sessionDir);
14787
+ }
14788
+ return;
14789
+ }
14790
+ if (!config.fileUploads) {
14791
+ console.warn(`[SKILLS] File uploads are not configured; project files are not synced into ${sessionDir}.`);
14792
+ return;
14793
+ }
14794
+ const { projectPrefix } = projectFilePrefix(projectId);
14795
+ const remote = /* @__PURE__ */ new Map();
14796
+ try {
14797
+ for (const obj of await listS3ObjectsByPrefix(projectPrefix, config)) {
14798
+ const idx = obj.key.indexOf(projectPrefix);
14799
+ const name = idx >= 0 ? obj.key.slice(idx + projectPrefix.length) : "";
14800
+ if (!isFlatName(name)) continue;
14801
+ remote.set(name, { size: obj.size, key: obj.key });
14802
+ }
14803
+ } catch (err3) {
14804
+ console.error(`[SKILLS] Failed to list project files for project ${projectId}; keeping the local copy.`, err3);
14805
+ return;
14806
+ }
14807
+ await sweepStaleHelpers(sessionDir);
14808
+ await mkdir(dirname(projectSyncMarkerPath(sessionDir)), { recursive: true });
14809
+ await writeFile(projectSyncMarkerPath(sessionDir), projectId);
14810
+ const trashes = [];
14811
+ const staging = helperPath(sessionDir, ".project-staging");
14812
+ let installed = false;
14813
+ try {
14814
+ const old = await moveAway(dir, sessionDir);
14815
+ trashes.push(old);
14816
+ await mkdir(dirname(staging), { recursive: true });
14817
+ await mkdir(staging);
14818
+ const local = [];
14819
+ const oldStat = old && previous === projectId ? await lstat(old).catch(() => null) : null;
14820
+ if (old && oldStat?.isDirectory()) {
14821
+ for (const name of await readdir(old)) {
14822
+ const st = await lstat(join2(old, name)).catch(() => null);
14823
+ if (!st?.isFile() || remote.get(name)?.size !== st.size) continue;
14824
+ await rename(join2(old, name), join2(staging, name));
14825
+ const moved = await lstat(join2(staging, name)).catch(() => null);
14826
+ if (!moved?.isFile()) {
14827
+ await rename(join2(staging, name), join2(old, `.rejected-${randomBytes2(4).toString("hex")}`)).catch(() => {
14828
+ });
14829
+ continue;
14830
+ }
14831
+ local.push({ name, size: moved.size });
14832
+ }
14833
+ }
14834
+ const plan = planProjectSync(
14835
+ [...remote].map(([name, r]) => ({ name, size: r.size })),
14836
+ local
14837
+ );
14838
+ for (const name of plan.download) {
14839
+ try {
14840
+ const bytes = await getS3ObjectBytes(remote.get(name).key, config);
14841
+ await writeFile(join2(staging, name), bytes, { flag: "wx" });
14842
+ } catch (err3) {
14843
+ console.error(`[SKILLS] Failed to sync project file ${name} (project ${projectId}); continuing.`, err3);
14844
+ }
14845
+ }
14846
+ for (let attempt = 0; attempt < 2 && !installed; attempt++) {
14847
+ try {
14848
+ await rename(staging, dir);
14849
+ installed = true;
14850
+ } catch (err3) {
14851
+ const code = errCode(err3);
14852
+ if (attempt === 0 && (code === "EEXIST" || code === "ENOTEMPTY" || code === "ENOTDIR" || code === "EISDIR")) {
14853
+ trashes.push(await moveAway(dir, sessionDir));
14854
+ continue;
14855
+ }
14856
+ console.error(`[SKILLS] Could not install the project folder for session ${sessionDir}; skipping this turn.`, err3);
14857
+ break;
14858
+ }
14859
+ }
14860
+ } catch (err3) {
14861
+ console.error(`[SKILLS] Project sync failed for project ${projectId}; continuing.`, err3);
14862
+ } finally {
14863
+ if (!installed) await discard(staging, sessionDir);
14864
+ for (const t of trashes) await discard(t, sessionDir);
14865
+ }
14866
+ }
14867
+ async function resolveSandboxProjectId(args, deps) {
14868
+ const { projectId, ownerId } = args;
14869
+ if (!projectId || ownerId == null) return null;
14870
+ try {
14871
+ const project = await deps.getProject(projectId);
14872
+ if (!project) return null;
14873
+ const owner = args.owner && String(args.owner.id) === String(ownerId) ? args.owner : await deps.getUser(ownerId);
14874
+ if (!owner) return null;
14875
+ const rbac = await deps.getRbac(project);
14876
+ const allowed = hasProjectAccess({ project, rbac, user: owner, want: "read" });
14877
+ return allowed ? String(project.id) : null;
14878
+ } catch (err3) {
14879
+ console.error(`[SKILLS] Failed to resolve project ${projectId} for the session sandbox; continuing without project files.`, err3);
14880
+ return null;
14481
14881
  }
14482
- console.warn(
14483
- `[EXULU] ${body}
14484
- Set requireSystemDependencies=true in ExuluConfig to make this fatal at startup.`
14485
- );
14486
14882
  }
14487
14883
 
14488
- // src/exulu/skill-env/inventory.ts
14489
- var ENV_CLASSIFICATION = {
14490
- // --- secrets: credentials, tokens, signing/verification secrets, keys.
14491
- // Knowing the value grants access to something.
14492
- NEXTAUTH_SECRET: "secret",
14493
- POSTGRES_DB_PASSWORD: "secret",
14494
- LITELLM_MASTER_KEY: "secret",
14495
- LITELLM_DATABASE_URL: "secret",
14496
- COMPANION_S3_SECRET: "secret",
14497
- COMPANION_S3_KEY: "secret",
14498
- ANTHROPIC_API_KEY: "secret",
14499
- GEMINI_API_KEY: "secret",
14500
- PERPLEXITY_API_KEY: "secret",
14501
- RECALL_API_KEY: "secret",
14502
- JIRA_CLIENT_SECRET: "secret",
14503
- GOOGLE_CLIENT_SECRET: "secret",
14504
- REDIS_PASSWORD: "secret",
14505
- NPM_TOKEN: "secret",
14506
- // Found via `rg process\.env\.[A-Z0-9_]+ src ee` (Step 3 of the task brief):
14507
- EXULU_API_KEY: "secret",
14508
- // auth header for remote LiteLLM client mode (resolve-model.ts)
14509
- INTERNAL_SECRET: "secret",
14510
- // compared against an internal-request header (src/auth/auth.ts)
14511
- RECALL_WORKSPACE_VERIFICATION_SECRET: "secret",
14512
- // verifies inbound Recall webhook signatures
14513
- SMTP_PASSWORD: "secret",
14514
- // EXULU_ENTERPRISE_LICENSE: the check (ee/entitlements.ts) only tests a
14515
- // string prefix, not a cryptographic signature, so it is closer to a
14516
- // capability token than a password — but knowing it still unlocks
14517
- // enterprise entitlements, so classified secret per the fail-safe rule.
14518
- EXULU_ENTERPRISE_LICENSE: "secret",
14519
- // POSTGRES_DB_USER / REDIS_USER / SMTP_USER: a username alone grants
14520
- // nothing without its paired password. Classified secret anyway — the
14521
- // design's claim is "a skill never sees the platform's own credentials",
14522
- // and a username is half of one. No skill has a legitimate need for the
14523
- // platform's database, cache, or mail identity; an admin can expose one
14524
- // deliberately as a platform variable if that ever changes.
14525
- POSTGRES_DB_USER: "secret",
14526
- REDIS_USER: "secret",
14527
- SMTP_USER: "secret",
14528
- // --- deployment credentials the consumer app reads on our behalf.
14529
- // `@exulu/backend` is a library: these never appear as `process.env.<NAME>` in
14530
- // src/ or ee/, so the code scan cannot see them — they come from the
14531
- // Server/Worker rows of mintlify-docs/self-hosting/environment-variables.mdx
14532
- // and from config.litellm.yaml's `os.environ/` directives. They were reaching
14533
- // every skill until this block existed.
14534
- //
14535
- // VERTEX_CREDENTIALS_PATH is worse than a leaked string: it is a filesystem
14536
- // path to a GCP service-account JSON, and in bwrap mode the sandbox binds /
14537
- // read-only with only ~ denied, so a skill can read the key file at the
14538
- // documented ./vertex-auth.json. Stripping the path does not make that file
14539
- // unreadable — it removes the pointer every tool follows, which is as far as
14540
- // this layer reaches.
14541
- VERTEX_CREDENTIALS_PATH: "secret",
14542
- GOOGLE_VERTEX_CREDENTIALS_JSON: "secret",
14543
- // inline service-account JSON, same credential without the file
14544
- // A GCP project id is not a password, but it is half of the Vertex identity
14545
- // and no skill has a legitimate need for it — same reasoning as
14546
- // POSTGRES_DB_USER above.
14547
- GOOGLE_VERTEX_PROJECT: "secret",
14548
- COHERE_API_KEY: "secret",
14549
- // reranker provider key (os.environ/COHERE_API_KEY)
14550
- OPENAI_API_KEY: "secret",
14551
- // TTS / model provider key
14552
- AZURE_API_KEY_EU: "secret",
14553
- // image-generation provider key
14554
- SIGNOZ_ACCESS_TOKEN: "secret",
14555
- // OTLP ingest token; read via ExuluOtel's parameter object, invisible to the code scan
14556
- HF_AUTH_TOKEN: "secret",
14557
- // HuggingFace token for pyannote diarization; documented as Whisper-container-only, stripped here fail-safe
14558
- LITELLM_API_KEY: "secret",
14559
- // supervisor-populated proxy key handed to the bundled LiteLLM UI
14560
- // --- runtime: paths, locales, feature flags, hostnames, ports, log levels.
14561
- // Only changes behaviour.
14562
- PATH: "runtime",
14563
- HOME: "runtime",
14564
- LANG: "runtime",
14565
- TZ: "runtime",
14566
- TMPDIR: "runtime",
14567
- NODE_ENV: "runtime",
14568
- PORT: "runtime",
14569
- DEBUG: "runtime",
14570
- BACKEND: "runtime",
14571
- FRONTEND: "runtime",
14572
- // Found via `rg process\.env\.[A-Z0-9_]+ src ee` (Step 3 of the task brief):
14573
- AUTH_MODE: "runtime",
14574
- // "password" | "otp" mode selector, echoed by GET /config
14575
- // Platform fallback model for POST /claims/check when the request names no
14576
- // model and no agent config supplies one. It is a model IDENTIFIER, not a
14577
- // credential: knowing the string grants access to nothing, because reaching
14578
- // that model still needs the deployment's own proxy credentials
14579
- // (LITELLM_MASTER_KEY / EXULU_API_KEY, both classified secret) and passes
14580
- // through resolveModel's catalog. All it changes is which model a check
14581
- // runs on — behaviour, which is this class's definition. Same reasoning as
14582
- // EXULU_ENTITY_EXTRACTION_MODEL, TRANSCRIPTION_MODEL and TTS_MODEL below.
14583
- CLAIM_CHECK_DEFAULT_MODEL: "runtime",
14584
- // Request deadline (ms) for POST /claims/check, overriding routes.ts's
14585
- // 60,000 default. A number of milliseconds is a setting, not a credential —
14586
- // knowing it grants no access, it only changes how long the handler waits
14587
- // before cancelling and returning 504. Same reasoning as
14588
- // CLAIM_CHECK_DEFAULT_MODEL above.
14589
- CLAIM_CHECK_TIMEOUT_MS: "runtime",
14590
- DISABLE_SCHEMA_UPDATE: "runtime",
14591
- // LiteLLM child-process flag
14592
- EXULU_ENTITY_EXTRACTION_MODEL: "runtime",
14593
- // Request-rate ceilings for external users, classified exactly as their
14594
- // guest counterparts below: a number of requests is a setting, not a
14595
- // credential. Arrived with the external-rate-limit PR, which predates this
14596
- // inventory and so could not have classified them itself.
14597
- EXULU_EXTERNAL_RATE_PER_HOUR: "runtime",
14598
- EXULU_EXTERNAL_RATE_PER_MINUTE: "runtime",
14599
- EXULU_GUEST_MAX_MESSAGE_CHARS: "runtime",
14600
- EXULU_GUEST_MAX_TOTAL_CHARS: "runtime",
14601
- EXULU_GUEST_RATE_PER_HOUR: "runtime",
14602
- EXULU_GUEST_RATE_PER_MINUTE: "runtime",
14603
- EXULU_REQUIRE_SANDBOX: "runtime",
14604
- EXULU_TRUST_PROXY: "runtime",
14605
- EXULU_USE_LITELLM: "runtime",
14606
- EXULU_VS_TIMING: "runtime",
14607
- LITELLM_BASE_URL: "runtime",
14608
- LITELLM_CONFIG_PATH: "runtime",
14609
- LITELLM_HOST: "runtime",
14610
- LITELLM_PORT: "runtime",
14611
- LITELLM_UI_PATH: "runtime",
14612
- NEXT_PUBLIC_AGENT_VISUALIZATION: "runtime",
14613
- POSTGRES_DB_HOST: "runtime",
14614
- POSTGRES_DB_NAME: "runtime",
14615
- POSTGRES_DB_PORT: "runtime",
14616
- POSTGRES_DB_SSL: "runtime",
14617
- PUBLIC_API_BASE_URL: "runtime",
14618
- RECALL_REGION: "runtime",
14619
- RECALL_RECORDING_RETENTION_HOURS: "runtime",
14620
- RECALL_STORE_VIDEO_LOCALLY: "runtime",
14621
- REDIS_HOST: "runtime",
14622
- REDIS_PORT: "runtime",
14623
- SERVER_ROOT_PATH: "runtime",
14624
- // OTLP endpoints, not credentials — the token above is the credential. They
14625
- // are credential-SHAPED (`_URL`), so they need a line here for the
14626
- // documentation reconciliation test to pass; `runtime` is the honest answer.
14627
- SIGNOZ_TRACES_URL: "runtime",
14628
- SIGNOZ_LOGS_URL: "runtime",
14629
- SMTP_FROM: "runtime",
14630
- SMTP_HOST: "runtime",
14631
- SMTP_PORT: "runtime",
14632
- SMTP_SECURE: "runtime",
14633
- TOTAL_MAX_RECORDINGS_DURATION_PER_MONTH: "runtime",
14634
- TRANSCRIPTION_MODEL: "runtime",
14635
- TRANSCRIPTION_SERVER: "runtime",
14636
- TTS_MODEL: "runtime",
14637
- TTS_VOICE: "runtime",
14638
- WHISPER_HOST: "runtime",
14639
- WHISPER_PORT: "runtime"
14640
- };
14641
- var isSecretEnvName = (name) => ENV_CLASSIFICATION[name] === "secret";
14642
- var SECRET_SHAPED_ENV_NAME = /(SECRET|PASSWORD|TOKEN|_KEY|CREDENTIAL|PRIVATE|_URL|_URI|_DSN|_PASS\b|PWD|APIKEY|LICENSE)/i;
14643
- var isSecretShapedEnvName = (name) => SECRET_SHAPED_ENV_NAME.test(name);
14644
- var findUnclassifiedSecretShaped = (env) => Object.keys(env).filter((n) => isSecretShapedEnvName(n) && !(n in ENV_CLASSIFICATION)).sort();
14645
-
14646
- // ee/invoke-skills/skill-env.ts
14647
- var POSIX_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
14648
- var buildSkillEnv = ({
14649
- processEnv,
14650
- grantedVariables,
14651
- overrides = {},
14652
- extraSecretNames = []
14653
- }) => {
14654
- const env = {};
14655
- const strippedSecretNames = [];
14656
- const extraSecrets = new Set(extraSecretNames);
14657
- for (const [name, value] of Object.entries(processEnv)) {
14658
- if (isSecretEnvName(name) || extraSecrets.has(name)) {
14659
- strippedSecretNames.push(name);
14660
- continue;
14884
+ // ee/invoke-skills/safe-fs.ts
14885
+ import { basename as basename2, dirname as dirname2, isAbsolute, join as join3, resolve as resolve3, sep as sep2 } from "path";
14886
+ var UnsafeSessionPathError = class extends Error {
14887
+ constructor(message) {
14888
+ super(message);
14889
+ this.name = "UnsafeSessionPathError";
14890
+ }
14891
+ };
14892
+ var errCode2 = (err3) => err3?.code;
14893
+ var isInside = (root, path3) => path3 === root || path3.startsWith(root + sep2);
14894
+ async function readRegularFileInside(sessionDir, path3) {
14895
+ const skip = (why) => {
14896
+ console.warn(`[SKILLS] Not reading ${path3} back from the sandbox: ${why}.`);
14897
+ return null;
14898
+ };
14899
+ let root;
14900
+ let parent;
14901
+ try {
14902
+ root = await realpath(sessionDir);
14903
+ parent = await realpath(dirname2(path3));
14904
+ } catch {
14905
+ return skip("path does not resolve");
14906
+ }
14907
+ if (!isInside(root, parent)) return skip("it resolves outside the session directory");
14908
+ let handle;
14909
+ try {
14910
+ handle = await open(
14911
+ path3,
14912
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | constants.O_NOCTTY
14913
+ );
14914
+ } catch (err3) {
14915
+ return skip(errCode2(err3) === "ELOOP" ? "it is a symbolic link" : `open failed (${errCode2(err3) ?? "unknown"})`);
14916
+ }
14917
+ try {
14918
+ const st = await handle.stat();
14919
+ if (!st.isFile()) return skip("it is not a regular file");
14920
+ if (st.size > MAX_ADOPT_UPLOAD_BYTES) {
14921
+ return skip(`it is larger than the ${MAX_ADOPT_UPLOAD_BYTES / (1024 * 1024)}MB upload limit (${st.size} bytes)`);
14661
14922
  }
14662
- env[name] = value;
14923
+ const fdPath = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => null);
14924
+ if (fdPath !== null) {
14925
+ if (!isInside(root, fdPath)) return skip("it resolves outside the session directory");
14926
+ } else {
14927
+ const again = await realpath(dirname2(path3)).catch(() => null);
14928
+ if (again === null || !isInside(root, again)) return skip("it resolves outside the session directory");
14929
+ }
14930
+ const chunks = [];
14931
+ let total = 0;
14932
+ const chunkSize = Math.min(Math.max(st.size + 1, 64 * 1024), 1024 * 1024);
14933
+ for (; ; ) {
14934
+ const chunk = Buffer.allocUnsafe(chunkSize);
14935
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
14936
+ if (bytesRead === 0) break;
14937
+ total += bytesRead;
14938
+ if (total > MAX_ADOPT_UPLOAD_BYTES) return skip("it grew past the upload limit while being read");
14939
+ chunks.push(chunk.subarray(0, bytesRead));
14940
+ }
14941
+ return Buffer.concat(chunks, total);
14942
+ } finally {
14943
+ await handle.close().catch(() => {
14944
+ });
14663
14945
  }
14664
- const baseKeys = new Set(Object.keys(env));
14665
- const grantedNames = [];
14666
- const skippedNames = [];
14667
- for (const [name, value] of Object.entries(grantedVariables)) {
14668
- if (!POSIX_NAME.test(name) || baseKeys.has(name)) {
14669
- skippedNames.push(name);
14670
- continue;
14946
+ }
14947
+ function safeSegments(relativePath) {
14948
+ if (!relativePath || isAbsolute(relativePath) || relativePath.includes("\\")) {
14949
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": not a plain relative path.`);
14950
+ }
14951
+ const segments = relativePath.split("/").filter((s) => s !== "" && s !== ".");
14952
+ if (segments.length === 0 || segments.includes("..")) {
14953
+ throw new UnsafeSessionPathError(`Refusing path "${relativePath}": it contains a ".." segment or no file name.`);
14954
+ }
14955
+ return segments;
14956
+ }
14957
+ async function ensureDirInside(sessionDir, segments) {
14958
+ const root = await realpath(sessionDir);
14959
+ let current = sessionDir;
14960
+ for (const segment of segments) {
14961
+ current = join3(current, segment);
14962
+ let st = await lstat2(current).catch((err3) => errCode2(err3) === "ENOENT" ? null : Promise.reject(err3));
14963
+ if (!st) {
14964
+ try {
14965
+ await mkdir2(current);
14966
+ } catch (err3) {
14967
+ if (errCode2(err3) !== "EEXIST") throw err3;
14968
+ }
14969
+ st = await lstat2(current);
14970
+ }
14971
+ if (!st.isDirectory()) {
14972
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it is not a real directory.`);
14671
14973
  }
14672
- env[name] = value;
14673
- grantedNames.push(name);
14674
14974
  }
14675
- Object.assign(env, overrides);
14676
- return {
14677
- env,
14678
- strippedSecretNames: strippedSecretNames.sort(),
14679
- grantedNames: grantedNames.sort(),
14680
- skippedNames: skippedNames.sort()
14681
- };
14682
- };
14683
-
14684
- // ee/invoke-skills/binary-file-guard.ts
14685
- var BINARY_DOCUMENT_EXTENSIONS = /* @__PURE__ */ new Set([
14686
- ".pdf",
14687
- ".doc",
14688
- ".docx",
14689
- ".xls",
14690
- ".xlsx",
14691
- ".ppt",
14692
- ".pptx",
14693
- ".odt",
14694
- ".ods",
14695
- ".odp",
14696
- ".zip",
14697
- ".gz",
14698
- ".png",
14699
- ".jpg",
14700
- ".jpeg",
14701
- ".gif",
14702
- ".bmp",
14703
- ".tif",
14704
- ".tiff",
14705
- ".webp"
14706
- ]);
14707
- function isBinaryDocumentPath(path3) {
14708
- const dot = path3.lastIndexOf(".");
14709
- if (dot < 0) return false;
14710
- return BINARY_DOCUMENT_EXTENSIONS.has(path3.slice(dot).toLowerCase());
14975
+ const real = await realpath(current);
14976
+ if (!isInside(root, real)) {
14977
+ throw new UnsafeSessionPathError(`Refusing to write under ${current}: it resolves outside the session directory.`);
14978
+ }
14979
+ return current;
14711
14980
  }
14712
- function looksBinary(content) {
14713
- return content.slice(0, 8192).includes("\0");
14981
+ async function writeFileInside(sessionDir, relativePath, bytes, opts = {}) {
14982
+ const segments = safeSegments(relativePath);
14983
+ const name = segments[segments.length - 1];
14984
+ const parent = await ensureDirInside(sessionDir, segments.slice(0, -1));
14985
+ const destination = join3(parent, name);
14986
+ if (opts.notUnder !== void 0 && await landsInside(sessionDir, destination, opts.notUnder)) {
14987
+ throw new UnsafeSessionPathError(`Refusing to write ${destination}: it lands in ${opts.notUnder}/.`);
14988
+ }
14989
+ const temp = join3(parent, `.exulu-write-${randomBytes3(8).toString("hex")}`);
14990
+ await writeFile2(temp, bytes, { flag: "wx" });
14991
+ try {
14992
+ await rename2(temp, destination);
14993
+ } catch (err3) {
14994
+ await unlink(temp).catch(() => {
14995
+ });
14996
+ throw err3;
14997
+ }
14998
+ return destination;
14714
14999
  }
14715
- function binaryReadHint(path3) {
14716
- return `"${path3}" is a binary file \u2014 readFile would return raw bytes that cannot be interpreted and would flood the context. The text of mail attachments is already in the conversation (the <file file name=\u2026> block); for other documents use parse_document to extract the text first, then read within that extracted text.`;
15000
+ async function ensureRealDirectory(sessionDir, relativeDir) {
15001
+ const segments = safeSegments(relativeDir);
15002
+ let current = sessionDir;
15003
+ for (const segment of segments) {
15004
+ current = join3(current, segment);
15005
+ const st = await lstat2(current).catch(() => null);
15006
+ if (st && !st.isDirectory()) {
15007
+ console.warn(`[SKILLS] ${current} is not a real directory; replacing it.`);
15008
+ await unlink(current);
15009
+ }
15010
+ }
15011
+ return ensureDirInside(sessionDir, segments);
14717
15012
  }
14718
-
14719
- // ee/invoke-skills/variable-grants.ts
14720
- var selectRowsToDecrypt = (rows) => rows.filter((row) => Boolean(row?.name) && row.allow_skill_access === true);
14721
- var deriveWithheldNames = (rows, granted) => [
14722
- ...new Set(
14723
- rows.filter((row) => Boolean(row?.name)).map((row) => row.name).filter((name) => !(name in granted))
14724
- )
14725
- ].sort();
14726
- var selectGrantedVariables = (rows) => {
14727
- const out = {};
14728
- for (const row of rows) {
14729
- if (!row?.name) continue;
14730
- if (row.allow_skill_access !== true) continue;
14731
- if (row.name.startsWith("_")) continue;
14732
- if (row.name.includes("=")) continue;
14733
- if (typeof row.value !== "string") continue;
14734
- out[row.name] = row.value;
15013
+ async function removeEntryInside(sessionDir, relativePath) {
15014
+ const segments = safeSegments(relativePath);
15015
+ const target = join3(sessionDir, ...segments);
15016
+ const root = await realpath(sessionDir);
15017
+ const parentReal = await realpath(dirname2(target)).catch(() => null);
15018
+ if (parentReal === null) return;
15019
+ if (!isInside(root, parentReal)) {
15020
+ throw new UnsafeSessionPathError(`Refusing to remove ${target}: its parent resolves outside the session directory.`);
14735
15021
  }
14736
- return out;
14737
- };
14738
-
14739
- // src/exulu/litellm/os-environ-names.ts
14740
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
14741
- var OS_ENVIRON_DIRECTIVE = /os\.environ\/([A-Za-z_][A-Za-z0-9_]*)/g;
14742
- var parseOsEnvironNames = (yamlText) => {
14743
- const found = /* @__PURE__ */ new Set();
14744
- for (const match of yamlText.matchAll(OS_ENVIRON_DIRECTIVE)) {
14745
- const name = match[1];
14746
- if (!name) continue;
14747
- if (ENV_CLASSIFICATION[name] === "runtime") continue;
14748
- found.add(name);
15022
+ const st = await lstat2(target).catch(() => null);
15023
+ if (!st) return;
15024
+ if (!st.isDirectory()) {
15025
+ await unlink(target);
15026
+ return;
14749
15027
  }
14750
- return [...found].sort();
14751
- };
14752
- var readLiteLLMOsEnvironNames = (configPath = resolveLiteLLMConfigPath()) => {
15028
+ await discardEntry(target, sessionDir);
15029
+ }
15030
+ var MAX_LINK_HOPS = 40;
15031
+ async function realLocation(path3, hops = { n: 0 }) {
14753
15032
  try {
14754
- if (!existsSync3(configPath)) return [];
14755
- return parseOsEnvironNames(readFileSync2(configPath, "utf8"));
15033
+ return await realpath(path3);
14756
15034
  } catch (err3) {
14757
- console.warn(
14758
- `[SKILLS] Could not read LiteLLM config at ${configPath} to collect os.environ/ credential names; the skill environment falls back to the static secret inventory.`,
14759
- err3
14760
- );
14761
- return [];
15035
+ if (errCode2(err3) !== "ENOENT") throw err3;
14762
15036
  }
14763
- };
14764
-
14765
- // src/exulu/audit/config.ts
14766
- import os from "os";
14767
- import path from "path";
14768
- var normalizePrefix = (p) => {
14769
- const raw = (p ?? "audit").trim().replace(/^\/+|\/+$/g, "");
14770
- return `${raw || "audit"}/`;
14771
- };
14772
- var hasAllS3Fields = (t) => !!t && !!t.s3region && !!t.s3key && !!t.s3secret && !!t.s3Bucket;
14773
- var resolveAuditConfig = (config) => {
14774
- const a = config.audit;
14775
- if (!a || a.enabled !== true) return null;
14776
- const dedicated = hasAllS3Fields(a.s3);
14777
- const source = dedicated ? a.s3 : config.fileUploads;
14778
- if (!hasAllS3Fields(source)) {
14779
- throw new Error(
14780
- "[EXULU] audit.enabled is true but no S3 target is configured. Set config.audit.s3 or config.fileUploads."
14781
- );
15037
+ const st = await lstat2(path3).catch((err3) => errCode2(err3) === "ENOENT" ? null : Promise.reject(err3));
15038
+ if (st?.isSymbolicLink()) {
15039
+ if (++hops.n > MAX_LINK_HOPS) throw Object.assign(new Error(`Too many links resolving ${path3}`), { code: "ELOOP" });
15040
+ return realLocation(resolve3(dirname2(path3), await readlink(path3)), hops);
14782
15041
  }
14783
- if (!Number.isInteger(a.retentionDays) || a.retentionDays <= 0) {
14784
- throw new Error(`[EXULU] audit.retentionDays must be a positive integer, got ${a.retentionDays}.`);
15042
+ const parent = dirname2(path3);
15043
+ if (parent === path3) return path3;
15044
+ return join3(await realLocation(parent, hops), basename2(path3));
15045
+ }
15046
+ async function landsInside(sessionDir, path3, relativeDir) {
15047
+ const segments = safeSegments(relativeDir);
15048
+ try {
15049
+ const entry = await realLocation(join3(sessionDir, ...segments));
15050
+ const target = await realLocation(resolve3(path3));
15051
+ return isInside(entry, target);
15052
+ } catch (err3) {
15053
+ return errCode2(err3) !== "ENOTDIR";
14785
15054
  }
14786
- const usingSharedFileUploadsBucket = !dedicated;
14787
- return {
14788
- target: {
14789
- s3region: source.s3region,
14790
- s3key: source.s3key,
14791
- s3secret: source.s3secret,
14792
- s3Bucket: source.s3Bucket,
14793
- s3prefix: normalizePrefix(source.s3prefix),
14794
- ...source.s3endpoint ? { s3endpoint: source.s3endpoint } : {}
14795
- },
14796
- retentionDays: a.retentionDays,
14797
- manageLifecycle: a.manageLifecycle ?? !usingSharedFileUploadsBucket,
14798
- usingSharedFileUploadsBucket,
14799
- spoolDir: a.spoolDir ?? path.join(os.tmpdir(), "exulu-audit-spool"),
14800
- flush: {
14801
- maxRecords: a.flush?.maxRecords ?? 100,
14802
- maxIntervalMs: a.flush?.maxIntervalMs ?? 5e3
14803
- },
14804
- payload: {
14805
- maxBytes: a.payload?.maxBytes ?? 32768,
14806
- captureOutput: a.payload?.captureOutput ?? true,
14807
- redactKeys: a.payload?.redactKeys ?? []
14808
- },
14809
- failureMode: a.failureMode ?? "open",
14810
- toolCalls: {
14811
- enabled: a.sources?.toolCalls?.enabled ?? true,
14812
- include: a.sources?.toolCalls?.include ?? [],
14813
- exclude: a.sources?.toolCalls?.exclude ?? []
14814
- },
14815
- skillSandbox: {
14816
- enabled: a.sources?.skillSandbox?.enabled ?? false
14817
- }
14818
- };
14819
- };
15055
+ }
14820
15056
 
14821
- // src/exulu/audit/s3-writer.ts
14822
- import {
14823
- S3Client as S3Client2,
14824
- PutObjectCommand as PutObjectCommand2,
14825
- GetBucketLifecycleConfigurationCommand,
14826
- PutBucketLifecycleConfigurationCommand
14827
- } from "@aws-sdk/client-s3";
14828
- var RETRYABLE = /* @__PURE__ */ new Set(["SignatureDoesNotMatch", "InvalidAccessKeyId", "AccessDenied"]);
14829
- var buildAuditS3Client = (t) => new S3Client2({
14830
- region: t.s3region,
14831
- ...t.s3endpoint ? { forcePathStyle: true, endpoint: t.s3endpoint } : {},
14832
- credentials: { accessKeyId: t.s3key, secretAccessKey: t.s3secret },
14833
- requestChecksumCalculation: "WHEN_REQUIRED",
14834
- responseChecksumValidation: "WHEN_REQUIRED"
14835
- });
14836
- var createAuditS3Writer = (target, client, opts) => {
14837
- const c = client ?? buildAuditS3Client(target);
14838
- const maxRetries = opts?.maxRetries ?? 3;
14839
- const backoffMs = opts?.backoffMs ?? ((attempt) => Math.pow(2, attempt) * 1e3);
14840
- const putNdjson = async (key, body) => {
14841
- let lastError = null;
14842
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
14843
- const command = new PutObjectCommand2({
14844
- Bucket: target.s3Bucket,
14845
- Key: key,
14846
- Body: Buffer.from(body, "utf8"),
14847
- ContentType: "application/x-ndjson"
14848
- });
14849
- try {
14850
- await c.send(command);
14851
- return;
14852
- } catch (error) {
14853
- lastError = error;
14854
- if (RETRYABLE.has(error?.name) && attempt < maxRetries) {
14855
- await new Promise((r) => setTimeout(r, backoffMs(attempt)));
15057
+ // ee/invoke-skills/skill-actions/tool.ts
15058
+ var RUN_SKILL_ACTION_TOOL_ID = "run_skill_action";
15059
+ var TEXT_MAX_CHARS = 1e4;
15060
+ var ITEMS_DEFAULT_LIMIT = 50;
15061
+ var ITEMS_MAX_LIMIT = 500;
15062
+ var ARGS_FILE_STEM = "args";
15063
+ var isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15064
+ var listOrNone = (names) => names.length ? names.join(", ") : "(none)";
15065
+ var createRunSkillActionTool = (deps) => {
15066
+ const { handle, loaded, contexts, connectedContextIds, truncate, resultCharLimit } = deps;
15067
+ const description = `Run a declared action of a skill. The platform reads the knowledge-base items the action needs with the current user's rights, hands them to the skill's script as files, runs the script in the session sandbox and returns its exit code and output (files it creates come back as download links). Pass ids, filters and text only in \`inputs\`. Item inputs take an id string or { external_id }; items inputs take { where?, limit? } (default ${ITEMS_DEFAULT_LIMIT}, max ${ITEMS_MAX_LIMIT}); text inputs take a string (max ${TEXT_MAX_CHARS} characters). Available actions:
15068
+ ` + describeActions(loaded);
15069
+ return new ExuluTool({
15070
+ id: RUN_SKILL_ACTION_TOOL_ID,
15071
+ name: RUN_SKILL_ACTION_TOOL_ID,
15072
+ category: "skills",
15073
+ description,
15074
+ type: "function",
15075
+ inputSchema: z18.object({
15076
+ skill: z18.string().describe("The skill's name, as listed in this description."),
15077
+ action: z18.string().describe("The action's name within that skill."),
15078
+ inputs: z18.record(z18.string(), z18.unknown()).optional().describe("The action's inputs by name, as listed in this description.")
15079
+ }),
15080
+ config: [],
15081
+ needsApproval: false,
15082
+ execute: async (params) => {
15083
+ const refuse = (message) => ({ result: `Not run: ${message}` });
15084
+ const skillName = params?.skill;
15085
+ const actionName = params?.action;
15086
+ if (typeof skillName !== "string" || !Object.hasOwn(loaded.bySkill, skillName)) {
15087
+ return refuse(
15088
+ `unknown skill "${String(skillName)}". Available: ${listOrNone(Object.keys(loaded.bySkill))}.`
15089
+ );
15090
+ }
15091
+ const skill = loaded.bySkill[skillName];
15092
+ if (typeof actionName !== "string" || !Object.hasOwn(skill.actions, actionName)) {
15093
+ return refuse(
15094
+ `unknown action "${String(actionName)}" for skill "${skillName}". Available: ${listOrNone(Object.keys(skill.actions))}.`
15095
+ );
15096
+ }
15097
+ const action = skill.actions[actionName];
15098
+ const label = `${skillName} / ${actionName}`;
15099
+ const declaredNames = Object.keys(action.inputs);
15100
+ const inputList = `Inputs of ${label}: ${listOrNone(declaredNames)}.`;
15101
+ const given = params?.inputs === void 0 || params?.inputs === null ? {} : params.inputs;
15102
+ if (!isPlainObject3(given)) {
15103
+ return refuse(`inputs must be an object keyed by input name. ${inputList}`);
15104
+ }
15105
+ for (const key of Object.keys(given)) {
15106
+ if (!Object.hasOwn(action.inputs, key)) {
15107
+ return refuse(`unknown input "${key}". ${inputList}`);
15108
+ }
15109
+ }
15110
+ const argsInput = Object.hasOwn(action.inputs, ARGS_FILE_STEM) ? action.inputs[ARGS_FILE_STEM] : void 0;
15111
+ if (argsInput && argsInput.type !== "text") {
15112
+ return refuse(
15113
+ `${label} cannot run: its ${argsInput.type} input is named "${ARGS_FILE_STEM}", which collides with ${ARGS_FILE_STEM}.json (the file of the text inputs). The skill's actions.yaml must rename it.`
15114
+ );
15115
+ }
15116
+ const resolved = [];
15117
+ for (const [name, input] of Object.entries(action.inputs)) {
15118
+ const value = Object.hasOwn(given, name) ? given[name] : void 0;
15119
+ if (input.type === "text") {
15120
+ if (value === void 0 || value === null) {
15121
+ if (input.required) return refuse(`input "${name}" is required. ${inputList}`);
15122
+ continue;
15123
+ }
15124
+ if (typeof value !== "string") return refuse(`input "${name}" must be a string.`);
15125
+ if (value.length > TEXT_MAX_CHARS) {
15126
+ return refuse(`input "${name}" is ${value.length} characters long; the maximum is ${TEXT_MAX_CHARS}.`);
15127
+ }
15128
+ resolved.push({ name, type: "text", value });
14856
15129
  continue;
14857
15130
  }
14858
- throw error;
15131
+ const context = contexts.find((c) => c.id === input.context);
15132
+ if (!connectedContextIds.has(input.context) || !context) {
15133
+ return refuse(
15134
+ `input "${name}" reads the knowledge base "${input.context}", which is not connected to this agent.`
15135
+ );
15136
+ }
15137
+ if (input.type === "item") {
15138
+ if (value === void 0 || value === null) return refuse(`input "${name}" is required. ${inputList}`);
15139
+ if (typeof value === "string" && value.trim() !== "") {
15140
+ resolved.push({ name, type: "item", context, input, ref: { id: value } });
15141
+ } else if (isPlainObject3(value) && Object.keys(value).length === 1 && typeof value.external_id === "string" && value.external_id.trim() !== "") {
15142
+ resolved.push({ name, type: "item", context, input, ref: { external_id: value.external_id } });
15143
+ } else {
15144
+ return refuse(`input "${name}" must be an item id (a non-empty string) or { "external_id": "<id>" }.`);
15145
+ }
15146
+ continue;
15147
+ }
15148
+ if (value !== void 0 && value !== null && !isPlainObject3(value)) {
15149
+ return refuse(`input "${name}" must be { "where"?: {...}, "limit"?: number } or omitted.`);
15150
+ }
15151
+ const spec = value ?? {};
15152
+ const surplus = Object.keys(spec).filter((k) => k !== "where" && k !== "limit");
15153
+ if (surplus.length) {
15154
+ return refuse(`input "${name}" has unknown key "${surplus[0]}"; it takes only "where" and "limit".`);
15155
+ }
15156
+ if (spec.where !== void 0 && !isPlainObject3(spec.where)) {
15157
+ return refuse(`input "${name}": "where" must be an object of field filters.`);
15158
+ }
15159
+ if (spec.limit !== void 0 && !(typeof spec.limit === "number" && Number.isInteger(spec.limit) && spec.limit >= 1)) {
15160
+ return refuse(`input "${name}": "limit" must be a whole number of at least 1 (maximum ${ITEMS_MAX_LIMIT}).`);
15161
+ }
15162
+ const fixed = input.where ?? {};
15163
+ const callerWhere = spec.where ?? {};
15164
+ const clash = Object.keys(callerWhere).find((k) => Object.hasOwn(fixed, k));
15165
+ if (clash) {
15166
+ return refuse(
15167
+ `input "${name}": the field "${clash}" is already filtered by the action itself and cannot be filtered again.`
15168
+ );
15169
+ }
15170
+ const where = { ...fixed, ...callerWhere };
15171
+ resolved.push({
15172
+ name,
15173
+ type: "items",
15174
+ context,
15175
+ input,
15176
+ where: Object.keys(where).length ? where : void 0,
15177
+ limit: spec.limit
15178
+ });
15179
+ }
15180
+ const caller = { user: params?.user, req: params?.req };
15181
+ const files = [];
15182
+ const warnings = [];
15183
+ const textArgs = {};
15184
+ for (const r of resolved) {
15185
+ if (r.type === "text") {
15186
+ textArgs[r.name] = r.value;
15187
+ continue;
15188
+ }
15189
+ if (r.type === "item") {
15190
+ const outcome2 = await readContextItem(r.context, { ...r.ref, fields: r.input.fields }, caller);
15191
+ if (!outcome2.ok) return refuse(`input "${r.name}": ${outcome2.message}`);
15192
+ files.push({ file: `${r.name}.json`, content: outcome2.item });
15193
+ continue;
15194
+ }
15195
+ const outcome = await findContextItems(
15196
+ r.context,
15197
+ { where: r.where, limit: r.limit ?? ITEMS_DEFAULT_LIMIT, maxLimit: ITEMS_MAX_LIMIT, fields: r.input.fields },
15198
+ caller
15199
+ );
15200
+ if (!outcome.ok) return refuse(`input "${r.name}": ${outcome.message}`);
15201
+ files.push({
15202
+ file: `${r.name}.json`,
15203
+ content: { items: outcome.items, limit: outcome.limit, truncated: outcome.truncated }
15204
+ });
15205
+ if (outcome.truncated) warnings.push(`warning: input "${r.name}" was cut at ${outcome.limit} items`);
15206
+ }
15207
+ if (resolved.some((r) => r.type === "text")) {
15208
+ files.push({ file: `${ARGS_FILE_STEM}.json`, content: textArgs });
15209
+ }
15210
+ const sessionDir = handle.sessionDir;
15211
+ const runId = randomUUID6();
15212
+ const runRelative = `${ACTION_INPUTS_DIR}/${runId}`;
15213
+ try {
15214
+ const parent = await ensureRealDirectory(sessionDir, ACTION_INPUTS_DIR);
15215
+ await mkdir3(join4(parent, runId), { mode: 448 });
15216
+ for (const { file, content } of files) {
15217
+ await writeFileInside(sessionDir, `${runRelative}/${file}`, JSON.stringify(content));
15218
+ }
15219
+ const outcome = await handle.runCommand(action.run, {
15220
+ extraEnv: {
15221
+ EXULU_INPUTS_DIR: join4(sessionDir, runRelative),
15222
+ EXULU_SKILL_DIR: skill.skillDir
15223
+ },
15224
+ timeoutMs: action.timeoutSeconds * 1e3
15225
+ });
15226
+ const fixed = [`exit_code: ${outcome.exitCode}`];
15227
+ if (outcome.timedOut) fixed.push(`timed out after ${action.timeoutSeconds}s`);
15228
+ fixed.push(...warnings);
15229
+ const { output, block } = splitArtifactsBlock(
15230
+ outcome.stdout ?? "",
15231
+ (outcome.artifacts ?? []).some((a) => a.url)
15232
+ );
15233
+ return {
15234
+ result: fitResult({
15235
+ fixed,
15236
+ stdout: output,
15237
+ artifactsBlock: block,
15238
+ stderr: outcome.stderr ?? "",
15239
+ truncate,
15240
+ limit: resultCharLimit
15241
+ })
15242
+ };
15243
+ } finally {
15244
+ await removeEntryInside(sessionDir, runRelative).catch(
15245
+ (err3) => console.error(`[SKILLS] Could not remove the action inputs directory ${runRelative}:`, err3)
15246
+ );
14859
15247
  }
14860
15248
  }
14861
- if (lastError) throw lastError;
14862
- };
14863
- const getLifecycle = async () => c.send(new GetBucketLifecycleConfigurationCommand({ Bucket: target.s3Bucket }));
14864
- const putLifecycle = async (config) => {
14865
- await c.send(
14866
- new PutBucketLifecycleConfigurationCommand({
14867
- Bucket: target.s3Bucket,
14868
- LifecycleConfiguration: config
14869
- })
14870
- );
14871
- };
14872
- return { putNdjson, getLifecycle, putLifecycle };
14873
- };
14874
-
14875
- // src/exulu/audit/lifecycle.ts
14876
- var AUDIT_LIFECYCLE_RULE_ID = "exulu-audit-retention";
14877
- var buildRule = (prefix, retentionDays) => ({
14878
- ID: AUDIT_LIFECYCLE_RULE_ID,
14879
- Filter: { Prefix: prefix },
14880
- Status: "Enabled",
14881
- Expiration: { Days: retentionDays }
14882
- });
14883
- var applyRetentionLifecycle = async (writer, opts) => {
14884
- const rule = buildRule(opts.prefix, opts.retentionDays);
14885
- const config = { Rules: [rule] };
14886
- if (!opts.manage) {
14887
- console.warn(
14888
- `[EXULU] audit retention: not managing the S3 lifecycle for this bucket. Apply this rule manually:
14889
- ${JSON.stringify(config, null, 2)}`
14890
- );
14891
- return;
14892
- }
14893
- try {
14894
- let existing = [];
14895
- try {
14896
- const current = await writer.getLifecycle();
14897
- existing = (current?.Rules ?? []).filter((r) => r.ID !== AUDIT_LIFECYCLE_RULE_ID);
14898
- } catch (error) {
14899
- if (error?.name !== "NoSuchLifecycleConfiguration") throw error;
14900
- }
14901
- await writer.putLifecycle({ Rules: [...existing, rule] });
14902
- console.log(`[EXULU] audit retention: S3 lifecycle set to expire "${opts.prefix}" after ${opts.retentionDays} days.`);
14903
- } catch (error) {
14904
- console.warn(
14905
- `[EXULU] audit retention: could not set the S3 lifecycle (${error?.name ?? "error"}). Apply this rule manually:
14906
- ${JSON.stringify(config, null, 2)}`
14907
- );
14908
- }
15249
+ });
14909
15250
  };
14910
-
14911
- // src/exulu/audit/sink.ts
14912
- import { randomUUID as randomUUID6 } from "crypto";
14913
- import { promises as fs } from "fs";
14914
- import path2 from "path";
14915
- var createFsSpoolStore = (dir) => ({
14916
- write: async (name, body) => {
14917
- await fs.mkdir(dir, { recursive: true });
14918
- await fs.writeFile(path2.join(dir, name), body, "utf8");
14919
- },
14920
- list: async () => {
14921
- try {
14922
- return (await fs.readdir(dir)).filter((f) => f.endsWith(".ndjson"));
14923
- } catch {
14924
- return [];
14925
- }
14926
- },
14927
- read: async (name) => fs.readFile(path2.join(dir, name), "utf8"),
14928
- remove: async (name) => {
14929
- await fs.rm(path2.join(dir, name), { force: true });
15251
+ var RESULT_MARGIN_CHARS = 256;
15252
+ var STDERR_SHARE = 0.3;
15253
+ var fitResult = (p) => {
15254
+ const assemble = (out, err3) => [...p.fixed, `stdout:
15255
+ ${out}${p.artifactsBlock}`, `stderr:
15256
+ ${err3}`].join("\n");
15257
+ const size = (text) => JSON.stringify({ result: text }).length;
15258
+ const full = assemble(p.stdout, p.stderr);
15259
+ if (size(full) <= p.limit) return full;
15260
+ const room = p.limit - size(assemble("", "")) - RESULT_MARGIN_CHARS;
15261
+ if (room <= 0) return assemble("", "");
15262
+ let errBudget = Math.min(p.stderr.length, Math.floor(room * STDERR_SHARE));
15263
+ let outBudget = Math.min(p.stdout.length, room - errBudget);
15264
+ errBudget = Math.min(p.stderr.length, room - outBudget);
15265
+ for (let attempt = 0; attempt < 6; attempt++) {
15266
+ const out = p.stdout.length <= outBudget ? p.stdout : p.truncate(p.stdout, "stdout", Math.max(1, outBudget));
15267
+ const err3 = p.stderr.length <= errBudget ? p.stderr : p.truncate(p.stderr, "stderr", Math.max(1, errBudget));
15268
+ const text = assemble(out, err3);
15269
+ const over = size(text) - p.limit;
15270
+ if (over <= 0) return text;
15271
+ const outCut = out !== p.stdout;
15272
+ const errCut = err3 !== p.stderr;
15273
+ const total = (outCut ? outBudget : 0) + (errCut ? errBudget : 0);
15274
+ const scale = Math.max(0, (total - over - RESULT_MARGIN_CHARS) / Math.max(1, total)) * 0.9;
15275
+ if (outCut) outBudget = Math.floor(outBudget * scale);
15276
+ if (errCut) errBudget = Math.floor(errBudget * scale);
15277
+ }
15278
+ return assemble("", "");
15279
+ };
15280
+ var disabledSearchContexts = (searchConfig) => {
15281
+ const row = Array.isArray(searchConfig?.config) ? searchConfig.config.find((c) => c?.name === "knowledge_bases") : void 0;
15282
+ let raw;
15283
+ if (row?.variable) {
15284
+ if (row.type !== "json" && row.type !== "string") return null;
15285
+ raw = row.variable;
15286
+ } else {
15287
+ raw = row?.value;
14930
15288
  }
14931
- });
14932
- var pad = (n) => String(n).padStart(2, "0");
14933
- var AuditSink = class {
14934
- constructor(cfg, writer, spool, opts) {
14935
- this.cfg = cfg;
14936
- this.writer = writer;
14937
- this.spool = spool;
14938
- this.now = opts?.now ?? (() => /* @__PURE__ */ new Date());
15289
+ if (raw === void 0 || raw === null) return /* @__PURE__ */ new Set();
15290
+ if (typeof raw === "string") {
15291
+ if (raw.trim() === "") return /* @__PURE__ */ new Set();
15292
+ try {
15293
+ raw = JSON.parse(raw);
15294
+ } catch {
15295
+ return null;
15296
+ }
14939
15297
  }
14940
- buffer = [];
14941
- timer = null;
14942
- now;
14943
- objectKey() {
14944
- const d = this.now();
14945
- const dt = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
14946
- return `${this.cfg.target.s3prefix}dt=${dt}/${pad(d.getUTCHours())}/${d.getTime()}-${randomUUID6()}.ndjson`;
15298
+ if (!isPlainObject3(raw)) return null;
15299
+ const disabled = /* @__PURE__ */ new Set();
15300
+ for (const [contextId, profile] of Object.entries(raw)) {
15301
+ if (!isPlainObject3(profile)) return null;
15302
+ if (profile.enabled !== void 0 && typeof profile.enabled !== "boolean") return null;
15303
+ if (profile.enabled === false) disabled.add(contextId);
14947
15304
  }
14948
- serialize(events) {
14949
- return events.map((e) => JSON.stringify(e)).join("\n") + "\n";
15305
+ return disabled;
15306
+ };
15307
+ var deriveConnectedContextIds = (args) => {
15308
+ const ids = /* @__PURE__ */ new Set();
15309
+ for (const id of args.editorContextIds) {
15310
+ const segment = contextToolSegment({ id });
15311
+ const readToolIds = [`get_${segment}_item`, `find_${segment}_items`];
15312
+ if (readToolIds.some((toolId) => !args.disabledToolIds?.has(toolId))) ids.add(id);
14950
15313
  }
14951
- record(event) {
14952
- this.buffer.push(event);
14953
- if (this.buffer.length >= this.cfg.flush.maxRecords) {
14954
- void this.flush();
14955
- } else if (!this.timer) {
14956
- this.timer = setTimeout(() => void this.flush(), this.cfg.flush.maxIntervalMs);
14957
- this.timer.unref?.();
15314
+ if (args.agenticSearch) {
15315
+ const disabled = disabledSearchContexts(args.agenticSearch.config);
15316
+ if (disabled) {
15317
+ for (const id of args.contextIds) if (!disabled.has(id)) ids.add(id);
14958
15318
  }
15319
+ } else if (args.projectSearchContextIds) {
15320
+ for (const id of args.projectSearchContextIds) ids.add(id);
14959
15321
  }
14960
- async flush() {
14961
- if (this.timer) {
14962
- clearTimeout(this.timer);
14963
- this.timer = null;
15322
+ if (args.memoryContextId) ids.delete(args.memoryContextId);
15323
+ return ids;
15324
+ };
15325
+
15326
+ // ee/invoke-skills/create-sandbox.ts
15327
+ import {
15328
+ SandboxManager
15329
+ } from "@anthropic-ai/sandbox-runtime";
15330
+ import { mkdir as mkdir4, rm as rm2, readdir as readdir2, stat, lstat as lstat3 } from "fs/promises";
15331
+ import { existsSync as existsSync4 } from "fs";
15332
+ import { join as join6, dirname as dirname3, resolve as resolve4, relative, posix } from "path";
15333
+ import { exec as exec2, spawn } from "child_process";
15334
+ import { promisify as promisify3 } from "util";
15335
+
15336
+ // src/exulu/system-dependencies.ts
15337
+ import { exec } from "child_process";
15338
+ import { existsSync as existsSync2 } from "fs";
15339
+ import { join as join5 } from "path";
15340
+ import { promisify as promisify2 } from "util";
15341
+ var execAsync = promisify2(exec);
15342
+ var REQUIRED_SYSTEM_DEPENDENCIES = [
15343
+ {
15344
+ check: { kind: "binary", binary: "pandoc" },
15345
+ displayName: "Pandoc",
15346
+ purpose: "docx skill: text extraction and tracked-changes conversion",
15347
+ installHints: {
15348
+ debian: "apt-get install -y pandoc",
15349
+ macos: "brew install pandoc"
14964
15350
  }
14965
- if (this.buffer.length === 0) return;
14966
- const batch = this.buffer;
14967
- this.buffer = [];
14968
- const body = this.serialize(batch);
14969
- try {
14970
- await this.writer.putNdjson(this.objectKey(), body);
14971
- await this.drainSpool();
14972
- } catch (error) {
14973
- const name = `${Date.now()}-${randomUUID6()}.ndjson`;
14974
- try {
14975
- await this.spool.write(name, body);
14976
- console.warn(`[EXULU] audit: S3 write failed, spooled ${batch.length} record(s) to disk (${name}).`, error);
14977
- } catch (spoolError) {
14978
- console.error(`[EXULU] audit: S3 write AND local spool failed \u2014 ${batch.length} record(s) lost.`, spoolError);
14979
- }
15351
+ },
15352
+ {
15353
+ check: { kind: "binary", binary: "soffice" },
15354
+ displayName: "LibreOffice",
15355
+ purpose: "docx skill: converting .docx documents to PDF for visual analysis",
15356
+ installHints: {
15357
+ debian: "apt-get install -y libreoffice",
15358
+ macos: "brew install --cask libreoffice"
15359
+ }
15360
+ },
15361
+ {
15362
+ check: { kind: "binary", binary: "pdftoppm" },
15363
+ displayName: "Poppler (pdftoppm)",
15364
+ purpose: "docx skill: converting PDF pages to images",
15365
+ installHints: {
15366
+ debian: "apt-get install -y poppler-utils",
15367
+ macos: "brew install poppler"
15368
+ }
15369
+ },
15370
+ {
15371
+ check: { kind: "binary", binary: "pdftotext" },
15372
+ displayName: "Poppler (pdftotext)",
15373
+ purpose: "parse_document tool: extracting page-marked text from PDFs",
15374
+ installHints: {
15375
+ debian: "apt-get install -y poppler-utils",
15376
+ macos: "brew install poppler"
15377
+ }
15378
+ },
15379
+ {
15380
+ check: { kind: "npm-global", packageName: "docx" },
15381
+ displayName: "docx (npm global)",
15382
+ purpose: "docx skill: programmatically constructing new .docx documents",
15383
+ installHints: {
15384
+ debian: "npm install -g docx",
15385
+ macos: "npm install -g docx"
14980
15386
  }
14981
15387
  }
14982
- async drainSpool() {
14983
- const names = await this.spool.list();
14984
- for (const name of names) {
15388
+ ];
15389
+ var cachedNpmGlobalRoot;
15390
+ async function getNpmGlobalRoot() {
15391
+ if (cachedNpmGlobalRoot !== void 0) return cachedNpmGlobalRoot;
15392
+ try {
15393
+ const { stdout } = await execAsync("npm root -g", { shell: "/bin/sh" });
15394
+ cachedNpmGlobalRoot = stdout.trim() || null;
15395
+ } catch {
15396
+ cachedNpmGlobalRoot = null;
15397
+ }
15398
+ return cachedNpmGlobalRoot;
15399
+ }
15400
+ async function probeDependency(dep) {
15401
+ switch (dep.check.kind) {
15402
+ case "binary": {
14985
15403
  try {
14986
- const body = await this.spool.read(name);
14987
- await this.writer.putNdjson(this.objectKey(), body);
14988
- await this.spool.remove(name);
15404
+ await execAsync(`command -v ${dep.check.binary}`, { shell: "/bin/sh" });
15405
+ return true;
14989
15406
  } catch {
14990
- return;
15407
+ return false;
14991
15408
  }
14992
15409
  }
15410
+ case "npm-global": {
15411
+ const root = await getNpmGlobalRoot();
15412
+ if (!root) return false;
15413
+ return existsSync2(join5(root, dep.check.packageName));
15414
+ }
14993
15415
  }
14994
- async recordDurable(event) {
14995
- await this.writer.putNdjson(this.objectKey(), this.serialize([event]));
14996
- }
14997
- async close() {
14998
- await this.flush();
15416
+ }
15417
+ async function checkSystemDependencies() {
15418
+ const probes = await Promise.all(
15419
+ REQUIRED_SYSTEM_DEPENDENCIES.map(async (dep) => ({
15420
+ dep,
15421
+ present: await probeDependency(dep)
15422
+ }))
15423
+ );
15424
+ return {
15425
+ missing: probes.filter((p) => !p.present).map((p) => p.dep)
15426
+ };
15427
+ }
15428
+ function formatMissing(dep) {
15429
+ const probeLabel = dep.check.kind === "binary" ? dep.check.binary : `npm:${dep.check.packageName} (global)`;
15430
+ return ` - ${dep.displayName} (${probeLabel}) \u2014 ${dep.purpose}
15431
+ Debian/Ubuntu: ${dep.installHints.debian}
15432
+ macOS: ${dep.installHints.macos}`;
15433
+ }
15434
+ async function reportSystemDependencies(opts) {
15435
+ const { missing } = await checkSystemDependencies();
15436
+ if (missing.length === 0) return;
15437
+ const body = `${missing.length} system dependency check(s) failed:
15438
+ ` + missing.map(formatMissing).join("\n");
15439
+ if (opts.requireSystemDependencies) {
15440
+ throw new Error(
15441
+ `[EXULU] Required system dependencies are missing. Install them and restart, or set requireSystemDependencies=false in ExuluConfig to downgrade to a warning.
15442
+ ${body}`
15443
+ );
14999
15444
  }
15000
- };
15445
+ console.warn(
15446
+ `[EXULU] ${body}
15447
+ Set requireSystemDependencies=true in ExuluConfig to make this fatal at startup.`
15448
+ );
15449
+ }
15001
15450
 
15002
- // src/exulu/audit/event.ts
15003
- var AUDIT_EVENT_TYPES = {
15004
- TOOL_CALL: "tool.call",
15005
- SKILL_SANDBOX_CREATED: "skill.sandbox.created"
15451
+ // src/exulu/skill-env/inventory.ts
15452
+ var ENV_CLASSIFICATION = {
15453
+ // --- secrets: credentials, tokens, signing/verification secrets, keys.
15454
+ // Knowing the value grants access to something.
15455
+ NEXTAUTH_SECRET: "secret",
15456
+ POSTGRES_DB_PASSWORD: "secret",
15457
+ LITELLM_MASTER_KEY: "secret",
15458
+ LITELLM_DATABASE_URL: "secret",
15459
+ COMPANION_S3_SECRET: "secret",
15460
+ COMPANION_S3_KEY: "secret",
15461
+ ANTHROPIC_API_KEY: "secret",
15462
+ GEMINI_API_KEY: "secret",
15463
+ PERPLEXITY_API_KEY: "secret",
15464
+ RECALL_API_KEY: "secret",
15465
+ JIRA_CLIENT_SECRET: "secret",
15466
+ GOOGLE_CLIENT_SECRET: "secret",
15467
+ REDIS_PASSWORD: "secret",
15468
+ NPM_TOKEN: "secret",
15469
+ // Found via `rg process\.env\.[A-Z0-9_]+ src ee` (Step 3 of the task brief):
15470
+ EXULU_API_KEY: "secret",
15471
+ // auth header for remote LiteLLM client mode (resolve-model.ts)
15472
+ INTERNAL_SECRET: "secret",
15473
+ // compared against an internal-request header (src/auth/auth.ts)
15474
+ RECALL_WORKSPACE_VERIFICATION_SECRET: "secret",
15475
+ // verifies inbound Recall webhook signatures
15476
+ SMTP_PASSWORD: "secret",
15477
+ // EXULU_ENTERPRISE_LICENSE: the check (ee/entitlements.ts) only tests a
15478
+ // string prefix, not a cryptographic signature, so it is closer to a
15479
+ // capability token than a password — but knowing it still unlocks
15480
+ // enterprise entitlements, so classified secret per the fail-safe rule.
15481
+ EXULU_ENTERPRISE_LICENSE: "secret",
15482
+ // POSTGRES_DB_USER / REDIS_USER / SMTP_USER: a username alone grants
15483
+ // nothing without its paired password. Classified secret anyway — the
15484
+ // design's claim is "a skill never sees the platform's own credentials",
15485
+ // and a username is half of one. No skill has a legitimate need for the
15486
+ // platform's database, cache, or mail identity; an admin can expose one
15487
+ // deliberately as a platform variable if that ever changes.
15488
+ POSTGRES_DB_USER: "secret",
15489
+ REDIS_USER: "secret",
15490
+ SMTP_USER: "secret",
15491
+ // --- deployment credentials the consumer app reads on our behalf.
15492
+ // `@exulu/backend` is a library: these never appear as `process.env.<NAME>` in
15493
+ // src/ or ee/, so the code scan cannot see them — they come from the
15494
+ // Server/Worker rows of mintlify-docs/self-hosting/environment-variables.mdx
15495
+ // and from config.litellm.yaml's `os.environ/` directives. They were reaching
15496
+ // every skill until this block existed.
15497
+ //
15498
+ // VERTEX_CREDENTIALS_PATH is worse than a leaked string: it is a filesystem
15499
+ // path to a GCP service-account JSON, and in bwrap mode the sandbox binds /
15500
+ // read-only with only ~ denied, so a skill can read the key file at the
15501
+ // documented ./vertex-auth.json. Stripping the path does not make that file
15502
+ // unreadable — it removes the pointer every tool follows, which is as far as
15503
+ // this layer reaches.
15504
+ VERTEX_CREDENTIALS_PATH: "secret",
15505
+ GOOGLE_VERTEX_CREDENTIALS_JSON: "secret",
15506
+ // inline service-account JSON, same credential without the file
15507
+ // A GCP project id is not a password, but it is half of the Vertex identity
15508
+ // and no skill has a legitimate need for it — same reasoning as
15509
+ // POSTGRES_DB_USER above.
15510
+ GOOGLE_VERTEX_PROJECT: "secret",
15511
+ COHERE_API_KEY: "secret",
15512
+ // reranker provider key (os.environ/COHERE_API_KEY)
15513
+ OPENAI_API_KEY: "secret",
15514
+ // TTS / model provider key
15515
+ AZURE_API_KEY_EU: "secret",
15516
+ // image-generation provider key
15517
+ SIGNOZ_ACCESS_TOKEN: "secret",
15518
+ // OTLP ingest token; read via ExuluOtel's parameter object, invisible to the code scan
15519
+ HF_AUTH_TOKEN: "secret",
15520
+ // HuggingFace token for pyannote diarization; documented as Whisper-container-only, stripped here fail-safe
15521
+ LITELLM_API_KEY: "secret",
15522
+ // supervisor-populated proxy key handed to the bundled LiteLLM UI
15523
+ // --- runtime: paths, locales, feature flags, hostnames, ports, log levels.
15524
+ // Only changes behaviour.
15525
+ PATH: "runtime",
15526
+ HOME: "runtime",
15527
+ LANG: "runtime",
15528
+ TZ: "runtime",
15529
+ TMPDIR: "runtime",
15530
+ NODE_ENV: "runtime",
15531
+ PORT: "runtime",
15532
+ DEBUG: "runtime",
15533
+ BACKEND: "runtime",
15534
+ FRONTEND: "runtime",
15535
+ // Found via `rg process\.env\.[A-Z0-9_]+ src ee` (Step 3 of the task brief):
15536
+ AUTH_MODE: "runtime",
15537
+ // "password" | "otp" mode selector, echoed by GET /config
15538
+ // Platform fallback model for POST /claims/check when the request names no
15539
+ // model and no agent config supplies one. It is a model IDENTIFIER, not a
15540
+ // credential: knowing the string grants access to nothing, because reaching
15541
+ // that model still needs the deployment's own proxy credentials
15542
+ // (LITELLM_MASTER_KEY / EXULU_API_KEY, both classified secret) and passes
15543
+ // through resolveModel's catalog. All it changes is which model a check
15544
+ // runs on — behaviour, which is this class's definition. Same reasoning as
15545
+ // EXULU_ENTITY_EXTRACTION_MODEL, TRANSCRIPTION_MODEL and TTS_MODEL below.
15546
+ CLAIM_CHECK_DEFAULT_MODEL: "runtime",
15547
+ // Request deadline (ms) for POST /claims/check, overriding routes.ts's
15548
+ // 60,000 default. A number of milliseconds is a setting, not a credential —
15549
+ // knowing it grants no access, it only changes how long the handler waits
15550
+ // before cancelling and returning 504. Same reasoning as
15551
+ // CLAIM_CHECK_DEFAULT_MODEL above.
15552
+ CLAIM_CHECK_TIMEOUT_MS: "runtime",
15553
+ DISABLE_SCHEMA_UPDATE: "runtime",
15554
+ // LiteLLM child-process flag
15555
+ EXULU_ENTITY_EXTRACTION_MODEL: "runtime",
15556
+ // Request-rate ceilings for external users, classified exactly as their
15557
+ // guest counterparts below: a number of requests is a setting, not a
15558
+ // credential. Arrived with the external-rate-limit PR, which predates this
15559
+ // inventory and so could not have classified them itself.
15560
+ EXULU_EXTERNAL_RATE_PER_HOUR: "runtime",
15561
+ EXULU_EXTERNAL_RATE_PER_MINUTE: "runtime",
15562
+ EXULU_GUEST_MAX_MESSAGE_CHARS: "runtime",
15563
+ EXULU_GUEST_MAX_TOTAL_CHARS: "runtime",
15564
+ EXULU_GUEST_RATE_PER_HOUR: "runtime",
15565
+ EXULU_GUEST_RATE_PER_MINUTE: "runtime",
15566
+ EXULU_REQUIRE_SANDBOX: "runtime",
15567
+ EXULU_TRUST_PROXY: "runtime",
15568
+ EXULU_USE_LITELLM: "runtime",
15569
+ EXULU_VS_TIMING: "runtime",
15570
+ LITELLM_BASE_URL: "runtime",
15571
+ LITELLM_CONFIG_PATH: "runtime",
15572
+ LITELLM_HOST: "runtime",
15573
+ LITELLM_PORT: "runtime",
15574
+ LITELLM_UI_PATH: "runtime",
15575
+ NEXT_PUBLIC_AGENT_VISUALIZATION: "runtime",
15576
+ POSTGRES_DB_HOST: "runtime",
15577
+ POSTGRES_DB_NAME: "runtime",
15578
+ POSTGRES_DB_PORT: "runtime",
15579
+ POSTGRES_DB_SSL: "runtime",
15580
+ PUBLIC_API_BASE_URL: "runtime",
15581
+ RECALL_REGION: "runtime",
15582
+ RECALL_RECORDING_RETENTION_HOURS: "runtime",
15583
+ RECALL_STORE_VIDEO_LOCALLY: "runtime",
15584
+ REDIS_HOST: "runtime",
15585
+ REDIS_PORT: "runtime",
15586
+ SERVER_ROOT_PATH: "runtime",
15587
+ // OTLP endpoints, not credentials — the token above is the credential. They
15588
+ // are credential-SHAPED (`_URL`), so they need a line here for the
15589
+ // documentation reconciliation test to pass; `runtime` is the honest answer.
15590
+ SIGNOZ_TRACES_URL: "runtime",
15591
+ SIGNOZ_LOGS_URL: "runtime",
15592
+ SMTP_FROM: "runtime",
15593
+ SMTP_HOST: "runtime",
15594
+ SMTP_PORT: "runtime",
15595
+ SMTP_SECURE: "runtime",
15596
+ TOTAL_MAX_RECORDINGS_DURATION_PER_MONTH: "runtime",
15597
+ TRANSCRIPTION_MODEL: "runtime",
15598
+ TRANSCRIPTION_SERVER: "runtime",
15599
+ TTS_MODEL: "runtime",
15600
+ TTS_VOICE: "runtime",
15601
+ WHISPER_HOST: "runtime",
15602
+ WHISPER_PORT: "runtime"
15006
15603
  };
15604
+ var isSecretEnvName = (name) => ENV_CLASSIFICATION[name] === "secret";
15605
+ var SECRET_SHAPED_ENV_NAME = /(SECRET|PASSWORD|TOKEN|_KEY|CREDENTIAL|PRIVATE|_URL|_URI|_DSN|_PASS\b|PWD|APIKEY|LICENSE)/i;
15606
+ var isSecretShapedEnvName = (name) => SECRET_SHAPED_ENV_NAME.test(name);
15607
+ var findUnclassifiedSecretShaped = (env) => Object.keys(env).filter((n) => isSecretShapedEnvName(n) && !(n in ENV_CLASSIFICATION)).sort();
15007
15608
 
15008
- // src/exulu/audit/redact.ts
15009
- var SECRET_KEY_DENYLIST = [
15010
- "oauth",
15011
- "credentials",
15012
- "accesstoken",
15013
- "refreshtoken",
15014
- "password",
15015
- "secret",
15016
- "token",
15017
- "apikey",
15018
- "authorization",
15019
- "nonce"
15020
- ];
15021
- var FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
15022
- "req",
15023
- "model",
15024
- "contexts",
15025
- "upload",
15026
- "memory",
15027
- "exuluConfig",
15028
- "toolVariablesConfig",
15029
- "allExuluTools",
15030
- "currentTools",
15031
- "sessionItems",
15032
- "audit"
15033
- ]);
15034
- var isSecretKey = (key, extra) => {
15035
- const k = key.toLowerCase();
15036
- if (extra.some((e) => k.includes(e.toLowerCase()))) return true;
15037
- return SECRET_KEY_DENYLIST.some((term) => k.includes(term));
15038
- };
15039
- var redact = (value, redactKeys, seen) => {
15040
- if (value === null || typeof value !== "object") return value;
15041
- if (seen.has(value)) return "[circular]";
15042
- seen.add(value);
15043
- if (Array.isArray(value)) return value.map((v) => redact(v, redactKeys, seen));
15044
- const out = {};
15045
- for (const [key, val] of Object.entries(value)) {
15046
- if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
15047
- if (isSecretKey(key, redactKeys)) {
15048
- if (val !== null && typeof val === "object") {
15049
- out[key] = "[redacted]";
15050
- }
15609
+ // ee/invoke-skills/skill-env.ts
15610
+ var POSIX_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
15611
+ var buildSkillEnv = ({
15612
+ processEnv,
15613
+ grantedVariables,
15614
+ overrides = {},
15615
+ extraSecretNames = []
15616
+ }) => {
15617
+ const env = {};
15618
+ const strippedSecretNames = [];
15619
+ const extraSecrets = new Set(extraSecretNames);
15620
+ for (const [name, value] of Object.entries(processEnv)) {
15621
+ if (isSecretEnvName(name) || extraSecrets.has(name)) {
15622
+ strippedSecretNames.push(name);
15051
15623
  continue;
15052
15624
  }
15053
- out[key] = redact(val, redactKeys, seen);
15054
- }
15055
- return out;
15056
- };
15057
- var sanitizeData = (value, opts) => {
15058
- let cleaned;
15059
- try {
15060
- cleaned = redact(value, opts.redactKeys ?? [], /* @__PURE__ */ new WeakSet());
15061
- } catch {
15062
- cleaned = "[unserializable]";
15625
+ env[name] = value;
15063
15626
  }
15064
- let serialized;
15065
- try {
15066
- serialized = JSON.stringify(cleaned) ?? "";
15067
- } catch {
15068
- return { value: "[unserializable]", truncated: false };
15627
+ const baseKeys = new Set(Object.keys(env));
15628
+ const grantedNames = [];
15629
+ const skippedNames = [];
15630
+ for (const [name, value] of Object.entries(grantedVariables)) {
15631
+ if (!POSIX_NAME.test(name) || baseKeys.has(name)) {
15632
+ skippedNames.push(name);
15633
+ continue;
15634
+ }
15635
+ env[name] = value;
15636
+ grantedNames.push(name);
15069
15637
  }
15070
- if (serialized.length <= opts.maxBytes) return { value: cleaned, truncated: false };
15638
+ Object.assign(env, overrides);
15071
15639
  return {
15072
- value: { _truncated: true, preview: serialized.slice(0, opts.maxBytes) },
15073
- truncated: true
15640
+ env,
15641
+ strippedSecretNames: strippedSecretNames.sort(),
15642
+ grantedNames: grantedNames.sort(),
15643
+ skippedNames: skippedNames.sort()
15074
15644
  };
15075
15645
  };
15076
15646
 
15077
- // src/exulu/auth/describe.ts
15078
- var describeCredentialIdentity = async (auth, userId, toolId) => {
15079
- const provider = providerKeyFor(toolId ?? auth.provider, auth);
15080
- const base = {
15081
- provider,
15082
- authType: auth.authType,
15083
- account: String(userId)
15084
- };
15085
- if (auth.authType !== "oauth") return base;
15086
- try {
15087
- const row = await credentialStore.get(provider, userId);
15088
- if (!row || row.authType !== "oauth") return base;
15089
- const { scopes, expiresAt } = row.data;
15090
- return {
15091
- ...base,
15092
- ...scopes ? { scopes: scopes.split(" ").filter(Boolean) } : {},
15093
- ...expiresAt !== void 0 ? { expiresAt } : {}
15094
- };
15095
- } catch (error) {
15096
- console.error(`[EXULU] describeCredentialIdentity failed for provider "${provider}":`, error);
15097
- return base;
15098
- }
15099
- };
15647
+ // ee/invoke-skills/binary-file-guard.ts
15648
+ var BINARY_DOCUMENT_EXTENSIONS = /* @__PURE__ */ new Set([
15649
+ ".pdf",
15650
+ ".doc",
15651
+ ".docx",
15652
+ ".xls",
15653
+ ".xlsx",
15654
+ ".ppt",
15655
+ ".pptx",
15656
+ ".odt",
15657
+ ".ods",
15658
+ ".odp",
15659
+ ".zip",
15660
+ ".gz",
15661
+ ".png",
15662
+ ".jpg",
15663
+ ".jpeg",
15664
+ ".gif",
15665
+ ".bmp",
15666
+ ".tif",
15667
+ ".tiff",
15668
+ ".webp"
15669
+ ]);
15670
+ function isBinaryDocumentPath(path3) {
15671
+ const dot = path3.lastIndexOf(".");
15672
+ if (dot < 0) return false;
15673
+ return BINARY_DOCUMENT_EXTENSIONS.has(path3.slice(dot).toLowerCase());
15674
+ }
15675
+ function looksBinary(content) {
15676
+ return content.slice(0, 8192).includes("\0");
15677
+ }
15678
+ function binaryReadHint(path3) {
15679
+ return `"${path3}" is a binary file \u2014 readFile would return raw bytes that cannot be interpreted and would flood the context. The text of mail attachments is already in the conversation (the <file file name=\u2026> block); for other documents use parse_document to extract the text first, then read within that extracted text.`;
15680
+ }
15100
15681
 
15101
- // src/exulu/audit/emitters/tool-call.ts
15102
- var str = (v) => v === void 0 || v === null ? void 0 : String(v);
15103
- var isAuthShortCircuit = (output) => {
15104
- if (!output || typeof output !== "object") return false;
15105
- const o = output;
15106
- return !!o.credentialRequest || !!o.oauth?.authorizationUrl;
15107
- };
15108
- var buildToolCallEvent = async (ctx, opts) => {
15109
- const nowIso = opts.nowIso ?? (() => (/* @__PURE__ */ new Date()).toISOString());
15110
- const status = ctx.status === "error" ? "error" : isAuthShortCircuit(ctx.output) ? "auth_required" : "ok";
15111
- const input = sanitizeData(ctx.input, { maxBytes: opts.maxBytes, redactKeys: opts.redactKeys });
15112
- const data = { input: input.value };
15113
- const truncated = {};
15114
- if (input.truncated) truncated.input = true;
15115
- if (opts.captureOutput && status !== "auth_required") {
15116
- const output = sanitizeData(ctx.output, { maxBytes: opts.maxBytes, redactKeys: opts.redactKeys });
15117
- data.output = output.value;
15118
- if (output.truncated) truncated.output = true;
15119
- }
15120
- let credential;
15121
- if (ctx.tool.authentication && ctx.user?.id != null) {
15122
- credential = await describeCredentialIdentity(
15123
- ctx.tool.authentication,
15124
- Number(ctx.user.id),
15125
- ctx.tool.id
15126
- );
15682
+ // ee/invoke-skills/variable-grants.ts
15683
+ var selectRowsToDecrypt = (rows) => rows.filter((row) => Boolean(row?.name) && row.allow_skill_access === true);
15684
+ var deriveWithheldNames = (rows, granted) => [
15685
+ ...new Set(
15686
+ rows.filter((row) => Boolean(row?.name)).map((row) => row.name).filter((name) => !(name in granted))
15687
+ )
15688
+ ].sort();
15689
+ var selectGrantedVariables = (rows) => {
15690
+ const out = {};
15691
+ for (const row of rows) {
15692
+ if (!row?.name) continue;
15693
+ if (row.allow_skill_access !== true) continue;
15694
+ if (row.name.startsWith("_")) continue;
15695
+ if (row.name.includes("=")) continue;
15696
+ if (typeof row.value !== "string") continue;
15697
+ out[row.name] = row.value;
15127
15698
  }
15128
- const err3 = ctx.error;
15129
- return {
15130
- v: 1,
15131
- ts: nowIso(),
15132
- type: AUDIT_EVENT_TYPES.TOOL_CALL,
15133
- actor: {
15134
- kind: "user",
15135
- userId: str(ctx.user?.id),
15136
- email: ctx.user?.email,
15137
- roleId: str(ctx.user?.role?.id),
15138
- projectId: ctx.projectId
15139
- },
15140
- context: {
15141
- sessionId: ctx.sessionID,
15142
- agentId: ctx.agent?.id,
15143
- agentName: ctx.agent?.name,
15144
- toolCallId: ctx.toolCallId
15145
- },
15146
- target: { kind: "tool", id: ctx.tool.id, name: ctx.tool.name, category: ctx.tool.category, builtin: ctx.builtin },
15147
- ...ctx.client ? { client: ctx.client } : {},
15148
- ...credential ? { credential } : {},
15149
- status,
15150
- ...status === "error" ? { error: { name: err3?.name, message: String(err3?.message ?? err3 ?? "unknown error") } } : {},
15151
- data,
15152
- durationMs: ctx.durationMs,
15153
- ...Object.keys(truncated).length ? { truncated } : {}
15154
- };
15699
+ return out;
15155
15700
  };
15156
15701
 
15157
- // src/exulu/audit/logger.ts
15158
- var noop = {
15159
- enabled: false,
15160
- failClosed: false,
15161
- isBuiltin: () => false,
15162
- shouldAuditTool: () => false,
15163
- shouldAuditSkillSandbox: () => false,
15164
- record: () => {
15165
- },
15166
- recordToolCall: async () => {
15167
- },
15168
- flush: async () => {
15169
- },
15170
- close: async () => {
15702
+ // src/exulu/litellm/os-environ-names.ts
15703
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
15704
+ var OS_ENVIRON_DIRECTIVE = /os\.environ\/([A-Za-z_][A-Za-z0-9_]*)/g;
15705
+ var parseOsEnvironNames = (yamlText) => {
15706
+ const found = /* @__PURE__ */ new Set();
15707
+ for (const match of yamlText.matchAll(OS_ENVIRON_DIRECTIVE)) {
15708
+ const name = match[1];
15709
+ if (!name) continue;
15710
+ if (ENV_CLASSIFICATION[name] === "runtime") continue;
15711
+ found.add(name);
15171
15712
  }
15713
+ return [...found].sort();
15172
15714
  };
15173
- var RealAuditLogger = class {
15174
- constructor(resolved, builtinToolIds) {
15175
- this.resolved = resolved;
15176
- this.builtinToolIds = builtinToolIds;
15177
- this.failClosed = resolved.failureMode === "closed";
15178
- const writer = createAuditS3Writer(resolved.target);
15179
- this.sink = new AuditSink(resolved, writer, createFsSpoolStore(resolved.spoolDir));
15180
- }
15181
- enabled = true;
15182
- failClosed;
15183
- sink;
15184
- lifecycleWriter() {
15185
- return createAuditS3Writer(this.resolved.target);
15186
- }
15187
- isBuiltin(id) {
15188
- return this.builtinToolIds.has(id);
15189
- }
15190
- shouldAuditTool(id) {
15191
- const t = this.resolved.toolCalls;
15192
- if (!t.enabled) return false;
15193
- if (t.exclude.includes(id)) return false;
15194
- if (t.include.length > 0) return t.include.includes(id);
15195
- return true;
15196
- }
15197
- shouldAuditSkillSandbox() {
15198
- return this.resolved.skillSandbox.enabled;
15199
- }
15200
- record(event) {
15201
- this.sink.record(event);
15202
- }
15203
- async recordToolCall(ctx) {
15204
- const event = await buildToolCallEvent(ctx, {
15205
- maxBytes: this.resolved.payload.maxBytes,
15206
- captureOutput: this.resolved.payload.captureOutput,
15207
- redactKeys: this.resolved.payload.redactKeys
15208
- });
15209
- if (this.failClosed) await this.sink.recordDurable(event);
15210
- else this.sink.record(event);
15211
- }
15212
- flush() {
15213
- return this.sink.flush();
15214
- }
15215
- close() {
15216
- return this.sink.close();
15217
- }
15218
- get resolvedConfig() {
15219
- return this.resolved;
15715
+ var readLiteLLMOsEnvironNames = (configPath = resolveLiteLLMConfigPath()) => {
15716
+ try {
15717
+ if (!existsSync3(configPath)) return [];
15718
+ return parseOsEnvironNames(readFileSync2(configPath, "utf8"));
15719
+ } catch (err3) {
15720
+ console.warn(
15721
+ `[SKILLS] Could not read LiteLLM config at ${configPath} to collect os.environ/ credential names; the skill environment falls back to the static secret inventory.`,
15722
+ err3
15723
+ );
15724
+ return [];
15220
15725
  }
15221
15726
  };
15222
- var _instance;
15223
- var _signalClose;
15224
- var build = (config, builtinToolIds) => {
15225
- const resolved = resolveAuditConfig(config);
15226
- return resolved ? new RealAuditLogger(resolved, builtinToolIds) : noop;
15227
- };
15228
- var getAuditLogger = (config) => {
15229
- if (!_instance) _instance = build(config, /* @__PURE__ */ new Set());
15230
- return _instance;
15727
+
15728
+ // src/exulu/audit/config.ts
15729
+ import os from "os";
15730
+ import path from "path";
15731
+ var normalizePrefix = (p) => {
15732
+ const raw = (p ?? "audit").trim().replace(/^\/+|\/+$/g, "");
15733
+ return `${raw || "audit"}/`;
15231
15734
  };
15232
- var initAudit = async (config, opts) => {
15233
- _instance = build(config, opts?.builtinToolIds ?? /* @__PURE__ */ new Set());
15234
- if (_instance instanceof RealAuditLogger) {
15235
- const r = _instance.resolvedConfig;
15236
- await applyRetentionLifecycle(_instance.lifecycleWriter(), {
15237
- prefix: r.target.s3prefix,
15238
- retentionDays: r.retentionDays,
15239
- manage: r.manageLifecycle
15240
- });
15241
- if (_signalClose) {
15242
- process.off("SIGTERM", _signalClose);
15243
- process.off("SIGINT", _signalClose);
15244
- }
15245
- const close = () => {
15246
- void _instance?.close();
15247
- };
15248
- _signalClose = close;
15249
- process.on("SIGTERM", close);
15250
- process.on("SIGINT", close);
15735
+ var hasAllS3Fields = (t) => !!t && !!t.s3region && !!t.s3key && !!t.s3secret && !!t.s3Bucket;
15736
+ var resolveAuditConfig = (config) => {
15737
+ const a = config.audit;
15738
+ if (!a || a.enabled !== true) return null;
15739
+ const dedicated = hasAllS3Fields(a.s3);
15740
+ const source = dedicated ? a.s3 : config.fileUploads;
15741
+ if (!hasAllS3Fields(source)) {
15742
+ throw new Error(
15743
+ "[EXULU] audit.enabled is true but no S3 target is configured. Set config.audit.s3 or config.fileUploads."
15744
+ );
15251
15745
  }
15252
- return _instance;
15253
- };
15254
-
15255
- // src/exulu/audit/emitters/skill-sandbox.ts
15256
- var str2 = (v) => v === void 0 || v === null ? void 0 : String(v);
15257
- var buildSkillSandboxEvent = (ctx, opts = {}) => {
15258
- const nowIso = opts.nowIso ?? (() => (/* @__PURE__ */ new Date()).toISOString());
15746
+ if (!Number.isInteger(a.retentionDays) || a.retentionDays <= 0) {
15747
+ throw new Error(`[EXULU] audit.retentionDays must be a positive integer, got ${a.retentionDays}.`);
15748
+ }
15749
+ const usingSharedFileUploadsBucket = !dedicated;
15259
15750
  return {
15260
- v: 1,
15261
- ts: nowIso(),
15262
- type: AUDIT_EVENT_TYPES.SKILL_SANDBOX_CREATED,
15263
- actor: {
15264
- kind: "agent",
15265
- userId: str2(ctx.user?.id),
15266
- email: ctx.user?.email,
15267
- roleId: str2(ctx.user?.role?.id),
15268
- projectId: ctx.projectId
15751
+ target: {
15752
+ s3region: source.s3region,
15753
+ s3key: source.s3key,
15754
+ s3secret: source.s3secret,
15755
+ s3Bucket: source.s3Bucket,
15756
+ s3prefix: normalizePrefix(source.s3prefix),
15757
+ ...source.s3endpoint ? { s3endpoint: source.s3endpoint } : {}
15269
15758
  },
15270
- context: {
15271
- sessionId: ctx.sessionID,
15272
- agentId: ctx.agent?.id,
15273
- agentName: ctx.agent?.name
15759
+ retentionDays: a.retentionDays,
15760
+ manageLifecycle: a.manageLifecycle ?? !usingSharedFileUploadsBucket,
15761
+ usingSharedFileUploadsBucket,
15762
+ spoolDir: a.spoolDir ?? path.join(os.tmpdir(), "exulu-audit-spool"),
15763
+ flush: {
15764
+ maxRecords: a.flush?.maxRecords ?? 100,
15765
+ maxIntervalMs: a.flush?.maxIntervalMs ?? 5e3
15274
15766
  },
15275
- target: { kind: "skill_sandbox", id: ctx.sessionID },
15276
- status: "ok",
15277
- data: {
15278
- skills: ctx.skills.map((s) => ({ id: s.id, name: s.name, version: s.version })),
15279
- grantedVariableNames: ctx.grantedNames,
15280
- withheldVariableNames: ctx.withheldNames,
15281
- skippedVariableNames: ctx.skippedNames,
15282
- strippedSecretCount: ctx.strippedSecretCount,
15283
- degradedSandbox: ctx.degradedSandbox
15767
+ payload: {
15768
+ maxBytes: a.payload?.maxBytes ?? 32768,
15769
+ captureOutput: a.payload?.captureOutput ?? true,
15770
+ redactKeys: a.payload?.redactKeys ?? []
15284
15771
  },
15285
- client: ctx.client
15772
+ failureMode: a.failureMode ?? "open",
15773
+ toolCalls: {
15774
+ enabled: a.sources?.toolCalls?.enabled ?? true,
15775
+ include: a.sources?.toolCalls?.include ?? [],
15776
+ exclude: a.sources?.toolCalls?.exclude ?? []
15777
+ },
15778
+ skillSandbox: {
15779
+ enabled: a.sources?.skillSandbox?.enabled ?? false
15780
+ }
15781
+ };
15782
+ };
15783
+
15784
+ // src/exulu/audit/s3-writer.ts
15785
+ import {
15786
+ S3Client as S3Client2,
15787
+ PutObjectCommand as PutObjectCommand2,
15788
+ GetBucketLifecycleConfigurationCommand,
15789
+ PutBucketLifecycleConfigurationCommand
15790
+ } from "@aws-sdk/client-s3";
15791
+ var RETRYABLE = /* @__PURE__ */ new Set(["SignatureDoesNotMatch", "InvalidAccessKeyId", "AccessDenied"]);
15792
+ var buildAuditS3Client = (t) => new S3Client2({
15793
+ region: t.s3region,
15794
+ ...t.s3endpoint ? { forcePathStyle: true, endpoint: t.s3endpoint } : {},
15795
+ credentials: { accessKeyId: t.s3key, secretAccessKey: t.s3secret },
15796
+ requestChecksumCalculation: "WHEN_REQUIRED",
15797
+ responseChecksumValidation: "WHEN_REQUIRED"
15798
+ });
15799
+ var createAuditS3Writer = (target, client, opts) => {
15800
+ const c = client ?? buildAuditS3Client(target);
15801
+ const maxRetries = opts?.maxRetries ?? 3;
15802
+ const backoffMs = opts?.backoffMs ?? ((attempt) => Math.pow(2, attempt) * 1e3);
15803
+ const putNdjson = async (key, body) => {
15804
+ let lastError = null;
15805
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
15806
+ const command = new PutObjectCommand2({
15807
+ Bucket: target.s3Bucket,
15808
+ Key: key,
15809
+ Body: Buffer.from(body, "utf8"),
15810
+ ContentType: "application/x-ndjson"
15811
+ });
15812
+ try {
15813
+ await c.send(command);
15814
+ return;
15815
+ } catch (error) {
15816
+ lastError = error;
15817
+ if (RETRYABLE.has(error?.name) && attempt < maxRetries) {
15818
+ await new Promise((r) => setTimeout(r, backoffMs(attempt)));
15819
+ continue;
15820
+ }
15821
+ throw error;
15822
+ }
15823
+ }
15824
+ if (lastError) throw lastError;
15825
+ };
15826
+ const getLifecycle = async () => c.send(new GetBucketLifecycleConfigurationCommand({ Bucket: target.s3Bucket }));
15827
+ const putLifecycle = async (config) => {
15828
+ await c.send(
15829
+ new PutBucketLifecycleConfigurationCommand({
15830
+ Bucket: target.s3Bucket,
15831
+ LifecycleConfiguration: config
15832
+ })
15833
+ );
15286
15834
  };
15835
+ return { putNdjson, getLifecycle, putLifecycle };
15287
15836
  };
15288
15837
 
15289
- // ee/invoke-skills/create-sandbox.ts
15290
- import { createBashTool } from "bash-tool";
15291
- import { tool as tool2 } from "ai";
15292
- import { z as z17 } from "zod";
15293
- import CryptoJS3 from "crypto-js";
15294
-
15295
- // ee/invoke-skills/project-sync.ts
15296
- import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "fs/promises";
15297
- import { randomBytes as randomBytes2 } from "crypto";
15298
- import { basename, dirname, join as join2, resolve as resolve2, sep } from "path";
15299
- import { execFile } from "child_process";
15300
- import { promisify as promisify2 } from "util";
15301
- function planProjectSync(remote, local) {
15302
- const localSizes = new Map(local.map((e) => [e.name, e.size]));
15303
- const remoteNames = new Set(remote.map((e) => e.name));
15304
- return {
15305
- download: remote.filter((e) => localSizes.get(e.name) !== e.size).map((e) => e.name),
15306
- remove: local.filter((e) => !remoteNames.has(e.name)).map((e) => e.name)
15307
- };
15308
- }
15309
- function projectSyncMarkerPath(sessionDir) {
15310
- return join2(dirname(sessionDir), ".project-sync", basename(sessionDir));
15311
- }
15312
- async function readMarker(sessionDir) {
15313
- try {
15314
- return (await readFile(projectSyncMarkerPath(sessionDir), "utf8")).trim() || null;
15315
- } catch {
15316
- return null;
15317
- }
15318
- }
15319
- async function clearProjectSyncMarker(sessionDir) {
15320
- await rm(projectSyncMarkerPath(sessionDir), { force: true });
15321
- }
15322
- var isFlatName = (name) => !!name && !name.includes("/") && !name.includes("\\") && name !== "." && name !== "..";
15323
- var HELPER_KINDS = [".project-staging", ".project-trash"];
15324
- var helperRoot = (sessionDir, kind) => join2(dirname(sessionDir), kind);
15325
- var helperPath = (sessionDir, kind) => join2(helperRoot(sessionDir, kind), `${basename(sessionDir)}-${randomBytes2(8).toString("hex")}`);
15326
- var execFileAsync = promisify2(execFile);
15327
- async function removeTreeSafely(path3, sessionDir) {
15328
- const target = resolve2(path3);
15329
- const inside = HELPER_KINDS.some((kind) => {
15330
- const root = resolve2(helperRoot(sessionDir, kind));
15331
- return target.startsWith(root + sep) && !target.slice(root.length + 1).includes(sep);
15332
- });
15333
- if (!inside) {
15334
- console.error(`[SKILLS] Refusing to remove ${path3}: not a project staging or trash directory.`);
15335
- return false;
15838
+ // src/exulu/audit/lifecycle.ts
15839
+ var AUDIT_LIFECYCLE_RULE_ID = "exulu-audit-retention";
15840
+ var buildRule = (prefix, retentionDays) => ({
15841
+ ID: AUDIT_LIFECYCLE_RULE_ID,
15842
+ Filter: { Prefix: prefix },
15843
+ Status: "Enabled",
15844
+ Expiration: { Days: retentionDays }
15845
+ });
15846
+ var applyRetentionLifecycle = async (writer, opts) => {
15847
+ const rule = buildRule(opts.prefix, opts.retentionDays);
15848
+ const config = { Rules: [rule] };
15849
+ if (!opts.manage) {
15850
+ console.warn(
15851
+ `[EXULU] audit retention: not managing the S3 lifecycle for this bucket. Apply this rule manually:
15852
+ ${JSON.stringify(config, null, 2)}`
15853
+ );
15854
+ return;
15336
15855
  }
15337
15856
  try {
15338
- await execFileAsync("rm", ["-rf", "--", target]);
15339
- return true;
15340
- } catch (err3) {
15341
- console.error(`[SKILLS] Failed to remove ${target}; leaving it for a later sweep.`, err3);
15342
- return false;
15857
+ let existing = [];
15858
+ try {
15859
+ const current = await writer.getLifecycle();
15860
+ existing = (current?.Rules ?? []).filter((r) => r.ID !== AUDIT_LIFECYCLE_RULE_ID);
15861
+ } catch (error) {
15862
+ if (error?.name !== "NoSuchLifecycleConfiguration") throw error;
15863
+ }
15864
+ await writer.putLifecycle({ Rules: [...existing, rule] });
15865
+ console.log(`[EXULU] audit retention: S3 lifecycle set to expire "${opts.prefix}" after ${opts.retentionDays} days.`);
15866
+ } catch (error) {
15867
+ console.warn(
15868
+ `[EXULU] audit retention: could not set the S3 lifecycle (${error?.name ?? "error"}). Apply this rule manually:
15869
+ ${JSON.stringify(config, null, 2)}`
15870
+ );
15343
15871
  }
15344
- }
15345
- var DAY_MS = 24 * 60 * 60 * 1e3;
15346
- async function sweepStaleHelpers(sessionDir) {
15347
- const prefix = `${basename(sessionDir)}-`;
15348
- for (const kind of HELPER_KINDS) {
15349
- const root = helperRoot(sessionDir, kind);
15350
- let names;
15872
+ };
15873
+
15874
+ // src/exulu/audit/sink.ts
15875
+ import { randomUUID as randomUUID7 } from "crypto";
15876
+ import { promises as fs } from "fs";
15877
+ import path2 from "path";
15878
+ var createFsSpoolStore = (dir) => ({
15879
+ write: async (name, body) => {
15880
+ await fs.mkdir(dir, { recursive: true });
15881
+ await fs.writeFile(path2.join(dir, name), body, "utf8");
15882
+ },
15883
+ list: async () => {
15351
15884
  try {
15352
- names = await readdir(root);
15885
+ return (await fs.readdir(dir)).filter((f) => f.endsWith(".ndjson"));
15353
15886
  } catch {
15354
- continue;
15355
- }
15356
- for (const name of names) {
15357
- if (!name.startsWith(prefix)) continue;
15358
- const st = await lstat(join2(root, name)).catch(() => null);
15359
- if (st && Date.now() - st.mtimeMs > DAY_MS) await removeTreeSafely(join2(root, name), sessionDir);
15887
+ return [];
15360
15888
  }
15889
+ },
15890
+ read: async (name) => fs.readFile(path2.join(dir, name), "utf8"),
15891
+ remove: async (name) => {
15892
+ await fs.rm(path2.join(dir, name), { force: true });
15361
15893
  }
15362
- }
15363
- var errCode = (err3) => err3?.code;
15364
- async function moveAway(dir, sessionDir) {
15365
- const trash = helperPath(sessionDir, ".project-trash");
15366
- await mkdir(dirname(trash), { recursive: true });
15367
- try {
15368
- await rename(dir, trash);
15369
- return trash;
15370
- } catch (err3) {
15371
- if (errCode(err3) === "ENOENT") return null;
15372
- throw err3;
15894
+ });
15895
+ var pad = (n) => String(n).padStart(2, "0");
15896
+ var AuditSink = class {
15897
+ constructor(cfg, writer, spool, opts) {
15898
+ this.cfg = cfg;
15899
+ this.writer = writer;
15900
+ this.spool = spool;
15901
+ this.now = opts?.now ?? (() => /* @__PURE__ */ new Date());
15373
15902
  }
15374
- }
15375
- async function discard(path3, sessionDir) {
15376
- if (path3) await removeTreeSafely(path3, sessionDir);
15377
- }
15378
- async function discardEntry(path3, sessionDir) {
15379
- await discard(await moveAway(path3, sessionDir), sessionDir);
15380
- }
15381
- async function syncProjectDir(args) {
15382
- const { sessionDir, projectId, config } = args;
15383
- const dir = join2(sessionDir, PROJECT_DIR);
15384
- const previous = await readMarker(sessionDir);
15385
- if (!projectId) {
15386
- if (previous !== null) {
15387
- await discard(await moveAway(dir, sessionDir), sessionDir);
15388
- await clearProjectSyncMarker(sessionDir);
15389
- }
15390
- return;
15903
+ buffer = [];
15904
+ timer = null;
15905
+ now;
15906
+ objectKey() {
15907
+ const d = this.now();
15908
+ const dt = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
15909
+ return `${this.cfg.target.s3prefix}dt=${dt}/${pad(d.getUTCHours())}/${d.getTime()}-${randomUUID7()}.ndjson`;
15391
15910
  }
15392
- if (!config.fileUploads) {
15393
- console.warn(`[SKILLS] File uploads are not configured; project files are not synced into ${sessionDir}.`);
15394
- return;
15911
+ serialize(events) {
15912
+ return events.map((e) => JSON.stringify(e)).join("\n") + "\n";
15395
15913
  }
15396
- const { projectPrefix } = projectFilePrefix(projectId);
15397
- const remote = /* @__PURE__ */ new Map();
15398
- try {
15399
- for (const obj of await listS3ObjectsByPrefix(projectPrefix, config)) {
15400
- const idx = obj.key.indexOf(projectPrefix);
15401
- const name = idx >= 0 ? obj.key.slice(idx + projectPrefix.length) : "";
15402
- if (!isFlatName(name)) continue;
15403
- remote.set(name, { size: obj.size, key: obj.key });
15914
+ record(event) {
15915
+ this.buffer.push(event);
15916
+ if (this.buffer.length >= this.cfg.flush.maxRecords) {
15917
+ void this.flush();
15918
+ } else if (!this.timer) {
15919
+ this.timer = setTimeout(() => void this.flush(), this.cfg.flush.maxIntervalMs);
15920
+ this.timer.unref?.();
15404
15921
  }
15405
- } catch (err3) {
15406
- console.error(`[SKILLS] Failed to list project files for project ${projectId}; keeping the local copy.`, err3);
15407
- return;
15408
15922
  }
15409
- await sweepStaleHelpers(sessionDir);
15410
- await mkdir(dirname(projectSyncMarkerPath(sessionDir)), { recursive: true });
15411
- await writeFile(projectSyncMarkerPath(sessionDir), projectId);
15412
- const trashes = [];
15413
- const staging = helperPath(sessionDir, ".project-staging");
15414
- let installed = false;
15415
- try {
15416
- const old = await moveAway(dir, sessionDir);
15417
- trashes.push(old);
15418
- await mkdir(dirname(staging), { recursive: true });
15419
- await mkdir(staging);
15420
- const local = [];
15421
- const oldStat = old && previous === projectId ? await lstat(old).catch(() => null) : null;
15422
- if (old && oldStat?.isDirectory()) {
15423
- for (const name of await readdir(old)) {
15424
- const st = await lstat(join2(old, name)).catch(() => null);
15425
- if (!st?.isFile() || remote.get(name)?.size !== st.size) continue;
15426
- await rename(join2(old, name), join2(staging, name));
15427
- const moved = await lstat(join2(staging, name)).catch(() => null);
15428
- if (!moved?.isFile()) {
15429
- await rename(join2(staging, name), join2(old, `.rejected-${randomBytes2(4).toString("hex")}`)).catch(() => {
15430
- });
15431
- continue;
15432
- }
15433
- local.push({ name, size: moved.size });
15923
+ async flush() {
15924
+ if (this.timer) {
15925
+ clearTimeout(this.timer);
15926
+ this.timer = null;
15927
+ }
15928
+ if (this.buffer.length === 0) return;
15929
+ const batch = this.buffer;
15930
+ this.buffer = [];
15931
+ const body = this.serialize(batch);
15932
+ try {
15933
+ await this.writer.putNdjson(this.objectKey(), body);
15934
+ await this.drainSpool();
15935
+ } catch (error) {
15936
+ const name = `${Date.now()}-${randomUUID7()}.ndjson`;
15937
+ try {
15938
+ await this.spool.write(name, body);
15939
+ console.warn(`[EXULU] audit: S3 write failed, spooled ${batch.length} record(s) to disk (${name}).`, error);
15940
+ } catch (spoolError) {
15941
+ console.error(`[EXULU] audit: S3 write AND local spool failed \u2014 ${batch.length} record(s) lost.`, spoolError);
15434
15942
  }
15435
15943
  }
15436
- const plan = planProjectSync(
15437
- [...remote].map(([name, r]) => ({ name, size: r.size })),
15438
- local
15439
- );
15440
- for (const name of plan.download) {
15944
+ }
15945
+ async drainSpool() {
15946
+ const names = await this.spool.list();
15947
+ for (const name of names) {
15441
15948
  try {
15442
- const bytes = await getS3ObjectBytes(remote.get(name).key, config);
15443
- await writeFile(join2(staging, name), bytes, { flag: "wx" });
15444
- } catch (err3) {
15445
- console.error(`[SKILLS] Failed to sync project file ${name} (project ${projectId}); continuing.`, err3);
15949
+ const body = await this.spool.read(name);
15950
+ await this.writer.putNdjson(this.objectKey(), body);
15951
+ await this.spool.remove(name);
15952
+ } catch {
15953
+ return;
15446
15954
  }
15447
15955
  }
15448
- for (let attempt = 0; attempt < 2 && !installed; attempt++) {
15449
- try {
15450
- await rename(staging, dir);
15451
- installed = true;
15452
- } catch (err3) {
15453
- const code = errCode(err3);
15454
- if (attempt === 0 && (code === "EEXIST" || code === "ENOTEMPTY" || code === "ENOTDIR" || code === "EISDIR")) {
15455
- trashes.push(await moveAway(dir, sessionDir));
15456
- continue;
15457
- }
15458
- console.error(`[SKILLS] Could not install the project folder for session ${sessionDir}; skipping this turn.`, err3);
15459
- break;
15956
+ }
15957
+ async recordDurable(event) {
15958
+ await this.writer.putNdjson(this.objectKey(), this.serialize([event]));
15959
+ }
15960
+ async close() {
15961
+ await this.flush();
15962
+ }
15963
+ };
15964
+
15965
+ // src/exulu/audit/event.ts
15966
+ var AUDIT_EVENT_TYPES = {
15967
+ TOOL_CALL: "tool.call",
15968
+ SKILL_SANDBOX_CREATED: "skill.sandbox.created"
15969
+ };
15970
+
15971
+ // src/exulu/audit/redact.ts
15972
+ var SECRET_KEY_DENYLIST = [
15973
+ "oauth",
15974
+ "credentials",
15975
+ "accesstoken",
15976
+ "refreshtoken",
15977
+ "password",
15978
+ "secret",
15979
+ "token",
15980
+ "apikey",
15981
+ "authorization",
15982
+ "nonce"
15983
+ ];
15984
+ var FRAMEWORK_INTERNAL_KEYS = /* @__PURE__ */ new Set([
15985
+ "req",
15986
+ "model",
15987
+ "contexts",
15988
+ "upload",
15989
+ "memory",
15990
+ "exuluConfig",
15991
+ "toolVariablesConfig",
15992
+ "allExuluTools",
15993
+ "currentTools",
15994
+ "sessionItems",
15995
+ "audit"
15996
+ ]);
15997
+ var isSecretKey = (key, extra) => {
15998
+ const k = key.toLowerCase();
15999
+ if (extra.some((e) => k.includes(e.toLowerCase()))) return true;
16000
+ return SECRET_KEY_DENYLIST.some((term) => k.includes(term));
16001
+ };
16002
+ var redact = (value, redactKeys, seen) => {
16003
+ if (value === null || typeof value !== "object") return value;
16004
+ if (seen.has(value)) return "[circular]";
16005
+ seen.add(value);
16006
+ if (Array.isArray(value)) return value.map((v) => redact(v, redactKeys, seen));
16007
+ const out = {};
16008
+ for (const [key, val] of Object.entries(value)) {
16009
+ if (FRAMEWORK_INTERNAL_KEYS.has(key)) continue;
16010
+ if (isSecretKey(key, redactKeys)) {
16011
+ if (val !== null && typeof val === "object") {
16012
+ out[key] = "[redacted]";
15460
16013
  }
16014
+ continue;
15461
16015
  }
15462
- } catch (err3) {
15463
- console.error(`[SKILLS] Project sync failed for project ${projectId}; continuing.`, err3);
15464
- } finally {
15465
- if (!installed) await discard(staging, sessionDir);
15466
- for (const t of trashes) await discard(t, sessionDir);
16016
+ out[key] = redact(val, redactKeys, seen);
15467
16017
  }
15468
- }
15469
- async function resolveSandboxProjectId(args, deps) {
15470
- const { projectId, ownerId } = args;
15471
- if (!projectId || ownerId == null) return null;
16018
+ return out;
16019
+ };
16020
+ var sanitizeData = (value, opts) => {
16021
+ let cleaned;
15472
16022
  try {
15473
- const project = await deps.getProject(projectId);
15474
- if (!project) return null;
15475
- const owner = args.owner && String(args.owner.id) === String(ownerId) ? args.owner : await deps.getUser(ownerId);
15476
- if (!owner) return null;
15477
- const rbac = await deps.getRbac(project);
15478
- const allowed = hasProjectAccess({ project, rbac, user: owner, want: "read" });
15479
- return allowed ? String(project.id) : null;
15480
- } catch (err3) {
15481
- console.error(`[SKILLS] Failed to resolve project ${projectId} for the session sandbox; continuing without project files.`, err3);
15482
- return null;
16023
+ cleaned = redact(value, opts.redactKeys ?? [], /* @__PURE__ */ new WeakSet());
16024
+ } catch {
16025
+ cleaned = "[unserializable]";
15483
16026
  }
15484
- }
15485
-
15486
- // ee/invoke-skills/safe-fs.ts
15487
- import { constants } from "fs";
15488
- import { lstat as lstat2, mkdir as mkdir2, open, readlink, realpath, rename as rename2, unlink, writeFile as writeFile2 } from "fs/promises";
15489
- import { randomBytes as randomBytes3 } from "crypto";
15490
- import { dirname as dirname2, isAbsolute, join as join3, sep as sep2 } from "path";
15491
- var UnsafeSessionPathError = class extends Error {
15492
- constructor(message) {
15493
- super(message);
15494
- this.name = "UnsafeSessionPathError";
16027
+ let serialized;
16028
+ try {
16029
+ serialized = JSON.stringify(cleaned) ?? "";
16030
+ } catch {
16031
+ return { value: "[unserializable]", truncated: false };
15495
16032
  }
16033
+ if (serialized.length <= opts.maxBytes) return { value: cleaned, truncated: false };
16034
+ return {
16035
+ value: { _truncated: true, preview: serialized.slice(0, opts.maxBytes) },
16036
+ truncated: true
16037
+ };
15496
16038
  };
15497
- var errCode2 = (err3) => err3?.code;
15498
- var isInside = (root, path3) => path3 === root || path3.startsWith(root + sep2);
15499
- async function readRegularFileInside(sessionDir, path3) {
15500
- const skip = (why) => {
15501
- console.warn(`[SKILLS] Not reading ${path3} back from the sandbox: ${why}.`);
15502
- return null;
16039
+
16040
+ // src/exulu/auth/describe.ts
16041
+ var describeCredentialIdentity = async (auth, userId, toolId) => {
16042
+ const provider = providerKeyFor(toolId ?? auth.provider, auth);
16043
+ const base = {
16044
+ provider,
16045
+ authType: auth.authType,
16046
+ account: String(userId)
15503
16047
  };
15504
- let root;
15505
- let parent;
16048
+ if (auth.authType !== "oauth") return base;
15506
16049
  try {
15507
- root = await realpath(sessionDir);
15508
- parent = await realpath(dirname2(path3));
15509
- } catch {
15510
- return skip("path does not resolve");
16050
+ const row = await credentialStore.get(provider, userId);
16051
+ if (!row || row.authType !== "oauth") return base;
16052
+ const { scopes, expiresAt } = row.data;
16053
+ return {
16054
+ ...base,
16055
+ ...scopes ? { scopes: scopes.split(" ").filter(Boolean) } : {},
16056
+ ...expiresAt !== void 0 ? { expiresAt } : {}
16057
+ };
16058
+ } catch (error) {
16059
+ console.error(`[EXULU] describeCredentialIdentity failed for provider "${provider}":`, error);
16060
+ return base;
15511
16061
  }
15512
- if (!isInside(root, parent)) return skip("it resolves outside the session directory");
15513
- let handle;
15514
- try {
15515
- handle = await open(
15516
- path3,
15517
- constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK | constants.O_NOCTTY
16062
+ };
16063
+
16064
+ // src/exulu/audit/emitters/tool-call.ts
16065
+ var str = (v) => v === void 0 || v === null ? void 0 : String(v);
16066
+ var isAuthShortCircuit = (output) => {
16067
+ if (!output || typeof output !== "object") return false;
16068
+ const o = output;
16069
+ return !!o.credentialRequest || !!o.oauth?.authorizationUrl;
16070
+ };
16071
+ var buildToolCallEvent = async (ctx, opts) => {
16072
+ const nowIso = opts.nowIso ?? (() => (/* @__PURE__ */ new Date()).toISOString());
16073
+ const status = ctx.status === "error" ? "error" : isAuthShortCircuit(ctx.output) ? "auth_required" : "ok";
16074
+ const input = sanitizeData(ctx.input, { maxBytes: opts.maxBytes, redactKeys: opts.redactKeys });
16075
+ const data = { input: input.value };
16076
+ const truncated = {};
16077
+ if (input.truncated) truncated.input = true;
16078
+ if (opts.captureOutput && status !== "auth_required") {
16079
+ const output = sanitizeData(ctx.output, { maxBytes: opts.maxBytes, redactKeys: opts.redactKeys });
16080
+ data.output = output.value;
16081
+ if (output.truncated) truncated.output = true;
16082
+ }
16083
+ let credential;
16084
+ if (ctx.tool.authentication && ctx.user?.id != null) {
16085
+ credential = await describeCredentialIdentity(
16086
+ ctx.tool.authentication,
16087
+ Number(ctx.user.id),
16088
+ ctx.tool.id
15518
16089
  );
15519
- } catch (err3) {
15520
- return skip(errCode2(err3) === "ELOOP" ? "it is a symbolic link" : `open failed (${errCode2(err3) ?? "unknown"})`);
15521
16090
  }
15522
- try {
15523
- const st = await handle.stat();
15524
- if (!st.isFile()) return skip("it is not a regular file");
15525
- if (st.size > MAX_ADOPT_UPLOAD_BYTES) {
15526
- return skip(`it is larger than the ${MAX_ADOPT_UPLOAD_BYTES / (1024 * 1024)}MB upload limit (${st.size} bytes)`);
15527
- }
15528
- const fdPath = await readlink(`/proc/self/fd/${handle.fd}`).catch(() => null);
15529
- if (fdPath !== null) {
15530
- if (!isInside(root, fdPath)) return skip("it resolves outside the session directory");
15531
- } else {
15532
- const again = await realpath(dirname2(path3)).catch(() => null);
15533
- if (again === null || !isInside(root, again)) return skip("it resolves outside the session directory");
15534
- }
15535
- const chunks = [];
15536
- let total = 0;
15537
- const chunkSize = Math.min(Math.max(st.size + 1, 64 * 1024), 1024 * 1024);
15538
- for (; ; ) {
15539
- const chunk = Buffer.allocUnsafe(chunkSize);
15540
- const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
15541
- if (bytesRead === 0) break;
15542
- total += bytesRead;
15543
- if (total > MAX_ADOPT_UPLOAD_BYTES) return skip("it grew past the upload limit while being read");
15544
- chunks.push(chunk.subarray(0, bytesRead));
15545
- }
15546
- return Buffer.concat(chunks, total);
15547
- } finally {
15548
- await handle.close().catch(() => {
15549
- });
16091
+ const err3 = ctx.error;
16092
+ return {
16093
+ v: 1,
16094
+ ts: nowIso(),
16095
+ type: AUDIT_EVENT_TYPES.TOOL_CALL,
16096
+ actor: {
16097
+ kind: "user",
16098
+ userId: str(ctx.user?.id),
16099
+ email: ctx.user?.email,
16100
+ roleId: str(ctx.user?.role?.id),
16101
+ projectId: ctx.projectId
16102
+ },
16103
+ context: {
16104
+ sessionId: ctx.sessionID,
16105
+ agentId: ctx.agent?.id,
16106
+ agentName: ctx.agent?.name,
16107
+ toolCallId: ctx.toolCallId
16108
+ },
16109
+ target: { kind: "tool", id: ctx.tool.id, name: ctx.tool.name, category: ctx.tool.category, builtin: ctx.builtin },
16110
+ ...ctx.client ? { client: ctx.client } : {},
16111
+ ...credential ? { credential } : {},
16112
+ status,
16113
+ ...status === "error" ? { error: { name: err3?.name, message: String(err3?.message ?? err3 ?? "unknown error") } } : {},
16114
+ data,
16115
+ durationMs: ctx.durationMs,
16116
+ ...Object.keys(truncated).length ? { truncated } : {}
16117
+ };
16118
+ };
16119
+
16120
+ // src/exulu/audit/logger.ts
16121
+ var noop = {
16122
+ enabled: false,
16123
+ failClosed: false,
16124
+ isBuiltin: () => false,
16125
+ shouldAuditTool: () => false,
16126
+ shouldAuditSkillSandbox: () => false,
16127
+ record: () => {
16128
+ },
16129
+ recordToolCall: async () => {
16130
+ },
16131
+ flush: async () => {
16132
+ },
16133
+ close: async () => {
16134
+ }
16135
+ };
16136
+ var RealAuditLogger = class {
16137
+ constructor(resolved, builtinToolIds) {
16138
+ this.resolved = resolved;
16139
+ this.builtinToolIds = builtinToolIds;
16140
+ this.failClosed = resolved.failureMode === "closed";
16141
+ const writer = createAuditS3Writer(resolved.target);
16142
+ this.sink = new AuditSink(resolved, writer, createFsSpoolStore(resolved.spoolDir));
15550
16143
  }
15551
- }
15552
- function safeSegments(relativePath) {
15553
- if (!relativePath || isAbsolute(relativePath) || relativePath.includes("\\")) {
15554
- throw new UnsafeSessionPathError(`Refusing path "${relativePath}": not a plain relative path.`);
16144
+ enabled = true;
16145
+ failClosed;
16146
+ sink;
16147
+ lifecycleWriter() {
16148
+ return createAuditS3Writer(this.resolved.target);
15555
16149
  }
15556
- const segments = relativePath.split("/").filter((s) => s !== "" && s !== ".");
15557
- if (segments.length === 0 || segments.includes("..")) {
15558
- throw new UnsafeSessionPathError(`Refusing path "${relativePath}": it contains a ".." segment or no file name.`);
16150
+ isBuiltin(id) {
16151
+ return this.builtinToolIds.has(id);
15559
16152
  }
15560
- return segments;
15561
- }
15562
- async function ensureDirInside(sessionDir, segments) {
15563
- const root = await realpath(sessionDir);
15564
- let current = sessionDir;
15565
- for (const segment of segments) {
15566
- current = join3(current, segment);
15567
- let st = await lstat2(current).catch((err3) => errCode2(err3) === "ENOENT" ? null : Promise.reject(err3));
15568
- if (!st) {
15569
- try {
15570
- await mkdir2(current);
15571
- } catch (err3) {
15572
- if (errCode2(err3) !== "EEXIST") throw err3;
15573
- }
15574
- st = await lstat2(current);
15575
- }
15576
- if (!st.isDirectory()) {
15577
- throw new UnsafeSessionPathError(`Refusing to write under ${current}: it is not a real directory.`);
15578
- }
16153
+ shouldAuditTool(id) {
16154
+ const t = this.resolved.toolCalls;
16155
+ if (!t.enabled) return false;
16156
+ if (t.exclude.includes(id)) return false;
16157
+ if (t.include.length > 0) return t.include.includes(id);
16158
+ return true;
15579
16159
  }
15580
- const real = await realpath(current);
15581
- if (!isInside(root, real)) {
15582
- throw new UnsafeSessionPathError(`Refusing to write under ${current}: it resolves outside the session directory.`);
16160
+ shouldAuditSkillSandbox() {
16161
+ return this.resolved.skillSandbox.enabled;
15583
16162
  }
15584
- return current;
15585
- }
15586
- async function writeFileInside(sessionDir, relativePath, bytes) {
15587
- const segments = safeSegments(relativePath);
15588
- const name = segments[segments.length - 1];
15589
- const parent = await ensureDirInside(sessionDir, segments.slice(0, -1));
15590
- const destination = join3(parent, name);
15591
- const temp = join3(parent, `.exulu-write-${randomBytes3(8).toString("hex")}`);
15592
- await writeFile2(temp, bytes, { flag: "wx" });
15593
- try {
15594
- await rename2(temp, destination);
15595
- } catch (err3) {
15596
- await unlink(temp).catch(() => {
16163
+ record(event) {
16164
+ this.sink.record(event);
16165
+ }
16166
+ async recordToolCall(ctx) {
16167
+ const event = await buildToolCallEvent(ctx, {
16168
+ maxBytes: this.resolved.payload.maxBytes,
16169
+ captureOutput: this.resolved.payload.captureOutput,
16170
+ redactKeys: this.resolved.payload.redactKeys
15597
16171
  });
15598
- throw err3;
16172
+ if (this.failClosed) await this.sink.recordDurable(event);
16173
+ else this.sink.record(event);
15599
16174
  }
15600
- return destination;
15601
- }
15602
- async function ensureRealDirectory(sessionDir, relativeDir) {
15603
- const segments = safeSegments(relativeDir);
15604
- let current = sessionDir;
15605
- for (const segment of segments) {
15606
- current = join3(current, segment);
15607
- const st = await lstat2(current).catch(() => null);
15608
- if (st && !st.isDirectory()) {
15609
- console.warn(`[SKILLS] ${current} is not a real directory; replacing it.`);
15610
- await unlink(current);
15611
- }
16175
+ flush() {
16176
+ return this.sink.flush();
15612
16177
  }
15613
- return ensureDirInside(sessionDir, segments);
15614
- }
15615
- async function removeEntryInside(sessionDir, relativePath) {
15616
- const segments = safeSegments(relativePath);
15617
- const target = join3(sessionDir, ...segments);
15618
- const root = await realpath(sessionDir);
15619
- const parentReal = await realpath(dirname2(target)).catch(() => null);
15620
- if (parentReal === null) return;
15621
- if (!isInside(root, parentReal)) {
15622
- throw new UnsafeSessionPathError(`Refusing to remove ${target}: its parent resolves outside the session directory.`);
16178
+ close() {
16179
+ return this.sink.close();
15623
16180
  }
15624
- const st = await lstat2(target).catch(() => null);
15625
- if (!st) return;
15626
- if (!st.isDirectory()) {
15627
- await unlink(target);
15628
- return;
16181
+ get resolvedConfig() {
16182
+ return this.resolved;
15629
16183
  }
15630
- await discardEntry(target, sessionDir);
15631
- }
16184
+ };
16185
+ var _instance;
16186
+ var _signalClose;
16187
+ var build = (config, builtinToolIds) => {
16188
+ const resolved = resolveAuditConfig(config);
16189
+ return resolved ? new RealAuditLogger(resolved, builtinToolIds) : noop;
16190
+ };
16191
+ var getAuditLogger = (config) => {
16192
+ if (!_instance) _instance = build(config, /* @__PURE__ */ new Set());
16193
+ return _instance;
16194
+ };
16195
+ var initAudit = async (config, opts) => {
16196
+ _instance = build(config, opts?.builtinToolIds ?? /* @__PURE__ */ new Set());
16197
+ if (_instance instanceof RealAuditLogger) {
16198
+ const r = _instance.resolvedConfig;
16199
+ await applyRetentionLifecycle(_instance.lifecycleWriter(), {
16200
+ prefix: r.target.s3prefix,
16201
+ retentionDays: r.retentionDays,
16202
+ manage: r.manageLifecycle
16203
+ });
16204
+ if (_signalClose) {
16205
+ process.off("SIGTERM", _signalClose);
16206
+ process.off("SIGINT", _signalClose);
16207
+ }
16208
+ const close = () => {
16209
+ void _instance?.close();
16210
+ };
16211
+ _signalClose = close;
16212
+ process.on("SIGTERM", close);
16213
+ process.on("SIGINT", close);
16214
+ }
16215
+ return _instance;
16216
+ };
16217
+
16218
+ // src/exulu/audit/emitters/skill-sandbox.ts
16219
+ var str2 = (v) => v === void 0 || v === null ? void 0 : String(v);
16220
+ var buildSkillSandboxEvent = (ctx, opts = {}) => {
16221
+ const nowIso = opts.nowIso ?? (() => (/* @__PURE__ */ new Date()).toISOString());
16222
+ return {
16223
+ v: 1,
16224
+ ts: nowIso(),
16225
+ type: AUDIT_EVENT_TYPES.SKILL_SANDBOX_CREATED,
16226
+ actor: {
16227
+ kind: "agent",
16228
+ userId: str2(ctx.user?.id),
16229
+ email: ctx.user?.email,
16230
+ roleId: str2(ctx.user?.role?.id),
16231
+ projectId: ctx.projectId
16232
+ },
16233
+ context: {
16234
+ sessionId: ctx.sessionID,
16235
+ agentId: ctx.agent?.id,
16236
+ agentName: ctx.agent?.name
16237
+ },
16238
+ target: { kind: "skill_sandbox", id: ctx.sessionID },
16239
+ status: "ok",
16240
+ data: {
16241
+ skills: ctx.skills.map((s) => ({ id: s.id, name: s.name, version: s.version })),
16242
+ grantedVariableNames: ctx.grantedNames,
16243
+ withheldVariableNames: ctx.withheldNames,
16244
+ skippedVariableNames: ctx.skippedNames,
16245
+ strippedSecretCount: ctx.strippedSecretCount,
16246
+ degradedSandbox: ctx.degradedSandbox
16247
+ },
16248
+ client: ctx.client
16249
+ };
16250
+ };
15632
16251
 
15633
16252
  // ee/invoke-skills/create-sandbox.ts
16253
+ import { createBashTool } from "bash-tool";
16254
+ import { tool as tool2 } from "ai";
16255
+ import { z as z19 } from "zod";
16256
+ import CryptoJS3 from "crypto-js";
15634
16257
  var getAllExuluVariables = async () => {
15635
16258
  const { db } = await postgresClient();
15636
16259
  const rows = await db.from("variables").select("*");
@@ -15660,8 +16283,8 @@ var backendSecretFiles = () => {
15660
16283
  const names = [".env", ".env.local", ".env.production", ".env.production.local"];
15661
16284
  const paths = /* @__PURE__ */ new Set();
15662
16285
  for (const name of names) {
15663
- paths.add(join4(cwd, name));
15664
- paths.add(join4("/app", name));
16286
+ paths.add(join6(cwd, name));
16287
+ paths.add(join6("/app", name));
15665
16288
  }
15666
16289
  return [...paths];
15667
16290
  };
@@ -15686,18 +16309,18 @@ function probeSandboxSupport() {
15686
16309
  if (process.platform !== "linux") {
15687
16310
  return { canSandbox: false, reason: `Unsupported platform: ${process.platform}` };
15688
16311
  }
15689
- return await new Promise((resolve4) => {
16312
+ return await new Promise((resolve5) => {
15690
16313
  const child = spawn("bwrap", ["--dev-bind", "/", "/", "--", "/bin/true"], { env: {} });
15691
16314
  let stderr = "";
15692
16315
  child.stderr.on("data", (chunk) => {
15693
16316
  stderr += chunk.toString();
15694
16317
  });
15695
16318
  child.on("error", (err3) => {
15696
- resolve4({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
16319
+ resolve5({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
15697
16320
  });
15698
16321
  child.on("exit", (code) => {
15699
- if (code === 0) resolve4({ canSandbox: true });
15700
- else resolve4({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
16322
+ if (code === 0) resolve5({ canSandbox: true });
16323
+ else resolve5({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
15701
16324
  });
15702
16325
  });
15703
16326
  })();
@@ -15734,11 +16357,13 @@ async function downloadSkill(skill, skillsDirectory, config) {
15734
16357
  }
15735
16358
  const sessionDir = dirname3(skillsDirectory);
15736
16359
  await ensureRealDirectory(sessionDir, `skills/${skill.name}`);
16360
+ let actionsBytes;
15737
16361
  for (const file of files) {
15738
16362
  const prefixIndex = file.key.indexOf(versionPrefix);
15739
16363
  const relativePath = prefixIndex >= 0 ? file.key.slice(prefixIndex + versionPrefix.length) : file.key;
15740
16364
  if (!relativePath) continue;
15741
16365
  const bytes = await getS3ObjectBytes(file.key, config);
16366
+ if (relativePath === ACTIONS_FILE) actionsBytes = Buffer.from(bytes);
15742
16367
  try {
15743
16368
  await writeFileInside(sessionDir, `skills/${skill.name}/${relativePath}`, bytes);
15744
16369
  } catch (err3) {
@@ -15746,16 +16371,29 @@ async function downloadSkill(skill, skillsDirectory, config) {
15746
16371
  console.error(`[SKILLS] Skipping skill file ${file.key}: ${err3.message}`);
15747
16372
  }
15748
16373
  }
16374
+ return actionsBytes;
16375
+ }
16376
+ async function installSkill(skill, skillsDirectory, config, skillActions) {
16377
+ skillActions.delete(skill.id);
16378
+ const actionsBytes = await downloadSkill(skill, skillsDirectory, config);
16379
+ skillActions.set(skill.id, {
16380
+ skillId: skill.id,
16381
+ name: skill.name,
16382
+ version: skill.current_version,
16383
+ declaration: declarationFromBytes(actionsBytes)
16384
+ });
15749
16385
  }
15750
16386
  async function removeInstalledSkill(skillsDirectory, skillName) {
15751
16387
  const sessionDir = dirname3(skillsDirectory);
15752
16388
  await ensureRealDirectory(sessionDir, "skills");
15753
16389
  await removeEntryInside(sessionDir, `skills/${skillName}`);
15754
16390
  }
16391
+ var SKILLS_READ_ONLY_MESSAGE = (path3) => `writeFile refused: "${path3}" is inside the skills/ folder, which is read-only in a session. Write your files to the session directory instead (e.g. "./out/report.md"). A skill changes only when a new version of it is saved (skill_update or the skill editor); the session picks it up on the next turn or a reload of the skills.`;
15755
16392
  function isArtifactPath(absPath, sessionDir, opts = {}) {
15756
- const resolved = resolve3(absPath);
16393
+ const resolved = resolve4(absPath);
15757
16394
  const rel = relative(sessionDir, resolved);
15758
16395
  if (!rel || rel.startsWith("..")) return false;
16396
+ if (isActionInputsPath(rel)) return false;
15759
16397
  const first = rel.split("/")[0];
15760
16398
  if (opts.hasProject && first === PROJECT_DIR) return false;
15761
16399
  return first !== "skills";
@@ -15784,11 +16422,16 @@ function resolveSessionPath(inputPath, sessionDir) {
15784
16422
  const resolved = posix.resolve(sessionDir, sessionRelative);
15785
16423
  if (resolved !== sessionDir && !resolved.startsWith(sessionDir + "/")) {
15786
16424
  throw new Error(
15787
- `Path "${inputPath}" resolves outside the session directory. Use a path inside "${sessionDir}" (relative paths recommended, e.g. "skills/<name>/SKILL.md").`
16425
+ `Path "${inputPath}" resolves outside the session directory. Use a path inside "${sessionDir}" (relative paths recommended, e.g. "out/report.md", or "skills/<name>/SKILL.md" to read a skill).`
15788
16426
  );
15789
16427
  }
15790
16428
  return resolved;
15791
16429
  }
16430
+ async function landsInSkills(sessionDir, localPath, key) {
16431
+ if (!await landsInside(sessionDir, localPath, "skills")) return false;
16432
+ console.warn(`[SKILLS] Not writing session file ${key} into the session: it lands in skills/, which only a saved skill version fills.`);
16433
+ return true;
16434
+ }
15792
16435
  async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opts = {}) {
15793
16436
  const userPrefix = `user_${userId}/sessions/${sessionId}/`;
15794
16437
  let objects;
@@ -15811,7 +16454,8 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
15811
16454
  if (!relativePath) continue;
15812
16455
  if (isIgnoredArtifactPath(relativePath)) continue;
15813
16456
  if (opts.skipProjectDir && relativePath.split("/")[0] === PROJECT_DIR) continue;
15814
- const localPath = join4(sessionDir, relativePath);
16457
+ const localPath = join6(sessionDir, relativePath);
16458
+ if (await landsInSkills(sessionDir, localPath, obj.key)) continue;
15815
16459
  if (opts.onlyMissing) {
15816
16460
  let localSize;
15817
16461
  try {
@@ -15824,7 +16468,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
15824
16468
  }
15825
16469
  try {
15826
16470
  const bytes = await getS3ObjectBytes(obj.key, config);
15827
- await writeFileInside(sessionDir, relativePath, bytes);
16471
+ await writeFileInside(sessionDir, relativePath, bytes, { notUnder: "skills" });
15828
16472
  } catch (err3) {
15829
16473
  console.error(
15830
16474
  `[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
@@ -15835,7 +16479,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
15835
16479
  }
15836
16480
  async function downloadKeyIntoSandbox(opts) {
15837
16481
  const { sessionId, userId, fullS3Key, config } = opts;
15838
- const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
16482
+ const sessionDir = join6("/tmp", "exulu-sessions", sessionId);
15839
16483
  if (!existsSync4(sessionDir)) {
15840
16484
  return { written: false };
15841
16485
  }
@@ -15848,8 +16492,9 @@ async function downloadKeyIntoSandbox(opts) {
15848
16492
  }
15849
16493
  const relativePath = fullS3Key.slice(idx + userPrefix.length);
15850
16494
  if (!relativePath) return { written: false };
16495
+ if (await landsInSkills(sessionDir, join6(sessionDir, relativePath), fullS3Key)) return { written: false };
15851
16496
  const bytes = await getS3ObjectBytes(fullS3Key, config);
15852
- const localPath = await writeFileInside(sessionDir, relativePath, bytes);
16497
+ const localPath = await writeFileInside(sessionDir, relativePath, bytes, { notUnder: "skills" });
15853
16498
  return { written: true, localPath };
15854
16499
  }
15855
16500
  async function resolvePythonVenvPath() {
@@ -15864,11 +16509,11 @@ async function resolvePythonVenvPath() {
15864
16509
  async function refreshSessionSkills(sessionId, skills, config) {
15865
16510
  const cached = sandboxCache.get(sessionId);
15866
16511
  if (!cached) return { refreshed: 0, sandbox: false };
15867
- const skillsDirectory = join4(cached.handle.sessionDir, "skills");
16512
+ const skillsDirectory = join6(cached.handle.sessionDir, "skills");
15868
16513
  let refreshed = 0;
15869
16514
  for (const skill of skills) {
15870
16515
  await removeInstalledSkill(skillsDirectory, skill.name);
15871
- await downloadSkill(skill, skillsDirectory, config);
16516
+ await installSkill(skill, skillsDirectory, config, cached.skillActions);
15872
16517
  cached.installedSkills.set(skill.id, skill.current_version);
15873
16518
  refreshed++;
15874
16519
  }
@@ -15886,14 +16531,14 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent, op
15886
16531
  };
15887
16532
  if (cached) {
15888
16533
  cached.projectState.projectId = projectId;
15889
- const skillsDirectory2 = join4(cached.handle.sessionDir, "skills");
16534
+ const skillsDirectory2 = join6(cached.handle.sessionDir, "skills");
15890
16535
  for (const skill of skills) {
15891
16536
  const installedVersion = cached.installedSkills.get(skill.id);
15892
16537
  if (installedVersion === skill.current_version) continue;
15893
16538
  if (installedVersion !== void 0) {
15894
16539
  await removeInstalledSkill(skillsDirectory2, skill.name);
15895
16540
  }
15896
- await downloadSkill(skill, skillsDirectory2, config);
16541
+ await installSkill(skill, skillsDirectory2, config, cached.skillActions);
15897
16542
  cached.installedSkills.set(skill.id, skill.current_version);
15898
16543
  }
15899
16544
  if (userId && config.fileUploads) {
@@ -15909,13 +16554,15 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent, op
15909
16554
  await syncProject(cached.handle.sessionDir);
15910
16555
  return cached.handle;
15911
16556
  }
15912
- const sessionDir = join4("/tmp", "exulu-sessions", sessionId);
16557
+ const sessionDir = join6("/tmp", "exulu-sessions", sessionId);
15913
16558
  const dirExisted = existsSync4(sessionDir);
15914
- await mkdir3(sessionDir, { recursive: true });
15915
- const skillsDirectory = join4(sessionDir, "skills");
16559
+ await mkdir4(sessionDir, { recursive: true });
16560
+ const skillsDirectory = join6(sessionDir, "skills");
16561
+ await ensureRealDirectory(sessionDir, "skills");
15916
16562
  const installedSkills = /* @__PURE__ */ new Map();
16563
+ const skillActions = /* @__PURE__ */ new Map();
15917
16564
  for (const skill of skills) {
15918
- await downloadSkill(skill, skillsDirectory, config);
16565
+ await installSkill(skill, skillsDirectory, config, skillActions);
15919
16566
  installedSkills.set(skill.id, skill.current_version);
15920
16567
  }
15921
16568
  const persistenceEnabled = !!(userId && config.fileUploads);
@@ -15989,7 +16636,21 @@ Probe error: ${probe.reason ?? "(no detail)"}`
15989
16636
  ...pythonVenvPath ? [pythonVenvPath] : []
15990
16637
  ],
15991
16638
  allowWrite: [sessionDir],
15992
- denyWrite: []
16639
+ // Skill folders are read-only inside the sandbox; only the platform (this
16640
+ // process: download, version re-sync, reload, removal) writes them. A script
16641
+ // runs with the rights of whoever triggers it — in a shared session another
16642
+ // speaker — so nothing run in the sandbox may change what a later run executes.
16643
+ // The runtime layers this deny over the session-dir allow:
16644
+ // - macOS (seatbelt): `deny file-write*` + `deny file-write-unlink` on the
16645
+ // subpath come after the allow (later rules win), and unlink of each
16646
+ // ancestor is denied, so a rename of skills/ or a skill's folder fails too.
16647
+ // - Linux (bwrap): `--ro-bind skills skills` after the session-dir `--bind`;
16648
+ // writes get EROFS, renaming the mount point EBUSY, links into it EXDEV.
16649
+ // Paths are resolved through symlinks when each command is wrapped, which is
16650
+ // why skills/ is created above before the first command.
16651
+ // Not enforced in degraded mode (useDirectExec): nothing is. The writeFile
16652
+ // tool refuses skills/ paths itself; bash and runCommand cannot be confined.
16653
+ denyWrite: [skillsDirectory]
15993
16654
  }
15994
16655
  };
15995
16656
  let configuredVariables = {};
@@ -16010,7 +16671,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16010
16671
  extraSecretNames: litellmConfigSecretNames(),
16011
16672
  overrides: {
16012
16673
  ...npmGlobalRoot ? { NODE_PATH: npmGlobalRoot } : {},
16013
- ...pythonVenvPath ? { PATH: `${join4(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
16674
+ ...pythonVenvPath ? { PATH: `${join6(pythonVenvPath, "bin")}:${process.env.PATH ?? ""}`, VIRTUAL_ENV: pythonVenvPath } : {}
16014
16675
  }
16015
16676
  });
16016
16677
  if (skippedNames.length) {
@@ -16090,7 +16751,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16090
16751
  if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir, { hasProject })) {
16091
16752
  return {};
16092
16753
  }
16093
- const rel = relative(sessionDir, resolve3(absPath));
16754
+ const rel = relative(sessionDir, resolve4(absPath));
16094
16755
  const s3Key = artifactS3Key(sessionId, rel);
16095
16756
  const out = {};
16096
16757
  try {
@@ -16119,6 +16780,11 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16119
16780
  }
16120
16781
  async function writeFilesInternal(files, hasProject = hasProjectNow()) {
16121
16782
  const results = [];
16783
+ for (const file of files) {
16784
+ if (await landsInside(sessionDir, file.path, "skills")) {
16785
+ throw new Error(SKILLS_READ_ONLY_MESSAGE(file.path));
16786
+ }
16787
+ }
16122
16788
  for (const file of files) {
16123
16789
  const wrapped = await wrapIfNeeded(
16124
16790
  `mkdir -p ${shellQuote(dirname3(file.path))} && cat > ${shellQuote(file.path)}`
@@ -16151,8 +16817,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16151
16817
  }
16152
16818
  async function snapshotSessionArtifacts(hasProject) {
16153
16819
  const map = /* @__PURE__ */ new Map();
16154
- const skillsDir = join4(sessionDir, "skills");
16155
- const projectDir = hasProject ? join4(sessionDir, PROJECT_DIR) : null;
16820
+ const skillsDir = join6(sessionDir, "skills");
16821
+ const projectDir = hasProject ? join6(sessionDir, PROJECT_DIR) : null;
16156
16822
  const walk = async (dir) => {
16157
16823
  let entries;
16158
16824
  try {
@@ -16161,7 +16827,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16161
16827
  return;
16162
16828
  }
16163
16829
  for (const entry of entries) {
16164
- const full = join4(dir, entry.name);
16830
+ const full = join6(dir, entry.name);
16165
16831
  if (full === skillsDir) continue;
16166
16832
  if (projectDir !== null && full === projectDir) continue;
16167
16833
  if (isIgnoredArtifactPath(relative(sessionDir, full))) continue;
@@ -16187,10 +16853,10 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16187
16853
  destination: sessionDir
16188
16854
  });
16189
16855
  const writeFileTool = tool2({
16190
- description: 'Write content to a file in the sandbox. Creates parent directories if needed. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/<Skill name>/SKILL.md") and leading-slash paths ("/skills/<Skill name>/SKILL.md") work and reach the same file. When the path is under the session artifact tree, the file is also uploaded to S3 and a short-lived presigned URL is returned in the tool output.',
16191
- inputSchema: z17.object({
16192
- path: z17.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
16193
- content: z17.string().describe("The content to write to the file")
16856
+ 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 ("report.md", "out/report.md") and leading-slash paths ("/out/report.md") work and reach the same file. The skills/ folder is read-only: a path inside it is refused. A skill changes only when a new version of it is saved (skill_update or the skill editor); write your own files to the session directory. 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.',
16857
+ inputSchema: z19.object({
16858
+ path: z19.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
16859
+ content: z19.string().describe("The content to write to the file")
16194
16860
  }),
16195
16861
  execute: async ({ path: path3, content }) => {
16196
16862
  const hasProject = hasProjectNow();
@@ -16210,8 +16876,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16210
16876
  });
16211
16877
  const readFileTool = tool2({
16212
16878
  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.',
16213
- inputSchema: z17.object({
16214
- path: z17.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
16879
+ inputSchema: z19.object({
16880
+ path: z19.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
16215
16881
  }),
16216
16882
  execute: async ({ path: path3 }) => {
16217
16883
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -16225,77 +16891,123 @@ Probe error: ${probe.reason ?? "(no detail)"}`
16225
16891
  return { content };
16226
16892
  }
16227
16893
  });
16894
+ async function runWithArtifactMirroring(execute) {
16895
+ const hasProject = hasProjectNow();
16896
+ const before = persistenceEnabled ? await snapshotSessionArtifacts(hasProject) : null;
16897
+ const result = await execute();
16898
+ const artifacts = [];
16899
+ if (persistenceEnabled && before) {
16900
+ const skipProject = hasProject || hasProjectNow();
16901
+ const after = await snapshotSessionArtifacts(skipProject);
16902
+ const changedPaths = [];
16903
+ for (const [path3, mtime] of after) {
16904
+ const beforeMtime = before.get(path3);
16905
+ if (beforeMtime === void 0 || beforeMtime < mtime) {
16906
+ changedPaths.push(path3);
16907
+ }
16908
+ }
16909
+ for (const path3 of changedPaths) {
16910
+ try {
16911
+ const content = await readRegularFileInside(sessionDir, path3);
16912
+ if (content === null) continue;
16913
+ const persisted = await persistArtifactToS3(path3, content, skipProject);
16914
+ artifacts.push({
16915
+ path: path3,
16916
+ relativePath: relative(sessionDir, path3),
16917
+ key: persisted.key,
16918
+ url: persisted.url
16919
+ });
16920
+ } catch (err3) {
16921
+ console.error(
16922
+ `[SKILLS] Failed to mirror bash-produced artifact ${path3} to S3; continuing.`,
16923
+ err3
16924
+ );
16925
+ }
16926
+ }
16927
+ }
16928
+ let stdout = result?.stdout ?? "";
16929
+ const { kept, omitted } = capArtifacts(artifacts);
16930
+ const withUrls = kept.filter((a) => a.url);
16931
+ if (withUrls.length > 0) {
16932
+ const lines = [];
16933
+ for (const a of withUrls) {
16934
+ lines.push(` ${a.relativePath}: ${a.url}`);
16935
+ }
16936
+ if (omitted > 0) {
16937
+ lines.push(` \u2026 ${omitted} more file(s) were created and mirrored but are not listed here.`);
16938
+ }
16939
+ stdout = appendArtifactsBlock(stdout, lines);
16940
+ }
16941
+ return {
16942
+ ...result,
16943
+ stdout,
16944
+ artifacts: kept,
16945
+ ...omitted > 0 ? { artifactsOmitted: omitted } : {}
16946
+ };
16947
+ }
16228
16948
  const originalBashTool = tools.bash;
16229
16949
  const bashTool = tool2({
16230
16950
  description: originalBashTool.description ?? "",
16231
- inputSchema: z17.object({
16232
- command: z17.string().describe("The bash command to execute.")
16951
+ inputSchema: z19.object({
16952
+ command: z19.string().describe("The bash command to execute.")
16233
16953
  }),
16234
16954
  execute: async (args, opts2) => {
16235
- const hasProject = hasProjectNow();
16236
- const before = persistenceEnabled ? await snapshotSessionArtifacts(hasProject) : null;
16237
16955
  const originalExecute = originalBashTool.execute;
16238
16956
  if (!originalExecute) {
16239
16957
  throw new Error("bash tool execute is undefined");
16240
16958
  }
16241
- const result = await originalExecute(args, opts2);
16242
- const artifacts = [];
16243
- if (persistenceEnabled && before) {
16244
- const skipProject = hasProject || hasProjectNow();
16245
- const after = await snapshotSessionArtifacts(skipProject);
16246
- const changedPaths = [];
16247
- for (const [path3, mtime] of after) {
16248
- const beforeMtime = before.get(path3);
16249
- if (beforeMtime === void 0 || beforeMtime < mtime) {
16250
- changedPaths.push(path3);
16251
- }
16252
- }
16253
- for (const path3 of changedPaths) {
16959
+ return runWithArtifactMirroring(() => originalExecute(args, opts2));
16960
+ }
16961
+ });
16962
+ const runCommand = (command, options = {}) => runWithArtifactMirroring(async () => {
16963
+ const wrapped = await wrapIfNeeded(`cd ${shellQuote(sessionDir)} && ${command}`);
16964
+ const callEnv = { ...sandboxedExecEnv, ...options.extraEnv ?? {} };
16965
+ return await new Promise((resolvePromise) => {
16966
+ const child = spawn("/bin/bash", ["-c", wrapped], { env: callEnv, cwd: sessionDir, detached: true });
16967
+ let stdout = "";
16968
+ let stderr = "";
16969
+ let timedOut = false;
16970
+ let settled = false;
16971
+ let timer;
16972
+ const append = (cur, chunk) => cur.length >= EXEC_MAX_BUFFER ? cur : (cur + chunk).slice(0, EXEC_MAX_BUFFER);
16973
+ child.stdout?.setEncoding("utf8");
16974
+ child.stderr?.setEncoding("utf8");
16975
+ child.stdout?.on("data", (c) => {
16976
+ stdout = append(stdout, c);
16977
+ });
16978
+ child.stderr?.on("data", (c) => {
16979
+ stderr = append(stderr, c);
16980
+ });
16981
+ const finish = (exitCode) => {
16982
+ if (settled) return;
16983
+ settled = true;
16984
+ if (timer) clearTimeout(timer);
16985
+ resolvePromise({ stdout, stderr, exitCode: timedOut ? 124 : exitCode, timedOut });
16986
+ };
16987
+ if (options.timeoutMs !== void 0 && options.timeoutMs > 0) {
16988
+ timer = setTimeout(() => {
16989
+ timedOut = true;
16254
16990
  try {
16255
- const content = await readRegularFileInside(sessionDir, path3);
16256
- if (content === null) continue;
16257
- const persisted = await persistArtifactToS3(path3, content, skipProject);
16258
- artifacts.push({
16259
- path: path3,
16260
- relativePath: relative(sessionDir, path3),
16261
- key: persisted.key,
16262
- url: persisted.url
16263
- });
16264
- } catch (err3) {
16265
- console.error(
16266
- `[SKILLS] Failed to mirror bash-produced artifact ${path3} to S3; continuing.`,
16267
- err3
16268
- );
16991
+ if (child.pid) process.kill(-child.pid, "SIGKILL");
16992
+ } catch {
16993
+ child.kill("SIGKILL");
16269
16994
  }
16270
- }
16271
- }
16272
- let stdout = result?.stdout ?? "";
16273
- const { kept, omitted } = capArtifacts(artifacts);
16274
- const withUrls = kept.filter((a) => a.url);
16275
- if (withUrls.length > 0) {
16276
- const lines = ["", "[exulu-artifacts]"];
16277
- for (const a of withUrls) {
16278
- lines.push(` ${a.relativePath}: ${a.url}`);
16279
- }
16280
- if (omitted > 0) {
16281
- lines.push(` \u2026 ${omitted} more file(s) were created and mirrored but are not listed here.`);
16282
- }
16283
- stdout = `${stdout}
16284
- ${lines.join("\n")}`;
16995
+ }, options.timeoutMs);
16285
16996
  }
16286
- return {
16287
- ...result,
16288
- stdout,
16289
- artifacts: kept,
16290
- ...omitted > 0 ? { artifactsOmitted: omitted } : {}
16291
- };
16292
- }
16997
+ child.on("error", (err3) => {
16998
+ stderr = `${stderr}${err3.message}`;
16999
+ finish(1);
17000
+ });
17001
+ child.on("close", (code, signal) => finish(typeof code === "number" ? code : signal ? 128 : 1));
17002
+ });
16293
17003
  });
16294
17004
  const wrappedTools = { ...tools, bash: bashTool, readFile: readFileTool, writeFile: writeFileTool };
16295
17005
  const handle = {
16296
17006
  sessionDir,
16297
17007
  tools: wrappedTools,
16298
17008
  wrapCommand: (command) => wrapIfNeeded(command),
17009
+ runCommand,
17010
+ skillActions,
16299
17011
  cleanup: async () => {
16300
17012
  sandboxCache.delete(sessionId);
16301
17013
  if (!useDirectExec) {
@@ -16305,7 +17017,7 @@ ${lines.join("\n")}`;
16305
17017
  await clearProjectSyncMarker(sessionDir);
16306
17018
  }
16307
17019
  };
16308
- sandboxCache.set(sessionId, { handle, installedSkills, projectState });
17020
+ sandboxCache.set(sessionId, { handle, installedSkills, skillActions, projectState });
16309
17021
  return handle;
16310
17022
  }
16311
17023
 
@@ -16437,7 +17149,7 @@ function buildSaveSessionFile(args) {
16437
17149
  }
16438
17150
 
16439
17151
  // src/templates/tools/routine-status-tool.ts
16440
- import { z as z18 } from "zod";
17152
+ import { z as z20 } from "zod";
16441
17153
  var SET_ROUTINE_STATUS_TOOL_ID = "set_routine_status";
16442
17154
  function createRoutineStatusTool(handle) {
16443
17155
  if (!handle || handle.statuses.length === 0) return void 0;
@@ -16450,8 +17162,8 @@ function createRoutineStatusTool(handle) {
16450
17162
  category: "routines",
16451
17163
  type: "function",
16452
17164
  needsApproval: false,
16453
- inputSchema: z18.object({
16454
- status: z18.enum(keys).describe("The work status key to set.")
17165
+ inputSchema: z20.object({
17166
+ status: z20.enum(keys).describe("The work status key to set.")
16455
17167
  }),
16456
17168
  config: [],
16457
17169
  execute: async ({ status }) => {
@@ -16491,7 +17203,7 @@ var truncateToolOutput = (output, maxContextLength, toolName, tailFraction = 0.1
16491
17203
  };
16492
17204
 
16493
17205
  // src/exulu/tool-output-offload.ts
16494
- import { randomUUID as randomUUID7 } from "crypto";
17206
+ import { randomUUID as randomUUID8 } from "crypto";
16495
17207
 
16496
17208
  // src/exulu/context-budget.ts
16497
17209
  var DEFAULT_CONTEXT_WINDOW = 128e3;
@@ -16595,7 +17307,7 @@ var PREVIEW_CHARS = 4e3;
16595
17307
  var storeAsSessionFile = async (serialized, ctx) => {
16596
17308
  if (!ctx.sessionID || !ctx.exuluConfig?.fileUploads) return void 0;
16597
17309
  const safeTool = ctx.toolName.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
16598
- const name = `tool-output-${safeTool}-${randomUUID7().slice(0, 8)}.txt`;
17310
+ const name = `tool-output-${safeTool}-${randomUUID8().slice(0, 8)}.txt`;
16599
17311
  try {
16600
17312
  await uploadFile(
16601
17313
  Buffer.from(serialized, "utf-8"),
@@ -16663,7 +17375,7 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
16663
17375
  };
16664
17376
 
16665
17377
  // src/templates/tools/session-file-read-tool.ts
16666
- import { z as z19 } from "zod";
17378
+ import { z as z21 } from "zod";
16667
17379
 
16668
17380
  // src/templates/tools/resolve-file-key.ts
16669
17381
  var NO_PROJECT_FILES_ERROR = "This session has no project files.";
@@ -16744,10 +17456,10 @@ var createSessionFileReadTool = ({
16744
17456
  name: SESSION_FILE_READ_TOOL_NAME,
16745
17457
  needsApproval: false,
16746
17458
  description: "Read a line range from a file stored in this session's files \u2014 including offloaded tool outputs (tool-output-*.txt) and uploaded documents. Use offset (1-based line number) and limit to page through large files instead of reading everything at once. Files of the session's project are addressed as `project/<name>` and are read-only.",
16747
- inputSchema: z19.object({
16748
- filename: z19.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
16749
- offset: z19.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
16750
- limit: z19.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
17459
+ inputSchema: z21.object({
17460
+ filename: z21.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
17461
+ offset: z21.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
17462
+ limit: z21.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
16751
17463
  }),
16752
17464
  type: "function",
16753
17465
  category: "session",
@@ -16760,7 +17472,7 @@ var createSessionFileReadTool = ({
16760
17472
  };
16761
17473
 
16762
17474
  // src/templates/tools/parse-document-tool.ts
16763
- import { z as z20 } from "zod";
17475
+ import { z as z22 } from "zod";
16764
17476
  import { extname as extname2 } from "path";
16765
17477
  import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
16766
17478
 
@@ -16770,7 +17482,7 @@ import { promisify as promisify4 } from "util";
16770
17482
  import { existsSync as existsSync5 } from "fs";
16771
17483
  import { mkdtemp, readdir as readdir3, readFile as readFile2, rm as rm3, writeFile as writeFile3 } from "fs/promises";
16772
17484
  import { tmpdir } from "os";
16773
- import { join as join5 } from "path";
17485
+ import { join as join7 } from "path";
16774
17486
  var execFileAsync2 = promisify4(execFile2);
16775
17487
  var MAX_STDOUT_BYTES = 64 * 1024 * 1024;
16776
17488
  var LEGACY_OFFICE_CONVERSION_TARGETS = {
@@ -16787,9 +17499,9 @@ async function convertLegacyOfficeToModern(bytes, ext) {
16787
17499
  if (!target) {
16788
17500
  throw new Error(`No modern-format conversion target registered for "${ext}"`);
16789
17501
  }
16790
- const dir = await mkdtemp(join5(tmpdir(), "exulu-officeconv-"));
17502
+ const dir = await mkdtemp(join7(tmpdir(), "exulu-officeconv-"));
16791
17503
  try {
16792
- const inputPath = join5(dir, `input${ext}`);
17504
+ const inputPath = join7(dir, `input${ext}`);
16793
17505
  await writeFile3(inputPath, bytes);
16794
17506
  try {
16795
17507
  await execFileAsync2(
@@ -16802,7 +17514,7 @@ async function convertLegacyOfficeToModern(bytes, ext) {
16802
17514
  `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err3 instanceof Error ? err3.message : String(err3))
16803
17515
  );
16804
17516
  }
16805
- const outputPath = join5(dir, `input.${target}`);
17517
+ const outputPath = join7(dir, `input.${target}`);
16806
17518
  if (!existsSync5(outputPath)) {
16807
17519
  throw new Error(`LibreOffice produced no output converting "${ext}" to ${target}`);
16808
17520
  }
@@ -16812,9 +17524,9 @@ async function convertLegacyOfficeToModern(bytes, ext) {
16812
17524
  }
16813
17525
  }
16814
17526
  async function pdfToText(pdf) {
16815
- const dir = await mkdtemp(join5(tmpdir(), "exulu-parse-"));
17527
+ const dir = await mkdtemp(join7(tmpdir(), "exulu-parse-"));
16816
17528
  try {
16817
- const inputPath = join5(dir, "input.pdf");
17529
+ const inputPath = join7(dir, "input.pdf");
16818
17530
  await writeFile3(inputPath, pdf);
16819
17531
  const { stdout } = await execFileAsync2("pdftotext", ["-layout", inputPath, "-"], {
16820
17532
  timeout: 6e4,
@@ -16826,9 +17538,9 @@ async function pdfToText(pdf) {
16826
17538
  }
16827
17539
  }
16828
17540
  async function pdfPageCount(pdf) {
16829
- const dir = await mkdtemp(join5(tmpdir(), "exulu-pdfinfo-"));
17541
+ const dir = await mkdtemp(join7(tmpdir(), "exulu-pdfinfo-"));
16830
17542
  try {
16831
- const inputPath = join5(dir, "input.pdf");
17543
+ const inputPath = join7(dir, "input.pdf");
16832
17544
  await writeFile3(inputPath, pdf);
16833
17545
  const { stdout } = await execFileAsync2("pdfinfo", [inputPath], { timeout: 3e4, maxBuffer: 1e6 });
16834
17546
  const match = /^Pages:\s+(\d+)/m.exec(stdout);
@@ -16839,14 +17551,14 @@ async function pdfPageCount(pdf) {
16839
17551
  }
16840
17552
  }
16841
17553
  async function renderPdfPageToPng(pdf, page, scaleTo) {
16842
- const dir = await mkdtemp(join5(tmpdir(), "exulu-render-"));
17554
+ const dir = await mkdtemp(join7(tmpdir(), "exulu-render-"));
16843
17555
  try {
16844
- const inputPath = join5(dir, "input.pdf");
17556
+ const inputPath = join7(dir, "input.pdf");
16845
17557
  await writeFile3(inputPath, pdf);
16846
17558
  try {
16847
17559
  await execFileAsync2(
16848
17560
  "pdftoppm",
16849
- ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, join5(dir, "page")],
17561
+ ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, join7(dir, "page")],
16850
17562
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
16851
17563
  );
16852
17564
  } catch (err3) {
@@ -16855,7 +17567,7 @@ async function renderPdfPageToPng(pdf, page, scaleTo) {
16855
17567
  }
16856
17568
  const produced = (await readdir3(dir)).find((f) => f.startsWith("page") && f.endsWith(".png"));
16857
17569
  if (!produced) return null;
16858
- return await readFile2(join5(dir, produced));
17570
+ return await readFile2(join7(dir, produced));
16859
17571
  } finally {
16860
17572
  await rm3(dir, { recursive: true, force: true });
16861
17573
  }
@@ -17412,8 +18124,8 @@ ${text.trim()}`).join("\n")
17412
18124
  while (true) {
17413
18125
  while (queue.length > 0) yield queue.shift();
17414
18126
  if (finished) break;
17415
- await new Promise((resolve4) => {
17416
- wake = resolve4;
18127
+ await new Promise((resolve5) => {
18128
+ wake = resolve5;
17417
18129
  });
17418
18130
  wake = void 0;
17419
18131
  }
@@ -17430,11 +18142,11 @@ ${text.trim()}`).join("\n")
17430
18142
  // Without a document processor the tool reads the text layer only: say so, and keep the
17431
18143
  // original wording so existing deployments see no change beyond the reuse sentence.
17432
18144
  description: exuluConfig.attachments?.documentProcessor ? "Extract the text of an uploaded PDF or Office document from this session's files, with \"--- page N ---\" markers for PDFs so you can locate content by page. Results are stored and reused, so reading the same document again is fast, but the first read of a long document can take minutes. To SEE a page or an image inside a document, use view_document_page. Files of the session's project are addressed as `project/<name>` and are read-only." : "Extract the text of an uploaded PDF or Office document from this session's files, with \"--- page N ---\" markers for PDFs so you can locate content by page. Free and fast (no OCR): works only on documents with a real text layer. To SEE a page or an image inside a document, use view_document_page. Extracted text is stored and reused, so reading the same document again is fast. Files of the session's project are addressed as `project/<name>` and are read-only.",
17433
- inputSchema: z20.object({
17434
- filename: z20.string().describe('Exact session file name, e.g. "report.pdf"'),
17435
- pages: z20.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
17436
- offset: z20.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
17437
- limit: z20.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
18145
+ inputSchema: z22.object({
18146
+ filename: z22.string().describe('Exact session file name, e.g. "report.pdf"'),
18147
+ pages: z22.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
18148
+ offset: z22.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
18149
+ limit: z22.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
17438
18150
  }),
17439
18151
  type: "function",
17440
18152
  category: "session",
@@ -17447,19 +18159,19 @@ ${text.trim()}`).join("\n")
17447
18159
  };
17448
18160
 
17449
18161
  // src/templates/tools/view-document-page-tool.ts
17450
- import { z as z21 } from "zod";
18162
+ import { z as z23 } from "zod";
17451
18163
  import { extname as extname4 } from "path";
17452
18164
 
17453
18165
  // src/sessions/pdf-preview-cache.ts
17454
18166
  import { exec as exec3 } from "child_process";
17455
18167
  import { existsSync as existsSync6 } from "fs";
17456
- import { mkdir as mkdir4, readFile as readFile3, rename as rename3, rm as rm4, writeFile as writeFile4 } from "fs/promises";
17457
- import { extname as extname3, join as join6 } from "path";
18168
+ import { mkdir as mkdir5, readFile as readFile3, rename as rename3, rm as rm4, writeFile as writeFile4 } from "fs/promises";
18169
+ import { extname as extname3, join as join8 } from "path";
17458
18170
  import { promisify as promisify5 } from "util";
17459
18171
  var execAsync3 = promisify5(exec3);
17460
18172
  var CACHE_ROOT = "/tmp/exulu-pdf-cache";
17461
- var CACHE_IN = join6(CACHE_ROOT, "_in");
17462
- var CACHE_OUT = join6(CACHE_ROOT, "_out");
18173
+ var CACHE_IN = join8(CACHE_ROOT, "_in");
18174
+ var CACHE_OUT = join8(CACHE_ROOT, "_out");
17463
18175
  var inFlight2 = /* @__PURE__ */ new Map();
17464
18176
  var PreviewRenderError = class extends Error {
17465
18177
  constructor(message) {
@@ -17476,7 +18188,7 @@ async function getPdfPreviewBytes(opts) {
17476
18188
  if (!safeEtag) {
17477
18189
  throw new PreviewRenderError(`Invalid ETag for ${sourceKey}`);
17478
18190
  }
17479
- const cachedPath = join6(CACHE_ROOT, `${safeEtag}.pdf`);
18191
+ const cachedPath = join8(CACHE_ROOT, `${safeEtag}.pdf`);
17480
18192
  if (existsSync6(cachedPath)) {
17481
18193
  return readFile3(cachedPath);
17482
18194
  }
@@ -17484,11 +18196,11 @@ async function getPdfPreviewBytes(opts) {
17484
18196
  if (existing) return existing;
17485
18197
  const promise = (async () => {
17486
18198
  try {
17487
- await mkdir4(CACHE_IN, { recursive: true });
17488
- await mkdir4(CACHE_OUT, { recursive: true });
18199
+ await mkdir5(CACHE_IN, { recursive: true });
18200
+ await mkdir5(CACHE_OUT, { recursive: true });
17489
18201
  const ext = (extname3(sourceKey) || ".docx").toLowerCase();
17490
- const inputPath = join6(CACHE_IN, `${safeEtag}${ext}`);
17491
- const outputPath = join6(CACHE_OUT, `${safeEtag}.pdf`);
18202
+ const inputPath = join8(CACHE_IN, `${safeEtag}${ext}`);
18203
+ const outputPath = join8(CACHE_OUT, `${safeEtag}.pdf`);
17492
18204
  try {
17493
18205
  const bytes = await getS3ObjectBytes(sourceKey, config);
17494
18206
  await writeFile4(inputPath, bytes);
@@ -17722,9 +18434,9 @@ var createViewDocumentPageTool = ({
17722
18434
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
17723
18435
  needsApproval: false,
17724
18436
  description: "LOOK at a page of an uploaded PDF/Office document, or at an uploaded image, from this session's files. The rendered image is attached as a user message directly after this tool result so you can visually analyze photos, charts, scans, and layouts. Use parse_document first to find which page you need. Requires a vision-capable model. Files of the session's project are addressed as `project/<name>` and are read-only.",
17725
- inputSchema: z21.object({
17726
- filename: z21.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
17727
- page: z21.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
18437
+ inputSchema: z23.object({
18438
+ filename: z23.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
18439
+ page: z23.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
17728
18440
  }),
17729
18441
  type: "function",
17730
18442
  category: "session",
@@ -17773,7 +18485,7 @@ var isReadingProgress = (value) => {
17773
18485
  return typeof v.filename === "string" && typeof v.pagesDone === "number" && typeof v.pagesTotal === "number";
17774
18486
  };
17775
18487
  var OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
17776
- var generateS3Key = (filename) => `${randomUUID8()}-${filename}`;
18488
+ var generateS3Key = (filename) => `${randomUUID9()}-${filename}`;
17777
18489
  var s3Client2;
17778
18490
  var hydrateVariables = async (tool3) => {
17779
18491
  const { db } = await postgresClient();
@@ -17971,6 +18683,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
17971
18683
  if (viewDocumentPageTool && !disabled.has(viewDocumentPageTool.id)) {
17972
18684
  currentTools.push(viewDocumentPageTool);
17973
18685
  }
18686
+ let agenticSearchActive = false;
18687
+ let projectSearchContextIds;
17974
18688
  console.log("[EXULU] Creating agentic search tool", contexts?.length, model);
17975
18689
  if (contexts?.length && model && !disabled.has("agentic_context_search")) {
17976
18690
  const index = currentTools.findIndex((tool3) => tool3.id === "agentic_context_search");
@@ -17988,6 +18702,7 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
17988
18702
  projectScope
17989
18703
  });
17990
18704
  if (agenticSearchTool) {
18705
+ agenticSearchActive = true;
17991
18706
  currentTools[index] = {
17992
18707
  ...currentTools[index],
17993
18708
  // important to keep the original tool config
@@ -18016,6 +18731,7 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
18016
18731
  projectScope
18017
18732
  });
18018
18733
  if (projectSearchTool) {
18734
+ projectSearchContextIds = scopedContexts.map((c) => c.id);
18019
18735
  currentTools.push(projectSearchTool);
18020
18736
  }
18021
18737
  }
@@ -18026,6 +18742,38 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
18026
18742
  currentTools.splice(currentTools.indexOf(agenticSearchTool), 1);
18027
18743
  }
18028
18744
  }
18745
+ if (sharedSessionSandbox && !disabled.has(RUN_SKILL_ACTION_TOOL_ID)) {
18746
+ const loadedActions = loadSkillActions(
18747
+ sharedSessionSandbox.sessionDir,
18748
+ currentSkills ?? [],
18749
+ sharedSessionSandbox.skillActions
18750
+ );
18751
+ const hasActions = Object.values(loadedActions.bySkill).some((s) => Object.keys(s.actions).length > 0);
18752
+ if (hasActions || loadedActions.problems.length > 0) {
18753
+ const contextIds = contexts.map((c) => c.id);
18754
+ const editor = parseKbEditorConfig(agent?.tools);
18755
+ const sandbox = sharedSessionSandbox;
18756
+ currentTools.push(
18757
+ createRunSkillActionTool({
18758
+ handle: sandbox,
18759
+ loaded: loadedActions,
18760
+ contexts,
18761
+ connectedContextIds: deriveConnectedContextIds({
18762
+ contextIds,
18763
+ memoryContextId: agent?.memory,
18764
+ editorContextIds: editor.enabled ? Object.keys(editor.knowledgeBases).filter((id) => contextIds.includes(id)) : [],
18765
+ disabledToolIds: disabled,
18766
+ agenticSearch: agenticSearchActive ? { config: configs?.find((c) => c.id === "agentic_context_search") } : void 0,
18767
+ projectSearchContextIds
18768
+ }),
18769
+ // Same head/tail rules as the bash wrapper below; the tool hands each stream
18770
+ // its share of the guard's cap so the whole result (links included) fits.
18771
+ truncate: (text, kind, charLimit) => kind === "stdout" ? truncateToolOutput(text, budget.contextWindow, RUN_SKILL_ACTION_TOOL_ID, 0.1, charLimit) : truncateToolOutput(text, budget.contextWindow, `${RUN_SKILL_ACTION_TOOL_ID} stderr`, 0.4, charLimit),
18772
+ resultCharLimit: toolOutputCharLimit
18773
+ })
18774
+ );
18775
+ }
18776
+ }
18029
18777
  const sanitizedTools = currentTools ? currentTools.map((tool3) => ({
18030
18778
  ...tool3,
18031
18779
  name: sanitizeToolName(tool3.name)
@@ -18485,7 +19233,10 @@ export {
18485
19233
  createCreateProjectPickerTool,
18486
19234
  canRegisterSaveToProject,
18487
19235
  resolveSkillByName,
19236
+ canWritePublicSkill,
18488
19237
  canAccessSkill,
19238
+ ensureSkillWrite,
19239
+ ensureSkillRead,
18489
19240
  filterReadableSkills,
18490
19241
  parseFrontmatter,
18491
19242
  parseSkillFrontmatter,