dsh-clash-subscription 0.2.3 → 0.4.2

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
@@ -1,21 +1,35 @@
1
1
  /**
2
2
  * Host half of the Clash subscription proxy bundle.
3
3
  *
4
- * The plugin owns a private mihomo core fed by a subscription the user imports, and
5
- * points the Harness' existing process-wide outbound policy at that core. Nothing
6
- * else changes: loopback and LAN stay direct, Chinese destinations stay direct, and
7
- * only traffic that would otherwise be blocked goes through a subscription node —
4
+ * The plugin owns a private mihomo core fed by one or more subscriptions the user
5
+ * imports, and points the Harness' existing process-wide outbound policy at that core.
6
+ * Nothing else changes: loopback and LAN stay direct, Chinese destinations stay direct,
7
+ * and only traffic that would otherwise be blocked goes through a subscription node —
8
8
  * with no Clash Verge desktop app, system proxy, or per-command environment variable.
9
9
  *
10
+ * Several subscriptions may be configured at once. Each becomes its own core provider
11
+ * and contributes its nodes to the same exit group, so adding a second subscription
12
+ * extends the node table instead of replacing the first.
13
+ *
10
14
  * @module dsh-clash-proxy
11
15
  */
12
16
  import { mkdirSync } from 'node:fs'
13
17
  import { homedir } from 'node:os'
14
18
  import { join } from 'node:path'
15
19
  import { Core, findCoreBinary, splitList } from './lib/core.js'
20
+ import { installCore, installCoreFromFile, platformKey } from './lib/corefetch.js'
21
+ import { installVendoredCore, vendoredFor } from './lib/vendored.js'
22
+ import { fetchGeoDatabases, hasGeoDatabase } from './lib/geo.js'
16
23
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
17
24
  import { Routing } from './lib/routing.js'
18
- import { normalizeSubscriptionUrl, probeSubscription } from './lib/subscription.js'
25
+ import {
26
+ displayName,
27
+ effectiveSubscriptionText,
28
+ nodePrefix,
29
+ parseSubscriptions,
30
+ probeSubscriptions,
31
+ providerName,
32
+ } from './lib/subscription.js'
19
33
  import { maskToken, mountRoutes } from './lib/routes.js'
20
34
 
21
35
  export const name = 'clash-proxy'
@@ -34,6 +48,9 @@ export const inject = ['tools']
34
48
  * code paths that must not await a module load.
35
49
  */
36
50
  export const CONFIG_DEFAULTS = {
51
+ /** One subscription per line, optionally prefixed with a display name. */
52
+ subscriptionUrls: '',
53
+ /** Single-URL field from 0.2; read for migration, never written back. */
37
54
  subscriptionUrl: '',
38
55
  node: '',
39
56
  corePath: '',
@@ -47,6 +64,14 @@ export const CONFIG_DEFAULTS = {
47
64
  speedTestMinutes: 30,
48
65
  /** How many nodes one cycle measures, lowest-index first in the group's order. */
49
66
  speedTestCount: 8,
67
+ /** How often the core is checked for liveness, in minutes; 0 disables the watchdog. */
68
+ healthCheckMinutes: 1,
69
+ /** Download a private core automatically when the machine has none. */
70
+ autoFetchCore: false,
71
+ /** Pin the core version to a build whose digest this plugin ships; empty means current. */
72
+ coreVersion: '',
73
+ /** Fetch GeoIP databases after routing works; they are an upgrade, not a requirement. */
74
+ autoFetchGeo: true,
50
75
  }
51
76
 
52
77
  /**
@@ -63,6 +88,7 @@ async function buildConfigSchema() {
63
88
  const z = loaded.default ?? loaded
64
89
  if (typeof z?.object !== 'function') return undefined
65
90
  return z.object({
91
+ subscriptionUrls: z.string().default(''),
66
92
  subscriptionUrl: z.string().default(''),
67
93
  node: z.string().default(''),
68
94
  corePath: z.string().default(''),
@@ -74,6 +100,10 @@ async function buildConfigSchema() {
74
100
  dataDir: z.string().default(''),
75
101
  speedTestMinutes: z.number().default(30),
76
102
  speedTestCount: z.number().default(8),
103
+ healthCheckMinutes: z.number().default(1),
104
+ autoFetchCore: z.boolean().default(false),
105
+ coreVersion: z.string().default(''),
106
+ autoFetchGeo: z.boolean().default(true),
77
107
  })
78
108
  } catch {
79
109
  return undefined
@@ -95,9 +125,15 @@ export function resolveConfig(raw) {
95
125
  const mode = String(config.mode ?? 'rule').trim().toLowerCase()
96
126
  config.mode = mode === 'global' ? 'global' : 'rule'
97
127
  config.autoStart = config.autoStart !== false && config.autoStart !== 'false'
98
- for (const field of ['subscriptionUrl', 'node', 'corePath', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir']) {
128
+ config.autoFetchCore = config.autoFetchCore === true || config.autoFetchCore === 'true'
129
+ config.autoFetchGeo = config.autoFetchGeo !== false && config.autoFetchGeo !== 'false'
130
+ for (const field of ['subscriptionUrls', 'subscriptionUrl', 'node', 'corePath', 'coreVersion', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir']) {
99
131
  config[field] = String(config[field] ?? '').trim()
100
132
  }
133
+ // A profile written by 0.2 carries only `subscriptionUrl`. Normalizing it into the
134
+ // list here means every downstream reader sees one shape, and the panel shows the
135
+ // user's existing subscription in the list editor on first open.
136
+ if (config.subscriptionUrls === '' && config.subscriptionUrl !== '') config.subscriptionUrls = config.subscriptionUrl
101
137
  const clamp = (value, min, max, fallback) => {
102
138
  const numeric = Number(value)
103
139
  if (!Number.isFinite(numeric)) return fallback
@@ -105,6 +141,7 @@ export function resolveConfig(raw) {
105
141
  }
106
142
  config.speedTestMinutes = clamp(config.speedTestMinutes, 0, 1440, 30)
107
143
  config.speedTestCount = clamp(config.speedTestCount, 1, 40, 8)
144
+ config.healthCheckMinutes = clamp(config.healthCheckMinutes, 0, 60, 1)
108
145
  return config
109
146
  }
110
147
 
@@ -134,14 +171,35 @@ export class Runtime {
134
171
  /** Resolved once: the answer cannot change mid-process, and a stable value keeps
135
172
  * `blocker` and `ensurePolicyModule` from disagreeing. */
136
173
  this.installRoot = locateInstallRoot(process.argv)
137
- this.binary = findCoreBinary(config.corePath)
174
+ this.binary = findCoreBinary(config.corePath, this.dataDir)
138
175
  this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger })
139
176
  this.routing = undefined
140
177
  this.lastError = undefined
141
178
  this.lastProbe = undefined
