/* tslint:disable */
/* eslint-disable */

/**
 * A stateful GGUF chunk accumulator exposed to JavaScript.
 *
 * JavaScript usage:
 * ```js
 * const loader = new GgufChunkLoader();
 * // Feed chunks as they arrive
 * const reader = response.body.getReader();
 * while (true) {
 *   const {done, value} = await reader.read();
 *   if (done) break;
 *   const result = loader.feed(value);
 *   if (result.header_ready) console.log('header parsed!', result.n_tensors);
 * }
 * ```
 */
export class GgufChunkLoader {
    free(): void;
    [Symbol.dispose](): void;
    /**
     * Total bytes received so far.
     */
    bytes_received(): number;
    /**
     * Feed a new chunk of bytes. Returns a JSON status object.
     *
     * # Errors
     * Returns a JS error string on parse failure.
     */
    feed(chunk: Uint8Array): any;
    /**
     * Whether the GGUF header has been fully parsed.
     */
    header_ready(): boolean;
    /**
     * Number of tensors declared in the header (0 if header not yet parsed).
     */
    n_tensors(): bigint;
    /**
     * Create a new chunk loader.
     */
    constructor();
}

/**
 * A streaming GGUF loader for WebAssembly environments.
 *
 * Designed for browser use where models may be many gigabytes and cannot be
 * loaded into `Uint8Array` all at once.  Two access patterns are supported:
 *
 * ## Push mode
 *
 * Feed chunks from a `ReadableStream` via `push_chunk`.  The loader
 * accumulates bytes until it has enough to parse the GGUF header (typically
 * 50–100 KB for models with many tensors).  Once the header is parsed,
 * `is_header_ready` returns `true` and `tensor_names` is populated.
 *
 * In push mode the entire file is buffered in memory.  For models that must
 * remain partially on disk (multi-GB) use pull mode instead.
 *
 * ## Pull mode
 *
 * After the header is parsed (which requires a push-mode phase), individual
 * tensors can be fetched on demand via `read_tensor`, which accepts a JS
 * byte-range callback `(offset: number, size: number) => Promise<Uint8Array>`.
 * Fetched tensors are cached in an LRU with configurable capacity.
 */
export class StreamingGgufLoader {
    free(): void;
    [Symbol.dispose](): void;
    /**
     * Returns the number of bytes accumulated so far.
     */
    bytes_buffered(): number;
    /**
     * Returns `true` if the GGUF header has been successfully parsed.
     */
    is_header_ready(): boolean;
    /**
     * Create a new streaming GGUF loader.
     *
     * `cache_capacity` controls how many tensors the LRU cache holds
     * simultaneously.  Pass `undefined` / `None` to use the default of 8.
     */
    constructor(cache_capacity?: number | null);
    /**
     * Returns a progress descriptor as a JS `Object`.
     *
     * Fields:
     * - `bytes_buffered` — total bytes fed via `push_chunk`
     * - `phase`          — `"waiting_for_header"` or `"header_parsed"`
     * - `tensor_count`   — number of tensors in the index (0 before header)
     * - `cache_size`     — number of tensors currently in the LRU cache
     */
    progress(): object;
    /**
     * Feed a chunk of bytes from a `ReadableStream` reader.
     *
     * Bytes are appended to an internal buffer.  After each call the loader
     * attempts to parse the GGUF header from the accumulated bytes.  The
     * attempt uses grow-and-retry semantics: if the buffer is too short the
     * error is swallowed and the call returns `false`; a genuine parse error
     * (bad magic, unsupported version) is returned as a `JsValue` error.
     *
     * Returns `true` once the header (and tensor index) has been successfully
     * parsed; returns `false` while still accumulating.
     */
    push_chunk(chunk: Uint8Array): boolean;
    /**
     * Fetch tensor data by name using a JS byte-range callback.
     *
     * `fetcher` is a JS function with signature:
     * ```js
     * (offset: number, size: number) => Promise<Uint8Array>
     * ```
     *
     * The LRU cache is checked first; on a miss the fetcher is called with the
     * absolute file offset and byte length.  The result is stored in the cache
     * before being returned.
     *
     * # Errors
     *
     * Returns a `JsValue` error if:
     * - The header has not been parsed yet.
     * - The tensor name is not in the index.
     * - The fetcher rejects its promise.
     * - The lock is poisoned.
     */
    read_tensor(name: string, fetcher: Function): Promise<Uint8Array>;
    /**
     * Returns tensor metadata as a JSON string, or `None` if the name is
     * not in the index.
     *
     * The JSON object has fields:
     * - `file_offset` — absolute byte offset in the GGUF file (as a number)
     * - `size_bytes`  — tensor data size in bytes
     * - `dtype`       — quantization type string (e.g. `"Q4_0"`)
     * - `shape`       — array of dimension sizes
     */
    tensor_meta_json(name: string): string | undefined;
    /**
     * Returns a JS `Array` of tensor name strings after the header is ready.
     *
     * Returns an empty array if called before the header is parsed.
     */
    tensor_names(): Array<any>;
}

