@exulu/backend 5.4.0 → 5.5.1

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.
@@ -137,8 +137,8 @@ var supervise = async (cfg) => {
137
137
  pollHealth(cfg.host, cfg.port).then(() => "ready"),
138
138
  exitPromise.then((code2) => ({ exited: code2 }))
139
139
  ]);
140
- } catch (err2) {
141
- log(`Readiness probe failed: ${err2.message}`);
140
+ } catch (err3) {
141
+ log(`Readiness probe failed: ${err3.message}`);
142
142
  try {
143
143
  internal.child?.kill("SIGTERM");
144
144
  } catch {
@@ -236,9 +236,9 @@ var waitForLiteLLMReady = async () => {
236
236
  let res;
237
237
  try {
238
238
  res = await fetch(url, { method: "GET", headers: remote ? authHeaders : {} });
239
- } catch (err2) {
239
+ } catch (err3) {
240
240
  throw new Error(
241
- `LiteLLM proxy not reachable at ${url} (is the Exulu server process running?): ${err2.message}`
241
+ `LiteLLM proxy not reachable at ${url} (is the Exulu server process running?): ${err3.message}`
242
242
  );
243
243
  }
244
244
  if (!res.ok) {
@@ -412,8 +412,8 @@ function createTaggedFetch(tags) {
412
412
  headers: stripContentLengthHeader(init.headers)
413
413
  };
414
414
  return globalThis.fetch(input, nextInit);
415
- } catch (err2) {
416
- console.warn("[vertex-labels] label injection failed, forwarding unchanged", err2);
415
+ } catch (err3) {
416
+ console.warn("[vertex-labels] label injection failed, forwarding unchanged", err3);
417
417
  return globalThis.fetch(input, init);
418
418
  }
419
419
  };
@@ -508,11 +508,11 @@ async function postgresClient() {
508
508
  // Log pool events to help debug connection issues
509
509
  afterCreate: (conn, done) => {
510
510
  console.log("[EXULU] New database connection created");
511
- conn.query("SET statement_timeout = 1800000; SET hnsw.ef_search = 20", (err2) => {
512
- if (err2) {
513
- console.error("[EXULU] Error setting connection parameters:", err2);
511
+ conn.query("SET statement_timeout = 1800000; SET hnsw.ef_search = 20", (err3) => {
512
+ if (err3) {
513
+ console.error("[EXULU] Error setting connection parameters:", err3);
514
514
  }
515
- done(err2, conn);
515
+ done(err3, conn);
516
516
  });
517
517
  }
518
518
  }
@@ -641,11 +641,11 @@ async function tagInfo(names) {
641
641
  let json;
642
642
  try {
643
643
  json = await call("/tag/info", { names });
644
- } catch (err2) {
645
- if (err2 instanceof LiteLLMAdminError && /not found/i.test(err2.message)) {
644
+ } catch (err3) {
645
+ if (err3 instanceof LiteLLMAdminError && /not found/i.test(err3.message)) {
646
646
  return out;
647
647
  }
648
- throw err2;
648
+ throw err3;
649
649
  }
650
650
  for (const name of names) {
651
651
  const raw = json?.[name];
@@ -845,8 +845,8 @@ async function enrichSpendFromActivity(map) {
845
845
  map[name].spend = spend;
846
846
  }
847
847
  }
848
- } catch (err2) {
849
- console.warn("[EXULU] enrichSpendFromActivity failed", err2);
848
+ } catch (err3) {
849
+ console.warn("[EXULU] enrichSpendFromActivity failed", err3);
850
850
  }
851
851
  }
852
852
  var DEFAULT_SETTINGS = {
@@ -940,8 +940,8 @@ async function getTagBudgetMap() {
940
940
  await enrichSpendFromActivity(map);
941
941
  tagMapCache = { expiry: Date.now() + TAG_MAP_TTL_MS, map };
942
942
  return map;
943
- } catch (err2) {
944
- console.warn("[EXULU] getTagBudgetMap failed", err2);
943
+ } catch (err3) {
944
+ console.warn("[EXULU] getTagBudgetMap failed", err3);
945
945
  return {};
946
946
  } finally {
947
947
  tagMapInflight = void 0;
@@ -974,8 +974,8 @@ async function provisionDefaultUserBudget(userId) {
974
974
  budget_duration: g.budget_duration
975
975
  });
976
976
  provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
977
- } catch (err2) {
978
- console.warn("[EXULU] ensureUserBudget failed", err2);
977
+ } catch (err3) {
978
+ console.warn("[EXULU] ensureUserBudget failed", err3);
979
979
  }
980
980
  }
981
981
  var READ_TTL_MS = 30 * 1e3;
@@ -1007,8 +1007,8 @@ async function getUserBudgetView(userId) {
1007
1007
  } : null;
1008
1008
  readCache.set(tag, { expiry: Date.now() + READ_TTL_MS, view });
1009
1009
  return view;
1010
- } catch (err2) {
1011
- console.warn("[EXULU] getUserBudgetView failed", err2);
1010
+ } catch (err3) {
1011
+ console.warn("[EXULU] getUserBudgetView failed", err3);
1012
1012
  return null;
1013
1013
  }
1014
1014
  }
@@ -1076,10 +1076,10 @@ async function resolveModel(input) {
1076
1076
  }
1077
1077
  try {
1078
1078
  await waitForLiteLLMReady();
1079
- } catch (err2) {
1079
+ } catch (err3) {
1080
1080
  throw new ResolveModelError(
1081
1081
  "LITELLM_NOT_READY",
1082
- `LiteLLM is not ready: ${err2.message}`
1082
+ `LiteLLM is not ready: ${err3.message}`
1083
1083
  );
1084
1084
  }
1085
1085
  if (user?.id) await provisionDefaultUserBudget(user.id);
@@ -1723,7 +1723,7 @@ var ExuluTool = class _ExuluTool {
1723
1723
  if (!agent) {
1724
1724
  throw new Error("Agent not found.");
1725
1725
  }
1726
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-437EHCSN.js");
1726
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-C5LYP4UN.js");
1727
1727
  const tools = await convertExuluToolsToAiSdkTools2(
1728
1728
  [this],
1729
1729
  [],
@@ -1815,7 +1815,7 @@ var ContextEmbedderNotConfiguredError = class extends Error {
1815
1815
  this.contextId = contextId;
1816
1816
  }
1817
1817
  };
1818
- var isEmbedderNotConfigured = (err2) => !!err2 && err2.name === "ContextEmbedderNotConfiguredError";
1818
+ var isEmbedderNotConfigured = (err3) => !!err3 && err3.name === "ContextEmbedderNotConfiguredError";
1819
1819
 
1820
1820
  // src/templates/tools/session-items-retrieval-tool.ts
1821
1821
  import { z as z2 } from "zod";
@@ -1892,11 +1892,11 @@ var createSessionItemsRetrievalTool = async ({
1892
1892
  limit: 10,
1893
1893
  page: 1
1894
1894
  });
1895
- } catch (err2) {
1896
- if (isEmbedderNotConfigured(err2)) {
1897
- return err2.message;
1895
+ } catch (err3) {
1896
+ if (isEmbedderNotConfigured(err3)) {
1897
+ return err3.message;
1898
1898
  }
1899
- throw err2;
1899
+ throw err3;
1900
1900
  }
1901
1901
  })
1902
1902
  );
@@ -1968,10 +1968,10 @@ async function resolveReranker(input) {
1968
1968
  }
1969
1969
  try {
1970
1970
  await waitForLiteLLMReady();
1971
- } catch (err2) {
1971
+ } catch (err3) {
1972
1972
  throw new ResolveRerankerError(
1973
1973
  "LITELLM_NOT_READY",
1974
- `LiteLLM is not ready: ${err2.message}`
1974
+ `LiteLLM is not ready: ${err3.message}`
1975
1975
  );
1976
1976
  }
1977
1977
  const { baseUrl, authHeaders } = resolveLiteLLMTarget();
@@ -2038,8 +2038,8 @@ async function resolveReranker(input) {
2038
2038
  }));
2039
2039
  reranked.sort((a, b) => b.rerank_score - a.rerank_score);
2040
2040
  return reranked;
2041
- } catch (err2) {
2042
- console.error("[EXULU] Error reranking:", err2);
2041
+ } catch (err3) {
2042
+ console.error("[EXULU] Error reranking:", err3);
2043
2043
  return [];
2044
2044
  }
2045
2045
  };
@@ -2148,8 +2148,8 @@ function jsonVal(name, schema, v) {
2148
2148
  if (typeof v === "string" && v.trim().length > 0) {
2149
2149
  try {
2150
2150
  candidate = JSON.parse(v);
2151
- } catch (err2) {
2152
- console.warn(`[EXULU pipeline] config "${name}" is not valid JSON \u2014 using defaults.`, err2);
2151
+ } catch (err3) {
2152
+ console.warn(`[EXULU pipeline] config "${name}" is not valid JSON \u2014 using defaults.`, err3);
2153
2153
  candidate = void 0;
2154
2154
  }
2155
2155
  } else if (typeof v !== "object" || v === null) {
@@ -2162,8 +2162,8 @@ function jsonVal(name, schema, v) {
2162
2162
  }
2163
2163
  try {
2164
2164
  return schema.parse(defaultFor(name));
2165
- } catch (err2) {
2166
- console.warn(`[EXULU pipeline] failed to parse fallback for option "${name}" \u2014 falling back to schema.parse(undefined).`, err2);
2165
+ } catch (err3) {
2166
+ console.warn(`[EXULU pipeline] failed to parse fallback for option "${name}" \u2014 falling back to schema.parse(undefined).`, err3);
2167
2167
  try {
2168
2168
  return schema.parse(void 0);
2169
2169
  } catch {
@@ -2714,10 +2714,10 @@ async function resolveIdentifierPins({
2714
2714
  });
2715
2715
  })
2716
2716
  );
2717
- } catch (err2) {
2717
+ } catch (err3) {
2718
2718
  console.warn(
2719
2719
  `[EXULU pipeline] identifier extraction for "${set.name}" failed \u2014 skipping.`,
2720
- err2
2720
+ err3
2721
2721
  );
2722
2722
  }
2723
2723
  })
@@ -2832,8 +2832,8 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
2832
2832
  enabledContexts,
2833
2833
  routingRules: wantsClassification ? routingRules : [],
2834
2834
  extraInstructions
2835
- }).catch((err2) => {
2836
- console.warn("[EXULU pipeline] merged routing call failed \u2014 falling back to the v1 hops.", err2);
2835
+ }).catch((err3) => {
2836
+ console.warn("[EXULU pipeline] merged routing call failed \u2014 falling back to the v1 hops.", err3);
2837
2837
  return null;
2838
2838
  })
2839
2839
  ) : null;
@@ -2851,7 +2851,7 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
2851
2851
  pageNumber: z5.number().int().nullable().optional()
2852
2852
  })
2853
2853
  });
2854
- } catch (err2) {
2854
+ } catch (err3) {
2855
2855
  steps.push({ text: "Doc/page detection failed \u2014 skipping filename and page hints." });
2856
2856
  return {
2857
2857
  output: {
@@ -2875,7 +2875,7 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
2875
2875
  }),
2876
2876
  messages: [{ role: "user", content: question }]
2877
2877
  });
2878
- } catch (err2) {
2878
+ } catch (err3) {
2879
2879
  return { output: { explicitlyRequestedKnowledgeBases: [] } };
2880
2880
  }
2881
2881
  })()
@@ -2917,8 +2917,8 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
2917
2917
  text: totalMatched > 0 ? `User referenced specific document(s); pinning ${totalMatched} file(s): ${matchedNames.join(", ")}` : `User referenced document(s) ${hints.join(", ")} but no matching file was found.`
2918
2918
  });
2919
2919
  }
2920
- } catch (err2) {
2921
- console.warn("[EXULU pipeline] Document reference resolution failed:", err2);
2920
+ } catch (err3) {
2921
+ console.warn("[EXULU pipeline] Document reference resolution failed:", err3);
2922
2922
  steps.push({ text: "Document reference resolution failed \u2014 continuing without file pins." });
2923
2923
  }
2924
2924
  }
@@ -2987,7 +2987,7 @@ ${extraInstructions}
2987
2987
  text: "Classification returned unknown rule \u2014 using implicit all-main rule."
