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/index.js CHANGED
@@ -20,10 +20,12 @@ import { Core, findCoreBinary, splitList } from './lib/core.js'
20
20
  import { installCore, installCoreFromFile, platformKey } from './lib/corefetch.js'
21
21
  import { installVendoredCore, vendoredFor } from './lib/vendored.js'
22
22
  import { fetchGeoDatabases, hasGeoDatabase } from './lib/geo.js'
23
- import { DEFAULT_PROBES, judgeNode, rankNodes, resolveProbes } from './lib/select.js'
23
+ import { judgeNode, resolveProbes } from './lib/select.js'
24
+ import { REAL_PROBES, gatingSpecs, judgeNodeHealth, resolveProbes as resolveRealProbes, runProbes } from './lib/realprobe.js'
25
+ import { HealthWatch, rankHealth } from './lib/watch.js'
24
26
  import { buildExcludeFilter, isBlocked, partitionNodes, validateBlocklist } from './lib/blocklist.js'
25
27
  import { readInventory, rememberNodes } from './lib/inventory.js'
26
- import { buildNodeRows, summariseRows } from './lib/health.js'
28
+ import { summariseRows } from './lib/health.js'
27
29
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
28
30
  import { Routing } from './lib/routing.js'
29
31
  import {
@@ -35,10 +37,11 @@ import {
35
37
  providerName,
36
38
  } from './lib/subscription.js'
37
39
  import { maskToken, mountRoutes } from './lib/routes.js'
40
+ import { SKILL_CONTENT, SKILL_DESCRIPTION, SKILL_NAME, SKILL_WHEN_TO_USE } from './lib/skill.js'
38
41
 
39
42
  export const name = 'clash-proxy'
40
43
 
41
- export const inject = ['tools']
44
+ export const inject = ['tools', 'skills']
42
45
 
43
46
  /**
44
47
  * Defaults for every field, so a plugin row may omit all of them.
@@ -87,10 +90,10 @@ export const CONFIG_DEFAULTS = {
87
90
  * The core removes them from its proxy table entirely, so nothing can select or route to them.
88
91
  */
89
92
  blocklist: '',
90
- /** Extra capability probes as `id=url` lines; built-ins cover gstatic/google/openai/anthropic. */
93
+ /** Extra capability probes as `id=url`, built-ins cover gstatic/google/github/git/openai/anthropic. */
91
94
  probes: '',
92
95
  /**
93
- * Probe ids a node must pass to be chosen. Empty means every probe in the set.
96
+ * Probe ids a node must pass to be chosen. Empty means every probe that gates usability.
94
97
  * This is what turns "fastest node" into "node that actually works for my services".
95
98
  */
96
99
  requiredProbes: '',
@@ -108,6 +111,53 @@ export const CONFIG_DEFAULTS = {
108
111
  probeSamples: 2,
109
112
  /** Per-probe budget in milliseconds. */
110
113
  probeTimeoutMs: 8000,
114
+ /**
115
+ * Watch the live node with real requests and switch away when it keeps failing.
116
+ *
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.
126
+ */
127
+ autoSwitch: true,
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. */
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',
151
+ /** How many candidate nodes one switch search may test, cheapest first; 0 means all. */
152
+ healthSwitchCandidates: 12,
153
+ /** Let a switch proceed even while connections are open. Off by default: it aborts work. */
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,
111
161
  }
112
162
 
113
163
  /**
@@ -153,6 +203,14 @@ async function buildConfigSchema() {
153
203
  reselectIdleGraceMs: z.number().default(20000),
154
204
  probeSamples: z.number().default(2),
155
205
  probeTimeoutMs: z.number().default(8000),
206
+ autoSwitch: z.boolean().default(true),
207
+ healthRoundSeconds: z.number().default(30),
208
+ healthStrikeLimit: z.number().default(3),
209
+ healthMaxDelayMs: z.number().default(400),
210
+ healthBaselineProbe: z.string().default('google'),
211
+ healthSwitchCandidates: z.number().default(12),
212
+ switchWhileBusy: z.boolean().default(false),
213
+ healthSurveyEvery: z.number().default(20),
156
214
  })
157
215
  } catch {
158
216
  return undefined
@@ -200,6 +258,25 @@ export function resolveConfig(raw) {
200
258
  config.reselectIdleGraceMs = clamp(config.reselectIdleGraceMs, 0, 600_000, 20_000)
201
259
  config.probeSamples = clamp(config.probeSamples, 1, 5, 2)
202
260
  config.probeTimeoutMs = clamp(config.probeTimeoutMs, 1_000, 60_000, 8_000)
261
+ config.autoSwitch = config.autoSwitch !== false && config.autoSwitch !== 'false'
262
+ config.switchWhileBusy = config.switchWhileBusy === true || config.switchWhileBusy === 'true'
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)
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'
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)
203
280
  return config
204
281
  }
205
282
 
@@ -246,8 +323,8 @@ export class Runtime {
246
323
  this.idleSince = undefined
247
324
  /** When the current node was last verified. */
248
325
  this.lastCheckAt = undefined
249
- /** Timer for the periodic re-check. */
250
- this.reselectTimer = undefined
326
+ /** Timer for the single health/selection round. */
327
+ this.healthTimer = undefined
251
328
  /** Progress/result of the optional GeoIP upgrade. */
252
329
  this.geo = undefined
253
330
  /** True while that upgrade is running. */
@@ -270,6 +347,18 @@ export class Runtime {
270
347
  this.measuredAt = 0
271
348
  this.timer = undefined
272
349
  this.watchdog = undefined
350
+ /** The probe plan in force, so a status read does not re-parse the config four times. */
351
+ this.watch = new HealthWatch({ strikeLimit: config.healthStrikeLimit ?? 3, logger: this.log })
352
+ /** Last health round: outcome, streak, and the probe detail behind it. */
353
+ this.health = undefined
354
+ /** Node name to last real-probe verdict, merged into every status read. */
355
+ this.healthRows = new Map()
356
+ /** Timer for the real-probe health round. */
357
+ this.healthTimer = undefined
358
+ /** True while a round is running, so two ticks cannot overlap. */
359
+ this.healthRunning = false
360
+ /** What the last automatic switch did, for the panel. */
361
+ this.lastSwitch = undefined
273
362
  /** Persistence hook, set by `apply` from the config editor; undefined when the profile has none. */
274
363
  this.editor = undefined
275
364
  /** Timer factory and context-bound re-arm, installed by `apply`. */
@@ -396,6 +485,17 @@ export class Runtime {
396
485
  blocklistFilter: buildExcludeFilter(this.config.blocklist),
397
486
  corePath: this.config.corePath,
398
487
  coreVersion: this.config.coreVersion,
488
+ probes: this.config.probes,
489
+ requiredProbes: this.config.requiredProbes,
490
+ autoReselect: this.config.autoReselect,
491
+ reselectMinutes: this.config.reselectMinutes,
492
+ autoSwitch: this.config.autoSwitch,
493
+ healthRoundSeconds: this.config.healthRoundSeconds,
494
+ healthStrikeLimit: this.config.healthStrikeLimit,
495
+ healthMaxDelayMs: this.config.healthMaxDelayMs,
496
+ healthSwitchCandidates: this.config.healthSwitchCandidates,
497
+ healthSurveyEvery: this.config.healthSurveyEvery,
498
+ switchWhileBusy: this.config.switchWhileBusy,
399
499
  source: 'configured',
400
500
  }
401
501
  }
@@ -469,6 +569,16 @@ export class Runtime {
469
569
  }
470
570
  }
