mlx-bun 0.4.0 → 1.0.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.
Files changed (601) hide show
  1. package/README.md +1453 -88
  2. package/THIRD_PARTY_NOTICES.md +882 -0
  3. package/bin/mlx-bun.convert.mjs +4 -0
  4. package/bin/mlx-bun.fuse.mjs +4 -0
  5. package/bin/mlx-bun.generate.mjs +4 -0
  6. package/bin/mlx-bun.lora.mjs +4 -0
  7. package/bin/mlx-bun.mjs +13 -21
  8. package/bin/mlx-bun.server.mjs +4 -0
  9. package/bin/mlx-bun.upload.mjs +4 -0
  10. package/dist/web/app.js +9584 -0
  11. package/package.json +50 -53
  12. package/src/cli/ane-install.ts +76 -0
  13. package/src/cli/args.ts +179 -0
  14. package/src/cli/engine-entry.ts +68 -0
  15. package/src/cli/inference.ts +214 -0
  16. package/src/cli/job-entry.ts +97 -0
  17. package/src/cli/library-host.ts +117 -0
  18. package/src/cli/main.ts +57 -0
  19. package/src/cli/memory-engine.ts +163 -0
  20. package/src/cli/memory.ts +36 -0
  21. package/src/cli/mlx-lm-aliases.ts +309 -0
  22. package/src/cli/model-choice.ts +33 -0
  23. package/src/cli/model-selection.ts +84 -0
  24. package/src/cli/module-host.ts +11 -0
  25. package/src/cli/module-verbs.ts +50 -0
  26. package/src/cli/numerical-policy.ts +12 -0
  27. package/src/cli/perplexity.ts +89 -0
  28. package/src/cli/serve-host.ts +423 -0
  29. package/src/cli/serve-isolated.ts +217 -0
  30. package/src/cli/serve-options.ts +106 -0
  31. package/src/cli/serve-state.ts +205 -0
  32. package/src/cli/serve.ts +500 -0
  33. package/src/cli/served-model-host.ts +102 -0
  34. package/src/cli/server-entry.ts +148 -0
  35. package/src/cli/serving-unit.ts +177 -0
  36. package/src/{tui.ts → cli/terminal.ts} +13 -8
  37. package/src/cli/worker-adapters.ts +34 -0
  38. package/src/cli/worker-entry.ts +272 -0
  39. package/src/cli/worker-unit.ts +179 -0
  40. package/src/engine/adapter-operation.ts +26 -0
  41. package/src/engine/cache-services.ts +114 -0
  42. package/src/engine/completion.ts +39 -0
  43. package/src/engine/generation-gateway.ts +358 -0
  44. package/src/engine/index.ts +59 -0
  45. package/src/engine/kv-budget.ts +120 -0
  46. package/src/engine/media-preparation.ts +232 -0
  47. package/src/engine/model-binding.ts +24 -0
  48. package/src/engine/model-host.ts +513 -0
  49. package/src/engine/model-serving.ts +89 -0
  50. package/src/{serve → engine}/preparation.ts +10 -8
  51. package/src/{serve → engine}/session-completion-engine.ts +6 -6
  52. package/src/engine/telemetry.ts +109 -0
  53. package/src/hub/downloads.ts +116 -0
  54. package/src/jobs/db.ts +16 -7
  55. package/src/jobs/events.ts +29 -0
  56. package/src/jobs/executable.ts +5 -0
  57. package/src/jobs/host.ts +51 -0
  58. package/src/jobs/in-process.ts +55 -0
  59. package/src/{contracts/jobs.ts → jobs/protocol.ts} +7 -9
  60. package/src/jobs/runner.ts +150 -231
  61. package/src/jobs/service.ts +75 -0
  62. package/src/jobs/sse.ts +59 -23
  63. package/src/jobs/worker-memory.ts +46 -0
  64. package/src/jobs/worker-process.ts +163 -0
  65. package/src/jobs/worker-supervisor.ts +258 -0
  66. package/src/modules.ts +58 -0
  67. package/src/publishing/catalog-hub.ts +18 -0
  68. package/src/publishing/credentials.ts +31 -0
  69. package/src/publishing/upload.ts +37 -0
  70. package/src/residency/leased-adapters.ts +21 -0
  71. package/src/residency/local-records.ts +16 -0
  72. package/src/residency/model-residency.ts +405 -0
  73. package/src/residency/record-index.ts +28 -0
  74. package/src/residency/resident-estimate.ts +50 -0
  75. package/src/{anthropic.ts → server/anthropic.ts} +3 -81
  76. package/src/server/cache-routes.ts +36 -0
  77. package/src/{serve → server}/chat-request.ts +12 -10
  78. package/src/{serve → server}/chat-stage.ts +27 -22
  79. package/src/{client.ts → server/client.ts} +28 -2
  80. package/src/{serve → server}/completion-executor.ts +42 -42
  81. package/src/server/decision-body.ts +55 -0
  82. package/src/server/decision-routes.ts +134 -0
  83. package/src/server/decision-wire.ts +228 -0
  84. package/src/{serve → server}/discovery-routes.ts +42 -83
  85. package/src/server/generated-token-history.ts +57 -0
  86. package/src/{serve → server}/http.ts +25 -13
  87. package/src/{serve → server}/inference-request.ts +5 -5
  88. package/src/server/job-routes.ts +20 -0
  89. package/src/server/media-prompt.ts +63 -0
  90. package/src/server/memory-completion-client.ts +46 -0
  91. package/src/server/model-routes.ts +192 -0
  92. package/src/{serve → server}/openai-wire.ts +3 -2
  93. package/src/{serve → server}/pipeline.ts +1 -1
  94. package/src/server/prompt-builder.ts +13 -0
  95. package/src/server/prompt-contracts.ts +17 -0
  96. package/src/server/proxy-routes.ts +187 -0
  97. package/src/server/publishing-routes.ts +41 -0
  98. package/src/{serve → server}/request-plan.ts +8 -8
  99. package/src/{serve → server}/request-prep.ts +82 -68
  100. package/src/{serve → server}/responses-client.ts +30 -13
  101. package/src/{responses.ts → server/responses.ts} +12 -93
  102. package/src/server/routes.ts +205 -0
  103. package/src/server/start.ts +72 -0
  104. package/src/server/status-routes.ts +108 -0
  105. package/src/{serve → server}/text-completion-stage.ts +25 -4
  106. package/src/server/text-prompt.ts +12 -0
  107. package/src/{serve → server}/token-streams.ts +36 -38
  108. package/src/server/worker-routes.ts +311 -0
  109. package/src/storage/paths.ts +61 -0
  110. package/src/web/assets.ts +37 -0
  111. package/src/web/{src → browser}/api.ts +5 -23
  112. package/src/web/browser/chat-host.ts +17 -0
  113. package/src/web/browser/installed-panels.ts +6 -0
  114. package/src/web/browser/main.ts +55 -0
  115. package/src/web/browser/markdown.ts +279 -0
  116. package/src/web/browser/memory-panel.ts +9 -0
  117. package/src/web/browser/palette.ts +64 -0
  118. package/src/web/browser/protocol.ts +13 -0
  119. package/src/web/browser/shell.ts +467 -0
  120. package/src/web/{src → browser}/status.ts +32 -36
  121. package/src/web/build.ts +51 -0
  122. package/src/web/public/app.html +1054 -0
  123. package/src/web/{sw.js → public/sw.js} +4 -3
  124. package/src/web/{vendor → public/vendor}/hljs-theme.css +2 -2
  125. package/src/web/{vendor → public/vendor}/hljs.js +2 -2
  126. package/THIRD_PARTY_LICENSES.md +0 -51
  127. package/docs/README.md +0 -94
  128. package/docs/archive/hlg-sampling.md +0 -350
  129. package/docs/archive/investigations/audio-input-plan.md +0 -356
  130. package/docs/archive/investigations/chunk-finetune-experiment.md +0 -84
  131. package/docs/archive/investigations/colibri-glm52-port.md +0 -1486
  132. package/docs/archive/investigations/colibri-oracle-pin.md +0 -1284
  133. package/docs/archive/investigations/curve-bisector-routing.md +0 -123
  134. package/docs/archive/investigations/decode-roofline-lookagain.md +0 -348
  135. package/docs/archive/investigations/diffusion-gemma-port.md +0 -602
  136. package/docs/archive/investigations/dspark-handoff.md +0 -224
  137. package/docs/archive/investigations/expert-offload-single-user-moe.md +0 -292
  138. package/docs/archive/investigations/faithful-l1-consolidation.md +0 -310
  139. package/docs/archive/investigations/hlg-sampling-investigation.md +0 -970
  140. package/docs/archive/investigations/indexshare-performance-spike.md +0 -357
  141. package/docs/archive/investigations/kernel-perf-review-2026-07.md +0 -171
  142. package/docs/archive/investigations/lab-build-journal.md +0 -157
  143. package/docs/archive/investigations/minicpm5-decode-megakernel.md +0 -489
  144. package/docs/archive/investigations/openjarvis-fit.md +0 -198
  145. package/docs/archive/investigations/openwiki-evaluation.md +0 -249
  146. package/docs/archive/investigations/optimization_plan.md +0 -346
  147. package/docs/archive/investigations/orpo-base-uf-experiment-and-directions.md +0 -120
  148. package/docs/archive/investigations/orpo-flash-cce-pin-leak.md +0 -167
  149. package/docs/archive/investigations/orpo-uf-testing-handoff.md +0 -126
  150. package/docs/archive/investigations/pareto-specialized-runtime-findings.md +0 -92
  151. package/docs/archive/investigations/pi-builtin-investigation.md +0 -308
  152. package/docs/archive/investigations/pre-colibri-stabilization.md +0 -329
  153. package/docs/archive/investigations/qwen38-27b-campaign-log.md +0 -1092
  154. package/docs/archive/investigations/segmented-backward-handoff.md +0 -148
  155. package/docs/archive/investigations/starter-model-port-handoff.md +0 -342
  156. package/docs/archive/investigations/steel-flash-cce-handoff.md +0 -489
  157. package/docs/archive/investigations/the-dreaming-handoff.md +0 -141
  158. package/docs/archive/investigations/trainer-validation-experiment.md +0 -173
  159. package/docs/archive/planning/chat-ui-vision-memory-first.md +0 -199
  160. package/docs/archive/planning/chat-ui-vision.md +0 -50
  161. package/docs/archive/planning/chunk-task-roadmap.md +0 -77
  162. package/docs/archive/planning/curve-sampler-research-plan.md +0 -331
  163. package/docs/archive/planning/journal.md +0 -316
  164. package/docs/archive/planning/memory-docs-and-dag-plan.md +0 -194
  165. package/docs/archive/planning/pi-integration-review.md +0 -178
  166. package/docs/archive/planning/release-notes-v0.0.10.md +0 -57
  167. package/docs/archive/planning/release-notes-v0.0.11.md +0 -239
  168. package/docs/archive/planning/release-notes-v0.0.12.md +0 -80
  169. package/docs/archive/planning/release-notes-v0.0.13.md +0 -77
  170. package/docs/archive/planning/release-notes-v0.0.9.md +0 -122
  171. package/docs/archive/planning/release-notes-v0.2.0.md +0 -49
  172. package/docs/archive/planning/release-notes-v0.3.0.md +0 -35
  173. package/docs/archive/planning/web-ui-pass-plan.md +0 -213
  174. package/docs/archive/planning/website-readme-pass-plan.md +0 -224
  175. package/docs/design/batching.md +0 -1841
  176. package/docs/design/decode-speed-program.md +0 -2349
  177. package/docs/design/dreaming-nightly-pipeline.md +0 -684
  178. package/docs/design/generic-model-support.md +0 -705
  179. package/docs/design/kv-cache.md +0 -824
  180. package/docs/design/orpo-training.md +0 -680
  181. package/docs/design/speculative-decoding.md +0 -1990
  182. package/docs/design/turboquant.md +0 -2212
  183. package/docs/design/unified-engine-frontier-plan.md +0 -1880
  184. package/docs/design/web-chat-redesign.md +0 -695
  185. package/docs/planning/PRODUCT_ROADMAP.md +0 -594
  186. package/docs/planning/ResearchTopics.md +0 -119
  187. package/docs/planning/release-notes-v0.4.0.md +0 -45
  188. package/docs/planning/video-series.md +0 -421
  189. package/docs/reference/benchmarks.md +0 -3613
  190. package/docs/reference/cli.md +0 -585
  191. package/docs/reference/distribution.md +0 -355
  192. package/docs/reference/environment.md +0 -398
  193. package/docs/reference/glossary.md +0 -39
  194. package/docs/reference/library-api.md +0 -674
  195. package/docs/reference/memory.md +0 -260
  196. package/docs/reference/models.md +0 -334
  197. package/docs/reference/server-api.md +0 -1775
  198. package/docs/reference/server-config.md +0 -846
  199. package/docs/reference/training.md +0 -462
  200. package/docs/reference/troubleshooting.md +0 -158
  201. package/src/admission-plan.ts +0 -18
  202. package/src/audio/conformer.ts +0 -647
  203. package/src/audio/decode.ts +0 -133
  204. package/src/audio/features.ts +0 -202
  205. package/src/audio/transcode.ts +0 -67
  206. package/src/backends/mlx/assistant-target.ts +0 -46
  207. package/src/backends/mlx/autoregressive-draft-rows.ts +0 -120
  208. package/src/backends/mlx/autoregressive.ts +0 -108
  209. package/src/backends/mlx/batch-group.ts +0 -1790
  210. package/src/backends/mlx/cache-attachment.ts +0 -67
  211. package/src/backends/mlx/cache-layout.ts +0 -31
  212. package/src/backends/mlx/checkpoint-state.ts +0 -53
  213. package/src/backends/mlx/continuation-persistence.ts +0 -106
  214. package/src/backends/mlx/continuation-request.ts +0 -43
  215. package/src/backends/mlx/continuation.ts +0 -77
  216. package/src/backends/mlx/diffusion.ts +0 -39
  217. package/src/backends/mlx/draft-target.ts +0 -32
  218. package/src/backends/mlx/evaluation.ts +0 -105
  219. package/src/backends/mlx/fill-append.ts +0 -45
  220. package/src/backends/mlx/full-kv-row-append.ts +0 -32
  221. package/src/backends/mlx/full-kv-row-donor.ts +0 -54
  222. package/src/backends/mlx/full-transitioning-kv-rows.ts +0 -65
  223. package/src/backends/mlx/gateway-binding.ts +0 -130
  224. package/src/backends/mlx/graph.ts +0 -38
  225. package/src/backends/mlx/kv-codec.ts +0 -9
  226. package/src/backends/mlx/kv-maintenance.ts +0 -133
  227. package/src/backends/mlx/kv-tensor-rows.ts +0 -212
  228. package/src/backends/mlx/memory-client.ts +0 -189
  229. package/src/backends/mlx/methods.ts +0 -90
  230. package/src/backends/mlx/model-prompt.ts +0 -164
  231. package/src/backends/mlx/model-serving.ts +0 -79
  232. package/src/backends/mlx/prefill-cohort.ts +0 -89
  233. package/src/backends/mlx/prefill-rows.ts +0 -200
  234. package/src/backends/mlx/prefill.ts +0 -33
  235. package/src/backends/mlx/projected-context-rows.ts +0 -72
  236. package/src/backends/mlx/request-policy.ts +0 -20
  237. package/src/backends/mlx/request-state-policy.ts +0 -41
  238. package/src/backends/mlx/rollback.ts +0 -89
  239. package/src/backends/mlx/row-sampling.ts +0 -49
  240. package/src/backends/mlx/serial-executor.ts +0 -242
  241. package/src/backends/mlx/speculative-group.ts +0 -359
  242. package/src/backends/mlx/speculative-round.ts +0 -161
  243. package/src/backends/mlx/speculative.ts +0 -114
  244. package/src/backends/mlx/state-rows.ts +0 -104
  245. package/src/backends/mlx/state-views.ts +0 -46
  246. package/src/backends/mlx/target-layout-capability.ts +0 -35
  247. package/src/backends/mlx/text-engine.ts +0 -73
  248. package/src/backends/mlx/transitioning-kv-rows.ts +0 -165
  249. package/src/chat-template.ts +0 -382
  250. package/src/cli.ts +0 -3168
  251. package/src/config.ts +0 -399
  252. package/src/contracts/completion.ts +0 -16
  253. package/src/contracts/execution.ts +0 -60
  254. package/src/contracts/generation.ts +0 -103
  255. package/src/contracts/host.ts +0 -7
  256. package/src/contracts/pi-provider.ts +0 -30
  257. package/src/contracts/pi.ts +0 -259
  258. package/src/contracts/prefix-cache.ts +0 -23
  259. package/src/contracts/resources.ts +0 -25
  260. package/src/contracts/sampling.ts +0 -23
  261. package/src/contracts/scheduling.ts +0 -45
  262. package/src/contracts/tsconfig.json +0 -14
  263. package/src/dataset/generators.ts +0 -1087
  264. package/src/dataset/index.ts +0 -12
  265. package/src/dataset/job.ts +0 -81
  266. package/src/dataset/llm.ts +0 -71
  267. package/src/dataset/registry.ts +0 -528
  268. package/src/diffusion/diffusion-generate.ts +0 -507
  269. package/src/download.ts +0 -505
  270. package/src/embed.ts +0 -77
  271. package/src/engine/admission.ts +0 -59
  272. package/src/engine/cancellation.ts +0 -38
  273. package/src/engine/engine.ts +0 -56
  274. package/src/engine/execution-coordinator.ts +0 -70
  275. package/src/engine/execution-plan.ts +0 -53
  276. package/src/engine/resources.ts +0 -53
  277. package/src/engine/scheduler.ts +0 -72
  278. package/src/engine/session.ts +0 -247
  279. package/src/eval/README.md +0 -130
  280. package/src/eval/ifeval.ts +0 -81
  281. package/src/eval/kl-prompts.ts +0 -29
  282. package/src/eval/kl.ts +0 -590
  283. package/src/eval/perplexity.ts +0 -164
  284. package/src/eval/quality-db.ts +0 -92
  285. package/src/eval/reference-logits.ts +0 -207
  286. package/src/eval/runner.ts +0 -124
  287. package/src/eval/score.ts +0 -49
  288. package/src/eval/tasks/bfcl.ts +0 -535
  289. package/src/eval/tasks/gsm8k.ts +0 -98
  290. package/src/eval/tasks/hashhop.ts +0 -139
  291. package/src/eval/tasks/humaneval.ts +0 -275
  292. package/src/eval/tasks/ifeval.ts +0 -525
  293. package/src/eval/tasks/mmlu.ts +0 -157
  294. package/src/eval/ultrafeedback.ts +0 -60
  295. package/src/evaldb.ts +0 -199
  296. package/src/expert-io.ts +0 -393
  297. package/src/expert-offload-build.ts +0 -77
  298. package/src/expert-offload.ts +0 -76
  299. package/src/expert-residency.ts +0 -1134
  300. package/src/expert-usage.ts +0 -415
  301. package/src/fill/echo-index.ts +0 -188
  302. package/src/fill/fill-session.ts +0 -452
  303. package/src/fill/proposal.ts +0 -68
  304. package/src/fill/schema-rows.ts +0 -506
  305. package/src/fill/tool-boundary.ts +0 -103
  306. package/src/fit.ts +0 -249
  307. package/src/generate.ts +0 -1346
  308. package/src/grammar.ts +0 -591
  309. package/src/harness-pi.ts +0 -184
  310. package/src/hf-push.ts +0 -628
  311. package/src/hub-rest.ts +0 -242
  312. package/src/index.ts +0 -63
  313. package/src/inference/denoising.ts +0 -17
  314. package/src/inference/draft-acceptance.ts +0 -41
  315. package/src/inference/draft-output.ts +0 -49
  316. package/src/inference/graph.ts +0 -33
  317. package/src/inference/prefill.ts +0 -39
  318. package/src/inference/rollback.ts +0 -7
  319. package/src/jobs/index.ts +0 -31
  320. package/src/jobs/job-entry.ts +0 -107
  321. package/src/jobs/task-client.ts +0 -19
  322. package/src/jobs/types.ts +0 -2
  323. package/src/kv-scheme.ts +0 -257
  324. package/src/kv-store.ts +0 -1099
  325. package/src/lab/README.md +0 -18
  326. package/src/lab/curve/curve-designer.html +0 -303
  327. package/src/lab/curve/curve-sampler.ts +0 -122
  328. package/src/lab/expert-trace/expert-trace.ts +0 -69
  329. package/src/lab/paged-kv/paged-kv-rows.ts +0 -83
  330. package/src/lab/paged-kv/paged-kv.ts +0 -270
  331. package/src/library.ts +0 -40
  332. package/src/lora.ts +0 -408
  333. package/src/md-modules.d.ts +0 -49
  334. package/src/media-fetch.ts +0 -442
  335. package/src/memory/article.ts +0 -558
  336. package/src/memory/chunk-validation.ts +0 -150
  337. package/src/memory/chunk.ts +0 -318
  338. package/src/memory/cluster.ts +0 -351
  339. package/src/memory/coverage.ts +0 -134
  340. package/src/memory/crosslink.ts +0 -0
  341. package/src/memory/db.ts +0 -253
  342. package/src/memory/entity.ts +0 -203
  343. package/src/memory/gate.ts +0 -187
  344. package/src/memory/history.ts +0 -152
  345. package/src/memory/ingest.ts +0 -335
  346. package/src/memory/model.ts +0 -183
  347. package/src/memory/normalize.ts +0 -671
  348. package/src/memory/parse.ts +0 -22
  349. package/src/memory/pipeline.ts +0 -275
  350. package/src/memory/prompts.ts +0 -65
  351. package/src/memory/query.ts +0 -334
  352. package/src/memory/reconcile.ts +0 -734
  353. package/src/memory/redirect.ts +0 -108
  354. package/src/memory/reindex.ts +0 -325
  355. package/src/memory/resolve.ts +0 -307
  356. package/src/memory/rest.ts +0 -245
  357. package/src/memory/route.ts +0 -272
  358. package/src/memory/schedule.ts +0 -165
  359. package/src/memory/stages.ts +0 -777
  360. package/src/memory/synthesize.ts +0 -1638
  361. package/src/memory/tools.ts +0 -749
  362. package/src/memory/vault.ts +0 -1194
  363. package/src/memory/wikify.ts +0 -1064
  364. package/src/mlx/array.ts +0 -388
  365. package/src/mlx/autograd.ts +0 -304
  366. package/src/mlx/checkpoint.ts +0 -149
  367. package/src/mlx/compile.ts +0 -168
  368. package/src/mlx/custom-vjp.ts +0 -188
  369. package/src/mlx/ffi.ts +0 -512
  370. package/src/mlx/materialize.ts +0 -23
  371. package/src/mlx/metal-kernel.ts +0 -159
  372. package/src/mlx/ops.ts +0 -1021
  373. package/src/mlx/quantized-rows.ts +0 -36
  374. package/src/mlx/token-bitmask.ts +0 -52
  375. package/src/mlx/turboquant-kv-decode.ts +0 -82
  376. package/src/mlx/turboquant-kv-inverse.ts +0 -122
  377. package/src/mlx/turboquant-ops.ts +0 -861
  378. package/src/mlx/turboquant-tables.ts +0 -237
  379. package/src/mmap.ts +0 -90
  380. package/src/model/artifact-identity.ts +0 -73
  381. package/src/model/batched-kv.ts +0 -235
  382. package/src/model/batched-mask.ts +0 -279
  383. package/src/model/batched-quant.ts +0 -212
  384. package/src/model/batched-quantized-kv.ts +0 -144
  385. package/src/model/batched-rotating-quant.ts +0 -353
  386. package/src/model/batched-rotating-state.ts +0 -149
  387. package/src/model/batched-rotating.ts +0 -338
  388. package/src/model/batched-row-storage.ts +0 -179
  389. package/src/model/batched-ssm.ts +0 -52
  390. package/src/model/batched-turboquant-kv.ts +0 -93
  391. package/src/model/compiled-decode.ts +0 -712
  392. package/src/model/decoded-kv-donor.ts +0 -12
  393. package/src/model/delayed-quantized-kv.ts +0 -72
  394. package/src/model/delayed-rotating-quantized-kv.ts +0 -93
  395. package/src/model/delayed-turboquant-kv.ts +0 -55
  396. package/src/model/diffusion-gemma.ts +0 -1026
  397. package/src/model/factory.ts +0 -189
  398. package/src/model/fingerprint.ts +0 -33
  399. package/src/model/flash-attention.ts +0 -694
  400. package/src/model/full-prefill-padding.ts +0 -56
  401. package/src/model/full-prefill-row.ts +0 -105
  402. package/src/model/gemma4-base.ts +0 -2351
  403. package/src/model/gemma4.ts +0 -1315
  404. package/src/model/generated/gemma4-12b.ts +0 -429
  405. package/src/model/generated/gemma4-26b.ts +0 -448
  406. package/src/model/generated/gemma4-e4b.ts +0 -717
  407. package/src/model/generated/index.ts +0 -18
  408. package/src/model/glm52-atlas.ts +0 -511
  409. package/src/model/glm52-cache.ts +0 -792
  410. package/src/model/glm52-config.ts +0 -262
  411. package/src/model/glm52-container.ts +0 -305
  412. package/src/model/glm52-coupling.ts +0 -388
  413. package/src/model/glm52-dsa.ts +0 -606
  414. package/src/model/glm52-expert-layout.ts +0 -253
  415. package/src/model/glm52-layout.ts +0 -152
  416. package/src/model/glm52-memory.ts +0 -500
  417. package/src/model/glm52-mla.ts +0 -792
  418. package/src/model/glm52-moe.ts +0 -223
  419. package/src/model/glm52-pilot.ts +0 -537
  420. package/src/model/glm52-reference.ts +0 -445
  421. package/src/model/glm52-residency.ts +0 -557
  422. package/src/model/glm52-resident-weights.ts +0 -135
  423. package/src/model/glm52-streamed-experts.ts +0 -453
  424. package/src/model/glm52-streamed-metal.ts +0 -610
  425. package/src/model/glm52-weights.ts +0 -503
  426. package/src/model/glm52.ts +0 -1132
  427. package/src/model/implementation.ts +0 -69
  428. package/src/model/kv-attention-view.ts +0 -67
  429. package/src/model/minicpm5.ts +0 -376
  430. package/src/model/profile.ts +0 -443
  431. package/src/model/qwen-append.ts +0 -12
  432. package/src/model/qwen-conv.ts +0 -52
  433. package/src/model/qwen3-delta-state.ts +0 -74
  434. package/src/model/qwen3-delta.ts +0 -451
  435. package/src/model/qwen3-moe.ts +0 -404
  436. package/src/model/qwen3-mrope.ts +0 -252
  437. package/src/model/qwen3.ts +0 -277
  438. package/src/model/qwen3_5-checkpoint.ts +0 -164
  439. package/src/model/qwen3_5.ts +0 -819
  440. package/src/model/rotating-kv-donor.ts +0 -35
  441. package/src/model/rotating-kv-layout.ts +0 -262
  442. package/src/model/rotating-row-transaction.ts +0 -35
  443. package/src/model/speculative-rotating-kv.ts +0 -101
  444. package/src/model/ssm-prefill-padding.ts +0 -39
  445. package/src/model/support.ts +0 -102
  446. package/src/model/trellis-balanced-scatter.ts +0 -51
  447. package/src/model/trellis-linear.ts +0 -672
  448. package/src/model/trellis-shared-m.ts +0 -151
  449. package/src/model/trellis-shared-scatter.ts +0 -144
  450. package/src/model/trellis-splitk-prefill.ts +0 -158
  451. package/src/model/trellis-tiled-prefill.ts +0 -136
  452. package/src/model/trellis-vector-expand.ts +0 -62
  453. package/src/model/trellis-wide-prefill.ts +0 -94
  454. package/src/model/turboquant-codec.ts +0 -83
  455. package/src/model/universal/archs.ts +0 -332
  456. package/src/model/universal/dense.ts +0 -612
  457. package/src/model/universal/modules.ts +0 -170
  458. package/src/model/universal/rope.ts +0 -381
  459. package/src/native/expert_io.c +0 -523
  460. package/src/native/frame_extract.swift +0 -140
  461. package/src/native-pack.ts +0 -162
  462. package/src/pi-provider.ts +0 -53
  463. package/src/pi-session.ts +0 -81
  464. package/src/pi-terminal.ts +0 -274
  465. package/src/pi-web.ts +0 -1932
  466. package/src/preflight.ts +0 -158
  467. package/src/prompt-cache.ts +0 -460
  468. package/src/quantize/allocator.ts +0 -627
  469. package/src/quantize/atomic-output.ts +0 -38
  470. package/src/quantize/calibration.ts +0 -181
  471. package/src/quantize/config-writer.ts +0 -145
  472. package/src/quantize/index.ts +0 -84
  473. package/src/quantize/job.ts +0 -162
  474. package/src/quantize/quantizer.ts +0 -666
  475. package/src/quantize/rotate.ts +0 -603
  476. package/src/quantize/safetensors-writer.ts +0 -249
  477. package/src/quantize/sensitivity.ts +0 -216
  478. package/src/quantize/trellis.ts +0 -586
  479. package/src/quantize/weight-transform.ts +0 -292
  480. package/src/registry.ts +0 -602
  481. package/src/runtime-config.ts +0 -81
  482. package/src/safetensors.ts +0 -158
  483. package/src/sampler.ts +0 -1011
  484. package/src/serve/admin-routes.ts +0 -184
  485. package/src/serve/assets/curve-terrain.html +0 -105
  486. package/src/serve/assets/training-inference-map.html +0 -575
  487. package/src/serve/aux-routes.ts +0 -132
  488. package/src/serve/batch-scheduler.ts +0 -8
  489. package/src/serve/checkpoint-identity.ts +0 -64
  490. package/src/serve/generation-gateway.ts +0 -496
  491. package/src/serve/isolate.ts +0 -609
  492. package/src/serve/kv-budget.ts +0 -14
  493. package/src/serve/lab-routes.ts +0 -341
  494. package/src/serve/lane-registry.ts +0 -45
  495. package/src/serve/model-admin-routes.ts +0 -155
  496. package/src/serve/model-binding.ts +0 -43
  497. package/src/serve/model-host.ts +0 -511
  498. package/src/serve/parent-application.ts +0 -56
  499. package/src/serve/prompt-response-trace.ts +0 -147
  500. package/src/serve/response-lease.ts +0 -24
  501. package/src/serve/session-search.ts +0 -326
  502. package/src/serve/static-routes.ts +0 -101
  503. package/src/server.ts +0 -1314
  504. package/src/spec/assistant-rows.ts +0 -92
  505. package/src/spec/assistant-source.ts +0 -126
  506. package/src/spec/cache-identity.ts +0 -22
  507. package/src/spec/deepspec-rows.ts +0 -29
  508. package/src/spec/deepspec-source.ts +0 -145
  509. package/src/spec/dflash-source.ts +0 -149
  510. package/src/spec/drafter.ts +0 -304
  511. package/src/spec/dspark/ab-stats.ts +0 -136
  512. package/src/spec/dspark/calibration.ts +0 -112
  513. package/src/spec/dspark/data-dflash.ts +0 -156
  514. package/src/spec/dspark/data.ts +0 -201
  515. package/src/spec/dspark/deepspec-module.ts +0 -776
  516. package/src/spec/dspark/generate-dflash.ts +0 -245
  517. package/src/spec/dspark/generate.ts +0 -290
  518. package/src/spec/dspark/loader.ts +0 -23
  519. package/src/spec/dspark/loss.ts +0 -213
  520. package/src/spec/dspark/module-dflash.ts +0 -560
  521. package/src/spec/dspark/module.ts +0 -540
  522. package/src/spec/dspark/quantize-drafter.ts +0 -91
  523. package/src/spec/dspark/sample.ts +0 -112
  524. package/src/spec/generate.ts +0 -276
  525. package/src/spec/glm52-mtp-graph.ts +0 -29
  526. package/src/spec/glm52-mtp-rows.ts +0 -132
  527. package/src/spec/glm52-mtp-source.ts +0 -317
  528. package/src/spec/glm52-mtp-state.ts +0 -33
  529. package/src/spec/ngram-source.ts +0 -204
  530. package/src/spec/projected-draft-rows.ts +0 -73
  531. package/src/spec/qwen-mtp-module.ts +0 -171
  532. package/src/spec/qwen-mtp-rows.ts +0 -219
  533. package/src/spec/qwen-mtp-source.ts +0 -383
  534. package/src/spec/qwen-mtp-state.ts +0 -30
  535. package/src/spec/serve-loop.ts +0 -585
  536. package/src/spec/source.ts +0 -215
  537. package/src/spec/two-model-rows.ts +0 -61
  538. package/src/spec/two-model.ts +0 -113
  539. package/src/ssd-cache.ts +0 -372
  540. package/src/ssd-durability.ts +0 -211
  541. package/src/tokenizer.ts +0 -335
  542. package/src/tool-approvals.ts +0 -131
  543. package/src/tool-call.ts +0 -695
  544. package/src/train/dataset.ts +0 -484
  545. package/src/train/diffusion-lora.ts +0 -216
  546. package/src/train/export.ts +0 -32
  547. package/src/train/flash-cce.ts +0 -1234
  548. package/src/train/forward.ts +0 -266
  549. package/src/train/fuse.ts +0 -243
  550. package/src/train/index.ts +0 -46
  551. package/src/train/job.ts +0 -205
  552. package/src/train/lora-params.ts +0 -254
  553. package/src/train/loss.ts +0 -1591
  554. package/src/train/merge.ts +0 -195
  555. package/src/train/optimizer.ts +0 -183
  556. package/src/train/prefix-shared.ts +0 -490
  557. package/src/train/rank.ts +0 -137
  558. package/src/train/segmented.ts +0 -1828
  559. package/src/train/steel-qmm-header.ts +0 -1461
  560. package/src/train/trainer.ts +0 -1221
  561. package/src/train/watch.ts +0 -542
  562. package/src/vision/diffusion-vision.ts +0 -620
  563. package/src/vision/embedder.ts +0 -168
  564. package/src/vision/preprocess.ts +0 -247
  565. package/src/vision/prompt.ts +0 -373
  566. package/src/vision/qwen3vl-preprocess.ts +0 -409
  567. package/src/vision/qwen3vl-prompt.ts +0 -196
  568. package/src/vision/qwen3vl-tower.ts +0 -555
  569. package/src/vision/siglip.ts +0 -599
  570. package/src/vision/video-frames.ts +0 -148
  571. package/src/web/app.html +0 -2143
  572. package/src/web/app.js +0 -5703
  573. package/src/web/skills/memory/SKILL.md +0 -120
  574. package/src/web/skills/web-research/SKILL.md +0 -46
  575. package/src/web/skills.ts +0 -97
  576. package/src/web/src/adapters-panel.ts +0 -288
  577. package/src/web/src/assistant.ts +0 -451
  578. package/src/web/src/chat.ts +0 -1057
  579. package/src/web/src/composer.ts +0 -959
  580. package/src/web/src/dataset.ts +0 -132
  581. package/src/web/src/finetune.ts +0 -267
  582. package/src/web/src/hub.ts +0 -428
  583. package/src/web/src/main.ts +0 -98
  584. package/src/web/src/markdown.ts +0 -0
  585. package/src/web/src/memory-panel.ts +0 -572
  586. package/src/web/src/model-picker.ts +0 -159
  587. package/src/web/src/palette.ts +0 -346
  588. package/src/web/src/protocol.ts +0 -26
  589. package/src/web/src/quantize.ts +0 -167
  590. package/src/web/src/rag.ts +0 -274
  591. package/src/web/src/sessions.ts +0 -469
  592. package/src/web/src/shell.ts +0 -804
  593. package/src/web/src/ui-catalog.ts +0 -78
  594. package/src/web/vendor/README.md +0 -61
  595. package/src/web-assets.ts +0 -47
  596. package/src/web-tools.ts +0 -478
  597. package/src/weights.ts +0 -255
  598. /package/src/{serve → server}/completion-sink.ts +0 -0
  599. /package/src/web/{icon.svg → public/icon.svg} +0 -0
  600. /package/src/web/{manifest.webmanifest → public/manifest.webmanifest} +0 -0
  601. /package/src/web/{vendor → public/vendor}/hljs-LICENSE +0 -0