2988
2988
  });
2989
2989
  }
2990
- } catch (err2) {
2990
+ } catch (err3) {
2991
2991
  mainContexts = enabledContexts.map((c) => c.id);
2992
2992
  fallbackContexts = [];
2993
2993
  steps.push({
@@ -3006,8 +3006,8 @@ ${extraInstructions}
3006
3006
  hasExplicitDocAndPage,
3007
3007
  steps
3008
3008
  };
3009
- } catch (err2) {
3010
- console.warn("[EXULU pipeline] runRoutingPhase failed:", err2);
3009
+ } catch (err3) {
3010
+ console.warn("[EXULU pipeline] runRoutingPhase failed:", err3);
3011
3011
  return {
3012
3012
  mainContexts: enabledContexts.map((c) => c.id),
3013
3013
  fallbackContexts: [],
@@ -3437,8 +3437,8 @@ ${glossary.map((g) => `${g.term} : ${g.meaning}`).join("\n")}` : "";
3437
3437
  updatedImportantKeyword,
3438
3438
  steps
3439
3439
  };
3440
- } catch (err2) {
3441
- console.warn("[EXULU pipeline] memory phase failed \u2014 continuing without memory.", err2);
3440
+ } catch (err3) {
3441
+ console.warn("[EXULU pipeline] memory phase failed \u2014 continuing without memory.", err3);
3442
3442
  return neutralResult(question, keywords, importantKeyword);
3443
3443
  }
3444
3444
  }
@@ -3711,13 +3711,13 @@ async function searchContexts(opts) {
3711
3711
  return tagContext(await singleSearch({ query: keywordQuery, config: searchConfig, user, role, pinnedItemIds, context: ctx }), ctx);
3712
3712
  }
3713
3713
  return [];
3714
- } catch (err2) {
3715
- if (isEmbedderNotConfigured(err2)) {
3714
+ } catch (err3) {
3715
+ if (isEmbedderNotConfigured(err3)) {
3716
3716
  console.warn(
3717
- `[EXULU pipeline] context "${ctxId}" is not searchable: ${err2.message}`
3717
+ `[EXULU pipeline] context "${ctxId}" is not searchable: ${err3.message}`
3718
3718
  );
3719
3719
  } else {
3720
- console.warn(`[EXULU pipeline] searchContexts failed for context "${ctxId}":`, err2);
3720
+ console.warn(`[EXULU pipeline] searchContexts failed for context "${ctxId}":`, err3);
3721
3721
  }
3722
3722
  return [];
3723
3723
  }
@@ -3855,8 +3855,8 @@ async function rerankResults(opts) {
3855
3855
  duplicateOf.set(a, [...duplicateOf.get(a) ?? [], b]);
3856
3856
  duplicateOf.set(b, [...duplicateOf.get(b) ?? [], a]);
3857
3857
  }
3858
- } catch (err2) {
3859
- console.warn("[EXULU pipeline] near-duplicate lookup failed \u2014 selecting without suppression:", err2);
3858
+ } catch (err3) {
3859
+ console.warn("[EXULU pipeline] near-duplicate lookup failed \u2014 selecting without suppression:", err3);
3860
3860
  duplicateOf = /* @__PURE__ */ new Map();
3861
3861
  }
3862
3862
  }
@@ -3939,15 +3939,15 @@ function makeNearDuplicateFinder(opts) {
3939
3939
  [ids, ids, threshold]
3940
3940
  );
3941
3941
  return (res.rows ?? []).map((r) => [r.a, r.b]);
3942
- } catch (err2) {
3943
- console.warn(`[EXULU pipeline] near-duplicate query failed for "${ctxId}":`, err2);
3942
+ } catch (err3) {
3943
+ console.warn(`[EXULU pipeline] near-duplicate query failed for "${ctxId}":`, err3);
3944
3944
  return [];
3945
3945
  }
3946
3946
  })
3947
3947
  );
3948
3948
  return results.flat();
3949
- } catch (err2) {
3950
- console.warn("[EXULU pipeline] near-duplicate lookup failed to acquire a database connection:", err2);
3949
+ } catch (err3) {
3950
+ console.warn("[EXULU pipeline] near-duplicate lookup failed to acquire a database connection:", err3);
3951
3951
  return [];
3952
3952
  }
3953
3953
  };
@@ -4283,10 +4283,10 @@ function createAgenticRetrievalTool(opts) {
4283
4283
  if (rerankerId && rerankerId !== "none") {
4284
4284
  try {
4285
4285
  reranker = await resolveReranker({ model: rerankerId, user, roleId: role });
4286
- } catch (err2) {
4286
+ } catch (err3) {
4287
4287
  console.warn(
4288
4288
  `[EXULU pipeline] could not resolve reranker "${rerankerId}", continuing without reranking:`,
4289
- err2
4289
+ err3
4290
4290
  );
4291
4291
  }
4292
4292
  }
@@ -4299,10 +4299,10 @@ function createAgenticRetrievalTool(opts) {
4299
4299
  rbacBypass: true
4300
4300
  });
4301
4301
  utilityModel = resolved.languageModel ?? model;
4302
- } catch (err2) {
4302
+ } catch (err3) {
4303
4303
  console.warn(
4304
4304
  `[EXULU pipeline] could not resolve utility model "${cfg.utilityModel}", falling back to agent model:`,
4305
- err2
4305
+ err3
4306
4306
  );
4307
4307
  }
4308
4308
  }
@@ -4642,8 +4642,8 @@ Verified answer:
4642
4642
  }
4643
4643
  yield { result: serializeOutput(result, hideSources) };
4644
4644
  return { result: serializeOutput(result, hideSources) };
4645
- } catch (err2) {
4646
- console.warn("[EXULU pipeline] retrieval pipeline failed:", err2);
4645
+ } catch (err3) {
4646
+ console.warn("[EXULU pipeline] retrieval pipeline failed:", err3);
4647
4647
  result.steps.push({
4648
4648
  stepNumber: 1,
4649
4649
  text: "Retrieval degraded due to an internal error \u2014 returning partial results.",
@@ -4679,7 +4679,7 @@ function sanitizeToolName(name) {
4679
4679
  }
4680
4680
 
4681
4681
  // src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts
4682
- import { randomUUID as randomUUID5 } from "crypto";
4682
+ import { randomUUID as randomUUID7 } from "crypto";
4683
4683
 
4684
4684
  // types/enums/statistics.ts
4685
4685
  var STATISTICS_TYPE_ENUM = {
@@ -5286,8 +5286,8 @@ var createUppyRoutes = async (app, config) => {
5286
5286
  const url = await getPresignedUrl(bucket, key, config);
5287
5287
  res.setHeader("Access-Control-Allow-Origin", "*");
5288
5288
  res.json({ url, method: "GET", expiresIn });
5289
- } catch (err2) {
5290
- next(err2);
5289
+ } catch (err3) {
5290
+ next(err3);
5291
5291
  }
5292
5292
  });
5293
5293
  app.post("/s3/object", async (req, res) => {
@@ -5555,9 +5555,9 @@ var createUppyRoutes = async (app, config) => {
5555
5555
  Metadata: sanitizeMetadata(metadata)
5556
5556
  };
5557
5557
  const command = new CreateMultipartUploadCommand(params);
5558
- return client.send(command, (err2, data) => {
5559
- if (err2) {
5560
- next(err2);
5558
+ return client.send(command, (err3, data) => {
5559
+ if (err3) {
5560
+ next(err3);
5561
5561
  return;
5562
5562
  }
5563
5563
  res.setHeader("Access-Control-Allow-Origin", "*");
@@ -5627,9 +5627,9 @@ var createUppyRoutes = async (app, config) => {
5627
5627
  UploadId: uploadId,
5628
5628
  PartNumberMarker: startAt
5629
5629
  }),
5630
- (err2, data) => {
5631
- if (err2) {
5632
- next(err2);
5630
+ (err3, data) => {
5631
+ if (err3) {
5632
+ next(err3);
5633
5633
  return;
5634
5634
  }
5635
5635
  parts.push(...data?.Parts ?? []);
@@ -5671,9 +5671,9 @@ var createUppyRoutes = async (app, config) => {
5671
5671
  Parts: parts
5672
5672
  }
5673
5673
  }),
5674
- (err2, data) => {
5675
- if (err2) {
5676
- next(err2);
5674
+ (err3, data) => {
5675
+ if (err3) {
5676
+ next(err3);
5677
5677
  return;
5678
5678
  }
5679
5679
  res.setHeader("Access-Control-Allow-Origin", "*");
@@ -5702,9 +5702,9 @@ var createUppyRoutes = async (app, config) => {
5702
5702
  Key: key,
5703
5703
  UploadId: uploadId
5704
5704
  }),
5705
- (err2) => {
5706
- if (err2) {
5707
- next(err2);
5705
+ (err3) => {
5706
+ if (err3) {
5707
+ next(err3);
5708
5708
  return;
5709
5709
  }
5710
5710
  res.json({
@@ -6510,10 +6510,10 @@ async function resolveEmbedder(input) {
6510
6510
  }
6511
6511
  try {
6512
6512
  await waitForLiteLLMReady();
6513
- } catch (err2) {
6513
+ } catch (err3) {
6514
6514
  throw new ResolveEmbedderError(
6515
6515
  "LITELLM_NOT_READY",
6516
- `LiteLLM is not ready: ${err2.message}`
6516
+ `LiteLLM is not ready: ${err3.message}`
6517
6517
  );
6518
6518
  }
6519
6519
  const { baseUrl, authHeaders } = resolveLiteLLMTarget();
@@ -6691,14 +6691,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
6691
6691
  for (const row of rows) {
6692
6692
  const centered = new Float64Array(dims);
6693
6693
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
6694
- const z16 = new Float64Array(basis.length);
6694
+ const z17 = new Float64Array(basis.length);
6695
6695
  for (const [b, vec] of basis.entries()) {
6696
6696
  let dot = 0;
6697
6697
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
6698
- z16[b] = dot;
6698
+ z17[b] = dot;
6699
6699
  }
6700
6700
  for (const [b, target] of next.entries()) {
6701
- const scale = z16[b] ?? 0;
6701
+ const scale = z17[b] ?? 0;
6702
6702
  if (scale === 0) continue;
6703
6703
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
6704
6704
  }
@@ -6796,12 +6796,12 @@ function ridgeFit(Z, Y, lambda) {
6796
6796
  });
6797
6797
  return { map, intercept };
6798
6798
  }
6799
- function applyMap(z16, map, intercept) {
6799
+ function applyMap(z17, map, intercept) {
6800
6800
  const out = [];
6801
6801
  for (let j = 0; j < 3; j += 1) {
6802
6802
  let v = intercept[j] ?? 0;
6803
6803
  const row = map[j] ?? [];
6804
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z16[d] ?? 0);
6804
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z17[d] ?? 0);
6805
6805
  out.push(Number.isFinite(v) ? v : 0);
6806
6806
  }
6807
6807
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -6824,8 +6824,8 @@ function fitResidual(Z, Y, map, intercept) {
6824
6824
  for (let i = 0; i < Z.length; i += 1) {
6825
6825
  const zi = Z[i] ?? [];
6826
6826
  const yi = Y[i] ?? [];
6827
- const [x, y, z16] = applyMap(zi, map, intercept);
6828
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z16 - finite(yi[2]));
6827
+ const [x, y, z17] = applyMap(zi, map, intercept);
6828
+ total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z17 - finite(yi[2]));
6829
6829
  }
6830
6830
  return finite(total / Z.length);
6831
6831
  }
@@ -6965,8 +6965,8 @@ async function chunkCoordinates({
6965
6965
  }
6966
6966
  return null;
6967
6967
  }
6968
- const [x, y, z16] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6969
- return { x, y, z: z16 };
6968
+ const [x, y, z17] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6969
+ return { x, y, z: z17 };
6970
6970
  });
6971
6971
  } catch (e) {
6972
6972
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -6997,10 +6997,10 @@ var getEmbedderSetting = async (contextId) => {
6997
6997
  model: model.trim(),
6998
6998
  queue: typeof queue === "string" && queue.trim() ? queue.trim() : null
6999
6999
  };
7000
- } catch (err2) {
7000
+ } catch (err3) {
7001
7001
  console.warn(
7002
7002
  `[EXULU] Could not read the embedder setting for "${contextId}":`,
7003
- err2.message
7003
+ err3.message
7004
7004
  );
7005
7005
  return null;
7006
7006
  }
@@ -7073,9 +7073,9 @@ var hydrateContextEmbedders = async (contexts, deps = {}) => {
7073
7073
  }
7074
7074
  try {
7075
7075
  modelInfo(info.databaseModel);
7076
- } catch (err2) {
7076
+ } catch (err3) {
7077
7077
  console.error(
7078
- `[EXULU] Context "${context.id}" has a stored embedder "${info.databaseModel}" that is not a usable embedding model (${err2.message.split("\n")[0]}). Ignoring the override and falling back to the model declared in code${info.codeModel ? ` ("${info.codeModel}")` : " (none)"}.`
7078
+ `[EXULU] Context "${context.id}" has a stored embedder "${info.databaseModel}" that is not a usable embedding model (${err3.message.split("\n")[0]}). Ignoring the override and falling back to the model declared in code${info.codeModel ? ` ("${info.codeModel}")` : " (none)"}.`
7079
7079
  );
7080
7080
  context.embedder = codeEmbedder;
7081
7081
  continue;
@@ -7094,10 +7094,10 @@ var hydrateContextEmbedders = async (contexts, deps = {}) => {
7094
7094
  }
7095
7095
  }
7096
7096
  context.embedder = { model: info.databaseModel, queue };
7097
- } catch (err2) {
7097
+ } catch (err3) {
7098
7098
  console.error(
7099
7099
  `[EXULU] Could not hydrate the embedder for context "${context.id}":`,
7100
- err2.message
7100
+ err3.message
7101
7101
  );
7102
7102
  }
7103
7103
  }
@@ -7535,8 +7535,8 @@ var hydrateEntityTypes = async (context) => {
7535
7535
  description: row.description || ""
7536
7536
  });
7537
7537
  }
7538
- } catch (err2) {
7539
- console.warn("[EXULU] Could not read entity_type_settings:", err2.message);
7538
+ } catch (err3) {
7539
+ console.warn("[EXULU] Could not read entity_type_settings:", err3.message);
7540
7540
  }
7541
7541
  return Array.from(byName.values());
7542
7542
  };
@@ -7565,10 +7565,10 @@ var upsertEntitySuggestions = async (context, suggestions) => {
7565
7565
  if (rows.length) {
7566
7566
  await db2.from("entity_type_settings").insert(rows);
7567
7567
  }
7568
- } catch (err2) {
7568
+ } catch (err3) {
7569
7569
  console.warn(
7570
7570
  "[EXULU] Could not persist entity suggestions:",
7571
- err2.message
7571
+ err3.message
7572
7572
  );
7573
7573
  }
7574
7574
  };
@@ -7588,8 +7588,8 @@ var getEntityModelSetting = async (contextId) => {
7588
7588
  }
7589
7589
  }
7590
7590
  return typeof value === "string" && value.trim() ? value.trim() : null;
7591
- } catch (err2) {
7592
- console.warn("[EXULU] Could not read entity model setting:", err2.message);
7591
+ } catch (err3) {
7592
+ console.warn("[EXULU] Could not read entity model setting:", err3.message);
7593
7593
  return null;
7594
7594
  }
7595
7595
  };
@@ -7714,10 +7714,10 @@ var extractEntitiesForItem = async ({
7714
7714
  rbacBypass: true
7715
7715
  });
7716
7716
  languageModel = resolved.languageModel;
7717
- } catch (err2) {
7717
+ } catch (err3) {
7718
7718
  console.error(
7719
7719
  `[EXULU] Entity extraction skipped for context ${context.id}: could not resolve model ${modelId}:`,
7720
- err2.message
7720
+ err3.message
7721
7721
  );
7722
7722
  return empty;
7723
7723
  }
@@ -7782,10 +7782,10 @@ var extractEntitiesForItem = async ({
7782
7782
  });
7783
7783
  }
7784
7784
  }
7785
- } catch (err2) {
7785
+ } catch (err3) {
7786
7786
  console.error(
7787
7787
  `[EXULU] Entity extraction batch failed for context ${context.id} (continuing):`,
7788
- err2.message
7788
+ err3.message
7789
7789
  );
7790
7790
  }
7791
7791
  }
@@ -8130,8 +8130,8 @@ var captureEntitiesBeforeReembed = async (context, itemId) => {
8130
8130
  try {
8131
8131
  if (!await chunkEntitiesTableExists(context)) return [];
8132
8132
  return await getEntityIdsForItem(context, itemId);
8133
- } catch (err2) {
8134
- console.error("[EXULU] captureEntitiesBeforeReembed failed (continuing):", err2.message);
8133
+ } catch (err3) {
8134
+ console.error("[EXULU] captureEntitiesBeforeReembed failed (continuing):", err3.message);
8135
8135
  return [];
8136
8136
  }
8137
8137
  };
@@ -8161,10 +8161,10 @@ var extractAndIngestEntities = async ({
8161
8161
  `[EXULU] Entity ingestion complete for item ${itemId} in context ${context.id}: ${mentions.length} mentions.`
8162
8162
  );
8163
8163
  return mentions.length;
8164
- } catch (err2) {
8164
+ } catch (err3) {
8165
8165
  console.error(
8166
8166
  `[EXULU] Entity ingestion failed for item ${itemId} in context ${context.id} (non-fatal):`,
8167
- err2.message
8167
+ err3.message
8168
8168
  );
8169
8169
  return 0;
8170
8170
  }
@@ -8545,8 +8545,8 @@ var vectorSearch = async ({
8545
8545
  return { r, score: base + boost };
8546
8546
  }).sort((a, b) => b.score - a.score).map((x) => x.r);
8547
8547
  }
8548
- } catch (err2) {
8549
- console.error("[EXULU] Entity boost step failed (continuing):", err2.message);
8548
+ } catch (err3) {
8549
+ console.error("[EXULU] Entity boost step failed (continuing):", err3.message);
8550
8550
  }
8551
8551
  }
8552
8552
  results = results.slice(0, limit);
@@ -8573,8 +8573,8 @@ var vectorSearch = async ({
8573
8573
  results = results.map((r) => ({ ...r, chunk_entities: entMap.get(r.chunk_id) || [] }));
8574
8574
  }
8575
8575
  entityInsights = queryEntities.length ? await buildEntityInsights(context, queryEntities, finalIds) : { queryEntities: [] };
8576
- } catch (err2) {
8577
- console.error("[EXULU] Entity insights step failed (continuing):", err2.message);
8576
+ } catch (err3) {
8577
+ console.error("[EXULU] Entity insights step failed (continuing):", err3.message);
8578
8578
  }
8579
8579
  }
8580
8580
  await updateStatistic({
@@ -8740,8 +8740,8 @@ async function maybePruneJobResults(db2) {
8740
8740
  );
8741
8741
  }
8742
8742
  }
8743
- } catch (err2) {
8744
- console.error("[EXULU] job_results prune failed", err2);
8743
+ } catch (err3) {
8744
+ console.error("[EXULU] job_results prune failed", err3);
8745
8745
  } finally {
8746
8746
  pruning = false;
8747
8747
  }
@@ -8816,8 +8816,8 @@ var bullmqDecorator = async ({
8816
8816
  metadata: {}
8817
8817
  });
8818
8818
  void maybePruneJobResults(db2);
8819
- } catch (err2) {
8820
- console.error("[EXULU] enqueue job_results insert failed", err2);
8819
+ } catch (err3) {
8820
+ console.error("[EXULU] enqueue job_results insert failed", err3);
8821
8821
  }
8822
8822
  }
8823
8823
  const job = await queue.add(`${embedder || workflow || processor || evaluation}`, jobData, {
@@ -11784,6 +11784,13 @@ function collectMemoryDecisions(messages) {
11784
11784
 
11785
11785
  // src/templates/tools/context-write-tools.ts
11786
11786
  import { z as z11 } from "zod";
11787
+ import { randomUUID as randomUUID3 } from "crypto";
11788
+
11789
+ // src/exulu/session-files.ts
11790
+ function sessionFilePrefix(ownerId, sessionId, s3prefix) {
11791
+ const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
11792
+ return `${general}user_${ownerId}/sessions/${sessionId}/`;
11793
+ }
11787
11794
 
11788
11795
  // src/utils/check-item-write-access.ts
11789
11796
  var checkItemWriteAccess = async (context, record, user) => {
@@ -11927,6 +11934,7 @@ var RESERVED_INPUT_KEYS = /* @__PURE__ */ new Set([
11927
11934
  var buildWriteSchema = (context, mode) => {
11928
11935
  const shape = {};
11929
11936
  const contentKeys = [];
11937
+ const fileFields = [];
11930
11938
  const addContent = (key, schema, required) => {
11931
11939
  shape[key] = required && mode === "create" ? schema : schema.optional();
11932
11940
  contentKeys.push(key);
@@ -11946,10 +11954,21 @@ var buildWriteSchema = (context, mode) => {
11946
11954
  );
11947
11955
  }
11948
11956
  for (const field of context.fields ?? []) {
11949
- if (field.type === "file" || field.type === "uuid") continue;
11957
+ if (field.type === "uuid") continue;
11950
11958
  if (field.calculated === true || field.editable === false) continue;
11951
11959
  if (field.hidden === true) continue;
11952
11960
  if (RESERVED_INPUT_KEYS.has(field.name)) continue;
11961
+ if (field.type === "file") {
11962
+ const allowed = (field.allowedFileTypes ?? []).map((ext) => ext.toLowerCase());
11963
+ const column = `${field.name}_s3key`;
11964
+ const allowedNote = allowed.length ? ` Allowed types: ${allowed.join(", ")}.` : "";
11965
+ shape[field.name] = (field.required === true && mode === "create" ? z11.string() : z11.string().optional()).describe(
11966
+ `The ${field.name} file: the bare name of a file from this session's files (as listed there, no path).${allowedNote}` + (mode === "update" ? " Omit to keep the current file." : "")
11967
+ );
11968
+ contentKeys.push(column);
11969
+ fileFields.push({ input: field.name, column, allowed });
11970
+ continue;
11971
+ }
11953
11972
  let schema;
11954
11973
  switch (field.type) {
11955
11974
  case "enum":
@@ -11978,7 +11997,45 @@ var buildWriteSchema = (context, mode) => {
11978
11997
  }
11979
11998
  addContent(field.name, schema, field.required === true);
11980
11999
  }
11981
- return { shape, contentKeys };
12000
+ return { shape, contentKeys, fileFields };
12001
+ };
12002
+ var BARE_FILENAME = /^[^/\\]+$/;
12003
+ var attachSessionFiles = async (params, fileFields, deps) => {
12004
+ const wanted = fileFields.filter((f) => typeof params[f.input] === "string" && params[f.input].trim() !== "");
12005
+ if (wanted.length === 0) return void 0;
12006
+ const { user, sessionID, exuluConfig } = params;
12007
+ const uploads = exuluConfig?.fileUploads;
12008
+ if (!uploads?.s3Bucket) {
12009
+ return "File uploads are not configured on this instance, so files cannot be attached to items.";
12010
+ }
12011
+ if (!sessionID) {
12012
+ return "Files can only be attached from a chat session's files.";
12013
+ }
12014
+ const copy = deps.copyObject ?? copyS3Object;
12015
+ const general = uploads.s3prefix ? `${uploads.s3prefix.replace(/\/+$/, "")}/` : "";
12016
+ const owner = user?.type === "api" ? "api" : user?.id;
12017
+ for (const field of wanted) {
12018
+ const name = String(params[field.input]).trim();
12019
+ if (!BARE_FILENAME.test(name) || name === "." || name === "..") {
12020
+ return `"${name}" is not a session file name. Pass the bare file name exactly as listed in the session files, without a path.`;
12021
+ }
12022
+ const dot = name.lastIndexOf(".");
12023
+ const ext = dot >= 0 ? name.slice(dot).toLowerCase() : "";
12024
+ if (field.allowed.length && !field.allowed.includes(ext)) {
12025
+ return `"${name}" has type "${ext || "none"}", but the ${field.input} field only accepts ${field.allowed.join(", ")}.`;
12026
+ }
12027
+ const sourceKey = `${sessionFilePrefix(deps.sessionOwnerId ?? owner ?? "api", sessionID, uploads.s3prefix)}${name}`;
12028
+ const destKey = `${general}user_${owner}/${randomUUID3()}-_EXULU_${name}`;
12029
+ try {
12030
+ await copy(sourceKey, destKey, exuluConfig);
12031
+ } catch (error) {
12032
+ console.error(`[EXULU] KB editor: copying session file "${name}" failed`, error);
12033
+ return `"${name}" is not among this session's files. Upload it to the session (or ask the user to attach it) and try again.`;
12034
+ }
12035
+ params[field.column] = destKey;
12036
+ delete params[field.input];
12037
+ }
12038
+ return void 0;
11982
12039
  };
