@atlaskit/editor-plugin-autocomplete 3.1.0 → 3.2.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,380 @@ 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
+
113
+ /**
114
+ * Return the last `n` whitespace-separated words of `text`, joined by spaces.
115
+ * Mirrors the BE rolling-window truncation applied before both encoders.
116
+ */
117
+ const truncateToLastNWords = (text, n) => {
118
+ const words = text.trim().split(/\s+/u);
119
+ return words.length <= n ? text : words.slice(-n).join(' ');
120
+ };
121
+
122
+ // ─── Logit capture ─────────────────────────────────────────────────────────
123
+
124
+ /**
125
+ * A LogitProcessor that captures the raw next-token logits and passes them
126
+ * through unmodified.
127
+ *
128
+ * web-llm invokes `processLogits` on the CPU after the model's forward pass and
129
+ * before sampling, handing us the full `Float32Array(vocab_size)` at the current
130
+ * decode position. We copy it off web-llm's shared buffer (which it may reuse
131
+ * across calls) and return the original untouched so sampling is unaffected.
132
+ *
133
+ * This is the raw-logit access the BE-parity algorithm needs (masked softmax +
134
+ * prefix expansion, consumed in a later step). Registered for the causal LM
135
+ * only — the embedder never decodes tokens, so it produces no logits.
136
+ */
137
+ class CapturingLogitProcessor {
138
+ constructor() {
139
+ _defineProperty(this, "captured", null);
140
+ _defineProperty(this, "processLogits", logits => {
141
+ // Copy off web-llm's shared buffer — it may reuse `logits` across calls.
142
+ this.captured = new Float32Array(logits);
143
+ return logits;
144
+ });
145
+ _defineProperty(this, "processSampledToken", () => {
146
+ // No-op — we don't track sampled tokens.
147
+ });
148
+ _defineProperty(this, "resetState", () => {
149
+ this.captured = null;
150
+ });
151
+ }
152
+ }
153
+
154
+ // ─── BE-parity data + algorithm ──────────────────────────────────────────────
155
+
156
+ /**
157
+ * Prefix-expansion map: first-token id → words whose space-prefixed SmolLM2
158
+ * encoding starts with that token. Generated offline by
159
+ * `scripts/gen_first_token_to_words.py`, which mirrors the BE's in-memory map
160
+ * (`CausalLMEncoder._ensure_loaded`).
161
+ *
162
+ * Populated lazily by `loadBePayloadData()` from a dynamically-imported JSON so
163
+ * the (large) payload is only fetched when the local client is actually
164
+ * initialised — keeping it out of the editor's main chunk for the vast majority
165
+ * of users (who run with `useLocalModel` off).
166
+ */
167
+ let firstTokenToWords = new Map();
168
+
169
+ /**
170
+ * L2 (Atlassian-domain) word set, derived from the keys of `vocabulary_10k.json`.
171
+ * Used by `computeBePayload` for tier-aware ranking: any word in the prefix map
172
+ * that is not in this set is treated as L3 (general English), matching the BE.
173
+ * Populated lazily alongside `firstTokenToWords` — see `loadBePayloadData()`.
174
+ */
175
+ let l2Words = new Set();
176
+
177
+ /**
178
+ * Array of token IDs that appear as a first token for at least one vocabulary
179
+ * word. Derived from `firstTokenToWords` when the data loads so `computeBePayload`
180
+ * does not re-allocate this array on every word-boundary call.
181
+ */
182
+ let prefixMapTokenIds = [];
183
+
184
+ /** De-dupes concurrent loads and lets repeated calls await the same payload. */
185
+ let bePayloadDataPromise;
186
+
187
+ /**
188
+ * Unwrap a dynamically imported JSON module to the parsed JSON value, working
189
+ * across the two interop modes AFM's bundler chain emits:
190
+ *
191
+ * 1. **`.default`-wrapped namespace** — classic webpack (and Jest) hang the
192
+ * JSON value under the `default` export.
193
+ * 2. **Named-exports namespace** — webpack 5 / atlaspack with JSON
194
+ * named-exports (or native ESM JSON modules) expose each top-level key as
195
+ * a named export and shadow `default`, so `mod.default` can be `undefined`
196
+ * (or some unrelated value) even though `mod` itself holds the data.
197
+ *
198
+ * The caller MUST declare the underlying JSON shape via `shape` because, in
199
+ * named-exports mode, a dense array `["a","b"]` and a sparse numeric-keyed
200
+ * object `{"5":"a","12":"b"}` are emitted identically (`{"0":..}` / `{"5":..}`);
201
+ * no runtime heuristic can tell them apart, so only the caller knows which:
202
+ *
203
+ * - `'object'` — the JSON is a `{...}` (including sparse maps keyed by integer
204
+ * IDs). The named exports are rebuilt into a plain object so `Object.entries`
205
+ * yields the real keys, not synthetic array indices.
206
+ * - `'array'` — the JSON is a `[...]`, reconstructed from the `0..n-1` indices.
207
+ *
208
+ * :param mod: The raw module object returned by `await import('./*.json')`.
209
+ * :param shape: `'object'` if the source JSON is `{...}`, `'array'` if `[...]`.
210
+ * :returns: The parsed JSON value, or `null` if neither interop mode applies.
211
+ */
212
+ const unwrapJsonModule = (mod, shape) => {
213
+ if (mod == null || typeof mod !== 'object') {
214
+ return null;
215
+ }
216
+ const namespace = mod;
217
+
218
+ // Compute the named-export own-keys (strip synthetic markers).
219
+ const ownKeys = Object.keys(namespace).filter(k => k !== 'default' && k !== '__esModule');
220
+
221
+ // PREFER named exports when present — they always reflect the JSON's real
222
+ // top-level keys / indices, regardless of what `default` happens to be.
223
+ // Under JSON named-exports mode `default` is not necessarily the parsed
224
+ // value (e.g. for `{"service": 0, ...}` it can be the number `0`, with the
225
+ // real data in the named exports), so taking `default` first would corrupt it.
226
+ if (ownKeys.length > 0) {
227
+ if (shape === 'array') {
228
+ // JSON arrays are dense; reconstruct from `0..length-1` indices.
229
+ const len = ownKeys.length;
230
+ const arr = new Array(len);
231
+ for (let i = 0; i < len; i++) {
232
+ arr[i] = namespace[String(i)];
233
+ }
234
+ return arr;
235
+ }
236
+ // shape === 'object'. Rebuild a plain object from the (stripped) own
237
+ // keys so callers can `Object.entries()` it without iterating over
238
+ // `default` / `__esModule`, and to detach from the module-namespace
239
+ // object (which is sealed/non-extensible on some bundler outputs).
240
+ const obj = {};
241
+ for (const k of ownKeys) {
242
+ obj[k] = namespace[k];
243
+ }
244
+ return obj;
245
+ }
246
+
247
+ // Fallback: no named exports — classic webpack JSON-module interop where
248
+ // the whole parsed JSON value is hung under `default`. Trust it.
249
+ if ('default' in namespace && namespace.default != null) {
250
+ return namespace.default;
251
+ }
252
+ return null;
253
+ };
40
254
 
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';
255
+ /**
256
+ * Lazily load and build the BE-parity lookup tables from their JSON payloads.
257
+ * The dynamic imports are split into their own async chunks so neither file is
258
+ * bundled into the editor's main chunk unless local inference is initialised.
259
+ *
260
+ * :returns:
261
+ * A promise that resolves once `firstTokenToWords`, `l2Words` and
262
+ * `prefixMapTokenIds` are populated.
263
+ */
264
+ const loadBePayloadData = () => {
265
+ if (!bePayloadDataPromise) {
266
+ bePayloadDataPromise = (async () => {
267
+ 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')]);
268
+ const firstTokenToWordsData = unwrapJsonModule(firstTokenToWordsModule, 'object');
269
+ const vocabularyData = unwrapJsonModule(vocabularyModule, 'object');
270
+ if (firstTokenToWordsData == null || (vocabularyData === null || vocabularyData === void 0 ? void 0 : vocabularyData.words) == null) {
271
+ // Hard-fail with a precise message so the catch() in initEngine logs
272
+ // exactly which import couldn't be unwrapped, rather than the generic
273
+ // V8 "Cannot convert undefined or null to object" we hit before the
274
+ // helper was added.
275
+ 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'}`);
276
+ }
277
+ firstTokenToWords = new Map(Object.entries(firstTokenToWordsData).map(([tokenId, words]) => [Number(tokenId), words]));
278
+ l2Words = new Set(Object.keys(vocabularyData.words));
279
+ prefixMapTokenIds = Array.from(firstTokenToWords.keys());
280
+ if (isAutocompleteDebugEnabled()) {
281
+ // eslint-disable-next-line no-console
282
+ console.log('%c[LocalSlowLane] %c✅ BE-parity payload data loaded:', 'color: #9c27b0; font-weight: bold;', 'color: #4caf50; font-weight: bold;', {
283
+ firstTokenToWordsEntries: firstTokenToWords.size,
284
+ l2WordsCount: l2Words.size,
285
+ prefixMapTokenIdsLength: prefixMapTokenIds.length
286
+ });
287
+ }
288
+ })().catch(e => {
289
+ // Don't cache a rejected promise — a transient import failure would
290
+ // otherwise prevent the local model from ever initialising again this
291
+ // session. Reset so the next init attempt retries.
292
+ bePayloadDataPromise = undefined;
293
+ throw e;
294
+ });
295
+ }
296
+ return bePayloadDataPromise;
297
+ };
44
298
 
