dsh-clash-subscription 0.7.0 → 0.8.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,120 @@
1
+ # 0.8.0 · 一个循环、30 秒、延迟进判定;插件自带技能
2
+
3
+ > 上一版 `0.7.0` · 本版 `0.8.0`
4
+
5
+ ## 为什么改
6
+
7
+ 0.7.0 有两个定时器做同一件事,而且延迟完全不参与判定:
8
+
9
+ | 0.7.0 的字段 | 实际行为 |
10
+ |---|---|
11
+ | `reselectMinutes: 15` | 每 15 分钟按能力重挑一次节点 |
12
+ | `healthRoundMinutes: 2` | 每 2 分钟真实探测当前节点 |
13
+ | — | 延迟只显示在面板上,**从不影响去留** |
14
+
15
+ 后果:一个 1 800 ms 的节点每次都通过探测,于是被永久保留,而所有走它的请求都慢得像卡住。
16
+ 两个循环还会互相清零计数,同一个节点得到两份结论。
17
+
18
+ ## 改了什么
19
+
20
+ ### 1. 合并成一个循环
21
+
22
+ `reselect` 不再是独立定时器,手动 `action=reselect` 变成「立刻跑一轮」。
23
+ 删掉了 `scheduleReselect` / `stopReselect`,只留 `scheduleHealthRound`。
24
+
25
+ ```
26
+ 每 30 秒:
27
+ ├─ 通过当前节点发真实请求(gstatic 204 / GitHub 配额 / git 拉取)
28
+ ├─ 测 Google 延迟(warm)
29
+ ├─ 可用 且 延迟 ≤ 400 ms → 保持,strikes = 0
30
+ ├─ 不可用 或 延迟超阈值 → strikes += 1
31
+ └─ strikes ≥ 3 → 排除当前节点,按真实探测结果切到最优
32
+ ```
33
+
34
+ | 字段 | 默认 | 说明 |
35
+ |---|---|---|
36
+ | `healthRoundSeconds` | **30** | 轮询间隔(秒)。0 = 关闭 |
37
+ | `healthStrikeLimit` | 3 | 连续几轮不合格才切 |
38
+ | `healthMaxDelayMs` | **400** | 延迟阈值;0 = 只看连通性 |
39
+ | `healthBaselineProbe` | **google** | 延迟取哪个探针 |
40
+ | `healthSurveyEvery` | 20 | 每 N 轮后台巡测其他节点(30 秒间隔下约 10 分钟) |
41
+
42
+ 旧的 `healthRoundMinutes` 会自动迁移成秒(2 分钟 → 120 秒),不会静默回落到 30 秒默认。
43
+
44
+ ### 2. 延迟改成 Google,且要 warm
45
+
46
+ **基准是 Google 的 `generate_204`**:静态 204,没有 API 处理逻辑,是最接近「这个节点离你多远」的量。
47
+
48
+ 但直接测出来是错的,实测两次修正:
49
+
50
+ | 错法 | 实测 | 真因 |
51
+ |---|---|---|
52
+ | 用所有探针的**总和** | 健康节点 1 286 ms,其中 gstatic 只占 90 ms | GitHub 自己的处理时间和三次 TLS 握手都在总和里,节点不背这个锅 |
53
+ | 用**第一次**请求 | 同一节点首轮 513 ms,之后 82 ms | 每个探针都是 `Connection: close`,首次要付 DNS + TCP + TLS;真实流量是复用的 |
54
+
55
+ 所以延迟 = **Google 探针的第二次测量**。e2e 实测:`warm 149ms (cold 240ms)`,阈值 400 ms 内保持不动。
56
+
57
+ ### 3. Google 不通 ≠ 节点慢
58
+
59
+ Google 不是门槛探针(`gating: false`)。它不通时:
60
+
61
+ - 不判 `slow`,不发明一个延迟;
62
+ - `latencySource` 标为 `unreachable`,面板能解释;
63
+ - 节点只按门槛探针判去留。
64
+
65
+ 否则一个 Google 被限、但 GitHub/git 全通的节点会被当成慢节点切走。
66
+
67
+ ### 4. 插件自带技能
68
+
69
+ 原来这套排障知识只写在 README 和工具描述里,真正需要它的时候没人去翻。
70
+ 现在通过 `ctx.skills.register()` 注册成技能 `clash-proxy-egress`,随插件加载/卸载:
71
+
72
+ | 项 | 值 |
73
+ |---|---|
74
+ | 名字 | `clash-proxy-egress` |
75
+ | 何时触发 | 境外命令失败(git/curl/npm/pip/web_fetch)、问代理通不通、问为什么某节点慢、要指定地区出口 |
76
+ | 内容 | 取证三条命令 → 修复阶梯(start → select → restart → refresh,按代价从小到大)→ 按真实探测挑节点 → 不要抢自动切换 → 症状对照表 |
77
+ | 长度 | 3 051 字符,含 8 个代码围栏 |
78
+
79
+ 技能里明确写了两条最常犯的错:
80
+
81
+ 1. **不要开桌面 Clash Verge 或改系统代理** —— 会和插件抢同一个 dispatcher,表现是「时通时不通」;
82
+ 2. **`strikes` 没到上限时不要手动换节点** —— 会把计数清零,坏节点永远攒不满 3 轮。
83
+
84
+ ### 5. 新增 `action=restart`
85
+
86
+ 「内核在跑但控制 API 不应答」时的一条命令,不用先 stop 再 start。
87
+
88
+ ## 验收
89
+
90
+ ```
91
+ node test/regression-070.mjs → 106 passed, 0 failed
92
+ node test/regression-063.mjs → 31 passed, 0 failed
93
+ node test/e2e-080.mjs → 21 passed, 0 failed(真内核 + 真订阅 + 真请求)
94
+ ```
95
+
96
+ e2e 真实输出:
97
+
98
+ ```
99
+ round#1: state=ok latency=149ms source=warm ceiling=400 strikes=0
100
+ warm 149ms (cold 240ms) → 用第二次测量
101
+ gstatic 204 / github 200 / git 200
102
+
103
+ strict round (ceiling=1ms): state=slow latency=184ms strikes=1
104
+ 前两轮不切换: slow/1 slow/2
105
+ round3: state=switched from=🇸🇬 新加坡01 to=🇺🇸 美国02 tested=7
106
+ ```
107
+
108
+ ## 一个被测试抓住的判据错误(留档)
109
+
110
+ 第一版把 `verdict.total`(所有门槛探针耗时之和)当延迟比 400 ms,e2e 立刻报
111
+ `健康节点首轮通过: slow 1286ms`。改用 Google 单探针后又报 `slow 513ms`,
112
+ 再查才发现那是冷启动。两次都是判据错,不是节点慢——**如果没在真机上跑一遍,
113
+ 上线后会把整批健康节点判成慢节点并疯狂切换**。
114
+
115
+ ## 遗留
116
+
117
+ - 面板新增的两个字段(`healthMaxDelayMs` / `healthSurveyEvery`)已接进 `client.js`,
118
+ 但**没有在真浏览器里看过渲染**(本轮只跑了逻辑测试)。
119
+ - `healthSurveyEvery` 的后台巡测只做了单元级验证,真机轮次里被设为 0 跳过,
120
+ 以避免 e2e 结果受巡测干扰。
package/client.js CHANGED
@@ -117,16 +117,20 @@ const en = {
117
117
  healthTitle: 'Health watch and automatic switching',
118
118
  autoSwitch: 'Watch the node with real requests',
119
119
  autoSwitchHint: 'Every round sends real requests through the live node: GitHub API (including the remaining quota), a git fetch, and a 204 endpoint. A node counts as usable only when all of those answer. This is what catches a rate-limited node, which a plain latency check reports as healthy.',
120
- healthRound: 'Round interval (minutes)',
121
- healthRoundHint: 'How often the real-request round runs. 0 turns it off.',
120
+ healthRound: 'Round interval (seconds)',
121
+ healthRoundHint: 'How often the real-request round runs. Default 30. 0 turns it off. Each round sends a few real requests through the live node, so very short intervals cost quota.',
122
122
  healthStrikes: 'Bad rounds before switching',
123
- healthStrikesHint: 'Consecutive failed rounds before the node is given up on. Any good round resets the count, so one noisy sample never causes a switch. Default 3.',
123
+ healthStrikesHint: 'Consecutive failed rounds before the node is given up on. A round fails when a required request does not answer, OR when the node is slower than the latency ceiling. Any good round resets the count. Default 3.',
124
+ healthMaxDelay: 'Latency ceiling (ms)',
125
+ healthMaxDelayHint: 'A node slower than this does not stay selected. 0 disables the ceiling and only reachability decides. Default 400 ms.',
126
+ healthSurvey: 'Survey other nodes every N rounds',
127
+ healthSurveyHint: 'In the background, once every N rounds, measure the other nodes for real so a switch picks from a ranked list instead of starting a slow search when the line is already broken. 0 disables the survey. Default 20 rounds (about 10 minutes at 30 s).',
124
128
  healthCandidates: 'Nodes tried per switch',
125
129
  healthCandidatesHint: 'How many alternatives one switch tests, fastest first. 0 tests every node, which on a 54-node subscription takes minutes.',
126
130
  switchWhileBusy: 'Switch even with connections open',
127
131
  switchWhileBusyHint: 'Off by default: a switch aborts whatever is in flight. On means a broken node is abandoned immediately instead of waiting for the line to go quiet.',
128
132
  limitedNote: '{count} limited, {blocked} blocked',
129
- healthRoundNote: 'Last round: {state} · streak {strikes}/{limit}',
133
+ healthRoundNote: 'Every {every}s · last round {state} at {latency} ms (ceiling {ceiling} ms) · streak {strikes}/{limit}',
130
134
  lastSwitchNote: 'Switched {from} → {to} at {time}',
131
135
  runHealth: 'Check the live node now',
132
136
  healthRunning: 'Checking the live node…',
@@ -211,16 +215,20 @@ const zh = {
211
215
  healthTitle: '可用性监视与自动切换',
212
216
  autoSwitch: '用真实请求监视当前节点',
213
217
  autoSwitchHint: '每轮都通过当前节点实发请求:GitHub API(连剩余配额一起看)、git 拉取、以及一个 204 连通性端点。全部通过才算可用。这正是「限流节点被判成可用」的那个缺口——普通延迟检测对 403 也报成功。',
214
- healthRound: '检测间隔(分钟)',
215
- healthRoundHint: '多久跑一轮真实请求检测。0 = 关闭。',
218
+ healthRound: '检测间隔(秒)',
219
+ healthRoundHint: '多久跑一轮真实请求检测,默认 30 秒。0 = 关闭。每轮都会通过当前节点发几次真实请求,间隔太短会消耗服务配额。',
216
220
  healthStrikes: '连续几轮失败才切换',
217
- healthStrikesHint: '节点连续失败多少轮才放弃。任何一轮通过都会把计数清零,所以单次抖动不会触发切换。默认 3。',
221
+ healthStrikesHint: '节点连续失败多少轮才放弃。记为失败有两种情况:必需的请求没通,或者节点延迟超过上面那条阈值。任何一轮通过都会把计数清零。默认 3。',
222
+ healthMaxDelay: '延迟阈值(毫秒)',
223
+ healthMaxDelayHint: '超过这个延迟的节点不会被保留。填 0 表示只看连通性,不管快慢。默认 400 毫秒。',
224
+ healthSurvey: '每几轮巡测一次其他节点',
225
+ healthSurveyHint: '后台每 N 轮真实测一次其他节点,切换时直接从排好序的候选里挑,不用等线路已经坏了才开始慢慢搜。0 = 关闭巡测。默认 20 轮(30 秒间隔下约 10 分钟)。',
218
226
  healthCandidates: '每次切换试几个节点',
219
227
  healthCandidatesHint: '一次切换最多试多少个候选,按延迟从低到高。0 = 全试,54 个节点要几分钟。',
220
228
  switchWhileBusy: '有连接在进行时也切换',
221
229
  switchWhileBusyHint: '默认关闭:切换会中断正在进行的请求。打开后坏节点会被立刻丢弃,不等线路空闲。',
222
230
  limitedNote: '{count} 个限流,{blocked} 个不通',
223
- healthRoundNote: '最近一轮:{state} · 连续 {strikes}/{limit}',
231
+ healthRoundNote: '每 {every} 秒 · 最近一轮 {state},{latency} ms(阈值 {ceiling} ms)· 连续 {strikes}/{limit}',
224
232
  lastSwitchNote: '已于 {time} 从「{from}」切到「{to}」',
225
233
  runHealth: '立刻检测当前节点',
226
234
  healthRunning: '正在检测当前节点…',
@@ -439,8 +447,10 @@ function sections(t) {
439
447
  title: t('healthTitle'),
440
448
  fields: [
441
449
  { key: 'autoSwitch', kind: 'switch', label: t('autoSwitch'), hint: t('autoSwitchHint') },
442
- { key: 'healthRoundMinutes', kind: 'number', label: t('healthRound'), hint: t('healthRoundHint'), min: 0, max: 120, step: 1 },
450
+ { key: 'healthRoundSeconds', kind: 'number', label: t('healthRound'), hint: t('healthRoundHint'), min: 0, max: 3600, step: 5 },
443
451
  { key: 'healthStrikeLimit', kind: 'number', label: t('healthStrikes'), hint: t('healthStrikesHint'), min: 1, max: 20, step: 1 },
452
+ { key: 'healthMaxDelayMs', kind: 'number', label: t('healthMaxDelay'), hint: t('healthMaxDelayHint'), min: 0, max: 30000, step: 50 },
453
+ { key: 'healthSurveyEvery', kind: 'number', label: t('healthSurvey'), hint: t('healthSurveyHint'), min: 0, max: 10000, step: 5 },
444
454
  { key: 'healthSwitchCandidates', kind: 'number', label: t('healthCandidates'), hint: t('healthCandidatesHint'), min: 0, max: 100, step: 1 },
445
455
  { key: 'switchWhileBusy', kind: 'switch', label: t('switchWhileBusy'), hint: t('switchWhileBusyHint') },
446
456
  ],
@@ -877,9 +887,12 @@ function Panel(props) {
877
887
  live.health.enabled === false
878
888
  ? t('healthOff')
879
889
  : fill(t('healthRoundNote'), {
890
+ every: live.health.everySeconds ?? 30,
880
891
  state: live.health.lastRound?.state ?? t('never'),
881
892
  strikes: live.health.lastRound?.strikes ?? 0,
882
893
  limit: live.health.strikeLimit ?? 3,
894
+ latency: live.health.lastRound?.latency ?? '—',
895
+ ceiling: live.health.maxDelayMs ?? 400,
883
896
  }),
884
897
  live.health.lastSwitch?.state === 'switched'
885
898
  ? ' · ' + fill(t('lastSwitchNote'), {
package/index.js CHANGED
@@ -37,10 +37,11 @@ import {
37
37
  providerName,
38
38
  } from './lib/subscription.js'
39
39
  import { maskToken, mountRoutes } from './lib/routes.js'
40
+ import { SKILL_CONTENT, SKILL_DESCRIPTION, SKILL_NAME, SKILL_WHEN_TO_USE } from './lib/skill.js'
40
41
 
41
42
  export const name = 'clash-proxy'
42
43
 
43
- export const inject = ['tools']
44
+ export const inject = ['tools', 'skills']
44
45
 
45
46
  /**
46
47
  * Defaults for every field, so a plugin row may omit all of them.
@@ -113,20 +114,50 @@ export const CONFIG_DEFAULTS = {
113
114
  /**
114
115
  * Watch the live node with real requests and switch away when it keeps failing.
115
116
  *
116
- * Separate from `autoReselect`: that one acts on a single bad sample every 15 minutes, which
117
- * is both too eager (one sample is noise) and too slow (15 minutes of a broken node). This
118
- * cycle runs every `healthRoundMinutes` and only switches after `healthStrikeLimit`
119
- * consecutive bad rounds.
117
+ * One cycle, not two. 0.7.0 had both this and a separate `autoReselect` pass, and the two did
118
+ * the same thing on different clocks — which meant the same node could be judged by two
119
+ * different instruments and the panel had two answers to one question. They are merged here:
120
+ * a single round runs every `healthRoundSeconds` and does everything a round needs.
121
+ *
122
+ * A node is kept while it is **usable and under the latency ceiling**; it is given up on only
123
+ * after `healthStrikeLimit` consecutive rounds fail either test. Latency did not participate
124
+ * before, so a node answering in 1 800 ms was kept indefinitely even though every request
125
+ * through it was slow enough to look broken.
120
126
  */
121
127
  autoSwitch: true,
122
- /** How often the health round runs, in minutes; 0 disables it. */
123
- healthRoundMinutes: 2,
124
- /** Consecutive bad rounds before the node is given up on. */
128
+ /** How often the round runs, in seconds; 0 disables it. */
129
+ healthRoundSeconds: 30,
130
+ /** Consecutive failed rounds before the node is given up on. */
125
131
  healthStrikeLimit: 3,
132
+ /**
133
+ * Latency ceiling in milliseconds, compared against the **Google probe's warm round trip**.
134
+ *
135
+ * Google's `generate_204` is the closest thing to a pure distance measurement: it is a static
136
+ * 204 with no API processing, and it is the endpoint every other client uses as a reachability
137
+ * baseline.
138
+ *
139
+ * Two corrections came from measurement, both of which matter more than the choice of endpoint:
140
+ *
141
+ * 1. The sum across probes is the wrong number — a healthy node totalled ~1 290 ms while this
142
+ * probe alone answered in ~90 ms, because GitHub's processing and three TLS handshakes are
143
+ * in the total.
144
+ * 2. The first request after a core start is cold — the same node answered 513 ms and then
145
+ * 82 ms, since every probe opens a fresh connection and only the first pays DNS. Real
146
+ * traffic reuses warm state, so the second measurement is the one that means something.
147
+ */
148
+ healthMaxDelayMs: 400,
149
+ /** Which probe supplies the latency number. Google is the distance baseline, not a gate. */
150
+ healthBaselineProbe: 'google',
126
151
  /** How many candidate nodes one switch search may test, cheapest first; 0 means all. */
127
152
  healthSwitchCandidates: 12,
128
153
  /** Let a switch proceed even while connections are open. Off by default: it aborts work. */
129
154
  switchWhileBusy: false,
155
+ /**
156
+ * Re-check every node's real capability in the background, on the same round, so the panel can
157
+ * rank alternatives without spending the switch on a slow search at the worst moment.
158
+ * `healthSurveyEvery` rounds; 0 disables the survey.
159
+ */
160
+ healthSurveyEvery: 20,
130
161
  }
131
162
 
132
163
  /**
@@ -173,10 +204,13 @@ async function buildConfigSchema() {
173
204
  probeSamples: z.number().default(2),
174
205
  probeTimeoutMs: z.number().default(8000),
175
206
  autoSwitch: z.boolean().default(true),
176
- healthRoundMinutes: z.number().default(2),
207
+ healthRoundSeconds: z.number().default(30),
177
208
  healthStrikeLimit: z.number().default(3),
209
+ healthMaxDelayMs: z.number().default(400),
210
+ healthBaselineProbe: z.string().default('google'),
178
211
  healthSwitchCandidates: z.number().default(12),
179
212
  switchWhileBusy: z.boolean().default(false),
213
+ healthSurveyEvery: z.number().default(20),
180
214
  })
181
215
  } catch {
182
216
  return undefined
@@ -226,9 +260,23 @@ export function resolveConfig(raw) {
226
260
  config.probeTimeoutMs = clamp(config.probeTimeoutMs, 1_000, 60_000, 8_000)
227
261
  config.autoSwitch = config.autoSwitch !== false && config.autoSwitch !== 'false'
228
262
  config.switchWhileBusy = config.switchWhileBusy === true || config.switchWhileBusy === 'true'
229
- config.healthRoundMinutes = clamp(config.healthRoundMinutes, 0, 120, 2)
263
+ // 30 s is the default; the floor is 5 s so a misconfigured 1 s cannot turn the round into a
264
+ // permanent probe loop, and each round costs real requests against a real service.
265
+ config.healthRoundSeconds = clamp(config.healthRoundSeconds, 0, 3_600, 30)
230
266
  config.healthStrikeLimit = clamp(config.healthStrikeLimit, 1, 20, 3)
267
+ config.healthMaxDelayMs = clamp(config.healthMaxDelayMs, 0, 30_000, 400)
268
+ config.healthBaselineProbe = String(config.healthBaselineProbe ?? 'google').trim() || 'google'
231
269
  config.healthSwitchCandidates = clamp(config.healthSwitchCandidates, 0, 100, 12)
270
+ config.healthSurveyEvery = clamp(config.healthSurveyEvery, 0, 10_000, 20)
271
+ // 0.7.0 kept the interval in minutes; carry the value over so an existing profile does not
272
+ // silently fall back to the new 30 s default when someone had deliberately set 15 minutes.
273
+ const legacyMinutes = Number(input.healthRoundMinutes)
274
+ if (!Number.isFinite(Number(input.healthRoundSeconds)) && Number.isFinite(legacyMinutes) && legacyMinutes > 0) {
275
+ config.healthRoundSeconds = clamp(legacyMinutes * 60, 0, 3_600, 30)
276
+ }
277
+ // `reselect` is merged into this round now. Both fields stay readable so an old profile does
278
+ // not fail validation, but neither drives a timer any more.
279
+ config.reselectMinutes = clamp(config.reselectMinutes, 0, 1440, 15)
232
280
  return config
233
281
  }
234
282
 
@@ -275,8 +323,8 @@ export class Runtime {
275
323
  this.idleSince = undefined
276
324
  /** When the current node was last verified. */
277
325
  this.lastCheckAt = undefined
278
- /** Timer for the periodic re-check. */
279
- this.reselectTimer = undefined
326
+ /** Timer for the single health/selection round. */
327
+ this.healthTimer = undefined
280
328
  /** Progress/result of the optional GeoIP upgrade. */
281
329
  this.geo = undefined
282
330
  /** True while that upgrade is running. */
@@ -442,9 +490,11 @@ export class Runtime {
442
490
  autoReselect: this.config.autoReselect,
443
491
  reselectMinutes: this.config.reselectMinutes,
444
492
  autoSwitch: this.config.autoSwitch,
445
- healthRoundMinutes: this.config.healthRoundMinutes,
493
+ healthRoundSeconds: this.config.healthRoundSeconds,
446
494
  healthStrikeLimit: this.config.healthStrikeLimit,
495
+ healthMaxDelayMs: this.config.healthMaxDelayMs,
447
496
  healthSwitchCandidates: this.config.healthSwitchCandidates,
497
+ healthSurveyEvery: this.config.healthSurveyEvery,
448
498
  switchWhileBusy: this.config.switchWhileBusy,
449
499
  source: 'configured',
450
500
  }
@@ -520,9 +570,11 @@ export class Runtime {
520
570
  }
521
571
  if (next.speedTestMinutes !== previous.speedTestMinutes) this.requestRearm()
522
572
  if (
523
- next.healthRoundMinutes !== previous.healthRoundMinutes ||
573
+ next.healthRoundSeconds !== previous.healthRoundSeconds ||
524
574
  next.autoSwitch !== previous.autoSwitch ||
525
- next.healthStrikeLimit !== previous.healthStrikeLimit
575
+ next.healthStrikeLimit !== previous.healthStrikeLimit ||
576
+ next.healthMaxDelayMs !== previous.healthMaxDelayMs ||
577
+ next.healthSurveyEvery !== previous.healthSurveyEvery
526
578
  ) {
527
579
  this.watch.strikeLimit = next.healthStrikeLimit
528
580
  this.requestRearm()
@@ -671,33 +723,91 @@ export class Runtime {
671
723
  return { state: 'probe-unavailable', node: current }
672
724
  }
673
725
 
674
- this.healthRows.set(current, { results, verdict, at: Date.now() })
726
+ // Google is not a gating probe, so it is absent from both `plan.specs` and the `results`
727
+ // this round produced — the node already answered the gating set, and Google has to be
728
+ // measured separately. One measurement is taken for the warm number, and a second only
729
+ // when that one failed, so "Google unreachable" can be told from "Google slow".
730
+ //
731
+ // Consequence worth stating: an unreachable Google does **not** make the node slow. The
732
+ // ceiling is skipped for that round and the node is judged on the gating probes alone,
733
+ // because inventing a latency for an unreachable host would switch away from a node that
734
+ // may be perfectly fast for everything else.
735
+ const baseline =
736
+ plan.probes.find((spec) => spec.id === this.config.healthBaselineProbe) ??
737
+ plan.specs[0]
738
+ let latency
739
+ let latencySource = 'not-measured'
740
+ let coldLatency
741
+ if (verdict.usable === true && baseline !== undefined && typeof this.core.remeasure === 'function') {
742
+ try {
743
+ const first = await this.core.remeasure(baseline, { timeoutMs: this.config.probeTimeoutMs ?? 8000 })
744
+ if (typeof first?.ms === 'number' && first.ok === true) {
745
+ coldLatency = first.ms
746
+ // Second measurement: the first one on a freshly started core pays DNS + TCP + TLS for
747
+ // that host, which is not the node's latency. Measured, 513 ms cold vs 82 ms warm.
748
+ const warm = await this.core.remeasure(baseline, { timeoutMs: this.config.probeTimeoutMs ?? 8000 })
749
+ if (typeof warm?.ms === 'number' && warm.ok === true) {
750
+ latency = warm.ms
751
+ latencySource = 'warm'
752
+ } else {
753
+ latency = first.ms
754
+ latencySource = 'cold'
755
+ }
756
+ } else {
757
+ latencySource = 'unreachable'
758
+ }
759
+ } catch (error) {
760
+ // A probe that throws is a broken instrument, not a slow node: no latency verdict.
761
+ latencySource = 'failed'
762
+ this.log(`latency measurement failed on ${current}: ${error?.message ?? error}`)
763
+ }
764
+ }
765
+ const ceiling = Number(this.config.healthMaxDelayMs ?? 400)
766
+ const tooSlow = ceiling > 0 && verdict.usable === true && latency !== undefined && latency > ceiling
767
+ const judged = tooSlow ? { ...verdict, usable: false, failed: [...verdict.failed, 'latency'], slow: true } : verdict
768
+
769
+ this.healthRows.set(current, { results, verdict: judged, at: Date.now() })
675
770
  this.lastMatrix = [{ name: current, results }]
676
771
  this.lastCheckAt = Date.now()
677
- const counted = this.watch.record(current, verdict, { probes: results })
772
+ const counted = this.watch.record(current, judged, { probes: results })
678
773
  // `degraded` is a usable node that is short on quota. It is reported, never acted on:
679
774
  // switching away from it would land on an equally short node and lose the connection.
680
- const state = verdict.usable ? (verdict.degraded === true ? 'degraded' : 'ok') : 'bad'
775
+ const state = judged.usable ? (judged.degraded === true ? 'degraded' : 'ok') : judged.slow === true ? 'slow' : 'bad'
681
776
  const report = {
682
777
  state,
683
778
  node: current,
684
779
  required: plan.gating,
685
780
  results,
686
- verdict,
781
+ verdict: judged,
782
+ /** Warm baseline round trip in ms — the number the ceiling refers to. */
783
+ latency,
784
+ /** `warm` | `cold` | `unreachable` | `not-measured`: how to read `latency`. */
785
+ latencySource,
786
+ /** Cold first measurement, kept so a genuinely slow node can be told from a cold start. */
787
+ coldLatency,
788
+ /** Sum across every gating probe; informational, never compared to the ceiling. */
789
+ totalLatency: verdict.total,
790
+ ceiling,
791
+ baseline: baseline?.id,
687
792
  strikes: counted.strikes,
688
793
  strikeLimit: counted.limit,
689
794
  giveUp: counted.giveUp,
690
795
  at: new Date().toISOString(),
691
796
  }
692
797
  this.health = report
693
- if (verdict.usable) {
694
- this.log(`health round ok on ${current} (${Object.keys(results).join('/')})`)
798
+ if (judged.usable) {
799
+ this.log(`round ok on ${current} (${latency ?? '?'} ms, ${Object.keys(results).join('/')})`)
800
+ void this.runSurveyTick()
695
801
  return report
696
802
  }
697
- this.log(
698
- `health round bad on ${current} ${counted.strikes}/${counted.limit}: ${verdict.failed.join(',') || 'no-answer'}` +
699
- (verdict.limited.length > 0 ? ` (limited: ${verdict.limited.join(',')})` : ''),
700
- )
803
+ if (tooSlow) {
804
+ this.log(`round slow on ${current}: ${latency} ms > ${ceiling} ms ceiling (${counted.strikes}/${counted.limit})`)
805
+ } else {
806
+ this.log(
807
+ `round bad on ${current} ${counted.strikes}/${counted.limit}: ${judged.failed.join(',') || 'no-answer'}` +
808
+ (judged.limited.length > 0 ? ` (limited: ${judged.limited.join(',')})` : ''),
809
+ )
810
+ }
701
811
  if (!counted.giveUp) return report
702
812
  return await this.switchAfterStrikes(report, plan, options)
703
813
  } finally {
@@ -786,18 +896,50 @@ export class Runtime {
786
896
  }
787
897
 
788
898
  /**
789
- * Arm the real-probe health round.
899
+ * Re-check the current node on demand, as `clash_proxy action=reselect` and the panel's
900
+ * button do.
901
+ *
902
+ * This is the manual entry point now, not a second timer: the scheduled work all lives in
903
+ * `healthRound`, so a manual reselect runs one round with `force` and reports the same shape.
904
+ *
905
+ * @param options - `force` skips the busy gate.
906
+ * @returns the round report.
907
+ */
908
+ async autoReselect(options = {}) {
909
+ const report = await this.healthRound({ ...options, force: true })
910
+ if (report.state === 'switched') {
911
+ return { state: 'switched', from: report.from, to: report.to, failed: report.failed, required: report.required, verdict: report.verdict }
912
+ }
913
+ if (report.state === 'ok' || report.state === 'degraded') {
914
+ return { state: 'kept', node: report.node, required: report.required, results: report.results, verdict: report.verdict, latency: report.latency }
915
+ }
916
+ if (report.state === 'no-alternative') {
917
+ return { state: 'no-alternative', lostNode: report.node, failed: report.verdict?.failed ?? [], required: report.required }
918
+ }
919
+ return report
920
+ }
921
+
922
+ /**
923
+ * Arm the single health/selection round.
924
+ *
925
+ * One timer drives everything: the live node's verdict, the latency ceiling, the automatic
926
+ * switch, and (every `healthSurveyEvery` rounds) a background survey of the other nodes so a
927
+ * switch has a ranked list ready instead of starting a slow search at the worst moment.
928
+ *
929
+ * The round is single-flight (`healthRunning`), so a period shorter than one round's duration
930
+ * skips ticks instead of stacking them — measured, one round takes ~1.3 s on a healthy node,
931
+ * so 30 s leaves plenty of headroom, but a dead node with several timeouts can exceed it.
790
932
  *
791
933
  * @param schedule - timer factory from the plugin context.
792
934
  */
793
935
  scheduleHealthRound(schedule) {
794
936
  if (this.healthTimer !== undefined) this.healthTimer()
795
937
  this.healthTimer = undefined
796
- const minutes = this.config.healthRoundMinutes
797
- if (this.config.autoSwitch === false || minutes <= 0 || typeof schedule !== 'function') return
938
+ const seconds = Number(this.config.healthRoundSeconds ?? 30)
939
+ if (this.config.autoSwitch === false || seconds <= 0 || typeof schedule !== 'function') return
798
940
  this.healthTimer = schedule(() => {
799
941
  void this.healthRound().catch((error) => this.log(`health round failed: ${error?.message ?? error}`))
800
- }, minutes * 60_000)
942
+ }, seconds * 1000)
801
943
  }
802
944
 
803
945
  /** Stop the health round. Safe to call when none is running. */
@@ -808,110 +950,55 @@ export class Runtime {
808
950
  }
809
951
 
810
952
  /**
811
- * Re-check the current node's capabilities and switch only when it is no longer usable.
953
+ * Survey the nodes that are not currently selected, on a slow cadence.
954
+ *
955
+ * The switch path can measure candidates on demand, but doing it only then means the search
956
+ * starts exactly when the line is already broken and the user is waiting. A background survey
957
+ * keeps `healthRows` populated for every node, so the switch picks from known-good candidates
958
+ * and the panel can show real per-node verdicts without being opened at the right moment.
812
959
  *
813
- * Kept for the `reselect` action and the coarser schedule: it now asks the real probes first,
814
- * and only falls back to the latency matrix when the probe listener is unavailable. Any switch
815
- * it makes resets the health streak, so the two cycles cannot fight over the same node.
960
+ * Bounded by `healthSwitchCandidates` and skipped while a switch is in progress.
816
961
  *
817
- * @param options - `force` bypasses the idle gate.
818
- * @returns what happened and why.
962
+ * @returns the survey result, or `{ state: 'skipped' }` when it did not run.
819
963
  */
820
- async autoReselect(options = {}) {
821
- const gate = await this.canReselectNow(options)
822
- if (!gate.ok) return { state: 'skipped', ...gate }
823
-
964
+ async runSurveyTick() {
965
+ const every = Number(this.config.healthSurveyEvery ?? 20)
966
+ if (every <= 0 || this.healthRunning !== true) return { state: 'skipped' }
967
+ // Counted inside a round, so `healthRoundSeconds * every` is the survey period.
968
+ this.surveyTicks = (this.surveyTicks ?? 0) + 1
969
+ if (this.surveyTicks % every !== 0) return { state: 'not-due', ticks: this.surveyTicks }
970
+ if (this.switching === true) return { state: 'skipped' }
971
+ if (this.core === undefined || this.core.running !== true) return { state: 'core-not-running' }
824
972
  const plan = this.probePlan()
825
- const group = await this.core.group()
973
+ const group = await this.core.group().catch(() => undefined)
974
+ if (group === undefined) return { state: 'no-group' }
826
975
  const current = group.now
827
- if (current === undefined || current === 'DIRECT') {
828
- const result = await this.core.autoSelect(this.preferredNode, {
829
- probes: plan.probes,
830
- required: plan.gating,
976
+ const cap = Number(this.config.healthSwitchCandidates ?? 12)
977
+ const candidates = group.all
978
+ .filter((name) => name !== 'DIRECT' && name !== 'REJECT' && name !== current)
979
+ .slice(0, cap > 0 ? cap : undefined)
980
+ if (candidates.length === 0) return { state: 'no-candidates' }
981
+ this.switching = true
982
+ try {
983
+ const matrix = await this.core.realMatrix({
984
+ nodes: candidates,
831
985
  specs: plan.specs,
832
- budgetMs: this.config.selectBudgetMs,
986
+ gating: plan.gating,
833
987
  delays: this.measured,
834
- })
835
- if (result.chosen !== undefined) this.rememberNode(result.chosen)
836
- return { state: result.chosen === undefined ? 'no-node' : 'selected', chosen: result.chosen, required: plan.gating }
837
- }
838
-
839
- const { results, verdict } = await this.core.checkNodeReal(current, plan.specs, plan.gating, {
840
- timeoutMs: this.config.probeTimeoutMs ?? 8000,
841
- })
842
- if (Object.keys(results).length === 0) {
843
- // No real verdict available: fall back to the old reachability matrix rather than
844
- // reporting a failure the instrument cannot substantiate.
845
- const legacy = resolveProbes(this.config.probes, this.config.requiredProbes)
846
- const legacyResults = await this.core.capabilities(current, legacy.probes, {
988
+ budgetMs: Math.min(Number(this.config.selectBudgetMs ?? 90_000), 60_000),
847
989
  timeoutMs: this.config.probeTimeoutMs ?? 8000,
848
- samples: this.config.probeSamples ?? 2,
849
990
  })
850
- const legacyVerdict = judgeNode(legacyResults, legacy.required)
851
- this.lastMatrix = [{ name: current, results: legacyResults }]
852
- this.lastCheckAt = Date.now()
853
- if (legacyVerdict.usable) return { state: 'kept', node: current, required: legacy.required, results: legacyResults, measured: 'reachability' }
854
- return { state: 'no-verdict', node: current, results: legacyResults }
855
- }
856
-
857
- this.healthRows.set(current, { results, verdict, at: Date.now() })
858
- this.lastMatrix = [{ name: current, results }]
859
- this.lastCheckAt = Date.now()
860
- if (verdict.usable) {
861
- this.watch.reset(current)
862
- this.log(`node ${current} still passes ${plan.gating.join('/')}`)
863
- return { state: 'kept', node: current, required: plan.gating, results, verdict }
864
- }
865
-
866
- this.log(`node ${current} failed ${(verdict.failed ?? []).join(',') || 'probes'}; searching again`)
867
- const result = await this.core.autoSelect('', {
868
- probes: plan.probes,
869
- required: plan.gating,
870
- specs: plan.specs,
871
- budgetMs: this.config.selectBudgetMs,
872
- delays: this.measured,
873
- exclude: [current],
874
- })
875
- if (result.chosen === undefined) {
876
- return { state: 'no-alternative', lostNode: current, failed: verdict.failed, required: plan.gating }
877
- }
878
- if (result.chosen === current) {
879
- return { state: 'unchanged', node: current, failed: verdict.failed, verdict }
991
+ const at = Date.now()
992
+ for (const row of matrix.rows) this.healthRows.set(row.name, { results: row.results, verdict: row.verdict, at })
993
+ this.lastSurvey = { at: new Date(at).toISOString(), tested: matrix.tested, usable: matrix.rows.filter((r) => r.verdict?.usable === true).length }
994
+ this.log(`survey: ${this.lastSurvey.usable}/${matrix.tested} nodes usable`)
995
+ return { state: 'surveyed', ...this.lastSurvey }
996
+ } catch (error) {
997
+ this.log(`survey failed: ${error?.message ?? error}`)
998
+ return { state: 'failed', reason: String(error?.message ?? error) }
999
+ } finally {
1000
+ this.switching = false
880
1001
  }
881
- this.rememberNode(result.chosen)
882
- this.watch.reset(result.chosen)
883
- this.lastSwitch = { state: 'switched', from: current, to: result.chosen, at: new Date().toISOString(), failed: verdict.failed }
884
- this.log(`switched ${current} -> ${result.chosen}`)
885
- return { state: 'switched', from: current, to: result.chosen, failed: verdict.failed, required: plan.gating, verdict }
886
- }
887
-
888
- /**
889
- * Arm the periodic capability re-check.
890
- *
891
- * Same rule as the other cycles: the interval must be created in the plugin context, so this
892
- * is only ever called from a callback the plugin registered itself. A tick that finds the
893
- * line busy returns immediately, which is why the period can be short without ever
894
- * interrupting work.
895
- *
896
- * @param schedule - timer factory from the plugin context.
897
- */
898
- scheduleReselect(schedule) {
899
- if (this.reselectTimer !== undefined) this.reselectTimer()
900
- this.reselectTimer = undefined
901
- const minutes = this.config.reselectMinutes
902
- if (this.config.autoReselect === false || minutes <= 0 || typeof schedule !== 'function') return
903
- this.reselectTimer = schedule(() => {
904
- void this.autoReselect().catch((error) => {
905
- this.log('capability re-check failed: ' + String(error?.message ?? error))
906
- })
907
- }, minutes * 60_000)
908
- }
909
-
910
- /** Stop the re-check. Safe to call when none is running. */
911
- stopReselect() {
912
- if (this.reselectTimer === undefined) return
913
- this.reselectTimer()
914
- this.reselectTimer = undefined
915
1002
  }
916
1003
 
917
1004
  /**
@@ -1647,9 +1734,12 @@ export class Runtime {
1647
1734
  * node is limited, so why has it not switched yet".
1648
1735
  */
1649
1736
  health: {
1650
- enabled: this.config.autoSwitch !== false && this.config.healthRoundMinutes > 0,
1651
- everyMinutes: this.config.healthRoundMinutes,
1737
+ enabled: this.config.autoSwitch !== false && this.config.healthRoundSeconds > 0,
1738
+ everySeconds: this.config.healthRoundSeconds,
1652
1739
  strikeLimit: this.watch.strikeLimit,
1740
+ maxDelayMs: this.config.healthMaxDelayMs,
1741
+ surveyEvery: this.config.healthSurveyEvery,
1742
+ survey: this.lastSurvey ?? null,
1653
1743
  lastRound: this.health ?? null,
1654
1744
  inFlight: this.healthRunning === true,
1655
1745
  lastSwitch: this.lastSwitch ?? null,
@@ -1702,7 +1792,6 @@ export async function apply(ctx, rawConfig) {
1702
1792
  ctx.effect(() => () => {
1703
1793
  runtime.stopTimer()
1704
1794
  runtime.stopWatchdog()
1705
- runtime.stopReselect()
1706
1795
  runtime.stopHealthRound()
1707
1796
  void runtime.stop()
1708
1797
  })
@@ -1736,21 +1825,18 @@ export async function apply(ctx, rawConfig) {
1736
1825
  runtime.rearm = () => {
1737
1826
  runtime.scheduleSpeedTest(schedule)
1738
1827
  runtime.scheduleWatchdog(schedule)
1739
- runtime.scheduleReselect(schedule)
1740
1828
  runtime.scheduleHealthRound(schedule)
1741
1829
  }
1742
1830
  runtime.scheduleSpeedTest(schedule)
1743
1831
  runtime.scheduleWatchdog(schedule)
1744
- runtime.scheduleReselect(schedule)
1745
1832
  runtime.scheduleHealthRound(schedule)
1746
1833
  return () => {
1747
1834
  runtime.rearm = undefined
1748
1835
  runtime.stopTimer()
1749
1836
  runtime.stopWatchdog()
1750
- runtime.stopReselect()
1751
1837
  runtime.stopHealthRound()
1752
1838
  }
1753
- }, 'clash-proxy: speed test cycle and watchdog')
1839
+ }, 'clash-proxy: health round, speed test cycle and watchdog')
1754
1840
  })
1755
1841
 
1756
1842
  if (runtime.installRoot === undefined) {
@@ -1795,6 +1881,29 @@ export async function apply(ctx, rawConfig) {
1795
1881
  })
1796
1882
 
1797
1883
  ctx.tools.register(subscriptionTool(runtime))
1884
+
1885
+ /**
1886
+ * Ship the operating manual as a skill rather than as a README.
1887
+ *
1888
+ * `inject` above names `skills`, so this fiber has the registry. Registration is an ordinary
1889
+ * effect: unloading the plugin removes the skill with it, and there is no file in a user
1890
+ * directory that could drift away from this code.
1891
+ *
1892
+ * The registration is attempted in a narrow try/catch because a host that predates the skill
1893
+ * registry (or a profile with the skill layer disabled) must not fail to load the proxy — the
1894
+ * proxy still works, the assistant just has to read the same facts from the tool description.
1895
+ */
1896
+ try {
1897
+ ctx.skills.register({
1898
+ name: SKILL_NAME,
1899
+ description: SKILL_DESCRIPTION,
1900
+ whenToUse: SKILL_WHEN_TO_USE,
1901
+ content: SKILL_CONTENT,
1902
+ })
1903
+ log(`skill ${SKILL_NAME} registered`)
1904
+ } catch (error) {
1905
+ log(`skill ${SKILL_NAME} not registered: ${error?.message ?? error}`)
1906
+ }
1798
1907
  }
1799
1908
 
1800
1909
  /**
@@ -1810,6 +1919,8 @@ function subscriptionTool(runtime) {
1810
1919
  'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and one or more user-imported subscriptions.',
1811
1920
  'Once it runs, foreign requests from this process (web_fetch, search, LLM transports, shells) are routed through the subscription automatically, while domestic traffic and loopback stay direct — no desktop app, no system proxy, no per-command environment variables.',
1812
1921
  'action=status reports the core, the installed policy, every subscription with its node count, the node table and live traffic.',
1922
+ 'action=restart stops and starts the core in one call, for a core that is running but no longer answers its control API.',
1923
+ 'A 403 whose body says "rate limit exceeded" is a spent quota, not a blocked network: the node still works and the answer is another node or a wait, never a repair.',
1813
1924
  'action=import takes one or more subscription URLs (one per line, raw https:// or clash://install-config?url=… import links), probes them, restarts the core on them and routes through it. Without append it replaces the list; with append it adds to it.',
1814
1925
  'action=start brings routing up on the configured subscriptions; action=stop takes it down and restores direct connections.',
1815
1926
  'action=select switches the exit node by name (see the node list from status); action=test measures latency for one node or the current one; action=refresh re-downloads every subscription.',
@@ -1819,8 +1930,8 @@ function subscriptionTool(runtime) {
1819
1930
  properties: {
1820
1931
  action: {
1821
1932
  type: 'string',
1822
- enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh', 'bootstrap', 'reselect', 'health'],
1823
- description: 'status reports state; import sets or appends subscriptions; start/stop control routing; select switches the exit node; test measures latency; refresh re-downloads every subscription; bootstrap downloads and installs a private mihomo core when the machine has none; health runs one real-request health round on the live node (GitHub quota, git fetch, base connectivity) and switches after enough consecutive bad rounds.',
1933
+ enum: ['status', 'import', 'start', 'stop', 'restart', 'select', 'test', 'refresh', 'bootstrap', 'reselect', 'health'],
1934
+ description: 'status reports state; import sets or appends subscriptions; start/stop control routing; restart rebuilds the core (use when it runs but its control API does not answer); select switches the exit node; test measures latency; refresh re-downloads every subscription; bootstrap downloads and installs a private mihomo core when the machine has none; health runs one real-request health round on the live node (base connectivity, GitHub quota, git fetch) and switches after enough consecutive failed or too-slow rounds.',
1824
1935
  },
1825
1936
  url: { type: 'string', description: 'One or more subscription URLs for action=import, one per line. A leading "name " is kept as the display name.' },
1826
1937
  append: { type: 'boolean', description: 'For action=import: add to the existing subscriptions instead of replacing them.' },
@@ -1884,6 +1995,16 @@ function subscriptionTool(runtime) {
1884
1995
  ].join('\n'),
1885
1996
  }
1886
1997
  }
1998
+ if (action === 'restart') {
1999
+ // One call for "the core is up but unusable". `start()` already stops first, so this
2000
+ // is not a second path through the lifecycle — it is the same path, named for the case
2001
+ // that needs it, so a caller does not have to remember to stop first.
2002
+ const report = await runtime.start()
2003
+ return {
2004
+ ...report,
2005
+ summary: `已重建内核:${report.endpoint},当前节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。`,
2006
+ }
2007
+ }
1887
2008
  if (action === 'start') {
1888
2009
  const report = await runtime.start()
1889
2010
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
package/lib/core.js CHANGED
@@ -691,6 +691,27 @@ export class Core {
691
691
  return results
692
692
  }
693
693
 
694
+ /**
695
+ * Measure one probe again through the current probe-group selection, without moving it.
696
+ *
697
+ * Used for latency, which must not be judged on a cold request. Every probe opens its own
698
+ * connection (`Connection: close`), so a core that has just started pays DNS resolution plus
699
+ * TCP and TLS setup on the first request for a host: measured on this machine, the same node
700
+ * answered `gstatic` in **513 ms** on the first request after a fresh core start and in
701
+ * **82 ms** on every request after, because only the first one had to resolve the name. Real
702
+ * traffic reuses both the resolver cache and its connections, so the cold number is not the
703
+ * node's latency — and judging a node on it marked every healthy node too slow.
704
+ *
705
+ * @param spec - the probe to repeat.
706
+ * @param options - `timeoutMs`, `attempts`.
707
+ * @returns the probe result, or undefined when the listener is not up.
708
+ */
709
+ async remeasure(spec, options = {}) {
710
+ if (this.probePort === undefined || spec === undefined) return undefined
711
+ const results = await runProbes(this.probePort, [spec], options)
712
+ return results[spec.id]
713
+ }
714
+
694
715
  /**
695
716
  * Ask one node the real question, through the dedicated probe listener.
696
717
  *
package/lib/routes.js CHANGED
@@ -43,9 +43,11 @@ export const EDITABLE_FIELDS = [
43
43
  'autoReselect',
44
44
  'reselectMinutes',
45
45
  'autoSwitch',
46
- 'healthRoundMinutes',
46
+ 'healthRoundSeconds',
47
47
  'healthStrikeLimit',
48
+ 'healthMaxDelayMs',
48
49
  'healthSwitchCandidates',
50
+ 'healthSurveyEvery',
49
51
  'switchWhileBusy',
50
52
  ]
51
53
 
package/lib/skill.js ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The skill this plugin ships with itself.
3
+ *
4
+ * A plugin that owns the process-wide outbound policy cannot be usefully documented in a README
5
+ * nobody opens at the moment it matters. The failure this skill prevents is specific: a command
6
+ * fails, the assistant concludes "the network is down", and starts opening a desktop proxy that
7
+ * fights the plugin for the same dispatcher. Neither condition is usually true — the plugin is
8
+ * routing, and the fix is a different exit node.
9
+ *
10
+ * Registered through `ctx.skills.register()` in `apply()`, so it travels with the package and
11
+ * disappears when the plugin is unloaded; no file in a user directory, nothing to keep in sync.
12
+ */
13
+
14
+ /** Kebab-case name the model and the user both address it by. */
15
+ export const SKILL_NAME = 'clash-proxy-egress'
16
+
17
+ /** One-line routing description shown in the skill catalog. */
18
+ export const SKILL_DESCRIPTION =
19
+ 'Route DeepSeek Harness outbound traffic through this plugin\'s private mihomo core: check whether egress is actually healthy, repair it in order (status -> start -> restart -> switch node), and never open a second proxy that fights it.'
20
+
21
+ /** When the catalog should surface this skill. */
22
+ export const SKILL_WHEN_TO_USE =
23
+ 'A foreign request fails (git clone/pull, curl, npm/pnpm/pip, web_fetch, a foreign API), or the user asks whether the proxy is up, why a node is slow, which node is selected, or how to get out through a specific region. Not for domestic-only failures and not for DNS problems on a LAN host.'
24
+
25
+ /**
26
+ * The instruction body.
27
+ *
28
+ * Written as a decision procedure, not a catalogue: every step names the command that answers it
29
+ * and the observation that makes the next step correct. The repair ladder is ordered by blast
30
+ * radius, because each rung costs every in-flight connection something — and the last rung costs
31
+ * the whole process every socket it holds.
32
+ */
33
+ export const SKILL_CONTENT = `# 走插件出网:判断、修复、换节点
34
+
35
+ Harness 的外网由 \`dsh-clash-subscription\` 插件统一代理。插件起一个私有 mihomo 内核,
36
+ 把**本进程和它派生的子进程**的出网指向那个内核:境外走订阅节点,国内直连,loopback 与局域网不走代理。
37
+
38
+ 所以第一件事永远是:**先判断现在到底通不通,再决定要不要动它**。
39
+ 「命令失败了」既不等于「外网不通」,也不等于「插件挂了」。
40
+
41
+ ## 一、先取证,三条命令
42
+
43
+ ### 1. 插件状态(唯一权威)
44
+
45
+ \`\`\`bash
46
+ curl -sS -m 8 http://127.0.0.1:<宿主端口>/clash-proxy/status
47
+ \`\`\`
48
+
49
+ 宿主端口取当前会话 GUI 的端口(DSH 每次启动可能不同)。返回里只看这几个字段:
50
+
51
+ | 字段 | 含义 | 正常值 |
52
+ |---|---|---|
53
+ | \`running\` | 内核进程在不在 | \`true\` |
54
+ | \`routingVerified\` | 进程出网策略是不是本插件装的 | \`"active"\` |
55
+ | \`routingHealthy\` | 策略 + 内核同时成立 | \`true\` |
56
+ | \`node\` | 当前出口 | 具体节点名,不是 \`DIRECT\` |
57
+ | \`health.lastRound.state\` | 最近一轮真实探测结论 | \`ok\` / \`degraded\` |
58
+ | \`health.lastRound.strikes\` | 连续失败轮数 / 上限 | 小于 \`strikeLimit\` |
59
+
60
+ \`routingHealthy: true\` 就**什么都不要做**,直接跑原命令。
61
+
62
+ ### 2. 真实出网(区分「插件通」和「节点能出」)
63
+
64
+ \`\`\`bash
65
+ curl -sS -o /dev/null -w '%{http_code}\\n' -m 12 https://api.github.com/rate_limit
66
+ \`\`\`
67
+
68
+ - \`200\` → 通。
69
+ - \`403\` 且响应体含 \`API rate limit exceeded\` → **通了但配额耗尽**,不是墙,也不是插件问题。
70
+ - \`000\` / 超时 → 插件可能在跑但节点出不去,进第二节。
71
+
72
+ ### 3. 子进程继承(命令行的常见误判)
73
+
74
+ \`\`\`bash
75
+ env | grep -i proxy
76
+ \`\`\`
77
+
78
+ 应当看到 \`HTTP_PROXY\` / \`HTTPS_PROXY\` 指向 \`http://127.0.0.1:<内核端口>\`。
79
+ **没有**就是子进程没拿到策略,这时 \`git\`/\`npm\` 会当作直连失败,而不是代理失败。
80
+
81
+ ## 二、修复阶梯(按代价从小到大,不要跳级)
82
+
83
+ | 级别 | 动作 | 代价 | 什么时候用 |
84
+ |---|---|---|---|
85
+ | 0 | 什么都不做 | 0 | \`routingHealthy: true\` |
86
+ | 1 | \`action=start\` | 重装策略,不换节点 | \`running: false\`,或策略丢了(\`routingVerified != active\`) |
87
+ | 2 | \`action=select node=<名>\` | 只换出口,**断掉该节点上的在飞连接** | 策略正常、节点出不去(第 2 条命令 \`000\`) |
88
+ | 3 | \`action=restart\` / 先 \`stop\` 再 \`start\` | 重建内核,全部连接重来 | 内核进程在但控制 API 不应答 |
89
+ | 4 | \`action=refresh\` | 重下订阅,可能换一批节点 | 节点表为空,或订阅过期 |
90
+
91
+ **不要做的事**:
92
+
93
+ - 不要开桌面 Clash Verge 或改系统代理。插件的内核与桌面端会抢同一个 dispatcher 和同一份
94
+ 环境变量,表现是「时通时不通」「git 能拉但 npm 装不上」。
95
+ - 不要在没取证的情况下列「网络正常」或「插件坏了」。
96
+ - 不要改 mode / 端口 / 订阅列表来「试一试」。换节点就够了。
97
+
98
+ ## 三、换节点:按真实探测结果挑,不要按延迟挑
99
+
100
+ 节点列表不是等价的。一个延迟 200 ms 的节点可能:
101
+
102
+ - GitHub 配额已耗尽(\`200\` 但 \`x-ratelimit-remaining: 0\`);
103
+ - git 拉取的第一个请求超时;
104
+ - 只有基础连通能过。
105
+
106
+ \`status\` 里每个节点带 \`usable\` 三态,这就是判据:
107
+
108
+ | \`usable\` | 含义 | 用它吗 |
109
+ |---|---|---|
110
+ | \`ok\` | 所有门槛探针通过 | 优先 |
111
+ | \`limited\` | 线路正常,只是某个服务配额耗尽 | 可以,排在 \`ok\` 之后 |
112
+ | \`blocked\` | 有探针硬失败(超时 / 重置 / 状态码不对) | 不要 |
113
+
114
+ \`limited\` 是可用状态,不是故障。整个订阅的出口地址可能同时耗尽同一个配额,
115
+ 这时坚持挑一个「配额干净」的节点只会把连接白断一次。
116
+
117
+ 换法:
118
+
119
+ \`\`\`
120
+ clash_proxy action=select node=<精确节点名>
121
+ \`\`\`
122
+
123
+ 节点名要逐字复制(含旗帜 emoji 与空格)。
124
+
125
+ ## 四、自动切换已经在跑,不要抢它
126
+
127
+ 插件自己每 30 秒做一轮:通过当前节点发真请求(基础连通 204、GitHub API 连配额、git 拉取),
128
+ **可用且延迟低于阈值**就保持;连续 3 轮不合格才自动切到最优节点。
129
+
130
+ 所以:
131
+
132
+ - 用户问「为什么还没换」,先看 \`health.lastRound.strikes\`:1/3、2/3 是正常的等待,不是卡住。
133
+ - 不要在 \`strikes\` 还没到上限时手动换节点,那会把计数清零,坏节点永远攒不满 3 轮。
134
+ - 要立刻验证,用 \`action=health\` 强制跑一轮并看明细。
135
+
136
+ ## 五、按症状查
137
+
138
+ | 症状 | 先查 | 通常是 |
139
+ |---|---|---|
140
+ | \`git clone\` 卡住 / \`ECONNRESET\` | 第 2 条命令 | 节点出不去,或 git 协议被该节点掐断 |
141
+ | GitHub API \`403\` | 响应体有没有 \`rate limit exceeded\` | 配额耗尽,等重置或换地区节点 |
142
+ | \`npm\`/\`pnpm\` 装不上但 \`curl\` 能通 | \`env \\| grep -i proxy\` | 子进程环境缺失 |
143
+ | 国内站点 000 | —— | 国内站自身慢,与插件无关,重试即可 |
144
+ | \`web_fetch\` 全部失败 | \`routingHealthy\` | 内核死了,级别 1 |
145
+ | 只有某个 AI 服务连不上 | 该节点的 \`usable\` 与失败探针 | 该服务的地区/机房限制,换节点 |
146
+ | 面板显示节点「限流」但还能上网 | —— | 正常,配额是单服务限制 |
147
+
148
+ ## 六、边界
149
+
150
+ - 只动插件自己的出口与生命周期;不改订阅、不改 mode、不改端口。
151
+ - 换节点会断开该节点上的在飞请求。有下载或流式响应在跑时,等它结束或明确告诉用户会被中断。
152
+ - 插件的内核与桌面 Clash 是两套栈。用户开着桌面端时,不要试图让两者共存。
153
+ `
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-clash-subscription",
3
- "version": "0.7.0",
4
- "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin, with real-request node health checks (status codes and remaining quota, not just latency) and automatic switching after consecutive failed rounds.",
3
+ "version": "0.8.0",
4
+ "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin, with real-request node health checks every 30 seconds (status codes, GitHub quota, git fetch, Google latency under a 400 ms ceiling) and automatic switching to the best node after three consecutive failed rounds.",
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.7.0.md",
37
+ "CHANGELOG-0.8.0.md",
38
38
  "LICENSE"
39
39
  ],
40
40
  "engines": {
@@ -69,6 +69,6 @@
69
69
  "scripts": {
70
70
  "test": "node test/regression-070.mjs",
71
71
  "test:legacy": "node test/regression-063.mjs",
72
- "test:e2e": "node test/e2e-070.mjs"
72
+ "test:e2e": "node test/e2e-080.mjs"
73
73
  }
74
74
  }
@@ -1,129 +0,0 @@
1
- # 0.7.0 · 可用性判据换成真实请求,连续失败自动切换
2
-
3
- > 上一版 `0.6.4` · 本版 `0.7.0`
4
-
5
- ## 0.6.4 漏掉了什么
6
-
7
- 面板把**限流节点显示成「可用」**。根因不在面板,在判据:
8
-
9
- ```js
10
- // 0.6.4(lib/core.js):只要内核回了 delay 数字就算通过
11
- const data = await this.api(`${path}?${query}`)
12
- if (typeof data?.delay === 'number' && data.delay > 0) return data.delay
13
- ```
14
-
15
- `/proxies/<name>/delay` 和 `/providers/.../healthcheck` 只回答「目标有没有回包」,**不解释回的是什么**:
16
-
17
- | 实测(本机、真实订阅、2026-11-15) | 内核回报 | 真实情况 |
18
- |---|---|---|
19
- | `api.github.com/rate_limit` 返回 `403 rate limit exceeded` | `{"delay":179}` | 配额已耗尽,API 完全不可用 |
20
- | 路径返回 `404` | `{"delay":301}` | 通,但不是要的结果 |
21
- | `github.com` git 拉取 15 s 超时 | `{"delay":287}` | 根本拉不下来 |
22
- | `expected=418` 参数(想让它校验状态码) | `{"delay":187}` | **内核直接忽略这个参数** |
23
-
24
- `expected` 被忽略这件事决定了整条路走不通:拿它做能力判定从根上不成立。
25
-
26
- 而且默认探针集里**没有 GitHub、没有 git 协议**:
27
-
28
- ```js
29
- // 0.6.4(lib/select.js)
30
- export const DEFAULT_PROBES = [
31
- { id: 'gstatic', ... }, { id: 'google', ... }, { id: 'openai', ... }, { id: 'anthropic', ... },
32
- ]
33
- ```
34
-
35
- 于是 8 个节点全绿,其中 6 个实际不可用。
36
-
37
- ## 改法
38
-
39
- ### 1. 真实请求,读真状态码与配额(新增 `lib/realprobe.js`)
40
-
41
- 经一个**专用监听端口**发真实请求,判据是状态码 + 响应头 + 响应体前缀:
42
-
43
- | 探针 | 通过条件 | 为什么 |
44
- |---|---|---|
45
- | `gstatic` | 恰好 `204` | 只认这个端点该给的东西 |
46
- | `github` | `200` **且** `x-ratelimit-remaining ≥ 1` | 限流时状态码仍是 200,只有配额头能说明问题 |
47
- | `git` | `200` **且**响应体含 `service=git-upload-pack` | 就是 `git clone` 的第一个请求;拦截门户的 200 不算 |
48
- | `google` / `openai` / `anthropic` | 状态码在各自白名单内 | 参考项,默认不参与门槛 |
49
-
50
- `github` 与 `git` 参与门槛,`openai` / `anthropic` 默认只作参考——一个不可达的额外服务不该清空候选列表。
51
-
52
- ### 2. 独立探测口,测节点不动机上流量(`lib/core.js`)
53
-
54
- 内核按**连接**选节点,所以「测哪个节点」与「线上走哪个」必须分开:
55
-
56
- ```json
57
- "listeners": [{ "name": "probe-in", "type": "mixed", "listen": "127.0.0.1", "port": <probePort>, "proxy": "PROBE" }]
58
- "proxy-groups": [{ "name": "PROXY", ... }, { "name": "PROBE", "type": "select", "use": [...], "proxies": ["DIRECT"] }]
59
- ```
60
-
61
- 实测:`PUT /proxies/PROBE` 之后经探测口发请求,`PROXY` 的选择始终不动。
62
-
63
- ### 3. 连续 3 轮失败才切换(新增 `lib/watch.js`)
64
-
65
- - 每 `healthRoundMinutes`(默认 2 分钟)跑一轮,只测当前节点;
66
- - 连续 `healthStrikeLimit`(默认 3)轮**硬失败**才切换,任何一轮通过就把计数清零;
67
- - 切换时排除刚被放弃的节点,按「无硬失败 → 少失败 → 非降级 → 延迟低」选最优;
68
- - 线路有在飞连接时推迟到下一轮(`switchWhileBusy` 可关掉这个保护)。
69
-
70
- `status.health` 里带 streak、限值、上一轮明细与上次切换记录,所以「为什么还没切」是可查的。
71
-
72
- ### 4. 限流是「降级」,不是「不通」
73
-
74
- 这是本轮实测逼出来的修正:某一刻**全网配额同时为 0**,若把限流算失败,则每个节点都被判死、切换永远报 `no-alternative`,插件卡在一个它自己反复宣布坏掉的节点上。
75
-
76
- 现在的三态:
77
-
78
- | 状态 | 含义 | 可选 |
79
- |---|---|---|
80
- | `ok` | 全部门槛探针通过 | ✅ |
81
- | `limited` | 线路正常,只有配额耗尽 | ✅(排在 `ok` 之后) |
82
- | `blocked` | 有探针硬失败(超时/重置/状态码不对) | ❌ |
83
-
84
- 限流轮**不计 strike**:切到另一个配额同样耗尽的节点只会丢掉连接。
85
-
86
- ## 顺带修掉的三个真问题
87
-
88
- | 问题 | 症状 | 修法 |
89
- |---|---|---|
90
- | `http.request({method:'CONNECT'})` 的 socket 交给 `tls.connect` | 每个 HTTPS 探针都报 `Client network socket disconnected before secure TLS connection was established`,而同一端口 `curl` 是 200 | 改成裸 socket:自己读 `200 Connection established`,再把 socket 交给 TLS |
91
- | 等响应体读完才判定 | `git/info/refs` 一次回 266–357 KB,耗时 6–18 s,把好节点判成 `timeout` | 收满响应头 + 1 KB 前缀就判定 |
92
- | 探针并发跑 | 同一节点实测:串行 4 轮 0 失败,并发 2 有 1 次隧道被掐断 | 默认串行(`concurrency: 1`);传输层失败重试一次,HTTP 状态不重试 |
93
-
94
- ## 配置新增
95
-
96
- | 字段 | 默认 | 说明 |
97
- |---|---|---|
98
- | `autoSwitch` | `true` | 用真实请求监视当前节点 |
99
- | `healthRoundMinutes` | `2` | 轮询间隔;0 = 关闭 |
100
- | `healthStrikeLimit` | `3` | 连续几轮失败才切换 |
101
- | `healthSwitchCandidates` | `12` | 一次切换试几个候选(按延迟从低到高) |
102
- | `switchWhileBusy` | `false` | 有连接在进行时也切换 |
103
-
104
- `probes` 字段仍可自定义,且**不能靠重写配置绕过门槛**:写 `github=<url>` 会保留内置的配额判据,要改必须显式写 `;expect=` / `;gating=0`。
105
-
106
- ## 验收
107
-
108
- ```
109
- node test/regression-070.mjs → 67 passed, 0 failed
110
- node test/regression-063.mjs → 31 passed, 0 failed(旧版断言未回归)
111
- node test/e2e-070.mjs → 14 passed, 0 failed(真内核 + 真订阅 + 真请求)
112
- ```
113
-
114
- e2e 的真实输出(本机、2026-11-15):
115
-
116
- ```
117
- 节点 verdict 硬失败 硬失败探针 github(剩余) git
118
- 邮箱客服…@gmail.com blocked 3 3 blocked(-) blocked empty
119
- 最新官网 ok.riolu.work blocked 3 3 blocked(-) blocked empty
120
- 支持AI:新加坡/马来/美国/台湾 blocked 3 3 blocked(-) blocked empty
121
- 🇭🇰 香港01 limited 0 1 → 0 limited(0) ok
122
- 🇭🇰 香港02 / 🇯🇵 日本01-03 limited 0 0 limited(0) ok
123
-
124
- 把线上节点强制设成那个 blocked 的:
125
- rounds: bad/1 → bad/2 → switched/3
126
- lastSwitch: from 邮箱客服… → to 🇯🇵 日本01 (degraded=false)
127
- ```
128
-
129
- 旧判据下这 8 个节点全部显示「可用」,新版把 3 个判死、5 个判限流,并给出原因。