dsh-clash-subscription 0.2.3 → 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,710 +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
- /** Resolved once: the answer cannot change mid-process, and a stable value keeps
135
- * `blocker` and `ensurePolicyModule` from disagreeing. */
136
- this.installRoot = locateInstallRoot(process.argv)
137
- this.binary = findCoreBinary(config.corePath)
138
- this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger })
139
- this.routing = undefined
140
- this.lastError = undefined
141
- this.lastProbe = undefined
142
- this.measured = new Map()
143
- this.measuredAt = 0
144
- this.timer = undefined
145
- /** Persistence hook, set by `apply` from the config editor; undefined when the profile has none. */
146
- this.editor = undefined
147
- /** Timer factory and context-bound re-arm, installed by `apply`. */
148
- this.schedule = undefined
149
- this.rearm = undefined
150
- }
151
-
152
- /**
153
- * Measure node latency, merging into the results already known.
154
- *
155
- * Three modes matter here and the first version conflated them, which made the panel
156
- * report two thirds of a subscription as unreachable:
157
- *
158
- * - the cycle measures `speedTestCount` nodes so a long subscription stays affordable;
159
- * - `only` measures one named node, which is what the panel's per-row test does;
160
- * - `all` measures every node and is only used when the user explicitly asks.
161
- *
162
- * Results accumulate instead of replacing: a node measured in an earlier pass keeps
163
- * its latency, so the panel distinguishes "not measured yet" from "measured and dead"
164
- * instead of painting both as unreachable.
165
- *
166
- * @param options - `force` ignores the cache window; `only` restricts to one node;
167
- * `all` measures every node.
168
- * @returns node name to delay in milliseconds, or null when it did not answer. A node
169
- * absent from the map has not been measured.
170
- */
171
- async nodeDelays(options = {}) {
172
- if (this.core === undefined || !this.core.running) return {}
173
- const forced = options.force === true || options.only !== undefined || options.all === true
174
- const fresh = Date.now() - this.measuredAt < this.config.speedTestMinutes * 60_000
175
- if (!forced && fresh && this.measured.size > 0) return Object.fromEntries(this.measured)
176
-
177
- const group = await this.core.group()
178
- const available = group.all.filter((entry) => entry !== 'DIRECT')
179
- let candidates
180
- if (options.only !== undefined) {
181
- const only = String(options.only).trim()
182
- candidates = available.includes(only) ? [only] : []
183
- } else if (options.all === true) {
184
- candidates = available
185
- } else {
186
- // Prefer nodes with no measurement yet, so repeated cycles eventually cover the
187
- // whole subscription instead of re-testing the same first N forever.
188
- const unmeasured = available.filter((name) => !this.measured.has(name))
189
- const pool = unmeasured.length > 0 ? unmeasured : available
190
- candidates = pool.slice(0, this.config.speedTestCount)
191
- }
192
-
193
- const measured = new Map(this.measured)
194
- const batchSize = 5
195
- for (let at = 0; at < candidates.length; at += batchSize) {
196
- const batch = candidates.slice(at, at + batchSize)
197
- const answers = await Promise.all(
198
- batch.map(async (name) => ({ name, delay: await this.core.delay(name, 5000) })),
199
- )
200
- for (const answer of answers) measured.set(answer.name, answer.delay)
201
- }
202
- this.measured = measured
203
- this.measuredAt = Date.now()
204
- return Object.fromEntries(measured)
205
- }
206
-
207
- /** Record a node the user picked, so a restart keeps it without a config edit. */
208
- rememberNode(name) {
209
- this.config.node = name
210
- }
211
-
212
- /** The configuration a page may read, with the subscription token masked. */
213
- publicConfig() {
214
- return {
215
- subscriptionUrl: this.config.subscriptionUrl,
216
- effectiveSubscriptionUrl: maskToken(this.subscriptionUrl),
217
- node: this.config.node,
218
- mode: this.config.mode,
219
- autoStart: this.config.autoStart,
220
- speedTestMinutes: this.config.speedTestMinutes,
221
- speedTestCount: this.config.speedTestCount,
222
- directDomains: this.config.directDomains,
223
- proxyDomains: this.config.proxyDomains,
224
- dnsServers: this.config.dnsServers,
225
- corePath: this.config.corePath,
226
- source: 'configured',
227
- }
228
- }
229
-
230
- /**
231
- * Persist a configuration change and apply it.
232
- *
233
- * The write goes through the config editor, which owns the profile patch: a plugin
234
- * that rewrote that file itself would drop other plugins' rows and comments. When
235
- * the editor is unavailable the change still applies to this process and the answer
236
- * says so, rather than reporting a save that did not happen.
237
- *
238
- * @param patch - field subset already validated by the caller.
239
- * @returns the applied configuration and any warning about persistence.
240
- */
241
- async saveConfig(patch) {
242
- const previous = this.config
243
- const next = resolveConfig({ ...previous, ...patch })
244
- const changedCore = ['subscriptionUrl', 'mode', 'dnsServers', 'directDomains', 'proxyDomains', 'corePath'].some(
245
- (key) => next[key] !== previous[key],
246
- )
247
- this.config = next
248
-
249
- const warnings = []
250
- const editor = this.editor
251
- if (editor === undefined) {
252
- warnings.push('not persisted: the profile has no config editor, so this applies until the Harness restarts')
253
- } else {
254
- try {
255
- await editor(patch)
256
- } catch (error) {
257
- warnings.push(`not persisted: ${error?.message ?? error}`)
258
- }
259
- }
260
-
261
- // A routing-relevant change needs the core restarted; a node or timing change does
262
- // not, because the group selection and the measurement cycle read live values.
263
- if (changedCore && this.core?.running === true) {
264
- try {
265
- await this.start()
266
- } catch (error) {
267
- warnings.push(`routing was not restarted: ${error?.message ?? error}`)
268
- }
269
- }
270
- if (next.speedTestMinutes !== previous.speedTestMinutes) this.requestRearm()
271
- return { config: this.publicConfig(), warnings }
272
- }
273
-
274
- /**
275
- * Restart the measurement cycle from the current configuration.
276
- *
277
- * The interval factory must run in the plugin's own context: a request handler runs
278
- * in a different fiber, and calling into the timer service from there throws
279
- * "cannot get required service in inactive context". So this only ever runs from a
280
- * callback the plugin registered itself.
281
- *
282
- * @param schedule - timer factory from the plugin context.
283
- */
284
- scheduleSpeedTest(schedule) {
285
- if (this.timer !== undefined) this.timer()
286
- this.timer = undefined
287
- const minutes = this.config.speedTestMinutes
288
- if (minutes <= 0 || typeof schedule !== 'function') return
289
- this.timer = schedule(() => {
290
- void this.nodeDelays({ force: true }).catch((error) => {
291
- this.log(`speed test failed: ${error?.message ?? error}`)
292
- })
293
- }, minutes * 60_000)
294
- }
295
-
296
- /**
297
- * Re-arm the cycle after a configuration change.
298
- *
299
- * Called from a request handler, so it cannot touch the timer service itself; it
300
- * defers to `rearm`, a function the plugin context installed and that hops back into
301
- * its own fiber through the host's effect boundary.
302
- */
303
- requestRearm() {
304
- if (typeof this.rearm === 'function') this.rearm()
305
- }
306
-
307
- /**
308
- * Probe one subscription URL without changing any state.
309
- *
310
- * @param raw - the URL to probe, as typed in the form.
311
- * @returns a result the form renders as a hint.
312
- */
313
- async probe(raw) {
314
- const text = String(raw ?? '').trim()
315
- 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) }
321
- }
322
- try {
323
- const result = await probeSubscription(url, { timeoutMs: 15_000 })
324
- 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}`,
332
- }
333
- } catch (error) {
334
- // The probe runs through whatever policy is installed, so a failure here may
335
- // mean "not routed yet" rather than "wrong URL"; say which.
336
- return { ok: false, error: `probe failed: ${String(error?.message ?? error)}` }
337
- }
338
- }
339
-
340
- /** The subscription to use. There is no fallback: an empty value means unconfigured. */
341
- get subscriptionUrl() {
342
- return String(this.config.subscriptionUrl ?? '').trim()
343
- }
344
-
345
- /** The node preference, empty when the user has not chosen one. */
346
- get preferredNode() {
347
- return String(this.config.node ?? '').trim()
348
- }
349
-
350
- /**
351
- * A one-line reason the runtime cannot start, or undefined when it can.
352
- *
353
- * The installation root is part of this list on purpose. The first release omitted it,
354
- * so a packaged build whose layout the locator did not recognise kept `autoStart`
355
- * firing on every boot and failing at the same throw — with `blocker` still reporting
356
- * "ready" and the panel showing nothing but a stale lastError.
357
- */
358
- 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
- }
362
- if (this.installRoot === undefined) {
363
- 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
- }
365
- if (this.subscriptionUrl === '') {
366
- return 'no subscription: paste a subscription URL in Settings → Clash proxy'
367
- }
368
- return undefined
369
- }
370
-
371
- /**
372
- * Load the shared policy module once, from the installation the host runs from.
373
- *
374
- * Resolution order lives in `lib/install.js`: an explicit environment variable, then
375
- * the process arguments, then the executable path, then well-known positions beside
376
- * the executable. A failure here is fatal for routing, so the message names the
377
- * executable and the variable that fixes it rather than repeating "from the process
378
- * arguments" — which was the only hint the first release offered, and it was wrong for
379
- * every packaged build.
380
- */
381
- async ensurePolicyModule() {
382
- if (this.routing !== undefined) return this.routing
383
- const root = this.installRoot
384
- if (root === undefined) {
385
- throw new Error(
386
- `cannot locate the dsh installation root: no known layout matched process.argv or ${process.execPath}; set DSH_INSTALL_ROOT to the directory holding the dsh package.json`,
387
- )
388
- }
389
- const proxyModule = await loadHttpProxyModule(root)
390
- const undiciPath = resolveFromInstall(root, 'undici')
391
- this.log(`policy module from ${root} (${installName(root) ?? 'unnamed'})`)
392
- this.routing = new Routing({ proxyModule, undiciPath, logger: this.log })
393
- return this.routing
394
- }
395
-
396
- /**
397
- * Import the subscription and bring routing up.
398
- *
399
- * @param options - overrides for one start, e.g. a newly pasted URL.
400
- * @returns the start report.
401
- */
402
- async start(options = {}) {
403
- mkdirSync(this.dataDir, { recursive: true })
404
- const blocker = this.blocker
405
- if (blocker !== undefined) throw new Error(blocker)
406
-
407
- const url = normalizeSubscriptionUrl(options.subscriptionUrl ?? this.subscriptionUrl)
408
-
409
- const routing = await this.ensurePolicyModule()
410
- const endpoint = await this.core.start({
411
- subscriptionUrl: url,
412
- mode: this.config.mode,
413
- dnsServers: splitList(this.config.dnsServers),
414
- directDomains: this.config.directDomains,
415
- proxyDomains: this.config.proxyDomains,
416
- // No geo directories are passed: the core's own data directory is authoritative,
417
- // and discovery supplies a machine-level fallback only when that copy is absent.
418
- })
419
- const variables = await routing.apply(endpoint.host, endpoint.port)
420
-
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
- }))
432
-
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
- const preferred = String(options.node ?? this.preferredNode ?? '').trim()
437
- // A fresh group starts on DIRECT, which would route foreign traffic straight out.
438
- // Selecting a real node is part of bringing routing up, not an optional extra.
439
- const selected = group.all.some((entry) => entry !== 'DIRECT')
440
- ? await this.core.autoSelect(preferred).catch(() => undefined)
441
- : undefined
442
- this.lastError = undefined
443
- return {
444
- endpoint: `http://${endpoint.host}:${endpoint.port}`,
445
- geo: endpoint.geo,
446
- group: await this.core.group(),
447
- selected,
448
- variables,
449
- probe: this.lastProbe,
450
- configPath: this.core.configPath,
451
- }
452
- }
453
-
454
- /**
455
- * Poll the group until the subscription provider contributes at least one node.
456
- *
457
- * @returns the group snapshot, even when it stayed empty.
458
- */
459
- async waitForNodes() {
460
- const deadline = Date.now() + 20_000
461
- let group = await this.core.group()
462
- while (group.all.length <= 1 && Date.now() < deadline) {
463
- await new Promise((resolve) => setTimeout(resolve, 500))
464
- group = await this.core.group()
465
- }
466
- return group
467
- }
468
-
469
- /** Stop the measurement cycle. Safe to call when none is running. */
470
- stopTimer() {
471
- if (this.timer === undefined) return
472
- this.timer()
473
- this.timer = undefined
474
- }
475
-
476
- /** Stop routing first, so nothing is sent to a port that is about to close. */
477
- async stop() {
478
- if (this.routing !== undefined) await this.routing.releaseToDirect()
479
- if (this.core !== undefined) await this.core.stop()
480
- }
481
-
482
- /** The status the model and the panel both read. */
483
- async status() {
484
- const running = this.core?.running === true
485
- 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 }
487
- const traffic = running ? await this.core.connections().catch(() => undefined) : undefined
488
- const policy = this.routing === undefined ? { state: 'none' } : await this.routing.verify()
489
- return {
490
- binary: this.binary,
491
- dataDir: this.dataDir,
492
- running,
493
- endpoint: running ? `http://127.0.0.1:${this.core.mixedPort}` : undefined,
494
- routing: this.routing?.active === true,
495
- /** Whether the installed dispatcher is really this plugin's — see Routing#verify. */
496
- routingVerified: policy.state,
497
- endpointEnvironment: this.routing?.endpoint,
498
- childEnvironment: this.routing?.childOverlay() ?? {},
499
- node: group.now,
500
- nodeCount: Math.max(0, group.all.length - 1),
501
- nodes: group.all.filter((entry) => entry !== 'DIRECT').slice(0, 40),
502
- provider,
503
- traffic,
504
- blocker: this.blocker,
505
- lastError: this.lastError ?? this.core?.lastError,
506
- probe: this.lastProbe,
507
- delays: Object.fromEntries(this.measured),
508
- measuredAt: this.measuredAt === 0 ? null : new Date(this.measuredAt).toISOString(),
509
- source: 'configured',
510
- }
511
- }
512
- }
513
-
514
- /**
515
- * Mount the plugin.
516
- *
517
- * @param ctx - registrant context; `tools` is injected.
518
- * @param rawConfig - the Loader row's configuration.
519
- */
520
- export async function apply(ctx, rawConfig) {
521
- const config = resolveConfig(rawConfig)
522
- const log = (message) => ctx.logger?.info?.(`[clash-proxy] ${message}`) ?? undefined
523
- const runtime = new Runtime(config, log)
524
-
525
- ctx.effect(() => () => {
526
- runtime.stopTimer()
527
- void runtime.stop()
528
- })
529
-
530
- // Persistence rides the config editor, which keeps the rest of the profile patch
531
- // intact. A profile without one still works: the change applies to this process and
532
- // the save answer reports that it was not written.
533
- ctx.inject(['configEditor'], (editorCtx) => {
534
- editorCtx.effect(() => {
535
- const editor = editorCtx.get('configEditor')
536
- const entry = editorCtx.fiber?.entry
537
- if (editor === undefined || entry === undefined) return () => {}
538
- runtime.editor = async (patch) => {
539
- await editor.edit(entry, (current) => ({ ...current, ...patch }))
540
- }
541
- return () => {
542
- runtime.editor = undefined
543
- }
544
- }, 'clash-proxy: config persistence')
545
- })
546
-
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.
551
- ctx.inject(['timer'], (timerCtx) => {
552
- timerCtx.effect(() => {
553
- const schedule = (callback, delay) => timerCtx.timer.interval(callback, delay)
554
- runtime.schedule = schedule
555
- runtime.rearm = () => runtime.scheduleSpeedTest(schedule)
556
- runtime.scheduleSpeedTest(schedule)
557
- return () => {
558
- runtime.rearm = undefined
559
- runtime.stopTimer()
560
- }
561
- }, 'clash-proxy: speed test cycle')
562
- })
563
-
564
- if (runtime.installRoot === undefined) {
565
- // Say it once, at load: everything downstream (the panel, routing, the tool) needs
566
- // this root, and a silent failure here is indistinguishable from "not configured".
567
- log(`outbound policy unavailable: ${runtime.blocker}`)
568
- }
569
-
570
- if (config.autoStart === true && runtime.blocker === undefined) {
571
- // Boot in the background: a slow subscription must not delay the Harness' own startup.
572
- void runtime.start().catch((error) => {
573
- runtime.lastError = String(error?.message ?? error)
574
- log(`auto start failed: ${runtime.lastError}`)
575
- })
576
- } else if (config.autoStart === true) {
577
- log(`auto start skipped: ${runtime.blocker}`)
578
- }
579
-
580
- // Panel routes ride a `webServer` sub-fiber rather than a one-shot `ctx.get`:
581
- // loader entries settle concurrently, so reading the service at apply time would
582
- // silently skip the mount whenever the web server activates after this plugin.
583
- ctx.inject(['webServer'], (webCtx) => {
584
- webCtx.effect(() => {
585
- const webServer = webCtx.get('webServer')
586
- if (webServer === undefined) return () => {}
587
- const disposers = mountRoutes(webServer, runtime, log)
588
- return () => {
589
- for (const dispose of disposers) dispose()
590
- }
591
- }, 'clash-proxy: panel routes')
592
- })
593
-
594
- ctx.tools.register(subscriptionTool(runtime))
595
- }
596
-
597
- /**
598
- * The single model-facing tool: one action word per operation.
599
- *
600
- * @param runtime - the activation's runtime.
601
- * @returns the raw tool definition.
602
- */
603
- function subscriptionTool(runtime) {
604
- return {
605
- name: 'clash_proxy',
606
- description: [
607
- 'Manage the Harness\' own outbound proxy, backed by a private Clash/mihomo core and a user-imported subscription.',
608
- '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.',
613
- ].join(' '),
614
- parameters: {
615
- type: 'object',
616
- properties: {
617
- action: {
618
- 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.',
621
- },
622
- url: { type: 'string', description: 'Subscription URL for action=import (raw https:// or clash://install-config?url=…).' },
623
- node: { type: 'string', description: 'Exact node name for action=select or action=test; omit to use the current selection.' },
624
- },
625
- required: ['action'],
626
- },
627
- output: {
628
- schema: { type: 'object' },
629
- render(_args, value) {
630
- return [{ type: 'text', text: String(value?.summary ?? JSON.stringify(value)) }]
631
- },
632
- },
633
- timeoutMs: 120_000,
634
- async execute(args) {
635
- const action = String(args?.action ?? 'status')
636
- try {
637
- if (action === 'status') {
638
- const status = await runtime.status()
639
- return { ...status, summary: describeStatus(status) }
640
- }
641
- if (action === 'stop') {
642
- await runtime.stop()
643
- const status = await runtime.status()
644
- return { ...status, summary: '代理已停止,所有外网请求恢复直连。' }
645
- }
646
- 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 })
651
- return {
652
- ...report,
653
- summary: [
654
- `订阅已导入:${report.probe.format},${report.probe.nodeCount} 个节点,${report.probe.bytes} 字节。`,
655
- `内核 ${report.endpoint},当前节点「${report.group.now ?? '未选择'}」。`,
656
- `策略已安装,外网走代理、国内直连。`,
657
- ].join('\n'),
658
- }
659
- }
660
- if (action === 'start') {
661
- const report = await runtime.start()
662
- return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
663
- }
664
- if (action === 'select') {
665
- const node = String(args?.node ?? '').trim()
666
- if (node === '') throw new Error('action=select needs a node name')
667
- const group = await runtime.core.select(node)
668
- return { group, summary: `已切换到「${group.now}」。` }
669
- }
670
- if (action === 'test') {
671
- const target = String(args?.node ?? '').trim()
672
- if (target !== '') {
673
- const delay = await runtime.core.delay(target)
674
- return { node: target, delay, summary: delay === null ? `「${target}」测速失败。` : `「${target}」延迟 ${delay} ms。` }
675
- }
676
- const status = await runtime.status()
677
- if (status.node === undefined) throw new Error('no node selected')
678
- const delay = await runtime.core.delay(status.node)
679
- return { node: status.node, delay, summary: delay === null ? `「${status.node}」测速失败。` : `「${status.node}」延迟 ${delay} ms。` }
680
- }
681
- if (action === 'refresh') {
682
- const provider = await runtime.core.updateProvider()
683
- const group = await runtime.core.group()
684
- return { provider, group, summary: `订阅已刷新:${group.all.length - 1} 个节点。` }
685
- }
686
- throw new Error(`unknown action "${action}"`)
687
- } catch (error) {
688
- runtime.lastError = String(error?.message ?? error)
689
- return { error: runtime.lastError, summary: `clash_proxy ${action} 失败:${runtime.lastError}` }
690
- }
691
- },
692
- }
693
- }
694
-
695
- /**
696
- * Compose the human-readable status line.
697
- *
698
- * @param status - the status object.
699
- * @returns the summary text.
700
- */
701
- function describeStatus(status) {
702
- if (status.blocker !== undefined) return `未运行:${status.blocker}`
703
- const lines = [
704
- `内核:${status.running ? `运行中 ${status.endpoint}` : '未运行'}${status.binary === undefined ? '(未找到二进制)' : ''}`,
705
- `出网策略:${status.routing ? `已安装 → ${status.endpointEnvironment}` : '未安装(直连)'}`,
706
- `当前节点:${status.node ?? '未选择'}(可选 ${status.nodeCount} 个)`,
707
- ]
708
- if (status.lastError !== undefined) lines.push(`最近错误:${status.lastError}`)
709
- return lines.join('\n')
710
- }
1
+ export const probe = true