471
571
  if (next.speedTestMinutes !== previous.speedTestMinutes) this.requestRearm()
572
+ if (
573
+ next.healthRoundSeconds !== previous.healthRoundSeconds ||
574
+ next.autoSwitch !== previous.autoSwitch ||
575
+ next.healthStrikeLimit !== previous.healthStrikeLimit ||
576
+ next.healthMaxDelayMs !== previous.healthMaxDelayMs ||
577
+ next.healthSurveyEvery !== previous.healthSurveyEvery
578
+ ) {
579
+ this.watch.strikeLimit = next.healthStrikeLimit
580
+ this.requestRearm()
581
+ }
472
582
  return { config: this.publicConfig(), warnings }
473
583
  }
474
584
 
@@ -564,96 +674,331 @@ export class Runtime {
564
674
  }
565
675
 
566
676
  /**
567
- * Re-check the current node's capabilities and switch only when it is no longer usable.
677
+ * The probe plan in force, resolved from configuration.
568
678
  *
569
- * This is the automatic half of selection. The startup choice already proves a node can
570
- * reach every required service, but a node degrades: a service starts blocking the range, a
571
- * provider rotates the server behind a name. Re-running the full matrix on every tick would
572
- * be wasteful and would keep tearing down connections, so the current node is verified first
573
- * and the expensive search only runs when that verification fails.
679
+ * @returns `{ probes, gating, specs }`, where `specs` are the ones that gate usability.
680
+ */
681
+ probePlan() {
682
+ const resolved = resolveRealProbes(this.config.probes, this.config.requiredProbes)
683
+ return { ...resolved, specs: gatingSpecs(resolved.probes, resolved.gating) }
684
+ }
685
+
686
+ /**
687
+ * Run one real-probe round against the node that is currently carrying traffic.
688
+ *
689
+ * This is the piece the plugin was missing. Its old check asked mihomo whether a URL answered
690
+ * at all, and a GitHub rate-limit `403` counts as "answered" — measured, the panel reported
691
+ * six unusable nodes as `usable` while five of them had `x-ratelimit-remaining: 0` and two
692
+ * could not complete a git fetch at all. So the round sends the real requests through the
693
+ * probe listener, reads the real status and quota, and records a strike only when a probe
694
+ * that gates usability failed.
574
695
  *
575
- * @param options - `force` bypasses the idle gate.
576
- * @returns what happened and why.
696
+ * A usable round resets the streak, because a node that recovers must not be switched away
697
+ * from for old failures.
698
+ *
699
+ * @param options - `force` ignores the enable flag; `node` overrides the node under test.
700
+ * @returns the round report.
577
701
  */
