@antfly/embedded 0.0.0-stage → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,322 @@
1
+ import { C as CheckReport, S as StableSnapshotReport, R as RestoreOptions, N as NativeLibrary, I as InferenceOptions, J as JsonInput, P as PullProgress, D as Database, U as Uint64Like } from './database-BY3WSLgt.cjs';
2
+ export { a as Capabilities, b as CompactReport, G as GraphDirection, c as InferenceMode, d as InferenceStatus, L as LibraryNotFoundError, e as LibrarySource, f as MIN_THREAD_STACK_SIZE, M as MemoryAdmissionStats, O as OpenMode, g as OpenOptions, h as PendingWorkStatus, i as Profile, j as ReplayGeneratedEnrichmentsResult, k as ResolvedLibrary, l as SUPPORTED_ABI_VERSION, m as Status, n as Storage, o as StorageStatus, T as THREADING_SERIALIZED, p as TTLCleanupOptions, q as TxnStatus, r as UnsupportedPlatformError, V as VacuumReport, W as WriteIntent, s as create, t as createHosted, u as createWithOptions, v as embeddedPlatformPackageName, w as open, x as openHosted, y as openReadonly, z as openStatusOnly, A as openWithOptions, B as platformLibraryFileName, E as resolveLibrary } from './database-BY3WSLgt.cjs';
3
+ import 'koffi';
4
+
5
+ /** Thrown by validateAbi() when the loaded libantfly does not match the header this binding was written against. */
6
+ declare class AbiMismatchError extends Error {
7
+ constructor(message: string);
8
+ }
9
+ /** Returns the loaded Antfly C ABI version (antfly_abi_version()). */
10
+ declare function abiVersion(): number;
11
+ /**
12
+ * Reports the loaded libantfly threading contract, like sqlite3_threadsafe().
13
+ * Always THREADING_SERIALIZED for the current libantfly.
14
+ */
15
+ declare function threadingMode(): number;
16
+ /**
17
+ * Verifies that the loaded C library matches the header this binding was
18
+ * compiled against: antfly_abi_version() and the antfly_open_options struct
19
+ * size. Called automatically by every open/create/checkFile call; exposed so
20
+ * applications can fail fast at startup too.
21
+ */
22
+ declare function validateAbi(): void;
23
+ /**
24
+ * Verifies that the loaded C library's antfly_inference_options struct size
25
+ * matches the header this binding was compiled against, like validateAbi()
26
+ * does for antfly_open_options. Called automatically by Inference.open();
27
+ * exposed so applications can fail fast at startup too.
28
+ */
29
+ declare function validateInferenceAbi(): void;
30
+
31
+ /**
32
+ * Stable Antfly C ABI error codes (antfly_error_code in antfly.h). Values and
33
+ * descriptions mirror go/pkg/embedded/errors.go so behavior stays identical
34
+ * across bindings; a conformance/errors test cross-checks these against the
35
+ * loaded library's antfly_error_code_name/antfly_error_code_description.
36
+ */
37
+ declare enum ErrorCode {
38
+ OK = 0,
39
+ InvalidArgument = 1,
40
+ NotFound = 2,
41
+ VersionConflict = 3,
42
+ IntentConflict = 4,
43
+ TxnNotFound = 5,
44
+ Busy = 6,
45
+ /**
46
+ * The operation crossed its publication point, but crash durability could
47
+ * not be confirmed. Inspect the destination; do not retry automatically.
48
+ */
49
+ OutcomeUnknown = 7,
50
+ /**
51
+ * The operation requires a capability unavailable on this platform or
52
+ * filesystem. Retrying unchanged will not succeed.
53
+ */
54
+ Unsupported = 8,
55
+ /**
56
+ * A bounded drain such as runUntilIdle detected a managed index making no
57
+ * forward progress and gave up.
58
+ */
59
+ Stalled = 9,
60
+ /**
61
+ * The caller cancelled the call by returning false from its progress or
62
+ * stream callback (Inference.pull()'s onProgress, Inference.generateStream()'s
63
+ * onChunk).
64
+ */
65
+ Cancelled = 10,
66
+ Internal = 255
67
+ }
68
+ /** Stable symbolic C ABI name for code, e.g. "ANTFLY_BUSY". */
69
+ declare function errorCodeName(code: number): string;
70
+ /** Short stable description for code. */
71
+ declare function errorCodeDescription(code: number): string;
72
+ /**
73
+ * AntflyError wraps a stable Antfly C ABI error code. `.code` is the numeric
74
+ * antfly_error_code, `.codeName` is its stable symbolic name (e.g.
75
+ * "ANTFLY_BUSY"), matching antfly_error_code_name.
76
+ */
77
+ declare class AntflyError extends Error {
78
+ readonly code: number;
79
+ readonly codeName: string;
80
+ /**
81
+ * Parsed JSON error body, when the failing call returned one. Currently
82
+ * only Inference calls populate this (embed/rerank/.../pull): libantfly
83
+ * always fills their antfly_buffer output with {"error": ..., "message":
84
+ * ...} on failure, even though the call also returns a non-OK error code.
85
+ */
86
+ body?: unknown;
87
+ constructor(code: number, message?: string);
88
+ }
89
+ declare class InvalidArgumentError extends AntflyError {
90
+ constructor(message?: string);
91
+ }
92
+ declare class NotFoundError extends AntflyError {
93
+ constructor(message?: string);
94
+ }
95
+ declare class VersionConflictError extends AntflyError {
96
+ constructor(message?: string);
97
+ }
98
+ declare class IntentConflictError extends AntflyError {
99
+ constructor(message?: string);
100
+ }
101
+ declare class TxnNotFoundError extends AntflyError {
102
+ constructor(message?: string);
103
+ }
104
+ declare class BusyError extends AntflyError {
105
+ constructor(message?: string);
106
+ }
107
+ declare class OutcomeUnknownError extends AntflyError {
108
+ constructor(message?: string);
109
+ }
110
+ declare class UnsupportedError extends AntflyError {
111
+ constructor(message?: string);
112
+ }
113
+ declare class StalledError extends AntflyError {
114
+ constructor(message?: string);
115
+ }
116
+ declare class CancelledError extends AntflyError {
117
+ constructor(message?: string);
118
+ }
119
+ declare class InternalError extends AntflyError {
120
+ constructor(message?: string);
121
+ }
122
+
123
+ /** Runs Lite integrity checks for path without opening a database handle and returns the raw JSON result. */
124
+ declare function checkFileRaw(path: string): Promise<Buffer>;
125
+ /** Runs Lite integrity checks for path without opening a database handle and returns the typed result. */
126
+ declare function checkFile(path: string): Promise<CheckReport>;
127
+ /**
128
+ * Opens srcPath read-only, copies a stable Lite snapshot to destPath, and
129
+ * returns the raw JSON result. Neither path needs an open handle.
130
+ */
131
+ declare function copyStableSnapshotFileRaw(srcPath: string, destPath: string, replace: boolean): Promise<Buffer>;
132
+ /** Typed form of copyStableSnapshotFileRaw. */
133
+ declare function copyStableSnapshotFile(srcPath: string, destPath: string, replace: boolean): Promise<StableSnapshotReport>;
134
+ /**
135
+ * Creates a database at path from a portable Antfly backup archive, of the
136
+ * storage kind opts.storage selects (default Storage.Lite). A backup of
137
+ * either kind restores into either kind. For Lite destinations path must end
138
+ * with .aflite (checked client-side only). OutcomeUnknown means the
139
+ * destination was published but crash durability could not be confirmed;
140
+ * inspect it and do not retry automatically.
141
+ */
142
+ declare function restore(path: string, backup: Uint8Array, opts?: RestoreOptions): Promise<void>;
143
+ /**
144
+ * restore() reading the archive from backupPath. For Lite destinations it
145
+ * streams with bounded memory use. Busy means the source changed during
146
+ * streaming or the source/destination is concurrently locked; retry after
147
+ * the files are stable and no writer is active. Unsupported means the source
148
+ * filesystem lacks required advisory locking; copy the archive to a
149
+ * supported local filesystem.
150
+ */
151
+ declare function restoreFile(path: string, backupPath: string, opts?: RestoreOptions): Promise<void>;
152
+ /** Decodes a base64 artifact ID without opening a database. */
153
+ declare function decodeArtifactIdRaw(artifactIdBase64: string): Promise<Buffer>;
154
+ /** Typed form of decodeArtifactIdRaw. */
155
+ declare function decodeArtifactId(artifactIdBase64: string): Promise<unknown>;
156
+
157
+ /**
158
+ * Return false from a pull() onProgress or generateStream() onChunk
159
+ * callback to cancel; anything else (including void/undefined) continues.
160
+ */
161
+ type CallbackResult = boolean | void;
162
+ /**
163
+ * An embedded Antfly inference runtime handle: no database, just model
164
+ * inference (embed, rerank, chunk, generate, rewrite, decide, extract, read/OCR,
165
+ * transcribe) via the libantfly antfly_inference_* C ABI. Models load on
166
+ * first use and stay cached until close().
167
+ *
168
+ * Every JSON call except pull() and generateStream() is async (runs on
169
+ * koffi's worker thread pool via fn.async(...), like Database) and has the
170
+ * same close semantics: close() waits for every call this binding has
171
+ * dispatched before freeing the native handle, and rejects new calls
172
+ * immediately once close() has started.
173
+ *
174
+ * pull() and generateStream() are the exceptions: both run synchronously
175
+ * on the calling (JS main) thread and block the event loop for their
176
+ * duration. This is required for their callbacks (pull's onProgress,
177
+ * generateStream's onChunk) -- JS execution is single-threaded, so a
178
+ * callback koffi delivers from a background thread (as happens for a call
179
+ * made via fn.async(...), which runs on koffi's worker thread pool) has to
180
+ * be queued back onto the JS main thread rather than invoked in a true
181
+ * blocking round-trip; per koffi's docs that queuing only runs "as soon as
182
+ * the event loop has a chance to run", which could reorder or delay a
183
+ * report arbitrarily relative to the (already-freed) antfly_slice data it
184
+ * points to, and could even deadlock if the main thread never yields.
185
+ * Calling synchronously keeps the whole call, including every callback
186
+ * invocation, on one OS thread throughout, matching antfly.h's "called on
187
+ * the calling thread" guarantee exactly. See README.md's "Embedded
188
+ * inference" section.
189
+ */
190
+ declare class Inference implements AsyncDisposable {
191
+ #private;
192
+ /** @internal use Inference.open() instead of the constructor. */
193
+ constructor(native: NativeLibrary, handle: unknown);
194
+ /** Starts the embedded inference runtime with no database. Returns UnsupportedError if this build does not link the inference runtime or it cannot start. */
195
+ static open(options?: InferenceOptions): Promise<Inference>;
196
+ /** Idempotent; waits for in-flight calls before freeing the native handle. Calls made after close() rejects with InvalidArgumentError. */
197
+ close(): Promise<void>;
198
+ [Symbol.asyncDispose](): Promise<void>;
199
+ embedRaw(request: JsonInput): Promise<Buffer>;
200
+ embed(request: JsonInput): Promise<unknown>;
201
+ rerankRaw(request: JsonInput): Promise<Buffer>;
202
+ rerank(request: JsonInput): Promise<unknown>;
203
+ chunkRaw(request: JsonInput): Promise<Buffer>;
204
+ chunk(request: JsonInput): Promise<unknown>;
205
+ /** A generate request with "stream": true fails with InvalidArgumentError; responses are always complete. Use generateStream() to stream. */
206
+ generateRaw(request: JsonInput): Promise<Buffer>;
207
+ generate(request: JsonInput): Promise<unknown>;
208
+ /**
209
+ * Streams a generate request (antfly_inference_generate_stream_json): the
210
+ * same request body as generate(), with "stream" set for you. onChunk is
211
+ * called synchronously, on the calling thread, once per streamed chunk
212
+ * (a parsed "chat.completion.chunk" JSON object), as the model produces
213
+ * tokens.
214
+ *
215
+ * Returning `false` from onChunk stops generation early; the call then
216
+ * rejects with CancelledError. A thrown error also stops generation and
217
+ * is rethrown from this call (generation does not continue in the
218
+ * background). generateStream() runs synchronously on the JS thread and
219
+ * blocks the event loop for its duration -- see the class docstring for
220
+ * why (the same koffi callback-threading constraint as pull()); this is
221
+ * the reason this binding offers a callback, not an async iterator.
222
+ *
223
+ * A request rejected before generation starts (e.g. a missing model)
224
+ * rejects the same way generate() does, with the JSON error body on
225
+ * `.body`. A failure mid-stream rejects InternalError with
226
+ * `.body.error === "STREAM_FAILED"`.
227
+ */
228
+ generateStreamRaw(request: JsonInput, onChunk: (chunkJson: Buffer) => CallbackResult): Promise<Buffer>;
229
+ generateStream(request: JsonInput, onChunk: (chunk: unknown) => CallbackResult): Promise<unknown>;
230
+ /** Up to 128 non-streaming generate requests in one call; per-item failures are reported in the response. */
231
+ generateBatchRaw(request: JsonInput): Promise<Buffer>;
232
+ generateBatch(request: JsonInput): Promise<unknown>;
233
+ rewriteRaw(request: JsonInput): Promise<Buffer>;
234
+ rewrite(request: JsonInput): Promise<unknown>;
235
+ /** Named choice, ordinal score, and Boolean questions using DecideRequest JSON. */
236
+ decideRaw(request: JsonInput): Promise<Buffer>;
237
+ /** Parsed DecideResponse from the same contract as POST /ai/v1/decisions. */
238
+ decide(request: JsonInput): Promise<unknown>;
239
+ extractRaw(request: JsonInput): Promise<Buffer>;
240
+ extract(request: JsonInput): Promise<unknown>;
241
+ /** OCR. */
242
+ readRaw(request: JsonInput): Promise<Buffer>;
243
+ read(request: JsonInput): Promise<unknown>;
244
+ transcribeRaw(request: JsonInput): Promise<Buffer>;
245
+ transcribe(request: JsonInput): Promise<unknown>;
246
+ /** The installed models, as returned by GET /ai/v1/models. */
247
+ listModelsRaw(): Promise<Buffer>;
248
+ listModels(): Promise<unknown>;
249
+ /**
250
+ * Downloads a model from the Hugging Face Hub into the handle's models
251
+ * directory, like `antfly inference pull`. request: {"model": "owner/name[:variant]",
252
+ * required; "variants": [...]; "token": "..." (default $HF_TOKEN);
253
+ * "tasks"/"capabilities" to override the model manifest; "projector":
254
+ * "auto" | "none" | "match"; "max_artifact_bytes"/"max_model_bytes"}.
255
+ *
256
+ * onProgress (optional) is called synchronously, on the calling thread,
257
+ * as each file starts, every 16 MiB, and as it completes; see the class
258
+ * docstring for why pull() itself runs synchronously (blocking the event
259
+ * loop) rather than on koffi's async worker pool. Returning `false` from
260
+ * onProgress cancels the pull -- the call then rejects with
261
+ * CancelledError, and completed files stay staged, so a later pull()
262
+ * for the same model resumes rather than restarts. A thrown error also
263
+ * cancels the pull and is rethrown from this call.
264
+ *
265
+ * `signal` (optional) is a best-effort, honestly-limited cancellation
266
+ * knob: because pull() blocks the JS thread for its whole duration,
267
+ * there is no way to interrupt it asynchronously from the outside the
268
+ * way `fetch(url, { signal })` can. An already-aborted signal rejects
269
+ * immediately without starting the pull; otherwise the signal is polled
270
+ * only at the same report points as onProgress (each file start, every
271
+ * 16 MiB, file end) -- an abort in between those points is not observed
272
+ * until the next one. Prefer returning `false` from onProgress when you
273
+ * need precise control.
274
+ *
275
+ * A model missing from the hub rejects with NotFoundError, a bad request
276
+ * or a model over the size limits with InvalidArgumentError, and a
277
+ * network or hub failure with BusyError. close() waits for a pull in
278
+ * progress.
279
+ */
280
+ pullRaw(request: JsonInput, onProgress?: (progress: PullProgress) => CallbackResult, signal?: AbortSignal): Promise<Buffer>;
281
+ pull(request: JsonInput, onProgress?: (progress: PullProgress) => CallbackResult, signal?: AbortSignal): Promise<unknown>;
282
+ }
283
+
284
+ interface SqlDiagnostic {
285
+ code: string;
286
+ message: string;
287
+ hint?: string;
288
+ retryable?: boolean;
289
+ }
290
+ declare class SqlError extends Error {
291
+ readonly diagnostic: SqlDiagnostic;
292
+ readonly transactionId?: string | undefined;
293
+ readonly sqlstate: string;
294
+ constructor(diagnostic: SqlDiagnostic, transactionId?: string | undefined);
295
+ }
296
+ interface SqlColumn {
297
+ name: string;
298
+ type: string;
299
+ }
300
+ interface SqlResult<Row = Record<string, unknown>> {
301
+ columns: readonly SqlColumn[];
302
+ rows: Row[];
303
+ rowsAffected: bigint;
304
+ commandTag: string;
305
+ }
306
+
307
+ /** One SQL session. Use a separate Connection for concurrently active transactions. */
308
+ declare class Connection {
309
+ #private;
310
+ readonly database: Database;
311
+ readonly session: Uint64Like;
312
+ private readonly direct;
313
+ private constructor();
314
+ static open(database: Database): Promise<Connection>;
315
+ execute<Row = Record<string, unknown>>(statement: string, parameters?: readonly unknown[]): Promise<SqlResult<Row>>;
316
+ query<Row = Record<string, unknown>>(statement: string, parameters?: readonly unknown[]): Promise<SqlResult<Row>>;
317
+ stream<Row = Record<string, unknown>>(statement: string, parameters?: readonly unknown[], chunkSize?: number): AsyncGenerator<SqlResult<Row>>;
318
+ transaction<T>(operation: (transaction: Connection) => Promise<T>): Promise<T>;
319
+ close(): Promise<void>;
320
+ }
321
+
322
+ export { AbiMismatchError, AntflyError, BusyError, CancelledError, CheckReport, Connection, Database, ErrorCode, Inference, InferenceOptions, IntentConflictError, InternalError, InvalidArgumentError, JsonInput, NotFoundError, OutcomeUnknownError, PullProgress, RestoreOptions, type SqlColumn, SqlError, type SqlResult, StableSnapshotReport, StalledError, TxnNotFoundError, Uint64Like, UnsupportedError, VersionConflictError, abiVersion, checkFile, checkFileRaw, copyStableSnapshotFile, copyStableSnapshotFileRaw, decodeArtifactId, decodeArtifactIdRaw, errorCodeDescription, errorCodeName, restore, restoreFile, threadingMode, validateAbi, validateInferenceAbi };
@@ -0,0 +1,322 @@
1
+ import { C as CheckReport, S as StableSnapshotReport, R as RestoreOptions, N as NativeLibrary, I as InferenceOptions, J as JsonInput, P as PullProgress, D as Database, U as Uint64Like } from './database-BY3WSLgt.js';
2
+ export { a as Capabilities, b as CompactReport, G as GraphDirection, c as InferenceMode, d as InferenceStatus, L as LibraryNotFoundError, e as LibrarySource, f as MIN_THREAD_STACK_SIZE, M as MemoryAdmissionStats, O as OpenMode, g as OpenOptions, h as PendingWorkStatus, i as Profile, j as ReplayGeneratedEnrichmentsResult, k as ResolvedLibrary, l as SUPPORTED_ABI_VERSION, m as Status, n as Storage, o as StorageStatus, T as THREADING_SERIALIZED, p as TTLCleanupOptions, q as TxnStatus, r as UnsupportedPlatformError, V as VacuumReport, W as WriteIntent, s as create, t as createHosted, u as createWithOptions, v as embeddedPlatformPackageName, w as open, x as openHosted, y as openReadonly, z as openStatusOnly, A as openWithOptions, B as platformLibraryFileName, E as resolveLibrary } from './database-BY3WSLgt.js';
3
+ import 'koffi';
4
+
5
+ /** Thrown by validateAbi() when the loaded libantfly does not match the header this binding was written against. */
6
+ declare class AbiMismatchError extends Error {
7
+ constructor(message: string);
8
+ }
9
+ /** Returns the loaded Antfly C ABI version (antfly_abi_version()). */
10
+ declare function abiVersion(): number;
11
+ /**
12
+ * Reports the loaded libantfly threading contract, like sqlite3_threadsafe().
13
+ * Always THREADING_SERIALIZED for the current libantfly.
14
+ */
15
+ declare function threadingMode(): number;
16
+ /**
17
+ * Verifies that the loaded C library matches the header this binding was
18
+ * compiled against: antfly_abi_version() and the antfly_open_options struct
19
+ * size. Called automatically by every open/create/checkFile call; exposed so
20
+ * applications can fail fast at startup too.
21
+ */
22
+ declare function validateAbi(): void;
23
+ /**
24
+ * Verifies that the loaded C library's antfly_inference_options struct size
25
+ * matches the header this binding was compiled against, like validateAbi()
26
+ * does for antfly_open_options. Called automatically by Inference.open();
27
+ * exposed so applications can fail fast at startup too.
28
+ */
29
+ declare function validateInferenceAbi(): void;
30
+
31
+ /**
32
+ * Stable Antfly C ABI error codes (antfly_error_code in antfly.h). Values and
33
+ * descriptions mirror go/pkg/embedded/errors.go so behavior stays identical
34
+ * across bindings; a conformance/errors test cross-checks these against the
35
+ * loaded library's antfly_error_code_name/antfly_error_code_description.
36
+ */
37
+ declare enum ErrorCode {
38
+ OK = 0,
39
+ InvalidArgument = 1,
40
+ NotFound = 2,
41
+ VersionConflict = 3,
42
+ IntentConflict = 4,
43
+ TxnNotFound = 5,
44
+ Busy = 6,
45
+ /**
46
+ * The operation crossed its publication point, but crash durability could
47
+ * not be confirmed. Inspect the destination; do not retry automatically.
48
+ */
49
+ OutcomeUnknown = 7,
50
+ /**
51
+ * The operation requires a capability unavailable on this platform or
52
+ * filesystem. Retrying unchanged will not succeed.
53
+ */
54
+ Unsupported = 8,
55
+ /**
56
+ * A bounded drain such as runUntilIdle detected a managed index making no
57
+ * forward progress and gave up.
58
+ */
59
+ Stalled = 9,
60
+ /**
61
+ * The caller cancelled the call by returning false from its progress or
62
+ * stream callback (Inference.pull()'s onProgress, Inference.generateStream()'s
63
+ * onChunk).
64
+ */
65
+ Cancelled = 10,
66
+ Internal = 255
67
+ }
68
+ /** Stable symbolic C ABI name for code, e.g. "ANTFLY_BUSY". */
69
+ declare function errorCodeName(code: number): string;
70
+ /** Short stable description for code. */
71
+ declare function errorCodeDescription(code: number): string;
72
+ /**
73
+ * AntflyError wraps a stable Antfly C ABI error code. `.code` is the numeric
74
+ * antfly_error_code, `.codeName` is its stable symbolic name (e.g.
75
+ * "ANTFLY_BUSY"), matching antfly_error_code_name.
76
+ */
77
+ declare class AntflyError extends Error {
78
+ readonly code: number;
79
+ readonly codeName: string;
80
+ /**
81
+ * Parsed JSON error body, when the failing call returned one. Currently
82
+ * only Inference calls populate this (embed/rerank/.../pull): libantfly
83
+ * always fills their antfly_buffer output with {"error": ..., "message":
84
+ * ...} on failure, even though the call also returns a non-OK error code.
85
+ */
86
+ body?: unknown;
87
+ constructor(code: number, message?: string);
88
+ }
89
+ declare class InvalidArgumentError extends AntflyError {
90
+ constructor(message?: string);
91
+ }
92
+ declare class NotFoundError extends AntflyError {
93
+ constructor(message?: string);
94
+ }
95
+ declare class VersionConflictError extends AntflyError {
96
+ constructor(message?: string);
97
+ }
98
+ declare class IntentConflictError extends AntflyError {
99
+ constructor(message?: string);
100
+ }
101
+ declare class TxnNotFoundError extends AntflyError {
102
+ constructor(message?: string);
103
+ }
104
+ declare class BusyError extends AntflyError {
105
+ constructor(message?: string);
106
+ }
107
+ declare class OutcomeUnknownError extends AntflyError {
108
+ constructor(message?: string);
109
+ }
110
+ declare class UnsupportedError extends AntflyError {
111
+ constructor(message?: string);
112
+ }
113
+ declare class StalledError extends AntflyError {
114
+ constructor(message?: string);
115
+ }
116
+ declare class CancelledError extends AntflyError {
117
+ constructor(message?: string);
118
+ }
119
+ declare class InternalError extends AntflyError {
120
+ constructor(message?: string);
121
+ }
122
+
123
+ /** Runs Lite integrity checks for path without opening a database handle and returns the raw JSON result. */
124
+ declare function checkFileRaw(path: string): Promise<Buffer>;
125
+ /** Runs Lite integrity checks for path without opening a database handle and returns the typed result. */
126
+ declare function checkFile(path: string): Promise<CheckReport>;
127
+ /**
128
+ * Opens srcPath read-only, copies a stable Lite snapshot to destPath, and
129
+ * returns the raw JSON result. Neither path needs an open handle.
130
+ */
131
+ declare function copyStableSnapshotFileRaw(srcPath: string, destPath: string, replace: boolean): Promise<Buffer>;
132
+ /** Typed form of copyStableSnapshotFileRaw. */
133
+ declare function copyStableSnapshotFile(srcPath: string, destPath: string, replace: boolean): Promise<StableSnapshotReport>;
134
+ /**
135
+ * Creates a database at path from a portable Antfly backup archive, of the
136
+ * storage kind opts.storage selects (default Storage.Lite). A backup of
137
+ * either kind restores into either kind. For Lite destinations path must end
138
+ * with .aflite (checked client-side only). OutcomeUnknown means the
139
+ * destination was published but crash durability could not be confirmed;
140
+ * inspect it and do not retry automatically.
141
+ */
142
+ declare function restore(path: string, backup: Uint8Array, opts?: RestoreOptions): Promise<void>;
143
+ /**
144
+ * restore() reading the archive from backupPath. For Lite destinations it
145
+ * streams with bounded memory use. Busy means the source changed during
146
+ * streaming or the source/destination is concurrently locked; retry after
147
+ * the files are stable and no writer is active. Unsupported means the source
148
+ * filesystem lacks required advisory locking; copy the archive to a
149
+ * supported local filesystem.
150
+ */
151
+ declare function restoreFile(path: string, backupPath: string, opts?: RestoreOptions): Promise<void>;
152
+ /** Decodes a base64 artifact ID without opening a database. */
153
+ declare function decodeArtifactIdRaw(artifactIdBase64: string): Promise<Buffer>;
154
+ /** Typed form of decodeArtifactIdRaw. */
155
+ declare function decodeArtifactId(artifactIdBase64: string): Promise<unknown>;
156
+
157
+ /**
158
+ * Return false from a pull() onProgress or generateStream() onChunk
159
+ * callback to cancel; anything else (including void/undefined) continues.
160
+ */
161
+ type CallbackResult = boolean | void;
162
+ /**
163
+ * An embedded Antfly inference runtime handle: no database, just model
164
+ * inference (embed, rerank, chunk, generate, rewrite, decide, extract, read/OCR,
165
+ * transcribe) via the libantfly antfly_inference_* C ABI. Models load on
166
+ * first use and stay cached until close().
167
+ *
168
+ * Every JSON call except pull() and generateStream() is async (runs on
169
+ * koffi's worker thread pool via fn.async(...), like Database) and has the
170
+ * same close semantics: close() waits for every call this binding has
171
+ * dispatched before freeing the native handle, and rejects new calls
172
+ * immediately once close() has started.
173
+ *
174
+ * pull() and generateStream() are the exceptions: both run synchronously
175
+ * on the calling (JS main) thread and block the event loop for their
176
+ * duration. This is required for their callbacks (pull's onProgress,
177
+ * generateStream's onChunk) -- JS execution is single-threaded, so a
178
+ * callback koffi delivers from a background thread (as happens for a call
179
+ * made via fn.async(...), which runs on koffi's worker thread pool) has to
180
+ * be queued back onto the JS main thread rather than invoked in a true
181
+ * blocking round-trip; per koffi's docs that queuing only runs "as soon as
182
+ * the event loop has a chance to run", which could reorder or delay a
183
+ * report arbitrarily relative to the (already-freed) antfly_slice data it
184
+ * points to, and could even deadlock if the main thread never yields.
185
+ * Calling synchronously keeps the whole call, including every callback
186
+ * invocation, on one OS thread throughout, matching antfly.h's "called on
187
+ * the calling thread" guarantee exactly. See README.md's "Embedded
188
+ * inference" section.
189
+ */
190
+ declare class Inference implements AsyncDisposable {
191
+ #private;
192
+ /** @internal use Inference.open() instead of the constructor. */
193
+ constructor(native: NativeLibrary, handle: unknown);
194
+ /** Starts the embedded inference runtime with no database. Returns UnsupportedError if this build does not link the inference runtime or it cannot start. */
195
+ static open(options?: InferenceOptions): Promise<Inference>;
196
+ /** Idempotent; waits for in-flight calls before freeing the native handle. Calls made after close() rejects with InvalidArgumentError. */
197
+ close(): Promise<void>;
198
+ [Symbol.asyncDispose](): Promise<void>;
199
+ embedRaw(request: JsonInput): Promise<Buffer>;
200
+ embed(request: JsonInput): Promise<unknown>;
201
+ rerankRaw(request: JsonInput): Promise<Buffer>;
202
+ rerank(request: JsonInput): Promise<unknown>;
203
+ chunkRaw(request: JsonInput): Promise<Buffer>;
204
+ chunk(request: JsonInput): Promise<unknown>;
205
+ /** A generate request with "stream": true fails with InvalidArgumentError; responses are always complete. Use generateStream() to stream. */
206
+ generateRaw(request: JsonInput): Promise<Buffer>;
207
+ generate(request: JsonInput): Promise<unknown>;
208
+ /**
209
+ * Streams a generate request (antfly_inference_generate_stream_json): the
210
+ * same request body as generate(), with "stream" set for you. onChunk is
211
+ * called synchronously, on the calling thread, once per streamed chunk
212
+ * (a parsed "chat.completion.chunk" JSON object), as the model produces
213
+ * tokens.
214
+ *
215
+ * Returning `false` from onChunk stops generation early; the call then
216
+ * rejects with CancelledError. A thrown error also stops generation and
217
+ * is rethrown from this call (generation does not continue in the
218
+ * background). generateStream() runs synchronously on the JS thread and
219
+ * blocks the event loop for its duration -- see the class docstring for
220
+ * why (the same koffi callback-threading constraint as pull()); this is
221
+ * the reason this binding offers a callback, not an async iterator.
222
+ *
223
+ * A request rejected before generation starts (e.g. a missing model)
224
+ * rejects the same way generate() does, with the JSON error body on
225
+ * `.body`. A failure mid-stream rejects InternalError with
226
+ * `.body.error === "STREAM_FAILED"`.
227
+ */
228
+ generateStreamRaw(request: JsonInput, onChunk: (chunkJson: Buffer) => CallbackResult): Promise<Buffer>;
229
+ generateStream(request: JsonInput, onChunk: (chunk: unknown) => CallbackResult): Promise<unknown>;
230
+ /** Up to 128 non-streaming generate requests in one call; per-item failures are reported in the response. */
231
+ generateBatchRaw(request: JsonInput): Promise<Buffer>;
232
+ generateBatch(request: JsonInput): Promise<unknown>;
233
+ rewriteRaw(request: JsonInput): Promise<Buffer>;
234
+ rewrite(request: JsonInput): Promise<unknown>;
235
+ /** Named choice, ordinal score, and Boolean questions using DecideRequest JSON. */
236
+ decideRaw(request: JsonInput): Promise<Buffer>;
237
+ /** Parsed DecideResponse from the same contract as POST /ai/v1/decisions. */
238
+ decide(request: JsonInput): Promise<unknown>;
239
+ extractRaw(request: JsonInput): Promise<Buffer>;
240
+ extract(request: JsonInput): Promise<unknown>;
241
+ /** OCR. */
242
+ readRaw(request: JsonInput): Promise<Buffer>;
243
+ read(request: JsonInput): Promise<unknown>;
244
+ transcribeRaw(request: JsonInput): Promise<Buffer>;
245
+ transcribe(request: JsonInput): Promise<unknown>;
246
+ /** The installed models, as returned by GET /ai/v1/models. */
247
+ listModelsRaw(): Promise<Buffer>;
248
+ listModels(): Promise<unknown>;
249
+ /**
250
+ * Downloads a model from the Hugging Face Hub into the handle's models
251
+ * directory, like `antfly inference pull`. request: {"model": "owner/name[:variant]",
252
+ * required; "variants": [...]; "token": "..." (default $HF_TOKEN);
253
+ * "tasks"/"capabilities" to override the model manifest; "projector":
254
+ * "auto" | "none" | "match"; "max_artifact_bytes"/"max_model_bytes"}.
255
+ *
256
+ * onProgress (optional) is called synchronously, on the calling thread,
257
+ * as each file starts, every 16 MiB, and as it completes; see the class
258
+ * docstring for why pull() itself runs synchronously (blocking the event
259
+ * loop) rather than on koffi's async worker pool. Returning `false` from
260
+ * onProgress cancels the pull -- the call then rejects with
261
+ * CancelledError, and completed files stay staged, so a later pull()
262
+ * for the same model resumes rather than restarts. A thrown error also
263
+ * cancels the pull and is rethrown from this call.
264
+ *
265
+ * `signal` (optional) is a best-effort, honestly-limited cancellation
266
+ * knob: because pull() blocks the JS thread for its whole duration,
267
+ * there is no way to interrupt it asynchronously from the outside the
268
+ * way `fetch(url, { signal })` can. An already-aborted signal rejects
269
+ * immediately without starting the pull; otherwise the signal is polled
270
+ * only at the same report points as onProgress (each file start, every
271
+ * 16 MiB, file end) -- an abort in between those points is not observed
272
+ * until the next one. Prefer returning `false` from onProgress when you
273
+ * need precise control.
274
+ *
275
+ * A model missing from the hub rejects with NotFoundError, a bad request
276
+ * or a model over the size limits with InvalidArgumentError, and a
277
+ * network or hub failure with BusyError. close() waits for a pull in
278
+ * progress.
279
+ */
280
+ pullRaw(request: JsonInput, onProgress?: (progress: PullProgress) => CallbackResult, signal?: AbortSignal): Promise<Buffer>;
281
+ pull(request: JsonInput, onProgress?: (progress: PullProgress) => CallbackResult, signal?: AbortSignal): Promise<unknown>;
282
+ }
283
+
284
+ interface SqlDiagnostic {
285
+ code: string;
286
+ message: string;
287
+ hint?: string;
288
+ retryable?: boolean;
289
+ }
290
+ declare class SqlError extends Error {
291
+ readonly diagnostic: SqlDiagnostic;
292
+ readonly transactionId?: string | undefined;
293
+ readonly sqlstate: string;
294
+ constructor(diagnostic: SqlDiagnostic, transactionId?: string | undefined);
295
+ }
296
+ interface SqlColumn {
297
+ name: string;
298
+ type: string;
299
+ }
300
+ interface SqlResult<Row = Record<string, unknown>> {
301
+ columns: readonly SqlColumn[];
302
+ rows: Row[];
303
+ rowsAffected: bigint;
304
+ commandTag: string;
305
+ }
306
+
307
+ /** One SQL session. Use a separate Connection for concurrently active transactions. */
308
+ declare class Connection {
309
+ #private;
310
+ readonly database: Database;
311
+ readonly session: Uint64Like;
312
+ private readonly direct;
313
+ private constructor();
314
+ static open(database: Database): Promise<Connection>;
315
+ execute<Row = Record<string, unknown>>(statement: string, parameters?: readonly unknown[]): Promise<SqlResult<Row>>;
316
+ query<Row = Record<string, unknown>>(statement: string, parameters?: readonly unknown[]): Promise<SqlResult<Row>>;
317
+ stream<Row = Record<string, unknown>>(statement: string, parameters?: readonly unknown[], chunkSize?: number): AsyncGenerator<SqlResult<Row>>;
318
+ transaction<T>(operation: (transaction: Connection) => Promise<T>): Promise<T>;
319
+ close(): Promise<void>;
320
+ }
321
+
322
+ export { AbiMismatchError, AntflyError, BusyError, CancelledError, CheckReport, Connection, Database, ErrorCode, Inference, InferenceOptions, IntentConflictError, InternalError, InvalidArgumentError, JsonInput, NotFoundError, OutcomeUnknownError, PullProgress, RestoreOptions, type SqlColumn, SqlError, type SqlResult, StableSnapshotReport, StalledError, TxnNotFoundError, Uint64Like, UnsupportedError, VersionConflictError, abiVersion, checkFile, checkFileRaw, copyStableSnapshotFile, copyStableSnapshotFileRaw, decodeArtifactId, decodeArtifactIdRaw, errorCodeDescription, errorCodeName, restore, restoreFile, threadingMode, validateAbi, validateInferenceAbi };