@lunora/ai 1.0.0-alpha.9 → 1.0.0-alpha.91

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