dsh-clash-subscription 0.2.2 → 0.4.2-probe.5

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,678 +1 @@
1
- /**
2
- * Host half of the Clash subscription proxy bundle.
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 —
8
- * with no Clash Verge desktop app, system proxy, or per-command environment variable.
9
- *
10
- * @module dsh-clash-proxy
11
- */
12
- import { mkdirSync } from 'node:fs'
13
- import { homedir } from 'node:os'
14
- import { join } from 'node:path'
15
- import { Core, findCoreBinary, splitList } from './lib/core.js'
16
- import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
17
- import { Routing } from './lib/routing.js'
18
- import { normalizeSubscriptionUrl, probeSubscription } from './lib/subscription.js'
19
- import { maskToken, mountRoutes } from './lib/routes.js'
20
-
21
- export const name = 'clash-proxy'
22
-
23
- export const inject = ['tools']
24
-
25
- /**
26
- * Defaults for every field, so a plugin row may omit all of them.
27
- *
28
- * The loader validates a row's config against the exported `Config` only when that
29
- * export is a native schemastery schema, and the Settings page is discovered from
30
- * that same schema. A profile-installed plugin cannot import `@deepseek-ai/schemastery`
31
- * by bare specifier (the profile's `node_modules` holds no copy), so the schema is
32
- * built from the installation's own module — the same instance the host validates
33
- * with. {@link resolveConfig} stays as the dependency-free normalization used by
34
- * code paths that must not await a module load.
35
- */
36
- export const CONFIG_DEFAULTS = {
37
- subscriptionUrl: '',
38
- node: '',
39
- corePath: '',
40
- mode: 'rule',
41
- autoStart: true,
42
- dnsServers: '',
43
- directDomains: '',
44
- proxyDomains: '',
45
- dataDir: '',
46
- /** How often the plugin re-measures its nodes, in minutes; 0 disables the cycle. */
47
- speedTestMinutes: 30,
48
- /** How many nodes one cycle measures, lowest-index first in the group's order. */
49
- speedTestCount: 8,
50
- }
51
-
52
- /**
53
- * Build the native config schema from the installation's schema library.
54
- *
55
- * @returns the schema, or undefined when the installation cannot be located.
56
- */
57
- async function buildConfigSchema() {
58
- try {
59
- const root = locateInstallRoot(process.argv)
60
- if (root === undefined) return undefined
61
- const { pathToFileURL } = await import('node:url')
62
- const loaded = await import(pathToFileURL(resolveFromInstall(root, '@deepseek-ai/schemastery')).href)
63
- const z = loaded.default ?? loaded
64
- if (typeof z?.object !== 'function') return undefined
65
- return z.object({
66
- subscriptionUrl: z.string().default(''),
67
- node: z.string().default(''),
68
- corePath: z.string().default(''),
69
- mode: z.string().default('rule'),
70
- autoStart: z.boolean().default(true),
71
- dnsServers: z.string().default(''),
72
- directDomains: z.string().default(''),
73
- proxyDomains: z.string().default(''),
74
- dataDir: z.string().default(''),
75
- speedTestMinutes: z.number().default(30),
76
- speedTestCount: z.number().default(8),
77
- })
78
- } catch {
79
- return undefined
80
- }
81
- }
82
-
83
- /** The native schema, or undefined on a host whose installation cannot be found. */
84
- export const Config = await buildConfigSchema()
85
-
86
- /**
87
- * Coerce and validate one raw configuration.
88
- *
89
- * @param raw - the Loader row's `config`, possibly partial or absent.
90
- * @returns a complete, validated configuration.
91
- */
92
- export function resolveConfig(raw) {
93
- const input = raw !== null && typeof raw === 'object' ? raw : {}
94
- const config = { ...CONFIG_DEFAULTS, ...input }
95
- const mode = String(config.mode ?? 'rule').trim().toLowerCase()
96
- config.mode = mode === 'global' ? 'global' : 'rule'
97
- config.autoStart = config.autoStart !== false && config.autoStart !== 'false'
98
- for (const field of ['subscriptionUrl', 'node', 'corePath', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir']) {
99
- config[field] = String(config[field] ?? '').trim()
100
- }
101
- const clamp = (value, min, max, fallback) => {
102
- const numeric = Number(value)
103
- if (!Number.isFinite(numeric)) return fallback
104
- return Math.min(max, Math.max(min, Math.round(numeric)))
105
- }
106
- config.speedTestMinutes = clamp(config.speedTestMinutes, 0, 1440, 30)
107
- config.speedTestCount = clamp(config.speedTestCount, 1, 40, 8)
108
- return config
109
- }
110
-
111
- /**
112
- * Resolve the plugin's data directory.
113
- *
114
- * @param configured - configured directory, possibly empty.
115
- * @returns the absolute directory, created on demand by callers that write.
116
- */
117
- function resolveDataDir(configured) {
118
- if (typeof configured === 'string' && configured.trim() !== '') return configured.trim()
119
- const home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
120
- return join(home, 'data', 'dsh-clash-proxy')
121
- }
122
-
123
- /**
124
- * Everything one activation owns: the core, the routing policy, and the last outcome.
125
- *
126
- * Exported so the measurement policy can be asserted against a stub core, without a
127
- * real process or network.
128
- */
129
- export class Runtime {
130
- constructor(config, logger) {
131
- this.config = config
132
- this.log = logger
133
- this.dataDir = resolveDataDir(config.dataDir)
134
- this.binary = findCoreBinary(config.corePath)
135
- this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger })
136
- this.routing = undefined
137
- this.lastError = undefined
138
- this.lastProbe = undefined
139
- this.measured = new Map()
140
- this.measuredAt = 0
141
- this.timer = undefined
142
- /** Persistence hook, set by `apply` from the config editor; undefined when the profile has none. */
143
- this.editor = undefined
144
- /** Timer factory and context-bound re-arm, installed by `apply`. */
145
- this.schedule = undefined
146
- this.rearm = undefined
147
- }
148
-
149
- /**
150
- * Measure node latency, merging into the results already known.
151
- *
152
- * Three modes matter here and the first version conflated them, which made the panel
153
- * report two thirds of a subscription as unreachable:
154
- *
155
- * - the cycle measures `speedTestCount` nodes so a long subscription stays affordable;
156
- * - `only` measures one named node, which is what the panel's per-row test does;
157
- * - `all` measures every node and is only used when the user explicitly asks.
158
- *
159
- * Results accumulate instead of replacing: a node measured in an earlier pass keeps
160
- * its latency, so the panel distinguishes "not measured yet" from "measured and dead"
161
- * instead of painting both as unreachable.
162
- *
163
- * @param options - `force` ignores the cache window; `only` restricts to one node;
164
- * `all` measures every node.
165
- * @returns node name to delay in milliseconds, or null when it did not answer. A node
166
- * absent from the map has not been measured.
167
- */
168
- async nodeDelays(options = {}) {
169
- if (this.core === undefined || !this.core.running) return {}
170
- const forced = options.force === true || options.only !== undefined || options.all === true
171
- const fresh = Date.now() - this.measuredAt < this.config.speedTestMinutes * 60_000
172
- if (!forced && fresh && this.measured.size > 0) return Object.fromEntries(this.measured)
173
-
174
- const group = await this.core.group()
175
- const available = group.all.filter((entry) => entry !== 'DIRECT')
176
- let candidates
177
- if (options.only !== undefined) {
178
- const only = String(options.only).trim()
179
- candidates = available.includes(only) ? [only] : []
180
- } else if (options.all === true) {
181
- candidates = available
182
- } else {
183
- // Prefer nodes with no measurement yet, so repeated cycles eventually cover the
184
- // whole subscription instead of re-testing the same first N forever.
185
- const unmeasured = available.filter((name) => !this.measured.has(name))
186
- const pool = unmeasured.length > 0 ? unmeasured : available
187
- candidates = pool.slice(0, this.config.speedTestCount)
188
- }
189
-
190
- const measured = new Map(this.measured)
191
- const batchSize = 5
192
- for (let at = 0; at < candidates.length; at += batchSize) {
193
- const batch = candidates.slice(at, at + batchSize)
194
- const answers = await Promise.all(
195
- batch.map(async (name) => ({ name, delay: await this.core.delay(name, 5000) })),
196
- )
197
- for (const answer of answers) measured.set(answer.name, answer.delay)
198
- }
199
- this.measured = measured
200
- this.measuredAt = Date.now()
201
- return Object.fromEntries(measured)
202
- }
203
-
204
- /** Record a node the user picked, so a restart keeps it without a config edit. */
205
- rememberNode(name) {
206
- this.config.node = name
207
- }
208
-
209
- /** The configuration a page may read, with the subscription token masked. */
210
- publicConfig() {
211
- return {
212
- subscriptionUrl: this.config.subscriptionUrl,
213
- effectiveSubscriptionUrl: maskToken(this.subscriptionUrl),
214
- node: this.config.node,
215
- mode: this.config.mode,
216
- autoStart: this.config.autoStart,
217
- speedTestMinutes: this.config.speedTestMinutes,
218
- speedTestCount: this.config.speedTestCount,
219
- directDomains: this.config.directDomains,
220
- proxyDomains: this.config.proxyDomains,
221
- dnsServers: this.config.dnsServers,
222
- corePath: this.config.corePath,
223
- source: 'configured',
224
- }
225
- }
226
-
227
- /**
228
- * Persist a configuration change and apply it.
229
- *
230
- * The write goes through the config editor, which owns the profile patch: a plugin
231
- * that rewrote that file itself would drop other plugins' rows and comments. When
232
- * the editor is unavailable the change still applies to this process and the answer
233
- * says so, rather than reporting a save that did not happen.
234
- *
235
- * @param patch - field subset already validated by the caller.
236
- * @returns the applied configuration and any warning about persistence.
237
- */
238
- async saveConfig(patch) {
239
- const previous = this.config
240
- const next = resolveConfig({ ...previous, ...patch })
241
- const changedCore = ['subscriptionUrl', 'mode', 'dnsServers', 'directDomains', 'proxyDomains', 'corePath'].some(
242
- (key) => next[key] !== previous[key],
243
- )
244
- this.config = next
245
-
246
- const warnings = []
247
- const editor = this.editor
248
- if (editor === undefined) {
249
- warnings.push('not persisted: the profile has no config editor, so this applies until the Harness restarts')
250
- } else {
251
- try {
252
- await editor(patch)
253
- } catch (error) {
254
- warnings.push(`not persisted: ${error?.message ?? error}`)
255
- }
256
- }
257
-
258
- // A routing-relevant change needs the core restarted; a node or timing change does
259
- // not, because the group selection and the measurement cycle read live values.
260
- if (changedCore && this.core?.running === true) {
261
- try {
262
- await this.start()
263
- } catch (error) {
264
- warnings.push(`routing was not restarted: ${error?.message ?? error}`)
265
- }
266
- }
267
- if (next.speedTestMinutes !== previous.speedTestMinutes) this.requestRearm()
268
- return { config: this.publicConfig(), warnings }
269
- }
270
-
271
- /**
272
- * Restart the measurement cycle from the current configuration.
273
- *
274
- * The interval factory must run in the plugin's own context: a request handler runs
275
- * in a different fiber, and calling into the timer service from there throws
276
- * "cannot get required service in inactive context". So this only ever runs from a
277
- * callback the plugin registered itself.
278
- *
279
- * @param schedule - timer factory from the plugin context.
280
- */
281
- scheduleSpeedTest(schedule) {
282
- if (this.timer !== undefined) this.timer()
283
- this.timer = undefined
284
- const minutes = this.config.speedTestMinutes
285
- if (minutes <= 0 || typeof schedule !== 'function') return
286
- this.timer = schedule(() => {
287
- void this.nodeDelays({ force: true }).catch((error) => {
288
- this.log(`speed test failed: ${error?.message ?? error}`)
289
- })
290
- }, minutes * 60_000)
291
- }
292
-
293
- /**
294
- * Re-arm the cycle after a configuration change.
295
- *
296
- * Called from a request handler, so it cannot touch the timer service itself; it
297
- * defers to `rearm`, a function the plugin context installed and that hops back into
298
- * its own fiber through the host's effect boundary.
299
- */
300
- requestRearm() {
301
- if (typeof this.rearm === 'function') this.rearm()
302
- }
303
-
304
- /**
305
- * Probe one subscription URL without changing any state.
306
- *
307
- * @param raw - the URL to probe, as typed in the form.
308
- * @returns a result the form renders as a hint.
309
- */
310
- async probe(raw) {
311
- const text = String(raw ?? '').trim()
312
- if (text === '') return { ok: false, error: 'subscription URL is empty' }
313
- let url
314
- try {
315
- url = normalizeSubscriptionUrl(text)
316
- } catch (error) {
317
- return { ok: false, error: String(error?.message ?? error) }
318
- }
319
- try {
320
- const result = await probeSubscription(url, { timeoutMs: 15_000 })
321
- return {
322
- ok: result.ok,
323
- status: result.status,
324
- format: result.format,
325
- nodeCount: result.nodeCount,
326
- bytes: result.bytes,
327
- url: maskToken(url),
328
- error: result.ok ? undefined : `the server answered ${result.status}`,
329
- }
330
- } catch (error) {
331
- // The probe runs through whatever policy is installed, so a failure here may
332
- // mean "not routed yet" rather than "wrong URL"; say which.
333
- return { ok: false, error: `probe failed: ${String(error?.message ?? error)}` }
334
- }
335
- }
336
-
337
- /** The subscription to use. There is no fallback: an empty value means unconfigured. */
338
- get subscriptionUrl() {
339
- return String(this.config.subscriptionUrl ?? '').trim()
340
- }
341
-
342
- /** The node preference, empty when the user has not chosen one. */
343
- get preferredNode() {
344
- return String(this.config.node ?? '').trim()
345
- }
346
-
347
- /** A one-line reason the runtime cannot start, or undefined when it can. */
348
- get blocker() {
349
- if (this.binary === undefined) {
350
- return 'no mihomo core binary found: install Clash Verge or set corePath to a mihomo/clash executable'
351
- }
352
- if (this.subscriptionUrl === '') {
353
- return 'no subscription: paste a subscription URL in Settings → Clash proxy'
354
- }
355
- return undefined
356
- }
357
-
358
- /** Load the shared policy module once, from the installation the host runs from. */
359
- async ensurePolicyModule() {
360
- if (this.routing !== undefined) return this.routing
361
- const root = locateInstallRoot(process.argv)
362
- if (root === undefined) throw new Error('cannot locate the dsh installation root from the process arguments')
363
- const proxyModule = await loadHttpProxyModule(root)
364
- const undiciPath = resolveFromInstall(root, 'undici')
365
- this.log(`policy module from ${root} (${installName(root) ?? 'unnamed'})`)
366
- this.routing = new Routing({ proxyModule, undiciPath, logger: this.log })
367
- return this.routing
368
- }
369
-
370
- /**
371
- * Import the subscription and bring routing up.
372
- *
373
- * @param options - overrides for one start, e.g. a newly pasted URL.
374
- * @returns the start report.
375
- */
376
- async start(options = {}) {
377
- mkdirSync(this.dataDir, { recursive: true })
378
- const blocker = this.blocker
379
- if (blocker !== undefined) throw new Error(blocker)
380
-
381
- const url = normalizeSubscriptionUrl(options.subscriptionUrl ?? this.subscriptionUrl)
382
-
383
- const routing = await this.ensurePolicyModule()
384
- const endpoint = await this.core.start({
385
- subscriptionUrl: url,
386
- mode: this.config.mode,
387
- dnsServers: splitList(this.config.dnsServers),
388
- directDomains: this.config.directDomains,
389
- proxyDomains: this.config.proxyDomains,
390
- // No geo directories are passed: the core's own data directory is authoritative,
391
- // and discovery supplies a machine-level fallback only when that copy is absent.
392
- })
393
- const variables = await routing.apply(endpoint.host, endpoint.port)
394
-
395
- // The probe runs after routing is up on purpose: a subscription host is often
396
- // itself blocked, so probing first would report a 403 that says nothing about the
397
- // subscription. The core re-fetches the same URL through its own provider anyway.
398
- this.lastProbe = await probeSubscription(url).catch((error) => ({
399
- status: 0,
400
- ok: false,
401
- bytes: 0,
402
- format: 'unreachable',
403
- nodeCount: 0,
404
- error: String(error?.message ?? error),
405
- }))
406
-
407
- // The provider downloads in the background right after boot; give it a moment so
408
- // the first status report carries a node table instead of an empty group.
409
- const group = await this.waitForNodes()
410
- const preferred = String(options.node ?? this.preferredNode ?? '').trim()
411
- // A fresh group starts on DIRECT, which would route foreign traffic straight out.
412
- // Selecting a real node is part of bringing routing up, not an optional extra.
413
- const selected = group.all.some((entry) => entry !== 'DIRECT')
414
- ? await this.core.autoSelect(preferred).catch(() => undefined)
415
- : undefined
416
- this.lastError = undefined
417
- return {
418
- endpoint: `http://${endpoint.host}:${endpoint.port}`,
419
- geo: endpoint.geo,
420
- group: await this.core.group(),
421
- selected,
422
- variables,
423
- probe: this.lastProbe,
424
- configPath: this.core.configPath,
425
- }
426
- }
427
-
428
- /**
429
- * Poll the group until the subscription provider contributes at least one node.
430
- *
431
- * @returns the group snapshot, even when it stayed empty.
432
- */
433
- async waitForNodes() {
434
- const deadline = Date.now() + 20_000
435
- let group = await this.core.group()
436
- while (group.all.length <= 1 && Date.now() < deadline) {
437
- await new Promise((resolve) => setTimeout(resolve, 500))
438
- group = await this.core.group()
439
- }
440
- return group
441
- }
442
-
443
- /** Stop the measurement cycle. Safe to call when none is running. */
444
- stopTimer() {
445
- if (this.timer === undefined) return
446
- this.timer()
447
- this.timer = undefined
448
- }
449
-
450
- /** Stop routing first, so nothing is sent to a port that is about to close. */
451
- async stop() {
452
- if (this.routing !== undefined) await this.routing.releaseToDirect()
453
- if (this.core !== undefined) await this.core.stop()
454
- }
455
-
456
- /** The status the model and the panel both read. */
457
- async status() {
458
- const running = this.core?.running === true
459
- const group = running ? await this.core.group().catch(() => ({ all: [], now: undefined })) : { all: [], now: undefined }
460
- const provider = running ? await this.core.providerStatus() : { updatedAt: null, vehicleType: null }
461
- const traffic = running ? await this.core.connections().catch(() => undefined) : undefined
462
- const policy = this.routing === undefined ? { state: 'none' } : await this.routing.verify()
463
- return {
464
- binary: this.binary,
465
- dataDir: this.dataDir,
466
- running,
467
- endpoint: running ? `http://127.0.0.1:${this.core.mixedPort}` : undefined,
468
- routing: this.routing?.active === true,
469
- /** Whether the installed dispatcher is really this plugin's — see Routing#verify. */
470
- routingVerified: policy.state,
471
- endpointEnvironment: this.routing?.endpoint,
472
- childEnvironment: this.routing?.childOverlay() ?? {},
473
- node: group.now,
474
- nodeCount: Math.max(0, group.all.length - 1),
475
- nodes: group.all.filter((entry) => entry !== 'DIRECT').slice(0, 40),
476
- provider,
477
- traffic,
478
- blocker: this.blocker,
479
- lastError: this.lastError ?? this.core?.lastError,
480
- probe: this.lastProbe,
481
- delays: Object.fromEntries(this.measured),
482
- measuredAt: this.measuredAt === 0 ? null : new Date(this.measuredAt).toISOString(),
483
- source: 'configured',
484
- }
485
- }
486
- }
487
-
488
- /**
489
- * Mount the plugin.
490
- *
491
- * @param ctx - registrant context; `tools` is injected.
492
- * @param rawConfig - the Loader row's configuration.
493
- */
494
- export async function apply(ctx, rawConfig) {
495
- const config = resolveConfig(rawConfig)
496
- const log = (message) => ctx.logger?.info?.(`[clash-proxy] ${message}`) ?? undefined
497
- const runtime = new Runtime(config, log)
498
-
499
- ctx.effect(() => () => {
500
- runtime.stopTimer()
501
- void runtime.stop()
502
- })
503
-
504
- // Persistence rides the config editor, which keeps the rest of the profile patch
505
- // intact. A profile without one still works: the change applies to this process and
506
- // the save answer reports that it was not written.
507
- ctx.inject(['configEditor'], (editorCtx) => {
508
- editorCtx.effect(() => {
509
- const editor = editorCtx.get('configEditor')
510
- const entry = editorCtx.fiber?.entry
511
- if (editor === undefined || entry === undefined) return () => {}
512
- runtime.editor = async (patch) => {
513
- await editor.edit(entry, (current) => ({ ...current, ...patch }))
514
- }
515
- return () => {
516
- runtime.editor = undefined
517
- }
518
- }, 'clash-proxy: config persistence')
519
- })
520
-
521
- // The measurement cycle rides the host timer service, so it is disposed with the
522
- // plugin and repeated plugin reloads never stack timers. `rearm` is published here,
523
- // in plugin context, for the request handler that saves a new interval to call: it
524
- // re-enters this context instead of touching the timer service from a foreign fiber.
525
- ctx.inject(['timer'], (timerCtx) => {
526
- timerCtx.effect(() => {
527
- const schedule = (callback, delay) => timerCtx.timer.interval(callback, delay)
528
- runtime.schedule = schedule
529
- runtime.rearm = () => runtime.scheduleSpeedTest(schedule)
530
- runtime.scheduleSpeedTest(schedule)
531
- return () => {
532
- runtime.rearm = undefined
533
- runtime.stopTimer()
534
- }
535
- }, 'clash-proxy: speed test cycle')
536
- })
537
-
538
- if (config.autoStart === true && runtime.blocker === undefined) {
539
- // Boot in the background: a slow subscription must not delay the Harness' own startup.
540
- void runtime.start().catch((error) => {
541
- runtime.lastError = String(error?.message ?? error)
542
- log(`auto start failed: ${runtime.lastError}`)
543
- })
544
- } else if (config.autoStart === true) {
545
- log(`auto start skipped: ${runtime.blocker}`)
546
- }
547
-
548
- // Panel routes ride a `webServer` sub-fiber rather than a one-shot `ctx.get`:
549
- // loader entries settle concurrently, so reading the service at apply time would
550
- // silently skip the mount whenever the web server activates after this plugin.
551
- ctx.inject(['webServer'], (webCtx) => {
552
- webCtx.effect(() => {
553
- const webServer = webCtx.get('webServer')
554
- if (webServer === undefined) return () => {}
555
- const disposers = mountRoutes(webServer, runtime, log)
556
- return () => {
557
- for (const dispose of disposers) dispose()
558
- }
559
- }, 'clash-proxy: panel routes')
560
- })
561
-
562
- ctx.tools.register(subscriptionTool(runtime))
563
- }
564
-
565
- /**
566
- * The single model-facing tool: one action word per operation.
567
- *
568
- * @param runtime - the activation's runtime.
569
- * @returns the raw tool definition.
570
- */
571
- function subscriptionTool(runtime) {
572
- return {
573
- name: 'clash_proxy',
574
- description: [
575
- 'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and a user-imported subscription.',
576
- '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.',
577
- 'action=status reports the core, the installed policy, the node table and live traffic.',
578
- '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.',
579
- 'action=start brings routing up on the configured subscription; action=stop takes it down and restores direct connections.',
580
- '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.',
581
- ].join(' '),
582
- parameters: {
583
- type: 'object',
584
- properties: {
585
- action: {
586
- type: 'string',
587
- enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh'],
588
- 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.',
589
- },
590
- url: { type: 'string', description: 'Subscription URL for action=import (raw https:// or clash://install-config?url=…).' },
591
- node: { type: 'string', description: 'Exact node name for action=select or action=test; omit to use the current selection.' },
592
- },
593
- required: ['action'],
594
- },
595
- output: {
596
- schema: { type: 'object' },
597
- render(_args, value) {
598
- return [{ type: 'text', text: String(value?.summary ?? JSON.stringify(value)) }]
599
- },
600
- },
601
- timeoutMs: 120_000,
602
- async execute(args) {
603
- const action = String(args?.action ?? 'status')
604
- try {
605
- if (action === 'status') {
606
- const status = await runtime.status()
607
- return { ...status, summary: describeStatus(status) }
608
- }
609
- if (action === 'stop') {
610
- await runtime.stop()
611
- const status = await runtime.status()
612
- return { ...status, summary: '代理已停止,所有外网请求恢复直连。' }
613
- }
614
- if (action === 'import') {
615
- const url = String(args?.url ?? '').trim()
616
- if (url === '') throw new Error('action=import needs a url')
617
- runtime.config.subscriptionUrl = url
618
- const report = await runtime.start({ subscriptionUrl: url })
619
- return {
620
- ...report,
621
- summary: [
622
- `订阅已导入:${report.probe.format},${report.probe.nodeCount} 个节点,${report.probe.bytes} 字节。`,
623
- `内核 ${report.endpoint},当前节点「${report.group.now ?? '未选择'}」。`,
624
- `策略已安装,外网走代理、国内直连。`,
625
- ].join('\n'),
626
- }
627
- }
628
- if (action === 'start') {
629
- const report = await runtime.start()
630
- return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
631
- }
632
- if (action === 'select') {
633
- const node = String(args?.node ?? '').trim()
634
- if (node === '') throw new Error('action=select needs a node name')
635
- const group = await runtime.core.select(node)
636
- return { group, summary: `已切换到「${group.now}」。` }
637
- }
638
- if (action === 'test') {
639
- const target = String(args?.node ?? '').trim()
640
- if (target !== '') {
641
- const delay = await runtime.core.delay(target)
642
- return { node: target, delay, summary: delay === null ? `「${target}」测速失败。` : `「${target}」延迟 ${delay} ms。` }
643
- }
644
- const status = await runtime.status()
645
- if (status.node === undefined) throw new Error('no node selected')
646
- const delay = await runtime.core.delay(status.node)
647
- return { node: status.node, delay, summary: delay === null ? `「${status.node}」测速失败。` : `「${status.node}」延迟 ${delay} ms。` }
648
- }
649
- if (action === 'refresh') {
650
- const provider = await runtime.core.updateProvider()
651
- const group = await runtime.core.group()
652
- return { provider, group, summary: `订阅已刷新:${group.all.length - 1} 个节点。` }
653
- }
654
- throw new Error(`unknown action "${action}"`)
655
- } catch (error) {
656
- runtime.lastError = String(error?.message ?? error)
657
- return { error: runtime.lastError, summary: `clash_proxy ${action} 失败:${runtime.lastError}` }
658
- }
659
- },
660
- }
661
- }
662
-
663
- /**
664
- * Compose the human-readable status line.
665
- *
666
- * @param status - the status object.
667
- * @returns the summary text.
668
- */
669
- function describeStatus(status) {
670
- if (status.blocker !== undefined) return `未运行:${status.blocker}`
671
- const lines = [
672
- `内核:${status.running ? `运行中 ${status.endpoint}` : '未运行'}${status.binary === undefined ? '(未找到二进制)' : ''}`,
673
- `出网策略:${status.routing ? `已安装 → ${status.endpointEnvironment}` : '未安装(直连)'}`,
674
- `当前节点:${status.node ?? '未选择'}(可选 ${status.nodeCount} 个)`,
675
- ]
676
- if (status.lastError !== undefined) lines.push(`最近错误:${status.lastError}`)
677
- return lines.join('\n')
678
- }
1
+ export const probe = true