omnicell-router 0.8.4 → 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 (363) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/capture/recorder.d.ts +4 -10
  4. package/backend/dist/capture/recorder.js +6 -58
  5. package/backend/dist/cli/clients/base.d.ts +36 -11
  6. package/backend/dist/cli/clients/base.js +31 -15
  7. package/backend/dist/cli/clients/claude.d.ts +9 -0
  8. package/backend/dist/cli/clients/claude.js +6 -0
  9. package/backend/dist/cli/clients/codex.d.ts +8 -0
  10. package/backend/dist/cli/clients/codex.js +5 -0
  11. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  12. package/backend/dist/cli/clients/core-adapters.js +1 -1
  13. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  14. package/backend/dist/cli/clients/dsh.js +5 -0
  15. package/backend/dist/cli/clients/grok.d.ts +15 -1
  16. package/backend/dist/cli/clients/grok.js +16 -2
  17. package/backend/dist/cli/clients/index.d.ts +13 -1
  18. package/backend/dist/cli/clients/index.js +97 -19
  19. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  20. package/backend/dist/cli/clients/kimi.js +3 -0
  21. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  22. package/backend/dist/cli/clients/model-meta.js +6 -3
  23. package/backend/dist/cli/clients/omp.d.ts +6 -0
  24. package/backend/dist/cli/clients/omp.js +3 -0
  25. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  26. package/backend/dist/cli/clients/openclaw.js +3 -0
  27. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  28. package/backend/dist/cli/clients/opencode.js +5 -0
  29. package/backend/dist/cli/clients/pi.d.ts +6 -0
  30. package/backend/dist/cli/clients/pi.js +3 -0
  31. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  32. package/backend/dist/cli/clients/update-check.js +309 -0
  33. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  34. package/backend/dist/cli/clients/workbuddy.js +66 -0
  35. package/backend/dist/cli/index.js +5 -4
  36. package/backend/dist/cli/paths.js +8 -0
  37. package/backend/dist/cli/types.d.ts +92 -16
  38. package/backend/dist/config/comments-en.js +31 -26
  39. package/backend/dist/config/comments-zh.js +29 -24
  40. package/backend/dist/config/defaults.d.ts +194 -33
  41. package/backend/dist/config/defaults.js +193 -32
  42. package/backend/dist/config/env.d.ts +10 -0
  43. package/backend/dist/config/env.js +3 -2
  44. package/backend/dist/config/index.d.ts +7 -0
  45. package/backend/dist/config/index.js +184 -43
  46. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  47. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  48. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  49. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  50. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  51. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  52. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  53. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  54. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  55. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  56. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  57. package/backend/dist/config/runtime.js +1 -1
  58. package/backend/dist/config/schema.d.ts +3 -3
  59. package/backend/dist/config/schema.js +14 -4
  60. package/backend/dist/config/types.d.ts +167 -38
  61. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  62. package/backend/dist/egress-proxy/asset-download.js +420 -0
  63. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  64. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  65. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  66. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  67. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  68. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  69. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  70. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  71. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  72. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  73. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  74. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  75. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  76. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  77. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  78. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  79. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  80. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  81. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  82. package/backend/dist/forward-proxy/egress.js +50 -17
  83. package/backend/dist/forward-proxy/h2-forward.js +36 -10
  84. package/backend/dist/forward-proxy/index.d.ts +11 -8
  85. package/backend/dist/forward-proxy/index.js +22 -60
  86. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  87. package/backend/dist/forward-proxy/interceptor.js +4 -4
  88. package/backend/dist/forward-proxy/relay.js +3 -3
  89. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  90. package/backend/dist/forward-proxy/rules.js +25 -4
  91. package/backend/dist/forward-proxy/server.d.ts +0 -16
  92. package/backend/dist/forward-proxy/server.js +124 -156
  93. package/backend/dist/harness/host/hosts.js +3 -2
  94. package/backend/dist/index.js +53 -18
  95. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  96. package/backend/dist/ingress-proxy/access-log.js +774 -0
  97. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  98. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  99. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  100. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  101. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  102. package/backend/dist/ingress-proxy/ca.js +273 -0
  103. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  104. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  105. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  106. package/backend/dist/ingress-proxy/egress.js +364 -0
  107. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  108. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  109. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  110. package/backend/dist/ingress-proxy/index.js +144 -0
  111. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  112. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  113. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  114. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  115. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  116. package/backend/dist/ingress-proxy/relay.js +188 -0
  117. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  118. package/backend/dist/ingress-proxy/rules.js +348 -0
  119. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  120. package/backend/dist/ingress-proxy/server.js +2065 -0
  121. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  122. package/backend/dist/ingress-proxy/sni.js +124 -0
  123. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  124. package/backend/dist/ingress-proxy/status.js +15 -0
  125. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  126. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  127. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  128. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  129. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  130. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  131. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  132. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  133. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  134. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  135. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  136. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  137. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  138. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  139. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  140. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  141. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  142. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  143. package/backend/dist/ir/adapters/openai-chat.js +45 -3
  144. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  145. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  146. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  147. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  148. package/backend/dist/ir/adapters/openai-responses.d.ts +82 -24
  149. package/backend/dist/ir/adapters/openai-responses.js +146 -37
  150. package/backend/dist/ir/media.d.ts +20 -0
  151. package/backend/dist/ir/media.js +41 -0
  152. package/backend/dist/ir/tool-identity.d.ts +35 -0
  153. package/backend/dist/ir/tool-identity.js +40 -0
  154. package/backend/dist/ir/types.d.ts +9 -1
  155. package/backend/dist/local/build-jobs.d.ts +66 -0
  156. package/backend/dist/local/build-jobs.js +243 -0
  157. package/backend/dist/local/detect.d.ts +32 -0
  158. package/backend/dist/local/detect.js +145 -0
  159. package/backend/dist/local/draft-match.d.ts +58 -0
  160. package/backend/dist/local/draft-match.js +124 -0
  161. package/backend/dist/local/engine-runtime.d.ts +522 -0
  162. package/backend/dist/local/engine-runtime.js +1 -0
  163. package/backend/dist/local/engines.d.ts +241 -0
  164. package/backend/dist/local/engines.js +651 -0
  165. package/backend/dist/local/gguf.d.ts +35 -0
  166. package/backend/dist/local/gguf.js +314 -0
  167. package/backend/dist/local/hf.d.ts +120 -0
  168. package/backend/dist/local/hf.js +304 -0
  169. package/backend/dist/local/install.d.ts +90 -0
  170. package/backend/dist/local/install.js +421 -0
  171. package/backend/dist/local/llamacpp.d.ts +55 -0
  172. package/backend/dist/local/llamacpp.js +177 -0
  173. package/backend/dist/local/local-provider.d.ts +81 -0
  174. package/backend/dist/local/local-provider.js +301 -0
  175. package/backend/dist/local/machine-stats.d.ts +87 -0
  176. package/backend/dist/local/machine-stats.js +332 -0
  177. package/backend/dist/local/model-store.d.ts +347 -0
  178. package/backend/dist/local/model-store.js +1215 -0
  179. package/backend/dist/local/part-sweep.d.ts +32 -0
  180. package/backend/dist/local/part-sweep.js +156 -0
  181. package/backend/dist/local/plan.d.ts +65 -0
  182. package/backend/dist/local/plan.js +146 -0
  183. package/backend/dist/local/resources.d.ts +49 -0
  184. package/backend/dist/local/resources.js +64 -0
  185. package/backend/dist/local/run-stats.d.ts +95 -0
  186. package/backend/dist/local/run-stats.js +195 -0
  187. package/backend/dist/local/runner.d.ts +235 -0
  188. package/backend/dist/local/runner.js +1392 -0
  189. package/backend/dist/local/settings.d.ts +79 -0
  190. package/backend/dist/local/settings.js +180 -0
  191. package/backend/dist/local/strata-catalog.d.ts +30 -0
  192. package/backend/dist/local/strata-catalog.js +511 -0
  193. package/backend/dist/local/strata-drafting.d.ts +46 -0
  194. package/backend/dist/local/strata-drafting.js +265 -0
  195. package/backend/dist/local/strata.d.ts +278 -0
  196. package/backend/dist/local/strata.js +1392 -0
  197. package/backend/dist/local/tar.d.ts +20 -0
  198. package/backend/dist/local/tar.js +367 -0
  199. package/backend/dist/local/transport.d.ts +35 -0
  200. package/backend/dist/local/transport.js +89 -0
  201. package/backend/dist/local/tune.d.ts +58 -0
  202. package/backend/dist/local/tune.js +324 -0
  203. package/backend/dist/observability/http-exchange.d.ts +2 -2
  204. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  205. package/backend/dist/opencode/catalog/auto-pull.js +276 -70
  206. package/backend/dist/opencode/catalog/ocr-store.js +3 -1
  207. package/backend/dist/opencode/catalog/overrides-store.d.ts +10 -1
  208. package/backend/dist/opencode/catalog/overrides-store.js +6 -0
  209. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  210. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  211. package/backend/dist/opencode/catalog/repository.js +25 -2
  212. package/backend/dist/opencode/catalog/sources/models-dev.js +13 -3
  213. package/backend/dist/opencode/catalog/types.d.ts +35 -3
  214. package/backend/dist/opencode/catalog/types.js +38 -1
  215. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  216. package/backend/dist/opencode/credentials/sync.js +12 -3
  217. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  218. package/backend/dist/opencode/credentials/types.js +25 -0
  219. package/backend/dist/opencode/probe.d.ts +21 -4
  220. package/backend/dist/opencode/probe.js +34 -10
  221. package/backend/dist/pipeline/directives.d.ts +9 -4
  222. package/backend/dist/pipeline/directives.js +14 -10
  223. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  224. package/backend/dist/pipeline/orchestrator.js +497 -165
  225. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  226. package/backend/dist/plugins/environment-ack.js +81 -0
  227. package/backend/dist/plugins/gateways.d.ts +6 -6
  228. package/backend/dist/plugins/gateways.js +2 -2
  229. package/backend/dist/plugins/host.d.ts +98 -14
  230. package/backend/dist/plugins/host.js +622 -87
  231. package/backend/dist/plugins/install-run.d.ts +27 -0
  232. package/backend/dist/plugins/install-run.js +99 -0
  233. package/backend/dist/plugins/manifest.d.ts +84 -32
  234. package/backend/dist/plugins/manifest.js +149 -45
  235. package/backend/dist/plugins/market-install.d.ts +18 -0
  236. package/backend/dist/plugins/market-install.js +111 -0
  237. package/backend/dist/plugins/market-source.d.ts +100 -0
  238. package/backend/dist/plugins/market-source.js +449 -0
  239. package/backend/dist/plugins/market-updates.d.ts +70 -0
  240. package/backend/dist/plugins/market-updates.js +97 -0
  241. package/backend/dist/plugins/market.d.ts +677 -0
  242. package/backend/dist/plugins/market.js +2113 -0
  243. package/backend/dist/plugins/source-index.d.ts +155 -0
  244. package/backend/dist/plugins/source-index.js +217 -0
  245. package/backend/dist/plugins/types.d.ts +402 -37
  246. package/backend/dist/projects/worktrees.d.ts +88 -0
  247. package/backend/dist/projects/worktrees.js +220 -0
  248. package/backend/dist/providers/boot-direct.d.ts +41 -7
  249. package/backend/dist/providers/boot-direct.js +252 -36
  250. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  251. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  252. package/backend/dist/providers/executors/dispatch.js +28 -9
  253. package/backend/dist/providers/executors/openai-chat.js +14 -2
  254. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  255. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  256. package/backend/dist/providers/member-match.d.ts +32 -9
  257. package/backend/dist/providers/member-match.js +65 -21
  258. package/backend/dist/providers/model-resolution.d.ts +62 -0
  259. package/backend/dist/providers/model-resolution.js +62 -0
  260. package/backend/dist/providers/price-order.d.ts +51 -0
  261. package/backend/dist/providers/price-order.js +54 -0
  262. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  263. package/backend/dist/providers/registry.d.ts +84 -25
  264. package/backend/dist/providers/registry.js +209 -114
  265. package/backend/dist/providers/selection.d.ts +91 -0
  266. package/backend/dist/providers/selection.js +158 -0
  267. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  268. package/backend/dist/providers/virtual-meta.js +74 -18
  269. package/backend/dist/quota/cli-login.d.ts +25 -4
  270. package/backend/dist/quota/cli-login.js +35 -5
  271. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  272. package/backend/dist/quota/coverage-generation.js +29 -0
  273. package/backend/dist/quota/declarations.js +8 -4
  274. package/backend/dist/quota/engine.js +2 -2
  275. package/backend/dist/quota/prober.d.ts +43 -2
  276. package/backend/dist/quota/prober.js +97 -22
  277. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  278. package/backend/dist/resilience/error-classifier.js +29 -0
  279. package/backend/dist/router/index.d.ts +1 -1
  280. package/backend/dist/router/index.js +17 -1
  281. package/backend/dist/router/layer2-decision.d.ts +1 -1
  282. package/backend/dist/router/layer2-decision.js +2 -2
  283. package/backend/dist/routes/console.js +928 -310
  284. package/backend/dist/routes/environments.js +1 -1
  285. package/backend/dist/routes/local-models.d.ts +2 -0
  286. package/backend/dist/routes/local-models.js +1414 -0
  287. package/backend/dist/routes/mihomo.d.ts +2 -2
  288. package/backend/dist/routes/mihomo.js +20 -11
  289. package/backend/dist/routes/projects.js +121 -0
  290. package/backend/dist/server.js +318 -13
  291. package/backend/dist/session/session-manager.d.ts +42 -5
  292. package/backend/dist/session/session-manager.js +64 -11
  293. package/backend/dist/session/session-row.d.ts +29 -8
  294. package/backend/dist/session/session-row.js +18 -13
  295. package/backend/dist/snapshot/bundle.d.ts +40 -0
  296. package/backend/dist/snapshot/bundle.js +177 -0
  297. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  298. package/backend/dist/snapshot/handoff/compress.js +77 -0
  299. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  300. package/backend/dist/snapshot/handoff/index.js +160 -0
  301. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  302. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  303. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  304. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  305. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  306. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  307. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  308. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  309. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  310. package/backend/dist/snapshot/media-fs.js +50 -0
  311. package/backend/dist/snapshot/media.d.ts +32 -0
  312. package/backend/dist/snapshot/media.js +87 -0
  313. package/backend/dist/snapshot/store.d.ts +226 -0
  314. package/backend/dist/snapshot/store.js +887 -0
  315. package/backend/dist/snapshot/tree.d.ts +112 -0
  316. package/backend/dist/snapshot/tree.js +207 -0
  317. package/backend/dist/snapshot/types.d.ts +212 -0
  318. package/backend/dist/snapshot/types.js +14 -0
  319. package/backend/dist/snapshot/view.d.ts +19 -0
  320. package/backend/dist/snapshot/view.js +57 -0
  321. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  322. package/backend/dist/snapshot/write-worker.js +129 -0
  323. package/backend/dist/surfaces/body-admission.d.ts +67 -2
  324. package/backend/dist/surfaces/body-admission.js +218 -13
  325. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  326. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  327. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  328. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  329. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  330. package/backend/dist/surfaces/gateway-chat.js +50 -12
  331. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  332. package/backend/dist/surfaces/ocr-headers.js +11 -7
  333. package/backend/dist/surfaces/systemone.js +1 -1
  334. package/backend/dist/surfaces/transport-fastify.js +32 -5
  335. package/backend/dist/surfaces/transport-node-http.d.ts +9 -3
  336. package/backend/dist/surfaces/transport-node-http.js +6 -19
  337. package/backend/dist/surfaces/types.d.ts +11 -3
  338. package/backend/dist/trace/persist.js +21 -1
  339. package/backend/dist/trace/tracker.d.ts +35 -3
  340. package/backend/dist/trace/tracker.js +23 -0
  341. package/backend/dist/types/openai.d.ts +8 -0
  342. package/backend/dist/types/router.d.ts +17 -6
  343. package/backend/dist/types/router.js +14 -2
  344. package/backend/dist/utils/client-families.d.ts +66 -0
  345. package/backend/dist/utils/client-families.js +127 -0
  346. package/backend/dist/utils/event-ring.d.ts +1 -1
  347. package/backend/dist/utils/event-ring.js +1 -1
  348. package/backend/dist/utils/proxy-node.js +1 -1
  349. package/backend/dist/utils/proxy.d.ts +135 -11
  350. package/backend/dist/utils/proxy.js +144 -29
  351. package/backend/dist/utils/run-command.d.ts +21 -1
  352. package/backend/dist/utils/run-command.js +64 -4
  353. package/backend/dist/utils/server-liveness.d.ts +3 -2
  354. package/backend/dist/utils/server-liveness.js +3 -2
  355. package/backend/dist/utils/session-file.d.ts +28 -0
  356. package/backend/dist/utils/session-file.js +34 -0
  357. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  358. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  359. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  360. package/frontend/dist/assets/{index-KI1OW5x6.css → index-CqDSOPQ0.css} +1 -1
  361. package/frontend/dist/index.html +2 -2
  362. package/package.json +3 -1
  363. package/frontend/dist/assets/index-Dk76uc7e.js +0 -1522
