@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.
- package/dist/{chunk-UXHMHM4E.js → chunk-ASF74XFZ.js} +271 -33
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-FHFMJSD2.js → convert-exulu-tools-to-ai-sdk-tools-MFLZQONB.js} +3 -1
- package/dist/index.cjs +2761 -355
- package/dist/index.js +2425 -305
- package/ee/agentic-retrieval/pipeline/config.test.ts +42 -0
- package/ee/agentic-retrieval/pipeline/config.ts +36 -0
- package/ee/agentic-retrieval/pipeline/index.test.ts +3 -3
- package/ee/agentic-retrieval/pipeline/index.ts +43 -1
- package/ee/agentic-retrieval/pipeline/micro-call.test.ts +58 -0
- package/ee/agentic-retrieval/pipeline/micro-call.ts +20 -3
- package/ee/agentic-retrieval/pipeline/near-duplicates.test.ts +50 -0
- package/ee/agentic-retrieval/pipeline/near-duplicates.ts +74 -0
- package/ee/agentic-retrieval/pipeline/prefilter.test.ts +32 -0
- package/ee/agentic-retrieval/pipeline/prefilter.ts +13 -1
- package/ee/agentic-retrieval/pipeline/rerank.test.ts +79 -0
- package/ee/agentic-retrieval/pipeline/rerank.ts +61 -6
- package/ee/claim-check/agent-config.ts +26 -0
- package/ee/claim-check/concurrency.test.ts +33 -0
- package/ee/claim-check/concurrency.ts +30 -0
- package/ee/claim-check/evidence.test.ts +198 -0
- package/ee/claim-check/evidence.ts +162 -0
- package/ee/claim-check/prompts/decompose.ts +52 -0
- package/ee/claim-check/prompts/disambiguate.ts +58 -0
- package/ee/claim-check/prompts/select-disambiguate.ts +17 -0
- package/ee/claim-check/prompts/select.ts +55 -0
- package/ee/claim-check/prompts/shared.test.ts +193 -0
- package/ee/claim-check/prompts/shared.ts +89 -0
- package/ee/claim-check/prompts/verify.ts +56 -0
- package/ee/claim-check/rate-limit.test.ts +40 -0
- package/ee/claim-check/rate-limit.ts +82 -0
- package/ee/claim-check/routes.test.ts +1188 -0
- package/ee/claim-check/routes.ts +682 -0
- package/ee/claim-check/run.test.ts +1317 -0
- package/ee/claim-check/run.ts +710 -0
- package/ee/claim-check/score.test.ts +108 -0
- package/ee/claim-check/score.ts +75 -0
- package/ee/claim-check/second-chance.test.ts +89 -0
- package/ee/claim-check/second-chance.ts +80 -0
- package/ee/claim-check/split.test.ts +179 -0
- package/ee/claim-check/split.ts +220 -0
- package/ee/claim-check/stages/decompose.test.ts +129 -0
- package/ee/claim-check/stages/decompose.ts +64 -0
- package/ee/claim-check/stages/disambiguate.test.ts +130 -0
- package/ee/claim-check/stages/disambiguate.ts +74 -0
- package/ee/claim-check/stages/select-disambiguate.test.ts +137 -0
- package/ee/claim-check/stages/select-disambiguate.ts +90 -0
- package/ee/claim-check/stages/select.test.ts +155 -0
- package/ee/claim-check/stages/select.ts +94 -0
- package/ee/claim-check/stages/usage.ts +11 -0
- package/ee/claim-check/stages/verify.test.ts +154 -0
- package/ee/claim-check/stages/verify.ts +78 -0
- package/ee/claim-check/types.ts +178 -0
- package/ee/entitlements.ts +3 -0
- package/ee/schemas.ts +71 -0
- package/ee/workers.ts +16 -0
- package/package.json +1 -1
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
// ee/claim-check/routes.ts
|
|
2
|
+
//
|
|
3
|
+
// POST /claims/check. The payload is trusted on purpose (spec decision 4):
|
|
4
|
+
// the endpoint is a product for clients who bring their own sources and never
|
|
5
|
+
// touch an IMP knowledge base. What that buys in reach it pays for in abuse
|
|
6
|
+
// surface, so every guard here is load-bearing.
|
|
7
|
+
import type { Express, Request, Response } from "express";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import type { LanguageModel } from "ai";
|
|
10
|
+
import type { User } from "@EXULU_TYPES/models/user";
|
|
11
|
+
import type { ScopeCheckResult } from "@SRC/utils/check-api-key-scope";
|
|
12
|
+
import { isExternalOrAnonymousUser } from "@SRC/exulu/resolve-max-steps";
|
|
13
|
+
import { treatAsGuest } from "@SRC/exulu/public-surface";
|
|
14
|
+
import { type ClaimCheckOptions, type ClaimCheckResult, type ClaimCheckSource, type ClaimCheckSourceType } from "./types";
|
|
15
|
+
import type { ClaimCheckRateLimiter } from "./rate-limit";
|
|
16
|
+
import { pipelineConfigFor } from "./agent-config";
|
|
17
|
+
|
|
18
|
+
export const CLAIM_CHECK_PATH = "/claims/check";
|
|
19
|
+
export const CLAIM_CHECK_SESSION_PATH = "/claims/check/:session";
|
|
20
|
+
|
|
21
|
+
/** Rejects anything that is not a v4-shaped uuid before the database sees it. */
|
|
22
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* `auth.user.id` must not just be truthy, it must coerce to a finite number:
|
|
26
|
+
* the `claim_checks.user` column is a float, knex keeps a `NaN` binding alive
|
|
27
|
+
* rather than dropping it, `pg` sends it as the literal string `"NaN"`, and
|
|
28
|
+
* Postgres evaluates `NaN = NaN` as true — so a future auth path that ever
|
|
29
|
+
* produced a truthy non-numeric principal id would read and write one shared
|
|
30
|
+
* bucket instead of erroring. Not reachable today (every auth branch yields a
|
|
31
|
+
* numeric id); this is a guard against that never happening, not a fix for a
|
|
32
|
+
* live bug.
|
|
33
|
+
*/
|
|
34
|
+
function hasNumericUserId(user: { id?: unknown } | undefined): boolean {
|
|
35
|
+
return Boolean(user?.id) && Number.isFinite(Number(user?.id));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The status for a request that failed the gate above.
|
|
40
|
+
*
|
|
41
|
+
* `auth.code` describes the authentication ATTEMPT, not this gate: when a
|
|
42
|
+
* principal came back but its id is unusable, the attempt may well have
|
|
43
|
+
* "succeeded" (`code: 200`, or a `0` a future branch might leave unset), and
|
|
44
|
+
* echoing that would answer a 200 — or a nonsensical 0 — with an
|
|
45
|
+
* "Unauthorized." body. A principal we refuse to key a row by is a 401,
|
|
46
|
+
* whatever the attempt said. Only a genuine auth failure's own code (403 on a
|
|
47
|
+
* disabled key, say) is passed through.
|
|
48
|
+
*/
|
|
49
|
+
function unauthorizedStatus(auth: { user?: unknown; code?: number }): number {
|
|
50
|
+
if (auth.user) return 401;
|
|
51
|
+
return (auth.code ?? 0) || 401;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Payload caps: an answer is prose, evidence is documents. Beyond these, 413. */
|
|
55
|
+
const MAX_ANSWER_CHARS = 200_000;
|
|
56
|
+
const MAX_EVIDENCE_CHARS = 2_000_000;
|
|
57
|
+
const MAX_SOURCES = 200;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Request deadline (spec §4). Without it, a hung provider holds one of the 20
|
|
61
|
+
* global in-flight slots until the transport gives up, and twenty such
|
|
62
|
+
* requests 429 the endpoint deployment-wide. The engine races a timer: the
|
|
63
|
+
* signal cancels the provider calls, the slot is released either way, and the
|
|
64
|
+
* caller gets a 504 rather than an open socket.
|
|
65
|
+
*
|
|
66
|
+
* This is the fallback default, and stays the module's own ceiling when
|
|
67
|
+
* `CLAIM_CHECK_TIMEOUT_MS` is unset or unusable — see
|
|
68
|
+
* `resolveClaimCheckTimeoutMs` below, which is what the handler actually
|
|
69
|
+
* races against.
|
|
70
|
+
*/
|
|
71
|
+
export const CLAIM_CHECK_TIMEOUT_MS = 60_000;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* `CLAIM_CHECK_TIMEOUT_MS` the env var, read fresh per request (not cached at
|
|
75
|
+
* module load) so a deployment can raise it without a restart of this
|
|
76
|
+
* module's test doubles, and so the garbage-value fallback below is testable
|
|
77
|
+
* without re-importing the module. Parsed defensively: an operator raising
|
|
78
|
+
* `claim_check.caps.maxSentences` without raising this would otherwise spend
|
|
79
|
+
* hundreds of provider calls and still get a 504, which is strictly worse
|
|
80
|
+
* than the cap's own "partial" degradation — so a non-numeric or
|
|
81
|
+
* non-positive value falls back to the default rather than disabling the
|
|
82
|
+
* deadline (e.g. turning it into `NaN`, which never fires).
|
|
83
|
+
*/
|
|
84
|
+
export function resolveClaimCheckTimeoutMs(): number {
|
|
85
|
+
const raw = process.env.CLAIM_CHECK_TIMEOUT_MS;
|
|
86
|
+
if (raw === undefined) return CLAIM_CHECK_TIMEOUT_MS;
|
|
87
|
+
const parsed = Number(raw);
|
|
88
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : CLAIM_CHECK_TIMEOUT_MS;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Thrown by the deadline race only, so the catch can tell 504 from 500. */
|
|
92
|
+
class ClaimCheckTimeoutError extends Error {}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A locale the engine can actually segment with. An unusable tag used to reach
|
|
96
|
+
* `new Intl.Segmenter` inside the engine and throw into its outer catch, so
|
|
97
|
+
* garbage produced 200 + an empty partial result instead of §4's 400.
|
|
98
|
+
*/
|
|
99
|
+
function localeIsUsable(locale: string): boolean {
|
|
100
|
+
try {
|
|
101
|
+
new Intl.Segmenter(locale, { granularity: "sentence" });
|
|
102
|
+
return true;
|
|
103
|
+
} catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* requested ?? configured, floored by the configured value.
|
|
110
|
+
*
|
|
111
|
+
* A request can only ever TIGHTEN a cap, so an authenticated non-admin cannot
|
|
112
|
+
* buy itself thousands of provider calls and thousands of full retrievals by
|
|
113
|
+
* posting a bigger number. There is deliberately no absolute module ceiling on
|
|
114
|
+
* top (ruling R33): a ceiling clamps the OPERATOR's own configured value too,
|
|
115
|
+
* which is how a 44,000-character NEWLIFT answer (568 sentences after list
|
|
116
|
+
* segmentation) ended up 21% checked with no configuration path to raise it.
|
|
117
|
+
* An operator configuring their own agent is trusted, because they pay for it,
|
|
118
|
+
* as with every other retrieval knob. `configured` comes from the agent's
|
|
119
|
+
* `claim_check.caps`, whose schema defaults are CLAIM_CHECK_DEFAULTS.caps — so
|
|
120
|
+
* the agent-less caller still gets the engine defaults, from one definition.
|
|
121
|
+
*/
|
|
122
|
+
function clampCap(requested: number | undefined, configured: number): number {
|
|
123
|
+
return Math.min(requested ?? configured, configured);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Spelled once, derived from the one declaration of `ClaimCheckSourceType`
|
|
128
|
+
* (./types) rather than re-spelled here: `satisfies` below catches an entry
|
|
129
|
+
* that is not a member of that union, and the type-level check right after
|
|
130
|
+
* catches the opposite drift — a union member missing from this array. Two
|
|
131
|
+
* independently hand-spelled lists would drift silently the day a seventh
|
|
132
|
+
* type is added there: the enum would just reject a type the rest of the
|
|
133
|
+
* system emits, with no compile error pointing at why.
|
|
134
|
+
*/
|
|
135
|
+
const SOURCE_TYPES = [
|
|
136
|
+
"knowledge_base",
|
|
137
|
+
"document",
|
|
138
|
+
"memory",
|
|
139
|
+
"web",
|
|
140
|
+
"session_item",
|
|
141
|
+
"other",
|
|
142
|
+
] as const satisfies readonly ClaimCheckSourceType[];
|
|
143
|
+
type _SourceTypesCoverTheWholeUnion = ClaimCheckSourceType extends (typeof SOURCE_TYPES)[number] ? true : never;
|
|
144
|
+
const _sourceTypesCoverTheWholeUnion: _SourceTypesCoverTheWholeUnion = true;
|
|
145
|
+
|
|
146
|
+
const requestSchema = z.object({
|
|
147
|
+
question: z.string().min(1),
|
|
148
|
+
answer: z.string().min(1),
|
|
149
|
+
sources: z
|
|
150
|
+
.array(
|
|
151
|
+
z.object({
|
|
152
|
+
content: z.string(),
|
|
153
|
+
name: z.string().optional(),
|
|
154
|
+
// Purely informational (spec §2: no trust tiers, dropped before the
|
|
155
|
+
// engine sees it — see assignSourceIds below), so an unrecognised
|
|
156
|
+
// value is IGNORED, not rejected: `.catch(undefined)` keeps the enum
|
|
157
|
+
// as documentation and as the inferred type, but falls back to
|
|
158
|
+
// `undefined` instead of failing the whole request over a mislabeled
|
|
159
|
+
// field nothing downstream reads. Before this task, an unknown
|
|
160
|
+
// `type` wasn't in the schema at all and was silently stripped by
|
|
161
|
+
// zod's default object parsing — a bare `.optional()` here (no
|
|
162
|
+
// `.catch`) would turn that pre-existing 200 into a 400, which is a
|
|
163
|
+
// tightening this loosening-only task must not make. Do not remove
|
|
164
|
+
// the `.catch` to "validate properly": that is the bug this guards.
|
|
165
|
+
type: z.enum(SOURCE_TYPES).optional().catch(undefined),
|
|
166
|
+
id: z.string().min(1).optional(),
|
|
167
|
+
}),
|
|
168
|
+
)
|
|
169
|
+
.default([]),
|
|
170
|
+
agent: z.string().optional(),
|
|
171
|
+
session: z.string().optional(),
|
|
172
|
+
messageId: z.string().optional(),
|
|
173
|
+
model: z.string().optional(),
|
|
174
|
+
locale: z
|
|
175
|
+
.string()
|
|
176
|
+
.refine(localeIsUsable, { message: "locale is not a usable BCP 47 language tag" })
|
|
177
|
+
.optional(),
|
|
178
|
+
options: z
|
|
179
|
+
.object({
|
|
180
|
+
fidelity: z.enum(["fast", "paper"]).optional(),
|
|
181
|
+
completions: z.number().int().min(1).max(3).optional(),
|
|
182
|
+
reRetrieve: z.boolean().optional(),
|
|
183
|
+
thresholds: z.object({ warn: z.number().min(0).max(1), alert: z.number().min(0).max(1) }).partial().optional(),
|
|
184
|
+
caps: z
|
|
185
|
+
.object({
|
|
186
|
+
maxSentences: z.number().int().positive(),
|
|
187
|
+
maxClaims: z.number().int().positive(),
|
|
188
|
+
maxReRetrievals: z.number().int().min(0),
|
|
189
|
+
})
|
|
190
|
+
.partial()
|
|
191
|
+
.optional(),
|
|
192
|
+
})
|
|
193
|
+
.optional(),
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* One source as the request carries it — derived from the schema three lines
|
|
198
|
+
* above rather than hand-spelled, so loosening a field there cannot leave
|
|
199
|
+
* this type claiming the old shape.
|
|
200
|
+
*/
|
|
201
|
+
type RequestSource = z.infer<typeof requestSchema>["sources"][number];
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* One id per source, because `evidence[].sourceId` has to resolve to exactly
|
|
205
|
+
* one document. A caller may supply ids for some sources, none, or all — so a
|
|
206
|
+
* generated id gets `_` suffixes until it stops colliding with a supplied
|
|
207
|
+
* one, and two sources supplying the SAME id are refused outright: an
|
|
208
|
+
* evidence quote that cannot be traced to exactly one document is worse than
|
|
209
|
+
* a rejected request, since the panel shows a quote to a reader as the
|
|
210
|
+
* justification for a verdict.
|
|
211
|
+
*
|
|
212
|
+
* `type` is accepted on the request (spec §3-4: it lets a UI label and group
|
|
213
|
+
* sources, and makes a request self-describing in a log) and deliberately
|
|
214
|
+
* dropped right here, before the engine ever sees a source. The engine
|
|
215
|
+
* (run.ts, evidence.ts) treats every source identically regardless of where
|
|
216
|
+
* it came from — spec §2 rejects trust tiers, so a web page and a
|
|
217
|
+
* knowledge-base document carry the same evidentiary weight. Do not thread
|
|
218
|
+
* this field through to the engine "to not lose it": the engine's source
|
|
219
|
+
* type is `{ id, name?, content }` on purpose, and stays that way.
|
|
220
|
+
*/
|
|
221
|
+
function assignSourceIds(
|
|
222
|
+
sources: RequestSource[],
|
|
223
|
+
): { ok: true; sources: ClaimCheckSource[] } | { ok: false; detail: string } {
|
|
224
|
+
const supplied = new Set<string>();
|
|
225
|
+
for (const s of sources) {
|
|
226
|
+
if (!s.id) continue;
|
|
227
|
+
if (supplied.has(s.id)) return { ok: false, detail: `duplicate source id "${s.id}"` };
|
|
228
|
+
supplied.add(s.id);
|
|
229
|
+
}
|
|
230
|
+
const used = new Set(supplied);
|
|
231
|
+
return {
|
|
232
|
+
ok: true,
|
|
233
|
+
sources: sources.map((s, i) => {
|
|
234
|
+
let id = s.id;
|
|
235
|
+
if (!id) {
|
|
236
|
+
id = `s${i + 1}`;
|
|
237
|
+
while (used.has(id)) id = `${id}_`;
|
|
238
|
+
}
|
|
239
|
+
used.add(id);
|
|
240
|
+
return s.name ? { id, name: s.name, content: s.content } : { id, content: s.content };
|
|
241
|
+
}),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export type ClaimCheckRouteDeps = {
|
|
246
|
+
authenticate: (req: Request) => Promise<{ user?: User; error?: boolean; code?: number; message?: string }>;
|
|
247
|
+
checkApiKeyScope: (user: User | undefined, agentId: string) => ScopeCheckResult;
|
|
248
|
+
checkRecordAccess: (record: any, request: "read" | "write", user?: User) => Promise<boolean>;
|
|
249
|
+
getAgent: (id: string) => Promise<any | undefined>;
|
|
250
|
+
resolveModel: (input: { modelId: string; user?: User }) => Promise<{ languageModel?: LanguageModel }>;
|
|
251
|
+
runCheck: (args: {
|
|
252
|
+
question: string;
|
|
253
|
+
answer: string;
|
|
254
|
+
sources: { id: string; name?: string; content: string }[];
|
|
255
|
+
model: LanguageModel;
|
|
256
|
+
options: ClaimCheckOptions;
|
|
257
|
+
locale?: string;
|
|
258
|
+
secondChance?: (claimText: string) => Promise<any[]>;
|
|
259
|
+
signal?: AbortSignal;
|
|
260
|
+
}) => Promise<ClaimCheckResult>;
|
|
261
|
+
isLicensed: () => boolean;
|
|
262
|
+
limiter: ClaimCheckRateLimiter;
|
|
263
|
+
/** src/exulu/external-rate-limit.ts — the same pair every sibling handler uses. */
|
|
264
|
+
isExternalUser: (user: User | undefined) => boolean;
|
|
265
|
+
externalRateLimitExceeded: (userId: string) => boolean;
|
|
266
|
+
platformDefaultModel: () => Promise<string>;
|
|
267
|
+
/** Supplied by Task 13; absent means no second-chance retrieval. */
|
|
268
|
+
secondChanceFor?: (args: { agent: any; user?: User; model: LanguageModel; cap: number }) =>
|
|
269
|
+
| ((claimText: string) => Promise<any[]>)
|
|
270
|
+
| undefined;
|
|
271
|
+
/** Upsert one stored check. Absent in tests that do not exercise persistence. */
|
|
272
|
+
saveClaimCheck?: (args: {
|
|
273
|
+
session: string;
|
|
274
|
+
messageId: string;
|
|
275
|
+
userId: number;
|
|
276
|
+
result: ClaimCheckResult;
|
|
277
|
+
}) => Promise<void>;
|
|
278
|
+
/** Stored checks for a session, keyed by message id, scoped to the caller. */
|
|
279
|
+
listClaimChecks?: (args: { session: string; userId: number }) => Promise<Record<string, ClaimCheckResult>>;
|
|
280
|
+
/**
|
|
281
|
+
* The stored check for ONE message, scoped to the caller — consulted before
|
|
282
|
+
* the engine runs (spec §5.2). Absent means no lookup and no caching, which
|
|
283
|
+
* is the pre-stage-3 behaviour.
|
|
284
|
+
*/
|
|
285
|
+
findClaimCheck?: (args: {
|
|
286
|
+
session: string;
|
|
287
|
+
messageId: string;
|
|
288
|
+
userId: number;
|
|
289
|
+
}) => Promise<ClaimCheckResult | undefined>;
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
export function registerClaimCheckRoutes(app: Express, deps: ClaimCheckRouteDeps): void {
|
|
293
|
+
app.post(CLAIM_CHECK_PATH, async (req: Request, res: Response) => {
|
|
294
|
+
// An unlicensed deployment does not advertise a feature it has not bought.
|
|
295
|
+
if (!deps.isLicensed()) {
|
|
296
|
+
res.status(404).json({ detail: "Not found." });
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const parsed = requestSchema.safeParse(req.body);
|
|
301
|
+
if (!parsed.success) {
|
|
302
|
+
res.status(400).json({ detail: `Invalid request body: ${parsed.error.issues[0]?.message ?? "unknown"}` });
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const body = parsed.data;
|
|
306
|
+
|
|
307
|
+
// `type` was already reduced to a known value or `undefined` above
|
|
308
|
+
// (unrecognised values are ignored, not rejected — see the schema's
|
|
309
|
+
// `.catch`) and is discarded here, before anything else touches
|
|
310
|
+
// `sources` — see assignSourceIds's own doc comment.
|
|
311
|
+
const assigned = assignSourceIds(body.sources);
|
|
312
|
+
if (!assigned.ok) {
|
|
313
|
+
res.status(400).json({ detail: assigned.detail });
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const sources = assigned.sources;
|
|
317
|
+
|
|
318
|
+
if (body.answer.length > MAX_ANSWER_CHARS) {
|
|
319
|
+
res.status(413).json({ detail: `answer exceeds ${MAX_ANSWER_CHARS} characters.` });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (sources.length > MAX_SOURCES) {
|
|
323
|
+
res.status(413).json({ detail: `more than ${MAX_SOURCES} sources.` });
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const evidenceChars = sources.reduce((n, s) => n + s.content.length, 0);
|
|
327
|
+
if (evidenceChars > MAX_EVIDENCE_CHARS) {
|
|
328
|
+
res.status(413).json({ detail: `source content exceeds ${MAX_EVIDENCE_CHARS} characters in total.` });
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const auth = await deps.authenticate(req);
|
|
333
|
+
if (!hasNumericUserId(auth.user)) {
|
|
334
|
+
res.status(unauthorizedStatus(auth)).json({ detail: auth.message ?? "Unauthorized." });
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
const user = auth.user as User;
|
|
338
|
+
|
|
339
|
+
// Spec §4: the external/guest budget applies here as everywhere else, so
|
|
340
|
+
// an external identity does not get a fresh 30/min on the most expensive
|
|
341
|
+
// endpoint in the product. This is on TOP of the claim-check limiter
|
|
342
|
+
// below, which applies to every role.
|
|
343
|
+
if (deps.isExternalUser(user) && deps.externalRateLimitExceeded(String(user.id))) {
|
|
344
|
+
res.status(429).json({ detail: "Too many requests. Try again later." });
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// R22: `resolveModel`'s `rbacBypass`/`rbacRequest` are declared but read
|
|
349
|
+
// nowhere, and `MODEL_FORBIDDEN` is never thrown (src/exulu/resolve-model.ts)
|
|
350
|
+
// — there is no per-user model entitlement check to lean on there. Without
|
|
351
|
+
// a gate here, any authenticated caller could name an arbitrary (and
|
|
352
|
+
// arbitrarily expensive) model on an endpoint that is deliberately fed
|
|
353
|
+
// arbitrary text. So a request-supplied `model` is honoured only for a
|
|
354
|
+
// super admin; everyone else must configure claim_check.model on the agent.
|
|
355
|
+
if (body.model && !user.super_admin) {
|
|
356
|
+
res.status(403).json({
|
|
357
|
+
detail:
|
|
358
|
+
"Choosing the model per request requires a super-admin key; configure claim_check.model on the agent instead.",
|
|
359
|
+
});
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Same reasoning as the model gate, for the two knobs that multiply the
|
|
364
|
+
// call count rather than the price per call: `paper` unmerges every stage
|
|
365
|
+
// and batches one sentence per call, and `completions` votes each of those
|
|
366
|
+
// stages N times. Both are benchmark instruments (spec §8), and our own
|
|
367
|
+
// benchmark runs with an admin key.
|
|
368
|
+
if ((body.options?.fidelity === "paper" || (body.options?.completions ?? 1) > 1) && !user.super_admin) {
|
|
369
|
+
res.status(403).json({
|
|
370
|
+
detail:
|
|
371
|
+
"`options.fidelity: \"paper\"` and `options.completions` above 1 require a super-admin key; " +
|
|
372
|
+
"configure claim_check.fidelity and claim_check.completions on the agent instead.",
|
|
373
|
+
});
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
let agent: any | undefined;
|
|
378
|
+
if (body.agent) {
|
|
379
|
+
const scope = deps.checkApiKeyScope(user, body.agent);
|
|
380
|
+
if (!scope.allowed) {
|
|
381
|
+
res.status(scope.code).json({ detail: scope.reason });
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
// A malformed id (not a UUID) makes the lookup throw rather than return
|
|
385
|
+
// undefined, which used to surface as a 500. "No such agent" is the same
|
|
386
|
+
// fact either way, so it answers 404.
|
|
387
|
+
try {
|
|
388
|
+
agent = await deps.getAgent(body.agent);
|
|
389
|
+
} catch (err) {
|
|
390
|
+
console.warn(
|
|
391
|
+
`[EXULU] claim check: agent lookup for "${body.agent}" failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
if (!agent) {
|
|
395
|
+
res.status(404).json({ detail: `Agent ${body.agent} not found.` });
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (!(await deps.checkRecordAccess(agent, "read", user))) {
|
|
399
|
+
res.status(403).json({ detail: "You don't have access to this agent." });
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// R1: task 2's zod parser, not a hand-rolled one — one parser for the
|
|
405
|
+
// claim_check blob, never two that can drift apart.
|
|
406
|
+
const cfg = pipelineConfigFor(agent);
|
|
407
|
+
|
|
408
|
+
// Spec §3/§5: claim_check is opt-in per agent because the feature costs
|
|
409
|
+
// money, and no check ever runs for an agent whose admin left it off —
|
|
410
|
+
// otherwise naming that agent here would spend its model's tokens and run
|
|
411
|
+
// second-chance retrieval against its knowledge bases anyway.
|
|
412
|
+
if (agent && !cfg.claimCheck.enabled) {
|
|
413
|
+
res.status(403).json({
|
|
414
|
+
detail: "Claim check is not enabled for this agent; set claim_check.enabled on its knowledge-search tool.",
|
|
415
|
+
});
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// Spec §5: a guest or external viewer sees no claim check unless the agent
|
|
420
|
+
// says they may. isExternalOrAnonymousUser is the helper the sibling
|
|
421
|
+
// show_sources_to_external_users flag uses, and this is the same
|
|
422
|
+
// visibility question about the same kind of viewer. treatAsGuest adds
|
|
423
|
+
// the public surface: a signed-in internal user viewing a public agent
|
|
424
|
+
// link renders in guest mode, so the endpoint must refuse them the same
|
|
425
|
+
// way the chat's finish-part fragment does (src/exulu/claim-check/finish-metadata.ts).
|
|
426
|
+
if (agent && (treatAsGuest(req, user) || isExternalOrAnonymousUser(user)) && !cfg.claimCheck.showToExternalUsers) {
|
|
427
|
+
res.status(403).json({
|
|
428
|
+
detail:
|
|
429
|
+
"Claim check is not available to external users for this agent; " +
|
|
430
|
+
"set claim_check.showToExternalUsers to allow it.",
|
|
431
|
+
});
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// A verdict already on disk is not bought twice (spec §5.2's result cache,
|
|
436
|
+
// in this branch's shape). A double-fire, a user-initiated re-check or a
|
|
437
|
+
// retry after a transport hiccup would otherwise pay ~8 provider calls
|
|
438
|
+
// again for an answer that is already stored.
|
|
439
|
+
//
|
|
440
|
+
// Three properties this must keep:
|
|
441
|
+
// - It sits AFTER every gate above, so a stored row can never become a
|
|
442
|
+
// way to read a verdict for an agent whose admin turned the check off,
|
|
443
|
+
// or an agent the caller may not use.
|
|
444
|
+
// - It is scoped by the authenticated caller exactly as the GET is —
|
|
445
|
+
// (session, message_id, user) in one query, never a request-supplied
|
|
446
|
+
// identity (see src/exulu/claim-check/store.ts).
|
|
447
|
+
// - A lookup failure falls THROUGH to running the check. A cache that
|
|
448
|
+
// can break the feature it accelerates is worse than no cache.
|
|
449
|
+
//
|
|
450
|
+
// §9 keeps the Redis hash-keyed cache deferred: it now only matters for
|
|
451
|
+
// agent-less API callers who name no session, who have no row to find.
|
|
452
|
+
if (deps.findClaimCheck && body.session && body.messageId && UUID_RE.test(body.session)) {
|
|
453
|
+
try {
|
|
454
|
+
const stored = await deps.findClaimCheck({
|
|
455
|
+
session: body.session,
|
|
456
|
+
messageId: body.messageId,
|
|
457
|
+
userId: Number(user.id),
|
|
458
|
+
});
|
|
459
|
+
if (stored) {
|
|
460
|
+
res.status(200).json(stored);
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
} catch (err) {
|
|
464
|
+
console.warn(
|
|
465
|
+
"[EXULU claim-check] could not read the stored check for this message; running the check.",
|
|
466
|
+
err,
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const candidates = [
|
|
472
|
+
body.model,
|
|
473
|
+
cfg.claimCheck.model,
|
|
474
|
+
cfg.utilityModel,
|
|
475
|
+
agent?.model,
|
|
476
|
+
await deps.platformDefaultModel(),
|
|
477
|
+
].filter((id): id is string => Boolean(id));
|
|
478
|
+
|
|
479
|
+
if (candidates.length === 0) {
|
|
480
|
+
// The platform default comes from the CLAIM_CHECK_DEFAULT_MODEL env var
|
|
481
|
+
// (see src/exulu/routes.ts). The DB-backed platform setting the spec
|
|
482
|
+
// sketched does not exist and is a recorded deferral, so naming it here
|
|
483
|
+
// was a first-run dead end for the agent-less API client.
|
|
484
|
+
res.status(400).json({
|
|
485
|
+
detail:
|
|
486
|
+
"No model to run the check with: pass `model`, configure claim_check.model on the agent, " +
|
|
487
|
+
"or set the CLAIM_CHECK_DEFAULT_MODEL environment variable on the backend.",
|
|
488
|
+
});
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// No rbacBypass is passed here (unlike the retrieval tool's utility_model) —
|
|
493
|
+
// that flag is inert in resolveModel today, but the super-admin gate above
|
|
494
|
+
// is what actually keeps a non-admin caller off an arbitrary model.
|
|
495
|
+
let model: LanguageModel | undefined;
|
|
496
|
+
let lastError: unknown;
|
|
497
|
+
for (const modelId of candidates) {
|
|
498
|
+
try {
|
|
499
|
+
const resolved = await deps.resolveModel({ modelId, user });
|
|
500
|
+
if (resolved.languageModel) {
|
|
501
|
+
model = resolved.languageModel;
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
} catch (err) {
|
|
505
|
+
lastError = err;
|
|
506
|
+
// A transient infra failure on an early candidate must stay visible
|
|
507
|
+
// even when a later candidate resolves and the request succeeds.
|
|
508
|
+
console.warn(
|
|
509
|
+
`[EXULU] claim check: model "${modelId}" failed to resolve: ${err instanceof Error ? err.message : String(err)}`,
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (!model) {
|
|
514
|
+
res.status(400).json({
|
|
515
|
+
detail: `Could not resolve a model for the claim check${lastError instanceof Error ? `: ${lastError.message}` : ""}.`,
|
|
516
|
+
});
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const options: ClaimCheckOptions = {
|
|
521
|
+
fidelity: body.options?.fidelity ?? cfg.claimCheck.fidelity,
|
|
522
|
+
completions: body.options?.completions ?? cfg.claimCheck.completions,
|
|
523
|
+
reRetrieve: typeof body.options?.reRetrieve === "boolean" ? body.options.reRetrieve : cfg.claimCheck.reRetrieve,
|
|
524
|
+
thresholds: {
|
|
525
|
+
warn: body.options?.thresholds?.warn ?? cfg.claimCheck.thresholds.warn,
|
|
526
|
+
alert: body.options?.thresholds?.alert ?? cfg.claimCheck.thresholds.alert,
|
|
527
|
+
},
|
|
528
|
+
// Caps CLAMP, they do not override: a caller may tighten a check (cheaper,
|
|
529
|
+
// narrower) but never loosen one.
|
|
530
|
+
caps: {
|
|
531
|
+
maxSentences: clampCap(body.options?.caps?.maxSentences, cfg.claimCheck.caps.maxSentences),
|
|
532
|
+
maxClaims: clampCap(body.options?.caps?.maxClaims, cfg.claimCheck.caps.maxClaims),
|
|
533
|
+
maxReRetrievals: clampCap(body.options?.caps?.maxReRetrievals, cfg.claimCheck.caps.maxReRetrievals),
|
|
534
|
+
},
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
// A warn above alert makes every label "alert" — a misconfiguration that
|
|
538
|
+
// would be read as a hallucination finding, so it is refused, not applied.
|
|
539
|
+
if (options.thresholds.warn > options.thresholds.alert) {
|
|
540
|
+
res.status(400).json({
|
|
541
|
+
detail:
|
|
542
|
+
`thresholds.warn (${options.thresholds.warn}) must not exceed thresholds.alert ` +
|
|
543
|
+
`(${options.thresholds.alert}); check the request options and the agent's claim_check.thresholds.`,
|
|
544
|
+
});
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const slot = deps.limiter.take(String(user.id));
|
|
549
|
+
if (!slot.ok) {
|
|
550
|
+
res.status(429).json({ detail: slot.reason ?? "Too many requests. Try again later." });
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const controller = new AbortController();
|
|
555
|
+
const timeoutMs = resolveClaimCheckTimeoutMs();
|
|
556
|
+
let deadline: ReturnType<typeof setTimeout> | undefined;
|
|
557
|
+
// Set only on the success path, and read only after the slot is released
|
|
558
|
+
// below — persistence must never hold the global in-flight budget open,
|
|
559
|
+
// and the write needs its own deadline, not one that raced a
|
|
560
|
+
// Promise.race the response already settled.
|
|
561
|
+
let completedResult: ClaimCheckResult | undefined;
|
|
562
|
+
try {
|
|
563
|
+
const secondChance =
|
|
564
|
+
agent && options.reRetrieve && deps.secondChanceFor
|
|
565
|
+
? deps.secondChanceFor({ agent, user, model, cap: options.caps.maxReRetrievals })
|
|
566
|
+
: undefined;
|
|
567
|
+
|
|
568
|
+
const timedOut = new Promise<never>((_resolve, reject) => {
|
|
569
|
+
deadline = setTimeout(() => {
|
|
570
|
+
controller.abort();
|
|
571
|
+
reject(new ClaimCheckTimeoutError());
|
|
572
|
+
}, timeoutMs);
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
const result = await Promise.race([
|
|
576
|
+
deps.runCheck({
|
|
577
|
+
question: body.question,
|
|
578
|
+
answer: body.answer,
|
|
579
|
+
sources,
|
|
580
|
+
model,
|
|
581
|
+
options,
|
|
582
|
+
signal: controller.signal,
|
|
583
|
+
...(body.locale ? { locale: body.locale } : {}),
|
|
584
|
+
...(secondChance ? { secondChance } : {}),
|
|
585
|
+
}),
|
|
586
|
+
timedOut,
|
|
587
|
+
]);
|
|
588
|
+
// Recorded BEFORE the response is sent: if the client has gone away and
|
|
589
|
+
// res.json throws, the check was already paid for, and discarding it
|
|
590
|
+
// then is the one case where persistence matters most — the next load
|
|
591
|
+
// of that session would re-buy a verdict we already had.
|
|
592
|
+
completedResult = result;
|
|
593
|
+
res.status(200).json(result);
|
|
594
|
+
} catch (err) {
|
|
595
|
+
if (err instanceof ClaimCheckTimeoutError) {
|
|
596
|
+
console.warn(`[EXULU] claim check exceeded the ${timeoutMs} ms deadline.`);
|
|
597
|
+
res.status(504).json({
|
|
598
|
+
detail: `The claim check did not finish within ${timeoutMs / 1000} seconds and was cancelled.`,
|
|
599
|
+
});
|
|
600
|
+
} else {
|
|
601
|
+
console.error("[EXULU] claim check failed.", err);
|
|
602
|
+
res.status(500).json({ detail: "The claim check failed." });
|
|
603
|
+
}
|
|
604
|
+
} finally {
|
|
605
|
+
// Always release: an unreleased slot leaks the global in-flight budget —
|
|
606
|
+
// including on the timeout path, where the engine may still be unwinding.
|
|
607
|
+
if (deadline) clearTimeout(deadline);
|
|
608
|
+
deps.limiter.release();
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// Persistence is a convenience, not part of the verdict, and runs ONLY
|
|
612
|
+
// after the slot is released and the deadline timer is cleared above: a
|
|
613
|
+
// database write that hangs must never pin the deployment-wide in-flight
|
|
614
|
+
// budget that 429s this endpoint for every other caller. The response
|
|
615
|
+
// was already sent inside the try block; a reload losing the panel is
|
|
616
|
+
// worse than nothing, but a database hiccup here must not turn a
|
|
617
|
+
// completed check into an error the caller has already paid for — so
|
|
618
|
+
// this runs outside any try/catch that could still touch `res`, in its
|
|
619
|
+
// own try/catch that only logs.
|
|
620
|
+
if (completedResult && body.session && body.messageId && UUID_RE.test(body.session)) {
|
|
621
|
+
if (!deps.saveClaimCheck) {
|
|
622
|
+
// A missing dep is a deployment wiring defect, not "nothing to store".
|
|
623
|
+
// The GET refuses loudly for exactly this reason; skipping silently
|
|
624
|
+
// here meant a panel that never survived a reload, with no signal
|
|
625
|
+
// anywhere that the wiring had been dropped.
|
|
626
|
+
console.error(
|
|
627
|
+
"[EXULU claim-check] saveClaimCheck is not wired; this check cannot survive a reload.",
|
|
628
|
+
);
|
|
629
|
+
} else {
|
|
630
|
+
try {
|
|
631
|
+
await deps.saveClaimCheck({
|
|
632
|
+
session: body.session,
|
|
633
|
+
messageId: body.messageId,
|
|
634
|
+
userId: Number(user.id),
|
|
635
|
+
result: completedResult,
|
|
636
|
+
});
|
|
637
|
+
} catch (err) {
|
|
638
|
+
console.warn("[EXULU claim-check] could not store the check for this message.", err);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
// GET /claims/check/:session — the only read path to the claim_checks
|
|
645
|
+
// table (it has no GraphQL surface: see ee/schemas.ts's claimChecksSchema).
|
|
646
|
+
// The stored payload holds the answer's sentences and verbatim source
|
|
647
|
+
// quotes, so scoping here is the only thing standing between one user and
|
|
648
|
+
// another user's stored answers: the query itself filters by session AND
|
|
649
|
+
// the authenticated caller's id, never by session alone with a JS filter,
|
|
650
|
+
// and a request-supplied user id is never trusted.
|
|
651
|
+
app.get(CLAIM_CHECK_SESSION_PATH, async (req: Request, res: Response) => {
|
|
652
|
+
if (!deps.isLicensed()) {
|
|
653
|
+
res.status(404).json({ detail: "Not found." });
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
const session = req.params.session ?? "";
|
|
657
|
+
if (!UUID_RE.test(session)) {
|
|
658
|
+
res.status(400).json({ detail: "session must be a uuid." });
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
const auth = await deps.authenticate(req);
|
|
662
|
+
if (!hasNumericUserId(auth.user)) {
|
|
663
|
+
res.status(unauthorizedStatus(auth)).json({ detail: auth.message ?? "Unauthorized." });
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (!deps.listClaimChecks) {
|
|
667
|
+
// A missing dep is a deployment wiring defect, not "nothing stored":
|
|
668
|
+
// answering 200 here would make a future regression that drops the
|
|
669
|
+
// wiring read as an empty, legitimate result instead of failing loudly.
|
|
670
|
+
console.error("[EXULU claim-check] listClaimChecks is not wired; refusing to answer as if nothing were stored.");
|
|
671
|
+
res.status(500).json({ detail: "Could not read stored checks." });
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
const checks = await deps.listClaimChecks({ session, userId: Number((auth.user as User).id) });
|
|
676
|
+
res.status(200).json({ checks });
|
|
677
|
+
} catch (err) {
|
|
678
|
+
console.error("[EXULU claim-check] could not read stored checks.", err);
|
|
679
|
+
res.status(500).json({ detail: "Could not read stored checks." });
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
}
|