dsh-clash-subscription 0.7.0 → 0.9.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/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,74 @@ 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
+ /**
131
+ * Consecutive attempts on the live node inside one round before it is given up on.
132
+ *
133
+ * The retries happen **immediately**, not one per timer tick: a node that fails gets its
134
+ * second and third chance seconds later, and only then does the round measure every other
135
+ * node. Spreading the attempts across ticks made a dead node cost a minute and a half before
136
+ * anything was done about it.
137
+ */
138
+ healthAttempts: 3,
139
+ /** Consecutive failed rounds before the node is given up on. */
125
140
  healthStrikeLimit: 3,
126
- /** How many candidate nodes one switch search may test, cheapest first; 0 means all. */
127
- healthSwitchCandidates: 12,
141
+ /**
142
+ * Latency ceiling in milliseconds, compared against the **Google probe's warm round trip**.
143
+ *
144
+ * Google's `generate_204` is the closest thing to a pure distance measurement: it is a static
145
+ * 204 with no API processing, and it is the endpoint every other client uses as a reachability
146
+ * baseline.
147
+ *
148
+ * Two corrections came from measurement, both of which matter more than the choice of endpoint:
149
+ *
150
+ * 1. The sum across probes is the wrong number — a healthy node totalled ~1 290 ms while this
151
+ * probe alone answered in ~90 ms, because GitHub's processing and three TLS handshakes are
152
+ * in the total.
153
+ * 2. The first request after a core start is cold — the same node answered 513 ms and then
154
+ * 82 ms, since every probe opens a fresh connection and only the first pays DNS. Real
155
+ * traffic reuses warm state, so the second measurement is the one that means something.
156
+ */
157
+ healthMaxDelayMs: 400,
158
+ /**
159
+ * Latency samples per attempt; the median of the samples after the first is compared.
160
+ *
161
+ * Measured, consecutive Google probes on one node in one minute returned 2256, 967, 1412, 179,
162
+ * 1190 and 180 ms — a single sample against a 400 ms ceiling decides mostly by luck. Three is
163
+ * the cheapest sample that rejects one outlier; the first sample is dropped from the median
164
+ * because it pays DNS + TCP + TLS on a freshly started core.
165
+ */
166
+ healthLatencySamples: 3,
167
+ /** Which probe supplies the latency number. Google is the distance baseline, not a gate. */
168
+ healthBaselineProbe: 'google',
169
+ /**
170
+ * Cap on how many nodes one switch measures. 0 (the default) measures every unblocked node.
171
+ *
172
+ * A cap turns "find the best exit" into "find the best of the first N", which on a large
173
+ * subscription can pick a worse node than one further down the list. It stays configurable for
174
+ * an operator on a very large subscription who would rather switch fast than switch well.
175
+ */
176
+ healthSwitchCandidates: 0,
128
177
  /** Let a switch proceed even while connections are open. Off by default: it aborts work. */
129
178
  switchWhileBusy: false,
179
+ /**
180
+ * Re-check every node's real capability in the background, on the same round, so the panel can
181
+ * rank alternatives without spending the switch on a slow search at the worst moment.
182
+ * `healthSurveyEvery` rounds; 0 disables the survey.
183
+ */
184
+ healthSurveyEvery: 20,
130
185
  }
131
186
 
132
187
  /**
@@ -173,10 +228,15 @@ async function buildConfigSchema() {
173
228
  probeSamples: z.number().default(2),
174
229
  probeTimeoutMs: z.number().default(8000),
175
230
  autoSwitch: z.boolean().default(true),
176
- healthRoundMinutes: z.number().default(2),
231
+ healthRoundSeconds: z.number().default(30),
232
+ healthAttempts: z.number().default(3),
177
233
  healthStrikeLimit: z.number().default(3),
178
- healthSwitchCandidates: z.number().default(12),
234
+ healthMaxDelayMs: z.number().default(400),
235
+ healthLatencySamples: z.number().default(3),
236
+ healthBaselineProbe: z.string().default('google'),
237
+ healthSwitchCandidates: z.number().default(0),
179
238
  switchWhileBusy: z.boolean().default(false),
239
+ healthSurveyEvery: z.number().default(20),
180
240
  })
181
241
  } catch {
182
242
  return undefined
@@ -226,9 +286,25 @@ export function resolveConfig(raw) {
226
286
  config.probeTimeoutMs = clamp(config.probeTimeoutMs, 1_000, 60_000, 8_000)
227
287
  config.autoSwitch = config.autoSwitch !== false && config.autoSwitch !== 'false'
228
288
  config.switchWhileBusy = config.switchWhileBusy === true || config.switchWhileBusy === 'true'
229
- config.healthRoundMinutes = clamp(config.healthRoundMinutes, 0, 120, 2)
289
+ // 30 s is the default; the floor is 5 s so a misconfigured 1 s cannot turn the round into a
290
+ // permanent probe loop, and each round costs real requests against a real service.
291
+ config.healthRoundSeconds = clamp(config.healthRoundSeconds, 0, 3_600, 30)
230
292
  config.healthStrikeLimit = clamp(config.healthStrikeLimit, 1, 20, 3)
231
- config.healthSwitchCandidates = clamp(config.healthSwitchCandidates, 0, 100, 12)
293
+ config.healthMaxDelayMs = clamp(config.healthMaxDelayMs, 0, 30_000, 400)
294
+ config.healthLatencySamples = clamp(config.healthLatencySamples, 2, 5, 3)
295
+ config.healthBaselineProbe = String(config.healthBaselineProbe ?? 'google').trim() || 'google'
296
+ config.healthAttempts = clamp(config.healthAttempts, 1, 10, 3)
297
+ config.healthSwitchCandidates = clamp(config.healthSwitchCandidates, 0, 200, 0)
298
+ config.healthSurveyEvery = clamp(config.healthSurveyEvery, 0, 10_000, 20)
299
+ // 0.7.0 kept the interval in minutes; carry the value over so an existing profile does not
300
+ // silently fall back to the new 30 s default when someone had deliberately set 15 minutes.
301
+ const legacyMinutes = Number(input.healthRoundMinutes)
302
+ if (!Number.isFinite(Number(input.healthRoundSeconds)) && Number.isFinite(legacyMinutes) && legacyMinutes > 0) {
303
+ config.healthRoundSeconds = clamp(legacyMinutes * 60, 0, 3_600, 30)
304
+ }
305
+ // `reselect` is merged into this round now. Both fields stay readable so an old profile does
306
+ // not fail validation, but neither drives a timer any more.
307
+ config.reselectMinutes = clamp(config.reselectMinutes, 0, 1440, 15)
232
308
  return config
233
309
  }
234
310
 
@@ -275,8 +351,8 @@ export class Runtime {
275
351
  this.idleSince = undefined
276
352
  /** When the current node was last verified. */
