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