179
+ /** Result of the last core download, for the panel and the tool. */
180
+ this.bootstrap = undefined
181
+ /** True while a download is in flight, so two clicks cannot race one archive. */
182
+ this.bootstrapping = false
183
+ /** Progress/result of the optional GeoIP upgrade. */
184
+ this.geo = undefined
185
+ /** True while that upgrade is running. */
186
+ this.geoUpgrading = false
187
+ /** True while `start()` is running, so the watchdog never races a deliberate restart. */
188
+ this.starting = false
189
+ /**
190
+ * Whether this activation is supposed to own a running core.
191
+ *
192
+ * The watchdog gates on this rather than on `autoStart`: `autoStart` only says who
193
+ * started the core (the Harness, or the user pressing Start), and a core started by
194
+ * hand deserves the same recovery as one started at boot.
195
+ */
196
+ this.engaged = false
197
+ /** Set when the watchdog gave up and left the process direct. */
198
+ this.degraded = undefined
142
199
  this.measured = new Map()
143
200
  this.measuredAt = 0
144
201
  this.timer = undefined
202
+ this.watchdog = undefined
145
203
  /** Persistence hook, set by `apply` from the config editor; undefined when the profile has none. */
146
204
  this.editor = undefined
147
205
  /** Timer factory and context-bound re-arm, installed by `apply`. */
@@ -149,6 +207,17 @@ export class Runtime {
149
207
  this.rearm = undefined
150
208
  }
151
209
 
210
+ /**
211
+ * The parsed subscription list.
212
+ *
213
+ * Recomputed on read so a config edit takes effect without a restart of the plugin.
214
+ *
215
+ * @returns `{ entries, errors }`.
216
+ */
217
+ get subscriptions() {
218
+ return parseSubscriptions(effectiveSubscriptionText(this.config))
219
+ }
220
+
152
221
  /**
153
222
  * Measure node latency, merging into the results already known.
154
223
  *
@@ -209,24 +278,54 @@ export class Runtime {
209
278
  this.config.node = name
210
279
  }
211
280
 
212
- /** The configuration a page may read, with the subscription token masked. */
281
+ /** The configuration a page may read, with the subscription tokens masked. */
213
282
  publicConfig() {
283
+ const parsed = this.subscriptions
214
284
  return {
215
- subscriptionUrl: this.config.subscriptionUrl,
216
- effectiveSubscriptionUrl: maskToken(this.subscriptionUrl),
285
+ subscriptionUrls: effectiveSubscriptionText(this.config),
286
+ /** Masked one-per-line echo, for a read-only display. */
287
+ effectiveSubscriptionUrls: this.maskList(parsed.entries),
288
+ /** Kept for a 0.2 client: the first subscription, masked. */
289
+ subscriptionUrl: parsed.entries[0]?.url ?? '',
290
+ effectiveSubscriptionUrl: maskToken(parsed.entries[0]?.url ?? ''),
291
+ subscriptions: parsed.entries.map((entry) => ({
292
+ name: displayName(entry),
293
+ provider: providerName(entry),
294
+ url: maskToken(entry.url),
295
+ index: entry.index,
296
+ })),
297
+ subscriptionErrors: parsed.errors,
217
298
  node: this.config.node,
218
299
  mode: this.config.mode,
219
300
  autoStart: this.config.autoStart,
220
301
  speedTestMinutes: this.config.speedTestMinutes,
221
302
  speedTestCount: this.config.speedTestCount,
303
+ healthCheckMinutes: this.config.healthCheckMinutes,
222
304
  directDomains: this.config.directDomains,
223
305
  proxyDomains: this.config.proxyDomains,
224
306
  dnsServers: this.config.dnsServers,
225
307
  corePath: this.config.corePath,
308
+ coreVersion: this.config.coreVersion,
226
309
  source: 'configured',
227
310
  }
228
311
  }
229
312
 
