omnicell-router 0.8.2 → 0.10.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 (400) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/auth/api-keys.js +11 -0
  4. package/backend/dist/auth/key-models.d.ts +36 -0
  5. package/backend/dist/auth/key-models.js +99 -0
  6. package/backend/dist/capture/recorder.d.ts +4 -10
  7. package/backend/dist/capture/recorder.js +6 -58
  8. package/backend/dist/cli/clients/activity.js +2 -0
  9. package/backend/dist/cli/clients/base.d.ts +36 -11
  10. package/backend/dist/cli/clients/base.js +31 -15
  11. package/backend/dist/cli/clients/claude.d.ts +9 -0
  12. package/backend/dist/cli/clients/claude.js +6 -0
  13. package/backend/dist/cli/clients/codex.d.ts +78 -0
  14. package/backend/dist/cli/clients/codex.js +475 -57
  15. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  16. package/backend/dist/cli/clients/core-adapters.js +1 -1
  17. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  18. package/backend/dist/cli/clients/dsh.js +5 -0
  19. package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
  20. package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
  21. package/backend/dist/cli/clients/grok.d.ts +15 -1
  22. package/backend/dist/cli/clients/grok.js +16 -2
  23. package/backend/dist/cli/clients/index.d.ts +13 -1
  24. package/backend/dist/cli/clients/index.js +97 -19
  25. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  26. package/backend/dist/cli/clients/kimi.js +3 -0
  27. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  28. package/backend/dist/cli/clients/model-meta.js +6 -3
  29. package/backend/dist/cli/clients/omp.d.ts +6 -0
  30. package/backend/dist/cli/clients/omp.js +3 -0
  31. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  32. package/backend/dist/cli/clients/openclaw.js +3 -0
  33. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  34. package/backend/dist/cli/clients/opencode.js +8 -2
  35. package/backend/dist/cli/clients/pi.d.ts +6 -0
  36. package/backend/dist/cli/clients/pi.js +3 -0
  37. package/backend/dist/cli/clients/reserved.js +2 -0
  38. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  39. package/backend/dist/cli/clients/update-check.js +309 -0
  40. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  41. package/backend/dist/cli/clients/workbuddy.js +66 -0
  42. package/backend/dist/cli/index.js +5 -4
  43. package/backend/dist/cli/paths.js +8 -0
  44. package/backend/dist/cli/types.d.ts +101 -16
  45. package/backend/dist/config/comments-en.js +34 -25
  46. package/backend/dist/config/comments-zh.js +33 -24
  47. package/backend/dist/config/defaults.d.ts +280 -22
  48. package/backend/dist/config/defaults.js +279 -21
  49. package/backend/dist/config/env.d.ts +10 -0
  50. package/backend/dist/config/env.js +3 -2
  51. package/backend/dist/config/index.d.ts +22 -1
  52. package/backend/dist/config/index.js +218 -43
  53. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  54. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  55. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  56. package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
  57. package/backend/dist/config/migrations/v4-to-v5.js +42 -0
  58. package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
  59. package/backend/dist/config/migrations/v5-to-v6.js +29 -0
  60. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  61. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  62. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  63. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  64. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  65. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  66. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  67. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  68. package/backend/dist/config/runtime.js +1 -1
  69. package/backend/dist/config/schema.d.ts +3 -3
  70. package/backend/dist/config/schema.js +18 -4
  71. package/backend/dist/config/types.d.ts +221 -41
  72. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  73. package/backend/dist/egress-proxy/asset-download.js +420 -0
  74. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  75. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  76. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  77. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  78. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  79. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  80. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  81. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  82. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  83. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  84. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  85. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  86. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  87. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  88. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  89. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  90. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  91. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  92. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  93. package/backend/dist/forward-proxy/egress.js +63 -17
  94. package/backend/dist/forward-proxy/h2-forward.js +42 -15
  95. package/backend/dist/forward-proxy/index.d.ts +11 -8
  96. package/backend/dist/forward-proxy/index.js +27 -60
  97. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  98. package/backend/dist/forward-proxy/interceptor.js +4 -4
  99. package/backend/dist/forward-proxy/relay.js +3 -3
  100. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  101. package/backend/dist/forward-proxy/rules.js +25 -4
  102. package/backend/dist/forward-proxy/server.d.ts +12 -16
  103. package/backend/dist/forward-proxy/server.js +237 -171
  104. package/backend/dist/harness/host/hosts.js +3 -2
  105. package/backend/dist/index.js +59 -19
  106. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  107. package/backend/dist/ingress-proxy/access-log.js +774 -0
  108. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  109. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  110. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  111. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  112. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  113. package/backend/dist/ingress-proxy/ca.js +273 -0
  114. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  115. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  116. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  117. package/backend/dist/ingress-proxy/egress.js +364 -0
  118. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  119. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  120. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  121. package/backend/dist/ingress-proxy/index.js +144 -0
  122. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  123. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  124. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  125. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  126. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  127. package/backend/dist/ingress-proxy/relay.js +188 -0
  128. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  129. package/backend/dist/ingress-proxy/rules.js +348 -0
  130. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  131. package/backend/dist/ingress-proxy/server.js +2065 -0
  132. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  133. package/backend/dist/ingress-proxy/sni.js +124 -0
  134. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  135. package/backend/dist/ingress-proxy/status.js +15 -0
  136. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  137. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  138. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  139. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  140. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  141. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  142. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  143. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  144. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  145. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  146. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  147. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  148. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  149. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  150. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  151. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  152. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  153. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  154. package/backend/dist/ir/adapters/openai-chat.js +50 -6
  155. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  156. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  157. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  158. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  159. package/backend/dist/ir/adapters/openai-responses.d.ts +92 -1
  160. package/backend/dist/ir/adapters/openai-responses.js +163 -12
  161. package/backend/dist/ir/capabilities.js +4 -0
  162. package/backend/dist/ir/media.d.ts +20 -0
  163. package/backend/dist/ir/media.js +41 -0
  164. package/backend/dist/ir/tool-identity.d.ts +35 -0
  165. package/backend/dist/ir/tool-identity.js +40 -0
  166. package/backend/dist/ir/types.d.ts +9 -1
  167. package/backend/dist/ir/validate.d.ts +24 -0
  168. package/backend/dist/ir/validate.js +113 -63
  169. package/backend/dist/local/build-jobs.d.ts +66 -0
  170. package/backend/dist/local/build-jobs.js +243 -0
  171. package/backend/dist/local/detect.d.ts +32 -0
  172. package/backend/dist/local/detect.js +145 -0
  173. package/backend/dist/local/draft-match.d.ts +58 -0
  174. package/backend/dist/local/draft-match.js +124 -0
  175. package/backend/dist/local/engine-runtime.d.ts +522 -0
  176. package/backend/dist/local/engine-runtime.js +1 -0
  177. package/backend/dist/local/engines.d.ts +241 -0
  178. package/backend/dist/local/engines.js +651 -0
  179. package/backend/dist/local/gguf.d.ts +35 -0
  180. package/backend/dist/local/gguf.js +314 -0
  181. package/backend/dist/local/hf.d.ts +120 -0
  182. package/backend/dist/local/hf.js +304 -0
  183. package/backend/dist/local/install.d.ts +90 -0
  184. package/backend/dist/local/install.js +421 -0
  185. package/backend/dist/local/llamacpp.d.ts +55 -0
  186. package/backend/dist/local/llamacpp.js +177 -0
  187. package/backend/dist/local/local-provider.d.ts +81 -0
  188. package/backend/dist/local/local-provider.js +301 -0
  189. package/backend/dist/local/machine-stats.d.ts +87 -0
  190. package/backend/dist/local/machine-stats.js +332 -0
  191. package/backend/dist/local/model-store.d.ts +347 -0
  192. package/backend/dist/local/model-store.js +1215 -0
  193. package/backend/dist/local/part-sweep.d.ts +32 -0
  194. package/backend/dist/local/part-sweep.js +156 -0
  195. package/backend/dist/local/plan.d.ts +65 -0
  196. package/backend/dist/local/plan.js +146 -0
  197. package/backend/dist/local/resources.d.ts +49 -0
  198. package/backend/dist/local/resources.js +64 -0
  199. package/backend/dist/local/run-stats.d.ts +95 -0
  200. package/backend/dist/local/run-stats.js +195 -0
  201. package/backend/dist/local/runner.d.ts +235 -0
  202. package/backend/dist/local/runner.js +1392 -0
  203. package/backend/dist/local/settings.d.ts +79 -0
  204. package/backend/dist/local/settings.js +180 -0
  205. package/backend/dist/local/strata-catalog.d.ts +30 -0
  206. package/backend/dist/local/strata-catalog.js +511 -0
  207. package/backend/dist/local/strata-drafting.d.ts +46 -0
  208. package/backend/dist/local/strata-drafting.js +265 -0
  209. package/backend/dist/local/strata.d.ts +278 -0
  210. package/backend/dist/local/strata.js +1392 -0
  211. package/backend/dist/local/tar.d.ts +20 -0
  212. package/backend/dist/local/tar.js +367 -0
  213. package/backend/dist/local/transport.d.ts +35 -0
  214. package/backend/dist/local/transport.js +89 -0
  215. package/backend/dist/local/tune.d.ts +58 -0
  216. package/backend/dist/local/tune.js +324 -0
  217. package/backend/dist/observability/http-exchange.d.ts +2 -2
  218. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  219. package/backend/dist/opencode/catalog/auto-pull.js +284 -77
  220. package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
  221. package/backend/dist/opencode/catalog/ocr-store.js +4 -2
  222. package/backend/dist/opencode/catalog/overrides-store.d.ts +15 -4
  223. package/backend/dist/opencode/catalog/overrides-store.js +28 -19
  224. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  225. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  226. package/backend/dist/opencode/catalog/repository.js +28 -5
  227. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
  228. package/backend/dist/opencode/catalog/sources/models-dev.js +42 -14
  229. package/backend/dist/opencode/catalog/types.d.ts +42 -12
  230. package/backend/dist/opencode/catalog/types.js +38 -1
  231. package/backend/dist/opencode/credentials/def-materialize.js +27 -21
  232. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  233. package/backend/dist/opencode/credentials/sync.js +12 -3
  234. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  235. package/backend/dist/opencode/credentials/types.js +25 -0
  236. package/backend/dist/opencode/migrate/engine.d.ts +20 -0
  237. package/backend/dist/opencode/migrate/engine.js +71 -0
  238. package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
  239. package/backend/dist/opencode/migrate/migrator.js +6 -0
  240. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
  241. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
  242. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
  243. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
  244. package/backend/dist/opencode/probe.d.ts +21 -4
  245. package/backend/dist/opencode/probe.js +34 -10
  246. package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
  247. package/backend/dist/opencode/provider-def-adapters.js +43 -27
  248. package/backend/dist/opencode/provider-defs.d.ts +10 -16
  249. package/backend/dist/opencode/provider-defs.js +45 -45
  250. package/backend/dist/opencode/user-config.d.ts +23 -26
  251. package/backend/dist/opencode/user-config.js +95 -77
  252. package/backend/dist/pipeline/directives.d.ts +9 -4
  253. package/backend/dist/pipeline/directives.js +14 -10
  254. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  255. package/backend/dist/pipeline/orchestrator.js +514 -172
  256. package/backend/dist/plugins/builtin/model-gateway.js +38 -12
  257. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  258. package/backend/dist/plugins/environment-ack.js +81 -0
  259. package/backend/dist/plugins/gateways.d.ts +6 -6
  260. package/backend/dist/plugins/gateways.js +2 -2
  261. package/backend/dist/plugins/host.d.ts +100 -16
  262. package/backend/dist/plugins/host.js +637 -99
  263. package/backend/dist/plugins/install-run.d.ts +27 -0
  264. package/backend/dist/plugins/install-run.js +99 -0
  265. package/backend/dist/plugins/manifest.d.ts +84 -32
  266. package/backend/dist/plugins/manifest.js +149 -45
  267. package/backend/dist/plugins/market-install.d.ts +18 -0
  268. package/backend/dist/plugins/market-install.js +111 -0
  269. package/backend/dist/plugins/market-source.d.ts +100 -0
  270. package/backend/dist/plugins/market-source.js +449 -0
  271. package/backend/dist/plugins/market-updates.d.ts +70 -0
  272. package/backend/dist/plugins/market-updates.js +97 -0
  273. package/backend/dist/plugins/market.d.ts +677 -0
  274. package/backend/dist/plugins/market.js +2113 -0
  275. package/backend/dist/plugins/source-index.d.ts +155 -0
  276. package/backend/dist/plugins/source-index.js +217 -0
  277. package/backend/dist/plugins/types.d.ts +402 -37
  278. package/backend/dist/projects/worktrees.d.ts +88 -0
  279. package/backend/dist/projects/worktrees.js +220 -0
  280. package/backend/dist/providers/boot-direct.d.ts +41 -7
  281. package/backend/dist/providers/boot-direct.js +284 -44
  282. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  283. package/backend/dist/providers/dial-wire.d.ts +17 -0
  284. package/backend/dist/providers/dial-wire.js +49 -0
  285. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  286. package/backend/dist/providers/executors/dispatch.js +28 -9
  287. package/backend/dist/providers/executors/openai-chat.js +14 -2
  288. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  289. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  290. package/backend/dist/providers/member-match.d.ts +32 -9
  291. package/backend/dist/providers/member-match.js +65 -21
  292. package/backend/dist/providers/model-resolution.d.ts +62 -0
  293. package/backend/dist/providers/model-resolution.js +62 -0
  294. package/backend/dist/providers/price-order.d.ts +51 -0
  295. package/backend/dist/providers/price-order.js +54 -0
  296. package/backend/dist/providers/protocols-field.d.ts +24 -0
  297. package/backend/dist/providers/protocols-field.js +66 -0
  298. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  299. package/backend/dist/providers/registry.d.ts +87 -26
  300. package/backend/dist/providers/registry.js +232 -121
  301. package/backend/dist/providers/selection.d.ts +91 -0
  302. package/backend/dist/providers/selection.js +158 -0
  303. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  304. package/backend/dist/providers/virtual-meta.js +74 -18
  305. package/backend/dist/quota/cli-login.d.ts +25 -4
  306. package/backend/dist/quota/cli-login.js +38 -6
  307. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  308. package/backend/dist/quota/coverage-generation.js +29 -0
  309. package/backend/dist/quota/declarations.js +8 -4
  310. package/backend/dist/quota/engine.js +2 -2
  311. package/backend/dist/quota/prober.d.ts +43 -2
  312. package/backend/dist/quota/prober.js +97 -22
  313. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  314. package/backend/dist/resilience/error-classifier.js +29 -0
  315. package/backend/dist/router/index.d.ts +1 -1
  316. package/backend/dist/router/index.js +17 -1
  317. package/backend/dist/router/layer2-decision.d.ts +1 -1
  318. package/backend/dist/router/layer2-decision.js +2 -2
  319. package/backend/dist/routes/console.js +1043 -405
  320. package/backend/dist/routes/environments.js +1 -1
  321. package/backend/dist/routes/local-models.d.ts +2 -0
  322. package/backend/dist/routes/local-models.js +1414 -0
  323. package/backend/dist/routes/mihomo.d.ts +2 -2
  324. package/backend/dist/routes/mihomo.js +20 -11
  325. package/backend/dist/routes/projects.js +121 -0
  326. package/backend/dist/server.js +409 -15
  327. package/backend/dist/session/session-manager.d.ts +42 -5
  328. package/backend/dist/session/session-manager.js +64 -11
  329. package/backend/dist/session/session-row.d.ts +29 -8
  330. package/backend/dist/session/session-row.js +18 -13
  331. package/backend/dist/snapshot/bundle.d.ts +40 -0
  332. package/backend/dist/snapshot/bundle.js +177 -0
  333. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  334. package/backend/dist/snapshot/handoff/compress.js +77 -0
  335. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  336. package/backend/dist/snapshot/handoff/index.js +160 -0
  337. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  338. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  339. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  340. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  341. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  342. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  343. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  344. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  345. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  346. package/backend/dist/snapshot/media-fs.js +50 -0
  347. package/backend/dist/snapshot/media.d.ts +32 -0
  348. package/backend/dist/snapshot/media.js +87 -0
  349. package/backend/dist/snapshot/store.d.ts +226 -0
  350. package/backend/dist/snapshot/store.js +887 -0
  351. package/backend/dist/snapshot/tree.d.ts +112 -0
  352. package/backend/dist/snapshot/tree.js +207 -0
  353. package/backend/dist/snapshot/types.d.ts +212 -0
  354. package/backend/dist/snapshot/types.js +14 -0
  355. package/backend/dist/snapshot/view.d.ts +19 -0
  356. package/backend/dist/snapshot/view.js +57 -0
  357. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  358. package/backend/dist/snapshot/write-worker.js +129 -0
  359. package/backend/dist/surfaces/anthropic.js +4 -1
  360. package/backend/dist/surfaces/body-admission.d.ts +344 -0
  361. package/backend/dist/surfaces/body-admission.js +818 -0
  362. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  363. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  364. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  365. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  366. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  367. package/backend/dist/surfaces/gateway-chat.js +50 -12
  368. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  369. package/backend/dist/surfaces/ocr-headers.js +11 -7
  370. package/backend/dist/surfaces/systemone.js +1 -1
  371. package/backend/dist/surfaces/transport-fastify.js +32 -5
  372. package/backend/dist/surfaces/transport-node-http.d.ts +51 -6
  373. package/backend/dist/surfaces/transport-node-http.js +76 -16
  374. package/backend/dist/surfaces/types.d.ts +11 -3
  375. package/backend/dist/trace/persist.js +21 -1
  376. package/backend/dist/trace/tracker.d.ts +35 -3
  377. package/backend/dist/trace/tracker.js +23 -0
  378. package/backend/dist/types/openai.d.ts +8 -0
  379. package/backend/dist/types/router.d.ts +17 -6
  380. package/backend/dist/types/router.js +14 -2
  381. package/backend/dist/utils/client-families.d.ts +66 -0
  382. package/backend/dist/utils/client-families.js +127 -0
  383. package/backend/dist/utils/event-ring.d.ts +1 -1
  384. package/backend/dist/utils/event-ring.js +1 -1
  385. package/backend/dist/utils/proxy-node.js +1 -1
  386. package/backend/dist/utils/proxy.d.ts +135 -11
  387. package/backend/dist/utils/proxy.js +144 -29
  388. package/backend/dist/utils/run-command.d.ts +21 -1
  389. package/backend/dist/utils/run-command.js +64 -4
  390. package/backend/dist/utils/server-liveness.d.ts +28 -0
  391. package/backend/dist/utils/server-liveness.js +32 -0
  392. package/backend/dist/utils/session-file.d.ts +28 -0
  393. package/backend/dist/utils/session-file.js +34 -0
  394. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  395. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  396. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  397. package/frontend/dist/assets/{index-DxZ9MHKB.css → index-CqDSOPQ0.css} +1 -1
  398. package/frontend/dist/index.html +2 -2
  399. package/package.json +3 -1
  400. package/frontend/dist/assets/index-55VVwfFQ.js +0 -1521