45
299
  /**
46
- * Original target repo (add-basics fine-tune). **Not compatible with WebLLM 0.2.x** (no `tensor-cache.json`).
47
- * @see module doc above
300
+ * Convert a raw next-token logit vector into a whole-word probability payload,
301
+ * faithfully porting the BE `CausalLMEncoder._get_top_k_probs`
302
+ * (`cc-smarts/python-sidecar/src/causal_lm_encoder.py`).
303
+ *
304
+ * Steps: (1) numerically-stable masked softmax over only the token ids present
305
+ * in the prefix-expansion map; (2) spread each token's probability to every
306
+ * whole word sharing that first token, taking the max; (3) reserve the top L2
307
+ * words unconditionally; (4) rank the remainder in a log-space pool with an
308
+ * additive L2 bias; (5) emit raw probabilities for the survivors, lowercased
309
+ * and trimmed at `MIN_PROB`.
310
+ *
311
+ * :params:
312
+ * rawLogits: Full-vocabulary logits from the LM's single decode step
313
+ * prefixMap: Map of first-token id to the words starting with that token
314
+ * domainWords: Set of L2 (domain) words, for tier-aware ranking
315
+ * :returns:
316
+ * A record of lowercase word to probability — the BE `lm_logits` payload
317
+ */
318
+ export const computeBePayload = (rawLogits, prefixMap, domainWords,
319
+ /**
320
+ * Pre-derived token-ID array for the softmax mask. Defaults to the
321
+ * module-level `prefixMapTokenIds` (zero allocation in production). Pass
322
+ * `Array.from(prefixMap.keys())` in tests that supply a custom prefixMap so
323
+ * the softmax mask stays consistent with the iteration in Step 2.
48
324
  */
49
- export const HUGGINGFACE_TB_SMOLLM_ADD_BASICS_REPO = 'https://huggingface.co/HuggingFaceTB/smollm-135M-instruct-add-basics-q0f16-MLC';
325
+ validTokenIds = prefixMapTokenIds) => {
326
+ // 1. Numerically-stable masked softmax over validTokenIds only.
327
+ let maxLogit = -Infinity;
328
+ for (const id of validTokenIds) {
329
+ const v = rawLogits[id];
330
+ if (v > maxLogit) {
331
+ maxLogit = v;
332
+ }
333
+ }
334
+ let sumExp = 0;
335
+ const expByToken = new Map();
336
+ for (const id of validTokenIds) {
337
+ const e = Math.exp(rawLogits[id] - maxLogit);
338
+ expByToken.set(id, e);
339
+ sumExp += e;
340
+ }
341
+
342
+ // 2. Prefix expansion with max aggregation (probabilities sum to 1 over the
343
+ // masked subset, so divide each token's exp by sumExp on the fly).
344
+ const wordProbs = new Map();
345
+ for (const [id, words] of prefixMap) {
346
+ var _expByToken$get;
347
+ const p = sumExp > 0 ? ((_expByToken$get = expByToken.get(id)) !== null && _expByToken$get !== void 0 ? _expByToken$get : 0) / sumExp : 0;
348
+ for (const w of words) {
349
+ var _wordProbs$get;
350
+ const prev = (_wordProbs$get = wordProbs.get(w)) !== null && _wordProbs$get !== void 0 ? _wordProbs$get : 0;
351
+ if (p > prev) {
352
+ wordProbs.set(w, p);
353
+ }
354
+ }
355
+ }
356
+
357
+ // 3. Split into L2 / L3 and reserve the top L2 slots unconditionally.
358
+ const l2Matches = [];
359
+ const l3Matches = [];
360
+ for (const [w, p] of wordProbs) {
361
+ if (domainWords.has(w)) {
362
+ l2Matches.push([w, p]);
363
+ } else {
364
+ l3Matches.push([w, p]);
365
+ }
366
+ }
367
+ l2Matches.sort((a, b) => b[1] - a[1]);
368
+ const reserved = l2Matches.slice(0, BE_PARITY.RESERVED_L2_SLOTS);
369
+
370
+ // 4. Pool the leftovers in log space; the L2 bias only affects ranking here.
371
+ // Words in l2Matches are unique and the array is sorted descending, so the
372
+ // non-reserved entries are exactly the tail after the reserved prefix — slice
373
+ // it directly rather than allocating a Set and scanning every entry on this
374
+ // hot path (runs ~every word boundary while typing).
375
+ const pool = [];
376
+ for (const [w, p] of l2Matches.slice(BE_PARITY.RESERVED_L2_SLOTS)) {
377
+ pool.push([w, Math.log(Math.max(p, 1e-10)) + BE_PARITY.L2_BIAS]);
378
+ }
379
+ for (const [w, p] of l3Matches) {
380
+ pool.push([w, Math.log(Math.max(p, 1e-10))]);
381
+ }
382
+ pool.sort((a, b) => b[1] - a[1]);
383
+ const remainingSlots = Math.max(0, BE_PARITY.TOP_K_WORDS - reserved.length);
384
+ const poolWinners = pool.slice(0, remainingSlots);
385
+
386
+ // 5. Assemble payload: store RAW probabilities (the bias was ranking-only),
387
+ // lowercase keys, trimmed at MIN_PROB. Reserved first, then pool winners.
388
+ // Reserved entries are written first; pool-winner writes must NOT clobber a
389
+ // reserved entry whose normalised key collides (two source words can
390
+ // `.trim().toLowerCase()` to the same key — e.g. "Function" vs "function ").
391
+ // Without the existence guard, a low-probability pool winner would silently
392
+ // overwrite the (higher-probability) reserved entry, degrading top-K
393
+ // quality in a way that's invisible from the debug summary.
394
+ const result = {};
395
+ const addEntry = (word, prob, allowOverwrite) => {
396
+ if (prob <= BE_PARITY.MIN_PROB) {
397
+ return;
398
+ }
399
+ const key = word.trim().toLowerCase();
400
+ if (!allowOverwrite && key in result) {
401
+ return;
402
+ }
403
+ result[key] = prob;
404
+ };
405
+ for (const [w, p] of reserved) {
406
+ addEntry(w, p, true);
407
+ }
408
+ for (const [w] of poolWinners) {
409
+ var _wordProbs$get2;
410
+ addEntry(w, (_wordProbs$get2 = wordProbs.get(w)) !== null && _wordProbs$get2 !== void 0 ? _wordProbs$get2 : 0, false);
411
+ }
412
+ if (isAutocompleteDebugEnabled()) {
413
+ const topReserved = reserved.slice(0, 5).map(([w, p]) => `${w}:${(p * 100).toFixed(2)}%`).join(', ');
414
+ const topPool = poolWinners.slice(0, 5).map(([w]) => {
415
+ var _wordProbs$get3;
416
+ return `${w}:${(((_wordProbs$get3 = wordProbs.get(w)) !== null && _wordProbs$get3 !== void 0 ? _wordProbs$get3 : 0) * 100).toFixed(2)}%`;
417
+ }).join(', ');
418
+ // eslint-disable-next-line no-console
419
+ 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)');
420
+ }
421
+ return result;
422
+ };
50
423
 
