@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,28 @@
1
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
1
2
  /**
2
3
  * Local Slow Lane Client: On-device inference via @mlc-ai/web-llm.
3
4
  *
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.
5
+ * Drop-in replacement for the network-based slow-lane-client. Instead of calling
6
+ * a backend API, this client runs two models in the browser via WebGPU, in a
7
+ * single MLCEngine, to reproduce the BE encoder's outputs on-device:
8
+ *
9
+ * - Causal LM (SmolLM2-135M-Instruct): one decode step per word boundary. A
10
+ * registered LogitProcessor captures the raw next-token logits, which
11
+ * `computeBePayload` turns into a whole-word `lm_logits` payload — a faithful
12
+ * port of the BE `CausalLMEncoder._get_top_k_probs` (masked softmax over the
13
+ * vocab's first-tokens, prefix expansion, L2 reservation, log-space pooling).
14
+ * - Semantic embedder (Snowflake Arctic Embed S): produces the real 384-d
15
+ * `semantic_vector`. Inputs are wrapped as passages (see `wrapForArctic`) so
16
+ * the runtime vector lands in the same space as the precomputed word bin.
7
17
  *
8
18
  * ── 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:
19
+ * The models are small enough (~640 MB combined VRAM) that WebGPU inference on
20
+ * the main thread is viable:
11
21
  *
12
22
  * - 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)
23
+ * - CPU overhead (BE-parity post-processing) is a few ms
24
+ * - Per-inference latency is well within autocomplete expectations
25
+ * (~250 ms between word boundaries)
16
26
  *
17
27
  * This avoids all the complexity of Web Workers:
18
28
  * - No CSP workarounds (blob URLs, inline scripts)
@@ -36,17 +46,404 @@ import { isWordBoundary } from './slow-lane-client';
36
46
  // ─── Constants ───────────────────────────────────────────────────────────────
37
47
 
38
48
  const DEFAULT_DEBOUNCE_MS = 300;
39
- export const LOCAL_MLC_MODEL_ID = 'SmolLM2-135M-Instruct-q0f16-MLC';
49
+ export const LOCAL_MLC_CAUSAL_MODEL_ID = 'SmolLM2-135M-Instruct-q0f16-MLC';
50
+
51
+ /**
52
+ * MLC ID for the semantic embedder (Snowflake Arctic Embed S, batch=4 variant).
53
+ *
54
+ * The `-b4` suffix selects the prebuilt variant compiled for a max batch size of
55
+ * 4 (≈239 MB VRAM) rather than `-b32` (≈1023 MB VRAM). Autocomplete embeds one
56
+ * context at a time, so `-b4` is the right fit. This model IS in
57
+ * `prebuiltAppConfig.model_list` of web-llm 0.2.82 — no `customModelConfig` needed.
58
+ */
59
+ export const LOCAL_MLC_EMBEDDING_MODEL_ID = 'snowflake-arctic-embed-s-q0f32-MLC-b4';
60
+
61
+ /**
62
+ * Wrap raw context text with BERT special tokens before embedding.
63
+ *
64
+ * web-llm's `EmbeddingPipeline` does NOT auto-prepend `[CLS]` / append `[SEP]`
65
+ * (the official MLC embeddings example wraps manually). The Python
66
+ * `sentence_transformers` side that generated the word-vector bin adds these
67
+ * inside `model.encode()`, so we must mirror it here for the runtime context
68
+ * vector to land in the same region of Arctic's embedding space as the bin.
69
+ *
70
+ * No query prefix is applied: the semantic step is sentence-to-sentence (`s2s`)
71
+ * similarity ("which words are conceptually similar to this context?"), not
72
+ * sentence-to-passage (`s2p`) retrieval. Arctic's query prefix would misframe
73
+ * the relationship. Encode both sides as passages. See implementation.md §4.3.
74
+ */
75
+ export const wrapForArctic = text => `[CLS] ${text} [SEP]`;
76
+
77
+ /**
78
+ * BE-parity constants — must match `CausalLMEncoder` defaults in the Python
79
+ * sidecar (`cc-smarts/python-sidecar/src/causal_lm_encoder.py`) and
80
+ * `SlowLaneEngine` (`typeahead_context_encoding.py`) so local payloads behave
81
+ * identically to the server-client setup.
82
+ */
83
+ export const BE_PARITY = {
84
+ /** Final payload size cap (BE: `top_k_words`). */
85
+ TOP_K_WORDS: 2000,
86
+ /** L2 (domain) words admitted unconditionally before pooling (BE: `reserved_l2_slots`). */
87
+ RESERVED_L2_SLOTS: 500,
88
+ /** Log-space additive bias favouring L2 over L3 in the pool (BE: `l2_bias`). */
89
+ L2_BIAS: 1.0,
90
+ /** Drop words below this probability from the final payload (BE: `> 0.00001`). */
91
+ MIN_PROB: 0.00001,
92
+ /**
93
+ * Word-level approximation of the BE causal LM token limit.
94
+ *
95
+ * BE: `CausalLMEncoder.max_context_tokens = 100` (BPE tokens, left-truncated).
96
+ * FE: no tokenizer available, so we approximate with word count. English text
97
+ * averages ~1.3–1.5 BPE tokens/word, meaning 100 words ≈ 130–150 tokens.
98
+ * Using 100 words keeps the approximation simple and errs on the side of
99
+ * sending slightly more context than the BE sees — acceptable for a PoC.
100
+ */
101
+ MAX_CONTEXT_TOKENS: 100,
102
+ /**
103
+ * Word-level rolling window for the semantic embedder.
104
+ *
105
+ * BE: `SlowLaneEngine.max_context_words = 100` (applied in
106
+ * `typeahead_context_encoding.py` before calling `SemanticEncoder.encode`).
107
+ * Truncated identically here so the runtime Arctic vector lands in the same
108
+ * region of the embedding space as the precomputed word-vector bin.
109
+ */
110
+ MAX_CONTEXT_WORDS: 100
111
+ };
112
+ const splitOnWhitespace = text => {
113
+ const trimmed = text.trim();
114
+ if (trimmed === '') {
115
+ return [];
116
+ }
117
+ const words = [];
118
+ let wordStart = -1;
119
+ for (let i = 0; i < trimmed.length; i++) {
120
+ if (trimmed[i].trim() === '') {
121
+ if (wordStart !== -1) {
122
+ words.push(trimmed.slice(wordStart, i));
123
+ wordStart = -1;
124
+ }
125
+ continue;
126
+ }
127
+ if (wordStart === -1) {
128
+ wordStart = i;
129
+ }
130
+ }
131
+ if (wordStart !== -1) {
132
+ words.push(trimmed.slice(wordStart));
133
+ }
134
+ return words;
135
+ };
136
+
137
+ /**
138
+ * Return the last `n` whitespace-separated words of `text`, joined by spaces.
139
+ * Mirrors the BE rolling-window truncation applied before both encoders.
140
+ */
141
+ const truncateToLastNWords = (text, n) => {
142
+ const words = splitOnWhitespace(text);
143
+ return words.length <= n ? text : words.slice(-n).join(' ');
144
+ };
145
+
146
+ // ─── Logit capture ─────────────────────────────────────────────────────────
147
+
148
+ /**
149
+ * A LogitProcessor that captures the raw next-token logits and passes them
150
+ * through unmodified.
151
+ *
152
+ * web-llm invokes `processLogits` on the CPU after the model's forward pass and
153
+ * before sampling, handing us the full `Float32Array(vocab_size)` at the current
154
+ * decode position. We copy it off web-llm's shared buffer (which it may reuse
155
+ * across calls) and return the original untouched so sampling is unaffected.
156
+ *
157
+ * This is the raw-logit access the BE-parity algorithm needs (masked softmax +
158
+ * prefix expansion, consumed in a later step). Registered for the causal LM
159
+ * only — the embedder never decodes tokens, so it produces no logits.
160
+ */
161
+ class CapturingLogitProcessor {
162
+ constructor() {
163
+ _defineProperty(this, "captured", null);
164
+ _defineProperty(this, "processLogits", logits => {
165
+ // Copy off web-llm's shared buffer — it may reuse `logits` across calls.
166
+ this.captured = new Float32Array(logits);
167
+ return logits;
168
+ });
169
+ _defineProperty(this, "processSampledToken", () => {
170
+ // No-op — we don't track sampled tokens.
171
+ });
172
+ _defineProperty(this, "resetState", () => {
173
+ this.captured = null;
174
+ });
175
+ }
176
+ }
177
+
178
+ // ─── BE-parity data + algorithm ──────────────────────────────────────────────
179
+
180
+ /**
181
+ * Prefix-expansion map: first-token id → words whose space-prefixed SmolLM2
182
+ * encoding starts with that token. Generated offline by
183
+ * `scripts/gen_first_token_to_words.py`, which mirrors the BE's in-memory map
184
+ * (`CausalLMEncoder._ensure_loaded`).
185
+ *
186
+ * Populated lazily by `loadBePayloadData()` from a dynamically-imported JSON so
187
+ * the (large) payload is only fetched when the local client is actually
188
+ * initialised — keeping it out of the editor's main chunk for the vast majority
189
+ * of users (who run with `useLocalModel` off).
190
+ */
191
+ let firstTokenToWords = new Map();
192
+
193
+ /**
194
+ * L2 (Atlassian-domain) word set, derived from the keys of `vocabulary_10k.json`.
195
+ * Used by `computeBePayload` for tier-aware ranking: any word in the prefix map
196
+ * that is not in this set is treated as L3 (general English), matching the BE.
197
+ * Populated lazily alongside `firstTokenToWords` — see `loadBePayloadData()`.
198
+ */
199
+ let l2Words = new Set();
200
+
201
+ /**
202
+ * Array of token IDs that appear as a first token for at least one vocabulary
203
+ * word. Derived from `firstTokenToWords` when the data loads so `computeBePayload`
204
+ * does not re-allocate this array on every word-boundary call.
205
+ */
206
+ let prefixMapTokenIds = [];
207
+
208
+ /** De-dupes concurrent loads and lets repeated calls await the same payload. */
209
+ let bePayloadDataPromise;
210
+
211
+ /**
212
+ * Unwrap a dynamically imported JSON module to the parsed JSON value, working
213
+ * across the two interop modes AFM's bundler chain emits:
214
+ *
215
+ * 1. **`.default`-wrapped namespace** — classic webpack (and Jest) hang the
216
+ * JSON value under the `default` export.
217
+ * 2. **Named-exports namespace** — webpack 5 / atlaspack with JSON
218
+ * named-exports (or native ESM JSON modules) expose each top-level key as
219
+ * a named export and shadow `default`, so `mod.default` can be `undefined`
220
+ * (or some unrelated value) even though `mod` itself holds the data.
221
+ *
222
+ * The caller MUST declare the underlying JSON shape via `shape` because, in
223
+ * named-exports mode, a dense array `["a","b"]` and a sparse numeric-keyed
224
+ * object `{"5":"a","12":"b"}` are emitted identically (`{"0":..}` / `{"5":..}`);
225
+ * no runtime heuristic can tell them apart, so only the caller knows which:
226
+ *
227
+ * - `'object'` — the JSON is a `{...}` (including sparse maps keyed by integer
228
+ * IDs). The named exports are rebuilt into a plain object so `Object.entries`
229
+ * yields the real keys, not synthetic array indices.
230
+ * - `'array'` — the JSON is a `[...]`, reconstructed from the `0..n-1` indices.
231
+ *
232
+ * :param mod: The raw module object returned by `await import('./*.json')`.
233
+ * :param shape: `'object'` if the source JSON is `{...}`, `'array'` if `[...]`.
234
+ * :returns: The parsed JSON value, or `null` if neither interop mode applies.
235
+ */
236
+ const unwrapJsonModule = (mod, shape) => {
237
+ if (mod == null || typeof mod !== 'object') {
238
+ return null;
239
+ }
240
+ const namespace = mod;
241
+
242
+ // Compute the named-export own-keys (strip synthetic markers).
243
+ const ownKeys = Object.keys(namespace).filter(k => k !== 'default' && k !== '__esModule');
244
+
245
+ // PREFER named exports when present — they always reflect the JSON's real
246
+ // top-level keys / indices, regardless of what `default` happens to be.
247
+ // Under JSON named-exports mode `default` is not necessarily the parsed
248
+ // value (e.g. for `{"service": 0, ...}` it can be the number `0`, with the
249
+ // real data in the named exports), so taking `default` first would corrupt it.
250
+ if (ownKeys.length > 0) {
251
+ if (shape === 'array') {
252
+ // JSON arrays are dense; reconstruct from `0..length-1` indices.
253
+ const len = ownKeys.length;
254
+ const arr = new Array(len);
255
+ for (let i = 0; i < len; i++) {
256
+ arr[i] = namespace[String(i)];
257
+ }
258
+ return arr;
259
+ }
260
+ // shape === 'object'. Rebuild a plain object from the (stripped) own
261
+ // keys so callers can `Object.entries()` it without iterating over
262
+ // `default` / `__esModule`, and to detach from the module-namespace
263
+ // object (which is sealed/non-extensible on some bundler outputs).
264
+ const obj = {};
265
+ for (const k of ownKeys) {
266
+ obj[k] = namespace[k];
267
+ }
268
+ return obj;
269
+ }
40
270
 
41
- /** HF root for the default weights (includes `tensor-cache.json` for WebLLM 0.2+). */
42
- export const LOCAL_MLC_HF_MODEL_REPO = 'https://huggingface.co/mlc-ai/SmolLM2-135M-Instruct-q0f16-MLC';
43
- export const LOCAL_MLC_MODEL_LIB_WASM_NAME = 'SmolLM2-135M-Instruct-q0f16-ctx4k_cs1k-webgpu.wasm';
271
+ // Fallback: no named exports — classic webpack JSON-module interop where
272
+ // the whole parsed JSON value is hung under `default`. Trust it.
273
+ if ('default' in namespace && namespace.default != null) {
274
+ return namespace.default;
275
+ }
276
+ return null;
277
+ };
278
+
279
+ /**
280
+ * Lazily load and build the BE-parity lookup tables from their JSON payloads.
281
+ * The dynamic imports are split into their own async chunks so neither file is
282
+ * bundled into the editor's main chunk unless local inference is initialised.
283
+ *
284
+ * :returns:
285
+ * A promise that resolves once `firstTokenToWords`, `l2Words` and
286
+ * `prefixMapTokenIds` are populated.
287
+ */
288
+ const loadBePayloadData = () => {
289
+ if (!bePayloadDataPromise) {
290
+ bePayloadDataPromise = (async () => {
291
+ const [firstTokenToWordsModule, vocabularyModule] = await Promise.all([import( /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-first-token-to-words" */'./data/first_token_to_words.json'), import( /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-vocabulary-10k" */'./data/vocabulary_10k.json')]);
292
+ const firstTokenToWordsData = unwrapJsonModule(firstTokenToWordsModule, 'object');
293
+ const vocabularyData = unwrapJsonModule(vocabularyModule, 'object');
294
+ if (firstTokenToWordsData == null || (vocabularyData === null || vocabularyData === void 0 ? void 0 : vocabularyData.words) == null) {
295
+ // Hard-fail with a precise message so the catch() in initEngine logs
296
+ // exactly which import couldn't be unwrapped, rather than the generic
297
+ // V8 "Cannot convert undefined or null to object" we hit before the
298
+ // helper was added.
299
+ throw new Error(`[LocalSlowLane] JSON module could not be unwrapped — ` + `firstTokenToWordsData=${firstTokenToWordsData == null ? 'null/undefined' : 'defined'}, ` + `vocabularyData=${vocabularyData == null ? 'null/undefined' : vocabularyData.words == null ? 'defined but missing .words' : 'defined'}`);
300
+ }
301
+ firstTokenToWords = new Map(Object.entries(firstTokenToWordsData).map(([tokenId, words]) => [Number(tokenId), words]));
302
+ l2Words = new Set(Object.keys(vocabularyData.words));
303
+ prefixMapTokenIds = Array.from(firstTokenToWords.keys());
304
+ if (isAutocompleteDebugEnabled()) {
305
+ // eslint-disable-next-line no-console
306
+ console.log('%c[LocalSlowLane] %c✅ BE-parity payload data loaded:', 'color: #9c27b0; font-weight: bold;', 'color: #4caf50; font-weight: bold;', {
307
+ firstTokenToWordsEntries: firstTokenToWords.size,
308
+ l2WordsCount: l2Words.size,
309
+ prefixMapTokenIdsLength: prefixMapTokenIds.length
310
+ });
311
+ }
312
+ })().catch(e => {
313
+ // Don't cache a rejected promise — a transient import failure would
314
+ // otherwise prevent the local model from ever initialising again this
315
+ // session. Reset so the next init attempt retries.
316
+ bePayloadDataPromise = undefined;
317
+ throw e;
318
+ });
319
+ }
320
+ return bePayloadDataPromise;
321
+ };
44
322
 
