dsh-clash-subscription 0.9.0 → 0.11.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.
@@ -0,0 +1,173 @@
1
+ # 0.11.0 · 不再选中被限流的节点
2
+
3
+ > 上一版 `0.10.0` · 本版 `0.11.0`
4
+
5
+ ## 症状
6
+
7
+ 订阅里有能用的节点,自动切换却停在一个**被限流**的节点上。面板上看得见:
8
+
9
+ ```
10
+ health.lastSwitch: from 🇺🇸 美国02 → to 🇸🇬 新加坡03
11
+ failed ["latency"] · degraded true
12
+ health.lastRound: node 新加坡03 · usable true · degraded true · limited ["github"]
13
+ ```
14
+
15
+ `新加坡03` 的 GitHub 配额已经耗尽,而当时存在配额干净的节点。切换还是选中了它。
16
+
17
+ ## 根因:同一个问题有两套排序,其中一套不看限流
18
+
19
+ `lib/watch.js` 的 `rankHealth()` 是排序的定义,它知道限流要排在干净节点之后。但**运行期的切换路径自己又写了一套**:
20
+
21
+ ```js
22
+ // 0.10.0 · index.js switchAfterStrikes 里的局部排序
23
+ const rank = (row) => [
24
+ row.verdict?.usable === true ? 0 : 1, // 可用
25
+ typeof row.latency === 'number' ? row.latency : Infinity,
26
+ (row.verdict?.failed ?? []).length,
27
+ (row.verdict?.blocked ?? []).length,
28
+ ]
29
+ ```
30
+
31
+ 它从不读 `verdict.degraded`。而 `lib/realprobe.js` 里 `usable: blocked.length === 0` **只数 blocked,不数 limited** —— 所以一个被限流的节点 `usable` 仍是 `true`,排名靠的是延迟。限流节点往往更快(配额耗尽不耽误普通请求),于是它赢了。
32
+
33
+ 启动时走的是 `lib/core.js` 的 `rankHealth(rows)[0]`,排序正确;运行期走的是这套局部排序,排序错误。**同一件事两个答案,取决于走哪条路**。
34
+
35
+ 用真实运行期代码取证(不是手写模拟):
36
+
37
+ | 场景 | 切换路径选中 | `rankHealth` 选中 |
38
+ |---|---|---|
39
+ | `ok` 300 ms vs `limited` 150 ms | `limited-150` ✗ | `ok-300` ✓ |
40
+ | `ok` 280 ms vs `limited` 150 / 160 ms | `limited-150` ✗ | `ok-280` ✓ |
41
+
42
+ ## 第二处:`rankHealth` 的最后一级不是延迟
43
+
44
+ 修好第一处后还有一个洞:`rankHealth` 比到最后一级用的是 `verdict.total`(探针耗时之和),而 **`total` 里根本没有 Google 延迟** —— `lib/realprobe.js` 只累加 `gating` 探针,Google 基线是 `gating: false`。
45
+
46
+ ```
47
+ A: google 100 ms · total 2300
48
+ B: google 300 ms · total 970
49
+ → rankHealth 选 B
50
+ ```
51
+
52
+ 用户要的是「延迟最低」,而 `total` 被 git fetch 的 300–2100 ms 摆动支配,测的不是延迟。
53
+
54
+ ## 第三处:限流节点一次就放行
55
+
56
+ `healthRound` 的接受条件是 `if (measured.verdict.usable === true) return`。因为限流不算 `blocked`,**限流节点第一次就通过,剩下两次重测和随后的全节点重选都不会发生**。实测:重启后 `lastRound` 是 `degraded / attempt 1/3 / failed ["github"]`,其余 8 个节点状态全是 `unknown` —— 压根没测。
57
+
58
+ ## 第四处:名为「暖态中位数」的取值在 2 样本时取较大者
59
+
60
+ ```js
61
+ // 0.10.0
62
+ const forMedian = samples.length > 1 ? samples.slice(1) : samples
63
+ const sorted = [...forMedian].sort((a, b) => a - b)
64
+ latency = sorted[Math.floor(sorted.length / 2)]
65
+ ```
66
+
67
+ 3 个样本丢掉第 1 个后剩 2 个,`floor(2 / 2) = 1` 取的是**较大者**。实测 `[513, 420, 380] → 420`(真中位 380)、`[513, 1500, 120] → 1500`。系统性把节点判慢,再把延迟上限当成硬失败,更多好节点被踢出候选。
68
+
69
+ ## 改了什么
70
+
71
+ ### 1. 只会有一套排序
72
+
73
+ `switchAfterStrikes` 里的局部 `rank` 整段删除,改为走 `rankHealth`:
74
+
75
+ ```js
76
+ const ranked = rankHealth(rows)
77
+ rows.sort((a, b) => ranked.indexOf(a) - ranked.indexOf(b))
78
+ ```
79
+
80
+ ### 2. `rankHealth` 在限流之后、耗时之前比真实延迟
81
+
82
+ ```js
83
+ (a, b) =>
84
+ good(a) - good(b) ||
85
+ blockedCount(a) - blockedCount(b) ||
86
+ degraded(a) - degraded(b) || // 配额干净优先
87
+ latency(a) - latency(b) || // ← 新增:Google 暖态延迟
88
+ score(a) - score(b) ||
89
+ total(a) - total(b),
90
+ ```
91
+
92
+ 没有延迟的节点(启动矩阵里还没测过 Google)排在有延迟的之后 —— 不能靠一个不存在的数字取胜。
93
+
94
+ ### 3. 限流算「有问题」
95
+
96
+ ```js
97
+ const clean = measured.verdict.usable === true && measured.verdict.degraded !== true
98
+ if (clean === true) { /* 接受,结束本轮 */ }
99
+ ```
100
+
101
+ 限流节点现在也会连测满 3 次。**这里故意没有 `attempt === attempts` 的逃生口**:加过一次,结果第 3 次仍限流时也走进接受分支、永不切换,正是要修的缺陷原样复活,11 条测试变红后删除。
102
+
103
+ 三次都不合格时按「是限流还是硬失败」分流:限流给 `state: 'limited'` 且 `giveUp: false`(不计 strike),硬失败照旧累计。
104
+
105
+ ### 4. 找不到干净节点时不说谎
106
+
107
+ 当前节点只是被限流、又没有配额干净的替代时,报告**不再说「不可用」**:
108
+
109
+ ```js
110
+ return { ...report, state: liveUsable === true ? "limited" : "no-alternative", ... }
111
+ ```
112
+
113
+ 那条线还在承载流量。说它不可用,是在描述用户明明正在用的连接。`health.lastSwitch.state` 相应记为 `no-clean-alternative`,与真正的 `no-alternative` 分开。
114
+
115
+ ### 5. 切换候选的门槛随之收紧
116
+
117
+ ```js
118
+ const improves = (row) =>
119
+ row.verdict?.usable === true && (liveUsable !== true || row.verdict?.degraded !== true)
120
+ ```
121
+
122
+ 当前节点硬失败时,任何可用节点都算改善;当前节点仅限流时,**只有配额干净的才算** —— 换一个同样限流的节点,答复质量一样,却要中断所有在途连接。
123
+
124
+ ### 6. 真中位数
125
+
126
+ ```js
127
+ const mid = sorted.length >> 1
128
+ latency = sorted.length % 2 === 1 ? sorted[mid] : Math.round((sorted[mid - 1] + sorted[mid]) / 2)
129
+ ```
130
+
131
+ ### 7. 摘要说清是哪种情况
132
+
133
+ `describeHealth()` 从工具分支里抽成 `Runtime` 方法,测试才断言得到它的措辞。三种历史错法在 JSDoc 里写明:
134
+
135
+ - 把正在承载流量的限流节点说成「不可用」
136
+ - 把一轮内连测 3 次说成「连续 3 轮失败」
137
+ - 打印 `undefined`(`strikes`/`strikeLimit` 从未进过 report)
138
+
139
+ ## 验收
140
+
141
+ ```
142
+ node test/regression-070.mjs → 134 passed, 0 failed ← 新增 9b / 9c / 9d / 18 四节
143
+ node test/regression-0100.mjs → 48 passed, 0 failed
144
+ node test/regression-063.mjs → 29 passed, 0 failed
145
+ node test/e2e-063.mjs → 10 passed, 0 failed
146
+ ```
147
+
148
+ 负向对照(证明这些测试抓得住回归,不是装饰):
149
+
150
+ | 还原哪一处 | 报出的失败 |
151
+ |---|---|
152
+ | 切回旧接受条件 `usable === true` 即 return | 9c 报 7 条 FAIL |
153
+ | 从 comparator 删掉 `latency(a) - latency(b) \|\|` | 9d 报 2 条 FAIL |
154
+ | `state` 还原成一律 `"no-alternative"` | 18 报 4 条 FAIL |
155
+
156
+ 真机数据验证(把 `/clash-proxy/status` 的 9 个节点喂新 `rankHealth`):
157
+
158
+ ```
159
+ 新加坡01 ok/123 → 新加坡03 ok/126 → 新加坡02 ok/127 → 台湾02 ok/187
160
+ → 台湾01 ok/203 → 美国02 ok/231 → 美国03 ok/253 → 马来西亚01 ok/无延迟
161
+ → 美国01 limited/247
162
+ ```
163
+
164
+ `ok` 全部排在 `limited` 之前,同档内按 Google 延迟升序。
165
+
166
+ ## 本版附带
167
+
168
+ - 包内补上 `vendor/`(`mihomo.exe.gz` + `SHA256SUMS.json`)。源码归档树一直缺这两份,所以 `e2e-070/080/090` 长期报 `CORE_MISSING` 跑不起来。
169
+ - `lib/skill.js` 的自述表同步:`limited` 行改为「不主动选;只有没有 `ok` 节点时才留」,切换规则改为「连通且不限流 → Google 延迟」排序,`lastRound.state` 取值列出 `ok / limited / slow / switched / bad`。
170
+
171
+ ## 需要重启才生效
172
+
173
+ 宿主进程在加载插件时把代码读进内存。装完本版后**要完全退出 DSH 再打开**,新逻辑才生效。
package/README.md CHANGED
@@ -119,8 +119,56 @@ unpacking and the executable **after**, and re-unpacks if an already-installed c
119
119
  matches — a corrupted or replaced binary is restored rather than trusted. If the manifest and
