mlx-bun 0.0.9 → 0.0.11

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.
Files changed (179) hide show
  1. package/README.md +66 -21
  2. package/THIRD_PARTY_LICENSES.md +1 -0
  3. package/docs/archive/mlx-bun-lab-report.html +275 -0
  4. package/docs/archive/wwdc-mlx-bun.html +848 -0
  5. package/docs/design/audio-input-plan.md +356 -0
  6. package/docs/design/batching-perf-path.md +255 -0
  7. package/docs/design/batching-v2-plan.md +23 -9
  8. package/docs/design/bucketing-stage.md +2 -1
  9. package/docs/design/compat-cli-surface-design.md +4 -3
  10. package/docs/design/decode-speed-program.md +172 -0
  11. package/docs/design/docs-reorg-plan.md +1 -1
  12. package/docs/design/dspark-serving-program.md +371 -0
  13. package/docs/design/dspark-speculative-decoding.md +167 -5
  14. package/docs/design/faithful-l1-consolidation.md +310 -0
  15. package/docs/design/generic-model-support.md +8 -5
  16. package/docs/design/grammar-spec-batching-integration.md +301 -0
  17. package/docs/design/minicpm5-decode-megakernel.md +16 -11
  18. package/docs/design/mlx-lm-tool-parity-plan.md +11 -1
  19. package/docs/design/omlx-adoption-map.md +98 -0
  20. package/docs/design/orpo-training.md +34 -30
  21. package/docs/design/paged-kv-cache.md +214 -0
  22. package/docs/design/parallel-slots.md +82 -49
  23. package/docs/design/parity-tier-dag.md +43 -33
  24. package/docs/design/repo-cleanup-plan.md +189 -0
  25. package/docs/design/runtime-isolation.md +19 -3
  26. package/docs/design/segmented-backward-training.md +18 -2
  27. package/docs/design/ssd-kv-cold-tier.md +288 -0
  28. package/docs/design/structured-output.md +484 -0
  29. package/docs/design/the-dreaming-master-plan.md +2 -3
  30. package/docs/design/turboquant-kv.md +235 -0
  31. package/docs/design/unified-engine-frontier-plan.md +774 -0
  32. package/docs/design/web-chat-beat-matrix.md +315 -0
  33. package/docs/design/web-chat-redesign.md +1112 -0
  34. package/docs/investigations/decode-roofline-lookagain.md +92 -6
  35. package/docs/investigations/dspark-handoff.md +182 -16
  36. package/docs/investigations/kernel-perf-review-2026-07.md +105 -26
  37. package/docs/investigations/lab-build-journal.md +2 -2
  38. package/docs/investigations/openwiki-evaluation.md +249 -0
  39. package/docs/planning/IDEAS.md +14 -0
  40. package/docs/planning/PRODUCT_ROADMAP.md +2 -3
  41. package/docs/planning/chat-ui-vision-memory-first.md +199 -0
  42. package/docs/planning/chat-ui-vision.md +50 -0
  43. package/docs/planning/memory-docs-and-dag-plan.md +15 -6
  44. package/docs/planning/release-notes-v0.0.10.md +57 -0
  45. package/docs/planning/release-notes-v0.0.11.md +239 -0
  46. package/docs/reference/cli.md +35 -16
  47. package/docs/reference/distribution.md +13 -6
  48. package/docs/reference/embedding.md +35 -14
  49. package/docs/reference/features-matrix.md +97 -0
  50. package/docs/reference/library-api.md +30 -9
  51. package/docs/reference/memory.md +26 -6
  52. package/docs/reference/models.md +11 -1
  53. package/docs/reference/orpo-quickstart.md +3 -4
  54. package/docs/reference/server-api.md +634 -22
  55. package/docs/reference/server-config.md +251 -119
  56. package/docs/reference/training.md +20 -16
  57. package/package.json +5 -3
  58. package/src/anthropic.ts +13 -0
  59. package/src/audio/conformer.ts +647 -0
  60. package/src/audio/decode.ts +133 -0
  61. package/src/audio/features.ts +202 -0
  62. package/src/audio/transcode.ts +67 -0
  63. package/src/cli.ts +402 -107
  64. package/src/config.ts +49 -2
  65. package/src/download.ts +40 -0
  66. package/src/eval/README.md +7 -6
  67. package/src/eval/kl.ts +59 -3
  68. package/src/eval/quality-db.ts +2 -2
  69. package/src/eval/runner.ts +3 -3
  70. package/src/expert-offload.ts +15 -2
  71. package/src/flags.ts +13 -0
  72. package/src/generate.ts +330 -16
  73. package/src/grammar.ts +585 -0
  74. package/src/hub-rest.ts +242 -0
  75. package/src/kv-store.ts +618 -122
  76. package/src/lora.ts +8 -0
  77. package/src/md-modules.d.ts +42 -0
  78. package/src/media-fetch.ts +284 -0
  79. package/src/memory/rest.ts +245 -0
  80. package/src/memory/vault.ts +74 -0
  81. package/src/mlx/array.ts +127 -19
  82. package/src/mlx/autograd.ts +2 -2
  83. package/src/mlx/ffi.ts +27 -3
  84. package/src/mlx/metal-kernel.ts +7 -4
  85. package/src/mlx/ops.ts +179 -23
  86. package/src/mlx/turboquant-ops.ts +831 -0
  87. package/src/mlx/turboquant-tables.ts +237 -0
  88. package/src/model/batched-mask.ts +62 -1
  89. package/src/model/batched-quant.ts +206 -0
  90. package/src/model/batched-rotating-quant.ts +346 -0
  91. package/src/model/batched-rotating.ts +46 -1
  92. package/src/model/compiled-decode.ts +4 -15
  93. package/src/model/factory.ts +10 -4
  94. package/src/model/gemma4-base.ts +391 -34
  95. package/src/model/gemma4.ts +122 -33
  96. package/src/model/generated/gemma4-12b.ts +9 -13
  97. package/src/model/generated/gemma4-26b.ts +10 -5
  98. package/src/model/generated/gemma4-e4b.ts +14 -9
  99. package/src/model/minicpm5.ts +58 -102
  100. package/src/model/paged-kv.ts +253 -0
  101. package/src/model/qwen3-delta.ts +123 -15
  102. package/src/model/qwen3-moe.ts +404 -0
  103. package/src/model/qwen3.ts +9 -8
  104. package/src/model/qwen3_5.ts +99 -25
  105. package/src/model/support.ts +12 -1
  106. package/src/model/universal/dense.ts +40 -5
  107. package/src/model/universal/rope.ts +36 -21
  108. package/src/pi-web.ts +1299 -82
  109. package/src/preflight.ts +27 -8
  110. package/src/prompt-cache.ts +338 -32
  111. package/src/quantize/quantizer.ts +16 -1
  112. package/src/registry.ts +61 -3
  113. package/src/serve/batch-scheduler.ts +1001 -76
  114. package/src/serve/generation-gateway.ts +292 -30
  115. package/src/serve/isolate.ts +417 -0
  116. package/src/serve/lane-registry.ts +44 -0
  117. package/src/serve/session-search.ts +326 -0
  118. package/src/server.ts +1460 -105
  119. package/src/spec/assistant-source.ts +150 -0
  120. package/src/spec/deepspec-source.ts +143 -0
  121. package/src/spec/dflash-source.ts +124 -0
  122. package/src/spec/dspark/ab-stats.ts +136 -0
  123. package/src/spec/dspark/calibration.ts +112 -0
  124. package/src/spec/dspark/deepspec-module.ts +801 -0
  125. package/src/spec/dspark/generate-dflash.ts +72 -20
  126. package/src/spec/dspark/loader.ts +23 -0
  127. package/src/spec/dspark/module-dflash.ts +278 -36
  128. package/src/spec/dspark/quantize-drafter.ts +91 -0
  129. package/src/spec/generate.ts +59 -25
  130. package/src/spec/ngram-source.ts +132 -0
  131. package/src/spec/serve-loop.ts +536 -0
  132. package/src/spec/source.ts +93 -0
  133. package/src/spec/two-model.ts +171 -0
  134. package/src/ssd-cache.ts +285 -0
  135. package/src/tokenizer.ts +288 -2
  136. package/src/tool-approvals.ts +131 -0
  137. package/src/tool-call.ts +408 -20
  138. package/src/train/flash-cce.ts +29 -26
  139. package/src/train/job.ts +0 -2
  140. package/src/train/loss.ts +53 -11
  141. package/src/train/prefix-shared.ts +30 -7
  142. package/src/train/segmented.ts +150 -46
  143. package/src/train/trainer.ts +22 -15
  144. package/src/vision/prompt.ts +217 -48
  145. package/src/web/app.html +1184 -1789
  146. package/src/web/app.js +5667 -0
  147. package/src/web/icon.svg +13 -0
  148. package/src/web/manifest.webmanifest +24 -0
  149. package/src/web/src/adapters-panel.ts +288 -0
  150. package/src/web/src/api.ts +57 -0
  151. package/src/web/src/assistant.ts +485 -0
  152. package/src/web/src/chat.ts +1050 -0
  153. package/src/web/src/composer.ts +959 -0
  154. package/src/web/src/dataset.ts +132 -0
  155. package/src/web/src/finetune.ts +267 -0
  156. package/src/web/src/hub.ts +428 -0
  157. package/src/web/src/main.ts +98 -0
  158. package/src/web/src/markdown.ts +0 -0
  159. package/src/web/src/memory-panel.ts +572 -0
  160. package/src/web/src/model-picker.ts +159 -0
  161. package/src/web/src/palette.ts +346 -0
  162. package/src/web/src/protocol.ts +62 -0
  163. package/src/web/src/quantize.ts +167 -0
  164. package/src/web/src/rag.ts +274 -0
  165. package/src/web/src/sessions.ts +469 -0
  166. package/src/web/src/shell.ts +804 -0
  167. package/src/web/src/status.ts +252 -0
  168. package/src/web/src/ui-catalog.ts +92 -0
  169. package/src/web/sw.js +71 -0
  170. package/src/web/vendor/README.md +61 -0
  171. package/src/web/vendor/hljs-LICENSE +29 -0
  172. package/src/web/vendor/hljs-theme.css +59 -0
  173. package/src/web/vendor/hljs.js +26 -0
  174. package/src/model/fused-decode-kernel.ts +0 -312
  175. package/src/model/fused-geglu-kernel.ts +0 -198
  176. package/src/model/fused-mlp-kernel.ts +0 -169
  177. package/src/model/fused-swiglu-kernel.ts +0 -240
  178. package/src/model/steel-linear-kernel.ts +0 -96
  179. package/src/status-page.html +0 -497
