@mlx-bun/module-chat 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,274 @@
1
+ // Part of the chat panel (`@mlx-bun/module-chat`): chat-with-files RAG v1
2
+ // (`02d723a:docs/design/web-chat-redesign.md` Appendix A, beat-matrix Axis 5).
3
+ //
4
+ // A small, dependency-free, pure BM25 retriever over attached-file text —
5
+ // matching optiq Lab's shipped v1 shape (the task's explicit target): chunk
6
+ // per-file, tokenize, score chunks against the outgoing message, return the
7
+ // top-K with enough metadata (filename + char range) for composer.ts to
8
+ // build a cited context block and chat.ts to render a Sources panel.
9
+ //
10
+ // No network, no embeddings, no external deps — this is the "dependency-
11
+ // free BM25 proves the v1 needs no vector infra" bet from the beat matrix.
12
+ // A later vector upgrade (packages/inference/src/embeddings/text.ts) is explicitly out of scope here
13
+ // (`02d723a:docs/design/web-chat-redesign.md` §5).
14
+
15
+ /* ────────────────────────────────────────────────────────────────────
16
+ Chunking
17
+ ──────────────────────────────────────────────────────────────────── */
18
+
19
+ /** One retrievable unit: a slice of one attached file's text, with the
20
+ * original [start,end) char offsets so the Sources panel can show a
21
+ * meaningful "filename + range" citation. */
22
+ export interface Chunk {
23
+ fileId: number;
24
+ fileName: string;
25
+ start: number;
26
+ end: number;
27
+ text: string;
28
+ }
29
+
30
+ const CHUNK_TARGET = 1200;
31
+
32
+ /** Split one file's text into ~CHUNK_TARGET-char chunks, preferring to break
33
+ * on paragraph boundaries (blank lines) so a chunk doesn't slice through
34
+ * the middle of a paragraph when a nearby boundary is available. Pure:
35
+ * takes text in, returns chunks with byte-accurate offsets into that same
36
+ * text (no trimming of the returned `text` field's positions — leading/
37
+ * trailing whitespace inside a chunk is fine, it's still exactly
38
+ * text.slice(start, end)).
39
+ *
40
+ * Algorithm: walk paragraph boundaries (split on /\n\s*\n/, keeping track
41
+ * of each paragraph's offset in the original string) and greedily pack
42
+ * paragraphs into a chunk until adding the next one would exceed
43
+ * CHUNK_TARGET *and* the chunk already has content — mirroring a standard
44
+ * greedy bin-packing chunker. A single paragraph longer than CHUNK_TARGET
45
+ * becomes its own oversized chunk rather than being split mid-word (never
46
+ * produce an empty chunk, never lose text). */
47
+ export function chunkText(fileId: number, fileName: string, text: string): Chunk[] {
48
+ if (!text) return [];
49
+ const chunks: Chunk[] = [];
50
+ // Split on blank-line paragraph boundaries, tracking each paragraph's
51
+ // [start,end) in the ORIGINAL string (not the split pieces' own indices).
52
+ const paraRe = /\n\s*\n/g;
53
+ const paras: { start: number; end: number }[] = [];
54
+ let last = 0;
55
+ let m: RegExpExecArray | null;
56
+ while ((m = paraRe.exec(text))) {
57
+ paras.push({ start: last, end: m.index });
58
+ last = m.index + m[0].length;
59
+ }
60
+ paras.push({ start: last, end: text.length });
61
+
62
+ let curStart = -1, curEnd = -1;
63
+ const flush = () => {
64
+ if (curStart < 0 || curEnd <= curStart) return;
65
+ chunks.push({ fileId, fileName, start: curStart, end: curEnd, text: text.slice(curStart, curEnd) });
66
+ curStart = -1; curEnd = -1;
67
+ };
68
+ for (const p of paras) {
69
+ if (p.end <= p.start) continue; // blank paragraph (consecutive blank lines) — nothing to add
70
+ const paraLen = p.end - p.start;
71
+ if (curStart < 0) {
72
+ // Starting a fresh chunk with this paragraph.
73
+ curStart = p.start; curEnd = p.end;
74
+ if (paraLen >= CHUNK_TARGET) flush(); // oversized single paragraph -> its own chunk immediately
75
+ continue;
76
+ }
77
+ const curLen = curEnd - curStart;
78
+ if (curLen + paraLen > CHUNK_TARGET) {
79
+ // Adding this paragraph would overflow the target — close the current
80
+ // chunk at the last paragraph boundary and start a new one with this
81
+ // paragraph (paragraph-boundary-preferring: we never split a paragraph
82
+ // in half to hit the target exactly).
83
+ flush();
84
+ curStart = p.start; curEnd = p.end;
85
+ if (paraLen >= CHUNK_TARGET) flush();
86
+ } else {
87
+ curEnd = p.end;
88
+ }
89
+ }
90
+ flush();
91
+ return chunks;
92
+ }
93
+
94
+ /** Chunk every attached text file (name/text pairs) into one flat list,
95
+ * independently per file (chunks never span files) — the shape composer.ts
96
+ * feeds from ComposerState.attachments. */
97
+ export function chunkFiles(files: { id: number; name: string; text: string }[]): Chunk[] {
98
+ const out: Chunk[] = [];
99
+ for (const f of files) out.push(...chunkText(f.id, f.name, f.text));
100
+ return out;
101
+ }
102
+
103
+ /* ────────────────────────────────────────────────────────────────────
104
+ Tokenizer
105
+ ──────────────────────────────────────────────────────────────────── */
106
+
107
+ /** Lowercase, alnum-run tokenizer. Pure and deliberately simple — no
108
+ * stemming/stopwords, matching the "dependency-free" bar; BM25's own
109
+ * length-normalization and IDF weighting do most of the useful work even
110
+ * over a raw token stream. */
111
+ export function tokenize(text: string): string[] {
112
+ const m = text.toLowerCase().match(/[a-z0-9]+/g);
113
+ return m || [];
114
+ }
115
+
116
+ /* ────────────────────────────────────────────────────────────────────
117
+ BM25 index + scoring
118
+ ──────────────────────────────────────────────────────────────────── */
119
+
120
+ // BM25 standard formula (Robertson/Sparck Jones), as in Manning/Raghavan/
121
+ // Schütze "Introduction to Information Retrieval" §11.4.3:
122
+ //
123
+ // score(D,Q) = Σ_{t∈Q} IDF(t) · ( f(t,D)·(k1+1) ) / ( f(t,D) + k1·(1-b+b·|D|/avgdl) )
124
+ //
125
+ // with IDF(t) = ln( (N - n(t) + 0.5) / (n(t) + 0.5) + 1 ) (the "+1" variant
126
+ // that keeps IDF non-negative for terms present in every document, per the
127
+ // same reference). k1=1.5, b=0.75 are the conventional defaults used there.
128
+ const K1 = 1.5;
129
+ const B = 0.75;
130
+
131
+ interface IndexedChunk {
132
+ chunk: Chunk;
133
+ termCounts: Map<string, number>;
134
+ length: number;
135
+ }
136
+
137
+ /** A BM25 index over a fixed chunk set. Built lazily (see buildIndex) and
138
+ * meant to be rebuilt whenever the attachment set changes — indexing a
139
+ * few dozen small chunks is cheap enough that no incremental-update path
140
+ * is warranted. */
141
+ export interface Bm25Index {
142
+ chunks: IndexedChunk[];
143
+ df: Map<string, number>; // document frequency per term
144
+ avgLength: number;
145
+ n: number;
146
+ }
147
+
148
+ export function buildIndex(chunks: Chunk[]): Bm25Index {
149
+ const indexed: IndexedChunk[] = [];
150
+ const df = new Map<string, number>();
151
+ let totalLen = 0;
152
+ for (const chunk of chunks) {
153
+ const toks = tokenize(chunk.text);
154
+ const termCounts = new Map<string, number>();
155
+ for (const t of toks) termCounts.set(t, (termCounts.get(t) || 0) + 1);
156
+ for (const t of termCounts.keys()) df.set(t, (df.get(t) || 0) + 1);
157
+ totalLen += toks.length;
158
+ indexed.push({ chunk, termCounts, length: toks.length });
159
+ }
160
+ return {
161
+ chunks: indexed,
162
+ df,
163
+ avgLength: indexed.length ? totalLen / indexed.length : 0,
164
+ n: indexed.length,
165
+ };
166
+ }
167
+
168
+ function idf(index: Bm25Index, term: string): number {
169
+ const n = index.df.get(term) || 0;
170
+ return Math.log((index.n - n + 0.5) / (n + 0.5) + 1);
171
+ }
172
+
173
+ export interface ScoredChunk {
174
+ chunk: Chunk;
175
+ score: number;
176
+ }
177
+
178
+ /** Score every chunk in `index` against `query`, returning the top `k` by
179
+ * descending BM25 score (ties broken by original chunk order, stable).
180
+ * Chunks that score 0 (no query term present at all) are excluded — a
181
+ * zero-overlap chunk is never a useful citation regardless of how few
182
+ * chunks exist. */
183
+ export function bm25TopK(index: Bm25Index, query: string, k: number): ScoredChunk[] {
184
+ const qTerms = tokenize(query);
185
+ if (!qTerms.length || !index.n) return [];
186
+ // Dedupe query terms but keep per-term query frequency out of the score
187
+ // (standard BM25 as written above weights by document term frequency
188
+ // only; query-term repetition isn't part of the classic formula).
189
+ const uniqueTerms = [...new Set(qTerms)];
190
+ const scored: ScoredChunk[] = [];
191
+ for (const ic of index.chunks) {
192
+ let score = 0;
193
+ for (const term of uniqueTerms) {
194
+ const f = ic.termCounts.get(term);
195
+ if (!f) continue;
196
+ const numer = f * (K1 + 1);
197
+ const denom = f + K1 * (1 - B + (B * ic.length) / (index.avgLength || 1));
198
+ score += idf(index, term) * (numer / denom);
199
+ }
200
+ if (score > 0) scored.push({ chunk: ic.chunk, score });
201
+ }
202
+ scored.sort((a, b) => b.score - a.score);
203
+ return scored.slice(0, k);
204
+ }
205
+
206
+ /* ────────────────────────────────────────────────────────────────────
207
+ Inline-vs-RAG decision + context-block assembly
208
+ ──────────────────────────────────────────────────────────────────── */
209
+
210
+ /** Above this total attached-text size, switch from "inline everything"
211
+ * to "retrieve top-K chunks" — LM Studio's transparent dual-mode
212
+ * threshold (`02d723a:docs/design/web-chat-redesign.md` Appendix A,
213
+ * beat-matrix Axis 5), tuned so ordinary small attachments
214
+ * (READMEs, short notes) never change behavior at all. */
215
+ export const INLINE_THRESHOLD_CHARS = 8000;
216
+
217
+ export const TOP_K = 6;
218
+
219
+ /** Pure: does this total attached-text length trigger retrieval mode? */
220
+ export function shouldRetrieve(totalChars: number): boolean {
221
+ return totalChars > INLINE_THRESHOLD_CHARS;
222
+ }
223
+
224
+ /** One numbered citation as composer.ts will inject it and chat.ts will
225
+ * reference by index — `n` is the 1-based [n] marker shown to the model
226
+ * and rendered back to the user. */
227
+ export interface Citation {
228
+ n: number;
229
+ fileName: string;
230
+ start: number;
231
+ end: number;
232
+ text: string;
233
+ }
234
+
235
+ /** Build the numbered [1]..[K] citation list from a scored top-K result.
236
+ * Pure — shared by composer.ts (building the outgoing context block) and
237
+ * chat.ts/tests (rendering the Sources panel from the same shape). */
238
+ export function toCitations(top: ScoredChunk[]): Citation[] {
239
+ return top.map((s, i) => ({
240
+ n: i + 1,
241
+ fileName: s.chunk.fileName,
242
+ start: s.chunk.start,
243
+ end: s.chunk.end,
244
+ text: s.chunk.text,
245
+ }));
246
+ }
247
+
248
+ /** Render the framed context block injected ahead of the user's message
249
+ * when in retrieval mode: each citation numbered [n] with filename+range,
250
+ * then ONE instruction line asking the model to cite sources with [n]
251
+ * markers when used. Plain text (this goes into the outgoing prompt, not
252
+ * HTML) — chat.ts/markdown.ts handle rendering [n] markers back as links
253
+ * separately, from the citation map, not from parsing this block. */
254
+ export function buildContextBlock(citations: Citation[]): string {
255
+ if (!citations.length) return "";
256
+ let out = "Context from attached files (retrieved by relevance to your message):\n\n";
257
+ for (const c of citations) {
258
+ out += `[${c.n}] ${c.fileName} (chars ${c.start}-${c.end}):\n${c.text}\n\n`;
259
+ }
260
+ out += "When you use information from the context above, cite it inline with the matching [n] marker.\n\n";
261
+ return out;
262
+ }
263
+
264
+ /** Full retrieval pipeline for one outgoing message: chunk the attached
265
+ * text files, index them, score against `queryText`, and return the
266
+ * top-K as citations ready for buildContextBlock. Returns [] if there's
267
+ * nothing to retrieve (no text files, or no query overlap at all). */
268
+ export function retrieve(files: { id: number; name: string; text: string }[], queryText: string, k = TOP_K): Citation[] {
269
+ const chunks = chunkFiles(files);
270
+ if (!chunks.length) return [];
271
+ const index = buildIndex(chunks);
272
+ const top = bm25TopK(index, queryText, k);
273
+ return toCitations(top);
274
+ }