120
120
  the archive ever disagree, the plugin refuses to run the binary at all.
121
121
 
122
- Only `win32-x64` ships. Other platforms report `platformSupported: false` and use `corePath`
123
- or `autoFetchCore` instead.
122
+ Only `win32-x64` ships a copy inside the package. Every other supported platform fetches the
123
+ release asset on first start instead; `status.coreSource` reports which applies
124
+ (`bundled` or `download`), and `status.platformSupported` is true when at least one of the two
125
+ paths exists.
126
+
127
+ | Platform | Core source | Archive |
128
+ |---|---|---|
129
+ | `win32-x64` | bundled + downloadable | `.zip` |
130
+ | `win32-arm64` | downloadable | `.zip` |
131
+ | `linux-x64` | downloadable | `.gz` (bare binary) |
132
+ | `linux-arm64` | downloadable | `.gz` (bare binary) |
133
+ | `darwin-x64` / `darwin-arm64` | downloadable | `.gz` (bare binary) |
134
+
135
+ ## Ubuntu (and other Linux): 24.04 LTS and 26.04 LTS
136
+
137
+ Supported. Nothing beyond the DSH runtime has to be installed beforehand.
138
+
139
+ **Why the distro version does not matter.** The release asset decompresses to a *statically
140
+ linked* ELF64 — verified: no `PT_INTERP`, no `GLIBC_*` symbols, no `ld-linux` reference — so the
141
+ system glibc is never consulted. The same binary runs on Ubuntu 22.04, 24.04 (Noble) and 26.04
142
+ (Resolute Raccoon).
143
+
144
+ **What happens on first start.**
145
+
146
+ 1. no bundled core exists for Linux, so `autoFetchCore` defaults to **on** there;
147
+ 2. the plugin downloads `mihomo-linux-amd64-compatible-v1.19.34.gz` (22 766 457 bytes) from the
148
+ GitHub release, trying `gh-proxy.com` / `ghfast.top` / `ghproxy.net` first if those answer
149
+ faster;
150
+ 3. the SHA-256 is checked against the publisher's own digest **before** anything is unpacked;
151
+ 4. the archive is decompressed with `node:zlib` — **not** with `tar`, because every Linux and
152
+ macOS release asset is a *bare gzip-compressed binary*, not a tar. Feeding one to
153
+ `tar -xzf` fails with `Unrecognized archive format`, which is exactly what 0.9.0 did after a
154
+ successful 22 MB download;
155
+ 5. the result (61 948 030 bytes) is written to
156
+ `${DSH_HOME}/data/dsh-clash-proxy/bin/mihomo` and chmod `0755`.
157
+
158
+ Because step 4 uses `node:zlib` instead of an external command, a slim image without `tar` still
159
+ works. `tar` is only needed if a release ever switches back to a `tar.gz` payload — both shapes
160
+ are handled and both are covered by tests.
161
+
162
+ **Pinning a version.** `coreVersion: 1.19.34` works on every listed platform:
163
+ `KNOWN_ARCHIVES` carries the publisher digest for each. Without a pin, the plugin asks the release
164
+ API, falling back to the release-page redirect when the API is rate limited.
165
+
166
+ **If the download cannot happen** (air-gapped host, or a mirror that does not carry it), set
167
+ `corePath` to a `mihomo` binary placed on disk, or install a local archive with
168
+ `installCoreFromFile`. Both are verified the same way.
169
+
170
+ **Not supported:** 32-bit x86 (`linux-ia32`) and architectures with no published asset. On those
171
+ `status.platformSupported` is false and the panel says so up front instead of failing later.
124
172
 
125
173
  ## The optional GeoIP upgrade
126
174
 
