dsh-go-plugin-sync 0.0.0-stage → 0.3.1

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/lib/index.js ADDED
@@ -0,0 +1,1657 @@
1
+ // dsh-go-plugin-sync — compare and apply dsh-go plugin manifests between hosts.
2
+ //
3
+ // Runs inside the DSH engine on hosts with the dsh-go bridge. The app only draws
4
+ // what package.json "dshGo" declares and calls these handlers when tapped.
5
+ //
6
+ // Channels:
7
+ // - file: export / import a manifest (workspace or system picker)
8
+ // - relay: a private Git repo both hosts can reach (push / pull + install)
9
+ // - ssh: direct SSH from this engine to a remote DSH host (scan / push / pull)
10
+ //
11
+ // Long operations run as detached shell tasks; the panel reads a status file and
12
+ // the log tail. Nothing happens without a tap. No secrets are stored by us:
13
+ // SSH uses a key file or agent, Git uses the system credential helper.
14
+
15
+ import { spawn } from 'node:child_process'
16
+ import { createHash } from 'node:crypto'
17
+ import {
18
+ accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync,
19
+ } from 'node:fs'
20
+ import { dirname, extname, join, relative, resolve, sep } from 'node:path'
21
+ import { deflateRawSync, inflateRawSync } from 'node:zlib'
22
+
23
+ export const name = 'dsh-go-plugin-sync'
24
+
25
+ const MAX_FILES = 300
26
+ const MAX_FILE_BYTES = 2 * 1024 * 1024
27
+ const MAX_TOTAL_BYTES = 8 * 1024 * 1024
28
+ const MANIFEST_V = 1
29
+ const MANIFEST_FILE = 'plugin-sync-manifest.json'
30
+ const CONFIG_FILE = 'plugin-sync-config.json'
31
+ const CODE_PREFIX = 'DSHSYNC1:'
32
+ const CODE_BUDGET = 1900
33
+ const TEXT_EXT = new Set(['.js', '.mjs', '.cjs', '.json', '.yml', '.yaml', '.md', '.txt', '.css', '.html', '.svg', '.ts'])
34
+ const REL_RE = /^[A-Za-z0-9._@-]+(?:\/[A-Za-z0-9._@-]+)*$/
35
+ const PKG_NAME = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
36
+ const SAFE_DIR = /^[A-Za-z0-9._-]+$/
37
+ const SAFE_PROFILE = /^[a-z0-9-]+$/
38
+
39
+ const STATE = new Map()
40
+ let scanCache = { key: '', at: 0, value: [] }
41
+
42
+ // ---------------------------------------------------------------- paths
43
+
44
+ const home = () => process.env.DSH_HOME || join(process.env.HOME || '/root', '.dsh')
45
+ const storeDir = () => join(home(), 'dsh-go', 'plugin-sync')
46
+ const pluginsRoot = () => join(home(), 'dsh-go', 'plugins')
47
+ const profileName = () => process.env.DSH_PROFILE || 'web'
48
+ const profileDir = () => process.env.DSH_PROFILE_DIR || join(home(), 'profiles', profileName())
49
+
50
+ const importFile = () => join(storeDir(), 'imported.json')
51
+ const relayWorkDir = () => join(storeDir(), 'relay-work')
52
+ const relayManifestFile = () => join(storeDir(), 'relay-manifest.json')
53
+ const sshManifestFile = () => join(storeDir(), 'ssh-manifest.json')
54
+ const pushManifestFile = () => join(storeDir(), 'push-manifest.json')
55
+ const remoteScannerFile = () => join(storeDir(), 'scan-remote.cjs')
56
+ const taskScriptPath = () => join(storeDir(), 'task.sh')
57
+ const taskLogPath = () => join(storeDir(), 'task.log')
58
+ const taskStatusPath = () => join(storeDir(), 'task-status.txt')
59
+
60
+ function readJson(path) {
61
+ try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return undefined }
62
+ }
63
+
64
+ function ensureStore() {
65
+ mkdirSync(storeDir(), { recursive: true })
66
+ }
67
+
68
+ function shQuote(value) {
69
+ return `'${String(value).replace(/'/g, `'\\''`)}'`
70
+ }
71
+
72
+ function safeName(value) {
73
+ return typeof value === 'string' && (PKG_NAME.test(value) || SAFE_DIR.test(value))
74
+ }
75
+
76
+ function safeRel(value) {
77
+ if (typeof value !== 'string' || value.length === 0 || value.length > 200) return false
78
+ if (value.includes('\\') || value.includes('\0') || value.startsWith('/') || value.includes('..')) return false
79
+ return REL_RE.test(value) && TEXT_EXT.has(extname(value).toLowerCase())
80
+ }
81
+
82
+ // ---------------------------------------------------------------- sync code
83
+
84
+ /** Text files of one plugin directory, relative paths -> contents. */
85
+ function readPluginTextFiles(dir) {
86
+ const files = {}
87
+ let total = 0
88
+ const walk = (base, rel, depth) => {
89
+ if (depth > 4 || total > 200_000) return
90
+ let entries
91
+ try { entries = readdirSync(base, { withFileTypes: true }) } catch { return }
92
+ for (const entry of entries) {
93
+ if (entry.name === 'node_modules' || entry.name === '.git') continue
94
+ const full = join(base, entry.name)
95
+ const next = rel ? `${rel}/${entry.name}` : entry.name
96
+ if (entry.isDirectory()) { walk(full, next, depth + 1); continue }
97
+ if (!entry.isFile() || !TEXT_EXT.has(extname(entry.name).toLowerCase())) continue
98
+ let text
99
+ try { text = readFileSync(full, 'utf8') } catch { continue }
100
+ if (text.length > 100_000) continue
101
+ total += text.length
102
+ if (total > 200_000) return
103
+ files[next] = text
104
+ }
105
+ }
106
+ walk(dir, '', 0)
107
+ return files
108
+ }
109
+
110
+ function encodeSyncPayload(payload) {
111
+ return CODE_PREFIX + deflateRawSync(Buffer.from(JSON.stringify(payload), 'utf8')).toString('base64url')
112
+ }
113
+
114
+ /** Compact sync code: manifest + (when it fits) text files of local plugins. */
115
+ function buildSyncCode(plugins) {
116
+ const entries = plugins
117
+ .filter((plugin) => plugin.name !== name)
118
+ .map((plugin) => ({
119
+ name: plugin.name,
120
+ version: plugin.version,
121
+ hash: plugin.hash,
122
+ relDir: plugin.relDir,
123
+ depSpec: plugin.depSpec,
124
+ files: plugin.relDir && SAFE_DIR.test(plugin.relDir) && existsSync(plugin.dir)
125
+ ? readPluginTextFiles(plugin.dir)
126
+ : {},
127
+ }))
128
+ if (entries.length === 0) return { error: 'empty' }
129
+ let code = encodeSyncPayload({ v: 2, t: 'dsh-go-plugin-sync', at: new Date().toISOString(), plugins: entries })
130
+ let withFiles = entries.filter((entry) => Object.keys(entry.files).length > 0).length
131
+ if (code.length > CODE_BUDGET) {
132
+ code = encodeSyncPayload({
133
+ v: 2,
134
+ t: 'dsh-go-plugin-sync',
135
+ at: new Date().toISOString(),
136
+ plugins: entries.map(({ files, ...rest }) => rest),
137
+ })
138
+ withFiles = 0
139
+ }
140
+ if (code.length > 2000) return { error: 'too-large' }
141
+ return { code, plugins: entries.length, withFiles }
142
+ }
143
+
144
+ function decodeSyncCode(text) {
145
+ const trimmed = String(text || '').trim().replace(/\s+/g, '')
146
+ if (!trimmed.startsWith(CODE_PREFIX)) return { error: '不是同步码' }
147
+ let doc
148
+ try {
149
+ doc = JSON.parse(inflateRawSync(Buffer.from(trimmed.slice(CODE_PREFIX.length), 'base64url')).toString('utf8'))
150
+ } catch {
151
+ return { error: '同步码损坏' }
152
+ }
153
+ if (!doc || doc.v !== 2 || doc.t !== 'dsh-go-plugin-sync' || !Array.isArray(doc.plugins)) return { error: '同步码版本不对' }
154
+ const plugins = []
155
+ for (const raw of doc.plugins.slice(0, 200)) {
156
+ if (!raw || typeof raw.name !== 'string' || !safeName(raw.name)) continue
157
+ const relDir = typeof raw.relDir === 'string' && SAFE_DIR.test(raw.relDir) ? raw.relDir : null
158
+ const files = {}
159
+ if (raw.files && typeof raw.files === 'object') {
160
+ for (const [rel, content] of Object.entries(raw.files)) {
161
+ if (!safeRel(rel) || typeof content !== 'string' || content.length > 100_000) continue
162
+ files[rel] = content
163
+ }
164
+ }
165
+ plugins.push({
166
+ name: raw.name,
167
+ version: typeof raw.version === 'string' ? raw.version : '0.0.0',
168
+ hash: typeof raw.hash === 'string' ? raw.hash : null,
169
+ relDir,
170
+ depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
171
+ files,
172
+ })
173
+ }
174
+ return {
175
+ plugins,
176
+ manifest: {
177
+ v: MANIFEST_V,
178
+ generator: 'dsh-go-plugin-sync',
179
+ exportedAt: typeof doc.at === 'string' ? doc.at : null,
180
+ host: { profile: 'sync-code' },
181
+ plugins: plugins.map(({ files, ...rest }) => rest),
182
+ },
183
+ }
184
+ }
185
+
186
+ /** Materialize text files for plugins this host does not have yet (never overwrites). */
187
+ function writeCodeFiles(decoded) {
188
+ let written = 0
189
+ for (const plugin of decoded.plugins) {
190
+ if (!plugin.relDir || Object.keys(plugin.files).length === 0) continue
191
+ const dir = join(pluginsRoot(), plugin.relDir)
192
+ if (existsSync(dir)) continue
193
+ try {
194
+ mkdirSync(dir, { recursive: true })
195
+ for (const [rel, content] of Object.entries(plugin.files)) {
196
+ const target = join(dir, rel)
197
+ mkdirSync(dirname(target), { recursive: true })
198
+ writeFileSync(target, content)
199
+ }
200
+ written++
201
+ } catch {}
202
+ }
203
+ return written
204
+ }
205
+
206
+ /** Read the pasted code from a v2 form submit (`event.value.values['data.paste.code']`). */
207
+ function codeFromSubmit(value) {
208
+ const values = value?.values
209
+ if (values && typeof values === 'object') {
210
+ const direct = values['data.paste.code']
211
+ if (typeof direct === 'string') return direct.trim()
212
+ for (const candidate of Object.values(values)) {
213
+ if (typeof candidate === 'string' && candidate.trim().startsWith(CODE_PREFIX)) return candidate.trim()
214
+ }
215
+ }
216
+ if (typeof value === 'string') return value.trim()
217
+ return ''
218
+ }
219
+
220
+ /** Decode a sync code, materialize files, and preselect every row (all by default). */
221
+ function applySyncCode(scope, text, sourceName) {
222
+ const decoded = decodeSyncCode(text)
223
+ if (decoded.error) return { error: decoded.error }
224
+ const state = stateFor(scope)
225
+ state.manifest = decoded.manifest
226
+ state.manifestSource = { kind: 'code' }
227
+ state.importedAt = new Date().toISOString()
228
+ state.sourceName = sourceName
229
+ persistImported(state)
230
+ writeCodeFiles(decoded)
231
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
232
+ const manifestNames = new Set(decoded.manifest.plugins.map((plugin) => plugin.name))
233
+ state.selected.clear()
234
+ let selected = 0
235
+ for (const row of rows) {
236
+ if (!manifestNames.has(row.name)) continue
237
+ state.selected.add(row.name)
238
+ selected++
239
+ }
240
+ return {
241
+ count: decoded.manifest.plugins.length,
242
+ selected,
243
+ installable: rows.filter((row) => row.action === 'install').length,
244
+ }
245
+ }
246
+
247
+ // ---------------------------------------------------------------- config
248
+
249
+ function expandHome(value) {
250
+ if (typeof value !== 'string' || value === '') return ''
251
+ if (value === '~') return process.env.HOME || '/root'
252
+ if (value.startsWith('~/')) return join(process.env.HOME || '/root', value.slice(2))
253
+ return value
254
+ }
255
+
256
+ function normalizeConfig(raw) {
257
+ const relay = raw?.relay && typeof raw.relay === 'object' ? raw.relay : {}
258
+ const ssh = raw?.ssh && typeof raw.ssh === 'object' ? raw.ssh : {}
259
+ const port = Number(ssh.port)
260
+ const profile = typeof ssh.profile === 'string' && SAFE_PROFILE.test(ssh.profile) ? ssh.profile : profileName()
261
+ return {
262
+ relay: {
263
+ repo: typeof relay.repo === 'string' ? relay.repo.trim() : '',
264
+ branch: typeof relay.branch === 'string' && relay.branch.trim() !== '' ? relay.branch.trim() : 'main',
265
+ dir: typeof relay.dir === 'string' && SAFE_DIR.test(relay.dir) ? relay.dir : 'dsh-go-plugins',
266
+ },
267
+ ssh: {
268
+ host: typeof ssh.host === 'string' ? ssh.host.trim() : '',
269
+ port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 22,
270
+ user: typeof ssh.user === 'string' ? ssh.user.trim() : '',
271
+ identity: typeof ssh.identity === 'string' ? expandHome(ssh.identity.trim()) : '',
272
+ remoteHome: typeof ssh.remoteHome === 'string' && ssh.remoteHome.trim() !== '' ? ssh.remoteHome.trim() : '~/.dsh',
273
+ dshPath: typeof ssh.dshPath === 'string' && ssh.dshPath.trim() !== '' ? ssh.dshPath.trim() : 'dsh',
274
+ nodePath: typeof ssh.nodePath === 'string' && ssh.nodePath.trim() !== '' ? ssh.nodePath.trim() : 'node',
275
+ profile,
276
+ },
277
+ }
278
+ }
279
+
280
+ function loadConfig(ctx, scope) {
281
+ const candidates = []
282
+ const ws = writableDir(ctx, scope)
283
+ if (ws) candidates.push(join(ws, CONFIG_FILE))
284
+ candidates.push(join(storeDir(), CONFIG_FILE))
285
+ for (const path of candidates) {
286
+ const raw = readJson(path)
287
+ if (raw && typeof raw === 'object') return normalizeConfig(raw)
288
+ }
289
+ return normalizeConfig({})
290
+ }
291
+
292
+ function configTemplate() {
293
+ return JSON.stringify({
294
+ relay: { repo: 'https://github.com/you/dsh-plugins.git', branch: 'main', dir: 'dsh-go-plugins' },
295
+ ssh: { host: '192.168.1.10', port: 22, user: 'root', identity: '', remoteHome: '~/.dsh', dshPath: 'dsh', nodePath: 'node', profile: 'web' },
296
+ }, null, 2) + '\n'
297
+ }
298
+
299
+ // ---------------------------------------------------------------- local scan
300
+
301
+ function collectFiles(root, out, depth = 0) {
302
+ if (depth > 6 || out.length >= MAX_FILES) return
303
+ let entries
304
+ try { entries = readdirSync(root, { withFileTypes: true }) } catch { return }
305
+ for (const entry of entries) {
306
+ if (out.length >= MAX_FILES) return
307
+ const full = join(root, entry.name)
308
+ if (entry.isDirectory()) collectFiles(full, out, depth + 1)
309
+ else if (entry.isFile()) out.push(full)
310
+ }
311
+ }
312
+
313
+ function shortHash(dir) {
314
+ const hash = createHash('sha256')
315
+ try { hash.update(readFileSync(join(dir, 'package.json'))) } catch { return null }
316
+ const files = []
317
+ collectFiles(join(dir, 'lib'), files)
318
+ files.sort()
319
+ let total = 0
320
+ for (const file of files) {
321
+ let bytes
322
+ try { bytes = readFileSync(file) } catch { continue }
323
+ if (bytes.length > MAX_FILE_BYTES) continue
324
+ total += bytes.length
325
+ if (total > MAX_TOTAL_BYTES) break
326
+ hash.update(relative(dir, file).split(sep).join('/'))
327
+ hash.update('\0')
328
+ hash.update(bytes)
329
+ hash.update('\0')
330
+ }
331
+ return hash.digest('hex').slice(0, 16)
332
+ }
333
+
334
+ /** A syncable plugin: a dsh-go native plugin or a Cordis bundle (official bundles excluded). */
335
+ function syncablePkg(pkg) {
336
+ if (!pkg || typeof pkg.name !== 'string') return false
337
+ if (pkg.name === name || pkg.name.startsWith('@deepseek-ai/')) return false
338
+ const native = pkg.dshGo && typeof pkg.dshGo === 'object'
339
+ const bundle = pkg.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle
340
+ return Boolean(native || bundle)
341
+ }
342
+
343
+ function titleOf(pkg) {
344
+ const title = pkg?.dshGo?.title
345
+ if (typeof title === 'string') return title
346
+ if (title && typeof title === 'object') return title.zh || title.en || ''
347
+ return typeof pkg?.displayName === 'string' ? pkg.displayName : ''
348
+ }
349
+
350
+ function makeEntry(pkg, dir, relDir, depSpec) {
351
+ return {
352
+ name: pkg.name,
353
+ version: typeof pkg.version === 'string' ? pkg.version : '0.0.0',
354
+ title: titleOf(pkg).slice(0, 40),
355
+ hash: shortHash(dir),
356
+ relDir: relDir || null,
357
+ depSpec: depSpec || null,
358
+ dir,
359
+ installed: false,
360
+ }
361
+ }
362
+
363
+ function scanSourcePlugins() {
364
+ const root = pluginsRoot()
365
+ const out = []
366
+ let entries
367
+ try { entries = readdirSync(root, { withFileTypes: true }) } catch { return out }
368
+ for (const entry of entries) {
369
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue
370
+ const dir = join(root, entry.name)
371
+ const pkg = readJson(join(dir, 'package.json'))
372
+ if (!syncablePkg(pkg)) continue
373
+ out.push(makeEntry(pkg, dir, entry.name, null))
374
+ }
375
+ return out
376
+ }
377
+
378
+ function scanInstalledPlugins() {
379
+ const profile = readJson(join(profileDir(), 'package.json'))
380
+ const deps = profile?.dependencies
381
+ if (!deps || typeof deps !== 'object') return []
382
+ const out = []
383
+ for (const [dep, spec] of Object.entries(deps)) {
384
+ const dir = join(profileDir(), 'node_modules', dep)
385
+ const pkg = readJson(join(dir, 'package.json'))
386
+ if (!syncablePkg(pkg)) continue
387
+ let relDir = null
388
+ if (typeof spec === 'string' && (spec.startsWith('link:') || spec.startsWith('file:'))) {
389
+ const raw = spec.slice(spec.indexOf(':') + 1)
390
+ const rel = relative(pluginsRoot(), resolve(profileDir(), raw))
391
+ if (rel && !rel.startsWith('..') && !rel.startsWith(sep) && !rel.includes('\0')) relDir = rel
392
+ }
393
+ const entry = makeEntry(pkg, dir, relDir, spec)
394
+ entry.installed = true
395
+ out.push(entry)
396
+ }
397
+ return out
398
+ }
399
+
400
+ function localPlugins() {
401
+ const map = new Map()
402
+ for (const plugin of scanSourcePlugins()) map.set(plugin.name, plugin)
403
+ for (const plugin of scanInstalledPlugins()) {
404
+ const previous = map.get(plugin.name)
405
+ if (previous) {
406
+ previous.installed = true
407
+ previous.depSpec = plugin.depSpec
408
+ if (!previous.relDir) previous.relDir = plugin.relDir
409
+ } else {
410
+ map.set(plugin.name, plugin)
411
+ }
412
+ }
413
+ return [...map.values()]
414
+ }
415
+
416
+ function localPluginsCached() {
417
+ const key = home()
418
+ if (scanCache.key === key && Date.now() - scanCache.at < 2000) return scanCache.value
419
+ const value = localPlugins()
420
+ scanCache = { key, at: Date.now(), value }
421
+ return value
422
+ }
423
+
424
+ // ---------------------------------------------------------------- manifest
425
+
426
+ function buildManifest(plugins) {
427
+ return {
428
+ v: MANIFEST_V,
429
+ generator: 'dsh-go-plugin-sync',
430
+ exportedAt: new Date().toISOString(),
431
+ host: { profile: profileName() },
432
+ plugins: plugins.map((plugin) => ({
433
+ name: plugin.name,
434
+ version: plugin.version,
435
+ title: plugin.title,
436
+ hash: plugin.hash,
437
+ relDir: plugin.relDir,
438
+ depSpec: plugin.depSpec,
439
+ installed: plugin.installed === true,
440
+ })),
441
+ }
442
+ }
443
+
444
+ function validManifest(doc) {
445
+ if (!doc || typeof doc !== 'object' || doc.v !== MANIFEST_V || !Array.isArray(doc.plugins)) return undefined
446
+ const plugins = []
447
+ for (const raw of doc.plugins.slice(0, 200)) {
448
+ if (!raw || typeof raw !== 'object' || typeof raw.name !== 'string' || raw.name.length > 120) continue
449
+ if (raw.name === name) continue
450
+ plugins.push({
451
+ name: raw.name,
452
+ version: typeof raw.version === 'string' ? raw.version : '0.0.0',
453
+ title: typeof raw.title === 'string' ? raw.title.slice(0, 40) : '',
454
+ hash: typeof raw.hash === 'string' ? raw.hash.slice(0, 64) : null,
455
+ relDir: typeof raw.relDir === 'string' && !raw.relDir.includes('..') ? raw.relDir : null,
456
+ depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
457
+ installed: raw.installed === true,
458
+ })
459
+ }
460
+ return {
461
+ v: MANIFEST_V,
462
+ generator: 'dsh-go-plugin-sync',
463
+ exportedAt: typeof doc.exportedAt === 'string' ? doc.exportedAt : null,
464
+ host: doc.host && typeof doc.host === 'object' ? { profile: String(doc.host.profile ?? '') } : undefined,
465
+ plugins,
466
+ }
467
+ }
468
+
469
+ /** A plain `name@version` registry spec, when the manifest has no local files. */
470
+ function registrySpecOf(remote) {
471
+ const version = String(remote?.version || '')
472
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) return null
473
+ const spec = remote?.depSpec
474
+ if (typeof spec === 'string' && spec !== '') {
475
+ if (/^(file:|link:|workspace:|portal:|exec:|git\+|github:|https?:|\.{0,2}\/|~\/)/i.test(spec)) return null
476
+ }
477
+ return `${remote.name}@${version}`
478
+ }
479
+
480
+ function diffRows(local, manifest, source) {
481
+ const localByName = new Map(local.map((plugin) => [plugin.name, plugin]))
482
+ const manifestByName = new Map((manifest?.plugins ?? []).map((plugin) => [plugin.name, plugin]))
483
+ const rows = []
484
+ for (const remote of manifest?.plugins ?? []) {
485
+ const here = localByName.get(remote.name)
486
+ const remoteDir = remote.relDir || remote.name
487
+ if (!here) {
488
+ let action = null
489
+ let localDir = null
490
+ let registrySpec = null
491
+ if (source?.kind === 'ssh') {
492
+ action = 'pull'
493
+ } else {
494
+ if (source?.kind === 'relay') localDir = join(source.pluginsDir, remoteDir)
495
+ else if (remote.relDir) localDir = join(pluginsRoot(), remote.relDir)
496
+ if (localDir && existsSync(join(localDir, 'package.json'))) {
497
+ action = 'install'
498
+ } else {
499
+ localDir = null
500
+ registrySpec = registrySpecOf(remote)
501
+ if (registrySpec) action = 'install'
502
+ }
503
+ }
504
+ rows.push({
505
+ name: remote.name,
506
+ version: remote.version,
507
+ remoteVersion: remote.version,
508
+ status: action ? 'installable' : 'missing',
509
+ action,
510
+ localDir,
511
+ registrySpec,
512
+ dirName: remoteDir,
513
+ })
514
+ continue
515
+ }
516
+ const same = (!remote.hash || !here.hash || remote.hash === here.hash) && remote.version === here.version
517
+ if (!same) {
518
+ rows.push({ name: here.name, version: here.version, remoteVersion: remote.version, status: 'conflict', action: null })
519
+ } else if (!here.installed) {
520
+ rows.push({ name: here.name, version: here.version, status: 'install', action: 'install', localDir: here.dir })
521
+ } else {
522
+ rows.push({ name: here.name, version: here.version, status: 'same', action: null })
523
+ }
524
+ }
525
+ for (const here of local) {
526
+ if (manifestByName.has(here.name)) continue
527
+ if (source?.kind === 'ssh') {
528
+ rows.push({ name: here.name, version: here.version, status: 'push', action: 'push', dirName: here.relDir || here.name })
529
+ } else {
530
+ rows.push({ name: here.name, version: here.version, status: 'extra', action: null })
531
+ }
532
+ }
533
+ const order = { conflict: 0, installable: 1, install: 2, push: 3, extra: 4, missing: 5, same: 6 }
534
+ rows.sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9) || a.name.localeCompare(b.name))
535
+ return rows
536
+ }
537
+
538
+ // ---------------------------------------------------------------- state
539
+
540
+ function stateKey(scope) {
541
+ return scope?.sessionId || 'global'
542
+ }
543
+
544
+ function loadImported() {
545
+ const raw = readJson(importFile())
546
+ const manifest = raw ? validManifest(raw.manifest) : undefined
547
+ const usable = manifest && manifest.plugins.length > 0 ? manifest : null
548
+ return {
549
+ manifest: usable,
550
+ manifestSource: usable ? { kind: 'file' } : null,
551
+ importedAt: typeof raw?.importedAt === 'string' ? raw.importedAt : null,
552
+ sourceName: typeof raw?.sourceName === 'string' ? raw.sourceName.slice(0, 120) : null,
553
+ selected: new Set(),
554
+ lastExportPath: null,
555
+ lastPastedCode: null,
556
+ relayLoadedAt: 0,
557
+ sshLoadedAt: 0,
558
+ }
559
+ }
560
+
561
+ function stateFor(scope) {
562
+ const key = stateKey(scope)
563
+ let state = STATE.get(key)
564
+ if (!state) {
565
+ state = loadImported()
566
+ STATE.set(key, state)
567
+ }
568
+ return state
569
+ }
570
+
571
+ function persistImported(state) {
572
+ try {
573
+ ensureStore()
574
+ writeFileSync(importFile(), JSON.stringify({
575
+ importedAt: state.importedAt,
576
+ sourceName: state.sourceName,
577
+ manifest: state.manifest,
578
+ }, null, 2) + '\n')
579
+ } catch {}
580
+ }
581
+
582
+ function loadManifestFrom(path, kind, pluginsDir) {
583
+ try {
584
+ const stat = statSync(path)
585
+ return { manifest: validManifest(readJson(path)), mtime: stat.mtimeMs, source: { kind, pluginsDir } }
586
+ } catch {
587
+ return null
588
+ }
589
+ }
590
+
591
+ /** Refresh the state manifest from relay / ssh results when those files are newer. */
592
+ function refreshManifests(state, cfg) {
593
+ const relay = loadManifestFrom(relayManifestFile(), 'relay', join(relayWorkDir(), cfg.relay.dir, 'plugins'))
594
+ if (relay?.manifest && relay.manifest.plugins.length > 0 && relay.mtime > state.relayLoadedAt) {
595
+ state.manifest = relay.manifest
596
+ state.manifestSource = relay.source
597
+ state.importedAt = relay.manifest.exportedAt
598
+ state.sourceName = 'Git 中转'
599
+ state.relayLoadedAt = relay.mtime
600
+ state.selected.clear()
601
+ }
602
+ const ssh = loadManifestFrom(sshManifestFile(), 'ssh', null)
603
+ if (ssh?.manifest && ssh.manifest.plugins.length > 0 && ssh.mtime > state.sshLoadedAt) {
604
+ state.manifest = ssh.manifest
605
+ state.manifestSource = ssh.source
606
+ state.importedAt = ssh.manifest.exportedAt
607
+ state.sourceName = 'SSH 远端'
608
+ state.sshLoadedAt = ssh.mtime
609
+ state.selected.clear()
610
+ }
611
+ }
612
+
613
+ // ---------------------------------------------------------------- run status
614
+
615
+ function readTaskStatus() {
616
+ try {
617
+ const parts = readFileSync(taskStatusPath(), 'utf8').trim().split(/\s+/)
618
+ const started = Number(parts[1]) || 0
619
+ if (parts[0] === 'running') return { running: true, startedAt: started * 1000, kind: parts[2] || '' }
620
+ if (parts[0] === 'done') {
621
+ const failed = Number(parts[2]) || 0
622
+ return { running: false, finishedAt: started * 1000, failed, kind: parts[3] || '', ok: failed === 0 }
623
+ }
624
+ } catch {}
625
+ return null
626
+ }
627
+
628
+ function readLogTail(max = 4) {
629
+ try {
630
+ const lines = readFileSync(taskLogPath(), 'utf8').trim().split('\n').filter(Boolean)
631
+ return lines.slice(-max).map((line) => line.length > 120 ? `${line.slice(0, 120)}…` : line)
632
+ } catch {
633
+ return []
634
+ }
635
+ }
636
+
637
+ /** Per-item results of the last task, parsed from `@@ action name start|ok|fail` markers. */
638
+ function readTaskResults() {
639
+ let text
640
+ try { text = readFileSync(taskLogPath(), 'utf8') } catch { return [] }
641
+ const results = []
642
+ let current
643
+ for (const raw of text.split('\n')) {
644
+ const marker = /^@@ (\S+) (\S+) (start|ok|fail)$/.exec(raw)
645
+ if (marker) {
646
+ const [, action, name, phase] = marker
647
+ if (phase === 'start') {
648
+ current = { action, name, lines: [] }
649
+ continue
650
+ }
651
+ if (current && current.action === action && current.name === name) {
652
+ results.push({
653
+ action,
654
+ name,
655
+ ok: phase === 'ok',
656
+ message: phase === 'fail' ? current.lines.slice(-2).join(' ').slice(0, 140) : '',
657
+ })
658
+ current = undefined
659
+ }
660
+ continue
661
+ }
662
+ if (current) current.lines.push(raw.trim())
663
+ }
664
+ return results
665
+ }
666
+
667
+ // ---------------------------------------------------------------- task runner
668
+
669
+ function startTask(kind, lines) {
670
+ ensureStore()
671
+ const script = [
672
+ '#!/bin/sh',
673
+ `LOG=${shQuote(taskLogPath())}`,
674
+ `STATUS=${shQuote(taskStatusPath())}`,
675
+ `PROFILE=${shQuote(profileName())}`,
676
+ 'DSH_BIN="${DSH_BIN:-$(command -v dsh || echo /usr/local/bin/dsh)}"',
677
+ ': > "$LOG"',
678
+ 'failed=0',
679
+ 'say() { echo "$@" >> "$LOG"; }',
680
+ ...lines,
681
+ `echo "done $(date +%s) $failed ${kind}" > "$STATUS"`,
682
+ ].join('\n') + '\n'
683
+ writeFileSync(taskScriptPath(), script, { mode: 0o755 })
684
+ writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} ${kind}\n`)
685
+ const child = spawn('/bin/sh', [taskScriptPath()], { detached: true, stdio: 'ignore', env: process.env })
686
+ child.on('error', () => {})
687
+ child.unref()
688
+ }
689
+
690
+ function localAddCommand(dir) {
691
+ return `"$DSH_BIN" plugin --profile "$PROFILE" add ${shQuote(dir)}`
692
+ }
693
+
694
+ /** One result-reporting item: start marker, commands, ok/fail marker. */
695
+ function itemLines(action, name, commands) {
696
+ const tag = `${action} ${name}`
697
+ const lines = [`say "@@ ${tag} start"`, 'itemfailed=0']
698
+ for (const command of commands) {
699
+ lines.push(`${command} >> "$LOG" 2>&1 || itemfailed=$((itemfailed + 1))`)
700
+ }
701
+ lines.push(`if [ "$itemfailed" -eq 0 ]; then say "@@ ${tag} ok"; else failed=$((failed + 1)); say "@@ ${tag} fail"; fi`)
702
+ return lines
703
+ }
704
+
705
+ function sshPrelude(cfg) {
706
+ const target = cfg.ssh.user ? `${cfg.ssh.user}@${cfg.ssh.host}` : cfg.ssh.host
707
+ const keyOpt = cfg.ssh.identity ? `-i ${shQuote(cfg.ssh.identity)}` : ''
708
+ return [
709
+ `SSH_PORT=${shQuote(String(cfg.ssh.port))}`,
710
+ `SSH_TARGET=${shQuote(target)}`,
711
+ `SSH_KEY_OPT=${shQuote(keyOpt)}`,
712
+ 'ssh_run() { ssh -p "$SSH_PORT" -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 $SSH_KEY_OPT "$@"; }',
713
+ ]
714
+ }
715
+
716
+ function remotePaths(cfg) {
717
+ const home = cfg.ssh.remoteHome
718
+ const plugins = `${home}/dsh-go/plugins`
719
+ return { home, plugins }
720
+ }
721
+
722
+ function buildRelayPush(cfg, plugins, manifestPath) {
723
+ const work = relayWorkDir()
724
+ const lines = [
725
+ `RELAY_REPO=${shQuote(cfg.relay.repo)}`,
726
+ `RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
727
+ `RELAY_DIR=${shQuote(cfg.relay.dir)}`,
728
+ `WORK=${shQuote(work)}`,
729
+ 'if [ -d "$WORK/.git" ]; then',
730
+ ' say "pull relay"',
731
+ ' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
732
+ 'else',
733
+ ' rm -rf "$WORK"',
734
+ ' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
735
+ ' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
736
+ 'fi',
737
+ 'if [ "$failed" -eq 0 ]; then',
738
+ ' rm -rf "$WORK/$RELAY_DIR/plugins"',
739
+ ' mkdir -p "$WORK/$RELAY_DIR/plugins"',
740
+ ]
741
+ for (const plugin of plugins) {
742
+ if (!plugin.relDir || !SAFE_DIR.test(plugin.relDir)) continue
743
+ lines.push(` tar -C ${shQuote(pluginsRoot())} -cf - --exclude=node_modules --exclude=.git ${shQuote(plugin.relDir)} | tar -C "$WORK/$RELAY_DIR/plugins" -xf - >> "$LOG" 2>&1 || failed=$((failed + 1))`)
744
+ }
745
+ lines.push(
746
+ ` cp ${shQuote(manifestPath)} "$WORK/$RELAY_DIR/manifest.json" >> "$LOG" 2>&1 || failed=$((failed + 1))`,
747
+ ' git -C "$WORK" add -A >> "$LOG" 2>&1',
748
+ ' git -C "$WORK" -c user.name=dsh-go -c user.email=dsh-go@local commit -m "plugin-sync $(date +%s)" >> "$LOG" 2>&1 || true',
749
+ ' git -C "$WORK" push origin "$RELAY_BRANCH" >> "$LOG" 2>&1 || failed=$((failed + 1))',
750
+ 'fi',
751
+ )
752
+ return lines
753
+ }
754
+
755
+ function buildRelayPull(cfg) {
756
+ const work = relayWorkDir()
757
+ const relayManifest = relayManifestFile()
758
+ return [
759
+ `RELAY_REPO=${shQuote(cfg.relay.repo)}`,
760
+ `RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
761
+ `RELAY_DIR=${shQuote(cfg.relay.dir)}`,
762
+ `WORK=${shQuote(work)}`,
763
+ 'if [ -d "$WORK/.git" ]; then',
764
+ ' say "pull relay"',
765
+ ' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
766
+ 'else',
767
+ ' rm -rf "$WORK"',
768
+ ' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
769
+ ' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
770
+ 'fi',
771
+ 'if [ "$failed" -eq 0 ] && [ -f "$WORK/$RELAY_DIR/manifest.json" ]; then',
772
+ ` cp "$WORK/$RELAY_DIR/manifest.json" ${shQuote(relayManifest)} >> "$LOG" 2>&1 || failed=$((failed + 1))`,
773
+ 'elif [ "$failed" -eq 0 ]; then',
774
+ ' say "relay has no manifest"',
775
+ ' failed=$((failed + 1))',
776
+ 'fi',
777
+ ]
778
+ }
779
+
780
+ function buildSshTest(cfg) {
781
+ return [...sshPrelude(cfg), 'ssh_run "$SSH_TARGET" "true" >> "$LOG" 2>&1 || failed=$((failed + 1))']
782
+ }
783
+
784
+ function buildSshScan(cfg) {
785
+ const { home } = remotePaths(cfg)
786
+ const scanner = remoteScannerFile()
787
+ writeFileSync(scanner, remoteScannerSource())
788
+ return [
789
+ ...sshPrelude(cfg),
790
+ `ssh_run "$SSH_TARGET" "${cfg.ssh.nodePath} - ${home}" < ${shQuote(scanner)} > ${shQuote(sshManifestFile())} 2>> "$LOG" || failed=$((failed + 1))`,
791
+ ]
792
+ }
793
+
794
+ function buildSshPush(cfg, jobs) {
795
+ const { home, plugins } = remotePaths(cfg)
796
+ const dsh = cfg.ssh.dshPath
797
+ const profile = cfg.ssh.profile
798
+ const lines = [...sshPrelude(cfg)]
799
+ for (const job of jobs.filter((item) => safeName(item.dirName))) {
800
+ lines.push(...itemLines('push', job.name, [
801
+ `tar -C ${shQuote(pluginsRoot())} -czf - --exclude=node_modules --exclude=.git ${shQuote(job.dirName)} | ssh_run "$SSH_TARGET" "mkdir -p ${plugins} && tar -C ${plugins} -xzf -"`,
802
+ `ssh_run "$SSH_TARGET" "cd ${home} && ${dsh} plugin --profile ${profile} add ${plugins}/${job.dirName}"`,
803
+ ]))
804
+ }
805
+ return lines
806
+ }
807
+
808
+ function buildSshPull(cfg, jobs) {
809
+ const { plugins } = remotePaths(cfg)
810
+ const lines = [...sshPrelude(cfg)]
811
+ for (const job of jobs.filter((item) => safeName(item.dirName))) {
812
+ lines.push(...itemLines('pull', job.name, [
813
+ `ssh_run "$SSH_TARGET" "tar -C ${plugins} -czf - ${job.dirName}" | tar -C ${shQuote(pluginsRoot())} -xzf -`,
814
+ localAddCommand(join(pluginsRoot(), job.dirName)),
815
+ ]))
816
+ }
817
+ return lines
818
+ }
819
+
820
+ function buildApply(cfg, jobs) {
821
+ const lines = []
822
+ const installs = jobs.filter((job) => job.action === 'install')
823
+ const pushes = jobs.filter((job) => job.action === 'push')
824
+ const pulls = jobs.filter((job) => job.action === 'pull')
825
+ for (const job of installs) {
826
+ const target = job.localDir || job.registrySpec
827
+ if (target) lines.push(...itemLines('install', job.name, [localAddCommand(target)]))
828
+ }
829
+ if (pushes.length > 0) lines.push(...buildSshPush(cfg, pushes))
830
+ if (pulls.length > 0) lines.push(...buildSshPull(cfg, pulls))
831
+ return lines
832
+ }
833
+
834
+ let SCANNER_CACHE
835
+ function remoteScannerSource() {
836
+ if (SCANNER_CACHE) return SCANNER_CACHE
837
+ SCANNER_CACHE = [
838
+ "const fs = require('fs')",
839
+ "const path = require('path')",
840
+ "const crypto = require('crypto')",
841
+ "const root = path.join(process.argv[2], 'dsh-go', 'plugins')",
842
+ 'const out = []',
843
+ 'function walk(dir, acc, depth) {',
844
+ ' if (depth > 6 || acc.length >= 300) return',
845
+ ' let entries',
846
+ ' try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }',
847
+ ' for (const e of entries) {',
848
+ ' if (acc.length >= 300) return',
849
+ " const full = path.join(dir, e.name)",
850
+ ' if (e.isDirectory()) walk(full, acc, depth + 1)',
851
+ ' else if (e.isFile()) acc.push(full)',
852
+ ' }',
853
+ '}',
854
+ 'function hash(dir) {',
855
+ " const h = crypto.createHash('sha256')",
856
+ " try { h.update(fs.readFileSync(path.join(dir, 'package.json'))) } catch { return null }",
857
+ ' const files = []',
858
+ " walk(path.join(dir, 'lib'), files, 0)",
859
+ ' files.sort()',
860
+ ' for (const f of files) {',
861
+ ' let b',
862
+ ' try { b = fs.readFileSync(f) } catch { continue }',
863
+ ' if (b.length > 2097152) continue',
864
+ " h.update(path.relative(dir, f))",
865
+ " h.update('\\0')",
866
+ ' h.update(b)',
867
+ ' }',
868
+ " return h.digest('hex').slice(0, 16)",
869
+ '}',
870
+ "try {",
871
+ ' for (const e of fs.readdirSync(root, { withFileTypes: true })) {',
872
+ " if (!e.isDirectory() || e.name.startsWith('.')) continue",
873
+ ' const dir = path.join(root, e.name)',
874
+ ' let pkg',
875
+ " try { pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')) } catch { continue }",
876
+ " if (!pkg || typeof pkg.name !== 'string' || !pkg.dshGo) continue",
877
+ ' out.push({ name: pkg.name, version: String(pkg.version || \'0.0.0\'), hash: hash(dir), relDir: e.name, depSpec: null, installed: false })',
878
+ ' }',
879
+ '} catch {}',
880
+ "process.stdout.write(JSON.stringify({ v: 1, exportedAt: new Date().toISOString(), host: { profile: 'remote' }, plugins: out }))",
881
+ ].join('\n') + '\n'
882
+ return SCANNER_CACHE
883
+ }
884
+
885
+ // ---------------------------------------------------------------- workspace
886
+
887
+ function workspaceCandidates(ctx, scope) {
888
+ const out = []
889
+ try {
890
+ const registry = ctx?.get?.('workspaceRegistry')
891
+ if (registry && typeof registry.list === 'function') {
892
+ const list = registry.list() || []
893
+ if (scope?.sessionId) {
894
+ const match = list.find((w) => Array.isArray(w.sessionIds) && w.sessionIds.includes(scope.sessionId))
895
+ if (match?.path) out.push(match.path)
896
+ }
897
+ for (const w of list) if (w?.path) out.push(w.path)
898
+ }
899
+ } catch {}
900
+ if (process.env.DSH_WORKSPACE) out.push(process.env.DSH_WORKSPACE)
901
+ out.push(process.cwd(), join(home(), 'workspace'))
902
+ return [...new Set(out)]
903
+ }
904
+
905
+ function writableDir(ctx, scope) {
906
+ for (const dir of workspaceCandidates(ctx, scope)) {
907
+ try {
908
+ accessSync(dir, constants.W_OK)
909
+ if (statSync(dir).isDirectory()) return dir
910
+ } catch {}
911
+ }
912
+ return null
913
+ }
914
+
915
+ function exportTarget(ctx, scope) {
916
+ const dir = writableDir(ctx, scope)
917
+ return dir ? join(dir, MANIFEST_FILE) : join(storeDir(), MANIFEST_FILE)
918
+ }
919
+
920
+ // ---------------------------------------------------------------- view
921
+
922
+ function enableText(caps) {
923
+ return String(caps?.locale || '').toLowerCase().startsWith('en')
924
+ }
925
+
926
+ function statusLine(row, en) {
927
+ let text = {
928
+ same: en ? 'same' : '一致',
929
+ conflict: en ? 'conflict: local vs manifest differ' : '冲突:本机与清单不同',
930
+ install: en ? 'not installed yet' : '本机未安装',
931
+ installable: en ? 'can install from this manifest' : '可从这份清单安装',
932
+ missing: en ? 'files not on this host' : '本机缺少文件,需手动拷贝',
933
+ extra: en ? 'not in manifest' : '清单里没有',
934
+ push: en ? 'remote lacks it; can push' : '远端没有,可推送',
935
+ }[row.status] || row.status
936
+ if (row.action === 'install' && row.registrySpec) text = en ? 'install from npm' : '可从 npm 安装'
937
+ else if (row.action === 'install' && row.localDir) text = en ? 'install from files' : '可从文件安装'
938
+ else if (row.action === 'pull') text = en ? 'pull from remote' : '可从远端拉取'
939
+ const version = row.status === 'conflict' && row.remoteVersion && row.remoteVersion !== row.version
940
+ ? `${row.version} → ${row.remoteVersion}`
941
+ : row.version
942
+ return `${version} · ${text}`
943
+ }
944
+
945
+ function statusTone(status) {
946
+ if (status === 'conflict' || status === 'extra') return 'warn'
947
+ if (status === 'installable' || status === 'install' || status === 'push') return 'info'
948
+ if (status === 'missing') return 'bad'
949
+ return undefined
950
+ }
951
+
952
+ const TASK_LABELS = {
953
+ apply: ['应用所选', 'apply selected'],
954
+ 'relay-push': ['推送中转', 'push to relay'],
955
+ 'relay-pull': ['拉取中转', 'pull from relay'],
956
+ 'ssh-test': ['测试 SSH', 'test SSH'],
957
+ 'ssh-scan': ['拉远端清单', 'scan remote'],
958
+ }
959
+
960
+ function taskLabel(kind, en) {
961
+ return TASK_LABELS[kind]?.[en ? 1 : 0] || kind
962
+ }
963
+
964
+ function buildView(scope, caps, ctx) {
965
+ const en = enableText(caps)
966
+ const cfg = loadConfig(ctx, scope)
967
+ const state = stateFor(scope)
968
+ refreshManifests(state, cfg)
969
+ const local = localPluginsCached()
970
+ const rows = diffRows(local, state.manifest, state.manifestSource)
971
+ const components = Array.isArray(caps?.components) ? caps.components : []
972
+ const canForm = components.includes('form') && components.includes('textField')
973
+ const children = []
974
+
975
+ children.push({ type: 'text', text: en
976
+ ? 'Copy a sync code (all or selected), or paste one below. Sync only installs missing plugins; it never touches what you already have.'
977
+ : '复制同步码(全部或选中),或在下面粘贴导入。同步只安装缺少的插件,不会动已有的。' })
978
+
979
+ if (canForm) {
980
+ children.push({ type: 'form', submit: 'import-code', submitLabel: en ? 'Import code' : '导入同步码', children: [
981
+ {
982
+ type: 'textField',
983
+ label: en ? 'Sync code' : '同步码',
984
+ bind: 'data.paste.code',
985
+ multiline: true,
986
+ maxLines: 8,
987
+ maxLength: 2000,
988
+ placeholder: en ? 'Paste DSHSYNC1:… here' : '在这里粘贴 DSHSYNC1: 开头的同步码',
989
+ },
990
+ ] })
991
+ } else {
992
+ children.push({ type: 'callout', tone: 'info', text: en
993
+ ? 'This app version has no panel input; use the relay or file import.'
994
+ : '当前 App 版本不支持面板输入,请用中转或文件导入。' })
995
+ }
996
+
997
+ children.push({ type: 'row', children: [
998
+ { type: 'metric', label: en ? 'Local' : '本机', value: String(local.length) },
999
+ { type: 'metric', label: en ? 'Manifest' : '清单', value: state.manifest ? String(state.manifest.plugins.length) : '—' },
1000
+ { type: 'metric', label: en ? 'Selected' : '已选', value: String(state.selected.size) },
1001
+ ] })
1002
+
1003
+ children.push({ type: 'keyValue', items: [
1004
+ [en ? 'Relay' : '中转', cfg.relay.repo || (en ? 'not configured' : '未配置')],
1005
+ [en ? 'SSH' : 'SSH', cfg.ssh.host ? `${cfg.ssh.user ? `${cfg.ssh.user}@` : ''}${cfg.ssh.host}:${cfg.ssh.port}` : (en ? 'not configured' : '未配置')],
1006
+ ] })
1007
+
1008
+ const task = readTaskStatus()
1009
+ if (task?.running) {
1010
+ const stale = Date.now() - task.startedAt > 15 * 60 * 1000
1011
+ children.push({ type: 'callout', tone: stale ? 'warn' : 'info', text: stale
1012
+ ? (en ? 'A task started long ago; check the log.' : '任务开始很久了,看下日志。')
1013
+ : (en ? `${taskLabel(task.kind, true)} running…` : `正在${taskLabel(task.kind, false)}…`) })
1014
+ } else if (task && task.ok === false) {
1015
+ children.push({ type: 'callout', tone: 'bad', text: en
1016
+ ? `${taskLabel(task.kind, true)} failed (${task.failed}). Check the log.`
1017
+ : `${taskLabel(task.kind, false)}失败(${task.failed} 项),看日志。` })
1018
+ } else if (task?.ok) {
1019
+ children.push({ type: 'callout', tone: 'good', text: en
1020
+ ? `${taskLabel(task.kind, true)} finished.`
1021
+ : `${taskLabel(task.kind, false)}完成。` })
1022
+ if (task.kind === 'apply' || task.kind === 'ssh-push' || task.kind === 'ssh-scan') {
1023
+ children.push({ type: 'callout', tone: 'warn', text: en
1024
+ ? 'Installed plugins need an engine restart on that host.'
1025
+ : '装了插件的主机要重启一次引擎才加载。' })
1026
+ }
1027
+ }
1028
+
1029
+ const results = readTaskResults()
1030
+ if (results.length > 0) {
1031
+ const okCount = results.filter((result) => result.ok).length
1032
+ const failed = results.filter((result) => !result.ok)
1033
+ children.push({ type: 'text', text: en
1034
+ ? `Last run: ${okCount} ok · ${failed.length} failed`
1035
+ : `上次结果:成功 ${okCount} · 失败 ${failed.length}` })
1036
+ if (failed.length > 0) {
1037
+ children.push({ type: 'list', items: failed.slice(0, 8).map((result) => ({
1038
+ title: result.name,
1039
+ subtitle: result.message || (en ? 'failed' : '失败'),
1040
+ tone: 'bad',
1041
+ })) })
1042
+ }
1043
+ }
1044
+
1045
+ if (!state.manifest) {
1046
+ children.push({ type: 'callout', tone: 'info', text: en
1047
+ ? 'Select plugins below, then Copy code; or import a manifest / pull the relay first.'
1048
+ : '先在下面选中要同步的插件,再点复制同步码;也可以先导入清单或拉取中转。' })
1049
+ if (local.length > 0) {
1050
+ const shown = local.slice(0, 40)
1051
+ children.push({ type: 'list', items: shown.map((plugin) => ({
1052
+ title: plugin.name,
1053
+ subtitle: `${plugin.version} · ${en ? 'tap to select' : '点选'}`,
1054
+ trailing: state.selected.has(plugin.name) ? '✓' : '○',
1055
+ action: { id: 'toggle', args: { name: plugin.name } },
1056
+ })) })
1057
+ if (local.length > shown.length) {
1058
+ children.push({ type: 'text', text: en ? `…and ${local.length - shown.length} more` : `…还有 ${local.length - shown.length} 项` })
1059
+ }
1060
+ }
1061
+ } else {
1062
+ const when = state.manifest.exportedAt ? state.manifest.exportedAt.slice(0, 16).replace('T', ' ') : ''
1063
+ const source = state.sourceName || state.manifest.host?.profile || ''
1064
+ children.push({ type: 'text', text: en
1065
+ ? `Manifest: ${source || 'imported'}${when ? ` · ${when}` : ''}`
1066
+ : `清单来源:${source || '已导入'}${when ? ` · ${when}` : ''}` })
1067
+
1068
+ if (rows.length === 0) {
1069
+ children.push({ type: 'callout', tone: 'good', text: en ? 'The two hosts match.' : '两边完全一致。' })
1070
+ } else {
1071
+ const shown = rows.slice(0, 40)
1072
+ children.push({ type: 'list', items: shown.map((row) => {
1073
+ const item = {
1074
+ title: row.name,
1075
+ subtitle: statusLine(row, en),
1076
+ trailing: state.selected.has(row.name) ? '✓' : '○',
1077
+ action: { id: 'toggle', args: { name: row.name } },
1078
+ }
1079
+ const tone = statusTone(row.status)
1080
+ if (tone) item.tone = tone
1081
+ return item
1082
+ }) })
1083
+ if (rows.length > shown.length) {
1084
+ children.push({ type: 'text', text: en ? `…and ${rows.length - shown.length} more` : `…还有 ${rows.length - shown.length} 项` })
1085
+ }
1086
+ }
1087
+
1088
+ }
1089
+
1090
+ const primary = [
1091
+ { label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
1092
+ { label: en ? 'Select all' : '全选', action: 'select-all' },
1093
+ { label: en ? 'Clear' : '清空', action: 'clear' },
1094
+ { label: en ? 'Refresh' : '刷新', action: 'refresh' },
1095
+ ]
1096
+ children.push({ type: 'actions', items: primary })
1097
+
1098
+ children.push({ type: 'actions', items: [
1099
+ { label: en ? 'Retry failed' : '重试失败', action: 'retry-failed' },
1100
+ { label: en ? 'Export' : '导出清单', action: 'export' },
1101
+ { label: en ? 'Read workspace' : '工作区导入', action: 'import-workspace' },
1102
+ { label: en ? 'Guide' : '使用引导', action: 'guide' },
1103
+ ] })
1104
+
1105
+ if (state.manifest && state.selected.size > 0) {
1106
+ children.push({ type: 'confirm', id: 'apply', confirmLabel: en ? 'Apply' : '应用所选', cancelLabel: en ? 'Cancel' : '取消' })
1107
+ }
1108
+
1109
+ const log = readLogTail()
1110
+ if (log.length > 0) {
1111
+ children.push({ type: 'keyValue', items: log.map((line, index) => [en ? `log ${index + 1}` : `日志 ${index + 1}`, line]) })
1112
+ }
1113
+
1114
+ const view = { type: 'stack', title: en ? 'Plugin sync' : '插件同步', children }
1115
+ if (canForm) view.v = 2
1116
+ return view
1117
+ }
1118
+
1119
+ function buildGuide(scope, caps, ctx) {
1120
+ const en = enableText(caps)
1121
+ const cfg = loadConfig(ctx, scope)
1122
+ const configPath = join(writableDir(ctx, scope) || storeDir(), CONFIG_FILE)
1123
+ return {
1124
+ type: 'stack',
1125
+ title: en ? 'Plugin sync guide' : '插件同步使用引导',
1126
+ children: [
1127
+ { type: 'text', text: en
1128
+ ? 'A copies one string; on B open Sync, paste it into the code field and tap Import.'
1129
+ : 'A 主机复制同步码;B 主机打开「插件同步」,把码粘进输入框点「导入同步码」。' },
1130
+ { type: 'text', text: en
1131
+ ? 'Both hosts need this plugin installed once (manual first time).'
1132
+ : '两端都要先装好本插件(第一次手动装)。' },
1133
+ { type: 'text', text: en
1134
+ ? 'Sync only installs missing plugins. It never uninstalls or overwrites what you already have; version mismatches and failed installs are shown but left for you to decide.'
1135
+ : '同步只安装缺少的插件,不会卸载或覆盖你已经有的;版本对不上或者装不上的会标出来,但不会自动处理。' },
1136
+ { type: 'steps', items: [
1137
+ { label: en ? 'Copy on host A' : '在 A 主机复制', status: 'done', detail: en
1138
+ ? 'Panel → Copy code'
1139
+ : '插件同步面板 → 复制同步码' },
1140
+ { label: en ? 'Paste and import on B' : '在 B 粘贴并导入', status: 'current', detail: en
1141
+ ? 'Panel → code field → Import code'
1142
+ : '面板「同步码」输入框 → 导入同步码' },
1143
+ { label: en ? 'Select and apply on B' : '在 B 选中并应用', status: 'todo', detail: en
1144
+ ? 'All selected by default; deselect what you do not want'
1145
+ : '默认全选,可取消不要的项' },
1146
+ { label: en ? 'Retry failures' : '失败项点重试', status: 'todo', detail: en
1147
+ ? 'Retry failed in the panel'
1148
+ : '面板「重试失败项」' },
1149
+ { label: en ? 'Restart the engine' : '重启一次引擎', status: 'todo' },
1150
+ ] },
1151
+ { type: 'callout', tone: 'info', text: en
1152
+ ? 'The code is compressed text: it carries text files. If too large it falls back to manifest only and tries npm versions.'
1153
+ : '同步码是压缩文本,带的是文本文件;太大时退化为只带清单,本地插件会尝试按 npm 版本安装。' },
1154
+ { type: 'callout', tone: 'warn', text: en
1155
+ ? 'Only paste codes from a source you trust: plugin code runs on this host.'
1156
+ : '只粘贴可信来源的同步码:插件代码会在本机运行。' },
1157
+ { type: 'text', text: en
1158
+ ? 'Cordis bundles may depend on the DSH version or platform; failures show in the failed list.'
1159
+ : 'Cordis 插件可能依赖 DSH 版本或平台,装不上会进失败清单。' },
1160
+ { type: 'callout', tone: 'info', text: en
1161
+ ? `Config file: ${configPath}`
1162
+ : `配置文件:${configPath}` },
1163
+ { type: 'keyValue', items: [
1164
+ ['relay.repo', cfg.relay.repo || '—'],
1165
+ ['ssh.host', cfg.ssh.host || '—'],
1166
+ ] },
1167
+ { type: 'text', text: en
1168
+ ? 'Advanced: large plugins or two-way file sync use the Git relay / SSH below.'
1169
+ : '高级:大插件或双向文件同步用下面的 Git 中转 / SSH。' },
1170
+ { type: 'actions', items: [
1171
+ { label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
1172
+ { label: en ? 'Config template' : '生成配置模板', action: 'copy-config' },
1173
+ { label: en ? 'Back' : '返回同步', action: 'back' },
1174
+ ] },
1175
+ { type: 'actions', items: [
1176
+ { label: en ? 'Push relay' : '推送中转', action: 'relay-push' },
1177
+ { label: en ? 'Pull relay' : '拉取中转', action: 'relay-pull' },
1178
+ { label: en ? 'Scan SSH' : '拉远端清单', action: 'ssh-scan' },
1179
+ { label: en ? 'Test SSH' : '测试 SSH', action: 'ssh-test' },
1180
+ ] },
1181
+ ],
1182
+ }
1183
+ }
1184
+
1185
+ function stripValue(scope, en) {
1186
+ const task = readTaskStatus()
1187
+ if (task?.running) return { text: en ? 'Syncing…' : '同步中…', icon: 'refresh', tone: 'info' }
1188
+ if (task && task.ok === false) return { text: en ? `Sync failed: ${task.failed}` : `同步失败 ${task.failed} 项`, icon: 'warning', tone: 'bad' }
1189
+ const state = stateFor(scope)
1190
+ if (state.manifest) {
1191
+ const rows = diffRows(localPluginsCached(), state.manifest, state.manifestSource)
1192
+ const pending = rows.filter((row) => row.action).length
1193
+ if (pending > 0) return { text: en ? `Sync ${pending} left` : `待同步 ${pending} 项`, icon: 'refresh', tone: 'warn' }
1194
+ return { text: en ? 'Plugins in sync' : '插件已同步', icon: 'check', tone: 'good' }
1195
+ }
1196
+ return { text: en ? 'Plugin sync' : '插件同步', icon: 'refresh' }
1197
+ }
1198
+
1199
+ // ---------------------------------------------------------------- web ui
1200
+
1201
+ function webJson(res, status, value) {
1202
+ const body = JSON.stringify(value)
1203
+ res.writeHead(status, {
1204
+ 'content-type': 'application/json; charset=utf-8',
1205
+ 'cache-control': 'no-store',
1206
+ })
1207
+ res.end(body)
1208
+ }
1209
+
1210
+ function webReadBody(req, limit = 1024 * 1024) {
1211
+ return new Promise((resolve, reject) => {
1212
+ let total = 0
1213
+ const chunks = []
1214
+ req.on('data', (chunk) => {
1215
+ total += chunk.length
1216
+ if (total > limit) { reject(new Error('body too large')); req.destroy(); return }
1217
+ chunks.push(chunk)
1218
+ })
1219
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1220
+ req.on('error', reject)
1221
+ })
1222
+ }
1223
+
1224
+ function webSnapshot(ctx) {
1225
+ const scope = { sessionId: 'web-ui' }
1226
+ const state = stateFor(scope)
1227
+ const cfg = loadConfig(ctx, scope)
1228
+ const local = localPlugins()
1229
+ const rows = diffRows(local, state.manifest, state.manifestSource)
1230
+ return {
1231
+ plugins: local.map((plugin) => ({
1232
+ name: plugin.name,
1233
+ version: plugin.version,
1234
+ title: plugin.title,
1235
+ installed: plugin.installed,
1236
+ localFiles: Boolean(plugin.relDir),
1237
+ })),
1238
+ selected: [...state.selected],
1239
+ manifest: state.manifest,
1240
+ rows: rows.map((row) => ({
1241
+ name: row.name,
1242
+ version: row.version,
1243
+ status: row.status,
1244
+ action: row.action || null,
1245
+ subtitle: statusLine(row, false),
1246
+ })),
1247
+ task: readTaskStatus(),
1248
+ results: readTaskResults(),
1249
+ config: { relay: Boolean(cfg.relay.repo), ssh: Boolean(cfg.ssh.host) },
1250
+ }
1251
+ }
1252
+
1253
+ function webPageHtml() {
1254
+ return `<!doctype html>
1255
+ <html lang="zh-CN">
1256
+ <head>
1257
+ <meta charset="utf-8">
1258
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1259
+ <title>插件同步</title>
1260
+ <style>
1261
+ :root{color-scheme:light dark}
1262
+ body{font:14px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;margin:0;padding:16px;max-width:820px;margin-inline:auto}
1263
+ h1{font-size:20px;margin:0 0 4px}h2{font-size:15px;margin:20px 0 8px}
1264
+ .muted{opacity:.65}.row{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0}
1265
+ button{font:inherit;padding:7px 12px;border-radius:8px;border:1px solid #8884;background:#8881;cursor:pointer}
1266
+ button.primary{background:#3D6FD6;border-color:#3D6FD6;color:#fff}
1267
+ button:disabled{opacity:.5;cursor:default}
1268
+ textarea{width:100%;box-sizing:border-box;min-height:88px;font:12px/1.4 ui-monospace,monospace;padding:8px;border-radius:8px;border:1px solid #8884;background:#8881}
1269
+ ul{list-style:none;padding:0;margin:0}
1270
+ li.item{display:flex;align-items:center;gap:8px;padding:6px 4px;border-bottom:1px solid #8882}
1271
+ li.item .name{font-weight:600}li.item .meta{margin-left:auto;font-size:12px;opacity:.7}
1272
+ .status{font-size:12px;opacity:.8}.bad{color:#c62828}.good{color:#2e7d32}
1273
+ </style>
1274
+ </head>
1275
+ <body>
1276
+ <h1>插件同步</h1>
1277
+ <div class="muted">复制同步码到另一台主机导入;只安装缺少的插件,不卸载、不覆盖。</div>
1278
+ <div id="config" class="muted"></div>
1279
+
1280
+ <h2>发送(本机 → 同步码)</h2>
1281
+ <ul id="plugins"></ul>
1282
+ <div class="row">
1283
+ <button id="all">全选</button>
1284
+ <button id="none">清空</button>
1285
+ <button id="copy" class="primary">复制同步码</button>
1286
+ </div>
1287
+ <textarea id="code" placeholder="生成的同步码会显示在这里" readonly></textarea>
1288
+
1289
+ <h2>接收(同步码 → 本机)</h2>
1290
+ <textarea id="importCode" placeholder="粘贴 DSHSYNC1: 开头的同步码"></textarea>
1291
+ <div class="row"><button id="import" class="primary">导入同步码</button></div>
1292
+ <ul id="diff"></ul>
1293
+ <div class="row"><button id="apply" class="primary">安装选中</button></div>
1294
+
1295
+ <h2>状态</h2>
1296
+ <div id="status" class="status"></div>
1297
+ <div id="results"></div>
1298
+ <script>
1299
+ (function(){
1300
+ var localSelected=new Set(), diffSelected=new Set(), current={};
1301
+ function el(t,c,x){var n=document.createElement(t);if(c)n.className=c;if(x!=null)n.textContent=x;return n}
1302
+ function api(p,b){var o=b===undefined?{}:{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(b)};return fetch('api/'+p,o).then(function(r){return r.json()})}
1303
+ function setStatus(t,c){var n=document.getElementById('status');n.textContent=t;n.className='status'+(c?' '+c:'')}
1304
+ function renderPlugins(list){var ul=document.getElementById('plugins');ul.textContent='';(list||[]).forEach(function(p){var li=el('li','item');var cb=el('input');cb.type='checkbox';cb.checked=localSelected.has(p.name);cb.onchange=function(){if(cb.checked)localSelected.add(p.name);else localSelected.delete(p.name)};li.appendChild(cb);li.appendChild(el('span','name',p.name));li.appendChild(el('span','meta','v'+p.version+(p.installed?' · 已安装':' · 未安装')));ul.appendChild(li)})}
1305
+ function renderDiff(rows){var ul=document.getElementById('diff');ul.textContent='';if(!rows||!rows.length){ul.appendChild(el('li','muted','导入后在这里选择要安装的插件'));return}rows.forEach(function(r){var li=el('li','item');var cb=el('input');cb.type='checkbox';cb.disabled=!r.action;cb.checked=diffSelected.has(r.name);cb.onchange=function(){if(cb.checked)diffSelected.add(r.name);else diffSelected.delete(r.name)};li.appendChild(cb);li.appendChild(el('span','name',r.name));li.appendChild(el('span','meta',r.subtitle));ul.appendChild(li)})}
1306
+ function renderResults(list){var box=document.getElementById('results');box.textContent='';(list||[]).forEach(function(r){box.appendChild(el('div',r.ok?'good':'bad',(r.ok?'✓ ':'✗ ')+r.name+(r.message?' — '+r.message:'')))})}
1307
+ function renderTask(t){if(!t){setStatus('就绪');return}if(t.running){setStatus('正在执行…');return}setStatus(t.ok===false?('上次失败 '+t.failed+' 项'):'上次完成',t.ok===false?'bad':'good')}
1308
+ function refresh(){return api('state').then(function(s){if(s.error){setStatus(s.error,'bad');return}current=s;localSelected=new Set(s.selected||[]);diffSelected=new Set(s.selected||[]);renderPlugins(s.plugins);renderDiff(s.rows);renderResults(s.results);renderTask(s.task);var c=s.config||{};document.getElementById('config').textContent='中转:'+(c.relay?'已配置':'未配置')+' · SSH:'+(c.ssh?'已配置':'未配置')})}
1309
+ function poll(){api('status').then(function(s){if(s.task)renderTask(s.task);if(s.results)renderResults(s.results);if(s.task&&!s.task.running)refresh()}).catch(function(){})}
1310
+ document.getElementById('all').onclick=function(){(current.plugins||[]).forEach(function(p){localSelected.add(p.name)});renderPlugins(current.plugins)};
1311
+ document.getElementById('none').onclick=function(){localSelected.clear();renderPlugins(current.plugins)};
1312
+ document.getElementById('copy').onclick=function(){api('export',{names:Array.from(localSelected)}).then(function(r){if(r.error){setStatus(r.error,'bad');return}document.getElementById('code').value=r.code;if(navigator.clipboard)navigator.clipboard.writeText(r.code).catch(function(){});setStatus('已生成 '+r.count+' 个插件的同步码','good')})};
1313
+ document.getElementById('import').onclick=function(){var code=document.getElementById('importCode').value.trim();if(!code){setStatus('先粘贴同步码','bad');return}api('import',{code:code}).then(function(r){if(r.error){setStatus(r.error,'bad');return}setStatus('已导入 '+r.count+' 个插件,选中 '+r.selected+' 个','good');refresh()})};
1314
+ document.getElementById('apply').onclick=function(){var names=Array.from(diffSelected);if(!names.length){setStatus('先选择要安装的插件','bad');return}api('apply',{names:names}).then(function(r){if(r.error){setStatus(r.error,'bad');return}setStatus('已开始安装 '+r.count+' 项','good');refresh()})};
1315
+ refresh();setInterval(poll,3000);
1316
+ })();
1317
+ </script>
1318
+ </body>
1319
+ </html>`
1320
+ }
1321
+
1322
+ // ---------------------------------------------------------------- plugin
1323
+
1324
+ export function apply(ctx) {
1325
+ ctx.inject(['dshGo'], (ctx) => {
1326
+ const copyConfig = (scope) => {
1327
+ const target = writableDir(ctx, scope) || storeDir()
1328
+ const path = join(target, CONFIG_FILE)
1329
+ try {
1330
+ ensureStore()
1331
+ mkdirSync(target, { recursive: true })
1332
+ if (!existsSync(path)) writeFileSync(path, configTemplate())
1333
+ } catch {
1334
+ return { toast: '写配置模板失败' }
1335
+ }
1336
+ return [{ toast: '已生成配置模板,改完刷新' }, { copy: path }, { refresh: true }]
1337
+ }
1338
+
1339
+ const copyCode = (scope) => {
1340
+ const all = localPlugins()
1341
+ const state = stateFor(scope)
1342
+ const chosen = state.selected.size > 0
1343
+ ? all.filter((plugin) => state.selected.has(plugin.name))
1344
+ : all
1345
+ const result = buildSyncCode(chosen)
1346
+ if (result.error === 'empty') return { toast: '除本插件外没有其他插件' }
1347
+ if (result.error) return { toast: '同步码太大,改用导出清单' }
1348
+ const label = state.selected.size > 0 ? '已复制选中' : '已复制全部'
1349
+ return [{ copy: result.code }, { toast: `${label} ${result.plugins} 个插件` }, { refresh: true }]
1350
+ }
1351
+
1352
+ const relayPush = (scope) => {
1353
+ const cfg = loadConfig(ctx, scope)
1354
+ if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
1355
+ const local = localPlugins()
1356
+ const pushable = local.filter((plugin) => plugin.relDir && SAFE_DIR.test(plugin.relDir))
1357
+ if (pushable.length === 0) return { toast: '本机没有可推送的插件' }
1358
+ const manifest = buildManifest(local)
1359
+ try {
1360
+ ensureStore()
1361
+ writeFileSync(pushManifestFile(), JSON.stringify(manifest, null, 2) + '\n')
1362
+ } catch {
1363
+ return { toast: '写清单失败' }
1364
+ }
1365
+ startTask('relay-push', buildRelayPush(cfg, pushable, pushManifestFile()))
1366
+ return [{ toast: `已开始推送 ${pushable.length} 个插件` }, { refresh: true }]
1367
+ }
1368
+
1369
+ const relayPull = (scope) => {
1370
+ const cfg = loadConfig(ctx, scope)
1371
+ if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
1372
+ const state = stateFor(scope)
1373
+ state.relayLoadedAt = 0
1374
+ startTask('relay-pull', buildRelayPull(cfg))
1375
+ return [{ toast: '已开始拉取中转' }, { refresh: true }]
1376
+ }
1377
+
1378
+ const sshTest = (scope) => {
1379
+ const cfg = loadConfig(ctx, scope)
1380
+ if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
1381
+ startTask('ssh-test', buildSshTest(cfg))
1382
+ return [{ toast: '正在测试 SSH' }, { refresh: true }]
1383
+ }
1384
+
1385
+ const sshScan = (scope) => {
1386
+ const cfg = loadConfig(ctx, scope)
1387
+ if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
1388
+ const state = stateFor(scope)
1389
+ state.sshLoadedAt = 0
1390
+ startTask('ssh-scan', buildSshScan(cfg))
1391
+ return [{ toast: '正在拉远端清单' }, { refresh: true }]
1392
+ }
1393
+
1394
+ const retryFailed = (scope) => {
1395
+ const cfg = loadConfig(ctx, scope)
1396
+ const state = stateFor(scope)
1397
+ const failed = readTaskResults().filter((result) => !result.ok)
1398
+ if (failed.length === 0) return { toast: '没有失败项' }
1399
+ const names = new Set(failed.map((result) => result.name))
1400
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
1401
+ const jobs = rows.filter((row) => names.has(row.name) && row.action)
1402
+ if (jobs.length === 0) return { toast: '失败项已不在列表' }
1403
+ if (jobs.some((row) => row.action === 'push' || row.action === 'pull') && !cfg.ssh.host) {
1404
+ return { toast: '先配置 ssh.host' }
1405
+ }
1406
+ startTask('apply', buildApply(cfg, jobs))
1407
+ return [{ toast: `重试 ${jobs.length} 项` }, { refresh: true }]
1408
+ }
1409
+
1410
+ ctx.dshGo.panel('sync', {
1411
+ view(scope, caps) {
1412
+ try {
1413
+ return buildView(scope, caps, ctx)
1414
+ } catch (error) {
1415
+ return {
1416
+ type: 'stack',
1417
+ title: '插件同步',
1418
+ children: [{ type: 'text', text: `视图出错:${String(error?.message ?? error).slice(0, 100)}` }],
1419
+ }
1420
+ }
1421
+ },
1422
+
1423
+ data(scope, emit) {
1424
+ emit({ paste: { code: '' } })
1425
+ return () => {}
1426
+ },
1427
+
1428
+ actions: {
1429
+ 'copy-code': copyCode,
1430
+
1431
+ 'import-code'(scope, event) {
1432
+ const text = codeFromSubmit(event?.value)
1433
+ if (text === '') return { toast: '先粘贴同步码' }
1434
+ const result = applySyncCode(scope, text, '面板粘贴')
1435
+ if (result.error) return { toast: result.error }
1436
+ const toast = result.count === 0
1437
+ ? '已导入,没有插件'
1438
+ : `已导入 ${result.count} 个插件,选中 ${result.selected} 个`
1439
+ return [{ toast }, { patch: { paste: { code: '' } } }, { refresh: true }]
1440
+ },
1441
+
1442
+ export(scope) {
1443
+ const local = localPlugins()
1444
+ const manifest = buildManifest(local)
1445
+ const target = exportTarget(ctx, scope)
1446
+ try {
1447
+ ensureStore()
1448
+ mkdirSync(dirname(target), { recursive: true })
1449
+ writeFileSync(target, JSON.stringify(manifest, null, 2) + '\n')
1450
+ } catch {
1451
+ return { toast: '导出失败,检查工作区权限' }
1452
+ }
1453
+ const state = stateFor(scope)
1454
+ state.lastExportPath = target
1455
+ return [{ toast: '已导出插件清单' }, { copy: target }, { refresh: true }]
1456
+ },
1457
+
1458
+ 'import-workspace'(scope) {
1459
+ const candidates = []
1460
+ const dir = writableDir(ctx, scope)
1461
+ if (dir) candidates.push(join(dir, MANIFEST_FILE))
1462
+ candidates.push(exportTarget(ctx, scope), join(storeDir(), MANIFEST_FILE))
1463
+ for (const candidate of candidates) {
1464
+ if (!existsSync(candidate)) continue
1465
+ try {
1466
+ return importBuffer(scope, readFileSync(candidate), candidate, 'file')
1467
+ } catch {}
1468
+ }
1469
+ return { toast: `工作区没有 ${MANIFEST_FILE}` }
1470
+ },
1471
+
1472
+ toggle(scope, event) {
1473
+ const target = event?.value
1474
+ const name = typeof target === 'string' ? target : target?.name
1475
+ if (typeof name !== 'string') return { toast: '没有找到这一项' }
1476
+ const state = stateFor(scope)
1477
+ if (state.selected.has(name)) state.selected.delete(name)
1478
+ else state.selected.add(name)
1479
+ return { refresh: true }
1480
+ },
1481
+
1482
+ 'select-all'(scope) {
1483
+ const state = stateFor(scope)
1484
+ if (!state.manifest) {
1485
+ for (const plugin of localPlugins()) state.selected.add(plugin.name)
1486
+ return { refresh: true }
1487
+ }
1488
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
1489
+ for (const row of rows) state.selected.add(row.name)
1490
+ return { refresh: true }
1491
+ },
1492
+
1493
+ clear(scope) {
1494
+ stateFor(scope).selected.clear()
1495
+ return { refresh: true }
1496
+ },
1497
+
1498
+ refresh() {
1499
+ return { refresh: true }
1500
+ },
1501
+
1502
+ 'copy-config'(scope) {
1503
+ return copyConfig(scope)
1504
+ },
1505
+
1506
+ 'relay-push': relayPush,
1507
+ 'relay-pull': relayPull,
1508
+ 'ssh-test': sshTest,
1509
+ 'ssh-scan': sshScan,
1510
+ 'retry-failed': retryFailed,
1511
+
1512
+ guide() {
1513
+ return { open: 'panel:guide' }
1514
+ },
1515
+
1516
+ apply(scope, event) {
1517
+ if (event?.value?.confirmed !== true) return { toast: '已取消' }
1518
+ const cfg = loadConfig(ctx, scope)
1519
+ const state = stateFor(scope)
1520
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
1521
+ const jobs = rows.filter((row) => state.selected.has(row.name) && row.action)
1522
+ if (jobs.length === 0) {
1523
+ return { toast: state.selected.size > 0 ? '选中的都已安装' : '没有可执行的项' }
1524
+ }
1525
+ if (jobs.some((job) => job.action === 'install' && !job.localDir && !job.registrySpec)) {
1526
+ return { toast: '有项找不到安装来源' }
1527
+ }
1528
+ if (jobs.some((job) => job.action === 'push' || job.action === 'pull') && !cfg.ssh.host) {
1529
+ return { toast: '推/拉远端要先配置 ssh.host' }
1530
+ }
1531
+ startTask('apply', buildApply(cfg, jobs))
1532
+ state.selected.clear()
1533
+ return [{ toast: `已开始处理 ${jobs.length} 项` }, { refresh: true }]
1534
+ },
1535
+ },
1536
+ })
1537
+
1538
+ ctx.dshGo.panel('guide', {
1539
+ view(scope, caps) {
1540
+ try {
1541
+ return buildGuide(scope, caps, ctx)
1542
+ } catch {
1543
+ return { type: 'stack', title: '使用引导', children: [{ type: 'text', text: '引导加载失败' }] }
1544
+ }
1545
+ },
1546
+ actions: {
1547
+ 'copy-config'(scope) {
1548
+ return copyConfig(scope)
1549
+ },
1550
+ 'relay-push': relayPush,
1551
+ 'relay-pull': relayPull,
1552
+ 'ssh-test': sshTest,
1553
+ 'ssh-scan': sshScan,
1554
+ 'retry-failed': retryFailed,
1555
+ back() {
1556
+ return { open: 'panel:sync' }
1557
+ },
1558
+ },
1559
+ })
1560
+
1561
+ ctx.dshGo.strip('pending', (scope, emit, caps) => {
1562
+ const en = String(caps?.locale || '').toLowerCase().startsWith('en')
1563
+ const tick = () => {
1564
+ try { emit(stripValue(scope, en)) } catch {}
1565
+ }
1566
+ tick()
1567
+ const timer = setInterval(tick, 60_000)
1568
+ timer.unref?.()
1569
+ return () => clearInterval(timer)
1570
+ })
1571
+
1572
+ function importBuffer(scope, buffer, sourceName, kind) {
1573
+ let doc
1574
+ try {
1575
+ doc = JSON.parse(Buffer.isBuffer(buffer) ? buffer.toString('utf8') : String(buffer))
1576
+ } catch {
1577
+ return { toast: '文件不是合法 JSON' }
1578
+ }
1579
+ const manifest = validManifest(doc)
1580
+ if (!manifest) return { toast: '清单格式不对' }
1581
+ if (manifest.plugins.length === 0) return { toast: '清单里没有可同步插件' }
1582
+ const state = stateFor(scope)
1583
+ state.manifest = manifest
1584
+ state.manifestSource = { kind: kind || 'file' }
1585
+ state.importedAt = new Date().toISOString()
1586
+ state.sourceName = typeof sourceName === 'string' ? sourceName : null
1587
+ state.selected.clear()
1588
+ persistImported(state)
1589
+ return [{ toast: `已导入 ${manifest.plugins.length} 个插件` }, { refresh: true }]
1590
+ }
1591
+ })
1592
+
1593
+ ctx.inject(['webServer'], (webCtx) => {
1594
+ const handler = async (req, res) => {
1595
+ try {
1596
+ let rejection
1597
+ try { rejection = ctx.connection?.requestRejection?.(req) } catch {}
1598
+ if (rejection !== undefined) { res.writeHead(rejection); res.end(); return }
1599
+ const url = new URL(req.url || '/', 'http://dsh.local')
1600
+ const path = url.pathname.replace(/\/+$/, '') || '/'
1601
+ if (req.method === 'GET' && (path === '/dsh-go-plugin-sync' || url.pathname === '/dsh-go-plugin-sync/')) {
1602
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
1603
+ res.end(webPageHtml())
1604
+ return
1605
+ }
1606
+ if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/state') {
1607
+ webJson(res, 200, webSnapshot(ctx))
1608
+ return
1609
+ }
1610
+ if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/status') {
1611
+ webJson(res, 200, { task: readTaskStatus(), results: readTaskResults() })
1612
+ return
1613
+ }
1614
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/export') {
1615
+ const body = JSON.parse((await webReadBody(req)) || '{}')
1616
+ const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
1617
+ const all = localPlugins()
1618
+ const chosen = names.length > 0 ? all.filter((plugin) => names.includes(plugin.name)) : all
1619
+ const result = buildSyncCode(chosen)
1620
+ if (result.error === 'empty') { webJson(res, 200, { error: '没有可同步的插件' }); return }
1621
+ if (result.error) { webJson(res, 200, { error: '同步码太大,请减少插件或改用中转' }); return }
1622
+ webJson(res, 200, { code: result.code, count: result.plugins, withFiles: result.withFiles })
1623
+ return
1624
+ }
1625
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/import') {
1626
+ const body = JSON.parse((await webReadBody(req)) || '{}')
1627
+ const code = typeof body.code === 'string' ? body.code : ''
1628
+ const result = applySyncCode({ sessionId: 'web-ui' }, code, '网页版')
1629
+ if (result.error) { webJson(res, 200, { error: result.error }); return }
1630
+ webJson(res, 200, { ok: true, count: result.count, selected: result.selected })
1631
+ return
1632
+ }
1633
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/apply') {
1634
+ const body = JSON.parse((await webReadBody(req)) || '{}')
1635
+ const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
1636
+ const scope = { sessionId: 'web-ui' }
1637
+ const cfg = loadConfig(ctx, scope)
1638
+ const state = stateFor(scope)
1639
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
1640
+ const jobs = rows.filter((row) => names.includes(row.name) && row.action)
1641
+ if (jobs.length === 0) { webJson(res, 200, { error: '没有可安装的项' }); return }
1642
+ if (jobs.some((job) => job.action === 'push' || job.action === 'pull') && !cfg.ssh.host) {
1643
+ webJson(res, 200, { error: '先配置 ssh.host' }); return
1644
+ }
1645
+ startTask('apply', buildApply(cfg, jobs))
1646
+ webJson(res, 200, { ok: true, count: jobs.length })
1647
+ return
1648
+ }
1649
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
1650
+ res.end('not found')
1651
+ } catch (error) {
1652
+ try { webJson(res, 500, { error: String(error?.message || error) }) } catch {}
1653
+ }
1654
+ }
1655
+ ctx.effect(() => webCtx.webServer.register({ kind: 'prefix', path: '/dsh-go-plugin-sync', handler }), 'dsh-go-plugin-sync: web ui')
1656
+ })
1657
+ }