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,637 @@
1
+ /**
2
+ * mihomo sidecar lifecycle (ADR-0022).
3
+ *
4
+ * The gateway owns the process it spawns: pid file + an `owner` marker
5
+ * (`spawned` vs `adopted`) live under `<env>/mihomo/`. A controller that is
6
+ * already healthy is adopted; one this gateway spawned — including an orphan
7
+ * left by a hard-killed previous gateway — stays BOUND to the current
8
+ * gateway's lifetime and is killed on its exit. Every failed start reaps the
9
+ * process it just spawned, so a refused start never leaks a deaf listener into
10
+ * the next one. When the run policy turns the core off, only a process this
11
+ * gateway spawned is stopped — an operator's own mihomo (`adopted`) is never
12
+ * touched.
13
+ *
14
+ * Run policy is `proxy.mihomo.autoStart`, NOT the outbound mode. The core is an
15
+ * independent capability: it can serve a manual-URL outbound setup (pre-warm
16
+ * subscriptions, probe nodes, offer its mixed port to other clients) and it can
17
+ * be stopped while `mode: mihomo` stays configured. When `autoStart` is absent
18
+ * the pre-split rule applies (`proxy.enabled && proxy.mode === 'mihomo'`), so
19
+ * existing configs behave exactly as before. A missing binary is reported
20
+ * (`binary-missing`); the download helper is opt-in and never runs at boot.
21
+ * Subscription URLs and the controller secret are never logged.
22
+ */
23
+ import crypto from 'node:crypto';
24
+ import { spawn, spawnSync } from 'node:child_process';
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+ import { getEnvRootDir } from '../config/env.js';
28
+ import { renameWithRetry } from '../utils/atomic-write.js';
29
+ import { loadConfig, saveConfig } from '../config/index.js';
30
+ import { DEFAULT_MIHOMO_CONTROLLER_PORT, DEFAULT_MIHOMO_GROUP, DEFAULT_MIHOMO_MIXED_PORT, } from '../config/defaults.js';
31
+ import { resolveMihomoBinary } from './mihomo-binary.js';
32
+ import { MihomoClient } from './mihomo-client.js';
33
+ import { mihomoConfigSummary, renderMihomoConfig } from './mihomo-config.js';
34
+ import { geoAssetsPresent, rulesNeedGeo } from './mihomo-geo.js';
35
+ import { appendMihomoCoreLog, attachMihomoCoreLog, clearMihomoCoreLogs } from './mihomo-logs.js';
36
+ const PROBE_TIMEOUT_MS = 1500;
37
+ const DEFAULT_READY_TIMEOUT_MS = 15_000;
38
+ const DEFAULT_POLL_INTERVAL_MS = 200;
39
+ let testDeps = null;
40
+ let queue = Promise.resolve();
41
+ let lastError = { error: null, code: null };
42
+ /** The child THIS process spawned and still owns. Only a pid in here is killed
43
+ * on gateway exit; an adopted (operator-owned) core has none. */
44
+ let spawnedPid = null;
45
+ /** mihomo's own words when a listener cannot take its port. */
46
+ const BIND_FAILURE_RE = /bind:|address already in use|Only one usage of each socket address/i;
47
+ export function setMihomoSidecarDepsForTests(deps) {
48
+ testDeps = deps;
49
+ lastError = { error: null, code: null };
50
+ spawnedPid = null;
51
+ clearMihomoCoreLogs();
52
+ }
53
+ function merged(extra) {
54
+ return { ...testDeps, ...extra };
55
+ }
56
+ function enqueue(fn) {
57
+ const run = queue.then(fn, fn);
58
+ queue = run.then(() => undefined, () => undefined);
59
+ return run;
60
+ }
61
+ export function mihomoWorkDir(deps) {
62
+ return deps?.workDir ?? path.join(getEnvRootDir(), 'mihomo');
63
+ }
64
+ function remember(error, code) {
65
+ lastError = { error, code };
66
+ }
67
+ function proxyOf(deps) {
68
+ return deps.config ?? loadConfig().proxy ?? {};
69
+ }
70
+ /**
71
+ * Should the core be running? Two axes are involved and they are NOT the same
72
+ * question: `proxy.mode` says where outbound traffic goes, `autoStart` says
73
+ * whether this process should exist. Only the latter is consulted here, so the
74
+ * core can run while outbound goes direct (and can be stopped while the mode
75
+ * still says mihomo — the console shows that mismatch rather than "fixing" it
76
+ * by restarting a process the operator just stopped).
77
+ *
78
+ * An absent `autoStart` falls back to the historical rule, which keeps every
79
+ * existing config byte-identical in behaviour.
80
+ */
81
+ function shouldRun(proxy) {
82
+ return proxy.mihomo?.autoStart ?? (proxy.enabled === true && proxy.mode === 'mihomo');
83
+ }
84
+ function portsOf(proxy) {
85
+ const mihomo = proxy.mihomo ?? {};
86
+ return {
87
+ mixed: mihomo.mixedPort ?? DEFAULT_MIHOMO_MIXED_PORT,
88
+ controller: mihomo.controllerPort ?? DEFAULT_MIHOMO_CONTROLLER_PORT,
89
+ group: mihomo.selectedGroup || DEFAULT_MIHOMO_GROUP,
90
+ secret: (mihomo.controllerSecret || '').trim(),
91
+ };
92
+ }
93
+ function newSecret() {
94
+ return crypto.randomBytes(24).toString('hex');
95
+ }
96
+ /** Persist a generated secret through the normal config writer. Never logs it. */
97
+ export function persistMihomoSecret(secret) {
98
+ const current = loadConfig();
99
+ const proxy = current.proxy ?? {};
100
+ if ((proxy.mihomo?.controllerSecret || '') === secret)
101
+ return;
102
+ saveConfig({
103
+ proxy: {
104
+ ...proxy,
105
+ mihomo: { ...(proxy.mihomo ?? {}), controllerSecret: secret },
106
+ },
107
+ });
108
+ }
109
+ function readPid(file) {
110
+ try {
111
+ const pid = Number(fs.readFileSync(file, 'utf8').trim());
112
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ }
118
+ function pidAlive(pid) {
119
+ try {
120
+ process.kill(pid, 0);
121
+ return true;
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ }
127
+ function writePid(file, pid) {
128
+ fs.mkdirSync(path.dirname(file), { recursive: true });
129
+ fs.writeFileSync(file, String(pid), 'utf8');
130
+ }
131
+ function ownerOf(dir) {
132
+ try {
133
+ const raw = fs.readFileSync(path.join(dir, 'owner'), 'utf8').trim();
134
+ return raw === 'spawned' || raw === 'adopted' ? raw : null;
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ function writeOwner(dir, owner) {
141
+ fs.mkdirSync(dir, { recursive: true });
142
+ fs.writeFileSync(path.join(dir, 'owner'), owner, 'utf8');
143
+ }
144
+ /** Markers describe a LIVE managed process; they leave with it. */
145
+ function removeMarkers(dir) {
146
+ for (const name of ['mihomo.pid', 'owner']) {
147
+ try {
148
+ fs.unlinkSync(path.join(dir, name));
149
+ }
150
+ catch { /* already gone */ }
151
+ }
152
+ }
153
+ async function probe(fetchImpl, port, secret) {
154
+ if (!secret)
155
+ return { ok: false, version: null };
156
+ try {
157
+ const res = await fetchImpl(`http://127.0.0.1:${port}/version`, {
158
+ headers: { Authorization: `Bearer ${secret}` },
159
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
160
+ });
161
+ if (!res.ok)
162
+ return { ok: false, version: null };
163
+ let version = null;
164
+ try {
165
+ const body = await res.json();
166
+ if (typeof body?.version === 'string' && body.version.trim())
167
+ version = body.version;
168
+ }
169
+ catch {
170
+ version = null;
171
+ }
172
+ return { ok: true, version };
173
+ }
174
+ catch {
175
+ return { ok: false, version: null };
176
+ }
177
+ }
178
+ function writeGeneratedConfig(dir, proxy, secret) {
179
+ const { mixed, controller, group } = portsOf(proxy);
180
+ const rendered = renderMihomoConfig({
181
+ mixedPort: mixed,
182
+ controllerPort: controller,
183
+ secret,
184
+ group,
185
+ routingMode: proxy.mihomo?.routingMode,
186
+ groupType: proxy.mihomo?.groupType,
187
+ groupInterval: proxy.mihomo?.groupInterval,
188
+ groupTolerance: proxy.mihomo?.groupTolerance,
189
+ testUrl: proxy.mihomo?.testUrl,
190
+ rules: proxy.mihomo?.rules ?? [],
191
+ subscriptions: proxy.mihomo?.subscriptions ?? [],
192
+ manualNodes: proxy.mihomo?.manualNodes ?? [],
193
+ });
194
+ fs.mkdirSync(path.join(dir, 'providers'), { recursive: true });
195
+ const yamlPath = path.join(dir, 'config.yaml');
196
+ const next = rendered.yaml;
197
+ let changed = true;
198
+ try {
199
+ changed = fs.readFileSync(yamlPath, 'utf8') !== next;
200
+ }
201
+ catch {
202
+ changed = true;
203
+ }
204
+ if (changed) {
205
+ // Atomic: the file carries the controller secret and subscription URLs, and
206
+ // mihomo parses it on reload — a torn write would fail the whole config.
207
+ const tmp = `${yamlPath}.tmp`;
208
+ fs.writeFileSync(tmp, next, 'utf8');
209
+ renameWithRetry(tmp, yamlPath);
210
+ }
211
+ return { yamlPath, summary: mihomoConfigSummary(rendered, { mixedPort: mixed, controllerPort: controller }), changed };
212
+ }
213
+ function ensureSecret(proxy, deps) {
214
+ const existing = (proxy.mihomo?.controllerSecret || '').trim();
215
+ if (existing)
216
+ return existing;
217
+ const secret = newSecret();
218
+ proxy.mihomo = { ...(proxy.mihomo ?? {}), controllerSecret: secret };
219
+ try {
220
+ (deps.persistSecret ?? persistMihomoSecret)(secret);
221
+ }
222
+ catch (err) {
223
+ const message = err instanceof Error ? err.message : 'persist failed';
224
+ console.warn(`[Clash] could not persist controller secret (${message})`);
225
+ }
226
+ return secret;
227
+ }
228
+ function clientFor(port, secret, fetchImpl) {
229
+ return new MihomoClient({ port, secret, fetchImpl, timeoutMs: 8000 });
230
+ }
231
+ /** How long a remembered selection is retried after the core comes up. A
232
+ * provider-backed node only exists once mihomo has fetched the subscription,
233
+ * which routinely finishes AFTER the controller answers /version; without the
234
+ * retry a restart silently leaves the group on its first member until the
235
+ * operator picks again. */
236
+ const SELECTION_WAIT_MS = 30_000;
237
+ const SELECTION_POLL_MS = 500;
238
+ /** One attempt: select the remembered node only when the group actually lists
239
+ * it. Returns false while the provider snapshot is still loading. */
240
+ async function trySelect(client, group, node) {
241
+ try {
242
+ const snapshot = await client.proxies();
243
+ if (!snapshot.proxies[group]?.all?.includes(node))
244
+ return false;
245
+ await client.select(group, node);
246
+ console.log(`[Clash] selected "${node}" in group "${group}"`);
247
+ return true;
248
+ }
249
+ catch {
250
+ return false;
251
+ }
252
+ }
253
+ /**
254
+ * Re-apply the operator's remembered node UNDER A MANUAL GROUP. The first
255
+ * attempt is awaited so an already-loaded group switches immediately (startup
256
+ * goes through the saved node, no operator action); a provider that is still
257
+ * downloading is retried in the BACKGROUND, because blocking boot on a slow
258
+ * subscription buys nothing. Never throws: a missing node just leaves the
259
+ * core's default in place.
260
+ *
261
+ * `url-test` / `fallback` are skipped on purpose: their choice belongs to the
262
+ * core, and `PUT /proxies/{group}` is `URLTest.Set` — a PIN. A pinned node wins
263
+ * inside mihomo's `URLTest.fast()` for as long as it stays alive, so restoring
264
+ * the remembered pick would silently freeze auto-switching until the pinned
265
+ * node died.
266
+ */
267
+ async function applySelection(proxy, port, secret, fetchImpl) {
268
+ if ((proxy.mihomo?.groupType ?? 'select') !== 'select')
269
+ return;
270
+ const group = proxy.mihomo?.selectedGroup || DEFAULT_MIHOMO_GROUP;
271
+ const node = proxy.mihomo?.selectedNodes?.[group];
272
+ if (!node)
273
+ return;
274
+ const client = clientFor(port, secret, fetchImpl);
275
+ if (await trySelect(client, group, node))
276
+ return;
277
+ void (async () => {
278
+ const deadline = Date.now() + SELECTION_WAIT_MS;
279
+ while (Date.now() < deadline) {
280
+ await new Promise((resolve) => setTimeout(resolve, SELECTION_POLL_MS));
281
+ if (await trySelect(client, group, node))
282
+ return;
283
+ }
284
+ console.warn(`[Clash] remembered node "${node}" is not in group "${group}"; leaving the core default`);
285
+ })();
286
+ }
287
+ function defaultSpawn(cmd, args, opts) {
288
+ return spawn(cmd, args, opts);
289
+ }
290
+ function defaultKill(pid) {
291
+ try {
292
+ if (process.platform === 'win32') {
293
+ const res = spawnSync('taskkill', ['/F', '/T', '/PID', String(pid)], { windowsHide: true });
294
+ return res.status === 0;
295
+ }
296
+ process.kill(pid, 'SIGTERM');
297
+ return true;
298
+ }
299
+ catch {
300
+ return false;
301
+ }
302
+ }
303
+ function defaultPidByPort(port) {
304
+ try {
305
+ if (process.platform === 'win32') {
306
+ const res = spawnSync('powershell', ['-NoProfile', '-Command', `(Get-NetTCPConnection -LocalPort ${port} -State Listen | Select-Object -First 1).OwningProcess`], { windowsHide: true, encoding: 'utf8' });
307
+ const pid = Number(res.stdout?.trim());
308
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
309
+ }
310
+ const res = spawnSync('lsof', ['-ti', `tcp:${port}`], { encoding: 'utf8' });
311
+ const pid = Number(res.stdout?.trim().split(/\r?\n/)[0]);
312
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
313
+ }
314
+ catch {
315
+ return null;
316
+ }
317
+ }
318
+ function fail(code, error) {
319
+ remember(error, code);
320
+ return { ok: false, action: 'noop', reused: false, pid: null, version: null, error, code };
321
+ }
322
+ async function startUnlocked(deps) {
323
+ const proxy = proxyOf(deps);
324
+ if (!shouldRun(proxy)) {
325
+ // Diagnostic only: the console renders this code ('disabled') through its own
326
+ // i18n table, so this English text is a log/debug fallback, never the toast.
327
+ // Reaching it means `autoStart` is false — the start route flips that flag
328
+ // before calling in, so a direct caller is the only way here.
329
+ return fail('disabled', 'the Clash core is marked stopped (proxy.mihomo.autoStart is false)');
330
+ }
331
+ const { mixed, controller } = portsOf(proxy);
332
+ if (mixed === controller)
333
+ return fail('port-collision', 'Clash mixedPort and controllerPort must differ');
334
+ const secret = ensureSecret(proxy, deps);
335
+ const dir = mihomoWorkDir(deps);
336
+ let written;
337
+ try {
338
+ written = writeGeneratedConfig(dir, proxy, secret);
339
+ }
340
+ catch (err) {
341
+ const message = err instanceof Error ? err.message : 'config write failed';
342
+ return fail('spawn-failed', `could not write the Clash config (${message})`);
343
+ }
344
+ const fetchImpl = deps.fetchImpl ?? fetch;
345
+ const pidFile = path.join(dir, 'mihomo.pid');
346
+ // GEOIP / GEOSITE rows make the core download its geo databases while parsing
347
+ // the config, and a failed download is fatal ("can't download MMDB"). The
348
+ // files are an explicit console action, so a missing pair stops the start /
349
+ // reload here with a code the console can explain, instead of a dead core.
350
+ if (rulesNeedGeo(proxy.mihomo?.rules) && !geoAssetsPresent(dir)) {
351
+ return fail('geo-missing', 'GEOIP/GEOSITE rules need the geo databases — download them in the Clash panel first');
352
+ }
353
+ const health = await probe(fetchImpl, controller, secret);
354
+ if (health.ok) {
355
+ if (written.changed) {
356
+ try {
357
+ await clientFor(controller, secret, fetchImpl).reloadConfig(written.yamlPath);
358
+ }
359
+ catch (err) {
360
+ const message = err instanceof Error ? err.message : 'reload failed';
361
+ return fail('reload-failed', `Clash config reload failed (${message})`);
362
+ }
363
+ }
364
+ const recorded = readPid(pidFile);
365
+ const owner = ownerOf(dir);
366
+ if (!owner)
367
+ writeOwner(dir, 'adopted');
368
+ else if (owner === 'spawned') {
369
+ // An orphan this gateway shape spawned (a previous gateway was hard-killed)
370
+ // is taken over: from here it is ours to kill on exit. Markers naming a
371
+ // DEAD pid are stale — the live core is not the recorded one, so it is an
372
+ // operator's core and the marker must say so.
373
+ if (recorded != null && pidAlive(recorded))
374
+ spawnedPid = recorded;
375
+ else
376
+ writeOwner(dir, 'adopted');
377
+ }
378
+ await applySelection(proxy, controller, secret, fetchImpl);
379
+ remember(null, null);
380
+ console.log(`[Clash] ${written.changed ? 'reloaded' : 'adopted'} ${written.summary}`);
381
+ return {
382
+ ok: true,
383
+ action: written.changed ? 'reload' : 'adopt',
384
+ reused: true,
385
+ pid: recorded && pidAlive(recorded) ? recorded : null,
386
+ version: health.version,
387
+ error: null,
388
+ code: null,
389
+ };
390
+ }
391
+ // A pid file outlives its process on purpose, but a recorded process that
392
+ // holds NEITHER port failed to bind: it answers nothing while making every
393
+ // later start collide. Reap it instead of stacking another listener on top —
394
+ // but only an orphan this gateway shape spawned. An operator's own core
395
+ // (`adopted`) is never killed, even when it looks deaf.
396
+ const recorded = readPid(pidFile);
397
+ if (ownerOf(dir) === 'spawned' && recorded != null && pidAlive(recorded)) {
398
+ const pidByPort = deps.pidByPortImpl ?? defaultPidByPort;
399
+ const holdsPort = pidByPort(mixed) === recorded || pidByPort(controller) === recorded;
400
+ if (!holdsPort) {
401
+ (deps.killTreeImpl ?? defaultKill)(recorded);
402
+ if (spawnedPid === recorded)
403
+ spawnedPid = null;
404
+ removeMarkers(dir);
405
+ appendMihomoCoreLog('gateway', `reaped unresponsive core (pid ${recorded})`);
406
+ }
407
+ }
408
+ const resolved = (deps.binaryResolver ?? resolveMihomoBinary)(proxy.mihomo?.binaryPath);
409
+ if (!resolved.path)
410
+ return fail('binary-missing', 'Clash core binary not found — install it or set proxy.mihomo.binaryPath');
411
+ const spawnImpl = deps.spawnImpl ?? defaultSpawn;
412
+ const spawnState = { error: null, exitCode: null };
413
+ let child;
414
+ try {
415
+ child = spawnImpl(resolved.path, ['-d', dir, '-f', written.yamlPath], {
416
+ cwd: dir,
417
+ detached: false,
418
+ // Piped so the core's own output can be captured (the Logs section);
419
+ // both pipes are drained immediately below, so a chatty core never
420
+ // blocks on a full pipe buffer.
421
+ stdio: ['ignore', 'pipe', 'pipe'],
422
+ windowsHide: true,
423
+ shell: false,
424
+ });
425
+ }
426
+ catch (err) {
427
+ const message = err instanceof Error ? err.message : 'spawn failed';
428
+ return fail('spawn-failed', `failed to spawn the Clash core (${message})`);
429
+ }
430
+ const captured = [];
431
+ attachMihomoCoreLog(child, (line) => {
432
+ captured.push(line);
433
+ if (captured.length > 40)
434
+ captured.shift();
435
+ });
436
+ const childPid = child.pid ?? null;
437
+ const reap = () => {
438
+ // A kill that failed leaves a LIVE process behind; its markers must stay so
439
+ // the next start's self-heal — or the exit teardown — can find it again.
440
+ const killed = childPid == null || (deps.killTreeImpl ?? defaultKill)(childPid);
441
+ if (!killed)
442
+ return;
443
+ if (childPid != null && childPid === spawnedPid)
444
+ spawnedPid = null;
445
+ // Only markers that name THIS child leave with it — a pre-existing core's
446
+ // markers are not ours to delete.
447
+ if (childPid != null && readPid(pidFile) === childPid)
448
+ removeMarkers(dir);
449
+ };
450
+ /** mihomo's bind refusal is the useful diagnosis whenever the core dies. */
451
+ const bindFailure = () => {
452
+ const bind = captured.find((line) => BIND_FAILURE_RE.test(line));
453
+ if (!bind)
454
+ return null;
455
+ const port = /:(\d{2,5})\b/.exec(bind)?.[1] ?? null;
456
+ return fail('port-in-use', `the Clash core could not bind ${port ? `127.0.0.1:${port}` : 'its ports'} — another program is holding it`);
457
+ };
458
+ child.on?.('error', (err) => {
459
+ spawnState.error = err;
460
+ appendMihomoCoreLog('gateway', `spawn error: ${err.message}`);
461
+ });
462
+ child.on?.('exit', (code) => {
463
+ spawnState.exitCode = code;
464
+ appendMihomoCoreLog('gateway', `core process exited (code ${code ?? 'null'})`);
465
+ // Markers describe a live managed process; a core that exited on its own
466
+ // leaves nothing to manage (the log line above is the evidence).
467
+ if (child.pid != null && readPid(pidFile) === child.pid) {
468
+ removeMarkers(dir);
469
+ if (spawnedPid === child.pid)
470
+ spawnedPid = null;
471
+ }
472
+ });
473
+ child.unref?.();
474
+ if (child.pid) {
475
+ writePid(pidFile, child.pid);
476
+ writeOwner(dir, 'spawned');
477
+ spawnedPid = child.pid;
478
+ appendMihomoCoreLog('gateway', `core process started (pid ${child.pid})`);
479
+ }
480
+ const readyTimeoutMs = deps.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
481
+ const pollIntervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
482
+ const deadline = Date.now() + readyTimeoutMs;
483
+ for (;;) {
484
+ if (spawnState.error) {
485
+ const code = spawnState.error.code;
486
+ reap();
487
+ return bindFailure()
488
+ ?? fail('spawn-exited', `the Clash core exited immediately (${spawnState.error.message}${code ? ` [${code}]` : ''})`);
489
+ }
490
+ if (spawnState.exitCode !== null) {
491
+ reap();
492
+ return bindFailure() ?? fail('spawn-exited', `the Clash core exited immediately (code ${spawnState.exitCode})`);
493
+ }
494
+ const again = await probe(fetchImpl, controller, secret);
495
+ if (again.ok) {
496
+ await applySelection(proxy, controller, secret, fetchImpl);
497
+ remember(null, null);
498
+ console.log(`[Clash] started ${written.summary}${child.pid ? ` pid=${child.pid}` : ''}`);
499
+ return { ok: true, action: 'start', reused: false, pid: child.pid ?? null, version: again.version, error: null, code: null };
500
+ }
501
+ if (Date.now() >= deadline) {
502
+ // The core's own words decide the code: a listener that could not take
503
+ // its port is a configuration/ownership conflict, not a slow start.
504
+ reap();
505
+ return bindFailure()
506
+ ?? fail('not-ready', `the Clash core did not become ready within ${Math.round(readyTimeoutMs / 1000)}s`);
507
+ }
508
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
509
+ }
510
+ }
511
+ async function stopUnlocked(deps, onlySpawned) {
512
+ const proxy = proxyOf(deps);
513
+ const { controller } = portsOf(proxy);
514
+ const dir = mihomoWorkDir(deps);
515
+ const pidFile = path.join(dir, 'mihomo.pid');
516
+ const recorded = readPid(pidFile);
517
+ const owner = ownerOf(dir);
518
+ if (onlySpawned && owner !== 'spawned') {
519
+ return { ok: true, action: 'noop', reused: false, pid: null, version: null, error: null, code: null };
520
+ }
521
+ const kill = deps.killTreeImpl ?? defaultKill;
522
+ let pid = recorded && pidAlive(recorded) ? recorded : null;
523
+ if (pid == null && !onlySpawned) {
524
+ const fetchImpl = deps.fetchImpl ?? fetch;
525
+ const secret = (proxy.mihomo?.controllerSecret || '').trim();
526
+ const health = await probe(fetchImpl, controller, secret);
527
+ if (health.ok) {
528
+ pid = (deps.pidByPortImpl ?? defaultPidByPort)(controller);
529
+ if (pid == null)
530
+ return fail('pid-unknown', 'the Clash core is listening but its pid could not be identified');
531
+ }
532
+ }
533
+ if (pid == null) {
534
+ removeMarkers(dir);
535
+ spawnedPid = null;
536
+ remember(null, null);
537
+ return { ok: true, action: 'noop', reused: false, pid: null, version: null, error: null, code: null };
538
+ }
539
+ if (!kill(pid))
540
+ return fail('kill-failed', `failed to terminate the Clash core process ${pid}`);
541
+ removeMarkers(dir);
542
+ spawnedPid = null;
543
+ remember(null, null);
544
+ console.log(`[Clash] stopped pid=${pid}`);
545
+ return { ok: true, action: 'stop', reused: false, pid, version: null, error: null, code: null };
546
+ }
547
+ /**
548
+ * Synchronous teardown for the gateway's own exit handlers (ADR-0022): a core
549
+ * this process spawned is OUR child and must not survive the process that owns
550
+ * it. `process.on('exit')` allows only synchronous work, and the Windows kill
551
+ * is already `taskkill` via spawnSync — so this is the one place that is safe
552
+ * there. An adopted (operator-owned) core never has an entry here and is left
553
+ * running; a hard-killed gateway cannot run any handler, and the next boot
554
+ * adopts the survivor (taking ownership) or reaps it if it holds no port.
555
+ */
556
+ export function stopSpawnedMihomoSync(kill = defaultKill) {
557
+ const pid = spawnedPid;
558
+ spawnedPid = null;
559
+ if (pid == null || !pidAlive(pid))
560
+ return;
561
+ // The markers are the ownership record: a pid they no longer name has been
562
+ // replaced (or reused by an unrelated process) since we spawned it.
563
+ const dir = mihomoWorkDir();
564
+ const recorded = readPid(path.join(dir, 'mihomo.pid'));
565
+ if (recorded != null && recorded !== pid)
566
+ return;
567
+ try {
568
+ if (kill(pid) && recorded === pid)
569
+ removeMarkers(dir);
570
+ }
571
+ catch {
572
+ // Best effort: the teardown must never wedge process exit.
573
+ }
574
+ }
575
+ export function getMihomoStatus(extra) {
576
+ const deps = merged(extra);
577
+ const proxy = proxyOf(deps);
578
+ const { mixed, controller, secret } = portsOf(proxy);
579
+ const resolved = (deps.binaryResolver ?? resolveMihomoBinary)(proxy.mihomo?.binaryPath);
580
+ const dir = mihomoWorkDir(deps);
581
+ const recorded = readPid(path.join(dir, 'mihomo.pid'));
582
+ const alive = recorded != null && pidAlive(recorded);
583
+ const owner = ownerOf(dir);
584
+ return probe(deps.fetchImpl ?? fetch, controller, secret).then((health) => ({
585
+ installed: resolved.path != null,
586
+ binaryPath: resolved.path,
587
+ running: health.ok,
588
+ managed: owner === 'spawned' && alive,
589
+ adopted: owner === 'adopted' && (health.ok || alive),
590
+ pid: alive ? recorded : null,
591
+ mode: proxy.mode === 'mihomo' ? 'mihomo' : 'manual',
592
+ /** The outbound master switch — what `proxy.enabled` means, unchanged. */
593
+ enabled: proxy.enabled === true,
594
+ /** Whether the core is SUPPOSED to be running (same rule as `shouldRun`).
595
+ * Distinct from `running`, which is what the controller actually answers. */
596
+ autoStart: proxy.mihomo?.autoStart ?? (proxy.enabled === true && proxy.mode === 'mihomo'),
597
+ mixedPort: mixed,
598
+ controllerPort: controller,
599
+ secretConfigured: secret.length > 0,
600
+ version: health.version,
601
+ error: lastError.error,
602
+ code: lastError.code,
603
+ }));
604
+ }
605
+ export function startMihomoSidecar(extra) {
606
+ const deps = merged(extra);
607
+ return enqueue(() => startUnlocked(deps));
608
+ }
609
+ export function stopMihomoSidecar(extra) {
610
+ const deps = merged(extra);
611
+ return enqueue(() => stopUnlocked(deps, false));
612
+ }
613
+ export function restartMihomoSidecar(extra) {
614
+ const deps = merged(extra);
615
+ return enqueue(async () => {
616
+ const stopped = await stopUnlocked(deps, false);
617
+ if (!stopped.ok)
618
+ return stopped;
619
+ return startUnlocked(deps);
620
+ });
621
+ }
622
+ /**
623
+ * Bring the sidecar in line with the saved proxy section.
624
+ * Runs at boot and after a config save. Never throws.
625
+ */
626
+ export async function reconcileMihomoSidecar(proxy, extra) {
627
+ const deps = merged({ ...extra, ...(proxy ? { config: proxy } : {}) });
628
+ const current = proxyOf(deps);
629
+ if (!shouldRun(current)) {
630
+ return enqueue(() => stopUnlocked(deps, true));
631
+ }
632
+ return startMihomoSidecar(deps);
633
+ }
634
+ /** Test-only: the last log-safe failure, so suites can assert the secret stayed out of it. */
635
+ export function mihomoLastErrorForTests() {
636
+ return lastError;
637
+ }