package/src/tokenizer.ts CHANGED
@@ -17,6 +17,270 @@ export interface LoadedTokenizer {
17
17
  idToToken(id: number): string;
18
18
  readonly bosTokenId: number | null;
19
19
  readonly eosTokenId: number | null;
20
+ /** Absolute path to tokenizer.json (the model snapshot dir's copy). Set by
21
+ * loadTokenizer; read by src/grammar.ts to build the xgrammar TokenizerInfo
22
+ * (vocab extraction + vocab-type detection for constrained decoding). */
23
+ readonly tokenizerJsonPath?: string;
24
+ /** config.json vocab_size, may exceed the tokenizer vocab length when the
25
+ * embedding is padded to a power-of-two / 256. Read by src/grammar.ts to
26
+ * size the logit bitmask against the model's logit width, not the
27
+ * tokenizer's. Set by the server when it loads config; not set by the
28
+ * bare loadTokenizer() helper (callers that need it pass modelDir + config). */
29
+ vocabSize?: number;
30
+ /** mlx-lm streaming-detokenizer parity: true for ByteLevel-decoder (BPE)
31
+ * tokenizers, where mlx-lm's BPEStreamingDetokenizer drops ONE leading " "
32
+ * at the very start of a generated sequence (tokenizer_utils.py
33
+ * `_maybe_trim_space`: `elif not self.text: return current_text[1:]`).
34
+ * Our decode() delegates to @huggingface/tokenizers, whose ByteLevel
35
+ * decoder KEEPS that space — the serving StreamDecoder consults this flag
36
+ * to match mlx-lm's rendered bytes (e.g. MiniCPM5 /v1/completions:
37
+ * "2, 3, 5…" not " 2, 3, 5…"). SPM tokenizers need nothing: with a Strip
38
+ * decoder the strip already happens inside decode(); without one
39
+ * (gemma-4) mlx-lm uses trim_space=False and keeps the space too. */
40
+ readonly trimsLeadingSpace?: boolean;
41
+ /** mlx-lm streaming-detokenizer parity (companion to trimsLeadingSpace):
42
+ * for ByteLevel-decoder (BPE) tokenizers, the vocab id of the bare-space
43
+ * token "Ġ" — the ONLY token matching mlx-lm 0.31.3
44
+ * BPEStreamingDetokenizer.add_token's hold condition
45
+ * `len(v) == 1 and self._byte_decoder.get(v[0]) == 32`
46
+ * (tokenizer_utils.py:206-218, "For single spaces wait until the next
47
+ * token"). mlx_lm.server NEVER calls detokenizer.finalize() (grep: zero
48
+ * hits in server.py 0.31.3), so a generation ENDING on this token silently
49
+ * drops its space from the served bytes. The serving StreamDecoder
50
+ * consults this id to mirror both behaviors (MiniCPM5: id 242). */
51
+ readonly bareSpaceTokenId?: number;
52
+ /** Encode-path counters (memo hits / incremental splices / fallbacks /
53
+ * full encodes) — observability + test hook, no behavioral role. */
54
+ readonly encodeStats?: EncodeStats;
55
+ }
56
+
57
+ // Exact-input encode memo. Our pure-JS encode costs ~90 ms per 9.6k tokens
58
+ // (vs Rust tokenizers ~15 ms) and the serving hot paths re-encode BYTE-
59
+ // IDENTICAL text constantly: warm/ctx repeats re-render the same
60
+ // conversation, and regenerate flows resend it. A string-keyed LRU makes
61
+ // those free and is exact by construction (no BPE boundary reasoning).
62
+ // Bounded: keys are capped by count and total chars, so at most a few MB.
63
+ // The append-only multi-turn path (turn N+1's rendered prompt = turn N's
64
+ // plus a suffix) goes through IncrementalEncoder below; the native port is
65
+ // the endgame.
66
+ const ENCODE_MEMO_MAX_ENTRIES = 16;
67
+ const ENCODE_MEMO_MAX_CHARS = 1 << 21; // ~2M chars ≈ 4 MB of keys
68
+ class EncodeMemo {
69
+ #map = new Map<string, number[]>(); // Map preserves insertion order → LRU
70
+ #chars = 0;
71
+ get(key: string): number[] | undefined {
72
+ const hit = this.#map.get(key);
73
+ if (!hit) return undefined;
74
+ this.#map.delete(key); // bump recency
75
+ this.#map.set(key, hit);
76
+ return hit;
77
+ }
78
+ set(key: string, ids: number[]): void {
79
+ if (this.#map.has(key)) { this.#chars -= key.length; this.#map.delete(key); }
80
+ this.#map.set(key, ids);
81
+ this.#chars += key.length;
82
+ while (this.#map.size > ENCODE_MEMO_MAX_ENTRIES || this.#chars > ENCODE_MEMO_MAX_CHARS) {
83
+ const oldest = this.#map.keys().next().value as string | undefined;
84
+ if (oldest === undefined) break;
85
+ this.#chars -= oldest.length;
86
+ this.#map.delete(oldest);
87
+ }
88
+ }
89
+ /** Longest-common-string-prefix scan over memo entries with the same
90
+ * addSpecialTokens flag char ("S"/"s", the key's first char). ≤16 entries
91
+ * × O(commonLen) char compares — sub-ms at memo scale. `>=` keeps the most
92
+ * RECENT entry on common-length ties (Map iterates insertion order; recent
93
+ * entries are re-inserted last by get()). */
94
+ findBestPrefix(
95
+ flagChar: string,
96
+ text: string,
97
+ ): { text: string; ids: number[]; common: number } | null {
98
+ let best: { text: string; ids: number[]; common: number } | null = null;
99
+ for (const [key, ids] of this.#map) {
100
+ if (key[0] !== flagChar) continue;
101
+ const ptext = key.slice(2);
102
+ const n = Math.min(ptext.length, text.length);
103
+ let i = 0;
104
+ while (i < n && ptext.charCodeAt(i) === text.charCodeAt(i)) i++;
105
+ if (best === null || i >= best.common) best = { text: ptext, ids, common: i };
106
+ }
107
+ return best && best.common > 0 ? best : null;
108
+ }
109
+ }
110
+
111
+ // ---------------------------------------------------------------------------
112
+ // Incremental encode for append-only conversations.
113
+ //
114
+ // The installed @huggingface/tokenizers (0.1.3) Encoding exposes NO per-token
115
+ // offsets (types/static/types.d.ts: `Encoding = { ids, tokens,
116
+ // attention_mask }`), so char positions of token boundaries are recovered by
117
+ // decoding token TAILS and checking them against the known source text:
118
+ // decode(ids[T..N]) must be a literal suffix of the cached text (both target
119
+ // decoders round-trip: cpm5's ByteLevel is pure byte-concat, e4b's
120
+ // Sequence[Replace ▁→" ", ByteFallback, Fuse] inverts its normalizer; a tail
121
+ // cut mid-UTF-8-char yields U+FFFD and simply fails endsWith → step back).
122
+ // clean_up_tokenization_spaces must be forced FALSE here — the lib defaults
123
+ // it to config??true (dist decode()), which mangles offsets.
124
+ //
125
+ // Exactness contract: the fast path returns cached[0..T] + encode(tail) only
126
+ // after a seam VERIFICATION — re-encode from an anchor K tokens before the
127
+ // cut and require the first K+min(K,|tail|) tokens to reproduce
128
+ // cached[T-K..T] + tail[0..K] exactly. Any mismatch (BPE merges crossing the
129
+ // cut, decoder round-trip failure, mid-char cut) falls back to a full
130
+ // encode, so every returned result is either a verified splice or a
131
+ // from-scratch encode. SLACK backs the cut off the divergence point for
132
+ // merge locality; K≈32 tokens (~130 chars) exceeds any pre-token span the
133
+ // target tokenizers produce.
134
+ const INC_MIN_TEXT = 4096; // same gate as the memo: short prompts encode <1 ms
135
+ const INC_MIN_COMMON = 1024; // shared-prefix chars below this: splice not worth it
136
+ const INC_SLACK = 64; // chars backed off from the divergence point
137
+ const INC_VERIFY_TOKENS = 32; // K: seam window re-encoded and compared
138
+ const INC_CUT_ATTEMPTS = 8;
139
+
140
+ export interface EncodeStats {
141
+ memoHits: number;
142
+ incremental: number;
143
+ incrementalFallbacks: number; // splice attempted, verification/cut refused
144
+ full: number;
145
+ }
146
+
147
+ /** The subset of @huggingface/tokenizers' Tokenizer we need (encode/decode). */
148
+ type RawTokenizer = Pick<Tokenizer, "encode" | "decode">;
149
+
150
+ export class IncrementalEncoder {
151
+ readonly stats: EncodeStats = { memoHits: 0, incremental: 0, incrementalFallbacks: 0, full: 0 };
152
+ #tok: RawTokenizer;
153
+ #memo = new EncodeMemo();
154
+ /** Whether the post_processor only PREPENDS specials (BOS). An APPENDED
155
+ * special (EOS suffix template) would sit past the spliced tail where the
156
+ * seam verification cannot see it, so such tokenizers get no incremental
157
+ * path for addSpecialTokens=true. Both targets are prefix-only: cpm5
158
+ * TemplateProcessing single=[<s>, A], e4b single=[A]. */
159
+ #prefixOnlySpecials: boolean;
160
+
161
+ constructor(tok: RawTokenizer, prefixOnlySpecials: boolean) {
162
+ this.#tok = tok;
163
+ this.#prefixOnlySpecials = prefixOnlySpecials;
164
+ }
165
+
166
+ /** Test hook: inject a memo entry as if `ids` were the encode of `text`. */
167
+ seed(text: string, ids: number[], addSpecialTokens: boolean): void {
168
+ this.#memo.set(`${addSpecialTokens ? "S" : "s"}|${text}`, ids.slice());
169
+ }
170
+
171
+ #rawEncode(text: string, special: boolean): number[] {
172
+ return this.#tok.encode(text, { add_special_tokens: special }).ids.map(Number);
173
+ }
174
+
175
+ /** Raw tail decode for offset math: specials render as their literal vocab
176
+ * string (chat-template text contains them literally), cleanup forced off. */
177
+ #decodeTail(ids: number[]): string {
178
+ return this.#tok.decode(ids, {
179
+ skip_special_tokens: false,
180
+ clean_up_tokenization_spaces: false,
181
+ });
182
+ }
183
+
184
+ encode(text: string, special: boolean): number[] {
185
+ if (text.length < INC_MIN_TEXT) return this.#rawEncode(text, special);
186
+ const key = `${special ? "S" : "s"}|${text}`;
187
+ const hit = this.#memo.get(key);
188
+ if (hit) {
189
+ this.stats.memoHits++;
190
+ return hit.slice();
191
+ }
192
+ if (!special || this.#prefixOnlySpecials) {
193
+ const best = this.#memo.findBestPrefix(special ? "S" : "s", text);
194
+ if (best && best.common >= INC_MIN_COMMON) {
195
+ const inc = this.#tryIncremental(best.text, best.ids, best.common, text);
196
+ if (inc) {
197
+ this.stats.incremental++;
198
+ this.#memo.set(key, inc);
199
+ return inc.slice();
200
+ }
201
+ this.stats.incrementalFallbacks++;
202
+ }
203
+ }
204
+ const ids = this.#rawEncode(text, special);
205
+ this.stats.full++;
206
+ this.#memo.set(key, ids);
207
+ return ids.slice();
208
+ }
209
+
210
+ /** Splice cached prefix tokens with a fresh tail encode, or null to force
211
+ * the full-encode fallback. `common` = shared-prefix chars between ptext
212
+ * (the memoized source text of pids) and text. Cost is O(tail + seam), not
213
+ * O(text): two tail decodes + two suffix encodes. */
214
+ #tryIncremental(
215
+ ptext: string,
216
+ pids: number[],
217
+ common: number,
218
+ text: string,
219
+ ): number[] | null {
220
+ const target = common - INC_SLACK; // keep cached tokens ending at/before here
221
+ const N = pids.length;
222
+ const K = INC_VERIFY_TOKENS;
223
+ if (target <= 0 || N <= K + 2) return null;
224
+ // Estimate the cut token index from mean chars/token, then correct by
225
+ // decoding the actual tail. charStart(T) = ptext.length - |decode(T..N)|,
226
+ // valid only when the decoded tail is a literal suffix of ptext.
227
+ const avg = Math.max(ptext.length / N, 0.25);
228
+ let T = Math.min(
229
+ N - 1,
230
+ Math.max(K + 1, N - Math.ceil((ptext.length - target) / avg) - 4),
231
+ );
232
+ let cutChar = -1;
233
+ for (let attempt = 0; attempt < INC_CUT_ATTEMPTS; attempt++) {
234
+ if (T <= K) return null;
235
+ const d = this.#decodeTail(pids.slice(T));
236
+ if (!ptext.endsWith(d)) {
237
+ T = Math.max(K, T - 8); // mid-char cut (byte-fallback/ByteLevel) → back off
238
+ continue;
239
+ }
240
+ const start = ptext.length - d.length;
241
+ if (start > target) {
242
+ T = Math.max(K, T - Math.ceil((start - target) / avg) - 2);
243
+ continue;
244
+ }
245
+ cutChar = start;
246
+ break;
247
+ }
248
+ if (cutChar < 0) return null;
249
+ // Anchor K tokens before the cut; its char position via the same tail trick.
250
+ const anchorTail = this.#decodeTail(pids.slice(T - K));
251
+ if (!ptext.endsWith(anchorTail)) return null;
252
+ const anchorChar = ptext.length - anchorTail.length;
253
+ if (anchorChar >= cutChar) return null; // zero-width seam window: refuse
254
+ const tailIds = this.#rawEncode(text.slice(cutChar), false);
255
+ // Seam verification: a fresh encode from the anchor must reproduce the
256
+ // cached tokens across the cut AND the spliced tail's start. When the
257
+ // tail is shorter than K the verify encode covers the ENTIRE remainder,
258
+ // so require full equality (no trailing extras).
259
+ const verifyIds = this.#rawEncode(text.slice(anchorChar), false);
260
+ const expectedLen = K + Math.min(K, tailIds.length);
261
+ if (tailIds.length <= K ? verifyIds.length !== expectedLen : verifyIds.length < expectedLen)
262
+ return null;
263
+ for (let i = 0; i < K; i++) if (verifyIds[i] !== pids[T - K + i]) return null;
264
+ for (let i = K; i < expectedLen; i++) if (verifyIds[i] !== tailIds[i - K]) return null;
265
+ return pids.slice(0, T).concat(tailIds);
266
+ }
267
+ }
268
+
269
+ /** True when the tokenizer.json post_processor adds specials only BEFORE the
270
+ * sequence (or adds none): null, ByteLevel (offset-only, adds no ids), or a
271
+ * TemplateProcessing whose `single` template ends with the Sequence slot.
272
+ * Unknown processor types conservatively return false. */
273
+ export function specialsArePrefixOnly(tokenizerJson: unknown): boolean {
274
+ const pp = (tokenizerJson as { post_processor?: { type?: string; single?: unknown[] } })
275
+ .post_processor;
276
+ if (pp == null) return true;
277
+ if (pp.type === "ByteLevel") return true;
278
+ if (pp.type === "TemplateProcessing" && Array.isArray(pp.single)) {
279
+ const single = pp.single as Record<string, unknown>[];
280
+ const seqIdx = single.findIndex((item) => "Sequence" in item);
281
+ return seqIdx >= 0 && seqIdx === single.length - 1;
282
+ }
283
+ return false;
20
284
  }
