Spaces:
Running
Running
Sync from felladrin/MiniSearch@59d7d83 (part 2)
Browse filesFiles changed (42)
- scripts/documentation-validator.cjs-17
- scripts/npm-bundle-overlay.cjs+2-2
- server/authorityRanking.ts-1
- server/authorizationSinceLastRestart.ts+2-5
- server/biEncoderService.integration.test.ts+6-8
- server/biEncoderService.ts+3-9
- server/biEncoderWorker.ts+8-18
- server/biEncoderWorkerProtocol.ts+11-13
- server/configEndpointServerHook.ts+2-3
- server/downloadFileFromHuggingFaceRepository.ts+3-4
- server/fallbackSearchService.ts+11-40
- server/inferencesSinceLastRestart.ts+2-5
- server/internalApiEndpointServerHook.test.ts-11
- server/internalApiEndpointServerHook.ts+4-6
- server/officialLane.ts+2-5
- server/pageContentService.test.ts+15-21
- server/pageContentService.ts+13-21
- server/pageReadHostBreaker.ts+2-3
- server/rankSearchResults.test.ts+1-2
- server/rejectedTokens.ts+2-2
- server/rerankerService.ts+7-23
- server/rerankingSinceLastRestart.ts+1-3
- server/searchToken.test.ts+3-3
- server/searchToken.ts+3-9
- server/searchesSinceLastRestart.ts+7-10
- server/statusEndpointServerHook.test.ts+2-3
- server/thumbnailEndpointServerHook.test.ts-1
- server/thumbnailEndpointServerHook.ts+13-15
- server/utils/circuitBreaker.ts+6-11
- server/utils/httpResponse.ts-3
- server/utils/onnxModelLoader.ts+1-6
- server/utils/openableUrl.ts-3
- server/utils/pinnedFetch.ts-2
- server/utils/publicUrl.ts-7
- server/utils/streamUtils.ts-1
- server/validateAccessKeyServerHook.test.ts-1
- server/validateAccessKeyServerHook.ts-1
- server/verifyTokenAndRateLimit.test.ts-1
- server/verifyTokenAndRateLimit.ts+5-14
- server/webSearchService.test.ts-2
- server/webSearchService.ts+1-3
- shared/defaultSystemPrompt.ts+2-3
123456789101112131415168 unmodified lines252627282930313 unmodified lines353637383940411 unmodified line434445464748493 unmodified lines535455565758596061624 unmodified lines676869707172737475767778792 unmodified lines82838485868788899091#!/usr/bin/env node/*** Documentation Link Validator** This script validates that all linked files in documentation exist.* It checks markdown files for internal links and verifies the targets exist.*/const fs = require("node:fs");const path = require("node:path");// Configurationconst defaultDocsDir = path.join(__dirname, "..");// The .yml issue forms are listed so a renamed or deleted template is caught;// they only link out today, so the link check finds nothing in them.8 unmodified lines".github/ISSUE_TEMPLATE/security_vulnerability.yml",];// Regex patterns for finding internal linksconst markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;const htmlLinkRegex = /<a[^>]+href="([^"]+)"[^>]*>/g;3 unmodified linesconst relativePath = path.relative(docsDir, filePath);const issues = [];// Find all markdown linkslet match;while (true) {match = markdownLinkRegex.exec(content);1 unmodified lineconst linkText = match[1];const linkTarget = match[2];// Skip external links, anchors, and email linksif (linkTarget.startsWith("http") ||linkTarget.startsWith("mailto:") ||3 unmodified linescontinue;}// Resolve the target pathconst targetPath = path.resolve(path.dirname(filePath), linkTarget);// Check if target existsif (!fs.existsSync(targetPath)) {issues.push({type: "missing-file",4 unmodified lines}}// Find all HTML linkswhile (true) {match = htmlLinkRegex.exec(content);if (match === null) break;const linkTarget = match[1];// Skip external links and anchorsif (linkTarget.startsWith("http") ||linkTarget.startsWith("mailto:") ||2 unmodified linescontinue;}// Resolve the target pathconst targetPath = path.resolve(path.dirname(filePath), linkTarget);// Check if target existsif (!fs.existsSync(targetPath)) {issues.push({type: "missing-file",123456788 unmodified lines1718192021223 unmodified lines2627282930311 unmodified line3334353637383 unmodified lines42434445464748494 unmodified lines54555657585960616263642 unmodified lines6768697071727374#!/usr/bin/env nodeconst fs = require("node:fs");const path = require("node:path");const defaultDocsDir = path.join(__dirname, "..");// The .yml issue forms are listed so a renamed or deleted template is caught;// they only link out today, so the link check finds nothing in them.8 unmodified lines".github/ISSUE_TEMPLATE/security_vulnerability.yml",];const markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;const htmlLinkRegex = /<a[^>]+href="([^"]+)"[^>]*>/g;3 unmodified linesconst relativePath = path.relative(docsDir, filePath);const issues = [];let match;while (true) {match = markdownLinkRegex.exec(content);1 unmodified lineconst linkText = match[1];const linkTarget = match[2];if (linkTarget.startsWith("http") ||linkTarget.startsWith("mailto:") ||3 unmodified linescontinue;}const targetPath = path.resolve(path.dirname(filePath), linkTarget);if (!fs.existsSync(targetPath)) {issues.push({type: "missing-file",4 unmodified lines}}while (true) {match = htmlLinkRegex.exec(content);if (match === null) break;const linkTarget = match[1];if (linkTarget.startsWith("http") ||linkTarget.startsWith("mailto:") ||2 unmodified linescontinue;}const targetPath = path.resolve(path.dirname(filePath), linkTarget);if (!fs.existsSync(targetPath)) {issues.push({type: "missing-file",
123 unmodified lines124125126127128129130131123 unmodified linesfor (const [dep, range] of Object.entries(pkg.dependencies || {})) {const copy = resolveCopy(dir, dep);if (!copy) {const host = path.dirname(dir); // the node_modules that contains `dir`const target = path.join(host, dep);if (!fs.existsSync(path.join(SCRATCH, dep, "package.json"))) {console.error(`Missing ${dep} required by ${pkg.name}, not in overlay: fail.`,123 unmodified lines124125126127128129130131123 unmodified linesfor (const [dep, range] of Object.entries(pkg.dependencies || {})) {const copy = resolveCopy(dir, dep);if (!copy) {const containingNodeModules = path.dirname(dir);const target = path.join(containingNodeModules, dep);if (!fs.existsSync(path.join(SCRATCH, dep, "package.json"))) {console.error(`Missing ${dep} required by ${pkg.name}, not in overlay: fail.`,
90 unmodified lines9192939495969790 unmodified linesconst SINGLE_TOKEN_BONUS = 0.5;const DERIVED_LABEL_BONUS = 0.75;/** The default for callers that have no words to set aside. */const NO_IGNORED_WORDS: ReadonlySet<string> = new Set();// A label split into the query's words only counts when at least one of those90 unmodified lines91929394959690 unmodified linesconst SINGLE_TOKEN_BONUS = 0.5;const DERIVED_LABEL_BONUS = 0.75;const NO_IGNORED_WORDS: ReadonlySet<string> = new Set();// A label split into the query's words only counts when at least one of those
12345614 unmodified lines212223242526272829/*** Aggregate counters for the requests that reached token verification.** The rate limiter keys on the client IP, so that is the one thing these must* not keep: no address, no token, no query, and no timestamp per request. What* is left says whether the instance is being abused, whether a client is14 unmodified lines} from "./verifyTokenAndRateLimit.ts";/*** Which endpoint family a request was aimed at. `other` is what keeps the* totals closed when a new endpoint starts using the same verification funnel* and nobody extends this list.*/export type AuthorizationSurface =| "search"123414 unmodified lines1920212223242526/*** The rate limiter keys on the client IP, so that is the one thing these must* not keep: no address, no token, no query, and no timestamp per request. What* is left says whether the instance is being abused, whether a client is14 unmodified lines} from "./verifyTokenAndRateLimit.ts";/*** `other` is what keeps the totals closed when a new endpoint starts using the* same verification funnel and nobody extends this list.*/export type AuthorizationSurface =| "search"
44 unmodified lines454647484950515253209 unmodified lines26326426526626726826995 unmodified lines36536636736836937037137237337444 unmodified lines}/*** The per-text path this change replaced: one `session.run()` per text,* `[1, L]` tensors, mean pooling over the tokenizer's own mask. Kept here as* the reference the batched path must match.*/async function encodePerText(refSession: InferenceSession,209 unmodified lines/*** Runs one scoring request against a worker of its own and returns its reply.** The session lives in the worker now, so a `session.run` spy on this thread* would see nothing. The worker reports the dims of each forward pass instead,* which is what the bucketing assertions read.*/95 unmodified lines});/*** The acceptance measurement from #2730. On the main thread the same pass* blocked for ~815 ms (x86_64, 32 logical cores); with the session in the* worker it measures ~1.5 ms. The bar is left at the issue's 20 ms so the* test reports a regression rather than host-to-host noise.*/it("keeps the main-thread event-loop block under 20 ms for a 200-passage pass", async () => {const passages = Array.from({ length: 200 }, (_, i) =>44 unmodified lines4546474849505152209 unmodified lines26226326426526626726895 unmodified lines36436536636736836937037137244 unmodified lines}/*** The per-text reference the batched path must match: one `session.run()` per* text, `[1, L]` tensors, mean pooling over the tokenizer's own mask.*/async function encodePerText(refSession: InferenceSession,209 unmodified lines/*** Runs one scoring request against a worker of its own and returns its reply.** The session lives in the worker, so a `session.run` spy on this thread* would see nothing. The worker reports the dims of each forward pass instead,* which is what the bucketing assertions read.*/95 unmodified lines});/*** On the main thread the same pass blocked for ~815 ms (x86_64, 32 logical* cores); with the session in the worker it measures ~1.5 ms. The bar sits at* 20 ms so the test reports a regression rather than host-to-host noise.*/it("keeps the main-thread event-loop block under 20 ms for a 200-passage pass", async () => {const passages = Array.from({ length: 200 }, (_, i) =>
2 unmodified lines345678910111210 unmodified lines2324252627282995 unmodified lines1251261271281291301311321331342 unmodified lines* inference: it spawns `biEncoderWorker.ts`, forwards scoring requests to it* and matches the replies back to their callers.** The four exported functions keep the signatures they had when the session* lived here, so no caller changed. What changed is that a scoring pass no* longer stops the event loop: a 200-passage pool blocked the main thread for* ~815 ms before and stays under 20 ms now (see docs/page-content.md).*/import path from "node:path";10 unmodified lineslet isReady = false;let nextRequestId = 0;/** Resolvers for requests the worker has not answered yet, keyed by their id. */const pendingScores = new Map<number, (scores: number[]) => void>();/**95 unmodified linesreturn isReady;}/*** Returns dense (semantic) scores for passages given a query.* Falls back to empty array when the worker is not running.*/export async function scorePassages(query: string,passages: string[],2 unmodified lines3456789101110 unmodified lines22232425262795 unmodified lines1231241251261271282 unmodified lines* inference: it spawns `biEncoderWorker.ts`, forwards scoring requests to it* and matches the replies back to their callers.** Inference stays off the main thread because a scoring pass run inline stops* the event loop: a 200-passage pool blocks it for ~815 ms, against under 20 ms* through the worker (see docs/page-content.md).*/import path from "node:path";10 unmodified lineslet isReady = false;let nextRequestId = 0;const pendingScores = new Map<number, (scores: number[]) => void>();/**95 unmodified linesreturn isReady;}export async function scorePassages(query: string,passages: string[],
12345678910111224 unmodified lines37383940414243444525 unmodified lines71727374757677787998 unmodified lines17817918018118218318412 unmodified lines197198199200201202203204205206/*** The bi-encoder's ONNX session, running off the main thread.** `onnxruntime-node` runs inference synchronously on whichever JS thread calls* it, so scoring a 200-passage pool used to stop the server's event loop for* hundreds of milliseconds โ no other request could be served while a single* page-content read was ranking its passages. Here that work blocks only this* thread. The model is loaded here for the same reason: the ~450 MB of weights* must live in the worker's memory, not the main thread's.** Node loads this file directly (type stripping), so keep it to syntax that* erases: no enums, no parameter properties, no namespaces.24 unmodified linesconst MODEL_HF_FILE = "onnx/model.onnx";/*** Maximum tokens per encoding. The model was trained with a 256-token limit;* passages longer than that are truncated from the end, which is where the* passage content sits after the query prefix.*/const MAX_SEQUENCE_LENGTH = 256;25 unmodified lines}/*** Encodes a batch of texts into normalized embedding vectors with one* `session.run()` per length bucket.** Rows are sorted by token length and cut into buckets of at most* `BATCH_ROWS`, so each batch pads to its own near-uniform width instead of* the global max: attention is O(L^2), and padding a mixed-length chunk out98 unmodified lines}}// L2 normalize.let norm = 0;for (let d = 0; d < dim; d++) {norm += pooled[d] * pooled[d];12 unmodified linesreturn { embeddings, runDimensions };}/*** Computes cosine similarity between a query embedding and passage embeddings.* Both are assumed to be L2-normalized, so cosine similarity = dot product.*/function cosineSimilarities(query: Float32Array,passages: Float32Array[],12345678924 unmodified lines34353637383940414225 unmodified lines68697071727398 unmodified lines17217317417517617712 unmodified lines190191192193194195196/*** `onnxruntime-node` runs inference synchronously on whichever JS thread calls* it, and scoring a 200-passage pool takes hundreds of milliseconds, so it runs* on this thread instead of the server's event loop. The model is loaded here* for the same reason: the ~450 MB of weights must live in the worker's memory,* not the main thread's.** Node loads this file directly (type stripping), so keep it to syntax that* erases: no enums, no parameter properties, no namespaces.24 unmodified linesconst MODEL_HF_FILE = "onnx/model.onnx";/*** The model was trained with a 256-token limit; passages longer than that are* truncated from the end, which is where the passage content sits after the* query prefix.*/const MAX_SEQUENCE_LENGTH = 256;25 unmodified lines}/*** Rows are sorted by token length and cut into buckets of at most* `BATCH_ROWS`, so each batch pads to its own near-uniform width instead of* the global max: attention is O(L^2), and padding a mixed-length chunk out98 unmodified lines}}let norm = 0;for (let d = 0; d < dim; d++) {norm += pooled[d] * pooled[d];12 unmodified linesreturn { embeddings, runDimensions };}/** Both are assumed to be L2-normalized, so cosine similarity = dot product. */function cosineSimilarities(query: Float32Array,passages: Float32Array[],
9 unmodified lines1011121314151617181920212223242526272810 unmodified lines3940414243444546479 unmodified lines*//*** Rows per batched forward pass. The old chunk of 64 wrapped one-text-per-call* runs and bought no concurrency; now that a call really carries its rows, B* trades padding waste and cache pressure against per-call setup. B=64 measured* slower than the per-text path; the sweep cannot separate the two plausible* causes โ a 64-row bucket spans a wider length range, so padding waste* grows, and at L=256 with 12 heads the attention score tensor alone is* ~192 MiB live, which pressures cache. B=16 (~48 MiB) measured fastest on* a 200-passage pool on this host (x86_64, 32 cpus): 1.88x wall time and a* 223ms worst event-loop block against 1560ms for the per-text path.*/export const BATCH_ROWS = 16;/** Scoring work sent to the worker. `id` correlates the reply. */export interface BiEncoderRequest {type: "score";id: number;10 unmodified linesscores: number[];/*** The `input_ids` dims of each forward pass this request ran, in run* order. The session no longer lives on the main thread, so this is the* only way a test can assert on the bucketing; it is a few pairs of* numbers per request.*/runDimensions: number[][];}9 unmodified lines10111213141516171819202122232425262710 unmodified lines38394041424344459 unmodified lines*//*** B, the rows per forward pass, trades padding waste and cache pressure against* per-call setup. B=64 measured slower than the per-text path; the sweep* cannot separate the two plausible causes โ a 64-row bucket spans a wider* length range, so padding waste grows, and at L=256 with 12 heads the* attention score tensor alone is ~192 MiB live, which pressures cache. B=16* (~48 MiB) measured fastest on a 200-passage pool on this host (x86_64, 32* cpus): 1.88x wall time and a 223ms worst event-loop block against 1560ms for* the per-text path.*/export const BATCH_ROWS = 16;/** `id` correlates the reply. */export interface BiEncoderRequest {type: "score";id: number;10 unmodified linesscores: number[];/*** The `input_ids` dims of each forward pass this request ran, in run* order. The session lives in the worker, so this is the only way a test* can assert on the bucketing; it is a few pairs of numbers per request.*/runDimensions: number[][];}
8 unmodified lines910111213141516178 unmodified linesimport { getSearchToken } from "./searchToken.ts";/*** Vite server hook that serves runtime server config at /api/config.* Replaces the compile-time VITE_* defines so the published Docker image* is fully configurable via environment variables at runtime.*/export function configEndpointServerHook<T extends ViteDevServer | PreviewServer,8 unmodified lines9101112131415168 unmodified linesimport { getSearchToken } from "./searchToken.ts";/*** Serves the server config at /api/config at runtime rather than compiling it* in, so the published Docker image is configurable via environment variables.*/export function configEndpointServerHook<T extends ViteDevServer | PreviewServer,
26 unmodified lines2728293031323334353626 unmodified lines}/*** Downloads a repository file to `localFilePath`, skipping the transfer when the* cached copy already matches the size the Hub reports. A cached file of the* wrong size is replaced instead of trusted, so a truncated model recovers on* the next startup rather than failing to load forever.*/export async function downloadFileFromHuggingFaceRepository(hfRepo: string,26 unmodified lines27282930313233343526 unmodified lines}/*** A cached file of the wrong size is replaced instead of trusted, so a* truncated model recovers on the next startup rather than failing to load* forever.*/export async function downloadFileFromHuggingFaceRepository(hfRepo: string,
49 unmodified lines50515253545556575846 unmodified lines10510610710810911011111246 unmodified lines1591601611621631641651661671681692 unmodified lines1721731741751761771781791802 unmodified lines183184185186187188189190191192199 unmodified lines39239339439539639739839940040110 unmodified lines4124134144154164174184192 unmodified lines422423424425426427428429430431432433212 unmodified lines64664764864965065165265365465564 unmodified lines72072172272372472572672772872910 unmodified lines74074174274374474574674774849 unmodified linesresults?: ParallelSearchResult[];}// You.com's tool output: the web results sit one level deeper, under// `results.web`, and each result carries a plain description plus, when the// query matched the page, query-relevant highlights.interface YoucomWebResult {url?: string;title?: string | null;46 unmodified lines{name: "youcom",apiKeyVariable: "SEARCH_FALLBACK_YOUCOM_API_KEY",// The free profile needs no key at all, and the key, when present,// selects the authenticated endpoint instead.endpointUrl: (apiKey) =>apiKey? "https://api.you.com/mcp"46 unmodified lines}}/*** Whether the operator opted into the second text-search source. Off unless* `SEARCH_FALLBACK_ENABLED` is `true` or `1`, read at call time so tests can* toggle it.*/export function isSearchFallbackEnabled(): boolean {const value = (process.env.SEARCH_FALLBACK_ENABLED ?? "").trim()2 unmodified lines}/*** Checks the fallback configuration and throws on the first thing wrong with* it: a removed variable that is still set, an unknown provider name, a* provider list with no names in it, or a key with a control character in it.* Meant for server start, so a bad value stops the server instead of failing* every search that reaches the fallback.*/2 unmodified lines}/*** The providers the operator listed in `SEARCH_FALLBACK_PROVIDERS`, or every* built-in provider when it is unset or blank, as a fresh array the caller may* reorder. The listed order carries no meaning, since every call shuffles it.* Read at call time so tests can switch it.*/function readConfiguredProviders(): FallbackProvider[] {const stillSet = REMOVED_VARIABLES.filter(199 unmodified linesconst IMF_FIXDATE =/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/;/*** Reads Retry-After as delta-seconds or an IMF-fixdate HTTP-date, and clamps* the result to the bounds the module allows.*/function rateLimitPauseMs(retryAfter: string | null): number {const value = retryAfter?.trim() ?? "";let pauseMs = DEFAULT_RATE_LIMIT_PAUSE_MS;10 unmodified lines}/*** Throws the error the cascade pauses a provider on. Checked on every request* of the exchange, since any of them can be the one the limit lands on.*/async function rejectIfRateLimited(response: Response): Promise<void> {if (response.status !== 429) return;2 unmodified lines}/*** Runs one provider's MCP exchange: initialize, the initialized notification* when the endpoint opened a session, and the tool call. The session is* optional: with no session id on the initialize reply the endpoint is* stateless, so the notification and the session id are skipped, since there* is no session to acknowledge. The protocol version still goes on every* request after initialize.*/async function searchWithProvider(provider: FallbackProvider,212 unmodified lines};}/*** Maps You.com's `results.web` array by the same rules the Parallel path* follows, so the tuples reach ranking and rendering unchanged.*/function mapYoucomResults(document: YoucomSearchDocument,limit: number,64 unmodified linesreturn buildSnippet(result.contents?.highlights);}/*** Turns the endpoint's markdown excerpts into the plain, single-line snippet* the SearXNG path hands to ranking.*/function buildSnippet(excerpts: string[] | undefined): string {if (!Array.isArray(excerpts) || excerpts.length === 0) return "";10 unmodified lines}/*** Caps a finished snippet at the length the ranking path expects. Cuts at a* word boundary: a mid-word stump reads as a rendering bug, and the ellipsis* is what tells the reader the sentence was cut, not finished.*/function truncateSnippet(snippet: string): string {if (snippet.length <= MAX_SNIPPET_LENGTH) return snippet;49 unmodified lines50515253545546 unmodified lines10210310410510610746 unmodified lines1541551561571581591602 unmodified lines1631641651661671682 unmodified lines171172173174175176177178179199 unmodified lines37938038138238338410 unmodified lines3953963973983994004014022 unmodified lines405406407408409410411412413212 unmodified lines62662762862963063164 unmodified lines69669769869970070110 unmodified lines71271371471571671771871949 unmodified linesresults?: ParallelSearchResult[];}interface YoucomWebResult {url?: string;title?: string | null;46 unmodified lines{name: "youcom",apiKeyVariable: "SEARCH_FALLBACK_YOUCOM_API_KEY",endpointUrl: (apiKey) =>apiKey? "https://api.you.com/mcp"46 unmodified lines}}/** Read at call time so tests can toggle it. */export function isSearchFallbackEnabled(): boolean {const value = (process.env.SEARCH_FALLBACK_ENABLED ?? "").trim()2 unmodified lines}/*** Meant for server start, so a bad value stops the server instead of failing* every search that reaches the fallback.*/2 unmodified lines}/*** Returns a fresh array the caller may reorder. The listed order carries no* meaning, since every call shuffles it. Read at call time so tests can* switch it.*/function readConfiguredProviders(): FallbackProvider[] {const stillSet = REMOVED_VARIABLES.filter(199 unmodified linesconst IMF_FIXDATE =/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/;function rateLimitPauseMs(retryAfter: string | null): number {const value = retryAfter?.trim() ?? "";let pauseMs = DEFAULT_RATE_LIMIT_PAUSE_MS;10 unmodified lines}/*** Checked on every request of the exchange, since any of them can be the one* the limit lands on.*/async function rejectIfRateLimited(response: Response): Promise<void> {if (response.status !== 429) return;2 unmodified lines}/*** The session is optional: with no session id on the initialize reply the* endpoint is stateless, so the initialized notification and the session id* are skipped, since there is no session to acknowledge.*/async function searchWithProvider(provider: FallbackProvider,212 unmodified lines};}function mapYoucomResults(document: YoucomSearchDocument,limit: number,64 unmodified linesreturn buildSnippet(result.contents?.highlights);}function buildSnippet(excerpts: string[] | undefined): string {if (!Array.isArray(excerpts) || excerpts.length === 0) return "";10 unmodified lines}/*** Cuts at a word boundary: a mid-word stump reads as a rendering bug, and the* ellipsis is what tells the reader the sentence was cut, not finished.*/function truncateSnippet(snippet: string): string {if (snippet.length <= MAX_SNIPPET_LENGTH) return snippet;
12345679 unmodified lines8687888990919212 unmodified lines105106107108109110111112/*** Aggregate counters for the AI answers served through `/inference`.** Counts and durations only. The obvious thing to record about an inference is* the conversation, and that is the whole of what the user typed, so none of it* is kept: no prompt, no message, no answer, no token, and no timestamp per79 unmodified linescountsFor(model).abandoned++;}/** A retry moved to another model, which is the only reason the pool exists. */export function recordModelFallback(): void {modelFallbacks++;}12 unmodified lines}/*** Records one finished request. `firstTokenMs` is the wait the user actually* felt, so it is kept apart from `durationMs`, which covers the whole answer.*/export function recordInference({outcome,123479 unmodified lines84858687888912 unmodified lines102103104105106107108109/*** Counts and durations only. The obvious thing to record about an inference is* the conversation, and that is the whole of what the user typed, so none of it* is kept: no prompt, no message, no answer, no token, and no timestamp per79 unmodified linescountsFor(model).abandoned++;}export function recordModelFallback(): void {modelFallbacks++;}12 unmodified lines}/*** `firstTokenMs` is the wait the user actually felt, so it is kept apart from* `durationMs`, which covers the whole answer.*/export function recordInference({outcome,
500 unmodified lines50150250350450550650752 unmodified lines56056156256356456556656756856934 unmodified lines604605606607608609610295 unmodified lines90690790890991091191291326 unmodified lines94094194294394494594639 unmodified lines9869879889899909919923 unmodified lines99699799899910001001100224 unmodified lines102710281029103010311032103310341035103610371038500 unmodified linesreturn {stream: (async function* () {yield { type: "text-delta", text: "Half" } as never;// Wait until the abort signal fires, then emit the abort part.await new Promise<void>((resolve) => {const check = () => {if (abortSignal?.aborted) {52 unmodified lines.mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");// First call (model-a) stalls; second call (model-b) succeeds.vi.mocked(streamText).mockImplementationOnce(({ abortSignal }: { abortSignal?: AbortSignal } = {}) => {// Yields nothing, then emits an abort part when the signal fires.return {stream: (async function* () {await new Promise<void>((resolve) => {34 unmodified linesawait vi.runAllTimersAsync();await pending;// The ladder walked to model-b, which succeeded.expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0] as string);expect(writes.some((s: string) => s.includes("Recovered"))).toBe(true);295 unmodified linesit("re-lists the model pool when every model has been attempted", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);// Only model-a in the initial pool; it fails, then the pool is refreshed// to include model-b, which succeeds.vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockResolvedValueOnce([{ id: "model-b" }]);26 unmodified linesawait vi.runAllTimersAsync();await pending;// The pool was refreshed once, and the new model succeeded.expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0]).join("");39 unmodified linesawait vi.runAllTimersAsync();await pending;// model-b is still in the pool, so no re-list is needed.expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(1);expect(streamText).toHaveBeenCalledTimes(2);} finally {3 unmodified linesit("re-lists only once even when both the original and refetched pools fail", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);// Only model-a in the initial pool; refetch yields model-b, which also fails.vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockResolvedValueOnce([{ id: "model-b" }]);24 unmodified lines// The pool was refreshed once; even though both models failed we do not// loop on a failing /models endpoint.expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);// The refetched pool feeds selection โ the second call receives it.expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([{ id: "model-b" },]);expect(response.statusCode).toBe(503);// The counter moved from the successful refetch.expect(getInferenceStats().modelsRefetched).toBe(before.modelsRefetched + 1,);500 unmodified lines50150250350450550652 unmodified lines55956056156256356456556634 unmodified lines601602603604605606295 unmodified lines90290390490590690726 unmodified lines93493593693793893939 unmodified lines9799809819829839843 unmodified lines98898999099199299324 unmodified lines1018101910201021102210231024102510261027500 unmodified linesreturn {stream: (async function* () {yield { type: "text-delta", text: "Half" } as never;await new Promise<void>((resolve) => {const check = () => {if (abortSignal?.aborted) {52 unmodified lines.mockReturnValueOnce("model-a").mockReturnValueOnce("model-b");vi.mocked(streamText).mockImplementationOnce(({ abortSignal }: { abortSignal?: AbortSignal } = {}) => {return {stream: (async function* () {await new Promise<void>((resolve) => {34 unmodified linesawait vi.runAllTimersAsync();await pending;expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0] as string);expect(writes.some((s: string) => s.includes("Recovered"))).toBe(true);295 unmodified linesit("re-lists the model pool when every model has been attempted", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockResolvedValueOnce([{ id: "model-b" }]);26 unmodified linesawait vi.runAllTimersAsync();await pending;expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);expect(streamText).toHaveBeenCalledTimes(2);const writes = response.write.mock.calls.map((c) => c[0]).join("");39 unmodified linesawait vi.runAllTimersAsync();await pending;expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(1);expect(streamText).toHaveBeenCalledTimes(2);} finally {3 unmodified linesit("re-lists only once even when both the original and refetched pools fail", async () => {vi.stubEnv("INTERNAL_OPENAI_COMPATIBLE_API_MODEL", undefined);vi.mocked(listOpenAiCompatibleModels).mockResolvedValueOnce([{ id: "model-a" }]).mockResolvedValueOnce([{ id: "model-b" }]);24 unmodified lines// The pool was refreshed once; even though both models failed we do not// loop on a failing /models endpoint.expect(listOpenAiCompatibleModels).toHaveBeenCalledTimes(2);expect(vi.mocked(selectRandomModel).mock.calls[1][0]).toEqual([{ id: "model-b" },]);expect(response.statusCode).toBe(503);expect(getInferenceStats().modelsRefetched).toBe(before.modelsRefetched + 1,);
253 unmodified lines254255256257258259260261262136 unmodified lines399400401402403404405406407408253 unmodified lineslet model = process.env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL;let availableModels: { id: string }[] = [];const attemptedModels = new Set<string>();// Tracks whether a mid-request model-list re-fetch has already run.// Set before the try so a failing `/models` endpoint does not trigger// another refetch on the next failed attempt โ we already gave it a shot.let hasRefetched = false;if (!model) {136 unmodified linesif (hasEmittedContent) break;if (attempt >= maxAttempts) break;// Re-list when every model in the current pool has been attempted// and we have not already re-listed this request. A provider whose// pool changes mid-flight needs a fresh listing to recover; without// the `!hasRefetched` guard we would loop on a stale list.if (!process.env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL &&availableModels.every((m) => attemptedModels.has(m.id)) &&253 unmodified lines254255256257258259260261136 unmodified lines398399400401402403404405406253 unmodified lineslet model = process.env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL;let availableModels: { id: string }[] = [];const attemptedModels = new Set<string>();// Set before the try so a failing `/models` endpoint does not trigger// another refetch on the next failed attempt.let hasRefetched = false;if (!model) {136 unmodified linesif (hasEmittedContent) break;if (attempt >= maxAttempts) break;// A provider whose pool changes mid-flight needs a fresh listing to// recover; without the `!hasRefetched` guard we would loop on a// stale list.if (!process.env.INTERNAL_OPENAI_COMPATIBLE_API_MODEL &&availableModels.every((m) => attemptedModels.has(m.id)) &&
52 unmodified lines5354555657585960616263646566676852 unmodified lines]);export interface OfficialLaneRequest {/** The registrable domain the query named, as the second query scopes it. */domain: string;/** The scoped query sent to the search engines. */query: string;}/*** The second query this search warrants, or null when it warrants none. The* domain is taken from the results (`namedDomain`), so this only fires when the* official site already appeared somewhere in the set.*/export function officialLaneRequest(query: string,52 unmodified lines5354555657585960616263646552 unmodified lines]);export interface OfficialLaneRequest {domain: string;query: string;}/*** The domain is taken from the results (`namedDomain`), so this only fires when* the official site already appeared somewhere in the set.*/export function officialLaneRequest(query: string,
401 unmodified lines40240340440540640740840934 unmodified lines4444454464474484494505 unmodified lines456457458459460461462124 unmodified lines58758858959059159259359459559659759884 unmodified lines68368468568668768868938 unmodified lines7287297307317327337347357367377387397 unmodified lines74774874975075175275341 unmodified lines7957967977987998008018025 unmodified lines808809810811812813814401 unmodified lines});it("breaks a long block at sentence boundaries in any script", () => {// A regular expression over `[.!?]` finds no boundary here, so the block// used to be cut at an arbitrary character in the middle of a sentence.const passages = splitIntoPassages("็ซๆฏๅคฉ็กๅไบๅฐๅๅ ญไธชๅฐๆถ๏ผๅนด้ฟ็็ซ็กๅพๆดไน ใ".repeat(80),);34 unmodified linesfor (const passage of passages) {expect(passage.length).toBeLessThanOrEqual(1200);}// The overlap: the second piece starts with the tail of the first.const overlap = passages[0].slice(-long.length).trim();expect(passages[1].startsWith(overlap)).toBe(true);});5 unmodified linesfor (const passage of passages) {expect(passage.length).toBeLessThanOrEqual(1200);}// The overlap is a fixed tail, not a sentence.const overlap = passages[0].slice(-200);expect(passages[1].startsWith(overlap)).toBe(true);});124 unmodified lines});/*** The picker used to score by splitting on `[^\p{L}\p{N}]+`, which finds no* boundary in scripts that write none and shredded the ones that write words* with combining marks. Every query below then matched nothing, scoring fell* through to document order, and the boilerplate placed first won. Each case* puts the off-topic passage first and allows a budget that fits exactly one,* so document order and relevance cannot both be right.*/describe("selectPassages across scripts", () => {const cases = [84 unmodified linesdescribe.each(["lexical", "dense"])("selectPassagesAcrossPages (%s)",(mode) => {// Helper to call the internal selector indirectly through fetchPageContents.async function selectFrom(urls: string[], htmls: string[]) {if (mode === "dense") {scorePassagesMock.mockImplementation(async (_query, pool: string[]) =>38 unmodified linesit("drops a page whose passages are all near-duplicates of an earlier page", async () => {// Page A has one passage. Page B has one near-duplicate passage// (Jaccard >= 0.9). The new global dedup should suppress B's copy,// leaving B with no selected passages so it vanishes from the response.// The old per-page code would have returned both pages.// Note: with a query that matches no terms, A wins purely on flatten// order (lower global index), not on relevance. The test guards the// dedup drop path, not the ranking order.const base ="word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 ";const passageA = base.repeat(15);7 unmodified lines],);// Only page A should survive; page B's sole passage is a near-duplicate.expect(contents).toHaveLength(1);expect(contents[0].url).toContain("/a");});41 unmodified lineshttpOtherError: 1,});// A PDF is no longer dropped as notADocument; it goes through the passage// pipeline and is counted as read (or tooLittleText if the text is short).pdfGetTextMock.mockResolvedValue({text: "CAT SLEEPS 16 HOURS A DAY. ".repeat(20),});5 unmodified lines);const pdfOutcome = await countOutcomes("https://example.com/a.pdf");expect(pdfOutcome.read).toBe(1);// The notADocument case is still covered by a non-document type.fetchMock.mockResolvedValue(new Response("binary goo", {status: 200,401 unmodified lines40240340440540640740840934 unmodified lines4444454464474484495 unmodified lines455456457458459460124 unmodified lines58558658758858959059159259359459559684 unmodified lines68168268368468568638 unmodified lines7257267277287297307317327337347357 unmodified lines74374474574674774841 unmodified lines7907917927937947957967975 unmodified lines803804805806807808401 unmodified lines});it("breaks a long block at sentence boundaries in any script", () => {// A regular expression over `[.!?]` finds no boundary here, so it would// cut the block at an arbitrary character in the middle of a sentence.const passages = splitIntoPassages("็ซๆฏๅคฉ็กๅไบๅฐๅๅ ญไธชๅฐๆถ๏ผๅนด้ฟ็็ซ็กๅพๆดไน ใ".repeat(80),);34 unmodified linesfor (const passage of passages) {expect(passage.length).toBeLessThanOrEqual(1200);}const overlap = passages[0].slice(-long.length).trim();expect(passages[1].startsWith(overlap)).toBe(true);});5 unmodified linesfor (const passage of passages) {expect(passage.length).toBeLessThanOrEqual(1200);}const overlap = passages[0].slice(-200);expect(passages[1].startsWith(overlap)).toBe(true);});124 unmodified lines});/*** Splitting on `[^\p{L}\p{N}]+` finds no boundary in scripts that write none* and shreds the ones that write words with combining marks: every query below* would match nothing, scoring would fall through to document order, and the* boilerplate placed first would win. Each case puts the off-topic passage* first and allows a budget that fits exactly one, so document order and* relevance cannot both be right.*/describe("selectPassages across scripts", () => {const cases = [84 unmodified linesdescribe.each(["lexical", "dense"])("selectPassagesAcrossPages (%s)",(mode) => {async function selectFrom(urls: string[], htmls: string[]) {if (mode === "dense") {scorePassagesMock.mockImplementation(async (_query, pool: string[]) =>38 unmodified linesit("drops a page whose passages are all near-duplicates of an earlier page", async () => {// Page A has one passage. Page B has one near-duplicate passage// (Jaccard >= 0.9). The global dedup suppresses B's copy, leaving B with// no selected passages so it vanishes from the response.// With a query that matches no terms, A wins purely on flatten order// (lower global index), not on relevance. The test guards the dedup drop// path, not the ranking order.const base ="word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 ";const passageA = base.repeat(15);7 unmodified lines],);expect(contents).toHaveLength(1);expect(contents[0].url).toContain("/a");});41 unmodified lineshttpOtherError: 1,});// A PDF goes through the passage pipeline and is counted as read (or// tooLittleText if the text is short), not as notADocument.pdfGetTextMock.mockResolvedValue({text: "CAT SLEEPS 16 HOURS A DAY. ".repeat(20),});5 unmodified lines);const pdfOutcome = await countOutcomes("https://example.com/a.pdf");expect(pdfOutcome.read).toBe(1);fetchMock.mockResolvedValue(new Response("binary goo", {status: 200,
364 unmodified lines36536636736836937037137237337437537625 unmodified lines402403404405406407408112 unmodified lines521522523524525526527375 unmodified lines903904905906907908909910911912140 unmodified lines1053105410551056105710581059106010616 unmodified lines1068106910701071107210731074107510761077107848 unmodified lines11271128112911301131113211331134114 unmodified lines1249125012511252125312541255364 unmodified lines/*** Word and sentence boundaries come from ICU rather than from an expression* over character classes. `[^\p{L}\p{N}]+` cut Brahmic scripts and Thai at* every combining vowel mark and discarded the marks, turning a Hindi query* into one meaningless fragment, and no expression can find a boundary in* Chinese, Japanese or Thai, which write none: a whole sentence arrived as a* single token that matched nothing. Both segmenters are script-driven, so the* locale is left unset and the result is the same on every host.*/const wordSegmenter = new Intl.Segmenter(undefined, { granularity: "word" });const sentenceSegmenter = new Intl.Segmenter(undefined, {25 unmodified linesconst MIN_PREFIX_MATCH_CHARS = 3;const MAX_INFLECTION_CHARS = 3;/** Extracted text for a single page, keyed by the URL it was read from. */export interface PageContent {url: string;content: string;112 unmodified linesconst contentType = response.headers.get("content-type") ?? "";if (!READABLE_CONTENT_TYPES.test(contentType.trim())) {// PDF is not in READABLE_CONTENT_TYPES but we still want to read it.if (!contentType.trim().toLowerCase().startsWith("application/pdf")) {await response.body?.cancel().catch(() => {});return { outcome: "notADocument" };375 unmodified lines* the current pool, and returns how much weight each passage matched along* with the total available.** This is what replaced a stop-word list, which could only ever cover the one* language it was written in: a term found in most passages of a pool cannot* say which passage to quote, and a term confined to a few of them can, and* that holds whatever language the pool is in.*/function weighTerms(queryTerms: string[],140 unmodified linesmaxCharsPerUrl: number,): Map<string, string[]> {const selectedByUrl = new Map<string, string[]>();// Track every selected passage's tokens for cross-URL dedup.// Passages from the same page are allowed to coexist; dedup is only for// syndicated paragraphs that appear on different pages.const selectedTokens: { url: string; tokens: Set<string> }[] = [];let usedChars = 0;const usedPerUrl = new Map<string, number>();6 unmodified lines)continue;// Check against all selected passages from other URLs.// Size prefilter: Jaccard โฅ 0.9 requires sizes within 10ร, so skip// comparisons where the ratio is too small.let isDuplicate = false;for (const { url: otherUrl, tokens: otherTokens } of selectedTokens) {if (otherUrl === passage.url) continue;const minSize = Math.min(passage.tokens.size, otherTokens.size);const maxSize = Math.max(passage.tokens.size, otherTokens.size);48 unmodified linespassages: string[],maxChars: number,): Promise<string[]> {// Single-page wrapper over the production selector so tests exercise the// real code path.const input = passages.map((text, index) => ({url: "",text,114 unmodified linesMAX_PAGE_CHARS,);// Record page-read stats now that we know how many passages were kept.for (const page of pages) {const selected = selectedByUrl.get(page.url) ?? [];recordPageRead({364 unmodified lines36536636736836937037137237337437525 unmodified lines401402403404405406112 unmodified lines519520521522523524375 unmodified lines900901902903904905906907908909140 unmodified lines1050105110521053105410556 unmodified lines10621063106410651066106710681069107010711072107348 unmodified lines112211231124112511261127114 unmodified lines124212431244124512461247364 unmodified lines/*** Word and sentence boundaries come from ICU rather than from an expression* over character classes. `[^\p{L}\p{N}]+` cuts Brahmic scripts and Thai at* every combining vowel mark and discards the marks, and no expression can find* a boundary in Chinese, Japanese or Thai, which write none. Both segmenters* are script-driven, so the locale is left unset and the result is the same on* every host.*/const wordSegmenter = new Intl.Segmenter(undefined, { granularity: "word" });const sentenceSegmenter = new Intl.Segmenter(undefined, {25 unmodified linesconst MIN_PREFIX_MATCH_CHARS = 3;const MAX_INFLECTION_CHARS = 3;export interface PageContent {url: string;content: string;112 unmodified linesconst contentType = response.headers.get("content-type") ?? "";if (!READABLE_CONTENT_TYPES.test(contentType.trim())) {if (!contentType.trim().toLowerCase().startsWith("application/pdf")) {await response.body?.cancel().catch(() => {});return { outcome: "notADocument" };375 unmodified lines* the current pool, and returns how much weight each passage matched along* with the total available.** A stop-word list could only cover the one language it was written in: a term* found in most passages of a pool cannot say which passage to quote, and a* term confined to a few of them can, and that holds whatever language the* pool is in.*/function weighTerms(queryTerms: string[],140 unmodified linesmaxCharsPerUrl: number,): Map<string, string[]> {const selectedByUrl = new Map<string, string[]>();const selectedTokens: { url: string; tokens: Set<string> }[] = [];let usedChars = 0;const usedPerUrl = new Map<string, number>();6 unmodified lines)continue;// Jaccard โฅ 0.9 requires the smaller set to be at least 90% of the larger,// so skip comparisons where the size ratio is too small.let isDuplicate = false;for (const { url: otherUrl, tokens: otherTokens } of selectedTokens) {// Dedup targets syndicated paragraphs across pages; one page's own// passages may coexist.if (otherUrl === passage.url) continue;const minSize = Math.min(passage.tokens.size, otherTokens.size);const maxSize = Math.max(passage.tokens.size, otherTokens.size);48 unmodified linespassages: string[],maxChars: number,): Promise<string[]> {const input = passages.map((text, index) => ({url: "",text,114 unmodified linesMAX_PAGE_CHARS,);for (const page of pages) {const selected = selectedByUrl.get(page.url) ?? [];recordPageRead({
49 unmodified lines50515253545556576 unmodified lines6465666768697049 unmodified lines}/*** Whether a read from `host` may go ahead now. Every admitted read must be* settled, or a half-open host keeps waiting for a probe that never ends.*/admit(host: string): boolean {if (!this.circuits.allows(host)) return false;6 unmodified linesreturn true;}/** Records how an admitted read from `host` ended. */settle(host: string, outcome: string): void {this.probing.delete(host);49 unmodified lines50515253545556576 unmodified lines64656667686949 unmodified lines}/*** Every admitted read must be settled, or a half-open host keeps waiting for* a probe that never ends.*/admit(host: string): boolean {if (!this.circuits.allows(host)) return false;6 unmodified linesreturn true;}settle(host: string, outcome: string): void {this.probing.delete(host);
79 unmodified lines8081828384858688 unmodified lines17517617717817918018179 unmodified lines["B", "b", "https://b.com"],["C", "c", "https://c.com"],]);// Results are sorted by score descending (B has higher score than A, C is dropped by score filter)expect(result[0][0]).toBe("B");});88 unmodified lines[longTitle, "short", "https://a.com"],]);const docs = mockRerank.mock.calls[0][1] as string[];// Truncation is now token-based inside the reranker, so the full document// reaches it; nothing is cut by character count upstream.expect(docs[0]).toBe(`${longTitle}\nshort`);expect(docs[0].length).toBeGreaterThan(512);79 unmodified lines80818283848588 unmodified lines17417517617717817918079 unmodified lines["B", "b", "https://b.com"],["C", "c", "https://c.com"],]);expect(result[0][0]).toBe("B");});88 unmodified lines[longTitle, "short", "https://a.com"],]);const docs = mockRerank.mock.calls[0][1] as string[];// Truncation is token-based inside the reranker, so the full document// reaches it; nothing is cut by character count upstream.expect(docs[0]).toBe(`${longTitle}\nshort`);expect(docs[0].length).toBeGreaterThan(512);
3 unmodified lines45678910113 unmodified lines* A process verifies against one search token for its whole life, so a token* that failed once cannot become valid again in this process: the lookup is* exact rather than a heuristic. A replay of a dead token then costs a Set* check instead of a full argon2id verification, which is what a stream of* dead search URLs from earlier deployments used to pay.*/const rejectedTokens = new Set<string>();3 unmodified lines45678910113 unmodified lines* A process verifies against one search token for its whole life, so a token* that failed once cannot become valid again in this process: the lookup is* exact rather than a heuristic. A replay of a dead token then costs a Set* check instead of a full argon2id verification, which a stream of dead search* URLs from earlier deployments would otherwise pay.*/const rejectedTokens = new Set<string>();
27 unmodified lines282930313233343536373839405 unmodified lines46474849505152535455562 unmodified lines5960616263646566676816 unmodified lines85868788899091921 unmodified line94959697989910010110210310427 unmodified linesconst VNNI_MODEL_HF_FILE = "onnx/model_qint8_avx512_vnni.onnx";/*** Parses the CPU feature flags out of `/proc/cpuinfo` content. Every online* processor gets its own `flags` line, and the lines are not always identical:* on an Intel hybrid CPU the E-cores lack instructions the P-cores have, so a* feature counts only when every line reports it. The intersection is the set* the scheduler cannot dodge. Returns null when no flags line is there, which* is the signal to keep the portable build rather than a guess at the* instruction set.*/export function parseCpuFlags(cpuinfo: string): string[] | null {const lines = [...cpuinfo.matchAll(/^flags[ \t]*:[ \t]*(.*)$/gm)];5 unmodified lines);}/*** Reads the CPU feature flags from `/proc/cpuinfo`. Returns null when the file* is not there or unreadable, which is the signal to keep the portable build* rather than a guess at the instruction set.*/function readCpuFlags(): string[] | null {try {return parseCpuFlags(fs.readFileSync("/proc/cpuinfo", "utf8"));2 unmodified lines}}/*** Picks the quantized build for this CPU: the VNNI build on a Linux x64 host* that reports `avx512_vnni`, the portable build everywhere else.*/export function selectModelFile(platform: string,arch: string,16 unmodified lines* Hard ceiling rather than a tuning knob: the model has 514 learned position* embeddings, two of which XLM-RoBERTa reserves, so a 513-token pair fails* outright with `indices element out of data bounds` at the position-embedding* gather. Still more generous than what shipped before #2260, which cut* documents to 512 characters upstream.*/const MAX_SEQUENCE_LENGTH = 512;1 unmodified linelet session: InferenceSession | null = null;let tokenizer: Tokenizer | null = null;/*** Sanitizes Unicode surrogate pairs in input string* @param input - String to sanitize* @returns Sanitized string with valid Unicode surrogates*/export function sanitizeUnicodeSurrogates(input: string) {let output = "";27 unmodified lines2829303132333435363738395 unmodified lines4546474849502 unmodified lines53545556575816 unmodified lines757677787980811 unmodified line83848586878827 unmodified linesconst VNNI_MODEL_HF_FILE = "onnx/model_qint8_avx512_vnni.onnx";/*** Every online processor gets its own `flags` line, and the lines are not* always identical: on an Intel hybrid CPU the E-cores lack instructions the* P-cores have, so a feature counts only when every line reports it. The* intersection is the set the scheduler cannot dodge. Returns null when no* flags line is there, which is the signal to keep the portable build rather* than a guess at the instruction set.*/export function parseCpuFlags(cpuinfo: string): string[] | null {const lines = [...cpuinfo.matchAll(/^flags[ \t]*:[ \t]*(.*)$/gm)];5 unmodified lines);}function readCpuFlags(): string[] | null {try {return parseCpuFlags(fs.readFileSync("/proc/cpuinfo", "utf8"));2 unmodified lines}}export function selectModelFile(platform: string,arch: string,16 unmodified lines* Hard ceiling rather than a tuning knob: the model has 514 learned position* embeddings, two of which XLM-RoBERTa reserves, so a 513-token pair fails* outright with `indices element out of data bounds` at the position-embedding* gather.*/const MAX_SEQUENCE_LENGTH = 512;1 unmodified linelet session: InferenceSession | null = null;let tokenizer: Tokenizer | null = null;export function sanitizeUnicodeSurrogates(input: string) {let output = "";
12345678910/*** Aggregate counters for the reranking stage.** The reranker sees the query and every snippet, and none of that is kept: how* many results came in, how many survived the score filter, how long the model* took, and how often it was unavailable. Those are the numbers the filter's* two thresholds should be moved against, and today they have none.*/import type { SearchType } from "./searchesSinceLastRestart.ts";12345678/*** The reranker sees the query and every snippet, and none of that is kept: how* many results came in, how many survived the score filter, how long the model* took, and how often it was unavailable. Those are the numbers the filter's* two thresholds should be moved against.*/import type { SearchType } from "./searchesSinceLastRestart.ts";
38 unmodified lines39404142434445464738 unmodified linesdescribe("searchToken", () => {it("should generate a fresh token instead of adopting one already in the file", async () => {// The published image used to ship a token in the temp directory, and a// container that read it shared one token with every other container built// from that image, and with anyone who pulled the image and read the layer.mockExistsSync.mockReturnValue(true);mockReadFileSync.mockReturnValue("token-baked-into-the-image");38 unmodified lines39404142434445464738 unmodified linesdescribe("searchToken", () => {it("should generate a fresh token instead of adopting one already in the file", async () => {// A token baked into the image's temp directory would be shared by every// container built from that image, and by anyone who pulled the image and// read the layer.mockExistsSync.mockReturnValue(true);mockReadFileSync.mockReturnValue("token-baked-into-the-image");
15 unmodified lines161718192021222324252627282930313233343515 unmodified lineslet tokenFileWritten = false;/*** The search token this process verifies against, generated on first use and* written with 0600 permissions.** Never adopted from the file. A token that survives into a published image is* one every container of that build shares, and anyone who pulls the image can* read it out of the layer, so the file is a record for the operator and for* `hasSearchTokenFileChanged`, not a source of truth.** Held for the life of the process. Reading the file on every request let* anything that rewrote it re-key a running server: the clients holding the* previous token were rejected from that moment on, and so was every new page* load, because the token being handed out had been captured when the server* started. A server that keeps its own token instead can still verify the* clients it handed that token to.*/export function getSearchToken() {if (processToken !== null) return processToken;15 unmodified lines161718192021222324252627282915 unmodified lineslet tokenFileWritten = false;/*** Never adopted from the file. A token that survives into a published image is* one every container of that build shares, and anyone who pulls the image can* read it out of the layer, so the file is a record for the operator and for* `hasSearchTokenFileChanged`, not a source of truth.** Held for the life of the process: reading the file on every request would let* anything that can rewrite it re-key a running server, and every open page,* which caches the token from `/api/config`, would fail its next search.*/export function getSearchToken() {if (processToken !== null) return processToken;
20 unmodified lines21222324252627282925 unmodified lines5556575859606162636442 unmodified lines10710810911011111211314 unmodified lines1281291301311321331343 unmodified lines13813914014114214314420 unmodified linesgraphicalSearchesSinceLastRestart++;}// The three counters below stand in for the per-search log lines that used to// carry the query text: how often each case happens is what anyone acts on, and// that survives without recording what was searched for.let searchesWithoutResultsSinceLastRestart = 0;let searchesWithUnresponsiveEnginesSinceLastRestart = 0;25 unmodified lines// The fallback is only consulted after SearXNG has already failed, so these two// say whether the second source pulls its weight: served is a search the caller// got anyway, failed is one that ended as the 502 there was before it existed,// including a search whose SearXNG retries left the deadline too little time to// ask the fallback at all. A search with the fallback off, or an image search,// lands in neither.let searchesServedByFallback = 0;let searchesFailedOnFallback = 0;42 unmodified lines};}/** One engine SearXNG reported as unresponsive, with the reason it gave. */export interface UnresponsiveEngine {engine: string;reason: string;14 unmodified lines*/export type EngineFailure = "blocked" | "timeout" | "other";/** Which engines failed, how often, and what the last failure was. */const unresponsiveEngines = new Map<string,{ failures: number; lastFailure: EngineFailure }3 unmodified lines* The search types whose last search was lost to unresponsive engines. Keyed by* type because text and image searches go out to different engine pools: with* one shared flag, the image search the client fires after a failed text search* cleared the degradation the text engines were still in.*/const searchTypesFailingOnEngines = new Set<SearchType>();20 unmodified lines21222324252627282925 unmodified lines55565758596061626342 unmodified lines10610710810911011114 unmodified lines1261271281291301313 unmodified lines13513613713813914014120 unmodified linesgraphicalSearchesSinceLastRestart++;}// The three counters below stand in for per-search log lines, which would carry// the query text: how often each case happens is what anyone acts on, and that// survives without recording what was searched for.let searchesWithoutResultsSinceLastRestart = 0;let searchesWithUnresponsiveEnginesSinceLastRestart = 0;25 unmodified lines// The fallback is only consulted after SearXNG has already failed, so these two// say whether the second source pulls its weight: served is a search the caller// got anyway, failed is one that still ended as a 502, including a search whose// SearXNG retries left the deadline too little time to ask the fallback at all.// A search with the fallback off, or an image search, lands in neither.let searchesServedByFallback = 0;let searchesFailedOnFallback = 0;42 unmodified lines};}export interface UnresponsiveEngine {engine: string;reason: string;14 unmodified lines*/export type EngineFailure = "blocked" | "timeout" | "other";const unresponsiveEngines = new Map<string,{ failures: number; lastFailure: EngineFailure }3 unmodified lines* The search types whose last search was lost to unresponsive engines. Keyed by* type because text and image searches go out to different engine pools: with* one shared flag, the image search the client fires after a failed text search* would clear the degradation the text engines are still in.*/const searchTypesFailingOnEngines = new Set<SearchType>();
61 unmodified lines62636465666768697061 unmodified linesit("publishes the web search verdict and the per-engine tally", async () => {const status = await callStatus();// Passed through rather than recomputed: the hook used to derive this// field itself from a liveness probe, which reported an open circuit as// healthy.expect(status.webSearchServiceStatus).toBe("degraded");expect(status.searches).toMatchObject({degradedSearchTypes: [],61 unmodified lines626364656667686961 unmodified linesit("publishes the web search verdict and the per-engine tally", async () => {const status = await callStatus();// Passed through rather than recomputed: a liveness probe reports an open// circuit as healthy.expect(status.webSearchServiceStatus).toBe("degraded");expect(status.searches).toMatchObject({degradedSearchTypes: [],
579 unmodified lines580581582583584585586579 unmodified lines// load.await load(firstUrl);expect(fetched(firstUrl)).toBe(1);// secondUrl (least recently used) was evicted and fetches again.await load(secondUrl);expect(fetched(secondUrl)).toBe(2);});579 unmodified lines580581582583584585579 unmodified lines// load.await load(firstUrl);expect(fetched(firstUrl)).toBe(1);await load(secondUrl);expect(fetched(secondUrl)).toBe(2);});
14 unmodified lines151617181920212222 unmodified lines45464748495051525354555657585960616263646 unmodified lines717273747576777814 unmodified linesimport { thumbnailRateLimiter } from "./verifyTokenAndRateLimit.ts";/*** Security review for issue #2524 (audited 2026-09-17). What each item of* the audit checklist maps to:** - Private ranges (10/8, 172.16/12, 192.168/16), link-local including* the cloud metadata address 169.254.169.254, loopback (127/8, ::1),22 unmodified lines* plus the shared token gate bound the total, and a global cap would let* one caller's grid starve every other user's tiles.** Residual risk after this change: the endpoint still fetches arbitrary* public URLs, so a caller can use it to GET any public host โ bounded by* the rate limiter, the size cap and the timeout, and useful only for* raster images. The pinned address is the one DNS gave at vetting time; a* host whose DNS later repoints stays unreachable here until its records* are re-checked, which is the pin working, not failing. Content itself is* untrusted: served same-origin, it carries `nosniff` and a sandbox CSP,* and only raster types pass the allowlist, so no script-carrying format* reaches a browser. `/page-content` has not adopted the pin yet and still* carries the old rebinding residual (see `resolvePublicUrl`'s docstring).*//*** Off the critical path: the search response no longer waits on a thumbnail,* so the budget is set against how long a user tolerates a placeholder tile,* not against the whole grid. It bounds the redirect hops too, DNS included.*/6 unmodified lines/*** Raster types only, by name: the response is served same-origin, and an SVG* loaded by direct navigation is a document whose scripts would run on this* origin. A data URL in an `<img>` (what the old search path produced) stays* inert; this endpoint must not open that door.*/const ACCEPTED_CONTENT_TYPES = ["image/avif",14 unmodified lines1516171819202122 unmodified lines44454647484950515253545556575859606162636 unmodified lines7071727374757614 unmodified linesimport { thumbnailRateLimiter } from "./verifyTokenAndRateLimit.ts";/*** Where each SSRF defense of this endpoint lives:** - Private ranges (10/8, 172.16/12, 192.168/16), link-local including* the cloud metadata address 169.254.169.254, loopback (127/8, ::1),22 unmodified lines* plus the shared token gate bound the total, and a global cap would let* one caller's grid starve every other user's tiles.** Residual risk: the endpoint fetches arbitrary public URLs, so a caller can* use it to GET any public host โ bounded by the rate limiter, the size cap* and the timeout, and useful only for raster images. The pinned address is* the one DNS gave at vetting time; a host whose DNS later repoints stays* unreachable here until its records are re-checked, which is the pin* working, not failing. Content itself is untrusted: served same-origin, it* carries `nosniff` and a sandbox CSP, and only raster types pass the* allowlist, so no script-carrying format reaches a browser. `/page-content`* does not pin, so it keeps the rebinding window (see `resolvePublicUrl`'s* docstring).*//*** Off the critical path: the search response does not wait on a thumbnail,* so the budget is set against how long a user tolerates a placeholder tile,* not against the whole grid. It bounds the redirect hops too, DNS included.*/6 unmodified lines/*** Raster types only, by name: the response is served same-origin, and an SVG* loaded by direct navigation is a document whose scripts would run on this* origin.*/const ACCEPTED_CONTENT_TYPES = ["image/avif",
29 unmodified lines3031323334353610 unmodified lines47484950515253545556575 unmodified lines6364656667686910 unmodified lines8081828384858620 unmodified lines10710810911011111211311411529 unmodified linesthis.options = { ...defaultOptions, ...options };}/** Runs `fn` under the named circuit, tripping it after repeated failures. */async execute<T>(key: string, fn: () => Promise<T>): Promise<T> {if (!this.allows(key)) {throw new Error(`Circuit breaker is open for ${key}`);10 unmodified lines}/*** Whether a call under the named circuit may go ahead right now. An open* circuit whose reset timeout has elapsed becomes half-open here, so the* caller that asked is the one that probes it. With `recordSuccess` and* `recordFailure` this is `execute` taken apart, for a caller whose* failures are return values rather than exceptions.*/allows(key: string): boolean {const metrics = this.metrics.get(key);5 unmodified linesreturn true;}/** A success under the named circuit: clears its failures, or closes it after a probe. */recordSuccess(key: string): void {// A circuit nothing has failed under is closed with no failures already,// so a success on it has nothing to record and no entry to create.10 unmodified lines}}/** A failure under the named circuit, opening it at the threshold. */recordFailure(key: string): void {const metrics = this.getOrCreateMetrics(key);20 unmodified lines}/*** How often this circuit has opened. A closed circuit says nothing about* whether the instance spent the last hour serving no searches at all, which* is what this answers.*/getOpens(key: string): number {return this.metrics.get(key)?.opens ?? 0;29 unmodified lines30313233343510 unmodified lines464748495051525354555 unmodified lines61626364656610 unmodified lines77787980818220 unmodified lines10310410510610710810911029 unmodified linesthis.options = { ...defaultOptions, ...options };}async execute<T>(key: string, fn: () => Promise<T>): Promise<T> {if (!this.allows(key)) {throw new Error(`Circuit breaker is open for ${key}`);10 unmodified lines}/*** An open circuit whose reset timeout has elapsed becomes half-open here, so* the caller that asked is the one that probes it. With `recordSuccess` and* `recordFailure` this is `execute` taken apart, for a caller whose failures* are return values rather than exceptions.*/allows(key: string): boolean {const metrics = this.metrics.get(key);5 unmodified linesreturn true;}recordSuccess(key: string): void {// A circuit nothing has failed under is closed with no failures already,// so a success on it has nothing to record and no entry to create.10 unmodified lines}}recordFailure(key: string): void {const metrics = this.getOrCreateMetrics(key);20 unmodified lines}/*** A closed circuit says nothing about whether the instance spent the last* hour serving no searches at all, which is what this answers.*/getOpens(key: string): number {return this.metrics.get(key)?.opens ?? 0;
20 unmodified lines21222324252627282920 unmodified linessafeEndResponse(response, JSON.stringify(payload));}/*** Sends a 400 response with the first Zod validation error message.*/export function sendValidationError(response: ServerResponse,error: ZodError,20 unmodified lines21222324252620 unmodified linessafeEndResponse(response, JSON.stringify(payload));}export function sendValidationError(response: ServerResponse,error: ZodError,
12 unmodified lines13141516171819202122100 unmodified lines12312412512612712812913012 unmodified linesconst printMessage = createModelLogger(path.basename(import.meta.url));/*** Creates a debug logger with the same enabled-always behavior used by the* model services.*/export function createModelLogger(moduleName: string) {const printMessage = debug(moduleName);printMessage.enabled = true;100 unmodified lines/*** Downloads model files from a Hugging Face repo and returns a ready* inference session, tokenizer, and the tokenizer's real pad token id. The* tokenizer files use the standard Hugging Face names when not overridden.*/export async function loadOnnxModel(modelRepo: string,12 unmodified lines131415161718100 unmodified lines11912012112212312412512 unmodified linesconst printMessage = createModelLogger(path.basename(import.meta.url));export function createModelLogger(moduleName: string) {const printMessage = debug(moduleName);printMessage.enabled = true;100 unmodified lines/*** Downloads model files from a Hugging Face repo and returns a ready* inference session, tokenizer, and the tokenizer's real pad token id.*/export async function loadOnnxModel(modelRepo: string,
1234567/*** Whether a search result's url is a link a browser can open: `http` or* `https`, on a host with a dot in it.** Brave Search turned its result links into encrypted redirects on* `search.brave.com/go/v1` (https://brave.com/blog/google-goto-anti-scraping/),* whose destination only a browser that asks Brave for the key can read.1234/*** Brave Search turned its result links into encrypted redirects on* `search.brave.com/go/v1` (https://brave.com/blog/google-goto-anti-scraping/),* whose destination only a browser that asks Brave for the key can read.
23 unmodified lines242526272829303123 unmodified lines* against the IP being dialled, and the `Host` header is set explicitly so* virtual-host routing is unaffected.** @param url - The URL to fetch; its protocol picks http or https* @param address - The vetted IP literal to connect to, IPv4 or IPv6* @throws When the protocol is not http(s) or the request fails*/export function requestPinnedToVettedAddress(23 unmodified lines24252627282923 unmodified lines* against the IP being dialled, and the `Host` header is set explicitly so* virtual-host routing is unaffected.** @throws When the protocol is not http(s) or the request fails*/export function requestPinnedToVettedAddress(
112 unmodified lines1131141151161171181194 unmodified lines12412512612712812913013113244 unmodified lines177178179180181182183184185112 unmodified lines});/*** Whether an IP literal falls inside a range MiniSearch refuses to fetch from.* Addresses that fail to parse are treated as blocked, since an address the* guard cannot reason about is not one it can clear.*/4 unmodified lines}/*** Validates a URL the server is about to fetch on a client's behalf and* returns the address the fetch must connect to.** Returning the vetted address is what makes pinning possible. A caller* that validates here and then dials the hostname again (a plain `fetch`)* re-resolves at connect time, and that second answer can differ from the44 unmodified lines}/*** Validates a URL that the server is about to fetch on a client's behalf,* rejecting non-HTTP schemes and hosts that resolve into a blocked range.** This check alone does not close the DNS-rebinding window: a caller that* fetches by hostname after validating here re-resolves at connect time,* so a name that answers publicly now and privately a moment later still112 unmodified lines1131141151161171184 unmodified lines12312412512612712844 unmodified lines173174175176177178112 unmodified lines});/*** Addresses that fail to parse are treated as blocked, since an address the* guard cannot reason about is not one it can clear.*/4 unmodified lines}/*** Returning the vetted address is what makes pinning possible. A caller* that validates here and then dials the hostname again (a plain `fetch`)* re-resolves at connect time, and that second answer can differ from the44 unmodified lines}/*** This check alone does not close the DNS-rebinding window: a caller that* fetches by hostname after validating here re-resolves at connect time,* so a name that answers publicly now and privately a moment later still
43 unmodified lines4445464748495043 unmodified linesreturn { bytes, truncated: !reachedEnd };}/** Calculates the backoff delay for a retry attempt, with jitter. */export function calculateBackoffTime(attempt: number,baseDelayMs = 100,43 unmodified lines44454647484943 unmodified linesreturn { bytes, truncated: !reachedEnd };}export function calculateBackoffTime(attempt: number,baseDelayMs = 100,
134 unmodified lines135136137138139140141134 unmodified lines});expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));// The request was within budget, so the limiter let it through.expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);});134 unmodified lines135136137138139140134 unmodified lines});expect(res.end).toHaveBeenCalledWith(JSON.stringify({ valid: true }));expect(mockConsumeRateLimitPoint).toHaveBeenCalledTimes(1);});
9 unmodified lines101112131415169 unmodified lines*/const MAX_BODY_BYTES = 4 * 1024;/** POST /api/validate-access-key: checks an argon2id hash against the configured `ACCESS_KEYS`. */export function validateAccessKeyServerHook<T extends ViteDevServer | PreviewServer,>(server: T) {9 unmodified lines1011121314159 unmodified lines*/const MAX_BODY_BYTES = 4 * 1024;export function validateAccessKeyServerHook<T extends ViteDevServer | PreviewServer,>(server: T) {
447 unmodified lines448449450451452453454447 unmodified linesconst mockReq = makeMockRequest("192.168.1.100");await verifyTokenAndRateLimit(makeValidHash("valid"), mockReq);await consumeRateLimitPoint(mockReq);// Both went through the one shared limiter, keyed on the same address.expect(consumeInstances.size).toBe(1);expect(mockConsume).toHaveBeenCalledTimes(2);expect(mockConsume).toHaveBeenNthCalledWith(1, "127.0.0.1");447 unmodified lines448449450451452453447 unmodified linesconst mockReq = makeMockRequest("192.168.1.100");await verifyTokenAndRateLimit(makeValidHash("valid"), mockReq);await consumeRateLimitPoint(mockReq);expect(consumeInstances.size).toBe(1);expect(mockConsume).toHaveBeenCalledTimes(2);expect(mockConsume).toHaveBeenNthCalledWith(1, "127.0.0.1");
39 unmodified lines404142434445469 unmodified lines56575859606162636465666768697027 unmodified lines989910010110210310410510610710835 unmodified lines14414514614714814915015115215315439 unmodified linesduration: THUMBNAIL_RATE_LIMIT_DURATION_SECONDS,});/** Why a request was turned away, named by the check that turned it away. */export type RejectionReason = "rateLimited" | "missingToken" | "invalidToken";/**9 unmodified linesreason: RejectionReason;};/** Whether to trust proxy-set forwarding headers. Off unless `TRUST_PROXY` is `true`/`1`. */function isProxyTrusted(): boolean {const value = process.env.TRUST_PROXY?.trim().toLowerCase();return value === "true" || value === "1";}/*** Resolves the client IP used as the rate-limit key.** `X-Forwarded-For` / `X-Real-IP` are only honored when `TRUST_PROXY` is* enabled. On a directly-exposed instance those headers are fully* client-controlled, so trusting them would let a caller forge a fresh IP per27 unmodified lines}/*** Consume one point from the shared rate limiter for a request, keyed by the* client IP. Returns `true` when the request is within budget, `false` when the* limiter refuses it.** It reuses the same limiter instance the token-verified endpoints consume* from, so a tokenless caller cannot get a second, independent budget by* hitting a different endpoint. (The one deliberate exception is /thumbnail,* which verifies a token like the rest and carries its own budget because a35 unmodified linesrequest?: IncomingMessage,limiter: RateLimiterMemory = rateLimiter,): Promise<TokenVerificationResult> {// Rate-limit before anything else. An invalid or missing token used to skip// the limiter entirely, and every rejected request still pays for a full// argon2 verification, which is expensive enough to be a DoS lever on a// publicly reachable instance: a caller could send an endless stream of// bogus tokens and pin the server's CPU without ever hitting the limiter.const rateLimitKey = request ? getClientIp(request) : (token ?? "anonymous");try {await limiter.consume(rateLimitKey);39 unmodified lines4041424344459 unmodified lines55565758596061626364656627 unmodified lines94959697989910035 unmodified lines13613713813914014114214314414539 unmodified linesduration: THUMBNAIL_RATE_LIMIT_DURATION_SECONDS,});export type RejectionReason = "rateLimited" | "missingToken" | "invalidToken";/**9 unmodified linesreason: RejectionReason;};function isProxyTrusted(): boolean {const value = process.env.TRUST_PROXY?.trim().toLowerCase();return value === "true" || value === "1";}/*** `X-Forwarded-For` / `X-Real-IP` are only honored when `TRUST_PROXY` is* enabled. On a directly-exposed instance those headers are fully* client-controlled, so trusting them would let a caller forge a fresh IP per27 unmodified lines}/*** Reuses the same limiter instance the token-verified endpoints consume* from, so a tokenless caller cannot get a second, independent budget by* hitting a different endpoint. (The one deliberate exception is /thumbnail,* which verifies a token like the rest and carries its own budget because a35 unmodified linesrequest?: IncomingMessage,limiter: RateLimiterMemory = rateLimiter,): Promise<TokenVerificationResult> {// Rate-limit before anything else: every rejected request still pays for a// full argon2 verification, which is expensive enough to be a DoS lever on a// publicly reachable instance, so a stream of bogus tokens must hit the// limiter before it can pin the server's CPU.const rateLimitKey = request ? getClientIp(request) : (token ?? "anonymous");try {await limiter.consume(rateLimitKey);
472 unmodified lines473474475476477478479480472 unmodified linesemptyBreaker,);// The breaker still records which one was a failure, and now the caller// can tell them apart from the outcome as well.expect(downBreaker.getState("searxng")).toBe("OPEN");expect(emptyBreaker.getState("searxng")).toBe("CLOSED");expect(noResults).toEqual([]);472 unmodified lines473474475476477478472 unmodified linesemptyBreaker,);expect(downBreaker.getState("searxng")).toBe("OPEN");expect(emptyBreaker.getState("searxng")).toBe("CLOSED");expect(noResults).toEqual([]);
26 unmodified lines2728293031323334353637125 unmodified lines16316416516616716816926 unmodified linesconst MAX_RETRIES = 3;const BASE_RETRY_DELAY = 1000;// successThreshold: 1 preserves the previous breaker's single-success reset:// once resetTimeout elapses, one healthy request closes the circuit again.const searxngCircuitBreaker = new CircuitBreaker({failureThreshold: 5,resetTimeout: 60_000,successThreshold: 1,});125 unmodified lines);}/** A concise, human-readable summary of the engines that failed. */export function formatUnresponsiveEngines(engines: UnresponsiveEngine[]) {return engines.map(({ engine, reason }) => (reason ? `${engine} (${reason})` : engine))26 unmodified lines27282930313233343536125 unmodified lines16216316416516616726 unmodified linesconst MAX_RETRIES = 3;const BASE_RETRY_DELAY = 1000;const searxngCircuitBreaker = new CircuitBreaker({failureThreshold: 5,resetTimeout: 60_000,// Once resetTimeout elapses, one healthy request closes the circuit again.successThreshold: 1,});125 unmodified lines);}export function formatUnresponsiveEngines(engines: UnresponsiveEngine[]) {return engines.map(({ engine, reason }) => (reason ? `${engine} (${reason})` : engine))
8 unmodified lines910111213141516178 unmodified lines* client/modules/systemPrompt.ts.*//*** The citation example inside the prompt, on a placeholder domain: the* previous example, a real video link, was copied by small models as if it* were one of the sources.*/export const CITATION_EXAMPLE = "[example.com](https://example.com/page)";8 unmodified lines9101112131415168 unmodified lines* client/modules/systemPrompt.ts.*//*** The citation example inside the prompt, on a placeholder domain: small* models copy a real link in the example as if it were one of the sources.*/export const CITATION_EXAMPLE = "[example.com](https://example.com/page)";
scripts/documentation-validator.cjs-17
scripts/npm-bundle-overlay.cjs+2-2
server/authorityRanking.ts-1
server/authorizationSinceLastRestart.ts+2-5
server/biEncoderService.integration.test.ts+6-8
server/biEncoderService.ts+3-9
server/biEncoderWorker.ts+8-18
server/biEncoderWorkerProtocol.ts+11-13
server/configEndpointServerHook.ts+2-3
server/downloadFileFromHuggingFaceRepository.ts+3-4
server/fallbackSearchService.ts+11-40
server/inferencesSinceLastRestart.ts+2-5
server/internalApiEndpointServerHook.test.ts-11
server/internalApiEndpointServerHook.ts+4-6
server/officialLane.ts+2-5
server/pageContentService.test.ts+15-21
server/pageContentService.ts+13-21
server/pageReadHostBreaker.ts+2-3
server/rankSearchResults.test.ts+1-2
server/rejectedTokens.ts+2-2
server/rerankerService.ts+7-23
server/rerankingSinceLastRestart.ts+1-3
server/searchToken.test.ts+3-3
server/searchToken.ts+3-9
server/searchesSinceLastRestart.ts+7-10
server/statusEndpointServerHook.test.ts+2-3
server/thumbnailEndpointServerHook.test.ts-1
server/thumbnailEndpointServerHook.ts+13-15
server/utils/circuitBreaker.ts+6-11
server/utils/httpResponse.ts-3
server/utils/onnxModelLoader.ts+1-6
server/utils/openableUrl.ts-3
server/utils/pinnedFetch.ts-2
server/utils/publicUrl.ts-7
server/utils/streamUtils.ts-1
server/validateAccessKeyServerHook.test.ts-1
server/validateAccessKeyServerHook.ts-1
server/verifyTokenAndRateLimit.test.ts-1
server/verifyTokenAndRateLimit.ts+5-14
server/webSearchService.test.ts-2
server/webSearchService.ts+1-3
shared/defaultSystemPrompt.ts+2-3