/**
 * Configuration options for creating a [`StreamingGgufLoader`].
 *
 * Provides named-parameter ergonomics from JavaScript; alternatively callers
 * may construct `StreamingGgufLoader` directly with `new(cacheCapacity)`.
 */
export class StreamingLoadOptions {
    free(): void;
    [Symbol.dispose](): void;
    /**
     * Create options with defaults: `progress_enabled = true`, `cache_capacity = 8`.
     */
    constructor();
    /**
     * LRU cache capacity (number of tensors).
     */
    cache_capacity: number;
    /**
     * Whether to emit `progress()` events (reserved for future use).
     */
    progress_enabled: boolean;
}

/**
 * Opaque handle wrapping a loaded `InferenceEngine` for use from JS.
 */
export class WasmEngine {
    private constructor();
    free(): void;
    [Symbol.dispose](): void;
    /**
     * Run text generation on this engine.
     *
     * Equivalent to the top-level [`generate`] function but reuses an already
     * loaded model, avoiding the expensive load step on subsequent calls.
     */
    generate(prompt: string, max_tokens: number, on_token?: Function | null): string;
}

/**
 * Store a GGUF model in the browser's IndexedDB under the given name.
 */
export function cacheModel(name: string, data: Uint8Array): Promise<void>;

/**
 * Remove a model from the IndexedDB cache.
 */
export function deleteCachedModel(name: string): Promise<void>;

/**
 * Dequantize a buffer of Q4_K blocks to an array of f32 values.
 *
 * The Q4_K block layout is 144 bytes per 256 weights.
 * `data` must be a multiple of 144 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 144) * 256`.  Throws a JavaScript error string on any
 * malformed input.
 */
export function dequantQ4K(data: Uint8Array): Float32Array;

/**
 * Dequantize a buffer of Q4_0 blocks to an array of f32 values.
 *
 * The Q4_0 block layout is 18 bytes per 32 weights:
 * - 2 bytes: FP16 scale factor
 * - 16 bytes: 32 × 4-bit nibbles packed two per byte
 *
 * `data` must be a multiple of 18 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 18) * 32`.  Throws a JavaScript error string on any
 * malformed input.
 */
export function dequantQ4_0(data: Uint8Array): Float32Array;

/**
 * Dequantize Q4_0 blocks using the CPU fallback path.
 *
 * Always works in WASM — does not require WebGPU.
 */
export function dequantQ4_0WithFallback(data: Uint8Array): Float32Array;

/**
 * Dequantize a buffer of Q5_K blocks to an array of f32 values.
 *
 * The Q5_K block layout is 176 bytes per 256 weights.
 * `data` must be a multiple of 176 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 176) * 256`.  Throws a JavaScript error string on any
 * malformed input.
 */
export function dequantQ5K(data: Uint8Array): Float32Array;

/**
 * Dequantize a buffer of Q6_K blocks to an array of f32 values.
 *
 * The Q6_K block layout is 210 bytes per 256 weights.
 * `data` must be a multiple of 210 bytes.  Returns a `Vec<f32>` of length
 * `(data.len() / 210) * 256`.  Throws a JavaScript error string on any
 * malformed input.
 */
export function dequantQ6K(data: Uint8Array): Float32Array;

/**
 * Dequantize Q8_0 blocks using the CPU fallback path.
 *
 * Always works in WASM — does not require WebGPU.
 */
export function dequantQ8_0WithFallback(data: Uint8Array): Float32Array;

/**
 * GEMV (matrix-vector multiply) using the CPU fallback path.
 *
 * `weights` is a row-major `rows × cols` matrix.
 * `input` is a vector of length `cols`.
 * Returns a vector of length `rows`.
 */
export function gemvCpuFallback(weights: Float32Array, input: Float32Array, rows: number, cols: number): Float32Array;

/**
 * Run full text generation from an in-memory GGUF model.
 *
 * # Arguments
 *
 * - `model_bytes`    — raw bytes of the `.gguf` model file (copied in JS
 *                      via `new Uint8Array(buffer)`)
 * - `tokenizer_json` — contents of the HuggingFace `tokenizer.json` file
 *                      for this model
 * - `prompt`         — input text prompt
 * - `max_tokens`     — maximum number of tokens to generate (generation
 *                      stops earlier if the model produces an EOS token)
 * - `on_token`       — optional JS callback invoked with each generated token
 *                      text as a string, enabling streaming output
 *
 * Returns the generated text as a JS string, or throws a JS error.
 *
 * # Notes
 *
 * This function requires the `inference` feature (enabled by default).
 * It uses `oxillama-runtime` with the pure-Rust `tokenizer-wasm` backend
 * (`fancy-regex`) so it is safe on `wasm32-unknown-unknown`.
 *
 * Model loading is done via `InferenceEngine::load_model_from_bytes` which
 * accepts raw GGUF bytes — no filesystem access is needed inside the WASM sandbox.
 */