11983
12040
  var canonicalizeEnumFields = (context, params) => {
11984
12041
  for (const field of context.fields ?? []) {
@@ -12004,18 +12061,19 @@ var pickContent = (params, contentKeys) => {
12004
12061
  return item;
12005
12062
  };
12006
12063
  var jobNote = (job) => job ? ` Processing/embeddings queued (job: ${job}); changes become searchable when the job completes.` : "";
12007
- var createContextWriteTools = (context, perms, skipApproval) => {
12064
+ var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
12008
12065
  const tools = [];
12009
12066
  const segment = sanitizeName(context.id).slice(0, MAX_CONTEXT_SEGMENT);
12010
12067
  const contextLabel = context.description ? ` ${context.description}` : "";
12011
12068
  if (perms.create) {
12012
- const { shape, contentKeys } = buildWriteSchema(context, "create");
12069
+ const { shape, contentKeys, fileFields } = buildWriteSchema(context, "create");
12070
+ const fileNote = fileFields.length ? " File fields take the name of a file from this session's files." : "";
12013
12071
  tools.push(
12014
12072
  new ExuluTool({
12015
12073
  id: `create_${segment}_item`,
12016
12074
  name: `Create ${context.name} item`,
12017
12075
  category: "knowledge_base_editing",
12018
- description: `Create a new item in the "${context.name}" knowledge base.${contextLabel}`,
12076
+ description: `Create a new item in the "${context.name}" knowledge base.${contextLabel}${fileNote}`,
12019
12077
  type: "function",
12020
12078
  inputSchema: z11.object(shape),
12021
12079
  config: [],
@@ -12030,6 +12088,10 @@ var createContextWriteTools = (context, perms, skipApproval) => {
12030
12088
  if (enumError) {
12031
12089
  return { result: enumError };
12032
12090
  }
12091
+ const fileError = await attachSessionFiles(params, fileFields, deps);
12092
+ if (fileError) {
12093
+ return { result: fileError };
12094
+ }
12033
12095
  const item = pickContent(params, contentKeys);
12034
12096
  item.created_by = String(user.id);
12035
12097
  const { item: created, job } = await context.createItem(
@@ -12056,14 +12118,15 @@ var createContextWriteTools = (context, perms, skipApproval) => {
12056
12118
  );
12057
12119
  }
12058
12120
  if (perms.update) {
12059
- const { shape, contentKeys } = buildWriteSchema(context, "update");
12121
+ const { shape, contentKeys, fileFields } = buildWriteSchema(context, "update");
12122
+ const fileNote = fileFields.length ? " File fields take the name of a file from this session's files; omit them to keep the current file." : "";
12060
12123
  const NOT_FOUND = `Item not found in "${context.name}" or you don't have write access to it.`;
12061
12124
  tools.push(
12062
12125
  new ExuluTool({
12063
12126
  id: `update_${segment}_item`,
12064
12127
  name: `Update ${context.name} item`,
12065
12128
  category: "knowledge_base_editing",
12066
- description: `Update an existing item in the "${context.name}" knowledge base. Provide the item's id (or external_id) plus only the fields to change; omitted fields keep their values.`,
12129
+ description: `Update an existing item in the "${context.name}" knowledge base. Provide the item's id (or external_id) plus only the fields to change; omitted fields keep their values.${fileNote}`,
12067
12130
  type: "function",
12068
12131
  inputSchema: z11.object(shape),
12069
12132
  config: [],
@@ -12091,6 +12154,10 @@ var createContextWriteTools = (context, perms, skipApproval) => {
12091
12154
  if (enumError) {
12092
12155
  return { result: enumError };
12093
12156
  }
12157
+ const fileError = await attachSessionFiles(params, fileFields, deps);
12158
+ if (fileError) {
12159
+ return { result: fileError };
12160
+ }
12094
12161
  const patch = pickContent(params, contentKeys);
12095
12162
  if (Object.keys(patch).length === 0) {
12096
12163
  return { result: "No fields to update were provided." };
@@ -12124,7 +12191,7 @@ var createKbEditorPickerTool = () => new ExuluTool({
12124
12191
  id: KB_EDITOR_TOOL_ID,
12125
12192
  name: "Knowledge base editor",
12126
12193
  category: "default",
12127
- description: "Let this agent create or update items in selected knowledge bases during chat. Configure per knowledge base whether the agent may create and/or update items.",
12194
+ description: "Let this agent create or update items in selected knowledge bases during chat, including attaching files from the session's files to file fields. Configure per knowledge base whether the agent may create and/or update items.",
12128
12195
  type: "function",
12129
12196
  inputSchema: z11.object({}),
12130
12197
  config: [
@@ -12144,7 +12211,7 @@ var createKbEditorPickerTool = () => new ExuluTool({
12144
12211
  result: "This entry is configuration-only; Exulu expands it into per-context create/update tools at runtime."
12145
12212
  })
12146
12213
  });
12147
- var collectKbWriteTools = (agent, contexts) => {
12214
+ var collectKbWriteTools = (agent, contexts, deps = {}) => {
12148
12215
  if (!agent?.tools || !contexts?.length) {
12149
12216
  return [];
12150
12217
  }
@@ -12158,10 +12225,553 @@ var collectKbWriteTools = (agent, contexts) => {
12158
12225
  if (!context) {
12159
12226
  continue;
12160
12227
  }
12161
- tools.push(...createContextWriteTools(context, perms, config.skipApproval));
12228
+ tools.push(...createContextWriteTools(context, perms, config.skipApproval, deps));
12229
+ }
12230
+ return tools;
12231
+ };
12232
+
12233
+ // src/templates/tools/skill-author-tools.ts
12234
+ import { randomUUID as randomUUID4 } from "crypto";
12235
+ import { z as z12 } from "zod";
12236
+
12237
+ // ee/rbac-resolver.ts
12238
+ var RBACResolver = async (db2, entityName, resourceId, rights_mode) => {
12239
+ const license = checkLicense();
12240
+ if (!license.rbac) {
12241
+ return {
12242
+ type: "public",
12243
+ users: [],
12244
+ roles: [],
12245
+ teams: []
12246
+ };
12247
+ }
12248
+ const rbacRecords = await db2.from("rbac").where({
12249
+ entity: entityName,
12250
+ target_resource_id: resourceId
12251
+ }).select("*");
12252
+ const users = rbacRecords.filter((r) => r.access_type === "User")?.map((r) => ({ id: r.user_id, rights: r.rights }));
12253
+ const roles = rbacRecords.filter((r) => r.access_type === "Role")?.map((r) => ({ id: r.role_id, rights: r.rights }));
12254
+ const teams = rbacRecords.filter((r) => r.access_type === "Team")?.map((r) => ({ id: r.team_id, rights: r.rights }));
12255
+ let type = rights_mode || "private";
12256
+ if (type === "users" && users.length === 0) type = "private";
12257
+ if (type === "roles" && roles.length === 0) type = "private";
12258
+ if (type === "teams" && teams.length === 0) type = "private";
12259
+ return {
12260
+ type,
12261
+ users,
12262
+ roles,
12263
+ teams
12264
+ };
12265
+ };
12266
+
12267
+ // src/utils/check-record-access.ts
12268
+ var checkRecordAccessCache = /* @__PURE__ */ new Map();
12269
+ var checkRecordAccess = async (record, request, user) => {
12270
+ const setRecordAccessCache = (hasAccess2) => {
12271
+ checkRecordAccessCache.set(`${record.id}-${request}-${user?.id}`, {
12272
+ hasAccess: hasAccess2,
12273
+ expiresAt: new Date(Date.now() + 1e3 * 60 * 1)
12274
+ // 1 minute
12275
+ });
12276
+ };
12277
+ const cachedAccess = checkRecordAccessCache.get(`${record.id}-${request}-${user?.id}`);
12278
+ if (cachedAccess && cachedAccess.expiresAt > /* @__PURE__ */ new Date()) {
12279
+ return cachedAccess.hasAccess;
12280
+ }
12281
+ const isPublic = record.rights_mode === "public";
12282
+ const byUsers = record.rights_mode === "users";
12283
+ const byRoles = record.rights_mode === "roles";
12284
+ const byTeams = record.rights_mode === "teams";
12285
+ const createdBy = typeof record.created_by === "string" ? record.created_by : record.created_by?.toString();
12286
+ const isCreator = user ? createdBy === user.id.toString() : false;
12287
+ const isAdmin = user ? user.super_admin : false;
12288
+ const isApi = user ? user.type === "api" : false;
12289
+ const isAdminApi = isApi && (!user.scope_mode || user.scope_mode === "admin");
12290
+ const isAgentsScopedApi = isApi && user.scope_mode === "agents" && request === "read" && Array.isArray(user.agent_ids) && user.agent_ids.includes(String(record.id));
12291
+ let hasAccess = "none";
12292
+ if (isPublic || isCreator || isAdmin || isAdminApi || isAgentsScopedApi) {
12293
+ setRecordAccessCache(true);
12294
+ return true;
12295
+ }
12296
+ if (byUsers) {
12297
+ if (!user) {
12298
+ setRecordAccessCache(false);
12299
+ return false;
12300
+ }
12301
+ hasAccess = record.RBAC?.users?.find((x) => x.id === user.id)?.rights || "none";
12302
+ if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
12303
+ console.error(
12304
+ `[EXULU] Your current user ${user.id} does not have access to this record, current access type is: ${hasAccess}.`
12305
+ );
12306
+ setRecordAccessCache(false);
12307
+ return false;
12308
+ } else {
12309
+ setRecordAccessCache(true);
12310
+ return true;
12311
+ }
12312
+ }
12313
+ if (byRoles) {
12314
+ if (!user) {
12315
+ setRecordAccessCache(false);
12316
+ return false;
12317
+ }
12318
+ hasAccess = record.RBAC?.roles?.find((x) => x.id === user.role?.id)?.rights || "none";
12319
+ if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
12320
+ console.error(
12321
+ `[EXULU] Your current role ${user.role?.name} does not have access to this record, current access type is: ${hasAccess}.`
12322
+ );
12323
+ setRecordAccessCache(false);
12324
+ return false;
12325
+ } else {
12326
+ setRecordAccessCache(true);
12327
+ return true;
12328
+ }
12329
+ }
12330
+ if (byTeams) {
12331
+ if (!user) {
12332
+ setRecordAccessCache(false);
12333
+ return false;
12334
+ }
12335
+ hasAccess = record.RBAC?.teams?.find((x) => x.id === user.team?.id)?.rights || "none";
12336
+ if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
12337
+ console.error(
12338
+ `[EXULU] Your current team ${user.team?.name} does not have access to this record, current access type is: ${hasAccess}.`
12339
+ );
12340
+ setRecordAccessCache(false);
12341
+ return false;
12342
+ } else {
12343
+ setRecordAccessCache(true);
12344
+ return true;
12345
+ }
12346
+ }
12347
+ setRecordAccessCache(false);
12348
+ return false;
12349
+ };
12350
+
12351
+ // src/skills/skill-access.ts
12352
+ async function resolveSkillByName(db2, name) {
12353
+ const row = await db2("skills").where({ name }).first();
12354
+ return row ?? null;
12355
+ }
12356
+ async function canAccessSkill(db2, skill, action, user) {
12357
+ const rbac = await RBACResolver(db2, "skill", skill.id, skill.rights_mode || "private");
12358
+ return checkRecordAccess({ ...skill, RBAC: rbac }, action, user);
12359
+ }
12360
+ async function filterReadableSkills(db2, skills, user) {
12361
+ const out = [];
12362
+ for (const s of skills) {
12363
+ if (await canAccessSkill(db2, s, "read", user)) out.push(s);
12364
+ }
12365
+ return out;
12366
+ }
12367
+
12368
+ // src/skills/frontmatter.ts
12369
+ import JSZip from "jszip";
12370
+ function parseFrontmatter(md) {
12371
+ const match = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(md);
12372
+ if (!match) return {};
12373
+ const block = match[1];
12374
+ const out = {};
12375
+ for (const line of block.split(/\r?\n/)) {
12376
+ const m = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
12377
+ if (!m) continue;
12378
+ const key = m[1];
12379
+ let v = m[2].trim();
12380
+ if (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'")) {
12381
+ v = v.slice(1, -1);
12382
+ }
12383
+ out[key] = v;
12384
+ }
12385
+ return out;
12386
+ }
12387
+ async function parseSkillFrontmatter(zipBytes) {
12388
+ let zip;
12389
+ try {
12390
+ zip = await JSZip.loadAsync(zipBytes);
12391
+ } catch {
12392
+ return {};
12393
+ }
12394
+ const paths = [];
12395
+ zip.forEach((p, entry) => {
12396
+ if (!entry.dir) paths.push(p);
12397
+ });
12398
+ const heads = new Set(paths.map((p) => p.split("/")[0]).filter(Boolean));
12399
+ let strip = (p) => p;
12400
+ if (heads.size === 1) {
12401
+ const head = [...heads][0] + "/";
12402
+ if (paths.every((p) => p.startsWith(head))) strip = (p) => p.slice(head.length);
12403
+ }
12404
+ const skillPath = paths.find((p) => strip(p) === "SKILL.md");
12405
+ if (!skillPath) return {};
12406
+ const md = await zip.file(skillPath).async("string");
12407
+ const fm = parseFrontmatter(md);
12408
+ return { name: fm.name, description: fm.description };
12409
+ }
12410
+
12411
+ // src/templates/tools/skill-author-config.ts
12412
+ var SKILL_AUTHOR_TOOL_ID = "skill_author";
12413
+ var asBool = (v, fallback) => {
12414
+ if (typeof v === "boolean") return v;
12415
+ if (typeof v === "string") {
12416
+ if (v.toLowerCase() === "true") return true;
12417
+ if (v.toLowerCase() === "false") return false;
12418
+ }
12419
+ return fallback;
12420
+ };
12421
+ var parseSkillAuthorConfig = (tools) => {
12422
+ const off = { enabled: false, create: false, update: false, skipApproval: false };
12423
+ let entries = tools;
12424
+ if (typeof entries === "string") {
12425
+ try {
12426
+ entries = JSON.parse(entries);
12427
+ } catch {
12428
+ return off;
12429
+ }
12430
+ }
12431
+ if (!Array.isArray(entries)) return off;
12432
+ const entry = entries.find((t) => t?.id === SKILL_AUTHOR_TOOL_ID);
12433
+ if (!entry) return off;
12434
+ const raw = (name) => {
12435
+ const row = Array.isArray(entry.config) ? entry.config.find((c) => c?.name === name) : void 0;
12436
+ return row?.value ?? row?.variable ?? row?.default;
12437
+ };
12438
+ return {
12439
+ enabled: true,
12440
+ create: asBool(raw("create"), true),
12441
+ update: asBool(raw("update"), true),
12442
+ skipApproval: asBool(raw("skip_approval"), false)
12443
+ };
12444
+ };
12445
+ var SKILL_AUTHOR_PROMPT = [
12446
+ "Skill authoring: you can turn a procedure into a reusable skill with skill_create, and improve an existing one with skill_update (skill_list and skill_read show what exists).",
12447
+ "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.",
12448
+ "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.",
12449
+ "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.",
12450
+ "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."
12451
+ ].join(" ");
12452
+
12453
+ // src/templates/tools/skill-author-tools.ts
12454
+ var MAX_FILES = 100;
12455
+ var MAX_FILE_BYTES = 200 * 1024;
12456
+ var MAX_READ_BYTES = 60 * 1024;
12457
+ var defaultIo = () => ({
12458
+ upload: (bytes, key, config, contentType) => uploadFile(bytes, key, config, { contentType }, void 0, void 0, true),
12459
+ list: (prefix, config) => listS3ObjectsByPrefix(prefix, config),
12460
+ copy: (a, b, config) => copyS3Object(a, b, config),
12461
+ remove: (key, config) => deleteS3Object(key, config),
12462
+ read: (key, config) => getS3ObjectContent(key, config)
12463
+ });
12464
+ var err2 = (result) => ({ type: "skill_error", result });
12465
+ var safeSkillPath = (raw) => {
12466
+ const p = String(raw ?? "").trim().replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+/, "");
12467
+ if (!p || p.length > 200) return null;
12468
+ if (/[\x00-\x1f\x7f]/.test(p)) return null;
12469
+ if (p.split("/").some((seg) => seg === "" || seg === "." || seg === "..")) return null;
12470
+ return p;
12471
+ };
12472
+ var contentTypeFor = (path3) => {
12473
+ const ext = path3.slice(path3.lastIndexOf(".") + 1).toLowerCase();
12474
+ const types = {
12475
+ md: "text/markdown",
12476
+ txt: "text/plain",
12477
+ json: "application/json",
12478
+ html: "text/html",
12479
+ csv: "text/csv",
12480
+ py: "text/x-python",
12481
+ sh: "text/x-shellscript",
12482
+ js: "text/javascript",
12483
+ ts: "text/typescript",
12484
+ yaml: "text/yaml",
12485
+ yml: "text/yaml"
12486
+ };
12487
+ return types[ext] ?? "text/plain";
12488
+ };
12489
+ var yamlString = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, " ")}"`;
12490
+ var ensureFrontmatter = (content, name, description) => {
12491
+ if (/^---\s*\n/.test(content)) return content;
12492
+ return `---
12493
+ name: ${yamlString(name)}
12494
+ description: ${yamlString(description)}
12495
+ ---
12496
+
12497
+ ${content.replace(/^\s+/, "")}`;
12498
+ };
12499
+ var generalPrefix = (config) => config?.fileUploads?.s3prefix ? `${String(config.fileUploads.s3prefix).replace(/\/+$/, "")}/` : "";
12500
+ var relativePaths = (keys, config, prefix) => keys.map((f) => f.key.replace(generalPrefix(config) + prefix, "")).filter((p) => p && !p.endsWith("/"));
12501
+ async function resolveSkill(db2, ref) {
12502
+ const value = String(ref ?? "").trim();
12503
+ if (!value) return null;
12504
+ const byId = /^[0-9a-f-]{36}$/i.test(value) ? await db2("skills").where({ id: value }).first() : null;
12505
+ return byId ?? await resolveSkillByName(db2, value);
12506
+ }
12507
+ var normalizeFiles = (raw) => {
12508
+ if (!Array.isArray(raw)) return { files: [] };
12509
+ if (raw.length > MAX_FILES) return { error: `At most ${MAX_FILES} files per call.` };
12510
+ const files = [];
12511
+ for (const entry of raw) {
12512
+ const path3 = safeSkillPath(entry?.path);
12513
+ const content = typeof entry?.content === "string" ? entry.content : null;
12514
+ if (!path3) return { error: `"${String(entry?.path ?? "")}" is not a valid file path inside the skill (relative, no "..").` };
12515
+ if (content === null) return { error: `File "${path3}" has no text content.` };
12516
+ if (Buffer.byteLength(content, "utf8") > MAX_FILE_BYTES) return { error: `File "${path3}" is larger than ${MAX_FILE_BYTES / 1024} KB.` };
12517
+ files.push({ path: path3, content });
12518
+ }
12519
+ return { files };
12520
+ };
12521
+ var createSkillAuthorTools = (agent, deps = {}) => {
12522
+ const config = parseSkillAuthorConfig(agent.tools);
12523
+ if (!config.enabled) return [];
12524
+ const io = { ...defaultIo(), ...deps.io ?? {} };
12525
+ const getDb = deps.db ?? (async () => (await postgresClient()).db);
12526
+ const now = deps.now ?? (() => /* @__PURE__ */ new Date());
12527
+ const category = `${agent.name}_skills`;
12528
+ const approvalFn = config.skipApproval ? void 0 : async () => true;
12529
+ const tools = [];
12530
+ tools.push(
12531
+ new ExuluTool({
12532
+ id: "skill_list",
12533
+ name: "skill_list",
12534
+ category,
12535
+ type: "function",
12536
+ config: [],
12537
+ needsApproval: false,
12538
+ 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.",
12539
+ inputSchema: z12.object({ query: z12.string().optional().describe("Optional substring to filter by name or description") }),
12540
+ execute: async (params) => {
12541
+ const { user } = params;
12542
+ if (!user?.id) return err2("Skills require a signed-in user.");
12543
+ const db2 = await getDb();
12544
+ const rows = await db2("skills").select("id", "name", "description", "current_version", "rights_mode", "created_by");
12545
+ const readable = await filterReadableSkills(db2, rows, user);
12546
+ const q = String(params.query ?? "").trim().toLowerCase();
12547
+ const skills = readable.filter((s) => !q || `${s.name} ${s.description ?? ""}`.toLowerCase().includes(q)).map((s) => ({ id: s.id, name: s.name, description: s.description ?? "", version: s.current_version ?? 1 }));
12548
+ return {
12549
+ type: "skill_list",
12550
+ skills,
12551
+ result: skills.length ? skills.map((s) => `${s.name} (v${s.version}): ${s.description}`).join("\n") : "No skills found."
12552
+ };
12553
+ }
12554
+ })
12555
+ );
12556
+ tools.push(
12557
+ new ExuluTool({
12558
+ id: "skill_read",
12559
+ name: "skill_read",
12560
+ category,
12561
+ type: "function",
12562
+ config: [],
12563
+ needsApproval: false,
12564
+ 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.",
12565
+ inputSchema: z12.object({
12566
+ skill: z12.string().describe("The skill's name or id"),
12567
+ path: z12.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
12568
+ }),
12569
+ execute: async (params) => {
12570
+ const { user, exuluConfig } = params;
12571
+ if (!user?.id) return err2("Skills require a signed-in user.");
12572
+ const db2 = await getDb();
12573
+ const skill = await resolveSkill(db2, params.skill);
12574
+ if (!skill || !await canAccessSkill(db2, skill, "read", user)) {
12575
+ return { type: "skill_no_access", skill: String(params.skill), result: `No skill "${params.skill}" that you can read.` };
12576
+ }
12577
+ const version = skill.current_version ?? 1;
12578
+ const prefix = `skills/${skill.id}/v${version}/`;
12579
+ const files = relativePaths(await io.list(prefix, exuluConfig), exuluConfig, prefix);
12580
+ const path3 = params.path ? safeSkillPath(params.path) : "SKILL.md";
12581
+ if (!path3) return err2(`"${params.path}" is not a valid path inside the skill.`);
12582
+ if (!files.includes(path3)) return err2(`The skill has no file "${path3}". Files: ${files.join(", ") || "(none)"}`);
12583
+ let content = await io.read(generalPrefix(exuluConfig) + prefix + path3, exuluConfig);
12584
+ if (Buffer.byteLength(content, "utf8") > MAX_READ_BYTES) content = content.slice(0, MAX_READ_BYTES) + "\n\u2026(truncated)";
12585
+ return {
12586
+ type: "skill_read",
12587
+ skillId: skill.id,
12588
+ name: skill.name,
12589
+ version,
12590
+ files,
12591
+ path: path3,
12592
+ content,
12593
+ result: `Skill "${skill.name}" v${version}, files: ${files.join(", ")}
12594
+
12595
+ --- ${path3} ---
12596
+ ${content}`
12597
+ };
12598
+ }
12599
+ })
12600
+ );
12601
+ if (config.create) {
12602
+ tools.push(
12603
+ new ExuluTool({
12604
+ id: "skill_create",
12605
+ name: "skill_create",
12606
+ category,
12607
+ type: "function",
12608
+ config: [],
12609
+ needsApproval: !config.skipApproval,
12610
+ needsApprovalFn: approvalFn,
12611
+ 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.",
12612
+ inputSchema: z12.object({
12613
+ name: z12.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
12614
+ description: z12.string().describe("One line: what the skill does and when to use it"),
12615
+ files: z12.array(z12.object({ path: z12.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z12.string() })).min(1).describe("The skill's files; SKILL.md is required")
12616
+ }),
12617
+ execute: async (params) => {
12618
+ const { user, exuluConfig } = params;
12619
+ if (!user?.id) return err2("Skills require a signed-in user.");
12620
+ if (!exuluConfig?.fileUploads) return err2("File uploads are not configured on this instance, so skills cannot be stored.");
12621
+ const decision = params.skillDecision?.kind === "create" ? params.skillDecision : void 0;
12622
+ const name = String(decision?.name ?? params.name ?? "").trim();
12623
+ const description = String(decision?.description ?? params.description ?? "").trim();
12624
+ if (!name || name.length > 80) return err2("A skill needs a name of at most 80 characters.");
12625
+ const parsed = normalizeFiles(params.files);
12626
+ if ("error" in parsed) return err2(parsed.error);
12627
+ const files = parsed.files;
12628
+ const skillMd = files.find((f) => f.path === "SKILL.md");
12629
+ if (!skillMd) return err2("A skill needs a SKILL.md at its root.");
12630
+ skillMd.content = ensureFrontmatter(skillMd.content, name, description);
12631
+ const db2 = await getDb();
12632
+ if (await resolveSkillByName(db2, name)) return err2(`A skill named "${name}" already exists. Use skill_update to change it, or choose another name.`);
12633
+ const rights_mode = decision?.rights_mode ?? "private";
12634
+ const skillId = randomUUID4();
12635
+ const stamp = now().toISOString();
12636
+ for (const f of files) {
12637
+ await io.upload(Buffer.from(f.content, "utf8"), `skills/${skillId}/v1/${f.path}`, exuluConfig, contentTypeFor(f.path));
12638
+ }
12639
+ await db2("skills").insert({
12640
+ id: skillId,
12641
+ name,
12642
+ description: description || parseFrontmatter(skillMd.content).description || "",
12643
+ s3folder: `skills/${skillId}`,
12644
+ tags: JSON.stringify([]),
12645
+ usage_count: 0,
12646
+ favorite_count: 0,
12647
+ current_version: 1,
12648
+ history: JSON.stringify([{ version: 1, created_at: stamp, label: `Created in chat with ${agent.name}` }]),
12649
+ rights_mode,
12650
+ created_by: user.id
12651
+ });
12652
+ if (decision?.rbac && rights_mode !== "private" && rights_mode !== "public") {
12653
+ await handleRBACUpdate(db2, "skill", skillId, decision.rbac, []);
12654
+ }
12655
+ const paths = files.map((f) => f.path);
12656
+ return {
12657
+ type: "skill_created",
12658
+ skillId,
12659
+ name,
12660
+ version: 1,
12661
+ rights_mode,
12662
+ files: paths,
12663
+ enableOnAgent: decision?.enableOnAgent === true,
12664
+ result: `Created skill "${name}" (v1, ${rights_mode}) with ${paths.length} file(s): ${paths.join(", ")}. It is in the skill library at /skills/${skillId}. An agent loads it once it is enabled on that agent and the next conversation turn starts.`
12665
+ };
12666
+ }
12667
+ })
12668
+ );
12669
+ }
12670
+ if (config.update) {
12671
+ tools.push(
12672
+ new ExuluTool({
12673
+ id: "skill_update",
12674
+ name: "skill_update",
12675
+ category,
12676
+ type: "function",
12677
+ config: [],
12678
+ needsApproval: !config.skipApproval,
12679
+ needsApprovalFn: approvalFn,
12680
+ 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.",
12681
+ inputSchema: z12.object({
12682
+ skill: z12.string().describe("The skill's name or id"),
12683
+ files: z12.array(z12.object({ path: z12.string(), content: z12.string() })).optional().describe("Files to add or replace, full content each"),
12684
+ deletePaths: z12.array(z12.string()).optional().describe("Paths to remove in the new version"),
12685
+ description: z12.string().optional().describe("A new one-line description, if it changed"),
12686
+ label: z12.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
12687
+ }),
12688
+ execute: async (params) => {
12689
+ const { user, exuluConfig } = params;
12690
+ if (!user?.id) return err2("Skills require a signed-in user.");
12691
+ if (!exuluConfig?.fileUploads) return err2("File uploads are not configured on this instance, so skills cannot be stored.");
12692
+ const decision = params.skillDecision?.kind === "update" ? params.skillDecision : void 0;
12693
+ const db2 = await getDb();
12694
+ const skill = await resolveSkill(db2, params.skill);
12695
+ if (!skill || !await canAccessSkill(db2, skill, "write", user)) {
12696
+ return { type: "skill_no_access", skill: String(params.skill), result: `No skill "${params.skill}" that you may change.` };
12697
+ }
12698
+ const parsed = normalizeFiles(params.files);
12699
+ if ("error" in parsed) return err2(parsed.error);
12700
+ const changes = parsed.files;
12701
+ const removals = [];
12702
+ for (const raw of Array.isArray(params.deletePaths) ? params.deletePaths : []) {
12703
+ const p = safeSkillPath(raw);
12704
+ if (!p) return err2(`"${String(raw)}" is not a valid path inside the skill.`);
12705
+ if (p === "SKILL.md") return err2("SKILL.md cannot be removed; replace it instead.");
12706
+ removals.push(p);
12707
+ }
12708
+ const description = String(decision?.description ?? params.description ?? "").trim();
12709
+ if (changes.length === 0 && removals.length === 0 && !description) {
12710
+ return err2("Nothing to change: pass files to add or replace, paths to remove, or a new description.");
12711
+ }
12712
+ const skillMd = changes.find((f) => f.path === "SKILL.md");
12713
+ if (skillMd) skillMd.content = ensureFrontmatter(skillMd.content, skill.name, description || skill.description || "");
12714
+ const currentVersion = skill.current_version ?? 1;
12715
+ const newVersion = currentVersion + 1;
12716
+ const currentPrefix = `skills/${skill.id}/v${currentVersion}/`;
12717
+ const newPrefix = `skills/${skill.id}/v${newVersion}/`;
12718
+ const gp = generalPrefix(exuluConfig);
12719
+ const existing = await io.list(currentPrefix, exuluConfig);
12720
+ const changedPaths = new Set(changes.map((f) => f.path));
12721
+ const removedSet = new Set(removals);
12722
+ for (const file of existing) {
12723
+ const rel = file.key.replace(gp + currentPrefix, "");
12724
+ if (!rel || rel.endsWith("/") || changedPaths.has(rel) || removedSet.has(rel)) continue;
12725
+ await io.copy(file.key, file.key.replace(gp + currentPrefix, gp + newPrefix), exuluConfig);
12726
+ }
12727
+ for (const f of changes) {
12728
+ await io.upload(Buffer.from(f.content, "utf8"), `${newPrefix}${f.path}`, exuluConfig, contentTypeFor(f.path));
12729
+ }
12730
+ const stamp = now().toISOString();
12731
+ const history = Array.isArray(skill.history) ? skill.history : [];
12732
+ const label = String(decision?.label ?? params.label ?? "").trim() || `Updated in chat with ${agent.name}`;
12733
+ await db2("skills").where({ id: skill.id }).update({
12734
+ current_version: newVersion,
12735
+ updatedAt: stamp,
12736
+ ...description ? { description } : {},
12737
+ history: JSON.stringify([...history, { version: newVersion, created_at: stamp, label }])
12738
+ });
12739
+ const changed = changes.map((f) => f.path);
12740
+ return {
12741
+ type: "skill_updated",
12742
+ skillId: skill.id,
12743
+ name: skill.name,
12744
+ version: newVersion,
12745
+ rights_mode: skill.rights_mode ?? "private",
12746
+ changed,
12747
+ removed: removals,
12748
+ enableOnAgent: decision?.enableOnAgent === true,
12749
+ result: `Published v${newVersion} of skill "${skill.name}": ${changed.length} file(s) changed${removals.length ? `, ${removals.length} removed` : ""}. Agents pick up the new version when their next conversation turn starts.`
12750
+ };
12751
+ }
12752
+ })
12753
+ );
12162
12754
  }
12163
12755
  return tools;
12164
12756
  };
12757
+ var createSkillAuthorPickerTool = () => new ExuluTool({
12758
+ id: SKILL_AUTHOR_TOOL_ID,
12759
+ name: "Skill author",
12760
+ category: "default",
12761
+ 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.",
12762
+ type: "function",
12763
+ inputSchema: z12.object({}),
12764
+ config: [
12765
+ { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
12766
+ { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
12767
+ { name: "skip_approval", description: "Create and update without the confirmation card (visibility then defaults to private).", type: "boolean", default: false }
12768
+ ],
12769
+ execute: async () => ({ result: "This entry is configuration-only; Exulu expands it into the skill tools at runtime." })
12770
+ });
12771
+ var collectSkillAuthorTools = (agent, deps = {}) => {
12772
+ if (!agent?.tools) return [];
12773
+ return createSkillAuthorTools(agent, deps);
12774
+ };
12165
12775
 
12166
12776
  // ee/invoke-skills/create-sandbox.ts
12167
12777
  import {
@@ -12548,10 +13158,10 @@ var readLiteLLMOsEnvironNames = (configPath = resolveLiteLLMConfigPath()) => {
12548
13158
  try {
12549
13159
  if (!existsSync4(configPath)) return [];
12550
13160
  return parseOsEnvironNames(readFileSync2(configPath, "utf8"));
12551
- } catch (err2) {
13161
+ } catch (err3) {
12552
13162
  console.warn(
12553
13163
  `[SKILLS] Could not read LiteLLM config at ${configPath} to collect os.environ/ credential names; the skill environment falls back to the static secret inventory.`,
12554
- err2
13164
+ err3
12555
13165
  );
12556
13166
  return [];
12557
13167
  }
@@ -12704,7 +13314,7 @@ ${JSON.stringify(config, null, 2)}`
12704
13314
  };
12705
13315
 
12706
13316
  // src/exulu/audit/sink.ts
12707
- import { randomUUID as randomUUID3 } from "crypto";
13317
+ import { randomUUID as randomUUID5 } from "crypto";
12708
13318
  import { promises as fs } from "fs";
12709
13319
  import path2 from "path";
12710
13320
  var createFsSpoolStore = (dir) => ({
@@ -12738,7 +13348,7 @@ var AuditSink = class {
12738
13348
  objectKey() {
12739
13349
  const d = this.now();
12740
13350
  const dt = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
12741
- return `${this.cfg.target.s3prefix}dt=${dt}/${pad(d.getUTCHours())}/${d.getTime()}-${randomUUID3()}.ndjson`;
13351
+ return `${this.cfg.target.s3prefix}dt=${dt}/${pad(d.getUTCHours())}/${d.getTime()}-${randomUUID5()}.ndjson`;
12742
13352
  }
12743
13353
  serialize(events) {
12744
13354
  return events.map((e) => JSON.stringify(e)).join("\n") + "\n";
@@ -12765,7 +13375,7 @@ var AuditSink = class {
12765
13375
  await this.writer.putNdjson(this.objectKey(), body);
12766
13376
  await this.drainSpool();
12767
13377
  } catch (error) {
12768
- const name = `${Date.now()}-${randomUUID3()}.ndjson`;
13378
+ const name = `${Date.now()}-${randomUUID5()}.ndjson`;
12769
13379
  try {
12770
13380
  await this.spool.write(name, body);
12771
13381
  console.warn(`[EXULU] audit: S3 write failed, spooled ${batch.length} record(s) to disk (${name}).`, error);
@@ -12920,7 +13530,7 @@ var buildToolCallEvent = async (ctx, opts) => {
12920
13530
  ctx.tool.id
12921
13531
  );
12922
13532
  }
12923
- const err2 = ctx.error;
13533
+ const err3 = ctx.error;
12924
13534
  return {
12925
13535
  v: 1,
12926
13536
  ts: nowIso(),
@@ -12942,7 +13552,7 @@ var buildToolCallEvent = async (ctx, opts) => {
12942
13552
  ...ctx.client ? { client: ctx.client } : {},
12943
13553
  ...credential ? { credential } : {},
12944
13554
  status,
12945
- ...status === "error" ? { error: { name: err2?.name, message: String(err2?.message ?? err2 ?? "unknown error") } } : {},
13555
+ ...status === "error" ? { error: { name: err3?.name, message: String(err3?.message ?? err3 ?? "unknown error") } } : {},
12946
13556
  data,
12947
13557
  durationMs: ctx.durationMs,
12948
13558
  ...Object.keys(truncated).length ? { truncated } : {}
@@ -13084,7 +13694,7 @@ var buildSkillSandboxEvent = (ctx, opts = {}) => {
13084
13694
  // ee/invoke-skills/create-sandbox.ts
13085
13695
  import { createBashTool } from "bash-tool";
13086
13696
  import { tool as tool2 } from "ai";
13087
- import { z as z12 } from "zod";
13697
+ import { z as z13 } from "zod";
13088
13698
  import CryptoJS3 from "crypto-js";
13089
13699
  var getAllExuluVariables = async () => {
13090
13700
  const { db: db2 } = await postgresClient();
@@ -13096,10 +13706,10 @@ var getAllExuluVariables = async () => {
13096
13706
  try {
13097
13707
  const bytes = CryptoJS3.AES.decrypt(value, process.env.NEXTAUTH_SECRET);
13098
13708
  value = bytes.toString(CryptoJS3.enc.Utf8);
13099
- } catch (err2) {
13709
+ } catch (err3) {
13100
13710
  console.error(
13101
13711
  `[VARIABLES] Failed to decrypt variable "${row.name}"; skipping.`,
13102
- err2
13712
+ err3
13103
13713
  );
13104
13714
  continue;
13105
13715
  }
@@ -13147,8 +13757,8 @@ function probeSandboxSupport() {
13147
13757
  child.stderr.on("data", (chunk) => {
13148
13758
  stderr += chunk.toString();
13149
13759
  });
13150
- child.on("error", (err2) => {
13151
- resolve4({ canSandbox: false, reason: `bwrap not executable: ${err2.message}` });
13760
+ child.on("error", (err3) => {
13761
+ resolve4({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
13152
13762
  });
13153
13763
  child.on("exit", (code) => {
13154
13764
  if (code === 0) resolve4({ canSandbox: true });
@@ -13226,10 +13836,10 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13226
13836
  let objects;
13227
13837
  try {
13228
13838
  objects = await listS3ObjectsByPrefix(userPrefix, config);
13229
- } catch (err2) {
13839
+ } catch (err3) {
13230
13840
  console.error(
13231
13841
  `[SKILLS] Failed to list S3 artifacts for session ${sessionId} (user ${userId}); proceeding with empty session dir.`,
13232
- err2
13842
+ err3
13233
13843
  );
13234
13844
  return;
13235
13845
  }
@@ -13256,10 +13866,10 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
13256
13866
  const bytes = await getS3ObjectBytes(obj.key, config);
13257
13867
  await mkdir(dirname(localPath), { recursive: true });
13258
13868
  await writeFile(localPath, bytes);
13259
- } catch (err2) {
13869
+ } catch (err3) {
13260
13870
  console.error(
13261
13871
  `[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
13262
- err2
13872
+ err3
13263
13873
  );
13264
13874
  }
13265
13875
  }
@@ -13289,11 +13899,24 @@ async function resolvePythonVenvPath() {
13289
13899
  try {
13290
13900
  const { getPythonVenvPath } = await import("./python-setup-UYSNAW5V.js");
13291
13901
  return getPythonVenvPath();
13292
- } catch (err2) {
13293
- console.warn("[SKILLS] Could not resolve the Python venv for the session sandbox; skill scripts fall back to the system python.", err2);
13902
+ } catch (err3) {
13903
+ console.warn("[SKILLS] Could not resolve the Python venv for the session sandbox; skill scripts fall back to the system python.", err3);
13294
13904
  return void 0;
13295
13905
  }
13296
13906
  }
13907
+ async function refreshSessionSkills(sessionId, skills, config) {
13908
+ const cached = sandboxCache.get(sessionId);
13909
+ if (!cached) return { refreshed: 0, sandbox: false };
13910
+ const skillsDirectory = join2(cached.handle.sessionDir, "skills");
13911
+ let refreshed = 0;
13912
+ for (const skill of skills) {
13913
+ await rm(join2(skillsDirectory, skill.name), { recursive: true, force: true });
13914
+ await downloadSkill(skill, skillsDirectory, config);
13915
+ cached.installedSkills.set(skill.id, skill.current_version);
13916
+ refreshed++;
13917
+ }
13918
+ return { refreshed, sandbox: true };
13919
+ }
13297
13920
  async function createSessionSandbox(sessionId, skills, config, userId, agent) {
13298
13921
  const cached = sandboxCache.get(sessionId);
13299
13922
  if (cached) {
@@ -13310,8 +13933,8 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent) {
13310
13933
  if (userId && config.fileUploads) {
13311
13934
  try {
13312
13935
  await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, { onlyMissing: true });
13313
- } catch (err2) {
13314
- console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err2);
13936
+ } catch (err3) {
13937
+ console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err3);
13315
13938
  }
13316
13939
  }
13317
13940
  return cached.handle;
@@ -13400,10 +14023,10 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13400
14023
  const loaded = await getAllExuluVariables();
13401
14024
  configuredVariables = loaded.granted;
13402
14025
  withheldNames = loaded.withheldNames;
13403
- } catch (err2) {
14026
+ } catch (err3) {
13404
14027
  console.error(
13405
14028
  `[SKILLS] Failed to load configured variables for session ${sessionId}; bash env will not include them.`,
13406
- err2
14029
+ err3
13407
14030
  );
13408
14031
  }
13409
14032
  const { env: sandboxedExecEnv, strippedSecretNames, grantedNames, skippedNames } = buildSkillEnv({
@@ -13436,10 +14059,10 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13436
14059
  degradedSandbox: useDirectExec
13437
14060
  })
13438
14061
  );
13439
- } catch (err2) {
14062
+ } catch (err3) {
13440
14063
  console.error(
13441
14064
  `[SKILLS] audit: skill-sandbox emit failed for session ${sessionId}; continuing.`,
13442
- err2
14065
+ err3
13443
14066
  );
13444
14067
  }
13445
14068
  }
@@ -13512,17 +14135,17 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13512
14135
  const keyOnly = fullKey.slice(slashIdx + 1);
13513
14136
  try {
13514
14137
  out.url = await getPresignedUrl(bucket, keyOnly, config);
13515
- } catch (err2) {
14138
+ } catch (err3) {
13516
14139
  console.error(
13517
14140
  `[SKILLS] Upload succeeded but presign failed for ${fullKey}; continuing without URL.`,
13518
- err2
14141
+ err3
13519
14142
  );
13520
14143
  }
13521
14144
  }
13522
- } catch (err2) {
14145
+ } catch (err3) {
13523
14146
  console.error(
13524
14147
  `[SKILLS] Failed to upload artifact ${s3Key} for session ${sessionId} (user ${userId}); continuing.`,
13525
- err2
14148
+ err3
13526
14149
  );
13527
14150
  }
13528
14151
  return out;
@@ -13595,9 +14218,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13595
14218
  });
13596
14219
  const writeFileTool = tool2({
13597
14220
  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/foo.md") and leading-slash paths ("/skills/foo.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.',
13598
- inputSchema: z12.object({
13599
- path: z12.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
13600
- content: z12.string().describe("The content to write to the file")
14221
+ inputSchema: z13.object({
14222
+ path: z13.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
14223
+ content: z13.string().describe("The content to write to the file")
13601
14224
  }),
13602
14225
  execute: async ({ path: path3, content }) => {
13603
14226
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -13616,8 +14239,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13616
14239
  });
13617
14240
  const readFileTool = tool2({
13618
14241
  description: 'Read the contents of a file from the sandbox. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/foo.md") and leading-slash paths ("/skills/foo.md") work and reach the same file. If the file does not exist, the error message is surfaced verbatim.',
13619
- inputSchema: z12.object({
13620
- path: z12.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
14242
+ inputSchema: z13.object({
14243
+ path: z13.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
13621
14244
  }),
13622
14245
  execute: async ({ path: path3 }) => {
13623
14246
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -13628,8 +14251,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13628
14251
  const originalBashTool = tools.bash;
13629
14252
  const bashTool = tool2({
13630
14253
  description: originalBashTool.description ?? "",
13631
- inputSchema: z12.object({
13632
- command: z12.string().describe("The bash command to execute.")
14254
+ inputSchema: z13.object({
14255
+ command: z13.string().describe("The bash command to execute.")
13633
14256
  }),
13634
14257
  execute: async (args, opts) => {
13635
14258
  const before = persistenceEnabled ? await snapshotSessionArtifacts() : null;
@@ -13658,10 +14281,10 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13658
14281
  key: persisted.key,
13659
14282
  url: persisted.url
13660
14283
  });
13661
- } catch (err2) {
14284
+ } catch (err3) {
13662
14285
  console.error(
13663
14286
  `[SKILLS] Failed to mirror bash-produced artifact ${path3} to S3; continuing.`,
13664
- err2
14287
+ err3
13665
14288
  );
13666
14289
  }
13667
14290
  }
@@ -13729,7 +14352,7 @@ var truncateToolOutput = (output, maxContextLength, toolName, tailFraction = 0.1
13729
14352
  };
13730
14353
 
13731
14354
  // src/exulu/tool-output-offload.ts
13732
- import { randomUUID as randomUUID4 } from "crypto";
14355
+ import { randomUUID as randomUUID6 } from "crypto";
13733
14356
 
13734
14357
  // src/exulu/context-budget.ts
13735
14358
  var DEFAULT_CONTEXT_WINDOW = 128e3;
@@ -13833,7 +14456,7 @@ var PREVIEW_CHARS = 4e3;
13833
14456
  var storeAsSessionFile = async (serialized, ctx) => {
13834
14457
  if (!ctx.sessionID || !ctx.exuluConfig?.fileUploads) return void 0;
13835
14458
  const safeTool = ctx.toolName.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
13836
- const name = `tool-output-${safeTool}-${randomUUID4().slice(0, 8)}.txt`;
14459
+ const name = `tool-output-${safeTool}-${randomUUID6().slice(0, 8)}.txt`;
13837
14460
  try {
13838
14461
  await uploadFile(
13839
14462
  Buffer.from(serialized, "utf-8"),
@@ -13843,8 +14466,8 @@ var storeAsSessionFile = async (serialized, ctx) => {
13843
14466
  ctx.user?.id
13844
14467
  );
13845
14468
  return name;
13846
- } catch (err2) {
13847
- console.error("[EXULU] Failed to offload oversized tool output to session files.", err2);
14469
+ } catch (err3) {
14470
+ console.error("[EXULU] Failed to offload oversized tool output to session files.", err3);
13848
14471
  return void 0;
13849
14472
  }
13850
14473
  };
@@ -13901,15 +14524,7 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
13901
14524
  };
13902
14525
 
13903
14526
  // src/templates/tools/session-file-read-tool.ts
13904
- import { z as z13 } from "zod";
13905
-
13906
- // src/exulu/session-files.ts
13907
- function sessionFilePrefix(ownerId, sessionId, s3prefix) {
13908
- const general = s3prefix ? `${s3prefix.replace(/\/+$/, "")}/` : "";
13909
- return `${general}user_${ownerId}/sessions/${sessionId}/`;
13910
- }
13911
-
13912
- // src/templates/tools/session-file-read-tool.ts
14527
+ import { z as z14 } from "zod";
13913
14528
  var DEFAULT_LIMIT = 250;
13914
14529
  var MAX_CONTENT_CHARS = 16e3;
13915
14530
  var SESSION_FILE_READ_TOOL_NAME = "read_session_file";
@@ -13953,8 +14568,8 @@ var createSessionFileReadTool = ({
13953
14568
  offset: start + 1,
13954
14569
  linesReturned
13955
14570
  };
13956
- } catch (err2) {
13957
- return { error: `Failed to read session file "${safeName}": ${err2 instanceof Error ? err2.message : "unknown error"}` };
14571
+ } catch (err3) {
14572
+ return { error: `Failed to read session file "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
13958
14573
  }
13959
14574
  };
13960
14575
  return ExuluTool.internal({
@@ -13962,10 +14577,10 @@ var createSessionFileReadTool = ({
13962
14577
  name: SESSION_FILE_READ_TOOL_NAME,
13963
14578
  needsApproval: false,
13964
14579
  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.",
13965
- inputSchema: z13.object({
13966
- filename: z13.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
13967
- offset: z13.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
13968
- limit: z13.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
14580
+ inputSchema: z14.object({
14581
+ filename: z14.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
14582
+ offset: z14.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
14583
+ limit: z14.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
13969
14584
  }),
13970
14585
  type: "function",
13971
14586
  category: "session",
@@ -13978,7 +14593,7 @@ var createSessionFileReadTool = ({
13978
14593
  };
13979
14594
 
13980
14595
  // src/templates/tools/parse-document-tool.ts
13981
- import { z as z14 } from "zod";
14596
+ import { z as z15 } from "zod";
13982
14597
  import { extname } from "path";
13983
14598
  import { parseOfficeAsync } from "officeparser";
13984
14599
 
@@ -14015,9 +14630,9 @@ async function convertLegacyOfficeToModern(bytes, ext) {
14015
14630
  ["--headless", "--convert-to", target, inputPath, "--outdir", dir],
14016
14631
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
14017
14632
  );
14018
- } catch (err2) {
14633
+ } catch (err3) {
14019
14634
  throw new Error(
14020
- `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err2 instanceof Error ? err2.message : String(err2))
14635
+ `LibreOffice could not convert the legacy "${ext}" file to ${target}: ` + (err3 instanceof Error ? err3.message : String(err3))
14021
14636
  );
14022
14637
  }
14023
14638
  const outputPath = join3(dir, `input.${target}`);
@@ -14054,9 +14669,9 @@ async function renderPdfPageToPng(pdf, page, scaleTo) {
14054
14669
  ["-png", "-f", String(page), "-l", String(page), "-scale-to", String(scaleTo), inputPath, join3(dir, "page")],
14055
14670
  { timeout: 6e4, maxBuffer: MAX_STDOUT_BYTES }
14056
14671
  );
14057
- } catch (err2) {
14058
- if (err2?.code === 99) return null;
14059
- throw err2;
14672
+ } catch (err3) {
14673
+ if (err3?.code === 99) return null;
14674
+ throw err3;
14060
14675
  }
14061
14676
  const produced = (await readdir2(dir)).find((f) => f.startsWith("page") && f.endsWith(".png"));
14062
14677
  if (!produced) return null;
@@ -14202,8 +14817,8 @@ ${text.trim()}`).join("\n");
14202
14817
  offset: start + 1,
14203
14818
  linesReturned
14204
14819
  };
14205
- } catch (err2) {
14206
- return { error: `Failed to parse "${safeName}": ${err2 instanceof Error ? err2.message : "unknown error"}` };
14820
+ } catch (err3) {
14821
+ return { error: `Failed to parse "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
14207
14822
  }
14208
14823
  };
14209
14824
  return ExuluTool.internal({
@@ -14211,11 +14826,11 @@ ${text.trim()}`).join("\n");
14211
14826
  name: PARSE_DOCUMENT_TOOL_NAME,
14212
14827
  needsApproval: false,
14213
14828
  description: `Extract the text of an uploaded PDF or Office document from this session's files, with "--- page N ---" markers for PDFs so you can locate content by page. Free and fast (no OCR): works only on documents with a real text layer. To SEE a page or an image inside a document, use view_document_page.`,
14214
- inputSchema: z14.object({
14215
- filename: z14.string().describe('Exact session file name, e.g. "report.pdf"'),
14216
- pages: z14.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14217
- offset: z14.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14218
- limit: z14.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
14829
+ inputSchema: z15.object({
14830
+ filename: z15.string().describe('Exact session file name, e.g. "report.pdf"'),
14831
+ pages: z15.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14832
+ offset: z15.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14833
+ limit: z15.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
14219
14834
  }),
14220
14835
  type: "function",
14221
14836
  category: "session",
@@ -14228,7 +14843,7 @@ ${text.trim()}`).join("\n");
14228
14843
  };
14229
14844
 
14230
14845
  // src/templates/tools/view-document-page-tool.ts
14231
- import { z as z15 } from "zod";
14846
+ import { z as z16 } from "zod";
14232
14847
  import { extname as extname3 } from "path";
14233
14848
 
14234
14849
  // src/sessions/pdf-preview-cache.ts
@@ -14278,9 +14893,9 @@ async function getPdfPreviewBytes(opts) {
14278
14893
  `soffice --headless --convert-to pdf "${inputPath}" --outdir "${CACHE_OUT}"`,
14279
14894
  { timeout: 6e4, maxBuffer: 16 * 1024 * 1024 }
14280
14895
  );
14281
- } catch (err2) {
14896
+ } catch (err3) {
14282
14897
  throw new PreviewRenderError(
14283
- `LibreOffice conversion failed for ${sourceKey} (etag ${etag}): ${err2?.stderr ?? err2?.message ?? "unknown error"}`
14898
+ `LibreOffice conversion failed for ${sourceKey} (etag ${etag}): ${err3?.stderr ?? err3?.message ?? "unknown error"}`
14284
14899
  );
14285
14900
  }
14286
14901
  if (!existsSync7(outputPath)) {
@@ -14490,8 +15105,8 @@ var createViewDocumentPageTool = ({
14490
15105
  page: pageNumber,
14491
15106
  note: "The rendered image follows this tool result as an attached user message \u2014 analyze it there. If no image message follows, the attachment has expired; call this tool again to re-render it."
14492
15107
  };
14493
- } catch (err2) {
14494
- return { error: `Failed to render "${safeName}": ${err2 instanceof Error ? err2.message : "unknown error"}` };
15108
+ } catch (err3) {
15109
+ return { error: `Failed to render "${safeName}": ${err3 instanceof Error ? err3.message : "unknown error"}` };
14495
15110
  }
14496
15111
  };
14497
15112
  return ExuluTool.internal({
@@ -14499,9 +15114,9 @@ var createViewDocumentPageTool = ({
14499
15114
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
14500
15115
  needsApproval: false,
14501
15116
  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.",
14502
- inputSchema: z15.object({
14503
- filename: z15.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
14504
- page: z15.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
15117
+ inputSchema: z16.object({
15118
+ filename: z16.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
15119
+ page: z16.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
14505
15120
  }),
14506
15121
  type: "function",
14507
15122
  category: "session",
@@ -14545,7 +15160,7 @@ function extractClientInfo(req) {
14545
15160
 
14546
15161
  // src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts
14547
15162
  var OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS = /* @__PURE__ */ new Set(["agentic_context_search"]);
14548
- var generateS3Key = (filename) => `${randomUUID5()}-${filename}`;
15163
+ var generateS3Key = (filename) => `${randomUUID7()}-${filename}`;
14549
15164
  var s3Client2;
14550
15165
  var getMimeType = (type) => {
14551
15166
  switch (type) {
@@ -14617,10 +15232,10 @@ var hydrateVariables = async (tool3) => {
14617
15232
  }
14618
15233
  try {
14619
15234
  toolConfig.value = JSON.parse(toolConfig.variable.toString());
14620
- } catch (err2) {
15235
+ } catch (err3) {
14621
15236
  console.warn(
14622
15237
  `[EXULU] Config option "${toolConfig.name}" holds invalid JSON \u2014 falling back to the tool's declared default.`,
14623
- err2
15238
+ err3
14624
15239
  );
14625
15240
  toolConfig.value = void 0;
14626
15241
  }
@@ -14643,7 +15258,7 @@ var hydrateVariables = async (tool3) => {
14643
15258
  await Promise.all(promises);
14644
15259
  return tool3;
14645
15260
  };
14646
- var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions) => {
15261
+ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approvedTools, allExuluTools, configs, contexts, user, exuluConfig, sessionID, req, project, sessionItems, model, agent, memoryItems, contextWindow, disabledTools, sessionOwnerId, memoryDecisions, skillDecisions) => {
14647
15262
  if (!currentTools) return {};
14648
15263
  if (!allExuluTools) {
14649
15264
  allExuluTools = [];
@@ -14665,10 +15280,10 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
14665
15280
  // skill.sandbox.created event can be joined to the agent that caused it.
14666
15281
  agent ? { id: agent.id, name: agent.name, slug: agent.slug } : void 0
14667
15282
  );
14668
- } catch (err2) {
15283
+ } catch (err3) {
14669
15284
  console.error(
14670
15285
  "[EXULU] Failed to eagerly create shared skill sandbox; outer agent will not have readFile/writeFile available.",
14671
- err2
15286
+ err3
14672
15287
  );
14673
15288
  }
14674
15289
  }
@@ -14718,11 +15333,16 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
14718
15333
  }
14719
15334
  }
14720
15335
  }
14721
- for (const kbWriteTool of collectKbWriteTools(agent, contexts)) {
15336
+ for (const kbWriteTool of collectKbWriteTools(agent, contexts, { sessionOwnerId })) {
14722
15337
  if (!disabled.has(kbWriteTool.id)) {
14723
15338
  currentTools.push(kbWriteTool);
14724
15339
  }
14725
15340
  }
15341
+ for (const skillTool of collectSkillAuthorTools(agent)) {
15342
+ if (!disabled.has(skillTool.id)) {
15343
+ currentTools.push(skillTool);
15344
+ }
15345
+ }
14726
15346
  console.log("[EXULU] Convert tools array to object, session items", sessionItems);
14727
15347
  if (sessionItems) {
14728
15348
  const sessionItemsRetrievalTool = await createSessionItemsRetrievalTool({
@@ -14968,6 +15588,7 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
14968
15588
  sessionItems,
14969
15589
  memory: memoryItems,
14970
15590
  memoryDecision: memoryDecisions?.get(options?.toolCallId ?? ""),
15591
+ skillDecision: skillDecisions?.get(options?.toolCallId ?? ""),
14971
15592
  req,
14972
15593
  // Convert config to object format if a config object
14973
15594
  // is available, after we added the .value property
@@ -15151,6 +15772,7 @@ export {
15151
15772
  willEmbedOnQueue,
15152
15773
  hydrateContextEmbedders,
15153
15774
  refreshContextEmbeddersIfStale,
15775
+ VALID_RIGHTS_MODES,
15154
15776
  updateStatistic,
15155
15777
  preprocessQuery,
15156
15778
  resolveSearchQueryTexts,
@@ -15180,6 +15802,7 @@ export {
15180
15802
  TERMINAL_JOB_STATES,
15181
15803
  maybePruneJobResults,
15182
15804
  ExuluContext2 as ExuluContext,
15805
+ checkRecordAccess,
15183
15806
  authRegistry,
15184
15807
  encrypt,
15185
15808
  decrypt,
@@ -15199,15 +15822,28 @@ export {
15199
15822
  displayName,
15200
15823
  createRecallCollector,
15201
15824
  buildMemoryPromptBlock,
15825
+ normalizeRbac,
15202
15826
  collectMemoryDecisions,
15827
+ sessionFilePrefix,
15203
15828
  KB_EDITOR_TOOL_ID,
15204
15829
  createKbEditorPickerTool,
15830
+ RBACResolver,
15831
+ resolveSkillByName,
15832
+ canAccessSkill,
15833
+ filterReadableSkills,
15834
+ parseFrontmatter,
15835
+ parseSkillFrontmatter,
15836
+ SKILL_AUTHOR_TOOL_ID,
15837
+ parseSkillAuthorConfig,
15838
+ SKILL_AUTHOR_PROMPT,
15839
+ createSkillAuthorPickerTool,
15205
15840
  isIgnoredArtifactPath,
15206
15841
  reportSystemDependencies,
15207
15842
  findUnclassifiedSecretShaped,
15208
15843
  getAuditLogger,
15209
15844
  initAudit,
15210
15845
  downloadKeyIntoSandbox,
15846
+ refreshSessionSkills,
15211
15847
  truncateToolOutput,
15212
15848
  DEFAULT_CONTEXT_WINDOW,
15213
15849
  deriveContextBudget,
@@ -15221,7 +15857,6 @@ export {
15221
15857
  guardExtractedFileText,
15222
15858
  SCRUBBED_CREDENTIAL_TEXT,
15223
15859
  SCRUBBED_OAUTH_TEXT,
15224
- sessionFilePrefix,
15225
15860
  SESSION_FILE_READ_TOOL_NAME,
15226
15861
  PARSE_DOCUMENT_TOOL_NAME,
15227
15862
  PreviewRenderError,