@atlaskit/editor-plugin-autocomplete 3.1.0 → 3.3.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.
@@ -1,18 +1,27 @@
1
1
  /**
2
2
  * Local Slow Lane Client: On-device inference via @mlc-ai/web-llm.
3
3
  *
4
- * Drop-in replacement for the network-based slow-lane-client. Instead of
5
- * calling a backend API, this client uses MLC WebLLM to run a small language
6
- * model (SmolLM 135M) directly in the browser via WebGPU.
4
+ * Drop-in replacement for the network-based slow-lane-client. Instead of calling
5
+ * a backend API, this client runs two models in the browser via WebGPU, in a
6
+ * single MLCEngine, to reproduce the BE encoder's outputs on-device:
7
+ *
8
+ * - Causal LM (SmolLM2-135M-Instruct): one decode step per word boundary. A
9
+ * registered LogitProcessor captures the raw next-token logits, which
10
+ * `computeBePayload` turns into a whole-word `lm_logits` payload — a faithful
11
+ * port of the BE `CausalLMEncoder._get_top_k_probs` (masked softmax over the
12
+ * vocab's first-tokens, prefix expansion, L2 reservation, log-space pooling).
13
+ * - Semantic embedder (Snowflake Arctic Embed S): produces the real 384-d
14
+ * `semantic_vector`. Inputs are wrapped as passages (see `wrapForArctic`) so
15
+ * the runtime vector lands in the same space as the precomputed word bin.
7
16
  *
8
17
  * ── Why main thread (no Web Worker)? ─────────────────────────────────────
9
- * SmolLM 135M is small enough (~270 MB weights, 350-400 MB VRAM) that
10
- * WebGPU inference on the main thread is production-viable:
18
+ * The models are small enough (~640 MB combined VRAM) that WebGPU inference on
19
+ * the main thread is viable:
11
20
  *
12
21
  * - WebGPU GPU compute is inherently async (doesn't block the main thread)
13
- * - CPU overhead (tokenization + post-processing) is only 5-10 ms
14
- * - Single forward pass latency is 50-150 ms — well within autocomplete
15
- * expectations (~250 ms between word boundaries)
22
+ * - CPU overhead (BE-parity post-processing) is a few ms
23
+ * - Per-inference latency is well within autocomplete expectations
24
+ * (~250 ms between word boundaries)
16
25
  *
17
26
  * This avoids all the complexity of Web Workers:
18
27
  * - No CSP workarounds (blob URLs, inline scripts)
@@ -26,12 +35,13 @@
26
35
  * asynchronously after each updateContext() call.
27
36
  */
28
37
 
29
- import type { MLCEngine, InitProgressReport, AppConfig } from '@mlc-ai/web-llm';
38
+ import type { MLCEngine, InitProgressReport, AppConfig, LogitProcessor } from '@mlc-ai/web-llm';
30
39
 
31
40
  import { isAutocompleteDebugEnabled } from './debug-mode';
32
41
  import { isWordBoundary } from './slow-lane-client';
33
42
 
34
43
  type WebLlmModelRecord = NonNullable<AppConfig['model_list']>[number];
44
+ type EmbeddingApiResponse = { data?: Array<{ embedding?: unknown }> };
35
45
 
36
46
  // ─── Types ───────────────────────────────────────────────────────────────────
37
47
 