package/client.js CHANGED
@@ -81,7 +81,7 @@ const en = {
81
81
  noUsableNode: 'No node reached every required service.',
82
82
  usableCount: '{usable} / {total} nodes usable',
83
83
  autoFetchCore: 'Fetch a core automatically',
84
- autoFetchCoreHint: 'When no mihomo binary is present, download a verified private copy on startup instead of waiting for you to press Download.',
84
+ autoFetchCoreHint: 'When no mihomo binary is present, download a verified private copy on startup instead of waiting for you to press Download. On Linux and macOS there is no bundled core, so this is on by default there — the plugin fetches the 22 MB release asset once, verifies it against the publisher SHA-256, and unpacks it into its own data directory.',
85
85
  dns: 'DNS servers',
86
86
  dnsHint: 'Comma-separated resolvers the core uses for its own lookups.',
87
87
  start: 'Start',
@@ -248,7 +248,7 @@ const zh = {
248
248
  noUsableNode: '没有任何节点能访问全部必需服务。',
249
249
  usableCount: '{usable} / {total} 个节点可用',
250
250
  autoFetchCore: '自动获取内核',
251
- autoFetchCoreHint: '机器上没有 mihomo 时,启动时自动下载一份经过校验的私有内核,不用手动点下载。',
251
+ autoFetchCoreHint: '机器上没有 mihomo 时,启动时自动下载一份经过校验的私有内核,不用手动点下载。Linux 与 macOS 没有自带内核,因此在那里默认开启:首次启动会下载 22 MB 的发布资产,用发布方 SHA-256 校验后解包进插件自己的数据目录。',
252
252
  dns: 'DNS 服务器',
253
253
  dnsHint: '逗号分隔,内核自己解析时使用。',
254
254
  start: '启动',
package/index.js CHANGED
@@ -79,7 +79,16 @@ export const CONFIG_DEFAULTS = {
79
79
  speedTestCount: 8,
80
80
  /** How often the core is checked for liveness, in minutes; 0 disables the watchdog. */
81
81
  healthCheckMinutes: 1,
82
- /** Download a private core automatically when the machine has none. */
82
+ /**
83
+ * Download a private core automatically when the machine has none.
84
+ *
85
+ * Default off was right while every supported platform shipped a vendored copy: downloading
86
+ * was an optimisation. Linux and macOS have no vendored copy (the payload is 61 MB, which is
87
+ * not something to embed for a platform whose package can just fetch it), so on those the flag
88
+ * being off means a fresh install does nothing at all until someone presses a button. The
89
+ * effective default is therefore "on when there is nothing bundled for this platform", handled
90
+ * in `resolveConfig` rather than by leaving the literal `false` here.
91
+ */
83
92
  autoFetchCore: false,
84
93
  /** Pin the core version to a build whose digest this plugin ships; empty means current. */
85
94
  coreVersion: '',
@@ -259,6 +268,11 @@ export function resolveConfig(raw) {
259
268
  config.mode = mode === 'global' ? 'global' : 'rule'
260
269
  config.autoStart = config.autoStart !== false && config.autoStart !== 'false'
261
270
  config.autoFetchCore = config.autoFetchCore === true || config.autoFetchCore === 'true'
271
+ // A platform with no bundled core gets the download switched on, because otherwise a fresh
272
+ // install there has no core and no action: the panel offers a button, but nothing happens on
273
+ // its own and "the proxy does not work" looks like a bug rather than an unset default. An
274
+ // explicit `true`/`false` in the profile still wins, so this only fills the gap.
275
+ if (input.autoFetchCore === undefined && vendoredFor() === undefined) config.autoFetchCore = true
262
276
  config.autoFetchGeo = config.autoFetchGeo !== false && config.autoFetchGeo !== 'false'
263
277
  config.autoReselect = config.autoReselect !== false && config.autoReselect !== 'false'
264
278
  for (const field of ['subscriptionUrls', 'subscriptionUrl', 'node', 'corePath', 'coreVersion', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir', 'probes', 'requiredProbes']) {
@@ -780,7 +794,12 @@ export class Runtime {
780
794
  coldLatency = samples[0]
781
795
  const forMedian = samples.length > 1 ? samples.slice(1) : samples
782
796
  const sorted = [...forMedian].sort((a, b) => a - b)
783
- latency = sorted[Math.floor(sorted.length / 2)]
797
+ // True median. Indexing at floor(n / 2) is the median only for odd n; at n = 2 it
798
+ // returned the SLOWER of the two warm samples (measured: 513, 420, 380 -> 420 while the
799
+ // real median is 380). That biased every two-sample node towards the ceiling and pushed
800
+ // healthy nodes into failed: latency -- the other half of picking the rate-limited node.
801
+ const mid = sorted.length >> 1
802
+ latency = sorted.length % 2 === 1 ? sorted[mid] : Math.round((sorted[mid - 1] + sorted[mid]) / 2)
784
803
  latencySource = samples.length > 1 ? 'warm-median' : 'cold'
785
804
  } else {
786
805
  latencySource = 'unreachable'
@@ -851,6 +870,16 @@ export class Runtime {
851
870
 
852
871
  const attempts = Math.max(1, Number(this.config.healthAttempts ?? 3))
853
872
  const tried = []
873
+ // A round keeps retrying until it sees a node with no problem at all, not merely a node
874
+ // that can carry traffic. `limited` counts as a problem here even though judgeNodeHealth
875
+ // keeps `usable` true for it: a rate-limited node answers, so it can stay selected, but the
876
+ // whole point of the round is to notice it and move to a node with quota left. Accepting the
877
+ // first `usable` verdict is what let a node with GitHub quota 0 survive every round in a
878
+ // row "because it was usable", with the retries and the switch neither ever reached.
879
+ //
880
+ // `clean` is computed once per attempt rather than once above the loop: it is the verdict
881
+ // of THIS measurement, and a node that is limited on attempt 1 and clean on attempt 2 must
882
+ // end the loop at attempt 2.
854
883
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
855
884
  const measured = await this.measureNode(current, plan)
856
885
  if (measured === undefined) {
@@ -872,12 +901,22 @@ export class Runtime {
872
901
  this.lastMatrix = [{ name: current, results: measured.results }]
873
902
  this.lastCheckAt = Date.now()
874
903
 
875
- if (measured.verdict.usable === true) {
876
- // Kept. One good attempt ends the round; the remaining attempts are not spent, because
877
- // the node already answered the question this round is asking.
878
- this.watch.record(current, measured.verdict, { probes: measured.results })
904
+ const clean = measured.verdict.usable === true && measured.verdict.degraded !== true
905
+ // A node with no problem ends the round at once. A node that answered but is short on
906
+ // quota does NOT: it gets the remaining attempts like any other problem, and only when
907
+ // every attempt still shows a problem does the round search for a replacement. Note that
908
+ // this condition deliberately has no `attempt === attempts` escape hatch: a node that is
909
+ // still short on quota on its LAST attempt must fall out of the loop into the switch, and
910
+ // an escape hatch here would accept it instead -- which is the defect this loop exists to
911
+ // remove, reintroduced one branch lower.
912
+ if (clean === true) {
913
+ // Kept. The remaining attempts are not spent, because the node already answered the
914
+ // question this round is asking.
915
+ const watched = this.watch.record(current, measured.verdict, { probes: measured.results })
879
916
  const report = {
880
- state: measured.verdict.degraded === true ? 'degraded' : 'ok',
917
+ // `clean` above already excluded a degraded verdict, so this branch only ever
918
+ // reports ok. The old ternary kept a degraded arm that could no longer run.
919
+ state: 'ok',
881
920
  node: current,
882
921
  required: plan.gating,
883
922
  results: measured.results,
@@ -892,6 +931,8 @@ export class Runtime {
892
931
  attempts: tried,
893
932
  attemptLimit: attempts,
894
933
  giveUp: false,
934
+ strikes: watched.strikes,
935
+ strikeLimit: watched.limit,
895
936
  at: new Date().toISOString(),
896
937
  }
897
938
  this.health = report
@@ -907,18 +948,29 @@ export class Runtime {
907
948
  )
908
949
  }
909
950
 
910
- // Every attempt failed.
911
- this.watch.record(current, { usable: false, failed: tried.at(-1)?.failed ?? [], limited: [], blocked: [], score: 100 })
912
- const verdictNow = {
913
- usable: false,
914
- degraded: false,
915
- failed: tried.at(-1)?.failed ?? [],
916
- limited: [],
917
- blocked: [],
918
- slow: tried.every((entry) => entry.slow === true),
919
- }
951
+ // Every attempt showed a problem.
952
+ //
953
+ // Two different problems end up here. A hard failure means the node cannot carry traffic at
954
+ // all, so it takes a strike and the search accepts any usable replacement. A node that is
955
+ // only short on quota CAN carry traffic, so it takes no strike -- but it still does not get
956
+ // to stay: the search runs anyway and only a quota-clean replacement displaces it, because
957
+ // swapping one rate-limited node for another tears down every connection in flight and
958
+ // buys nothing.
959
+ const last = tried.at(-1)
960
+ const quotaOnly = last?.usable === true
961
+ const verdictNow = quotaOnly
962
+ ? { usable: true, degraded: true, failed: last?.failed ?? [], limited: last?.failed ?? [], blocked: [], score: 1 }
963
+ : {
964
+ usable: false,
965
+ degraded: false,
966
+ failed: last?.failed ?? [],
967
+ limited: [],
968
+ blocked: [],
969
+ slow: tried.every((entry) => entry.slow === true),
970
+ }
971
+ const watched = this.watch.record(current, verdictNow, { probes: this.healthRows.get(current)?.results })
920
972
  const report = {
921
- state: verdictNow.slow ? 'slow' : 'bad',
973
+ state: quotaOnly ? 'limited' : verdictNow.slow === true ? 'slow' : 'bad',
922
974
  node: current,
923
975
  required: plan.gating,
924
976
  verdict: verdictNow,
@@ -928,11 +980,17 @@ export class Runtime {
928
980
  attempt: attempts,
929
981
  attempts: tried,
930
982
  attemptLimit: attempts,
931
- giveUp: true,
983
+ giveUp: quotaOnly !== true,
984
+ strikes: watched.strikes,
985
+ strikeLimit: watched.limit,
932
986
  at: new Date().toISOString(),
933
987
  }
934
988
  this.health = report
935
- this.log(`${attempts} attempts all failed on ${current}; searching every unblocked node`)
989
+ this.log(
990
+ quotaOnly
991
+ ? `${attempts} attempts on ${current} all rate-limited; looking for a quota-clean node`
992
+ : `${attempts} attempts all failed on ${current}; searching every unblocked node`
993
+ )
936
994
  return await this.switchAfterStrikes(report, plan, options)
937
995
  } finally {
938
996
  this.healthRunning = false
@@ -948,12 +1006,15 @@ export class Runtime {
948
1006
  * worse node than one further down the list. `healthSwitchCandidates` still exists as an
949
1007
  * operator escape hatch for a huge subscription, but its default is 0 (everything).
950
1008
  *
951
- * "Best" is decided from this round's measurements, in this order:
1009
+ * "Best" is decided by rankHealth (lib/watch.js), which is also what the startup path uses,
1010
+ * so both paths answer the same question the same way. That ordering is: usable first, then
1011
+ * fewest blocked probes, then a quota-clean node before a rate-limited one, then the measured
1012
+ * Google latency, then the probe-time sum as a last resort.
952
1013
  *
953
- * 1. usable (no gating probe failed) before anything else;
954
- * 2. the lowest warm Google latency — this is the number the ceiling talks about, and the
955
- * fastest working node is what "最优" means here;
956
- * 3. fewer failed probes, then a quota-limited node before an unreachable one, as tie-breaks.
1014
+ * Latency sits AFTER the quota check and not before it: a node whose GitHub quota is spent
1015
+ * still answers, so it keeps its place in the table, but it must not displace a node with
1016
+ * quota left merely by being faster. Among nodes that are equally clean, latency decides,
1017
+ * which is what "best" means to the person watching the panel.
957
1018
  *
958
1019
  * The node that just failed is not a candidate for its own replacement.
959
1020
  *
@@ -1002,30 +1063,35 @@ export class Runtime {
1002
1063
  }
1003
1064
  this.lastMatrix = rows.map((row) => ({ name: row.name, results: row.results }))
1004
1065
 
1005
- // Usable first, then fastest warm latency, then fewest failures, then a limited node before
1006
- // an unreachable one. Missing latency sorts last among usable nodes: a node whose speed could
1007
- // not be measured is not the one to prefer.
1008
- const rank = (row) => [
1009
- row.verdict?.usable === true ? 0 : 1,
1010
- typeof row.latency === 'number' ? row.latency : Number.POSITIVE_INFINITY,
1011
- (row.verdict?.failed ?? []).length,
1012
- (row.verdict?.blocked ?? []).length,
1013
- ]
1014
- rows.sort((a, b) => {
1015
- const ra = rank(a)
1016
- const rb = rank(b)
1017
- for (let i = 0; i < ra.length; i += 1) {
1018
- if (ra[i] !== rb[i]) return ra[i] - rb[i]
1019
- }
1020
- return a.name.localeCompare(b.name)
1021
- })
1022
- const best = rows[0]
1066
+ // rankHealth (lib/watch.js) is the single definition of "better node": usable first, then
1067
+ // fewest blocked probes, then a quota-clean node before a rate-limited one, then Google
1068
+ // latency. This path used to carry its own ordering -- usable, latency, failures -- which never
1069
+ // consulted degraded, so a rate-limited node that happened to answer faster beat a quota-clean
1070
+ // one and the switch landed on exactly the node the plugin itself called limited. Two
1071
+ // orderings for one question is how that happened; there is now one.
1072
+ const ranked = rankHealth(rows)
1073
+ rows.sort((a, b) => ranked.indexOf(a) - ranked.indexOf(b))
1074
+ // What counts as an improvement depends on why the search started. When the live node is
1075
+ // actually failing, any usable node is better. When it merely ran out of quota, only a
1076
+ // quota-clean node is: a different rate-limited node would answer exactly as well, and the
1077
+ // switch would tear down every connection in flight to get there. rankHealth already puts a
1078
+ // clean node first, so this only ever declines a candidate set that had no clean node at all.
1079
+ const liveUsable = report.verdict?.usable === true
1080
+ const improves = (row) =>
1081
+ row.verdict?.usable === true && (liveUsable !== true || row.verdict?.degraded !== true)
1082
+ const best = rows.find(improves)
1023
1083
  const tested = rows.length
1024
1084
  const elapsedMs = Date.now() - startedAt
1025
1085
 
1026
- if (best === undefined || best.verdict?.usable !== true) {
1086
+ if (best === undefined) {
1087
+ // Two different dead ends share this branch, and they must not report the same thing. A
1088
+ // node that FAILED cannot carry traffic, so "no alternative" is the plain truth. A node
1089
+ // that is merely out of quota is still carrying traffic right now; telling the reader it
1090
+ // is unusable because no cleaner node was found would be a lie about the line they are
1091
+ // using, so that case keeps the limited state it arrived with.
1092
+ const deadEnd = liveUsable === true ? 'no-clean-alternative' : 'no-alternative'
1027
1093
  this.lastSwitch = {
1028
- state: 'no-alternative',
1094
+ state: deadEnd,
1029
1095
  from: report.node,
1030
1096
  at: new Date().toISOString(),
1031
1097
  tested,
@@ -1033,8 +1099,12 @@ export class Runtime {
1033
1099
  // Every candidate's reason, so "no alternative" can be audited instead of trusted.
1034
1100
  rejected: rows.slice(0, 8).map((row) => ({ name: row.name, failed: row.verdict?.failed ?? [], latency: row.latency })),
1035
1101
  }
1036
- this.log(`no usable alternative to ${report.node} out of ${tested} tested`)
1037
- return { ...report, state: 'no-alternative', tested, elapsedMs }
1102
+ this.log(
1103
+ liveUsable === true
1104
+ ? `${report.node} is rate-limited but no quota-clean alternative exists out of ${tested} tested; keeping it`
1105
+ : `no usable alternative to ${report.node} out of ${tested} tested`,
1106
+ )
1107
+ return { ...report, state: liveUsable === true ? "limited" : "no-alternative", tested, elapsedMs }
1038
1108
  }
1039
1109
 
1040
1110
  await this.core.select(best.name)
@@ -1079,15 +1149,76 @@ export class Runtime {
1079
1149
  if (report.state === 'switched') {
1080
1150
  return { state: 'switched', from: report.from, to: report.to, failed: report.failed, required: report.required, verdict: report.verdict }
1081
1151
  }
1082
- if (report.state === 'ok' || report.state === 'degraded') {
1083
- return { state: 'kept', node: report.node, required: report.required, results: report.results, verdict: report.verdict, latency: report.latency }
1152
+ if (report.state === 'ok' || report.state === 'degraded' || report.state === 'limited') {
1153
+ // `limited` lands here on purpose: the node answered, it is carrying traffic, and no
1154
+ // quota-clean replacement existed. That is a KEPT node with a caveat, not a lost one.
1155
+ return {
1156
+ state: report.state === 'limited' ? 'limited' : 'kept',
1157
+ node: report.node,
1158
+ required: report.required,
1159
+ results: report.results,
1160
+ verdict: report.verdict,
1161
+ latency: report.latency,
1162
+ limited: report.verdict?.limited ?? [],
1163
+ }
1084
1164
  }
1085
- if (report.state === 'no-alternative') {
1086
- return { state: 'no-alternative', lostNode: report.node, failed: report.verdict?.failed ?? [], required: report.required }
1165
+ if (report.state === 'no-alternative' || report.state === 'slow') {
1166
+ return { state: report.state, lostNode: report.node, failed: report.verdict?.failed ?? [], required: report.required }
1087
1167
  }
1088
1168
  return report
1089
1169
  }
1090
1170
 
1171
+ /**
1172
+ * Turn a health round report into the sentence a person reads.
1173
+ *
1174
+ * A method rather than inline tool code because the wording IS the behaviour being fixed here,
1175
+ * and the three ways it went wrong all need to be assertable: calling a node that is carrying
1176
+ * traffic "unusable", describing an in-round retry count as a number of failed rounds, and
1177
+ * printing undefined for a field that only some states ever set.
1178
+ */
1179
+ describeHealth(report) {
1180
+ const describeProbe = (row) => {
1181
+ if (row === undefined) return '无响应'
1182
+ if (row.ok === true) return `${row.ms} ms`
1183
+ if (row.state === 'limited') {
1184
+ return row.reason === 'rate-limited-in-body' || row.reason === 'status-403'
1185
+ ? `限流(HTTP ${row.status})`
1186
+ : row.remaining !== undefined
1187
+ ? `配额耗尽(剩余 ${row.remaining}${row.resetAt === undefined ? '' : `,${row.resetAt} 重置`})`
1188
+ : `受限(${row.reason})`
1189
+ }
1190
+ return `不通(${row.reason})`
1191
+ }
1192
+ // The vocabulary has to match how a round actually works: one round makes `attemptLimit`
1193
+ // attempts back to back, and only a hard failure counts a strike ACROSS rounds. Saying
1194
+ // "failed N rounds in a row" for an in-round count was simply wrong.
1195
+ const tries = report.attempts?.length ?? report.attemptLimit ?? 3
1196
+ const streak = report.strikes === undefined ? '' : `(连续失败 ${report.strikes}/${report.strikeLimit} 轮)`
1197
+ const lines = [
1198
+ report.state === 'ok'
1199
+ ? `节点「${report.node}」全部必需探测通过${streak}。`
1200
+ : report.state === 'slow'
1201
+ ? `节点「${report.node}」本轮连测 ${tries} 次都超过延迟上限(${report.latency} ms > ${report.ceiling} ms)${streak}。`
1202
+ : report.state === 'limited'
1203
+ ? `节点「${report.node}」连测 ${tries} 次仍被限流(${(report.verdict?.limited ?? []).join(',')}),但常规联网不受影响;没找到配额干净的替代节点,暂不切换。`
1204
+ : report.state === 'switched'
1205
+ ? `节点「${report.from}」本轮连测 ${tries} 次不合格${streak},已自动切到「${report.to}」${report.toLatency === undefined ? '' : `(${report.toLatency} ms)`}。`
1206
+ : report.state === 'no-alternative'
1207
+ ? `节点「${report.node}」本轮连测 ${tries} 次不合格${streak},但没有其他节点通过探测(已测 ${report.tested} 个)。`
1208
+ : report.state === 'switch-deferred'
1209
+ ? `节点「${report.node}」本轮连测 ${tries} 次不合格${streak},但有 ${report.connections} 条连接在进行,本轮不切换。`
1210
+ : report.state === 'bad'
1211
+ ? `节点「${report.node}」本轮连测 ${tries} 次不合格${streak}。`
1212
+ : `本轮未执行:${report.state}`,
1213
+ ]
1214
+ const probes = report.results ?? {}
1215
+ if (Object.keys(probes).length > 0) {
1216
+ lines.push('探测明细:')
1217
+ for (const [id, row] of Object.entries(probes)) lines.push(` ${row.label ?? id}:${describeProbe(row)}`)
1218
+ }
1219
+ return lines.join('\n')
1220
+ }
1221
+
1091
1222
  /**
1092
1223
  * Arm the single health/selection round.
1093
1224
  *
@@ -1941,7 +2072,17 @@ export class Runtime {
1941
2072
  })),
1942
2073
  },
1943
2074
  /** Whether a download could be attempted at all on this platform. */
1944
- platformSupported: platformKey() !== undefined,
2075
+ /**
2076
+ * Whether a core can be obtained on this platform at all.
2077
+ *
2078
+ * `platformKey()` only says the release has an asset for this pair. Reporting that alone as
2079
+ * "supported" was wrong on Linux: the panel said yes while both acquisition paths refused —
2080
+ * there is no vendored copy for it, and a pinned `coreVersion` had no digest entry. What
2081
+ * actually matters is whether at least one path exists, so both are checked and the answer
2082
+ * says which one it is.
2083
+ */
2084
+ platformSupported: platformKey() !== undefined || vendoredFor() !== undefined,
2085
+ coreSource: vendoredFor() !== undefined ? 'bundled' : platformKey() !== undefined ? 'download' : undefined,
1945
2086
  degraded: this.degraded,
1946
2087
  lastError: this.lastError ?? this.core?.lastError,
1947
2088
  probe: this.lastProbe,
@@ -2189,46 +2330,20 @@ function subscriptionTool(runtime) {
2189
2330
  ...result,
2190
2331
  summary: result.state === 'kept'
2191
2332
  ? '当前节点「' + result.node + '」仍能访问全部必需服务(' + (result.required ?? []).join('/') + '),未切换。'
2192
- : result.state === 'switched'
2193
- ? '已从「' + result.from + '」切到「' + result.to + '」(原节点失去 ' + (result.failed ?? []).join(',') + ')。'
2194
- : result.state === 'selected'
2195
- ? '已选「' + result.chosen + '」。'
2196
- : '没有可用节点:' + (result.required ?? []).join(', ') + ' 无法全部访问。',
2333
+ : result.state === 'limited'
2334
+ ? '当前节点「' + result.node + '」限流(' + (result.limited ?? []).join(',') + '),但常规联网正常;没有找到配额干净的替代节点,保留当前节点。'
2335
+ : result.state === 'switched'
2336
+ ? '已从「' + result.from + '」切到「' + result.to + '」(原节点失去 ' + (result.failed ?? []).join(',') + ')。'
2337
+ : result.state === 'selected'
2338
+ ? '已选「' + result.chosen + '」。'
2339
+ : result.state === 'switch-deferred'
2340
+ ? '当前节点「' + result.node + '」不合格,但有 ' + result.connections + ' 条连接在进行,本轮不切换。'
2341
+ : '没有可用节点:' + (result.required ?? []).join(', ') + ' 无法全部访问。',
2197
2342
  }
2198
2343
  }
2199
2344
  if (action === 'health') {
2200
2345
  const report = await runtime.healthRound({ force: true })
2201
- const describeProbe = (row) => {
2202
- if (row === undefined) return '无响应'
2203
- if (row.ok === true) return `${row.ms} ms`
2204
- if (row.state === 'limited') {
2205
- return row.reason === 'rate-limited-in-body' || row.reason === 'status-403'
2206
- ? `限流(HTTP ${row.status})`
2207
- : row.remaining !== undefined
2208
- ? `配额耗尽(剩余 ${row.remaining}${row.resetAt === undefined ? '' : `,${row.resetAt} 重置`})`
2209
- : `受限(${row.reason})`
2210
- }
2211
- return `不通(${row.reason})`
2212
- }
2213
- const lines = [
2214
- report.state === 'ok'
2215
- ? `节点「${report.node}」全部必需探测通过(连续失败 ${report.strikes}/${report.strikeLimit})。`
2216
- : report.state === 'switched'
2217
- ? `节点「${report.from}」连续 ${report.strikes} 轮不可用,已自动切到「${report.to}」。`
2218
- : report.state === 'no-alternative'
2219
- ? `节点「${report.node}」连续 ${report.strikes} 轮不可用,但没有其他节点通过探测(已测 ${report.tested} 个)。`
2220
- : report.state === 'switch-deferred'
2221
- ? `节点「${report.node}」已连续 ${report.strikes} 轮不可用,但有 ${report.connections} 条连接在进行,本轮不切换。`
2222
- : report.state === 'bad'
2223
- ? `节点「${report.node}」本轮不可用(连续 ${report.strikes}/${report.strikeLimit})。`
2224
- : `本轮未执行:${report.state}`,
2225
- ]
2226
- const probes = report.results ?? {}
2227
- if (Object.keys(probes).length > 0) {
2228
- lines.push('探测明细:')
2229
- for (const [id, row] of Object.entries(probes)) lines.push(` ${row.label ?? id}:${describeProbe(row)}`)
2230
- }
2231
- return { ...report, summary: lines.join('\n') }
2346
+ return { ...report, summary: runtime.describeHealth(report) }
2232
2347
  }
2233
2348
  if (action === 'test') {
2234
2349
  const target = String(args?.node ?? '').trim()
package/lib/corefetch.js CHANGED
@@ -22,8 +22,10 @@
22
22
  */
23
23
  import { createHash } from 'node:crypto'
24
24
  import { spawn } from 'node:child_process'
25
- import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
25
+ import { createReadStream, createWriteStream, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
26
+ import { open } from 'node:fs/promises'
26
27
  import { join } from 'node:path'
28
+ import { createGunzip } from 'node:zlib'
27
29
 
28
30
  /**
29
31
  * Mirror prefixes tried before the direct GitHub URL.
@@ -84,6 +86,36 @@ export const KNOWN_ARCHIVES = {
84
86
  size: 22417383,
85
87
  archive: 'zip',
86
88
  },
89
+ // Every Linux and macOS asset is a bare gzip-compressed binary, not a tar — see
90
+ // `unpackCore`. The `-compatible` builds are preferred for the same reason as on Windows:
91
+ // they are compiled for the oldest supported CPU baseline, so a `v3`-style build cannot
92
+ // crash on an older machine with SIGILL. Ubuntu 24.04 and 26.04 both run these: the payload
93
+ // is statically linked (no PT_INTERP, no GLIBC_* symbols), so the distro's glibc version is
94
+ // irrelevant.
95
+ 'linux-x64': {
96
+ url: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.19.34/mihomo-linux-amd64-compatible-v1.19.34.gz',
97
+ digest: '2763f5b414527f7baf6dc57e3f82f3ab561eedf34bfd7c2f2cde1f7e592efe06',
98
+ size: 22766457,
99
+ archive: 'gz',
100
+ },
101
+ 'linux-arm64': {
102
+ url: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.19.34/mihomo-linux-arm64-v1.19.34.gz',
103
+ digest: 'daaf78a6240a282cdfd75bcbf98fe321f6bd52765cc29e79f344191198f0b50f',
104
+ size: 20684679,
105
+ archive: 'gz',
106
+ },
107
+ 'darwin-x64': {
108
+ url: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.19.34/mihomo-darwin-amd64-compatible-v1.19.34.gz',
109
+ digest: '703bceaa494732fa456f47e6ac2f06bf0bc5593d4c927d5f61e10f1a31039c37',
110
+ size: 22213898,
111
+ archive: 'gz',
112
+ },
113
+ 'darwin-arm64': {
114
+ url: 'https://github.com/MetaCubeX/mihomo/releases/download/v1.19.34/mihomo-darwin-arm64-v1.19.34.gz',
115
+ digest: '1a7a20eca63fbbaec90137717465bfde488d0db2a3a79b8fadebf9b2545b6e4c',
116
+ size: 20649699,
117
+ archive: 'gz',
118
+ },
87
119
  },
88
120
  }
89
121
 
@@ -524,13 +556,23 @@ function runTool(command, args) {
524
556
  /**
525
557
  * Unpack the archive and move the executable into place.
526
558
  *
527
- * `tar` is used for `.gz` on every platform (it is present on Windows 10+, macOS and
528
- * Linux, and reads gzip natively). `.zip` also goes through `tar` on Windows, whose
529
- * bundled `bsdtar` reads zip; that avoids shipping an unzip library for one platform.
559
+ * Two archive shapes have to be handled, and conflating them is what broke Linux:
560
+ *
561
+ * 1. a **tar** (optionally gzipped) — the Windows release assets are `.zip`, whose entries
562
+ * carry the build-suffixed name;
563
+ * 2. a **bare gzip-compressed binary** — every Linux and macOS release asset is this shape.
564
+ * Measured on v1.19.34: `mihomo-linux-amd64-compatible-v1.19.34.gz` decompresses to a single
565
+ * 61 948 030-byte ELF with no `ustar` header at offset 257, and the darwin assets are the same
566
+ * with a Mach-O payload. `tar -xzf` cannot read either, so it failed with
567
+ * "Unrecognized archive format" *after* a successful 22 MB download.
568
+ *
569
+ * So a `.gz` is decompressed with `node:zlib` (no external tool, present on every Node ≥ 22
570
+ * build) and then classified: a tar payload is extracted with `tar`, a bare payload *is* the
571
+ * core and is moved straight into place. That also removes the dependency on `tar` being
572
+ * installed for the common Linux case, which matters on slim Ubuntu images.
530
573
  *
531
- * The archive's own file name is not trusted to equal the final name: whichever file
532
- * looks like the core is renamed, so a release that changes its internal name keeps
533
- * working.
574
+ * The archive's own file name is not trusted to equal the final name: whichever file looks like
575
+ * the core is renamed, so a release that changes its internal name keeps working.
534
576
  *
535
577
  * @param archivePath - downloaded archive.
536
578
  * @param kind - `zip` or `gz`.
@@ -541,34 +583,137 @@ function runTool(command, args) {
541
583
  export async function unpackCore(archivePath, kind, workDir, finalPath) {
542
584
  mkdirSync(workDir, { recursive: true })
543
585
  if (kind === 'gz') {
544
- // -z: gzip, -x: extract, -f: file, -O: to stdout would lose the name; extract then find.
545
- await runTool('tar', ['-xzf', archivePath, '-C', workDir])
546
- } else if (kind === 'zip') {
547
- await runTool('tar', ['-xf', archivePath, '-C', workDir])
548
- } else {
549
- throw new Error(`unsupported archive kind "${kind}"`)
586
+ // 1. Decompress once, to a file. Streaming keeps the 61 MB payload off the heap.
587
+ const inflated = join(workDir, 'payload.bin')
588
+ await gunzipFile(archivePath, inflated)
589
+ // 2. Is the payload a tar? A POSIX tar carries "ustar" at offset 257 of its header block.
590
+ if (await isTarArchive(inflated)) {
591
+ // Some releases ship `mihomo-linux-amd64-v1.19.34.gz` where the .gz wraps a tar.
592
+ await runTool('tar', ['-xf', inflated, '-C', workDir])
593
+ const source = pickCoreFrom(workDir)
594
+ return await placeCore(source, finalPath)
595
+ }
596
+ // 3. A bare binary: it is the core, already fully decompressed.
597
+ return await placeCore(inflated, finalPath)
598
+ }
599
+
600
+ if (kind === 'zip') {
601
+ // `.zip` only ever arrives on Windows (its assets are the only zip ones), where the bundled
602
+ // `bsdtar` reads it. On Linux `unzip` is tried first and `tar` second, because GNU tar cannot
603
+ // read zip and a stock Ubuntu image may have either tool or neither — the error names both.
604
+ if (process.platform === 'win32') {
605
+ await runTool('tar', ['-xf', archivePath, '-C', workDir])
606
+ } else {
607
+ try {
608
+ await runTool('unzip', ['-o', '-q', archivePath, '-d', workDir])
609
+ } catch (first) {
610
+ try {
611
+ await runTool('tar', ['-xf', archivePath, '-C', workDir])
612
+ } catch (second) {
613
+ throw new Error(
614
+ `could not unpack ${archivePath}: neither \`unzip\` nor a zip-capable \`tar\` worked ` +
615
+ `(unzip: ${first?.message ?? first}; tar: ${second?.message ?? second}). ` +
616
+ `Install unzip, or download the .gz asset for this platform instead.`,
617
+ )
618
+ }
619
+ }
620
+ }
621
+ return await placeCore(pickCoreFrom(workDir), finalPath)
622
+ }
623
+
624
+ throw new Error(`unsupported archive kind "${kind}"`)
625
+ }
626
+
627
+ /**
628
+ * Stream a gzip file into a plain file.
629
+ *
630
+ * @param archivePath - the `.gz` file.
631
+ * @param destination - where the decompressed bytes go.
632
+ */
633
+ function gunzipFile(archivePath, destination) {
634
+ return new Promise((resolve, reject) => {
635
+ const input = createReadStream(archivePath)
636
+ const output = createWriteStream(destination)
637
+ const gunzip = createGunzip()
638
+ const fail = (error) => {
639
+ input.destroy()
640
+ output.destroy()
641
+ gunzip.destroy()
642
+ reject(error)
643
+ }
644
+ input.once('error', fail)
645
+ output.once('error', fail)
646
+ gunzip.once('error', fail)
647
+ output.once('finish', resolve)
648
+ input.pipe(gunzip).pipe(output)
649
+ })
650
+ }
651
+
652
+ /**
653
+ * Whether a file is a POSIX tar archive.
654
+ *
655
+ * @param path - file to test.
656
+ * @returns true when `ustar` sits at offset 257, which is where every tar variant puts it.
657
+ */
658
+ async function isTarArchive(path) {
659
+ const handle = await open(path, 'r')
660
+ try {
661
+ const buffer = Buffer.alloc(262)
662
+ const { bytesRead } = await handle.read(buffer, 0, 262, 0)
663
+ if (bytesRead < 262) return false
664
+ return buffer.subarray(257, 262).toString('latin1') === 'ustar'
665
+ } finally {
666
+ await handle.close()
550
667
  }
668
+ }
551
669
 
552
- const entries = readdirSync(workDir)
553
- // The archive names its payload after the build, not after the fixed name this plugin
554
- // stores it under: the Windows zip holds `mihomo-windows-amd64-compatible.exe`. Match the
555
- // build suffix rather than only the bare `mihomo.exe`, or a correct download is reported
556
- // as holding no core at all — which is exactly what happened on the first run.
670
+ /**
671
+ * Find the core executable among unpacked entries.
672
+ *
673
+ * @param workDir - directory holding unpacked files.
674
+ * @returns the path of the best candidate.
675
+ */
676
+ function pickCoreFrom(workDir) {
677
+ const entries = readdirSync(workDir).filter((name) => name !== 'payload.bin')
678
+ // The archive names its payload after the build, not after the fixed name this plugin stores it
679
+ // under: the Windows zip holds `mihomo-windows-amd64-compatible.exe`. Match the build suffix
680
+ // rather than only the bare name, or a correct download is reported as holding no core at all.
557
681
  const isCore = (name) =>
558
682
  /^(verge-)?mihomo([-.][\w.-]+)?(\.exe)?$/i.test(name) ||
559
683
  /^(verge-)?mihomo(-[\w.-]+)?\.exe$/i.test(name) ||
560
684
  /^clash(-meta)?([-.][\w.-]+)?(\.exe)?$/i.test(name)
561
685
  const wanted = entries.filter(isCore)
562
- // Prefer an exact `mihomo` / `mihomo.exe` when the archive ships several matches.
563
686
  wanted.sort((a, b) => Number(!/^(verge-)?mihomo(\.exe)?$/i.test(a)) - Number(!/^(verge-)?mihomo(\.exe)?$/i.test(b)))
564
- const source = wanted.length > 0 ? join(workDir, wanted[0]) : undefined
565
- if (source === undefined) {
687
+ if (wanted.length === 0) {
566
688
  throw new Error(`the archive held no core executable (found: ${entries.slice(0, 5).join(', ') || 'nothing'})`)
567
689
  }
690
+ return join(workDir, wanted[0])
691
+ }
692
+
693
+ /**
694
+ * Move a candidate into its final location and make it executable.
695
+ *
696
+ * @param source - the unpacked binary.
697
+ * @param finalPath - where it must live.
698
+ * @returns the path and its size.
699
+ */
700
+ async function placeCore(source, finalPath) {
568
701
  mkdirSync(join(finalPath, '..'), { recursive: true })
569
702
  if (existsSync(finalPath)) rmSync(finalPath, { force: true })
570
703
  renameSync(source, finalPath)
571
- if (process.platform !== 'win32') chmodSync(finalPath, 0o755)
704
+ // Linux and macOS refuse to exec a file without the execute bit, and the failure surfaces much
705
+ // later as an opaque EACCES from spawn. Applied on every non-Windows platform — and keyed on
706
+ // `process.platform`, which is genuinely the platform whose filesystem is being written, since
707
+ // the chmod has to land on the machine actually holding the file.
708
+ if (process.platform !== 'win32') {
709
+ try {
710
+ chmodSync(finalPath, 0o755)
711
+ } catch (error) {
712
+ // A read-only or noexec mount reports this; the caller's spawn will fail with a clearer
713
+ // message than a silent success would produce.
714
+ throw new Error(`could not make ${finalPath} executable: ${error?.message ?? error}`)
715
+ }
716
+ }
572
717
  return { path: finalPath, bytes: statSync(finalPath).size }
573
718
  }
574
719
 
package/lib/skill.js CHANGED
@@ -54,7 +54,7 @@ curl -sS -m 8 http://127.0.0.1:<宿主端口>/clash-proxy/status
54
54
  | \`routingVerified\` | 进程出网策略是不是本插件装的 | \`"active"\` |
55
55
  | \`routingHealthy\` | 策略 + 内核同时成立 | \`true\` |
56
56
  | \`node\` | 当前出口 | 具体节点名,不是 \`DIRECT\` |
57
- | \`health.lastRound.state\` | 最近一轮真实探测结论 | \`ok\` / \`degraded\` |
57
+ | \`health.lastRound.state\` | 最近一轮真实探测结论 | \`ok\` / \`limited\` / \`slow\` / \`switched\` / \`bad\` |
58
58
  | \`health.lastRound.attempt\` | 本轮第几次尝试通过的 | 1 或 2;3 表示三次都不合格 |
59
59
  | \`health.lastRound.attemptLimit\` | 一轮内最多试几次 | 3 |
60
60
 
@@ -109,11 +109,11 @@ env | grep -i proxy
109
109
  | \`usable\` | 含义 | 用它吗 |
110
110
  |---|---|---|
111
111
  | \`ok\` | 所有门槛探针通过 | 优先 |
112
- | \`limited\` | 线路正常,只是某个服务配额耗尽 | 可以,排在 \`ok\` 之后 |
112
+ | \`limited\` | 线路正常,只是某个服务配额耗尽 | 不主动选;只有没有 \`ok\` 节点时才留 |
113
113
  | \`blocked\` | 有探针硬失败(超时 / 重置 / 状态码不对) | 不要 |
114
114
 
115
- \`limited\` 是可用状态,不是故障。整个订阅的出口地址可能同时耗尽同一个配额,
116
- 这时坚持挑一个「配额干净」的节点只会把连接白断一次。
115
+ \`limited\` 是可用状态,不是故障,但它不是首选:自动切换只在找不到配额干净的节点时
116
+ 才留在 \`limited\` 节点上,并在报告里说清「限流、但常规联网不受影响」。
117
117
 
118
118
  换法:
119
119
 
@@ -130,12 +130,12 @@ clash_proxy action=select node=<精确节点名>
130
130
  1. 通过它发真请求(基础连通 204、GitHub API 连配额、git 拉取)+ 测 Google 延迟;
131
131
  2. 不合格就**立刻**再试一次,不合格再试第三次——不等下一个 30 秒;
132
132
  3. 只要任何一次合格就保持,剩下的次数不浪费;
133
- 4. 三次都不合格,就把**所有未被屏蔽的节点**各测一遍,切到「可用且真实延迟最低」的那个。
133
+ 4. 三次都不合格,就把**所有未被屏蔽的节点**各测一遍,按「连通且不限流 → Google 延迟」排序,切到排第一的那个。
134
134
 
135
135
  所以:
136
136
 
137
137
  - 用户问「为什么还没换」,先看 \`health.lastRound.attempt\`:1 或 2 表示已经通过;3 表示三次全败、正在切换。
138
- - 不合格 = **不可用**(某个门槛探针没通)**或真实延迟过高**(超过 \`health.maxDelayMs\`,默认 400 ms)。
138
+ - 不合格 = **不可用**(某个门槛探针没通)**、被限流**(如 GitHub 配额为 0)**或真实延迟过高**(超过 \`health.maxDelayMs\`,默认 400 ms)。带限流但没别的干净节点时,报告会说「限流」,不说「不可用」。
139
139
  - 三次重试是**同一轮内连续**的,所以坏节点几秒内就会被处理,不需要手动介入。
140
140
  - 手动换节点会打断正在进行的切换搜索,没必要别动它。
141
141
  - 要立刻验证,用 \`action=health\` 强制跑一轮并看明细。
@@ -151,6 +151,23 @@ clash_proxy action=select node=<精确节点名>
151
151
  | \`web_fetch\` 全部失败 | \`routingHealthy\` | 内核死了,级别 1 |
152
152
  | 只有某个 AI 服务连不上 | 该节点的 \`usable\` 与失败探针 | 该服务的地区/机房限制,换节点 |
153
153
  | 面板显示节点「限流」但还能上网 | —— | 正常,配额是单服务限制 |
154
+ | Linux 上首次启动很久没反应 | \`status.bootstrap\` | 正在下载 22 MB 内核,不是卡死 |
155
+
156
+ ## 五之二、Linux / Ubuntu 特有的事
157
+
158
+ Ubuntu 22.04 / 24.04 LTS / 26.04 LTS 都支持,且**不需要预装任何东西**。二进制是静态链接的(无 \`PT_INTERP\`、无 \`GLIBC_*\`),所以发行版 glibc 版本无关。
159
+
160
+ | 现象 | 真因 | 动作 |
161
+ |---|---|---|
162
+ | 首次启动什么都不发生,面板显示"未运行" | Linux 没有自带内核,需要下载 22 MB | 等首次下载完成(\`status.bootstrap\` 有进度),或点「下载内核」 |
163
+ | \`bootstrap\` 显示 \`Unrecognized archive format\` | 旧版用 \`tar -xzf\` 解 Linux 资产,而那是**裸 gzip 二进制**不是 tar | 升级到 0.10.0+(改用 \`node:zlib\` 解压) |
164
+ | \`no vendored core for linux-x64\` | 同上,旧版没有 Linux 自带内核且未开自动下载 | 升级,或设 \`corePath\` 指向已有的 \`mihomo\` |
165
+ | 内核文件存在但 \`spawn EACCES\` | 缺执行位 | \`chmod 755\` 那个 \`bin/mihomo\`;0.10.0+ 会自动设 |
166
+ | 下载卡住 | GitHub 在境内慢 | 插件会先试 gh-proxy.com / ghfast.top / ghproxy.net |
167
+
168
+ 内核落点固定为 \`\${DSH_HOME}/data/dsh-clash-proxy/bin/mihomo\`(Linux 上不带 \`.exe\`)。
169
+
170
+ **不要**用 \`apt install mihomo\` 之类的路径替换它:插件只认自己的二进制(或你显式配置的 \`corePath\`),混用系统的 Clash 会重演"两层代理互相抢"的老问题。
154
171
 
155
172
  ## 六、边界
156
173
 
package/lib/watch.js CHANGED
@@ -127,7 +127,16 @@ export class HealthWatch {
127
127
  * 2. `blocked` count, so a node failing two probes loses to one failing one;
128
128
  * 3. `degraded` (quota only) after plain-good — a rate-limited node still works, so it is the
129
129
  * right pick when nothing better exists, but not before a node with quota left;
130
- * 4. measured total, so among equals the fastest wins.
130
+ * 4. the lowest `latency` — the warm Google round trip, which is the number the ceiling is
131
+ * defined against and the number the panel shows;
132
+ * 5. measured probe total, as a last resort for rows that carry no latency (the startup matrix
133
+ * probes status codes only and never measures Google).
134
+ *
135
+ * Step 4 used to be step 5, and that was wrong: `latency` measures one static 204, while the
136
+ * probe total sums gstatic, the GitHub API and a git fetch, whose timings swing by seconds. On a
137
+ * live subscription the git fetch alone moved between 300 ms and 2 100 ms, so the total was
138
+ * dominated by the coldest probe rather than the line, and a node with a 100 ms Google round trip
139
+ * could lose to one with 300 ms purely because its git fetch was slow.
131
140
  *
132
141
  * `score` already folds 2 and 3 together arithmetically; the explicit fields are kept as the
133
142
  * comparison so the ordering survives someone changing the weight.
@@ -140,9 +149,19 @@ export function rankHealth(rows) {
140
149
  const good = (row) => (row.verdict?.usable === true ? 0 : 1)
141
150
  const blockedCount = (row) => (row.verdict?.blocked ?? []).length
142
151
  const degraded = (row) => (row.verdict?.degraded === true ? 1 : 0)
152
+ // A row with no measured latency sorts after every row that has one: a node whose speed is
153
+ // unknown must not win on the strength of a number that does not exist.
154
+ const latency = (row) =>
155
+ typeof row.latency === 'number' && Number.isFinite(row.latency) ? row.latency : Number.POSITIVE_INFINITY
143
156
  const score = (row) => Number(row.verdict?.score ?? 0)
144
157
  const total = (row) => Number(row.verdict?.total ?? Number.POSITIVE_INFINITY)
145
158
  return [...list].sort(
146
- (a, b) => good(a) - good(b) || blockedCount(a) - blockedCount(b) || degraded(a) - degraded(b) || score(a) - score(b) || total(a) - total(b),
159
+ (a, b) =>
160
+ good(a) - good(b) ||
161
+ blockedCount(a) - blockedCount(b) ||
162
+ degraded(a) - degraded(b) ||
163
+ latency(a) - latency(b) ||
164
+ score(a) - score(b) ||
165
+ total(a) - total(b),
147
166
  )
148
167
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-clash-subscription",
3
- "version": "0.9.0",
4
- "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin. Every 30 seconds the live node gets up to three immediate real-request attempts (base connectivity, GitHub quota, git fetch, Google latency median under a 400 ms ceiling); after three failures every unblocked node is measured and the fastest usable one is selected.",
3
+ "version": "0.11.0",
4
+ "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin. Runs on Windows, Linux (Ubuntu 22.04/24.04/26.04 LTS) and macOS: the core is fetched and SHA-256 verified on platforms without a bundled copy, from a bare gzip asset unpacked with node:zlib. Every 30 seconds the live node gets up to three immediate real-request attempts; a rate-limited node now counts as a problem, and after three failures every unblocked node is measured and the best one wins: connectivity and a clean quota before the lowest Google latency.",
5
5
  "keywords": [
6
6
  "dsh",
7
7
  "dsh-plugin",
@@ -34,7 +34,7 @@
34
34
  "locale/*.json",
35
35
  "icon.svg",
36
36
  "README.md",
37
- "CHANGELOG-0.9.0.md",
37
+ "CHANGELOG-0.11.0.md",
38
38
  "LICENSE"
39
39
  ],
40
40
  "engines": {
@@ -69,6 +69,7 @@
69
69
  "scripts": {
70
70
  "test": "node test/regression-070.mjs",
71
71
  "test:legacy": "node test/regression-063.mjs",
72
+ "test:linux": "node test/regression-0100.mjs",
72
73
  "test:e2e": "node test/e2e-090.mjs"
73
74
  }
74
75
  }
@@ -1,122 +0,0 @@
1
- # 0.9.0 · 一轮内连续 3 次尝试;不合格就测遍全部节点
2
-
3
- > 上一版 `0.8.0` · 本版 `0.9.0`
4
-
5
- ## 为什么改
6
-
7
- 0.8.0 把「连续 3 轮不合格」实现成了**跨轮累积**:每 30 秒记一次 strike,攒满 3 次才切换。
8
- 后果是一个坏节点要占着 90 秒以上才被处理,而且中途只要有一次抖动通过,计数清零、从头再攒。
9
-
10
- 用户要的是:**一次检测不合格就立刻再测,还不合格就立刻再测一次,三次都不合格才切换。**
11
-
12
- ## 改了什么
13
-
14
- ### 1. 三次尝试在一轮内连续完成
15
-
16
- ```
17
- 每 30 秒触发一轮:
18
- attempt 1 → 不合格
19
- attempt 2 → 立即重试(不等下一个 30 秒)→ 不合格
20
- attempt 3 → 立即再试 → 不合格
21
- ↓
22
- 测遍【全部未被屏蔽的节点】,切到最优
23
- ```
24
-
25
- 只要任何一次合格就保持,**剩下的次数不再浪费**(省配额)。
26
- 实测间隔:**7.4 秒 / 7.9 秒**,三次总跨度 15.4 秒。
27
-
28
- | 字段 | 默认 | 说明 |
29
- |---|---|---|
30
- | `healthAttempts` | **3** | 一轮内最多试几次;合格即停 |
31
- | `healthRoundSeconds` | 30 | 多久触发一轮 |
32
- | `healthStrikeLimit` | 3 | 保留作为跨轮兜底,正常路径不再依赖它 |
33
-
34
- ### 2. 不合格的定义:不可用 **或** 真实延迟过高
35
-
36
- | 判定 | 条件 |
37
- |---|---|
38
- | 不可用 | 某个门槛探针没通(gstatic 非 204 / GitHub 配额 0 / git 拉不到) |
39
- | 延迟过高 | Google 实测中位延迟 > `healthMaxDelayMs`(默认 400 ms) |
40
-
41
- 两者都写进 `verdict.failed`,所以面板能说清是哪一条。
42
-
43
- ### 3. 切换时测遍全部未被屏蔽节点
44
-
45
- `healthSwitchCandidates` 默认从 **12 改成 0 = 全部**。上限会把「找最优出口」变成
46
- 「在前 12 个里找最优」,54 节点的订阅可能因此错过更好的节点。
47
-
48
- 实测:8 节点订阅,去掉当前节点与被屏蔽的,**7/7 全测**。
49
-
50
- 排序规则(这是"最优"的定义):
51
-
52
- 1. 可用优先;
53
- 2. **真实延迟最低**(Google 中位);
54
- 3. 失败探针更少;
55
- 4. 限流优先于不通(配额会重置,线路坏不会)。
56
-
57
- 被屏蔽的节点不参与(`group.all` 本身已排除,代码里再用 `isBlocked` 兜一层)。
58
-
59
- ## 两个被真机测试逼出来的修正
60
-
61
- ### A. 单次延迟采样不可信 → 改中位数
62
-
63
- 同一节点同一分钟连续测 Google:
64
-
65
- ```
66
- 2256, 967, 1412, 179, 1190, 180 ms
67
- ```
68
-
69
- 拿一次采样比 400 ms 阈值,基本是掷骰子——慢但没坏的节点会被判死,快但很差的会被放过。
70
-
71
- 改成 **3 次采样取中位数**,且**丢掉第一次**(新内核首次要付 DNS+TCP+TLS,实测 513 ms vs 82 ms)。
72
- 新增 `healthLatencySamples`(默认 3,范围 2–5)。
73
-
74
- ### B. 测不到延迟时阈值会静默失效 → 加回落链
75
-
76
- `latency === undefined` 时,`tooSlow` 恒为 false,阈值**形同不存在**,一个 Google 不通的慢节点会被永久保留。
77
-
78
- 回落顺序:warm Google 中位 → cold Google → **最快的那条已通过的门槛探针**。
79
- 只有全都没答时才留 undefined,而那种节点已经因为门槛探针失败而被判不合格。
80
-
81
- `latencySource` 会标 `warm-median` / `cold` / `fallback-probe` / `unreachable`,面板能解释这个数从哪来。
82
-
83
- ## 验收
84
-
85
- ```
86
- node test/regression-070.mjs → 112 passed, 0 failed
87
- node test/regression-063.mjs → 31 passed, 0 failed
88
- node test/e2e-090.mjs → 13 passed, 0 failed(真内核 + 真订阅 + 真请求)
89
- ```
90
-
91
- e2e 真实输出:
92
-
93
- ```
94
- strict round: attempts=3
95
- attempt 1: usable=false latency=3544
96
- attempt 2: usable=false latency=3090
97
- attempt 3: usable=false latency=3445
98
- gaps between attempts: 7427, 7935 ms ← 立即重试,不是等 30 秒
99
- 三次尝试总跨度: 15362 ms(整轮含全节点实测 74622 ms)
100
- tested 7 candidate(s) of 7 unblocked non-live node(s) ← 全测
101
-
102
- measured (usable first, fastest first):
103
- 🇸🇬 新加坡01 usable=true latency=274
104
- 🇺🇸 美国01 usable=true latency=340
105
- 🇸🇬 新加坡02 usable=true latency=346
106
- 🇲🇾 马来西亚01 usable=true latency=352
107
- 🇹🇼 台湾02 usable=true latency=384
108
- 🇺🇸 美国02 usable=false latency=577
109
- ```
110
-
111
- ## 附带更新
112
-
113
- - 插件自带的 `clash-proxy-egress` 技能:把「连续 3 轮」改成「一轮内连续 3 次」,
114
- 判据从 `health.lastRound.strikes` 改成 `health.lastRound.attempt`,并写明
115
- 「不合格 = 不可用 或 延迟过高」与「三次全败会测遍全部未屏蔽节点」。
116
- - `status.health` 新增 `attempts`、`baselineProbe`、`switchCandidates` 字段。
117
-
118
- ## 遗留
119
-
120
- - `healthStrikeLimit` 仍然存在但正常路径不再驱动切换(同一轮内 3 次尝试已经取代它)。
121
- 保留是为了兼容旧配置不报错,后续版本可以考虑移除。
122
- - 面板新增字段(`healthAttempts`、`healthLatencySamples`)已接配置层,未在真浏览器里核对渲染。