dsh-clash-subscription 0.6.4 → 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.
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/lib/watch.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The "three bad rounds and switch" state machine.
3
+ *
4
+ * Re-picking a node on a single failed sample is the failure mode this replaces: measured on
5
+ * this machine, one round reported a node as blocked and the next round found it fine, because
6
+ * the first answer arrived from a connection the previous node had already established. A
7
+ * switch tears down every connection that node is carrying, so acting on noise is worse than
8
+ * acting one round late.
9
+ *
10
+ * The rule implemented here is the one asked for: a node is given up on only after it has
11
+ * failed `strikeLimit` consecutive rounds, and a single good round resets the count to zero.
12
+ * Until then the panel shows the streak, so "why has it not switched yet" is answerable.
13
+ *
14
+ * @module dsh-clash-proxy/watch
15
+ */
16
+
17
+ /**
18
+ * Track consecutive failures per node and decided when to give up on one.
19
+ */
20
+ export class HealthWatch {
21
+ /**
22
+ * @param options - `strikeLimit` (default 3) and an optional logger.
23
+ */
24
+ constructor(options = {}) {
25
+ this.strikeLimit = Math.max(1, Number(options.strikeLimit ?? 3))
26
+ this.log = options.logger ?? (() => {})
27
+ /** Node name to consecutive failed rounds. Cleared on any usable round. */
28
+ this.strikes = new Map()
29
+ /** Node name to the last verdict, so the panel can explain the streak. */
30
+ this.last = new Map()
31
+ /** Every round is numbered so a late round can be discarded instead of counted. */
32
+ this.round = 0
33
+ this.history = []
34
+ }
35
+
36
+ /**
37
+ * Count one round's verdict for the node that carried traffic.
38
+ *
39
+ * A degraded round (quota spent, tunnel fine) does **not** count as a strike. Measured on a
40
+ * live subscription: every node's GitHub quota was exhausted at once, and counting that as
41
+ * failure made the round report three strikes, trigger a switch search, and then find no
42
+ * alternative — wedging the plugin on a node it kept declaring broken while every other node
43
+ * was equally short on quota and equally able to carry traffic. Only a hard failure
44
+ * (`blocked`) is a strike.
45
+ *
46
+ * @param name - the node under test.
47
+ * @param verdict - output of `judgeNodeHealth`.
48
+ * @param detail - probe results and timing, kept for the panel.
49
+ * @returns `{ strikes, limit, giveUp, since }` where `giveUp` means the limit was reached.
50
+ */
51
+ record(name, verdict, detail = {}) {
52
+ this.round += 1
53
+ const key = String(name ?? '')
54
+ if (key === '') return { strikes: 0, limit: this.strikeLimit, giveUp: false }
55
+ const usable = verdict?.usable === true
56
+ const strikes = usable ? 0 : (this.strikes.get(key) ?? 0) + 1
57
+ this.strikes.set(key, strikes)
58
+ const entry = {
59
+ name: key,
60
+ round: this.round,
61
+ at: Date.now(),
62
+ usable,
63
+ degraded: verdict?.degraded === true,
64
+ strikes,
65
+ limit: this.strikeLimit,
66
+ failed: Array.isArray(verdict?.failed) ? verdict.failed : [],
67
+ limited: Array.isArray(verdict?.limited) ? verdict.limited : [],
68
+ blocked: Array.isArray(verdict?.blocked) ? verdict.blocked : [],
69
+ probes: detail.probes ?? {},
70
+ total: verdict?.total,
71
+ }
72
+ this.last.set(key, entry)
73
+ this.history.push(entry)
74
+ // Bounded: the panel only ever shows the recent few, and an unbounded array would grow for
75
+ // the lifetime of the process.
76
+ if (this.history.length > 200) this.history = this.history.slice(-200)
77
+ if (!usable) {
78
+ this.log(
79
+ `node ${key} failed round ${strikes}/${this.strikeLimit} (${(entry.failed ?? []).join(',') || 'unknown'})`,
80
+ )
81
+ }
82
+ return { strikes, limit: this.strikeLimit, giveUp: !usable && strikes >= this.strikeLimit, since: this.strikes.get(key) }
83
+ }
84
+
85
+ /**
86
+ * Forget one node's streak, for a deliberate user choice or a successful switch.
87
+ *
88
+ * @param name - the node.
89
+ */
90
+ reset(name) {
91
+ const key = String(name ?? '')
92
+ if (key === '') return
93
+ this.strikes.delete(key)
94
+ const entry = this.last.get(key)
95
+ if (entry !== undefined) this.last.set(key, { ...entry, strikes: 0 })
96
+ }
97
+
98
+ /**
99
+ * The current streak map, as plain data for the status payload.
100
+ *
101
+ * @returns one row per node seen this session, worst first.
102
+ */
103
+ rows() {
104
+ return [...this.last.values()]
105
+ .map((entry) => ({
106
+ name: entry.name,
107
+ strikes: entry.strikes,
108
+ limit: entry.limit,
109
+ usable: entry.usable,
110
+ failed: entry.failed,
111
+ limited: entry.limited,
112
+ blocked: entry.blocked,
113
+ at: new Date(entry.at).toISOString(),
114
+ probes: entry.probes,
115
+ }))
116
+ .sort((a, b) => b.strikes - a.strikes || a.name.localeCompare(b.name))
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Pick the best node from a per-node verdict set.
122
+ *
123
+ * Ordering, and why each step is there:
124
+ *
125
+ * 1. `usable` (no hard failure) before anything else — a node that dropped the request cannot
126
+ * carry work at all;
127
+ * 2. `blocked` count, so a node failing two probes loses to one failing one;
128
+ * 3. `degraded` (quota only) after plain-good — a rate-limited node still works, so it is the
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.
131
+ *
132
+ * `score` already folds 2 and 3 together arithmetically; the explicit fields are kept as the
133
+ * comparison so the ordering survives someone changing the weight.
134
+ *
135
+ * @param rows - one `{ name, verdict }` per candidate.
136
+ * @returns the ranked list, best first.
137
+ */
138
+ export function rankHealth(rows) {
139
+ const list = Array.isArray(rows) ? rows.filter((row) => row !== null && typeof row === 'object') : []
140
+ const good = (row) => (row.verdict?.usable === true ? 0 : 1)
141
+ const blockedCount = (row) => (row.verdict?.blocked ?? []).length
142
+ const degraded = (row) => (row.verdict?.degraded === true ? 1 : 0)
143
+ const score = (row) => Number(row.verdict?.score ?? 0)
144
+ const total = (row) => Number(row.verdict?.total ?? Number.POSITIVE_INFINITY)
145
+ 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),
147
+ )
148
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-clash-subscription",
3
- "version": "0.6.4",
4
- "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin, so blocked sites work while domestic traffic stays direct — no other software involved.",
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.6.4.md",
37
+ "CHANGELOG-0.8.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-063.mjs",
71
- "test:e2e": "node test/e2e-063.mjs"
70
+ "test": "node test/regression-070.mjs",
71
+ "test:legacy": "node test/regression-063.mjs",
72
+ "test:e2e": "node test/e2e-080.mjs"
72
73
  }
