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,1215 @@
1
+ /**
2
+ * Local GGUF model registry + downloader (Local Models marketplace).
3
+ *
4
+ * A "model" here is one downloaded file from a HuggingFace repo — the unit
5
+ * llama-server actually loads. Files live at
6
+ * `<ocrHome>/models/<owner>/<name>/<filename>.gguf` and the registry at
7
+ * `<ocrHome>/models/installed.json` mirrors the engine registry's shape.
8
+ *
9
+ * Downloads reuse the engine asset pipeline (`proxy/asset-download`): a
10
+ * `.part` file plus a validator sidecar survive a cancel or a crash, the
11
+ * next attempt resumes with `Range`/`If-Range`, and an LFS sha256 (the Hub
12
+ * publishes it in the tree API) is verified before a record is written —
13
+ * resume is never a way to serve spliced weights.
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { cleanupAssetPart, downloadAssetToFile, withAssetLock, } from '../egress-proxy/asset-download.js';
18
+ import { hfFileUrl, isValidRepoId, parseGgufQuant, parseParamsB, SHARD_RE } from './hf.js';
19
+ import { engineById, engineSupportFor } from './engines.js';
20
+ import { readGgufMeta } from './gguf.js';
21
+ import { llamaDraftChoiceUsable, matchDraftsOnDisk, strataDraftingUsable } from './draft-match.js';
22
+ import { resolveStrataLayout, strataDraftLayerPresent } from './strata.js';
23
+ import { resolveHfToken, resolveModelsDir } from './settings.js';
24
+ import { localTransport } from './transport.js';
25
+ /** Model weights run far past engine archives; 512GB is a sanity ceiling. */
26
+ const MAX_MODEL_BYTES = 512 * 1024 * 1024 * 1024;
27
+ export function modelsRoot() {
28
+ return resolveModelsDir().dir;
29
+ }
30
+ function modelsStateFile() {
31
+ return path.join(modelsRoot(), 'installed.json');
32
+ }
33
+ export function readInstalledModels() {
34
+ try {
35
+ const parsed = JSON.parse(fs.readFileSync(modelsStateFile(), 'utf8'));
36
+ return parsed && typeof parsed === 'object' ? parsed : {};
37
+ }
38
+ catch {
39
+ return {};
40
+ }
41
+ }
42
+ function writeInstalledModels(state) {
43
+ fs.mkdirSync(modelsRoot(), { recursive: true });
44
+ fs.writeFileSync(modelsStateFile(), `${JSON.stringify(state, null, 2)}\n`);
45
+ }
46
+ /**
47
+ * Every stored profile for one model, legacy fields folded in. The single
48
+ * read path: nothing outside this module should touch `record.strata`.
49
+ */
50
+ export function profilesOf(row) {
51
+ const out = {};
52
+ if (row.profiles && typeof row.profiles === 'object')
53
+ Object.assign(out, row.profiles);
54
+ if (row.strata && out.strata === undefined)
55
+ out.strata = row.strata;
56
+ return out;
57
+ }
58
+ /** The stored profile of one engine, or undefined when unset. */
59
+ export function profileFor(row, engineId) {
60
+ return profilesOf(row)[engineId];
61
+ }
62
+ /**
63
+ * Current header-scan generation; see `InstalledModelMeta.scanVersion`.
64
+ *
65
+ * 3: Strata's verdict stopped depending on a stored profile and started
66
+ * depending on whether its workspace resolves on disk (ADR-0045 §8). A cached
67
+ * row from generation 2 answers a question this build no longer asks, so it is
68
+ * re-derived once rather than leaving the console on a stale "needs setup".
69
+ *
70
+ * 4: verdicts gained `buildable` (ADR-0045 §9 — the missing pack is one the
71
+ * engine can build itself). A generation-3 row carries a pack refusal WITHOUT
72
+ * the flag, so the console would never offer the build action until the row
73
+ * was re-derived for another reason.
74
+ *
75
+ * 5: Strata's layout moved under the gateway home (ADR-0045 §13). A generation-4
76
+ * row can say `serves: true` because the model file sat inside a developer
77
+ * checkout the gateway no longer consults, and it never carries `buildable`
78
+ * for a model whose only gap is the pack under `<ocrHome>/strata/data`.
79
+ *
80
+ * Generation 5 is not a disk clock. A row scanned before the control bundle
81
+ * landed still says `serve/server.py` is missing after the file exists.
82
+ * `strataDiskStale` re-derives that row on the next list; an engine install
83
+ * rescans the registry outright (ADR-0045 §13).
84
+ *
85
+ * 6: a ready-made pack (NVFP4) became servable — its anchor is the DENSE half,
86
+ * so the generation-5 MoE-header gate refuses it — and the projector scan
87
+ * widened to the catalog download's `<owner>/<repo>` folders. A row cached
88
+ * under generation 5 carries a refusal (or a text-only launch) this build no
89
+ * longer gives.
90
+ *
91
+ * 7: a runnable model reports `preparable` (the draft layer it can still
92
+ * build). Generation 6 was written by builds that predate the flag, so their
93
+ * rows would never offer that build until something else re-derived them.
94
+ */
95
+ export const META_SCAN_VERSION = 7;
96
+ /**
97
+ * A family match that does not serve is a function of the runtime on disk,
98
+ * not of the GGUF header. Re-resolve it. A dense refusal is not: layout
99
+ * resolution would disagree with the expert check and rescan forever.
100
+ *
101
+ * A SERVING row is normally final, with one exception: `preparable` is a disk
102
+ * fact too (the draft layer either exists or it does not), and the layer can
103
+ * appear without the gateway (the vendor's own installer, a copied folder).
104
+ * Left alone, the row would keep offering a Pack that answers `nothing-to-do`
105
+ * forever — the dead button this module exists to avoid.
106
+ */
107
+ function strataDiskStale(row) {
108
+ const verdict = row.meta?.engines?.strata;
109
+ if (!verdict || verdict.family !== true)
110
+ return false;
111
+ if (verdict.serves === true) {
112
+ if (verdict.preparable !== true)
113
+ return false;
114
+ // One cheap probe (a few stats), never a full lookahead: this runs on every
115
+ // list call for every runnable Strata model.
116
+ return strataDraftLayerPresent(profileFor(row, 'strata'));
117
+ }
118
+ const again = resolveStrataLayout({ modelPath: row.filePath, profile: profileFor(row, 'strata'), ...(row.meta?.arch ? { arch: row.meta.arch } : {}) });
119
+ if (again.ok)
120
+ return true;
121
+ if (Boolean(again.buildable) !== Boolean(verdict.buildable))
122
+ return true;
123
+ return again.reason !== verdict.reason;
124
+ }
125
+ /** Read + cache the GGUF header facts for one record (badges, planner). */
126
+ function metaFor(row) {
127
+ const parsed = readGgufMeta(row.filePath);
128
+ const support = engineSupportFor(row.filePath, parsed.ok ? parsed : null, profilesOf(row));
129
+ return {
130
+ at: Date.now(),
131
+ scanVersion: META_SCAN_VERSION,
132
+ ...(parsed.arch ? { arch: parsed.arch } : {}),
133
+ ...(parsed.name ? { name: parsed.name } : {}),
134
+ ...(parsed.layers != null ? { layers: parsed.layers } : {}),
135
+ ...(parsed.maxCtx != null ? { maxCtx: parsed.maxCtx } : {}),
136
+ ...(parsed.experts != null ? { experts: parsed.experts } : {}),
137
+ ...(parsed.expertsUsed != null ? { expertsUsed: parsed.expertsUsed } : {}),
138
+ ...(parsed.heads != null ? { heads: parsed.heads } : {}),
139
+ ...(parsed.kvHeads != null ? { kvHeads: parsed.kvHeads } : {}),
140
+ ...(parsed.headDim != null ? { headDim: parsed.headDim } : {}),
141
+ ...(parsed.embedding != null ? { embedding: parsed.embedding } : {}),
142
+ runnable: support.runnable,
143
+ moe: support.moe,
144
+ engines: support.engines,
145
+ // `strataFamily` is deliberately not re-derived: every family claim now
146
+ // lives in the per-engine verdict, so no shared field names an engine.
147
+ };
148
+ }
149
+ /** Drop registry rows whose file vanished (manual cleanup keeps the list honest). */
150
+ export function listInstalledModels() {
151
+ const state = readInstalledModels();
152
+ let dirty = false;
153
+ const rows = Object.values(state).filter((row) => {
154
+ try {
155
+ return fs.statSync(row.filePath).isFile();
156
+ }
157
+ catch {
158
+ delete state[row.id];
159
+ dirty = true;
160
+ return false;
161
+ }
162
+ });
163
+ // Lazy header scan: a record without meta gets one, persisted back so the
164
+ // next list call is a pure registry read. Downloads are sha-verified, so a
165
+ // cached header cannot go stale under the same path for downloaded rows.
166
+ // `engines` is the ADR-0045 verdict block and `scanVersion` its generation —
167
+ // a row cached before either existed, or by a gate that has since widened
168
+ // (ADR-0045 §6), is re-derived once, so an upgrade never leaves the console
169
+ // showing a verdict the current code would no longer give.
170
+ for (const row of rows) {
171
+ const stale = !row.meta || !row.meta.engines || row.meta.scanVersion !== META_SCAN_VERSION || strataDiskStale(row);
172
+ if (stale && row.filePath.toLowerCase().endsWith('.gguf')) {
173
+ row.meta = metaFor(row);
174
+ state[row.id] = row;
175
+ dirty = true;
176
+ }
177
+ }
178
+ if (dirty) {
179
+ try {
180
+ writeInstalledModels(state);
181
+ }
182
+ catch {
183
+ // A failed write only re-runs the scan next time.
184
+ }
185
+ }
186
+ // Newest first: the displayed date IS the sort key, so the card order and
187
+ // the tertiary meta line never disagree (a download sorts by fetch time, an
188
+ // import by the file's own mtime). Registry id is the stable tiebreak.
189
+ return rows.sort((a, b) => b.downloadedAt - a.downloadedAt || a.id.localeCompare(b.id));
190
+ }
191
+ /** Storage used by the models directory, best effort (the card footer). */
192
+ export function modelsDiskUsage() {
193
+ let total = 0;
194
+ const walk = (dir, depth) => {
195
+ if (depth > 6)
196
+ return;
197
+ let entries;
198
+ try {
199
+ entries = fs.readdirSync(dir, { withFileTypes: true });
200
+ }
201
+ catch {
202
+ return;
203
+ }
204
+ for (const entry of entries) {
205
+ const abs = path.join(dir, entry.name);
206
+ if (entry.isDirectory())
207
+ walk(abs, depth + 1);
208
+ else if (entry.isFile() && !entry.name.endsWith('.json')) {
209
+ try {
210
+ total += fs.statSync(abs).size;
211
+ }
212
+ catch {
213
+ // A file that vanished mid-walk contributes nothing.
214
+ }
215
+ }
216
+ }
217
+ };
218
+ walk(modelsRoot(), 0);
219
+ return total;
220
+ }
221
+ /** One filename segment relative to the repo root — no traversal, no absolute. */
222
+ function validRepoFile(filename) {
223
+ const normalized = filename.replace(/\\/g, '/');
224
+ return !!normalized && !normalized.startsWith('/') && !normalized.split('/').some((seg) => seg === '..' || seg === '');
225
+ }
226
+ function contentIndexFile() {
227
+ return path.join(modelsRoot(), 'catalog-files.json');
228
+ }
229
+ function readContentIndex() {
230
+ try {
231
+ const parsed = JSON.parse(fs.readFileSync(contentIndexFile(), 'utf8'));
232
+ return parsed && typeof parsed === 'object' ? parsed : {};
233
+ }
234
+ catch {
235
+ return {};
236
+ }
237
+ }
238
+ /** Record one verified file, keyed by its digest. Best effort: a failed write
239
+ * only costs a future re-download. Written to a temp file and renamed, so a
240
+ * crash mid-write cannot leave a truncated index (a torn JSON would silently
241
+ * switch deduplication off until the next install rewrote it). */
242
+ function rememberContent(sha256, filePath, size) {
243
+ const target = contentIndexFile();
244
+ try {
245
+ const index = readContentIndex();
246
+ index[sha256] = { rel: path.relative(modelsRoot(), filePath), size };
247
+ fs.mkdirSync(path.dirname(target), { recursive: true });
248
+ const temp = `${target}.${process.pid}.tmp`;
249
+ fs.writeFileSync(temp, `${JSON.stringify(index, null, 2)}\n`);
250
+ fs.renameSync(temp, target);
251
+ }
252
+ catch {
253
+ // The download itself succeeded; the index is an optimisation.
254
+ try {
255
+ fs.rmSync(`${target}.${process.pid}.tmp`, { force: true });
256
+ }
257
+ catch {
258
+ // an orphan temp file is harmless
259
+ }
260
+ }
261
+ }
262
+ /** The on-disk copy of a digest, when it is still there, the right size, AND
263
+ * still carries that digest's verification mark.
264
+ *
265
+ * The mark is what makes this safe to hard-link into another model: the index
266
+ * is a convenience record written after a verified download, while the `.sha256`
267
+ * sidecar is the per-file claim that THIS path was verified. Requiring it means
268
+ * a file the gateway never verified (copied in by hand, restored from a backup
269
+ * without its sidecar, written by another tool) is never propagated as
270
+ * "verified bytes". Neither record is a live hash — re-reading a 51 GB file on
271
+ * every install would defeat the dedupe — so this detects an unproven file, not
272
+ * a same-length rewrite that keeps its mark. */
273
+ function contentHit(sha256, size) {
274
+ const entry = readContentIndex()[sha256];
275
+ if (!entry)
276
+ return undefined;
277
+ if (size != null && entry.size !== size)
278
+ return undefined;
279
+ const abs = path.join(modelsRoot(), entry.rel);
280
+ if (!verifiedAs(abs, sha256, size ?? entry.size))
281
+ return undefined;
282
+ return abs;
283
+ }
284
+ /** The files one install wrote, as paths relative to the models root, always with
285
+ * `/` separators (a record is portable text; Windows separators would differ
286
+ * from the `repo/file` spelling everywhere else). A path outside the root is
287
+ * dropped: removal only ever deletes inside it, and a record must not carry an
288
+ * entry the delete path would refuse anyway. */
289
+ function repoRelativeFiles(done) {
290
+ const root = path.resolve(modelsRoot());
291
+ const out = [];
292
+ for (const entry of done) {
293
+ const abs = path.resolve(entry.filePath);
294
+ if (!abs.startsWith(root + path.sep))
295
+ continue;
296
+ const rel = path.relative(root, abs).split(path.sep).join('/');
297
+ if (rel && !out.includes(rel))
298
+ out.push(rel);
299
+ }
300
+ return out;
301
+ }
302
+ /**
303
+ * Download one repo file into the models tree WITHOUT registering it.
304
+ * Concurrent calls for the SAME destination serialise on the final path
305
+ * (two tabs must not interleave `.part` writes); different files download
306
+ * side by side. Split-weight shards land as plain files here — the caller
307
+ * registers once it has the whole group (or, for one file, right away).
308
+ */
309
+ /** Sidecar a verified file carries: the digest that was actually checked against
310
+ * its bytes. It is what lets a re-run skip a multi-GB file WITHOUT trusting its
311
+ * size alone — and what stops a corrupted file from being hard-linked into
312
+ * another model as "verified bytes" (the dedupe chain's whole premise). Written
313
+ * only after `downloadAssetToFile` verified the digest. */
314
+ function verifiedMarkPath(filePath) {
315
+ return `${filePath}.sha256`;
316
+ }
317
+ function writeVerifiedMark(filePath, sha256) {
318
+ try {
319
+ fs.writeFileSync(verifiedMarkPath(filePath), `${sha256}\n`);
320
+ }
321
+ catch {
322
+ // A missing mark only costs one re-download later.
323
+ }
324
+ }
325
+ /** True when this exact file was verified against `sha256` (a mark, no rehash). */
326
+ function verifiedAs(filePath, sha256, size) {
327
+ try {
328
+ if (size != null && fs.statSync(filePath).size !== size)
329
+ return false;
330
+ const mark = fs.readFileSync(verifiedMarkPath(filePath), 'utf8').trim().toLowerCase();
331
+ return mark === sha256.toLowerCase();
332
+ }
333
+ catch {
334
+ return false;
335
+ }
336
+ }
337
+ async function downloadRepoFile(repo, filename, opts) {
338
+ const emit = (event) => opts.onEvent?.(event);
339
+ const [owner, name] = repo.split('/');
340
+ const finalPath = path.join(modelsRoot(), owner, name, filename);
341
+ const partPath = `${finalPath}.part`;
342
+ return withAssetLock(finalPath, async () => {
343
+ // 1. Already here and PROVEN: a file of the pinned size whose verification
344
+ // mark carries the pinned digest needs no transfer. Size alone is not
345
+ // enough — a truncated or foreign file of the same byte count would be
346
+ // accepted here and then hard-linked into other models as "verified".
347
+ // Without a digest (a Hub download re-run) the old size check still
348
+ // applies, because there is nothing better to compare against.
349
+ if (opts.size != null) {
350
+ try {
351
+ if (fs.statSync(finalPath).isFile() && fs.statSync(finalPath).size === opts.size) {
352
+ const proven = opts.sha256 ? verifiedAs(finalPath, opts.sha256, opts.size) : false;
353
+ if (proven) {
354
+ rememberContent(opts.sha256, finalPath, opts.size);
355
+ return { ok: true, filePath: finalPath, size: opts.size, resumedFrom: 0 };
356
+ }
357
+ if (!opts.sha256) {
358
+ return { ok: true, filePath: finalPath, size: opts.size, resumedFrom: 0 };
359
+ }
360
+ // Size matches but the mark does not: re-download over it (the
361
+ // downloader verifies the digest and replaces the file).
362
+ }
363
+ }
364
+ catch {
365
+ // absent — download it
366
+ }
367
+ }
368
+ // 2. Another model in this tree already holds these exact bytes (the
369
+ // engine catalog pins one file into several sizes): LINK it. A hard
370
+ // link costs no bytes and keeps both models independently removable,
371
+ // because the inode survives either unlink.
372
+ if (opts.sha256) {
373
+ const shared = contentHit(opts.sha256, opts.size);
374
+ if (shared && path.resolve(shared) !== path.resolve(finalPath)) {
375
+ emit({ type: 'stage', stage: 'finalize' });
376
+ try {
377
+ fs.mkdirSync(path.dirname(finalPath), { recursive: true });
378
+ fs.linkSync(shared, finalPath);
379
+ const size = fs.statSync(finalPath).size;
380
+ // The source was verified, and the inode is the same bytes: the mark
381
+ // is carried over so this copy is provably verified too.
382
+ writeVerifiedMark(finalPath, opts.sha256);
383
+ rememberContent(opts.sha256, finalPath, size);
384
+ return { ok: true, filePath: finalPath, size, resumedFrom: 0 };
385
+ }
386
+ catch {
387
+ // A different volume, or no hard links on this filesystem: fall
388
+ // through and download normally. Correctness never depends on it.
389
+ }
390
+ }
391
+ }
392
+ emit({ type: 'stage', stage: 'download', asset: filename });
393
+ let result;
394
+ try {
395
+ result = await downloadAssetToFile({
396
+ url: hfFileUrl(repo, filename, opts.revision),
397
+ partPath,
398
+ // The market's leg, not a bare `fetch`: a download that dialed direct
399
+ // while the list went through the proxy would be the same leak with a
400
+ // nicer UI. Resolved per attempt, so a console flip applies to the
401
+ // next file without a restart.
402
+ fetchImpl: localTransport(),
403
+ maxBytes: MAX_MODEL_BYTES,
404
+ headers: {
405
+ 'User-Agent': 'omnicell-router',
406
+ // The console-configured token (settings chain) is what unlocks a
407
+ // gated repo — the env var alone used to leave page-set tokens dead.
408
+ ...(resolveHfToken().token ? { Authorization: `Bearer ${resolveHfToken().token}` } : {}),
409
+ },
410
+ ...(opts.sha256 ? { sha256: opts.sha256 } : {}),
411
+ ...(opts.signal ? { signal: opts.signal } : {}),
412
+ onProgress: (downloaded, total) => {
413
+ emit({ type: 'progress', asset: filename, downloaded, total });
414
+ },
415
+ });
416
+ }
417
+ catch (err) {
418
+ const message = err instanceof Error ? err.message : 'download failed';
419
+ return { ok: false, code: 'download-failed', error: message };
420
+ }
421
+ if (!result.ok)
422
+ return { ok: false, code: result.code, error: result.error };
423
+ emit({ type: 'stage', stage: 'finalize' });
424
+ try {
425
+ // A catalog file may live in a per-model subfolder of the repo.
426
+ fs.mkdirSync(path.dirname(finalPath), { recursive: true });
427
+ // Rename, don't copy: a finished 20GB part must not be written twice.
428
+ fs.renameSync(partPath, finalPath);
429
+ cleanupAssetPart(partPath);
430
+ }
431
+ catch (err) {
432
+ const message = err instanceof Error ? err.message : 'move failed';
433
+ return { ok: false, code: 'install-failed', error: `could not move the download into place (${message})` };
434
+ }
435
+ // Verified bytes only: `downloadAssetToFile` checked the digest above.
436
+ if (opts.sha256) {
437
+ writeVerifiedMark(finalPath, opts.sha256);
438
+ rememberContent(opts.sha256, finalPath, result.size);
439
+ }
440
+ return { ok: true, filePath: finalPath, size: result.size, resumedFrom: result.resumedFrom };
441
+ });
442
+ }
443
+ /**
444
+ * Drop a stored draft choice only when it is PROVABLY unusable (see the two
445
+ * predicates in `draft-match.ts`). What is on disk decides what the picker
446
+ * offers, never what the profile keeps: a draft GGUF outside the models root and
447
+ * a drafting mode whose layer has not been fetched yet are both legitimate, and
448
+ * a re-scan must not erase either (ADR-0045: Detect "does not remove a choice").
449
+ */
450
+ function pruneDraftChoice(row) {
451
+ const llama = row.profiles?.llamacpp;
452
+ if (llama && typeof llama === 'object' && !Array.isArray(llama)) {
453
+ const profile = llama;
454
+ if (!llamaDraftChoiceUsable(profile.specType, profile.draftModel)) {
455
+ delete profile.specType;
456
+ }
457
+ }
458
+ const strataProfile = (row.profiles?.strata ?? row.strata);
459
+ if (strataProfile && !strataDraftingUsable(strataProfile.drafting)) {
460
+ delete strataProfile.drafting;
461
+ }
462
+ }
463
+ function fillLlamaDraft(row, match) {
464
+ const kinds = Object.keys(match.files);
465
+ if (kinds.length !== 1)
466
+ return;
467
+ const profiles = profilesOf(row);
468
+ const llama = (profiles.llamacpp && typeof profiles.llamacpp === 'object' && !Array.isArray(profiles.llamacpp))
469
+ ? { ...profiles.llamacpp }
470
+ : {};
471
+ if (llama.specType != null)
472
+ return;
473
+ llama.specType = kinds[0];
474
+ llama.draftModel = match.files[kinds[0]];
475
+ profiles.llamacpp = llama;
476
+ row.profiles = profiles;
477
+ delete row.strata;
478
+ }
479
+ /** Re-pair every installed model with the drafters currently on disk. */
480
+ export function refreshDraftMatches() {
481
+ const state = readInstalledModels();
482
+ const rows = Object.values(state);
483
+ const metas = new Map(rows.map((row) => [row.filePath, readGgufMeta(row.filePath)]));
484
+ for (const row of rows) {
485
+ const first = row.draftMatch == null;
486
+ const match = matchDraftsOnDisk({
487
+ filename: row.filename,
488
+ meta: metas.get(row.filePath) ?? { ok: false },
489
+ others: rows.filter((other) => other.id !== row.id).map((other) => ({
490
+ filePath: other.filePath,
491
+ filename: other.filename,
492
+ meta: metas.get(other.filePath) ?? { ok: false },
493
+ })),
494
+ });
495
+ if (first)
496
+ fillLlamaDraft(row, match);
497
+ pruneDraftChoice(row);
498
+ row.draftMatch = match;
499
+ }
500
+ writeInstalledModels(state);
501
+ return Object.values(state);
502
+ }
503
+ /** Write one registry row; the files on disk are the caller's responsibility. */
504
+ function registerInstalled(model) {
505
+ const installed = { ...model, downloadedAt: Date.now() };
506
+ try {
507
+ const state = readInstalledModels();
508
+ state[installed.id] = installed;
509
+ writeInstalledModels(state);
510
+ try {
511
+ const refreshed = refreshDraftMatches().find((row) => row.id === installed.id);
512
+ if (refreshed)
513
+ Object.assign(installed, refreshed);
514
+ }
515
+ catch {
516
+ // The row is already stored. A pairing failure leaves it unmatched.
517
+ }
518
+ }
519
+ catch (err) {
520
+ const message = err instanceof Error ? err.message : 'state write failed';
521
+ return { ok: false, code: 'install-failed', error: `model downloaded but the record write failed (${message})` };
522
+ }
523
+ return { ok: true, installed, resumedFrom: installed.resumedFrom ?? 0 };
524
+ }
525
+ /**
526
+ * Download one repo file into the models tree and register it. Concurrent
527
+ * calls for the SAME destination serialise on the final path (two tabs must
528
+ * not interleave `.part` writes); different files download side by side.
529
+ */
530
+ export async function downloadHfModel(opts) {
531
+ if (!isValidRepoId(opts.repo))
532
+ return { ok: false, code: 'invalid-model', error: `invalid model id '${opts.repo}'` };
533
+ if (!validRepoFile(opts.filename))
534
+ return { ok: false, code: 'invalid-file', error: `invalid file name '${opts.filename}'` };
535
+ const filename = opts.filename.replace(/\\/g, '/');
536
+ const result = await downloadRepoFile(opts.repo, filename, {
537
+ ...(opts.revision ? { revision: opts.revision } : {}),
538
+ ...(opts.size != null ? { size: opts.size } : {}),
539
+ ...(opts.sha256 ? { sha256: opts.sha256 } : {}),
540
+ ...(opts.signal ? { signal: opts.signal } : {}),
541
+ ...(opts.onEvent ? { onEvent: opts.onEvent } : {}),
542
+ });
543
+ if (!result.ok)
544
+ return result;
545
+ return registerInstalled({
546
+ id: `${opts.repo}/${filename}`,
547
+ repo: opts.repo,
548
+ filename,
549
+ filePath: result.filePath,
550
+ size: result.size,
551
+ ...(parseGgufQuant(filename) ? { quant: parseGgufQuant(filename) } : {}),
552
+ ...(parseParamsB(filename) ?? parseParamsB(opts.repo)
553
+ ? { paramsB: parseParamsB(filename) ?? parseParamsB(opts.repo) }
554
+ : {}),
555
+ ...(result.resumedFrom > 0 ? { resumedFrom: result.resumedFrom } : {}),
556
+ });
557
+ }
558
+ /**
559
+ * Download a split-weight group (…-00001-of-00002.gguf …) and register ONE
560
+ * model anchored at shard 1 — llama-server handed that path discovers the
561
+ * siblings itself. Shards fetch sequentially (one `.part` stream at a time);
562
+ * a mid-group failure keeps every staged part on disk, so the next attempt
563
+ * resumes each shard where it stopped. Progress reports cumulative bytes
564
+ * against the whole group.
565
+ */
566
+ export async function downloadHfModelGroup(opts) {
567
+ if (!isValidRepoId(opts.repo))
568
+ return { ok: false, code: 'invalid-model', error: `invalid model id '${opts.repo}'` };
569
+ const parts = opts.parts.filter((part) => validRepoFile(part.path));
570
+ if (parts.length < 2)
571
+ return { ok: false, code: 'invalid-file', error: 'a split group needs at least two shard parts' };
572
+ const firstMatch = SHARD_RE.exec(path.basename(parts[0].path));
573
+ if (!firstMatch || Number(firstMatch[2]) !== 1) {
574
+ return { ok: false, code: 'invalid-file', error: `group must be ordered with shard 1 first ('${parts[0].path}')` };
575
+ }
576
+ const baseName = firstMatch[1];
577
+ // The group key: same base name and shard count on every part.
578
+ for (const part of parts) {
579
+ const match = SHARD_RE.exec(path.basename(part.path));
580
+ if (!match || match[1].toLowerCase() !== baseName.toLowerCase() || Number(match[3]) !== parts.length) {
581
+ return { ok: false, code: 'invalid-file', error: `inconsistent shard group ('${part.path}')` };
582
+ }
583
+ }
584
+ const emit = (event) => opts.onEvent?.(event);
585
+ const groupTotal = parts.reduce((sum, part) => sum + (part.size ?? 0), 0);
586
+ const doneFiles = [];
587
+ for (let index = 0; index < parts.length; index += 1) {
588
+ const part = parts[index];
589
+ const completedBefore = doneFiles.reduce((sum, done) => sum + done.size, 0);
590
+ const result = await downloadRepoFile(opts.repo, part.path.replace(/\\/g, '/'), {
591
+ ...(opts.revision ? { revision: opts.revision } : {}),
592
+ ...(part.size != null ? { size: part.size } : {}),
593
+ ...(part.sha256 ? { sha256: part.sha256 } : {}),
594
+ ...(opts.signal ? { signal: opts.signal } : {}),
595
+ onEvent: (event) => {
596
+ // Rewrite per-part progress into group-cumulative bytes so the bar
597
+ // climbs monotonically to the real total instead of resetting per shard.
598
+ if (event.type === 'progress') {
599
+ emit({
600
+ type: 'progress',
601
+ asset: part.path,
602
+ downloaded: completedBefore + event.downloaded,
603
+ total: groupTotal > 0 ? groupTotal : event.total,
604
+ });
605
+ }
606
+ else {
607
+ emit(event);
608
+ }
609
+ },
610
+ });
611
+ if (!result.ok) {
612
+ return { ok: false, code: result.code, error: `${part.path}: ${result.error}` };
613
+ }
614
+ doneFiles.push(result);
615
+ }
616
+ const primary = parts[0].path.replace(/\\/g, '/');
617
+ const size = doneFiles.reduce((sum, done) => sum + done.size, 0);
618
+ const resumedFrom = doneFiles.reduce((sum, done) => sum + done.resumedFrom, 0);
619
+ return registerInstalled({
620
+ id: `${opts.repo}/${primary}`,
621
+ repo: opts.repo,
622
+ filename: primary,
623
+ filePath: doneFiles[0].filePath,
624
+ // Every shard: removing a split model must reclaim all of it, not just the
625
+ // anchor llama-server is handed.
626
+ files: repoRelativeFiles(doneFiles),
627
+ size,
628
+ ...(parseGgufQuant(baseName) ? { quant: parseGgufQuant(baseName) } : {}),
629
+ ...(parseParamsB(baseName) ?? parseParamsB(opts.repo)
630
+ ? { paramsB: parseParamsB(baseName) ?? parseParamsB(opts.repo) }
631
+ : {}),
632
+ ...(resumedFrom > 0 ? { resumedFrom } : {}),
633
+ });
634
+ }
635
+ /**
636
+ * Bytes available on the volume holding `dir` (the nearest existing ancestor is
637
+ * measured for a directory that does not exist yet). `undefined` when the
638
+ * platform cannot answer — a missing reading must never refuse an install.
639
+ */
640
+ export function freeDiskBytes(dir) {
641
+ let probe = path.resolve(dir);
642
+ for (let depth = 0; depth < 8; depth += 1) {
643
+ try {
644
+ const stats = fs.statfsSync(probe);
645
+ return Number(stats.bavail) * Number(stats.bsize);
646
+ }
647
+ catch {
648
+ const parent = path.dirname(probe);
649
+ if (parent === probe)
650
+ return undefined;
651
+ probe = parent;
652
+ }
653
+ }
654
+ return undefined;
655
+ }
656
+ /** Disk headroom kept free beyond the bytes an install writes: a full volume
657
+ * makes every unrelated write (registry, logs, captures) fail too. */
658
+ export const INSTALL_DISK_MARGIN_BYTES = 1024 * 1024 * 1024;
659
+ export async function downloadCatalogModel(opts) {
660
+ if (!isValidRepoId(opts.repo))
661
+ return { ok: false, code: 'invalid-model', error: `invalid model id '${opts.repo}'` };
662
+ const files = opts.files.filter((file) => validRepoFile(file.path));
663
+ if (files.length === 0)
664
+ return { ok: false, code: 'invalid-file', error: 'the catalog entry names no downloadable file' };
665
+ // The declared anchor IS the launch argument (`--native` / `--pack`), so a
666
+ // value that is not one of the pinned files is refused — falling back to
667
+ // `files[0]` would hand the engine a different file than the catalog chose.
668
+ const declaredAnchor = opts.anchor?.replace(/\\/g, '/');
669
+ if (declaredAnchor && !files.some((file) => file.path.replace(/\\/g, '/') === declaredAnchor)) {
670
+ return { ok: false, code: 'invalid-file', error: `the declared anchor '${opts.anchor}' is not one of the pinned files` };
671
+ }
672
+ const wanted = opts.mmproj && validRepoFile(opts.mmproj.path) ? [...files, opts.mmproj] : files;
673
+ const total = wanted.reduce((sum, file) => sum + (file.size ?? 0), 0);
674
+ // A 129 GB install on a fuller disk fails at 90% and leaves the operator with
675
+ // nothing but a `.part` and a full volume. Refuse up front, naming both
676
+ // numbers — and only for bytes that still have to be written (a resumed
677
+ // install counts what is missing, not the whole set).
678
+ const stillNeeded = wanted.reduce((sum, file) => {
679
+ if (file.size == null)
680
+ return sum;
681
+ const rel = file.path.replace(/\\/g, '/');
682
+ const finalPath = path.join(modelsRoot(), ...opts.repo.split('/'), ...rel.split('/'));
683
+ try {
684
+ if (fs.statSync(finalPath).size === file.size) {
685
+ // A size match counts only when the file was PROVEN (or when the
686
+ // catalog pins no digest): a half-written file of the right length must
687
+ // not make this install look complete.
688
+ if (!file.sha256 || verifiedAs(finalPath, file.sha256, file.size))
689
+ return sum;
690
+ }
691
+ }
692
+ catch {
693
+ // not on disk
694
+ }
695
+ if (file.sha256 && contentHit(file.sha256, file.size))
696
+ return sum;
697
+ // A resumed install already holds part of the file: count only the tail, or
698
+ // a 129 GB download stopped at 90% is refused on a volume that has room for
699
+ // the last 13 GB.
700
+ let resumedBytes = 0;
701
+ try {
702
+ resumedBytes = fs.statSync(`${finalPath}.part`).size;
703
+ }
704
+ catch {
705
+ resumedBytes = 0;
706
+ }
707
+ return sum + Math.max(0, file.size - Math.max(0, resumedBytes));
708
+ }, 0);
709
+ if (stillNeeded > 0) {
710
+ const free = freeDiskBytes(modelsRoot());
711
+ const needed = stillNeeded + INSTALL_DISK_MARGIN_BYTES;
712
+ if (free != null && free < needed) {
713
+ return {
714
+ ok: false,
715
+ code: 'insufficient-disk',
716
+ error: `not enough space in ${modelsRoot()}: this install needs ${Math.ceil(needed / 1e9)} GB more (files + 1 GB headroom), ${Math.floor(free / 1e9)} GB free`,
717
+ };
718
+ }
719
+ }
720
+ const doneFiles = [];
721
+ for (let index = 0; index < wanted.length; index += 1) {
722
+ const file = wanted[index];
723
+ const completedBefore = doneFiles.reduce((sum, done) => sum + done.size, 0);
724
+ const result = await downloadRepoFile(opts.repo, file.path.replace(/\\/g, '/'), {
725
+ ...(opts.revision ? { revision: opts.revision } : {}),
726
+ ...(file.size != null ? { size: file.size } : {}),
727
+ ...(file.sha256 ? { sha256: file.sha256 } : {}),
728
+ ...(opts.signal ? { signal: opts.signal } : {}),
729
+ onEvent: (event) => {
730
+ // One bar for the whole install: per-file progress arrives reset, and a
731
+ // row that jumps backwards reads as a failed restart.
732
+ if (event.type === 'progress') {
733
+ opts.onEvent?.({
734
+ type: 'progress',
735
+ asset: file.path,
736
+ downloaded: completedBefore + event.downloaded,
737
+ total: total > 0 ? total : event.total,
738
+ });
739
+ }
740
+ else {
741
+ opts.onEvent?.(event);
742
+ }
743
+ },
744
+ });
745
+ if (!result.ok)
746
+ return { ok: false, code: result.code, error: `${file.path}: ${result.error}` };
747
+ doneFiles.push(result);
748
+ }
749
+ const primary = declaredAnchor ?? files[0].path.replace(/\\/g, '/');
750
+ const anchorIndex = Math.max(0, files.findIndex((file) => file.path.replace(/\\/g, '/') === primary));
751
+ const size = doneFiles.slice(0, files.length).reduce((sum, done) => sum + done.size, 0);
752
+ const resumedFrom = doneFiles.reduce((sum, done) => sum + done.resumedFrom, 0);
753
+ const baseName = path.basename(primary);
754
+ const quant = parseGgufQuant(baseName);
755
+ const paramsB = parseParamsB(baseName) ?? parseParamsB(opts.repo);
756
+ return registerInstalled({
757
+ id: `${opts.repo}/${primary}`,
758
+ repo: opts.repo,
759
+ filename: primary,
760
+ filePath: doneFiles[anchorIndex].filePath,
761
+ // The whole install, so removing the row reclaims every byte it wrote
762
+ // (shards, a ready pack's pack/, PLE table, embedding, projector).
763
+ files: repoRelativeFiles(doneFiles),
764
+ size,
765
+ ...(quant ? { quant } : {}),
766
+ ...(paramsB ? { paramsB } : {}),
767
+ ...(resumedFrom > 0 ? { resumedFrom } : {}),
768
+ });
769
+ }
770
+ /**
771
+ * Set (or, with `null`, clear) one model's launch profile for one engine.
772
+ *
773
+ * The shape is the ENGINE's: normalization comes from its runtime, so this
774
+ * function never learns a field name. The meta block is re-derived in the same
775
+ * write because `runnable` is a FUNCTION of the profiles (ADR-0045) — a profile
776
+ * change that did not refresh it would leave the console claiming an engine
777
+ * the runner would refuse.
778
+ */
779
+ export function setEngineProfile(id, engineId, raw) {
780
+ const engine = engineById(engineId);
781
+ if (!engine)
782
+ return { ok: false, code: 'unknown-engine', error: `unknown engine '${engineId}'` };
783
+ const spec = engine.runtime?.profile;
784
+ if (!spec)
785
+ return { ok: false, code: 'engine-has-no-profile', error: `${engine.name} takes no launch profile` };
786
+ const state = readInstalledModels();
787
+ const record = state[id];
788
+ if (!record)
789
+ return { ok: false, code: 'model-missing', error: 'model is not installed' };
790
+ const profiles = profilesOf(record);
791
+ if (raw === null) {
792
+ delete profiles[engineId];
793
+ }
794
+ else {
795
+ const normalized = spec.normalize(raw);
796
+ if (!normalized.ok)
797
+ return normalized;
798
+ profiles[engineId] = normalized.profile;
799
+ }
800
+ // Migrate forward: the legacy single-engine field is folded into `profiles`
801
+ // on the first write, so reads have exactly one path from here on.
802
+ if (profiles[engineId] === undefined)
803
+ delete profiles[engineId];
804
+ record.profiles = profiles;
805
+ delete record.strata;
806
+ record.meta = metaFor(record);
807
+ try {
808
+ writeInstalledModels(state);
809
+ }
810
+ catch (err) {
811
+ return { ok: false, code: 'write-failed', error: err instanceof Error ? err.message : 'could not persist the profile' };
812
+ }
813
+ return { ok: true, model: record };
814
+ }
815
+ /**
816
+ * The shape of an operator-chosen model name (ADR-0044 §7): a single URL- and
817
+ * config-safe token — it becomes the tail of the gateway id (`local/<name>`),
818
+ * so slashes, whitespace and shell-ish characters are out. Starts with a
819
+ * letter or digit; 1-64 chars.
820
+ */
821
+ export const MODEL_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
822
+ /**
823
+ * Set (or, with an empty string / null, clear) one model's operator name.
824
+ *
825
+ * Uniqueness is case-insensitive across the registry: the name becomes a
826
+ * gateway-visible id tail, and two ids differing only by case would route
827
+ * differently per surface. The registry KEY (`<repo>/<file>`) never changes —
828
+ * a rename moves only the `local/<…>` spelling, so the caller is responsible
829
+ * for reporting which config references the old id orphaned (the route scans
830
+ * and warns; nothing is silently rewritten).
831
+ */
832
+ export function setModelName(id, raw) {
833
+ const state = readInstalledModels();
834
+ const record = state[id];
835
+ if (!record)
836
+ return { ok: false, code: 'model-missing', error: 'model is not installed' };
837
+ const name = typeof raw === 'string' ? raw.trim() : '';
838
+ const previousName = record.name;
839
+ if (!name) {
840
+ if (record.name === undefined)
841
+ return { ok: true, model: record };
842
+ delete record.name;
843
+ }
844
+ else {
845
+ if (!MODEL_NAME_RE.test(name)) {
846
+ return {
847
+ ok: false,
848
+ code: 'invalid-name',
849
+ error: `invalid model name '${name}': use 1-64 chars of letters, digits, '.', '_' or '-', starting with a letter or digit`,
850
+ };
851
+ }
852
+ const clash = Object.values(state).find((row) => row.id !== id && row.name !== undefined && row.name.toLowerCase() === name.toLowerCase());
853
+ if (clash) {
854
+ return { ok: false, code: 'name-taken', error: `the name '${name}' already belongs to ${clash.id}` };
855
+ }
856
+ if (record.name === name)
857
+ return { ok: true, model: record };
858
+ record.name = name;
859
+ }
860
+ try {
861
+ writeInstalledModels(state);
862
+ }
863
+ catch (err) {
864
+ return { ok: false, code: 'write-failed', error: err instanceof Error ? err.message : 'could not persist the name' };
865
+ }
866
+ return { ok: true, model: record, ...(previousName !== undefined ? { previousName } : {}) };
867
+ }
868
+ /** Strata's profile writer — a named alias of the generic one (ADR-0044 §4). */
869
+ export function setStrataProfile(id, raw) {
870
+ return setEngineProfile(id, 'strata', raw);
871
+ }
872
+ /**
873
+ * Enable / disable one model (the console's status toggle). The registry key,
874
+ * profile and file on disk never change — `enabled: false` only retires the
875
+ * gateway-visible id until re-enabled, which is why a disabled model cannot be
876
+ * launched in the meantime.
877
+ */
878
+ export function setModelEnabled(id, enabled) {
879
+ const state = readInstalledModels();
880
+ const record = state[id];
881
+ if (!record)
882
+ return { ok: false, code: 'model-missing', error: 'model is not installed' };
883
+ if (enabled) {
884
+ if (record.enabled !== false)
885
+ return { ok: true, model: record };
886
+ delete record.enabled;
887
+ }
888
+ else {
889
+ record.enabled = false;
890
+ }
891
+ try {
892
+ writeInstalledModels(state);
893
+ }
894
+ catch (err) {
895
+ return { ok: false, code: 'write-failed', error: err instanceof Error ? err.message : 'could not persist the toggle' };
896
+ }
897
+ return { ok: true, model: record };
898
+ }
899
+ /**
900
+ * Re-derive and persist ONE record's meta block out of band. The verdicts are
901
+ * a function of the DISK (ADR-0045 §8), and an engine build (ADR-0045 §9) is
902
+ * exactly such a change: the pack it wrote flips `serves` without any profile
903
+ * or registry edit, and only a rescan lets the console see it.
904
+ */
905
+ export function rescanModelMeta(id) {
906
+ const state = readInstalledModels();
907
+ const record = state[id];
908
+ if (!record || !record.filePath.toLowerCase().endsWith('.gguf'))
909
+ return;
910
+ record.meta = metaFor(record);
911
+ try {
912
+ writeInstalledModels(state);
913
+ }
914
+ catch {
915
+ // A failed write only re-runs the scan on the next list.
916
+ }
917
+ }
918
+ /** Re-derive every GGUF row. An engine install changes the disk the verdicts
919
+ * read (the control bundle, the binary) without touching the model files. */
920
+ export function rescanInstalledModels() {
921
+ const state = readInstalledModels();
922
+ let dirty = false;
923
+ for (const record of Object.values(state)) {
924
+ if (!record.filePath.toLowerCase().endsWith('.gguf'))
925
+ continue;
926
+ record.meta = metaFor(record);
927
+ dirty = true;
928
+ }
929
+ if (!dirty)
930
+ return;
931
+ try {
932
+ writeInstalledModels(state);
933
+ }
934
+ catch {
935
+ // The next list retries a row whose verdict still disagrees with disk.
936
+ }
937
+ }
938
+ /** Delete one model file and its registry row. */
939
+ export function removeHfModel(id) {
940
+ const state = readInstalledModels();
941
+ const record = state[id];
942
+ if (!record)
943
+ return { ok: false, error: 'model is not installed' };
944
+ if (record.repo === IMPORT_REPO) {
945
+ // Imported rows point at the user's own files: unregister only — the
946
+ // file on disk is the user's and is never touched.
947
+ delete state[id];
948
+ try {
949
+ writeInstalledModels(state);
950
+ }
951
+ catch {
952
+ // File stays; a failed state write only leaves a stale row.
953
+ }
954
+ return { ok: true };
955
+ }
956
+ // Only ever delete inside the models root — same containment rule the
957
+ // engine uninstall applies to a corrupt record.
958
+ const root = path.resolve(modelsRoot());
959
+ // Every file the install wrote, not just the launch anchor: a split-weight
960
+ // model keeps its shards beside the anchor, and a ready-made pack keeps its
961
+ // `pack/*.bin`, PLE table and embedding under the repo's own layout. A file
962
+ // that is HARD-LINKED into a sibling model costs nothing to unlink here — the
963
+ // shared inode survives through the other model's path.
964
+ const targets = new Set([path.resolve(record.filePath)]);
965
+ for (const rel of record.files ?? []) {
966
+ targets.add(path.resolve(root, rel));
967
+ }
968
+ const inside = [...targets].filter((target) => target.startsWith(root + path.sep));
969
+ if (inside.length === 0) {
970
+ return { ok: false, error: 'model record points outside the models root; remove it manually' };
971
+ }
972
+ for (const file of inside) {
973
+ try {
974
+ fs.rmSync(file, { force: true, maxRetries: 2 });
975
+ // Its verification mark and any staged residue belong to it: left behind,
976
+ // they keep the emptied folder alive and outlive the row they describe.
977
+ for (const sidecar of [`${file}.sha256`, `${file}.part`, `${file}.part.json`]) {
978
+ fs.rmSync(sidecar, { force: true });
979
+ }
980
+ }
981
+ catch (err) {
982
+ const message = err instanceof Error ? err.message : 'delete failed';
983
+ return { ok: false, error: `could not delete the model file (${message})` };
984
+ }
985
+ }
986
+ // A ready pack leaves `pack/` and the repo folder behind as empty shells.
987
+ // Prune upward, but never past the models root and never a folder that still
988
+ // holds another model's files.
989
+ for (const file of inside) {
990
+ let dir = path.dirname(file);
991
+ while (dir.startsWith(root + path.sep)) {
992
+ try {
993
+ if (fs.readdirSync(dir).length > 0)
994
+ break;
995
+ fs.rmdirSync(dir);
996
+ }
997
+ catch {
998
+ break;
999
+ }
1000
+ dir = path.dirname(dir);
1001
+ }
1002
+ }
1003
+ delete state[id];
1004
+ try {
1005
+ writeInstalledModels(state);
1006
+ }
1007
+ catch {
1008
+ // File gone; a failed state write only leaves a stale row.
1009
+ }
1010
+ return { ok: true };
1011
+ }
1012
+ /**
1013
+ * Repo marker for rows imported from the local disk. Such rows register the
1014
+ * file where it lies (multi-GB weights are never copied) and deleting them
1015
+ * only drops the registry entry.
1016
+ */
1017
+ export const IMPORT_REPO = 'local-import';
1018
+ /**
1019
+ * Collapse split weights into one registrable unit per group: llama-server
1020
+ * is handed the FIRST shard and discovers the siblings itself, so only that
1021
+ * path may enter the registry — registering every shard would list one
1022
+ * model N times and each row would under-report the real weight size.
1023
+ * Groups are keyed by directory + base name + shard count; an incomplete
1024
+ * group is an error, never a partial registration that cannot run.
1025
+ */
1026
+ function resolveShardGroups(files, errors) {
1027
+ const singles = [];
1028
+ const groups = new Map();
1029
+ for (const file of files) {
1030
+ const match = SHARD_RE.exec(path.basename(file));
1031
+ if (!match) {
1032
+ singles.push(file);
1033
+ continue;
1034
+ }
1035
+ const key = `${path.dirname(file).toLowerCase()}::${match[1].toLowerCase()}::${match[3]}`;
1036
+ let group = groups.get(key);
1037
+ if (!group) {
1038
+ group = { total: Number(match[3]), parts: new Map() };
1039
+ groups.set(key, group);
1040
+ }
1041
+ group.parts.set(Number(match[2]), file);
1042
+ }
1043
+ const resolved = singles.map((file) => ({ primary: file, parts: [file] }));
1044
+ for (const group of groups.values()) {
1045
+ const missing = [];
1046
+ for (let part = 1; part <= group.total; part += 1) {
1047
+ if (!group.parts.has(part))
1048
+ missing.push(part);
1049
+ }
1050
+ const primary = group.parts.get(1);
1051
+ if (missing.length > 0 || !primary) {
1052
+ const name = primary ? path.basename(primary) : `…-of-${String(group.total).padStart(5, '0')}.gguf`;
1053
+ errors.push(`${name}: incomplete split model, missing shard(s) ${missing.map((n) => String(n).padStart(5, '0')).join(', ')}`);
1054
+ continue;
1055
+ }
1056
+ resolved.push({ primary, parts: Array.from({ length: group.total }, (_, i) => group.parts.get(i + 1)) });
1057
+ }
1058
+ return resolved;
1059
+ }
1060
+ /** Register one on-disk .gguf file into `state` (not persisted here). */
1061
+ function importLocalFile(absPath, state, sizeOverride) {
1062
+ try {
1063
+ const stat = fs.statSync(absPath);
1064
+ if (!stat.isFile())
1065
+ return { kind: 'error', error: `${absPath}: not a file` };
1066
+ const size = sizeOverride ?? stat.size;
1067
+ if (size > MAX_MODEL_BYTES)
1068
+ return { kind: 'error', error: `${absPath}: exceeds the 512GB ceiling` };
1069
+ if (Object.values(state).some((row) => path.resolve(row.filePath) === path.resolve(absPath))) {
1070
+ return { kind: 'duplicate' };
1071
+ }
1072
+ const filename = path.basename(absPath);
1073
+ if (!filename.toLowerCase().endsWith('.gguf'))
1074
+ return { kind: 'error', error: `${absPath}: not a .gguf file` };
1075
+ // Quant/params live in the base name; the shard suffix is noise for both.
1076
+ const baseName = filename.replace(SHARD_RE, '$1');
1077
+ // Unique key even when two folders hold the same filename.
1078
+ let id = `${IMPORT_REPO}/${filename}`;
1079
+ let n = 2;
1080
+ while (state[id])
1081
+ id = `${IMPORT_REPO}/${filename.replace(/\.gguf$/i, '')}-${n++}.gguf`;
1082
+ const model = {
1083
+ id,
1084
+ repo: IMPORT_REPO,
1085
+ filename,
1086
+ filePath: path.resolve(absPath),
1087
+ size,
1088
+ ...(parseGgufQuant(baseName) ? { quant: parseGgufQuant(baseName) } : {}),
1089
+ ...(parseParamsB(baseName) ? { paramsB: parseParamsB(baseName) } : {}),
1090
+ // For an imported file the honest timestamp is the file's own mtime —
1091
+ // the import moment says nothing about when the weights were produced,
1092
+ // while a downloaded row records its fetch time (registerInstalled).
1093
+ downloadedAt: Math.round(stat.mtimeMs),
1094
+ };
1095
+ state[model.id] = model;
1096
+ return { kind: 'imported', model };
1097
+ }
1098
+ catch (err) {
1099
+ return { kind: 'error', error: `${absPath}: ${err instanceof Error ? err.message : 'stat failed'}` };
1100
+ }
1101
+ }
1102
+ /**
1103
+ * Import .gguf files that already exist on this machine. `target` may be one
1104
+ * file or a directory (walked up to depth 4, 200-file cap). Records point at
1105
+ * the original paths — nothing is copied or moved. Split weights
1106
+ * (`-00001-of-00002.gguf` …) collapse into ONE row anchored at the first
1107
+ * shard, with the size of all shards combined.
1108
+ */
1109
+ export function importLocalModels(target) {
1110
+ const abs = path.resolve(target);
1111
+ let stat;
1112
+ try {
1113
+ stat = fs.statSync(abs);
1114
+ }
1115
+ catch (err) {
1116
+ return { imported: [], skipped: 0, errors: [err instanceof Error ? err.message : 'path not found'] };
1117
+ }
1118
+ const state = readInstalledModels();
1119
+ const imported = [];
1120
+ const errors = [];
1121
+ let skipped = 0;
1122
+ const files = [];
1123
+ if (stat.isFile()) {
1124
+ files.push(abs);
1125
+ // Picking one shard of a split model imports the whole set: scan the
1126
+ // sibling shards in the same directory so a group stays a group.
1127
+ const shardMatch = SHARD_RE.exec(path.basename(abs));
1128
+ if (shardMatch) {
1129
+ try {
1130
+ for (const entry of fs.readdirSync(path.dirname(abs), { withFileTypes: true })) {
1131
+ if (!entry.isFile())
1132
+ continue;
1133
+ const sibling = path.join(path.dirname(abs), entry.name);
1134
+ if (path.resolve(sibling) === path.resolve(abs))
1135
+ continue;
1136
+ const siblingMatch = SHARD_RE.exec(entry.name);
1137
+ if (siblingMatch && siblingMatch[1].toLowerCase() === shardMatch[1].toLowerCase() && siblingMatch[3] === shardMatch[3]) {
1138
+ files.push(sibling);
1139
+ }
1140
+ }
1141
+ }
1142
+ catch {
1143
+ // Sibling scan is best effort; the single file still imports.
1144
+ }
1145
+ }
1146
+ }
1147
+ else if (stat.isDirectory()) {
1148
+ const walk = (dir, depth) => {
1149
+ if (depth > 4 || files.length >= 200)
1150
+ return;
1151
+ let entries;
1152
+ try {
1153
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1154
+ }
1155
+ catch (err) {
1156
+ errors.push(`${dir}: ${err instanceof Error ? err.message : 'read failed'}`);
1157
+ return;
1158
+ }
1159
+ for (const entry of entries) {
1160
+ if (files.length >= 200)
1161
+ return;
1162
+ const child = path.join(dir, entry.name);
1163
+ if (entry.isDirectory())
1164
+ walk(child, depth + 1);
1165
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.gguf'))
1166
+ files.push(child);
1167
+ }
1168
+ };
1169
+ walk(abs, 0);
1170
+ }
1171
+ if (files.length === 0) {
1172
+ errors.push(`${abs}: no .gguf files found`);
1173
+ return { imported, skipped, errors };
1174
+ }
1175
+ for (const group of resolveShardGroups(files, errors)) {
1176
+ // The size a planner sees is the whole weight set, not one shard.
1177
+ let size;
1178
+ if (group.parts.length > 1) {
1179
+ try {
1180
+ size = group.parts.reduce((sum, part) => sum + fs.statSync(part).size, 0);
1181
+ }
1182
+ catch (err) {
1183
+ errors.push(`${group.primary}: ${err instanceof Error ? err.message : 'shard size failed'}`);
1184
+ continue;
1185
+ }
1186
+ }
1187
+ const outcome = importLocalFile(group.primary, state, size);
1188
+ if (outcome.kind === 'imported')
1189
+ imported.push(outcome.model);
1190
+ else if (outcome.kind === 'duplicate')
1191
+ skipped += 1;
1192
+ else
1193
+ errors.push(outcome.error);
1194
+ }
1195
+ if (imported.length > 0) {
1196
+ try {
1197
+ writeInstalledModels(state);
1198
+ try {
1199
+ const refreshed = new Map(refreshDraftMatches().map((row) => [row.id, row]));
1200
+ for (let i = 0; i < imported.length; i += 1) {
1201
+ const again = refreshed.get(imported[i].id);
1202
+ if (again)
1203
+ imported[i] = again;
1204
+ }
1205
+ }
1206
+ catch {
1207
+ // Rows are stored. Pairing can be repeated from Detect.
1208
+ }
1209
+ }
1210
+ catch (err) {
1211
+ return { imported: [], skipped, errors: [`record write failed: ${err instanceof Error ? err.message : 'unknown'}`] };
1212
+ }
1213
+ }
1214
+ return { imported, skipped, errors };
1215
+ }