578
- async autoReselect(options = {}) {
579
- const gate = await this.canReselectNow(options)
580
- if (!gate.ok) return { state: 'skipped', ...gate }
702
+ async healthRound(options = {}) {
703
+ if (this.core === undefined || this.core.running !== true) return { state: 'core-not-running' }
704
+ if (this.starting === true) return { state: 'starting' }
705
+ if (this.config.autoSwitch === false && options.force !== true) return { state: 'disabled' }
706
+ if (this.healthRunning === true) return { state: 'in-flight' }
707
+ this.healthRunning = true
708
+ try {
709
+ const plan = this.probePlan()
710
+ if (plan.specs.length === 0) return { state: 'no-probes' }
711
+ const group = await this.core.group()
712
+ const current = String(options.node ?? group.now ?? '').trim()
713
+ if (current === '' || current === 'DIRECT') {
714
+ return { state: 'no-node', required: plan.gating }
715
+ }
581
716
 
582
- const plan = resolveProbes(this.config.probes, this.config.requiredProbes)
583
- const group = await this.core.group()
584
- const current = group.now
585
- if (current === undefined || current === 'DIRECT') {
586
- // Nothing real is selected; a full search is the only way forward and it disturbs nobody.
587
- const result = await this.core.autoSelect(this.preferredNode, {
588
- probes: plan.probes,
589
- required: plan.required,
590
- budgetMs: this.config.selectBudgetMs,
717
+ const { results, verdict } = await this.core.checkNodeReal(current, plan.specs, plan.gating, {
718
+ timeoutMs: this.config.probeTimeoutMs ?? 8000,
591
719
  })
592
- this.lastMatrix = result.matrix
593
- if (result.chosen !== undefined) this.rememberNode(result.chosen)
594
- return { state: result.chosen === undefined ? 'no-node' : 'selected', chosen: result.chosen, required: plan.required }
720
+ if (Object.keys(results).length === 0) {
721
+ // The probe listener is not answering, which says nothing about the node. Reporting a
722
+ // strike here would switch away from a healthy node because the instrument broke.
723
+ return { state: 'probe-unavailable', node: current }
724
+ }
725
+
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() })
770
+ this.lastMatrix = [{ name: current, results }]
771
+ this.lastCheckAt = Date.now()
772
+ const counted = this.watch.record(current, judged, { probes: results })
773
+ // `degraded` is a usable node that is short on quota. It is reported, never acted on:
774
+ // switching away from it would land on an equally short node and lose the connection.
775
+ const state = judged.usable ? (judged.degraded === true ? 'degraded' : 'ok') : judged.slow === true ? 'slow' : 'bad'
776
+ const report = {
777
+ state,
778
+ node: current,
779
+ required: plan.gating,
780
+ results,
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,
792
+ strikes: counted.strikes,
793
+ strikeLimit: counted.limit,
794
+ giveUp: counted.giveUp,
795
+ at: new Date().toISOString(),
796
+ }
797
+ this.health = report
798
+ if (judged.usable) {
799
+ this.log(`round ok on ${current} (${latency ?? '?'} ms, ${Object.keys(results).join('/')})`)
800
+ void this.runSurveyTick()
801
+ return report
802
+ }
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
+ }
811
+ if (!counted.giveUp) return report
812
+ return await this.switchAfterStrikes(report, plan, options)
813
+ } finally {
814
+ this.healthRunning = false
815
+ }
816
+ }
817
+
818
+ /**
819
+ * Switch away from a node whose streak reached the limit.
820
+ *
821
+ * The search is bounded by `healthSwitchCandidates` and ordered by measured latency, because
822
+ * a 54-node subscription cannot be probed for real inside one round without spending minutes
823
+ * on nodes that answered worst last time. The node that just failed is excluded from its own
824
+ * replacement, which is the difference between "we tried" and "we picked it again".
825
+ *
826
+ * Busy-line handling: a switch tears down in-flight connections. When the line is carrying
827
+ * work the switch waits for the next round unless `switchWhileBusy` is on — a broken node that
828
+ * stays selected for one more round is cheaper than aborting a download mid-flight.
829
+ *
830
+ * @param report - the failing round.
831
+ * @param plan - the probe plan.
832
+ * @param options - `force` bypasses the busy gate.
833
+ * @returns the round report with the switch result attached.
834
+ */
835
+ async switchAfterStrikes(report, plan, options = {}) {
836
+ const traffic = await this.core.connections().catch(() => undefined)
837
+ const limit = Number(this.config.reselectIdleConnections ?? 2)
838
+ // `force` means "run this round now", not "ignore in-flight work": the two were conflated
839
+ // in the first draft and an explicit check aborted a download. Only `bypassBusy` (or the
840
+ // configuration switch) may interrupt traffic.
841
+ const bypassBusy = options.bypassBusy === true || this.config.switchWhileBusy === true
842
+ if (!bypassBusy && traffic !== undefined && traffic.count > limit) {
843
+ this.log(`switch deferred: ${traffic.count} connections in flight (limit ${limit})`)
844
+ return { ...report, state: 'switch-deferred', connections: traffic.count }
595
845
  }
596
846
 
597
- // Cheap check first: is the node already selected still good for every required service?
598
- const results = await this.core.capabilities(current, plan.probes, {
847
+ const group = await this.core.group()
848
+ const candidates = group.all.filter((name) => name !== 'DIRECT' && name !== 'REJECT' && name !== report.node)
849
+ const cap = Number(this.config.healthSwitchCandidates ?? 12)
850
+ const ordered = cap > 0 ? candidates.slice(0, cap) : candidates
851
+ const startedAt = Date.now()
852
+ const matrix = await this.core.realMatrix({
853
+ nodes: ordered,
854
+ specs: plan.specs,
855
+ gating: plan.gating,
856
+ delays: this.measured,
857
+ budgetMs: Math.min(Number(this.config.selectBudgetMs ?? 90_000), 120_000),
599
858
  timeoutMs: this.config.probeTimeoutMs ?? 8000,
600
- samples: this.config.probeSamples ?? 2,
601
859
  })
602
- const verdict = judgeNode(results, plan.required)
603
- this.lastMatrix = [{ name: current, results }]
604
- this.lastCheckAt = Date.now()
605
- if (verdict.usable) {
606
- this.log('node ' + current + ' still reaches ' + plan.required.join('/'))
607
- return { state: 'kept', node: current, required: plan.required, results }
860
+ const best = matrix.best
861
+ this.healthRows = new Map(
862
+ matrix.rows.map((row) => [row.name, { results: row.results, verdict: row.verdict, at: Date.now() }]),
863
+ )
864
+ this.lastMatrix = matrix.rows.map((row) => ({ name: row.name, results: row.results }))
865
+ // `usable` here means "no hard failure". A degraded node (quota spent, tunnel fine) is a
866
+ // legitimate replacement: with every exit address out of GitHub quota, insisting on a
867
+ // quota-clean node leaves the plugin on the node it just gave up on.
868
+ if (best === undefined || best.verdict?.usable !== true) {
869
+ this.lastSwitch = {
870
+ state: 'no-alternative',
871
+ from: report.node,
872
+ at: new Date().toISOString(),
873
+ tested: matrix.tested,
874
+ elapsedMs: Date.now() - startedAt,
875
+ }
876
+ this.log(`no usable alternative to ${report.node} out of ${matrix.tested} tested`)
877
+ return { ...report, state: 'no-alternative', tested: matrix.tested }
608
878
  }
609
879
 
610
- this.log('node ' + current + ' lost ' + (verdict.failed.join(',') || verdict.missing.join(',')) + '; searching again')
611
- const result = await this.core.autoSelect('', {
612
- probes: plan.probes,
613
- required: plan.required,
614
- budgetMs: this.config.selectBudgetMs,
615
- samples: this.config.probeSamples ?? 2,
616
- })
617
- this.lastMatrix = result.matrix
618
- if (result.chosen === undefined) {
619
- return { state: 'no-alternative', lostNode: current, failed: verdict.failed, required: plan.required }
880
+ await this.core.select(best.name)
881
+ this.rememberNode(best.name)
882
+ this.watch.reset(best.name)
883
+ this.lastSwitch = {
884
+ state: 'switched',
885
+ from: report.node,
886
+ to: best.name,
887
+ at: new Date().toISOString(),
888
+ failed: report.verdict?.failed ?? [],
889
+ limited: report.verdict?.limited ?? [],
890
+ degraded: best.verdict?.degraded === true,
891
+ tested: matrix.tested,
892
+ elapsedMs: Date.now() - startedAt,
893
+ }
894
+ this.log(`switched ${report.node} -> ${best.name} after ${report.strikes} bad rounds`)
895
+ return { ...report, state: 'switched', from: report.node, to: best.name, switchedTo: best.name, tested: matrix.tested }
896
+ }
897
+
898
+ /**
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 }
620
912
  }
621
- if (result.chosen === current) {
622
- // The search re-picked the same node, which contradicts the probe; report rather than loop.
623
- return { state: 'unchanged', node: current, failed: verdict.failed }
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 }
624
915
  }
625
- this.rememberNode(result.chosen)
626
- this.log('switched ' + current + ' -> ' + result.chosen)
627
- return { state: 'switched', from: current, to: result.chosen, failed: verdict.failed, required: plan.required }
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
628
920
  }
629
921
 
630
922
  /**
631
- * Arm the periodic capability re-check.
923
+ * Arm the single health/selection round.
632
924
  *
633
- * Same rule as the other cycles: the interval must be created in the plugin context, so this
634
- * is only ever called from a callback the plugin registered itself. A tick that finds the
635
- * line busy returns immediately, which is why the period can be short without ever
636
- * interrupting work.
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.
637
932
  *
638
933
  * @param schedule - timer factory from the plugin context.
639
934
  */
640
- scheduleReselect(schedule) {
641
- if (this.reselectTimer !== undefined) this.reselectTimer()
642
- this.reselectTimer = undefined
643
- const minutes = this.config.reselectMinutes
644
- if (this.config.autoReselect === false || minutes <= 0 || typeof schedule !== 'function') return
645
- this.reselectTimer = schedule(() => {
646
- void this.autoReselect().catch((error) => {
647
- this.log('capability re-check failed: ' + String(error?.message ?? error))
648
- })
649
- }, minutes * 60_000)
935
+ scheduleHealthRound(schedule) {
936
+ if (this.healthTimer !== undefined) this.healthTimer()
937
+ this.healthTimer = undefined
938
+ const seconds = Number(this.config.healthRoundSeconds ?? 30)
939
+ if (this.config.autoSwitch === false || seconds <= 0 || typeof schedule !== 'function') return
940
+ this.healthTimer = schedule(() => {
941
+ void this.healthRound().catch((error) => this.log(`health round failed: ${error?.message ?? error}`))
942
+ }, seconds * 1000)
650
943
  }
651
944
 
652
- /** Stop the re-check. Safe to call when none is running. */
653
- stopReselect() {
654
- if (this.reselectTimer === undefined) return
655
- this.reselectTimer()
656
- this.reselectTimer = undefined
945
+ /** Stop the health round. Safe to call when none is running. */
946
+ stopHealthRound() {
947
+ if (this.healthTimer === undefined) return
948
+ this.healthTimer()
949
+ this.healthTimer = undefined
950
+ }
951
+
952
+ /**
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.
959
+ *
960
+ * Bounded by `healthSwitchCandidates` and skipped while a switch is in progress.
961
+ *
962
+ * @returns the survey result, or `{ state: 'skipped' }` when it did not run.
963
+ */
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' }
972
+ const plan = this.probePlan()
973
+ const group = await this.core.group().catch(() => undefined)
974
+ if (group === undefined) return { state: 'no-group' }
975
+ const current = group.now
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,
985
+ specs: plan.specs,
986
+ gating: plan.gating,
987
+ delays: this.measured,
988
+ budgetMs: Math.min(Number(this.config.selectBudgetMs ?? 90_000), 60_000),
989
+ timeoutMs: this.config.probeTimeoutMs ?? 8000,
990
+ })
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
1001
+ }
657
1002
  }
658
1003
 
659
1004
  /**
@@ -1114,29 +1459,35 @@ export class Runtime {
1114
1459
  const preferred = String(options.node ?? this.preferredNode ?? '').trim()
1115
1460
  // A fresh group starts on DIRECT, which would route foreign traffic straight out.
1116
1461
  // Selecting a real node is part of bringing routing up, not an optional extra.
1117
- // Selection is capability-based: a node must reach every required service, not merely
1118
- // answer a latency check. The matrix is kept so the panel can show why a node lost.
1119
- const plan = resolveProbes(this.config.probes, this.config.requiredProbes)
1462
+ // Selection is capability-based: a node must pass the real probes, not merely answer a
1463
+ // latency check. The verdicts are kept so the panel can show why a node lost.
1464
+ const plan = this.probePlan()
1120
1465
  const selection = group.all.some((entry) => entry !== 'DIRECT')
1121
1466
  ? await this.core
1122
1467
  .autoSelect(preferred, {
1123
1468
  probes: plan.probes,
1124
- required: plan.required,
1469
+ required: plan.gating,
1470
+ specs: plan.specs,
1125
1471
  budgetMs: this.config.selectBudgetMs,
1472
+ delays: this.measured,
1126
1473
  })
1127
1474
  .catch((error) => {
1128
1475
  this.log('capability selection failed: ' + String(error?.message ?? error))
1129
- return { chosen: undefined, matrix: [] }
1476
+ return { chosen: undefined, rows: [], tested: 0 }
1130
1477
  })
1131
- : { chosen: undefined, matrix: [] }
1478
+ : { chosen: undefined, rows: [], tested: 0 }
1132
1479
  const selected = selection.chosen
1133
- this.lastMatrix = selection.matrix
1134
- const ranked = rankNodes(selection.matrix, plan.required)
1135
- if (selected === undefined && selection.matrix.length > 0) {
1136
- this.log('no node could reach every required probe: ' + plan.required.join(', '))
1480
+ if (Array.isArray(selection.rows)) {
1481
+ this.lastMatrix = selection.rows.map((row) => ({ name: row.name, results: row.results }))
1482
+ this.healthRows = new Map(selection.rows.map((row) => [row.name, { results: row.results, verdict: row.verdict, at: Date.now() }]))
1483
+ }
1484
+ const probeRows = Array.isArray(selection.rows) ? selection.rows : []
1485
+ if (selected === undefined && probeRows.length > 0) {
1486
+ this.log('no node passed the real probes: ' + plan.gating.join(', '))
1137
1487
  } else if (selected !== undefined) {
1138
- this.log('selected ' + selected + ' (' + plan.required.join('/') + ' all reachable)')
1488
+ this.log('selected ' + selected + ' (' + plan.gating.join('/') + ' all passed real probes)')
1139
1489
  }
1490
+ const ranked = rankHealth(probeRows)
1140
1491
  void ranked
1141
1492
  this.lastError = undefined
1142
1493
  this.degraded = undefined
@@ -1241,9 +1592,48 @@ export class Runtime {
1241
1592
  if (this.core !== undefined) await this.core.stop()
1242
1593
  }
1243
1594
 
1595
+ /**
1596
+ * One panel row per node: latency, verdict, and the probe that produced it.
1597
+ *
1598
+ * `usable` keeps its three states (`ok` / `blocked` / `unknown`) so the panel markup does not
1599
+ * change shape; `limited` is carried beside it because "out of GitHub quota" is neither a
1600
+ * working node nor a dead one, and collapsing it into either is what produced the wrong label
1601
+ * in the first place.
1602
+ *
1603
+ * @param names - node names in table order.
1604
+ * @returns one row per name.
1605
+ */
1606
+ buildRealRows(names) {
1607
+ const list = Array.isArray(names) ? names : []
1608
+ return list.map((name) => {
1609
+ const delay = this.measured.has(name) ? this.measured.get(name) : undefined
1610
+ const entry = this.healthRows.get(name)
1611
+ if (entry === undefined) {
1612
+ return { name, delay, usable: 'unknown', limited: [], failed: [], blocked: [], state: 'unknown', probes: {} }
1613
+ }
1614
+ const verdict = entry.verdict ?? {}
1615
+ // `limited` is "usable, but short on quota" — selectable, and ranked after a quota-clean
1616
+ // node. `blocked` is the only state that means "cannot carry the request".
1617
+ const usable =
1618
+ verdict.usable === true ? (verdict.degraded === true ? 'limited' : 'ok') : 'blocked'
1619
+ return {
1620
+ name,
1621
+ delay,
1622
+ usable,
1623
+ selectable: verdict.usable === true,
1624
+ limited: verdict.limited ?? [],
1625
+ failed: verdict.failed ?? [],
1626
+ blocked: verdict.blocked ?? [],
1627
+ state: usable,
1628
+ total: verdict.total,
1629
+ probes: entry.results ?? {},
1630
+ at: entry.at === undefined ? undefined : new Date(entry.at).toISOString(),
1631
+ }
1632
+ })
1633
+ }
1634
+
1244
1635
  /** The status the model and the panel both read. */
1245
- async status() {
1246
- const running = this.core?.running === true
1636
+ async status() { const running = this.core?.running === true
1247
1637
  const group = running ? await this.core.group().catch(() => ({ all: [], now: undefined })) : { all: [], now: undefined }
1248
1638
  // The core hides blocked nodes, so it never reports them. Keep every name this runtime has
1249
1639
  // seen, otherwise the panel has no way to show what the blocklist is currently removing.
@@ -1318,29 +1708,43 @@ export class Runtime {
1318
1708
  },
1319
1709
  /** Per-node probe results from the last selection, and which services gate it. */
1320
1710
  /**
1321
- * One row per live node with its latency and usability together. The panel draws this and
1322
- * nothing else for the node list, so latency and capability cannot drift apart on screen.
1711
+ * One row per live node with latency, usability and *why* — the third field is what the
1712
+ * old rows lacked, and its absence is why "usable" appeared next to a rate-limited node.
1323
1713
  */
1324
1714
  nodeRows: (() => {
1325
1715
  const live = group.all.filter((name) => name !== 'DIRECT')
1326
- const rows = buildNodeRows(live, Object.fromEntries(this.measured), {
1327
- required: resolveProbes(this.config.probes, this.config.requiredProbes).required,
1328
- nodes: this.lastMatrix,
1329
- })
1716
+ const rows = this.buildRealRows(live)
1330
1717
  return { rows, summary: summariseRows(rows) }
1331
1718
  })(),
1332
1719
  capability: {
1333
- required: resolveProbes(this.config.probes, this.config.requiredProbes).required,
1334
- probes: resolveProbes(this.config.probes, this.config.requiredProbes).probes.map((probe) => ({ id: probe.id, label: probe.label })),
1335
- nodes: this.lastMatrix.map((row) => {
1336
- const verdict = rankNodes([row], resolveProbes(this.config.probes, this.config.requiredProbes).required).usable[0]
1337
- return {
1338
- name: row.name,
1339
- results: row.results,
1340
- usable: verdict !== undefined,
1341
- failed: Object.entries(row.results).filter(([, value]) => value === null).map(([id]) => id),
1342
- }
1343
- }),
1720
+ required: this.probePlan().gating,
1721
+ probes: this.probePlan().probes.map((probe) => ({ id: probe.id, label: probe.label, gating: probe.gating === true })),
1722
+ nodes: [...this.healthRows.entries()].map(([name, entry]) => ({
1723
+ name,
1724
+ results: entry.results,
1725
+ usable: entry.verdict?.usable === true,
1726
+ failed: entry.verdict?.failed ?? [],
1727
+ limited: entry.verdict?.limited ?? [],
1728
+ blocked: entry.verdict?.blocked ?? [],
1729
+ })),
1730
+ },
1731
+ /**
1732
+ * The health watch: whether the round is armed, how many consecutive failures the live
1733
+ * node has, and what the last automatic switch did. This is the answer to "it says the
1734
+ * node is limited, so why has it not switched yet".
1735
+ */
1736
+ health: {
1737
+ enabled: this.config.autoSwitch !== false && this.config.healthRoundSeconds > 0,
1738
+ everySeconds: this.config.healthRoundSeconds,
1739
+ strikeLimit: this.watch.strikeLimit,
1740
+ maxDelayMs: this.config.healthMaxDelayMs,
1741
+ surveyEvery: this.config.healthSurveyEvery,
1742
+ survey: this.lastSurvey ?? null,
1743
+ lastRound: this.health ?? null,
1744
+ inFlight: this.healthRunning === true,
1745
+ lastSwitch: this.lastSwitch ?? null,
1746
+ rows: this.watch.rows(),
1747
+ probePort: this.core?.probePort,
1344
1748
  },
1345
1749
  /** Whether the core uses an embedded CIDR rule set for the domestic bypass. */
1346
1750
  cnRuleSet: this.core?.cnRuleSet === undefined
@@ -1388,7 +1792,7 @@ export async function apply(ctx, rawConfig) {
1388
1792
  ctx.effect(() => () => {
1389
1793
  runtime.stopTimer()
1390
1794
  runtime.stopWatchdog()
1391
- runtime.stopReselect()
1795
+ runtime.stopHealthRound()
1392
1796
  void runtime.stop()
1393
1797
  })
1394
1798
 
@@ -1421,18 +1825,18 @@ export async function apply(ctx, rawConfig) {
1421
1825
  runtime.rearm = () => {
1422
1826
  runtime.scheduleSpeedTest(schedule)
1423
1827
  runtime.scheduleWatchdog(schedule)
1424
- runtime.scheduleReselect(schedule)
1828
+ runtime.scheduleHealthRound(schedule)
1425
1829
  }
1426
1830
  runtime.scheduleSpeedTest(schedule)
1427
1831
  runtime.scheduleWatchdog(schedule)
1428
- runtime.scheduleReselect(schedule)
1832
+ runtime.scheduleHealthRound(schedule)
1429
1833
  return () => {
1430
1834
  runtime.rearm = undefined
1431
1835
  runtime.stopTimer()
1432
1836
  runtime.stopWatchdog()
1433
- runtime.stopReselect()
1837
+ runtime.stopHealthRound()
1434
1838
  }
1435
- }, 'clash-proxy: speed test cycle and watchdog')
1839
+ }, 'clash-proxy: health round, speed test cycle and watchdog')
1436
1840
  })
1437
1841
 
1438
1842
  if (runtime.installRoot === undefined) {
@@ -1477,6 +1881,29 @@ export async function apply(ctx, rawConfig) {
1477
1881
  })
1478
1882
 
1479
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
+ }
1480
1907
  }
