@exulu/backend 5.1.1 → 5.2.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.
Files changed (56) hide show
  1. package/dist/{chunk-UXHMHM4E.js → chunk-ASF74XFZ.js} +271 -33
  2. package/dist/{convert-exulu-tools-to-ai-sdk-tools-FHFMJSD2.js → convert-exulu-tools-to-ai-sdk-tools-MFLZQONB.js} +3 -1
  3. package/dist/index.cjs +2761 -355
  4. package/dist/index.js +2425 -305
  5. package/ee/agentic-retrieval/pipeline/config.test.ts +42 -0
  6. package/ee/agentic-retrieval/pipeline/config.ts +36 -0
  7. package/ee/agentic-retrieval/pipeline/index.test.ts +3 -3
  8. package/ee/agentic-retrieval/pipeline/index.ts +43 -1
  9. package/ee/agentic-retrieval/pipeline/micro-call.test.ts +58 -0
  10. package/ee/agentic-retrieval/pipeline/micro-call.ts +20 -3
  11. package/ee/agentic-retrieval/pipeline/near-duplicates.test.ts +50 -0
  12. package/ee/agentic-retrieval/pipeline/near-duplicates.ts +74 -0
  13. package/ee/agentic-retrieval/pipeline/prefilter.test.ts +32 -0
  14. package/ee/agentic-retrieval/pipeline/prefilter.ts +13 -1
  15. package/ee/agentic-retrieval/pipeline/rerank.test.ts +79 -0
  16. package/ee/agentic-retrieval/pipeline/rerank.ts +61 -6
  17. package/ee/claim-check/agent-config.ts +26 -0
  18. package/ee/claim-check/concurrency.test.ts +33 -0
  19. package/ee/claim-check/concurrency.ts +30 -0
  20. package/ee/claim-check/evidence.test.ts +198 -0
  21. package/ee/claim-check/evidence.ts +162 -0
  22. package/ee/claim-check/prompts/decompose.ts +52 -0
  23. package/ee/claim-check/prompts/disambiguate.ts +58 -0
  24. package/ee/claim-check/prompts/select-disambiguate.ts +17 -0
  25. package/ee/claim-check/prompts/select.ts +55 -0
  26. package/ee/claim-check/prompts/shared.test.ts +193 -0
  27. package/ee/claim-check/prompts/shared.ts +89 -0
  28. package/ee/claim-check/prompts/verify.ts +56 -0
  29. package/ee/claim-check/rate-limit.test.ts +40 -0
  30. package/ee/claim-check/rate-limit.ts +82 -0
  31. package/ee/claim-check/routes.test.ts +1188 -0
  32. package/ee/claim-check/routes.ts +682 -0
  33. package/ee/claim-check/run.test.ts +1317 -0
  34. package/ee/claim-check/run.ts +710 -0
  35. package/ee/claim-check/score.test.ts +108 -0
  36. package/ee/claim-check/score.ts +75 -0
  37. package/ee/claim-check/second-chance.test.ts +89 -0
  38. package/ee/claim-check/second-chance.ts +80 -0
  39. package/ee/claim-check/split.test.ts +179 -0
  40. package/ee/claim-check/split.ts +220 -0
  41. package/ee/claim-check/stages/decompose.test.ts +129 -0
  42. package/ee/claim-check/stages/decompose.ts +64 -0
  43. package/ee/claim-check/stages/disambiguate.test.ts +130 -0
  44. package/ee/claim-check/stages/disambiguate.ts +74 -0
  45. package/ee/claim-check/stages/select-disambiguate.test.ts +137 -0
  46. package/ee/claim-check/stages/select-disambiguate.ts +90 -0
  47. package/ee/claim-check/stages/select.test.ts +155 -0
  48. package/ee/claim-check/stages/select.ts +94 -0
  49. package/ee/claim-check/stages/usage.ts +11 -0
  50. package/ee/claim-check/stages/verify.test.ts +154 -0
  51. package/ee/claim-check/stages/verify.ts +78 -0
  52. package/ee/claim-check/types.ts +178 -0
  53. package/ee/entitlements.ts +3 -0
  54. package/ee/schemas.ts +71 -0
  55. package/ee/workers.ts +16 -0
  56. package/package.json +1 -1
