dsh-clash-subscription 0.10.0 → 0.12.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,159 @@
1
+ # 0.12.0 · 更新节点与订阅链接不再绕节点
2
+
3
+ > 上一版 `0.11.0` · 本版 `0.12.0`
4
+
5
+ ## 症状
6
+
7
+ 节点列表本来能更新,但一按「检测全部」就报不可达;有时能通,过一会儿同样的链接又报
8
+ `fetch failed`。把代理停掉再检测,反而正常。
9
+
10
+ 这类"时好时坏"的报告是最糟糕的一种:它让人以为是订阅站的问题,去换链接、去找客服,而
11
+ 真正的原因是**检测本身经过了要检测的东西**。
12
+
13
+ ## 根因:订阅检查走的是全局 dispatcher
14
+
15
+ 插件在 `routing.apply()` 里把 undici 的全局 dispatcher 指向自己的内核:
16
+
17
+ ```js
18
+ // lib/routing.js · 0.11.0
19
+ this.dispose = await this.proxyModule.installProxyFromEnvironment(env, …)
20
+ const undici = await import(pathToFileURL(this.undiciPath).href)
21
+ this.installed = undici.getGlobalDispatcher()
22
+ ```
23
+
24
+ 那是**给整个进程用的**,插件自己的订阅检测也在里面。而 `lib/subscription.js` 的
25
+ `probeSubscription()` 写的是:
26
+
27
+ ```js
28
+ const request = options.fetch ?? fetch // 没有 options.fetch 时就是全局 fetch
29
+ ```
30
+
31
+ 两条叠起来就是:检查订阅链接的请求,先被送进本地内核,再由某个节点送出去。于是
32
+
33
+ - **节点挂了,链接被判不可达。** 订阅站明明是好的,报告却说是坏的。
34
+ - **检测在花节点的配额。** 「查一下链接」这个动作本身消耗掉它要评估的那个节点的额度。
35
+ - **同一个链接两次答案不同。** 中途换了节点,答案就跟着变,而链接一个字都没改。
36
+
37
+ `startInner()` 里的顺序把这一点钉死了:`routing.apply()` 在第 1746 行,`probeEntries()`
38
+ 在第 1757 行——首次启动的探测必然在代理装好之后执行。
39
+
40
+ 内核侧(拉取订阅内容)本来就没问题:`proxy-providers` 不写 `proxy:` 时 mihomo 走直连。
41
+ 用真机内核三组对照验证过(每变体独立 work 目录以排除缓存):
42
+
43
+ | provider 配置 | `updatedAt` | `nodes` | 结论 |
44
+ |---|---|---|---|
45
+ | `proxy: 'DIRECT'` | 2026-11-26T07:55:55Z | 55 | 直连拉取正常 |
46
+ | `proxy: 'NO-SUCH-NODE'` | `0001-01-01T00:00:00Z` | 0 | 字段真的生效,且名字被严格校验 |
47
+ | 省略 `proxy` 键 | 2026-11-26T07:56:30Z | 55 | 默认直连 |
48
+ | `proxy: 'PROXY'` | 2026-11-26T07:57:42Z | 55 | 也能拉到(走组) |
49
+
50
+ 顺带记一笔:`mihomo -t` 只验 YAML/JSON 结构,**不验** `proxy` 指向的节点是否存在——
51
+ 两个变体都返回 `test is successful`。证明这个字段生效只能看真机
52
+ `/providers/proxies/<name>` 的 `updatedAt` + `nodes`。
53
+
54
+ ## 改法一:插件侧检查改走直连 dispatcher
55
+
56
+ undici 是**按请求**解析 dispatcher 的,所以带 `dispatcher` 的请求会绕开全局那个,而不动
57
+ 进程其余部分的策略。新增 `lib/direct.js`:
58
+
59
+ ```js
60
+ export class DirectLine {
61
+ constructor({ undiciPath, logger, connectTimeoutMs = 20_000 }) { … }
62
+
63
+ async connect() { // 首次使用时建 agent,之后复用
64
+ if (this.agent !== undefined) return this.fetch
65
+ if (this.pending === undefined) {
66
+ this.pending = (async () => {
67
+ const undici = await import(pathToFileURL(this.undiciPath).href)
68
+ this.undici = undici
69
+ this.agent = new undici.Agent({ connect: { timeout: this.connectTimeoutMs } })
70
+ return this.fetch
71
+ })()
72
+ …
73
+ }
74
+ return await this.pending
75
+ }
76
+
77
+ async fetch(url, init = {}) {
78
+ await this.connect()
79
+ return await this.undici.fetch(url, { ...init, dispatcher: this.agent })
80
+ }
81
+ }
82
+ ```
83
+
84
+ `index.js` 的 `Runtime` 持有它(`probeFetch()` / `ensureDirectLine()`),两个检测入口都把
85
+ 它注入 `probeSubscriptions`:
86
+
87
+ ```js
88
+ // probe(raw) 面板「检测全部」
89
+ const direct = await this.probeFetch()
90
+ const report = await probeSubscriptions(parsed.entries, { timeoutMs: 15_000, fetch: direct })
91
+ return { ...report, direct: direct !== undefined, … }
92
+
93
+ // probeEntries(entries) 启动后按 provider 汇总
94
+ const direct = await this.probeFetch()
95
+ const report = await probeSubscriptions(entries, { timeoutMs: 20_000, fetch: direct })
96
+ return { ...report, direct: direct !== undefined }
97
+ ```
98
+
99
+ `direct: false` 是**降级标记**,不是报错:这个安装根解析不到 `undici` 时退回全局 fetch,
100
+ 面板上会写明「直连不可用,这次检测走了已安装的代理」,而不是把一条好链接报成坏的。
101
+
102
+ agent 按需创建、跨多次检测复用(多订阅时每条重新握手比检测本身还贵),`stop()` 时关闭。
103
+
104
+ ## 改法二:内核侧显式写 `proxy: 'DIRECT'`
105
+
106
+ 内核默认直连是**没写下来的默认**。插件不该静默依赖一个没写下来的行为——哪天它变了,
107
+ 订阅下载就会悄悄开始花节点配额。所以 `lib/core.js` 的 `buildConfig` 现在把意图写进配置:
108
+
109
+ ```js
110
+ const proxyTarget = String(providerProxy ?? 'DIRECT').trim()
111
+ …
112
+ providers[name] = {
113
+ type: 'http',
114
+ url: …,
115
+ interval: 3600,
116
+ path: …,
117
+ ...(proxyTarget === '' ? {} : { proxy: proxyTarget }),
118
+ …
119
+ }
120
+ ```
121
+
122
+ `providerProxy` 留了覆盖口子(写成节点名就走代理,写成空串就交回内核默认),默认值就是用户
123
+ 要的行为。
124
+
125
+ ## 为什么这条改法能证明
126
+
127
+ `test/regression-0120.mjs` 不读源码文本,全部断言取运行结果。它起一个本机 HTTP 服务当订阅
128
+ 站,把全局 dispatcher 指到关闭的端口 `http://127.0.0.1:9` 复现「已装代理」的真实状态,并且
129
+ 故意把 `noProxy` 给空串——让连本机地址都被塞进死代理,取最坏情况:
130
+
131
+ | 断言 | 结果 |
132
+ |---|---|
133
+ | 负向对照:全局 fetch 经死代理取订阅 | `connect ECONNREFUSED 127.0.0.1:9`(证明「走代理」真的会挂) |
134
+ | `DirectLine` 用同一个 undici、同一个 URL | `200`,字节数与正文一致 |
135
+ | 同一 `DirectLine` 第二次取 | `200`(agent 复用成立) |
136
+ | `probeSubscriptions` 不注入 fetch | `ok: false`(这就是用户看到的症状) |
137
+ | `probeSubscriptions` 注入直连 fetch | `ok: true`,`nodeCount: 2`,`format: clash` |
138
+ | `runtime.probe()` 在死代理下 | `ok: true` 且 `direct: true` |
139
+ | `runtime.probeEntries()` 在死代理下 | `ok: true` 且 `direct: true` |
140
+ | `runtime.stop()` | 直连线路 `active: false`(不留悬挂连接) |
141
+ | `buildConfig` 产物 | `proxy-providers.sub0.proxy === 'DIRECT'` |
142
+
143
+ 四套回归:`regression-0120` 27 passed / `regression-070` 134 / `regression-0100` 48 /
144
+ `regression-063` 29,全绿。
145
+
146
+ ## 影响面
147
+
148
+ - 面板「检测全部」「首启探测」「内核拉取订阅」三条路都不再经过节点。
149
+ - 走节点的是**业务流量**——它本来就该走节点,这一点没变。
150
+ - 没有新增配置项:默认行为就是要的行为,不必让用户去开一个开关。
151
+ - `providerProxy` 是内部参数(不暴露在设置页),只在 `buildConfig` 的入参上。
152
+
153
+ ## 升级
154
+
155
+ ```
156
+ dsh plugin update dsh-clash-subscription
157
+ ```
158
+
159
+ 装完**完全退出 DSH 再打开**:宿主进程若早于文件改动启动,会继续跑旧代码。
package/README.md CHANGED
@@ -68,6 +68,16 @@ name — two providers routinely both name a node `香港01`, and without a pref
68
68
  duplicate names. A provider that fails to download shows `未拉到节点` on its own row and does
