@exulu/backend 5.10.1 → 5.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -659,7 +659,7 @@ var ExuluTool = class _ExuluTool {
659
659
  if (!agent) {
660
660
  throw new Error("Agent not found.");
661
661
  }
662
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-LL7R3VTK.js");
662
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-FX6KTVPQ.js");
663
663
  const tools = await convertExuluToolsToAiSdkTools2(
664
664
  [this],
665
665
  [],
@@ -1757,6 +1757,10 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
1757
1757
  })
1758
1758
  });
1759
1759
  } catch (err3) {
1760
+ console.warn(
1761
+ "[EXULU pipeline] doc/page detection failed \u2014 skipping filename and page hints.",
1762
+ err3
1763
+ );
1760
1764
  steps.push({ text: "Doc/page detection failed \u2014 skipping filename and page hints." });
1761
1765
  return {
1762
1766
  output: {
@@ -1781,6 +1785,10 @@ If explicit, return the knowledge base ids. If not, return an empty array.`;
1781
1785
  messages: [{ role: "user", content: question }]
1782
1786
  });
1783
1787
  } catch (err3) {
1788
+ console.warn(
1789
+ "[EXULU pipeline] explicit knowledge base detection failed \u2014 treating the question as naming none.",
1790
+ err3
1791
+ );
1784
1792
  return { output: { explicitlyRequestedKnowledgeBases: [] } };
1785
1793
  }
1786
1794
  })()
@@ -1893,6 +1901,10 @@ ${extraInstructions}
1893
1901
  });
1894
1902
  }
1895
1903
  } catch (err3) {
1904
+ console.warn(
1905
+ "[EXULU pipeline] classification failed \u2014 using the implicit all-main rule.",
1906
+ err3
1907
+ );
1896
1908
  mainContexts = enabledContexts.map((c) => c.id);
1897
1909
  fallbackContexts = [];
1898
1910
  steps.push({
@@ -2655,7 +2667,9 @@ var convertGraphqlOperatorToPostgresQuery = (query, fieldName, operators, table,
2655
2667
  console.log("[EXULU] operators.lte", operators.lte);
2656
2668
  console.log("[EXULU] fieldName", fieldName);
2657
2669
  if (operators.lte === 0 || operators.lte === "0") {
2658
- query = query.whereNull(fieldName).orWhere(fieldName, "=", 0);
2670
+ query = query.where(function() {
2671
+ this.whereNull(fieldName).orWhere(fieldName, "=", 0);
2672
+ });
2659
2673
  } else {
2660
2674
  query = query.where(fieldName, "<=", operators.lte);
2661
2675
  }
@@ -6153,14 +6167,14 @@ function randomizedPCA(rows, dims, k, seed, iterations) {
6153
6167
  for (const row of rows) {
6154
6168
  const centered = new Float64Array(dims);
6155
6169
  for (let d = 0; d < dims; d += 1) centered[d] = (row[d] ?? 0) - (mean[d] ?? 0);
6156
- const z18 = new Float64Array(basis.length);
6170
+ const z19 = new Float64Array(basis.length);
6157
6171
  for (const [b, vec] of basis.entries()) {
6158
6172
  let dot = 0;
6159
6173
  for (let d = 0; d < dims; d += 1) dot += (centered[d] ?? 0) * (vec[d] ?? 0);
6160
- z18[b] = dot;
6174
+ z19[b] = dot;
6161
6175
  }
6162
6176
  for (const [b, target] of next.entries()) {
6163
- const scale = z18[b] ?? 0;
6177
+ const scale = z19[b] ?? 0;
6164
6178
  if (scale === 0) continue;
6165
6179
  for (let d = 0; d < dims; d += 1) target[d] = (target[d] ?? 0) + (centered[d] ?? 0) * scale;
6166
6180
  }
@@ -6258,12 +6272,12 @@ function ridgeFit(Z, Y, lambda) {
6258
6272
  });
6259
6273
  return { map, intercept };
6260
6274
  }
6261
- function applyMap(z18, map, intercept) {
6275
+ function applyMap(z19, map, intercept) {
6262
6276
  const out = [];
6263
6277
  for (let j = 0; j < 3; j += 1) {
6264
6278
  let v = intercept[j] ?? 0;
6265
6279
  const row = map[j] ?? [];
6266
- for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z18[d] ?? 0);
6280
+ for (let d = 0; d < row.length; d += 1) v += (row[d] ?? 0) * (z19[d] ?? 0);
6267
6281
  out.push(Number.isFinite(v) ? v : 0);
6268
6282
  }
6269
6283
  return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
@@ -6286,8 +6300,8 @@ function fitResidual(Z, Y, map, intercept) {
6286
6300
  for (let i = 0; i < Z.length; i += 1) {
6287
6301
  const zi = Z[i] ?? [];
6288
6302
  const yi = Y[i] ?? [];
6289
- const [x, y, z18] = applyMap(zi, map, intercept);
6290
- total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z18 - finite(yi[2]));
6303
+ const [x, y, z19] = applyMap(zi, map, intercept);
6304
+ total += Math.hypot(x - finite(yi[0]), y - finite(yi[1]), z19 - finite(yi[2]));
6291
6305
  }
6292
6306
  return finite(total / Z.length);
6293
6307
  }
@@ -6427,8 +6441,8 @@ async function chunkCoordinates({
6427
6441
  }
6428
6442
  return null;
6429
6443
  }
6430
- const [x, y, z18] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6431
- return { x, y, z: z18 };
6444
+ const [x, y, z19] = applyMap(projectComponents(l2normalize(v), mean, basis), projection.map, projection.intercept);
6445
+ return { x, y, z: z19 };
6432
6446
  });
6433
6447
  } catch (e) {
6434
6448
  console.error("[EXULU] could not compute chunk coordinates", e instanceof Error ? e.message : String(e));
@@ -6869,6 +6883,9 @@ var applyAccessControl = (table, query, user, field_prefix) => {
6869
6883
  };
6870
6884
 
6871
6885
  // src/graphql/resolvers/apply-filters.ts
6886
+ var applyFiltersGrouped = (query, filters, table, field_prefix) => query.where(function() {
6887
+ applyFilters(this, filters, table, field_prefix);
6888
+ });
6872
6889
  var applyFilters = (query, filters, table, field_prefix) => {
6873
6890
  if (!filters) {
6874
6891
  return query;
@@ -8826,8 +8843,12 @@ var ExuluContext2 = class {
8826
8843
  ...item.external_id ? { external_id: item.external_id } : {}
8827
8844
  }).first();
8828
8845
  if (result) {
8829
- const chunksCount = await db.from(getChunksTableName(this.id)).where({ source: result.id }).count("id");
8830
- result.chunksCount = Number(chunksCount[0].count) || 0;
8846
+ if (this.embedder) {
8847
+ const chunksCount = await db.from(getChunksTableName(this.id)).where({ source: result.id }).count("id");
8848
+ result.chunksCount = Number(chunksCount[0].count) || 0;
8849
+ } else {
8850
+ result.chunksCount = 0;
8851
+ }
8831
8852
  }
8832
8853
  return result;
8833
8854
  };
@@ -8835,16 +8856,20 @@ var ExuluContext2 = class {
8835
8856
  filters,
8836
8857
  fields,
8837
8858
  user,
8838
- role
8859
+ role,
8860
+ limit
8839
8861
  }) => {
8840
8862
  const { db } = await postgresClient();
8841
8863
  const tableDefinition = convertContextToTableDefinition(this);
8842
8864
  let query = db.from(getTableName(this.id)).select(fields || "*");
8843
- query = applyFilters(query, filters || [], tableDefinition);
8865
+ query = applyFiltersGrouped(query, filters || [], tableDefinition);
8844
8866
  if (user) {
8845
8867
  const acUser = role && (!user.role || user.role.id !== role) ? { ...user, role: { ...user.role ?? {}, id: role } } : user;
8846
8868
  query = applyAccessControl(tableDefinition, query, acUser);
8847
8869
  }
8870
+ if (typeof limit === "number" && Number.isFinite(limit) && limit > 0) {
8871
+ query = query.limit(Math.floor(limit));
8872
+ }
8848
8873
  const items = await query;
8849
8874
  return items;
8850
8875
  };
@@ -11365,7 +11390,7 @@ function collectMemoryDecisions(messages) {
11365
11390
  }
11366
11391
 
11367
11392
  // src/templates/tools/context-write-tools.ts
11368
- import { z as z12 } from "zod";
11393
+ import { z as z13 } from "zod";
11369
11394
  import { randomUUID as randomUUID3 } from "crypto";
11370
11395
 
11371
11396
  // src/exulu/session-files.ts
@@ -11448,6 +11473,17 @@ var checkItemWriteAccess = async (context, record, user) => {
11448
11473
  return false;
11449
11474
  };
11450
11475
 
11476
+ // src/exulu/public-surface.ts
11477
+ var PUBLIC_SURFACE_HEADER = "x-public-surface";
11478
+ function isPublicSurface(req) {
11479
+ const raw = req?.headers?.[PUBLIC_SURFACE_HEADER];
11480
+ const value = Array.isArray(raw) ? raw[0] : raw;
11481
+ return value === "1" || value === "true";
11482
+ }
11483
+ function treatAsGuest(req, user) {
11484
+ return isPublicSurface(req) || !user?.id;
11485
+ }
11486
+
11451
11487
  // src/templates/tools/kb-editor-config.ts
11452
11488
  import { z as z11 } from "zod";
11453
11489
  var KB_EDITOR_TOOL_ID = "knowledge_base_editor";
@@ -11502,8 +11538,424 @@ var parseKbEditorConfig = (tools) => {
11502
11538
  return { enabled: true, knowledgeBases, skipApproval };
11503
11539
  };
11504
11540
 
11541
+ // src/utils/check-record-access.ts
11542
+ var checkRecordAccessCache = /* @__PURE__ */ new Map();
11543
+ var checkRecordAccess = async (record, request, user) => {
11544
+ const setRecordAccessCache = (hasAccess2) => {
11545
+ checkRecordAccessCache.set(`${record.id}-${request}-${user?.id}`, {
11546
+ hasAccess: hasAccess2,
11547
+ expiresAt: new Date(Date.now() + 1e3 * 60 * 1)
11548
+ // 1 minute
11549
+ });
11550
+ };
11551
+ const cachedAccess = checkRecordAccessCache.get(`${record.id}-${request}-${user?.id}`);
11552
+ if (cachedAccess && cachedAccess.expiresAt > /* @__PURE__ */ new Date()) {
11553
+ return cachedAccess.hasAccess;
11554
+ }
11555
+ const isPublic = record.rights_mode === "public";
11556
+ const byUsers = record.rights_mode === "users";
11557
+ const byRoles = record.rights_mode === "roles";
11558
+ const byTeams = record.rights_mode === "teams";
11559
+ const createdBy = typeof record.created_by === "string" ? record.created_by : record.created_by?.toString();
11560
+ const isCreator = user ? createdBy === user.id.toString() : false;
11561
+ const isAdmin = user ? user.super_admin : false;
11562
+ const isApi = user ? user.type === "api" : false;
11563
+ const isAdminApi = isApi && (!user.scope_mode || user.scope_mode === "admin");
11564
+ const isAgentsScopedApi = isApi && user.scope_mode === "agents" && request === "read" && Array.isArray(user.agent_ids) && user.agent_ids.includes(String(record.id));
11565
+ let hasAccess = "none";
11566
+ if (isPublic || isCreator || isAdmin || isAdminApi || isAgentsScopedApi) {
11567
+ setRecordAccessCache(true);
11568
+ return true;
11569
+ }
11570
+ if (byUsers) {
11571
+ if (!user) {
11572
+ setRecordAccessCache(false);
11573
+ return false;
11574
+ }
11575
+ hasAccess = record.RBAC?.users?.find((x) => x.id === user.id)?.rights || "none";
11576
+ if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
11577
+ console.error(
11578
+ `[EXULU] Your current user ${user.id} does not have access to this record, current access type is: ${hasAccess}.`
11579
+ );
11580
+ setRecordAccessCache(false);
11581
+ return false;
11582
+ } else {
11583
+ setRecordAccessCache(true);
11584
+ return true;
11585
+ }
11586
+ }
11587
+ if (byRoles) {
11588
+ if (!user) {
11589
+ setRecordAccessCache(false);
11590
+ return false;
11591
+ }
11592
+ hasAccess = record.RBAC?.roles?.find((x) => x.id === user.role?.id)?.rights || "none";
11593
+ if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
11594
+ console.error(
11595
+ `[EXULU] Your current role ${user.role?.name} does not have access to this record, current access type is: ${hasAccess}.`
11596
+ );
11597
+ setRecordAccessCache(false);
11598
+ return false;
11599
+ } else {
11600
+ setRecordAccessCache(true);
11601
+ return true;
11602
+ }
11603
+ }
11604
+ if (byTeams) {
11605
+ if (!user) {
11606
+ setRecordAccessCache(false);
11607
+ return false;
11608
+ }
11609
+ hasAccess = record.RBAC?.teams?.find((x) => x.id === user.team?.id)?.rights || "none";
11610
+ if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
11611
+ console.error(
11612
+ `[EXULU] Your current team ${user.team?.name} does not have access to this record, current access type is: ${hasAccess}.`
11613
+ );
11614
+ setRecordAccessCache(false);
11615
+ return false;
11616
+ } else {
11617
+ setRecordAccessCache(true);
11618
+ return true;
11619
+ }
11620
+ }
11621
+ setRecordAccessCache(false);
11622
+ return false;
11623
+ };
11624
+
11625
+ // src/templates/tools/context-read-tools.ts
11626
+ import { z as z12 } from "zod";
11627
+ var FIND_DEFAULT_LIMIT = 20;
11628
+ var FIND_MAX_LIMIT = 50;
11629
+ var SUPPORTED_OPERATORS = ["eq", "ne", "in", "contains", "gte", "lte"];
11630
+ var CONTAINS_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set(["number", "boolean", "date", "uuid"]);
11631
+ var RANGE_UNSUPPORTED_TYPES = /* @__PURE__ */ new Set(["json", "uuid"]);
11632
+ var operatorsForField = (field) => SUPPORTED_OPERATORS.filter((operator) => {
11633
+ if (operator === "contains") return !CONTAINS_UNSUPPORTED_TYPES.has(field.type);
11634
+ if (operator === "gte" || operator === "lte") return !RANGE_UNSUPPORTED_TYPES.has(field.type);
11635
+ return true;
11636
+ });
11637
+ var SYSTEM_FIELDS = [
11638
+ // `id` is a uuid column, not text: `contains` would compile to
11639
+ // `"id" ilike $1` and Postgres refuses that outright (42883).
11640
+ { name: "id", type: "uuid", findDefault: true },
11641
+ { name: "createdAt", type: "date", findDefault: false },
11642
+ { name: "updatedAt", type: "date", findDefault: true },
11643
+ { name: "rights_mode", type: "text", findDefault: false },
11644
+ { name: "archived", type: "boolean", findDefault: false }
11645
+ ];
11646
+ var CORE_CONTENT_FIELDS = [
11647
+ { name: "name", type: "text" },
11648
+ { name: "description", type: "text" },
11649
+ { name: "tags", type: "text" },
11650
+ { name: "external_id", type: "text" }
11651
+ ];
11652
+ var readableContextFields = (context) => {
11653
+ const fields = [];
11654
+ const seen = /* @__PURE__ */ new Set();
11655
+ const add = (field) => {
11656
+ if (seen.has(field.name)) return;
11657
+ seen.add(field.name);
11658
+ fields.push(field);
11659
+ };
11660
+ for (const system of SYSTEM_FIELDS) {
11661
+ add({ ...system, column: system.name, isFile: false });
11662
+ }
11663
+ for (const core of CORE_CONTENT_FIELDS) {
11664
+ add({ ...core, column: core.name, isFile: false, findDefault: true });
11665
+ }
11666
+ for (const field of context.fields ?? []) {
11667
+ if (!field?.name || !field.type) continue;
11668
+ if (isHiddenField(field)) continue;
11669
+ const isFile = field.type === "file";
11670
+ add({
11671
+ name: field.name,
11672
+ column: sanitizeName(isFile ? `${field.name}_s3key` : field.name),
11673
+ type: field.type,
11674
+ isFile,
11675
+ // A file column holds an opaque storage key, which is noise in a list —
11676
+ // asked for by name it is still returned.
11677
+ findDefault: !isFile
11678
+ });
11679
+ }
11680
+ return fields;
11681
+ };
11682
+ var nameList = (fields) => fields.map((f) => f.name).join(", ");
11683
+ var resolveFields = (readable, requested, contextName) => {
11684
+ if (!Array.isArray(requested) || requested.length === 0) {
11685
+ return { fields: readable };
11686
+ }
11687
+ const byName = new Map(readable.map((f) => [f.name, f]));
11688
+ const picked = [];
11689
+ const unknown = [];
11690
+ for (const raw of requested) {
11691
+ const name = String(raw);
11692
+ const field = byName.get(name);
11693
+ if (!field) {
11694
+ unknown.push(name);
11695
+ continue;
11696
+ }
11697
+ if (!picked.includes(field)) picked.push(field);
11698
+ }
11699
+ if (unknown.length > 0) {
11700
+ return {
11701
+ error: `Unknown field name${unknown.length > 1 ? "s" : ""} ${unknown.map((n) => `"${n}"`).join(", ")} for "${contextName}". Valid field names: ${nameList(readable)}.`
11702
+ };
11703
+ }
11704
+ const id = readable.find((f) => f.name === "id");
11705
+ if (id && !picked.includes(id)) picked.unshift(id);
11706
+ return { fields: picked };
11707
+ };
11708
+ var selectList = (fields) => fields.map((field) => field.column === field.name ? field.column : `${field.column} as ${field.name}`);
11709
+ var whereByColumn = (filterable, where) => {
11710
+ const byName = new Map(filterable.map((f) => [f.name, f]));
11711
+ const mapped = {};
11712
+ for (const [name, operators] of Object.entries(where)) {
11713
+ mapped[byName.get(name)?.column ?? name] = operators;
11714
+ }
11715
+ return mapped;
11716
+ };
11717
+ var projectRow = (record, fields, explicit) => {
11718
+ const out = {};
11719
+ for (const field of fields) {
11720
+ const value = record[field.column];
11721
+ if (value === void 0 || value === null) {
11722
+ if (explicit) out[field.name] = null;
11723
+ continue;
11724
+ }
11725
+ out[field.name] = value;
11726
+ }
11727
+ return out;
11728
+ };
11729
+ var clampLimit = (raw) => {
11730
+ const asNumber = typeof raw === "number" || typeof raw === "string" && raw.trim() !== "" ? Math.floor(Number(raw)) : Number.NaN;
11731
+ if (!Number.isFinite(asNumber) || asNumber <= 0) return FIND_DEFAULT_LIMIT;
11732
+ return Math.min(asNumber, FIND_MAX_LIMIT);
11733
+ };
11734
+ var validateWhere = (filterable, where, contextName) => {
11735
+ const names = new Set(filterable.map((f) => f.name));
11736
+ const unknown = Object.keys(where).filter((key) => !names.has(key));
11737
+ if (unknown.length > 0) {
11738
+ return `Unknown filter field${unknown.length > 1 ? "s" : ""} ${unknown.map((n) => `"${n}"`).join(", ")} for "${contextName}". Valid filter fields: ${nameList(filterable)}.`;
11739
+ }
11740
+ const byName = new Map(filterable.map((f) => [f.name, f]));
11741
+ for (const [name, operators] of Object.entries(where)) {
11742
+ if (!operators || typeof operators !== "object" || Array.isArray(operators)) {
11743
+ return `The filter on "${name}" must be an object of operators, e.g. { "${name}": { "eq": \u2026 } }.`;
11744
+ }
11745
+ const allowed = operatorsForField(byName.get(name));
11746
+ const keys = Object.keys(operators);
11747
+ const inValue = operators["in"];
11748
+ if (Array.isArray(inValue) && inValue.length === 0) {
11749
+ return `The "in" filter on "${name}" is an empty list, which matches nothing. Give at least one value, or drop the filter.`;
11750
+ }
11751
+ const badOperators = keys.filter((key) => !allowed.includes(key));
11752
+ if (keys.length === 0 || badOperators.length > 0) {
11753
+ return `The filter on "${name}" uses ${keys.length === 0 ? "no operator" : `unsupported operator(s) ${badOperators.map((k) => `"${k}"`).join(", ")}`}. Supported operators for "${name}": ${allowed.join(", ")}.`;
11754
+ }
11755
+ }
11756
+ return void 0;
11757
+ };
11758
+ var JSON_FILTER_VALUE = z12.union([
11759
+ z12.string(),
11760
+ z12.number(),
11761
+ z12.boolean(),
11762
+ z12.record(z12.string(), z12.any()),
11763
+ z12.array(z12.any())
11764
+ ]);
11765
+ var filterValueSchema = (type) => {
11766
+ switch (type) {
11767
+ case "json":
11768
+ return JSON_FILTER_VALUE;
11769
+ case "number":
11770
+ return z12.number();
11771
+ case "boolean":
11772
+ return z12.boolean();
11773
+ default:
11774
+ return z12.string();
11775
+ }
11776
+ };
11777
+ var operatorsSchema = (field) => {
11778
+ const value = filterValueSchema(field.type);
11779
+ const allowed = operatorsForField(field);
11780
+ const shape = {
11781
+ eq: value.optional(),
11782
+ ne: value.optional(),
11783
+ // An empty list is not a filter: `whereIn(col, [])` matches no row at all,
11784
+ // which the model reads as "there are none" (final wave, Minor 6).
11785
+ in: z12.array(value).min(1).optional()
11786
+ };
11787
+ if (allowed.includes("contains")) {
11788
+ shape["contains"] = value.optional();
11789
+ }
11790
+ if (allowed.includes("gte")) {
11791
+ shape["gte"] = value.optional();
11792
+ shape["lte"] = value.optional();
11793
+ }
11794
+ return z12.looseObject(shape).optional().describe(
11795
+ `Filter on ${field.name} (${allowed.join(", ")})` + (field.type === "json" ? ": eq/ne/in match the whole stored value, contains does json containment." : ".") + // The platform's own semantics, disclosed because nothing else does:
11796
+ // `lte: 0` deliberately matches NULL as well (final wave, Minor 4).
11797
+ (allowed.includes("lte") ? " `lte` with `0` also matches items where the field is empty." : "")
11798
+ );
11799
+ };
11800
+ var whereSchema = (filterable) => {
11801
+ const shape = {};
11802
+ for (const field of filterable) {
11803
+ shape[field.name] = operatorsSchema(field);
11804
+ }
11805
+ return z12.looseObject(shape).optional().describe(
11806
+ `Filter: an object of field name to operators, e.g. { "name": { "contains": "widget" } }. Several fields are combined with AND. Operators: ${SUPPORTED_OPERATORS.join(", ")} \u2014 "contains" only on text, enum and json fields (each field's own list is on its filter).`
11807
+ );
11808
+ };
11809
+ var checkItemReadAccess = async (context, record, user) => {
11810
+ if (!user) return false;
11811
+ if (await checkRecordAccess(record, "read", user)) return true;
11812
+ const mode = record?.rights_mode;
11813
+ if (mode !== "users" && mode !== "roles" && mode !== "teams") return false;
11814
+ const entity = getTableName(context.id);
11815
+ const { db } = await postgresClient();
11816
+ if (mode === "users") {
11817
+ const grant2 = await db.from("rbac").where({ entity, target_resource_id: record.id, access_type: "User", user_id: user.id }).first();
11818
+ return !!grant2;
11819
+ }
11820
+ if (mode === "roles") {
11821
+ const roleId = typeof user.role === "string" ? user.role : user.role?.id;
11822
+ if (!roleId) return false;
11823
+ const grant2 = await db.from("rbac").where({ entity, target_resource_id: record.id, access_type: "Role", role_id: roleId }).first();
11824
+ return !!grant2;
11825
+ }
11826
+ const teamId = typeof user.team === "string" ? user.team : user.team?.id;
11827
+ if (!teamId) return false;
11828
+ const grant = await db.from("rbac").where({ entity, target_resource_id: record.id, access_type: "Team", team_id: teamId }).first();
11829
+ return !!grant;
11830
+ };
11831
+ var createContextReadTools = (context, deps = {}) => {
11832
+ const segment = contextToolSegment(context);
11833
+ const contextLabel = context.description ? ` ${context.description}` : "";
11834
+ const readable = readableContextFields(context);
11835
+ const filterable = readable.filter((field) => !field.isFile);
11836
+ const findDefaults = readable.filter((field) => field.findDefault);
11837
+ const NOT_FOUND = itemNotFoundMessage(context, "read");
11838
+ const checkAccess = deps.checkAccess ?? checkItemReadAccess;
11839
+ const fieldsInput = (defaults) => z12.array(z12.string()).optional().describe(
11840
+ `Which fields to return \u2014 "id" is always returned whether you name it or not. Omitted, ${defaults}. Available: ${nameList(readable)}.`
11841
+ );
11842
+ const getTool = new ExuluTool({
11843
+ id: `get_${segment}_item`,
11844
+ name: `Get ${context.name} item`,
11845
+ category: "knowledge_base_reading",
11846
+ description: `Read one item from the "${context.name}" knowledge base by id or external_id.${contextLabel} Returns the item's fields as JSON. Reading changes nothing and needs no approval.`,
11847
+ type: "function",
11848
+ inputSchema: z12.object({
11849
+ id: z12.string().optional().describe("The id of the item to read."),
11850
+ external_id: z12.string().optional().describe("The external_id of the item to read, if the id is unknown."),
11851
+ fields: fieldsInput("every readable field of the item is returned")
11852
+ }),
11853
+ config: [],
11854
+ needsApproval: false,
11855
+ execute: async (params) => {
11856
+ const { user } = params;
11857
+ if (treatAsGuest(params.req, user)) {
11858
+ return { result: NOT_FOUND };
11859
+ }
11860
+ if (!params.id && !params.external_id) {
11861
+ return { result: "Provide the id or external_id of the item to read." };
11862
+ }
11863
+ const selection = resolveFields(readable, params.fields, context.name);
11864
+ if ("error" in selection) {
11865
+ return { result: selection.error };
11866
+ }
11867
+ try {
11868
+ const record = await context.getItem({
11869
+ item: { id: params.id, external_id: params.external_id }
11870
+ });
11871
+ if (!record?.id) {
11872
+ return { result: NOT_FOUND };
11873
+ }
11874
+ if (!await checkAccess(context, record, user)) {
11875
+ return { result: NOT_FOUND };
11876
+ }
11877
+ const explicit = Array.isArray(params.fields) && params.fields.length > 0;
11878
+ return {
11879
+ result: `Item: ${JSON.stringify(projectRow(record, selection.fields, explicit))}`
11880
+ };
11881
+ } catch (error) {
11882
+ console.error(`[EXULU] Error reading item in context ${context.id}`, error);
11883
+ return {
11884
+ result: `Failed to read the item in "${context.name}": ${error instanceof Error ? error.message : String(error)}`
11885
+ };
11886
+ }
11887
+ }
11888
+ });
11889
+ const findTool = new ExuluTool({
11890
+ id: `find_${segment}_items`,
11891
+ name: `Find ${context.name} items`,
11892
+ category: "knowledge_base_reading",
11893
+ description: `Find items in the "${context.name}" knowledge base with a structured filter over their fields.${contextLabel} Exact, field-by-field lookup \u2014 for a meaning-based search use the knowledge base search tool instead. Returns up to ${FIND_MAX_LIMIT} items (${FIND_DEFAULT_LIMIT} by default). Archived items are included unless you filter them out with { "archived": { "eq": false } }. Reading changes nothing and needs no approval.`,
11894
+ type: "function",
11895
+ inputSchema: z12.object({
11896
+ where: whereSchema(filterable),
11897
+ limit: z12.coerce.number().optional().describe(
11898
+ `How many items to return at most. Default ${FIND_DEFAULT_LIMIT}, maximum ${FIND_MAX_LIMIT} (a larger number is clamped).`
11899
+ ),
11900
+ fields: fieldsInput(
11901
+ `${findDefaults.map((f) => f.name).join(", ")} are returned`
11902
+ )
11903
+ }),
11904
+ config: [],
11905
+ needsApproval: false,
11906
+ execute: async (params) => {
11907
+ const { user } = params;
11908
+ const limit = clampLimit(params.limit);
11909
+ if (treatAsGuest(params.req, user)) {
11910
+ return { result: "Found 0 item(s): []" };
11911
+ }
11912
+ const requested = Array.isArray(params.fields) && params.fields.length > 0 ? params.fields : void 0;
11913
+ const selection = resolveFields(requested ? readable : findDefaults, requested, context.name);
11914
+ if ("error" in selection) {
11915
+ return { result: selection.error };
11916
+ }
11917
+ const where = params.where && typeof params.where === "object" && !Array.isArray(params.where) ? params.where : void 0;
11918
+ if (where && Object.keys(where).length > 0) {
11919
+ const whereError = validateWhere(filterable, where, context.name);
11920
+ if (whereError) {
11921
+ return { result: whereError };
11922
+ }
11923
+ }
11924
+ try {
11925
+ const items = await context.getItems({
11926
+ filters: where && Object.keys(where).length > 0 ? [whereByColumn(filterable, where)] : [],
11927
+ fields: selectList(selection.fields),
11928
+ user,
11929
+ // A user's role can be the bare id string as well as an object;
11930
+ // `user.role?.id` on a string silently yields undefined, which knex
11931
+ // then refuses as an undefined binding (fix round 1, F3).
11932
+ role: typeof user.role === "string" ? user.role : user.role?.id,
11933
+ limit
11934
+ });
11935
+ return { result: `Found ${items.length} item(s): ${JSON.stringify(items)}` };
11936
+ } catch (error) {
11937
+ if (error instanceof UnknownFilterPathError) {
11938
+ console.warn(`[EXULU] ${findTool.id} refused an unknown json filter path:`, error.message);
11939
+ const field = filterable.find((candidate) => candidate.column === error.field);
11940
+ return {
11941
+ result: field && field.name !== error.field ? new UnknownFilterPathError(field.name, error.offendingPaths, error.validPaths).message : error.message
11942
+ };
11943
+ }
11944
+ console.error(`[EXULU] Error finding items in context ${context.id}`, error);
11945
+ return {
11946
+ result: `Failed to find items in "${context.name}": ${error instanceof Error ? error.message : String(error)}`
11947
+ };
11948
+ }
11949
+ }
11950
+ });
11951
+ return [getTool, findTool];
11952
+ };
11953
+
11505
11954
  // src/templates/tools/context-write-tools.ts
11506
11955
  var MAX_CONTEXT_SEGMENT = 68;
11956
+ var contextToolSegment = (context) => sanitizeName(context.id).slice(0, MAX_CONTEXT_SEGMENT);
11957
+ var itemNotFoundMessage = (context, access) => `Item not found in "${context.name}" or you don't have ${access} access to it.`;
11958
+ var isHiddenField = (field) => field.hidden === true;
11507
11959
  var RESERVED_INPUT_KEYS = /* @__PURE__ */ new Set([
11508
11960
  "model",
11509
11961
  "user",
@@ -11530,29 +11982,29 @@ var buildWriteSchema = (context, mode) => {
11530
11982
  contentKeys.push(key);
11531
11983
  };
11532
11984
  if (mode === "update") {
11533
- shape["id"] = z12.string().optional().describe("The id of the item to update.");
11534
- shape["external_id"] = z12.string().optional().describe("The external_id of the item to update, if the id is unknown. Lookup only \u2014 it is never changed.");
11985
+ shape["id"] = z13.string().optional().describe("The id of the item to update.");
11986
+ shape["external_id"] = z13.string().optional().describe("The external_id of the item to update, if the id is unknown. Lookup only \u2014 it is never changed.");
11535
11987
  }
11536
- addContent("name", z12.string().describe("The name of the item."), true);
11537
- addContent("description", z12.string().describe("A description of the item."), false);
11538
- addContent("tags", z12.array(z12.string()).describe("Tags for the item."), false);
11988
+ addContent("name", z13.string().describe("The name of the item."), true);
11989
+ addContent("description", z13.string().describe("A description of the item."), false);
11990
+ addContent("tags", z13.array(z13.string()).describe("Tags for the item."), false);
11539
11991
  if (mode === "create") {
11540
11992
  addContent(
11541
11993
  "external_id",
11542
- z12.string().describe("An optional external identifier for the item, e.g. an id from a source system."),
11994
+ z13.string().describe("An optional external identifier for the item, e.g. an id from a source system."),
11543
11995
  false
11544
11996
  );
11545
11997
  }
11546
11998
  for (const field of context.fields ?? []) {
11547
11999
  if (field.type === "uuid") continue;
11548
12000
  if (field.calculated === true || field.editable === false) continue;
11549
- if (field.hidden === true) continue;
12001
+ if (isHiddenField(field)) continue;
11550
12002
  if (RESERVED_INPUT_KEYS.has(field.name)) continue;
11551
12003
  if (field.type === "file") {
11552
12004
  const allowed = (field.allowedFileTypes ?? []).map((ext) => ext.toLowerCase());
11553
12005
  const column = `${field.name}_s3key`;
11554
12006
  const allowedNote = allowed.length ? ` Allowed types: ${allowed.join(", ")}.` : "";
11555
- shape[field.name] = (field.required === true && mode === "create" ? z12.string() : z12.string().optional()).describe(
12007
+ shape[field.name] = (field.required === true && mode === "create" ? z13.string() : z13.string().optional()).describe(
11556
12008
  `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." : "")
11557
12009
  );
11558
12010
  contentKeys.push(column);
@@ -11562,34 +12014,34 @@ var buildWriteSchema = (context, mode) => {
11562
12014
  let schema;
11563
12015
  switch (field.type) {
11564
12016
  case "enum":
11565
- schema = z12.string().describe(
12017
+ schema = z13.string().describe(
11566
12018
  `The ${field.name} of the item. Must be one of: ${(field.enumValues ?? []).join(", ")}`
11567
12019
  );
11568
12020
  break;
11569
12021
  case "json":
11570
12022
  jsonFieldNames.push(field.name);
11571
- schema = field.schema ? loosenForTransport(field.schema).describe(`The ${field.name} of the item.`) : z12.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
12023
+ schema = field.schema ? loosenForTransport(field.schema).describe(`The ${field.name} of the item.`) : z13.string().describe(`The ${field.name} of the item, as a valid JSON string.`);
11572
12024
  break;
11573
12025
  case "markdown":
11574
- schema = z12.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
12026
+ schema = z13.string().describe(`The ${field.name} of the item, as a valid Markdown string.`);
11575
12027
  break;
11576
12028
  case "date":
11577
- schema = z12.string().describe(`The ${field.name} of the item, as an ISO-8601 date string.`);
12029
+ schema = z13.string().describe(`The ${field.name} of the item, as an ISO-8601 date string.`);
11578
12030
  break;
11579
12031
  case "number":
11580
- schema = z12.number().describe(`The ${field.name} of the item.`);
12032
+ schema = z13.number().describe(`The ${field.name} of the item.`);
11581
12033
  break;
11582
12034
  case "boolean":
11583
- schema = z12.boolean().describe(`The ${field.name} of the item.`);
12035
+ schema = z13.boolean().describe(`The ${field.name} of the item.`);
11584
12036
  break;
11585
12037
  default:
11586
- schema = z12.string().describe(`The ${field.name} of the item.`);
12038
+ schema = z13.string().describe(`The ${field.name} of the item.`);
11587
12039
  break;
11588
12040
  }
11589
12041
  addContent(field.name, schema, field.required === true);
11590
12042
  }
11591
12043
  if (mode === "update" && jsonFieldNames.length > 0 && !shape["merge"]) {
11592
- shape["merge"] = z12.array(z12.string()).optional().describe(
12044
+ shape["merge"] = z13.array(z13.string()).optional().describe(
11593
12045
  `Names of json fields in THIS call (choose from: ${jsonFieldNames.join(", ")}) whose given value should be merged into the stored value instead of replacing it: only the keys given are changed, every other stored key is kept, and giving a key an explicit null value deletes just that key. Omit a field's name here (or omit "merge" entirely) to replace its whole value, as normal. Every name must be spelled exactly as listed above AND be a field you are sending a value for in this same call; a name that is neither is refused, not ignored. Do not run two merges on the same item at once: a merge reads the stored value and writes the combined result in two steps with no lock, so overlapping merges can lose one of them.`
11594
12046
  );
11595
12047
  }
@@ -11659,7 +12111,7 @@ var pickContent = (params, contentKeys) => {
11659
12111
  var jobNote = (job) => job ? ` Processing/embeddings queued (job: ${job}); changes become searchable when the job completes.` : "";
11660
12112
  var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
11661
12113
  const tools = [];
11662
- const segment = sanitizeName(context.id).slice(0, MAX_CONTEXT_SEGMENT);
12114
+ const segment = contextToolSegment(context);
11663
12115
  const contextLabel = context.description ? ` ${context.description}` : "";
11664
12116
  if (perms.create) {
11665
12117
  const { shape, contentKeys, fileFields } = buildWriteSchema(context, "create");
@@ -11671,12 +12123,12 @@ var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
11671
12123
  category: "knowledge_base_editing",
11672
12124
  description: `Create a new item in the "${context.name}" knowledge base.${contextLabel}${fileNote}`,
11673
12125
  type: "function",
11674
- inputSchema: z12.object(shape),
12126
+ inputSchema: z13.object(shape),
11675
12127
  config: [],
11676
12128
  needsApproval: !skipApproval,
11677
12129
  execute: async (params) => {
11678
12130
  const { user, exuluConfig } = params;
11679
- if (!user?.id) {
12131
+ if (treatAsGuest(params.req, user)) {
11680
12132
  return { result: "Knowledge base writes require an authenticated user." };
11681
12133
  }
11682
12134
  try {
@@ -11716,7 +12168,7 @@ var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
11716
12168
  if (perms.update) {
11717
12169
  const { shape, contentKeys, fileFields } = buildWriteSchema(context, "update");
11718
12170
  const fileNote = fileFields.length ? " File fields take the name of a file from this session's files; omit them to keep the current file." : "";
11719
- const NOT_FOUND = `Item not found in "${context.name}" or you don't have write access to it.`;
12171
+ const NOT_FOUND = itemNotFoundMessage(context, "write");
11720
12172
  tools.push(
11721
12173
  new ExuluTool({
11722
12174
  id: `update_${segment}_item`,
@@ -11724,12 +12176,12 @@ var createContextWriteTools = (context, perms, skipApproval, deps = {}) => {
11724
12176
  category: "knowledge_base_editing",
11725
12177
  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}`,
11726
12178
  type: "function",
11727
- inputSchema: z12.object(shape),
12179
+ inputSchema: z13.object(shape),
11728
12180
  config: [],
11729
12181
  needsApproval: !skipApproval,
11730
12182
  execute: async (params) => {
11731
12183
  const { user, exuluConfig } = params;
11732
- if (!user?.id) {
12184
+ if (treatAsGuest(params.req, user)) {
11733
12185
  return { result: "Knowledge base writes require an authenticated user." };
11734
12186
  }
11735
12187
  try {
@@ -11796,9 +12248,9 @@ var createKbEditorPickerTool = () => new ExuluTool({
11796
12248
  id: KB_EDITOR_TOOL_ID,
11797
12249
  name: "Knowledge base editor",
11798
12250
  category: "default",
11799
- 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.",
12251
+ 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. Per selected knowledge base the entry expands into create, update, get and find tools \u2014 writing implies reading, and the read tools never ask for approval.",
11800
12252
  type: "function",
11801
- inputSchema: z12.object({}),
12253
+ inputSchema: z13.object({}),
11802
12254
  config: [
11803
12255
  {
11804
12256
  name: "knowledge_bases",
@@ -11813,7 +12265,7 @@ var createKbEditorPickerTool = () => new ExuluTool({
11813
12265
  }
11814
12266
  ],
11815
12267
  execute: async () => ({
11816
- result: "This entry is configuration-only; Exulu expands it into per-context create/update tools at runtime."
12268
+ result: "This entry is configuration-only; Exulu expands it into per-context create, update, get and find tools at runtime."
11817
12269
  })
11818
12270
  });
11819
12271
  var collectKbWriteTools = (agent, contexts, deps = {}) => {
@@ -11831,13 +12283,14 @@ var collectKbWriteTools = (agent, contexts, deps = {}) => {
11831
12283
  continue;
11832
12284
  }
11833
12285
  tools.push(...createContextWriteTools(context, perms, config.skipApproval, deps));
12286
+ tools.push(...createContextReadTools(context));
11834
12287
  }
11835
12288
  return tools;
11836
12289
  };
11837
12290
 
11838
12291
  // src/templates/tools/skill-author-tools.ts
11839
12292
  import { randomUUID as randomUUID4 } from "crypto";
11840
- import { z as z13 } from "zod";
12293
+ import { z as z14 } from "zod";
11841
12294
 
11842
12295
  // ee/rbac-resolver.ts
11843
12296
  var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
@@ -11869,90 +12322,6 @@ var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
11869
12322
  };
11870
12323
  };
11871
12324
 
11872
- // src/utils/check-record-access.ts
11873
- var checkRecordAccessCache = /* @__PURE__ */ new Map();
11874
- var checkRecordAccess = async (record, request, user) => {
11875
- const setRecordAccessCache = (hasAccess2) => {
11876
- checkRecordAccessCache.set(`${record.id}-${request}-${user?.id}`, {
11877
- hasAccess: hasAccess2,
11878
- expiresAt: new Date(Date.now() + 1e3 * 60 * 1)
11879
- // 1 minute
11880
- });
11881
- };
11882
- const cachedAccess = checkRecordAccessCache.get(`${record.id}-${request}-${user?.id}`);
11883
- if (cachedAccess && cachedAccess.expiresAt > /* @__PURE__ */ new Date()) {
11884
- return cachedAccess.hasAccess;
11885
- }
11886
- const isPublic = record.rights_mode === "public";
11887
- const byUsers = record.rights_mode === "users";
11888
- const byRoles = record.rights_mode === "roles";
11889
- const byTeams = record.rights_mode === "teams";
11890
- const createdBy = typeof record.created_by === "string" ? record.created_by : record.created_by?.toString();
11891
- const isCreator = user ? createdBy === user.id.toString() : false;
11892
- const isAdmin = user ? user.super_admin : false;
11893
- const isApi = user ? user.type === "api" : false;
11894
- const isAdminApi = isApi && (!user.scope_mode || user.scope_mode === "admin");
11895
- const isAgentsScopedApi = isApi && user.scope_mode === "agents" && request === "read" && Array.isArray(user.agent_ids) && user.agent_ids.includes(String(record.id));
11896
- let hasAccess = "none";
11897
- if (isPublic || isCreator || isAdmin || isAdminApi || isAgentsScopedApi) {
11898
- setRecordAccessCache(true);
11899
- return true;
11900
- }
11901
- if (byUsers) {
11902
- if (!user) {
11903
- setRecordAccessCache(false);
11904
- return false;
11905
- }
11906
- hasAccess = record.RBAC?.users?.find((x) => x.id === user.id)?.rights || "none";
11907
- if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
11908
- console.error(
11909
- `[EXULU] Your current user ${user.id} does not have access to this record, current access type is: ${hasAccess}.`
11910
- );
11911
- setRecordAccessCache(false);
11912
- return false;
11913
- } else {
11914
- setRecordAccessCache(true);
11915
- return true;
11916
- }
11917
- }
11918
- if (byRoles) {
11919
- if (!user) {
11920
- setRecordAccessCache(false);
11921
- return false;
11922
- }
11923
- hasAccess = record.RBAC?.roles?.find((x) => x.id === user.role?.id)?.rights || "none";
11924
- if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
11925
- console.error(
11926
- `[EXULU] Your current role ${user.role?.name} does not have access to this record, current access type is: ${hasAccess}.`
11927
- );
11928
- setRecordAccessCache(false);
11929
- return false;
11930
- } else {
11931
- setRecordAccessCache(true);
11932
- return true;
11933
- }
11934
- }
11935
- if (byTeams) {
11936
- if (!user) {
11937
- setRecordAccessCache(false);
11938
- return false;
11939
- }
11940
- hasAccess = record.RBAC?.teams?.find((x) => x.id === user.team?.id)?.rights || "none";
11941
- if (!hasAccess || hasAccess === "none" || hasAccess !== request) {
11942
- console.error(
11943
- `[EXULU] Your current team ${user.team?.name} does not have access to this record, current access type is: ${hasAccess}.`
11944
- );
11945
- setRecordAccessCache(false);
11946
- return false;
11947
- } else {
11948
- setRecordAccessCache(true);
11949
- return true;
11950
- }
11951
- }
11952
- setRecordAccessCache(false);
11953
- return false;
11954
- };
11955
-
11956
12325
  // src/skills/skill-access.ts
11957
12326
  async function resolveSkillByName(db, name) {
11958
12327
  const row = await db("skills").where({ name }).first();
@@ -12141,7 +12510,7 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12141
12510
  config: [],
12142
12511
  needsApproval: false,
12143
12512
  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.",
12144
- inputSchema: z13.object({ query: z13.string().optional().describe("Optional substring to filter by name or description") }),
12513
+ inputSchema: z14.object({ query: z14.string().optional().describe("Optional substring to filter by name or description") }),
12145
12514
  execute: async (params) => {
12146
12515
  const { user } = params;
12147
12516
  if (!user?.id) return err2("Skills require a signed-in user.");
@@ -12167,9 +12536,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
12167
12536
  config: [],
12168
12537
  needsApproval: false,
12169
12538
  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.",
12170
- inputSchema: z13.object({
12171
- skill: z13.string().describe("The skill's name or id"),
12172
- path: z13.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
12539
+ inputSchema: z14.object({
12540
+ skill: z14.string().describe("The skill's name or id"),
12541
+ path: z14.string().optional().describe("A file path inside the skill to read instead of SKILL.md")
12173
12542
  }),
12174
12543
  execute: async (params) => {
12175
12544
  const { user, exuluConfig } = params;
@@ -12214,10 +12583,10 @@ ${content}`
12214
12583
  needsApproval: !config.skipApproval,
12215
12584
  needsApprovalFn: approvalFn,
12216
12585
  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.",
12217
- inputSchema: z13.object({
12218
- name: z13.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
12219
- description: z13.string().describe("One line: what the skill does and when to use it"),
12220
- files: z13.array(z13.object({ path: z13.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z13.string() })).min(1).describe("The skill's files; SKILL.md is required")
12586
+ inputSchema: z14.object({
12587
+ name: z14.string().describe("Short, specific skill name (e.g. 'quarterly-report-from-crm')"),
12588
+ description: z14.string().describe("One line: what the skill does and when to use it"),
12589
+ files: z14.array(z14.object({ path: z14.string().describe("Relative path inside the skill, e.g. SKILL.md or references/checklist.md"), content: z14.string() })).min(1).describe("The skill's files; SKILL.md is required")
12221
12590
  }),
12222
12591
  execute: async (params) => {
12223
12592
  const { user, exuluConfig } = params;
@@ -12283,12 +12652,12 @@ ${content}`
12283
12652
  needsApproval: !config.skipApproval,
12284
12653
  needsApprovalFn: approvalFn,
12285
12654
  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.",
12286
- inputSchema: z13.object({
12287
- skill: z13.string().describe("The skill's name or id"),
12288
- files: z13.array(z13.object({ path: z13.string(), content: z13.string() })).optional().describe("Files to add or replace, full content each"),
12289
- deletePaths: z13.array(z13.string()).optional().describe("Paths to remove in the new version"),
12290
- description: z13.string().optional().describe("A new one-line description, if it changed"),
12291
- label: z13.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
12655
+ inputSchema: z14.object({
12656
+ skill: z14.string().describe("The skill's name or id"),
12657
+ files: z14.array(z14.object({ path: z14.string(), content: z14.string() })).optional().describe("Files to add or replace, full content each"),
12658
+ deletePaths: z14.array(z14.string()).optional().describe("Paths to remove in the new version"),
12659
+ description: z14.string().optional().describe("A new one-line description, if it changed"),
12660
+ label: z14.string().optional().describe("A short label for this version, e.g. 'Added the review checklist'")
12292
12661
  }),
12293
12662
  execute: async (params) => {
12294
12663
  const { user, exuluConfig } = params;
@@ -12365,7 +12734,7 @@ var createSkillAuthorPickerTool = () => new ExuluTool({
12365
12734
  category: "default",
12366
12735
  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.",
12367
12736
  type: "function",
12368
- inputSchema: z13.object({}),
12737
+ inputSchema: z14.object({}),
12369
12738
  config: [
12370
12739
  { name: "create", description: "The agent may propose new skills.", type: "boolean", default: true },
12371
12740
  { name: "update", description: "The agent may publish new versions of skills the user can write.", type: "boolean", default: true },
@@ -13334,7 +13703,7 @@ var buildSkillSandboxEvent = (ctx, opts = {}) => {
13334
13703
  // ee/invoke-skills/create-sandbox.ts
13335
13704
  import { createBashTool } from "bash-tool";
13336
13705
  import { tool as tool2 } from "ai";
13337
- import { z as z14 } from "zod";
13706
+ import { z as z15 } from "zod";
13338
13707
  import CryptoJS3 from "crypto-js";
13339
13708
  var getAllExuluVariables = async () => {
13340
13709
  const { db } = await postgresClient();
@@ -13858,9 +14227,9 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13858
14227
  });
13859
14228
  const writeFileTool = tool2({
13860
14229
  description: 'Write content to a file in the sandbox. Creates parent directories if needed. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/<Skill name>/SKILL.md") and leading-slash paths ("/skills/<Skill name>/SKILL.md") work and reach the same file. When the path is under the session artifact tree, the file is also uploaded to S3 and a short-lived presigned URL is returned in the tool output.',
13861
- inputSchema: z14.object({
13862
- path: z14.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
13863
- content: z14.string().describe("The content to write to the file")
14230
+ inputSchema: z15.object({
14231
+ path: z15.string().describe("The path where the file should be written. Relative paths and leading-slash paths are both resolved against the session sandbox root."),
14232
+ content: z15.string().describe("The content to write to the file")
13864
14233
  }),
13865
14234
  execute: async ({ path: path3, content }) => {
13866
14235
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -13879,8 +14248,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13879
14248
  });
13880
14249
  const readFileTool = tool2({
13881
14250
  description: 'Read the contents of a file from the sandbox. Paths are always resolved against the session sandbox root \u2014 both relative paths ("skills/<Skill name>/SKILL.md") and leading-slash paths ("/skills/<Skill name>/SKILL.md") work and reach the same file. Skills live in a folder per skill: "skills/<Skill name>/SKILL.md", never "skills/<Skill name>.md". If the file does not exist, the error message is surfaced verbatim.',
13882
- inputSchema: z14.object({
13883
- path: z14.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
14251
+ inputSchema: z15.object({
14252
+ path: z15.string().describe("The path of the file to read. Relative paths and leading-slash paths are both resolved against the session sandbox root.")
13884
14253
  }),
13885
14254
  execute: async ({ path: path3 }) => {
13886
14255
  const resolvedPath = resolveSessionPath(path3, sessionDir);
@@ -13897,8 +14266,8 @@ Probe error: ${probe.reason ?? "(no detail)"}`
13897
14266
  const originalBashTool = tools.bash;
13898
14267
  const bashTool = tool2({
13899
14268
  description: originalBashTool.description ?? "",
13900
- inputSchema: z14.object({
13901
- command: z14.string().describe("The bash command to execute.")
14269
+ inputSchema: z15.object({
14270
+ command: z15.string().describe("The bash command to execute.")
13902
14271
  }),
13903
14272
  execute: async (args, opts) => {
13904
14273
  const before = persistenceEnabled ? await snapshotSessionArtifacts() : null;
@@ -14170,7 +14539,7 @@ var buildAuthToolModelOutput = (tool3) => ({ output }) => {
14170
14539
  };
14171
14540
 
14172
14541
  // src/templates/tools/session-file-read-tool.ts
14173
- import { z as z15 } from "zod";
14542
+ import { z as z16 } from "zod";
14174
14543
  var DEFAULT_LIMIT = 250;
14175
14544
  var MAX_CONTENT_CHARS = 16e3;
14176
14545
  var SESSION_FILE_READ_TOOL_NAME = "read_session_file";
@@ -14223,10 +14592,10 @@ var createSessionFileReadTool = ({
14223
14592
  name: SESSION_FILE_READ_TOOL_NAME,
14224
14593
  needsApproval: false,
14225
14594
  description: "Read a line range from a file stored in this session's files \u2014 including offloaded tool outputs (tool-output-*.txt) and uploaded documents. Use offset (1-based line number) and limit to page through large files instead of reading everything at once.",
14226
- inputSchema: z15.object({
14227
- filename: z15.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
14228
- offset: z15.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
14229
- limit: z15.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
14595
+ inputSchema: z16.object({
14596
+ filename: z16.string().describe('Exact session file name as referenced in a truncation notice, e.g. "tool-output-web_search-a1b2c3d4.txt"'),
14597
+ offset: z16.number().int().min(1).optional().describe("1-based first line to read (default 1)"),
14598
+ limit: z16.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT})`)
14230
14599
  }),
14231
14600
  type: "function",
14232
14601
  category: "session",
@@ -14239,7 +14608,7 @@ var createSessionFileReadTool = ({
14239
14608
  };
14240
14609
 
14241
14610
  // src/templates/tools/parse-document-tool.ts
14242
- import { z as z16 } from "zod";
14611
+ import { z as z17 } from "zod";
14243
14612
  import { extname } from "path";
14244
14613
  import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
14245
14614
 
@@ -14608,11 +14977,11 @@ ${text.trim()}`).join("\n");
14608
14977
  name: PARSE_DOCUMENT_TOOL_NAME,
14609
14978
  needsApproval: false,
14610
14979
  description: `Extract the text of an uploaded PDF or Office document from this session's files, with "--- page N ---" markers for PDFs so you can locate content by page. Free and fast (no OCR): works only on documents with a real text layer. To SEE a page or an image inside a document, use view_document_page.`,
14611
- inputSchema: z16.object({
14612
- filename: z16.string().describe('Exact session file name, e.g. "report.pdf"'),
14613
- pages: z16.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14614
- offset: z16.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14615
- limit: z16.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
14980
+ inputSchema: z17.object({
14981
+ filename: z17.string().describe('Exact session file name, e.g. "report.pdf"'),
14982
+ pages: z17.string().optional().describe('PDF page or range to extract, e.g. "2" or "1-5" (default: all pages) (PDF only)'),
14983
+ offset: z17.number().int().min(1).optional().describe("1-based first output line to read (default 1)"),
14984
+ limit: z17.number().int().min(1).max(1e3).optional().describe(`Number of lines to read (default ${DEFAULT_LIMIT2})`)
14616
14985
  }),
14617
14986
  type: "function",
14618
14987
  category: "session",
@@ -14625,7 +14994,7 @@ ${text.trim()}`).join("\n");
14625
14994
  };
14626
14995
 
14627
14996
  // src/templates/tools/view-document-page-tool.ts
14628
- import { z as z17 } from "zod";
14997
+ import { z as z18 } from "zod";
14629
14998
  import { extname as extname3 } from "path";
14630
14999
 
14631
15000
  // src/sessions/pdf-preview-cache.ts
@@ -14896,9 +15265,9 @@ var createViewDocumentPageTool = ({
14896
15265
  name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
14897
15266
  needsApproval: false,
14898
15267
  description: "LOOK at a page of an uploaded PDF/Office document, or at an uploaded image, from this session's files. The rendered image is attached as a user message directly after this tool result so you can visually analyze photos, charts, scans, and layouts. Use parse_document first to find which page you need. Requires a vision-capable model.",
14899
- inputSchema: z17.object({
14900
- filename: z17.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
14901
- page: z17.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
15268
+ inputSchema: z18.object({
15269
+ filename: z18.string().describe('Exact session file name, e.g. "report.pdf" or "screenshot.png"'),
15270
+ page: z18.number().int().min(1).optional().describe("Page number to render (default 1; ignored for image files)")
14902
15271
  }),
14903
15272
  type: "function",
14904
15273
  category: "session",
@@ -15073,8 +15442,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15073
15442
  let projectScope;
15074
15443
  if (project && !disabled.has("agentic_context_search")) {
15075
15444
  const { db } = await postgresClient();
15076
- const projectRow = await db.from("projects").where("id", project).first();
15077
- let rawItems = projectRow?.project_items;
15445
+ const projectRow2 = await db.from("projects").where("id", project).first();
15446
+ let rawItems = projectRow2?.project_items;
15078
15447
  if (typeof rawItems === "string") {
15079
15448
  try {
15080
15449
  rawItems = JSON.parse(rawItems);
@@ -15082,12 +15451,12 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
15082
15451
  rawItems = void 0;
15083
15452
  }
15084
15453
  }
15085
- if (projectRow && Array.isArray(rawItems) && rawItems.length > 0) {
15454
+ if (projectRow2 && Array.isArray(rawItems) && rawItems.length > 0) {
15086
15455
  projectScope = {
15087
- id: projectRow.id,
15088
- name: projectRow.name,
15089
- description: projectRow.description ?? void 0,
15090
- customInstructions: projectRow.custom_instructions ?? void 0,
15456
+ id: projectRow2.id,
15457
+ name: projectRow2.name,
15458
+ description: projectRow2.description ?? void 0,
15459
+ customInstructions: projectRow2.custom_instructions ?? void 0,
15091
15460
  items: rawItems,
15092
15461
  kbProfileDefaults: buildProjectKbProfileDefaults(rawItems)
15093
15462
  };
@@ -15554,6 +15923,7 @@ export {
15554
15923
  hasAgentsReadAccess,
15555
15924
  hasAgentsWriteAccess,
15556
15925
  applyAccessControl,
15926
+ applyFiltersGrouped,
15557
15927
  applyFilters,
15558
15928
  workflowTemplatesSchema,
15559
15929
  userCredentialsSchema,
@@ -15595,6 +15965,8 @@ export {
15595
15965
  collectMemoryDecisions,
15596
15966
  sessionFilePrefix,
15597
15967
  sanitizeFilename,
15968
+ isPublicSurface,
15969
+ treatAsGuest,
15598
15970
  KB_EDITOR_TOOL_ID,
15599
15971
  createKbEditorPickerTool,
15600
15972
  RBACResolver,