/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/embed/native-embedder * * In-process sentence embeddings and cross-encoder reranking through the Rust * bridge (`bxc-embed`, candle). No API key, no network at query time; models * are installed explicitly with `bxc install --models`. * * The symbols are bound as an optional extension of the bridge library: when * the loaded bridge was built without them, or the model is not installed, * `tryLoad()` returns `null` and callers fall back to another embedder. */ import { CString, FFIType, type Pointer } from "bun:ffi"; import { cString, createLazyLibrary } from "../native/loader.ts"; import { awaitNativeJob, BXC_BRIDGE_ABI_VERSION, bridgeLibraryPath, isBridgeAvailable, } from "../rust/bridge.ts"; import type { Embedder, EmbeddingKind } from "./embedder.ts"; const embedLibrary = createLazyLibrary({ name: "bxc rust-bridge (embeddings)", candidates: () => { const path = bridgeLibraryPath(); return path ? [path] : []; }, symbols: { bxc_embed_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast }, bxc_rerank_submit: { args: [FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast }, bxc_embed_info: { args: [], returns: FFIType.ptr }, bxc_embed_install_submit: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.u64_fast }, bxc_free_string: { args: [FFIType.ptr], returns: FFIType.void }, }, abi: { symbol: "bxc_bridge_abi_version", expected: BXC_BRIDGE_ABI_VERSION }, installHint: "Rebuild the Rust bridge with bxc-embed (`bun run build:linux`).", }); export interface ModelStatus { id: string; dim?: number; installed: boolean; dir: string; sizeBytes: number; } export interface EmbeddingModelsInfo { embed: ModelStatus | null; rerank: ModelStatus | null; modelsDir: string; available: { embed: string[]; rerank: string[] }; } async function readJob(id: number | bigint, signal?: AbortSignal): Promise { const json = await awaitNativeJob(Number(id), signal); const parsed = JSON.parse(json) as T | { error: string }; if (parsed && typeof parsed === "object" && "error" in parsed && typeof parsed.error === "string") { throw new Error(parsed.error); } return parsed as T; } /** Installation status of the configured models, or `null` without bindings. */ export function embeddingModelsInfo(): EmbeddingModelsInfo | null { if (!isBridgeAvailable() || !embedLibrary.available()) return null; const sym = embedLibrary.symbols(); const ptr = sym.bxc_embed_info() as Pointer | null; if (!ptr) return null; try { return JSON.parse(new CString(ptr).toString()) as EmbeddingModelsInfo; } finally { sym.bxc_free_string(ptr); } } /** Download and verify a model (embedding or reranker id). */ export async function installEmbeddingModel(id: string, timeoutMs = 30 * 60_000): Promise<{ id: string; dir: string }> { return readJob(embedLibrary.symbols().bxc_embed_install_submit(cString(id), timeoutMs)); } export class NativeEmbedder implements Embedder { readonly model: string; readonly dim: number; readonly semantic = true; readonly #timeoutMs: number; private constructor(model: string, dim: number, timeoutMs: number) { this.model = model; this.dim = dim; this.#timeoutMs = timeoutMs; } /** Load the configured model if the bindings exist and it is installed. */ static async tryLoad(options: { timeoutMs?: number } = {}): Promise { const info = embeddingModelsInfo(); if (!info?.embed?.installed || !info.embed.dim) return null; return new NativeEmbedder(info.embed.id, info.embed.dim, options.timeoutMs ?? 120_000); } async embed(texts: readonly string[], kind: EmbeddingKind = "passage"): Promise { if (texts.length === 0) return []; const result = await readJob<{ model: string; dim: number; count: number; data: string }>( embedLibrary.symbols().bxc_embed_submit(cString(JSON.stringify(texts)), cString(kind), this.#timeoutMs), ); const bytes = Uint8Array.fromBase64(result.data); const flat = new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4); return Array.from({ length: result.count }, (_, i) => flat.slice(i * result.dim, (i + 1) * result.dim)); } } export class NativeReranker { readonly model: string; readonly #timeoutMs: number; private constructor(model: string, timeoutMs: number) { this.model = model; this.#timeoutMs = timeoutMs; } static async tryLoad(options: { timeoutMs?: number } = {}): Promise { const info = embeddingModelsInfo(); if (!info?.rerank?.installed) return null; return new NativeReranker(info.rerank.id, options.timeoutMs ?? 120_000); } /** Relevance scores aligned with `passages` (higher is more relevant). */ async score(query: string, passages: string[]): Promise { if (passages.length === 0) return []; const ranked = await readJob>( embedLibrary.symbols().bxc_rerank_submit(cString(query), cString(JSON.stringify(passages)), this.#timeoutMs), ); const scores = Array.from({ length: passages.length }).fill(Number.NEGATIVE_INFINITY); for (const { index, score } of ranked) scores[index] = score; return scores; } }