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