@@ -0,0 +1,1392 @@
1
+ /**
2
+ * Local model run supervisor (Local Models console).
3
+ *
4
+ * A RUN is one launched inference server process serving one registry model
5
+ * over its OpenAI-compatible HTTP API. Ownership follows the mihomo sidecar
6
+ * doctrine's division (ADR-0022): a run this gateway spawned is bound to the
7
+ * gateway's lifetime and killed on its exit. A survivor of a hard-killed
8
+ * gateway is ADOPTED on boot once its pid AND its command line both prove it is
9
+ * still one of our engines (a recycled pid belongs to a stranger — ADR-0043's
10
+ * 2026-11-29 amendment), so the record re-enters `starting` and the readiness
11
+ * poll resumes; deafness is deliberately NOT an adoption or a death gate, since
12
+ * llama-server answers `/health` 503 while loading and Strata's front-end binds
13
+ * only after the engine is READY. A row an older sweep closed too early is
14
+ * re-probed from the runs-list poll (LAST-READOPT probe, throttled per id).
15
+ * Runs persist as `<ocrHome>/engines/runs.json` so a restart never loses sight
16
+ * of a live server it started.
17
+ *
18
+ * Today the runner drives llama.cpp's `llama-server` and Strata's engine — and
19
+ * any future engine — through ONE abstraction: each engine ships an
20
+ * `EngineRuntime` (file gate, placement authority, argv legs, profile) and this
21
+ * module asks it instead of branching on an engine name (ADR-0045). Layered
22
+ * execution for gateway-placed engines IS llama.cpp's `-ngl N` (N layers in
23
+ * VRAM, the rest on CPU/RAM, mmap streaming the remainder from disk); the
24
+ * placement plan (`plan.ts`) computes N and the console's automatic-layer-plan
25
+ * panel previews it. Engines that own their own placement (Strata's
26
+ * `--expert-cache`) are launched with `ngl: -1` and no layer plan at all.
27
+ *
28
+ * Process output lands in a per-run ring (`runLogs`) the console's run-log
29
+ * drawer polls. The same ring is snapshotted to
30
+ * `<ocrHome>/engines/run-logs/<id>.json` so a failed launch still has its
31
+ * transcript after a gateway restart (ADR-0043 §5). Prune and delete remove
32
+ * the file with the record.
33
+ *
34
+ * Both the resident ring and the snapshot are retained only for the newest
35
+ * `LOCAL_RUN_LOG_KEEP_RUNS` ENDED runs (`sweepRunLogs`, run at boot, when a
36
+ * run ends, and on prune): an engine that is launched and stopped a thousand
37
+ * times must not leave a thousand rings in the heap or a thousand files on
38
+ * disk. The run RECORD survives the sweep — it is the console's history, and
39
+ * a transcript that aged out simply reads as empty.
40
+ */
41
+ import { execFile, spawn, spawnSync } from 'node:child_process';
42
+ import fs from 'node:fs';
43
+ import net from 'node:net';
44
+ import os from 'node:os';
45
+ import path from 'node:path';
46
+ import { DEFAULT_LOCAL_RUN_PORT, LOCAL_DEFAULT_CTX, LOCAL_RUN_LOG_KEEP_RUNS, LOCAL_RUN_MAX_RESTARTS, LOCAL_RUN_READOPT_INTERVAL_MS, LOCAL_RUN_READY_TIMEOUT_MS, LOCAL_RUN_RESTART_WINDOW_MS, } from '../config/defaults.js';
47
+ import { getOcrHomeDir } from '../cli/paths.js';
48
+ import { EventRing, MIHOMO_LOG_RING_CAPACITY, nextRingEventId } from '../utils/event-ring.js';
49
+ import { engineById, engineSupportFor, installedEngineFor, launchableEngines, readInstalledEngines, } from './engines.js';
50
+ import { readGgufMeta } from './gguf.js';
51
+ import { autoCtx, nglForPlan, planPlacement, KV_ELEM_Q8_0 } from './plan.js';
52
+ import { profileFor, profilesOf, readInstalledModels } from './model-store.js';
53
+ import { detectDependencies } from './detect.js';
54
+ export { llamaServerArgs } from './llamacpp.js';
55
+ /**
56
+ * Detected total VRAM, memoised: the probe shells out to nvidia-smi (seconds),
57
+ * and an engine-owned placement reads this ONE fact per launch (its resource
58
+ * rule needs the card size). A probe failure is a reading of "no card", not an
59
+ * error — an engine that needs no number simply gets none.
60
+ */
61
+ let vramProbe = null;
62
+ async function machineVramMb() {
63
+ if (vramProbe && Date.now() - vramProbe.at < 120_000)
64
+ return vramProbe.mb;
65
+ try {
66
+ const report = await detectDependencies();
67
+ vramProbe = { at: Date.now(), ...(report.vramMb != null ? { mb: report.vramMb } : {}) };
68
+ }
69
+ catch {
70
+ vramProbe = { at: Date.now() };
71
+ }
72
+ return vramProbe.mb;
73
+ }
74
+ export const DEFAULT_RUN_OPTIONS = {
75
+ ctx: 0,
76
+ ngl: -1,
77
+ flashAttn: true,
78
+ kvCacheQ8: true,
79
+ reasoning: false,
80
+ autoRestart: true,
81
+ headroom: true,
82
+ threads: 0,
83
+ extraArgs: [],
84
+ };
85
+ let testDeps = null;
86
+ /** Test seam, mirroring setMihomoSidecarDepsForTests. */
87
+ export function setLocalRunnerDepsForTests(deps) {
88
+ testDeps = deps;
89
+ if (!deps) {
90
+ for (const [id] of children)
91
+ children.delete(id);
92
+ }
93
+ }
94
+ function dep(key) {
95
+ return testDeps?.[key];
96
+ }
97
+ /* ------------------------------------------------------------------------- *
98
+ * Persisted registry
99
+ * ------------------------------------------------------------------------- */
100
+ function runsDir() {
101
+ return path.join(getOcrHomeDir(), 'engines');
102
+ }
103
+ function runsStateFile() {
104
+ return path.join(runsDir(), 'runs.json');
105
+ }
106
+ function readRunRecords() {
107
+ try {
108
+ const parsed = JSON.parse(fs.readFileSync(runsStateFile(), 'utf8'));
109
+ if (!parsed || typeof parsed !== 'object')
110
+ return {};
111
+ for (const record of Object.values(parsed))
112
+ backfillErrorCode(record);
113
+ return parsed;
114
+ }
115
+ catch {
116
+ return {};
117
+ }
118
+ }
119
+ /**
120
+ * Recover `lastErrorCode` for records written before the field existed.
121
+ *
122
+ * Without this, an archive recorded by an older build keeps showing the raw
123
+ * English sentence forever — the console localizes on the CODE, and a missing
124
+ * code is exactly the "unknown, stay raw" path. The sentences below are the
125
+ * ones this module minted, so the mapping is lossless; anything unrecognized
126
+ * is left alone (a raw engine message we never minted a code for).
127
+ */
128
+ function backfillErrorCode(record) {
129
+ if (record.lastErrorCode || !record.lastError)
130
+ return;
131
+ const text = record.lastError;
132
+ if (text === 'engine process died before becoming ready')
133
+ record.lastErrorCode = 'engine-died-before-ready';
134
+ else if (text === 'gateway restarted while the engine was running')
135
+ record.lastErrorCode = 'gateway-restarted';
136
+ else if (/^the engine did not become ready within \d+ min$/.test(text))
137
+ record.lastErrorCode = 'load-timeout';
138
+ else if (/^crashed \(exit .+\); restart \d+\/\d+$/.test(text))
139
+ record.lastErrorCode = 'crashed-restarting';
140
+ else if (/^engine exited \(code .+\)$/.test(text))
141
+ record.lastErrorCode = 'engine-exited';
142
+ }
143
+ function writeRunRecords(state) {
144
+ fs.mkdirSync(runsDir(), { recursive: true });
145
+ const tmp = `${runsStateFile()}.tmp`;
146
+ fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
147
+ fs.renameSync(tmp, runsStateFile());
148
+ }
149
+ /** Live view: the in-memory map is authoritative for active runs; the file
150
+ * remembers ended ones until the console prunes them. */
151
+ const live = new Map();
152
+ const children = new Map();
153
+ const logs = new Map();
154
+ const ANSI_RE = /\x1b\[?[0-9;?]*[a-zA-Z]/g;
155
+ const LINE_MAX_CHARS = 2000;
156
+ /** One re-adoption probe per id per interval; cleared when the row is
157
+ * re-adopted, re-closed or deleted. */
158
+ const lastReadoptProbe = new Map();
159
+ /**
160
+ * One raw child-process line as a log ring stores it; null = nothing to log.
161
+ * Shared with the build supervisor (build-jobs.ts) so run and build logs read
162
+ * identically.
163
+ */
164
+ export function sanitizeRunLogText(raw) {
165
+ const text = raw.replace(ANSI_RE, '').replace(/\r$/, '');
166
+ if (!text.trim())
167
+ return null;
168
+ return text.length > LINE_MAX_CHARS ? `${text.slice(0, LINE_MAX_CHARS)}…` : text;
169
+ }
170
+ /** Engine lines batch; a gateway line (exit, spawn error, timeout) flushes the ring immediately. */
171
+ const LOG_FLUSH_MS = 200;
172
+ const LOG_FLUSH_LINES = 25;
173
+ const logFlush = new Map();
174
+ const dirtyLines = new Map();
175
+ function runLogFile(id) {
176
+ // Run ids are minted here (`run-<base36>-<base36>`). Anything else must not
177
+ // become a path.
178
+ if (!/^run-[a-z0-9-]+$/i.test(id))
179
+ return null;
180
+ return path.join(runsDir(), 'run-logs', `${id}.json`);
181
+ }
182
+ function cancelLogFlush(id) {
183
+ const timer = logFlush.get(id);
184
+ if (timer)
185
+ clearTimeout(timer);
186
+ logFlush.delete(id);
187
+ dirtyLines.delete(id);
188
+ }
189
+ /** Rewrite this run's snapshot from the ring. Fail-open: a missed write only
190
+ * costs the transcript across a restart. */
191
+ function writeRunLog(id) {
192
+ const file = runLogFile(id);
193
+ const ring = logs.get(id);
194
+ if (!file || !ring)
195
+ return;
196
+ const rows = ring.rows();
197
+ if (rows.length === 0)
198
+ return;
199
+ try {
200
+ fs.mkdirSync(path.dirname(file), { recursive: true });
201
+ const tmp = `${file}.tmp`;
202
+ fs.writeFileSync(tmp, JSON.stringify(rows));
203
+ fs.renameSync(tmp, file);
204
+ }
205
+ catch {
206
+ // See the comment above.
207
+ }
208
+ }
209
+ function noteRunLog(id, stream) {
210
+ if (stream === 'gateway') {
211
+ cancelLogFlush(id);
212
+ writeRunLog(id);
213
+ return;
214
+ }
215
+ const n = (dirtyLines.get(id) ?? 0) + 1;
216
+ if (n >= LOG_FLUSH_LINES) {
217
+ cancelLogFlush(id);
218
+ writeRunLog(id);
219
+ return;
220
+ }
221
+ dirtyLines.set(id, n);
222
+ if (logFlush.has(id))
223
+ return;
224
+ logFlush.set(id, setTimeout(() => {
225
+ logFlush.delete(id);
226
+ dirtyLines.delete(id);
227
+ writeRunLog(id);
228
+ }, LOG_FLUSH_MS));
229
+ }
230
+ /** Drop the ring and its snapshot together (prune, delete). */
231
+ function forgetRunLog(id) {
232
+ cancelLogFlush(id);
233
+ logs.delete(id);
234
+ const file = runLogFile(id);
235
+ if (!file)
236
+ return;
237
+ try {
238
+ fs.unlinkSync(file);
239
+ }
240
+ catch { /* already gone */ }
241
+ try {
242
+ fs.unlinkSync(`${file}.tmp`);
243
+ }
244
+ catch { /* no partial write */ }
245
+ }
246
+ function replayRunLog(id, ring) {
247
+ const file = runLogFile(id);
248
+ if (!file)
249
+ return;
250
+ let parsed;
251
+ try {
252
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
253
+ }
254
+ catch {
255
+ return;
256
+ }
257
+ if (!Array.isArray(parsed))
258
+ return;
259
+ for (const line of parsed.slice(-MIHOMO_LOG_RING_CAPACITY)) {
260
+ if (!line || typeof line !== 'object')
261
+ continue;
262
+ const row = line;
263
+ if (typeof row.id !== 'string' || typeof row.text !== 'string')
264
+ continue;
265
+ const stream = row.stream === 'stderr' || row.stream === 'gateway' ? row.stream : 'stdout';
266
+ ring.append({
267
+ id: row.id,
268
+ ts: typeof row.ts === 'number' ? row.ts : 0,
269
+ stream,
270
+ text: row.text,
271
+ });
272
+ }
273
+ }
274
+ function ringFor(id) {
275
+ let ring = logs.get(id);
276
+ if (ring)
277
+ return ring;
278
+ ring = new EventRing(undefined, MIHOMO_LOG_RING_CAPACITY);
279
+ logs.set(id, ring);
280
+ replayRunLog(id, ring);
281
+ return ring;
282
+ }
283
+ /** Flush every ring. The gateway's exit hook calls this before killing
284
+ * children, so a restart still has the lines already captured. */
285
+ function flushAllRunLogsSync() {
286
+ for (const id of logs.keys()) {
287
+ cancelLogFlush(id);
288
+ writeRunLog(id);
289
+ }
290
+ }
291
+ /**
292
+ * Transcript retention (ADR-0043 §5): keep the ring and the snapshot of every
293
+ * LIVE run plus the newest `LOCAL_RUN_LOG_KEEP_RUNS` ended ones. Returns how
294
+ * many snapshot FILES were removed.
295
+ *
296
+ * The keep-set comes from `runs.json` — the record is the history, the
297
+ * transcript expires — and a log file whose record is gone is an orphan, so it
298
+ * goes too. Only files this module mints are considered: an unexpected name in
299
+ * the directory is not turned into a delete.
300
+ */
301
+ export function sweepRunLogs() {
302
+ const keep = new Set(live.keys());
303
+ const records = Object.values(readRunRecords());
304
+ for (const record of records) {
305
+ // A serving row keeps its transcript even when this process has not
306
+ // adopted it yet (the boot sweep adopts from this same file).
307
+ if (runIsServing(record))
308
+ keep.add(record.id);
309
+ }
310
+ const ended = records
311
+ .filter((record) => record.status === 'stopped' || record.status === 'failed')
312
+ .sort((a, b) => (b.stoppedAt ?? b.startedAt ?? 0) - (a.stoppedAt ?? a.startedAt ?? 0));
313
+ for (const record of ended.slice(0, LOCAL_RUN_LOG_KEEP_RUNS))
314
+ keep.add(record.id);
315
+ for (const id of logs.keys()) {
316
+ if (keep.has(id))
317
+ continue;
318
+ cancelLogFlush(id);
319
+ logs.delete(id);
320
+ }
321
+ const dir = path.join(runsDir(), 'run-logs');
322
+ let names;
323
+ try {
324
+ names = fs.readdirSync(dir);
325
+ }
326
+ catch {
327
+ return 0;
328
+ }
329
+ let dropped = 0;
330
+ for (const name of names) {
331
+ const match = /^(run-[a-z0-9-]+)\.json$/i.exec(name);
332
+ if (!match || keep.has(match[1]))
333
+ continue;
334
+ try {
335
+ fs.unlinkSync(path.join(dir, name));
336
+ dropped += 1;
337
+ }
338
+ catch {
339
+ // A locked file is retried by the next sweep.
340
+ }
341
+ }
342
+ return dropped;
343
+ }
344
+ export function appendRunLog(id, stream, raw) {
345
+ const text = sanitizeRunLogText(raw);
346
+ if (text === null)
347
+ return;
348
+ const ts = Date.now();
349
+ ringFor(id).append({
350
+ id: nextRingEventId('r-', ts),
351
+ ts,
352
+ stream,
353
+ text,
354
+ });
355
+ noteRunLog(id, stream);
356
+ }
357
+ export function runLogs(id, limit = 300) {
358
+ let ring = logs.get(id);
359
+ if (!ring) {
360
+ // A READ must not mint a ring: the drawer polls whatever id the console
361
+ // holds, and an unknown one would grow `logs` until the next sweep. Only a
362
+ // snapshot on disk (an ended run from an earlier process) replays, and it
363
+ // replays into a throwaway ring rather than being registered.
364
+ const file = runLogFile(id);
365
+ if (!file || !fs.existsSync(file))
366
+ return [];
367
+ ring = new EventRing(undefined, MIHOMO_LOG_RING_CAPACITY);
368
+ replayRunLog(id, ring);
369
+ }
370
+ const rows = ring.rows();
371
+ return limit >= rows.length ? rows : rows.slice(rows.length - limit);
372
+ }
373
+ function persist(run) {
374
+ try {
375
+ const state = readRunRecords();
376
+ state[run.id] = run;
377
+ writeRunRecords(state);
378
+ }
379
+ catch {
380
+ // A failed persist only costs the boot-time adoption of this run.
381
+ }
382
+ }
383
+ /** `live` means this process still owns the engine. A failed or stopped run
384
+ * that stays resident is what made delete answer `run-live` for a start that
385
+ * never came up — membership was being treated as "still running". */
386
+ function releaseRun(run) {
387
+ if (run.status === 'failed' || run.status === 'stopped') {
388
+ lastReadoptProbe.delete(run.id);
389
+ live.delete(run.id);
390
+ // The transcript of a run that just ended may push an older ended run out
391
+ // of the retention window (ADR-0043 §5) — its ring and snapshot go now,
392
+ // not at the next boot.
393
+ sweepRunLogs();
394
+ }
395
+ }
396
+ function runIsServing(run) {
397
+ return run.status === 'starting' || run.status === 'ready' || run.status === 'stopping';
398
+ }
399
+ function pidAlive(pid) {
400
+ const impl = dep('pidAliveImpl');
401
+ if (impl)
402
+ return impl(pid);
403
+ try {
404
+ process.kill(pid, 0);
405
+ return true;
406
+ }
407
+ catch {
408
+ return false;
409
+ }
410
+ }
411
+ function killTree(pid) {
412
+ const impl = dep('killTreeImpl');
413
+ if (impl)
414
+ return impl(pid);
415
+ try {
416
+ if (process.platform === 'win32') {
417
+ const res = spawnSync('taskkill', ['/F', '/T', '/PID', String(pid)], { windowsHide: true });
418
+ return res.status === 0;
419
+ }
420
+ process.kill(pid, 'SIGTERM');
421
+ return true;
422
+ }
423
+ catch {
424
+ return false;
425
+ }
426
+ }
427
+ /** Engine servers this gateway can be running: llama.cpp's binary and Strata's
428
+ * two (the front-end `python serve/server.py` and the engine exe). A pid whose
429
+ * command line names none of these is somebody else's process. */
430
+ const ENGINE_PROCESS_HINT = /llama-server|llama\.exe|strata|serve[\\/]server\.py/i;
431
+ /**
432
+ * The command line of a pid, or `null` when the OS cannot answer. Used ONLY to
433
+ * decide whether a pid this process did not spawn is still OUR engine — a
434
+ * recycled pid must never be adopted (the run would claim a stranger's process)
435
+ * and must never be killed (`taskkill /T` would take the stranger's children
436
+ * with it).
437
+ */
438
+ function processCommandLine(pid) {
439
+ const impl = dep('processCommandLineImpl');
440
+ if (impl)
441
+ return impl(pid);
442
+ try {
443
+ if (process.platform === 'win32') {
444
+ // `Get-CimInstance` is the only reliable Windows source; `wmic` is gone on
445
+ // current builds. -NoProfile keeps it from loading a user profile.
446
+ const res = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], { windowsHide: true, encoding: 'utf8', timeout: 5000 });
447
+ const text = (res.stdout ?? '').trim();
448
+ return res.status === 0 && text ? text : null;
449
+ }
450
+ const res = spawnSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', timeout: 5000 });
451
+ const text = (res.stdout ?? '').trim();
452
+ return res.status === 0 && text ? text : null;
453
+ }
454
+ catch {
455
+ return null;
456
+ }
457
+ }
458
+ /**
459
+ * Is `pid` still one of OUR engine servers? `true` when the command line proves
460
+ * it, `false` when it proves otherwise, and `null` when the OS could not answer —
461
+ * an unanswerable check must not silently turn into "kill it".
462
+ */
463
+ function pidLooksLikeOurEngine(pid) {
464
+ const commandLine = processCommandLine(pid);
465
+ if (commandLine == null)
466
+ return null;
467
+ return ENGINE_PROCESS_HINT.test(commandLine);
468
+ }
469
+ /**
470
+ * The same question WITHOUT blocking the event loop. The re-adoption window
471
+ * runs on the console's runs-list poll (every 2 s while the page is open), and
472
+ * the sync probe is a `powershell`/`ps` process creation: blocking there would
473
+ * stall every in-flight inference request the gateway is proxying. Only the
474
+ * operator-driven paths (stop, the boot sweep) may block, because their answer
475
+ * is needed before an irrecoverable `taskkill /T`.
476
+ */
477
+ function processCommandLineAsync(pid) {
478
+ const impl = dep('processCommandLineImpl');
479
+ if (impl)
480
+ return Promise.resolve(impl(pid));
481
+ const [cmd, args] = process.platform === 'win32'
482
+ ? ['powershell', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`]]
483
+ : ['ps', ['-p', String(pid), '-o', 'command=']];
484
+ return new Promise((resolve) => {
485
+ try {
486
+ execFile(cmd, args, { timeout: 5000, windowsHide: true, encoding: 'utf8' }, (err, stdout) => {
487
+ const text = (typeof stdout === 'string' ? stdout : '').trim();
488
+ resolve(!err && text ? text : null);
489
+ });
490
+ }
491
+ catch {
492
+ resolve(null);
493
+ }
494
+ });
495
+ }
496
+ async function pidLooksLikeOurEngineAsync(pid) {
497
+ const commandLine = await processCommandLineAsync(pid);
498
+ if (commandLine == null)
499
+ return null;
500
+ return ENGINE_PROCESS_HINT.test(commandLine);
501
+ }
502
+ /**
503
+ * May this gateway act on `pid`? `'ours'` when a child handle we hold still
504
+ * reports RUNNING (a live child holds its pid, so it cannot have been recycled)
505
+ * or when the command line proves it is our engine; `'stranger'` when the line
506
+ * proves otherwise; `'unverifiable'` when the OS could not answer.
507
+ *
508
+ * ONE gate for every kill: stop, the load-timeout hang guard and adopted aux
509
+ * legs all route through here, so no path can `taskkill /T` a recycled pid by
510
+ * accident (AGENTS.md: a recorded pid is not an identity).
511
+ */
512
+ function pidVerdict(run, pid) {
513
+ const child = children.get(run.id);
514
+ if (child != null && child.exitCode == null && child.killed !== true)
515
+ return 'ours';
516
+ const looks = pidLooksLikeOurEngine(pid);
517
+ return looks === true ? 'ours' : looks === false ? 'stranger' : 'unverifiable';
518
+ }
519
+ /* ------------------------------------------------------------------------- *
520
+ * Health + ports
521
+ * ------------------------------------------------------------------------- */
522
+ async function healthProbe(port) {
523
+ const impl = dep('healthProbe');
524
+ if (impl)
525
+ return impl(port);
526
+ const fetchImpl = dep('fetchImpl') ?? fetch;
527
+ try {
528
+ // llama-server answers /health 200 once the model is loaded (503 while
529
+ // loading); /v1/models is the fallback for builds without /health.
530
+ const res = await fetchImpl(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1500) });
531
+ if (res.ok)
532
+ return true;
533
+ if (res.status !== 503) {
534
+ const alt = await fetchImpl(`http://127.0.0.1:${port}/v1/models`, { signal: AbortSignal.timeout(1500) });
535
+ return alt.ok;
536
+ }
537
+ return false;
538
+ }
539
+ catch {
540
+ return false;
541
+ }
542
+ }
543
+ /** First free port from the base, skipping ports live runs already hold.
544
+ * "Free" = we can bind it on the listen host right now. `reserved` covers a
545
+ * port this process is about to hand out but has not spawned onto yet — the
546
+ * vision leg allocates right after the engine, and two unbound allocations in
547
+ * the same tick would otherwise collide. */
548
+ async function allocatePort(reserved) {
549
+ const held = new Set([...live.values()].filter((r) => r.status === 'starting' || r.status === 'ready').map((r) => r.port));
550
+ for (let port = DEFAULT_LOCAL_RUN_PORT; port < DEFAULT_LOCAL_RUN_PORT + 100; port++) {
551
+ if (held.has(port) || reserved?.has(port))
552
+ continue;
553
+ const taken = await new Promise((resolve) => {
554
+ const probe = net.createServer();
555
+ probe.once('error', () => resolve(true));
556
+ probe.once('listening', () => probe.close(() => resolve(false)));
557
+ probe.listen(port, '127.0.0.1');
558
+ });
559
+ if (!taken)
560
+ return port;
561
+ }
562
+ return DEFAULT_LOCAL_RUN_PORT;
563
+ }
564
+ /**
565
+ * The engine's server binary among the unpacked ones: the catalog's own
566
+ * `binaryNames` order wins (a `-cli` helper never takes the `-server` slot),
567
+ * and the first binary is the fallback for a build whose names moved.
568
+ */
569
+ function pickBinary(install, engine) {
570
+ const stem = (p) => path.basename(p).toLowerCase().replace(/\.(exe|bat|cmd)$/i, '');
571
+ for (const wanted of engine.binaryNames) {
572
+ const hit = install.binaries.find((bin) => stem(bin) === wanted.toLowerCase());
573
+ if (hit)
574
+ return hit;
575
+ }
576
+ return install.binaries[0] ?? null;
577
+ }
578
+ /** The backend family of one install (drives the planner, not the engine). */
579
+ function backendOf(engine, target) {
580
+ return engine.targets(process.platform, process.arch).find((t) => t.id === target)?.backend ?? 'cpu';
581
+ }
582
+ let runSeq = 0;
583
+ /**
584
+ * Launch one model on one installed engine target. The record is persisted
585
+ * BEFORE the spawn returns so a crash mid-launch still leaves a trace the
586
+ * boot sweep closes.
587
+ *
588
+ * Every engine-shaped question is answered by the engine's runtime
589
+ * (ADR-0045): `serves()` gates the launch, `placement` says who resolves
590
+ * ctx/ngl, `legs()` produces the argv. This function names no engine.
591
+ */
592
+ export async function startLocalRun(opts) {
593
+ const model = readInstalledModels()[opts.modelId];
594
+ if (!model)
595
+ return { ok: false, code: 'model-missing', error: `model '${opts.modelId}' is not in the registry` };
596
+ if (model.enabled === false) {
597
+ return { ok: false, code: 'model-disabled', error: `model '${opts.modelId}' is disabled — enable it on the installed-models page first` };
598
+ }
599
+ try {
600
+ fs.statSync(model.filePath);
601
+ }
602
+ catch {
603
+ return { ok: false, code: 'file-missing', error: `model file is gone: ${model.filePath}` };
604
+ }
605
+ const engine = engineById(opts.engine);
606
+ if (!engine)
607
+ return { ok: false, code: 'unknown-engine', error: `unknown engine '${opts.engine}'` };
608
+ const runtime = engine.runtime;
609
+ if (!runtime)
610
+ return { ok: false, code: 'engine-not-launchable', error: `${engine.name} is install-only; the gateway cannot launch it` };
611
+ const meta = readGgufMeta(model.filePath);
612
+ const support = engineSupportFor(model.filePath, meta.ok ? meta : null, profilesOf(model));
613
+ const verdict = support.engines[engine.id];
614
+ if (!verdict?.serves) {
615
+ return { ok: false, code: 'engine-cannot-serve', error: verdict?.reason ?? `${engine.name} cannot serve this file` };
616
+ }
617
+ // Target resolution: the explicit pick, else the engine's only install,
618
+ // else the GPU-backed install when there is a choice.
619
+ const installs = Object.values(readInstalledEngines()).filter((r) => r.engine === engine.id);
620
+ const install = opts.target
621
+ ? installedEngineFor(engine.id, opts.target)
622
+ : installs.length === 1
623
+ ? installs[0]
624
+ : (installs.find((r) => r.target !== 'cpu') ?? installs[0] ?? null);
625
+ if (!install)
626
+ return { ok: false, code: 'engine-not-installed', error: `${engine.name} is not installed${opts.target ? ` for target '${opts.target}'` : ''}` };
627
+ const binary = pickBinary(install, engine);
628
+ if (!binary)
629
+ return { ok: false, code: 'binary-missing', error: `no server binary under ${install.installDir}` };
630
+ const options = { ...DEFAULT_RUN_OPTIONS, ...(opts.options ?? {}), extraArgs: [...(opts.options?.extraArgs ?? [])] };
631
+ const backend = backendOf(engine, install.target);
632
+ const profile = runtime.profile ? profileFor(model, engine.id) : undefined;
633
+ // A profile names paths outside the models root (a pack, a draft head, an
634
+ // expert binary). Reporting ALL missing ones up front beats one failed
635
+ // launch per typo — the runner never guesses an alternative.
636
+ if (runtime.profile && profile !== undefined) {
637
+ const missing = runtime.profile.paths(profile, model.filePath).filter((p) => {
638
+ try {
639
+ fs.statSync(p);
640
+ return false;
641
+ }
642
+ catch {
643
+ return true;
644
+ }
645
+ });
646
+ if (missing.length > 0) {
647
+ return { ok: false, code: 'profile-path-missing', error: `the ${engine.name} launch profile points at missing paths: ${missing.join(', ')}` };
648
+ }
649
+ }
650
+ let ctx;
651
+ let ngl;
652
+ if (runtime.placement === 'engine') {
653
+ // The engine owns placement: the layer planner is BYPASSED rather than
654
+ // faked (ADR-0044 §5). `ngl -1` = not applicable, which is how the
655
+ // console knows not to draw layer bars.
656
+ const fallback = meta.ok && meta.maxCtx ? Math.min(meta.maxCtx, LOCAL_DEFAULT_CTX) : LOCAL_DEFAULT_CTX;
657
+ ctx = runtime.resolveCtx
658
+ ? runtime.resolveCtx({ requested: options.ctx, profile, meta: meta.ok ? meta : null })
659
+ : fallback;
660
+ ngl = -1;
661
+ }
662
+ else {
663
+ // The launch parameters ARE the plan: the same estimator the console's
664
+ // automatic-layer-plan panel previewed resolves ctx and the GPU layer split
665
+ // here.
666
+ const detect = await detectDependencies();
667
+ const planInput = {
668
+ sizeBytes: model.size,
669
+ meta: meta.ok ? meta : null,
670
+ ...(detect.vramMb != null ? { vramMb: detect.vramMb } : {}),
671
+ ramBytes: os.totalmem(),
672
+ backend,
673
+ kvElemBytes: options.kvCacheQ8 ? KV_ELEM_Q8_0 : 2,
674
+ headroom: options.headroom,
675
+ };
676
+ ctx = options.ctx > 0 ? options.ctx : autoCtx(planInput);
677
+ const plan = planPlacement({ ...planInput, ctx });
678
+ ngl = options.ngl >= 0 ? options.ngl : nglForPlan(plan);
679
+ }
680
+ const port = await allocatePort();
681
+ // Loopback always, with no override (ADR-0044 §4). The engine is an upstream
682
+ // of the gateway, never a second public face: a LAN listener would be a second
683
+ // API surface with no routing, no quota, no breaker and no capture. Everything
684
+ // a client needs from a local model is served by the gateway port.
685
+ const host = '127.0.0.1';
686
+ const run = {
687
+ id: `run-${Date.now().toString(36)}-${(runSeq++).toString(36)}`,
688
+ modelId: model.id,
689
+ engine: engine.id,
690
+ target: install.target,
691
+ binary,
692
+ host,
693
+ port,
694
+ pid: null,
695
+ status: 'starting',
696
+ ctx,
697
+ ngl,
698
+ options,
699
+ startedAt: Date.now(),
700
+ restarts: 0,
701
+ apiPath: '/v1',
702
+ };
703
+ live.set(run.id, run);
704
+ persist(run);
705
+ appendRunLog(run.id, 'gateway', `launching ${engine.name} (${install.target}) — ${path.basename(model.filePath)}, ctx ${ctx}, ngl ${ngl >= 0 ? ngl : 'n/a'}`);
706
+ const spawned = await spawnFor(run, model.filePath);
707
+ if (!spawned.ok) {
708
+ run.status = 'failed';
709
+ run.lastErrorCode = 'spawn-failed';
710
+ run.lastError = spawned.error;
711
+ run.stoppedAt = Date.now();
712
+ persist(run);
713
+ releaseRun(run);
714
+ return { ok: false, code: 'spawn-failed', error: spawned.error };
715
+ }
716
+ return { ok: true, run };
717
+ }
718
+ /**
719
+ * The argv legs one launch spawns, as the engine's runtime builds them: the
720
+ * engine first, its auxiliary legs after. Returns the refusal text when the
721
+ * engine needs data it does not have rather than spawning something
722
+ * half-formed (ADR-0045).
723
+ */
724
+ export async function launchLegs(run, modelPath, model) {
725
+ const engine = engineById(run.engine);
726
+ if (!engine?.runtime)
727
+ return { error: `unknown engine '${run.engine}'` };
728
+ const vramMb = await machineVramMb();
729
+ return engine.runtime.legs({
730
+ runId: run.id,
731
+ modelPath,
732
+ profile: model ? profileFor(model, run.engine) : undefined,
733
+ ...(vramMb != null ? { vramMb } : {}),
734
+ // The operator's name, when set — the engine answers as it (ADR-0044 §7).
735
+ ...(model?.name?.trim() ? { servedName: model.name.trim() } : {}),
736
+ port: run.port,
737
+ host: run.host,
738
+ ctx: run.ctx,
739
+ ngl: run.ngl,
740
+ options: run.options,
741
+ backend: backendOf(engine, run.target),
742
+ target: run.target,
743
+ binary: run.binary,
744
+ },
745
+ // Auxiliary legs get their own port by the same allocator; reserving the
746
+ // engine's keeps two allocations in one tick from colliding.
747
+ { allocatePort: () => allocatePort(new Set([run.port])) });
748
+ }
749
+ /**
750
+ * Drain one child pipe into whole lines (an undrained pipe can block the
751
+ * child). Shared with the build supervisor (build-jobs.ts).
752
+ */
753
+ export function pipeChildLines(pipe, onLine) {
754
+ if (!pipe)
755
+ return;
756
+ let pending = '';
757
+ pipe.on('data', (chunk) => {
758
+ pending += typeof chunk === 'string' ? chunk : String(chunk);
759
+ const lines = pending.split(/\r?\n/);
760
+ pending = lines.pop() ?? '';
761
+ for (const line of lines)
762
+ onLine(line);
763
+ if (pending.length > 8192) {
764
+ onLine(pending);
765
+ pending = '';
766
+ }
767
+ });
768
+ }
769
+ function attachPipes(run, child, label) {
770
+ const attach = (pipe, stream) => {
771
+ pipeChildLines(pipe, (line) => appendRunLog(run.id, stream, label ? `[${label}] ${line}` : line));
772
+ };
773
+ attach(child.stdout, 'stdout');
774
+ attach(child.stderr, 'stderr');
775
+ }
776
+ async function spawnFor(run, modelPath) {
777
+ const spawnImpl = dep('spawnImpl') ?? ((cmd, args, o) => spawn(cmd, args, o));
778
+ const model = readInstalledModels()[run.modelId] ?? null;
779
+ const legs = await launchLegs(run, modelPath, model);
780
+ if (!Array.isArray(legs))
781
+ return { ok: false, error: legs.error };
782
+ const main = legs[0];
783
+ let child;
784
+ try {
785
+ child = spawnImpl(main.cmd, main.args, {
786
+ cwd: main.cwd,
787
+ detached: false,
788
+ // Piped so the run log drawer can show the engine's own words; both
789
+ // pipes are drained below, so a chatty engine never blocks on a full
790
+ // pipe buffer.
791
+ stdio: ['ignore', 'pipe', 'pipe'],
792
+ windowsHide: true,
793
+ shell: false,
794
+ });
795
+ }
796
+ catch (err) {
797
+ return { ok: false, error: err instanceof Error ? err.message : 'spawn failed' };
798
+ }
799
+ run.pid = child.pid ?? null;
800
+ persist(run);
801
+ if (run.pid)
802
+ appendRunLog(run.id, 'gateway', `process started (pid ${run.pid}, port ${run.port})`);
803
+ attachPipes(run, child);
804
+ const record = run;
805
+ child.on?.('error', (err) => {
806
+ appendRunLog(run.id, 'gateway', `spawn error: ${err.message}`);
807
+ run.status = 'failed';
808
+ run.lastErrorCode = 'spawn-failed';
809
+ run.lastError = err.message;
810
+ run.stoppedAt = Date.now();
811
+ children.delete(record.id);
812
+ persist(run);
813
+ releaseRun(run);
814
+ });
815
+ child.on?.('exit', (code) => {
816
+ children.delete(record.id);
817
+ appendRunLog(run.id, 'gateway', `process exited (code ${code ?? 'null'})`);
818
+ // Stop, load-timeout and spawn-error already closed the run. The exit that
819
+ // follows the kill must not restart it or rewrite a failure as a crash.
820
+ if (record.status === 'stopping' || record.status === 'stopped' || record.status === 'failed') {
821
+ if (record.status !== 'failed') {
822
+ record.status = 'stopped';
823
+ record.stoppedAt = record.stoppedAt ?? Date.now();
824
+ }
825
+ record.exitCode = code;
826
+ persist(record);
827
+ releaseRun(record);
828
+ return;
829
+ }
830
+ // Unexpected exit: crash. Restart within budget when asked to. The budget
831
+ // resets after a full restart window of continuous readiness — a server
832
+ // that ran for hours earns a fresh allowance.
833
+ record.exitCode = code;
834
+ const stableSince = record.readyAt ?? record.startedAt;
835
+ if (Date.now() - stableSince > LOCAL_RUN_RESTART_WINDOW_MS)
836
+ record.restarts = 0;
837
+ const restartable = record.options.autoRestart && record.restarts < LOCAL_RUN_MAX_RESTARTS;
838
+ if (restartable && code !== 0) {
839
+ record.restarts += 1;
840
+ record.status = 'starting';
841
+ // A restart is a NEW load, so the readiness window starts NOW. Without
842
+ // this the load-timeout guard in `listLocalRuns()` measures from the
843
+ // ORIGINAL launch: a model that had been serving for hours and then
844
+ // crashed is already past the 10-minute budget, so its freshly respawned
845
+ // engine is killed on the very next poll with "load timed out".
846
+ record.startedAt = Date.now();
847
+ record.readyAt = undefined;
848
+ record.lastErrorCode = 'crashed-restarting';
849
+ record.lastError = `crashed (exit ${code ?? 'null'}); restart ${record.restarts}/${LOCAL_RUN_MAX_RESTARTS}`;
850
+ persist(record);
851
+ appendRunLog(record.id, 'gateway', record.lastError);
852
+ setTimeout(() => {
853
+ if (record.status !== 'starting')
854
+ return;
855
+ const fail = (error) => {
856
+ if (record.status !== 'starting')
857
+ return;
858
+ record.status = 'failed';
859
+ record.lastErrorCode = 'spawn-failed';
860
+ record.lastError = error;
861
+ record.stoppedAt = Date.now();
862
+ persist(record);
863
+ releaseRun(record);
864
+ };
865
+ // `legs()` is engine code and may throw. An unhandled rejection here is
866
+ // fatal under Node's default policy, so the respawn always settles the
867
+ // row instead of leaving it `starting` until the hang guard fires.
868
+ void spawnFor(record, modelPathOf(record) ?? modelPath)
869
+ .then((spawned) => {
870
+ if (!spawned.ok)
871
+ fail(spawned.error);
872
+ })
873
+ .catch((err) => fail(err instanceof Error ? err.message : 'restart failed'));
874
+ }, 2000);
875
+ return;
876
+ }
877
+ record.status = 'failed';
878
+ record.lastErrorCode = 'engine-exited';
879
+ record.lastError = `engine exited (code ${code ?? 'null'})`;
880
+ record.stoppedAt = Date.now();
881
+ persist(record);
882
+ releaseRun(record);
883
+ });
884
+ if (child.pid)
885
+ children.set(record.id, child);
886
+ // Auxiliary legs: spawned AFTER the engine, and their failure is reported
887
+ // rather than fatal (ADR-0044 §4) — the engine is what answers chat.
888
+ for (const leg of legs.slice(1)) {
889
+ spawnAuxLeg(run, leg, spawnImpl);
890
+ }
891
+ return { ok: true };
892
+ }
893
+ function spawnAuxLeg(run, leg, spawnImpl) {
894
+ const label = leg.name ?? (leg.key.includes('#') ? leg.key.slice(leg.key.indexOf('#') + 1) : 'aux');
895
+ let child;
896
+ try {
897
+ child = spawnImpl(leg.cmd, leg.args, {
898
+ cwd: leg.cwd,
899
+ detached: false,
900
+ stdio: ['ignore', 'pipe', 'pipe'],
901
+ windowsHide: true,
902
+ shell: false,
903
+ });
904
+ }
905
+ catch (err) {
906
+ appendRunLog(run.id, 'gateway', `${label} leg failed to start: ${err instanceof Error ? err.message : 'spawn failed'}`);
907
+ return;
908
+ }
909
+ const entry = { name: label, pid: child.pid ?? null, ...(leg.port !== undefined ? { port: leg.port } : {}) };
910
+ run.aux = [...(run.aux ?? []).filter((aux) => aux.name !== label), entry];
911
+ persist(run);
912
+ appendRunLog(run.id, 'gateway', `${label} leg started (pid ${child.pid ?? '?'}, port ${leg.port ?? run.port})`);
913
+ attachPipes(run, child, label);
914
+ // Keyed by `${runId}#${label}`, the SAME key `stopLocalRun` looks up: the
915
+ // handle is what proves a recorded aux pid is still ours, so both sides must
916
+ // agree on where it lives.
917
+ const childKey = `${run.id}#${label}`;
918
+ child.on?.('error', (err) => {
919
+ appendRunLog(run.id, 'gateway', `${label} leg error: ${err.message}`);
920
+ children.delete(childKey);
921
+ });
922
+ child.on?.('exit', (code) => {
923
+ children.delete(childKey);
924
+ appendRunLog(run.id, 'gateway', `${label} leg exited (code ${code ?? 'null'}) — the engine keeps serving`);
925
+ run.aux = (run.aux ?? []).map((aux) => (aux.name === label ? { ...aux, pid: null } : aux));
926
+ persist(run);
927
+ });
928
+ if (child.pid)
929
+ children.set(childKey, child);
930
+ }
931
+ /** The model path a restart respawns with (the registry is re-read — a
932
+ * deleted model fails the restart instead of resurrecting a stale path). */
933
+ function modelPathOf(run) {
934
+ const model = readInstalledModels()[run.modelId];
935
+ return model?.filePath ?? null;
936
+ }
937
+ /* ------------------------------------------------------------------------- *
938
+ * Stop / status / boot sweep
939
+ * ------------------------------------------------------------------------- */
940
+ export function stopLocalRun(id) {
941
+ const run = live.get(id) ?? readRunRecords()[id];
942
+ if (!run)
943
+ return { ok: false, error: 'unknown run' };
944
+ if (run.status !== 'starting' && run.status !== 'ready')
945
+ return { ok: true };
946
+ run.status = 'stopping';
947
+ persist(run);
948
+ appendRunLog(run.id, 'gateway', 'stop requested');
949
+ // Auxiliary legs are SEPARATE processes (each with its own pid), so killing
950
+ // the engine's tree would leave them holding VRAM. Stop them first — if one
951
+ // hangs, the engine stop still proceeds.
952
+ for (const aux of run.aux ?? []) {
953
+ if (aux.pid == null)
954
+ continue;
955
+ // An adopted leg's pid may have been recycled by an unrelated process since
956
+ // the previous boot: kill only what a live child handle or the command line
957
+ // still proves is ours.
958
+ if (pidAlive(aux.pid) && pidVerdict(run, aux.pid) === 'ours')
959
+ killTree(aux.pid);
960
+ children.delete(`${run.id}#${aux.name}`);
961
+ }
962
+ if (run.aux?.length) {
963
+ run.aux = run.aux.map((aux) => ({ ...aux, pid: null }));
964
+ }
965
+ const pid = run.pid;
966
+ // A pid can be recycled the moment its process EXITS — including a child this
967
+ // process spawned whose exit was never observed (a hitched handle keeps the
968
+ // `children` entry). So the entry alone proves nothing; only a child Node still
969
+ // considers RUNNING does (a live child holds its pid). Anything else must have
970
+ // its command line verified before `taskkill /T` acts: killing a stranger's
971
+ // whole tree is unrecoverable, while closing the row without killing merely
972
+ // leaves a process the operator can still see in the OS.
973
+ if (pid != null && pidAlive(pid)) {
974
+ const verdict = pidVerdict(run, pid);
975
+ if (verdict === 'stranger') {
976
+ appendRunLog(run.id, 'gateway', `pid ${pid} no longer looks like this engine (the pid was reused by another process); the record is closed without killing it`);
977
+ }
978
+ else if (verdict === 'unverifiable') {
979
+ appendRunLog(run.id, 'gateway', 'could not read the process command line to confirm pid identity; leaving the process alone');
980
+ }
981
+ else if (!killTree(pid)) {
982
+ run.status = 'ready';
983
+ persist(run);
984
+ return { ok: false, error: `could not terminate pid ${pid}` };
985
+ }
986
+ }
987
+ run.pid = null;
988
+ run.status = 'stopped';
989
+ run.stoppedAt = Date.now();
990
+ children.delete(id);
991
+ persist(run);
992
+ releaseRun(run);
993
+ return { ok: true };
994
+ }
995
+ /**
996
+ * Readopt window: re-probe a run the boot sweep CLOSED as
997
+ * `gateway-restarted` while its engine might still be loading, and re-adopt
998
+ * it when the process is still alive.
999
+ *
1000
+ * It is throttled by id — the console's runs list polls every few seconds,
1001
+ * and each probe is an HTTP dial — so the per-id stamp makes one attempt per
1002
+ * interval no matter how many pollers read the list.
1003
+ */
1004
+ async function maybeReadoptClosedRun(record) {
1005
+ if (record.status !== 'failed' || record.lastErrorCode !== 'gateway-restarted' || record.pid == null)
1006
+ return null;
1007
+ const at = lastReadoptProbe.get(record.id);
1008
+ if (at !== undefined && Date.now() - at < (dep('readoptIntervalMs') ?? LOCAL_RUN_READOPT_INTERVAL_MS))
1009
+ return null;
1010
+ lastReadoptProbe.set(record.id, Date.now());
1011
+ const alive = pidAlive(record.pid);
1012
+ if (!alive)
1013
+ return null;
1014
+ // Same identity rule as the boot sweep: a recycled pid answers another
1015
+ // process's port, so a healthy dial alone must not make this row claim it.
1016
+ // A pid that is provably NOT ours is dropped here, not kept: otherwise every
1017
+ // interval pays a process-table probe for a row that can never be adopted, and
1018
+ // a later stop could still target it. The probe is ASYNC on purpose — this
1019
+ // runs on the console's 2 s runs poll, and a blocking `powershell` there would
1020
+ // stall every request the gateway is proxying.
1021
+ if ((await pidLooksLikeOurEngineAsync(record.pid)) !== true) {
1022
+ record.pid = null;
1023
+ persist(record);
1024
+ return null;
1025
+ }
1026
+ const healthy = await healthProbe(record.port);
1027
+ if (!healthy)
1028
+ return null;
1029
+ // The process survived and its endpoint answers — the previous verdict was
1030
+ // wrong, and the row was one boot sweep away from never being looked at
1031
+ // again. Re-adopt it.
1032
+ const fresh = {
1033
+ ...record,
1034
+ status: 'ready',
1035
+ startedAt: Date.now(),
1036
+ readyAt: Date.now(),
1037
+ stoppedAt: undefined,
1038
+ exitCode: undefined,
1039
+ lastErrorCode: undefined,
1040
+ lastError: undefined,
1041
+ };
1042
+ live.set(fresh.id, fresh);
1043
+ persist(fresh);
1044
+ appendRunLog(fresh.id, 'gateway', 're-adopted an engine process the previous boot sweep closed too early; serving again');
1045
+ return fresh;
1046
+ }
1047
+ /** List every run the gateway knows: live rows refreshed, dead ones from the
1048
+ * registry. Health is probed live for active rows (few, bounded timeout);
1049
+ * rows the boot sweep closed as `gateway-restarted` get a throttled
1050
+ * re-adoption probe (see `maybeReadoptClosedRun`). */
1051
+ export async function listLocalRuns() {
1052
+ const records = readRunRecords();
1053
+ const out = [];
1054
+ const seen = new Set();
1055
+ for (const run of live.values()) {
1056
+ seen.add(run.id);
1057
+ if (run.status === 'starting' || run.status === 'ready') {
1058
+ const alive = run.pid != null && pidAlive(run.pid);
1059
+ const healthy = alive && (await healthProbe(run.port));
1060
+ if (healthy && run.status === 'starting') {
1061
+ run.status = 'ready';
1062
+ run.readyAt = Date.now();
1063
+ persist(run);
1064
+ appendRunLog(run.id, 'gateway', `ready — http://${run.host}:${run.port}${run.apiPath} (loopback only; clients call the gateway)`);
1065
+ }
1066
+ else if (!alive && !children.has(run.id) && run.lastErrorCode !== 'crashed-restarting') {
1067
+ // Adopted rows have no exit handler. A spawned child still in
1068
+ // `children` is owned by that handler, and `crashed-restarting` is the
1069
+ // gap before the respawn — closing either would cancel a restart and
1070
+ // leave a failed row that delete treated as still live.
1071
+ run.status = run.status === 'starting' ? 'failed' : 'stopped';
1072
+ if (run.status === 'failed') {
1073
+ run.lastErrorCode = 'engine-died-before-ready';
1074
+ run.lastError = 'engine process died before becoming ready';
1075
+ }
1076
+ run.stoppedAt = Date.now();
1077
+ persist(run);
1078
+ releaseRun(run);
1079
+ }
1080
+ else if (run.status === 'starting' && alive && Date.now() - run.startedAt > (dep('readyTimeoutMs') ?? LOCAL_RUN_READY_TIMEOUT_MS)) {
1081
+ // Still loading past the hang guard: stop it rather than leave a silent
1082
+ // weight-loader holding RAM forever — but through the SAME identity gate
1083
+ // as the stop button. The health probe above awaited, so an adopted row
1084
+ // whose engine died in that window has had time to lose its pid to the
1085
+ // OS; `taskkill /T` on it would take a stranger's tree down.
1086
+ appendRunLog(run.id, 'gateway', 'load timed out; stopping the engine');
1087
+ if (run.pid != null) {
1088
+ const verdict = pidVerdict(run, run.pid);
1089
+ if (verdict === 'ours') {
1090
+ killTree(run.pid);
1091
+ }
1092
+ else {
1093
+ appendRunLog(run.id, 'gateway', verdict === 'stranger'
1094
+ ? `pid ${run.pid} no longer looks like this engine (the pid was reused); the run is closed without killing it`
1095
+ : 'could not read the process command line to confirm pid identity; leaving the process alone');
1096
+ }
1097
+ // Nothing may act on the pid from here: the row is closed, and a stale
1098
+ // pointer is what a later boot sweep would try to adopt.
1099
+ run.pid = null;
1100
+ }
1101
+ run.status = 'failed';
1102
+ run.lastErrorCode = 'load-timeout';
1103
+ run.lastError = `the engine did not become ready within ${Math.round((dep('readyTimeoutMs') ?? LOCAL_RUN_READY_TIMEOUT_MS) / 60000)} min`;
1104
+ run.stoppedAt = Date.now();
1105
+ persist(run);
1106
+ releaseRun(run);
1107
+ }
1108
+ }
1109
+ out.push(run);
1110
+ }
1111
+ for (const record of Object.values(records)) {
1112
+ const adopted = await maybeReadoptClosedRun(record);
1113
+ if (!seen.has(record.id)) {
1114
+ out.push(adopted ?? record);
1115
+ }
1116
+ else if (adopted) {
1117
+ // The id was already pushed as a stale live row — swap in the fresh
1118
+ // re-adopted view instead of listing the run twice.
1119
+ const idx = out.findIndex((row) => row.id === record.id);
1120
+ if (idx >= 0)
1121
+ out[idx] = adopted;
1122
+ }
1123
+ }
1124
+ return out.sort((a, b) => b.startedAt - a.startedAt);
1125
+ }
1126
+ /** The fixed ask and answer length of the console's "measure speed" button —
1127
+ * one shape for every model and engine, so two numbers are comparable. */
1128
+ const BENCHMARK_PROMPT = 'Explain how a rainbow forms in clear, simple language.';
1129
+ const BENCHMARK_MAX_TOKENS = 192;
1130
+ const BENCHMARK_TIMEOUT_MS = 180_000;
1131
+ /**
1132
+ * Measure one running model: a fixed prompt through the engine's own OpenAI
1133
+ * surface, the engine's `usage.completion_tokens` over wall time. The numbers
1134
+ * are the engine's, not an estimate — the plan panel's estimate and this
1135
+ * reading sit side by side on purpose.
1136
+ */
1137
+ export async function benchmarkLocalRun(id) {
1138
+ const run = await getLocalRun(id);
1139
+ if (!run)
1140
+ return { ok: false, code: 'unknown-run', error: `unknown run '${id}'` };
1141
+ if (run.status !== 'ready')
1142
+ return { ok: false, code: 'not-ready', error: 'the run is not ready yet' };
1143
+ const base = `http://${run.host}:${run.port}`;
1144
+ // The engine names its own model (the pack's name or the operator alias);
1145
+ // asking it beats re-deriving that name here.
1146
+ let model = '';
1147
+ try {
1148
+ const listed = await fetch(`${base}/v1/models`, { signal: AbortSignal.timeout(10_000) });
1149
+ const body = (await listed.json());
1150
+ model = body?.data?.[0]?.id ?? '';
1151
+ }
1152
+ catch {
1153
+ // A server without /v1/models still answers chat with an empty model.
1154
+ }
1155
+ const started = Date.now();
1156
+ try {
1157
+ const res = await fetch(`${base}/v1/chat/completions`, {
1158
+ method: 'POST',
1159
+ headers: { 'content-type': 'application/json' },
1160
+ signal: AbortSignal.timeout(BENCHMARK_TIMEOUT_MS),
1161
+ body: JSON.stringify({
1162
+ ...(model ? { model } : {}),
1163
+ messages: [{ role: 'user', content: BENCHMARK_PROMPT }],
1164
+ temperature: 0,
1165
+ max_tokens: BENCHMARK_MAX_TOKENS,
1166
+ stream: false,
1167
+ }),
1168
+ });
1169
+ const ms = Date.now() - started;
1170
+ if (!res.ok)
1171
+ return { ok: false, code: 'engine-error', error: `the engine answered HTTP ${res.status}` };
1172
+ const body = (await res.json());
1173
+ const tokens = Number(body?.usage?.completion_tokens) || 0;
1174
+ if (tokens <= 0)
1175
+ return { ok: false, code: 'no-tokens', error: 'the engine reported no completion tokens' };
1176
+ return { ok: true, result: { tokens, ms, tokPerSec: Math.round((tokens / Math.max(1, ms)) * 1000 * 10) / 10 } };
1177
+ }
1178
+ catch (err) {
1179
+ return { ok: false, code: 'benchmark-failed', error: err instanceof Error ? err.message : String(err) };
1180
+ }
1181
+ }
1182
+ /** One run's current view (detail polling). */
1183
+ export async function getLocalRun(id) {
1184
+ const rows = await listLocalRuns();
1185
+ return rows.find((row) => row.id === id) ?? null;
1186
+ }
1187
+ /**
1188
+ * Boot sweep: close records whose process is gone, adopt survivors only when
1189
+ * their pid AND command line prove they are still our engine (a recycled pid
1190
+ * belongs to a stranger). An adopted run — spawned by us or not — re-enters
1191
+ * `starting`, status polls re-probe readiness through the normal path (and the
1192
+ * ready-timeout hang guard), the log ring replays the snapshot the previous
1193
+ * process flushed (pipes for NEW engine output died with that process), and
1194
+ * stop still kills by pid after the same identity check.
1195
+ */
1196
+ export async function restoreLocalRuns() {
1197
+ const records = readRunRecords();
1198
+ let changed = false;
1199
+ for (const record of Object.values(records)) {
1200
+ if (record.status !== 'starting' && record.status !== 'ready' && record.status !== 'stopping')
1201
+ continue;
1202
+ const alive = record.pid != null && pidAlive(record.pid);
1203
+ // A pid this process did NOT spawn can have been recycled since the last
1204
+ // boot. Adopting a stranger would make the console claim — and later kill —
1205
+ // a process that is not ours, so the identity is checked before adoption.
1206
+ // `null` (the OS could not answer) is treated as "not provably ours".
1207
+ const identity = alive && record.pid != null ? pidLooksLikeOurEngine(record.pid) : false;
1208
+ if (alive && identity === true) {
1209
+ // ADOPT every surviving process. A process-level survivor is a running
1210
+ // engine; a boot-time health probe cannot prove it stopped working.
1211
+ // The case that previously killed it is a model that was still loading
1212
+ // when the gateway died: llama-server answers /health 503 while loading
1213
+ // and Strata's server.py does not even bind its port before the engine
1214
+ // is READY (ADR-0045 §12), so the endpoint is unreachable for minutes.
1215
+ // A ready row with a transiently deaf endpoint (busy queue, reconnect
1216
+ // hiccup) previously got a FINAL `gateway-restarted` tombstone over a
1217
+ // perfectly good server. In both cases the pid is the whole story: a
1218
+ // healthy survivor is adopted as starting, the readiness poll resumes,
1219
+ // and the ready-timeout hang guard watches the window.
1220
+ live.set(record.id, record);
1221
+ const wasReady = record.status === 'ready';
1222
+ record.status = 'starting';
1223
+ record.startedAt = Date.now();
1224
+ record.readyAt = undefined;
1225
+ if (record.lastErrorCode === 'gateway-restarted') {
1226
+ record.lastErrorCode = undefined;
1227
+ record.lastError = undefined;
1228
+ }
1229
+ lastReadoptProbe.delete(record.id);
1230
+ // Auxiliary legs have no children entry after a restart — trust the pid
1231
+ // probe, never a recorded one: a dead pid is cleared so stop does not
1232
+ // chase a recycled pid.
1233
+ const aux = record.aux ?? [];
1234
+ const deadAux = aux.filter((entry) => entry.pid != null && !pidAlive(entry.pid));
1235
+ if (deadAux.length > 0) {
1236
+ record.aux = aux.map((entry) => (entry.pid != null && !pidAlive(entry.pid) ? { ...entry, pid: null } : entry));
1237
+ }
1238
+ persist(record);
1239
+ appendRunLog(record.id, 'gateway', wasReady
1240
+ ? 'adopted a surviving engine process from the previous gateway run; probing until the endpoint answers'
1241
+ : 'adopted an engine process that survived the previous gateway run; it keeps loading and the run stays in `starting`');
1242
+ continue;
1243
+ }
1244
+ record.status = record.status === 'stopping' ? 'stopped' : 'failed';
1245
+ record.stoppedAt = record.stoppedAt ?? Date.now();
1246
+ // An alive pid that is NOT our engine was recycled by an unrelated process:
1247
+ // the record must not keep pointing at it (that is what a later stop or
1248
+ // restart would act on), so the pid is dropped with the tombstone.
1249
+ if (alive && identity !== true)
1250
+ record.pid = null;
1251
+ if (record.status === 'failed' && record.lastError === undefined) {
1252
+ record.lastErrorCode = 'gateway-restarted';
1253
+ record.lastError =
1254
+ alive && identity !== true
1255
+ ? 'gateway restarted while the engine was running (its pid now belongs to another process)'
1256
+ : 'gateway restarted while the engine was running';
1257
+ }
1258
+ records[record.id] = record;
1259
+ changed = true;
1260
+ }
1261
+ if (changed) {
1262
+ try {
1263
+ writeRunRecords(records);
1264
+ }
1265
+ catch {
1266
+ // A failed sweep write only leaves stale rows until the next boot.
1267
+ }
1268
+ }
1269
+ // Transcript retention runs at boot too: an install that was launched and
1270
+ // stopped many times while an old build kept every snapshot gets cleaned up
1271
+ // even if no run ends during this lifetime (ADR-0043 §5).
1272
+ sweepRunLogs();
1273
+ }
1274
+ /**
1275
+ * Synchronous teardown for the gateway's exit handler (next to
1276
+ * stopSpawnedMihomoSync): engines THIS process spawned are our children and
1277
+ * must not survive us. Adopted survivors have no entry in `children` and are
1278
+ * left alone.
1279
+ */
1280
+ /** The live run currently serving one registry model (newest wins), or null. */
1281
+ export function activeRunFor(modelId) {
1282
+ let best = null;
1283
+ for (const run of live.values()) {
1284
+ if (run.modelId !== modelId)
1285
+ continue;
1286
+ if (run.status !== 'ready' && run.status !== 'starting')
1287
+ continue;
1288
+ if (!best || run.startedAt > best.startedAt)
1289
+ best = run;
1290
+ }
1291
+ return best;
1292
+ }
1293
+ /** The name the local server answers as `model`, given the registry record.
1294
+ * The operator-chosen name wins (ADR-0044 §7); then an engine whose profile
1295
+ * owns the served name (Strata's `model_name`); otherwise the file stem is
1296
+ * the honest default. */
1297
+ export function servedNameFor(model) {
1298
+ const operator = model.name?.trim();
1299
+ if (operator)
1300
+ return operator;
1301
+ for (const engine of launchableEngines()) {
1302
+ const spec = engine.runtime?.profile;
1303
+ if (!spec?.servedName)
1304
+ continue;
1305
+ const profile = profileFor(model, engine.id);
1306
+ // A name only exists for a server that would actually serve the file: an
1307
+ // engine that cannot load it must not rename it in the catalog.
1308
+ const verdict = engine.runtime?.serves({ modelPath: model.filePath, meta: model.meta ? { ok: true, ...model.meta } : null, profile });
1309
+ if (!verdict?.serves)
1310
+ continue;
1311
+ const name = spec.servedName(profile, { modelPath: model.filePath });
1312
+ if (name)
1313
+ return name;
1314
+ }
1315
+ return path.basename(model.filePath).replace(/\.gguf$/i, '');
1316
+ }
1317
+ export function stopSpawnedLocalRunsSync() {
1318
+ flushAllRunLogsSync();
1319
+ for (const [id, child] of children) {
1320
+ const pid = child.pid ?? live.get(id)?.pid;
1321
+ if (pid == null)
1322
+ continue;
1323
+ try {
1324
+ if (pidAlive(pid))
1325
+ killTree(pid);
1326
+ }
1327
+ catch {
1328
+ // Best effort: the teardown must never wedge process exit.
1329
+ }
1330
+ }
1331
+ children.clear();
1332
+ }
1333
+ /** Prune ended records (the registry keeps them for the console's history
1334
+ * until the operator clears). Returns how many rows were dropped. */
1335
+ export function pruneLocalRuns() {
1336
+ const records = readRunRecords();
1337
+ let dropped = 0;
1338
+ for (const [id, record] of Object.entries(records)) {
1339
+ const resident = live.get(id);
1340
+ if (resident && runIsServing(resident))
1341
+ continue;
1342
+ if (record.status === 'stopped' || record.status === 'failed') {
1343
+ live.delete(id);
1344
+ delete records[id];
1345
+ forgetRunLog(id);
1346
+ dropped += 1;
1347
+ }
1348
+ }
1349
+ if (dropped > 0) {
1350
+ try {
1351
+ writeRunRecords(records);
1352
+ }
1353
+ catch {
1354
+ // Best effort.
1355
+ }
1356
+ }
1357
+ // Prune is also the operator's "clean the log directory" action: snapshots
1358
+ // whose record was dropped in an earlier session (or by a hand-edited
1359
+ // runs.json) are orphans and go with it.
1360
+ sweepRunLogs();
1361
+ return dropped;
1362
+ }
1363
+ /**
1364
+ * Drop ONE ended run record (history hygiene from the monitor board).
1365
+ *
1366
+ * Returns the same `code` + `error` pair as every other local/ mutation, and
1367
+ * refuses a LIVE run by name: deleting the record of a serving engine would
1368
+ * orphan its process (nothing would own the stop), so the operator must stop
1369
+ * it first. `not-found` is reported distinctly from success so the board can
1370
+ * drop a stale row without pretending it deleted something.
1371
+ */
1372
+ export function deleteLocalRun(id) {
1373
+ const resident = live.get(id);
1374
+ if (resident && runIsServing(resident)) {
1375
+ return { ok: false, code: 'run-live', error: 'the run is still live; stop it before deleting the record' };
1376
+ }
1377
+ if (resident)
1378
+ live.delete(id);
1379
+ const records = readRunRecords();
1380
+ const record = records[id];
1381
+ if (!record)
1382
+ return { ok: false, code: 'not-found', error: `no run record "${id}"` };
1383
+ delete records[id];
1384
+ forgetRunLog(id);
1385
+ try {
1386
+ writeRunRecords(records);
1387
+ }
1388
+ catch (err) {
1389
+ return { ok: false, code: 'persist-failed', error: err instanceof Error ? err.message : String(err) };
1390
+ }
1391
+ return { ok: true };
1392
+ }