@@ -0,0 +1,1392 @@
1
+ /**
2
+ * Strata runtime — `EngineRuntime` + the run-config generator (ADR-0045, §7–§8).
3
+ *
4
+ * Three facts shape this file.
5
+ *
6
+ * 1. `strata.exe` is NOT an HTTP server. It is a resident stdin worker: `--serve`
7
+ * makes it read `GEN <max_new> <ids>` / `GENI …` lines and stream `T <id>`
8
+ * back, it has no tokenizer ("this build has no tokenizer"), and its argv
9
+ * parser treats ANY unknown flag as fatal (`unknown argument: --port` → exit
10
+ * 2). The HTTP/OpenAI surface is the vendor's `serve/server.py`, which owns
11
+ * the port, spawns `strata … --serve`, and spawns the `strata-vision` encoder
12
+ * when its config has a `vision` block.
13
+ *
14
+ * 2. The thing the front-end reads is a run config (`strata-*.json`) that IS the
15
+ * engine command line: pack, native shard, PLE table, expert binary, MTP
16
+ * head, ctx, kv, pool workers, CUDA DLL dirs. The gateway writes that file.
17
+ * The operator supplies nothing.
18
+ *
19
+ * 3. The layout is OURS, under the gateway home (ADR-0045 §13). A source
20
+ * checkout next to a model file is not an install and is never consulted:
21
+ * `<ocrHome>/strata/runtime` is the control bundle (`serve/server.py` plus
22
+ * the Python it ships), `<ocrHome>/strata/data` holds `packs/`, `models/`
23
+ * and `mtp/`, and the `strata.exe` that runs is the one this gateway
24
+ * installed. The model file stays wherever the registry put it. Pack
25
+ * matching is still by the model's folder name, under OUR data directory —
26
+ * a guess that silently picks the wrong pack would load the wrong weights.
27
+ *
28
+ * Consequences the rest of the gateway reads off this module:
29
+ * - `serves()` is TRUE whenever the layout resolves: there is no operator
30
+ * setup step left to gate on, so a supported model is never shown as
31
+ * "needs setup" again.
32
+ * - `placement: 'engine'` — the engine's `--expert-cache` owns the split.
33
+ * - `accepts`: no `-ngl`, no `--threads`, no `--kv` — the config owns them.
34
+ * - `resolveCtx` honours the requested ctx, because the config is ours now.
35
+ * - NO vision leg: `server.py` starts the encoder from the config's `vision`
36
+ * block. A gateway-spawned `strata-vision.exe` on a port could never be
37
+ * used — that binary speaks `ENC <image> <out>` on stdin.
38
+ *
39
+ * What the profile still carries: the per-launch knobs (`kv`, `maxContext`)
40
+ * and optional `mtp`/`mmproj` overrides for a layout discovery cannot see.
41
+ * Nothing there is required, and an empty profile is the normal case. The
42
+ * pack is NOT among them (§11): it is matched by the model's folder name or
43
+ * built by the gateway, and a match tie is refused, never overridden.
44
+ */
45
+ import fs from 'node:fs';
46
+ import os from 'node:os';
47
+ import path from 'node:path';
48
+ import { getOcrHomeDir } from '../cli/paths.js';
49
+ import { LOCAL_DEFAULT_CTX } from '../config/defaults.js';
50
+ import { CTX_LADDER } from './plan.js';
51
+ import { readGgufMeta } from './gguf.js';
52
+ import { hfEndpoint } from './hf.js';
53
+ import { resourceEnv, resourcePlan, resourceReserves } from './resources.js';
54
+ import { readLocalModelSettings, resolveHfToken, resolveModelsDir } from './settings.js';
55
+ import { readStrataCatalog } from './strata-catalog.js';
56
+ /** The engine's own context default when its config names none. */
57
+ export const STRATA_DEFAULT_CTX = LOCAL_DEFAULT_CTX;
58
+ /** A non-empty string, trimmed. */
59
+ function str(value) {
60
+ if (typeof value !== 'string')
61
+ return undefined;
62
+ const t = value.trim();
63
+ return t.length > 0 ? t : undefined;
64
+ }
65
+ const KV_VALUES = new Set(['int8', 'fp16', 'q4_0', 'k8v4']);
66
+ /**
67
+ * Normalise one raw blob. Unknown keys are dropped rather than rejected: a
68
+ * record written by an older build stored `root`/`workspace`/`dataRoot`/
69
+ * `python` (installation facts — engine setup owns them since §10), `pack`
70
+ * (a tie is refused on disk, never overridden — §11) or `config`, and a hard
71
+ * failure there would make an existing model unlaunchable. Those keys are
72
+ * simply ignored here.
73
+ */
74
+ export function normalizeStrataProfile(raw) {
75
+ if (raw === undefined || raw === null)
76
+ return { ok: true, profile: {} };
77
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
78
+ return { ok: false, code: 'profile-invalid', error: 'strata profile must be an object' };
79
+ }
80
+ const src = raw;
81
+ const profile = {};
82
+ const mtp = str(src.mtp);
83
+ // `'off'` is the old spec switch, stored on this key before `drafting`
84
+ // existed. Fold it over and drop the sentinel so a later "auto" can stick.
85
+ if (mtp && mtp !== 'off')
86
+ profile.mtp = mtp;
87
+ const drafting = str(src.drafting);
88
+ if (drafting === 'mtp' || drafting === 'dflash2' || drafting === 'off')
89
+ profile.drafting = drafting;
90
+ else if (mtp === 'off')
91
+ profile.drafting = 'off';
92
+ const mmproj = str(src.mmproj);
93
+ if (mmproj)
94
+ profile.mmproj = mmproj;
95
+ const resourceMode = str(src.resourceMode);
96
+ if (resourceMode === 'work' || resourceMode === 'performance')
97
+ profile.resourceMode = resourceMode;
98
+ const ctx = Number(src.maxContext);
99
+ if (Number.isFinite(ctx) && ctx >= 256)
100
+ profile.maxContext = Math.floor(ctx);
101
+ const kv = str(src.kv);
102
+ if (kv && KV_VALUES.has(kv))
103
+ profile.kv = kv;
104
+ const parallel = Number(src.parallel);
105
+ if (Number.isInteger(parallel) && parallel >= 2 && parallel <= 8)
106
+ profile.parallel = parallel;
107
+ return { ok: true, profile };
108
+ }
109
+ /** Typed view of a stored blob, or null when it is not a usable profile. */
110
+ function asProfile(raw) {
111
+ const normalized = normalizeStrataProfile(raw);
112
+ return normalized.ok ? normalized.profile : null;
113
+ }
114
+ function resolveWorkspaceParts() {
115
+ const missing = [];
116
+ const workspace = findWorkspace();
117
+ if (!workspace)
118
+ missing.push(`serve/server.py in ${strataRuntimeDir()}`);
119
+ // `findWorkspace()` only answers when `serve/server.py` is inside it, so this
120
+ // is a join, never a second check.
121
+ const entry = workspace ? path.join(workspace, SERVE_ENTRY) : undefined;
122
+ const python = workspace ? findPython(workspace) : undefined;
123
+ if (workspace && !python)
124
+ missing.push(`a Python interpreter for the front-end (${pythonCandidates(workspace)[0]})`);
125
+ const dataRoot = findDataRoot();
126
+ if (!workspace || !entry || !python || !dataRoot)
127
+ return { ok: false, missing };
128
+ return { ok: true, parts: { workspace, entry, python, dataRoot } };
129
+ }
130
+ function isDir(p) {
131
+ try {
132
+ return fs.statSync(p).isDirectory();
133
+ }
134
+ catch {
135
+ return false;
136
+ }
137
+ }
138
+ function isFile(p) {
139
+ try {
140
+ return fs.statSync(p).isFile();
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ }
146
+ /** Immediate child directories, capped — a scan must not walk a whole drive. */
147
+ function childDirs(dir, limit) {
148
+ try {
149
+ return fs
150
+ .readdirSync(dir, { withFileTypes: true })
151
+ .filter((entry) => entry.isDirectory())
152
+ .slice(0, limit)
153
+ .map((entry) => path.join(dir, entry.name));
154
+ }
155
+ catch {
156
+ return [];
157
+ }
158
+ }
159
+ const SERVE_ENTRY = path.join('serve', 'server.py');
160
+ function looksLikeWorkspace(dir) {
161
+ return isFile(path.join(dir, SERVE_ENTRY));
162
+ }
163
+ /**
164
+ * Engine-level setup values (ADR-0045 §10): an optional pin on the engines
165
+ * page. A pin that does not look like the thing it names is ignored — a stale
166
+ * path must not hide the directory the gateway owns.
167
+ */
168
+ function engineSetup() {
169
+ return readLocalModelSettings().engineSetup?.strata ?? {};
170
+ }
171
+ /** The control bundle: `serve/server.py` and the Python that runs it. */
172
+ export function strataRuntimeDir() {
173
+ return path.join(getOcrHomeDir(), 'strata', 'runtime');
174
+ }
175
+ /** The interpreter the control bundle runs with: a setup pin, else the bundle's own. */
176
+ export function strataPython() {
177
+ return findPython(strataControlRoot());
178
+ }
179
+ /** The control bundle that actually holds `strata_cli`. A setup pin wins when
180
+ * it looks like a workspace; otherwise the gateway's runtime directory. */
181
+ export function strataControlRoot() {
182
+ return findWorkspace() ?? strataRuntimeDir();
183
+ }
184
+ /** `packs/`, `models/`, `mtp/`. Created on demand — this directory is ours. */
185
+ export function strataDataDir() {
186
+ const dir = path.join(getOcrHomeDir(), 'strata', 'data');
187
+ fs.mkdirSync(path.join(dir, 'packs'), { recursive: true });
188
+ fs.mkdirSync(path.join(dir, 'models'), { recursive: true });
189
+ return dir;
190
+ }
191
+ /** Test seam: the catalog read executes the installed bundle, which a sandbox
192
+ * does not have. Tests inject the family table they want to exercise instead
193
+ * of shipping a fake Python tree (same pattern as the runner's dep seam). */
194
+ let catalogOverride;
195
+ export function setStrataCatalogForTests(catalog) {
196
+ catalogOverride = catalog;
197
+ }
198
+ /** The engine's own model catalog, read from the installed control bundle.
199
+ * `machine` lets the vendor's own fit rules project VRAM use for this host. */
200
+ export function strataCatalog(machine) {
201
+ if (catalogOverride !== undefined)
202
+ return catalogOverride;
203
+ return readStrataCatalog({ root: strataControlRoot(), python: strataPython(), ...(machine ? { machine } : {}) });
204
+ }
205
+ /**
206
+ * The catalog family a model file belongs to.
207
+ *
208
+ * The PINNED FILE NAME is the first answer: the vendor's table says exactly which
209
+ * bytes it pinned, so a match is evidence. When the name does not match (the
210
+ * operator renamed the file, or imported their own copy) the ARCHITECTURE decides
211
+ * — that is the vendor's OWN rule ("strata switches to it from the file's
212
+ * architecture"), and it matters because the two layouts launch differently:
213
+ * without it a renamed qwen35moe file would fall back to `gguf-pack` and get
214
+ * packed by `iq_pack.py`, which that family has no use for.
215
+ */
216
+ export function catalogFamilyFor(modelPath, archHint) {
217
+ const catalog = strataCatalog();
218
+ const families = catalog?.families ?? [];
219
+ const name = path.basename(modelPath).toLowerCase();
220
+ for (const family of families) {
221
+ for (const model of family.models) {
222
+ if (model.files.some((file) => path.basename(file.path).toLowerCase() === name))
223
+ return family;
224
+ }
225
+ }
226
+ if (!modelPath.toLowerCase().endsWith('.gguf'))
227
+ return undefined;
228
+ // `archHint` is the caller's already-parsed header (the serve gate has one):
229
+ // re-reading it here meant one extra file open per model on every console
230
+ // list, for an answer the caller already held.
231
+ const arch = archHint ?? readGgufMeta(modelPath).arch;
232
+ if (!arch)
233
+ return undefined;
234
+ return families.find((family) => family.layout.kind === 'gguf-inplace' && family.layout.arch === arch);
235
+ }
236
+ /**
237
+ * The role files of a ready-made pack, read off the catalog entry the engine
238
+ * pinned. The repository IS the launch layout — every file keeps its repo path
239
+ * (`pack/…`, `ple-fp8.gguf`, …) — so the anchor's own relative path locates
240
+ * its siblings: the repo root is the anchor minus that path, and each role's
241
+ * file is the root plus the entry's own path. Nothing is guessed from names,
242
+ * and a missing role is named rather than left to fail at engine start.
243
+ *
244
+ * The projector is the entry's own too: a ready pack keeps Qwen's vision tower
245
+ * unquantized, so it reads pictures through the SAME pinned `mmproj` every
246
+ * Flash-Next model uses. Resolving it here means an install is never silently
247
+ * text-only, and a machine with several such models can never pair the wrong
248
+ * projector (they are byte-identical today, but that is a coincidence, not a
249
+ * contract).
250
+ */
251
+ function readyRolePaths(family, modelPath) {
252
+ const normalized = modelPath.replace(/\\/g, '/');
253
+ let entry;
254
+ let anchorPath = '';
255
+ for (const model of family.models) {
256
+ const hit = model.files.find((file) => {
257
+ const rel = file.path.replace(/\\/g, '/');
258
+ return normalized.toLowerCase().endsWith(`/${rel.toLowerCase()}`);
259
+ });
260
+ if (hit) {
261
+ entry = model;
262
+ anchorPath = hit.path.replace(/\\/g, '/');
263
+ break;
264
+ }
265
+ }
266
+ if (!entry) {
267
+ return { ok: false, missing: [`this file's pinned entry in ${family.title}'s catalog`] };
268
+ }
269
+ const repoRoot = normalized.slice(0, normalized.length - anchorPath.length - 1);
270
+ const at = (role) => {
271
+ const file = entry.files.find((row) => row.role === role);
272
+ return file ? path.join(repoRoot, ...file.path.replace(/\\/g, '/').split('/')) : undefined;
273
+ };
274
+ // The pack folder is the directory holding the entry's `index.txt` (the
275
+ // vendor's own `ready_paths` anchors on exactly that name); a repository
276
+ // that names no index is not a ready pack, whatever its roles say.
277
+ const index = entry.files.find((file) => file.role === 'pack' && path.basename(file.path).toLowerCase() === 'index.txt');
278
+ const pack = index ? path.dirname(path.join(repoRoot, ...index.path.replace(/\\/g, '/').split('/'))) : undefined;
279
+ const dense = at('dense');
280
+ const ple = at('ple');
281
+ const embd = at('embd');
282
+ const pinnedMmproj = entry.mmproj
283
+ ? path.join(repoRoot, ...entry.mmproj.path.replace(/\\/g, '/').split('/'))
284
+ : undefined;
285
+ const missing = [];
286
+ if (!pack || !looksLikePack(pack))
287
+ missing.push(`the complete pack folder (${family.title}: pack/index.txt + native_experts.txt)`);
288
+ if (!dense || !isFile(dense))
289
+ missing.push('the dense GGUF (role dense)');
290
+ if (!ple || !isFile(ple))
291
+ missing.push('the n-gram PLE table (role ple)');
292
+ if (embd && !isFile(embd))
293
+ missing.push('the token embedding GGUF (role embd)');
294
+ if (missing.length > 0 || !pack || !dense || !ple)
295
+ return { ok: false, missing };
296
+ return {
297
+ ok: true,
298
+ repoRoot,
299
+ pack,
300
+ dense,
301
+ ple,
302
+ ...(embd ? { embd } : {}),
303
+ ...(pinnedMmproj && isFile(pinnedMmproj) ? { mmproj: pinnedMmproj } : {}),
304
+ };
305
+ }
306
+ /** The front-end. A setup pin wins when it really holds `serve/server.py`;
307
+ * otherwise the gateway's own runtime directory. A checkout beside a model
308
+ * file is not a candidate (ADR-0045 §13). */
309
+ function findWorkspace() {
310
+ const explicit = engineSetup().workspace;
311
+ if (explicit && looksLikeWorkspace(explicit))
312
+ return explicit;
313
+ const ours = strataRuntimeDir();
314
+ return looksLikeWorkspace(ours) ? ours : undefined;
315
+ }
316
+ /** A data root is the directory carrying both `packs/` and `models/`. */
317
+ function looksLikeDataRoot(dir) {
318
+ return isDir(path.join(dir, 'packs')) && isDir(path.join(dir, 'models'));
319
+ }
320
+ function findDataRoot() {
321
+ const explicit = engineSetup().dataRoot;
322
+ if (explicit && looksLikeDataRoot(explicit))
323
+ return explicit;
324
+ return strataDataDir();
325
+ }
326
+ /** The front-end's engine family (`drafting.hardware_for`). The planner says
327
+ * `rocm` for an HIP install; the front-end's name for that family is `hip`.
328
+ * An unknown family is omitted so detection is left unchanged. */
329
+ function strataDraftBackend(backend) {
330
+ if (backend === 'cuda' || backend === 'sycl' || backend === 'metal')
331
+ return backend;
332
+ if (backend === 'rocm' || backend === 'hip')
333
+ return 'hip';
334
+ return undefined;
335
+ }
336
+ /** The engine's own words: a directory with `native_experts.txt` is a native
337
+ * IQ pack, and that pack will not start without `--spec`. */
338
+ function nativeIqPack(dir) {
339
+ return isFile(path.join(dir, 'native_experts.txt'));
340
+ }
341
+ /**
342
+ * A pack is a directory the packer FINISHED: the weights or index beside
343
+ * `native_experts.txt`, the completion marker `iq_pack.py` publishes LAST
344
+ * ("a pack without it is not finished"). Requiring the marker is what makes a
345
+ * build interruptible: a half-written pack (an interrupted gateway build, a
346
+ * Ctrl-C'd manual one) never matches, so the engine can never load a
347
+ * truncated weight set and fail 40 GB into the read.
348
+ */
349
+ function looksLikePack(dir) {
350
+ return (isDir(dir) &&
351
+ (isFile(path.join(dir, 'dense.bin')) || isFile(path.join(dir, 'index.txt'))) &&
352
+ isFile(path.join(dir, 'native_experts.txt')));
353
+ }
354
+ function tokensOf(value) {
355
+ return value
356
+ .toLowerCase()
357
+ .split(/[^a-z0-9]+/i)
358
+ .filter((token) => token.length > 0 && !/^\d+$/.test(token) && token !== 'gguf');
359
+ }
360
+ /**
361
+ * Match a pack to a model. Exact name match first (`abl-IQ2_XS` → `abl-iq2_xs`,
362
+ * the vendor's own convention), then shared non-numeric tokens. A tie is
363
+ * reported, never broken arbitrarily: loading the wrong pack would run the
364
+ * wrong weights and look like a model bug.
365
+ */
366
+ export function matchPack(packsDir, modelPath) {
367
+ const modelDir = packFolderName(modelPath);
368
+ const modelFile = path.basename(modelPath).replace(/\.gguf$/i, '').toLowerCase();
369
+ const direct = path.join(packsDir, modelDir);
370
+ if (looksLikePack(direct))
371
+ return { pack: direct };
372
+ const directFile = path.join(packsDir, modelFile);
373
+ if (looksLikePack(directFile))
374
+ return { pack: directFile };
375
+ const wanted = new Set([...tokensOf(modelDir), ...tokensOf(modelFile)]);
376
+ const scored = childDirs(packsDir, 64)
377
+ .filter(looksLikePack)
378
+ .map((dir) => {
379
+ const name = path.basename(dir).toLowerCase();
380
+ const score = tokensOf(name).filter((token) => wanted.has(token)).length;
381
+ return { dir, name, score };
382
+ })
383
+ .filter((row) => row.score >= 2)
384
+ .sort((a, b) => b.score - a.score);
385
+ if (scored.length === 0)
386
+ return {};
387
+ if (scored.length > 1 && scored[0].score === scored[1].score) {
388
+ return { ambiguous: scored.filter((row) => row.score === scored[0].score).map((row) => row.dir) };
389
+ }
390
+ return { pack: scored[0].dir };
391
+ }
392
+ /** The drafter the generated config names. Absent on the profile is `auto`. */
393
+ function draftingOf(profile) {
394
+ return profile.drafting ?? 'auto';
395
+ }
396
+ /**
397
+ * The `--mtp N` depth an in-place family launches with, or undefined for none.
398
+ *
399
+ * An own-path family drafts from the MTP block INSIDE its own file, so the depth
400
+ * is the catalog's declaration — except when the operator turned drafting off:
401
+ * the spec switch answers the same question, and leaving the depth in place
402
+ * would keep the engine drafting after "off". Exported because that rule is the
403
+ * one thing about this layout an operator can observe.
404
+ */
405
+ export function inplaceMtpDrafts(layout, drafting) {
406
+ if (layout.kind !== 'gguf-inplace')
407
+ return undefined;
408
+ if (drafting === 'off')
409
+ return undefined;
410
+ return layout.mtp;
411
+ }
412
+ /** The MTP draft runtime: the directory `--mtp` accepts. DFlash2 and off do
413
+ * not take that folder; the front-end strips `--mtp` for those modes. */
414
+ function findMtp(dataRoot, profile) {
415
+ const drafting = draftingOf(profile);
416
+ if (drafting === 'off' || drafting === 'dflash2')
417
+ return undefined;
418
+ if (profile.mtp && isDir(profile.mtp))
419
+ return profile.mtp;
420
+ const rt = path.join(dataRoot, 'mtp', 'rt');
421
+ if (isFile(path.join(rt, 'experts.bin')) || isFile(path.join(rt, 'dense.bin')))
422
+ return rt;
423
+ return undefined;
424
+ }
425
+ /** The vision projector: one `mmproj-*.gguf` beside the model folders. The
426
+ * profile's `'off'` sentinel (the console's vision switch) skips the leg. */
427
+ function findMmproj(dataRoot, profile, modelPath) {
428
+ if (profile.mmproj === 'off')
429
+ return undefined;
430
+ if (profile.mmproj && isFile(profile.mmproj))
431
+ return profile.mmproj;
432
+ const dirs = [path.join(dataRoot, 'models'), path.dirname(modelPath)];
433
+ // A catalog download lands under `<modelsRoot>/<owner>/<repo>/<file>` (the
434
+ // vendor's own `<owner>--<repo>` layout, one level apart), so the projector
435
+ // it fetches is a SIBLING directory of the model's — never the same folder.
436
+ // Without this scan a downloaded projector is invisible to discovery.
437
+ const modelsRoot = resolveModelsDir().dir;
438
+ for (const owner of childDirs(modelsRoot, 32)) {
439
+ dirs.push(...childDirs(owner, 32));
440
+ }
441
+ const candidates = [];
442
+ for (const dir of dirs) {
443
+ let entries;
444
+ try {
445
+ entries = fs.readdirSync(dir);
446
+ }
447
+ catch {
448
+ continue;
449
+ }
450
+ for (const name of entries) {
451
+ if (/^mmproj.*\.gguf$/i.test(name))
452
+ candidates.push(path.join(dir, name));
453
+ }
454
+ }
455
+ if (candidates.length === 0)
456
+ return undefined;
457
+ if (candidates.length === 1)
458
+ return candidates[0];
459
+ const wanted = new Set(tokensOf(path.basename(modelPath)));
460
+ const scored = candidates
461
+ .map((file) => ({ file, score: tokensOf(path.basename(file)).filter((token) => wanted.has(token)).length }))
462
+ .sort((a, b) => b.score - a.score);
463
+ return scored[0].file;
464
+ }
465
+ /** The `bin` dirs under the runtime's `nvidia` packages — the engine's DLLs.
466
+ * The control bundle installs them into its own Python; a `.venv` is the
467
+ * older layout of the same directory. */
468
+ function findLibDirs(workspace) {
469
+ const sitePackages = [];
470
+ const roots = [
471
+ path.join(workspace, 'python', 'Lib', 'site-packages'),
472
+ path.join(workspace, '.venv', 'Lib', 'site-packages'),
473
+ ];
474
+ for (const dir of roots) {
475
+ if (isDir(dir))
476
+ sitePackages.push(dir);
477
+ }
478
+ for (const lib of [path.join(workspace, 'python', 'lib'), path.join(workspace, '.venv', 'lib')]) {
479
+ for (const dir of childDirs(lib, 8)) {
480
+ const candidate = path.join(dir, 'site-packages');
481
+ if (isDir(candidate))
482
+ sitePackages.push(candidate);
483
+ }
484
+ }
485
+ const out = [];
486
+ for (const base of sitePackages) {
487
+ for (const pkg of childDirs(path.join(base, 'nvidia'), 16)) {
488
+ const bin = path.join(pkg, 'bin');
489
+ if (isDir(bin))
490
+ out.push(bin);
491
+ }
492
+ }
493
+ return out;
494
+ }
495
+ /** Interpreters the control bundle ships, then a venv in the same directory. */
496
+ function pythonCandidates(workspace) {
497
+ return process.platform === 'win32'
498
+ ? [path.join(workspace, 'python', 'python.exe'), path.join(workspace, '.venv', 'Scripts', 'python.exe')]
499
+ : [
500
+ path.join(workspace, 'python', 'bin', 'python3'),
501
+ path.join(workspace, 'python', 'bin', 'python'),
502
+ path.join(workspace, '.venv', 'bin', 'python3'),
503
+ path.join(workspace, '.venv', 'bin', 'python'),
504
+ ];
505
+ }
506
+ function findPython(workspace) {
507
+ const explicit = engineSetup().python;
508
+ const candidates = explicit ? [explicit, ...pythonCandidates(workspace)] : pythonCandidates(workspace);
509
+ return candidates.find((candidate) => isFile(candidate));
510
+ }
511
+ /** Resolve every artefact one launch needs. The owned data directory is created
512
+ * if it is missing; everything else is a read. */
513
+ export function resolveStrataLayout(input) {
514
+ const profile = asProfile(input.profile) ?? {};
515
+ const parts = resolveWorkspaceParts();
516
+ if (!parts.ok) {
517
+ return {
518
+ ok: false,
519
+ missing: parts.missing,
520
+ reason: `Strata's run config is generated here, but its inputs are missing: ${parts.missing.join('; ')}.`,
521
+ };
522
+ }
523
+ const { workspace, entry, python, dataRoot } = parts.parts;
524
+ const family = catalogFamilyFor(input.modelPath, input.arch);
525
+ const kind = family?.layout.kind ?? 'gguf-pack';
526
+ // A ready-made pack IS the engine's internal format: nothing is built, the
527
+ // repository's own layout is the launch layout, and the four roles are named
528
+ // on the engine's command line separately. Resolving it here (rather than a
529
+ // refusal) is the whole point: the files are pinned, so their presence is
530
+ // the assertion that this model was installed the vendor's way.
531
+ if (kind === 'ready-pack' && family) {
532
+ const roles = readyRolePaths(family, input.modelPath);
533
+ if (!roles.ok) {
534
+ return {
535
+ ok: false,
536
+ missing: roles.missing,
537
+ reason: `This family ships as a ready-made Strata pack; its role files are incomplete at ${path.dirname(input.modelPath)}: ${roles.missing.join('; ')}.`,
538
+ };
539
+ }
540
+ const mtp = findMtp(dataRoot, profile);
541
+ // The family's own pinned projector wins; the generic scan is the fallback
542
+ // for a family whose catalog names none.
543
+ const mmproj = profile.mmproj === 'off' ? undefined : (roles.mmproj ?? findMmproj(dataRoot, profile, input.modelPath));
544
+ // The vendor's own argv ALWAYS names an expert profile (`config_for`:
545
+ // `--expert-profile … --expert-cache auto`), ready-made packs included —
546
+ // without it `--expert-cache auto` has no profile to drive.
547
+ const expertProfile = workspaceExpertProfile(workspace);
548
+ const engineExe = input.binary;
549
+ const visionExe = engineExe
550
+ ? path.join(path.dirname(engineExe), process.platform === 'win32' ? 'strata-vision.exe' : 'strata-vision')
551
+ : undefined;
552
+ const readyTokenizer = path.join(roles.pack, 'tokenizer');
553
+ const layout = {
554
+ workspace,
555
+ entry,
556
+ python,
557
+ dataRoot,
558
+ pack: roles.pack,
559
+ modelName: path.basename(roles.repoRoot).toLowerCase(),
560
+ libDirs: findLibDirs(workspace),
561
+ // Named only when it really ships: the profile's `paths()` is the launch
562
+ // precondition check, so an unconditional value here would turn a pack
563
+ // without a tokenizer folder into a false "profile points at missing
564
+ // paths" refusal (the engine's own default covers that case).
565
+ ...(isDir(readyTokenizer) ? { tokenizer: readyTokenizer } : {}),
566
+ ready: { dense: roles.dense, ple: roles.ple, ...(roles.embd ? { embd: roles.embd } : {}) },
567
+ ...(mtp ? { mtp } : {}),
568
+ ...(mmproj ? { mmproj } : {}),
569
+ ...(expertProfile ? { expertProfile } : {}),
570
+ ...(engineExe ? { engineExe } : {}),
571
+ ...(visionExe && isFile(visionExe) ? { visionExe } : {}),
572
+ };
573
+ return { ok: true, layout };
574
+ }
575
+ // A GGUF the engine reads IN PLACE is launched from the FILE, and the only
576
+ // thing prepared for it is its tokenizer (the vendor's own own-path install
577
+ // runs `strata_tokenizer.py` and writes no weights). Requiring a pack here
578
+ // would refuse a family the engine runs natively — the mistake this branch
579
+ // exists to undo.
580
+ if (kind === 'gguf-inplace') {
581
+ const packDir = strataPackTarget(dataRoot, input.modelPath);
582
+ const tokenizer = path.join(packDir, 'tokenizer');
583
+ // The vendor's tool writes vocab.json FIRST and then the rest, so a run
584
+ // interrupted after the first write leaves a directory its own presence gate
585
+ // would accept while the engine still lacks merges/types. All four are what
586
+ // one complete run produces (chat_template.jinja is conditional, so it is
587
+ // not required), and requiring them is what makes "prepared" mean prepared.
588
+ const parts = ['vocab.json', 'merges.txt', 'token_type.json', 'tokenizer.json'];
589
+ const absent = parts.filter((name) => !isFile(path.join(tokenizer, name)));
590
+ if (absent.length > 0) {
591
+ const tokenizerTool = path.join(workspace, 'tools', 'strata_tokenizer.py');
592
+ return {
593
+ ok: false,
594
+ missing: [`the tokenizer prepared from this GGUF (packs/<model>/tokenizer: ${absent.join(', ')})`],
595
+ ...(isFile(tokenizerTool) ? { buildable: true } : {}),
596
+ reason: `This model runs on Strata's own engine path (no pack), and its tokenizer is incomplete in ${tokenizer}: ${absent.join(', ')}.`,
597
+ };
598
+ }
599
+ const mtp = findMtp(dataRoot, profile);
600
+ const mmproj = findMmproj(dataRoot, profile, input.modelPath);
601
+ const engineExe = input.binary;
602
+ const visionExe = engineExe
603
+ ? path.join(path.dirname(engineExe), process.platform === 'win32' ? 'strata-vision.exe' : 'strata-vision')
604
+ : undefined;
605
+ const layout = {
606
+ workspace,
607
+ entry,
608
+ python,
609
+ dataRoot,
610
+ pack: packDir,
611
+ modelName: path.basename(packDir).toLowerCase(),
612
+ libDirs: findLibDirs(workspace),
613
+ tokenizer,
614
+ ...(mtp ? { mtp } : {}),
615
+ ...(mmproj ? { mmproj } : {}),
616
+ ...(engineExe ? { engineExe } : {}),
617
+ ...(visionExe && isFile(visionExe) ? { visionExe } : {}),
618
+ };
619
+ return { ok: true, layout };
620
+ }
621
+ // The pack is ALWAYS the matcher's answer — there is no profile override.
622
+ // A tie is refused below and the operator breaks it on disk (rename or
623
+ // remove the stray candidate), never in a form (ADR-0045 §11): a field that
624
+ // exists only for the once-ever collision reads as "you must configure the
625
+ // pack" to everyone else.
626
+ const matched = matchPack(path.join(dataRoot, 'packs'), input.modelPath);
627
+ const pack = matched.pack;
628
+ const ambiguity = matched.ambiguous;
629
+ if (!pack) {
630
+ const missing = [
631
+ ambiguity
632
+ ? `a single pack for this model (candidates: ${ambiguity.map((dir) => path.basename(dir)).join(', ')} — rename or remove all but the one built from this model)`
633
+ : 'a built pack for this model (packs/<model>)',
634
+ ];
635
+ // The pack is the ONE input the gateway can produce itself — but only when
636
+ // the workspace it builds from resolves whole and the packer is there. A
637
+ // tie is an operator decision, never a build trigger: building would
638
+ // publish under the exact-match name and silently pick a winner.
639
+ const packer = path.join(workspace, 'tools', 'iq_pack.py');
640
+ const buildable = !ambiguity && isFile(packer);
641
+ return {
642
+ ok: false,
643
+ missing,
644
+ ...(buildable ? { buildable: true } : {}),
645
+ reason: `Strata's run config is generated here, but its inputs are missing: ${missing.join('; ')}. Packs live under ${dataRoot}.`,
646
+ };
647
+ }
648
+ const mtp = findMtp(dataRoot, profile);
649
+ const mmproj = findMmproj(dataRoot, profile, input.modelPath);
650
+ // The exe is the one this gateway installed. A binary sitting inside the
651
+ // runtime tree is not a second engine and is never preferred (ADR-0045 §13).
652
+ const engineExe = input.binary;
653
+ const visionExe = engineExe
654
+ ? path.join(path.dirname(engineExe), process.platform === 'win32' ? 'strata-vision.exe' : 'strata-vision')
655
+ : undefined;
656
+ const tokenizer = path.join(pack, 'tokenizer');
657
+ // The engine's catalog names a per-family expert profile (the Coder keeps
658
+ // half of each layer's experts). It is a workspace artefact, and the family's
659
+ // own key is what selects it — `data/expert-profile.bin` stays the fallback.
660
+ const familyProfile = family?.layout.kind === 'gguf-pack' ? family.layout.packProfile : undefined;
661
+ const expertProfile = workspaceExpertProfile(workspace, familyProfile);
662
+ const layout = {
663
+ workspace,
664
+ entry,
665
+ python,
666
+ dataRoot,
667
+ pack,
668
+ modelName: path.basename(pack).toLowerCase(),
669
+ libDirs: findLibDirs(workspace),
670
+ // `tokenizer` is declared only when the pack actually ships one: the
671
+ // profile's `paths()` gates a launch, so naming a folder that a legacy or
672
+ // third-party pack never wrote would refuse a model that used to start
673
+ // (the engine's own default resolves `<pack>/tokenizer`).
674
+ ...(isDir(tokenizer) ? { tokenizer } : {}),
675
+ ...(mtp ? { mtp } : {}),
676
+ ...(expertProfile ? { expertProfile } : {}),
677
+ ...(mmproj ? { mmproj } : {}),
678
+ ...(engineExe ? { engineExe } : {}),
679
+ ...(visionExe && isFile(visionExe) ? { visionExe } : {}),
680
+ };
681
+ return { ok: true, layout };
682
+ }
683
+ /* ------------------------------------------------------------------------- *
684
+ * The generated run config
685
+ * ------------------------------------------------------------------------- */
686
+ /**
687
+ * The engine argv one launch passes (`strata-*.json`'s `args`, built here).
688
+ * `layout.pack` is the prepared directory either way, but only a PACKED model is
689
+ * launched with `--pack` and a shard as its `--native`: a family on the engine's
690
+ * own path is read from the GGUF itself (the vendor's `install_own_path` writes
691
+ * `--native <gguf> --mtp N` and no `--pack`), and a ready-made pack names its
692
+ * dense / PLE / embedding files by ROLE (the vendor's `ready` branch). The argv
693
+ * is therefore chosen from the family's layout, never from one fixed template.
694
+ */
695
+ export function strataEngineArgs(input) {
696
+ const { layout, modelPath, ctx, kv } = input;
697
+ const inplace = input.kind === 'gguf-inplace';
698
+ const ready = input.kind === 'ready-pack' ? layout.ready : undefined;
699
+ const args = ready
700
+ ? [
701
+ '--pack', layout.pack,
702
+ '--native', ready.dense,
703
+ // The dense GGUF is ONE shard despite its name: without this the engine
704
+ // looks for a second shard beside it (the vendor's own comment).
705
+ '--native-dense-gguf', ready.dense,
706
+ '--ple-gguf', ready.ple,
707
+ ...(ready.embd ? ['--embd-gguf', ready.embd] : []),
708
+ ]
709
+ : inplace
710
+ ? ['--native', modelPath, '--prefill', 'auto']
711
+ : ['--pack', layout.pack, '--native', modelPath, '--ple-gguf', modelPath];
712
+ if (ready || !inplace) {
713
+ if (layout.expertProfile)
714
+ args.push('--expert-profile', layout.expertProfile);
715
+ args.push('--expert-cache', 'auto', '--prefill', 'auto');
716
+ // `--spec` here is only the floor a native IQ pack refuses to start without
717
+ // (exit 2 when T < 2). The front-end owns the real choice (`drafting` on
718
+ // the config): it picks DFlash2, MTP or none from this GPU, this model and
719
+ // whichever drafter file is actually on disk, and replaces this window
720
+ // when it picks DFlash2. A pack that is not native does not get a window
721
+ // invented here. `--mtp` is the layer, named only when its runtime exists.
722
+ if (nativeIqPack(layout.pack) || layout.mtp)
723
+ args.push('--spec', '4');
724
+ if (layout.mtp)
725
+ args.push('--spec-min-p', '0.5', '--mtp', layout.mtp);
726
+ }
727
+ else if (input.mtpDrafts != null) {
728
+ // Its own path keeps every expert it can on the card and drafts with the
729
+ // block inside the file; there is no pack to give a `--spec` window to.
730
+ args.push('--mtp', String(input.mtpDrafts));
731
+ }
732
+ // No `--pool-workers`: the engine's own default (0) is "every physical core
733
+ // except the host's", which is exactly what a hand-written 15 meant. Pinning
734
+ // a count here would be a machine fact frozen into every launch.
735
+ args.push('--max-context', String(ctx), '--kv', kv);
736
+ // The resource switch: VRAM kept free so the Windows driver never pages the
737
+ // expert cache out to system RAM (below ~1-1.5 GiB free, decode collapses).
738
+ if (input.reserveMib != null)
739
+ args.push('--vram-reserve-mib', String(input.reserveMib));
740
+ args.push(...(input.extraArgs ?? []));
741
+ return args;
742
+ }
743
+ /** Where the generated configs live — our home, never inside the vendor tree. */
744
+ export function strataConfigDir() {
745
+ return path.join(getOcrHomeDir(), 'strata', 'configs');
746
+ }
747
+ /**
748
+ * Where a gateway-driven build writes the pack (ADR-0045 §9): the exact-name
749
+ * candidate `matchPack` tries first — the model's own folder, lowercased, the
750
+ * vendor's own convention (`abl-IQ2_XS` → `packs/abl-iq2_xs`). Building here
751
+ * means the finished pack resolves with zero configuration, and the packer's
752
+ * completion marker (`native_experts.txt`, published last) keeps a half-built
753
+ * directory invisible to `looksLikePack` until the rename lands.
754
+ */
755
+ export function strataPackTarget(dataRoot, modelPath) {
756
+ return path.join(dataRoot, 'packs', packFolderName(modelPath));
757
+ }
758
+ /**
759
+ * The model's own folder name, lowercased — the vendor's pack-folder convention
760
+ * (`abl-IQ2_XS` → `abl-iq2_xs`). A path whose folder component is empty, `.` or
761
+ * `..` (a model file sitting at a drive root, or an operator-imported path like
762
+ * `…/x/../m.gguf`) has no usable name: `path.join(packs, '..')` IS the data
763
+ * root, so the build would pack INTO the directory that holds every pack. The
764
+ * file's stem is the honest fallback, and it never leaves `packs/`.
765
+ */
766
+ function packFolderName(modelPath) {
767
+ const dir = path.basename(path.dirname(modelPath)).toLowerCase();
768
+ if (dir && dir !== '.' && dir !== '..')
769
+ return dir;
770
+ const stem = path.basename(modelPath).replace(/\.gguf$/i, '').toLowerCase();
771
+ return stem || 'model';
772
+ }
773
+ /** The config path for one (model, ctx) pair — stable, so a re-launch reuses it. */
774
+ export function strataConfigPath(layout, ctx) {
775
+ return path.join(strataConfigDir(), `${layout.modelName}-ctx${ctx}.json`);
776
+ }
777
+ /**
778
+ * Build the vendor config object. Everything the old console asked for is
779
+ * derived here. `exe` is the engine binary this gateway installed.
780
+ */
781
+ export function buildStrataConfig(input) {
782
+ const { layout, modelPath } = input;
783
+ const servedName = input.servedName ?? layout.modelName;
784
+ const drafting = input.drafting ?? 'auto';
785
+ const family = input.engineBackend ? strataDraftBackend(input.engineBackend) : undefined;
786
+ const config = {
787
+ exe: layout.engineExe ?? input.engineExe,
788
+ args: strataEngineArgs({
789
+ layout,
790
+ modelPath,
791
+ ctx: input.ctx,
792
+ kv: input.kv,
793
+ ...(input.layoutKind ? { kind: input.layoutKind } : {}),
794
+ ...(input.mtpDrafts != null ? { mtpDrafts: input.mtpDrafts } : {}),
795
+ ...(input.resources ? { reserveMib: input.resources.reserveMib } : {}),
796
+ extraArgs: input.extraArgs,
797
+ }),
798
+ cwd: layout.workspace,
799
+ model_name: servedName,
800
+ // The front-end reads this at every start and rewrites the drafter flags
801
+ // for this GPU, this file and the drafter packs that exist. Absent, it
802
+ // still defaults to auto; writing it keeps the operator's "off" from
803
+ // being ignored.
804
+ drafting,
805
+ // An in-place family switches the engine's PATH on this key; without it the
806
+ // engine reads a qwen35moe file as Flash-Next and refuses it.
807
+ ...(input.arch ? { arch: input.arch } : {}),
808
+ // Which engine this build is. On a machine with two vendors' cards, the
809
+ // front-end otherwise scores the idle card and picks the drafter for it.
810
+ ...(family ? { backend: family } : {}),
811
+ log: path.join(strataConfigDir(), `${layout.modelName}.log`),
812
+ lib_dirs: layout.libDirs,
813
+ };
814
+ if (drafting === 'off')
815
+ config.mtp = false;
816
+ // The engine reads `env` from its run config (server.py merges it into the
817
+ // engine's environment), so the RAM-keep figure needs no second file.
818
+ const env = resourceEnv(input.resources ?? null);
819
+ if (Object.keys(env).length > 0)
820
+ config.env = env;
821
+ // `parallel` is a SERVER-level key: server.py translates it into the
822
+ // engine's `--batch N` itself (and says when the engine clamps it). Writing
823
+ // --batch into args directly would bypass the server's own bookkeeping
824
+ // (#465, parallel_args()).
825
+ if (input.parallel !== undefined)
826
+ config.parallel = input.parallel;
827
+ if (layout.tokenizer)
828
+ config.tokenizer = layout.tokenizer;
829
+ // The encoder is `server.py`'s child; without a projector there is no vision
830
+ // block at all, so a text-only model never pays for the encoder.
831
+ if (layout.visionExe && layout.mmproj) {
832
+ config.vision = { exe: layout.visionExe, mmproj: layout.mmproj, model: modelPath };
833
+ }
834
+ return config;
835
+ }
836
+ /** Write the config and return its path. Errors surface as the launch error. */
837
+ export function writeStrataConfig(input) {
838
+ const target = strataConfigPath(input.layout, input.ctx);
839
+ try {
840
+ fs.mkdirSync(path.dirname(target), { recursive: true });
841
+ fs.writeFileSync(target, JSON.stringify(buildStrataConfig(input), null, 1), 'utf8');
842
+ }
843
+ catch (err) {
844
+ return { ok: false, error: `cannot write the generated Strata config at ${target}: ${err instanceof Error ? err.message : String(err)}` };
845
+ }
846
+ return { ok: true, path: target };
847
+ }
848
+ /* ------------------------------------------------------------------------- *
849
+ * Runtime descriptor
850
+ * ------------------------------------------------------------------------- */
851
+ /**
852
+ * Architectures Strata's engine serves (its curated MoE families' GGUF arch
853
+ * strings). Strata is family-locked — it does not serve arbitrary GGUF files —
854
+ * so the family gate lives HERE, in the engine's own runtime, never in the
855
+ * header parser or the runner.
856
+ */
857
+ export const STRATA_FAMILY_ARCHES = new Set([
858
+ // `qwen4exp` is what "Qwen3.8-Flash-Next" MoE checkpoints report in their
859
+ // GGUF header (48 layers / 512 experts in the field), and Strata runs them —
860
+ // the list is evidence-driven, not derived from a family name.
861
+ 'qwen3moe',
862
+ 'qwen3next',
863
+ 'qwen4exp',
864
+ // Qwen3.6-35B-A3B (and Ornith-1.5-35B-A3B, the same architecture): the engine
865
+ // reads these GGUFs on its own path, so the arch is served here as well.
866
+ 'qwen35moe',
867
+ 'deepseek2',
868
+ 'glm4moe',
869
+ 'gpt-oss',
870
+ ]);
871
+ const PROFILE_FIELDS = [
872
+ // The same four the run page offers, and the vendor's own list
873
+ // (`drafting.py` MODES): auto / MTP / DFlash2 / off.
874
+ {
875
+ key: 'drafting',
876
+ label: 'localModels.runSpec',
877
+ hint: 'localModels.runSpecHint',
878
+ kind: 'select',
879
+ runPageOwned: true,
880
+ placeholderKey: 'localModels.runSpecAuto',
881
+ options: [
882
+ { value: 'mtp', label: 'MTP' },
883
+ { value: 'dflash2', label: 'DFlash2' },
884
+ { value: 'off', label: 'off', labelKey: 'localModels.runSpecOff' },
885
+ ],
886
+ },
887
+ {
888
+ key: 'mmproj',
889
+ label: 'localModels.strataMmproj',
890
+ hint: 'localModels.strataMmprojHint',
891
+ kind: 'text',
892
+ mono: true,
893
+ picker: 'file',
894
+ runPageOwned: true,
895
+ },
896
+ {
897
+ key: 'kv',
898
+ label: 'localModels.strataKv',
899
+ hint: 'localModels.strataKvHint',
900
+ kind: 'select',
901
+ options: [
902
+ { value: 'int8', label: 'int8' },
903
+ { value: 'fp16', label: 'fp16' },
904
+ { value: 'q4_0', label: 'q4_0' },
905
+ { value: 'k8v4', label: 'k8v4' },
906
+ ],
907
+ },
908
+ {
909
+ key: 'maxContext',
910
+ label: 'localModels.strataMaxContext',
911
+ hint: 'localModels.strataMaxContextHint',
912
+ kind: 'select',
913
+ placeholderKey: 'localModels.runSpecAuto',
914
+ // The same ladder the run page's ctx picker shows — one source, one climb.
915
+ options: CTX_LADDER.map((step) => ({ value: String(step), label: step >= 1024 ? `${Math.round(step / 1024)}K` : String(step) })),
916
+ },
917
+ { key: 'parallel', label: 'localModels.strataParallel', hint: 'localModels.strataParallelHint', kind: 'number', min: 2, max: 8, step: 1, placeholder: '1' },
918
+ ];
919
+ /**
920
+ * What the engines-page card shows when nothing is pinned (ADR-0045 §13).
921
+ * These are the gateway's own directories, whether or not the files are
922
+ * there yet — an empty box that says "auto" hides the path the install uses.
923
+ * Stored overrides are not consulted: the card shows those itself.
924
+ */
925
+ function resolveSetupDiscovery() {
926
+ const workspace = strataRuntimeDir();
927
+ return {
928
+ workspace,
929
+ dataRoot: path.join(getOcrHomeDir(), 'strata', 'data'),
930
+ python: pythonCandidates(workspace).find(isFile) ?? pythonCandidates(workspace)[0],
931
+ };
932
+ }
933
+ const SETUP = {
934
+ intro: 'localModels.strataSetupIntro',
935
+ fields: [
936
+ { key: 'workspace', label: 'localModels.strataWorkspace', hint: 'localModels.strataWorkspaceHint', kind: 'text', mono: true, placeholder: 'auto', picker: 'directory' },
937
+ { key: 'dataRoot', label: 'localModels.strataDataRoot', hint: 'localModels.strataDataRootHint', kind: 'text', mono: true, placeholder: 'auto', picker: 'directory' },
938
+ { key: 'python', label: 'localModels.strataPython', hint: 'localModels.strataPythonHint', kind: 'text', mono: true, placeholder: 'auto', derived: true },
939
+ ],
940
+ resolve: () => resolveSetupDiscovery(),
941
+ normalize: (raw) => {
942
+ if (raw === undefined || raw === null)
943
+ return { ok: true, setup: {} };
944
+ if (typeof raw !== 'object' || Array.isArray(raw))
945
+ return { ok: false, error: 'strata setup must be an object' };
946
+ const src = raw;
947
+ const setup = {};
948
+ for (const key of ['workspace', 'dataRoot', 'python']) {
949
+ const value = str(src[key]);
950
+ if (value)
951
+ setup[key] = value;
952
+ }
953
+ return { ok: true, setup };
954
+ },
955
+ };
956
+ /**
957
+ * The engine's own load model for the plan panel's estimate cards (ADR-0045:
958
+ * the console renders the declaration; it never estimates an engine-owned
959
+ * placement itself). The dense half rides the GPU at VRAM bandwidth; one
960
+ * token pulls `expertsUsed / experts` of the expert mass through the pack
961
+ * index at page-cache bandwidth (cold-cache disk reads are the pessimistic
962
+ * tail, not the estimate).
963
+ */
964
+ const DENSE_GB_PER_SEC = 250;
965
+ const EXPERT_STREAM_GB_PER_SEC = 50;
966
+ /** Bytes a launch maps EAGERLY: the pack's dense half and its index. */
967
+ function eagerPackBytes(pack) {
968
+ const dense = path.join(pack, 'dense.bin');
969
+ if (!isFile(dense))
970
+ return undefined;
971
+ let total = fs.statSync(dense).size;
972
+ const index = path.join(pack, 'index.txt');
973
+ if (isFile(index))
974
+ total += fs.statSync(index).size;
975
+ return total;
976
+ }
977
+ /** The estimate half of the declaration, from facts the caller resolved. */
978
+ function estimateStrataRun(layout, where) {
979
+ const eager = eagerPackBytes(layout.pack);
980
+ if (eager == null)
981
+ return {};
982
+ const experts = where.meta?.experts ?? 0;
983
+ const used = where.meta?.expertsUsed ?? 0;
984
+ const total = where.sizeBytes ?? 0;
985
+ if (experts <= 0 || used <= 0 || total <= eager)
986
+ return { firstLoadBytes: eager };
987
+ const expertBytesPerToken = (total - eager) * Math.min(1, used / experts);
988
+ const secondsPerToken = eager / 1e9 / DENSE_GB_PER_SEC + expertBytesPerToken / 1e9 / EXPERT_STREAM_GB_PER_SEC;
989
+ return { estTokPerSec: Math.max(1, Math.round(1 / Math.max(1e-6, secondsPerToken))), firstLoadBytes: eager };
990
+ }
991
+ const PROFILE = {
992
+ intro: 'localModels.strataProfileIntro',
993
+ // No core group: there is nothing to fill in. The rows below are OVERRIDES
994
+ // for a workspace the layout cannot infer, and an empty record is normal.
995
+ groups: [{ id: 'advanced', label: 'localModels.strataSectionAdvanced', fields: [...PROFILE_FIELDS] }],
996
+ normalize: (raw) => normalizeStrataProfile(raw),
997
+ paths: (raw, modelPath) => {
998
+ const resolved = resolveStrataLayout({ modelPath, profile: raw });
999
+ if (!resolved.ok)
1000
+ return [];
1001
+ const { layout } = resolved;
1002
+ return [
1003
+ layout.workspace,
1004
+ layout.entry,
1005
+ layout.python,
1006
+ layout.pack,
1007
+ ...(layout.ready ? [layout.ready.dense, layout.ready.ple, ...(layout.ready.embd ? [layout.ready.embd] : [])] : []),
1008
+ ...(layout.engineExe ? [layout.engineExe] : []),
1009
+ ...(layout.tokenizer ? [layout.tokenizer] : []),
1010
+ ...(layout.mtp ? [layout.mtp] : []),
1011
+ ...(layout.expertProfile ? [layout.expertProfile] : []),
1012
+ ...(layout.mmproj ? [layout.mmproj] : []),
1013
+ ];
1014
+ },
1015
+ describe: (raw, ctx, _kvCacheQ8, where) => {
1016
+ if (!where?.modelPath)
1017
+ return { argv: [], features: [] };
1018
+ const resolved = resolveStrataLayout({ modelPath: where.modelPath, profile: raw, ...(where.binary ? { binary: where.binary } : {}) });
1019
+ if (!resolved.ok)
1020
+ return { argv: [], features: [] };
1021
+ const { layout } = resolved;
1022
+ // ONE line: the process the gateway actually spawns. The engine argv
1023
+ // (--pack/--native/--max-context) lives INSIDE the generated config — the
1024
+ // operator never typed it and never will, so echoing it here would dress a
1025
+ // derived fact up as a knob (and duplicate what the config filename already
1026
+ // says: pack name + ctx). The curious open the JSON; the chips carry the
1027
+ // capability readout.
1028
+ const parallel = (asProfile(raw) ?? {}).parallel ?? 1;
1029
+ // The resource switch's numbers are a launch fact the operator should see
1030
+ // next to MTP/Vision — the plan panel is where a switch and its effect meet.
1031
+ const reserves = resourceReserves({ vramMb: where.vramMb });
1032
+ const reserve = where.headroom === false ? reserves.performance : reserves.work;
1033
+ return {
1034
+ argv: [`--engine strata --config ${strataConfigPath(layout, ctx)}`],
1035
+ features: [
1036
+ { label: 'MTP', on: !!layout.mtp },
1037
+ { label: 'PLE', on: true },
1038
+ { label: 'Vision', on: !!(layout.visionExe && layout.mmproj) },
1039
+ { label: `VRAM −${reserve} MiB`, on: true },
1040
+ // One-at-a-time is the default and says nothing; a batch the operator
1041
+ // asked for is a fact worth seeing next to MTP/Vision.
1042
+ ...(parallel >= 2 ? [{ label: `Parallel ×${parallel}`, on: true }] : []),
1043
+ ],
1044
+ ...estimateStrataRun(layout, where),
1045
+ };
1046
+ },
1047
+ // The HTTP surface answers as the pack's name — the same string the generated
1048
+ // config's `model_name` carries, so a client and the console never disagree.
1049
+ servedName: (raw, where) => {
1050
+ if (!where?.modelPath)
1051
+ return undefined;
1052
+ const resolved = resolveStrataLayout({ modelPath: where.modelPath, profile: raw, ...(where.binary ? { binary: where.binary } : {}) });
1053
+ return resolved.ok ? resolved.layout.modelName : undefined;
1054
+ },
1055
+ };
1056
+ /**
1057
+ * Cheap disk probe (no directory scans): does the draft layer exist NOW? Used
1058
+ * by the model store to re-derive a cached `preparable` verdict — the layer can
1059
+ * appear without the gateway (the vendor's own installer, a copied folder), and
1060
+ * a stale `true` would keep offering a build that answers `nothing-to-do`.
1061
+ */
1062
+ export function strataDraftLayerPresent(profile) {
1063
+ return Boolean(findMtp(findDataRoot(), asProfile(profile) ?? {}));
1064
+ }
1065
+ /**
1066
+ * The expert HOTNESS profile a launch names. The vendor's own argv always
1067
+ * carries one (`--expert-profile … --expert-cache auto`, for ready-made packs
1068
+ * too — without it `auto` has no profile to drive); a family may pin its own
1069
+ * (the Coder keeps half of each layer's experts), and the workspace's generic
1070
+ * `data/expert-profile.bin` is the fallback.
1071
+ */
1072
+ function workspaceExpertProfile(workspace, familyProfile) {
1073
+ const specific = familyProfile ? path.join(workspace, 'data', familyProfile) : undefined;
1074
+ if (specific && isFile(specific))
1075
+ return specific;
1076
+ const generic = path.join(workspace, 'data', 'expert-profile.bin');
1077
+ return isFile(generic) ? generic : undefined;
1078
+ }
1079
+ /**
1080
+ * The MTP draft layer is missing AND this workspace can build it.
1081
+ *
1082
+ * Only the Qwen3.8-Flash-Next families take it: the vendor's own comment says
1083
+ * an own-path family (`qwen36`) has "no separate MTP draft layer … drafts with
1084
+ * the file's own MTP block", so fetching the Flash-Next drafter for it would
1085
+ * spend ~5 GB on weights the launch never reads.
1086
+ */
1087
+ function canBuildDraftLayer(workspace, dataRoot, profile, kind) {
1088
+ if (kind === 'gguf-inplace')
1089
+ return false;
1090
+ const typed = asProfile(profile) ?? {};
1091
+ if (findMtp(dataRoot, typed))
1092
+ return false;
1093
+ if (draftingOf(typed) === 'off' || draftingOf(typed) === 'dflash2')
1094
+ return false;
1095
+ return ['mtp_fetch.py', 'mtp_pack.py', 'mtp_rt.py'].every((tool) => isFile(path.join(workspace, 'tools', tool)));
1096
+ }
1097
+ /** What one launch writes into the engine's `--kv` flag. */
1098
+ function kvFor(profile) {
1099
+ return profile.kv ?? 'int8';
1100
+ }
1101
+ /**
1102
+ * The MTP draft layer, prepared the way the vendor's own setup prepares it:
1103
+ * `mtp_fetch.py fetch` pulls the ~5 GB of tensors the original checkpoint's
1104
+ * draft head needs, `mtp_pack.py` packs them, `mtp_rt.py` builds the runtime
1105
+ * directory `--mtp` takes. It is the ONE launch input this engine derives that
1106
+ * does not depend on the weights' layout, which is why every family gets it —
1107
+ * a ready-made pack included.
1108
+ *
1109
+ * `off` / `dflash2` are the operator's answers to the same question (no MTP
1110
+ * folder is used, so none is built), and an own-path family has no separate
1111
+ * layer at all; a finished layer costs no process. The mirror and token the
1112
+ * gateway already holds are passed through, so a machine that can download the
1113
+ * model can also fetch its draft layer.
1114
+ */
1115
+ function draftLayerLegs(jobId, workspace, python, dataRoot, drafting, kind) {
1116
+ // The drafter is the FLASH-NEXT head; an own-path family drafts from the
1117
+ // block inside its own file, so this chain does not apply to it.
1118
+ if (kind === 'gguf-inplace')
1119
+ return [];
1120
+ if (drafting === 'off' || drafting === 'dflash2')
1121
+ return [];
1122
+ const mtpDir = path.join(dataRoot, 'mtp');
1123
+ const packed = path.join(mtpDir, 'mtp-q2_0.gguf');
1124
+ const rt = path.join(mtpDir, 'rt');
1125
+ const tool = (name) => path.join(workspace, 'tools', name);
1126
+ const missing = ['mtp_fetch.py', 'mtp_pack.py', 'mtp_rt.py'].map(tool).filter((file) => !isFile(file));
1127
+ // A bundle that does not ship these tools can still RUN the model: the draft
1128
+ // layer is an optional drafter, and the generated config's `drafting: auto`
1129
+ // picks whatever is on disk (nothing, here). Refusing the whole prepare over an
1130
+ // optional sidecar would block a model that works — the same class of gate
1131
+ // ADR-0045 §6 forbids. Skipping is the honest answer; the launch simply has no
1132
+ // `--mtp`.
1133
+ if (missing.length > 0)
1134
+ return [];
1135
+ const token = resolveHfToken().token;
1136
+ const env = { HF_ENDPOINT: hfEndpoint() };
1137
+ if (token)
1138
+ env.HF_TOKEN = token;
1139
+ const layerDone = () => isFile(path.join(rt, 'experts.bin')) || isFile(path.join(rt, 'dense.bin'));
1140
+ return [
1141
+ {
1142
+ cmd: python,
1143
+ args: [tool('mtp_fetch.py'), 'fetch', '--out', mtpDir],
1144
+ cwd: workspace,
1145
+ key: `${jobId}:mtp-fetch`,
1146
+ aux: false,
1147
+ name: 'mtp-fetch',
1148
+ env,
1149
+ // This is the one build step that DIALS the hub: it inherits the market's
1150
+ // egress (a proxy market must fetch the draft layer over the same leg the
1151
+ // weights came through), not the ambient process environment.
1152
+ network: true,
1153
+ // The packed GGUF is the last thing the fetch leaves behind, and `rt`
1154
+ // supersedes it entirely: either one means the tensors are already here.
1155
+ skipIf: () => layerDone() || isFile(packed),
1156
+ },
1157
+ {
1158
+ cmd: python,
1159
+ args: [tool('mtp_pack.py'), '--src', mtpDir, '--experts', 'q2_0', '--out', packed],
1160
+ cwd: workspace,
1161
+ key: `${jobId}:mtp-pack`,
1162
+ aux: false,
1163
+ name: 'mtp-pack',
1164
+ skipIf: () => layerDone() || isFile(packed),
1165
+ },
1166
+ {
1167
+ cmd: python,
1168
+ args: [tool('mtp_rt.py'), '--gguf', packed, '--out', rt],
1169
+ cwd: workspace,
1170
+ key: `${jobId}:mtp-rt`,
1171
+ aux: false,
1172
+ name: 'mtp-rt',
1173
+ skipIf: layerDone,
1174
+ },
1175
+ ];
1176
+ }
1177
+ export const STRATA_RUNTIME = {
1178
+ // `--expert-cache auto` owns placement; there is no `-ngl` to fill in.
1179
+ placement: 'engine',
1180
+ // Every shared knob that would otherwise be a dead control: the pool, the
1181
+ // ctx ceiling and the KV type are the generated config's, and the front-end
1182
+ // takes none of them on its own command line. A control that changes nothing
1183
+ // is the bug ADR-0043 names.
1184
+ accepts: { ngl: false, threads: false, flashAttn: false, kv: false, reasoning: false, spec: true, vision: true, resources: true },
1185
+ serves: ({ modelPath, meta, profile }) => {
1186
+ if (!modelPath.toLowerCase().endsWith('.gguf')) {
1187
+ return { serves: false, family: false, reason: 'Strata loads GGUF shards; this file is not one, so its engine cannot serve it' };
1188
+ }
1189
+ // A ready-made pack is the engine's OWN format: its anchor is the DENSE
1190
+ // half, which is dense BY DESIGN (the routed experts live in `pack/`), so
1191
+ // the expert-count gate below would refuse a perfectly runnable model. The
1192
+ // layout's role files are the assertion here.
1193
+ const family = catalogFamilyFor(modelPath, meta?.arch);
1194
+ if (family?.layout.kind === 'ready-pack') {
1195
+ const resolved = resolveStrataLayout({ modelPath, profile, ...(meta?.arch ? { arch: meta.arch } : {}) });
1196
+ return resolved.ok
1197
+ ? {
1198
+ serves: true,
1199
+ family: true,
1200
+ ...(canBuildDraftLayer(resolved.layout.workspace, resolved.layout.dataRoot, profile, 'ready-pack') ? { preparable: true } : {}),
1201
+ }
1202
+ : { serves: false, family: true, reason: resolved.reason };
1203
+ }
1204
+ // An UNREADABLE header is not a dense model. Reporting "no routed experts"
1205
+ // for a truncated shard or a foreign file sent the operator looking for a
1206
+ // different model instead of the real cause (the wrong shard, or a failed
1207
+ // scan), so that answer is stated on its own.
1208
+ if (!meta || meta.ok === false) {
1209
+ const why = meta?.reason ? ` (${meta.reason})` : '';
1210
+ return {
1211
+ serves: false,
1212
+ family: false,
1213
+ reason: `this file's GGUF header could not be read${why}, so the engine's layout for it cannot be resolved — check that it is shard 1 of the model`,
1214
+ };
1215
+ }
1216
+ const experts = meta.experts ?? 0;
1217
+ const arch = meta.arch ?? '';
1218
+ if (experts <= 0) {
1219
+ return {
1220
+ serves: false,
1221
+ family: false,
1222
+ reason: 'this checkpoint declares no routed experts (it is dense), and Strata only serves Mixture-of-Experts models',
1223
+ };
1224
+ }
1225
+ // No operator setup step gates this: the front-end and the data directory
1226
+ // are the gateway's. `needsSetup` is never set (ADR-0045 §8, §13).
1227
+ const resolved = resolveStrataLayout({ modelPath, profile, ...(arch ? { arch } : {}) });
1228
+ if (resolved.ok) {
1229
+ const kind = family?.layout.kind ?? 'gguf-pack';
1230
+ return {
1231
+ serves: true,
1232
+ family: true,
1233
+ // The draft layer is the one thing a RUNNABLE model can still lack,
1234
+ // and its absence is a silent 2× in decode speed — so it is reported
1235
+ // as work the engine can do, not as a difference the operator cannot
1236
+ // see. An own-path family has no separate layer to build.
1237
+ ...(canBuildDraftLayer(resolved.layout.workspace, resolved.layout.dataRoot, profile, kind) ? { preparable: true } : {}),
1238
+ };
1239
+ }
1240
+ // Unresolvable, and the reason names the missing artefact.
1241
+ return {
1242
+ serves: false,
1243
+ family: arch ? STRATA_FAMILY_ARCHES.has(arch) : false,
1244
+ reason: resolved.reason,
1245
+ // The pack is the one input the gateway can produce itself (ADR-0045 §9):
1246
+ // when the layout says so, the console offers a build, not a form.
1247
+ ...(resolved.buildable ? { buildable: true } : {}),
1248
+ };
1249
+ },
1250
+ resolveCtx: ({ requested, profile, meta }) => {
1251
+ // The config is generated per launch, so the requested ctx IS the truth —
1252
+ // it is what `--max-context` will say. The ceiling is the model's trained
1253
+ // context, and the floor is the engine's own default.
1254
+ const overrides = asProfile(profile);
1255
+ const ceiling = meta?.maxCtx && meta.maxCtx >= 256 ? meta.maxCtx : undefined;
1256
+ const wanted = Number.isFinite(requested) && requested >= 256 ? Math.floor(requested) : (overrides?.maxContext ?? STRATA_DEFAULT_CTX);
1257
+ const chosen = overrides?.maxContext ?? wanted;
1258
+ return ceiling ? Math.min(chosen, ceiling) : chosen;
1259
+ },
1260
+ legs: async (facts) => {
1261
+ const profile = asProfile(facts.profile) ?? {};
1262
+ const resolved = resolveStrataLayout({ modelPath: facts.modelPath, profile, binary: facts.binary });
1263
+ if (!resolved.ok)
1264
+ return { error: resolved.reason };
1265
+ const { layout } = resolved;
1266
+ // The family's layout decides how the engine is told to load these weights
1267
+ // (a built pack, the GGUF itself with its architecture named, or the
1268
+ // ready-made role files).
1269
+ const family = catalogFamilyFor(facts.modelPath);
1270
+ const layoutKind = family?.layout.kind ?? 'gguf-pack';
1271
+ const drafting = draftingOf(profile);
1272
+ // An own-path family drafts from the MTP block inside its own file; the
1273
+ // depth is the catalog's, unless the operator's spec switch says off.
1274
+ const mtpDrafts = family && layoutKind === 'gguf-inplace' ? inplaceMtpDrafts(family.layout, drafting) : undefined;
1275
+ const config = writeStrataConfig({
1276
+ layout,
1277
+ modelPath: facts.modelPath,
1278
+ engineExe: layout.engineExe ?? facts.binary,
1279
+ ctx: facts.ctx,
1280
+ kv: kvFor(profile),
1281
+ ...(profile.parallel !== undefined ? { parallel: profile.parallel } : {}),
1282
+ drafting,
1283
+ engineBackend: facts.backend,
1284
+ layoutKind,
1285
+ ...(layoutKind === 'gguf-inplace' && family?.layout.kind === 'gguf-inplace'
1286
+ ? {
1287
+ ...(family.layout.arch ? { arch: family.layout.arch } : {}),
1288
+ ...(mtpDrafts != null ? { mtpDrafts } : {}),
1289
+ }
1290
+ : {}),
1291
+ ...(facts.servedName ? { servedName: facts.servedName } : {}),
1292
+ resources: resourcePlan({
1293
+ headroom: facts.options.headroom,
1294
+ ...(facts.vramMb != null ? { vramMb: facts.vramMb } : {}),
1295
+ ramBytes: os.totalmem(),
1296
+ }),
1297
+ extraArgs: facts.options.extraArgs,
1298
+ });
1299
+ if (!config.ok)
1300
+ return { error: config.error };
1301
+ const args = [layout.entry, '--engine', 'strata', '--config', config.path, '--port', String(facts.port)];
1302
+ if (facts.host && facts.host !== '127.0.0.1')
1303
+ args.push('--host', facts.host);
1304
+ // ONE leg. The vision encoder is `server.py`'s child (its config's `vision`
1305
+ // block), not the gateway's: `strata-vision.exe` reads `ENC` lines from
1306
+ // stdin, so a second process listening on a port would never be reachable.
1307
+ const leg = { cmd: layout.python, args, cwd: layout.workspace, key: facts.runId, aux: false, port: facts.port, name: 'engine' };
1308
+ return [leg];
1309
+ },
1310
+ /**
1311
+ * Prepare the launch input this family needs, with the workspace's OWN tooling
1312
+ * (ADR-0045 §9). WHICH tool is the family's layout, not a guess:
1313
+ *
1314
+ * - `gguf-pack` → `iq_pack.py --gguf <shard 1> --out packs/<model>` plus the
1315
+ * argv the catalog declares for this family (`--compat-bf16` for the Unsloth
1316
+ * and Gyro sets); the engine then loads `--pack`.
1317
+ * - `gguf-inplace` → `strata_tokenizer.py --gguf <shard 1> --out packs/<model>`,
1318
+ * exactly what the vendor's own-path install runs: the weights are read from
1319
+ * the GGUF, and only the tokenizer is prepared.
1320
+ * - `ready-pack` → nothing to pack; only the draft layer below applies.
1321
+ *
1322
+ * The MTP draft layer follows EVERY family in the vendor's own setup (its
1323
+ * ~5 GB of tensors from the original checkpoint → `mtp_pack.py` → `mtp_rt.py`),
1324
+ * so it is a second, INDEPENDENT chain of legs rather than part of the pack
1325
+ * branch: a ready-made pack has no pack step but still benefits from it, and a
1326
+ * pack that is already on disk still needs it. `skipIf` is the vendor's own
1327
+ * rule ("nothing already prepared is done again") applied per step, so a
1328
+ * finished layer costs no process and a restart resumes mid-chain.
1329
+ *
1330
+ * No leg has a port: a build serves nothing.
1331
+ */
1332
+ build: async (input) => {
1333
+ const parts = resolveWorkspaceParts();
1334
+ if (!parts.ok) {
1335
+ return {
1336
+ error: `cannot prepare this model — the Strata runtime is incomplete: ${parts.missing.join(', ')}.`,
1337
+ };
1338
+ }
1339
+ const { workspace, python, dataRoot } = parts.parts;
1340
+ const family = catalogFamilyFor(input.modelPath);
1341
+ const profile = asProfile(input.profile) ?? {};
1342
+ const legs = [];
1343
+ // ---- 1. the weights' launch input (skip for a ready-made pack)
1344
+ if (family?.layout.kind !== 'ready-pack') {
1345
+ const out = strataPackTarget(dataRoot, input.modelPath);
1346
+ const inplace = family?.layout.kind === 'gguf-inplace';
1347
+ const tool = inplace ? 'strata_tokenizer.py' : 'iq_pack.py';
1348
+ const toolPath = path.join(workspace, 'tools', tool);
1349
+ if (!isFile(toolPath)) {
1350
+ return { error: `cannot prepare this model — the tool is missing: ${toolPath}` };
1351
+ }
1352
+ // Already prepared is not re-prepared: the model's layout resolving at
1353
+ // all means its weights input exists (whatever directory the matcher
1354
+ // chose), an in-place family counts as done when its four tokenizer
1355
+ // files are all there (the vendor's own rule), and a packed one when the
1356
+ // packer's completion marker is. This is what lets a build that only
1357
+ // wants the draft layer skip a 60 GB repack.
1358
+ const existing = resolveStrataLayout({
1359
+ modelPath: input.modelPath,
1360
+ profile: input.profile,
1361
+ ...(input.binary ? { binary: input.binary } : {}),
1362
+ });
1363
+ const prepared = () => existing.ok ||
1364
+ (inplace
1365
+ ? ['vocab.json', 'merges.txt', 'token_type.json', 'tokenizer.json'].every((name) => isFile(path.join(out, 'tokenizer', name)))
1366
+ : looksLikePack(out));
1367
+ legs.push({
1368
+ cmd: python,
1369
+ args: [toolPath, '--gguf', input.modelPath, '--out', out, ...(inplace ? [] : family?.layout.kind === 'gguf-pack' ? (family.layout.packArgs ?? []) : [])],
1370
+ cwd: workspace,
1371
+ key: `${input.jobId}:${inplace ? 'tokenizer' : 'pack'}`,
1372
+ aux: false,
1373
+ name: inplace ? 'tokenizer' : 'pack',
1374
+ skipIf: prepared,
1375
+ });
1376
+ }
1377
+ // ---- 2. the MTP draft layer (optional: never blocks step 1)
1378
+ legs.push(...draftLayerLegs(input.jobId, workspace, python, dataRoot, draftingOf(profile), family?.layout.kind ?? 'gguf-pack'));
1379
+ // Nothing missing means nothing to do — and saying so is better than a job
1380
+ // that finishes instantly with no explanation.
1381
+ if (legs.every((leg) => leg.skipIf?.() === true)) {
1382
+ return { error: 'nothing to prepare: this model is already complete for this engine', code: 'nothing-to-do' };
1383
+ }
1384
+ return legs;
1385
+ },
1386
+ profile: PROFILE,
1387
+ setup: SETUP,
1388
+ catalog: strataCatalog,
1389
+ // The DFlash2 drafter is this engine's optional artefact (fetched through the
1390
+ // control bundle); the console renders that row from this declaration.
1391
+ drafter: true,
1392
+ };