45
323
  /**
46
- * Original target repo (add-basics fine-tune). **Not compatible with WebLLM 0.2.x** (no `tensor-cache.json`).
47
- * @see module doc above
324
+ * Convert a raw next-token logit vector into a whole-word probability payload,
325
+ * faithfully porting the BE `CausalLMEncoder._get_top_k_probs`
326
+ * (`cc-smarts/python-sidecar/src/causal_lm_encoder.py`).
327
+ *
328
+ * Steps: (1) numerically-stable masked softmax over only the token ids present
329
+ * in the prefix-expansion map; (2) spread each token's probability to every
330
+ * whole word sharing that first token, taking the max; (3) reserve the top L2
331
+ * words unconditionally; (4) rank the remainder in a log-space pool with an
332
+ * additive L2 bias; (5) emit raw probabilities for the survivors, lowercased
333
+ * and trimmed at `MIN_PROB`.
334
+ *
335
+ * :params:
336
+ * rawLogits: Full-vocabulary logits from the LM's single decode step
337
+ * prefixMap: Map of first-token id to the words starting with that token
338
+ * domainWords: Set of L2 (domain) words, for tier-aware ranking
339
+ * :returns:
340
+ * A record of lowercase word to probability — the BE `lm_logits` payload
341
+ */
342
+ export const computeBePayload = (rawLogits, prefixMap, domainWords,
343
+ /**
344
+ * Pre-derived token-ID array for the softmax mask. Defaults to the
345
+ * module-level `prefixMapTokenIds` (zero allocation in production). Pass
346
+ * `Array.from(prefixMap.keys())` in tests that supply a custom prefixMap so
347
+ * the softmax mask stays consistent with the iteration in Step 2.
48
348
  */
49
- export const HUGGINGFACE_TB_SMOLLM_ADD_BASICS_REPO = 'https://huggingface.co/HuggingFaceTB/smollm-135M-instruct-add-basics-q0f16-MLC';
349
+ validTokenIds = prefixMapTokenIds) => {
350
+ // 1. Numerically-stable masked softmax over validTokenIds only.
351
+ let maxLogit = -Infinity;
352
+ for (const id of validTokenIds) {
353
+ const v = rawLogits[id];
354
+ if (v > maxLogit) {
355
+ maxLogit = v;
356
+ }
357
+ }
358
+ let sumExp = 0;
359
+ const expByToken = new Map();
360
+ for (const id of validTokenIds) {
361
+ const e = Math.exp(rawLogits[id] - maxLogit);
362
+ expByToken.set(id, e);
363
+ sumExp += e;
364
+ }
365
+
366
+ // 2. Prefix expansion with max aggregation (probabilities sum to 1 over the
367
+ // masked subset, so divide each token's exp by sumExp on the fly).
368
+ const wordProbs = new Map();
369
+ for (const [id, words] of prefixMap) {
370
+ var _expByToken$get;
371
+ const p = sumExp > 0 ? ((_expByToken$get = expByToken.get(id)) !== null && _expByToken$get !== void 0 ? _expByToken$get : 0) / sumExp : 0;
372
+ for (const w of words) {
373
+ var _wordProbs$get;
374
+ const prev = (_wordProbs$get = wordProbs.get(w)) !== null && _wordProbs$get !== void 0 ? _wordProbs$get : 0;
375
+ if (p > prev) {
376
+ wordProbs.set(w, p);
377
+ }
378
+ }
379
+ }
380
+
381
+ // 3. Split into L2 / L3 and reserve the top L2 slots unconditionally.
382
+ const l2Matches = [];
383
+ const l3Matches = [];
384
+ for (const [w, p] of wordProbs) {
385
+ if (domainWords.has(w)) {
386
+ l2Matches.push([w, p]);
387
+ } else {
388
+ l3Matches.push([w, p]);
389
+ }
390
+ }
391
+ l2Matches.sort((a, b) => b[1] - a[1]);
392
+ const reserved = l2Matches.slice(0, BE_PARITY.RESERVED_L2_SLOTS);
393
+
394
+ // 4. Pool the leftovers in log space; the L2 bias only affects ranking here.
395
+ // Words in l2Matches are unique and the array is sorted descending, so the
396
+ // non-reserved entries are exactly the tail after the reserved prefix — slice
397
+ // it directly rather than allocating a Set and scanning every entry on this
398
+ // hot path (runs ~every word boundary while typing).
399
+ const pool = [];
400
+ for (const [w, p] of l2Matches.slice(BE_PARITY.RESERVED_L2_SLOTS)) {
401
+ pool.push([w, Math.log(Math.max(p, 1e-10)) + BE_PARITY.L2_BIAS]);
402
+ }
403
+ for (const [w, p] of l3Matches) {
404
+ pool.push([w, Math.log(Math.max(p, 1e-10))]);
405
+ }
406
+ pool.sort((a, b) => b[1] - a[1]);
407
+ const remainingSlots = Math.max(0, BE_PARITY.TOP_K_WORDS - reserved.length);
408
+ const poolWinners = pool.slice(0, remainingSlots);
409
+
410
+ // 5. Assemble payload: store RAW probabilities (the bias was ranking-only),
411
+ // lowercase keys, trimmed at MIN_PROB. Reserved first, then pool winners.
412
+ // Reserved entries are written first; pool-winner writes must NOT clobber a
413
+ // reserved entry whose normalised key collides (two source words can
414
+ // `.trim().toLowerCase()` to the same key — e.g. "Function" vs "function ").
415
+ // Without the existence guard, a low-probability pool winner would silently
416
+ // overwrite the (higher-probability) reserved entry, degrading top-K
417
+ // quality in a way that's invisible from the debug summary.
418
+ const result = {};
419
+ const addEntry = (word, prob, allowOverwrite) => {
420
+ if (prob <= BE_PARITY.MIN_PROB) {
421
+ return;
422
+ }
423
+ const key = word.trim().toLowerCase();
424
+ if (!allowOverwrite && key in result) {
425
+ return;
426
+ }
427
+ result[key] = prob;
428
+ };
429
+ for (const [w, p] of reserved) {
430
+ addEntry(w, p, true);
431
+ }
432
+ for (const [w] of poolWinners) {
433
+ var _wordProbs$get2;
434
+ addEntry(w, (_wordProbs$get2 = wordProbs.get(w)) !== null && _wordProbs$get2 !== void 0 ? _wordProbs$get2 : 0, false);
435
+ }
436
+ if (isAutocompleteDebugEnabled()) {
437
+ const topReserved = reserved.slice(0, 5).map(([w, p]) => `${w}:${(p * 100).toFixed(2)}%`).join(', ');
438
+ const topPool = poolWinners.slice(0, 5).map(([w]) => {
439
+ var _wordProbs$get3;
440
+ return `${w}:${(((_wordProbs$get3 = wordProbs.get(w)) !== null && _wordProbs$get3 !== void 0 ? _wordProbs$get3 : 0) * 100).toFixed(2)}%`;
441
+ }).join(', ');
442
+ // eslint-disable-next-line no-console
443
+ console.log('%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', 'color: #9c27b0; font-weight: bold;', 'color: inherit;', validTokenIds.length, wordProbs.size, l2Matches.length, l3Matches.length, reserved.length, poolWinners.length, Object.keys(result).length, maxLogit.toFixed(3), sumExp.toFixed(1), topReserved || '(none)', topPool || '(none)');
444
+ }
445
+ return result;
446
+ };
50
447
 