313
+ /**
314
+ * Mask every token in a parsed list, preserving the names and line order.
315
+ *
316
+ * @param entries - parsed subscription entries.
317
+ * @returns one masked `name url` line per entry.
318
+ */
319
+ maskList(entries) {
320
+ return (Array.isArray(entries) ? entries : [])
321
+ .map((entry) => {
322
+ const name = displayName(entry)
323
+ const masked = maskToken(entry.url)
324
+ return entry.name === '' ? masked : `${name} ${masked}`
325
+ })
326
+ .join('\n')
327
+ }
328
+
230
329
  /**
231
330
  * Persist a configuration change and apply it.
232
331
  *
@@ -241,18 +340,30 @@ export class Runtime {
241
340
  async saveConfig(patch) {
242
341
  const previous = this.config
243
342
  const next = resolveConfig({ ...previous, ...patch })
244
- const changedCore = ['subscriptionUrl', 'mode', 'dnsServers', 'directDomains', 'proxyDomains', 'corePath'].some(
245
- (key) => next[key] !== previous[key],
246
- )
343
+ const changedCore = [
344
+ 'subscriptionUrls',
345
+ 'subscriptionUrl',
346
+ 'mode',
347
+ 'dnsServers',
348
+ 'directDomains',
349
+ 'proxyDomains',
350
+ 'corePath',
351
+ ].some((key) => next[key] !== previous[key])
247
352
  this.config = next
248
353
 
249
354
  const warnings = []
250
355
  const editor = this.editor
356
+ // Write the patch as-is. An earlier version additionally blanked the legacy
357
+ // `subscriptionUrl` to stop it shadowing the list on the next read — and that silently
358
+ // destroyed the user's only copy of their subscription when the migration had put it
359
+ // there. Shadowing is handled by `effectiveSubscriptionText` preferring the list, which
360
+ // costs nothing and cannot lose data.
361
+ const written = patch
251
362
  if (editor === undefined) {
252
363
  warnings.push('not persisted: the profile has no config editor, so this applies until the Harness restarts')
253
364
  } else {
254
365
  try {
255
- await editor(patch)
366
+ await editor(written)
256
367
  } catch (error) {
257
368
  warnings.push(`not persisted: ${error?.message ?? error}`)
258
369
  }
@@ -293,6 +404,126 @@ export class Runtime {
293
404
  }, minutes * 60_000)
294
405
  }
295
406
 
407
+ /**
408
+ * Watch the core and recover from an unexpected exit.
409
+ *
410
+ * A core that dies leaves undici's dispatcher pointed at a closed port, so every
411
+ * outbound request fails with `ECONNREFUSED` while `verify()` still reports `active`
412
+ * — that was the 0.2 behaviour, and it silently broke every foreign request until
413
+ * the user noticed and restarted by hand. Three things happen here instead:
414
+ *
415
+ * 1. an unexpected exit removes the policy, so the process returns to direct
416
+ * connectivity rather than failing every request;
417
+ * 2. one automatic restart is attempted per failure, so a transient crash heals;
418
+ * 3. if the restart also fails, the runtime records {@link degraded} and stops
419
+ * retrying, which the panel and the tool both report.
420
+ *
421
+ * @param schedule - timer factory from the plugin context.
422
+ */
423
+ scheduleWatchdog(schedule) {
424
+ if (this.watchdog !== undefined) this.watchdog()
425
+ this.watchdog = undefined
426
+ const minutes = this.config.healthCheckMinutes
427
+ if (minutes <= 0 || typeof schedule !== 'function') return
428
+ this.watchdog = schedule(() => {
429
+ void this.checkHealth().catch((error) => this.log(`health check failed: ${error?.message ?? error}`))
430
+ }, minutes * 60_000)
431
+ }
432
+
433
+ /**
434
+ * One liveness pass: is the core still listening, and does the policy still route?
435
+ *
436
+ * Exported behaviour is observable through {@link status}; this method exists so the
437
+ * watchdog and a test can drive one pass without timers.
438
+ *
439
+ * @returns what the pass found and, when it acted, what it did.
440
+ */
441
+ async checkHealth() {
442
+ if (this.starting === true) return { state: 'starting' }
443
+ if (this.subscriptionUrl === '') return { state: 'unconfigured' }
444
+
445
+ // A core that arrived after the plugin loaded is picked up here. This is the "fill in
446
+ // the rest later" half of provisioning: nothing has to be re-saved or re-clicked once
447
+ // the download finishes, and a core placed by hand is discovered the same way.
448
+ if (this.binary === undefined) {
449
+ const found = findCoreBinary(this.config.corePath, this.dataDir)
450
+ if (found !== undefined) {
451
+ this.binary = found
452
+ this.core = new Core({ binary: found, workDir: this.dataDir, logger: this.log })
453
+ this.log(`core appeared at ${found}; bringing routing up`)
454
+ try {
455
+ await this.start()
456
+ this.engaged = true
457
+ return { state: 'core-arrived' }
458
+ } catch (error) {
459
+ this.lastError = String(error?.message ?? error)
460
+ return { state: 'failed', reason: this.lastError }
461
+ }
462
+ }
463
+ // Still no core. Start a download if the user allowed automatic provisioning, and
464
+ // never more than one at a time.
465
+ if (this.config.autoFetchCore === true && this.bootstrapping !== true) {
466
+ void this.bootstrapCore()
467
+ .then(() => this.checkHealth())
468
+ .catch((error) => {
469
+ this.lastError = String(error?.message ?? error)
470
+ this.log(`background core download failed: ${this.lastError}`)
471
+ })
472
+ return { state: 'fetching-core' }
473
+ }
474
+ return { state: 'no-core' }
475
+ }
476
+
477
+ if (this.engaged !== true && this.config.autoStart !== true) return { state: 'disabled' }
478
+
479
+ const running = this.core?.running === true
480
+ const policy = this.routing === undefined ? { state: 'none' } : await this.routing.verify()
481
+
482
+ if (running && policy.state === 'active') {
483
+ this.degraded = undefined
484
+ return { state: 'healthy' }
485
+ }
486
+
487
+ // Not running, or running with a policy that something else replaced: a restart
488
+ // repairs both, because `start()` re-installs the policy and re-spawns the core.
489
+ if (running && policy.state !== 'active') {
490
+ this.log(`outbound policy is ${policy.state}; reinstalling it`)
491
+ try {
492
+ await this.applyPolicy()
493
+ return { state: 'policy-reinstalled' }
494
+ } catch (error) {
495
+ this.degraded = `policy could not be reinstalled: ${error?.message ?? error}`
496
+ return { state: 'failed', reason: this.degraded }
497
+ }
498
+ }
499
+
500
+ // The core died. Return to direct first so requests stop failing against a closed
501
+ // port while the restart is in flight.
502
+ if (this.routing !== undefined) await this.routing.releaseToDirect()
503
+ this.log('core stopped unexpectedly; restarting it once')
504
+ try {
505
+ await this.start()
506
+ this.degraded = undefined
507
+ return { state: 'restarted' }
508
+ } catch (error) {
509
+ this.degraded = `restart failed: ${error?.message ?? error}`
510
+ this.lastError = this.degraded
511
+ this.log(this.degraded)
512
+ return { state: 'failed', reason: this.degraded }
513
+ }
514
+ }
515
+
516
+ /**
517
+ * Reinstall the outbound policy against the current core port.
518
+ *
519
+ * @returns the applied variables.
520
+ */
521
+ async applyPolicy() {
522
+ const routing = await this.ensurePolicyModule()
523
+ if (this.core?.mixedPort === undefined) throw new Error('the core has no proxy port')
524
+ return await routing.apply('127.0.0.1', this.core.mixedPort)
525
+ }
526
+
296
527
  /**
297
528
  * Re-arm the cycle after a configuration change.
298
529
  *
@@ -313,22 +544,25 @@ export class Runtime {
313
544
  async probe(raw) {
314
545
  const text = String(raw ?? '').trim()
315
546
  if (text === '') return { ok: false, error: 'subscription URL is empty' }
316
- let url
317
- try {
318
- url = normalizeSubscriptionUrl(text)
319
- } catch (error) {
320
- return { ok: false, error: String(error?.message ?? error) }
547
+ // The field now holds several lines; probe every entry so one bad line is named
548
+ // rather than only the first one being checked.
549
+ const parsed = parseSubscriptions(text)
550
+ if (parsed.entries.length === 0) {
551
+ return { ok: false, error: parsed.errors[0]?.reason ?? 'no subscription URL found', errors: parsed.errors }
321
552
  }
322
553
  try {
323
- const result = await probeSubscription(url, { timeoutMs: 15_000 })
554
+ const report = await probeSubscriptions(parsed.entries, { timeoutMs: 15_000 })
324
555
  return {
325
- ok: result.ok,
326
- status: result.status,
327
- format: result.format,
328
- nodeCount: result.nodeCount,
329
- bytes: result.bytes,
330
- url: maskToken(url),
331
- error: result.ok ? undefined : `the server answered ${result.status}`,
556
+ ...report,
557
+ ok: report.ok,
558
+ maskedUrls: this.maskList(parsed.entries),
559
+ errors: parsed.errors,
560
+ error: report.ok
561
+ ? undefined
562
+ : report.results
563
+ .filter((result) => !result.ok)
564
+ .map((result) => `${result.name}: ${result.error ?? `the server answered ${result.status}`}`)
565
+ .join('; '),
332
566
  }
333
567
  } catch (error) {
334
568
  // The probe runs through whatever policy is installed, so a failure here may
@@ -339,7 +573,7 @@ export class Runtime {
339
573
 
340
574
  /** The subscription to use. There is no fallback: an empty value means unconfigured. */
341
575
  get subscriptionUrl() {
342
- return String(this.config.subscriptionUrl ?? '').trim()
576
+ return effectiveSubscriptionText(this.config)
343
577
  }