1481
1908
 
1482
1909
  /**
@@ -1492,6 +1919,8 @@ function subscriptionTool(runtime) {
1492
1919
  'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and one or more user-imported subscriptions.',
1493
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.',
1494
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.',
1495
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.',
1496
1925
  'action=start brings routing up on the configured subscriptions; action=stop takes it down and restores direct connections.',
1497
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.',
@@ -1501,8 +1930,8 @@ function subscriptionTool(runtime) {
1501
1930
  properties: {
1502
1931
  action: {
1503
1932
  type: 'string',
1504
- enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh', 'bootstrap', 'reselect'],
1505
- 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.',
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.',
1506
1935
  },
1507
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.' },
1508
1937
  append: { type: 'boolean', description: 'For action=import: add to the existing subscriptions instead of replacing them.' },
@@ -1566,6 +1995,16 @@ function subscriptionTool(runtime) {
1566
1995
  ].join('\n'),
1567
1996
  }
1568
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
+ }
1569
2008
  if (action === 'start') {
1570
2009
  const report = await runtime.start()
1571
2010
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
@@ -1583,6 +2022,40 @@ function subscriptionTool(runtime) {
1583
2022
  : '没有可用节点:' + (result.required ?? []).join(', ') + ' 无法全部访问。',
1584
2023
  }
1585
2024
  }
2025
+ if (action === 'health') {
2026
+ const report = await runtime.healthRound({ force: true })
2027
+ const describeProbe = (row) => {
2028
+ if (row === undefined) return '无响应'
2029
+ if (row.ok === true) return `${row.ms} ms`
2030
+ if (row.state === 'limited') {
2031
+ return row.reason === 'rate-limited-in-body' || row.reason === 'status-403'
2032
+ ? `限流(HTTP ${row.status})`
2033
+ : row.remaining !== undefined
2034
+ ? `配额耗尽(剩余 ${row.remaining}${row.resetAt === undefined ? '' : `,${row.resetAt} 重置`})`
2035
+ : `受限(${row.reason})`
2036
+ }
2037
+ return `不通(${row.reason})`
2038
+ }
2039
+ const lines = [
2040
+ report.state === 'ok'
2041
+ ? `节点「${report.node}」全部必需探测通过(连续失败 ${report.strikes}/${report.strikeLimit})。`
2042
+ : report.state === 'switched'
2043
+ ? `节点「${report.from}」连续 ${report.strikes} 轮不可用,已自动切到「${report.to}」。`
2044
+ : report.state === 'no-alternative'
2045
+ ? `节点「${report.node}」连续 ${report.strikes} 轮不可用,但没有其他节点通过探测(已测 ${report.tested} 个)。`
2046
+ : report.state === 'switch-deferred'
2047
+ ? `节点「${report.node}」已连续 ${report.strikes} 轮不可用,但有 ${report.connections} 条连接在进行,本轮不切换。`
2048
+ : report.state === 'bad'
2049
+ ? `节点「${report.node}」本轮不可用(连续 ${report.strikes}/${report.strikeLimit})。`
2050
+ : `本轮未执行:${report.state}`,
2051
+ ]
2052
+ const probes = report.results ?? {}
2053
+ if (Object.keys(probes).length > 0) {
2054
+ lines.push('探测明细:')
2055
+ for (const [id, row] of Object.entries(probes)) lines.push(` ${row.label ?? id}:${describeProbe(row)}`)
2056
+ }
2057
+ return { ...report, summary: lines.join('\n') }
2058
+ }
1586
2059
  if (action === 'test') {
1587
2060
  const target = String(args?.node ?? '').trim()
1588
2061
  if (target !== '') {