@exulu/backend 5.1.2 → 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 (55) hide show
  1. package/dist/{chunk-37MKZIH2.js → chunk-ASF74XFZ.js} +265 -32
  2. package/dist/{convert-exulu-tools-to-ai-sdk-tools-BNDHJH7B.js → convert-exulu-tools-to-ai-sdk-tools-MFLZQONB.js} +3 -1
  3. package/dist/index.cjs +2748 -351
  4. package/dist/index.js +2419 -304
  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/package.json +1 -1
@@ -111,6 +111,16 @@ describe("show_sources_to_external_users option", () => {
111
111
  });
112
112
  });
113
113
 
114
+ describe("suppress_duplicate_passages", () => {
115
+ it("defaults to true when absent or empty, false only when explicitly false", () => {
116
+ expect(parsePipelineConfig({}).suppressDuplicatePassages).toBe(true);
117
+ expect(parsePipelineConfig({ suppress_duplicate_passages: "" }).suppressDuplicatePassages).toBe(true);
118
+ expect(parsePipelineConfig({ suppress_duplicate_passages: "false" }).suppressDuplicatePassages).toBe(false);
119
+ expect(parsePipelineConfig({ suppress_duplicate_passages: false }).suppressDuplicatePassages).toBe(false);
120
+ expect(parsePipelineConfig({ suppress_duplicate_passages: "true" }).suppressDuplicatePassages).toBe(true);
121
+ });
122
+ });
123
+
114
124
  describe("tuning.engine — the per-agent switch between the v1 flow and the parallel v2 flow", () => {
115
125
  it("defaults to v1 so existing agents keep today's behaviour", () => {
116
126
  expect(parsePipelineConfig({ tuning: '{"topK": 8}' }).tuning.engine).toBe("v1");
@@ -126,3 +136,35 @@ describe("tuning.engine — the per-agent switch between the v1 flow and the par
126
136
  warn.mockRestore();
127
137
  });
128
138
  });
139
+
140
+ describe("parsePipelineConfig — claim_check", () => {
141
+ it("defaults to disabled with the spec's thresholds and caps when the key is absent", () => {
142
+ const cfg = parsePipelineConfig({});
143
+ expect(cfg.claimCheck).toEqual({
144
+ enabled: false,
145
+ model: "",
146
+ fidelity: "fast",
147
+ completions: 1,
148
+ reRetrieve: true,
149
+ thresholds: { warn: 0.1, alert: 0.3 },
150
+ showToExternalUsers: false,
151
+ caps: { maxSentences: 120, maxClaims: 200, maxReRetrievals: 10 },
152
+ });
153
+ });
154
+
155
+ it("parses a JSON string and keeps unspecified keys at their defaults", () => {
156
+ const cfg = parsePipelineConfig({
157
+ claim_check: '{"enabled":true,"model":"vertex-gemini-3.5-flash","thresholds":{"warn":0.2,"alert":0.5}}',
158
+ });
159
+ expect(cfg.claimCheck.enabled).toBe(true);
160
+ expect(cfg.claimCheck.model).toBe("vertex-gemini-3.5-flash");
161
+ expect(cfg.claimCheck.thresholds).toEqual({ warn: 0.2, alert: 0.5 });
162
+ expect(cfg.claimCheck.fidelity).toBe("fast");
163
+ expect(cfg.claimCheck.caps.maxClaims).toBe(200);
164
+ });
165
+
166
+ it("falls back to defaults on malformed JSON and on a schema violation", () => {
167
+ expect(parsePipelineConfig({ claim_check: "{not json" }).claimCheck.enabled).toBe(false);
168
+ expect(parsePipelineConfig({ claim_check: { fidelity: "turbo" } }).claimCheck.fidelity).toBe("fast");
169
+ });
170
+ });
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { CLAIM_CHECK_DEFAULTS } from "@EE/claim-check/types";
2
3
 
3
4
  export const KB_KINDS = ["documents", "conversations", "records"] as const;
4
5
  export type KbKind = (typeof KB_KINDS)[number];
@@ -74,7 +75,32 @@ const tuningSchema = z.object({
74
75
  .default({ mergedMemoryCall: true, mergedRoutingCall: true, parallelPins: true }),
75
76
  });
76
77
 
78
+ const claimCheckSchema = z.object({
79
+ enabled: z.boolean().default(false),
80
+ /** Empty = fall back to the agent's utility model, then the agent's model. */
81
+ model: z.string().default(""),
82
+ fidelity: z.enum(["fast", "paper"]).default(CLAIM_CHECK_DEFAULTS.fidelity),
83
+ completions: z.number().int().min(1).max(3).default(CLAIM_CHECK_DEFAULTS.completions),
84
+ reRetrieve: z.boolean().default(CLAIM_CHECK_DEFAULTS.reRetrieve),
85
+ thresholds: z
86
+ .object({
87
+ warn: z.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.warn),
88
+ alert: z.number().min(0).max(1).default(CLAIM_CHECK_DEFAULTS.thresholds.alert),
89
+ })
90
+ // zod's .default() returns the value as-is (inner defaults are not applied), so spell it out.
91
+ .default(CLAIM_CHECK_DEFAULTS.thresholds),
92
+ showToExternalUsers: z.boolean().default(false),
93
+ caps: z
94
+ .object({
95
+ maxSentences: z.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxSentences),
96
+ maxClaims: z.number().int().positive().default(CLAIM_CHECK_DEFAULTS.caps.maxClaims),
97
+ maxReRetrievals: z.number().int().min(0).default(CLAIM_CHECK_DEFAULTS.caps.maxReRetrievals),
98
+ })
99
+ .default(CLAIM_CHECK_DEFAULTS.caps),
100
+ });
101
+
77
102
  export type KbProfile = z.infer<typeof kbProfileSchema>;