277
353
  this.lastCheckAt = undefined
278
- /** Timer for the periodic re-check. */
279
- this.reselectTimer = undefined
354
+ /** Timer for the single health/selection round. */
355
+ this.healthTimer = undefined
280
356
  /** Progress/result of the optional GeoIP upgrade. */
281
357
  this.geo = undefined
282
358
  /** True while that upgrade is running. */
@@ -442,9 +518,12 @@ export class Runtime {
442
518
  autoReselect: this.config.autoReselect,
443
519
  reselectMinutes: this.config.reselectMinutes,
444
520
  autoSwitch: this.config.autoSwitch,
445
- healthRoundMinutes: this.config.healthRoundMinutes,
521
+ healthRoundSeconds: this.config.healthRoundSeconds,
522
+ healthAttempts: this.config.healthAttempts,
446
523
  healthStrikeLimit: this.config.healthStrikeLimit,
524
+ healthMaxDelayMs: this.config.healthMaxDelayMs,
447
525
  healthSwitchCandidates: this.config.healthSwitchCandidates,
526
+ healthSurveyEvery: this.config.healthSurveyEvery,
448
527
  switchWhileBusy: this.config.switchWhileBusy,
449
528
  source: 'configured',
450
529
  }
@@ -520,9 +599,12 @@ export class Runtime {
520
599
  }
521
600
  if (next.speedTestMinutes !== previous.speedTestMinutes) this.requestRearm()
