@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.
- package/LICENSE +202 -0
- package/README.md +454 -2
- package/dist/chunk-ELM44XQ4.js +168 -0
- package/dist/database-BY3WSLgt.d.cts +558 -0
- package/dist/database-BY3WSLgt.d.ts +558 -0
- package/dist/index.cjs +2302 -0
- package/dist/index.d.cts +322 -0
- package/dist/index.d.ts +322 -0
- package/dist/index.js +2057 -0
- package/dist/kysely.cjs +346 -0
- package/dist/kysely.d.cts +28 -0
- package/dist/kysely.d.ts +28 -0
- package/dist/kysely.js +169 -0
- package/package.json +87 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Antfly, Inc.
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,455 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @antfly/embedded
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node.js binding for embedded Antfly databases and inference -- the stable `libantfly` C ABI --
|
|
4
|
+
using [koffi](https://koffi.dev) for FFI (prebuilt binaries, no node-gyp).
|
|
5
|
+
Applications embed a live `.aflite` database directly in the Node process
|
|
6
|
+
instead of talking to the network SDK.
|
|
7
|
+
|
|
8
|
+
**Node-only.** This package uses koffi to load a native shared library and
|
|
9
|
+
does not work in browsers. Antfly Lite also ships a separate WebAssembly
|
|
10
|
+
build for browser use; this package is unrelated to that build.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pnpm add @antfly/embedded
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Published platform packages include the Apache-2.0 `libantfly` library,
|
|
19
|
+
without installing CLI commands or an unused worker executable.
|
|
20
|
+
Prebuilt embedded packages support Linux x86-64 and ARM64 with glibc 2.28
|
|
21
|
+
or newer, and macOS ARM64. Windows, Intel macOS, and Alpine/musl do not
|
|
22
|
+
have prebuilt language packages. The native release archive matrix is
|
|
23
|
+
separate; a source build or native archive does not imply wheel/npm support.
|
|
24
|
+
Source checkouts
|
|
25
|
+
can build the shared library with "Library discovery" below. From the
|
|
26
|
+
`antfly` monorepo source tree, build it
|
|
27
|
+
with `cd zig && zig build lite` (produces `zig/zig-out/lib/libantfly.*`);
|
|
28
|
+
this package does not build it for you.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
import { create, THREADING_SERIALIZED, threadingMode } from "@antfly/embedded";
|
|
34
|
+
|
|
35
|
+
// `await using` calls Symbol.asyncDispose, which closes the handle.
|
|
36
|
+
await using db = await create("my.aflite");
|
|
37
|
+
|
|
38
|
+
await db.batch(
|
|
39
|
+
[{ key: "doc:1", value: { title: "hello", body: "world" } }],
|
|
40
|
+
BigInt(Date.now()) * 1_000_000n // nanoseconds
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
const doc = await db.lookup("doc:1"); // parsed JSON
|
|
44
|
+
const raw = await db.lookupRaw("doc:1"); // raw JSON bytes (Buffer)
|
|
45
|
+
|
|
46
|
+
const hits = await db.search({
|
|
47
|
+
full_text_search: { match: { field: "body", text: "world" } },
|
|
48
|
+
limit: 5,
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
console.log(threadingMode() === THREADING_SERIALIZED); // true
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Without top-level `await using` support, call `close()` explicitly (ideally
|
|
55
|
+
in a `finally` block), or rely on the best-effort `FinalizationRegistry`
|
|
56
|
+
cleanup as a last resort.
|
|
57
|
+
|
|
58
|
+
## Async-first, thread-safe by design
|
|
59
|
+
|
|
60
|
+
Every operation that touches an open handle is **async** and runs on koffi's
|
|
61
|
+
native worker thread pool via `fn.async(...)`, so database work never blocks
|
|
62
|
+
the Node event loop and concurrent calls actually run in parallel. Only cheap
|
|
63
|
+
metadata calls that never touch a handle -- `abiVersion()`, `threadingMode()`,
|
|
64
|
+
`validateAbi()`, `errorCodeName()` / `errorCodeDescription()` -- are
|
|
65
|
+
synchronous.
|
|
66
|
+
|
|
67
|
+
`libantfly` runs in **serialized threading mode** (`antfly_threading_mode()`
|
|
68
|
+
== `THREADING_SERIALIZED`, like `sqlite3_threadsafe()`): any thread may call
|
|
69
|
+
any function on any handle concurrently. Reads (`lookup`, `search`, `scan`,
|
|
70
|
+
`stats`, ...) run in parallel with each other and with writes; writes on one
|
|
71
|
+
handle queue behind each other instead of failing with `BusyError`; and
|
|
72
|
+
schema/index/enrichment changes wait for in-flight calls. See
|
|
73
|
+
`zig/CAPI.md`'s "Thread Safety" section for the full contract. A `Database`
|
|
74
|
+
is safe to share across any number of concurrent async operations -- open one
|
|
75
|
+
handle per file, not one per call.
|
|
76
|
+
|
|
77
|
+
### koffi's worker thread pool size
|
|
78
|
+
|
|
79
|
+
koffi dispatches async calls through Node's native async-work queue, which
|
|
80
|
+
runs on **libuv's shared threadpool** (the same pool used by `fs`, `dns`,
|
|
81
|
+
`zlib`, and `crypto.pbkdf2`). Its default size is 4 threads
|
|
82
|
+
(`UV_THREADPOOL_SIZE`, max 1024). If your application needs more than 4
|
|
83
|
+
truly concurrent native calls in flight (across `@antfly/embedded` and any other
|
|
84
|
+
libuv-threadpool consumer), set `UV_THREADPOOL_SIZE` **before the Node
|
|
85
|
+
process starts** (it cannot be changed at runtime):
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
UV_THREADPOOL_SIZE=16 node app.js
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`koffi.config()` additionally controls per-call memory pool sizing
|
|
92
|
+
(`async_stack_size`, `async_heap_size`, `resident_async_pools`,
|
|
93
|
+
`max_async_calls`) but does not change the number of worker threads; the
|
|
94
|
+
defaults are sufficient for this binding since `antfly_buffer` outputs are a
|
|
95
|
+
small fixed-size struct (the pointed-to bytes are heap-allocated by
|
|
96
|
+
`libantfly`, not stack/heap-marshaled by koffi).
|
|
97
|
+
|
|
98
|
+
### Close semantics
|
|
99
|
+
|
|
100
|
+
`db.close()` is idempotent and safe to call concurrently. It:
|
|
101
|
+
|
|
102
|
+
1. Immediately rejects (with `InvalidArgumentError`) any new call made after
|
|
103
|
+
`close()` has started.
|
|
104
|
+
2. Waits for every call this binding has already dispatched (queued on
|
|
105
|
+
koffi's worker pool, or actively executing) to settle.
|
|
106
|
+
3. Only then calls the native `antfly_db_close`, and marks the handle closed.
|
|
107
|
+
|
|
108
|
+
This extra bookkeeping exists because `antfly_db_close` only drains C calls
|
|
109
|
+
that have already **entered** the library; a koffi async call can be queued
|
|
110
|
+
on the libuv threadpool but not yet dequeued ("entered") when `close()`
|
|
111
|
+
starts. Freeing the handle while such a call is still queued would be a
|
|
112
|
+
use-after-free once that call finally runs. `@antfly/embedded` tracks its own
|
|
113
|
+
in-flight promises (comparable to the Go binding's `sync.RWMutex` held around
|
|
114
|
+
every call, exclusively in `Close`) so this can never happen.
|
|
115
|
+
|
|
116
|
+
`await using` (`Symbol.asyncDispose`) calls `close()` for you. A
|
|
117
|
+
`FinalizationRegistry` also closes the handle as a best-effort fallback if a
|
|
118
|
+
`Database` is garbage-collected without an explicit `close()` -- do not rely
|
|
119
|
+
on this for anything but leak mitigation; it is not deterministic.
|
|
120
|
+
|
|
121
|
+
## Library discovery
|
|
122
|
+
|
|
123
|
+
`@antfly/embedded` resolves the `libantfly` shared library in this order:
|
|
124
|
+
|
|
125
|
+
1. **`ANTFLY_LIBRARY`** environment variable -- an exact file path. Throws if
|
|
126
|
+
the file does not exist (fails loudly rather than silently falling
|
|
127
|
+
through).
|
|
128
|
+
2. **`ANTFLY_LIB_DIR`** environment variable -- a directory expected to
|
|
129
|
+
contain the platform library file (see below). Throws if the file is
|
|
130
|
+
missing from that directory.
|
|
131
|
+
3. The installed Apache **`@antfly/embedded-<platform>`** package's `lib/` directory,
|
|
132
|
+
resolved via `require.resolve`.
|
|
133
|
+
4. **`zig/zig-out/lib/`** found by walking up from this package's own
|
|
134
|
+
directory -- for running against a local `antfly` monorepo source
|
|
135
|
+
checkout.
|
|
136
|
+
5. The bare **system loader name**, resolved by the OS's normal shared
|
|
137
|
+
library search path (`LD_LIBRARY_PATH` / `DYLD_LIBRARY_PATH` / `PATH` /
|
|
138
|
+
rpath), matching the Go binding's fallback.
|
|
139
|
+
|
|
140
|
+
Platform file names: `libantfly.dylib` (macOS), `libantfly.so` (Linux),
|
|
141
|
+
`antfly.dll` (Windows).
|
|
142
|
+
|
|
143
|
+
Call `resolveLibrary()` yourself to see which tier resolved and why, without
|
|
144
|
+
loading the library.
|
|
145
|
+
|
|
146
|
+
### Embedded inference
|
|
147
|
+
|
|
148
|
+
`libantfly` runs inference **in-process**, in the calling process, on every
|
|
149
|
+
backend -- Metal, CUDA, ONNX, and CPU alike -- for both `Database` (with
|
|
150
|
+
`localRuntimeConfigured: true`) and the standalone `Inference` handle below.
|
|
151
|
+
There is no separate worker process and no `ANTFLY_INFERENCE_WORKER`
|
|
152
|
+
variable to configure. This is the trade SQLite makes for extensions that
|
|
153
|
+
touch a GPU driver: a call that reaches the device or driver has no per-call
|
|
154
|
+
abort, so `callTimeoutMs` and `close()` only take effect once the call
|
|
155
|
+
returns, and a driver fault terminates the process. Calls on CPU backends
|
|
156
|
+
still stop cooperatively. (The `antfly` server instead runs these backends
|
|
157
|
+
in a worker process it can kill and restart; a library cannot do that to its
|
|
158
|
+
host program.) See `zig/CAPI.md`'s "Inference In Process" section for the
|
|
159
|
+
full rationale.
|
|
160
|
+
|
|
161
|
+
### `Inference`: embedded inference without a database
|
|
162
|
+
|
|
163
|
+
`Inference.open(options?)` starts the embedded inference runtime with no
|
|
164
|
+
database attached -- models load on first use and stay cached until
|
|
165
|
+
`close()`. Each call sends the request JSON and returns the response JSON of
|
|
166
|
+
the matching `/ai/v1` route of the Antfly inference HTTP API
|
|
167
|
+
(`specs/openapi/inference/api.yaml`):
|
|
168
|
+
|
|
169
|
+
```typescript
|
|
170
|
+
import { Inference } from "@antfly/embedded";
|
|
171
|
+
|
|
172
|
+
const inf = await Inference.open({ modelsDir: "/path/to/models" });
|
|
173
|
+
try {
|
|
174
|
+
const { data } = (await inf.chunk({
|
|
175
|
+
input: "Ants live in colonies. Workers gather food.",
|
|
176
|
+
})) as { data: unknown[] };
|
|
177
|
+
|
|
178
|
+
const embeddings = await inf.embed({ model: "owner/name", input: ["hello"] });
|
|
179
|
+
} finally {
|
|
180
|
+
await inf.close();
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
For decision question types and examples, see the
|
|
185
|
+
[typed decision guide](../../../docs/guides/decisions.md).
|
|
186
|
+
|
|
187
|
+
- **Calls**: `embed`, `rerank`, `chunk`, `generate`, `generateBatch`,
|
|
188
|
+
`rewrite`, `decide`, `extract`, `read` (OCR), `transcribe`, `listModels` -- each with
|
|
189
|
+
a bare form (parsed JSON) and a `...Raw` form (raw `Buffer`), following the
|
|
190
|
+
same convention as `Database`. Binary inputs (images, audio) go inline in
|
|
191
|
+
the request JSON, as base64 or `data:` URIs. Responses are always
|
|
192
|
+
complete: a `generate` request with `"stream": true` rejects with
|
|
193
|
+
`InvalidArgumentError` -- use `generateStream()` to stream.
|
|
194
|
+
- **Errors**: every failed inference call still gets a JSON error body from
|
|
195
|
+
`libantfly` (`{"error": ..., "message": ...}`); this binding folds it into
|
|
196
|
+
the thrown `AntflyError`'s message and exposes the parsed body as
|
|
197
|
+
`.body`, in addition to the usual `.code`/`.codeName`. A model that is not
|
|
198
|
+
installed rejects with `NotFoundError` (`.body.error === "MODEL_NOT_FOUND"`).
|
|
199
|
+
- **`generateStream(request, onChunk)`** streams a generate request (the
|
|
200
|
+
same body as `generate()`, with `"stream"` set for you). `onChunk` is
|
|
201
|
+
called **synchronously, on the calling thread**, once per streamed chunk
|
|
202
|
+
(a parsed `chat.completion.chunk` JSON object). Returning `false` from
|
|
203
|
+
`onChunk` stops generation early and the call rejects with
|
|
204
|
+
`CancelledError`; a thrown error also stops generation and is rethrown.
|
|
205
|
+
Like `pull()` below, `generateStream()` runs synchronously and blocks the
|
|
206
|
+
Node event loop for its duration -- the same koffi callback-threading
|
|
207
|
+
constraint applies, which is why this binding exposes a callback rather
|
|
208
|
+
than an async iterator (an async iterator would need the call running off
|
|
209
|
+
the JS thread, which a koffi callback cannot do safely). `generateStreamRaw`
|
|
210
|
+
gives `onChunk` the raw per-chunk `Buffer` instead of parsed JSON.
|
|
211
|
+
- **`pull(request, onProgress?, signal?)`** downloads a model from the
|
|
212
|
+
Hugging Face Hub into the handle's models directory, like
|
|
213
|
+
`antfly inference pull`: `{ model: "owner/name[:variant]", variants?,
|
|
214
|
+
token?, tasks?, capabilities?, projector?, maxArtifactBytes?,
|
|
215
|
+
maxModelBytes? }` (as request JSON; field names follow the HTTP API, e.g.
|
|
216
|
+
`"model"`). The optional `onProgress` callback is called synchronously, on
|
|
217
|
+
the calling thread, as each file starts, every 16 MiB, and as it
|
|
218
|
+
completes. Returning `false` from `onProgress` cancels the pull -- the
|
|
219
|
+
call then rejects with `CancelledError`, and completed files stay staged,
|
|
220
|
+
so a later `pull()` for the same model resumes rather than restarts; a
|
|
221
|
+
thrown error also cancels the pull and is rethrown. The optional `signal`
|
|
222
|
+
(`AbortSignal`) is a best-effort, honestly-limited convenience on top of
|
|
223
|
+
that: because `pull()` blocks the JS thread for its whole duration, there
|
|
224
|
+
is no way to interrupt it asynchronously the way `fetch(url, { signal })`
|
|
225
|
+
can. An already-aborted signal rejects before the pull starts; otherwise
|
|
226
|
+
it is only checked at the same report points as `onProgress` -- prefer
|
|
227
|
+
returning `false` from `onProgress` when you need precise control.
|
|
228
|
+
Unlike every other `Inference`/`Database` call, **`pull()` runs
|
|
229
|
+
synchronously and blocks the Node event loop** for its duration -- this is
|
|
230
|
+
intentional: JS execution is single-threaded, and a callback koffi
|
|
231
|
+
delivers from a background thread (as happens for a call dispatched via
|
|
232
|
+
`fn.async(...)`, which runs on koffi's worker thread pool) has to be
|
|
233
|
+
queued back onto the JS main thread rather than invoked as a true
|
|
234
|
+
blocking round-trip; per koffi's docs that queuing only runs "as soon as
|
|
235
|
+
the event loop has a chance to run", which could reorder or delay a
|
|
236
|
+
report arbitrarily relative to the (already-freed) native data it points
|
|
237
|
+
to, or even deadlock. Calling synchronously keeps the whole call,
|
|
238
|
+
including every callback invocation, on one OS thread throughout,
|
|
239
|
+
matching the C API's "called on the calling thread" guarantee exactly.
|
|
240
|
+
`close()` waits for a pull in progress.
|
|
241
|
+
- **Options**: `InferenceOptions` -- `modelsDir` (defaults to
|
|
242
|
+
`$ANTFLY_INFERENCE_MODELS_DIR`, else `~/.antfly/inference/models`),
|
|
243
|
+
the same `*BudgetMb` resource knobs as `Database`'s `OpenOptions`, and
|
|
244
|
+
`callTimeoutMs` (a deadline per call; 0 means none).
|
|
245
|
+
- **Lifecycle**: `close()` is idempotent, safe to call concurrently, and
|
|
246
|
+
waits for in-flight calls; `Inference` implements `AsyncDisposable`
|
|
247
|
+
(`await using`), same as `Database`.
|
|
248
|
+
|
|
249
|
+
## ABI validation
|
|
250
|
+
|
|
251
|
+
`validateAbi()` checks that the loaded library's `antfly_abi_version()`
|
|
252
|
+
(expected: 2) and `antfly_open_options` struct size match what this binding
|
|
253
|
+
was compiled against, throwing `AbiMismatchError` otherwise. It runs
|
|
254
|
+
automatically before every open/create call and before `checkFile()`; call
|
|
255
|
+
it yourself at startup to fail fast.
|
|
256
|
+
|
|
257
|
+
## Storage kinds
|
|
258
|
+
|
|
259
|
+
Every open/create call accepts `storage` (`Storage.Lite`, the default, or
|
|
260
|
+
`Storage.Directory`) via `OpenOptions.storage`:
|
|
261
|
+
|
|
262
|
+
- `Storage.Lite` -- a single-file `.aflite` database (this package's usual
|
|
263
|
+
use case).
|
|
264
|
+
- `Storage.Directory` -- a normal single-node Antfly directory. Directory
|
|
265
|
+
storage is created by opening a missing path with `open`/`openWithOptions`;
|
|
266
|
+
`create`/`createWithOptions` only create `.aflite` files.
|
|
267
|
+
|
|
268
|
+
A portable `.afb` backup (`backup()`) round-trips across storage kinds: it
|
|
269
|
+
restores into either kind with the module-level `restore`/`restoreFile`, and
|
|
270
|
+
imports into an *empty* database of either kind with `importBackup()`.
|
|
271
|
+
`restore(path, backup, { storage, replace })` and
|
|
272
|
+
`restoreFile(path, backupPath, { storage, replace })` select the destination
|
|
273
|
+
kind with `storage` (default `Storage.Lite`); the `.aflite` suffix is only
|
|
274
|
+
required client-side when the destination is `Storage.Lite`.
|
|
275
|
+
|
|
276
|
+
## JSON conventions
|
|
277
|
+
|
|
278
|
+
Every request parameter that accepts a JSON body (`request`, `config`,
|
|
279
|
+
`schema`, ...) accepts a plain object (JSON.stringify'd), a JSON string, or
|
|
280
|
+
raw UTF-8 bytes (`Buffer` / `Uint8Array`).
|
|
281
|
+
|
|
282
|
+
Every JSON-returning operation has two forms:
|
|
283
|
+
|
|
284
|
+
- The bare name (e.g. `lookup`, `search`, `status`) returns **parsed JSON**
|
|
285
|
+
(typed as `unknown`, or a specific interface for `Status` /
|
|
286
|
+
`Capabilities` / the maintenance reports).
|
|
287
|
+
- The `...Raw` suffix (e.g. `lookupRaw`, `searchRaw`, `statusRaw`) returns
|
|
288
|
+
the **raw JSON bytes** as a `Buffer`, skipping the parse.
|
|
289
|
+
|
|
290
|
+
The packed **wire** searches (`denseSearchWire`, `textMatchWire`,
|
|
291
|
+
`textTermWire`, `textMatchPhraseWire`) are a different, non-JSON binary
|
|
292
|
+
format matching the server's wire protocol; they always take and return raw
|
|
293
|
+
bytes (`Buffer` / `Uint8Array`), never JSON.
|
|
294
|
+
|
|
295
|
+
`getRaw(key)` is the one exception to the naming scheme above: it mirrors
|
|
296
|
+
`antfly_db_get_raw` / the Go binding's `Raw(key)`, returning the document's
|
|
297
|
+
raw stored bytes (not JSON at all, since a document need not be JSON at the
|
|
298
|
+
storage layer).
|
|
299
|
+
|
|
300
|
+
Timestamps and versions that are `uint64_t` in the C ABI (`timestampNs`,
|
|
301
|
+
`expectedVersion`, `commitVersion`, `busyTimeoutMs`, ...) accept both
|
|
302
|
+
`number` and `bigint`; use `bigint` where precision matters; a nanosecond
|
|
303
|
+
Unix timestamp exceeds `Number.MAX_SAFE_INTEGER`, so `commitVersion()`
|
|
304
|
+
always returns `bigint`.
|
|
305
|
+
|
|
306
|
+
## Errors
|
|
307
|
+
|
|
308
|
+
Every failed call rejects with an `AntflyError` subclass carrying:
|
|
309
|
+
|
|
310
|
+
- `.code` -- the numeric `antfly_error_code`.
|
|
311
|
+
- `.codeName` -- the stable symbolic name, e.g. `"ANTFLY_BUSY"`, matching
|
|
312
|
+
`antfly_error_code_name()`.
|
|
313
|
+
- `.message` -- built from `antfly_error_code_description()`.
|
|
314
|
+
|
|
315
|
+
Subclasses: `InvalidArgumentError` (1), `NotFoundError` (2),
|
|
316
|
+
`VersionConflictError` (3), `IntentConflictError` (4), `TxnNotFoundError` (5),
|
|
317
|
+
`BusyError` (6), `OutcomeUnknownError` (7, not safe to retry automatically --
|
|
318
|
+
publication may have succeeded but crash durability could not be confirmed),
|
|
319
|
+
`UnsupportedError` (8, not transient), `StalledError` (9, a bounded drain
|
|
320
|
+
like `runUntilIdle` made no progress and gave up), `CancelledError` (10, the
|
|
321
|
+
caller returned `false` from an `Inference.pull()` `onProgress` or
|
|
322
|
+
`Inference.generateStream()` `onChunk` callback -- a callback that throws
|
|
323
|
+
instead stops the operation the same way, but rejects with the thrown error
|
|
324
|
+
itself, not `CancelledError`), `InternalError` (255).
|
|
325
|
+
|
|
326
|
+
## API surface
|
|
327
|
+
|
|
328
|
+
Mirrors `go/pkg/embedded`'s surface idiomatically:
|
|
329
|
+
|
|
330
|
+
- **Open/create**: `create`, `open`, `openReadonly`, `openStatusOnly`,
|
|
331
|
+
`openHosted`, `createHosted`, `openWithOptions`, `createWithOptions`, plus
|
|
332
|
+
`OpenOptions` (including `storage`), `Storage`, `OpenMode`, `Profile`,
|
|
333
|
+
`TxnStatus`, `GraphDirection`, `InferenceMode`, `THREADING_SERIALIZED`.
|
|
334
|
+
- **`Database`**: `close()`, `[Symbol.asyncDispose]`; `batch`/`batchJson`;
|
|
335
|
+
`lookup`/`lookupRaw`/`getRaw`; `scan`/`search`/`stats`; `status`,
|
|
336
|
+
`capabilities`, `check`, `pendingWorkStats`, `runUntilIdle` /
|
|
337
|
+
`runUntilIdleStatus`, `replayGeneratedEnrichments`; `getSchema`/
|
|
338
|
+
`setSchema`; `listIndexes`/`addIndex`/`deleteIndex` (returns `boolean`);
|
|
339
|
+
`listEnrichments`/`addEnrichment`/`deleteEnrichment`; graph
|
|
340
|
+
(`edges`/`neighbors`/`traverseEdges`/`executeGraphQueries`/
|
|
341
|
+
`findShortestPath`/`findKShortestPaths`/`matchPattern`); wire searches
|
|
342
|
+
(`denseSearchWire`/`textMatchWire`/`textTermWire`/`textMatchPhraseWire`);
|
|
343
|
+
`aggregateHits`, `lookupArtifact`; `extractEnrichments`/
|
|
344
|
+
`computeEnrichments`; transactions (`beginTransaction`/`writeTransaction`/
|
|
345
|
+
`resolveTransaction`/`transactionStatus`/`commitVersion` -- 16-byte
|
|
346
|
+
transaction ids accepted as a `Uint8Array(16)` or a 32-char hex string);
|
|
347
|
+
`backup`/`importBackup`, `backupToFile`; `compact`/`vacuum`/
|
|
348
|
+
`copyStableSnapshot`.
|
|
349
|
+
- **Module-level**: `checkFile`, `restore`/`restoreFile` (both take
|
|
350
|
+
`RestoreOptions` -- `{ storage, replace }`), `copyStableSnapshotFile`,
|
|
351
|
+
`decodeArtifactId`, `abiVersion`, `threadingMode`, `validateAbi`.
|
|
352
|
+
- **`Inference`**: `Inference.open(options?)`, `close()`,
|
|
353
|
+
`[Symbol.asyncDispose]`; `embed`/`rerank`/`chunk`/`generate`/
|
|
354
|
+
`generateBatch`/`rewrite`/`extract`/`read`/`transcribe`/`listModels`
|
|
355
|
+
(each with a `...Raw` form); `generateStream(request, onChunk)` /
|
|
356
|
+
`generateStreamRaw`; `pull(request, onProgress?, signal?)`; plus
|
|
357
|
+
`InferenceOptions`, `PullProgress`, `CancelledError`,
|
|
358
|
+
`validateInferenceAbi`. See "Embedded inference" above.
|
|
359
|
+
|
|
360
|
+
See `src/index.ts` for the full export list and `src/types.ts` for typed
|
|
361
|
+
`Status` / `Capabilities` / report interfaces.
|
|
362
|
+
|
|
363
|
+
## Testing
|
|
364
|
+
|
|
365
|
+
```bash
|
|
366
|
+
pnpm run typecheck
|
|
367
|
+
pnpm run lint
|
|
368
|
+
pnpm run build
|
|
369
|
+
pnpm run test # skips native-library tests cleanly if libantfly isn't found
|
|
370
|
+
ANTFLY_LITE_REQUIRE_LIBRARY=1 pnpm run test # fails instead of skipping if libantfly isn't found
|
|
371
|
+
ANTFLY_LIBRARY=/nonexistent pnpm run test # exercises the clean-skip path directly
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
`test/conformance.test.ts` runs every case under
|
|
375
|
+
`zig/pkg/antfly-embedded/capi-conformance/cases/*.json` through this public API,
|
|
376
|
+
mirroring `go/pkg/embedded/conformance_cgo_test.go`'s semantics, including the
|
|
377
|
+
`storage`-typed opens and the `import_backup`/`restore_open` cross-storage
|
|
378
|
+
cases. `test/storage.test.ts` adds coverage beyond conformance: restoring a
|
|
379
|
+
`.aflite` backup into directory storage and reopening it. `test/
|
|
380
|
+
concurrency.test.ts` covers mixed concurrent operations, `close()` racing
|
|
381
|
+
in-flight calls, `busyTimeoutMs` behavior, and that concurrent searches
|
|
382
|
+
overlap instead of serializing on the event loop. `test/errors.test.ts` and
|
|
383
|
+
`test/discovery.test.ts` include pure tests that need no native library at
|
|
384
|
+
all. `test/package.test.ts` builds and packs the package, then verifies CommonJS
|
|
385
|
+
and ESM discovery in isolated Node processes outside a checkout. It checks all
|
|
386
|
+
three platform packages and package-relative source discovery in installation
|
|
387
|
+
paths containing spaces, `#`, and `?`, without loading the fixture libraries. `test/inference.test.ts` covers the `Inference` handle: open/close,
|
|
388
|
+
calls that need no model (`chunk`, `listModels`), missing-model
|
|
389
|
+
`NotFoundError` for both `embed` and `generateStream`, `pull({})`/
|
|
390
|
+
streaming-`generate`/malformed-JSON-`generateStream` `InvalidArgumentError`
|
|
391
|
+
cases, an optional real-embedding test gated on a locally installed Qwen
|
|
392
|
+
model, an optional `generateStream` test gated on a locally installed Gemma
|
|
393
|
+
generate model (`~/.antfly/inference/models/ggml-org/gemma-4-e2b-it-gguf*`)
|
|
394
|
+
covering both a normal multi-chunk stream and cancelling after two chunks
|
|
395
|
+
(`CancelledError`, exactly two `onChunk` calls), and a network-gated
|
|
396
|
+
`pull()` test (`ANTFLY_INFERENCE_PULL_TEST_MODEL`, e.g.
|
|
397
|
+
`sparse-encoder-testing/splade-bert-tiny-nq-onnx`) that cancels on the first
|
|
398
|
+
progress report (`CancelledError`, model still absent from `listModels()`),
|
|
399
|
+
then pulls the same model to completion with progress callbacks.
|
|
400
|
+
|
|
401
|
+
## License
|
|
402
|
+
|
|
403
|
+
Apache-2.0
|
|
404
|
+
|
|
405
|
+
## SQL, Kysely, and multiple tables
|
|
406
|
+
|
|
407
|
+
`Connection` provides a promise-based SQL session over a `Database`:
|
|
408
|
+
|
|
409
|
+
```ts
|
|
410
|
+
import { create, Connection } from "@antfly/embedded";
|
|
411
|
+
const database = await create("app.aflite");
|
|
412
|
+
const connection = await Connection.open(database);
|
|
413
|
+
await connection.execute("CREATE TABLE people (id BIGINT PRIMARY KEY, name TEXT)");
|
|
414
|
+
await connection.transaction(async tx => {
|
|
415
|
+
await tx.execute("INSERT INTO people (id,name) VALUES ($1,$2)", [1n, "Ada"]);
|
|
416
|
+
});
|
|
417
|
+
const result = await connection.query("SELECT id,name FROM people");
|
|
418
|
+
for await (const page of connection.stream("SELECT id,name FROM people", [], 128)) {
|
|
419
|
+
console.log(page.rows);
|
|
420
|
+
}
|
|
421
|
+
await connection.close();
|
|
422
|
+
await database.close();
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
`query` reads all native cursor pages; `stream` yields bounded pages. Integer
|
|
426
|
+
columns use `bigint`, SQL NULL uses `null`, and JSON uses JavaScript values.
|
|
427
|
+
Use bigint parameters when values exceed JavaScript's safe integer range.
|
|
428
|
+
Errors carry `sqlstate` and an optional `transactionId`.
|
|
429
|
+
|
|
430
|
+
Install Kysely 0.29 and import the optional dialect subpath:
|
|
431
|
+
|
|
432
|
+
```ts
|
|
433
|
+
import { Kysely } from "kysely";
|
|
434
|
+
import { AntflyDialect } from "@antfly/embedded/kysely";
|
|
435
|
+
const sql = new Kysely<{ people: { id: bigint; name: string } }>({
|
|
436
|
+
dialect: new AntflyDialect({ database }),
|
|
437
|
+
});
|
|
438
|
+
const people = await sql.selectFrom("people").selectAll().execute();
|
|
439
|
+
await sql.destroy(); // The caller still owns database.
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
`createTable`, `listTables`, `openTable`, and `dropTable` expose the shared
|
|
443
|
+
document catalog. Table handles reuse existing schema, index, enrichment,
|
|
444
|
+
search, and document methods. Close them before dropping their tables;
|
|
445
|
+
database close invalidates them.
|
|
446
|
+
|
|
447
|
+
Portable `.afb` archives back up the entire database: its table catalog,
|
|
448
|
+
schemas, documents, indexes, enrichments, and constraint records. Call backup
|
|
449
|
+
on the database handle. Restore publishes all tables together into either
|
|
450
|
+
Lite or directory storage; import requires an empty database with no open
|
|
451
|
+
table handles, SQL sessions, or cursors. Table handles cannot export or import
|
|
452
|
+
backups.
|
|
453
|
+
|
|
454
|
+
See [the native SQL contract](../../../zig/CAPI.md#database-sql) for
|
|
455
|
+
READ COMMITTED, savepoints, transactional DDL restrictions, and commit outcomes.
|