103
+ export type ClaimCheckConfig = z.infer<typeof claimCheckSchema>;
78
104
  export type RoutingRule = z.infer<typeof routingRuleSchema>;
79
105
  export type IdentifierSet = z.infer<typeof identifierSetSchema>;
80
106
 
@@ -88,12 +114,16 @@ export type PipelineConfig = {
88
114
  projectSearch: boolean;
89
115
  /** Show source references (item names, IDs, chunk info) to external users and guests. When false, sources are hidden. Default true. */
90
116
  showSourcesToExternalUsers: boolean;
117
+ /** Widen the identifier-pin budget and drop near-identical passages during top-K selection. Default true. */
118
+ suppressDuplicatePassages: boolean;
91
119
  utilityModel: string;
92
120
  knowledgeBases: Record<string, KbProfile>;
93
121
  routing: z.infer<typeof routingSchema>;
94
122
  vocabulary: z.infer<typeof vocabularySchema>;
95
123
  memory: z.infer<typeof memorySchema>;
96
124
  tuning: z.infer<typeof tuningSchema>;
125
+ /** Post-answer claim verification (spec 2026-10-13). Off unless an admin enables it. */
126
+ claimCheck: ClaimCheckConfig;
97
127
  };
98
128
 
99
129
  const boolVal = (v: unknown): boolean => v === true || v === "true" || v === 1;
@@ -139,6 +169,7 @@ function defaultFor(name: string): unknown {
139
169
  case "vocabulary": return { glossary: [], identifiers: [], rewrites: [], styleHint: "" };
140
170
  case "memory": return {};
141
171
  case "tuning": return {};
172
+ case "claim_check": return {};
142
173
  default: return {};
143
174
  }
144
175
  }
@@ -159,12 +190,17 @@ export function parsePipelineConfig(raw?: Record<string, unknown>): PipelineConf
159
190
  r["show_sources_to_external_users"] === undefined || r["show_sources_to_external_users"] === ""
160
191
  ? true
161
192
  : boolVal(r["show_sources_to_external_users"]),
193
+ suppressDuplicatePassages:
194
+ r["suppress_duplicate_passages"] === undefined || r["suppress_duplicate_passages"] === ""
195
+ ? true
196
+ : boolVal(r["suppress_duplicate_passages"]),
162
197
  utilityModel: strVal(r["utility_model"], ""),
163
198
  knowledgeBases: jsonVal("knowledge_bases", knowledgeBasesSchema, r["knowledge_bases"]),
164
199
  routing: jsonVal("routing", routingSchema, r["routing"]),
165
200
  vocabulary: jsonVal("vocabulary", vocabularySchema, r["vocabulary"]),
166
201
  memory: jsonVal("memory", memorySchema, r["memory"]),
167
202
  tuning: jsonVal("tuning", tuningSchema, r["tuning"]),
203
+ claimCheck: jsonVal("claim_check", claimCheckSchema, r["claim_check"]),
168
204
  };
169
205
  }
170
206
 
