@lunora/ai 1.0.0-alpha.11 → 1.0.0-alpha.111

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.
Files changed (32) hide show
  1. package/README.md +18 -9
  2. package/dist/index.d.mts +93 -27
  3. package/dist/index.d.ts +93 -27
  4. package/dist/index.mjs +1 -3
  5. package/dist/packem_shared/AI_DEFAULT_EMBEDDING_MODEL_ENV-IwcHZiKj.mjs +1 -0
  6. package/dist/packem_shared/DEFAULT_MODEL_PRICES-CIJLs1Ah.mjs +1 -0
  7. package/dist/packem_shared/VECTORIZE_CAPABILITIES-CUQDoxis.mjs +1 -0
  8. package/dist/packem_shared/batchReranker-Bc38FBLH.mjs +1 -0
  9. package/dist/packem_shared/bm25-9q0Avwi-.mjs +1 -0
  10. package/dist/packem_shared/bm25LexicalStore-DMUzAL0O.mjs +1 -0
  11. package/dist/packem_shared/concurrent-C6nqBv41.mjs +1 -0
  12. package/dist/packem_shared/contentHash-BIn6ECP8.mjs +1 -0
  13. package/dist/packem_shared/createAi-Cebawe9R.mjs +1 -0
  14. package/dist/packem_shared/defineRag-CMTzKfS7.mjs +8 -0
  15. package/dist/packem_shared/defineRagSource-Q3f3niU8.mjs +1 -0
  16. package/dist/packem_shared/fixedWindowChunks-C461ahRE.mjs +1 -0
  17. package/dist/packem_shared/hybridRank-B4skyCLx.mjs +1 -0
  18. package/dist/packem_shared/markdownChunker-iW8V4klY.mjs +5 -0
  19. package/dist/packem_shared/matchesMetadataFilter-BbIOyA5g.mjs +1 -0
  20. package/dist/packem_shared/ragSyncTriggers-hgMcA4f2.mjs +1 -0
  21. package/dist/packem_shared/sql-D5aqEMCY.mjs +1 -0
  22. package/dist/packem_shared/sqlLexicalStore-4C_cIwef.mjs +1 -0
  23. package/dist/packem_shared/sqliteVectorStore-SjOFKoHo.mjs +1 -0
  24. package/dist/packem_shared/stable-key-B_BlboiY.mjs +1 -0
  25. package/dist/packem_shared/types.d-D-WK1t2B.d.mts +473 -0
  26. package/dist/packem_shared/types.d-D-WK1t2B.d.ts +473 -0
  27. package/dist/packem_shared/usage-GPnTSqR8.mjs +1 -0
  28. package/dist/rag/index.d.mts +1364 -0
  29. package/dist/rag/index.d.ts +1364 -0
  30. package/dist/rag/index.mjs +1 -0
  31. package/package.json +12 -16
  32. package/dist/packem_shared/createAi-Bq_4LMcp.mjs +0 -54