522
601
  if (
523
- next.healthRoundMinutes !== previous.healthRoundMinutes ||
602
+ next.healthRoundSeconds !== previous.healthRoundSeconds ||
524
603
  next.autoSwitch !== previous.autoSwitch ||
525
- next.healthStrikeLimit !== previous.healthStrikeLimit
604
+ next.healthAttempts !== previous.healthAttempts ||
605
+ next.healthStrikeLimit !== previous.healthStrikeLimit ||
606
+ next.healthMaxDelayMs !== previous.healthMaxDelayMs ||
607
+ next.healthSurveyEvery !== previous.healthSurveyEvery
526
608
  ) {
527
609
  this.watch.strikeLimit = next.healthStrikeLimit
528
610
  this.requestRearm()
@@ -632,17 +714,122 @@ export class Runtime {
632
714
  }
633
715
 
634
716
  /**
635
- * Run one real-probe round against the node that is currently carrying traffic.
717
+ * Measure one node once and turn it into a verdict.
718
+ *
719
+ * Extracted so one round can call it three times in a row without waiting for the next timer
720
+ * tick. "Unqualified" means either test failed:
721
+ *
722
+ * - a gating probe did not answer (unreachable / reset / wrong status), or
723
+ * - the Google round trip exceeded `healthMaxDelayMs`.
724
+ *
725
+ * Both are folded into `usable === false` on the returned verdict, with `failed` naming which,
726
+ * so the caller does not need a second condition.
636
727
  *
637
- * This is the piece the plugin was missing. Its old check asked mihomo whether a URL answered
638
- * at all, and a GitHub rate-limit `403` counts as "answered" — measured, the panel reported
639
- * six unusable nodes as `usable` while five of them had `x-ratelimit-remaining: 0` and two
640
- * could not complete a git fetch at all. So the round sends the real requests through the
641
- * probe listener, reads the real status and quota, and records a strike only when a probe
642
- * that gates usability failed.
728
+ * @param name - node to measure.
729
+ * @param plan - the probe plan in force.
730
+ * @returns `{ results, verdict, latency, latencySource, coldLatency, ceiling, baseline }`, or
731
+ * `undefined` when the probe listener did not answer (an instrument fault, not a node fault).
732
+ */
733
+ async measureNode(name, plan) {
734
+ const { results, verdict } = await this.core.checkNodeReal(name, plan.specs, plan.gating, {
735
+ timeoutMs: this.config.probeTimeoutMs ?? 8000,
736
+ })
737
+ if (Object.keys(results).length === 0) return undefined
738
+
739
+ // Google is not a gating probe, so it is absent from `plan.specs` and from `results`: the
740
+ // node already answered the gating set and Google has to be measured on its own. Two
741
+ // measurements are taken, and the second is the number that means something — the first one
742
+ // on a freshly started core pays DNS + TCP + TLS for that host (measured, 513 ms cold vs
743
+ // 82 ms warm), which is not the node's latency.
744
+ //
745
+ // An unreachable Google is **not** a slow node. The ceiling is skipped for that attempt and
746
+ // the node is judged on the gating probes alone, because inventing a latency for an
747
+ // unreachable host would switch away from a node that may be fast for everything else.
748
+ const baseline = plan.probes.find((spec) => spec.id === this.config.healthBaselineProbe) ?? plan.specs[0]
749
+ let latency
750
+ let latencySource = 'not-measured'
751
+ let coldLatency
752
+ /** Every Google sample taken this attempt, so the panel can show the spread. */
753
+ const samples = []
754
+ if (verdict.usable === true && baseline !== undefined && typeof this.core.remeasure === 'function') {
755
+ try {
756
+ // Pin the probe group to this node first. `probeNodeReal` already does that for the gating
757
+ // probes, but relying on that would make the latency number depend on call order: a
758
+ // candidate measured right after the live node would otherwise get the live node's
759
+ // latency. Moving it here makes `measureNode(name)` self-contained — measure the node you
760
+ // name, no matter what was measured before.
761
+ if (typeof this.core.selectProbe === 'function') await this.core.selectProbe(name)
762
+
763
+ // Three samples, and the number used is the MEDIAN of the last two.
764
+ //
765
+ // Measured on a live node, consecutive Google probes returned 2256, 967, 1412, 179, 1190
766
+ // and 180 ms for the same node in the same minute. A single sample against a 400 ms
767
+ // ceiling therefore decides mostly by luck: it lets a momentarily slow-but-fine node fail,
768
+ // and a momentarily fast-but-bad node pass. The median of a small sample is the standard
769
+ // defence, and it is cheap here because each probe is one request to a static endpoint.
770
+ //
771
+ // The first sample is discarded from the median when there are three, because the first
772
+ // one on a freshly started core pays DNS + TCP + TLS for that host — measured, 513 ms cold
773
+ // against 82 ms warm.
774
+ const wanted = Math.max(2, Math.min(Number(this.config.healthLatencySamples ?? 3), 5))
775
+ for (let i = 0; i < wanted; i += 1) {
776
+ const sample = await this.core.remeasure(baseline, { timeoutMs: this.config.probeTimeoutMs ?? 8000, expectNode: name })
777
+ if (typeof sample?.ms === 'number' && sample.ok === true) samples.push(sample.ms)
778
+ }
779
+ if (samples.length > 0) {
780
+ coldLatency = samples[0]
781
+ const forMedian = samples.length > 1 ? samples.slice(1) : samples
782
+ const sorted = [...forMedian].sort((a, b) => a - b)
783
+ latency = sorted[Math.floor(sorted.length / 2)]
784
+ latencySource = samples.length > 1 ? 'warm-median' : 'cold'
785
+ } else {
786
+ latencySource = 'unreachable'
787
+ }
788
+ } catch (error) {
789
+ latencySource = 'failed'
790
+ this.log(`latency measurement failed on ${name}: ${error?.message ?? error}`)
791
+ }
792
+ }
793
+
794
+ const ceiling = Number(this.config.healthMaxDelayMs ?? 400)
795
+
796
+ // A latency that could not be measured must not be treated as "fast enough".
797
+ //
798
+ // The ceiling is the whole point of "unqualified = unusable OR too slow", so `undefined`
799
+ // silently disabling it would let a node with an unreachable Google stay selected forever.
800
+ // But an unreachable Google is also not proof the node is slow, so it cannot simply fail
801
+ // either — that is what caused a healthy node to be switched away from when the probe itself
802
+ // hiccuped.
803
+ //
804
+ // The resolution is a fallback chain, and what it settles on is what gets compared:
805
+ // 1. the warm Google round trip (the measurement the ceiling is defined against);
806
+ // 2. the cold Google round trip (a real number, just includes connection setup);
807
+ // 3. the fastest gating probe that did answer (gstatic is a static 204 too, and every
808
+ // gating probe already ran, so this costs nothing).
809
+ // Only when nothing at all answered does the latency stay undefined — and a node in that
810
+ // state has already failed its gating probes, so it is unqualified on the other count.
811
+ if (latency === undefined) {
812
+ const fallback = [coldLatency, ...Object.values(results).map((row) => (row?.ok === true ? row?.ms : undefined))]
813
+ .filter((value) => typeof value === 'number' && value >= 0)
814
+ .sort((a, b) => a - b)[0]
815
+ if (typeof fallback === 'number') {
816
+ latency = fallback
817
+ latencySource = latencySource === 'unreachable' ? 'fallback-probe' : latencySource
818
+ }
819
+ }
820
+
821
+ const tooSlow = ceiling > 0 && verdict.usable === true && latency !== undefined && latency > ceiling
822
+ const judged = tooSlow ? { ...verdict, usable: false, failed: [...verdict.failed, 'latency'], slow: true } : verdict
823
+ return { results, verdict: judged, latency, latencySource, coldLatency, ceiling, baseline: baseline?.id, samples }
824
+ }
825
+
826
+ /**
827
+ * Run one real-probe round against the node that is currently carrying traffic.
643
828
  *
644
- * A usable round resets the streak, because a node that recovers must not be switched away
645
- * from for old failures.
829
+ * The round retries **immediately**, in the same round, rather than spreading attempts across
830
+ * timer ticks: a node that failed once gets a second and third chance seconds later, and only
831
+ * when all of them fail does the round search for a replacement. That is what makes a bad node
832
+ * cost seconds instead of a minute and a half, while still not switching on a single blip.
646
833
  *
647
834
  * @param options - `force` ignores the enable flag; `node` overrides the node under test.
648
835
  * @returns the round report.
@@ -662,43 +849,90 @@ export class Runtime {
662
849
  return { state: 'no-node', required: plan.gating }
663
850
  }
664
851
 
665
- const { results, verdict } = await this.core.checkNodeReal(current, plan.specs, plan.gating, {
666
- timeoutMs: this.config.probeTimeoutMs ?? 8000,
667
- })
668
- if (Object.keys(results).length === 0) {
669
- // The probe listener is not answering, which says nothing about the node. Reporting a
670
- // strike here would switch away from a healthy node because the instrument broke.
671
- return { state: 'probe-unavailable', node: current }
852
+ const attempts = Math.max(1, Number(this.config.healthAttempts ?? 3))
853
+ const tried = []
854
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
855
+ const measured = await this.measureNode(current, plan)
856
+ if (measured === undefined) {
857
+ // The probe listener is not answering, which says nothing about the node. Reporting a
858
+ // failure here would switch away from a healthy node because the instrument broke.
859
+ return { state: 'probe-unavailable', node: current, attempts: tried }
860
+ }
861
+ const entry = {
862
+ attempt,
863
+ usable: measured.verdict.usable === true,
864
+ latency: measured.latency,
865
+ latencySource: measured.latencySource,
866
+ failed: measured.verdict.failed ?? [],
867
+ slow: measured.verdict.slow === true,
868
+ at: new Date().toISOString(),
869
+ }
870
+ tried.push(entry)
871
+ this.healthRows.set(current, { results: measured.results, verdict: measured.verdict, at: Date.now() })
872
+ this.lastMatrix = [{ name: current, results: measured.results }]
873
+ this.lastCheckAt = Date.now()
874
+
875
+ if (measured.verdict.usable === true) {
876
+ // Kept. One good attempt ends the round; the remaining attempts are not spent, because
877
+ // the node already answered the question this round is asking.
878
+ this.watch.record(current, measured.verdict, { probes: measured.results })
879
+ const report = {
880
+ state: measured.verdict.degraded === true ? 'degraded' : 'ok',
881
+ node: current,
882
+ required: plan.gating,
883
+ results: measured.results,
884
+ verdict: measured.verdict,
885
+ latency: measured.latency,
886
+ latencySource: measured.latencySource,
887
+ coldLatency: measured.coldLatency,
888
+ totalLatency: measured.results && undefined,
889
+ ceiling: measured.ceiling,
890
+ baseline: measured.baseline,
891
+ attempt,
892
+ attempts: tried,
893
+ attemptLimit: attempts,
894
+ giveUp: false,
895
+ at: new Date().toISOString(),
896
+ }
897
+ this.health = report
898
+ this.log(`round ok on ${current} at attempt ${attempt}/${attempts} (${measured.latency ?? '?'} ms)`)
899
+ void this.runSurveyTick()
900
+ return report
901
+ }
902
+
903
+ this.log(
904
+ `round attempt ${attempt}/${attempts} failed on ${current}: ` +
905
+ `${measured.verdict.failed.join(',') || 'no-answer'}` +
906
+ (measured.latency === undefined ? '' : ` (${measured.latency} ms, ceiling ${measured.ceiling} ms)`),
907
+ )
672
908
  }
673
909
 
674
- this.healthRows.set(current, { results, verdict, at: Date.now() })
675
- this.lastMatrix = [{ name: current, results }]
676
- this.lastCheckAt = Date.now()
677
- const counted = this.watch.record(current, verdict, { probes: results })
678
- // `degraded` is a usable node that is short on quota. It is reported, never acted on:
679
- // 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'
910
+ // Every attempt failed.
911
+ this.watch.record(current, { usable: false, failed: tried.at(-1)?.failed ?? [], limited: [], blocked: [], score: 100 })
912
+ const verdictNow = {
913
+ usable: false,
914
+ degraded: false,
915
+ failed: tried.at(-1)?.failed ?? [],
916
+ limited: [],
917
+ blocked: [],
918
+ slow: tried.every((entry) => entry.slow === true),
919
+ }
681
920
  const report = {
682
- state,
921
+ state: verdictNow.slow ? 'slow' : 'bad',
683
922
  node: current,
684
923
  required: plan.gating,
685
- results,
686
- verdict,
687
- strikes: counted.strikes,
688
- strikeLimit: counted.limit,
689
- giveUp: counted.giveUp,
924
+ verdict: verdictNow,
925
+ latency: tried.at(-1)?.latency,
926
+ latencySource: tried.at(-1)?.latencySource,
927
+ ceiling: Number(this.config.healthMaxDelayMs ?? 400),
928
+ attempt: attempts,
929
+ attempts: tried,
930
+ attemptLimit: attempts,
931
+ giveUp: true,
690
932
  at: new Date().toISOString(),
691
933
  }
692
934
  this.health = report
693
- if (verdict.usable) {
694
- this.log(`health round ok on ${current} (${Object.keys(results).join('/')})`)
695
- return report
696
- }
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
- )
701
- if (!counted.giveUp) return report
935
+ this.log(`${attempts} attempts all failed on ${current}; searching every unblocked node`)
702
936
  return await this.switchAfterStrikes(report, plan, options)
703
937
  } finally {
704
938
  this.healthRunning = false
@@ -706,12 +940,22 @@ export class Runtime {
706
940
  }
707
941
 
708
942
  /**
709
- * Switch away from a node whose streak reached the limit.
943
+ * Switch away from a node that failed every attempt in its round.
710
944
  *
711
- * The search is bounded by `healthSwitchCandidates` and ordered by measured latency, because
712
- * a 54-node subscription cannot be probed for real inside one round without spending minutes
713
- * on nodes that answered worst last time. The node that just failed is excluded from its own
714
- * replacement, which is the difference between "we tried" and "we picked it again".
945
+ * Every unblocked node is measured, then the best one is chosen. Nothing is capped by default:
946
+ * the point of a switch is to find the best exit that exists right now, and a cap turns that
947
+ * into "the best of the first twelve", which on a 54-node subscription can silently pick a
948
+ * worse node than one further down the list. `healthSwitchCandidates` still exists as an
949
+ * operator escape hatch for a huge subscription, but its default is 0 (everything).
950
+ *
951
+ * "Best" is decided from this round's measurements, in this order:
952
+ *
953
+ * 1. usable (no gating probe failed) before anything else;
954
+ * 2. the lowest warm Google latency — this is the number the ceiling talks about, and the
955
+ * fastest working node is what "最优" means here;
956
+ * 3. fewer failed probes, then a quota-limited node before an unreachable one, as tie-breaks.
957
+ *
958
+ * The node that just failed is not a candidate for its own replacement.
715
959
  *
716
960
  * Busy-line handling: a switch tears down in-flight connections. When the line is carrying
717
961
  * work the switch waits for the next round unless `switchWhileBusy` is on — a broken node that
@@ -719,14 +963,14 @@ export class Runtime {
719
963
  *
720
964
  * @param report - the failing round.
721
965
  * @param plan - the probe plan.
722
- * @param options - `force` bypasses the busy gate.
966
+ * @param options - `bypassBusy` skips the busy gate.
723
967
  * @returns the round report with the switch result attached.
724
968
  */
725
969
  async switchAfterStrikes(report, plan, options = {}) {
726
970
  const traffic = await this.core.connections().catch(() => undefined)
727
971
  const limit = Number(this.config.reselectIdleConnections ?? 2)
728
- // `force` means "run this round now", not "ignore in-flight work": the two were conflated
729
- // in the first draft and an explicit check aborted a download. Only `bypassBusy` (or the
972
+ // `force` means "run this round now", not "ignore in-flight work": the two were conflated in
973
+ // an earlier draft and an explicit check aborted a download. Only `bypassBusy` (or the
730
974
  // configuration switch) may interrupt traffic.
731
975
  const bypassBusy = options.bypassBusy === true || this.config.switchWhileBusy === true
732
976
  if (!bypassBusy && traffic !== undefined && traffic.count > limit) {
@@ -735,36 +979,62 @@ export class Runtime {
735
979
  }
736
980
 
737
981
  const group = await this.core.group()
738
- const candidates = group.all.filter((name) => name !== 'DIRECT' && name !== 'REJECT' && name !== report.node)
739
- const cap = Number(this.config.healthSwitchCandidates ?? 12)
982
+ // `group.all` is what the core carries, which already excludes blocked nodes — the blocklist
983
+ // is applied as the provider's `exclude-filter`, so a hidden node never enters the table.
984
+ // Filtering again here is belt-and-braces for a table that was built before a blocklist edit.
985
+ const candidates = group.all.filter(
986
+ (name) => name !== 'DIRECT' && name !== 'REJECT' && name !== report.node && !isBlocked(name, this.config.blocklist),
987
+ )
988
+ const cap = Number(this.config.healthSwitchCandidates ?? 0)
740
989
  const ordered = cap > 0 ? candidates.slice(0, cap) : candidates
741
990
  const startedAt = Date.now()
742
- const matrix = await this.core.realMatrix({
743
- nodes: ordered,
744
- specs: plan.specs,
745
- gating: plan.gating,
746
- delays: this.measured,
747
- budgetMs: Math.min(Number(this.config.selectBudgetMs ?? 90_000), 120_000),
748
- timeoutMs: this.config.probeTimeoutMs ?? 8000,
991
+ this.log(`measuring ${ordered.length} candidate node(s) for a replacement`)
992
+
993
+ // Measured one at a time, reusing `measureNode` so a candidate is judged exactly like the
994
+ // live node was — same probes, same ceiling, same warm latency. The budget is generous
995
+ // because this path runs once per failure, not on every tick.
996
+ const rows = []
997
+ for (const name of ordered) {
998
+ const measured = await this.measureNode(name, plan)
999
+ if (measured === undefined) continue
1000
+ rows.push({ name, ...measured })
1001
+ this.healthRows.set(name, { results: measured.results, verdict: measured.verdict, at: Date.now() })
1002
+ }
1003
+ this.lastMatrix = rows.map((row) => ({ name: row.name, results: row.results }))
1004
+
1005
+ // Usable first, then fastest warm latency, then fewest failures, then a limited node before
1006
+ // an unreachable one. Missing latency sorts last among usable nodes: a node whose speed could
1007
+ // not be measured is not the one to prefer.
1008
+ const rank = (row) => [
1009
+ row.verdict?.usable === true ? 0 : 1,
1010
+ typeof row.latency === 'number' ? row.latency : Number.POSITIVE_INFINITY,
1011
+ (row.verdict?.failed ?? []).length,
1012
+ (row.verdict?.blocked ?? []).length,
1013
+ ]
1014
+ rows.sort((a, b) => {
1015
+ const ra = rank(a)
1016
+ const rb = rank(b)
1017
+ for (let i = 0; i < ra.length; i += 1) {
1018
+ if (ra[i] !== rb[i]) return ra[i] - rb[i]
1019
+ }
1020
+ return a.name.localeCompare(b.name)
749
1021
  })
750
- const best = matrix.best
751
- this.healthRows = new Map(
752
- matrix.rows.map((row) => [row.name, { results: row.results, verdict: row.verdict, at: Date.now() }]),
753
- )
754
- this.lastMatrix = matrix.rows.map((row) => ({ name: row.name, results: row.results }))
755
- // `usable` here means "no hard failure". A degraded node (quota spent, tunnel fine) is a
756
- // legitimate replacement: with every exit address out of GitHub quota, insisting on a
757
- // quota-clean node leaves the plugin on the node it just gave up on.
1022
+ const best = rows[0]
1023
+ const tested = rows.length
1024
+ const elapsedMs = Date.now() - startedAt
1025
+
758
1026
  if (best === undefined || best.verdict?.usable !== true) {
759
1027
  this.lastSwitch = {
760
1028
  state: 'no-alternative',
761
1029
  from: report.node,
762
1030
  at: new Date().toISOString(),
763
- tested: matrix.tested,
764
- elapsedMs: Date.now() - startedAt,
1031
+ tested,
1032
+ elapsedMs,
1033
+ // Every candidate's reason, so "no alternative" can be audited instead of trusted.
1034
+ rejected: rows.slice(0, 8).map((row) => ({ name: row.name, failed: row.verdict?.failed ?? [], latency: row.latency })),
765
1035
  }
766
- this.log(`no usable alternative to ${report.node} out of ${matrix.tested} tested`)
767
- return { ...report, state: 'no-alternative', tested: matrix.tested }
1036
+ this.log(`no usable alternative to ${report.node} out of ${tested} tested`)
1037
+ return { ...report, state: 'no-alternative', tested, elapsedMs }
768
1038
  }
769
1039
 
770
1040
  await this.core.select(best.name)
@@ -776,28 +1046,69 @@ export class Runtime {
776
1046
  to: best.name,
777
1047
  at: new Date().toISOString(),
778
1048
  failed: report.verdict?.failed ?? [],
779
- limited: report.verdict?.limited ?? [],
780
1049
  degraded: best.verdict?.degraded === true,
781
- tested: matrix.tested,
782
- elapsedMs: Date.now() - startedAt,
1050
+ latency: best.latency,
1051
+ tested,
1052
+ elapsedMs,
783
1053
  }
784
- this.log(`switched ${report.node} -> ${best.name} after ${report.strikes} bad rounds`)
785
- return { ...report, state: 'switched', from: report.node, to: best.name, switchedTo: best.name, tested: matrix.tested }
1054
+ this.log(`switched ${report.node} -> ${best.name} (${best.latency ?? '?'} ms) after ${report.attemptLimit ?? report.attempts?.length ?? 3} failed attempts`)
1055
+ return {
1056
+ ...report,
1057
+ state: 'switched',
1058
+ from: report.node,
1059
+ to: best.name,
1060
+ switchedTo: best.name,
1061
+ toLatency: best.latency,
1062
+ tested,
1063
+ elapsedMs,
1064
+ }
1065
+ }
1066
+
1067
+ /**
1068
+ * Re-check the current node on demand, as `clash_proxy action=reselect` and the panel's
1069
+ * button do.
1070
+ *
1071
+ * This is the manual entry point now, not a second timer: the scheduled work all lives in
1072
+ * `healthRound`, so a manual reselect runs one round with `force` and reports the same shape.
1073
+ *
1074
+ * @param options - `force` skips the busy gate.
1075
+ * @returns the round report.
1076
+ */
1077
+ async autoReselect(options = {}) {
1078
+ const report = await this.healthRound({ ...options, force: true })
1079
+ if (report.state === 'switched') {
1080
+ return { state: 'switched', from: report.from, to: report.to, failed: report.failed, required: report.required, verdict: report.verdict }
1081
+ }
1082
+ if (report.state === 'ok' || report.state === 'degraded') {
1083
+ return { state: 'kept', node: report.node, required: report.required, results: report.results, verdict: report.verdict, latency: report.latency }
1084
+ }
1085
+ if (report.state === 'no-alternative') {
1086
+ return { state: 'no-alternative', lostNode: report.node, failed: report.verdict?.failed ?? [], required: report.required }
1087
+ }
1088
+ return report
786
1089
  }
787
1090
 
788
1091
  /**
789
- * Arm the real-probe health round.
1092
+ * Arm the single health/selection round.
1093
+ *
1094
+ * One timer drives everything: the live node's verdict, the latency ceiling, the automatic
1095
+ * switch, and (every `healthSurveyEvery` rounds) a background survey of the other nodes so a
1096
+ * switch has a ranked list ready instead of starting a slow search at the worst moment.
1097
+ *
1098
+ * The round is single-flight (`healthRunning`), so a period shorter than one round's duration
1099
+ * skips ticks instead of stacking them — measured, one round takes ~1.3 s on a healthy node,
1100
+ * so 30 s leaves plenty of headroom, but a dead node with several timeouts can exceed it.
790
1101
  *
791
1102
  * @param schedule - timer factory from the plugin context.
792
1103
  */
793
1104
  scheduleHealthRound(schedule) {
794
1105
  if (this.healthTimer !== undefined) this.healthTimer()
795
1106
  this.healthTimer = undefined
796
- const minutes = this.config.healthRoundMinutes
797
- if (this.config.autoSwitch === false || minutes <= 0 || typeof schedule !== 'function') return
1107
+ const seconds = Number(this.config.healthRoundSeconds ?? 30)
1108
+ if (this.config.autoSwitch === false || seconds <= 0 || typeof schedule !== 'function') return
798
1109
  this.healthTimer = schedule(() => {
799
1110
  void this.healthRound().catch((error) => this.log(`health round failed: ${error?.message ?? error}`))
800
- }, minutes * 60_000)
1111
+ }, seconds * 1000)
801
1112
  }
802
1113
 
803
1114
  /** Stop the health round. Safe to call when none is running. */
@@ -808,110 +1119,55 @@ export class Runtime {
808
1119
  }
809
1120
 
810
1121
  /**
811
- * Re-check the current node's capabilities and switch only when it is no longer usable.
1122
+ * Survey the nodes that are not currently selected, on a slow cadence.
812
1123
  *
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.
1124
+ * The switch path can measure candidates on demand, but doing it only then means the search
1125
+ * starts exactly when the line is already broken and the user is waiting. A background survey
1126
+ * keeps `healthRows` populated for every node, so the switch picks from known-good candidates
1127
+ * and the panel can show real per-node verdicts without being opened at the right moment.
816
1128
  *
817
- * @param options - `force` bypasses the idle gate.
818
- * @returns what happened and why.
1129
+ * Bounded by `healthSwitchCandidates` and skipped while a switch is in progress.
1130
+ *
1131
+ * @returns the survey result, or `{ state: 'skipped' }` when it did not run.
819
1132
  */
820
- async autoReselect(options = {}) {
821
- const gate = await this.canReselectNow(options)
822
- if (!gate.ok) return { state: 'skipped', ...gate }
823
-
1133
+ async runSurveyTick() {
1134
+ const every = Number(this.config.healthSurveyEvery ?? 20)
1135
+ if (every <= 0 || this.healthRunning !== true) return { state: 'skipped' }
1136
+ // Counted inside a round, so `healthRoundSeconds * every` is the survey period.
1137
+ this.surveyTicks = (this.surveyTicks ?? 0) + 1
1138
+ if (this.surveyTicks % every !== 0) return { state: 'not-due', ticks: this.surveyTicks }
1139
+ if (this.switching === true) return { state: 'skipped' }
1140
+ if (this.core === undefined || this.core.running !== true) return { state: 'core-not-running' }
824
1141
  const plan = this.probePlan()
825
- const group = await this.core.group()
1142
+ const group = await this.core.group().catch(() => undefined)
1143
+ if (group === undefined) return { state: 'no-group' }
826
1144
  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,
1145
+ const cap = Number(this.config.healthSwitchCandidates ?? 12)
1146
+ const candidates = group.all
1147
+ .filter((name) => name !== 'DIRECT' && name !== 'REJECT' && name !== current)
1148
+ .slice(0, cap > 0 ? cap : undefined)
1149
+ if (candidates.length === 0) return { state: 'no-candidates' }
1150
+ this.switching = true
1151
+ try {
1152
+ const matrix = await this.core.realMatrix({
1153
+ nodes: candidates,
831
1154
  specs: plan.specs,
832
- budgetMs: this.config.selectBudgetMs,
1155
+ gating: plan.gating,
833
1156
  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, {
1157
+ budgetMs: Math.min(Number(this.config.selectBudgetMs ?? 90_000), 60_000),
847
1158
  timeoutMs: this.config.probeTimeoutMs ?? 8000,
848
- samples: this.config.probeSamples ?? 2,
849
1159
  })
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 }
1160
+ const at = Date.now()
1161
+ for (const row of matrix.rows) this.healthRows.set(row.name, { results: row.results, verdict: row.verdict, at })
1162
+ this.lastSurvey = { at: new Date(at).toISOString(), tested: matrix.tested, usable: matrix.rows.filter((r) => r.verdict?.usable === true).length }
1163
+ this.log(`survey: ${this.lastSurvey.usable}/${matrix.tested} nodes usable`)
1164
+ return { state: 'surveyed', ...this.lastSurvey }
1165
+ } catch (error) {
1166
+ this.log(`survey failed: ${error?.message ?? error}`)
1167
+ return { state: 'failed', reason: String(error?.message ?? error) }
1168
+ } finally {
1169
+ this.switching = false
880
1170
  }
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
1171
  }
916
1172
 
917
1173
  /**
@@ -1647,9 +1903,17 @@ export class Runtime {
1647
1903
  * node is limited, so why has it not switched yet".
1648
1904
  */
1649
1905
  health: {
1650
- enabled: this.config.autoSwitch !== false && this.config.healthRoundMinutes > 0,
1651
- everyMinutes: this.config.healthRoundMinutes,
1906
+ enabled: this.config.autoSwitch !== false && this.config.healthRoundSeconds > 0,
1907
+ everySeconds: this.config.healthRoundSeconds,
1908
+ /** Consecutive attempts inside one round before the node is given up on. */
1909
+ attempts: this.config.healthAttempts,
1652
1910
  strikeLimit: this.watch.strikeLimit,
1911
+ maxDelayMs: this.config.healthMaxDelayMs,
1912
+ baselineProbe: this.config.healthBaselineProbe,
1913
+ /** 0 means "measure every unblocked node when switching". */
1914
+ switchCandidates: this.config.healthSwitchCandidates,
1915
+ surveyEvery: this.config.healthSurveyEvery,
1916
+ survey: this.lastSurvey ?? null,
1653
1917
  lastRound: this.health ?? null,
1654
1918
  inFlight: this.healthRunning === true,
1655
1919
  lastSwitch: this.lastSwitch ?? null,
@@ -1702,7 +1966,6 @@ export async function apply(ctx, rawConfig) {
1702
1966
  ctx.effect(() => () => {
1703
1967
  runtime.stopTimer()
1704
1968
  runtime.stopWatchdog()
1705
- runtime.stopReselect()
1706
1969
  runtime.stopHealthRound()
1707
1970
  void runtime.stop()
1708
1971
  })
@@ -1736,21 +1999,18 @@ export async function apply(ctx, rawConfig) {
1736
1999
  runtime.rearm = () => {
1737
2000
  runtime.scheduleSpeedTest(schedule)
1738
2001
  runtime.scheduleWatchdog(schedule)
1739
- runtime.scheduleReselect(schedule)
1740
2002
  runtime.scheduleHealthRound(schedule)
1741
2003
  }
1742
2004
  runtime.scheduleSpeedTest(schedule)
1743
2005
  runtime.scheduleWatchdog(schedule)
1744
- runtime.scheduleReselect(schedule)
1745
2006
  runtime.scheduleHealthRound(schedule)
1746
2007
  return () => {
1747
2008
  runtime.rearm = undefined
1748
2009
  runtime.stopTimer()
1749
2010
  runtime.stopWatchdog()
1750
- runtime.stopReselect()
1751
2011
  runtime.stopHealthRound()
1752
2012
  }
1753
- }, 'clash-proxy: speed test cycle and watchdog')
2013
+ }, 'clash-proxy: health round, speed test cycle and watchdog')
1754
2014
  })