@@ -85,20 +95,467 @@ export interface LocalSlowLaneClient {
85
95
 
86
96
  const DEFAULT_DEBOUNCE_MS = 300;
87
97
 
88
- export const LOCAL_MLC_MODEL_ID = 'SmolLM2-135M-Instruct-q0f16-MLC';
98
+ export const LOCAL_MLC_CAUSAL_MODEL_ID = 'SmolLM2-135M-Instruct-q0f16-MLC';
99
+
100
+ /**
101
+ * MLC ID for the semantic embedder (Snowflake Arctic Embed S, batch=4 variant).
102
+ *
103
+ * The `-b4` suffix selects the prebuilt variant compiled for a max batch size of
104
+ * 4 (≈239 MB VRAM) rather than `-b32` (≈1023 MB VRAM). Autocomplete embeds one
105
+ * context at a time, so `-b4` is the right fit. This model IS in
106
+ * `prebuiltAppConfig.model_list` of web-llm 0.2.82 — no `customModelConfig` needed.
107
+ */
108
+ export const LOCAL_MLC_EMBEDDING_MODEL_ID = 'snowflake-arctic-embed-s-q0f32-MLC-b4';
109
+
110
+ /**
111
+ * Wrap raw context text with BERT special tokens before embedding.
112
+ *
113
+ * web-llm's `EmbeddingPipeline` does NOT auto-prepend `[CLS]` / append `[SEP]`
114
+ * (the official MLC embeddings example wraps manually). The Python
115
+ * `sentence_transformers` side that generated the word-vector bin adds these
116
+ * inside `model.encode()`, so we must mirror it here for the runtime context
117
+ * vector to land in the same region of Arctic's embedding space as the bin.
118
+ *
119
+ * No query prefix is applied: the semantic step is sentence-to-sentence (`s2s`)
120
+ * similarity ("which words are conceptually similar to this context?"), not
121
+ * sentence-to-passage (`s2p`) retrieval. Arctic's query prefix would misframe
122
+ * the relationship. Encode both sides as passages. See implementation.md §4.3.
123
+ */
124
+ export const wrapForArctic = (text: string): string => `[CLS] ${text} [SEP]`;
125
+
126
+ /**
127
+ * BE-parity constants — must match `CausalLMEncoder` defaults in the Python
128
+ * sidecar (`cc-smarts/python-sidecar/src/causal_lm_encoder.py`) and
129
+ * `SlowLaneEngine` (`typeahead_context_encoding.py`) so local payloads behave
130
+ * identically to the server-client setup.
131
+ */
132
+ export const BE_PARITY = {
133
+ /** Final payload size cap (BE: `top_k_words`). */
134
+ TOP_K_WORDS: 2000,
135
+ /** L2 (domain) words admitted unconditionally before pooling (BE: `reserved_l2_slots`). */
136
+ RESERVED_L2_SLOTS: 500,
137
+ /** Log-space additive bias favouring L2 over L3 in the pool (BE: `l2_bias`). */
138
+ L2_BIAS: 1.0,
139
+ /** Drop words below this probability from the final payload (BE: `> 0.00001`). */
140
+ MIN_PROB: 0.00001,
141
+ /**
142
+ * Word-level approximation of the BE causal LM token limit.
143
+ *
144
+ * BE: `CausalLMEncoder.max_context_tokens = 100` (BPE tokens, left-truncated).
145
+ * FE: no tokenizer available, so we approximate with word count. English text
146
+ * averages ~1.3–1.5 BPE tokens/word, meaning 100 words ≈ 130–150 tokens.
147
+ * Using 100 words keeps the approximation simple and errs on the side of
148
+ * sending slightly more context than the BE sees — acceptable for a PoC.
149
+ */
150
+ MAX_CONTEXT_TOKENS: 100,
151
+ /**
152
+ * Word-level rolling window for the semantic embedder.
153
+ *
154
+ * BE: `SlowLaneEngine.max_context_words = 100` (applied in
155
+ * `typeahead_context_encoding.py` before calling `SemanticEncoder.encode`).
156
+ * Truncated identically here so the runtime Arctic vector lands in the same
157
+ * region of the embedding space as the precomputed word-vector bin.
158
+ */
159
+ MAX_CONTEXT_WORDS: 100,
160
+ } as const;
161
+
162
+ const splitOnWhitespace = (text: string): string[] => {
163
+ const trimmed = text.trim();
164
+ if (trimmed === '') {
165
+ return [];
166
+ }
167
+
168
+ const words: string[] = [];
169
+ let wordStart = -1;
170
+
171
+ for (let i = 0; i < trimmed.length; i++) {
172
+ if (trimmed[i].trim() === '') {
173
+ if (wordStart !== -1) {
174
+ words.push(trimmed.slice(wordStart, i));
175
+ wordStart = -1;
176
+ }
177
+ continue;
178
+ }
179
+
180
+ if (wordStart === -1) {
181
+ wordStart = i;
182
+ }
183
+ }
184
+
185
+ if (wordStart !== -1) {
186
+ words.push(trimmed.slice(wordStart));
187
+ }
188
+
189
+ return words;
190
+ };
191
+
192
+ /**
193
+ * Return the last `n` whitespace-separated words of `text`, joined by spaces.
194
+ * Mirrors the BE rolling-window truncation applied before both encoders.
195
+ */
196
+ const truncateToLastNWords = (text: string, n: number): string => {
197
+ const words = splitOnWhitespace(text);
198
+ return words.length <= n ? text : words.slice(-n).join(' ');
199
+ };
200
+
201
+ // ─── Logit capture ─────────────────────────────────────────────────────────
202
+
203
+ /**
204
+ * A LogitProcessor that captures the raw next-token logits and passes them
205
+ * through unmodified.
206
+ *
207
+ * web-llm invokes `processLogits` on the CPU after the model's forward pass and
208
+ * before sampling, handing us the full `Float32Array(vocab_size)` at the current
209
+ * decode position. We copy it off web-llm's shared buffer (which it may reuse
210
+ * across calls) and return the original untouched so sampling is unaffected.
211
+ *
212
+ * This is the raw-logit access the BE-parity algorithm needs (masked softmax +
213
+ * prefix expansion, consumed in a later step). Registered for the causal LM
214
+ * only — the embedder never decodes tokens, so it produces no logits.
215
+ */
216
+ class CapturingLogitProcessor implements LogitProcessor {
217
+ captured: Float32Array | null = null;
218
+
219
+ processLogits = (logits: Float32Array): Float32Array => {
220
+ // Copy off web-llm's shared buffer — it may reuse `logits` across calls.
221
+ this.captured = new Float32Array(logits);
222
+ return logits;
223
+ };
224
+
225
+ processSampledToken = (): void => {
226
+ // No-op — we don't track sampled tokens.
227
+ };
228
+
229
+ resetState = (): void => {
230
+ this.captured = null;
231
+ };
232
+ }
233
+
234
+ // ─── BE-parity data + algorithm ──────────────────────────────────────────────
235
+
236
+ /**
237
+ * Prefix-expansion map: first-token id → words whose space-prefixed SmolLM2
238
+ * encoding starts with that token. Generated offline by
239
+ * `scripts/gen_first_token_to_words.py`, which mirrors the BE's in-memory map
240
+ * (`CausalLMEncoder._ensure_loaded`).
241
+ *
242
+ * Populated lazily by `loadBePayloadData()` from a dynamically-imported JSON so
243
+ * the (large) payload is only fetched when the local client is actually
244
+ * initialised — keeping it out of the editor's main chunk for the vast majority
245
+ * of users (who run with `useLocalModel` off).
246
+ */
247
+ let firstTokenToWords: Map<number, string[]> = new Map();
248
+
249
+ /**
250
+ * L2 (Atlassian-domain) word set, derived from the keys of `vocabulary_10k.json`.
251
+ * Used by `computeBePayload` for tier-aware ranking: any word in the prefix map
252
+ * that is not in this set is treated as L3 (general English), matching the BE.
253
+ * Populated lazily alongside `firstTokenToWords` — see `loadBePayloadData()`.
254
+ */
255
+ let l2Words: Set<string> = new Set();
256
+
257
+ /**
258
+ * Array of token IDs that appear as a first token for at least one vocabulary
259
+ * word. Derived from `firstTokenToWords` when the data loads so `computeBePayload`
260
+ * does not re-allocate this array on every word-boundary call.
261
+ */
262
+ let prefixMapTokenIds: number[] = [];
89
263
 
90
- /** HF root for the default weights (includes `tensor-cache.json` for WebLLM 0.2+). */
91
- export const LOCAL_MLC_HF_MODEL_REPO =
92
- 'https://huggingface.co/mlc-ai/SmolLM2-135M-Instruct-q0f16-MLC';
264
+ /** De-dupes concurrent loads and lets repeated calls await the same payload. */
265
+ let bePayloadDataPromise: Promise<void> | undefined;
266
+
267
+ /**
268
+ * Unwrap a dynamically imported JSON module to the parsed JSON value, working
269
+ * across the two interop modes AFM's bundler chain emits:
270
+ *
271
+ * 1. **`.default`-wrapped namespace** — classic webpack (and Jest) hang the
272
+ * JSON value under the `default` export.
273
+ * 2. **Named-exports namespace** — webpack 5 / atlaspack with JSON
274
+ * named-exports (or native ESM JSON modules) expose each top-level key as
275
+ * a named export and shadow `default`, so `mod.default` can be `undefined`
276
+ * (or some unrelated value) even though `mod` itself holds the data.
277
+ *
278
+ * The caller MUST declare the underlying JSON shape via `shape` because, in
279
+ * named-exports mode, a dense array `["a","b"]` and a sparse numeric-keyed
280
+ * object `{"5":"a","12":"b"}` are emitted identically (`{"0":..}` / `{"5":..}`);
281
+ * no runtime heuristic can tell them apart, so only the caller knows which:
282
+ *
283
+ * - `'object'` — the JSON is a `{...}` (including sparse maps keyed by integer
284
+ * IDs). The named exports are rebuilt into a plain object so `Object.entries`
285
+ * yields the real keys, not synthetic array indices.
286
+ * - `'array'` — the JSON is a `[...]`, reconstructed from the `0..n-1` indices.
287
+ *
288
+ * :param mod: The raw module object returned by `await import('./*.json')`.
289
+ * :param shape: `'object'` if the source JSON is `{...}`, `'array'` if `[...]`.
290
+ * :returns: The parsed JSON value, or `null` if neither interop mode applies.
291
+ */
292
+ const unwrapJsonModule = <T,>(mod: unknown, shape: 'object' | 'array'): T | null => {
293
+ if (mod == null || typeof mod !== 'object') {
294
+ return null;
295
+ }
296
+ const namespace = mod as Record<string, unknown> & { default?: unknown };
297
+
298
+ // Compute the named-export own-keys (strip synthetic markers).
299
+ const ownKeys = Object.keys(namespace).filter(
300
+ (k) => k !== 'default' && k !== '__esModule',
301
+ );
302
+
303
+ // PREFER named exports when present — they always reflect the JSON's real
304
+ // top-level keys / indices, regardless of what `default` happens to be.
305
+ // Under JSON named-exports mode `default` is not necessarily the parsed
306
+ // value (e.g. for `{"service": 0, ...}` it can be the number `0`, with the
307
+ // real data in the named exports), so taking `default` first would corrupt it.
308
+ if (ownKeys.length > 0) {
309
+ if (shape === 'array') {
310
+ // JSON arrays are dense; reconstruct from `0..length-1` indices.
311
+ const len = ownKeys.length;
312
+ const arr = new Array(len);
313
+ for (let i = 0; i < len; i++) {
314
+ arr[i] = namespace[String(i)];
315
+ }
316
+ return arr as T;
317
+ }
318
+ // shape === 'object'. Rebuild a plain object from the (stripped) own
319
+ // keys so callers can `Object.entries()` it without iterating over
320
+ // `default` / `__esModule`, and to detach from the module-namespace
321
+ // object (which is sealed/non-extensible on some bundler outputs).
322
+ const obj: Record<string, unknown> = {};
323
+ for (const k of ownKeys) {
324
+ obj[k] = namespace[k];
325
+ }
326
+ return obj as T;
327
+ }
328
+
329
+ // Fallback: no named exports — classic webpack JSON-module interop where
330
+ // the whole parsed JSON value is hung under `default`. Trust it.
331
+ if ('default' in namespace && namespace.default != null) {
332
+ return namespace.default as T;
333
+ }
334
+
335
+ return null;
336
+ };
337
+
338
+ /**
339
+ * Lazily load and build the BE-parity lookup tables from their JSON payloads.
340
+ * The dynamic imports are split into their own async chunks so neither file is
341
+ * bundled into the editor's main chunk unless local inference is initialised.
342
+ *
343
+ * :returns:
344
+ * A promise that resolves once `firstTokenToWords`, `l2Words` and
345
+ * `prefixMapTokenIds` are populated.
346
+ */
347
+ const loadBePayloadData = (): Promise<void> => {
348
+ if (!bePayloadDataPromise) {
349
+ bePayloadDataPromise = (async () => {
350
+ const [firstTokenToWordsModule, vocabularyModule] = await Promise.all([
351
+ import(
352
+ /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-first-token-to-words" */ './data/first_token_to_words.json'
353
+ ),
354
+ import(
355
+ /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-vocabulary-10k" */ './data/vocabulary_10k.json'
356
+ ),
357
+ ]);
358
+
359
+ const firstTokenToWordsData = unwrapJsonModule<Record<string, string[]>>(
360
+ firstTokenToWordsModule,
361
+ 'object',
362
+ );
363
+ const vocabularyData = unwrapJsonModule<{ words: Record<string, unknown> }>(
364
+ vocabularyModule,
365
+ 'object',
366
+ );
367
+
368
+ if (firstTokenToWordsData == null || vocabularyData?.words == null) {
369
+ // Hard-fail with a precise message so the catch() in initEngine logs
370
+ // exactly which import couldn't be unwrapped, rather than the generic
371
+ // V8 "Cannot convert undefined or null to object" we hit before the
372
+ // helper was added.
373
+ throw new Error(
374
+ `[LocalSlowLane] JSON module could not be unwrapped — ` +
375
+ `firstTokenToWordsData=${firstTokenToWordsData == null ? 'null/undefined' : 'defined'}, ` +
376
+ `vocabularyData=${vocabularyData == null ? 'null/undefined' : vocabularyData.words == null ? 'defined but missing .words' : 'defined'}`,
377
+ );
378
+ }
379
+
380
+ firstTokenToWords = new Map(
381
+ Object.entries(firstTokenToWordsData).map(([tokenId, words]) => [
382
+ Number(tokenId),
383
+ words,
384
+ ]),
385
+ );
386
+ l2Words = new Set(Object.keys(vocabularyData.words));
387
+ prefixMapTokenIds = Array.from(firstTokenToWords.keys());
93
388
 
94
- export const LOCAL_MLC_MODEL_LIB_WASM_NAME = 'SmolLM2-135M-Instruct-q0f16-ctx4k_cs1k-webgpu.wasm';
389
+ if (isAutocompleteDebugEnabled()) {
390
+ // eslint-disable-next-line no-console
391
+ console.log(
392
+ '%c[LocalSlowLane] %c✅ BE-parity payload data loaded:',
393
+ 'color: #9c27b0; font-weight: bold;',
394
+ 'color: #4caf50; font-weight: bold;',
395
+ {
396
+ firstTokenToWordsEntries: firstTokenToWords.size,
397
+ l2WordsCount: l2Words.size,
398
+ prefixMapTokenIdsLength: prefixMapTokenIds.length,
399
+ },
400
+ );
401
+ }
402
+ })().catch((e) => {
403
+ // Don't cache a rejected promise — a transient import failure would
404
+ // otherwise prevent the local model from ever initialising again this
405
+ // session. Reset so the next init attempt retries.
406
+ bePayloadDataPromise = undefined;
407
+ throw e;
408
+ });
409
+ }
410
+ return bePayloadDataPromise;
411
+ };
95
412
 
96
413
  /**
97
- * Original target repo (add-basics fine-tune). **Not compatible with WebLLM 0.2.x** (no `tensor-cache.json`).
98
- * @see module doc above
414
+ * Convert a raw next-token logit vector into a whole-word probability payload,
415
+ * faithfully porting the BE `CausalLMEncoder._get_top_k_probs`
416
+ * (`cc-smarts/python-sidecar/src/causal_lm_encoder.py`).
417
+ *
418
+ * Steps: (1) numerically-stable masked softmax over only the token ids present
419
+ * in the prefix-expansion map; (2) spread each token's probability to every
420
+ * whole word sharing that first token, taking the max; (3) reserve the top L2
421
+ * words unconditionally; (4) rank the remainder in a log-space pool with an
422
+ * additive L2 bias; (5) emit raw probabilities for the survivors, lowercased
423
+ * and trimmed at `MIN_PROB`.
424
+ *
425
+ * :params:
426
+ * rawLogits: Full-vocabulary logits from the LM's single decode step
427
+ * prefixMap: Map of first-token id to the words starting with that token
428
+ * domainWords: Set of L2 (domain) words, for tier-aware ranking
429
+ * :returns:
430
+ * A record of lowercase word to probability — the BE `lm_logits` payload
99
431
  */
100
- export const HUGGINGFACE_TB_SMOLLM_ADD_BASICS_REPO =
101
- 'https://huggingface.co/HuggingFaceTB/smollm-135M-instruct-add-basics-q0f16-MLC';
432
+ export const computeBePayload = (
433
+ rawLogits: Float32Array,
434
+ prefixMap: Map<number, string[]>,
435
+ domainWords: Set<string>,
436
+ /**
437
+ * Pre-derived token-ID array for the softmax mask. Defaults to the
438
+ * module-level `prefixMapTokenIds` (zero allocation in production). Pass
439
+ * `Array.from(prefixMap.keys())` in tests that supply a custom prefixMap so
440
+ * the softmax mask stays consistent with the iteration in Step 2.
441
+ */
442
+ validTokenIds: number[] = prefixMapTokenIds,
443
+ ): Record<string, number> => {
444
+
445
+ // 1. Numerically-stable masked softmax over validTokenIds only.
446
+ let maxLogit = -Infinity;
447
+ for (const id of validTokenIds) {
448
+ const v = rawLogits[id];
449
+ if (v > maxLogit) {
450
+ maxLogit = v;
451
+ }
452
+ }
453
+ let sumExp = 0;
454
+ const expByToken = new Map<number, number>();
455
+ for (const id of validTokenIds) {
456
+ const e = Math.exp(rawLogits[id] - maxLogit);
457
+ expByToken.set(id, e);
458
+ sumExp += e;
459
+ }
460
+
461
+ // 2. Prefix expansion with max aggregation (probabilities sum to 1 over the
462
+ // masked subset, so divide each token's exp by sumExp on the fly).
463
+ const wordProbs = new Map<string, number>();
464
+ for (const [id, words] of prefixMap) {
465
+ const p = sumExp > 0 ? (expByToken.get(id) ?? 0) / sumExp : 0;
466
+ for (const w of words) {
467
+ const prev = wordProbs.get(w) ?? 0;
468
+ if (p > prev) {
469
+ wordProbs.set(w, p);
470
+ }
471
+ }
472
+ }
473
+
474
+ // 3. Split into L2 / L3 and reserve the top L2 slots unconditionally.
475
+ const l2Matches: Array<[string, number]> = [];
476
+ const l3Matches: Array<[string, number]> = [];
477
+ for (const [w, p] of wordProbs) {
478
+ if (domainWords.has(w)) {
479
+ l2Matches.push([w, p]);
480
+ } else {
481
+ l3Matches.push([w, p]);
482
+ }
483
+ }
484
+ l2Matches.sort((a, b) => b[1] - a[1]);
485
+ const reserved = l2Matches.slice(0, BE_PARITY.RESERVED_L2_SLOTS);
486
+
487
+ // 4. Pool the leftovers in log space; the L2 bias only affects ranking here.
488
+ // Words in l2Matches are unique and the array is sorted descending, so the
489
+ // non-reserved entries are exactly the tail after the reserved prefix — slice
490
+ // it directly rather than allocating a Set and scanning every entry on this
491
+ // hot path (runs ~every word boundary while typing).
492
+ const pool: Array<[string, number]> = [];
493
+ for (const [w, p] of l2Matches.slice(BE_PARITY.RESERVED_L2_SLOTS)) {
494
+ pool.push([w, Math.log(Math.max(p, 1e-10)) + BE_PARITY.L2_BIAS]);
495
+ }
496
+ for (const [w, p] of l3Matches) {
497
+ pool.push([w, Math.log(Math.max(p, 1e-10))]);
498
+ }
499
+ pool.sort((a, b) => b[1] - a[1]);
500
+ const remainingSlots = Math.max(0, BE_PARITY.TOP_K_WORDS - reserved.length);
501
+ const poolWinners = pool.slice(0, remainingSlots);
502
+
503
+ // 5. Assemble payload: store RAW probabilities (the bias was ranking-only),
504
+ // lowercase keys, trimmed at MIN_PROB. Reserved first, then pool winners.
505
+ // Reserved entries are written first; pool-winner writes must NOT clobber a
506
+ // reserved entry whose normalised key collides (two source words can
507
+ // `.trim().toLowerCase()` to the same key — e.g. "Function" vs "function ").
508
+ // Without the existence guard, a low-probability pool winner would silently
509
+ // overwrite the (higher-probability) reserved entry, degrading top-K
510
+ // quality in a way that's invisible from the debug summary.
511
+ const result: Record<string, number> = {};
512
+ const addEntry = (word: string, prob: number, allowOverwrite: boolean): void => {
513
+ if (prob <= BE_PARITY.MIN_PROB) {
514
+ return;
515
+ }
516
+ const key = word.trim().toLowerCase();
517
+ if (!allowOverwrite && key in result) {
518
+ return;
519
+ }
520
+ result[key] = prob;
521
+ };
522
+ for (const [w, p] of reserved) {
523
+ addEntry(w, p, true);
524
+ }
525
+ for (const [w] of poolWinners) {
526
+ addEntry(w, wordProbs.get(w) ?? 0, false);
527
+ }
528
+
529
+ if (isAutocompleteDebugEnabled()) {
530
+ const topReserved = reserved
531
+ .slice(0, 5)
532
+ .map(([w, p]) => `${w}:${(p * 100).toFixed(2)}%`)
533
+ .join(', ');
534
+ const topPool = poolWinners
535
+ .slice(0, 5)
536
+ .map(([w]) => `${w}:${((wordProbs.get(w) ?? 0) * 100).toFixed(2)}%`)
537
+ .join(', ');
538
+ // eslint-disable-next-line no-console
539
+ console.log(
540
+ '%c[computeBePayload] %c%d valid tokens → %d words expanded | L2: %d / L3: %d | reserved: %d | pool winners: %d | final: %d words\n maxLogit(masked): %s | sumExp: %s\n top reserved L2: %s\n top pool: %s',
541
+ 'color: #9c27b0; font-weight: bold;',
542
+ 'color: inherit;',
543
+ validTokenIds.length,
544
+ wordProbs.size,
545
+ l2Matches.length,
546
+ l3Matches.length,
547
+ reserved.length,
548
+ poolWinners.length,
549
+ Object.keys(result).length,
550
+ maxLogit.toFixed(3),
551
+ sumExp.toFixed(1),
552
+ topReserved || '(none)',
553
+ topPool || '(none)',
554
+ );
555
+ }
556
+
557
+ return result;
558
+ };
102
559
 
103
560
  // ─── Factory ─────────────────────────────────────────────────────────────────
104
561
 
@@ -127,7 +584,7 @@ export const createLocalSlowLaneClient = (
127
584
  debounceMs = DEFAULT_DEBOUNCE_MS,
128
585
  onUpdate,
129
586
  onStatus,
130
- modelId = LOCAL_MLC_MODEL_ID,
587
+ modelId = LOCAL_MLC_CAUSAL_MODEL_ID,
131
588
  customModelConfig,
132
589
  } = config;
133
590
 
@@ -143,6 +600,9 @@ export const createLocalSlowLaneClient = (
143
600
  let initFailed = false;
144
601
  let engine: MLCEngine | null = null;
145
602
  let engineInitPromise: Promise<void> | null = null;
603
+ // Captures raw next-token logits from the LM's single decode step. Registered
604
+ // with the engine below; `lmLogitsCapture.captured` is consumed in a later step.
605
+ const lmLogitsCapture = new CapturingLogitProcessor();
146
606
 
147
607
  const unloadEngine = (engineToUnload: MLCEngine): void => {
148
608
  engineToUnload.unload().catch((error: unknown) => {
@@ -178,20 +638,25 @@ export const createLocalSlowLaneClient = (
178
638
  if (isAutocompleteDebugEnabled()) {
179
639
  // eslint-disable-next-line no-console
180
640
  console.log(
181
- `%c[LocalSlowLane] %c🚀 Initialising MLC engine with model: ${modelId}`,
641
+ `%c[LocalSlowLane] %c🚀 Initialising MLC engine with models: ${modelId} (LM) + ${LOCAL_MLC_EMBEDDING_MODEL_ID} (embedder)`,
182
642
  'color: #9c27b0; font-weight: bold;',
183
643
  'color: inherit;',
184
644
  );
185
645
  }
186
- onStatus?.(`Initialising model: ${modelId}…`);
646
+ onStatus?.(`Initialising models: ${modelId} + ${LOCAL_MLC_EMBEDDING_MODEL_ID}…`);
187
647
 
188
648
  if (!('gpu' in navigator)) {
189
649
  throw new Error('WebGPU not supported');
190
650
  }
191
651
 
192
- const { CreateMLCEngine, prebuiltAppConfig } = await import(
193
- /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-mlc-web-llm" */ '@mlc-ai/web-llm'
194
- );
652
+ // Fetch the web-llm runtime and the BE-parity lookup tables in parallel;
653
+ // both are dynamically imported so they stay out of the main editor chunk.
654
+ const [{ MLCEngine: MLCEngineCtor, prebuiltAppConfig }] = await Promise.all([
655
+ import(
656
+ /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-mlc-web-llm" */ '@mlc-ai/web-llm'
657
+ ),
658
+ loadBePayloadData(),
659
+ ]);
195
660
 
196
661
  const customModelRecord: WebLlmModelRecord | undefined = customModelConfig
197
662
  ? {
@@ -222,27 +687,49 @@ export const createLocalSlowLaneClient = (
222
687
  ],
223
688
  };
224
689
 
225
- engine = await CreateMLCEngine(modelId, {
690
+ // Construct the engine with the logit-capture processor registered for
691
+ // the causal LM only (the embedder never decodes tokens), then load
692
+ // both the LM and the embedder into the same engine (multi-model).
693
+ const newEngine = new MLCEngineCtor({
226
694
  appConfig,
227
695
  initProgressCallback,
696
+ logitProcessorRegistry: new Map([[modelId, lmLogitsCapture]]),
228
697
  });
229
698
 
699
+ await newEngine.reload([modelId, LOCAL_MLC_EMBEDDING_MODEL_ID]);
700
+
230
701
  if (destroyed) {
231
702
  // destroy() was called while we were loading — clean up
232
- unloadEngine(engine);
233
- engine = null;
703
+ unloadEngine(newEngine);
234
704
  return;
235
705
  }
236
706
 
707
+ engine = newEngine;
237
708
  ready = true;
238
709
 
239
710
  if (isAutocompleteDebugEnabled()) {
240
711
  // eslint-disable-next-line no-console
241
712
  console.log(
242
- '%c[LocalSlowLane] %c✅ MLC engine loaded and ready',
713
+ '%c[LocalSlowLane] %c✅ Both models loaded and ready',
243
714
  'color: #9c27b0; font-weight: bold;',
244
715
  'color: #4caf50;',
245
716
  );
717
+ // One-time identity summary so you can confirm which models are active
718
+ // without digging through the init-progress scroll.
719
+ // eslint-disable-next-line no-console
720
+ console.log(
721
+ '%c[LocalSlowLane] %c🧠 Causal LM →',
722
+ 'color: #9c27b0; font-weight: bold;',
723
+ 'color: #2196f3; font-weight: bold;',
724
+ modelId,
725
+ );
726
+ // eslint-disable-next-line no-console
727
+ console.log(
728
+ '%c[LocalSlowLane] %c🔢 Embedder →',
729
+ 'color: #9c27b0; font-weight: bold;',
730
+ 'color: #009688; font-weight: bold;',
731
+ LOCAL_MLC_EMBEDDING_MODEL_ID,
732
+ );
246
733
  }
247
734
  onStatus?.('Model loaded and ready.');
248
735
  } catch (err) {
@@ -271,83 +758,122 @@ export const createLocalSlowLaneClient = (
271
758
  // ── Inference ──────────────────────────────────────────────────────────
272
759
 
273
760
  /**
274
- * Run a single forward pass to extract next-token logit probabilities.
761
+ * Run a single forward pass to produce the BE-parity slow-lane outputs.
275
762
  *
276
- * We use the chat completions API with `max_tokens: 1` and `logprobs: true`
277
- * to get the model's next-token distribution without generating text.
278
- * This is the cheapest possible inference call — a single forward pass.
763
+ * Two calls run in parallel on the shared engine:
764
+ * - `completions.create({ max_tokens: 1 })` runs the causal LM for exactly
765
+ * one decode step. We ignore the generated text; the LogitProcessor
766
+ * captures the raw next-token logits during that step, which we turn into
767
+ * a whole-word payload via `computeBePayload`.
768
+ * - `embeddings.create(...)` runs the Arctic embedder to produce the real
769
+ * 384-d semantic vector (passage-encoded; see `wrapForArctic`).
279
770
  */
280
771
  const runInference = async (text: string, requestId: number): Promise<void> => {
281
772
  if (!engine || destroyed) {
282
773
  return;
283
774
  }
284
775
 
776
+ // Clear the capture buffer so we read only this pass's logits. The engine
777
+ // serialises per-model requests and updateContext is debounced, so the
778
+ // latest request's decode step is the last to populate `captured` before
779
+ // we read it below; stale requests bail on the latestRequestId guard.
780
+ lmLogitsCapture.resetState();
781
+
782
+ // Apply BE-parity rolling-window truncation before both encoders.
783
+ // BE semantic: last max_context_words words (typeahead_context_encoding.py:36)
784
+ // BE causal LM: last max_context_tokens BPE tokens (causal_lm_encoder.py:194–198),
785
+ // approximated here with word count (no tokenizer available on FE).
786
+ const lmText = truncateToLastNWords(text, BE_PARITY.MAX_CONTEXT_TOKENS);
787
+ const semanticText = truncateToLastNWords(text, BE_PARITY.MAX_CONTEXT_WORDS);
788
+ const arcticInput = wrapForArctic(semanticText);
789
+ const captureCompletionTime = <T,>(
790
+ promise: Promise<T>,
791
+ onResolved: (resolvedAt: number) => void,
792
+ ): Promise<T> =>
793
+ promise.then((value: T) => {
794
+ onResolved(performance.now());
795
+ return value;
796
+ });
797
+
798
+ if (isAutocompleteDebugEnabled()) {
799
+ // eslint-disable-next-line no-console
800
+ console.log(
801
+ `%c[LocalSlowLane] %c🔢 Arctic input (${arcticInput.length} chars, ${splitOnWhitespace(semanticText).length} words): "${arcticInput.length > 100 ? `${arcticInput.slice(0, 100)}…` : arcticInput}"`,
802
+ 'color: #9c27b0; font-weight: bold;',
803
+ 'color: #009688;',
804
+ );
805
+ // eslint-disable-next-line no-console
806
+ console.log(
807
+ `%c[LocalSlowLane] %c🧠 LM input (${lmText.length} chars, ${splitOnWhitespace(lmText).length} words): "${lmText.length > 100 ? `${lmText.slice(0, 100)}…` : lmText}"`,
808
+ 'color: #9c27b0; font-weight: bold;',
809
+ 'color: #2196f3;',
810
+ );
811
+ }
812
+
285
813
  try {
286
- // Use chat completion with logprobs to get next-token distribution
287
- const response = await engine.chat.completions.create({
288
- messages: [
289
- {
290
- role: 'user',
291
- content: text,
814
+ const tStart = performance.now();
815
+ let tLmDone = 0;
816
+ let tEmbDone = 0;
817
+
818
+ const [, embeddingResponse] = await Promise.all([
819
+ captureCompletionTime(
820
+ engine.completions.create({
821
+ model: modelId,
822
+ prompt: lmText,
823
+ max_tokens: 1,
824
+ temperature: 0,
825
+ logprobs: false,
826
+ })
827
+ ,
828
+ (resolvedAt) => {
829
+ tLmDone = resolvedAt;
292
830
  },
293
- ],
294
- max_tokens: 1,
295
- logprobs: true,
296
- top_logprobs: 5,
297
- temperature: 0,
298
- });
831
+ ),
832
+ captureCompletionTime(
833
+ engine.embeddings.create({
834
+ model: LOCAL_MLC_EMBEDDING_MODEL_ID,
835
+ input: arcticInput,
836
+ })
837
+ ,
838
+ (resolvedAt) => {
839
+ tEmbDone = resolvedAt;
840
+ },
841
+ ),
842
+ ]);
843
+
844
+ if (isAutocompleteDebugEnabled()) {
845
+ // eslint-disable-next-line no-console
846
+ console.log(
847
+ `%c[LocalSlowLane] %c⏱ LM: ${(tLmDone - tStart).toFixed(0)}ms | Embedder: ${(tEmbDone - tStart).toFixed(0)}ms | Total: ${(Math.max(tLmDone, tEmbDone) - tStart).toFixed(0)}ms`,
848
+ 'color: #9c27b0; font-weight: bold;',
849
+ 'color: #ff9800;',
850
+ );
851
+ }
299
852
 
300
853
  // Discard stale results
301
854
  if (requestId < latestRequestId || destroyed) {
302
855
  return;
303
856
  }
304
857
 
305
- // ── Extract LM logits ───────────────────────────────────────
306
- const lmLogits: Record<string, number> = {};
307
-
308
- const logprobsContent = response.choices?.[0]?.logprobs?.content;
309
- if (logprobsContent && logprobsContent.length > 0) {
310
- const tokenLogprobs = logprobsContent[0];
311
-
312
- // Add the top token
313
- if (tokenLogprobs.token) {
314
- const token = tokenLogprobs.token.trim().toLowerCase();
315
- // @ts-ignore TS1501: Unicode regex flag requires a newer TS target than the declaration build uses.
316
- if (token.length > 0 && /^[a-z]/iu.test(token)) {
317
- lmLogits[token] = Math.exp(tokenLogprobs.logprob);
318
- }
319
- }
320
-
321
- // Add alternative tokens from top_logprobs
322
- if (tokenLogprobs.top_logprobs) {
323
- for (const alt of tokenLogprobs.top_logprobs) {
324
- const token = alt.token.trim().toLowerCase();
325
- // @ts-ignore TS1501: Unicode regex flag requires a newer TS target than the declaration build uses.
326
- if (token.length > 0 && /^[a-z]/iu.test(token)) {
327
- lmLogits[token] = Math.exp(alt.logprob);
328
- }
329
- }
330
- }
331
- }
332
-
333
- storedLmLogits = Object.keys(lmLogits).length > 0 ? lmLogits : null;
334
-
335
- // ── Semantic vector ─────────────────────────────────────────
336
- // SmolLM is a generative model, not an embedding model, so we
337
- // don't get a true semantic vector. We generate a lightweight
338
- // pseudo-embedding from the logit distribution for compatibility
339
- // with the existing scoring pipeline.
340
- //
341
- // For a production implementation, you would use a dedicated
342
- // embedding model (e.g. via web-llm's embeddings API with an
343
- // embedding-specific model).
344
- if (storedLmLogits) {
345
- const logitValues = Object.values(storedLmLogits);
346
- storedContextVector = new Float32Array(logitValues);
858
+ // ── LM logits: whole-word BE-parity payload ──────────────────
859
+ const rawLogits = lmLogitsCapture.captured;
860
+ if (rawLogits) {
861
+ const payload = computeBePayload(rawLogits, firstTokenToWords, l2Words);
862
+ storedLmLogits = Object.keys(payload).length > 0 ? payload : null;
347
863
  } else {
348
- storedContextVector = null;
864
+ storedLmLogits = null;
349
865
  }
350
866
 
867
+ // ── Semantic vector: real 384-d Arctic embedding ─────────────
868
+ // Guard against base64-encoded responses (encoding_format: 'base64' would
869
+ // yield a string, and new Float32Array(string) silently produces an empty
870
+ // array, corrupting downstream cosine-similarity scoring).
871
+ const embedding = (embeddingResponse as EmbeddingApiResponse).data?.[0]?.embedding;
872
+ storedContextVector =
873
+ Array.isArray(embedding) && embedding.length > 0
874
+ ? new Float32Array(embedding as number[])
875
+ : null;
876
+
351
877
  if (isAutocompleteDebugEnabled()) {
352
878
  // eslint-disable-next-line no-console
353
879
  console.groupCollapsed(
@@ -355,16 +881,23 @@ export const createLocalSlowLaneClient = (
355
881
  'color: #9c27b0; font-weight: bold;',
356
882
  'color: inherit;',
357
883
  );
358
- // eslint-disable-next-line no-console
359
- console.log(
360
- storedContextVector
361
- ? `✅ pseudo-vector: ${storedContextVector.length} dims`
362
- : '❌ No vector',
363
- );
884
+ if (storedContextVector) {
885
+ let sumSq = 0;
886
+ for (let i = 0; i < storedContextVector.length; i++) {
887
+ sumSq += storedContextVector[i] * storedContextVector[i];
888
+ }
889
+ // eslint-disable-next-line no-console
890
+ console.log(
891
+ `✅ semantic vector: ${storedContextVector.length} dims (L2 norm ${Math.sqrt(sumSq).toFixed(3)})`,
892
+ );
893
+ } else {
894
+ // eslint-disable-next-line no-console
895
+ console.log('❌ No vector');
896
+ }
364
897
  // eslint-disable-next-line no-console
365
898
  console.log(
366
899
  storedLmLogits
367
- ? `✅ lm_logits: ${Object.keys(storedLmLogits).length} tokens`
900
+ ? `✅ lm_logits: ${Object.keys(storedLmLogits).length} words`
368
901
  : '❌ No lm_logits',
369
902
  );
370
903
  if (storedLmLogits) {