@@ -36,12 +36,12 @@ describe("createAgenticRetrievalTool", () => {
36
36
  const tool = createAgenticRetrievalTool({ contexts: [ctx("docs")], model: {} as any })!;
37
37
  const names = tool.config.map((c) => c.name).sort();
38
38
  expect(names).toEqual([
39
- "instructions", "knowledge_bases", "logging", "managed_context", "memory",
39
+ "claim_check", "instructions", "knowledge_bases", "logging", "managed_context", "memory",
40
40
  "max_steps", "project_search", "require_preselected_contexts", "reranker",
41
- "routing", "show_sources_to_external_users", "tuning", "utility_model", "vocabulary",
41
+ "routing", "show_sources_to_external_users", "suppress_duplicate_passages", "tuning", "utility_model", "vocabulary",
42
42
  ].sort());
43
43
  expect(tool.config.filter((c) => c.type === "json").map((c) => c.name).sort())
44
- .toEqual(["knowledge_bases", "memory", "routing", "tuning", "vocabulary"].sort());
44
+ .toEqual(["claim_check", "knowledge_bases", "memory", "routing", "tuning", "vocabulary"].sort());
45
45
  expect(tool.id).toBe("agentic_context_search");
46
46
  });
47
47
 
@@ -14,6 +14,7 @@ import { runMemoryPhase } from "./memory";
14
14
  import { resolveIdentifierPins } from "./prefilter";
15
15
  import { searchContexts } from "./search";
16
16
  import { rerankResults } from "./rerank";
17
+ import { makeNearDuplicateFinder } from "./near-duplicates";
17
18
  import type { AgenticRetrievalOutput, RerankState, ChunkWithScore } from "./types";
18
19
  import { withTiming } from "./timing";
19
20
  import { needsPinRerun } from "./pin-rerun";
@@ -26,6 +27,15 @@ export { parsePreselectedItems } from "./global-ids";
26
27
  // Helpers
27
28
  // ---------------------------------------------------------------------------
28
29
 
30
+ /**
31
+ * The agentic retrieval tool's display name — the one literal the model and
32
+ * the UI both see, and the one `sanitizeToolName` turns into the AI-SDK tool
33
+ * key (and so the `tool-${...}` part type) every caller of this tool keys on.
34
+ * Exported so a rename here fails those call sites' test suites (claim-check's
35
+ * finish-metadata, notably) instead of silently breaking the feature.
36
+ */
37
+ export const AGENTIC_RETRIEVAL_TOOL_NAME = "Context Search";
38
+
29
39
  /**
30
40
  * Accumulate chunks into result.chunks, deduplicating by chunk_id (first-seen wins).
31
41
  */