344
578
 
345
579
  /** The node preference, empty when the user has not chosen one. */
@@ -356,18 +590,106 @@ export class Runtime {
356
590
  * "ready" and the panel showing nothing but a stale lastError.
357
591
  */
358
592
  get blocker() {
359
- if (this.binary === undefined) {
360
- return 'no mihomo core binary found: install Clash Verge or set corePath to a mihomo/clash executable'
361
- }
593
+ // A missing core is NOT a blocker. The plugin installs, opens, and stores its
594
+ // configuration without one; the core is fetched in the background and routing comes
595
+ // up when it arrives. Reporting "cannot start" for a state the plugin can repair on
596
+ // its own was making an optional download look like a broken install.
362
597
  if (this.installRoot === undefined) {
363
598
  return 'cannot locate the dsh installation root: set DSH_INSTALL_ROOT to the directory holding the dsh package.json (a packaged build keeps it inside resources/app.asar)'
364
599
  }
365
600
  if (this.subscriptionUrl === '') {
366
- return 'no subscription: paste a subscription URL in Settings → Clash proxy'
601
+ return 'no subscription: paste one or more subscription URLs in Settings → Clash proxy'
602
+ }
603
+ const parsed = this.subscriptions
604
+ if (parsed.entries.length === 0) {
605
+ return `no usable subscription URL: ${parsed.errors[0]?.reason ?? 'the field holds no URL'}`
367
606
  }
368
607
  return undefined
369
608
  }
370
609
 
610
+ /**
611
+ * Whether this runtime can bring routing up right now.
612
+ *
613
+ * Kept apart from {@link blocker} because a missing core is now a *recoverable*
614
+ * state: the plugin can fetch one. The start path still refuses without a binary,
615
+ * but that refusal is no longer the end of the story.
616
+ *
617
+ * @returns true when the core and the installation root are both present.
618
+ */
619
+ get ready() {
620
+ return this.binary !== undefined && this.installRoot !== undefined
621
+ }
622
+
623
+ /**
624
+ * Download and install a core into this plugin's data directory.
625
+ *
626
+ * This is what makes the plugin independent of a desktop Clash installation. The
627
+ * download is verified against the release's published SHA-256 before anything is
628
+ * unpacked or moved into place, and `binary`/`core` are only reassigned once the
629
+ * executable exists — so a failed attempt leaves the previous core working.
630
+ *
631
+ * @param options - progress callback and an injectable fetch for a test.
632
+ * @returns the install report.
633
+ */
634
+ async bootstrapCore(options = {}) {
635
+ if (this.bootstrapping === true) throw new Error('a core download is already in progress')
636
+ if (platformKey() === undefined) {
637
+ throw new Error(`no released core for ${process.platform}-${process.arch}; set corePath to an existing executable`)
638
+ }
639
+ this.bootstrapping = true
640
+ this.bootstrap = { phase: 'starting' }
641
+ try {
642
+ const report = await installCore({
643
+ dataDir: this.dataDir,
644
+ version: this.config.coreVersion,
645
+ fetch: options.fetch,
646
+ onProgress: (progress) => {
647
+ this.bootstrap = progress
648
+ if (progress.phase === 'downloading' && progress.total > 0) {
649
+ this.log(`core download ${Math.round((progress.received / progress.total) * 100)}%`)
650
+ } else {
651
+ this.log(`core bootstrap: ${progress.phase}${progress.tag === undefined ? '' : ` ${progress.tag}`}`)
652
+ }
653
+ },
654
+ })
655
+ // Re-resolve through the same discovery the constructor used, so the state after
656
+ // a download is indistinguishable from a machine that already had a core.
657
+ this.binary = findCoreBinary(this.config.corePath, this.dataDir)
658
+ this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger: this.log })
659
+ this.bootstrap = { phase: 'done', ...report }
660
+ return report
661
+ } catch (error) {
662
+ this.bootstrap = { phase: 'failed', error: String(error?.message ?? error) }
663
+ throw error
664
+ } finally {
665
+ this.bootstrapping = false
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Install a core from an archive the user already placed on disk.
671
+ *
672
+ * The download path cannot work on a network that will not move 22 MB: measured here,
673
+ * every mirror stalled below the speed gate. An offline install keeps the plugin usable
674
+ * there, and it is verified exactly like a downloaded archive.
675
+ *
676
+ * @param archivePath - the archive to install.
677
+ * @param digest - expected SHA-256; empty accepts any archive and reports what it was.
678
+ * @returns the install report.
679
+ */
680
+ async installCoreFromArchive(archivePath, digest = '') {
681
+ const report = await installCoreFromFile(archivePath, digest, {
682
+ dataDir: this.dataDir,
683
+ onProgress: (progress) => {
684
+ this.bootstrap = progress
685
+ },
686
+ })
687
+ this.binary = findCoreBinary(this.config.corePath, this.dataDir)
688
+ this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger: this.log })
689
+ this.bootstrap = { phase: 'done', ...report }
690
+ return report
691
+ }
692
+
371
693
  /**
372
694
  * Load the shared policy module once, from the installation the host runs from.
373
695
  *
@@ -394,21 +716,143 @@ export class Runtime {
394
716
  }
395
717
 
396
718
  /**
397
- * Import the subscription and bring routing up.
719
+ * Import the subscriptions and bring routing up.
398
720
  *
399
- * @param options - overrides for one start, e.g. a newly pasted URL.
721
+ * @param options - overrides for one start, e.g. a newly pasted URL list.
400
722
  * @returns the start report.
401
723
  */
402
724
  async start(options = {}) {
403
- mkdirSync(this.dataDir, { recursive: true })
404
- const blocker = this.blocker
405
- if (blocker !== undefined) throw new Error(blocker)
725
+ this.starting = true
726
+ try {
727
+ return await this.startInner(options)
728
+ } finally {
729
+ this.starting = false
730
+ }
731
+ }
732
+
733
+ /**
734
+ * The body of {@link start}, with {@link starting} already raised.
735
+ *
736
+ * @param options - overrides for one start.
737
+ * @returns the start report.
738
+ */
739
+ /**
740
+ * Make a core available, using the copy that ships with the plugin.
741
+ *
742
+ * This is the "works right after install" half. The vendored archive is unpacked into the
743
+ * data directory on first use and verified both as an archive and as an executable, so the
744
+ * plugin never depends on reaching GitHub before it can proxy anything. Free space and a
745
+ * one-time unpack are the whole cost.
746
+ *
747
+ * A core found by discovery (a desktop Clash install, or a `corePath`) still wins: this
748
+ * only runs when nothing else is available.
749
+ *
750
+ * @param options - platform overrides and a progress callback.
751
+ * @returns the installed path, or undefined when this build has no vendored core.
752
+ */
753
+ async ensureVendoredCore(options = {}) {
754
+ if (vendoredFor(options.platform, options.arch) === undefined) return undefined
755
+ if (this.binary !== undefined) return this.binary
756
+ try {
757
+ const installed = await installVendoredCore(this.dataDir, {
758
+ ...options,
759
+ onProgress: (progress) => {
760
+ this.bootstrap = progress
761
+ if (progress.phase === 'unpacking' || progress.phase === 'installed') this.log(`core ${progress.phase}`)
762
+ },
763
+ })
764
+ this.binary = findCoreBinary(this.config.corePath, this.dataDir)
765
+ this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger: this.log })
766
+ this.bootstrap = { phase: 'ready', path: installed.path, reused: installed.reused }
767
+ return this.binary
768
+ } catch (error) {
769
+ this.bootstrap = { phase: 'failed', error: String(error?.message ?? error) }
770
+ this.log(`the bundled core could not be unpacked: ${this.bootstrap.error}`)
771
+ return undefined
772
+ }
773
+ }
406
774
 