73
74
  }
@@ -1,47 +0,0 @@
1
- # 0.6.4 · 钉点真正生效(0.6.3 的默认节点没落地)
2
-
3
- > 上一版 `0.6.3` · 本版 `0.6.4`
4
-
5
- ## 0.6.3 遗漏了什么
6
-
7
- 0.6.3 把默认节点写进了 `CONFIG_DEFAULTS.node`,看着对,实际不生效。
8
-
9
- 宿主给插件补默认值走的是 **`export const Config`(zod schema)**,不是 `CONFIG_DEFAULTS`:
10
-
11
- ```js
12
- // index.js(0.6.3,错的)
13
- export const Config = await buildConfigSchema() // 里层:node: z.string().default('')
14
- export function resolveConfig(raw) {
15
- const config = { ...CONFIG_DEFAULTS, ...input } // CONFIG_DEFAULTS.node 被 input.node='' 覆盖
16
- ```
17
-
18
- row 的 config 是空的,schema 先补出 `node: ''`,`resolveConfig` 再拿 `''` 覆盖掉
19
- `CONFIG_DEFAULTS.node`。实测(本机、装好的 0.6.3):
20
-
21
- ```
22
- 宿主 schema 解析空 row config -> node = ""
23
- 再经 resolveConfig -> node = ""
24
- >>> 真实运行是否钉到新加坡01: NO
25
- ```
26
-
27
- 所以 0.6.3 的其余四项修复都有效,只有钉点没落地。
28
-
29
- ## 改法
30
-
31
- `schema` 与 `CONFIG_DEFAULTS` 两处必须同值,并在测试里锁死这条不变量:
32
-
33
- ```js
34
- node: z.string().default('🇸🇬 新加坡01'),
35
- ```
36
-
37
- ## 验收
38
-
39
- `node test/regression-063.mjs` → **31 passed, 0 failed**(新增 2 条):
40
-
41
- | 断言 | 结果 |
42
- |---|---|
43
- | `schema({}).node === '🇸🇬 新加坡01'` | ok |
44
- | 再过 `resolveConfig` 钉点仍在(宿主真实取值路径) | ok |
45
-
46
- 端到端(`test/e2e-063.mjs`,真内核)本版复跑同 0.6.3:启动 **11.4 s**(0.6.2 为 20.6~25.0 s),
47
- 并发启动不再互杀,首次 `/status` 6 ms。