1755
2015
 
1756
2016
  if (runtime.installRoot === undefined) {
@@ -1795,6 +2055,29 @@ export async function apply(ctx, rawConfig) {
1795
2055
  })
1796
2056
 
1797
2057
  ctx.tools.register(subscriptionTool(runtime))
2058
+
2059
+ /**
2060
+ * Ship the operating manual as a skill rather than as a README.
2061
+ *
2062
+ * `inject` above names `skills`, so this fiber has the registry. Registration is an ordinary
2063
+ * effect: unloading the plugin removes the skill with it, and there is no file in a user
2064
+ * directory that could drift away from this code.
2065
+ *
2066
+ * The registration is attempted in a narrow try/catch because a host that predates the skill
2067
+ * registry (or a profile with the skill layer disabled) must not fail to load the proxy — the
2068
+ * proxy still works, the assistant just has to read the same facts from the tool description.
2069
+ */
2070
+ try {
2071
+ ctx.skills.register({
2072
+ name: SKILL_NAME,
2073
+ description: SKILL_DESCRIPTION,
2074
+ whenToUse: SKILL_WHEN_TO_USE,
2075
+ content: SKILL_CONTENT,
2076
+ })
2077
+ log(`skill ${SKILL_NAME} registered`)
2078
+ } catch (error) {
2079
+ log(`skill ${SKILL_NAME} not registered: ${error?.message ?? error}`)
2080
+ }
1798
2081
  }
