dsh-clash-subscription 0.10.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/index.js CHANGED
@@ -794,7 +794,12 @@ export class Runtime {
794
794
  coldLatency = samples[0]
795
795
  const forMedian = samples.length > 1 ? samples.slice(1) : samples
796
796
  const sorted = [...forMedian].sort((a, b) => a - b)
797
- 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)
798
803
  latencySource = samples.length > 1 ? 'warm-median' : 'cold'
799
804
  } else {
800
805
  latencySource = 'unreachable'
@@ -865,6 +870,16 @@ export class Runtime {
865
870
 
866
871
  const attempts = Math.max(1, Number(this.config.healthAttempts ?? 3))
867
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.
868
883
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
869
884
  const measured = await this.measureNode(current, plan)
870
885
  if (measured === undefined) {
@@ -886,12 +901,22 @@ export class Runtime {
886
901
  this.lastMatrix = [{ name: current, results: measured.results }]
887
902
  this.lastCheckAt = Date.now()
888
903
 
889
- if (measured.verdict.usable === true) {
890
- // Kept. One good attempt ends the round; the remaining attempts are not spent, because
891
- // the node already answered the question this round is asking.
892
- 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 })
893
916
  const report = {
894
- 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',
895
920
  node: current,
896
921
  required: plan.gating,
897
922
  results: measured.results,
@@ -906,6 +931,8 @@ export class Runtime {
906
931
  attempts: tried,
907
932
  attemptLimit: attempts,
908
933
  giveUp: false,
934
+ strikes: watched.strikes,
935
+ strikeLimit: watched.limit,
909
936
  at: new Date().toISOString(),
910
937
  }
911
938
  this.health = report
@@ -921,18 +948,29 @@ export class Runtime {
921
948
  )
922
949
  }
923
950
 
924
- // Every attempt failed.
925
- this.watch.record(current, { usable: false, failed: tried.at(-1)?.failed ?? [], limited: [], blocked: [], score: 100 })
926
- const verdictNow = {
927
- usable: false,
928
- degraded: false,
929
- failed: tried.at(-1)?.failed ?? [],
930
- limited: [],
931
- blocked: [],
932
- slow: tried.every((entry) => entry.slow === true),
933
- }
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 })
934
972
  const report = {
935
- state: verdictNow.slow ? 'slow' : 'bad',
973
+ state: quotaOnly ? 'limited' : verdictNow.slow === true ? 'slow' : 'bad',
936
974
  node: current,
937
975
  required: plan.gating,
938
976
  verdict: verdictNow,
@@ -942,11 +980,17 @@ export class Runtime {
942
980
  attempt: attempts,
943
981
  attempts: tried,
944
982
  attemptLimit: attempts,
945
- giveUp: true,
983
+ giveUp: quotaOnly !== true,
984
+ strikes: watched.strikes,
985
+ strikeLimit: watched.limit,
946
986
  at: new Date().toISOString(),
947
987
  }
948
988
  this.health = report
949
- 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
+ )
950
994
  return await this.switchAfterStrikes(report, plan, options)
951
995
  } finally {
952
996
  this.healthRunning = false
@@ -962,12 +1006,15 @@ export class Runtime {
962
1006
  * worse node than one further down the list. `healthSwitchCandidates` still exists as an
963
1007
  * operator escape hatch for a huge subscription, but its default is 0 (everything).
964
1008
  *
965
- * "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.
966
1013
  *
967
- * 1. usable (no gating probe failed) before anything else;
968
- * 2. the lowest warm Google latency — this is the number the ceiling talks about, and the
969
- * fastest working node is what "最优" means here;
970
- * 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.
971
1018
  *
972
1019
  * The node that just failed is not a candidate for its own replacement.
973
1020
  *
@@ -1016,30 +1063,35 @@ export class Runtime {
1016
1063
  }
1017
1064
  this.lastMatrix = rows.map((row) => ({ name: row.name, results: row.results }))
1018
1065
 
1019
- // Usable first, then fastest warm latency, then fewest failures, then a limited node before
1020
- // an unreachable one. Missing latency sorts last among usable nodes: a node whose speed could
1021
- // not be measured is not the one to prefer.
1022
- const rank = (row) => [
1023
- row.verdict?.usable === true ? 0 : 1,
1024
- typeof row.latency === 'number' ? row.latency : Number.POSITIVE_INFINITY,
1025
- (row.verdict?.failed ?? []).length,
1026
- (row.verdict?.blocked ?? []).length,
1027
- ]
1028
- rows.sort((a, b) => {
1029
- const ra = rank(a)
1030
- const rb = rank(b)
1031
- for (let i = 0; i < ra.length; i += 1) {
1032
- if (ra[i] !== rb[i]) return ra[i] - rb[i]
1033
- }
1034
- return a.name.localeCompare(b.name)
1035
- })
1036
- 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)
1037
1083
  const tested = rows.length
1038
1084
  const elapsedMs = Date.now() - startedAt
1039
1085
 
1040
- 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'
1041
1093
  this.lastSwitch = {
1042
- state: 'no-alternative',
1094
+ state: deadEnd,
1043
1095
  from: report.node,
1044
1096
  at: new Date().toISOString(),
1045
1097
  tested,
@@ -1047,8 +1099,12 @@ export class Runtime {
1047
1099
  // Every candidate's reason, so "no alternative" can be audited instead of trusted.
1048
1100
  rejected: rows.slice(0, 8).map((row) => ({ name: row.name, failed: row.verdict?.failed ?? [], latency: row.latency })),
1049
1101
  }
1050
- this.log(`no usable alternative to ${report.node} out of ${tested} tested`)
1051
- 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 }
1052
1108
  }