@@ -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-FHFMJSD2.js");
1726
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-MFLZQONB.js");
1727
1727
  const tools = await convertExuluToolsToAiSdkTools2(
1728
1728
  [this],
1729
1729
  [],
@@ -1819,6 +1819,7 @@ var isEmbedderNotConfigured = (err2) => !!err2 && err2.name === "ContextEmbedder
1819
1819
 
1820
1820
  // src/templates/tools/session-items-retrieval-tool.ts
1821
1821
  import { z as z2 } from "zod";
1822
+ var SESSION_ITEMS_RETRIEVAL_TOOL_NAME = "context_search in knowledge items added to session.";
1822
1823
  var createSessionItemsRetrievalTool = async ({
1823
1824
  user,
1824
1825
  role,
@@ -1828,7 +1829,7 @@ var createSessionItemsRetrievalTool = async ({
1828
1829
  console.log("[EXULU] Session search tool created for session", items);
1829
1830
  const sessionItemsRetrievalTool = ExuluTool.internal({
1830
1831
  id: "session_items_information_context_search",
1831
- name: "context_search in knowledge items added to session.",
1832
+ name: SESSION_ITEMS_RETRIEVAL_TOOL_NAME,
1832
1833
  description: "Context search in knowledge items added to session.",
1833
1834
  inputSchema: z2.object({
1834
1835
  query: z2.string().describe("The query to retrieve information from knowledge items added to the session.")
@@ -1923,7 +1924,8 @@ var ENTITLEMENTS = {
1923
1924
  "agent-feedback": false,
1924
1925
  "multi-agent-tooling": false,
1925
1926
  "advanced-document-processing": false,
1926
- "rate-limits": false
1927
+ "rate-limits": false,
1928
+ "claim-check": false
1927
1929
  };
1928
1930
  var checkLicense = () => {
1929
1931
  if (!process.env.EXULU_ENTERPRISE_LICENSE || process.env.EXULU_ENTERPRISE_LICENSE === "" || !process.env.EXULU_ENTERPRISE_LICENSE.startsWith("EXULU_EE_")) {
@@ -1942,7 +1944,8 @@ var checkLicense = () => {
1942
1944
  "agent-feedback": true,
1943
1945
  "multi-agent-tooling": true,
1944
1946
  "advanced-document-processing": true,
1945
- "rate-limits": true
1947
+ "rate-limits": true,
1948
+ "claim-check": true
1946
1949
  };
1947
1950
  }
1948
1951
  };
@@ -2045,6 +2048,18 @@ async function resolveReranker(input) {
2045
2048
 
2046
2049
  // ee/agentic-retrieval/pipeline/config.ts
2047
2050
  import { z as z3 } from "zod";
2051
+
2052
+ // ee/claim-check/types.ts
2053
+ var CLAIM_CHECK_MAX_OUTPUT_TOKENS = 8e3;
2054
+ var CLAIM_CHECK_DEFAULTS = {
2055
+ fidelity: "fast",
2056
+ completions: 1,
2057
+ reRetrieve: true,
2058
+ thresholds: { warn: 0.1, alert: 0.3 },
2059
+ caps: { maxSentences: 120, maxClaims: 200, maxReRetrievals: 10 }
2060
+ };
2061
+
2062
+ // ee/agentic-retrieval/pipeline/config.ts
2048
2063
  var KB_KINDS = ["documents", "conversations", "records"];
2049
2064
  var DEFAULT_PREFILTER_CUTOFF = 2.5;
2050
2065
  var RRF_K = 60;
@@ -2108,6 +2123,24 @@ var tuningSchema = z3.object({
2108
2123
  parallelPins: z3.boolean().default(true)
2109
2124
  }).default({ mergedMemoryCall: true, mergedRoutingCall: true, parallelPins: true })
2110
2125
  });
2126
+ var claimCheckSchema = z3.object({
2127
+ enabled: z3.boolean().default(false),
2128
+ /** Empty = fall back to the agent's utility model, then the agent's model. */
2129
+ model: z3.string().default(""),
2130
+ fidelity: z3.enum(["fast", "paper"]).default(CLAIM_CHECK_DEFAULTS.fidelity),
2131
+ completions: z3.number().int().min(1).max(3).default(CLAIM_CHECK_DEFAULTS.completions),
2132
+ reRetrieve: z3.boolean().default(CLAIM_CHECK_DEFAULTS.reRetrieve),
2133
+ thresholds: z3.object({
2134
+ warn: z3.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.warn),
2135
+ alert: z3.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.alert)
2136
+ }).default(CLAIM_CHECK_DEFAULTS.thresholds),
2137
+ showToExternalUsers: z3.boolean().default(false),
2138
+ caps: z3.object({
2139
+ maxSentences: z3.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxSentences),
2140
+ maxClaims: z3.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxClaims),
2141
+ maxReRetrievals: z3.number().int().min(0).default(CLAIM_CHECK_DEFAULTS.caps.maxReRetrievals)
2142
+ }).default(CLAIM_CHECK_DEFAULTS.caps)
2143
+ });
2111
2144
  var boolVal = (v) => v === true || v === "true" || v === 1;
2112
2145
  var strVal = (v, fallback) => typeof v === "string" && v.length > 0 ? v : fallback;
2113
2146
  function jsonVal(name, schema, v) {
@@ -2150,6 +2183,8 @@ function defaultFor(name) {
2150
2183
  return {};
2151
2184
  case "tuning":
2152
2185
  return {};
2186
+ case "claim_check":
2187
+ return {};
2153
2188
  default:
2154
2189
  return {};
2155
2190
  }
@@ -2164,12 +2199,14 @@ function parsePipelineConfig(raw) {
2164
2199
  logging: boolVal(r["logging"]),
2165
2200
  projectSearch: r["project_search"] === void 0 || r["project_search"] === "" ? true : boolVal(r["project_search"]),
2166
2201
  showSourcesToExternalUsers: r["show_sources_to_external_users"] === void 0 || r["show_sources_to_external_users"] === "" ? true : boolVal(r["show_sources_to_external_users"]),
2202
+ suppressDuplicatePassages: r["suppress_duplicate_passages"] === void 0 || r["suppress_duplicate_passages"] === "" ? true : boolVal(r["suppress_duplicate_passages"]),
2167
2203
  utilityModel: strVal(r["utility_model"], ""),
2168
2204
  knowledgeBases: jsonVal("knowledge_bases", knowledgeBasesSchema, r["knowledge_bases"]),
2169
2205
  routing: jsonVal("routing", routingSchema, r["routing"]),
2170
2206
  vocabulary: jsonVal("vocabulary", vocabularySchema, r["vocabulary"]),
2171
2207
  memory: jsonVal("memory", memorySchema, r["memory"]),
2172
- tuning: jsonVal("tuning", tuningSchema, r["tuning"])
2208
+ tuning: jsonVal("tuning", tuningSchema, r["tuning"]),
2209
+ claimCheck: jsonVal("claim_check", claimCheckSchema, r["claim_check"])
2173
2210
  };
2174
2211
  }
2175
2212
  var KIND_PRESETS = {
@@ -2297,7 +2334,8 @@ async function microCall(args) {
2297
2334
  temperature = 0,
2298
2335
  maxOutputTokens = MICRO_CALL_MAX_OUTPUT_TOKENS,
2299
2336
  maxAttempts = 3,
2300
- retryBaseDelayMs
2337
+ retryBaseDelayMs,
2338
+ abortSignal
2301
2339
  } = args;
2302
2340
  return withRetry(
2303
2341
  async () => {
@@ -2313,18 +2351,26 @@ async function microCall(args) {
2313
2351
  // tripled request volume per attempt while the provider was already
2314
2352
  // rate-limiting.
2315
2353
  maxRetries: 0,
2316
- providerOptions: microCallProviderOptions(model)
2354
+ providerOptions: microCallProviderOptions(model),
2355
+ ...abortSignal ? { abortSignal } : {}
2317
2356
  });
2357
+ const usage = result.usage;
2318
2358
  return {
2319
2359
  output: schema ? result.output : void 0,
2320
- text: result.text
2360
+ text: result.text,
2361
+ usage: {
2362
+ inputTokens: usage?.inputTokens ?? 0,
2363
+ outputTokens: usage?.outputTokens ?? 0
2364
+ }
2321
2365
  };
2322
2366
  },
2323
2367
  maxAttempts,
2324
2368
  {
2325
2369
  // Empty output is deterministic for identical params — retrying only
2326
- // added latency before the degraded path. Fail fast instead.
2327
- shouldRetry: (error) => !NoOutputGeneratedError.isInstance(error),
2370
+ // added latency before the degraded path. Fail fast instead. An aborted
2371
+ // signal is equally final: the caller's deadline has passed, so another
2372
+ // attempt can only spend tokens on a response nobody will read.
2373
+ shouldRetry: (error) => !NoOutputGeneratedError.isInstance(error) && abortSignal?.aborted !== true,
2328
2374
  ...retryBaseDelayMs !== void 0 ? { baseDelayMs: retryBaseDelayMs } : {}
2329
2375
  }
2330
2376
  );
@@ -2390,6 +2436,7 @@ function applyRewrites(question, rewrites) {
2390
2436
  // ee/agentic-retrieval/pipeline/prefilter.ts
2391
2437
  var SUPPLEMENT_MIN_TOKEN_LENGTH = 4;
2392
2438
  var SUPPLEMENT_BUDGET = 15;
2439
+ var SUPPLEMENT_BUDGET_WIDE = 50;
2393
2440
  var itemCaches = {};
2394
2441
  var ensureItemsCache = async ({
2395
2442
  cacheKey,
@@ -2458,7 +2505,8 @@ async function fuzzyPrefilter({
2458
2505
  normalize,
2459
2506
  cutoff = DEFAULT_PREFILTER_CUTOFF,
2460
2507
  limit,
2461
- supplementSeparatorVariants = false
2508
+ supplementSeparatorVariants = false,
2509
+ supplementBudget = SUPPLEMENT_BUDGET
2462
2510
  }) {
2463
2511
  const cache2 = await ensureItemsCache({ cacheKey, context, fields, normalize });
2464
2512
  if (!relevantKeywords?.length) {
@@ -2571,7 +2619,7 @@ async function fuzzyPrefilter({
2571
2619
  );
2572
2620
  const supplement = [];
2573
2621
  for (const { item } of candidates) {
2574
- if (supplement.length >= SUPPLEMENT_BUDGET) break;
2622
+ if (supplement.length >= supplementBudget) break;
2575
2623
  if (!item.id || seen.has(item.id)) continue;
2576
2624
  seen.add(item.id);
2577
2625
  supplement.push({
@@ -2612,7 +2660,8 @@ async function resolveIdentifierPins({
2612
2660
  identifierSets,
2613
2661
  contextsById,
2614
2662
  kbKindById,
2615
- model
2663
+ model,
2664
+ suppressDuplicatePassages = false
2616
2665
  }) {
2617
2666
  const pinsByContext = /* @__PURE__ */ new Map();
2618
2667
  const exactPinsByContext = /* @__PURE__ */ new Map();
@@ -2648,7 +2697,8 @@ async function resolveIdentifierPins({
2648
2697
  cutoff: DEFAULT_PREFILTER_CUTOFF,
2649
2698
  // Identifier pins are a hard id-whitelist over filenames,
2650
2699
  // which is exactly the case the supplement exists for.
2651
- supplementSeparatorVariants: true
2700
+ supplementSeparatorVariants: true,
2701
+ supplementBudget: suppressDuplicatePassages ? SUPPLEMENT_BUDGET_WIDE : void 0
2652
2702
  });
2653
2703
  if (!matched.length) return;
2654
2704
  const target = pinsByContext.get(ctxId) ?? /* @__PURE__ */ new Set();
@@ -3730,7 +3780,7 @@ function buildRerankObjects(chunks) {
3730
3780
  return objects;
3731
3781
  }
3732
3782
  async function rerankResults(opts) {
3733
- const { chunks, query, state, reranker, tuning } = opts;
3783
+ const { chunks, query, state, reranker, tuning, findNearDuplicates } = opts;
3734
3784
  if (chunks.length === 0) {
3735
3785
  return { limited_results: [], sorted_reranked_results: [], rerank_score_max_genuine: 0 };
3736
3786
  }
@@ -3795,14 +3845,53 @@ async function rerankResults(opts) {
3795
3845
  }
3796
3846
  }
3797
3847
  const { topK } = tuning;
3848
+ const candidateWindow = sorted.slice(0, Math.max(topK * 3, topK + 20));
3849
+ let duplicateOf = /* @__PURE__ */ new Map();
3850
+ if (findNearDuplicates && candidateWindow.length > 1) {
3851
+ try {
3852
+ const pairs = await findNearDuplicates(candidateWindow);
3853
+ for (const [a, b] of pairs) {
3854
+ if (!a || !b) continue;
3855
+ duplicateOf.set(a, [...duplicateOf.get(a) ?? [], b]);
3856
+ duplicateOf.set(b, [...duplicateOf.get(b) ?? [], a]);
3857
+ }
3858
+ } catch (err2) {
3859
+ console.warn("[EXULU pipeline] near-duplicate lookup failed \u2014 selecting without suppression:", err2);
3860
+ duplicateOf = /* @__PURE__ */ new Map();
3861
+ }
3862
+ }
3863
+ const selectDistinct = (pool, n) => {
3864
+ if (duplicateOf.size === 0) return pool.slice(0, n);
3865
+ const picked = [];
3866
+ const pickedIds = /* @__PURE__ */ new Set();
3867
+ const deferred = [];
3868
+ for (const c of pool) {
3869
+ if (picked.length >= n) break;
3870
+ const id = c.chunk_id;
3871
+ if (id && (duplicateOf.get(id) ?? []).some((other) => pickedIds.has(other))) {
3872
+ deferred.push(c);
3873
+ continue;
3874
+ }
3875
+ picked.push(c);
3876
+ if (id) pickedIds.add(id);
3877
+ }
3878
+ for (const c of deferred) {
3879
+ if (picked.length >= n) break;
3880
+ picked.push(c);
3881
+ }
3882
+ return picked;
3883
+ };
3798
3884
  let limited_results = (() => {
3799
- const top = sorted.slice(0, topK);
3885
+ const top = selectDistinct(sorted, topK);
3800
3886
  if (pinnedGroups.length === 0) return top;
3801
3887
  const byId = /* @__PURE__ */ new Map();
3802
3888
  for (const r of [...pinnedGroups, ...top]) {
3803
3889
  if (r.chunk_id && !byId.has(r.chunk_id)) byId.set(r.chunk_id, r);
3804
3890
  }
3805
- return Array.from(byId.values()).sort((a, b) => (b.rerank_score || 0) - (a.rerank_score || 0)).slice(0, Math.max(topK, pinnedGroups.length + topK));
3891
+ return selectDistinct(
3892
+ Array.from(byId.values()).sort((a, b) => (b.rerank_score || 0) - (a.rerank_score || 0)),
3893
+ Math.max(topK, pinnedGroups.length + topK)
3894
+ );
3806
3895
  })();
3807
3896
  if (state.userRequestedPage !== null) {
3808
3897
  const scopeToUserPinned = state.userPinnedItemIds.size > 0;
@@ -3811,11 +3900,59 @@ async function rerankResults(opts) {
3811
3900
  const p = r.chunk_metadata?.page;
3812
3901
  return typeof p === "number" && Math.abs(p - state.userRequestedPage) <= tuning.pageWindow;
3813
3902
  });
3814
- if (pageMatched.length > 0) limited_results = pageMatched.slice(0, topK);
3903
+ if (pageMatched.length > 0) limited_results = selectDistinct(pageMatched, topK);
3815
3904
  }
3816
3905
  return { limited_results, sorted_reranked_results: sorted, rerank_score_max_genuine };
3817
3906
  }
3818
3907
 
3908
+ // src/exulu/table-names.ts
3909
+ var getTableName = (id) => sanitizeName(id) + "_items";
3910
+ var getChunksTableName = (id) => sanitizeName(id) + "_chunks";
3911
+
3912
+ // ee/agentic-retrieval/pipeline/near-duplicates.ts
3913
+ var DUPLICATE_SIMILARITY_THRESHOLD = 0.97;
3914
+ function makeNearDuplicateFinder(opts) {
3915
+ const known = new Set(opts.contextIds);
3916
+ const threshold = opts.threshold ?? DUPLICATE_SIMILARITY_THRESHOLD;
3917
+ return async (candidates) => {
3918
+ const byContext = /* @__PURE__ */ new Map();
3919
+ for (const c of candidates) {
3920
+ const ctxId = c.context?.id;
3921
+ if (!c.chunk_id || !ctxId || !known.has(ctxId)) continue;
3922
+ byContext.set(ctxId, [...byContext.get(ctxId) ?? [], c.chunk_id]);
3923
+ }
3924
+ const work = [...byContext.entries()].filter(([, ids]) => ids.length > 1);
3925
+ if (work.length === 0) return [];
3926
+ try {
3927
+ const db2 = opts.db ?? (await postgresClient()).db;
3928
+ const results = await Promise.all(
3929
+ work.map(async ([ctxId, ids]) => {
3930
+ const table = getChunksTableName(ctxId);
3931
+ try {
3932
+ const res = await db2.raw(
3933
+ `select a.id as a, b.id as b
3934
+ from "${table}" a
3935
+ join "${table}" b on a.id < b.id
3936
+ where a.id = any(?) and b.id = any(?)
3937
+ and a.embedding is not null and b.embedding is not null
3938
+ and (1 - (a.embedding <=> b.embedding)) >= ?`,
3939
+ [ids, ids, threshold]
3940
+ );
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);
3944
+ return [];
3945
+ }
3946
+ })
3947
+ );
3948
+ return results.flat();
3949
+ } catch (err2) {
3950
+ console.warn("[EXULU pipeline] near-duplicate lookup failed to acquire a database connection:", err2);
3951
+ return [];
3952
+ }
3953
+ };
3954
+ }
3955
+
3819
3956
  // ee/agentic-retrieval/pipeline/pin-rerun.ts
3820
3957
  function needsPinRerun(originalQuestion, updatedQuestion) {
3821
3958
  if (originalQuestion === updatedQuestion) return false;
@@ -3925,6 +4062,7 @@ function retrievalBudgetGuard(limit, agenticToolKey, allToolKeys) {
3925
4062
  }
3926
4063
 
3927
4064
  // ee/agentic-retrieval/pipeline/index.ts
4065
+ var AGENTIC_RETRIEVAL_TOOL_NAME = "Context Search";
3928
4066
  function addChunks(result, chunks) {
3929
4067
  const seen = new Set(result.chunks.map((c) => c.chunk_id));
3930
4068
  for (const chunk of chunks) {
@@ -3978,7 +4116,7 @@ function createAgenticRetrievalTool(opts) {
3978
4116
  }
3979
4117
  return ExuluTool.internal({
3980
4118
  id: "agentic_context_search",
3981
- name: "Context Search",
4119
+ name: AGENTIC_RETRIEVAL_TOOL_NAME,
3982
4120
  description: `Intelligent knowledge search across the available knowledge bases: ${contexts.map((c) => c.name || c.id).join(", ")}. Routes the question to the right sources, searches them with query expansion, and returns reranked passages. Results are exhaustive for the given query: do NOT repeat the call with a rephrased version of the same question \u2014 re-call only with genuinely new information (a different product or model, an explicitly named source or document, or new details from the user).` + // Note: the description suffix intentionally remains even when the per-agent project_search
3983
4121
  // config is off — the config is only known at execute time, not at factory time.
3984
4122
  (projectScope ? ` Also searches the knowledge items attached to the project "${projectScope.name}".` : ""),
@@ -4034,6 +4172,12 @@ function createAgenticRetrievalTool(opts) {
4034
4172
  type: "boolean",
4035
4173
  default: true
4036
4174
  },
4175
+ {
4176
+ name: "suppress_duplicate_passages",
4177
+ description: "Keep only the best-scoring copy when several retrieved passages carry near-identical content (the same page re-uploaded under different filenames, a document filed in two folders). Nothing is merged or rewritten \u2014 redundant copies are dropped from the result so the places freed up can carry different information. Also widens the identifier-pin budget, which is only safe together with this. Leave empty to keep it on; set to false to restore the previous behaviour.",
4178
+ type: "boolean",
4179
+ default: true
4180
+ },
4037
4181
  {
4038
4182
  name: "knowledge_bases",
4039
4183
  description: "Per-knowledge-base profiles: enabled, kind (documents | conversations | records), instructions, and per-KB overrides (limit, expand, multiQuery, hyde). JSON object keyed by context id.",
@@ -4069,6 +4213,12 @@ function createAgenticRetrievalTool(opts) {
4069
4213
  description: "When disabled, hides source references (item names, IDs, chunk info) from external users and anonymous guests. Sources are stripped from the tool output and the system prompt guidance for citation is omitted.",
4070
4214
  type: "boolean",
4071
4215
  default: true
4216
+ },
4217
+ {
4218
+ name: "claim_check",
4219
+ description: "Post-answer claim verification: extracts the factual claims the answer makes and reports, per claim, whether the retrieved passages support it, contradict it, or say nothing about it. Runs AFTER the answer has streamed and never delays or changes it. Keys: enabled, model (a fast, cheap model is the right choice), fidelity (fast | paper), completions, reRetrieve, thresholds {warn, alert}, showToExternalUsers, caps {maxSentences, maxClaims, maxReRetrievals}.",
4220
+ type: "json",
4221
+ default: '{"enabled":false,"model":"","fidelity":"fast","thresholds":{"warn":0.1,"alert":0.3}}'
4072
4222
  }
4073
4223
  ],
4074
4224
  inputSchema: z7.object({
@@ -4197,7 +4347,8 @@ ${projectScope.customInstructions}` : ""
4197
4347
  identifierSets: cfg.vocabulary.identifiers,
4198
4348
  contextsById,
4199
4349
  kbKindById,
4200
- model: utilityModel
4350
+ model: utilityModel,
4351
+ suppressDuplicatePassages: cfg.suppressDuplicatePassages
4201
4352
  });
4202
4353
  const [memResult, routResult, parallelPins] = await Promise.all([
4203
4354
  withTiming(timings, "memoryMs", () => runMemoryPhase({
@@ -4366,6 +4517,7 @@ ${projectScope.customInstructions}` : ""
4366
4517
  keywords: updatedKeywords,
4367
4518
  importantKeyword: updatedImportantKeyword
4368
4519
  };
4520
+ const findNearDuplicates = cfg.suppressDuplicatePassages ? makeNearDuplicateFinder({ contextIds: Array.from(contextsById.keys()) }) : void 0;
4369
4521
  result.steps.push({
4370
4522
  stepNumber: 1,
4371
4523
  text: `Reranking ${mainSearch.chunks.length} chunks`,
@@ -4385,7 +4537,8 @@ ${projectScope.customInstructions}` : ""
4385
4537
  pinBoost: cfg.tuning.pinBoost,
4386
4538
  identifierBoost: cfg.tuning.identifierBoost,
4387
4539
  pageWindow: cfg.tuning.pageWindow
4388
- }
4540
+ },
4541
+ findNearDuplicates
4389
4542
  });
4390
4543
  result.steps.push({
4391
4544
  stepNumber: 1,
@@ -4440,7 +4593,8 @@ ${projectScope.customInstructions}` : ""
4440
4593
  pinBoost: cfg.tuning.pinBoost,
4441
4594
  identifierBoost: cfg.tuning.identifierBoost,
4442
4595
  pageWindow: cfg.tuning.pageWindow
4443
- }
4596
+ },
4597
+ findNearDuplicates
4444
4598
  });
4445
4599
  result.steps.push({
4446
4600
  stepNumber: 1,
@@ -5601,10 +5755,6 @@ var ExuluStorage = class {
5601
5755
  // todo add upload and delete methods
5602
5756
  };
5603
5757
 
5604
- // src/exulu/table-names.ts
5605
- var getTableName = (id) => sanitizeName(id) + "_items";
5606
- var getChunksTableName = (id) => sanitizeName(id) + "_chunks";
5607
-
5608
5758
  // src/exulu/context.ts
5609
5759
  import pgvector2 from "pgvector/knex";
5610
5760
 
@@ -6901,6 +7051,10 @@ var captureCodeEmbedder = (context) => {
6901
7051
  return codeEmbedders.get(context);
6902
7052
  };
6903
7053
  var codeEmbedderFor = (context) => codeEmbedders.has(context) ? codeEmbedders.get(context) : context.embedder;
7054
+ var contextEmbedderInfoFor = async (context, deps = {}) => {
7055
+ const resolve4 = deps.resolve ?? resolveContextEmbedder;
7056
+ return resolve4({ id: context.id, embedder: codeEmbedderFor(context) });
7057
+ };
6904
7058
  var willEmbedOnQueue = async (context, overrideQueue) => {
6905
7059
  if (overrideQueue) {
6906
7060
  return registeredQueues().some((q) => q.queue?.name === overrideQueue);
@@ -7039,10 +7193,13 @@ function preprocessQuery(query, options = {}) {
7039
7193
  enableStemming = true,
7040
7194
  detectLanguage = true,
7041
7195
  preserveCase = false,
7042
- minDetectionLength = 10
7196
+ minDetectionLength = 10,
7197
+ silent = false
7043
7198
  } = options;
7044
7199
  const language = detectLanguage ? detectQueryLanguage(query, minDetectionLength) : "eng";
7045
- console.log(`[EXULU] Query preprocessing - Detected language: ${language} for query: "${query}"`);
7200
+ if (!silent) {
7201
+ console.log(`[EXULU] Query preprocessing - Detected language: ${language} for query: "${query}"`);
7202
+ }
7046
7203
  if (!enableStemming) {
7047
7204
  return {
7048
7205
  original: query,
@@ -7060,7 +7217,9 @@ function preprocessQuery(query, options = {}) {
7060
7217
  return stemmed;
7061
7218
  });
7062
7219
  const processed = stemmedWords.join(" ");
7063
- console.log(`[EXULU] Query preprocessing - Original: "${query}" \u2192 Stemmed: "${processed}"`);
7220
+ if (!silent) {
7221
+ console.log(`[EXULU] Query preprocessing - Original: "${query}" \u2192 Stemmed: "${processed}"`);
7222
+ }
7064
7223
  return {
7065
7224
  original: query,
7066
7225
  processed,
@@ -9521,6 +9680,37 @@ var feedbackSchema = {
9521
9680
  }
9522
9681
  ]
9523
9682
  };
9683
+ var claimChecksSchema = {
9684
+ type: "claim_checks",
9685
+ graphql: false,
9686
+ name: {
9687
+ plural: "claim_checks",
9688
+ singular: "claim_check"
9689
+ },
9690
+ fields: [
9691
+ {
9692
+ name: "session",
9693
+ type: "uuid"
9694
+ },
9695
+ {
9696
+ name: "message_id",
9697
+ type: "text"
9698
+ },
9699
+ {
9700
+ name: "payload",
9701
+ type: "json"
9702
+ },
9703
+ {
9704
+ name: "score_label",
9705
+ type: "enum",
9706
+ enumValues: ["ok", "warn", "alert", "n/a"]
9707
+ },
9708
+ {
9709
+ name: "user",
9710
+ type: "number"
9711
+ }
9712
+ ]
9713
+ };
9524
9714
  var rolesSchema = {
9525
9715
  type: "roles",
9526
9716
  name: {
@@ -10860,6 +11050,19 @@ var sharedArtifactsSchema = {
10860
11050
  { name: "expires_at", type: "date", required: false },
10861
11051
  // null = no expiry
10862
11052
  { name: "content_type", type: "text", required: false }
11053
+ // `grant_viewer_identity`, `identity_granted_by` and `identity_granted_at`
11054
+ // were here. The viewer-identity capability is no longer a per-row grant:
11055
+ // `auth_mode: "regular"` carries it, because such an artifact only renders
11056
+ // for a logged-in user who passes RBAC on this row, so handing that user
11057
+ // their own identity grants nothing they did not already have.
11058
+ //
11059
+ // addMissingFields only ever adds columns, so removing these three leaves
11060
+ // them orphaned on databases that already ran init-db. Dropping them is a
11061
+ // manual, per-environment step:
11062
+ // alter table shared_artifacts
11063
+ // drop column if exists grant_viewer_identity,
11064
+ // drop column if exists identity_granted_by,
11065
+ // drop column if exists identity_granted_at;
10863
11066
  ]
10864
11067
  };
10865
11068
  var contextPresetsSchema = {
@@ -10993,6 +11196,9 @@ var coreSchemas = {
10993
11196
  if (license["agent-feedback"]) {
10994
11197
  schemas.feedbackSchema = () => addCoreFields(feedbackSchema);
10995
11198
  }
11199
+ if (license["claim-check"]) {
11200
+ schemas.claimChecksSchema = () => addCoreFields(claimChecksSchema);
11201
+ }
10996
11202
  if (license["rbac"]) {
10997
11203
  schemas.rolesSchema = () => addCoreFields(rolesSchema);
10998
11204
  schemas.teamsSchema = () => addCoreFields(teamsSchema);
@@ -12184,6 +12390,21 @@ var ENV_CLASSIFICATION = {
12184
12390
  // Found via `rg process\.env\.[A-Z0-9_]+ src ee` (Step 3 of the task brief):
12185
12391
  AUTH_MODE: "runtime",
12186
12392
  // "password" | "otp" mode selector, echoed by GET /config
12393
+ // Platform fallback model for POST /claims/check when the request names no
12394
+ // model and no agent config supplies one. It is a model IDENTIFIER, not a
12395
+ // credential: knowing the string grants access to nothing, because reaching
12396
+ // that model still needs the deployment's own proxy credentials
12397
+ // (LITELLM_MASTER_KEY / EXULU_API_KEY, both classified secret) and passes
12398
+ // through resolveModel's catalog. All it changes is which model a check
12399
+ // runs on — behaviour, which is this class's definition. Same reasoning as
12400
+ // EXULU_ENTITY_EXTRACTION_MODEL, TRANSCRIPTION_MODEL and TTS_MODEL below.
12401
+ CLAIM_CHECK_DEFAULT_MODEL: "runtime",
12402
+ // Request deadline (ms) for POST /claims/check, overriding routes.ts's
12403
+ // 60,000 default. A number of milliseconds is a setting, not a credential —
12404
+ // knowing it grants no access, it only changes how long the handler waits
12405
+ // before cancelling and returning 504. Same reasoning as
12406
+ // CLAIM_CHECK_DEFAULT_MODEL above.
12407
+ CLAIM_CHECK_TIMEOUT_MS: "runtime",
12187
12408
  DISABLE_SCHEMA_UPDATE: "runtime",
12188
12409
  // LiteLLM child-process flag
12189
12410
  EXULU_ENTITY_EXTRACTION_MODEL: "runtime",
@@ -13664,6 +13885,7 @@ function sessionFilePrefix(ownerId, sessionId, s3prefix) {
13664
13885
  // src/templates/tools/session-file-read-tool.ts
13665
13886
  var DEFAULT_LIMIT = 250;
13666
13887
  var MAX_CONTENT_CHARS = 16e3;
13888
+ var SESSION_FILE_READ_TOOL_NAME = "read_session_file";
13667
13889
  var createSessionFileReadTool = ({
13668
13890
  sessionID,
13669
13891
  user,
@@ -13710,7 +13932,7 @@ var createSessionFileReadTool = ({
13710
13932
  };
13711
13933
  return ExuluTool.internal({
13712
13934
  id: "read_session_file",
13713
- name: "read_session_file",
13935
+ name: SESSION_FILE_READ_TOOL_NAME,
13714
13936
  needsApproval: false,
13715
13937
  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.",
13716
13938
  inputSchema: z13.object({
@@ -13820,6 +14042,7 @@ async function renderPdfPageToPng(pdf, page, scaleTo) {
13820
14042
  // src/templates/tools/parse-document-tool.ts
13821
14043
  var DEFAULT_LIMIT2 = 250;
13822
14044
  var MAX_CONTENT_CHARS2 = 16e3;
14045
+ var PARSE_DOCUMENT_TOOL_NAME = "parse_document";
13823
14046
  var MIN_CHARS_PER_PAGE = 20;
13824
14047
  function looksLikeGarbledTextLayer(text) {
13825
14048
  let control = 0;
@@ -13958,7 +14181,7 @@ ${text.trim()}`).join("\n");
13958
14181
  };
13959
14182
  return ExuluTool.internal({
13960
14183
  id: "parse_document",
13961
- name: "parse_document",
14184
+ name: PARSE_DOCUMENT_TOOL_NAME,
13962
14185
  needsApproval: false,
13963
14186
  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.`,
13964
14187
  inputSchema: z14.object({
@@ -14130,6 +14353,7 @@ function imageAttachmentGuard() {
14130
14353
  }
14131
14354
 
14132
14355
  // src/templates/tools/view-document-page-tool.ts
14356
+ var VIEW_DOCUMENT_PAGE_TOOL_NAME = "view_document_page";
14133
14357
  var MAX_IMAGE_BYTES = 375e4;
14134
14358
  var SCALE_PRIMARY = 1568;
14135
14359
  var SCALE_FALLBACK = 1024;
@@ -14245,7 +14469,7 @@ var createViewDocumentPageTool = ({
14245
14469
  };
14246
14470
  return ExuluTool.internal({
14247
14471
  id: "view_document_page",
14248
- name: "view_document_page",
14472
+ name: VIEW_DOCUMENT_PAGE_TOOL_NAME,
14249
14473
  needsApproval: false,
14250
14474
  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.",
14251
14475
  inputSchema: z15.object({
@@ -14894,12 +15118,14 @@ export {
14894
15118
  exuluApp,
14895
15119
  setEmbedderSetting,
14896
15120
  clearEmbedderSetting,
14897
- resolveContextEmbedder,
14898
15121
  captureCodeEmbedder,
14899
15122
  codeEmbedderFor,
15123
+ contextEmbedderInfoFor,
14900
15124
  willEmbedOnQueue,
14901
15125
  hydrateContextEmbedders,
15126
+ refreshContextEmbeddersIfStale,
14902
15127
  updateStatistic,
15128
+ preprocessQuery,
14903
15129
  resolveSearchQueryTexts,
14904
15130
  chooseFullTextQuery,
14905
15131
  assertAllowedField,
@@ -14936,6 +15162,7 @@ export {
14936
15162
  exchangeCodeForTokens,
14937
15163
  verifyCredentialNonce,
14938
15164
  CredentialInvalidError,
15165
+ SESSION_ITEMS_RETRIEVAL_TOOL_NAME,
14939
15166
  sanitizeToolName,
14940
15167
  creatorId,
14941
15168
  handleRBACUpdate,
@@ -14968,19 +15195,30 @@ export {
14968
15195
  SCRUBBED_CREDENTIAL_TEXT,
14969
15196
  SCRUBBED_OAUTH_TEXT,
14970
15197
  sessionFilePrefix,
15198
+ SESSION_FILE_READ_TOOL_NAME,
15199
+ PARSE_DOCUMENT_TOOL_NAME,
14971
15200
  PreviewRenderError,
14972
15201
  getPdfPreviewBytes,
14973
15202
  imageAttachmentGuard,
15203
+ VIEW_DOCUMENT_PAGE_TOOL_NAME,
15204
+ OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS,
14974
15205
  hydrateVariables,
14975
15206
  convertExuluToolsToAiSdkTools,
14976
15207
  ExuluTool,
14977
15208
  resolveReranker,
15209
+ CLAIM_CHECK_MAX_OUTPUT_TOKENS,
15210
+ CLAIM_CHECK_DEFAULTS,
15211
+ parsePipelineConfig,
14978
15212
  withRetry,
14979
15213
  microCallProviderOptions,
15214
+ microCall,
15215
+ searchContexts,
15216
+ isExternalOrAnonymousUser,
14980
15217
  resolveRetrievalCallBudget,
14981
15218
  shouldShowSourcesToUser,
14982
15219
  resolveTurnStepBudget,
14983
15220
  finalAnswerGuard,
14984
15221
  retrievalBudgetGuard,
15222
+ AGENTIC_RETRIEVAL_TOOL_NAME,
14985
15223
  createAgenticRetrievalTool
14986
15224
  };
@@ -1,10 +1,12 @@
1
1
  import "dotenv/config";
2
2
  import {
3
+ OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS,
3
4
  convertExuluToolsToAiSdkTools,
4
5
  hydrateVariables
5
- } from "./chunk-UXHMHM4E.js";
6
+ } from "./chunk-ASF74XFZ.js";
6
7
  import "./chunk-4PDWNVNT.js";
7
8
  export {
9
+ OUTPUT_OFFLOAD_EXEMPT_TOOL_IDS,
8
10
  convertExuluToolsToAiSdkTools,
9
11
  hydrateVariables
10
12
  };