export function generate(model_bytes: Uint8Array, tokenizer_json: string, prompt: string, max_tokens: number, on_token?: Function | null): string;

/**
 * Initialize the WASM module (sets up panic hook for better error messages).
 *
 * Called automatically by the generated JS glue code when the WASM module
 * is first instantiated.
 */
export function init(): void;

/**
 * Request a `GPUDevice` from the browser's WebGPU API.
 *
 * Returns a `Promise` that resolves to the `GPUDevice` `JsValue`, or rejects
 * with a descriptive error string if WebGPU is unavailable or no adapter
 * could be obtained.
 *
 * # JavaScript usage
 *
 * ```js
 * const device = await initWebGpuDevice();
 * ```
 */
export function initWebGpuDevice(): Promise<any>;

/**
 * List all model names currently stored in the IndexedDB cache.
 */
export function listCachedModels(): Promise<Array<any>>;

/**
 * Return all tensor names stored in a GGUF file as a JS array of strings.
 *
 * Throws a JavaScript error string if parsing fails.
 */
export function listTensorNames(data: Uint8Array): any[];

/**
 * Retrieve a previously-cached GGUF model from IndexedDB.
 *
 * Returns `null` in JS if the model is not cached, or a `Uint8Array` if found.
 */
export function loadCachedModel(name: string): Promise<any>;

/**
 * Load a GGUF model from raw bytes, reporting progress via an optional JS callback.
 *
 * The callback is invoked with a percentage value (`0`, `25`, `100`) at key
 * milestones during loading.  Pass `undefined` / `null` to skip progress
 * reporting.
 *
 * Returns an opaque `WasmEngine` handle on success, or throws a JS error.
 */
export function loadModelFromBytesWithProgress(model_bytes: Uint8Array, tokenizer_json: string, on_progress?: Function | null): WasmEngine;

/**
 * Parse a GGUF file header from raw bytes and return key metadata as a JS object.
 *
 * The returned object has the following numeric fields:
 * - `tensorCount`   — number of tensors in the file
 * - `metadataCount` — number of metadata KV pairs
 * - `version`       — GGUF file version (2 or 3)
 *
 * Throws a JavaScript error string if the bytes are not a valid GGUF file.
 */
export function parseGgufHeader(data: Uint8Array): any;

/**
 * Parse a GGUF file and return typed metadata as a JS object.
 *
 * The returned object conforms to the [`GgufMetadataJs`] schema.  Optional
 * fields are `null` when the corresponding metadata key is absent.
 *
 * Throws a JavaScript error string if parsing fails.
 */
export function parseGgufMetadata(data: Uint8Array): any;

/**
 * Parse an incoming JSON message from JavaScript.
 *
 * Returns a JSON string representing the response message.
 *
 * # Errors
 * Returns a description of the parse error if the JSON is invalid.
 */
export function parseWorkerMessage(json: string): any;

/**
 * Check whether WebGPU is available in the current browser environment.
 */
export function webgpuAvailable(): boolean;

/**
 * Dequantize Q4_0 blocks asynchronously on the GPU.
 *
 * - `device` — a `GPUDevice` obtained from [`init_webgpu_device`].
 * - `data` — raw Q4_0 bytes (must be a multiple of 18 bytes per block).
 * - `n_blocks` — number of Q4_0 blocks in `data`.
 *
 * Returns a `Promise` that resolves to a `Float32Array` of length
 * `n_blocks * 32`.
 *
 * # JavaScript usage
 *
 * ```js
 * const result = await webgpuDequantQ4_0Async(device, uint8Data, nBlocks);
 * // result is a Float32Array
 * ```
 */
export function webgpuDequantQ4_0Async(device: any, data: Uint8Array, n_blocks: number): Promise<any>;

/**
 * GEMV on GPU: multiply Q4_0-quantized weight matrix by an f32 input vector.
 *
 * - `device` — a `GPUDevice` obtained from [`init_webgpu_device`].
 * - `weights` — raw Q4_0 bytes for the weight matrix, laid out as
 *   `rows` × `(cols/32)` blocks of 18 bytes each. `cols` must be a multiple
 *   of 32.
 * - `input` — f32 input vector of length `cols`.
 * - `rows` — number of output rows.
 * - `cols` — number of columns (= input vector length, multiple of 32).
 *
 * Returns a `Promise` that resolves to a `Float32Array` of length `rows`.
 *
 * # JavaScript usage
 *
 * ```js
 * const output = await webgpuGemvAsync(device, weightBytes, inputF32, rows, cols);
 * ```
 */
export function webgpuGemvAsync(device: any, weights: Uint8Array, input: Float32Array, rows: number, cols: number): Promise<any>;

/**
 * Serialize a token delta event to JSON for posting back to the host.
 *
 * # Errors
 * Returns an error if serialization fails.
 */
export function workerTokenEvent(delta: string): any;