51
424
  // ─── Factory ─────────────────────────────────────────────────────────────────
52
425
 
@@ -73,7 +446,7 @@ export const createLocalSlowLaneClient = (config = {}) => {
73
446
  debounceMs = DEFAULT_DEBOUNCE_MS,
74
447
  onUpdate,
75
448
  onStatus,
76
- modelId = LOCAL_MLC_MODEL_ID,
449
+ modelId = LOCAL_MLC_CAUSAL_MODEL_ID,
77
450
  customModelConfig
78
451
  } = config;
79
452
 
@@ -89,6 +462,9 @@ export const createLocalSlowLaneClient = (config = {}) => {
89
462
  let initFailed = false;
90
463
  let engine = null;
91
464
  let engineInitPromise = null;
465
+ // Captures raw next-token logits from the LM's single decode step. Registered
466
+ // with the engine below; `lmLogitsCapture.captured` is consumed in a later step.
467
+ const lmLogitsCapture = new CapturingLogitProcessor();
92
468
  const unloadEngine = engineToUnload => {
93
469
  engineToUnload.unload().catch(error => {
94
470
  if (isAutocompleteDebugEnabled()) {
@@ -112,16 +488,19 @@ export const createLocalSlowLaneClient = (config = {}) => {
112
488
  try {
113
489
  if (isAutocompleteDebugEnabled()) {
114
490
  // 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;');
491
+ 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
492
  }
117
- onStatus === null || onStatus === void 0 ? void 0 : onStatus(`Initialising model: ${modelId}…`);
493
+ onStatus === null || onStatus === void 0 ? void 0 : onStatus(`Initialising models: ${modelId} + ${LOCAL_MLC_EMBEDDING_MODEL_ID}…`);
118
494
  if (!('gpu' in navigator)) {
119
495
  throw new Error('WebGPU not supported');
120
496
  }
121
- const {
122
- CreateMLCEngine,
497
+
498
+ // Fetch the web-llm runtime and the BE-parity lookup tables in parallel;
499
+ // both are dynamically imported so they stay out of the main editor chunk.
500
+ const [{
501
+ MLCEngine: MLCEngineCtor,
123
502
  prebuiltAppConfig
124
- } = await import( /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-mlc-web-llm" */'@mlc-ai/web-llm');
503
+ }] = await Promise.all([import( /* webpackChunkName: "@atlaskit-internal_editor-plugin-autocomplete-mlc-web-llm" */'@mlc-ai/web-llm'), loadBePayloadData()]);
125
504
  const customModelRecord = customModelConfig ? {
126
505
  model: customModelConfig.model,
127
506
  model_id: modelId,
@@ -140,20 +519,32 @@ export const createLocalSlowLaneClient = (config = {}) => {
140
519
  const appConfig = {
141
520
  model_list: [...prebuiltAppConfig.model_list, ...(customModelRecord ? [customModelRecord] : [])]
142
521
  };
143
- engine = await CreateMLCEngine(modelId, {
522
+
523
+ // Construct the engine with the logit-capture processor registered for
524
+ // the causal LM only (the embedder never decodes tokens), then load
525
+ // both the LM and the embedder into the same engine (multi-model).
526
+ const newEngine = new MLCEngineCtor({
144
527
  appConfig,
145
- initProgressCallback
528
+ initProgressCallback,
529
+ logitProcessorRegistry: new Map([[modelId, lmLogitsCapture]])
146
530
  });
531
+ await newEngine.reload([modelId, LOCAL_MLC_EMBEDDING_MODEL_ID]);
147
532
  if (destroyed) {
148
533
  // destroy() was called while we were loading — clean up
149
- unloadEngine(engine);
150
- engine = null;
534
+ unloadEngine(newEngine);
151
535
  return;
152
536
  }
537
+ engine = newEngine;
153
538
  ready = true;
154
539
  if (isAutocompleteDebugEnabled()) {
155
540
  // eslint-disable-next-line no-console
156
- console.log('%c[LocalSlowLane] %c✅ MLC engine loaded and ready', 'color: #9c27b0; font-weight: bold;', 'color: #4caf50;');
541
+ console.log('%c[LocalSlowLane] %c✅ Both models loaded and ready', 'color: #9c27b0; font-weight: bold;', 'color: #4caf50;');
542
+ // One-time identity summary so you can confirm which models are active
543
+ // without digging through the init-progress scroll.
544
+ // eslint-disable-next-line no-console
545
+ console.log('%c[LocalSlowLane] %c🧠 Causal LM →', 'color: #9c27b0; font-weight: bold;', 'color: #2196f3; font-weight: bold;', modelId);
546
+ // eslint-disable-next-line no-console
547
+ console.log('%c[LocalSlowLane] %c🔢 Embedder →', 'color: #9c27b0; font-weight: bold;', 'color: #009688; font-weight: bold;', LOCAL_MLC_EMBEDDING_MODEL_ID);
157
548
  }
158
549
  onStatus === null || onStatus === void 0 ? void 0 : onStatus('Model loaded and ready.');
159
550
  } catch (err) {
@@ -181,85 +572,102 @@ export const createLocalSlowLaneClient = (config = {}) => {
181
572
  // ── Inference ──────────────────────────────────────────────────────────
182
573
 
183
574
  /**
184
- * Run a single forward pass to extract next-token logit probabilities.
575
+ * Run a single forward pass to produce the BE-parity slow-lane outputs.
185
576
  *
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.
577
+ * Two calls run in parallel on the shared engine:
578
+ * - `completions.create({ max_tokens: 1 })` runs the causal LM for exactly
579
+ * one decode step. We ignore the generated text; the LogitProcessor
580
+ * captures the raw next-token logits during that step, which we turn into
581
+ * a whole-word payload via `computeBePayload`.
582
+ * - `embeddings.create(...)` runs the Arctic embedder to produce the real
583
+ * 384-d semantic vector (passage-encoded; see `wrapForArctic`).
189
584
  */
190
585
  const runInference = async (text, requestId) => {
191
586
  if (!engine || destroyed) {
192
587
  return;
193
588
  }
589
+
590
+ // Clear the capture buffer so we read only this pass's logits. The engine
591
+ // serialises per-model requests and updateContext is debounced, so the
592
+ // latest request's decode step is the last to populate `captured` before
593
+ // we read it below; stale requests bail on the latestRequestId guard.
594
+ lmLogitsCapture.resetState();
595
+
596
+ // Apply BE-parity rolling-window truncation before both encoders.
597
+ // BE semantic: last max_context_words words (typeahead_context_encoding.py:36)
598
+ // BE causal LM: last max_context_tokens BPE tokens (causal_lm_encoder.py:194–198),
599
+ // approximated here with word count (no tokenizer available on FE).
600
+ const lmText = truncateToLastNWords(text, BE_PARITY.MAX_CONTEXT_TOKENS);
601
+ const semanticText = truncateToLastNWords(text, BE_PARITY.MAX_CONTEXT_WORDS);
602
+ const arcticInput = wrapForArctic(semanticText);
603
+ if (isAutocompleteDebugEnabled()) {
604
+ // eslint-disable-next-line no-console
605
+ console.log(`%c[LocalSlowLane] %c🔢 Arctic input (${arcticInput.length} chars, ${semanticText.split(/\s+/u).length} words): "${arcticInput.length > 100 ? `${arcticInput.slice(0, 100)}…` : arcticInput}"`, 'color: #9c27b0; font-weight: bold;', 'color: #009688;');
606
+ // eslint-disable-next-line no-console
607
+ console.log(`%c[LocalSlowLane] %c🧠 LM input (${lmText.length} chars, ${lmText.split(/\s+/u).length} words): "${lmText.length > 100 ? `${lmText.slice(0, 100)}…` : lmText}"`, 'color: #9c27b0; font-weight: bold;', 'color: #2196f3;');
608
+ }
194
609
  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
- }],
610
+ var _embeddingResponse$da, _embeddingResponse$da2;
611
+ const tStart = performance.now();
612
+ let tLmDone = 0;
613
+ let tEmbDone = 0;
614
+ const [, embeddingResponse] = await Promise.all([engine.completions.create({
615
+ model: modelId,
616
+ prompt: lmText,
202
617
  max_tokens: 1,
203
- logprobs: true,
204
- top_logprobs: 5,
205
- temperature: 0
206
- });
618
+ temperature: 0,
619
+ logprobs: false
620
+ }).then(r => {
621
+ tLmDone = performance.now();
622
+ return r;
623
+ }), engine.embeddings.create({
624
+ model: LOCAL_MLC_EMBEDDING_MODEL_ID,
625
+ input: arcticInput
626
+ }).then(r => {
627
+ tEmbDone = performance.now();
628
+ return r;
629
+ })]);
630
+ if (isAutocompleteDebugEnabled()) {
631
+ // eslint-disable-next-line no-console
632
+ 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;');
633
+ }
207
634
 
208
635
  // Discard stale results
209
636
  if (requestId < latestRequestId || destroyed) {
210
637
  return;
211
638
  }
212
639
 
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);
640
+ // ── LM logits: whole-word BE-parity payload ──────────────────
641
+ const rawLogits = lmLogitsCapture.captured;
642
+ if (rawLogits) {
643
+ const payload = computeBePayload(rawLogits, firstTokenToWords, l2Words);
644
+ storedLmLogits = Object.keys(payload).length > 0 ? payload : null;
253
645
  } else {
254
- storedContextVector = null;
646
+ storedLmLogits = null;
255
647
  }
648
+
649
+ // ── Semantic vector: real 384-d Arctic embedding ─────────────
650
+ // Guard against base64-encoded responses (encoding_format: 'base64' would
651
+ // yield a string, and new Float32Array(string) silently produces an empty
652
+ // array, corrupting downstream cosine-similarity scoring).
653
+ const embedding = (_embeddingResponse$da = embeddingResponse.data) === null || _embeddingResponse$da === void 0 ? void 0 : (_embeddingResponse$da2 = _embeddingResponse$da[0]) === null || _embeddingResponse$da2 === void 0 ? void 0 : _embeddingResponse$da2.embedding;
654
+ storedContextVector = Array.isArray(embedding) && embedding.length > 0 ? new Float32Array(embedding) : null;
256
655
  if (isAutocompleteDebugEnabled()) {
257
656
  // eslint-disable-next-line no-console
258
657
  console.groupCollapsed(`%c[LocalSlowLane] %c📥 Inference result (request #${requestId})`, 'color: #9c27b0; font-weight: bold;', 'color: inherit;');
658
+ if (storedContextVector) {
659
+ let sumSq = 0;
660
+ for (let i = 0; i < storedContextVector.length; i++) {
661
+ sumSq += storedContextVector[i] * storedContextVector[i];
662
+ }
663
+ // eslint-disable-next-line no-console
664
+ console.log(`✅ semantic vector: ${storedContextVector.length} dims (L2 norm ${Math.sqrt(sumSq).toFixed(3)})`);
665
+ } else {
666
+ // eslint-disable-next-line no-console
667
+ console.log('❌ No vector');
668
+ }
259
669
  // 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');
670
+ console.log(storedLmLogits ? `✅ lm_logits: ${Object.keys(storedLmLogits).length} words` : '❌ No lm_logits');
263
671
  if (storedLmLogits) {
264
672
  const topTokens = Object.entries(storedLmLogits).sort(([, a], [, b]) => b - a).slice(0, 10);
265
673
  // eslint-disable-next-line no-console