1053
1109
 
1054
1110
  await this.core.select(best.name)
@@ -1093,15 +1149,76 @@ export class Runtime {
1093
1149
  if (report.state === 'switched') {
1094
1150
  return { state: 'switched', from: report.from, to: report.to, failed: report.failed, required: report.required, verdict: report.verdict }
1095
1151
  }
1096
- if (report.state === 'ok' || report.state === 'degraded') {
1097
- 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
+ }
1098
1164
  }
1099
- if (report.state === 'no-alternative') {
1100
- 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 }
1101
1167
  }
1102
1168
  return report
1103
1169
  }
1104
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
+
1105
1222
  /**
1106
1223
  * Arm the single health/selection round.
1107
1224
  *
@@ -2213,46 +2330,20 @@ function subscriptionTool(runtime) {
2213
2330
  ...result,
2214
2331
  summary: result.state === 'kept'
2215
2332
  ? '当前节点「' + result.node + '」仍能访问全部必需服务(' + (result.required ?? []).join('/') + '),未切换。'
2216
- : result.state === 'switched'
2217
- ? '已从「' + result.from + '」切到「' + result.to + '」(原节点失去 ' + (result.failed ?? []).join(',') + ')。'
2218
- : result.state === 'selected'
2219
- ? '已选「' + result.chosen + '」。'
2220
- : '没有可用节点:' + (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(', ') + ' 无法全部访问。',
2221
2342
  }
2222
2343
  }
2223
2344
  if (action === 'health') {
2224
2345
  const report = await runtime.healthRound({ force: true })
2225
- const describeProbe = (row) => {
2226
- if (row === undefined) return '无响应'
2227
- if (row.ok === true) return `${row.ms} ms`
2228
- if (row.state === 'limited') {
2229
- return row.reason === 'rate-limited-in-body' || row.reason === 'status-403'
2230
- ? `限流(HTTP ${row.status})`
2231
- : row.remaining !== undefined
2232
- ? `配额耗尽(剩余 ${row.remaining}${row.resetAt === undefined ? '' : `,${row.resetAt} 重置`})`
2233
- : `受限(${row.reason})`
2234
- }
2235
- return `不通(${row.reason})`
2236
- }
2237
- const lines = [
2238
- report.state === 'ok'
2239
- ? `节点「${report.node}」全部必需探测通过(连续失败 ${report.strikes}/${report.strikeLimit})。`
2240
- : report.state === 'switched'
2241
- ? `节点「${report.from}」连续 ${report.strikes} 轮不可用,已自动切到「${report.to}」。`
2242
- : report.state === 'no-alternative'
2243
- ? `节点「${report.node}」连续 ${report.strikes} 轮不可用,但没有其他节点通过探测(已测 ${report.tested} 个)。`
2244
- : report.state === 'switch-deferred'
2245
- ? `节点「${report.node}」已连续 ${report.strikes} 轮不可用,但有 ${report.connections} 条连接在进行,本轮不切换。`
2246
- : report.state === 'bad'
2247
- ? `节点「${report.node}」本轮不可用(连续 ${report.strikes}/${report.strikeLimit})。`
2248
- : `本轮未执行:${report.state}`,
2249
- ]
2250
- const probes = report.results ?? {}
2251
- if (Object.keys(probes).length > 0) {
2252
- lines.push('探测明细:')
2253
- for (const [id, row] of Object.entries(probes)) lines.push(` ${row.label ?? id}:${describeProbe(row)}`)
2254
- }
2255
- return { ...report, summary: lines.join('\n') }
2346
+ return { ...report, summary: runtime.describeHealth(report) }
2256
2347
  }
2257
2348
  if (action === 'test') {
2258
2349
  const target = String(args?.node ?? '').trim()
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\` 强制跑一轮并看明细。
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.10.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; 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.10.0.md",
37
+ "CHANGELOG-0.11.0.md",
38
38
  "LICENSE"
39
39
  ],
40
40
  "engines": {
@@ -1,127 +0,0 @@
1
- # 0.10.0 · 支持 Ubuntu(及 Linux / macOS)
2
-
3
- > 上一版 `0.9.0` · 本版 `0.10.0`
4
-
5
- ## 0.9.0 在 Ubuntu 上会怎样
6
-
7
- 能安装,能识别平台,能下载内核,**然后卡在解包**。
8
-
9
- ```
10
- core download 100%
11
- core bootstrap: verified
12
- THROWS: tar exited 1: tar: Error opening archive: Unrecognized archive format
13
- ```
14
-
15
- ## 根因:Linux 的 `.gz` 不是 tar
16
-
17
- mihomo 的 Linux 与 macOS 发布资产是**裸二进制经 gzip 压缩**,不是 tar 归档。实测三份:
18
-
19
- | 资产 | 解压后 | 形态 |
20
- |---|---|---|
21
- | `mihomo-linux-amd64-compatible-v1.19.34.gz` | 61 948 030 字节 | ELF64,`ustar`=false |
22
- | `mihomo-linux-arm64-v1.19.34.gz` | 57 344 126 字节 | ELF,`ustar`=false |
23
- | `mihomo-darwin-arm64-v1.19.34.gz` | 56 698 738 字节 | Mach-O,`ustar`=false |
24
-
25
- 而旧代码对所有 `.gz` 都执行 `tar -xzf`,它只能读 tar 归档。
26
-
27
- ## 改了什么
28
-
29
- ### 1. 解包器按内容判别,不再按扩展名
30
-
31
- ```
32
- .gz → node:zlib 流式解压 → 看 offset 257 是不是 "ustar"
33
- ├─ 是 → tar 解包(兼容真有 tar.gz 的发布)
34
- └─ 否 → 它本身就是内核,直接落位
35
- ```
36
-
37
- 不再依赖外部 `tar` 命令,**精简 Ubuntu 镜像没有 tar 也能用**。`.zip` 在 Linux 上改为先试 `unzip`、再试 `tar`,都失败时把两个错误一起报出来(GNU tar 读不了 zip)。
38
-
39
- ### 2. 补全 `KNOWN_ARCHIVES` 摘要
40
-
41
- 原来只有 `win32-x64`,导致在 Linux 上设 `coreVersion: 1.19.34` 直接抛
42
- `coreVersion 1.19.34 has no verified archive for linux-x64`。
43
-
44
- 现在五条齐全,摘要全部取自发布方 API 自述值,并与本地下载的字节**逐条比对一致**:
45
-
46
- | 平台 | 摘要(前 16 位) | 体积 |
47
- |---|---|---|
48
- | `linux-x64` | `2763f5b414527f7b` | 22 766 457 |
49
- | `linux-arm64` | `daaf78a6240a282c` | 20 684 679 |
50
- | `darwin-x64` | `703bceaa494732fa` | 22 213 898 |
51
- | `darwin-arm64` | `1a7a20eca63fbbae` | 20 649 699 |
52
- | `win32-x64` | `cd6738d4648cc1a5` | 22 417 383 |
53
-
54
- Linux x64 优先用 `-compatible` 构建(CPU 基线版本),避免 `v3` 类构建在旧机器上触发 SIGILL。
55
-
56
- ### 3. `platformSupported` 不再谎报
57
-
58
- 旧值只看 `platformKey()`(发布页有没有对应资产),在 Linux 上返回 `true`,但两条获取路径其实都抛错。现在要求「自带内核或可下载,至少一条成立」,并新增 `coreSource` 说明来源:
59
-
60
- ```
61
- platformSupported = true
62
- coreSource = download ← 或 "bundled"
63
- ```
64
-
65
- ### 4. 无自带内核的平台默认开启自动获取
66
-
67
- `autoFetchCore` 默认 `false`,而 Linux/macOS 没有自带内核——装完什么都不发生,看起来像坏掉。现在:**未显式配置且本平台无自带内核时,默认开启**。显式写 `false` 仍然尊重。
68
-
69
- ### 5. `chmod` 失败不再静默
70
-
71
- `placeCore` 里给执行位;失败时抛出明确错误(`could not make ... executable`),而不是让 spawn 之后蹦出一个莫名其妙的 `EACCES`。
72
-
73
- ## 关于 glibc / 发行版版本
74
-
75
- **不需要针对 Ubuntu 版本做任何适配**。验证方式不是读文档,而是解析 ELF 程序头:
76
-
77
- ```
78
- ELF class = 64-bit
79
- e_machine = x86-64
80
- PT_INTERP = NONE → 静态链接
81
- GLIBC_2. 符号 = 无
82
- libc.so / ld-linux 引用 = 无
83
- ```
84
-
85
- 静态链接意味着系统 glibc 完全不参与,**同一个二进制在 Ubuntu 22.04 / 24.04 LTS (Noble) / 26.04 LTS (Resolute Raccoon) 上都能跑**。
86
-
87
- ## 验收
88
-
89
- ```
90
- node test/regression-070.mjs → 113 passed, 0 failed
91
- node test/regression-063.mjs → 31 passed, 0 failed
92
- node test/regression-0100.mjs → 48 passed, 0 failed ← 新增(Ubuntu 适配)
93
- ```
94
-
95
- 新增测试里有几条是靠运行结果取证的:
96
-
97
- | 断言 | 证据 |
98
- |---|---|
99
- | 裸 gzip 能解包 | 构造裸 gzip → 解出 4100 字节,ELF 头完整 |
100
- | **负向对照**:`tar -xzf` 对同一文件确实失败 | `exit=1`(证明这个修复是必要的,不是装饰) |
101
- | tar.gz 形状仍能处理 | 现场打包 tar.gz → 成员正确取出 |
102
- | 真实资产 61 948 030 字节 | 用真下载的 22 766 457 字节 `.gz` 解包 |
103
- | 静态链接 | 遍历程序头,确认无 `PT_INTERP` |
104
- | 五平台矩阵 | 每对平台都有「自带或可下载」 |
105
-
106
- 端到端(模拟 Linux 平台,真下载 + 真解包):
107
-
108
- ```
109
- core bootstrap: resolved v1.19.34 → verified → installed
110
- bytes = 61948030
111
- ELF magic = 7f454c46 ✓
112
- ```
113
-
114
- ## 一个被测试抓到的自身 bug
115
-
116
- 给技能补 Linux 章节时写了 `${DSH_HOME}/data/...`,而技能正文是模板字符串——`${}` 被当成插值求值,导入直接 `ReferenceError: DSH_HOME is not defined`。
117
-
118
- 原有断言 `!content.includes('${')` 抓不到它,因为**模块根本没加载成功**,断言不会执行。补了两条真正有效的:
119
-
120
- ```
121
- ok 源码里没有未转义的 ${(会被当成插值求值)
122
- ok 源码里未转义的反引号成对(模板未被截断)
123
- ```
124
-
125
- ## 本机无法验证的一点(如实记录)
126
-
127
- `chmod 0755` 设执行位这件事在 Windows 上无法验证:NTFS 没有 POSIX 执行位,`chmodSync` 只能切只读属性,`mode & 0o111` 恒为 0。所以模拟运行里显示 `executable? = NO` 是本机文件系统的限制,不是代码缺陷——真 Ubuntu 上该分支会执行。要彻底证实,需要在真 Linux 上跑一次 `test/regression-0100.mjs`。