@@ -0,0 +1,1364 @@
1
+ import { Tool } from 'ai';
2
+ import { E as EmbeddingModelInput, a as LunoraAi } from "../packem_shared/types.d-D-WK1t2B.mjs";
3
+ /**
4
+ * Built-in fixed-window chunker: split into `size`-char windows overlapping by
5
+ * `overlap` chars. Deliberately simple and deterministic — the zero-config
6
+ * default. Token-aware / sentence / semantic strategies plug in via
7
+ * `RagConfig.chunk`.
8
+ * @experimental
9
+ */
10
+ declare const fixedWindowChunks: (text: string, size: number, overlap: number) => ReadonlyArray<string>;
11
+ /**
12
+ * Options shared by the character-budgeted chunkers. `overlap` is a **floor**
13
+ * in characters: enough trailing atoms are carried into the next window to
14
+ * cover it, so the realised overlap lands on an atom boundary and is usually a
15
+ * little larger.
16
+ */
17
+ interface ChunkerOptions {
18
+ /** Overlap floor between adjacent chunks, in characters. Default 200. Must be `< size`. */
19
+ overlap?: number;
20
+ /** Maximum chunk size, in characters. Default 1000. */
21
+ size?: number;
22
+ }
23
+ /**
24
+ * Options for {@link tokenChunker}.
25
+ *
26
+ * `countTokens` is **required and injected**: a real token count needs the
27
+ * model's tokenizer, and `@lunora/ai` will not add one as a dependency or
28
+ * pretend a characters-per-token constant is a token count — a "token-aware"
29
+ * chunker built on an estimate is a character chunker with extra steps, and it
30
+ * silently overshoots on code and non-Latin scripts, which is exactly where the
31
+ * budget matters. Pass `js-tiktoken`, `gpt-tokenizer`, or your provider's
32
+ * counter.
33
+ */
34
+ interface TokenChunkerOptions {
35
+ /** Token counter for the target model — e.g. `(text) => encoding.encode(text).length`. */
36
+ countTokens: (text: string) => number;
37
+ /** Maximum chunk size, in tokens. Default 256. */
38
+ maxTokens?: number;
39
+ /** Overlap floor between adjacent chunks, in tokens. Default 0. Must be `< maxTokens`. */
40
+ overlapTokens?: number;
41
+ }
42
+ /**
43
+ * Split on sentence boundaries, then greedily pack whole sentences into
44
+ * `size`-bounded chunks. Prefer this over the fixed window for prose: chunks
45
+ * start and end where the author ended a thought, which is what the embedding
46
+ * model was trained on.
47
+ * @experimental
48
+ */
49
+ declare const sentenceChunker: (options?: ChunkerOptions) => ((text: string) => ReadonlyArray<string>);
50
+ /**
51
+ * Split a Markdown document at its ATX headings, then pack each section's
52
+ * sentences into `size`-bounded chunks.
53
+ *
54
+ * Every emitted chunk is prefixed with its **heading trail** (`# Guide > ##
55
+ * Auth > ### OAuth`), so a chunk taken from deep inside a long document still
56
+ * carries the context that says what it is about. That prefix is what makes a
57
+ * mid-document chunk retrievable by a query naming its section rather than its
58
+ * prose, and it is why this beats {@link sentenceChunker} on structured docs.
59
+ * @experimental
60
+ */
61
+ declare const markdownChunker: (options?: ChunkerOptions) => ((text: string) => ReadonlyArray<string>);
62
+ /**
63
+ * Pack sentences into chunks bounded by a real **token** count rather than a
64
+ * character count. Use this when the embedding model's context window is the
65
+ * binding constraint — a 512-token model silently truncates anything longer, so
66
+ * the tail of an over-long chunk is embedded as if it were never written.
67
+ * @experimental
68
+ */
69
+ declare const tokenChunker: (options: TokenChunkerOptions) => ((text: string) => ReadonlyArray<string>);
70
+ /**
71
+ * What a store can hold and return. Every field is a hard limit `defineRag`
72
+ * enforces locally, so a breach fails here — naming the store and the limit —
73
+ * rather than at the backend with nothing saying why.
74
+ */
75
+ interface RagVectorStoreCapabilities {
76
+ /**
77
+ * Ceiling on embedding dimensionality, or `false` for no limit.
78
+ *
79
+ * Vectorize stores at most 1536 at 32-bit precision, which rules out
80
+ * `text-embedding-3-large` (3072) and Qwen3-Embedding (4096). A store with
81
+ * no such limit declares `false` and those models just work.
82
+ */
83
+ maxDimensions: number | false;
84
+ /**
85
+ * Ceiling on a vector's id, in bytes, or `false` for no limit.
86
+ *
87
+ * Vectorize allows 64, and chunk ids are derived from the namespace and the
88
+ * caller's source id — a bucket key like
89
+ * `handbook/engineering/onboarding/day-one.md` under a uuid namespace is
90
+ * already past it. Without this the upsert is rejected at the far side with
91
+ * nothing naming the cause, the same failure {@link RagVectorStoreCapabilities.maxMetadataBytes}
92
+ * exists to replace.
93
+ */
94
+ maxIdBytes: number | false;
95
+ /**
96
+ * Ceiling on the serialized metadata object per vector, in bytes, or
97
+ * `false` for no limit. Covers the whole object — chunk text included when
98
+ * no `textStore` moves it out.
99
+ */
100
+ maxMetadataBytes: number | false;
101
+ /** Ceiling on `topK` when only indexed metadata is requested (text-store mode). */
102
+ maxTopK: number;
103
+ /** Ceiling on `topK` when the query asks for full metadata (the default mode). */
104
+ maxTopKWithMetadata: number;
105
+ }
106
+ /**
107
+ * The storage operations `defineRag` needs. Deliberately the same four
108
+ * operations `RagVectors` already exposes — this is a capability-carrying
109
+ * wrapper, not a new protocol, so adapting an existing implementation is a
110
+ * one-liner.
111
+ */
112
+ interface RagVectorStore {
113
+ capabilities: RagVectorStoreCapabilities;
114
+ deleteByIds: (ids: ReadonlyArray<string>, namespace?: string) => Promise<unknown>;
115
+ getByIds: (ids: ReadonlyArray<string>, namespace?: string) => Promise<ReadonlyArray<RagVectorRecord>>;
116
+ query: (input: RagVectorQueryInput) => Promise<RagVectorMatches>;
117
+ upsert: (input: RagVectorUpsertInput) => Promise<unknown>;
118
+ }
119
+ /**
120
+ * Vectorize's documented limits.
121
+ *
122
+ * `maxTopKWithMetadata` is 50, matching Vectorize V2. **Legacy V1 indexes cap
123
+ * at 20** and reject a larger `topK` remotely; a binding handle does not expose
124
+ * its index version, so this cannot branch on it.
125
+ */
126
+ declare const VECTORIZE_CAPABILITIES: RagVectorStoreCapabilities;
127
+ /**
128
+ * Wrap a `ctx.vectors` facade (or any {@link RagVectors}) as a store declaring
129
+ * Vectorize's limits. This is the default when no `store` is configured, so the
130
+ * behaviour of an existing `defineRag` is unchanged.
131
+ * @experimental
132
+ */
133
+ declare const vectorizeStore: (vectors: RagVectors, indexName: string) => RagVectorStore;
134
+ /**
135
+ * `(text) => vector` — the embedder shape `ctx.vectors` accepts on both its
136
+ * write (`upsert`) and read (`query`) inputs. Matches `@lunora/server`'s
137
+ * `VectorEmbedder` and `@lunora/bindings/vectors`' `EmbedFunction<string>`.
138
+ * @experimental
139
+ */
140
+ type RagEmbedder = (input: string) => Promise<ReadonlyArray<number>> | ReadonlyArray<number>;
141
+ /**
142
+ * `RagVectorMatch` is part of the experimental `@lunora/ai` API and may change without a major version bump.
143
+ * @experimental
144
+ */
145
+ interface RagVectorMatch {
146
+ id: string;
147
+ metadata?: Record<string, unknown>;
148
+ score: number;
149
+ }
150
+ /**
151
+ * `RagVectorMatches` is part of the experimental `@lunora/ai` API and may change without a major version bump.
152
+ * @experimental
153
+ */
154
+ interface RagVectorMatches {
155
+ count: number;
156
+ matches: ReadonlyArray<RagVectorMatch>;
157
+ }
158
+ /**
159
+ * `RagVectorQueryInput` is part of the experimental `@lunora/ai` API and may change without a major version bump.
160
+ * @experimental
161
+ */
162
+ interface RagVectorQueryInput {
163
+ /** Embedder used to vectorize `input`. */
164
+ embed?: RagEmbedder;
165
+ filter?: Record<string, unknown>;
166
+ /** Natural-language query text, embedded via `embed`. */
167
+ input?: string;
168
+ namespace?: string;
169
+ /**
170
+ * How much stored metadata to return on matches. The runtime honours it even
171
+ * though `@lunora/server`'s ctx type does not declare it — the helper relies
172
+ * on it to read chunk text back in metadata mode.
173
+ */
174
+ returnMetadata?: "all" | "indexed" | "none";
175
+ topK?: number;
176
+ }
177
+ /**
178
+ * `RagVectorRecord` is part of the experimental `@lunora/ai` API and may change without a major version bump.
179
+ * @experimental
180
+ */
181
+ interface RagVectorRecord {
182
+ id: string;
183
+ metadata?: Record<string, unknown>;
184
+ }
185
+ /**
186
+ * `RagVectorUpsertInput` is part of the experimental `@lunora/ai` API and may change without a major version bump.
187
+ * @experimental
188
+ */
189
+ interface RagVectorUpsertInput {
190
+ /** Embedder used to vectorize `input`. Optional — omitted for text-search indexes. */
191
+ embed?: RagEmbedder;
192
+ id: string;
193
+ input: string;
194
+ metadata?: Record<string, unknown>;
195
+ namespace?: string;
196
+ }
197
+ /**
198
+ * Structural subset of the vector surface the RAG helper needs. Both the
199
+ * `ctx.vectors` facade on Mutation/Action ctx (`@lunora/server`'s
200
+ * `VectorSearch`) and the raw `@lunora/bindings/vectors` `LunoraVectors`
201
+ * satisfy it — declared here so `@lunora/ai` depends on neither package.
202
+ * @experimental
203
+ */
204
+ interface RagVectors {
205
+ deleteByIds: (indexName: string, ids: ReadonlyArray<string>, namespace?: string) => Promise<unknown>;
206
+ getByIds: (indexName: string, ids: ReadonlyArray<string>, namespace?: string) => Promise<ReadonlyArray<RagVectorRecord>>;
207
+ query: (indexName: string, input: RagVectorQueryInput) => Promise<RagVectorMatches>;
208
+ upsert: (indexName: string, input: RagVectorUpsertInput) => Promise<unknown>;
209
+ }
210
+ /**
211
+ * The two facades `defineRag` binds. An `ActionCtx` satisfies this directly
212
+ * (`ctx.ai` is action-only, so RAG methods run inside actions); any object
213
+ * carrying the two facades works in tests.
214
+ * @experimental
215
+ */
216
+ interface RagContext {
217
+ /**
218
+ * Resolves a Workers AI embedding-model id (or the omitted default) — an
219
+ * `ActionCtx`'s `ctx.ai` satisfies it. OPTIONAL: when
220
+ * {@link RagConfig.embeddingModel} is a direct AI SDK `EmbeddingModel` object
221
+ * (bring-your-own embeddings, e.g. `@ai-sdk/openai`), the helper uses that
222
+ * object as-is and never reads `ai`, so a hand-built context may omit it and
223
+ * no `env.AI` binding is needed. A model-id string (or an omitted model) with
224
+ * no `ai` present throws a directed error.
225
+ */
226
+ ai?: Pick<LunoraAi, "embeddingModel">;
227
+ /**
228
+ * The verified retrieval identity, read by {@link RagConfig.rlsFilter} to
229
+ * derive a per-request row filter. An `ActionCtx` carrying `ctx.auth`
230
+ * satisfies this structurally, so `docs(ctx)` picks the identity up
231
+ * automatically; tests pass any value. `unknown` on purpose — `@lunora/ai`
232
+ * stays decoupled from `@lunora/server`'s identity type; `rlsFilter` narrows.
233
+ */
234
+ auth?: unknown;
235
+ /**
236
+ * Optional conversation / session id. When set (and `trace` is present), each
237
+ * embedding-model span additionally carries `gen_ai.conversation.id`, so a
238
+ * RAG embed done inside a multi-turn conversation groups with that
239
+ * conversation's other generation spans in the trace store. Omitted → the
240
+ * attribute is absent (backward-compatible).
241
+ */
242
+ conversationId?: string;
243
+ /**
244
+ * Optional `ctx.metrics` — an `ActionCtx`'s `ctx.metrics` satisfies it. When
245
+ * present, every embed counts its tokens and cost into the durable
246
+ * `gen_ai.usage.*` series, like a `ctx.ai.model(...)` call. `unknown` for the
247
+ * same decoupling reason as `trace`; `defineRag` narrows it.
248
+ */
249
+ metrics?: unknown;
250
+ /**
251
+ * Optional `ctx.trace` span factory — an `ActionCtx`'s `ctx.trace` satisfies
252
+ * it structurally. When present, `defineRag` wraps each embedding-model
253
+ * call in a `generation` span carrying `gen_ai.operation.name: "embeddings"`
254
+ * and `gen_ai.request.model` up front, plus — attached post-hoc through the
255
+ * span handle the tracer hands the body — `gen_ai.usage.input_tokens` (from
256
+ * the embed result's token usage) and `gen_ai.usage.cost` (probed from the
257
+ * embed result's provider metadata, e.g. AI Gateway) when those are present.
258
+ * So the embed shows up on the trace waterfall with its usage like any other
259
+ * instrumented model call. `unknown` on purpose — the same decoupling
260
+ * rationale as `auth`: `defineRag` narrows it to a callable and runs embeds
261
+ * untraced when it is absent (a hand-built context / test).
262
+ */
263
+ trace?: unknown;
264
+ /**
265
+ * The Vectorize facade backing the default store — an `ActionCtx`'s
266
+ * `ctx.vectors` satisfies it.
267
+ *
268
+ * OPTIONAL, because it is never read when {@link RagConfig.store} is set,
269
+ * and codegen only emits `ctx.vectors` for a schema that declares a vector
270
+ * index. Requiring it made "the store that needs no Vectorize" impossible
271
+ * to type-check in an app with no Vectorize index. Absent with no `store`
272
+ * configured throws a directed error when the RAG is bound.
273
+ */
274
+ vectors?: RagVectors;
275
+ }
276
+ /**
277
+ * Pluggable chunk-text storage. By default chunk text is stored in vector
278
+ * metadata (`__ragText`), which forces `returnMetadata: "all"` on retrieval and
279
+ * caps `topK` at 50 (the Vectorize full-metadata ceiling) — and each vector's
280
+ * metadata must stay under the ~10 KiB Vectorize cap. Supplying a text store
281
+ * (a DO table, KV, …) moves the text out of metadata: retrieval queries with
282
+ * `returnMetadata: "indexed"` (topK up to 100) and hydrates text by chunk id.
283
+ * @experimental
284
+ */
285
+ interface RagTextStore {
286
+ /** Fetch chunk texts by id, aligned with the input order; `undefined` for misses. */
287
+ getMany: (ids: ReadonlyArray<string>, options: {
288
+ namespace?: string;
289
+ }) => Promise<ReadonlyArray<string | undefined>>;
290
+ /** Persist chunk texts. Must be idempotent by chunk `id` (re-index re-puts). */
291
+ put: (chunks: ReadonlyArray<StoredRagChunk>, options: {
292
+ namespace?: string;
293
+ }) => Promise<void>;
294
+ /** Optional cleanup hook, invoked when a source's chunks are deleted. */
295
+ remove?: (ids: ReadonlyArray<string>, options: {
296
+ namespace?: string;
297
+ }) => Promise<void>;
298
+ }
299
+ /**
300
+ * A chunk handed to {@link RagTextStore.put} / {@link RagLexicalStore.index}.
301
+ * @experimental
302
+ */
303
+ interface StoredRagChunk {
304
+ chunkIndex: number;
305
+ id: string;
306
+ /**
307
+ * The caller `metadata` attached to this chunk's source at index time
308
+ * (internal `__rag*` keys excluded).
309
+ *
310
+ * Present so a {@link RagLexicalStore} can evaluate the same metadata
311
+ * filter the vector leg gets. Without it a lexical store has nothing to
312
+ * filter on and must fail closed on every filtered query — which made
313
+ * hybrid search and metadata-based RLS mutually exclusive.
314
+ */
315
+ metadata?: Record<string, unknown>;
316
+ sourceId: string;
317
+ text: string;
318
+ }
319
+ /**
320
+ * One lexical (BM25) hit returned by {@link RagLexicalStore.search}.
321
+ * @experimental
322
+ */
323
+ interface LexicalMatch {
324
+ /** The chunk vector id — the same id scheme the vector leg uses, so RRF can fuse the two. */
325
+ id: string;
326
+ /** BM25 relevance score (higher = better). Used only for the leg's internal ranking; RRF fuses by rank. */
327
+ score: number;
328
+ /** The chunk text, returned so a fused lexical-only hit needs no extra hydration round-trip. */
329
+ text: string;
330
+ }
331
+ /**
332
+ * Pluggable lexical (BM25 / keyword) store — the production seam for hybrid
333
+ * retrieval. When {@link RagConfig.lexicalStore} is set, `index()` mirrors each
334
+ * chunk's text here and `retrieve()` fuses this store's keyword ranking with the
335
+ * vector store's semantic ranking via Reciprocal Rank Fusion. Mirrors the
336
+ * {@link RagTextStore} shape (idempotent by chunk `id`, namespace-partitioned).
337
+ *
338
+ * `@lunora/ai/rag` ships `bm25LexicalStore()`, an in-memory reference adapter;
339
+ * production deployments plug a durable one (DO SQLite inverted index, D1,
340
+ * Vectorize-adjacent search service, …) behind this same interface.
341
+ * @experimental
342
+ */
343
+ interface RagLexicalStore {
344
+ /** Index chunk texts for keyword search. Must be idempotent by chunk `id` (re-index re-puts). */
345
+ index: (chunks: ReadonlyArray<StoredRagChunk>, options: {
346
+ namespace?: string;
347
+ }) => Promise<void>;
348
+ /** Optional cleanup hook, invoked when a source's chunks are deleted or a re-index shrinks it. */
349
+ remove?: (ids: ReadonlyArray<string>, options: {
350
+ namespace?: string;
351
+ }) => Promise<void>;
352
+ /**
353
+ * Rank chunks by lexical relevance to `query`. `filter` carries the same
354
+ * (RLS-merged) metadata predicate handed to the vector leg — a store that
355
+ * indexes metadata MUST honour it so hybrid retrieval can't surface a row
356
+ * the RLS filter would exclude. The shipped `bm25LexicalStore` does — it
357
+ * evaluates the predicate against each document's stored `metadata`. A store
358
+ * that indexes no metadata has nothing to filter on and must fail CLOSED on
359
+ * every filtered query rather than ignore the predicate.
360
+ */
361
+ search: (query: string, options: {
362
+ filter?: Record<string, unknown>;
363
+ namespace?: string;
364
+ topK: number;
365
+ }) => Promise<ReadonlyArray<LexicalMatch>>;
366
+ }
367
+ /**
368
+ * One graph hit returned by {@link RagGraphStore.related}.
369
+ * @experimental
370
+ */
371
+ interface GraphMatch {
372
+ /** The chunk vector id — the same id scheme the other legs use, so RRF can fuse the three. */
373
+ id: string;
374
+ /**
375
+ * Depth-decaying PROXIMITY, not relevance: `1` for a direct neighbour,
376
+ * halving per hop — exactly what `ctx.db.related` puts on each node. `hybridRank`
377
+ * scales this leg's RRF term by it, so a leg of distant hits weighs less than
378
+ * a leg of direct ones even when the two rank identically among themselves.
379
+ * Values outside `[0, 1]` are clamped.
380
+ */
381
+ score: number;
382
+ /** The chunk text, returned so a graph-only hit needs no extra hydration round-trip. */
383
+ text: string;
384
+ }
385
+ /**
386
+ * Pluggable relation-graph store — the third retrieval signal, alongside the
387
+ * vector (semantic) and lexical (keyword) legs.
388
+ *
389
+ * Keyword and embedding search both answer "which passages look like this
390
+ * question". Neither can answer "what is this connected to" when the connecting
391
+ * fact lives in a foreign key rather than in the text — a ticket's customer, a
392
+ * customer's other tickets, those tickets' messages. `ctx.db.related` walks
393
+ * exactly that graph, and this is the seam that feeds its result into retrieval.
394
+ *
395
+ * Implement it over a Lunora app whose RAG source ids ARE document ids: expand
396
+ * from the seed ids with `ctx.db.related`, then return the indexed chunks of the
397
+ * documents it reached, each carrying that node's `score`. Mirrors the
398
+ * {@link RagLexicalStore} shape (namespace-partitioned, `topK`-bounded).
399
+ * @experimental
400
+ */
401
+ interface RagGraphStore {
402
+ /**
403
+ * Whether {@link RagGraphStore.related} applies the `filter` it is handed to
404
+ * every document it returns.
405
+ *
406
+ * Required, and asked rather than assumed, because the honest answer is not
407
+ * derivable: `related` is somebody else's traversal and this package cannot
408
+ * see whether it narrows. `retrieve()` passes the SAME effective filter to
409
+ * all three legs — the caller's filter with `RagConfig.rlsFilter` merged
410
+ * over it — and the vector and lexical stores enforce it. A graph store that
411
+ * ignored it would return the neighbours of a document the caller may see
412
+ * even when those neighbours belong to another tenant, which is a leak the
413
+ * other two legs are specifically built to prevent. So a store that answers
414
+ * `false` is SKIPPED whenever a filter is in play, rather than trusted:
415
+ * retrieval loses its third signal and keeps its isolation. With no filter
416
+ * (no `rlsFilter`, no `RetrieveOptions.filter`) there is nothing to enforce
417
+ * and `false` costs nothing.
418
+ *
419
+ * Answer `true` only if every returned chunk's document really is matched
420
+ * against the filter — `ctx.db.related` under a schema with RLS policies
421
+ * does not count on its own, because the filter here is RAG metadata, not a
422
+ * row policy. The stricter reading is the safe one: if in doubt, `false`.
423
+ */
424
+ enforcesFilter: boolean;
425
+ /**
426
+ * Expand from the SOURCE document ids the search legs found and return
427
+ * chunks of the documents they connect to, best (nearest) first.
428
+ *
429
+ * Seeded rather than queried: the graph has no notion of a query string, so
430
+ * it widens a ranking the other legs produced instead of ranking on its own.
431
+ * A seed id that is not a graph node simply contributes nothing.
432
+ *
433
+ * `options.filter` is the effective metadata filter for this retrieval, and
434
+ * is present only for stores that declared {@link RagGraphStore.enforcesFilter}
435
+ * — see there for what declaring it commits you to.
436
+ */
437
+ related: (sourceIds: ReadonlyArray<string>, options: {
438
+ filter?: Record<string, unknown>;
439
+ namespace?: string;
440
+ topK: number;
441
+ }) => Promise<ReadonlyArray<GraphMatch>>;
442
+ }
443
+ /**
444
+ * A pre-defined, reusable filter expression. Declared on `RagConfig.filters`
445
+ * (keyed by name) and referenced by name from `RetrieveOptions.filter` — avoids
446
+ * repeating the same tenant/RBAC filter shape across every retrieval site.
447
+ * @example
448
+ * ```ts
449
+ * const docs = defineRag({
450
+ * index: "docs",
451
+ * filters: {
452
+ * published: { filter: { status: "published", deleted: false }, description: "Only published content" },
453
+ * },
454
+ * });
455
+ * // Later — reference by name:
456
+ * docs(ctx).retrieve("query", { filter: "published" });
457
+ * ```
458
+ * @experimental
459
+ */
460
+ interface RagNamedFilter {
461
+ /** Optional human-readable description for observability / Studio display. */
462
+ description?: string;
463
+ /** The filter expression passed verbatim to Vectorize's `filter` parameter. */
464
+ filter: Record<string, unknown>;
465
+ }
466
+ /**
467
+ * Re-score retrieved candidates against the query. Returns the chunks in their
468
+ * new order; may drop chunks. See {@link RagConfig.rerank}.
469
+ * @experimental
470
+ */
471
+ type RagReranker = (query: string, chunks: ReadonlyArray<RetrievedChunk>) => Promise<ReadonlyArray<RetrievedChunk>> | ReadonlyArray<RetrievedChunk>;
472
+ /**
473
+ * Rewrite a query, or expand it into several. See {@link RagConfig.transformQuery}.
474
+ * @experimental
475
+ */
476
+ type RagQueryTransform = (query: string, info: {
477
+ conversationId?: string;
478
+ namespace?: string;
479
+ }) => Promise<ReadonlyArray<string> | string> | ReadonlyArray<string> | string;
480
+ /**
481
+ * `RagConfig` is part of the experimental `@lunora/ai` API and may change without a major version bump.
482
+ * @experimental
483
+ */
484
+ interface RagConfig {
485
+ /**
486
+ * Suppress the one-time dev warning emitted when `index`/`retrieve` run
487
+ * without a `namespace`. Only appropriate for genuinely single-tenant apps —
488
+ * Vectorize indexes are account-global, so a namespace-less index shares
489
+ * vectors across every tenant.
490
+ */
491
+ allowSharedNamespace?: boolean;
492
+ /**
493
+ * Retain up to this many embeddings per bound context, keyed by text, so a
494
+ * repeated `retrieve()` of the same question does not re-embed it.
495
+ *
496
+ * Default 0 (retain nothing beyond one call). Indexing always batches its
497
+ * embeds regardless of this setting — the batch lives in its own
498
+ * request-scoped map, released when `index()` returns, so it neither needs
499
+ * this budget nor evicts what is held in it.
500
+ *
501
+ * Sized in entries, not bytes, but budget in bytes: one 1536-dimension
502
+ * embedding is ~12 KB, so 100 entries is over a megabyte held in the
503
+ * isolate. Keep it small.
504
+ */
505
+ cacheEmbeddings?: number;
506
+ /**
507
+ * How many chunks each retrieval leg fetches **before** fusion and
508
+ * reranking trim the result to `topK`.
509
+ *
510
+ * Defaults to `topK * 4` whenever anything downstream reorders — a
511
+ * `lexicalStore`, a multi-query `transformQuery`, or a `rerank` — and to
512
+ * plain `topK` otherwise. Bounded by the store ceiling (50 in metadata
513
+ * mode, 100 with a `textStore`).
514
+ *
515
+ * This is the knob that decides how much recall the reordering has to work
516
+ * with. Fetching only `topK` per leg defeats the point of having two: the
517
+ * whole reason to run a lexical leg is to surface a chunk the vector leg
518
+ * ranked *below* `topK`, and it cannot do that if it was never asked for
519
+ * more than `topK`.
520
+ */
521
+ candidates?: number;
522
+ /** Custom chunker; overrides the built-in fixed-window splitter. */
523
+ chunk?: (text: string) => ReadonlyArray<string>;
524
+ /** Overlap (chars) between adjacent chunks. Default 200. Must be < `chunkSize`. */
525
+ chunkOverlap?: number;
526
+ /** Target chunk size (chars). Default 1000. */
527
+ chunkSize?: number;
528
+ /**
529
+ * Embedding model, declared once so index + retrieve embed identically: a
530
+ * Workers AI id (e.g. `@cf/baai/bge-base-en-v1.5`) or any AI SDK
531
+ * `EmbeddingModel`.
532
+ *
533
+ * Omitting it resolves through `ai.embeddingModel(undefined)`, which falls
534
+ * back to `createAi`'s `defaultEmbeddingModel` — NOT `defaultModel`, which
535
+ * this said before and which would be a language-model id in an
536
+ * embedding-model slot. On the generated `ctx.ai` that default comes from
537
+ * `LUNORA_AI_DEFAULT_EMBEDDING_MODEL` in the Worker env; with neither set,
538
+ * the first index/retrieve throws.
539
+ */
540
+ embeddingModel?: EmbeddingModelInput;
541
+ /**
542
+ * Embedding-model version tag — an opt-in discriminator that partitions the
543
+ * vector space so a model swap can never silently return garbage. Vectors
544
+ * embedded by one model live in a different space from another's, and
545
+ * querying across the two returns meaningless neighbours. When set, the tag
546
+ * is folded into the effective Vectorize namespace (and chunk-id prefix) of
547
+ * every index/retrieve/remove, so bumping it re-partitions cleanly: old
548
+ * vectors become unreachable to new queries (empty ≫ wrong) until sources
549
+ * are re-indexed under the new tag.
550
+ *
551
+ * Set + bump this whenever you change {@link RagConfig.embeddingModel} (or
552
+ * its dimensions). Opt-in and non-breaking — omitting it keeps the exact
553
+ * chunk-id/namespace scheme of un-versioned indexes. Must match
554
+ * `^[A-Za-z0-9._-]{1,40}$` (e.g. `"bge-v1.5"`, `"v2"`).
555
+ */
556
+ embeddingModelVersion?: string;
557
+ /**
558
+ * Pre-defined named filter expressions. Each key is a filter name users
559
+ * pass through `RetrieveOptions.filter`. Throws at retrieve-time if the
560
+ * name is not found here — catches spelling mistakes early.
561
+ */
562
+ filters?: Record<string, RagNamedFilter>;
563
+ /**
564
+ * Pluggable relation-graph store — the third retrieval signal. When set,
565
+ * `retrieve()` seeds a traversal from the source documents the vector and
566
+ * lexical legs found and fuses the connected documents' chunks into the same
567
+ * RRF ranking, weighted by how far away they are. See {@link RagGraphStore}.
568
+ */
569
+ graphStore?: RagGraphStore;
570
+ /** Retrieval depth for the graph leg. Defaults to the effective candidate pool. */
571
+ graphTopK?: number;
572
+ /** The Vectorize index name (a `ctx.vectors` index binding key). */
573
+ index: string;
574
+ /**
575
+ * Pluggable lexical (BM25) store for hybrid retrieval. When set, `index()`
576
+ * mirrors chunk text into it and `retrieve()` fuses the vector (semantic)
577
+ * and lexical (keyword) rankings via Reciprocal Rank Fusion — recovering the
578
+ * exact-term / rare-token matches a pure-embedding search misses. Use the
579
+ * shipped `bm25LexicalStore()` reference adapter or plug your own durable
580
+ * one. See {@link RagLexicalStore}.
581
+ */
582
+ lexicalStore?: RagLexicalStore;
583
+ /** Retrieval depth for the lexical leg of hybrid search. Defaults to the effective `topK`. */
584
+ lexicalTopK?: number;
585
+ /**
586
+ * Ceiling on the embedding model's dimensionality, checked once per bound
587
+ * context against the first embedding actually produced. Defaults to
588
+ * **1536** — Vectorize's per-vector limit at 32-bit precision.
589
+ *
590
+ * The default rules out most current large embedding models
591
+ * (`text-embedding-3-large` and Gemini embedding at 3072,
592
+ * Qwen3-Embedding at 4096). Without the check they fail at Vectorize with
593
+ * nothing naming the cause; with it they fail at the first embed, naming
594
+ * the ceiling and both escapes — truncate via the provider's Matryoshka
595
+ * `dimensions` option, or set this to `false` when the index is not
596
+ * Vectorize-backed.
597
+ *
598
+ * `false` disables the check entirely: the right setting for a
599
+ * {@link RagVectors} implementation with a different (or no) ceiling.
600
+ */
601
+ maxEmbeddingDimensions?: number | false;
602
+ /**
603
+ * Enforce tenant isolation: throw (instead of the one-time dev warning)
604
+ * when `index`/`retrieve`/`remove` run without a `namespace`. Recommended
605
+ * for every multi-tenant app — Vectorize indexes are account-global, and
606
+ * in metadata mode the leaked payload includes raw chunk text.
607
+ */
608
+ requireNamespace?: boolean;
609
+ /**
610
+ * Re-score the retrieved candidates against the query before they are
611
+ * trimmed to `topK`. **Injected, not bundled** — a reranker is a model call,
612
+ * and `@lunora/ai` takes no provider dependency to make one. Adapt yours
613
+ * with `scoreReranker`/`batchReranker`, or write the two-line hook yourself.
614
+ *
615
+ * This is the standard quality step that vector search alone cannot do:
616
+ * an embedding is computed without the query, so it cannot know which of
617
+ * two topically-similar passages actually answers *this* question. A
618
+ * cross-encoder sees both at once and orders them accordingly.
619
+ *
620
+ * Retrieval fetches {@link RagConfig.candidates} chunks, hands them
621
+ * here, and keeps the first `topK` of whatever comes back — so the hook may
622
+ * reorder and drop, but its output order is final. Runs after hybrid fusion
623
+ * and before `chunkContext` expansion.
624
+ */
625
+ rerank?: RagReranker;
626
+ /**
627
+ * Row-level-security filter derived from the retrieval identity. Called once
628
+ * per `retrieve()` with {@link RagContext.auth} (the bound ctx's `auth`); the
629
+ * returned Vectorize metadata filter is merged over the caller's `filter`
630
+ * with **RLS keys winning** (a caller can never widen past what RLS allows),
631
+ * then applied to both the vector and the lexical legs. Return `undefined` to
632
+ * add no constraint (e.g. an admin identity). Runs on retrieval only —
633
+ * indexing is a trusted server path.
634
+ * @example
635
+ * ```ts
636
+ * const docs = defineRag({
637
+ * index: "docs",
638
+ * // only ever return the caller's own org, whatever else they ask for:
639
+ * rlsFilter: (auth) => ({ orgId: (auth as { orgId: string }).orgId }),
640
+ * });
641
+ * ```
642
+ */
643
+ rlsFilter?: (auth: unknown) => Promise<Record<string, unknown> | undefined> | Record<string, unknown> | undefined;
644
+ /**
645
+ * Back this RAG with a different vector store.
646
+ *
647
+ * Called once per bound context with that context, so a store needing
648
+ * per-request state (a Hyperdrive/pgvector connection from `ctx.sql`, a
649
+ * shard's own SQLite) can build itself from it. Defaults to wrapping
650
+ * `context.vectors` as a Vectorize-backed store.
651
+ *
652
+ * The store declares its own limits, and `defineRag` reads them instead of
653
+ * assuming Vectorize's — so a pgvector index is not held to a
654
+ * 1536-dimension ceiling or a 10 KiB metadata budget it does not have.
655
+ */
656
+ store?: (context: RagContext) => RagVectorStore;
657
+ /** Chunk-text storage override — see {@link RagTextStore}. */
658
+ textStore?: RagTextStore;
659
+ /** Default retrieval depth. Default 5. Capped by the store: 50 (metadata mode) / 100 (text-store mode) on Vectorize. */
660
+ topK?: number;
661
+ /**
662
+ * Rewrite or expand the query before it is embedded.
663
+ *
664
+ * The raw user query is often the worst possible search string: a
665
+ * conversational follow-up ("what about the other one?") carries its
666
+ * meaning in the preceding turns, and a short question shares few terms
667
+ * with the long passage that answers it.
668
+ *
669
+ * Return **one** string to rewrite, or **several** to run multi-query
670
+ * retrieval — each is embedded and searched independently and the rankings
671
+ * are fused with RRF, which recovers passages any single phrasing would
672
+ * miss. Returning the query unchanged is a no-op.
673
+ *
674
+ * **Injected, not bundled**, for the same reason as {@link RagConfig.rerank}:
675
+ * every useful strategy (HyDE, multi-query expansion, follow-up rewriting)
676
+ * needs a language model, and this package does not pick one for you. The
677
+ * lexical leg searches the first returned query.
678
+ */
679
+ transformQuery?: RagQueryTransform;
680
+ }
681
+ /**
682
+ * `IndexInput` is part of the experimental `@lunora/ai` API and may change without a major version bump.
683
+ * @experimental
684
+ */
685
+ interface IndexInput {
686
+ /**
687
+ * When `false`, throws if the source text produces zero chunks (e.g. empty
688
+ * or whitespace-only text). Default `true` (silently produces zero chunks).
689
+ */
690
+ allowEmptySources?: boolean;
691
+ /** Source document id — chunk ids derive from it as `${id}#${chunkIndex}`. */
692
+ id: string;
693
+ /**
694
+ * Relative weight in `[0, 1]` multiplied into this source's match scores at
695
+ * retrieval time (default 1). Lets canonical docs outrank incidental ones.
696
+ */
697
+ importance?: number;
698
+ /** Source metadata copied onto every chunk vector (e.g. title, url). */
699
+ metadata?: Record<string, unknown>;
700
+ /** Tenant/shard key. Required for multi-tenant apps — Vectorize is account-global. */
701
+ namespace?: string;
702
+ /**
703
+ * Called after each chunk is successfully upserted. Useful for progress
704
+ * tracking during large indexing operations — e.g. updating a UI progress
705
+ * bar or logging per-chunk status.
706
+ */
707
+ onChunk?: (info: {
708
+ chunkIndex: number;
709
+ id: string;
710
+ text: string;
711
+ total: number;
712
+ }) => void;
713
+ /**
714
+ * Index this source even when its identity hash (`text` + `metadata` +
715
+ * `importance`) is unchanged.
716
+ *
717
+ * The hash short-circuit skips chunking, embedding and every write — which
718
+ * is what makes a cron re-sync cheap, and also what makes attaching a
719
+ * `textStore` or `lexicalStore` to an ALREADY-indexed corpus a silent no-op:
720
+ * the new store is never written, so the keyword leg returns nothing
721
+ * forever with no error. Set this for the one pass that backfills it.
722
+ *
723
+ * It re-embeds, so it is not a setting to leave on.
724
+ */
725
+ reindex?: boolean;
726
+ /** The document body to chunk + embed + upsert. */
727
+ text: string;
728
+ }
729
+ /**
730
+ * `IndexResult` is part of the experimental `@lunora/ai` API and may change without a major version bump.
731
+ * @experimental
732
+ */
733
+ interface IndexResult {
734
+ /** Number of chunks the source is indexed into. */
735
+ chunks: number;
736
+ /** The deterministic chunk vector ids, in chunk order. */
737
+ ids: ReadonlyArray<string>;
738
+ /**
739
+ * True when the source's identity hash — its `text`, `metadata` and
740
+ * `importance` together — matched the previously indexed one, so
741
+ * chunking/embedding/upserts were skipped entirely (a no-op re-sync).
742
+ * Changing `metadata` alone (a tenant move, an ACL correction) therefore
743
+ * re-indexes: the old values are what `rlsFilter` scopes retrieval on.
744
+ */
745
+ unchanged: boolean;
746
+ }
747
+ /**
748
+ * `RemoveInput` is part of the experimental `@lunora/ai` API and may change without a major version bump.
749
+ * @experimental
750
+ */
751
+ interface RemoveInput {
752
+ /** The source document id whose chunks are removed. */
753
+ id: string;
754
+ namespace?: string;
755
+ }
756
+ /**
757
+ * `RetrieveOptions` is part of the experimental `@lunora/ai` API and may change without a major version bump.
758
+ * @experimental
759
+ */
760
+ interface RetrieveOptions {
761
+ /**
762
+ * Also return this many neighbouring chunks around each match (fetched by
763
+ * deterministic id, not re-queried) — "embed small, retrieve big". Neighbour
764
+ * text is stitched into the chunk's `text` in document order. Best combined
765
+ * with `chunkOverlap: 0`, since overlapping windows repeat boundary text.
766
+ */
767
+ chunkContext?: {
768
+ after?: number;
769
+ before?: number;
770
+ };
771
+ /**
772
+ * Vectorize filter expression — or the name of a pre-defined filter declared
773
+ * in `RagConfig.filters`. Passing a name that is not registered throws at
774
+ * call time, catching spelling mistakes early.
775
+ */
776
+ filter?: Record<string, unknown> | string;
777
+ /**
778
+ * Drop matches whose (importance-adjusted) score falls below this threshold.
779
+ *
780
+ * Applied to the VECTOR leg, where the score is still the cosine scale this
781
+ * option is documented against — every fusion below replaces `score` with an
782
+ * RRF score, and thresholding that against a cosine number keeps or drops
783
+ * chunks essentially at random. A chunk the vector leg rejected here stays
784
+ * rejected even if the lexical leg also ranks it; a lexical-only hit the
785
+ * vector leg never scored is NOT gated, since its BM25 score is not on this
786
+ * scale (see `hybridRank`).
787
+ */
788
+ minScore?: number;
789
+ namespace?: string;
790
+ /**
791
+ * Fires after retrieval completes, before chunk expansion. Useful for
792
+ * observability — logging query latency, hit counts, etc.
793
+ */
794
+ onRetrieve?: (info: {
795
+ matches: number;
796
+ query: string;
797
+ }) => void;
798
+ /**
799
+ * Set `false` to skip {@link RagConfig.rerank} for this call — the escape
800
+ * hatch for a latency-sensitive path (typeahead, an agent's inner loop)
801
+ * that cannot afford the extra model round-trip.
802
+ */
803
+ rerank?: false;
804
+ topK?: number;
805
+ /** Set `false` to skip {@link RagConfig.transformQuery} for this call. */
806
+ transformQuery?: false;
807
+ }
808
+ /**
809
+ * `RetrievedChunk` is part of the experimental `@lunora/ai` API and may change without a major version bump.
810
+ * @experimental
811
+ */
812
+ interface RetrievedChunk {
813
+ chunkIndex: number;
814
+ id: string;
815
+ /**
816
+ * The source-level importance weight that was multiplied into this chunk's
817
+ * score. `1` when no importance was set at index time.
818
+ */
819
+ importance: number;
820
+ /** Caller metadata stored on the vector (internal `__rag*` keys stripped). */
821
+ metadata?: Record<string, unknown>;
822
+ /** Cosine similarity, multiplied by the source's `importance` when one was set. */
823
+ score: number;
824
+ sourceId: string;
825
+ text: string;
826
+ }
827
+ /**
828
+ * `RagSource` is part of the experimental `@lunora/ai` API and may change without a major version bump.
829
+ * @experimental
830
+ */
831
+ interface RagSource {
832
+ id: string;
833
+ /** Caller metadata from the source's first-seen chunk (internal keys stripped). */
834
+ metadata?: Record<string, unknown>;
835
+ /**
836
+ * The source's importance weight (the `importance` value passed at index
837
+ * time, default 1), propagated so downstream consumers can factor it into
838
+ * their own ranking or UI.
839
+ */
840
+ weight?: number;
841
+ }
842
+ /**
843
+ * The retrieve return shape — designed so an agent memory step consumes it directly.
844
+ * @experimental
845
+ */
846
+ interface RetrieveResult {
847
+ /** Ranked chunks (best first). */
848
+ chunks: ReadonlyArray<RetrievedChunk>;
849
+ /** Ready-to-inject prompt context: chunks joined under `[source:<id>#<n>]` headers. */
850
+ context: string;
851
+ /** Deduped source references, in first-seen (best) order. */
852
+ sources: ReadonlyArray<RagSource>;
853
+ }
854
+ /**
855
+ * `RagToolOptions` is part of the experimental `@lunora/ai` API and may change without a major version bump.
856
+ * @experimental
857
+ */
858
+ interface RagToolOptions {
859
+ /** Tool description shown to the model. Defaults to a search description naming the index. */
860
+ description?: string;
861
+ /** Namespace applied to every tool-invoked retrieval (the tenant key). */
862
+ namespace?: string;
863
+ /** Retrieval depth for tool-invoked retrievals. */
864
+ topK?: number;
865
+ }
866
+ /**
867
+ * The per-request RAG surface returned by binding a ctx: `docs(ctx)`.
868
+ * @experimental
869
+ */
870
+ interface Rag {
871
+ /**
872
+ * Expose `retrieve` as an AI SDK tool (for `generateText`/`streamText`
873
+ * `tools:` maps), so a model can decide to search the index itself.
874
+ */
875
+ asTool: (options?: RagToolOptions) => Tool<{
876
+ query: string;
877
+ }, RetrieveResult>;
878
+ /**
879
+ * Chunk + embed + upsert one source document. Re-indexing the same `id` is
880
+ * an atomic-enough replace: unchanged content short-circuits via content
881
+ * hash, and stale chunks beyond the new count are deleted automatically.
882
+ */
883
+ index: (input: IndexInput) => Promise<IndexResult>;
884
+ /** Delete every chunk of a previously indexed source. */
885
+ remove: (input: RemoveInput) => Promise<void>;
886
+ /** Embed the query and return ranked chunks + prompt-ready context. */
887
+ retrieve: (query: string, options?: RetrieveOptions) => Promise<RetrieveResult>;
888
+ }
889
+ declare const defineRag: (config: RagConfig) => ((context: RagContext) => Rag);
890
+ /**
891
+ * Guess a MIME type from a file extension. Lowercases and strips a leading `.`
892
+ * from `extension`; returns `"application/octet-stream"` for unknown extensions.
893
+ *
894
+ * Covers the broad set of extensions users are likely to encounter in a web /
895
+ * document-processing context — images, video, audio, office docs, PDF, text,
896
+ * archives, and source code. Follows the same approach as Convex's
897
+ * `guessMimeType` helper.
898
+ * @experimental
899
+ */
900
+ declare const guessMimeTypeFromExtension: (extension: string) => string;
901
+ /**
902
+ * SHA-256 hex digest of binary data. Accepts a `BufferSource` (`ArrayBuffer` or
903
+ * `ArrayBufferView` such as `Uint8Array`). Useful for content-addressable
904
+ * storage — pair with `IndexInput.text` to detect duplicates across re-indexes.
905
+ * @experimental
906
+ */
907
+ declare const contentHash: (data: BufferSource) => Promise<string>;
908
+ /**
909
+ * How a leg's reciprocal-rank term is weighted before it is summed.
910
+ *
911
+ * `"rank"` is plain RRF: position in the leg is the only signal, which is the
912
+ * point — cosine, BM25 and graph-proximity scores are not comparable.
913
+ *
914
+ * `"proximity"` additionally scales the term by the chunk's own `score`, clamped
915
+ * into `[0, 1]`. It exists for the graph leg, where `score` is the depth decay
916
+ * `ctx.db.related` assigned (1, 0.5, 0.25 …) rather than a relevance score: a
917
+ * depth-2 neighbour should add half of what a depth-1 one does even where the
918
+ * two are adjacent in the leg's own ranking. Rank alone cannot express that — a
919
+ * leg of nothing but depth-3 hits would otherwise contribute exactly as much as
920
+ * a leg of direct neighbours, which is the whole distinction a proximity signal
921
+ * exists to carry.
922
+ */
923
+ type FusionWeight = "proximity" | "rank";
924
+ /** One ranked list feeding the fusion, and the rule its contribution follows. */
925
+ interface FusionLeg {
926
+ /** The leg's chunks, best first. */
927
+ chunks: ReadonlyArray<RetrievedChunk>;
928
+ /** Defaults to `"rank"`. See {@link FusionWeight}. */
929
+ weight?: FusionWeight;
930
+ }
931
+ interface HybridRankOptions {
932
+ /** RRF damping constant; higher flattens rank differences. Defaults to 60. */
933
+ k?: number;
934
+ }
935
+ /**
936
+ * Reciprocal Rank Fusion (RRF): merge ranked lists of chunks by their _rank
937
+ * position_ rather than their absolute scores, which are not comparable across
938
+ * different search methods (cosine vs BM25 vs graph proximity).
939
+ *
940
+ * Each leg contributes `1 / (k + rank)` to each chunk's fused score, where
941
+ * `rank` is 0-based position within that leg. The constant `k` (default 60)
942
+ * dampens the influence of high ranks. A leg declared `weight: "proximity"`
943
+ * scales its term by the chunk's own score — see {@link FusionWeight}.
944
+ *
945
+ * Legs are a LIST rather than one parameter per search method: what a leg needs
946
+ * to declare is its scoring rule, not its position, and a positional graph slot
947
+ * forced callers with no lexical leg to write `hybridRank(vector, [], graph)`.
948
+ *
949
+ * **The returned chunks carry the fused score in `score`**, multiplied by the
950
+ * chunk's `importance` so source weighting still applies. Writing it back is
951
+ * what makes the fusion survive: a caller that re-sorts by `score` — as
952
+ * `retrieve()` does, to apply importance weighting — would otherwise re-order
953
+ * by the incomparable inputs and discard the ranking this function computed.
954
+ * Since BM25 is unbounded while cosine is `[0, 1]`, that silently promoted
955
+ * every lexical-only hit above every vector hit.
956
+ *
957
+ * Importance is applied ONCE, by this call. A caller with several signals passes
958
+ * them as several legs to ONE call, never one call per leg: the returned list is
959
+ * both weighted and sorted by that weighting, so handing it back in as a leg
960
+ * makes the next pass derive its ranks from an already-weighted ordering and
961
+ * weight it a second time.
962
+ *
963
+ * So in hybrid mode `RetrievedChunk.score` is an RRF score (small, ~`1/60`
964
+ * scale), not a cosine similarity. `retrieve()` applies `minScore` to the
965
+ * vector leg *before* fusion for exactly this reason — the option is documented
966
+ * against the cosine scale.
967
+ *
968
+ * Ties are broken by preferring the chunk ranked higher in the FIRST leg,
969
+ * conventionally the vector one and typically the more semantically accurate.
970
+ *
971
+ * Callers MUST ensure every chunk across every leg carries a unique, comparable
972
+ * `id` — guaranteed by the chunk-id scheme `${sourceId}#${chunkIndex}`.
973
+ * @experimental
974
+ */
975
+ declare const hybridRank: (legs: ReadonlyArray<FusionLeg>, options?: HybridRankOptions) => ReadonlyArray<RetrievedChunk>;
976
+ /**
977
+ * An **in-memory** Okapi BM25 lexical store — the reference adapter behind
978
+ * `RagConfig.lexicalStore`, giving hybrid retrieval its keyword leg with zero
979
+ * infrastructure. State lives in the worker isolate: it is **not durable and not
980
+ * shared across isolates**, so it is intended for tests, local development, and
981
+ * single-isolate workloads. Production deployments plug a durable
982
+ * {@link RagLexicalStore} (a DO-SQLite inverted index, D1, or an external search
983
+ * service) behind the same seam.
984
+ *
985
+ * Tenant isolation is by `namespace` (each namespace keeps its own index), and
986
+ * each chunk's source `metadata` is stored alongside it so `search` evaluates
987
+ * the **same** metadata predicate the vector leg receives — including an
988
+ * `rlsFilter` result. A hit the filter excludes never reaches fusion.
989
+ *
990
+ * That matters because the filter carries the tenant/RBAC scope: a lexical leg
991
+ * that ignored it would leak excluded chunk text into the fused result no
992
+ * matter what the vector leg returned. This store previously had no metadata to
993
+ * check and so refused every filtered query, which made hybrid search and
994
+ * metadata-based RLS mutually exclusive.
995
+ * @experimental
996
+ */
997
+ declare const bm25LexicalStore: () => RagLexicalStore;
998
+ /**
999
+ * True when `metadata` satisfies every clause of `filter`. An empty or absent
1000
+ * filter matches everything; absent metadata satisfies only an empty filter.
1001
+ *
1002
+ * Clauses are ANDed, matching Vectorize.
1003
+ */
1004
+ declare const matchesMetadataFilter: (metadata: Record<string, unknown> | undefined, filter: Record<string, unknown> | undefined) => boolean;
1005
+ /** Options for {@link scoreReranker}. */
1006
+ interface ScoreRerankerOptions {
1007
+ /**
1008
+ * Drop chunks scoring below this threshold, in the scorer's own scale.
1009
+ * Omitted → nothing is dropped and the reranker only reorders.
1010
+ *
1011
+ * Worth setting: reranking's real value is not just promoting the best
1012
+ * passage but *rejecting* the ones vector search only matched topically,
1013
+ * and a chunk that survives to the prompt is a chunk the model may cite.
1014
+ */
1015
+ minScore?: number;
1016
+ /**
1017
+ * Score one `(query, passage)` pair for relevance. Higher is better; the
1018
+ * scale does not matter, only the ordering it induces.
1019
+ *
1020
+ * Called once per candidate chunk. Wrap a Workers AI reranker
1021
+ * (`ctx.ai.run("@cf/baai/bge-reranker-base", …)`), a Cohere/Voyage rerank
1022
+ * endpoint, or an LLM prompted to rate relevance.
1023
+ */
1024
+ score: (query: string, text: string) => Promise<number> | number;
1025
+ }
1026
+ /**
1027
+ * Batched variant — score every candidate in one call.
1028
+ */
1029
+ interface BatchRerankerOptions {
1030
+ /** Drop chunks scoring below this threshold. See {@link ScoreRerankerOptions.minScore}. */
1031
+ minScore?: number;
1032
+ /**
1033
+ * Score all candidates at once, returning one number per passage **in the
1034
+ * same order**. Prefer this over {@link ScoreRerankerOptions.score} when the
1035
+ * provider has a batch endpoint: cross-encoder APIs are priced and rate
1036
+ * limited per request, so N passages in one call beats N calls.
1037
+ *
1038
+ * A result whose length does not match the input is rejected rather than
1039
+ * zipped against the wrong passages.
1040
+ */
1041
+ scoreAll: (query: string, texts: ReadonlyArray<string>) => Promise<ReadonlyArray<number>> | ReadonlyArray<number>;
1042
+ }
1043
+ /**
1044
+ * Adapt a per-passage relevance scorer into a {@link RagReranker}.
1045
+ *
1046
+ * The scorer is **injected** — `@lunora/ai` takes no provider dependency to
1047
+ * make a model call. Scoring runs with bounded concurrency so a 50-candidate
1048
+ * pool does not fan out 50 simultaneous subrequests.
1049
+ *
1050
+ * ```ts
1051
+ * defineRag({
1052
+ * index: "docs",
1053
+ * rerank: scoreReranker({
1054
+ * score: async (query, text) => {
1055
+ * const result = await ctx.ai.run("@cf/baai/bge-reranker-base", { query, contexts: [{ text }] });
1056
+ * return result.response[0].score;
1057
+ * },
1058
+ * }),
1059
+ * });
1060
+ * ```
1061
+ * @experimental
1062
+ */
1063
+ declare const scoreReranker: (options: ScoreRerankerOptions) => RagReranker;
1064
+ /**
1065
+ * Adapt a **batch** relevance scorer into a {@link RagReranker} — one call for
1066
+ * the whole candidate pool. See {@link BatchRerankerOptions.scoreAll}.
1067
+ * @experimental
1068
+ */
1069
+ declare const batchReranker: (options: BatchRerankerOptions) => RagReranker;
1070
+ /** One object listed by a {@link RagObjectSource}. */
1071
+ interface RagSourceObject {
1072
+ /** Content type, when the source knows it. Falls back to the key's extension. */
1073
+ contentType?: string;
1074
+ /** Stable key — becomes the indexed source id. */
1075
+ key: string;
1076
+ /** Metadata attached to every chunk of this object. */
1077
+ metadata?: Record<string, unknown>;
1078
+ }
1079
+ /**
1080
+ * Where documents come from. Two operations, both injected.
1081
+ *
1082
+ * `list` is an async iterable rather than an array so the caller decides how to
1083
+ * page a large bucket rather than being forced to build one array up front.
1084
+ * `sync` still collects the KEYS it yields — it needs the full current key set
1085
+ * to work out what disappeared — but never more than one object's BODY at a
1086
+ * time, which is where the memory actually is.
1087
+ */
1088
+ interface RagObjectSource {
1089
+ /** Fetch one object's raw text. Return `undefined` to skip it (unreadable, unsupported). */
1090
+ get: (object: RagSourceObject) => Promise<string | undefined> | string | undefined;
1091
+ /** Enumerate the objects to index. */
1092
+ list: () => AsyncIterable<RagSourceObject> | Iterable<RagSourceObject>;
1093
+ }
1094
+ /** Turn a fetched object's raw text into indexable plain text. */
1095
+ type RagExtractor = (raw: string, object: RagSourceObject) => Promise<string | undefined> | string | undefined;
1096
+ /** Options for {@link defineRagSource}. */
1097
+ interface RagSourceOptions {
1098
+ /**
1099
+ * How many objects to process at once. Default 4.
1100
+ *
1101
+ * Each one is a fetch plus an embed plus an upsert, so this multiplies into
1102
+ * the subrequest budget — the default is deliberately low.
1103
+ */
1104
+ concurrency?: number;
1105
+ /**
1106
+ * Extractors keyed by content type (`text/html`, `application/pdf`, …), or
1107
+ * `"*"` as a fallback. A content type with no extractor and no `"*"` entry
1108
+ * is skipped and counted in `skipped` — never indexed as raw bytes, which
1109
+ * would fill the index with markup or binary noise that embeds to nothing
1110
+ * meaningful.
1111
+ */
1112
+ extractors?: Record<string, RagExtractor>;
1113
+ /** Namespace (tenant/shard key) applied to every indexed object. */
1114
+ namespace?: string;
1115
+ /** Called after each object is handled — for progress reporting. */
1116
+ onObject?: (info: {
1117
+ chunks: number;
1118
+ key: string;
1119
+ status: "indexed" | "skipped" | "unchanged";
1120
+ }) => void;
1121
+ }
1122
+ /** Per-pass options for {@link RagSourceSync.sync}. */
1123
+ interface RagSyncPassOptions {
1124
+ /**
1125
+ * The keys this index is believed to already hold. Any of them missing from
1126
+ * this pass's `list()` is deleted from the index.
1127
+ *
1128
+ * Pruning is what makes the index a mirror rather than an append-only pile:
1129
+ * a document removed at the source but left in the index keeps being
1130
+ * retrieved and cited, which is worse than never having indexed it.
1131
+ *
1132
+ * It is the CALLER's set, and required, because nothing else can hold it
1133
+ * honestly. A previous pass's keys remembered in the instance would be
1134
+ * empty on the shape this helper is documented in — built per request, from
1135
+ * a per-request `rag(ctx)` — so a prune that defaulted on would in practice
1136
+ * never run and never say so. Persist the set (a table, a KV key, the
1137
+ * bucket listing itself) and hand it in.
1138
+ *
1139
+ * Omitted ⇒ nothing is pruned, and `pruned` comes back empty.
1140
+ */
1141
+ knownKeys?: Iterable<string>;
1142
+ }
1143
+ /** What one {@link RagSourceSync.sync} pass did. */
1144
+ interface RagSyncReport {
1145
+ /** Keys indexed for the first time or re-indexed after a change. */
1146
+ indexed: string[];
1147
+ /** Keys deleted from the index because they no longer exist at the source. Empty unless `knownKeys` was supplied. */
1148
+ pruned: string[];
1149
+ /** Keys skipped — no extractor, or the source returned nothing. */
1150
+ skipped: string[];
1151
+ /** Keys whose content hash matched, so nothing was embedded. */
1152
+ unchanged: string[];
1153
+ }
1154
+ /** The bound ingestion surface. */
1155
+ interface RagSourceSync {
1156
+ /** Run one full pass over the source. */
1157
+ sync: (source: RagObjectSource, passOptions?: RagSyncPassOptions) => Promise<RagSyncReport>;
1158
+ }
1159
+ /**
1160
+ * Declare a bulk-ingestion pass over a {@link Rag}.
1161
+ *
1162
+ * ```ts
1163
+ * const ingest = defineRagSource(docs(ctx), { namespace: ctx.shardKey });
1164
+ *
1165
+ * const report = await ingest.sync(
1166
+ * {
1167
+ * list: async function* () {
1168
+ * for await (const object of bucket.list()) {
1169
+ * yield { key: object.key, metadata: { url: object.key } };
1170
+ * }
1171
+ * },
1172
+ * get: async (object) => (await bucket.get(object.key))?.text(),
1173
+ * },
1174
+ * // Pass what you already indexed to have deletions mirrored; omit it and
1175
+ * // nothing is pruned.
1176
+ * { knownKeys: await ctx.db.query("indexedDocs").collect().then((rows) => rows.map((row) => row.key)) },
1177
+ * );
1178
+ * ```
1179
+ * @experimental
1180
+ */
1181
+ declare const defineRagSource: (rag: Rag, options?: RagSourceOptions) => RagSourceSync;
1182
+ /**
1183
+ * Run one statement and return its rows.
1184
+ *
1185
+ * Rows come back as plain objects keyed by column name — the shape
1186
+ * `SqlStorage#exec().toArray()`, D1's `.all().results`, and `postgres.js` all
1187
+ * already produce. A statement returning nothing yields an empty array.
1188
+ *
1189
+ * May be synchronous: a Durable Object's SQLite is, and forcing it through a
1190
+ * promise would add a microtask per row batch for nothing.
1191
+ */
1192
+ type RagSqlExec = (sql: string, parameters: ReadonlyArray<unknown>) => Promise<ReadonlyArray<Record<string, unknown>>> | ReadonlyArray<Record<string, unknown>>;
1193
+ /** Options for {@link sqlLexicalStore}. */
1194
+ interface SqlLexicalStoreOptions {
1195
+ /** Execute one statement. See {@link RagSqlExec}. */
1196
+ exec: RagSqlExec;
1197
+ /**
1198
+ * Table-name prefix. Default `lunora_rag_lexical`; the postings table is
1199
+ * this plus `_terms`. Must be a bare SQL identifier.
1200
+ */
1201
+ table?: string;
1202
+ }
1203
+ declare const sqlLexicalStore: (options: SqlLexicalStoreOptions) => RagLexicalStore;
1204
+ /** Options for {@link sqliteVectorStore}. */
1205
+ interface SqliteVectorStoreOptions {
1206
+ /**
1207
+ * Keep a `sqlite-vec` `vec0` index (cosine distance) in `<table>_ann`, one
1208
+ * partition per namespace. Requires the extension in the executor's SQLite;
1209
+ * without it the first operation throws naming the missing module.
1210
+ *
1211
+ * The JSON table stays the source of truth: an index created over an
1212
+ * existing table is backfilled from it, and a match the table no longer
1213
+ * holds is dropped. Only an **unfiltered** query uses the index — `vec0`
1214
+ * applies a metadata filter after picking the `k` nearest, which would
1215
+ * return a short page, so a filtered query keeps the exact scan (and its
1216
+ * `maxScan` bound).
1217
+ */
1218
+ ann?: {
1219
+ dimensions: number;
1220
+ };
1221
+ /** Execute one statement. See {@link RagSqlExec}. */
1222
+ exec: RagSqlExec;
1223
+ /**
1224
+ * Ceiling on embedding dimensionality. Defaults to `false` (no limit) —
1225
+ * vectors are stored as JSON, so nothing here cares how wide they are, and
1226
+ * inheriting Vectorize's 1536 would be inventing a constraint.
1227
+ */
1228
+ maxDimensions?: number | false;
1229
+ /**
1230
+ * Upper bound on how many rows a single namespace may be scanned for.
1231
+ * Default 50,000.
1232
+ *
1233
+ * Search is linear, so this is the difference between a slow query and a
1234
+ * Worker that exceeds its CPU budget and is killed with nothing explaining
1235
+ * why. Exceeding it throws, naming the namespace and the count.
1236
+ */
1237
+ maxScan?: number;
1238
+ /** Table name. Default `lunora_rag_vectors`. Must be a bare SQL identifier. */
1239
+ table?: string;
1240
+ }
1241
+ declare const sqliteVectorStore: (options: SqliteVectorStoreOptions) => RagVectorStore;
1242
+ /**
1243
+ * A dispatchable function reference — the `internal.docs.reindex` you pass as
1244
+ * `action`. Typed structurally (rather than `unknown`) so passing the wrong
1245
+ * thing is a compile error: mis-wiring the action is the mistake this API is
1246
+ * most likely to see, and it would otherwise surface as a silent no-op.
1247
+ */
1248
+ interface RagSyncActionReference {
1249
+ readonly __lunoraRef: string;
1250
+ }
1251
+ /** Structural slice of `ctx.scheduler` — enough to defer the re-index. */
1252
+ interface RagSyncScheduler {
1253
+ runAfter: (delayMs: number, target: unknown, args?: Record<string, unknown>) => Promise<string>;
1254
+ }
1255
+ /** Structural slice of the `TriggerCtx` a `.triggers()` handler receives. */
1256
+ interface RagSyncTriggerContext {
1257
+ readonly scheduler: RagSyncScheduler;
1258
+ }
1259
+ /** The trigger events this helper handles, narrowed to what it reads. */
1260
+ interface RagSyncEvent {
1261
+ readonly doc?: Record<string, unknown>;
1262
+ readonly id: string;
1263
+ readonly previous?: Record<string, unknown>;
1264
+ }
1265
+ /** What the scheduled action receives — one document to re-index, or one to drop. */
1266
+ interface RagSyncArgs extends Record<string, unknown> {
1267
+ /** `true` when the source's chunks must go: call `rag.remove({ id, namespace })`. */
1268
+ deleted?: boolean;
1269
+ /** The source id — the same `id` you pass to `rag.index`/`rag.remove`. */
1270
+ id: string;
1271
+ /** The {@link RagSyncOptions.metadata} projection, to pass to `rag.index`. Absent on a delete or when there is none. */
1272
+ metadata?: Record<string, unknown>;
1273
+ /** The {@link RagSyncOptions.namespace} projection, to pass to `rag.index`/`rag.remove`. Absent when there is none. */
1274
+ namespace?: string;
1275
+ /** The text to embed. Absent on a delete. */
1276
+ text?: string;
1277
+ }
1278
+ interface RagSyncOptions<Document extends Record<string, unknown> = Record<string, unknown>> {
1279
+ /**
1280
+ * The internal action to dispatch — it receives {@link RagSyncArgs} and calls
1281
+ * `rag.index` / `rag.remove`. An action, not a mutation: embedding is network
1282
+ * I/O and never runs in the deterministic write path.
1283
+ */
1284
+ action: RagSyncActionReference;
1285
+ /**
1286
+ * How long to wait before re-indexing. A small delay coalesces nothing by
1287
+ * itself, but it keeps the embed off the write's own tail latency. Default
1288
+ * `0` — as soon as the mutation commits.
1289
+ */
1290
+ delayMs?: number;
1291
+ /** The source id to index under. Defaults to the row's own id. */
1292
+ id?: (document: Document) => string;
1293
+ /**
1294
+ * Metadata copied onto every chunk (`rag.index({ metadata })`) — the fields a
1295
+ * `rlsFilter` or `metadataFilter` scopes retrieval by, such as a tenant or
1296
+ * owner id. Compared on update like the text: a row that moves tenant with
1297
+ * unchanged text is re-indexed, so the old tenant stops retrieving it.
1298
+ */
1299
+ metadata?: (document: Document) => Record<string, unknown> | undefined;
1300
+ /**
1301
+ * The Vectorize namespace to index under (`rag.index({ namespace })`), e.g.
1302
+ * the tenant key. When it changes on update, the chunks in the old namespace
1303
+ * are removed before the row is indexed into the new one.
1304
+ */
1305
+ namespace?: (document: Document) => string | undefined;
1306
+ /** The text to embed. Return `undefined` to skip the row (a draft, an empty body). */
1307
+ text: (document: Document) => string | undefined;
1308
+ }
1309
+ /** One trigger definition, structurally — matches what `.triggers((t) => …)` returns. */
1310
+ type RagSyncHandler = (context: RagSyncTriggerContext, event: RagSyncEvent) => Promise<void>;
1311
+ /**
1312
+ * Build the three write-path handlers that keep a RAG index in step with a
1313
+ * table. Wire them into the table's `.triggers()`:
1314
+ *
1315
+ * ```ts
1316
+ * const sync = ragSyncTriggers({ action: internal.docs.reindex, text: (doc) => doc.body });
1317
+ *
1318
+ * export const schema = defineSchema({
1319
+ * docs: defineTable({ body: v.string(), title: v.string() }).triggers((t) => ({
1320
+ * ragDelete: t.afterDelete(sync.afterDelete),
1321
+ * ragInsert: t.afterInsert(sync.afterInsert),
1322
+ * ragUpdate: t.afterUpdate(sync.afterUpdate),
1323
+ * })),
1324
+ * });
1325
+ * ```
1326
+ *
1327
+ * The action on the other end forwards every field it receives:
1328
+ *
1329
+ * ```ts
1330
+ * export const reindex = internalAction
1331
+ * .input({
1332
+ * deleted: v.optional(v.boolean()),
1333
+ * id: v.string(),
1334
+ * metadata: v.optional(v.record(v.string(), v.any())),
1335
+ * namespace: v.optional(v.string()),
1336
+ * text: v.optional(v.string()),
1337
+ * })
1338
+ * .action(async ({ args, ctx }) => {
1339
+ * const rag = docsRag(ctx);
1340
+ * const { id, metadata, namespace, text } = args;
1341
+ *
1342
+ * await (args.deleted === true || text === undefined ? rag.remove({ id, namespace }) : rag.index({ id, metadata, namespace, text }));
1343
+ * });
1344
+ * ```
1345
+ *
1346
+ * A multi-tenant table also passes `metadata` and/or `namespace` (for example
1347
+ * `metadata: (doc) => ({ orgId: doc.orgId })`). Without them, a row that moves
1348
+ * tenant keeps its old scope in the index and stays retrievable by the tenant it
1349
+ * left. An action that drops `namespace` removes from (or indexes into) the
1350
+ * wrong namespace, and one whose `input` omits `metadata` / `namespace` rejects
1351
+ * the scheduled args and fails every job.
1352
+ *
1353
+ * Re-scoping is not atomic: the triggers only SCHEDULE the work, so after a row
1354
+ * changes namespace its chunks stay retrievable in the old one until the
1355
+ * scheduled delete runs (and until the re-index runs, it is missing from the new
1356
+ * one). The same holds for a metadata change. Lower `delayMs` shortens that
1357
+ * window; it does not close it.
1358
+ */
1359
+ declare const ragSyncTriggers: <Document extends Record<string, unknown> = Record<string, unknown>>(options: RagSyncOptions<Document>) => {
1360
+ afterDelete: RagSyncHandler;
1361
+ afterInsert: RagSyncHandler;
1362
+ afterUpdate: RagSyncHandler;
1363
+ };
1364
+ export { type BatchRerankerOptions, type ChunkerOptions, type FusionLeg, type FusionWeight, type GraphMatch, type HybridRankOptions, type IndexInput, type IndexResult, type LexicalMatch, type Rag, type RagConfig, type RagContext, type RagEmbedder, type RagExtractor, type RagGraphStore, type RagLexicalStore, type RagNamedFilter, type RagObjectSource, type RagQueryTransform, type RagReranker, type RagSource, type RagSourceObject, type RagSourceOptions, type RagSourceSync, type RagSqlExec, type RagSyncActionReference, type RagSyncArgs, type RagSyncOptions, type RagSyncPassOptions, type RagSyncReport, type RagTextStore, type RagToolOptions, type RagVectorMatch, type RagVectorMatches, type RagVectorQueryInput, type RagVectorRecord, type RagVectorStore, type RagVectorStoreCapabilities, type RagVectorUpsertInput, type RagVectors, type RemoveInput, type RetrieveOptions, type RetrieveResult, type RetrievedChunk, type ScoreRerankerOptions, type SqlLexicalStoreOptions, type SqliteVectorStoreOptions, type StoredRagChunk, type TokenChunkerOptions, VECTORIZE_CAPABILITIES, batchReranker, bm25LexicalStore, contentHash, defineRag, defineRagSource, fixedWindowChunks, guessMimeTypeFromExtension, hybridRank, markdownChunker, matchesMetadataFilter, ragSyncTriggers, scoreReranker, sentenceChunker, sqlLexicalStore, sqliteVectorStore, tokenChunker, vectorizeStore };