407
- const url = normalizeSubscriptionUrl(options.subscriptionUrl ?? this.subscriptionUrl)
775
+ /**
776
+ * Kick off the optional GeoIP upgrade in the background.
777
+ *
778
+ * Deliberately fire-and-forget. The upgrade improves accuracy for addresses the embedded
779
+ * list cannot describe; it must never delay or fail a start, and on a machine with no
780
+ * route to either mirror it simply does not happen.
781
+ *
782
+ * @returns nothing; progress goes to {@link geo} and the log.
783
+ */
784
+ scheduleGeoUpgrade() {
785
+ if (this.config.autoFetchGeo === false) {
786
+ this.geo = { phase: 'disabled' }
787
+ return
788
+ }
789
+ // Geo databases are seeded from any desktop Clash install at core start, so ask the disk
790
+ // rather than this runtime's memory: a present database means nothing to do, and an
791
+ // absent one is the only case worth a download.
792
+ if (hasGeoDatabase(this.dataDir)) {
793
+ this.geo = { phase: 'present' }
794
+ return
795
+ }
796
+ if (this.geoUpgrading === true) return
797
+ this.geoUpgrading = true
798
+ this.geo = { phase: 'fetching' }
799
+ void fetchGeoDatabases(this.dataDir)
800
+ .then((report) => {
801
+ this.geo = {
802
+ phase: report.ok ? 'done' : report.fetched.length > 0 ? 'partial' : 'unavailable',
803
+ fetched: report.fetched.map((entry) => ({ name: entry.name, bytes: entry.bytes, source: entry.source })),
804
+ failed: report.failed,
805
+ }
806
+ if (report.fetched.length > 0) {
807
+ this.log(`geoip upgraded: ${report.fetched.map((entry) => entry.name).join(', ')} — applies from the next core start`)
808
+ } else if (report.ok === false) {
809
+ this.log(`geoip upgrade unavailable (domestic routing keeps using the embedded list): ${report.failed.map((entry) => entry.name).join(', ')}`)
810
+ }
811
+ })
812
+ .catch((error) => {
813
+ this.geo = { phase: 'unavailable', error: String(error?.message ?? error) }
814
+ })
815
+ .finally(() => {
816
+ this.geoUpgrading = false
817
+ })
818
+ }
819
+
820
+ async startInner(options = {}) {
821
+ mkdirSync(this.dataDir, { recursive: true })
822
+ // Order matters, and it is the point of this method: configuration is validated and
823
+ // the subscription list is parsed BEFORE the core is required, so a missing core
824
+ // surfaces as "still fetching" rather than as "your configuration is wrong".
825
+ const parsed = parseSubscriptions(String(options.subscriptionUrls ?? this.subscriptionUrl))
826
+ if (parsed.entries.length === 0) {
827
+ throw new Error(`no usable subscription URL: ${parsed.errors[0]?.reason ?? 'the field holds no URL'}`)
828
+ }
829
+ if (this.installRoot === undefined) throw new Error(this.blocker)
830
+ if (this.binary === undefined) {
831
+ // Last chance before reporting a missing core: unpack the copy that ships with the
832
+ // plugin. This is why a fresh install needs no network at all.
833
+ await this.ensureVendoredCore()
834
+ }
835
+ if (this.binary === undefined) {
836
+ // Nothing to spawn yet. Fetching is a background concern, so this returns a state
837
+ // the caller can report instead of throwing: the panel shows "内核准备中", and the
838
+ // watchdog brings routing up once the download lands.
839
+ const error = new Error(
840
+ `no mihomo core yet (${platformKey() ?? `${process.platform}-${process.arch}`}); a download is needed before routing can start`,
841
+ )
842
+ error.code = 'CORE_MISSING'
843
+ throw error
844
+ }
408
845
 
409
846
  const routing = await this.ensurePolicyModule()
847
+ const coreEntries = parsed.entries.map((entry) => ({
848
+ provider: providerName(entry),
849
+ url: entry.url,
850
+ // Only prefix when there is more than one provider: a single subscription keeps
851
+ // the node names exactly as the provider wrote them.
852
+ prefix: nodePrefix(entry, parsed.entries.length),
853
+ }))
410
854
  const endpoint = await this.core.start({
411
- subscriptionUrl: url,
855
+ subscriptions: coreEntries,
412
856
  mode: this.config.mode,
413
857
  dnsServers: splitList(this.config.dnsServers),
414
858
  directDomains: this.config.directDomains,
@@ -418,21 +862,14 @@ export class Runtime {
418
862
  })
419
863
  const variables = await routing.apply(endpoint.host, endpoint.port)
420
864
 
421
- // The probe runs after routing is up on purpose: a subscription host is often
422
- // itself blocked, so probing first would report a 403 that says nothing about the
423
- // subscription. The core re-fetches the same URL through its own provider anyway.
424
- this.lastProbe = await probeSubscription(url).catch((error) => ({
425
- status: 0,
426
- ok: false,
427
- bytes: 0,
428
- format: 'unreachable',
429
- nodeCount: 0,
430
- error: String(error?.message ?? error),
431
- }))
865
+ // Wait for the providers before probing. The core answers its control API before a
866
+ // provider has downloaded anything, so probing at that point raced the fetch and
867
+ // reported ECONNRESET on a perfectly good subscription — the panel then showed
868
+ // "unreachable" next to 54 working nodes. Probe after the node table arrives, and
869
+ // wait per provider so a large second subscription is not cut short.
870
+ const group = await this.waitForNodes(parsed.entries.length)
871
+ this.lastProbe = await this.probeEntries(parsed.entries)
432
872
 
433
- // The provider downloads in the background right after boot; give it a moment so
434
- // the first status report carries a node table instead of an empty group.
435
- const group = await this.waitForNodes()
436
873
  const preferred = String(options.node ?? this.preferredNode ?? '').trim()
437
874
  // A fresh group starts on DIRECT, which would route foreign traffic straight out.
438
875
  // Selecting a real node is part of bringing routing up, not an optional extra.
@@ -440,29 +877,82 @@ export class Runtime {
440
877
  ? await this.core.autoSelect(preferred).catch(() => undefined)
441
878
  : undefined
442
879
  this.lastError = undefined
880
+ this.degraded = undefined
881
+ // Routing is now up under this activation's ownership, which is what arms the
882
+ // watchdog. Set last so a failure inside `start()` never arms it.
883
+ this.engaged = true
884
+ // Only now can a GeoIP database be fetched: the tunnel it must travel over exists at
885
+ // this point and not before. The embedded CIDR list already classifies domestic
886
+ // addresses, so this is an upgrade running in the background — never a startup
887
+ // dependency, and a failure is recorded rather than raised.
888
+ this.scheduleGeoUpgrade()
443
889
  return {
444
890
  endpoint: `http://${endpoint.host}:${endpoint.port}`,
445
891
  geo: endpoint.geo,
892
+ providers: endpoint.providers,
893
+ // The rule set the core loaded for the domestic bypass, so a caller can show that the
894
+ // split routing does not depend on a GeoIP database being present.
895
+ cnRuleSet: endpoint.cnRuleSet,
446
896
  group: await this.core.group(),
447
897
  selected,
448
898
  variables,
449
899
  probe: this.lastProbe,
900
+ subscriptionErrors: parsed.errors,
450
901
  configPath: this.core.configPath,
451
902
  }
452
903
  }
453
904
 
454
905
  /**
455
- * Poll the group until the subscription provider contributes at least one node.
906
+ * Probe every configured subscription, tolerating a failure in any of them.
456
907
  *
908
+ * @param entries - parsed subscription entries.
909
+ * @returns the labelled multi-probe report.
910
+ */
911
+ async probeEntries(entries) {
912
+ try {
913
+ return await probeSubscriptions(entries, { timeoutMs: 20_000 })
914
+ } catch (error) {
915
+ return {
916
+ results: [],
917
+ ok: false,
918
+ total: entries.length,
919
+ reachable: 0,
920
+ nodeCount: 0,
921
+ bytes: 0,
922
+ error: String(error?.message ?? error),
923
+ }
924
+ }
925
+ }
926
+
927
+ /**
928
+ * Wait until the subscription providers have contributed their nodes, or time out.
929
+ *
930
+ * An earlier version returned as soon as the group held *any* node, which was right
931
+ * for one subscription and wrong for several: the fast provider satisfied the
932
+ * condition while a large one (a 723 KB, 54-node document takes seconds) was still
933
+ * downloading, so the slow subscription was then reported as `ok: false` with zero
934
+ * nodes — a lie that only appears once you use more than one subscription. So the
935
+ * wait is per provider, and a provider that stays empty is reported by
936
+ * {@link Core.providerStatus} rather than hidden behind a group count.
937
+ *
938
+ * @param total - how many providers are configured.
457
939
  * @returns the group snapshot, even when it stayed empty.
458
940
  */
459
- async waitForNodes() {
941
+ async waitForNodes(total = 1) {
460
942
  const deadline = Date.now() + 20_000
943
+ const expected = Math.max(1, Number(total) || 1)
461
944
  let group = await this.core.group()
462
- while (group.all.length <= 1 && Date.now() < deadline) {
463
- await new Promise((resolve) => setTimeout(resolve, 500))
945
+ while (Date.now() < deadline) {
946
+ const status = await this.core.providerStatus().catch(() => ({ providers: [] }))
947
+ const arrived = (status.providers ?? []).filter((row) => row.nodeCount > 0).length
948
+ if (arrived >= expected) break
949
+ // A single provider that answered is enough to stop waiting only when every other
950
+ // one has already answered — the `arrived === expected` test above. Otherwise keep
951
+ // polling, but never longer than the deadline.
464
952
  group = await this.core.group()
953
+ await new Promise((resolve) => setTimeout(resolve, 500))
465
954
  }
955
+ group = await this.core.group()
466
956
  return group
467
957
  }
468
958
 
@@ -473,8 +963,18 @@ export class Runtime {
473
963
  this.timer = undefined
474
964
  }
475
965
 
966
+ /** Stop the watchdog. Safe to call when none is running. */
967
+ stopWatchdog() {
968
+ if (this.watchdog === undefined) return
969
+ this.watchdog()
970
+ this.watchdog = undefined
971
+ }
972
+
476
973
  /** Stop routing first, so nothing is sent to a port that is about to close. */
477
974
  async stop() {
975
+ // A stop is the user saying "leave me direct": disarm the watchdog before the port
976
+ // closes, or it would see an unexpected exit and restart what was just stopped.
977
+ this.engaged = false
478
978
  if (this.routing !== undefined) await this.routing.releaseToDirect()
479
979
  if (this.core !== undefined) await this.core.stop()
480
980
  }
@@ -483,9 +983,20 @@ export class Runtime {
483
983
  async status() {
484
984
  const running = this.core?.running === true
485
985
  const group = running ? await this.core.group().catch(() => ({ all: [], now: undefined })) : { all: [], now: undefined }
486
- const provider = running ? await this.core.providerStatus() : { updatedAt: null, vehicleType: null }
986
+ const provider = running
987
+ ? await this.core.providerStatus()
988
+ : { updatedAt: null, vehicleType: null, providers: [], ok: false, healthy: 0, total: 0 }
487
989
  const traffic = running ? await this.core.connections().catch(() => undefined) : undefined
488
990
  const policy = this.routing === undefined ? { state: 'none' } : await this.routing.verify()
991
+ const parsed = this.subscriptions
992
+ const providerRows = provider.providers.map((row) => {
993
+ const entry = parsed.entries.find((candidate) => providerName(candidate) === row.provider)
994
+ return {
995
+ ...row,
996
+ name: entry === undefined ? row.provider : displayName(entry),
997
+ url: entry === undefined ? '' : maskToken(entry.url),
998
+ }
999
+ })
489
1000
  return {
490
1001
  binary: this.binary,
491
1002
  dataDir: this.dataDir,
@@ -494,14 +1005,40 @@ export class Runtime {
494
1005
  routing: this.routing?.active === true,
495
1006
  /** Whether the installed dispatcher is really this plugin's — see Routing#verify. */
496
1007
  routingVerified: policy.state,
1008
+ /**
1009
+ * Whether the installed dispatcher still has something to talk to. `verify()`
1010
+ * answers "is this my dispatcher", not "does it work"; a dead core left it
1011
+ * reporting `active` over a closed port, so the two are reported apart.
1012
+ */
1013
+ routingHealthy: policy.state === 'active' && running,
497
1014
  endpointEnvironment: this.routing?.endpoint,
498
1015
  childEnvironment: this.routing?.childOverlay() ?? {},
499
1016
  node: group.now,
500
1017
  nodeCount: Math.max(0, group.all.length - 1),
501
1018
  nodes: group.all.filter((entry) => entry !== 'DIRECT').slice(0, 40),
502
1019
  provider,
1020
+ providers: providerRows,
1021
+ subscriptions: parsed.entries.map((entry) => ({
1022
+ name: displayName(entry),
1023
+ provider: providerName(entry),
1024
+ url: maskToken(entry.url),
1025
+ index: entry.index,
1026
+ })),
1027
+ subscriptionErrors: parsed.errors,
503
1028
  traffic,
504
1029
  blocker: this.blocker,
1030
+ ready: this.ready,
1031
+ /** Progress/result of a core download, when one has been attempted. */
1032
+ bootstrap: this.bootstrap,
1033
+ /** Optional GeoIP upgrade state; domestic routing works without it. */
1034
+ geoUpgrade: this.geo,
1035
+ /** Whether the core uses an embedded CIDR rule set for the domestic bypass. */
1036
+ cnRuleSet: this.core?.cnRuleSet === undefined
1037
+ ? undefined
1038
+ : { name: 'cn-cidr', count: this.core.cnRuleSet.count },
1039
+ /** Whether a download could be attempted at all on this platform. */
1040
+ platformSupported: platformKey() !== undefined,
1041
+ degraded: this.degraded,
505
1042
  lastError: this.lastError ?? this.core?.lastError,
506
1043
  probe: this.lastProbe,
507
1044
  delays: Object.fromEntries(this.measured),
@@ -524,6 +1061,7 @@ export async function apply(ctx, rawConfig) {
524
1061
 
525
1062
  ctx.effect(() => () => {
526
1063
  runtime.stopTimer()
1064
+ runtime.stopWatchdog()
527
1065
  void runtime.stop()
528
1066
  })
529
1067
 
@@ -544,21 +1082,27 @@ export async function apply(ctx, rawConfig) {
544
1082
  }, 'clash-proxy: config persistence')
545
1083
  })
546
1084
 
547
- // The measurement cycle rides the host timer service, so it is disposed with the
548
- // plugin and repeated plugin reloads never stack timers. `rearm` is published here,
549
- // in plugin context, for the request handler that saves a new interval to call: it
550
- // re-enters this context instead of touching the timer service from a foreign fiber.
1085
+ // The measurement cycle and the liveness watchdog ride the host timer service, so
1086
+ // they are disposed with the plugin and repeated plugin reloads never stack timers.
1087
+ // `rearm` is published here, in plugin context, for the request handler that saves a
1088
+ // new interval to call: it re-enters this context instead of touching the timer
1089
+ // service from a foreign fiber.
551
1090
  ctx.inject(['timer'], (timerCtx) => {
552
1091
  timerCtx.effect(() => {
553
1092
  const schedule = (callback, delay) => timerCtx.timer.interval(callback, delay)
554
1093
  runtime.schedule = schedule
555
- runtime.rearm = () => runtime.scheduleSpeedTest(schedule)
1094
+ runtime.rearm = () => {
1095
+ runtime.scheduleSpeedTest(schedule)
1096
+ runtime.scheduleWatchdog(schedule)
1097
+ }
556
1098
  runtime.scheduleSpeedTest(schedule)
1099
+ runtime.scheduleWatchdog(schedule)
557
1100
  return () => {
558
1101
  runtime.rearm = undefined
559
1102
  runtime.stopTimer()
1103
+ runtime.stopWatchdog()
560
1104
  }
561
- }, 'clash-proxy: speed test cycle')
1105
+ }, 'clash-proxy: speed test cycle and watchdog')
562
1106
  })
563
1107
 
564
1108
  if (runtime.installRoot === undefined) {
@@ -569,6 +1113,8 @@ export async function apply(ctx, rawConfig) {
569
1113
 
570
1114
  if (config.autoStart === true && runtime.blocker === undefined) {
571
1115
  // Boot in the background: a slow subscription must not delay the Harness' own startup.
1116
+ // `start()` unpacks the bundled core when nothing else is present, so this path works on
1117
+ // a machine with no network and no Clash installation.
572
1118
  void runtime.start().catch((error) => {
573
1119
  runtime.lastError = String(error?.message ?? error)
574
1120
  log(`auto start failed: ${runtime.lastError}`)
@@ -576,6 +1122,15 @@ export async function apply(ctx, rawConfig) {
576
1122
  } else if (config.autoStart === true) {
577
1123
  log(`auto start skipped: ${runtime.blocker}`)
578
1124
  }
1125
+ // A missing core is no longer a startup branch of its own: `start()` prefers the bundled
1126
+ // copy, and only a build without one falls back to the download below.
1127
+ if (config.autoFetchCore === true && runtime.binary === undefined && vendoredFor() === undefined) {
1128
+ log('no bundled core for this platform; downloading one because autoFetchCore is on')
1129
+ void runtime.bootstrapCore().catch((error) => {
1130
+ runtime.lastError = String(error?.message ?? error)
1131
+ log(`core download failed: ${runtime.lastError}`)
1132
+ })
1133
+ }
579
1134
 
580
1135
  // Panel routes ride a `webServer` sub-fiber rather than a one-shot `ctx.get`:
581
1136
  // loader entries settle concurrently, so reading the service at apply time would
@@ -604,22 +1159,23 @@ function subscriptionTool(runtime) {
604
1159
  return {
605
1160
  name: 'clash_proxy',
606
1161
  description: [
607
- 'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and a user-imported subscription.',
1162
+ 'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and one or more user-imported subscriptions.',
608
1163
  '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.',
609
- 'action=status reports the core, the installed policy, the node table and live traffic.',
610
- 'action=import takes a subscription URL (raw, or a clash://install-config?url= import link), probes it, restarts the core on it and routes through it.',
611
- 'action=start brings routing up on the configured subscription; action=stop takes it down and restores direct connections.',
612
- 'action=select switches the exit node by name (see the node list from status); action=test measures latency for one node or or the current one; action=refresh re-downloads the subscription.',
1164
+ 'action=status reports the core, the installed policy, every subscription with its node count, the node table and live traffic.',
1165
+ '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.',
1166
+ 'action=start brings routing up on the configured subscriptions; action=stop takes it down and restores direct connections.',
1167
+ '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.',
613
1168
  ].join(' '),
614
1169
  parameters: {
615
1170
  type: 'object',
616
1171
  properties: {
617
1172
  action: {
618
1173
  type: 'string',
619
- enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh'],
620
- description: 'status reports state; import sets and activates a subscription; start/stop control routing; select switches the exit node; test measures latency; refresh re-downloads the subscription.',
1174
+ enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh', 'bootstrap'],
1175
+ 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.',
621
1176
  },
622
- url: { type: 'string', description: 'Subscription URL for action=import (raw https:// or clash://install-config?url=…).' },
1177
+ url: { type: 'string', description: 'One or more subscription URLs for action=import, one per line. A leading "name " is kept as the display name.' },
1178
+ append: { type: 'boolean', description: 'For action=import: add to the existing subscriptions instead of replacing them.' },
623
1179
  node: { type: 'string', description: 'Exact node name for action=select or action=test; omit to use the current selection.' },
624
1180
  },
625
1181
  required: ['action'],
@@ -630,7 +1186,7 @@ function subscriptionTool(runtime) {
630
1186
  return [{ type: 'text', text: String(value?.summary ?? JSON.stringify(value)) }]
631
1187
  },
632
1188
  },
633
- timeoutMs: 120_000,
1189
+ timeoutMs: 180_000,
634
1190
  async execute(args) {
635
1191
  const action = String(args?.action ?? 'status')
636
1192
  try {
@@ -644,16 +1200,39 @@ function subscriptionTool(runtime) {
644
1200
  return { ...status, summary: '代理已停止,所有外网请求恢复直连。' }
645
1201
  }
646
1202
  if (action === 'import') {
647
- const url = String(args?.url ?? '').trim()
648
- if (url === '') throw new Error('action=import needs a url')
649
- runtime.config.subscriptionUrl = url
650
- const report = await runtime.start({ subscriptionUrl: url })
1203
+ const incoming = String(args?.url ?? '').trim()
1204
+ if (incoming === '') throw new Error('action=import needs a url')
1205
+ const merged = args?.append === true ? [runtime.subscriptionUrl, incoming].filter((part) => part !== '').join('\n') : incoming
1206
+ const parsed = parseSubscriptions(merged)
1207
+ if (parsed.entries.length === 0) {
1208
+ throw new Error(parsed.errors[0]?.reason ?? 'no usable subscription URL in the request')
1209
+ }
1210
+ // Persist first: a model-driven import must survive a restart exactly like a
1211
+ // save from the panel, which the 0.2 tool path did not do.
1212
+ const saved = await runtime.saveConfig({ subscriptionUrls: merged })
1213
+ const report = await runtime.start({ subscriptionUrls: merged })
651
1214
  return {
652
1215
  ...report,
1216
+ config: saved.config,
1217
+ warnings: saved.warnings,
653
1218
  summary: [
654
- `订阅已导入:${report.probe.format},${report.probe.nodeCount} 个节点,${report.probe.bytes} 字节。`,
655
- `内核 ${report.endpoint},当前节点「${report.group.now ?? '未选择'}」。`,
656
- `策略已安装,外网走代理、国内直连。`,
1219
+ `订阅已导入 ${parsed.entries.length} 条${args?.append === true ? '(追加)' : '(替换)'}:`,
1220
+ ...parsed.entries.map((entry) => ` ${displayName(entry)}:${maskToken(entry.url)}`),
1221
+ `内核 ${report.endpoint},当前节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。`,
1222
+ saved.warnings.length === 0 ? '配置已保存。' : `配置保存警告:${saved.warnings.join('; ')}`,
1223
+ ].join('\n'),
1224
+ }
1225
+ }
1226
+ if (action === 'bootstrap') {
1227
+ const report = await runtime.bootstrapCore()
1228
+ return {
1229
+ ...report,
1230
+ binary: runtime.binary,
1231
+ summary: [
1232
+ `已下载并验证内核:${report.tag},${Math.round(report.bytes / 1024 / 1024)} MB。`,
1233
+ `SHA-256 与发布页一致:${report.digest.slice(0, 16)}…`,
1234
+ `落盘位置:${report.path}`,
1235
+ runtime.subscriptionUrl === '' ? '下一步:在设置里填订阅链接,然后 action=start。' : '下一步:action=start 即可启动。',
657
1236
  ].join('\n'),
658
1237
  }
659
1238
  }
@@ -681,7 +1260,14 @@ function subscriptionTool(runtime) {
681
1260
  if (action === 'refresh') {
682
1261
  const provider = await runtime.core.updateProvider()
683
1262
  const group = await runtime.core.group()
684
- return { provider, group, summary: `订阅已刷新:${group.all.length - 1} 个节点。` }
1263
+ return {
1264
+ provider,
1265
+ group,
1266
+ summary: [
1267
+ `订阅已刷新:${provider.healthy}/${provider.total} 条可用,共 ${group.all.length - 1} 个节点。`,
1268
+ ...provider.providers.map((row) => ` ${row.provider}:${row.ok ? `${row.nodeCount} 个节点` : '未拉到节点'}`),
1269
+ ].join('\n'),
1270
+ }
685
1271
  }
686
1272
  throw new Error(`unknown action "${action}"`)
687
1273
  } catch (error) {
@@ -699,12 +1285,30 @@ function subscriptionTool(runtime) {
699
1285
  * @returns the summary text.
700
1286
  */
701
1287
  function describeStatus(status) {
702
- if (status.blocker !== undefined) return `未运行:${status.blocker}`
1288
+ if (status.blocker !== undefined) {
1289
+ const lines = [`未运行:${status.blocker}`]
1290
+ if (status.bootstrap !== undefined) {
1291
+ lines.push(`内核下载:${status.bootstrap.phase}${status.bootstrap.error === undefined ? '' : `(${status.bootstrap.error})`}`)
1292
+ }
1293
+ return lines.join('\n')
1294
+ }
703
1295
  const lines = [
704
1296
  `内核:${status.running ? `运行中 ${status.endpoint}` : '未运行'}${status.binary === undefined ? '(未找到二进制)' : ''}`,
705
- `出网策略:${status.routing ? `已安装 → ${status.endpointEnvironment}` : '未安装(直连)'}`,
1297
+ `出网策略:${status.routing ? `已安装 → ${status.endpointEnvironment}` : '未安装(直连)'}${
1298
+ status.routing === true && status.routingHealthy !== true ? '(内核不在,实际不生效)' : ''
1299
+ }`,
706
1300
  `当前节点:${status.node ?? '未选择'}(可选 ${status.nodeCount} 个)`,
707
1301
  ]
1302
+ const subscriptions = Array.isArray(status.subscriptions) ? status.subscriptions : []
1303
+ if (subscriptions.length > 0) {
1304
+ lines.push(`订阅 ${subscriptions.length} 条:`)
1305
+ for (const subscription of subscriptions) {
1306
+ const row = (status.providers ?? []).find((candidate) => candidate.provider === subscription.provider)
1307
+ const state = row === undefined ? '内核未运行' : row.ok ? `${row.nodeCount} 个节点` : '未拉到节点'
1308
+ lines.push(` ${subscription.name}:${state}`)
1309
+ }
1310
+ }
1311
+ if (status.degraded !== undefined) lines.push(`降级:${status.degraded}`)
708
1312
  if (status.lastError !== undefined) lines.push(`最近错误:${status.lastError}`)
709
1313
  return lines.join('\n')
710
1314
  }