1799
2082
 
1800
2083
  /**
@@ -1810,6 +2093,8 @@ function subscriptionTool(runtime) {
1810
2093
  'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and one or more user-imported subscriptions.',
1811
2094
  '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
2095
  'action=status reports the core, the installed policy, every subscription with its node count, the node table and live traffic.',
2096
+ 'action=restart stops and starts the core in one call, for a core that is running but no longer answers its control API.',
2097
+ '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
2098
  '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
2099
  'action=start brings routing up on the configured subscriptions; action=stop takes it down and restores direct connections.',
1815
2100
  '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 +2104,8 @@ function subscriptionTool(runtime) {
1819
2104
  properties: {
1820
2105
  action: {
1821
2106
  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.',
2107
+ enum: ['status', 'import', 'start', 'stop', 'restart', 'select', 'test', 'refresh', 'bootstrap', 'reselect', 'health'],
2108
+ 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
2109
  },
1825
2110
  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
2111
  append: { type: 'boolean', description: 'For action=import: add to the existing subscriptions instead of replacing them.' },
@@ -1884,6 +2169,16 @@ function subscriptionTool(runtime) {
1884
2169
  ].join('\n'),
1885
2170
  }
1886
2171
  }
2172
+ if (action === 'restart') {
2173
+ // One call for "the core is up but unusable". `start()` already stops first, so this
2174
+ // is not a second path through the lifecycle — it is the same path, named for the case
2175
+ // that needs it, so a caller does not have to remember to stop first.
2176
+ const report = await runtime.start()
2177
+ return {
2178
+ ...report,
2179
+ summary: `已重建内核:${report.endpoint},当前节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。`,
2180
+ }
2181
+ }
1887
2182
  if (action === 'start') {
1888
2183
  const report = await runtime.start()
1889
2184
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }