@lunora/ai 1.0.0-alpha.13 → 1.0.0-alpha.131

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