omnicell-router 0.7.0 → 0.8.2

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 (246) hide show
  1. package/backend/dist/cli/clients/activity.d.ts +35 -0
  2. package/backend/dist/cli/clients/activity.js +67 -0
  3. package/backend/dist/cli/clients/base.d.ts +13 -2
  4. package/backend/dist/cli/clients/claude.d.ts +2 -2
  5. package/backend/dist/cli/clients/codex.d.ts +2 -2
  6. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  7. package/backend/dist/cli/clients/core-adapters.js +3 -4
  8. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  9. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  10. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  11. package/backend/dist/cli/clients/grok.d.ts +2 -2
  12. package/backend/dist/cli/clients/index.d.ts +8 -1
  13. package/backend/dist/cli/clients/index.js +55 -21
  14. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  15. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  16. package/backend/dist/cli/clients/model-meta.js +1 -1
  17. package/backend/dist/cli/clients/omp.d.ts +2 -2
  18. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  19. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  20. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  21. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  22. package/backend/dist/cli/clients/pi.d.ts +2 -2
  23. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  24. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  25. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  26. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  27. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  28. package/backend/dist/cli/clients/reserved.js +2 -0
  29. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  30. package/backend/dist/cli/index.js +60 -9
  31. package/backend/dist/cli/types.d.ts +29 -8
  32. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  33. package/backend/dist/config/comments-en.js +6 -12
  34. package/backend/dist/config/comments-zh.js +6 -12
  35. package/backend/dist/config/defaults.d.ts +56 -1
  36. package/backend/dist/config/defaults.js +68 -0
  37. package/backend/dist/config/index.d.ts +9 -2
  38. package/backend/dist/config/index.js +26 -3
  39. package/backend/dist/config/types.d.ts +55 -43
  40. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  41. package/backend/dist/forward-proxy/egress.js +42 -4
  42. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  43. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  44. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  45. package/backend/dist/forward-proxy/rules.js +61 -14
  46. package/backend/dist/forward-proxy/server.js +226 -77
  47. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  48. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  49. package/backend/dist/harness/common/market.d.ts +3 -3
  50. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  55. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  57. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  66. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  67. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  68. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  69. package/backend/dist/harness/translation.js +64 -21
  70. package/backend/dist/harness/types.d.ts +1 -1
  71. package/backend/dist/harness/types.js +1 -1
  72. package/backend/dist/index.js +31 -18
  73. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  74. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  75. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  76. package/backend/dist/ir/adapters/anthropic.js +788 -0
  77. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  78. package/backend/dist/ir/adapters/chat.js +602 -0
  79. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  80. package/backend/dist/ir/adapters/google-stream.js +242 -0
  81. package/backend/dist/ir/adapters/google.d.ts +9 -0
  82. package/backend/dist/ir/adapters/google.js +317 -0
  83. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  84. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  85. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  86. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  87. package/backend/dist/ir/adapters/responses-output.js +348 -0
  88. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  89. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  90. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  91. package/backend/dist/ir/adapters/responses.js +646 -0
  92. package/backend/dist/ir/errors.d.ts +2 -2
  93. package/backend/dist/ir/types.d.ts +2 -1
  94. package/backend/dist/metrics/request-cost.d.ts +11 -2
  95. package/backend/dist/metrics/request-cost.js +12 -3
  96. package/backend/dist/observability/request-identity.d.ts +1 -1
  97. package/backend/dist/observability/trace-id.d.ts +40 -0
  98. package/backend/dist/observability/trace-id.js +134 -0
  99. package/backend/dist/observability/upstream-events.d.ts +82 -60
  100. package/backend/dist/observability/upstream-events.js +142 -67
  101. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  102. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  103. package/backend/dist/opencode/probe.d.ts +24 -1
  104. package/backend/dist/opencode/probe.js +28 -4
  105. package/backend/dist/opencode/user-config.d.ts +5 -0
  106. package/backend/dist/pipeline/directives.d.ts +6 -2
  107. package/backend/dist/pipeline/directives.js +7 -3
  108. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  109. package/backend/dist/pipeline/orchestrator.js +220 -194
  110. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  111. package/backend/dist/pipeline/unresolved-model.js +43 -0
  112. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  113. package/backend/dist/plugins/catalog-def.js +177 -0
  114. package/backend/dist/plugins/gateways.d.ts +62 -3
  115. package/backend/dist/plugins/gateways.js +139 -2
  116. package/backend/dist/plugins/host.d.ts +42 -5
  117. package/backend/dist/plugins/host.js +454 -38
  118. package/backend/dist/plugins/manifest.d.ts +119 -10
  119. package/backend/dist/plugins/manifest.js +265 -14
  120. package/backend/dist/plugins/pack.js +26 -0
  121. package/backend/dist/plugins/types.d.ts +187 -21
  122. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  123. package/backend/dist/protocols/systemone/convert.js +6 -1
  124. package/backend/dist/protocols/systemone/decide.js +18 -8
  125. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  126. package/backend/dist/providers/anthropic-messages.js +53 -0
  127. package/backend/dist/providers/anthropic.d.ts +7 -8
  128. package/backend/dist/providers/anthropic.js +36 -324
  129. package/backend/dist/providers/base.d.ts +14 -2
  130. package/backend/dist/providers/boot-direct.js +68 -38
  131. package/backend/dist/providers/dispatch.d.ts +5 -19
  132. package/backend/dist/providers/dispatch.js +46 -58
  133. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  134. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  135. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  136. package/backend/dist/providers/executors/dispatch.js +39 -9
  137. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  138. package/backend/dist/providers/executors/google-gemini.js +3 -0
  139. package/backend/dist/providers/executors/http-stream.js +16 -3
  140. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-chat.js +3 -0
  142. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  143. package/backend/dist/providers/executors/openai-responses.js +3 -0
  144. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  145. package/backend/dist/providers/google-gemini.d.ts +12 -0
  146. package/backend/dist/providers/google-gemini.js +50 -0
  147. package/backend/dist/providers/google.d.ts +7 -8
  148. package/backend/dist/providers/google.js +35 -308
  149. package/backend/dist/providers/http-json.d.ts +19 -0
  150. package/backend/dist/providers/http-json.js +104 -0
  151. package/backend/dist/providers/http-stream.d.ts +52 -0
  152. package/backend/dist/providers/http-stream.js +423 -0
  153. package/backend/dist/providers/member-match.d.ts +4 -5
  154. package/backend/dist/providers/member-match.js +4 -5
  155. package/backend/dist/providers/openai-chat.d.ts +13 -0
  156. package/backend/dist/providers/openai-chat.js +99 -0
  157. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  158. package/backend/dist/providers/openai-compatible.js +71 -368
  159. package/backend/dist/providers/openai-responses.d.ts +12 -0
  160. package/backend/dist/providers/openai-responses.js +68 -0
  161. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  162. package/backend/dist/providers/opencode-proxy.js +49 -125
  163. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  164. package/backend/dist/providers/plugin-adapter.js +31 -0
  165. package/backend/dist/providers/registry.d.ts +49 -24
  166. package/backend/dist/providers/registry.js +97 -55
  167. package/backend/dist/providers/responses.d.ts +7 -28
  168. package/backend/dist/providers/responses.js +45 -253
  169. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  170. package/backend/dist/providers/tool-markup-leak.js +57 -0
  171. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  172. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  173. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  174. package/backend/dist/providers/virtual-meta.js +49 -9
  175. package/backend/dist/proxy/asset-download.d.ts +54 -0
  176. package/backend/dist/proxy/asset-download.js +420 -0
  177. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  178. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  179. package/backend/dist/proxy/mihomo-binary.js +62 -51
  180. package/backend/dist/proxy/mihomo-client.js +15 -1
  181. package/backend/dist/proxy/mihomo-config.js +11 -2
  182. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  183. package/backend/dist/proxy/mihomo-geo.js +213 -0
  184. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  185. package/backend/dist/proxy/mihomo-logs.js +70 -0
  186. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  187. package/backend/dist/proxy/mihomo-pac.js +15 -0
  188. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  189. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  190. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  191. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  192. package/backend/dist/quota/adapters/minimax.js +36 -13
  193. package/backend/dist/quota/cli-login.d.ts +8 -0
  194. package/backend/dist/quota/cli-login.js +18 -0
  195. package/backend/dist/quota/declarations.js +10 -0
  196. package/backend/dist/quota/dsl.js +18 -5
  197. package/backend/dist/quota/engine.d.ts +22 -1
  198. package/backend/dist/quota/engine.js +170 -29
  199. package/backend/dist/quota/prober.d.ts +5 -0
  200. package/backend/dist/quota/prober.js +11 -2
  201. package/backend/dist/quota/types.d.ts +87 -8
  202. package/backend/dist/quota/verdict.d.ts +35 -0
  203. package/backend/dist/quota/verdict.js +135 -0
  204. package/backend/dist/ratelimit/admission.d.ts +131 -0
  205. package/backend/dist/ratelimit/admission.js +233 -0
  206. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  207. package/backend/dist/resilience/types.d.ts +2 -2
  208. package/backend/dist/router/layer2-decision.d.ts +1 -1
  209. package/backend/dist/router/layer2-decision.js +5 -8
  210. package/backend/dist/routes/console.js +248 -52
  211. package/backend/dist/routes/mihomo.d.ts +2 -0
  212. package/backend/dist/routes/mihomo.js +334 -29
  213. package/backend/dist/routes/responses.d.ts +87 -8
  214. package/backend/dist/routes/responses.js +314 -33
  215. package/backend/dist/server.js +34 -6
  216. package/backend/dist/session/session-manager.d.ts +6 -0
  217. package/backend/dist/session/session-manager.js +20 -9
  218. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  219. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  220. package/backend/dist/surfaces/chat.js +15 -0
  221. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  222. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  223. package/backend/dist/surfaces/direct-forward.js +206 -0
  224. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  225. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  226. package/backend/dist/surfaces/types.d.ts +11 -0
  227. package/backend/dist/trace/tracker.d.ts +32 -1
  228. package/backend/dist/trace/tracker.js +29 -4
  229. package/backend/dist/types/router.d.ts +34 -12
  230. package/backend/dist/types/router.js +35 -6
  231. package/backend/dist/utils/chat-stream.d.ts +21 -8
  232. package/backend/dist/utils/chat-stream.js +46 -9
  233. package/backend/dist/utils/event-ring.d.ts +4 -0
  234. package/backend/dist/utils/event-ring.js +4 -0
  235. package/backend/dist/utils/popularity.js +29 -4
  236. package/backend/dist/utils/proxy.d.ts +7 -0
  237. package/backend/dist/utils/proxy.js +35 -10
  238. package/backend/dist/utils/retry-after.d.ts +21 -0
  239. package/backend/dist/utils/retry-after.js +36 -0
  240. package/bin/ocr.js +2 -2
  241. package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
  242. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  243. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  244. package/frontend/dist/index.html +2 -2
  245. package/package.json +1 -1
  246. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -3,9 +3,13 @@