69
69
  not stop the others.
70
70
 
71
+ **Checks and downloads go direct.** The plugin installs itself as the process-wide outbound
72
+ policy, so a plain `fetch` — including this plugin's own subscription check — would travel
73
+ through a node. For the subscription link that is backwards: a dead or rate-limited node would
74
+ make a live link look broken, checking a link would spend the quota of the node it is meant to
75
+ evaluate, and the same link could report differently a minute apart. So the check carries its
76
+ own undici `dispatcher` (`lib/direct.js`), the same per-request override undici resolves
77
+ before the global one, and each core provider is written with `proxy: DIRECT` rather than
78
+ relying on the core's unwritten default. Business traffic still goes through the node; only
79
+ the link that supplies the nodes does not.
80
+
71
81
  ## Split routing
72
82
 
73
83
  | Destination | Path |
package/client.js CHANGED
@@ -19,6 +19,7 @@ const en = {
19
19
  probeOk: 'All {total} subscriptions reachable: {count} nodes, {size} KB.',
20
20
  probePartial: '{reachable}/{total} subscriptions reachable — see the rows below.',
21
21
  probeFailed: 'Check failed: {reason}',
22
+ probeViaProxy: 'Direct fetch was unavailable, so this check went through the installed proxy.',
22
23
  probeNeedsSave: 'Save first — this page writes the links, the running core reads the saved ones.',
23
24
  subscriptions: 'Subscriptions',
24
25
  subscriptionCount: '{count} configured',
@@ -153,6 +154,7 @@ const zh = {
153
154
  probeOk: '全部 {total} 条可达:共 {count} 个节点,{size} KB。',
154
155
  probePartial: '{reachable}/{total} 条可达——看下面的逐条结果。',
155
156
  probeFailed: '检测失败:{reason}',
157
+ probeViaProxy: '直连不可用,这次检测走了已安装的代理。',
156
158
  probeNeedsSave: '先保存——这个面板写的是配置,跑着的内核读的是已保存的那份。',
157
159
  subscriptions: '订阅列表',
158
160
  subscriptionCount: '已配置 {count} 条',
@@ -687,6 +689,7 @@ function Panel(props) {
687
689
  : fill(t('probePartial'), { reachable: answer.reachable ?? 0, total: answer.total ?? results.length })
688
690
  return h('div', { key: 'pr', className: 'clxp-probe', role: 'status' }, [
689
691
  h('p', { key: 'h', className: answer.ok ? 'clxp-ok' : 'clxp-error' }, headline),
692
+ ...(answer.direct === false ? [h('p', { key: 'd', className: 'clxp-note' }, t('probeViaProxy'))] : []),
690
693
  ...results.map((row) =>
691
694
  h('p', { key: `r-${row.provider ?? row.url}`, className: row.ok ? 'clxp-note' : 'clxp-error' }, [
692
695
  h('span', { key: 'n' }, `${row.name ?? row.url}:`),
package/index.js CHANGED
@@ -28,6 +28,7 @@ import { readInventory, rememberNodes } from './lib/inventory.js'
28
28
  import { summariseRows } from './lib/health.js'
29
29
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
30
30
  import { Routing } from './lib/routing.js'
31
+ import { DirectLine } from './lib/direct.js'
31
32
  import {
32
33
  displayName,
33
34
  effectiveSubscriptionText,
@@ -351,6 +352,16 @@ export class Runtime {
351
352
  this.binary = findCoreBinary(config.corePath, this.dataDir)
352
353
  this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger })
353
354
  this.routing = undefined
355
+ /**
356
+ * The direct line subscription checks use.
357
+ *
358
+ * Built on first use: an installation whose `undici` cannot be resolved must still
359
+ * open the panel, report, and fall back to the installed policy rather than failing
360
+ * to load.
361
+ */
362
+ this.directLine = undefined
363
+ /** Why that line could not be built, so the panel can say which path it took. */
364
+ this.directError = undefined
354
365
  this.lastError = undefined
355
366
  this.lastProbe = undefined
356
367
  /** Result of the last core download, for the panel and the tool. */
@@ -794,7 +805,12 @@ export class Runtime {
794
805
  coldLatency = samples[0]
795
806
  const forMedian = samples.length > 1 ? samples.slice(1) : samples
796
807
  const sorted = [...forMedian].sort((a, b) => a - b)
797
- latency = sorted[Math.floor(sorted.length / 2)]
808
+ // True median. Indexing at floor(n / 2) is the median only for odd n; at n = 2 it
809
+ // returned the SLOWER of the two warm samples (measured: 513, 420, 380 -> 420 while the
810
+ // real median is 380). That biased every two-sample node towards the ceiling and pushed
811
+ // healthy nodes into failed: latency -- the other half of picking the rate-limited node.
812
+ const mid = sorted.length >> 1
813
+ latency = sorted.length % 2 === 1 ? sorted[mid] : Math.round((sorted[mid - 1] + sorted[mid]) / 2)
798
814
  latencySource = samples.length > 1 ? 'warm-median' : 'cold'
799
815
  } else {
800
816
  latencySource = 'unreachable'
@@ -865,6 +881,16 @@ export class Runtime {
865
881
 
866
882
  const attempts = Math.max(1, Number(this.config.healthAttempts ?? 3))
867
883
  const tried = []
884
+ // A round keeps retrying until it sees a node with no problem at all, not merely a node
885
+ // that can carry traffic. `limited` counts as a problem here even though judgeNodeHealth
886
+ // keeps `usable` true for it: a rate-limited node answers, so it can stay selected, but the
887
+ // whole point of the round is to notice it and move to a node with quota left. Accepting the
888
+ // first `usable` verdict is what let a node with GitHub quota 0 survive every round in a
889
+ // row "because it was usable", with the retries and the switch neither ever reached.
890
+ //
891
+ // `clean` is computed once per attempt rather than once above the loop: it is the verdict
892
+ // of THIS measurement, and a node that is limited on attempt 1 and clean on attempt 2 must
893
+ // end the loop at attempt 2.
868
894
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
869
895
  const measured = await this.measureNode(current, plan)
870
896
  if (measured === undefined) {
@@ -886,12 +912,22 @@ export class Runtime {
886
912
  this.lastMatrix = [{ name: current, results: measured.results }]
887
913
  this.lastCheckAt = Date.now()
888
914
 
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 })
915
+ const clean = measured.verdict.usable === true && measured.verdict.degraded !== true
916
+ // A node with no problem ends the round at once. A node that answered but is short on
917
+ // quota does NOT: it gets the remaining attempts like any other problem, and only when
918
+ // every attempt still shows a problem does the round search for a replacement. Note that
919
+ // this condition deliberately has no `attempt === attempts` escape hatch: a node that is
920
+ // still short on quota on its LAST attempt must fall out of the loop into the switch, and
921
+ // an escape hatch here would accept it instead -- which is the defect this loop exists to
922
+ // remove, reintroduced one branch lower.
923
+ if (clean === true) {
924
+ // Kept. The remaining attempts are not spent, because the node already answered the
925
+ // question this round is asking.
926
+ const watched = this.watch.record(current, measured.verdict, { probes: measured.results })
893
927
  const report = {
894
- state: measured.verdict.degraded === true ? 'degraded' : 'ok',
928
+ // `clean` above already excluded a degraded verdict, so this branch only ever
929
+ // reports ok. The old ternary kept a degraded arm that could no longer run.
930
+ state: 'ok',
895
931
  node: current,
896
932
  required: plan.gating,
897
933
  results: measured.results,
@@ -906,6 +942,8 @@ export class Runtime {
906
942
  attempts: tried,
907
943
  attemptLimit: attempts,
908
944
  giveUp: false,
945
+ strikes: watched.strikes,
946
+ strikeLimit: watched.limit,
909
947
  at: new Date().toISOString(),
910
948
  }
911
949
  this.health = report
@@ -921,18 +959,29 @@ export class Runtime {
921
959
  )
922
960
  }
923
961
 
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
- }
962
+ // Every attempt showed a problem.
963
+ //
964
+ // Two different problems end up here. A hard failure means the node cannot carry traffic at
965
+ // all, so it takes a strike and the search accepts any usable replacement. A node that is
966
+ // only short on quota CAN carry traffic, so it takes no strike -- but it still does not get
967
+ // to stay: the search runs anyway and only a quota-clean replacement displaces it, because
968
+ // swapping one rate-limited node for another tears down every connection in flight and
969
+ // buys nothing.
970
+ const last = tried.at(-1)
971
+ const quotaOnly = last?.usable === true
972
+ const verdictNow = quotaOnly
973
+ ? { usable: true, degraded: true, failed: last?.failed ?? [], limited: last?.failed ?? [], blocked: [], score: 1 }
974
+ : {
975
+ usable: false,
976
+ degraded: false,
977
+ failed: last?.failed ?? [],
978
+ limited: [],
979
+ blocked: [],
980
+ slow: tried.every((entry) => entry.slow === true),
981
+ }
982
+ const watched = this.watch.record(current, verdictNow, { probes: this.healthRows.get(current)?.results })
934
983
  const report = {
935
- state: verdictNow.slow ? 'slow' : 'bad',
984
+ state: quotaOnly ? 'limited' : verdictNow.slow === true ? 'slow' : 'bad',
936
985
  node: current,
937
986
  required: plan.gating,
938
987
  verdict: verdictNow,
@@ -942,11 +991,17 @@ export class Runtime {
942
991
  attempt: attempts,
943
992
  attempts: tried,
944
993
  attemptLimit: attempts,
945
- giveUp: true,
994
+ giveUp: quotaOnly !== true,
995
+ strikes: watched.strikes,
996
+ strikeLimit: watched.limit,
946
997
  at: new Date().toISOString(),
947
998
  }
948
999
  this.health = report
949
- this.log(`${attempts} attempts all failed on ${current}; searching every unblocked node`)
1000
+ this.log(
1001
+ quotaOnly
1002
+ ? `${attempts} attempts on ${current} all rate-limited; looking for a quota-clean node`
1003
+ : `${attempts} attempts all failed on ${current}; searching every unblocked node`
1004
+ )
950
1005
  return await this.switchAfterStrikes(report, plan, options)
951
1006
  } finally {
952
1007
  this.healthRunning = false
@@ -962,12 +1017,15 @@ export class Runtime {
962
1017
  * worse node than one further down the list. `healthSwitchCandidates` still exists as an
963
1018
  * operator escape hatch for a huge subscription, but its default is 0 (everything).
964
1019
  *
965
- * "Best" is decided from this round's measurements, in this order:
1020
+ * "Best" is decided by rankHealth (lib/watch.js), which is also what the startup path uses,
1021
+ * so both paths answer the same question the same way. That ordering is: usable first, then
1022
+ * fewest blocked probes, then a quota-clean node before a rate-limited one, then the measured
1023
+ * Google latency, then the probe-time sum as a last resort.
966
1024
  *
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.
1025
+ * Latency sits AFTER the quota check and not before it: a node whose GitHub quota is spent
1026
+ * still answers, so it keeps its place in the table, but it must not displace a node with
1027
+ * quota left merely by being faster. Among nodes that are equally clean, latency decides,
1028
+ * which is what "best" means to the person watching the panel.
971
1029
  *
972
1030
  * The node that just failed is not a candidate for its own replacement.
973
1031
  *
@@ -1016,30 +1074,35 @@ export class Runtime {
1016
1074
  }
1017
1075
  this.lastMatrix = rows.map((row) => ({ name: row.name, results: row.results }))
1018
1076
 
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]
1077
+ // rankHealth (lib/watch.js) is the single definition of "better node": usable first, then
1078
+ // fewest blocked probes, then a quota-clean node before a rate-limited one, then Google
1079
+ // latency. This path used to carry its own ordering -- usable, latency, failures -- which never
1080
+ // consulted degraded, so a rate-limited node that happened to answer faster beat a quota-clean
1081
+ // one and the switch landed on exactly the node the plugin itself called limited. Two
1082
+ // orderings for one question is how that happened; there is now one.
1083
+ const ranked = rankHealth(rows)
1084
+ rows.sort((a, b) => ranked.indexOf(a) - ranked.indexOf(b))
1085
+ // What counts as an improvement depends on why the search started. When the live node is
1086
+ // actually failing, any usable node is better. When it merely ran out of quota, only a
1087
+ // quota-clean node is: a different rate-limited node would answer exactly as well, and the
1088
+ // switch would tear down every connection in flight to get there. rankHealth already puts a
1089
+ // clean node first, so this only ever declines a candidate set that had no clean node at all.
1090
+ const liveUsable = report.verdict?.usable === true
1091
+ const improves = (row) =>
1092
+ row.verdict?.usable === true && (liveUsable !== true || row.verdict?.degraded !== true)
1093
+ const best = rows.find(improves)
1037
1094
  const tested = rows.length
1038
1095
  const elapsedMs = Date.now() - startedAt
1039
1096
 
1040
- if (best === undefined || best.verdict?.usable !== true) {
1097
+ if (best === undefined) {
1098
+ // Two different dead ends share this branch, and they must not report the same thing. A
1099
+ // node that FAILED cannot carry traffic, so "no alternative" is the plain truth. A node
1100
+ // that is merely out of quota is still carrying traffic right now; telling the reader it
1101
+ // is unusable because no cleaner node was found would be a lie about the line they are
1102
+ // using, so that case keeps the limited state it arrived with.
1103
+ const deadEnd = liveUsable === true ? 'no-clean-alternative' : 'no-alternative'
1041
1104
  this.lastSwitch = {
1042
- state: 'no-alternative',
1105
+ state: deadEnd,
1043
1106
  from: report.node,
1044
1107
  at: new Date().toISOString(),
1045
1108
  tested,
@@ -1047,8 +1110,12 @@ export class Runtime {
1047
1110
  // Every candidate's reason, so "no alternative" can be audited instead of trusted.
1048
1111
  rejected: rows.slice(0, 8).map((row) => ({ name: row.name, failed: row.verdict?.failed ?? [], latency: row.latency })),
1049
1112
  }
1050
- this.log(`no usable alternative to ${report.node} out of ${tested} tested`)
1051
- return { ...report, state: 'no-alternative', tested, elapsedMs }
1113
+ this.log(
1114
+ liveUsable === true
1115
+ ? `${report.node} is rate-limited but no quota-clean alternative exists out of ${tested} tested; keeping it`
1116
+ : `no usable alternative to ${report.node} out of ${tested} tested`,
1117
+ )
1118
+ return { ...report, state: liveUsable === true ? "limited" : "no-alternative", tested, elapsedMs }
1052
1119
  }
1053
1120
 
1054
1121
  await this.core.select(best.name)
@@ -1093,15 +1160,76 @@ export class Runtime {
1093
1160
  if (report.state === 'switched') {
1094
1161
  return { state: 'switched', from: report.from, to: report.to, failed: report.failed, required: report.required, verdict: report.verdict }
1095
1162
  }
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 }
1163
+ if (report.state === 'ok' || report.state === 'degraded' || report.state === 'limited') {
1164
+ // `limited` lands here on purpose: the node answered, it is carrying traffic, and no
1165
+ // quota-clean replacement existed. That is a KEPT node with a caveat, not a lost one.
1166
+ return {
1167
+ state: report.state === 'limited' ? 'limited' : 'kept',
1168
+ node: report.node,
1169
+ required: report.required,
1170
+ results: report.results,
1171
+ verdict: report.verdict,
1172
+ latency: report.latency,
1173
+ limited: report.verdict?.limited ?? [],
1174
+ }
1098
1175
  }
1099
- if (report.state === 'no-alternative') {
1100
- return { state: 'no-alternative', lostNode: report.node, failed: report.verdict?.failed ?? [], required: report.required }
1176
+ if (report.state === 'no-alternative' || report.state === 'slow') {
1177
+ return { state: report.state, lostNode: report.node, failed: report.verdict?.failed ?? [], required: report.required }
1101
1178
  }
1102
1179
  return report
1103
1180
  }
1104
1181
 
1182
+ /**
1183
+ * Turn a health round report into the sentence a person reads.
1184
+ *
1185
+ * A method rather than inline tool code because the wording IS the behaviour being fixed here,
1186
+ * and the three ways it went wrong all need to be assertable: calling a node that is carrying
1187
+ * traffic "unusable", describing an in-round retry count as a number of failed rounds, and
1188
+ * printing undefined for a field that only some states ever set.
1189
+ */
1190
+ describeHealth(report) {
1191
+ const describeProbe = (row) => {
1192
+ if (row === undefined) return '无响应'
1193
+ if (row.ok === true) return `${row.ms} ms`
1194
+ if (row.state === 'limited') {
1195
+ return row.reason === 'rate-limited-in-body' || row.reason === 'status-403'
1196
+ ? `限流(HTTP ${row.status})`
1197
+ : row.remaining !== undefined
1198
+ ? `配额耗尽(剩余 ${row.remaining}${row.resetAt === undefined ? '' : `,${row.resetAt} 重置`})`
1199
+ : `受限(${row.reason})`
1200
+ }
1201
+ return `不通(${row.reason})`
1202
+ }
1203
+ // The vocabulary has to match how a round actually works: one round makes `attemptLimit`
1204
+ // attempts back to back, and only a hard failure counts a strike ACROSS rounds. Saying
1205
+ // "failed N rounds in a row" for an in-round count was simply wrong.
1206
+ const tries = report.attempts?.length ?? report.attemptLimit ?? 3
1207
+ const streak = report.strikes === undefined ? '' : `(连续失败 ${report.strikes}/${report.strikeLimit} 轮)`
1208
+ const lines = [
1209
+ report.state === 'ok'
1210
+ ? `节点「${report.node}」全部必需探测通过${streak}。`
1211
+ : report.state === 'slow'
1212
+ ? `节点「${report.node}」本轮连测 ${tries} 次都超过延迟上限(${report.latency} ms > ${report.ceiling} ms)${streak}。`
1213
+ : report.state === 'limited'
1214
+ ? `节点「${report.node}」连测 ${tries} 次仍被限流(${(report.verdict?.limited ?? []).join(',')}),但常规联网不受影响;没找到配额干净的替代节点,暂不切换。`
1215
+ : report.state === 'switched'
1216
+ ? `节点「${report.from}」本轮连测 ${tries} 次不合格${streak},已自动切到「${report.to}」${report.toLatency === undefined ? '' : `(${report.toLatency} ms)`}。`
1217
+ : report.state === 'no-alternative'
1218
+ ? `节点「${report.node}」本轮连测 ${tries} 次不合格${streak},但没有其他节点通过探测(已测 ${report.tested} 个)。`
1219
+ : report.state === 'switch-deferred'
1220
+ ? `节点「${report.node}」本轮连测 ${tries} 次不合格${streak},但有 ${report.connections} 条连接在进行,本轮不切换。`
1221
+ : report.state === 'bad'
1222
+ ? `节点「${report.node}」本轮连测 ${tries} 次不合格${streak}。`
1223
+ : `本轮未执行:${report.state}`,
1224
+ ]
1225
+ const probes = report.results ?? {}
1226
+ if (Object.keys(probes).length > 0) {
1227
+ lines.push('探测明细:')
1228
+ for (const [id, row] of Object.entries(probes)) lines.push(` ${row.label ?? id}:${describeProbe(row)}`)
1229
+ }
1230
+ return lines.join('\n')
1231
+ }
1232
+
1105
1233
  /**
1106
1234
  * Arm the single health/selection round.
1107
1235
  *
@@ -1305,10 +1433,15 @@ export class Runtime {
1305
1433
  return { ok: false, error: parsed.errors[0]?.reason ?? 'no subscription URL found', errors: parsed.errors }
1306
1434
  }
1307
1435
  try {
1308
- const report = await probeSubscriptions(parsed.entries, { timeoutMs: 15_000 })
1436
+ // The link is what supplies the nodes, so it is checked directly: a node that is
1437
+ // down or rate-limited must not make a live link look unreachable, and the answer
1438
+ // must not change just because a different node happened to be selected.
1439
+ const direct = await this.probeFetch()
1440
+ const report = await probeSubscriptions(parsed.entries, { timeoutMs: 15_000, fetch: direct })
1309
1441
  return {
1310
1442
  ...report,
1311
1443
  ok: report.ok,
1444
+ direct: direct !== undefined,
1312
1445
  maskedUrls: this.maskList(parsed.entries),
1313
1446
  errors: parsed.errors,
1314
1447
  error: report.ok
@@ -1319,12 +1452,58 @@ export class Runtime {
1319
1452
  .join('; '),
1320
1453
  }
1321
1454
  } catch (error) {
1322
- // The probe runs through whatever policy is installed, so a failure here may
1323
- // mean "not routed yet" rather than "wrong URL"; say which.
1455
+ // The check is direct, so a failure here is about the link's own reachability from
1456
+ // this machine (DNS, a firewall, a certificate) rather than "no node is selected".
1324
1457
  return { ok: false, error: `probe failed: ${String(error?.message ?? error)}` }
1325
1458
  }
1326
1459
  }
1327
1460
 
1461
+ /**
1462
+ * The fetch a subscription check must use: direct, never through a node.
1463
+ *
1464
+ * Returns undefined when the installation has no resolvable `undici`, so the check
1465
+ * falls back to the installed policy instead of failing outright — and says so,
1466
+ * rather than reporting a working link as unreachable.
1467
+ *
1468
+ * @returns the bound direct fetch, or undefined to use the global one.
1469
+ */
1470
+ async probeFetch() {
1471
+ const line = await this.ensureDirectLine()
1472
+ if (line === undefined) return undefined
1473
+ try {
1474
+ return await line.connect()
1475
+ } catch (error) {
1476
+ this.directError = String(error?.message ?? error)
1477
+ this.log(`direct line unavailable, checks use the installed policy: ${this.directError}`)
1478
+ return undefined
1479
+ }
1480
+ }
1481
+
1482
+ /**
1483
+ * Build the direct line once, or report why it cannot exist here.
1484
+ *
1485
+ * @returns the line, or undefined when this install cannot supply undici.
1486
+ */
1487
+ async ensureDirectLine() {
1488
+ if (this.directLine !== undefined) return this.directLine
1489
+ if (this.installRoot === undefined) {
1490
+ this.directError =
1491
+ `cannot locate the dsh installation root: no known layout matched process.argv or ${process.execPath}; set DSH_INSTALL_ROOT to the directory holding the dsh package.json`
1492
+ return undefined
1493
+ }
1494
+ try {
1495
+ const undiciPath = resolveFromInstall(this.installRoot, 'undici')
1496
+ const connectTimeoutMs = Math.max(5_000, Number(this.config.probeTimeoutMs) || 20_000)
1497
+ this.directLine = new DirectLine({ undiciPath, logger: this.log, connectTimeoutMs })
1498
+ this.directError = undefined
1499
+ return this.directLine
1500
+ } catch (error) {
1501
+ this.directError = String(error?.message ?? error)
1502
+ this.log(`direct line unavailable, checks use the installed policy: ${this.directError}`)
1503
+ return undefined
1504
+ }
1505
+ }
1506
+
1328
1507
  /** The subscription to use. There is no fallback: an empty value means unconfigured. */
1329
1508
  get subscriptionUrl() {
1330
1509
  return effectiveSubscriptionText(this.config)
@@ -1706,7 +1885,9 @@ export class Runtime {
1706
1885
  */
1707
1886
  async probeEntries(entries) {
1708
1887
  try {
1709
- return await probeSubscriptions(entries, { timeoutMs: 20_000 })
1888
+ const direct = await this.probeFetch()
1889
+ const report = await probeSubscriptions(entries, { timeoutMs: 20_000, fetch: direct })
1890
+ return { ...report, direct: direct !== undefined }
1710
1891
  } catch (error) {
1711
1892
  return {
1712
1893
  results: [],
@@ -1772,6 +1953,7 @@ export class Runtime {
1772
1953
  // closes, or it would see an unexpected exit and restart what was just stopped.
1773
1954
  this.engaged = false
1774
1955
  if (this.routing !== undefined) await this.routing.releaseToDirect()
1956
+ if (this.directLine !== undefined) await this.directLine.close()
1775
1957
  if (this.core !== undefined) await this.core.stop()
1776
1958
  }
1777
1959
 
@@ -2213,46 +2395,20 @@ function subscriptionTool(runtime) {
2213
2395
  ...result,
2214
2396
  summary: result.state === 'kept'
2215
2397
  ? '当前节点「' + 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(', ') + ' 无法全部访问。',
2398
+ : result.state === 'limited'
2399
+ ? '当前节点「' + result.node + '」限流(' + (result.limited ?? []).join(',') + '),但常规联网正常;没有找到配额干净的替代节点,保留当前节点。'
2400
+ : result.state === 'switched'
2401
+ ? '已从「' + result.from + '」切到「' + result.to + '」(原节点失去 ' + (result.failed ?? []).join(',') + ')。'
2402
+ : result.state === 'selected'
2403
+ ? '已选「' + result.chosen + '」。'
2404
+ : result.state === 'switch-deferred'
2405
+ ? '当前节点「' + result.node + '」不合格,但有 ' + result.connections + ' 条连接在进行,本轮不切换。'
2406
+ : '没有可用节点:' + (result.required ?? []).join(', ') + ' 无法全部访问。',
2221
2407
  }
2222
2408
  }
2223
2409
  if (action === 'health') {
2224
2410
  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') }
2411
+ return { ...report, summary: runtime.describeHealth(report) }
2256
2412
  }
2257
2413
  if (action === 'test') {
2258
2414
  const target = String(args?.node ?? '').trim()
package/lib/core.js CHANGED
@@ -193,6 +193,7 @@ export function buildConfig(options) {
193
193
  cnRuleSet,
194
194
  cnRuleSetPath,
195
195
  blocklist,
196
+ providerProxy,
196
197
  singleUrl,
197
198
  subscriptionUrl,
198
199
  providerPath,
@@ -226,6 +227,12 @@ export function buildConfig(options) {
226
227
  if (cnRuleSet !== undefined && cnRuleSet !== '') rules.push(`RULE-SET,${cnRuleSet},DIRECT`)
227
228
  rules.push('MATCH,PROXY')
228
229
 
230
+ // Written out rather than left to the core's default. The core does fetch a provider
231
+ // directly when the key is absent, but that is a default the plugin would silently
232
+ // depend on: if it ever changes, subscription downloads would quietly start spending
233
+ // a node's quota. Naming DIRECT makes the intent part of the config the panel shows.
234
+ const proxyTarget = String(providerProxy ?? 'DIRECT').trim()
235
+
229
236
  const providers = {}
230
237
  const names = []
231
238
  for (const [at, entry] of list.entries()) {
@@ -239,6 +246,7 @@ export function buildConfig(options) {
239
246
  url: String(entry?.url ?? ''),
240
247
  interval: 3600,
241
248
  path: path ?? `providers/${name}.yaml`,
249
+ ...(proxyTarget === '' ? {} : { proxy: proxyTarget }),
242
250
  ...(String(blocklist ?? '').trim() === '' ? {} : { 'exclude-filter': buildExcludeFilter(blocklist) }),
243
251
  'health-check': {
244
252
  enable: true,
package/lib/direct.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * A fetch that ignores the process-wide outbound policy.
3
+ *
4
+ * The plugin points undici's global dispatcher at its own core, so every `fetch` in
5
+ * the process — this plugin's subscription check included — travels through a
6
+ * subscription node. That is right for the Harness and wrong for the subscription
7
+ * link itself:
8
+ *
9
+ * - the link is what supplies the nodes, so a dead or rate-limited node must not be
10
+ * able to make a live link look broken;
11
+ * - checking through a node spends that node's quota to answer a question about the
12
+ * link;
13
+ * - and the answer would depend on which node happened to be selected, so the same
14
+ * link could report differently a minute apart with nothing changed.
15
+ *
16
+ * undici resolves a dispatcher per request, so a request carrying its own
17
+ * `dispatcher` bypasses the global one without touching the policy the rest of the
18
+ * process depends on. Measured on this machine with the global dispatcher pointed at
19
+ * a closed port (`http://127.0.0.1:9`): the plain `fetch` failed with
20
+ * `connect ECONNREFUSED 127.0.0.1:9` in 17 ms, while the same URL through this agent
21
+ * returned `200` and the full 723,720-byte document — twice in a row on one agent.
22
+ *
23
+ * The agent is built on first use and reused: with several subscriptions configured a
24
+ * fresh handshake per line costs more than the check itself.
25
+ *
26
+ * @module dsh-clash-proxy/direct
27
+ */
28
+
29
+ /**
30
+ * Owns one direct agent and the fetch bound to it.
31
+ */
32
+ export class DirectLine {
33
+ /**
34
+ * @param options - where undici lives, a logger, and the connect timeout.
35
+ */
36
+ constructor({ undiciPath, logger, connectTimeoutMs = 20_000 } = {}) {
37
+ this.undiciPath = undiciPath
38
+ this.log = logger ?? (() => {})
39
+ this.connectTimeoutMs = connectTimeoutMs
40
+ /** The undici module instance, kept so `fetch` does not re-import per call. */
41
+ this.undici = undefined
42
+ /** The agent this line owns, or undefined when none was built yet. */
43
+ this.agent = undefined
44
+ /** The in-flight build, so concurrent checks share one agent. */
45
+ this.pending = undefined
46
+ // Bound once: the value is handed to `probeSubscriptions` as `options.fetch`, and a
47
+ // bare method reference would lose `this` at the call site.
48
+ this.fetch = this.fetch.bind(this)
49
+ }
50
+
51
+ /** Whether an agent is live, i.e. the last {@link connect} succeeded. */
52
+ get active() {
53
+ return this.agent !== undefined
54
+ }
55
+
56
+ /**
57
+ * Build the agent if it is missing and return the fetch that uses it.
58
+ *
59
+ * @returns the bound fetch.
60
+ */
61
+ async connect() {
62
+ if (this.agent !== undefined) return this.fetch
63
+ if (this.pending === undefined) {
64
+ this.pending = (async () => {
65
+ const { pathToFileURL } = await import('node:url')
66
+ const undici = await import(pathToFileURL(this.undiciPath).href)
67
+ this.undici = undici
68
+ this.agent = new undici.Agent({ connect: { timeout: this.connectTimeoutMs } })
69
+ return this.fetch
70
+ })()
71
+ try {
72
+ return await this.pending
73
+ } finally {
74
+ this.pending = undefined
75
+ }
76
+ }
77
+ return await this.pending
78
+ }
79
+
80
+ /**
81
+ * Fetch with this line's dispatcher, whatever the global one is.
82
+ *
83
+ * @param url - the request target.
84
+ * @param init - the usual fetch init; `dispatcher` is set here and wins.
85
+ * @returns the response.
86
+ */
87
+ async fetch(url, init = {}) {
88
+ await this.connect()
89
+ return await this.undici.fetch(url, { ...init, dispatcher: this.agent })
90
+ }
91
+
92
+ /** Close the agent. Safe to call when none was built, and safe to call twice. */
93
+ async close() {
94
+ const agent = this.agent
95
+ this.agent = undefined
96
+ if (agent === undefined) return
97
+ try {
98
+ await agent.close()
99
+ } catch (error) {
100
+ this.log(`direct agent close failed: ${error?.message ?? error}`)
101
+ }
102
+ }
103
+ }
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.12.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.12.0.md",
38
38
  "LICENSE"
39
39
  ],
40
40
  "engines": {
@@ -67,7 +67,8 @@
67
67
  },
68
68
  "homepage": "https://github.com/lc297948801/dsh-clash-subscription#readme",
69
69
  "scripts": {
70
- "test": "node test/regression-070.mjs",
70
+ "test": "node test/regression-0120.mjs && node test/regression-070.mjs",
71
+ "test:direct": "node test/regression-0120.mjs",
71
72
  "test:legacy": "node test/regression-063.mjs",
72
73
  "test:linux": "node test/regression-0100.mjs",
73
74
  "test:e2e": "node test/e2e-090.mjs"
@@ -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`。