51
448
  // ─── Factory ─────────────────────────────────────────────────────────────────
52
449
 
@@ -73,7 +470,7 @@ export const createLocalSlowLaneClient = (config = {}) => {
73
470
  debounceMs = DEFAULT_DEBOUNCE_MS,
74
471
  onUpdate,
75
472
  onStatus,
76
- modelId = LOCAL_MLC_MODEL_ID,
473
+ modelId = LOCAL_MLC_CAUSAL_MODEL_ID,
77
474
  customModelConfig
78
475
  } = config;
79
476
 
@@ -89,6 +486,9 @@ export const createLocalSlowLaneClient = (config = {}) => {
89
486
  let initFailed = false;
90
487
  let engine = null;
91
488
  let engineInitPromise = null;
489
+ // Captures raw next-token logits from the LM's single decode step. Registered
490
+ // with the engine below; `lmLogitsCapture.captured` is consumed in a later step.
491
+ const lmLogitsCapture = new CapturingLogitProcessor();
92
492
  const unloadEngine = engineToUnload => {
93
493
  engineToUnload.unload().catch(error => {
94
494
  if (isAutocompleteDebugEnabled()) {
@@ -112,16 +512,19 @@ export const createLocalSlowLaneClient = (config = {}) => {
112
512
  try {
113
513
  if (isAutocompleteDebugEnabled()) {
114
514
  // eslint-disable-next-line no-console
115
- console.log(`%c[LocalSlowLane] %c🚀 Initialising MLC engine with model: ${modelId}`, 'color: #9c27b0; font-weight: bold;', 'color: inherit;');
515
+ console.log(`%c[LocalSlowLane] %c🚀 Initialising MLC engine with models: ${modelId} (LM) + ${LOCAL_MLC_EMBEDDING_MODEL_ID} (embedder)`, 'color: #9c27b0; font-weight: bold;', 'color: inherit;');
116
516
  }
117
- onStatus === null || onStatus === void 0 ? void 0 : onStatus(`Initialising model: ${modelId}…`);
517
+ onStatus === null || onStatus === void 0 ? void 0 : onStatus(`Initialising models: ${modelId} + ${LOCAL_MLC_EMBEDDING_MODEL_ID}…`);
118
518
  if (!('gpu' in navigator)) {
119
519
  throw new Error('WebGPU not supported');
120
520
  }
121
- const {
122
- CreateMLCEngine,
521
+
522
+ // Fetch the web-llm runtime and the BE-parity lookup tables in parallel;
523
+ // both are dynamically imported so they stay out of the main editor chunk.
524
+ const [{
525
+ MLCEngine: MLCEngineCtor,
123
526
  prebuiltAppConfig
124
- } = await import( /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-mlc-web-llm" */'@mlc-ai/web-llm');
527
+ }] = await Promise.all([import( /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-mlc-web-llm" */'@mlc-ai/web-llm'), loadBePayloadData()]);
125
528
  const customModelRecord = customModelConfig ? {
126
529
  model: customModelConfig.model,
127
530
  model_id: modelId,
@@ -140,20 +543,32 @@ export const createLocalSlowLaneClient = (config = {}) => {
140
543
  const appConfig = {
141
544
  model_list: [...prebuiltAppConfig.model_list, ...(customModelRecord ? [customModelRecord] : [])]
142
545
  };
143
- engine = await CreateMLCEngine(modelId, {
546
+
547
+ // Construct the engine with the logit-capture processor registered for
548
+ // the causal LM only (the embedder never decodes tokens), then load
549
+ // both the LM and the embedder into the same engine (multi-model).
550
+ const newEngine = new MLCEngineCtor({
144
551
  appConfig,
145
- initProgressCallback
552
+ initProgressCallback,
553
+ logitProcessorRegistry: new Map([[modelId, lmLogitsCapture]])
146
554
  });
555
+ await newEngine.reload([modelId, LOCAL_MLC_EMBEDDING_MODEL_ID]);
147
556
  if (destroyed) {
148
557
  // destroy() was called while we were loading — clean up
149
- unloadEngine(engine);
150
- engine = null;
558
+ unloadEngine(newEngine);
151
559
  return;
152
560
  }
561
+ engine = newEngine;
153
562
  ready = true;
154
563
  if (isAutocompleteDebugEnabled()) {
155
564
  // eslint-disable-next-line no-console
156
- console.log('%c[LocalSlowLane] %c✅ MLC engine loaded and ready', 'color: #9c27b0; font-weight: bold;', 'color: #4caf50;');
565
+ console.log('%c[LocalSlowLane] %c✅ Both models loaded and ready', 'color: #9c27b0; font-weight: bold;', 'color: #4caf50;');
566
+ // One-time identity summary so you can confirm which models are active
567
+ // without digging through the init-progress scroll.
568
+ // eslint-disable-next-line no-console
569
+ console.log('%c[LocalSlowLane] %c🧠 Causal LM →', 'color: #9c27b0; font-weight: bold;', 'color: #2196f3; font-weight: bold;', modelId);
570
+ // eslint-disable-next-line no-console
571
+ console.log('%c[LocalSlowLane] %c🔢 Embedder →', 'color: #9c27b0; font-weight: bold;', 'color: #009688; font-weight: bold;', LOCAL_MLC_EMBEDDING_MODEL_ID);
157
572
  }
158
573
  onStatus === null || onStatus === void 0 ? void 0 : onStatus('Model loaded and ready.');
159
574
  } catch (err) {
@@ -181,85 +596,104 @@ export const createLocalSlowLaneClient = (config = {}) => {
181
596
  // ── Inference ──────────────────────────────────────────────────────────
182
597
 
183
598
  /**
184
- * Run a single forward pass to extract next-token logit probabilities.
599
+ * Run a single forward pass to produce the BE-parity slow-lane outputs.
185
600
  *
186
- * We use the chat completions API with `max_tokens: 1` and `logprobs: true`
187
- * to get the model's next-token distribution without generating text.
188
- * This is the cheapest possible inference call — a single forward pass.
601
+ * Two calls run in parallel on the shared engine:
602
+ * - `completions.create({ max_tokens: 1 })` runs the causal LM for exactly
603
+ * one decode step. We ignore the generated text; the LogitProcessor
604
+ * captures the raw next-token logits during that step, which we turn into
605
+ * a whole-word payload via `computeBePayload`.
606
+ * - `embeddings.create(...)` runs the Arctic embedder to produce the real
607
+ * 384-d semantic vector (passage-encoded; see `wrapForArctic`).
189
608
  */
190
609
  const runInference = async (text, requestId) => {
191
610
  if (!engine || destroyed) {
192
611
  return;
193
612
  }
613
+
614
+ // Clear the capture buffer so we read only this pass's logits. The engine
615
+ // serialises per-model requests and updateContext is debounced, so the
616
+ // latest request's decode step is the last to populate `captured` before
617
+ // we read it below; stale requests bail on the latestRequestId guard.
618
+ lmLogitsCapture.resetState();
619
+
620
+ // Apply BE-parity rolling-window truncation before both encoders.
621
+ // BE semantic: last max_context_words words (typeahead_context_encoding.py:36)
622
+ // BE causal LM: last max_context_tokens BPE tokens (causal_lm_encoder.py:194–198),
623
+ // approximated here with word count (no tokenizer available on FE).
624
+ const lmText = truncateToLastNWords(text, BE_PARITY.MAX_CONTEXT_TOKENS);
625
+ const semanticText = truncateToLastNWords(text, BE_PARITY.MAX_CONTEXT_WORDS);
626
+ const arcticInput = wrapForArctic(semanticText);
627
+ const captureCompletionTime = (promise, onResolved) => promise.then(value => {
628
+ onResolved(performance.now());
629
+ return value;
630
+ });
631
+ if (isAutocompleteDebugEnabled()) {
632
+ // eslint-disable-next-line no-console
633
+ console.log(`%c[LocalSlowLane] %c🔢 Arctic input (${arcticInput.length} chars, ${splitOnWhitespace(semanticText).length} words): "${arcticInput.length > 100 ? `${arcticInput.slice(0, 100)}…` : arcticInput}"`, 'color: #9c27b0; font-weight: bold;', 'color: #009688;');
634
+ // eslint-disable-next-line no-console
635
+ console.log(`%c[LocalSlowLane] %c🧠 LM input (${lmText.length} chars, ${splitOnWhitespace(lmText).length} words): "${lmText.length > 100 ? `${lmText.slice(0, 100)}…` : lmText}"`, 'color: #9c27b0; font-weight: bold;', 'color: #2196f3;');
636
+ }
194
637
  try {
195
- var _response$choices, _response$choices$, _response$choices$$lo;
196
- // Use chat completion with logprobs to get next-token distribution
197
- const response = await engine.chat.completions.create({
198
- messages: [{
199
- role: 'user',
200
- content: text
201
- }],
638
+ var _data, _data$;
639
+ const tStart = performance.now();
640
+ let tLmDone = 0;
641
+ let tEmbDone = 0;
642
+ const [, embeddingResponse] = await Promise.all([captureCompletionTime(engine.completions.create({
643
+ model: modelId,
644
+ prompt: lmText,
202
645
  max_tokens: 1,
203
- logprobs: true,
204
- top_logprobs: 5,
205
- temperature: 0
206
- });
646
+ temperature: 0,
647
+ logprobs: false
648
+ }), resolvedAt => {
649
+ tLmDone = resolvedAt;
650
+ }), captureCompletionTime(engine.embeddings.create({
651
+ model: LOCAL_MLC_EMBEDDING_MODEL_ID,
652
+ input: arcticInput
653
+ }), resolvedAt => {
654
+ tEmbDone = resolvedAt;
655
+ })]);
656
+ if (isAutocompleteDebugEnabled()) {
657
+ // eslint-disable-next-line no-console
658
+ console.log(`%c[LocalSlowLane] %c⏱ LM: ${(tLmDone - tStart).toFixed(0)}ms | Embedder: ${(tEmbDone - tStart).toFixed(0)}ms | Total: ${(Math.max(tLmDone, tEmbDone) - tStart).toFixed(0)}ms`, 'color: #9c27b0; font-weight: bold;', 'color: #ff9800;');
659
+ }
207
660
 
208
661
  // Discard stale results
209
662
  if (requestId < latestRequestId || destroyed) {
210
663
  return;
211
664
  }
212
665
 
213
- // ── Extract LM logits ───────────────────────────────────────
214
- const lmLogits = {};
215
- const logprobsContent = (_response$choices = response.choices) === null || _response$choices === void 0 ? void 0 : (_response$choices$ = _response$choices[0]) === null || _response$choices$ === void 0 ? void 0 : (_response$choices$$lo = _response$choices$.logprobs) === null || _response$choices$$lo === void 0 ? void 0 : _response$choices$$lo.content;
216
- if (logprobsContent && logprobsContent.length > 0) {
217
- const tokenLogprobs = logprobsContent[0];
218
-
219
- // Add the top token
220
- if (tokenLogprobs.token) {
221
- const token = tokenLogprobs.token.trim().toLowerCase();
222
- // @ts-ignore TS1501: Unicode regex flag requires a newer TS target than the declaration build uses.
223
- if (token.length > 0 && /^[a-z]/iu.test(token)) {
224
- lmLogits[token] = Math.exp(tokenLogprobs.logprob);
225
- }
226
- }
227
-
228
- // Add alternative tokens from top_logprobs
229
- if (tokenLogprobs.top_logprobs) {
230
- for (const alt of tokenLogprobs.top_logprobs) {
231
- const token = alt.token.trim().toLowerCase();
232
- // @ts-ignore TS1501: Unicode regex flag requires a newer TS target than the declaration build uses.
233
- if (token.length > 0 && /^[a-z]/iu.test(token)) {
234
- lmLogits[token] = Math.exp(alt.logprob);
235
- }
236
- }
237
- }
238
- }
239
- storedLmLogits = Object.keys(lmLogits).length > 0 ? lmLogits : null;
240
-
241
- // ── Semantic vector ─────────────────────────────────────────
242
- // SmolLM is a generative model, not an embedding model, so we
243
- // don't get a true semantic vector. We generate a lightweight
244
- // pseudo-embedding from the logit distribution for compatibility
245
- // with the existing scoring pipeline.
246
- //
247
- // For a production implementation, you would use a dedicated
248
- // embedding model (e.g. via web-llm's embeddings API with an
249
- // embedding-specific model).
250
- if (storedLmLogits) {
251
- const logitValues = Object.values(storedLmLogits);
252
- storedContextVector = new Float32Array(logitValues);
666
+ // ── LM logits: whole-word BE-parity payload ──────────────────
667
+ const rawLogits = lmLogitsCapture.captured;
668
+ if (rawLogits) {
669
+ const payload = computeBePayload(rawLogits, firstTokenToWords, l2Words);
670
+ storedLmLogits = Object.keys(payload).length > 0 ? payload : null;
253
671
  } else {
254
- storedContextVector = null;
672
+ storedLmLogits = null;
255
673
  }
674
+
675
+ // ── Semantic vector: real 384-d Arctic embedding ─────────────
676
+ // Guard against base64-encoded responses (encoding_format: 'base64' would
677
+ // yield a string, and new Float32Array(string) silently produces an empty
678
+ // array, corrupting downstream cosine-similarity scoring).
679
+ const embedding = (_data = embeddingResponse.data) === null || _data === void 0 ? void 0 : (_data$ = _data[0]) === null || _data$ === void 0 ? void 0 : _data$.embedding;
680
+ storedContextVector = Array.isArray(embedding) && embedding.length > 0 ? new Float32Array(embedding) : null;
256
681
  if (isAutocompleteDebugEnabled()) {
257
682
  // eslint-disable-next-line no-console
258
683
  console.groupCollapsed(`%c[LocalSlowLane] %c📥 Inference result (request #${requestId})`, 'color: #9c27b0; font-weight: bold;', 'color: inherit;');
684
+ if (storedContextVector) {
685
+ let sumSq = 0;
686
+ for (let i = 0; i < storedContextVector.length; i++) {
687
+ sumSq += storedContextVector[i] * storedContextVector[i];
688
+ }
689
+ // eslint-disable-next-line no-console
690
+ console.log(`✅ semantic vector: ${storedContextVector.length} dims (L2 norm ${Math.sqrt(sumSq).toFixed(3)})`);
691
+ } else {
692
+ // eslint-disable-next-line no-console
693
+ console.log('❌ No vector');
694
+ }
259
695
  // eslint-disable-next-line no-console
260
- console.log(storedContextVector ? `✅ pseudo-vector: ${storedContextVector.length} dims` : '❌ No vector');
261
- // eslint-disable-next-line no-console
262
- console.log(storedLmLogits ? `✅ lm_logits: ${Object.keys(storedLmLogits).length} tokens` : '❌ No lm_logits');
696
+ console.log(storedLmLogits ? `✅ lm_logits: ${Object.keys(storedLmLogits).length} words` : '❌ No lm_logits');
263
697
  if (storedLmLogits) {
264
698
  const topTokens = Object.entries(storedLmLogits).sort(([, a], [, b]) => b - a).slice(0, 10);
265
699
  // eslint-disable-next-line no-console