@lunora/ai 1.0.0-alpha.7 → 1.0.0-alpha.70

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