import type { EmbedHealth, EmbedProvider, OnnxDType, OnnxPoolingStrategy } from '../../contracts/embed.js'; import { DEFAULT_ONNX_HF_MODEL_ID, DEFAULT_ONNX_REVISION, DEFAULT_ONNX_DTYPE, DEFAULT_ONNX_POOLING, ONNX_MODEL_REGISTRY, type OnnxModelRegistryEntry } from './onnx-registry.js'; export type { OnnxDType }; export type { OnnxPoolingStrategy }; export { DEFAULT_ONNX_HF_MODEL_ID, DEFAULT_ONNX_REVISION, DEFAULT_ONNX_DTYPE, DEFAULT_ONNX_POOLING, ONNX_MODEL_REGISTRY, type OnnxModelRegistryEntry, }; /** Structural subset of `@huggingface/transformers`' `Tensor` actually used * here — real call sites always receive a real `Tensor` instance. */ export interface OnnxTensorLike { readonly dims: number[]; tolist(): unknown; } export interface OnnxBatchEncoding { readonly attention_mask: OnnxTensorLike; readonly [key: string]: unknown; } export interface OnnxModelOutput { readonly last_hidden_state: OnnxTensorLike; } /** * Narrow surface over AutoTokenizer + AutoModel actually used by this * provider — tokenize -> run -> pool, mirroring * `@huggingface/transformers`' own `FeatureExtractionPipeline` internals * exactly (`tokenizer(texts, {padding:true, truncation:true})` -> * `model(inputs)` -> `mean_pooling(last_hidden_state, attention_mask)` -> * `.normalize(2, -1)`). `pool()` reuses the library's own tested * pooling/normalize tensor math rather than hand-rolling the arithmetic — * ADR-018 Risk B calls out a hand-rolled reimplementation as exactly where a * silent geometry-parity bug would hide. */ export interface OnnxBackend { tokenize(texts: string[]): Promise; run(inputs: OnnxBatchEncoding): Promise; /** Pool (mean or cls, per the resolved model's `OnnxPoolingStrategy` — * ADR-018 SLICE-5) + L2-normalize. Returns one flat unit vector per input * text, in input order. */ pool(output: OnnxModelOutput, attentionMask: OnnxTensorLike): Promise; } /** * Mean-pool `output.last_hidden_state` over `attentionMask`, then * L2-normalize — exported standalone (not inlined in the default backend) * so unit tests can exercise the EXACT production pooling/normalize code * path against hand-built synthetic `Tensor`s, with no ONNX session and no * model download (`Tensor` construction and `mean_pooling`/`.normalize()` * are pure tensor math, not inference — see * tests/providers/embed/onnx.test.ts). Reuses * `@huggingface/transformers`' own tested `mean_pooling` + `Tensor.normalize` * rather than hand-rolling the arithmetic (ADR-018 Risk B). */ export declare function poolMeanNormalize(output: OnnxModelOutput, attentionMask: OnnxTensorLike): Promise; /** * ADR-018 SLICE-5 — CLS-token pooling: take `last_hidden_state[:, 0]` (the * first sequence position, i.e. the `[CLS]`/`` token this repo's * tokenizers always place at position 0 regardless of right-padding), then * L2-normalize. Exported standalone for the same testability reason as * `poolMeanNormalize` — exercises the real production code path against * hand-built synthetic `Tensor`s. * * Mirrors `@huggingface/transformers`' own `FeatureExtractionPipeline` * internals exactly for `pooling: 'cls'`/`'first_token'`: * `result.slice(null, 0)` then `.normalize(2, -1)` (confirmed against the * installed package's dist bundle — same tensor-slice API `Tensor.slice()` * documents). `attentionMask` is accepted but unused — CLS pooling never * needs the mask, since the CLS token is always real content (never * padding) at position 0. Kept as a parameter purely to match * `OnnxBackend#pool()`'s shared signature with `poolMeanNormalize`. */ export declare function poolClsNormalize(output: OnnxModelOutput, _attentionMask: OnnxTensorLike): Promise; interface ResolvedOnnxLoadOpts { hfModelId: string; revision: string; dtype: OnnxDType; pooling: OnnxPoolingStrategy; cacheDir?: string; modelPath?: string; numThreads: number; } /** Files that must ALL exist for a cached snapshot to be loadable fully * offline. Matches both the hub layout and the library's on-disk cache * layout (`///...`). */ export declare function requiredSnapshotFiles(dtype: OnnxDType): string[]; /** * Resolve a COMPLETE local model snapshot directory, or `undefined` when at * least one required file is missing (→ caller falls back to the * hub-download path, which populates the cache for the next boot). * * Why this exists (2026-07-16 prod embed outage): passing a repo id + * pinned revision to `from_pretrained` is NOT offline-safe even with a * fully populated cache. `@huggingface/transformers` 4.2.0's * `loadTokenizer` → `get_tokenizer_files()` issues a network HEAD to the * hub on EVERY load, passing empty options — it ignores both the caller's * `revision` and `local_files_only`, and its cache key is keyed on `main` * while a pinned-revision download is cached under the SHA path, so the * lookup can never hit. When the hub is unreachable it resolves to zero * tokenizer files and the load dies with * `Cannot read properties of undefined (reading 'tokenizer_class')`. * Passing a DIRECTORY as `pretrained_model_name_or_path` bypasses the hub * entirely (`isValidHfModelId` rejects filesystem paths → every file is * read locally, zero network) — verified offline-clean on a box whose * node→huggingface.co path was hard-down while curl succeeded. * * Candidate order (first complete snapshot wins): * 1. `modelPath` itself (operator points straight at a snapshot dir) * 2. `modelPath//` (operator points at a cache root) * 3. `cacheDir//` (config.onnxEmbed.cacheDir) * 4. `libraryCacheDir//` (the library's own default * cache — where a prior boot's download actually landed) * * When `modelPath` is set, candidates 3-4 are NOT consulted (review * follow-up on #363): `modelPath` is the air-gapped operator's explicit * override, and silently falling back past it to a stray cache snapshot * would load weights the operator never pointed at — the incomplete- * modelPath case must fail loudly (the caller throws), never resolve * elsewhere. */ export declare function resolveLocalSnapshotDir(opts: Pick, libraryCacheDir?: string): string | undefined; export interface OnnxEmbedConfig { /** Canonical model label used for `QUERY_PREFIX_BY_MODEL` + * `ONNX_MODEL_REGISTRY` lookups + display — NOT the HF repo id. Defaults * to `'mxbai-embed-large-v1'`. Set to `'bge-m3'` to select the ADR-018 * SLICE-5 second model. */ model?: string; /** FEAT-409: expected output dim — defaults to DEFAULT_EMBED_DIM (1024). * Set from config.embedding.dim by providers/index.ts. */ dim?: number; /** RECALL-S1: query-side embedding instruction prefix — resolved by * providers/index.ts via resolveEmbedQueryPrefix, not this constructor. * See EmbedProvider.queryPrefix (src/contracts/embed.ts). Defaults to '' * (no prefix). */ queryPrefix?: string; /** HF repo id to load from. Defaults to `ONNX_MODEL_REGISTRY[model]`'s * `hfRepo`, falling back to `DEFAULT_ONNX_HF_MODEL_ID` for an * unregistered model. Explicit value here always overrides the * registry. */ hfModelId?: string; /** Pinned HF revision (commit SHA) — never `'main'`. Defaults to * `ONNX_MODEL_REGISTRY[model]`'s `defaultRevision`, falling back to * DEFAULT_ONNX_REVISION for an unregistered model. */ revision?: string; /** ORT weight precision. Defaults to `ONNX_MODEL_REGISTRY[model]`'s * `defaultDtype`, falling back to DEFAULT_ONNX_DTYPE ('q8') for an * unregistered model. */ dtype?: OnnxDType; /** ADR-018 SLICE-5 — pooling strategy override. Defaults to * `ONNX_MODEL_REGISTRY[model]`'s `pooling`, falling back to * DEFAULT_ONNX_POOLING ('mean') for an unregistered model. Set explicitly * to override a registered model's documented default (e.g. to restore * SLICE-1/2's mean-pooling behavior for mxbai on an existing install). */ pooling?: OnnxPoolingStrategy; /** Local cache directory for downloaded weights. providers/index.ts * defaults this to `/models/onnx/` (ADR-018 S2, wired 2026-07-16 * — the library's own default cache lives inside the release directory's * node_modules and is silently discarded on release rotation); unset here * defers to the library's own default cache resolution. */ cacheDir?: string; /** Explicit local snapshot override for offline/air-gapped installs. * When set, it is the ONLY location consulted and it MUST contain a * complete snapshot (`config.json`, `tokenizer.json`, * `tokenizer_config.json`, `onnx/model.onnx` — see * `requiredSnapshotFiles`) either directly at `modelPath` or at * `modelPath///`; otherwise boot throws (never a * silent hub download — ADR-015). BREAKING vs pre-#363 semantics, which * treated this as a `cache_dir` for the library's own resolution: an * install laid out for the old scheme must reshape to one of the two * layouts above (a directory populated by a prior daemon download * already matches the second). */ modelPath?: string; /** ORT intraOpNumThreads cap. Defaults to DEFAULT_NUM_THREADS (4). */ numThreads?: number; /** Test/DI seam only — overrides the default `@huggingface/transformers` * backed loader so unit tests can inject a fake backend instead of * downloading the real model. Production code never sets this. */ loadBackend?: (opts: { hfModelId: string; revision: string; dtype: OnnxDType; pooling: OnnxPoolingStrategy; cacheDir?: string; modelPath?: string; numThreads: number; }) => Promise; } export declare class OnnxEmbedProvider implements EmbedProvider { readonly name: "onnx"; readonly model: string; readonly dim: number; readonly queryPrefix: string; private readonly hfModelId; private readonly revision; private readonly dtype; private readonly pooling; private readonly cacheDir; private readonly modelPath; private readonly numThreads; private readonly loadBackend; private backendPromise; /** * ADR-018 SLICE-5 — model registry resolution. `hfModelId`/`revision`/ * `dtype`/`pooling` each resolve in this order: (1) an explicit * `OnnxEmbedConfig` field (== `config.onnxEmbed.*` from * `providers/index.ts`) always wins outright; (2) failing that, the * `ONNX_MODEL_REGISTRY` entry keyed by `this.model` supplies the * model-documented default; (3) failing that (model absent from the * registry — a custom/unverified model string), the original SLICE-1/2 * hardcoded constants (`DEFAULT_ONNX_HF_MODEL_ID`/`DEFAULT_ONNX_REVISION`/ * `DEFAULT_ONNX_DTYPE`/`DEFAULT_ONNX_POOLING`) apply, preserving * pre-SLICE-5 behavior for anything not explicitly onboarded. This is the * "add a model = one registry entry" mechanism SLICE-5 exists to * establish — switching `config.embedding.model` to `'bge-m3'` alone (no * other config change) resolves the correct HF repo, revision, dtype, AND * pooling strategy. */ constructor(config?: OnnxEmbedConfig); /** * Lazy, memoized session load (ADR-018 "Startup preload" decision): the * constructor never eagerly loads the ORT session or triggers a weight * download, mirroring `CodexSubscriptionLLMProvider`'s "no * construction-time throw" posture (providers/index.ts) — selecting * `provider: onnx` without a reachable model artifact does not crash * daemon boot, it surfaces through `embed()`/`health()` instead. The * FIRST real call after boot (or after switching to `onnx` in config) * pays session-load + possible first-run download latency inline; every * subsequent call in the process lifetime reuses the memoized session. A * failed load is NOT memoized, so a transient failure (e.g. network * unreachable on first download attempt) can be retried on the next call * rather than permanently wedging the provider. */ private getBackend; /** * ADR-018 SLICE-2 — startup preload. Public, idempotent wrapper around * `getBackend()`: triggers the SAME lazy, memoized session load the first * `embed()`/`health()` call would (no separate code path, no risk of * loading the model twice or diverging from that contract) — it just lets * a caller (serve.ts) trigger the load proactively, in the BACKGROUND, at * boot, so the daemon's first real `embed()` call after startup doesn't * pay the cold session-load / possible first-run weight-download latency * inline. Does not change the class's documented lazy-load posture (see * `getBackend()`'s doc comment above): a `preload()` that is never called * still leaves the provider fully lazy, and `preload()` itself still * never runs at construction time — only when a caller (serve.ts, gated * to `provider: 'onnx'` only) explicitly invokes it. Rejects on failure — * callers must catch and WARN, not let it crash the caller's own boot * path (mirrors every other opt-in preflight in this daemon: cold-start * failure degrades, it never crashes). */ preload(): Promise; /** * `signal` (issue #261 contract, honestly narrowed for in-process * inference): in-process ORT inference has no `fetch`-style mid-call * abort plumbing into the native session — a signal is checked BETWEEN * texts in this per-text loop (mirroring `OllamaEmbedProvider`'s loop * shape) and throws immediately once set, but a signal that fires * mid-inference on one text will NOT interrupt that single in-flight * `run()` call; it completes, then the next loop iteration's check aborts * the remaining batch. This is a materially weaker cancellation guarantee * than the HTTP providers have (ADR-018) — documented here, not silently * implied to match. */ embed(texts: string[], signal?: AbortSignal): Promise; /** * No HTTP call to an always-on external service, unlike * `OllamaEmbedProvider`'s `/api/tags` GET or `AzureOpenAIEmbedProvider`'s * embed ping — this is an in-process check (ADR-018 constraint #7). * Verifies the model loads (reusing the same lazy/memoized session as * `embed()`) and that a smoke inference on `'ping'` produces a vector of * the expected `dim`. NOTE: on a cold cache with no `modelPath` * configured, this can still trigger the same one-time weight download * `embed()`'s first call would — "no network call" describes the shape of * this method (no request/response to a runtime service), not a * guarantee that zero bytes ever cross the wire on a cold first call. */ health(): Promise; }