@@ -0,0 +1,423 @@
1
+ // The model-scoped half of the serve composition. startModelHost is the CLI's
2
+ // loader: runtime switches, expert offload, the model context and its startup
3
+ // adapter. startContextHost serves one or more models from the model host
4
+ // (residency/model-residency.ts): each loaded model is a serving unit (binding,
5
+ // caches, engine, routes: serving-unit.ts), the Whisper companion, the model
6
+ // router (server/model-routes.ts), and the listener that serves them with the
7
+ // state's routes and the modules' sockets. Both borrow persistent services from the AppState they are
8
+ // given, and one close releases everything they created in the app's order.
9
+ import { requireChatTemplate, releaseContext, type LoadedModelContext } from "../engine/model-host";
10
+ import { createKvBudget, type KvBudget } from "../engine/kv-budget";
11
+ import { createResidencyHost, ResidencyError, type ResidencyEntry, type ResidencyHost, type ResidencySource } from "../residency/model-residency";
12
+ import { leasedAdapters } from "../residency/leased-adapters";
13
+ import { defaultBudgetBytes, estimateRecordBytes } from "../residency/resident-estimate";
14
+ import { createRecordIndex } from "../residency/record-index";
15
+ import { listLocalRecords } from "../residency/local-records";
16
+ import type { DurabilityFlushResult, DurabilitySnapshotStats } from "@mlx-bun/inference/state";
17
+ import type { ModelRecord } from "@mlx-bun/hub/registry";
18
+ import pkgJson from "../../package.json" with { type: "json" };
19
+ import { loadInstalledModules } from "./module-host";
20
+ import { type RunningApp, type ServeOptions } from "./serve-options";
21
+ import type { AppState, RouteGroup } from "./serve-state";
22
+ import { createServingUnit, type ContextHost, type ContextHostOptions, type ServingUnit, type UnitShared } from "./serving-unit";
23
+
24
+ export type { ContextHost, ContextHostOptions } from "./serving-unit";
25
+ export { resolveServingLimits } from "./serve-options";
26
+
27
+ export interface ModelHostHooks {
28
+ /** Runs inside the listener's drain step, after cache demotion stops and
29
+ * before chat sessions and HTTP responses drain: the app stops its
30
+ * persistent producers (jobs, downloads) here while the engine is alive. */
31
+ beforeDrain?(): void | Promise<void>;
32
+ /** Internal (worker mode, `cli/worker-entry.ts`): bind this Unix socket path
33
+ * instead of the TCP `port`/`hostname`; the host then reports no port, and
34
+ * the link it lends the state carries the socket for loopback clients. */
35
+ unix?: string;
36
+ /** Internal (worker mode): the worker's admin surface wraps the model routes
37
+ * and answers ahead of them (health, lease, the drain gate). */
38
+ routes?(model: RouteGroup): RouteGroup;
39
+ /** Internal (worker mode): serve only the model this host was started with; another is the parent's to load in another worker. */
40
+ oneModel?: true;
41
+ }
42
+
43
+ /** Worker mode: the listener is a Unix socket, so there is no port to report. */
44
+ export interface RunningWorkerHost {
45
+ /** Drains the listener, releases the Whisper companion and every resident
46
+ * model (draining, flushing its saved state, releasing it), and restores
47
+ * process-wide settings. One drain however often it is called; it resolves
48
+ * with the cache persistence result of the models resident at close. */
49
+ close(): Promise<DurabilityFlushResult>;
50
+ /** Flush cache persistence of every resident model while serving (`POST /admin/cache/flush`'s result). */
51
+ flush(): Promise<DurabilityFlushResult>;
52
+ /** Pending cache persistence counters, readable at any time. */
53
+ stats(): DurabilitySnapshotStats;
54
+ }
55
+ export interface RunningModelHost extends RunningWorkerHost { port: number }
56
+
57
+ /** The other local models a host may load beside (or instead of) its first, by exact id. */
58
+ export interface ModelSource {
59
+ /** The local models this host can serve, as the registry knows them; never scans or downloads. */
60
+ records(): readonly ModelRecord[] | Promise<readonly ModelRecord[]>;
61
+ /** Load one model for serving; the host takes ownership of the context. */
62
+ load(record: ModelRecord): Promise<{ context: LoadedModelContext; defaultAdapter?: string; loadMs: number }>;
63
+ /** The model the host starts with, when it is not one `records` lists (a path given to `--model`). */
64
+ startup?: ModelRecord;
65
+ }
66
+
67
+ /** Internal: process-wide settings the loader applied, restored once with the
68
+ * host's own after the model is released, on close and on startup failure. */
69
+ interface ContextHostHooks extends ModelHostHooks { restoreLoader?(): void }
70
+
71
+ const idle = (): DurabilitySnapshotStats => ({ pendingSnapshots: 0, pendingSpills: 0, pendingSpillBytes: 0, droppedSpills: 0, failedSpills: 0 });
72
+ function mergeStats(all: readonly DurabilitySnapshotStats[]): DurabilitySnapshotStats {
73
+ return all.reduce((sum, item) => ({ pendingSnapshots: sum.pendingSnapshots + item.pendingSnapshots, pendingSpills: sum.pendingSpills + item.pendingSpills,
74
+ pendingSpillBytes: sum.pendingSpillBytes + item.pendingSpillBytes, droppedSpills: sum.droppedSpills + item.droppedSpills,
75
+ failedSpills: sum.failedSpills + item.failedSpills }), idle());
76
+ }
77
+ function mergeDurability(all: readonly DurabilityFlushResult[]): DurabilityFlushResult {
78
+ return { ...mergeStats(all), durable: all.every(item => item.durable), flushedSnapshots: all.reduce((n, item) => n + item.flushedSnapshots, 0),
79
+ missingSnapshots: all.reduce((n, item) => n + item.missingSnapshots, 0), elapsedMs: all.reduce((n, item) => Math.max(n, item.elapsedMs), 0) };
80
+ }
81
+
82
+ /** Serve's KV flags as the composition request names them, `--fused-sdpa` (the
83
+ * affine read kernels) with them. */
84
+ const kvFlags = ({ cache: { kvQuant, turboQuant, quantizedKvStart }, fusedSdpa }: ServeOptions) => ({
85
+ ...(kvQuant !== undefined ? { override: kvQuant } : {}), ...(turboQuant ? { turboQuant } : {}),
86
+ ...(quantizedKvStart !== undefined ? { quantizedKvStart } : {}), ...(fusedSdpa !== undefined ? { fusedSdpa } : {}) });
87
+
88
+ /** Model composition owns resources until each explicit ownership transfer. */
89
+ export function startModelHost(state: AppState, model: ModelRecord, options: ServeOptions, hooks?: ModelHostHooks & { unix?: undefined }): Promise<RunningModelHost>;
90
+ export function startModelHost(state: AppState, model: ModelRecord, options: ServeOptions, hooks: ModelHostHooks & { unix: string }): Promise<RunningWorkerHost>;
91
+ export function startModelHost(state: AppState, model: ModelRecord, options: ServeOptions, hooks?: ModelHostHooks): Promise<RunningModelHost | RunningWorkerHost>;
92
+ export async function startModelHost(state: AppState, model: ModelRecord, options: ServeOptions, hooks: ModelHostHooks = {}): Promise<RunningModelHost | RunningWorkerHost> {
93
+ const [{ loadContext }, { configureRuntime }] = await Promise.all([import("../engine"), import("@mlx-bun/inference/runtime/config")]);
94
+ const restoreRuntime = configureRuntime({
95
+ ...(options.forceWire ? { MLX_BUN_FORCE_WIRE: "1" } : {}),
96
+ ...(options.allowPrivateMedia ? { MLX_BUN_ALLOW_PRIVATE_MEDIA: "1" } : {}) });
97
+ // Offload routing and the runtime switches are restored only after the
98
+ // engine has released the model, ahead of the context host's allocator limit.
99
+ let restoreOffload: (() => void) | undefined;
100
+ let restoreLoader: (() => void) | undefined = () => { try { restoreOffload?.(); } finally { restoreRuntime(); } };
101
+ let cleanup: (() => void) | undefined;
102
+ try {
103
+ if (options.expertOffload) {
104
+ // Main: dense models log and continue; MoE experts route through the
105
+ // page-aligned file built on first use, activated before construction.
106
+ if (model.expertsBytes === 0) console.warn("--expert-offload ignored: this model has no experts (dense)");
107
+ else {
108
+ const { ensureOffloadFile, activateExpertOffload } = await import("@mlx-bun/inference/artifacts");
109
+ restoreOffload = activateExpertOffload(await ensureOffloadFile(model.path, message => console.log(`[serve] expert offload: ${message}`)));
110
+ }
111
+ }
112
+ /** One model, loaded for serving. `--draft-*` and `--adapter` belong to the model named at startup; the others load plain. */
113
+ const loadServed = async (record: ModelRecord): Promise<{ context: LoadedModelContext; defaultAdapter?: string; loadMs: number }> => {
114
+ const startup = record.repoId === model.repoId;
115
+ const draft = startup ? options.draft ?? {} : {};
116
+ const loadStarted = performance.now();
117
+ const context = await loadContext(record.path, record.repoId, {
118
+ ...(options.memoryBudgetBytes !== undefined ? { memoryBudgetBytes: options.memoryBudgetBytes } : {}),
119
+ // The composition's facts: the KV flags and batch cap. Startup adapters mount below.
120
+ kv: kvFlags(options), maxRows: options.capacity,
121
+ ...(options.cache.pagedKv ? { pagedKv: options.cache.pagedKv } : {}),
122
+ // Resource plan inputs for runtimes that plan memory up front; other models ignore this block.
123
+ runtime: { batchSize: options.capacity, maxGenerationTokens: options.defaultGeneratedTokens ?? 128,
124
+ ...(options.memoryBudgetBytes !== undefined ? { memoryBudgetBytes: options.memoryBudgetBytes } : {}),
125
+ ...(options.contextTokens !== undefined ? { contextTokens: options.contextTokens } : {}),
126
+ ...(options.mtp !== undefined ? { nativeDraft: options.mtp } : {}) },
127
+ ...(draft.adaptiveDepth ? { adaptiveDraftDepth: true } : {}),
128
+ // Main's gate: a draft model, or the model-free ngram kind, or mtp alone
129
+ // (the host resolves the bundled <model>/mtp/ companion).
130
+ ...(draft.modelDir || draft.kind === "ngram" || draft.kind === "mtp" ? {
131
+ ...(draft.modelDir ? { draftModelDir: draft.modelDir } : {}),
132
+ ...(draft.numTokens !== undefined ? { numDraftTokens: draft.numTokens } : {}),
133
+ ...(draft.kind ? { draftKind: draft.kind } : {}),
134
+ ...(draft.ngramMax !== undefined ? { ngramMax: draft.ngramMax } : {}),
135
+ ...(draft.ngramMin !== undefined ? { ngramMin: draft.ngramMin } : {}) } : {}),
136
+ });
137
+ try {
138
+ if (draft.modelDir) console.log(`[serve] draft: ${draft.modelDir.split("/").filter(Boolean).at(-1)}`);
139
+ else if (draft.kind === "ngram") console.log("[serve] draft: ngram (prompt lookup)");
140
+ requireChatTemplate(context);
141
+ // Main: a startup adapter mounts before any request and becomes the default
142
+ // for requests without an adapter field (an explicit adapter, including
143
+ // "none", still wins); a bad adapter fails startup and releases the model.
144
+ if (startup && options.adapterDir) {
145
+ const directory = options.adapterDir.replace(/\/+$/, "");
146
+ try {
147
+ const info = await context.adapters.mount(directory.split("/").pop()!, directory);
148
+ console.log(`[serve] adapter ${info.id} mounted (${info.mountedLayers} layers) · default for requests (select others via \`adapter\`)`);
149
+ return { context, defaultAdapter: info.id, loadMs: performance.now() - loadStarted };
150
+ } catch (error) {
151
+ throw new Error(`adapter mount failed: ${error instanceof Error ? error.message : String(error)}`);
152
+ }
153
+ }
154
+ return { context, loadMs: performance.now() - loadStarted };
155
+ } catch (error) {
156
+ try { context.dispose(); } catch (failure) { throw new AggregateError([error, failure], "startup and cleanup failed"); }
157
+ throw error;
158
+ }
159
+ };
160
+ const first = await loadServed(model);
161
+ cleanup = () => first.context.dispose();
162
+ // The context host takes the model and the loader's process settings on entry, including a failed start.
163
+ const restore = restoreLoader;
164
+ cleanup = undefined; restoreLoader = undefined;
165
+ // Expert offload routes the process's loads through one file: that model is all this process serves.
166
+ const models: ModelSource | undefined = options.expertOffload || hooks.oneModel ? undefined : { startup: model, load: loadServed, records: localRecords };
167
+ return await startContextHost(state, first.context, options,
168
+ { ownership: "owned", artifact: model, owner: "serve", loadMs: first.loadMs, ...(first.defaultAdapter ? { defaultAdapter: first.defaultAdapter } : {}),
169
+ ...(models ? { models } : {}) },
170
+ { ...hooks, restoreLoader: restore });
171
+ } catch (error) {
172
+ try { cleanup?.(); }
173
+ catch (failure) { throw new AggregateError([error, failure], "startup and cleanup failed"); }
174
+ finally { restoreLoader?.(); }
175
+ throw error;
176
+ }
177
+ }
178
+
179
+ /** The models `/v1/models` may list and the host may load: supported generation checkpoints the registry knows. */
180
+ const localRecords = () => listLocalRecords("generate");
181
+
182
+ /** Serve one or more models with the app's routes, chat, and listener. The
183
+ * first context is resident from the start; it is released by
184
+ * `input.ownership`, on close and on a failed start alike. Without
185
+ * `input.models` it is the only model and is never evicted; with it, any other
186
+ * local model loads when a request names it and fits the memory budget (the
187
+ * least recently used unpinned, unleased model is drained, its saved state
188
+ * flushed, and released first), and the first can be evicted and reloaded like
189
+ * the rest. Everything else the host created is released either way. It
190
+ * applies no runtime switches and activates no expert offload: those belong to
191
+ * whoever loaded the context. A context without a chat template is refused
192
+ * unless `input.buildPrompt` builds its prompts. */
193
+ export function startContextHost(state: AppState, context: LoadedModelContext, options: ContextHostOptions, input: ContextHost & { models?: ModelSource },
194
+ hooks?: ContextHostHooks & { unix?: undefined }): Promise<RunningModelHost>;
195
+ export function startContextHost(state: AppState, context: LoadedModelContext, options: ContextHostOptions, input: ContextHost & { models?: ModelSource },
196
+ hooks: ContextHostHooks): Promise<RunningModelHost | RunningWorkerHost>;
197
+ export async function startContextHost(state: AppState, context: LoadedModelContext, options: ContextHostOptions, input: ContextHost & { models?: ModelSource },
198
+ hooks: ContextHostHooks = {}): Promise<RunningModelHost | RunningWorkerHost> {
199
+ // Process-wide settings (the loader's, then this host's allocator limit) are
200
+ // restored only after the engine has released the model, on close and on
201
+ // startup failure alike, so a later host in the same process starts from
202
+ // the state it found. The restore runs once: a repeated close must not undo
203
+ // a later host's settings.
204
+ let restoreAllocator: (() => void) | undefined, restored = false;
205
+ const restoreProcess = () => {
206
+ if (restored) return;
207
+ restored = true;
208
+ try { hooks.restoreLoader?.(); } finally { restoreAllocator?.(); }
209
+ };
210
+ let cleanup: (() => void | Promise<unknown>) | undefined = () => releaseContext(context, input.ownership);
211
+ // The link is returned to the state once, like the process restore.
212
+ let detachLink = () => {};
213
+ const detach = () => { const release = detachLink; detachLink = () => {}; release(); };
214
+ try {
215
+ const [{ startServer }, { createModelRoutes },
216
+ { createHostServices, createModuleRoutes, declaredOperations }] = await Promise.all([
217
+ import("../server/start"), import("../server/model-routes"),
218
+ import("@mlx-bun/app-services"),
219
+ ]);
220
+ // Main: the plan's allocator limit, else the explicit budget, caps the
221
+ // allocator for the whole process and bounds optional cache residency.
222
+ const allocatorLimitBytes = context.memoryPlan?.allocatorLimitBytes ?? options.memoryBudgetBytes;
223
+ if (allocatorLimitBytes) {
224
+ const { setMemoryLimit } = await import("@mlx-bun/mlx/ffi");
225
+ const previous = setMemoryLimit(allocatorLimitBytes);
226
+ restoreAllocator = () => { setMemoryLimit(previous); };
227
+ }
228
+ // One saved-state budget over every model's store in this process.
229
+ const ssdBudget: KvBudget | undefined = options.cache.ssdCacheDir
230
+ ? createKvBudget(options.cache.ssdCacheDir, options.cache.ssdCacheMaxBytes ?? Infinity) : undefined;
231
+ let residency!: ResidencyHost<ServingUnit>;
232
+ // Each closing model's saved-state result; the ones at host close are the close's evidence.
233
+ const finalResults: DurabilityFlushResult[] = [];
234
+ let closingHost = false;
235
+ // Main's speech-to-text companion, served by the transcription module: an
236
+ // explicit --whisper-model, else the first downloaded Whisper checkpoint,
237
+ // resolved once on the first audio request (a later download needs a
238
+ // restart, as in main). The weights load per take and release per the
239
+ // --whisper-* policy; every decode runs with every resident model paused so
240
+ // it never overlaps generation, and a load first makes room in the budget.
241
+ const moduleHost = createHostServices({ whisper: options.whisper, events: state.events,
242
+ exclusive: async (fn, signal) => { const pause = await residency.pauseAll(signal); try { return await fn(); } finally { pause.dispose(); } },
243
+ admit: bytes => residency.makeRoom(bytes) });
244
+ const whisperInfo = async () => {
245
+ const id = await moduleHost.whisper.defaultFor("transcribe");
246
+ return id === undefined ? null : { id, resident: moduleHost.whisper.stats(id).resident };
247
+ };
248
+ const shared: UnitShared = { responses: state.responses, events: state.events, transcription: whisperInfo,
249
+ ...(ssdBudget ? { ssdBudget } : {}), ...(allocatorLimitBytes ? { allocatorLimitBytes } : {}),
250
+ onClosed: result => { if (closingHost) finalResults.push(result); } };
251
+ // The unit takes the context and releases it (by ownership) on close and on its own failed start.
252
+ cleanup = undefined;
253
+ const first = await createServingUnit(context, options, input, shared);
254
+ cleanup = () => first.close({ flush: true });
255
+ // The other local models, as the registry knows them: refreshed after a download or job, and at most every few seconds on a miss.
256
+ const records = input.models ? createRecordIndex(() => input.models!.records(), input.models.startup) : undefined;
257
+ const known = async (id: string): Promise<ModelRecord | undefined> => records?.find(id);
258
+ const machine = input.models ? (await import("@mlx-bun/inference/execution/fit")).thisMachine() : undefined;
259
+ const memory = input.models ? await import("@mlx-bun/mlx/ffi") : undefined;
260
+ // Every resident model together may use this much: by default a share of what the GPU can wire.
261
+ const budgetBytes = !input.models ? Infinity
262
+ : options.modelBudgetBytes ?? defaultBudgetBytes(memory!.maxRecommendedWorkingSetSize());
263
+ const estimate = (record: ModelRecord) => estimateRecordBytes(record, { budgetBytes, cache: options.cache, ...(machine ? { machine } : {}) });
264
+ const entryOf = (unit: ServingUnit): ResidencyEntry => ({ id: unit.id, bytes: unit.bytes(), operations: unit.operations });
265
+ const source: ResidencySource<ServingUnit> = {
266
+ async resolve(id) {
267
+ const record = await known(id);
268
+ if (!record) return undefined;
269
+ return { id: record.repoId, bytes: await estimate(record), operations: declaredOperations(record.modelType) };
270
+ },
271
+ async load(entry) {
272
+ const record = (await known(entry.id))!;
273
+ const loaded = await input.models!.load(record);
274
+ // A planned runtime's own allocator limit applies while it is resident.
275
+ const limit = loaded.context.memoryPlan?.allocatorLimitBytes;
276
+ const previous = limit ? (await import("@mlx-bun/mlx/ffi")).setMemoryLimit(limit) : undefined;
277
+ const unit = await createServingUnit(loaded.context, options,
278
+ { ownership: "owned", artifact: record, ...(input.owner ? { owner: input.owner } : {}), ...(loaded.defaultAdapter ? { defaultAdapter: loaded.defaultAdapter } : {}) },
279
+ { ...shared, ...(limit ? { allocatorLimitBytes: limit } : {}) });
280
+ if (previous === undefined) return unit;
281
+ const close = unit.close.bind(unit);
282
+ return Object.assign(unit, { close: async (options: { readonly flush: boolean }) => {
283
+ try { return await close(options); } finally { (await import("@mlx-bun/mlx/ffi")).setMemoryLimit(previous); }
284
+ } });
285
+ },
286
+ };
287
+ let current = first.id;
288
+ residency = createResidencyHost<ServingUnit>({ source, budgetBytes, events: state.events,
289
+ ...(memory ? { measured: () => memory.activeMemory() } : {}),
290
+ external: () => moduleHost.whisper.resident().reduce((sum, model) => sum + model.bytes, 0),
291
+ defaultFor: async operation => operation === "generate" ? current : undefined,
292
+ // Switching: the models this host may load; a caller's own context and an expert-offload process hold one model and never switch.
293
+ ...(input.models ? { async serve(id: string, signal: AbortSignal | undefined) {
294
+ if (id !== first.id && !await known(id)) throw new ResidencyError("not-found", `${id} is not a local model; download it first`);
295
+ (await residency.acquire(id, { ...(signal ? { signal } : {}), need: ["generate"] })).release();
296
+ current = id;
297
+ } } : {}),
298
+ uses: unit => [unit.artifactPath],
299
+ log: line => console.log(line) });
300
+ // A context the caller supplied cannot be reloaded, so it is never evicted.
301
+ residency.adopt(entryOf(first), first, { pin: !input.models, ...(input.loadMs !== undefined ? { loadMs: input.loadMs } : {}) });
302
+ let modules: Awaited<ReturnType<typeof loadInstalledModules>> | undefined;
303
+ // The modules stop first (admission stops, takes in flight are joined), then the models release.
304
+ const closeModules = async () => {
305
+ const errors: unknown[] = [];
306
+ try { await modules?.stop(); } catch (error) { errors.push(error); }
307
+ try { await moduleHost.whisper.close(); } catch (error) { errors.push(error); }
308
+ if (errors.length) throw new AggregateError(errors, "module cleanup failed");
309
+ };
310
+ const closeApp = async () => {
311
+ const errors: unknown[] = [];
312
+ // A request admitted before shutdown may lease the companion while
313
+ // responses drain. Close again here; each owner joins/releases only once.
314
+ try { await closeModules(); } catch (error) { errors.push(error); }
315
+ closingHost = true;
316
+ try { await residency.close(); } catch (error) { errors.push(error); }
317
+ if (errors.length) throw new AggregateError(errors, "application cleanup failed");
318
+ };
319
+ cleanup = closeApp;
320
+ // Attach before activation, so modules can resolve either operation while they start.
321
+ // A Unix listener has no port: the requested one stands in for Pi's TCP
322
+ // loopback, and for the link's URL placeholder (its clients use the socket).
323
+ let boundPort = options.port;
324
+ const invalidateLibrary = () => { records?.invalidate(); };
325
+ // Jobs and loopback clients reach this host from the first served request. A job pauses every resident model.
326
+ // Modules leasing the served model reach it as the current one: the id and weights follow a switch.
327
+ detachLink = state.attach({ get model() { return { id: current, bytes: (residency.peek(current) ?? first).context.model.weightsBytes }; },
328
+ get port() { return boundPort; }, ...(hooks.unix ? { unix: hooks.unix } : {}),
329
+ acquireExecutionLease: signal => residency.pauseAll(signal),
330
+ // Modules that generate through the model host (a dataset job) hold the model's residency lease until they release it.
331
+ hold: (id, signal) => residency.acquire(id, { need: ["generate"], ...(signal ? { signal } : {}) }),
332
+ invalidateLibrary,
333
+ resident: () => residency.resident(),
334
+ companions: moduleHost.whisper,
335
+ adapters: leasedAdapters(residency, () => current),
336
+ ...(input.models ? { serve: (id: string, signal: AbortSignal) => residency.serve(id, { signal }) } : {}) });
337
+ modules = await loadInstalledModules({ bindings: { ...moduleHost.bindings, modelHost: () => state.modelHost } });
338
+ const models = createModelRoutes({ host: residency, current: () => current, serves: async id => id === first.id || !!await known(id) });
339
+ const moduleRoutes = createModuleRoutes(modules.routes);
340
+ const residentUnits = () => residency.resident().flatMap(model => { const unit = residency.peek(model.id); return unit ? [unit] : []; });
341
+ const persistent = state.routes;
342
+ const modelRoutes = { handle: async (request: Request) => await models.handle(request) ?? await moduleRoutes.handle(request) ?? await persistent.jobs.handle(request) ??
343
+ await persistent.appModules.handle(request) ?? await persistent.publishing.handle(request) };
344
+ const routes = hooks.routes?.(modelRoutes) ?? modelRoutes;
345
+ // startServer owns engine cleanup on entry, including a bind failure.
346
+ cleanup = undefined;
347
+ const listener = await startServer({ routes, web: state.web, sockets: state.sockets,
348
+ beforeDrain: async () => {
349
+ const errors: unknown[] = [];
350
+ try { for (const unit of residentUnits()) unit.stopBackground(); } catch (error) { errors.push(error); }
351
+ // Whisper closes with the persistent owners before drain: admission stops,
352
+ // in-flight takes are joined, weights release ahead of the chat models.
353
+ for (const result of await Promise.allSettled([hooks.beforeDrain?.(), closeModules()]))
354
+ if (result.status === "rejected") errors.push(result.reason);
355
+ if (errors.length === 1) throw errors[0];
356
+ if (errors.length) throw new AggregateError(errors, "background shutdown failed");
357
+ },
358
+ closeEngine: closeApp }, hooks.unix ? { unix: hooks.unix } : { port: options.port, hostname: options.hostname });
359
+ if (listener.server.port !== undefined) boundPort = listener.server.port;
360
+ let closing: Promise<DurabilityFlushResult> | undefined;
361
+ const close = () => closing ??= (async () => {
362
+ try { await listener.close(); } finally { try { restoreProcess(); } finally { detach(); } }
363
+ return mergeDurability(finalResults);
364
+ })();
365
+ const host = { close, flush: async () => mergeDurability(await Promise.all(residentUnits().map(unit => unit.flush()))),
366
+ stats: () => mergeStats(residentUnits().map(unit => unit.stats())) };
367
+ return hooks.unix ? host : { port: boundPort, ...host };
368
+ } catch (error) {
369
+ try { await cleanup?.(); }
370
+ catch (failure) { throw new AggregateError([error, failure], "startup and cleanup failed"); }
371
+ finally { try { restoreProcess(); } finally { detach(); } }
372
+ throw error;
373
+ }
374
+ }
375
+
376
+ /** Transcription-only composition (main's `serve <whisper checkpoint>`): the
377
+ * audio routes plus `/v1`, `/v1/models`, `/health`, and `/stats` over the Whisper
378
+ * checkpoint alone; no chat model, prompt cache, jobs, or web app. `--preload`
379
+ * loads the weights before the listener binds; otherwise the first request
380
+ * pages them in. Every take runs one at a time inside the service. The
381
+ * internal hooks are the model host's: a Unix socket instead of TCP, a route
382
+ * wrapper, and a step ahead of the Whisper close (the worker app form). */
383
+ export async function startTranscriptionHost(model: ModelRecord, options: ServeOptions,
384
+ hooks: Pick<ModelHostHooks, "unix" | "routes" | "beforeDrain"> = {}): Promise<RunningApp> {
385
+ const [{ createCompanionInfoRoutes, createHostServices, createModuleRoutes, createModuleSockets }, { startServer }] = await Promise.all([
386
+ import("@mlx-bun/app-services"), import("../server/start"),
387
+ ]);
388
+ const whisper = options.whisper ?? {};
389
+ const moduleHost = createHostServices({ whisper: { ...whisper, modelDir: model.path, modelId: model.repoId } });
390
+ let modules: Awaited<ReturnType<typeof loadInstalledModules>> | undefined;
391
+ // The modules stop first (takes in flight are joined), then the weights release.
392
+ const close = async () => {
393
+ const errors: unknown[] = [];
394
+ try { await modules?.stop(); } catch (error) { errors.push(error); }
395
+ try { await moduleHost.whisper.close(); } catch (error) { errors.push(error); }
396
+ moduleHost.events.close();
397
+ if (errors.length) throw new AggregateError(errors, "transcription cleanup failed");
398
+ };
399
+ let cleanup: (() => Promise<void>) | undefined = close;
400
+ try {
401
+ modules = await loadInstalledModules(moduleHost);
402
+ if (whisper.preload) await moduleHost.whisper.preload(model.repoId);
403
+ const audio = createModuleRoutes(modules.routes);
404
+ const loaded = modules;
405
+ const info = createCompanionInfoRoutes({ modelId: model.repoId, models: moduleHost.whisper, counters: () => loaded.status("transcription"),
406
+ name: "mlx-bun", version: pkgJson.version, startedAt: Date.now(),
407
+ endpoints: [...modules.routes.map(route => `${route.spec.method} ${route.path}`), "GET /v1/models", "GET /health", "GET /stats"] });
408
+ // startServer owns the cleanup on entry, including a bind failure.
409
+ cleanup = undefined;
410
+ const routes: RouteGroup = { handle: async request => await audio.handle(request) ?? await info.handle(request) };
411
+ const listener = await startServer({
412
+ routes: hooks.routes?.(routes) ?? routes,
413
+ web: () => null,
414
+ // No chat: a transcription-only server declares no sockets.
415
+ sockets: createModuleSockets([]),
416
+ // Whisper closes before drain: admission stops, in-flight takes are joined, weights release.
417
+ beforeDrain: async () => { try { await hooks.beforeDrain?.(); } finally { await close(); } },
418
+ closeEngine: async () => {},
419
+ }, hooks.unix ? { unix: hooks.unix } : { port: options.port, hostname: options.hostname });
420
+ return { ...(hooks.unix ? {} : { port: listener.server.port! }), close: listener.close,
421
+ downloads: { active: [], start() { throw new Error("transcription-only server owns no downloads"); } } };
422
+ } catch (error) { await cleanup?.(); throw error; }
423
+ }
@@ -0,0 +1,217 @@
1
+ // The isolated serve composition, the default for `serve`: this process keeps the persistent
2
+ // CPU state (serve-state.ts), the web app, the chat module, the Responses history, the managed jobs and
3
+ // the modules that run beside them, and loads no model. Each resident model runs in its own
4
+ // worker process (worker-unit.ts; worker-entry.ts composes the model host over a Unix socket).
5
+ // This process holds their residency by memory fit with the same manager the in-process host
6
+ // uses (residency/model-residency.ts), counting each worker at the MLX memory it measures and reports
7
+ // (cli/worker-unit.ts; the estimate stands only before its first report): a model that fits the budget
8
+ // gets its own worker beside the others; otherwise the least recently used unpinned, unleased model is drained, its worker
9
+ // flushes its saved state durably and exits (the worker gets the CLI's shutdown budget, never a
10
+ // kill first), and naming it again spawns a worker that resumes from that state. Requests route
11
+ // by their `model` (server/model-routes.ts) and forward over the worker's socket; a crash
12
+ // respawns that worker with its model while the app stays up. Whisper is a companion worker of
13
+ // its own, which can be pinned. Each worker's events are relayed onto this process's bus.
14
+ // Nothing here imports the engine or a native module.
15
+ import { mkdtempSync, rmSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+ import type { AppModule } from "@mlx-bun/app-core";
19
+ import type { ModelRecord } from "@mlx-bun/hub/registry";
20
+ import { EngineUnavailableError, type WorkerRestartBudget } from "../jobs/worker-supervisor";
21
+ import { createWorkerMemoryClient } from "../server/memory-completion-client";
22
+ import { createModelRoutes } from "../server/model-routes";
23
+ import { createProxyRoutes } from "../server/proxy-routes";
24
+ import { createResponsesClient } from "../server/responses-client";
25
+ import { startServer } from "../server/start";
26
+ import { listLocalRecords } from "../residency/local-records";
27
+ import { leasedAdapters } from "../residency/leased-adapters";
28
+ import { createResidencyHost, ResidencyError, type ResidencyEntry, type ResidencyHost, type ResidencySource } from "../residency/model-residency";
29
+ import { createRecordIndex } from "../residency/record-index";
30
+ import { defaultBudgetBytes, estimateRecordBytes } from "../residency/resident-estimate";
31
+ import type { RunningApp, ServeOptions } from "./serve-options";
32
+ import { createAppState, type RouteGroup } from "./serve-state";
33
+ import { spawnWorkerUnit, type WorkerUnit, type WorkerUnitContext } from "./worker-unit";
34
+
35
+ /** What the composition root supplies (`modules`: the installed modules that run in the persistent state)
36
+ * and, internally for tests, stand-ins for the worker entry, the restart policy, and the model listing. */
37
+ export interface IsolatedServeHooks {
38
+ modules?: Parameters<typeof createAppState>[2];
39
+ /** Selects the dedicated task-model snapshot, without loading it in the parent. */
40
+ taskSnapshot?(): Promise<string>;
41
+ entry?: string;
42
+ restarts?: Partial<WorkerRestartBudget>;
43
+ env?: Record<string, string | undefined>;
44
+ readyTimeoutMs?: number;
45
+ graceMs?: number;
46
+ notice?(line: string): void;
47
+ log?(line: string): void;
48
+ error?(line: string): void;
49
+ /** Internal (tests): sees the app's event bus, where each worker's relayed events and the host's load/unload events arrive. */
50
+ observe?(events: Pick<import("@mlx-bun/app-core").EventBus, "subscribe">): void;
51
+ /** The local chat models the host may load, instead of the registry's. */
52
+ records?(): readonly ModelRecord[];
53
+ /** The Whisper checkpoints it may load, instead of the registry's. */
54
+ companions?(): readonly ModelRecord[];
55
+ }
56
+
57
+ /** Isolated composition: the persistent state and the startup model's worker first, the listener
58
+ * once that worker serves, so startup fails the way the in-process composition does when the model cannot load. */
59
+ export async function startIsolatedServer(model: ModelRecord, options: ServeOptions, hooks: IsolatedServeHooks = {}): Promise<RunningApp> {
60
+ let residency!: ResidencyHost<WorkerUnit>;
61
+ /** The model requests that name none are answered by, and Pi's `local`: the one the server started with, then the last switch. */
62
+ let current = model.repoId;
63
+ const workers = () => residency ? residency.resident().flatMap(({ id }) => { const unit = residency.peek(id); return unit ? [unit] : []; }) : [];
64
+ const currentUnit = () => residency?.peek(current);
65
+ // Snapshots a worker reads besides its own model: the memory task model, selected here and kept out of hub GC
66
+ // from the call that carries it for as long as that worker lives (a respawned worker holds none until asked).
67
+ const retained = new WeakMap<WorkerUnit, { restarts: number; paths: Set<string> }>();
68
+ const retention = (unit: WorkerUnit) => {
69
+ let held = retained.get(unit);
70
+ if (!held || held.restarts !== unit.supervisor.restarts) retained.set(unit, held = { restarts: unit.supervisor.restarts, paths: new Set() });
71
+ return held.paths;
72
+ };
73
+ // The parent loads no model: each synthesis stage call or batch runs on the current model's worker (its memory task
74
+ // model, over its private route). A run holds that model's residency lease from its first call to its last (the same
75
+ // `acquire` every consumer takes), so the worker it depends on is never drained under it; the worker takes its own
76
+ // execution lease per call. Each call selects the task model snapshot once, here (the worker never scans the cache):
77
+ // the call carries it, and a call that loads the task model loads exactly it.
78
+ const state = await createAppState({ ...options, memoryCompletions: async signal => {
79
+ let release: (() => void) | undefined;
80
+ let selected: Promise<WorkerUnit> | undefined;
81
+ const select = async () => {
82
+ if (!residency) throw new EngineUnavailableError("starting", null);
83
+ const lease = await residency.acquire(current, { signal, need: ["generate"] });
84
+ release = () => lease.release();
85
+ return lease.unit;
86
+ };
87
+ const client = createWorkerMemoryClient(async () => {
88
+ if (!hooks.taskSnapshot) throw new Error("memory synthesis has no task model snapshot selector in this composition");
89
+ const snapshot = await hooks.taskSnapshot();
90
+ // Planning and empty pipelines never acquire or reload a worker. The first real call captures one worker,
91
+ // whose residency stays held until the run (including every in-flight row) settles.
92
+ const unit = await (selected ??= select());
93
+ retention(unit).add(snapshot);
94
+ return { worker: unit.supervisor, snapshot };
95
+ }, signal);
96
+ return Object.assign(client, { release: () => release?.() });
97
+ } }, options.storagePaths ?? {}, hooks.modules ?? []);
98
+ hooks.observe?.(state.events);
99
+ // The sockets live in a private directory (0700) this process removes, one per worker.
100
+ const socketDir = mkdtempSync(join(tmpdir(), "mlx-worker-"));
101
+ const removeSocketDir = () => rmSync(socketDir, { recursive: true, force: true });
102
+ const notice = hooks.notice ?? (line => console.log(`[isolate] ${line}`));
103
+ // The startup worker until residency adopts it: a failure in between still stops it.
104
+ let unadopted: WorkerUnit | undefined;
105
+ const closeEngine = async () => {
106
+ try { await unadopted?.close({ flush: false }); } finally { try { await residency?.close(); } finally { removeSocketDir(); } }
107
+ };
108
+ let detachLink = () => {};
109
+ const detach = () => { const release = detachLink; detachLink = () => {}; release(); };
110
+ let cleanup: (() => Promise<void>) | undefined = closeEngine;
111
+ try {
112
+ const { thisMachine } = await import("@mlx-bun/inference/execution/fit");
113
+ const machine = thisMachine();
114
+ const context: WorkerUnitContext = { options, startup: model, socketDir, publish: event => state.events.publish(event), notice,
115
+ ...(hooks.entry ? { entry: hooks.entry } : {}), ...(hooks.restarts ? { restarts: hooks.restarts } : {}), ...(hooks.env ? { env: hooks.env } : {}),
116
+ ...(hooks.readyTimeoutMs !== undefined ? { readyTimeoutMs: hooks.readyTimeoutMs } : {}), ...(hooks.graceMs !== undefined ? { graceMs: hooks.graceMs } : {}),
117
+ ...(hooks.log ? { log: hooks.log } : {}), ...(hooks.error ? { error: hooks.error } : {}) };
118
+ // Startup fails fast, as the in-process composition does: the first model's worker serves before the listener binds. Its
119
+ // report is also how this process, which asks no Metal device itself, learns the device working set.
120
+ const first = unadopted = await spawnWorkerUnit(context, model, "primary", model.sizeBytes);
121
+ // What all resident workers may use together: `--model-budget`, else the share of the device working set the in-process
122
+ // host uses (residency/resident-estimate.ts), as the first worker reported it.
123
+ const budgetBytes = options.modelBudgetBytes ?? defaultBudgetBytes(first.measured()?.workingSetBytes);
124
+ const chatModels = createRecordIndex(() => hooks.records?.() ?? listLocalRecords("generate"), model);
125
+ const companionList = () => hooks.companions?.() ?? listLocalRecords("transcribe");
126
+ // Whisper: the checkpoint `--whisper-model` resolved to, else the first downloaded one, looked up once.
127
+ let whisper: Promise<ModelRecord | undefined> | undefined;
128
+ const whisperRecord = () => whisper ??= (async () => {
129
+ const explicit = options.whisper;
130
+ if (explicit?.modelDir && explicit.modelId) {
131
+ const listed = (await companionList()).find(record => record.repoId === explicit.modelId);
132
+ return listed ?? { repoId: explicit.modelId, path: explicit.modelDir, modelType: "whisper", sizeBytes: 0, expertsBytes: 0 } as unknown as ModelRecord;
133
+ }
134
+ return (await companionList())[0];
135
+ })();
136
+ const source: ResidencySource<WorkerUnit> = {
137
+ async resolve(id) {
138
+ const chat = await chatModels.find(id);
139
+ // A config the fit model cannot read leaves the checkpoint's own size as the estimate.
140
+ if (chat) return { id, bytes: await estimateRecordBytes(chat, { budgetBytes, cache: options.cache, machine }).catch(() => chat.sizeBytes), operations: ["generate"], role: "primary" };
141
+ const companion = await whisperRecord();
142
+ if (companion && companion.repoId === id) return { id, bytes: companion.sizeBytes, operations: ["transcribe"], role: "companion" };
143
+ return undefined;
144
+ },
145
+ async load(entry) {
146
+ const record = entry.role === "companion" ? (await whisperRecord())! : (await chatModels.find(entry.id))!;
147
+ return spawnWorkerUnit(context, record, entry.role ?? "primary", entry.bytes);
148
+ },
149
+ };
150
+ residency = createResidencyHost<WorkerUnit>({ source, budgetBytes, events: state.events,
151
+ defaultFor: async operation => operation === "generate" ? current : operation === "transcribe" ? (await whisperRecord())?.repoId : undefined,
152
+ async serve(id, signal) {
153
+ if (!await chatModels.find(id)) throw new ResidencyError("not-found", `${id} is not a local model; download it first`);
154
+ (await residency.acquire(id, { ...(signal ? { signal } : {}), need: ["generate"] })).release();
155
+ current = id;
156
+ },
157
+ // Hub cleanup keeps the snapshot of every resident worker's model, and the task model's on the worker that read it.
158
+ uses: unit => [unit.record.path, ...retention(unit)],
159
+ log: line => notice(line) });
160
+ const entryOf = (unit: WorkerUnit): ResidencyEntry => ({ id: unit.id, bytes: unit.bytes(), role: unit.role, operations: unit.operations });
161
+ residency.adopt(entryOf(first), first, { loadMs: first.readyMs });
162
+ unadopted = undefined;
163
+ // Whisper stays resident when asked to (`--whisper-resident`); otherwise it is the first to go when memory is short.
164
+ const companion = options.whisper?.resident ? await whisperRecord() : undefined;
165
+ if (companion) residency.pin(companion.repoId);
166
+
167
+ const models = createModelRoutes({ host: residency, current: () => current,
168
+ serves: async id => !!await chatModels.find(id),
169
+ transcription: async () => (await whisperRecord())?.repoId,
170
+ // Audio requests belong to the Whisper worker, which loads on first use and drains a chat model when memory is short.
171
+ companion: async pathname => (pathname.startsWith("/v1/audio/") || pathname.startsWith("/admin/transcription/")) ? (await whisperRecord())?.repoId : undefined });
172
+ const responses = createResponsesClient(state.responses);
173
+ const proxy = createProxyRoutes({ workers: () => workers(), current: () => current, models, responses,
174
+ modelId: model.repoId, startedAt: Date.now() });
175
+ const invalidateLibrary = () => { chatModels.invalidate(); };
176
+ const persistent = state.routes;
177
+ // The persistent groups answer first, in the direct host's order among themselves; the proxy takes every remaining path.
178
+ const routes: RouteGroup = { handle: async request => await persistent.jobs.handle(request) ??
179
+ await persistent.appModules.handle(request) ??
180
+ await persistent.publishing.handle(request) ?? await proxy.handle(request) };
181
+ let boundPort = options.port;
182
+ // The chat module lives in the state and reaches the model through the served model host (over this listener's proxy;
183
+ // its `local` model id is whatever is current), so web chat survives a worker restart and reports its failures as errors.
184
+ // Jobs pause every resident worker; loopback clients reach the workers through the proxy; a hub switch is this host's to make.
185
+ detachLink = state.attach({ get model() { return { id: current, bytes: currentUnit()?.bytes() ?? model.sizeBytes }; }, get port() { return boundPort; },
186
+ acquireExecutionLease: signal => residency.pauseAll(signal),
187
+ // Modules that generate through the model host (a dataset job) hold the model's residency lease until they release it.
188
+ hold: (id, signal) => residency.acquire(id, { need: ["generate"], ...(signal ? { signal } : {}) }),
189
+ invalidateLibrary,
190
+ resident: () => residency.resident(),
191
+ adapters: leasedAdapters(residency, () => current),
192
+ serve: (id, signal) => residency.serve(id, { signal }) });
193
+ // startServer owns engine cleanup on entry, including a bind failure.
194
+ cleanup = undefined;
195
+ const listener = await startServer({ routes, web: state.web, sockets: state.sockets,
196
+ // The app stops its producers (jobs, downloads) while the workers are alive, then chat and HTTP drain, then every
197
+ // worker is drained, flushes its saved state, and exits.
198
+ beforeDrain: () => state.close(),
199
+ closeEngine }, { port: options.port, hostname: options.hostname });
200
+ if (listener.server.port !== undefined) boundPort = listener.server.port;
201
+ let closing: Promise<void> | undefined;
202
+ return { port: boundPort, downloads: state.downloads, close: () => closing ??= (async () => {
203
+ const errors: unknown[] = [];
204
+ try { await listener.close(); } catch (error) { errors.push(error); } finally { detach(); }
205
+ // The listener's drain already closed the state; a repeated failure here is the same one.
206
+ try { await state.close(); } catch (error) { errors.push(error); }
207
+ if (errors.length) throw errors[0];
208
+ })() };
209
+ } catch (error) {
210
+ const failures: unknown[] = [];
211
+ try { await cleanup?.(); } catch (failure) { failures.push(failure); }
212
+ finally { detach(); }
213
+ try { await state.close(); } catch (failure) { failures.push(failure); }
214
+ if (failures.length) throw new AggregateError([error, ...failures], "startup and cleanup failed");
215
+ throw error;
216
+ }
217
+ }