21
285
 
22
286
  export async function loadTokenizer(modelDir: string): Promise<LoadedTokenizer> {
@@ -25,6 +289,7 @@ export async function loadTokenizer(modelDir: string): Promise<LoadedTokenizer>
25
289
  Bun.file(`${modelDir}/tokenizer_config.json`).json(),
26
290
  ]);
27
291
  const tok = new Tokenizer(tokenizerJson, tokenizerConfig);
292
+ const enc = new IncrementalEncoder(tok, specialsArePrefixOnly(tokenizerJson));
28
293
 
29
294
  const idOf = (key: string): number | null => {
30
295
  const t = tokenizerConfig[key];
@@ -34,9 +299,23 @@ export async function loadTokenizer(modelDir: string): Promise<LoadedTokenizer>
34
299
  return enc.ids.length === 1 ? Number(enc.ids[0]) : null;
35
300
  };
36
301
 
302
+ // mirror mlx-lm's `_is_bpe_decoder` (tokenizer_utils.py): top-level
303
+ // decoder type "ByteLevel" selects the BPE streaming detokenizer.
304
+ const isByteLevel =
305
+ (tokenizerJson as { decoder?: { type?: string } }).decoder?.type === "ByteLevel";
306
+ // The bare-space token: in the GPT-2 ByteLevel byte-to-unicode map, byte 32
307
+ // (space) renders as "Ġ" (U+0120) — the only single-char vocab entry whose
308
+ // byte decodes to 32, i.e. the only token mlx-lm's BPEStreamingDetokenizer
309
+ // withholds in _unflushed. Look it up straight in the BPE vocab.
310
+ const bareSpaceTokenId = isByteLevel
311
+ ? (tokenizerJson as { model?: { vocab?: Record<string, number> } }).model
312
+ ?.vocab?.["Ġ"]
313
+ : undefined;
314
+
37
315
  return {
38
- encode: (text, addSpecialTokens = true) =>
39
- tok.encode(text, { add_special_tokens: addSpecialTokens }).ids.map(Number),
316
+ // Memo + incremental-splice path live in IncrementalEncoder; short
317
+ // prompts (<4096 chars, <1 ms) bypass both inside it.
318
+ encode: (text, addSpecialTokens = true) => enc.encode(text, addSpecialTokens),
40
319
  decode: (ids, skipSpecialTokens = false) =>
41
320
  // python's decode([]) === ""; the JS lib throws on empty input
42
321
  ids.length === 0 ? "" : tok.decode(ids, { skip_special_tokens: skipSpecialTokens }),
@@ -45,5 +324,12 @@ export async function loadTokenizer(modelDir: string): Promise<LoadedTokenizer>
45
324
  .id_to_token(id) ?? tok.decode([id], { skip_special_tokens: false }),
46
325
  bosTokenId: idOf("bos_token"),
47
326
  eosTokenId: idOf("eos_token"),
327
+ tokenizerJsonPath: `${modelDir}/tokenizer.json`,
328
+ // ByteLevel/BPE = the only detokenizer class with the sequence-start
329
+ // space-trim and the bare-space hold-back our decode() lacks (see the
330
+ // interface docs above).
331
+ trimsLeadingSpace: isByteLevel,
332
+ bareSpaceTokenId: typeof bareSpaceTokenId === "number" ? bareSpaceTokenId : undefined,
333
+ encodeStats: enc.stats,
48
334
  };