3
3
  *
4
4
  * The gateway owns the process it spawns: pid file + an `owner` marker
5
5
  * (`spawned` vs `adopted`) live under `<env>/mihomo/`. A controller that is
6
- * already healthy is adopted and left running. Explicit stop kills a local
7
- * listener either way. When the run policy turns the core off, only a process
8
- * this gateway spawned is stopped — an operator's own mihomo is not touched.
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.
9
13
  *
10
14
  * Run policy is `proxy.mihomo.autoStart`, NOT the outbound mode. The core is an
11
15
  * independent capability: it can serve a manual-URL outbound setup (pre-warm
@@ -27,15 +31,24 @@ import { DEFAULT_MIHOMO_CONTROLLER_PORT, DEFAULT_MIHOMO_GROUP, DEFAULT_MIHOMO_MI
27
31
  import { resolveMihomoBinary } from './mihomo-binary.js';
28
32
  import { MihomoClient } from './mihomo-client.js';
29
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';
30
36
  const PROBE_TIMEOUT_MS = 1500;
31
37
  const DEFAULT_READY_TIMEOUT_MS = 15_000;
32
38
  const DEFAULT_POLL_INTERVAL_MS = 200;
33
39
  let testDeps = null;
34
40
  let queue = Promise.resolve();
35
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;
36
47
  export function setMihomoSidecarDepsForTests(deps) {
37
48
  testDeps = deps;
38
49
  lastError = { error: null, code: null };
50
+ spawnedPid = null;
51
+ clearMihomoCoreLogs();
39
52
  }
40
53
  function merged(extra) {
41
54
  return { ...testDeps, ...extra };
@@ -128,6 +141,15 @@ function writeOwner(dir, owner) {
128
141
  fs.mkdirSync(dir, { recursive: true });
129
142
  fs.writeFileSync(path.join(dir, 'owner'), owner, 'utf8');
130
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
+ }
131
153
  async function probe(fetchImpl, port, secret) {
132
154
  if (!secret)
133
155
  return { ok: false, version: null };
@@ -320,6 +342,14 @@ async function startUnlocked(deps) {
320
342
  return fail('spawn-failed', `could not write the Clash config (${message})`);
321
343
  }
322
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
+ }
323
353
  const health = await probe(fetchImpl, controller, secret);
324
354
  if (health.ok) {
325
355
  if (written.changed) {
@@ -331,10 +361,20 @@ async function startUnlocked(deps) {
331
361
  return fail('reload-failed', `Clash config reload failed (${message})`);
332
362
  }
333
363
  }
334
- const pidFile = path.join(dir, 'mihomo.pid');
335
364
  const recorded = readPid(pidFile);
336
- if (!ownerOf(dir))
365
+ const owner = ownerOf(dir);
366
+ if (!owner)
337
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
+ }
338
378
  await applySelection(proxy, controller, secret, fetchImpl);
339
379
  remember(null, null);
340
380
  console.log(`[Clash] ${written.changed ? 'reloaded' : 'adopted'} ${written.summary}`);
@@ -348,6 +388,23 @@ async function startUnlocked(deps) {
348
388
  code: null,
349
389
  };
350
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
+ }
351
408
  const resolved = (deps.binaryResolver ?? resolveMihomoBinary)(proxy.mihomo?.binaryPath);
352
409
  if (!resolved.path)
353
410
  return fail('binary-missing', 'Clash core binary not found — install it or set proxy.mihomo.binaryPath');
@@ -358,7 +415,10 @@ async function startUnlocked(deps) {
358
415
  child = spawnImpl(resolved.path, ['-d', dir, '-f', written.yamlPath], {
359
416
  cwd: dir,
360
417
  detached: false,
361
- stdio: 'ignore',
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'],
362
422
  windowsHide: true,
363
423
  shell: false,
364
424
  });
@@ -367,16 +427,55 @@ async function startUnlocked(deps) {
367
427
  const message = err instanceof Error ? err.message : 'spawn failed';
368
428
  return fail('spawn-failed', `failed to spawn the Clash core (${message})`);
369
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
+ };
370
458
  child.on?.('error', (err) => {
371
459
  spawnState.error = err;
460
+ appendMihomoCoreLog('gateway', `spawn error: ${err.message}`);
372
461
  });
373
462
  child.on?.('exit', (code) => {
374
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
+ }
375
472
  });
376
473
  child.unref?.();
377
474
  if (child.pid) {
378
- writePid(path.join(dir, 'mihomo.pid'), child.pid);
475
+ writePid(pidFile, child.pid);
379
476
  writeOwner(dir, 'spawned');
477
+ spawnedPid = child.pid;
478
+ appendMihomoCoreLog('gateway', `core process started (pid ${child.pid})`);
380
479
  }
381
480
  const readyTimeoutMs = deps.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
382
481
  const pollIntervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
@@ -384,10 +483,13 @@ async function startUnlocked(deps) {
384
483
  for (;;) {
385
484
  if (spawnState.error) {
386
485
  const code = spawnState.error.code;
387
- return fail('spawn-exited', `the Clash core exited immediately (${spawnState.error.message}${code ? ` [${code}]` : ''})`);
486
+ reap();
487
+ return bindFailure()
488
+ ?? fail('spawn-exited', `the Clash core exited immediately (${spawnState.error.message}${code ? ` [${code}]` : ''})`);
388
489
  }
389
490
  if (spawnState.exitCode !== null) {
390
- return fail('spawn-exited', `the Clash core exited immediately (code ${spawnState.exitCode})`);
491
+ reap();
492
+ return bindFailure() ?? fail('spawn-exited', `the Clash core exited immediately (code ${spawnState.exitCode})`);
391
493
  }
392
494
  const again = await probe(fetchImpl, controller, secret);
393
495
  if (again.ok) {
@@ -397,7 +499,11 @@ async function startUnlocked(deps) {
397
499
  return { ok: true, action: 'start', reused: false, pid: child.pid ?? null, version: again.version, error: null, code: null };
398
500
  }
399
501
  if (Date.now() >= deadline) {
400
- return fail('not-ready', `the Clash core did not become ready within ${Math.round(readyTimeoutMs / 1000)}s`);
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`);
401
507
  }
402
508
  await new Promise((r) => setTimeout(r, pollIntervalMs));
403
509
  }
@@ -425,31 +531,47 @@ async function stopUnlocked(deps, onlySpawned) {
425
531
  }
426
532
  }
427
533
  if (pid == null) {
428
- try {
429
- fs.unlinkSync(pidFile);
430
- }
431
- catch { /* already gone */ }
432
- try {
433
- fs.unlinkSync(path.join(dir, 'owner'));
434
- }
435
- catch { /* already gone */ }
534
+ removeMarkers(dir);
535
+ spawnedPid = null;
436
536
  remember(null, null);
437
537
  return { ok: true, action: 'noop', reused: false, pid: null, version: null, error: null, code: null };
438
538
  }
439
539
  if (!kill(pid))
440
540
  return fail('kill-failed', `failed to terminate the Clash core process ${pid}`);
441
- try {
442
- fs.unlinkSync(pidFile);
443
- }
444
- catch { /* already gone */ }
445
- try {
446
- fs.unlinkSync(path.join(dir, 'owner'));
447
- }
448
- catch { /* already gone */ }
541
+ removeMarkers(dir);
542
+ spawnedPid = null;
449
543
  remember(null, null);
450
544
  console.log(`[Clash] stopped pid=${pid}`);
451
545
  return { ok: true, action: 'stop', reused: false, pid, version: null, error: null, code: null };
452
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
+ }
453
575
  export function getMihomoStatus(extra) {
454
576
  const deps = merged(extra);
455
577
  const proxy = proxyOf(deps);
@@ -1,4 +1,5 @@
1
- import { LAST_BODY_MAX_CHARS, LAST_BODY_MAX_JSON_CHARS } from '../engine.js';
1
+ import { LAST_BODY_MAX_CHARS, LAST_BODY_MAX_JSON_CHARS, classifyThrownFailure, failureCause } from '../engine.js';
2
+ import { DEFAULT_QUOTA_PROBE_TIMEOUT_MS } from '../../config/defaults.js';
2
3
  /**
3
4
  * MiniMax quota — built-in code adapter (L-c).
4
5
  *
@@ -25,8 +26,7 @@ import { LAST_BODY_MAX_CHARS, LAST_BODY_MAX_JSON_CHARS } from '../engine.js';
25
26
  * 2. https://api.minimaxi.com/v1/api/openplatform/coding_plan/remains (counts = remaining)
26
27
  * (Note the CJK domain spelling: `minimaxi` with a trailing `i`.)
27
28
  * - Fallback trigger: HTTP 404 / 405 / >= 500, or a network throw. 401/403
28
- * (or envelope code 1004, or key-inactive wording) means the KEY is wrong,
29
- * not the URL — no fallback.
29
+ * (or envelope code 1004) means the KEY is wrong, not the URL — no fallback.
30
30
  * - Envelope: `{ base_resp: { status_code, status_msg } }` (camel variants
31
31
  * exist); `status_code != 0` is an API-level error even at HTTP 200.
32
32
  * - Windows: `model_remains[]`, each carrying a session (5h) and a weekly
@@ -157,13 +157,18 @@ export const MINIMAX_ADAPTER = {
157
157
  async probe(ctx) {
158
158
  const doFetch = ctx.fetchImpl ?? fetch;
159
159
  const now = ctx.now ?? Date.now;
160
- const timeoutMs = ctx.timeoutMs ?? 10_000;
160
+ const timeoutMs = ctx.timeoutMs ?? DEFAULT_QUOTA_PROBE_TIMEOUT_MS;
161
161
  const urls = urlsFor(ctx.providerId);
162
+ // Seeded with no capture: a chain that never issues a request has nothing
163
+ // to report. Every attempt below OVERWRITES this with its own `http`, so
164
+ // the console can say which leg failed and why (ADR-0009: a bare reason
165
+ // code is not evidence).
162
166
  let lastFailure = { ok: false, reason: 'network' };
163
167
  for (let i = 0; i < urls.length; i++) {
164
168
  const url = urls[i];
165
169
  const canFallback = i < urls.length - 1;
166
170
  const controller = new AbortController();
171
+ const started = now();
167
172
  const timer = setTimeout(() => controller.abort(), timeoutMs);
168
173
  try {
169
174
  const res = await doFetch(url, {
@@ -175,7 +180,7 @@ export const MINIMAX_ADAPTER = {
175
180
  signal: controller.signal,
176
181
  });
177
182
  // Hard key verdict — the credential is wrong, not the endpoint.
178
- const http = { url, status: res.status, ok: res.ok };
183
+ const http = { url, status: res.status, ok: res.ok, durationMs: now() - started };
179
184
  if (res.status === 401 || res.status === 403) {
180
185
  const raw = await res.text().catch(() => '');
181
186
  if (raw)
@@ -183,7 +188,15 @@ export const MINIMAX_ADAPTER = {
183
188
  return { ok: false, reason: 'auth', http };
184
189
  }
185
190
  if (!res.ok) {
186
- lastFailure = { ok: false, reason: 'status' };
191
+ // A non-401 rejection explains itself too (rate limit, dead endpoint,
192
+ // vendor outage) — the badge has to be able to say why, so the body
193
+ // rides the capture exactly as it does on the auth path above.
194
+ const raw = await res.text().catch(() => '');
195
+ if (raw)
196
+ http.body = raw.slice(0, LAST_BODY_MAX_CHARS);
197
+ // The capture rides the fallback too: the LAST leg that answered is
198
+ // the one whose status the badge has to explain.
199
+ lastFailure = { ok: false, reason: 'status', http };
187
200
  if ((res.status === 404 || res.status === 405 || res.status >= 500) && canFallback)
188
201
  continue;
189
202
  return { ...lastFailure, http };
@@ -209,12 +222,14 @@ export const MINIMAX_ADAPTER = {
209
222
  const base = payload.base_resp ?? payload.baseResp ?? null;
210
223
  if (base && typeof base === 'object') {
211
224
  const code = Number(base.status_code ?? base.statusCode) || 0;
212
- const msg = `${String(base.status_msg ?? base.statusMsg ?? '')} ${raw}`;
213
- if (code === 1004 || /invalid api key|invalid key|unauthorized|inactive/i.test(msg)) {
214
- return { ok: false, reason: 'auth', http };
215
- }
225
+ if (code === 1004)
226
+ return { ok: false, reason: 'auth', verdict: 'credential-rejected', http };
227
+ // A non-zero envelope code on HTTP 200 IS the account's verdict —
228
+ // MiniMax states "no active token plan subscription" as code 2062.
229
+ // The conclusion comes from the CODE (structured), never from the
230
+ // message wording: `status_msg` is vendor prose that changes.
216
231
  if (code !== 0)
217
- return { ok: false, reason: 'status', http };
232
+ return { ok: false, reason: 'status', verdict: 'plan-inactive', http };
218
233
  }
219
234
  const probeTimeMs = now();
220
235
  const windows = parseRemainsPayload(payload, probeTimeMs, url);
@@ -222,8 +237,16 @@ export const MINIMAX_ADAPTER = {
222
237
  return { ok: false, reason: 'shape', http };
223
238
  return { ok: true, windows, plan: ctx.providerId.includes('coding-plan') ? 'Token Plan' : undefined, http };
224
239
  }
225
- catch {
226
- lastFailure = { ok: false, reason: 'network' };
240
+ catch (err) {
241
+ // A transport throw (or the abort guard firing) has no body — the
242
+ // cause text is the entire evidence, so it goes into the capture. A leg
243
+ // that ran out of clock is `timeout`, never a credential verdict.
244
+ const thrown = classifyThrownFailure(err);
245
+ lastFailure = {
246
+ ok: false,
247
+ reason: thrown,
248
+ http: { url, durationMs: now() - started, ok: false, error: thrown, detail: failureCause(err) },
249
+ };
227
250
  if (!canFallback)
228
251
  return lastFailure;
229
252
  continue;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * One quota pair for a provider whose plugin owns login (`authTypes: ['none']`).
3
+ * There is no OCR key to hash. The prefix is the pair identity the console
4
+ * translates as the machine CLI login.
5
+ */
6
+ export declare const CLI_LOGIN_QUOTA_PREFIX = "cli-login";
7
+ /** True when the provider's model-service plugin refuses an OCR credential. */
8
+ export declare function providerUsesCliLogin(providerId: string): boolean;
@@ -0,0 +1,18 @@
1
+ import { getModelServicePlugin, pluginDeclinesCredentials } from '../plugins/host.js';
2
+ import { wireFor } from '../providers/wire.js';
3
+ import { getProviderNodeById } from '../opencode/user-config.js';
4
+ /**
5
+ * One quota pair for a provider whose plugin owns login (`authTypes: ['none']`).
6
+ * There is no OCR key to hash. The prefix is the pair identity the console
7
+ * translates as the machine CLI login.
8
+ */
9
+ export const CLI_LOGIN_QUOTA_PREFIX = 'cli-login';
10
+ /** True when the provider's model-service plugin refuses an OCR credential. */
11
+ export function providerUsesCliLogin(providerId) {
12
+ const def = getProviderNodeById(providerId);
13
+ const npm = typeof def?.npm === 'string' ? def.npm : typeof def?.package === 'string' ? def.package : undefined;
14
+ const options = def?.options;
15
+ const settings = def?.settings;
16
+ const base = typeof options?.baseURL === 'string' ? options.baseURL : typeof settings?.baseURL === 'string' ? settings.baseURL : undefined;
17
+ return pluginDeclinesCredentials(getModelServicePlugin(wireFor(npm, base)));
18
+ }
@@ -92,6 +92,11 @@ export const BUILTIN_QUOTA_DECLARATIONS = [
92
92
  // origin), Bearer (inference auth).
93
93
  url: 'https://open.bigmodel.cn/api/monitor/usage/quota/limit',
94
94
  auth: 'bearer',
95
+ // Zhipu answers HTTP 200 with a STRUCTURED refusal when the account holds
96
+ // no plan: `{ code: 500, msg: "…", success: false }`. `success: false` is
97
+ // the machine-readable field — the `msg` beside it is vendor prose (and
98
+ // localized), so the verdict reads the boolean, never the sentence.
99
+ refusalIf: { where: { path: 'success', truthy: true } },
95
100
  windows: {
96
101
  form: 'each',
97
102
  path: 'data.limits',
@@ -126,6 +131,11 @@ export const BUILTIN_QUOTA_DECLARATIONS = [
126
131
  // monitor endpoint above.
127
132
  url: 'https://open.bigmodel.cn/api/monitor/usage/quota/limit',
128
133
  auth: 'bearer',
134
+ // Zhipu answers HTTP 200 with a STRUCTURED refusal when the account holds
135
+ // no plan: `{ code: 500, msg: "…", success: false }`. `success: false` is
136
+ // the machine-readable field — the `msg` beside it is vendor prose (and
137
+ // localized), so the verdict reads the boolean, never the sentence.
138
+ refusalIf: { where: { path: 'success', truthy: true } },
129
139
  windows: {
130
140
  form: 'each',
131
141
  path: 'data.limits',
@@ -143,6 +143,8 @@ export function evalWhere(where, ctx) {
143
143
  const v = resolvePath(ctx.item, where.path, ctx.itemKey);
144
144
  if (where.exists)
145
145
  return v !== undefined && v !== null;
146
+ if (where.truthy)
147
+ return v === true;
146
148
  if (where.eq !== undefined) {
147
149
  if (typeof where.eq === 'boolean')
148
150
  return v === where.eq;
@@ -334,7 +336,7 @@ export function evalSuccessIf(entry, body) {
334
336
  // ─── Loader validation ──────────────────────────────────────────────────────
335
337
  const FIELD_KEYS = new Set(['path', 'header', 'literal', 'firstOf', 'scale', 'invertOf', 'time']);
336
338
  const WINDOW_KEYS = new Set(['name', 'nameCode', 'nameSpec', 'where', 'used', 'total', 'remaining', 'resetAt', 'unlimited']);
337
- const WHERE_KEYS = new Set(['path', 'exists', 'eq', 'in']);
339
+ const WHERE_KEYS = new Set(['path', 'exists', 'eq', 'in', 'truthy']);
338
340
  const NAME_KEYS = new Set(['template', 'from', 'enumMap', 'enumCode', 'fallback', 'code', 'argPath']);
339
341
  /**
340
342
  * Reject the banned classes at load, whole entry, loudly (the caller drops
@@ -350,7 +352,7 @@ export function validateEntry(entry) {
350
352
  // `method`, multi-url arrays, injected state): a loadable entry carries
351
353
  // exactly the schema keys — anything else rejects the WHOLE entry.
352
354
  const ENTRY_KEYS = new Set([
353
- 'id', 'providerId', 'url', 'auth', 'headers', 'successIf', 'windows',
355
+ 'id', 'providerId', 'url', 'auth', 'headers', 'successIf', 'refusalIf', 'windows',
354
356
  'cacheTtlMs', 'forkedFrom', 'verifiedAt', 'builtin',
355
357
  ]);
356
358
  for (const k of Object.keys(entry)) {
@@ -383,9 +385,20 @@ export function validateEntry(entry) {
383
385
  const err = validateWhere(entry.successIf, `entry ${entry.id}: successIf`);
384
386
  if (err)
385
387
  return err;
386
- if (entry.successIf.exists || entry.successIf.in)
388
+ if (entry.successIf.exists || entry.successIf.in || entry.successIf.truthy)
387
389
  return `entry ${entry.id}: successIf must be a single equality`;
388
390
  }
391
+ if (entry.refusalIf) {
392
+ if (typeof entry.refusalIf !== 'object' || entry.refusalIf === null)
393
+ return `entry ${entry.id}: refusalIf must be an object`;
394
+ for (const k of Object.keys(entry.refusalIf)) {
395
+ if (k !== 'where')
396
+ return `entry ${entry.id}: refusalIf: unknown key '${k}'`;
397
+ }
398
+ const err = validateWhere(entry.refusalIf.where, `entry ${entry.id}: refusalIf`);
399
+ if (err)
400
+ return err;
401
+ }
389
402
  const ws = entry.windows;
390
403
  if (!ws || typeof ws !== 'object')
391
404
  return `entry ${entry.id}: windows missing`;
@@ -488,9 +501,9 @@ function validateWhere(where, label) {
488
501
  }
489
502
  if (typeof where.path !== 'string')
490
503
  return `${label}: where.path must be a string`;
491
- const set = [where.exists !== undefined, where.eq !== undefined, where.in !== undefined].filter(Boolean).length;
504
+ const set = [where.exists !== undefined, where.truthy !== undefined, where.eq !== undefined, where.in !== undefined].filter(Boolean).length;
492
505
  if (set !== 1)
493
- return `${label}: exactly one of exists/eq/in must be set`;
506
+ return `${label}: exactly one of exists/truthy/eq/in must be set`;
494
507
  if (where.in !== undefined && (!Array.isArray(where.in) || where.in.length === 0))
495
508
  return `${label}: where.in must be a non-empty literal list`;
496
509
  if (where.eq !== undefined && typeof where.eq !== 'string' && typeof where.eq !== 'number' && typeof where.eq !== 'boolean')
@@ -96,6 +96,27 @@ export declare function runDslProbe(entry: QuotaProbeEntry, opts: RunProbeOpts):
96
96
  /** Display bound for one upstream failure message (the full body stays in the
97
97
  * memory-only last-probe capture; this is the one-line badge caption). */
98
98
  export declare const FAILURE_MESSAGE_MAX_CHARS = 160;
99
+ /**
100
+ * A probe that THREW is either a timeout or a plain transport fault — it is
101
+ * never a credential verdict. Node/undici report a wall-clock timeout with
102
+ * `err.name === 'AbortError'`, the same name an operator cancel carries, and the
103
+ * first pass labelled every throw `network` while a status branch reserved
104
+ * 401/403 for `auth`: a gateway that hung (or an auth shim that answered 504)
105
+ * then read as "key rejected", which sends the operator to re-auth a working
106
+ * credential. An HTTP ANSWER keeps its own class (`status`) — 504 says
107
+ * "upstream refused · HTTP 504", which is honest; this rule is for legs that
108
+ * never got an answer at all.
109
+ */
110
+ export declare function classifyThrownFailure(err: unknown): 'timeout' | 'network';
111
+ /**
112
+ * The cause of a failure that produced NO captured body: error class, its
113
+ * message, the transport code Node/Bun park on `cause` (`ENOTFOUND`,
114
+ * `ECONNREFUSED`, `ETIMEDOUT`, an abort) and the vendor's own words when the
115
+ * thrown error carries them in `errorBody` instead. A probe that throws is only
116
+ * ever labelled `network`, so without this line the operator cannot tell a dead
117
+ * resolver from a refused connection from a rejected credential chain.
118
+ */
119
+ export declare function failureCause(err: unknown): string;
99
120
  /**
100
121
  * Build the display-safe failure verdict for one attempt: transport reason +
101
122
  * HTTP status + the upstream's short message. Display-only evidence — it never
@@ -103,7 +124,7 @@ export declare const FAILURE_MESSAGE_MAX_CHARS = 160;
103
124
  */
104
125
  export declare function probeFailureDetail(outcome: Extract<QuotaProbeOutcome, {
105
126
  ok: false;
106
- }>, http: LastProbeCapture | undefined, at: number): Omit<QuotaProbeFailure, 'at'> & {
127
+ }>, http: LastProbeCapture | undefined, at: number, entry?: QuotaProbeEntry): Omit<QuotaProbeFailure, 'at'> & {
107
128
  at: number;
108
129
  };
109
130
  /**