@@ -119,7 +129,7 @@ export function createAgenticRetrievalTool(opts: {
119
129
 
120
130
  return ExuluTool.internal({
121
131
  id: "agentic_context_search",
122
- name: "Context Search",
132
+ name: AGENTIC_RETRIEVAL_TOOL_NAME,
123
133
  description:
124
134
  `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 — re-call only with genuinely new information (a different product or model, an explicitly named source or document, or new details from the user).` +
125
135
  // Note: the description suffix intentionally remains even when the per-agent project_search
@@ -178,6 +188,17 @@ export function createAgenticRetrievalTool(opts: {
178
188
  type: "boolean",
179
189
  default: true,
180
190
  },
191
+ {
192
+ name: "suppress_duplicate_passages",
193
+ description:
194
+ "Keep only the best-scoring copy when several retrieved passages carry near-identical content " +
195
+ "(the same page re-uploaded under different filenames, a document filed in two folders). " +
196
+ "Nothing is merged or rewritten — redundant copies are dropped from the result so the places " +
197
+ "freed up can carry different information. Also widens the identifier-pin budget, which is " +
198
+ "only safe together with this. Leave empty to keep it on; set to false to restore the previous behaviour.",
199
+ type: "boolean",
200
+ default: true,
201
+ },
181
202
  {
182
203
  name: "knowledge_bases",
183
204
  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.",
@@ -214,6 +235,17 @@ export function createAgenticRetrievalTool(opts: {
214
235
  type: "boolean",
215
236
  default: true,
216
237
  },
238
+ {
239
+ name: "claim_check",
240
+ description:
241
+ "Post-answer claim verification: extracts the factual claims the answer makes and reports, " +
242
+ "per claim, whether the retrieved passages support it, contradict it, or say nothing about it. " +
243
+ "Runs AFTER the answer has streamed and never delays or changes it. Keys: enabled, model " +
244
+ "(a fast, cheap model is the right choice), fidelity (fast | paper), completions, reRetrieve, " +
245
+ "thresholds {warn, alert}, showToExternalUsers, caps {maxSentences, maxClaims, maxReRetrievals}.",
246
+ type: "json",
247
+ default: '{"enabled":false,"model":"","fidelity":"fast","thresholds":{"warn":0.1,"alert":0.3}}',
248
+ },
217
249
  ],
218
250
  inputSchema: z.object({
219
251
  userQuery: z.string().describe("The original unaltered question from the user"),
@@ -398,6 +430,7 @@ export function createAgenticRetrievalTool(opts: {
398
430
  contextsById,
399
431
  kbKindById,
400
432
  model: utilityModel,
433
+ suppressDuplicatePassages: cfg.suppressDuplicatePassages,
401
434
  });
402
435
 
403
436
  const [memResult, routResult, parallelPins] = await Promise.all([
@@ -597,6 +630,13 @@ export function createAgenticRetrievalTool(opts: {
597
630
  };
598
631
 
599
632
  // ── Phase 3: rerank main results ──────────────────────────────────────
633
+ // Built once per run and shared by both rerank call sites below: each knowledge
634
+ // base stores its chunks in its own table, so the lookup is scoped to the known
635
+ // context ids (excludes the synthetic "memory" tag, which has no own table).
636
+ const findNearDuplicates = cfg.suppressDuplicatePassages
637
+ ? makeNearDuplicateFinder({ contextIds: Array.from(contextsById.keys()) })
638
+ : undefined;
639
+
600
640
  result.steps.push({
601
641
  stepNumber: 1,
602
642
  text: `Reranking ${mainSearch.chunks.length} chunks`,
@@ -618,6 +658,7 @@ export function createAgenticRetrievalTool(opts: {
618
658
  identifierBoost: cfg.tuning.identifierBoost,
619
659
  pageWindow: cfg.tuning.pageWindow,
620
660
  },
661
+ findNearDuplicates,
621
662
  });
622
663
 
623
664
  result.steps.push({
@@ -695,6 +736,7 @@ export function createAgenticRetrievalTool(opts: {
695
736
  identifierBoost: cfg.tuning.identifierBoost,
696
737
  pageWindow: cfg.tuning.pageWindow,
697
738
  },
739
+ findNearDuplicates,
698
740
  });
699
741
 
700
742
  result.steps.push({
@@ -109,4 +109,62 @@ describe("microCall", () => {
109
109
  expect(output).toEqual({ ok: true });
110
110
  expect(generateText).toHaveBeenCalledTimes(2);
111
111
  });
112
+
113
+ it("returns provider token usage, defaulting to zeros when absent", async () => {
114
+ (generateText as jest.Mock).mockResolvedValue({
115
+ output: { ok: true },
116
+ text: "{}",
117
+ usage: { inputTokens: 1234, outputTokens: 56 },
118
+ });
119
+ const withUsage = await microCall({ model: {} as any, prompt: "p", schema });
120
+ expect(withUsage.usage).toEqual({ inputTokens: 1234, outputTokens: 56 });
121
+
122
+ (generateText as jest.Mock).mockResolvedValue({ output: { ok: true }, text: "{}" });
123
+ const withoutUsage = await microCall({ model: {} as any, prompt: "p", schema });
124
+ expect(withoutUsage.usage).toEqual({ inputTokens: 0, outputTokens: 0 });
125
+ });
126
+
127
+ // Claim check's 60 s request deadline (spec §4) cancels its provider calls
128
+ // through this signal, so a hung provider stops holding an in-flight slot.
129
+ it("forwards an abort signal to the provider and omits it when absent", async () => {
130
+ (generateText as jest.Mock).mockResolvedValue({ output: { ok: true }, text: "" });
131
+ const controller = new AbortController();
132
+ await microCall({ model: {} as any, prompt: "p", schema, abortSignal: controller.signal });
133
+ expect((generateText as jest.Mock).mock.calls[0][0].abortSignal).toBe(controller.signal);
134
+
135
+ (generateText as jest.Mock).mockClear();
136
+ await microCall({ model: {} as any, prompt: "p", schema });
137
+ expect("abortSignal" in (generateText as jest.Mock).mock.calls[0][0]).toBe(false);
138
+ });
139
+
140
+ it("does not retry once the abort signal has fired", async () => {
141
+ const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
142
+ const controller = new AbortController();
143
+ (generateText as jest.Mock).mockImplementation(async () => {
144
+ controller.abort();
145
+ throw new Error("The operation was aborted");
146
+ });
147
+
148
+ await expect(
149
+ microCall({ model: {} as any, prompt: "p", schema, abortSignal: controller.signal, retryBaseDelayMs: 1 }),
150
+ ).rejects.toThrow("aborted");
151
+ expect(generateText).toHaveBeenCalledTimes(1);
152
+ errorSpy.mockRestore();
153
+ });
154
+
155
+ it("retries a LiteLLM tag-configuration error, which is a 429 aftershock and not a config fault", async () => {
156
+ (generateText as jest.Mock)
157
+ .mockRejectedValueOnce(new Error("Not allowed to access model due to tags configuration"))
158
+ .mockResolvedValueOnce({ output: { ok: true }, text: "{}", usage: { inputTokens: 5, outputTokens: 1 } });
159
+
160
+ const { output } = await microCall({
161
+ model: {} as any,
162
+ prompt: "p",
163
+ schema,
164
+ retryBaseDelayMs: 1,
165
+ });
166
+
167
+ expect(output).toEqual({ ok: true });
168
+ expect((generateText as jest.Mock).mock.calls.length).toBe(2);
169
+ });
112
170
  });
@@ -46,11 +46,17 @@ export type MicroCallArgs<OUTPUT> = {
46
46
  /** Total attempts for transient failures (network, provider 429/5xx). */
47
47
  maxAttempts?: number;
48
48
  retryBaseDelayMs?: number;
49
+ /**
50
+ * Cancels the provider request. Callers with a request deadline (claim
51
+ * check's 60 s cap) pass one so a hung provider stops holding a slot;
52
+ * retries stop as soon as it is aborted.
53
+ */
54
+ abortSignal?: AbortSignal;
49
55
  };
50
56
 
51
57
  export async function microCall<OUTPUT = undefined>(
52
58
  args: MicroCallArgs<OUTPUT>,
53
- ): Promise<{ output: OUTPUT; text: string }> {
59
+ ): Promise<{ output: OUTPUT; text: string; usage: { inputTokens: number; outputTokens: number } }> {
54
60
  const {
55
61
  model,
56
62
  system,
@@ -61,6 +67,7 @@ export async function microCall<OUTPUT = undefined>(
61
67
  maxOutputTokens = MICRO_CALL_MAX_OUTPUT_TOKENS,
62
68
  maxAttempts = 3,
63
69
  retryBaseDelayMs,
70
+ abortSignal,
64
71
  } = args;
65
72
 
66
73
  return withRetry(
@@ -78,20 +85,30 @@ export async function microCall<OUTPUT = undefined>(
78
85
  // rate-limiting.
79
86
  maxRetries: 0,
80
87
  providerOptions: microCallProviderOptions(model),
88
+ ...(abortSignal ? { abortSignal } : {}),
81
89
  } as Parameters<typeof generateText>[0]);
82
90
  // Read .output inside the retried closure — the SDK throws
83
91
  // NoOutputGeneratedError from this getter, so reading it later would
84
92
  // escape both the retry classification and the caller's per-call catch.
93
+ // Token usage rides along so callers that fan out many micro-calls
94
+ // (claim check) can report what a check cost without re-deriving it.
95
+ const usage = (result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage;
85
96
  return {
86
97
  output: (schema ? (result as { output: OUTPUT }).output : undefined) as OUTPUT,
87
98
  text: result.text,
99
+ usage: {
100
+ inputTokens: usage?.inputTokens ?? 0,
101
+ outputTokens: usage?.outputTokens ?? 0,
102
+ },
88
103
  };
89
104
  },
90
105
  maxAttempts,
91
106
  {
92
107
  // Empty output is deterministic for identical params — retrying only
93
- // added latency before the degraded path. Fail fast instead.
94
- shouldRetry: (error) => !NoOutputGeneratedError.isInstance(error),
108
+ // added latency before the degraded path. Fail fast instead. An aborted
109
+ // signal is equally final: the caller's deadline has passed, so another
110
+ // attempt can only spend tokens on a response nobody will read.
111
+ shouldRetry: (error) => !NoOutputGeneratedError.isInstance(error) && abortSignal?.aborted !== true,
95
112
  ...(retryBaseDelayMs !== undefined ? { baseDelayMs: retryBaseDelayMs } : {}),
96
113
  },
97
114
  );
@@ -0,0 +1,50 @@
1
+ import { makeNearDuplicateFinder, DUPLICATE_SIMILARITY_THRESHOLD } from "./near-duplicates";
2
+
3
+ const chunk = (id: string, ctx: string) => ({ chunk_id: id, context: { id: ctx } }) as any;
4
+
5
+ describe("makeNearDuplicateFinder", () => {
6
+ it("queries one table per context and returns the union of pairs", async () => {
7
+ const seen: string[] = [];
8
+ const bindingsSeen: unknown[] = [];
9
+ const db = { raw: jest.fn(async (sql: string, bindings: unknown) => { seen.push(sql); bindingsSeen.push(bindings);
10
+ return { rows: sql.includes("tech_doc") ? [{ a: "c1", b: "c2" }] : [{ a: "z1", b: "z2" }] }; }) } as any;
11
+ const find = makeNearDuplicateFinder({ contextIds: ["tech_doc_context", "zendesk_context"], db });
12
+ const pairs = await find([chunk("c1", "tech_doc_context"), chunk("c2", "tech_doc_context"),
13
+ chunk("z1", "zendesk_context"), chunk("z2", "zendesk_context")]);
14
+ expect(pairs).toEqual(expect.arrayContaining([["c1", "c2"], ["z1", "z2"]]));
15
+ expect(seen).toHaveLength(2);
16
+ expect(seen[0]).toContain("tech_doc_context_chunks");
17
+ // Both id arrays and the threshold must actually be bound — not just present in the SQL text.
18
+ expect(bindingsSeen[0]).toEqual([["c1", "c2"], ["c1", "c2"], DUPLICATE_SIMILARITY_THRESHOLD]);
19
+ expect(bindingsSeen[1]).toEqual([["z1", "z2"], ["z1", "z2"], DUPLICATE_SIMILARITY_THRESHOLD]);
20
+ });
21
+
22
+ it("skips contexts that are not known knowledge bases, e.g. memory", async () => {
23
+ const db = { raw: jest.fn(async () => ({ rows: [] })) } as any;
24
+ const find = makeNearDuplicateFinder({ contextIds: ["tech_doc_context"], db });
25
+ await find([chunk("m1", "memory"), chunk("m2", "memory")]);
26
+ expect(db.raw).not.toHaveBeenCalled();
27
+ });
28
+
29
+ it("returns the pairs it did get when one context query throws", async () => {
30
+ const db = { raw: jest.fn(async (sql: string) => {
31
+ if (sql.includes("zendesk")) throw new Error("boom");
32
+ return { rows: [{ a: "c1", b: "c2" }] };
33
+ }) } as any;
34
+ const find = makeNearDuplicateFinder({ contextIds: ["tech_doc_context", "zendesk_context"], db });
35
+ const pairs = await find([chunk("c1", "tech_doc_context"), chunk("c2", "tech_doc_context"),
36
+ chunk("z1", "zendesk_context"), chunk("z2", "zendesk_context")]);
37
+ expect(pairs).toEqual([["c1", "c2"]]);
38
+ });
39
+
40
+ it("skips a context with fewer than two candidates", async () => {
41
+ const db = { raw: jest.fn(async () => ({ rows: [] })) } as any;
42
+ const find = makeNearDuplicateFinder({ contextIds: ["tech_doc_context"], db });
43
+ await find([chunk("c1", "tech_doc_context")]);
44
+ expect(db.raw).not.toHaveBeenCalled();
45
+ });
46
+
47
+ it("uses 0.97 as the threshold", () => {
48
+ expect(DUPLICATE_SIMILARITY_THRESHOLD).toBe(0.97);
49
+ });
50
+ });
@@ -0,0 +1,74 @@
1
+ import { postgresClient } from "@SRC/postgres/client";
2
+ import { getChunksTableName } from "@SRC/exulu/table-names";
3
+ import type { ChunkWithScore } from "./types";
4
+
5
+ /** Measured separation: copies of one page score 0.982–0.996; the same table in the
6
+ * predecessor manual scores 0.9415. See the design spec for the full table. */
7
+ export const DUPLICATE_SIMILARITY_THRESHOLD = 0.97;
8
+
9
+ /**
10
+ * Builds the near-duplicate lookup handed to rerankResults. Candidates are grouped by
11
+ * context because each knowledge base stores its chunks in its own table; cross-context
12
+ * pairs are deliberately not computed. Any context whose query fails simply contributes
13
+ * no pairs.
14
+ *
15
+ * `contextIds` must be the set of known knowledge-base context ids (e.g. from
16
+ * `contextsById.keys()`). A candidate's context is only queried when it's a member of
17
+ * that set — in particular this excludes the synthetic "memory" context, which chunks
18
+ * are tagged with but which has no `memory_chunks` table (the real table is
19
+ * `newton_memory_context_chunks`, named after the memory *context*, not this tag).
20
+ */
21
+ export function makeNearDuplicateFinder(opts: {
22
+ contextIds: string[];
23
+ threshold?: number;
24
+ db?: { raw: (sql: string, bindings?: any) => Promise<{ rows: Array<{ a: string; b: string }> }> };
25
+ }) {
26
+ const known = new Set(opts.contextIds);
27
+ const threshold = opts.threshold ?? DUPLICATE_SIMILARITY_THRESHOLD;
28
+
29
+ return async (candidates: ChunkWithScore[]): Promise<Array<[string, string]>> => {
30
+ const byContext = new Map<string, string[]>();
31
+ for (const c of candidates) {
32
+ const ctxId = c.context?.id;
33
+ if (!c.chunk_id || !ctxId || !known.has(ctxId)) continue;
34
+ byContext.set(ctxId, [...(byContext.get(ctxId) ?? []), c.chunk_id]);
35
+ }
36
+ const work = [...byContext.entries()].filter(([, ids]) => ids.length > 1);
37
+ if (work.length === 0) return [];
38
+
39
+ // The whole lookup is optional and must never block a turn — acquiring the
40
+ // connection is wrapped here too, not left for rerank.ts's own try/catch to
41
+ // cover, so the finder honours the "never throws" contract on its own.
42
+ try {
43
+ const db = opts.db ?? (await postgresClient()).db;
44
+ const results = await Promise.all(
45
+ work.map(async ([ctxId, ids]) => {
46
+ // getChunksTableName applies sanitizeName and is the same helper 12+
47
+ // other call sites use (e.g. context-map.ts), double-quoted there too —
48
+ // direct interpolation is fine since the result is sanitized, unlike a
49
+ // bare `${ctxId}_chunks` which would skip that.
50
+ const table = getChunksTableName(ctxId);
51
+ try {
52
+ const res = await db.raw(
53
+ `select a.id as a, b.id as b
54
+ from "${table}" a
55
+ join "${table}" b on a.id < b.id
56
+ where a.id = any(?) and b.id = any(?)
57
+ and a.embedding is not null and b.embedding is not null
58
+ and (1 - (a.embedding <=> b.embedding)) >= ?`,
59
+ [ids, ids, threshold],
60
+ );
61
+ return (res.rows ?? []).map((r) => [r.a, r.b] as [string, string]);
62
+ } catch (err) {
63
+ console.warn(`[EXULU pipeline] near-duplicate query failed for "${ctxId}":`, err);
64
+ return [] as Array<[string, string]>;
65
+ }
66
+ }),
67
+ );
68
+ return results.flat();
69
+ } catch (err) {
70
+ console.warn("[EXULU pipeline] near-duplicate lookup failed to acquire a database connection:", err);
71
+ return [];
72
+ }
73
+ };
74
+ }
@@ -169,6 +169,38 @@ describe("fuzzyPrefilter supplement scope and degenerate corpora", () => {
169
169
  });
170
170
  });
171
171
 
172
+ describe("fuzzyPrefilter supplement budget", () => {
173
+ it("caps the separator supplement at the supplied budget", async () => {
174
+ const items = Array.from({ length: 80 }, (_, i) => ({
175
+ id: "i" + i, name: `hb_FST2XT_part${i}.pdf`, external_id: null,
176
+ }));
177
+ const context = { id: "c", getItems: async () => items } as any;
178
+ const common = {
179
+ cacheKey: "t2-" + Math.random(), relevantKeywords: ["FST-2XT"], context,
180
+ fields: ["id", "name"], normalize: (it: any) => it.name,
181
+ supplementSeparatorVariants: true,
182
+ };
183
+ const narrow = await fuzzyPrefilter({ ...common, supplementBudget: 15 });
184
+ const wide = await fuzzyPrefilter({ ...common, cacheKey: "t2w-" + Math.random(), supplementBudget: 50 });
185
+ expect(wide.length).toBeGreaterThan(narrow.length);
186
+ expect(wide.length).toBeLessThanOrEqual(50 + narrow.length);
187
+ });
188
+
189
+ it("defaults to the narrow budget when none is supplied (flag off)", async () => {
190
+ const items = Array.from({ length: 80 }, (_, i) => ({
191
+ id: "j" + i, name: `hb_FST2XT_part${i}.pdf`, external_id: null,
192
+ }));
193
+ const context = { id: "c", getItems: async () => items } as any;
194
+ const common = {
195
+ relevantKeywords: ["FST-2XT"], context, fields: ["id", "name"],
196
+ normalize: (it: any) => it.name, supplementSeparatorVariants: true,
197
+ };
198
+ const explicit = await fuzzyPrefilter({ ...common, cacheKey: "t2a-" + Math.random(), supplementBudget: 15 });
199
+ const omitted = await fuzzyPrefilter({ ...common, cacheKey: "t2b-" + Math.random() });
200
+ expect(omitted.length).toBe(explicit.length);
201
+ });
202
+ });
203
+
172
204
  describe("resolveIdentifierPins", () => {
173
205
  it("runs one extraction call per identifier set and routes pins to the set's contexts", async () => {
174
206
  (generateText as jest.Mock).mockResolvedValue({
@@ -27,6 +27,9 @@ type ItemsCache = {
27
27
  const SUPPLEMENT_MIN_TOKEN_LENGTH = 4;
28
28
  /** Most items the supplementary pass may add on top of the primary result. */
29
29
  const SUPPLEMENT_BUDGET = 15;
30
+ /** Budget used when suppress_duplicate_passages is on; safe only with suppression active,
31
+ * which is the only state that requests it. */
32
+ export const SUPPLEMENT_BUDGET_WIDE = 50;
30
33
 
31
34
  // ---------------------------------------------------------------------------
32
35
  // Cache
@@ -153,6 +156,7 @@ export async function fuzzyPrefilter({
153
156
  cutoff = DEFAULT_PREFILTER_CUTOFF,
154
157
  limit,
155
158
  supplementSeparatorVariants = false,
159
+ supplementBudget = SUPPLEMENT_BUDGET,
156
160
  }: {
157
161
  cacheKey: string;
158
162
  relevantKeywords: string[];
@@ -171,6 +175,8 @@ export async function fuzzyPrefilter({
171
175
  * default rather than silently widening every prefilter in the pipeline.
172
176
  */
173
177
  supplementSeparatorVariants?: boolean;
178
+ /** Max items the separator supplement may add. Defaults to the narrow budget. */
179
+ supplementBudget?: number;
174
180
  }): Promise<PrefilteredResult[]> {
175
181
  const cache = await ensureItemsCache({ cacheKey, context, fields, normalize });
176
182
 
@@ -348,7 +354,7 @@ export async function fuzzyPrefilter({
348
354
 
349
355
  const supplement: PrefilteredResult[] = [];
350
356
  for (const { item } of candidates) {
351
- if (supplement.length >= SUPPLEMENT_BUDGET) break;
357
+ if (supplement.length >= supplementBudget) break;
352
358
  if (!item.id || seen.has(item.id)) continue;
353
359
  seen.add(item.id);
354
360
  supplement.push({
@@ -403,12 +409,15 @@ export async function resolveIdentifierPins({
403
409
  contextsById,
404
410
  kbKindById,
405
411
  model,
412
+ suppressDuplicatePassages = false,
406
413
  }: {
407
414
  question: string;
408
415
  identifierSets: IdentifierSet[];
409
416
  contextsById: Map<string, any>;
410
417
  kbKindById: Map<string, KbKind>;
411
418
  model: any;
419
+ /** Widens the separator-insensitive supplement budget (see SUPPLEMENT_BUDGET_WIDE). */
420
+ suppressDuplicatePassages?: boolean;
412
421
  }): Promise<{
413
422
  pinsByContext: Map<string, Set<string>>;
414
423
  exactPinsByContext: Map<string, Set<string>>;
@@ -456,6 +465,9 @@ export async function resolveIdentifierPins({
456
465
  // Identifier pins are a hard id-whitelist over filenames,
457
466
  // which is exactly the case the supplement exists for.
458
467
  supplementSeparatorVariants: true,
468
+ supplementBudget: suppressDuplicatePassages
469
+ ? SUPPLEMENT_BUDGET_WIDE
470
+ : undefined,
459
471
  });
460
472
  if (!matched.length) return;
461
473
  const target = pinsByContext.get(ctxId) ?? new Set<string>();