49
335
  }
@@ -0,0 +1,131 @@
1
+ // Durable "always allow this tool" persistence for the web chat's
2
+ // tool-approval gate (web-chat-redesign.md §5.4/§6.5/§9 Phase 2, risk #6).
3
+ //
4
+ // Convention mirrors src/hf-push.ts's ~/.mlx-bun/hf.json: a single plain
5
+ // JSON file, mode 0600, no encryption-at-rest (the threat model is a single
6
+ // local user on their own machine). Versioned shape from day one so a
7
+ // future field addition can migrate instead of silently losing the file —
8
+ // risk #6 explicitly calls out the Claude-Desktop-resets-on-update failure
9
+ // mode as the thing NOT to repeat here.
10
+ //
11
+ // Keyed by tool NAME (stable identity — "bash", "edit", "write", or a
12
+ // custom tool's name), not by call args: "always allow bash" means every
13
+ // future bash call skips the card, matching every competitor's own
14
+ // granularity for this feature (per-tool, not per-command).
15
+
16
+ import { mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { homedir } from "node:os";
19
+
20
+ /** Home dir, honoring $HOME at call time — matches hf-push.ts's home(). */
21
+ function home(): string {
22
+ return process.env.HOME || homedir();
23
+ }
24
+
25
+ function configPath(): string {
26
+ return join(home(), ".mlx-bun", "tool-approvals.json");
27
+ }
28
+
29
+ export const TOOL_APPROVALS_VERSION = 1 as const;
30
+
31
+ /** On-disk shape. `allows` maps tool name -> true (present+true = always
32
+ * allow; absent = ask every time, the default). A plain boolean map (not a
33
+ * richer per-tool record) is deliberately the whole shape for v1 — nothing
34
+ * here needs migrating yet, but the version field exists so a future
35
+ * richer shape (e.g. per-tool scoping, expiry) has somewhere to land. */
36
+ export interface ToolApprovalsFileV1 {
37
+ version: 1;
38
+ allows: Record<string, true>;
39
+ }
40
+
41
+ /** Anything this module can load and return today. Widen this union (not
42
+ * ToolApprovalsFileV1) when a v2 shape ships, and teach loadToolApprovals'
43
+ * migration step to upgrade older files in place. */
44
+ export type ToolApprovalsFile = ToolApprovalsFileV1;
45
+
46
+ const EMPTY: ToolApprovalsFileV1 = { version: 1, allows: {} };
47
+
48
+ /**
49
+ * Load the durable approvals file, migrating forward if needed.
50
+ *
51
+ * Never throws: a missing file, unreadable file, or corrupt JSON all
52
+ * degrade to the empty default (ask every time) rather than crashing the
53
+ * approval gate — a config-file bug must never make mutating tools MORE
54
+ * permissive by accident, and "ask every time" is the safe failure mode.
55
+ */
56
+ export function loadToolApprovals(): ToolApprovalsFile {
57
+ let raw: string;
58
+ try {
59
+ raw = readFileSync(configPath(), "utf8");
60
+ } catch {
61
+ return { ...EMPTY, allows: {} };
62
+ }
63
+ let parsed: unknown;
64
+ try {
65
+ parsed = JSON.parse(raw);
66
+ } catch {
67
+ return { ...EMPTY, allows: {} };
68
+ }
69
+ return migrate(parsed);
70
+ }
71
+
72
+ /**
73
+ * Migrate an arbitrary parsed JSON value to the current ToolApprovalsFile
74
+ * shape. Unknown/missing `version` is treated as "pre-versioning" (there
75
+ * isn't one yet — this IS v1 — but the shape is defensive against a
76
+ * hand-edited or truncated file rather than assuming well-formedness).
77
+ * Unknown future versions (a downgrade scenario) fall back to empty rather
78
+ * than guessing at an unfamiliar shape.
79
+ */
80
+ function migrate(parsed: unknown): ToolApprovalsFile {
81
+ if (!parsed || typeof parsed !== "object") return { ...EMPTY, allows: {} };
82
+ const obj = parsed as Record<string, unknown>;
83
+ const version = obj.version;
84
+ if (version === 1 || version === undefined) {
85
+ const allowsRaw = obj.allows;
86
+ const allows: Record<string, true> = {};
87
+ if (allowsRaw && typeof allowsRaw === "object") {
88
+ for (const [k, v] of Object.entries(allowsRaw as Record<string, unknown>)) {
89
+ if (v === true) allows[k] = true;
90
+ }
91
+ }
92
+ return { version: 1, allows };
93
+ }
94
+ // Unrecognized/future version: don't guess at its shape. Ask every time
95
+ // is always the safe degradation.
96
+ return { ...EMPTY, allows: {} };
97
+ }
98
+
99
+ function saveToolApprovals(file: ToolApprovalsFile): void {
100
+ const dir = join(home(), ".mlx-bun");
101
+ mkdirSync(dir, { recursive: true });
102
+ const path = configPath();
103
+ writeFileSync(path, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
104
+ chmodSync(path, 0o600); // writeFileSync's mode is masked by umask on create
105
+ }
106
+
107
+ /** Whether `toolName` is currently in the durable always-allow set. */
108
+ export function isToolAlwaysAllowed(toolName: string): boolean {
109
+ return loadToolApprovals().allows[toolName] === true;
110
+ }
111
+
112
+ /** Persist "always allow this tool" for `toolName`. Idempotent. */
113
+ export function setToolAlwaysAllowed(toolName: string): ToolApprovalsFile {
114
+ const file = loadToolApprovals();
115
+ file.allows[toolName] = true;
116
+ saveToolApprovals(file);
117
+ return file;
118
+ }
119
+
120
+ /** Revoke a previously-granted always-allow (settings UI "forget" action). */
121
+ export function revokeToolAlwaysAllowed(toolName: string): ToolApprovalsFile {
122
+ const file = loadToolApprovals();
123
+ delete file.allows[toolName];
124
+ saveToolApprovals(file);
125
+ return file;
126
+ }
127
+
128
+ /** Full always-allow set, for a settings-panel listing. */
129
+ export function listAlwaysAllowedTools(): string[] {
130
+ return Object.keys(loadToolApprovals().allows).sort();
131
+ }