dsh-go-plugin-sync 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,1938 +1,2138 @@
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 taskRunnerPath = () => join(storeDir(), 'task-runner.cjs')
58
- const taskSpecPath = () => join(storeDir(), 'task-spec.json')
59
- const taskLogPath = () => join(storeDir(), 'task.log')
60
- const taskStatusPath = () => join(storeDir(), 'task-status.txt')
61
-
62
- function readJson(path) {
63
- try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return undefined }
64
- }
65
-
66
- function ensureStore() {
67
- mkdirSync(storeDir(), { recursive: true })
68
- }
69
-
70
- function shQuote(value) {
71
- return `'${String(value).replace(/'/g, `'\\''`)}'`
72
- }
73
-
74
- function safeName(value) {
75
- return typeof value === 'string' && (PKG_NAME.test(value) || SAFE_DIR.test(value))
76
- }
77
-
78
- /** A single directory name directly under the plugins root. */
79
- function safeDirName(value) {
80
- return typeof value === 'string' && value !== '.' && value !== '..' && SAFE_DIR.test(value)
81
- }
82
-
83
- /** Token used in task log markers; keeps `@@ action name start` one line and inert. */
84
- function markerName(value) {
85
- return String(value).replace(/[^A-Za-z0-9._@/-]/g, '_').slice(0, 80) || '_'
86
- }
87
-
88
- function safeRel(value) {
89
- if (typeof value !== 'string' || value.length === 0 || value.length > 200) return false
90
- if (value.includes('\\') || value.includes('\0') || value.startsWith('/') || value.includes('..')) return false
91
- return REL_RE.test(value) && TEXT_EXT.has(extname(value).toLowerCase())
92
- }
93
-
94
- // ---------------------------------------------------------------- sync code
95
-
96
- /** Text files of one plugin directory, relative paths -> contents. */
97
- function readPluginTextFiles(dir) {
98
- const files = {}
99
- let total = 0
100
- const walk = (base, rel, depth) => {
101
- if (depth > 4 || total > 200_000) return
102
- let entries
103
- try { entries = readdirSync(base, { withFileTypes: true }) } catch { return }
104
- for (const entry of entries) {
105
- if (entry.name === 'node_modules' || entry.name === '.git') continue
106
- const full = join(base, entry.name)
107
- const next = rel ? `${rel}/${entry.name}` : entry.name
108
- if (entry.isDirectory()) { walk(full, next, depth + 1); continue }
109
- if (!entry.isFile() || !TEXT_EXT.has(extname(entry.name).toLowerCase())) continue
110
- let text
111
- try { text = readFileSync(full, 'utf8') } catch { continue }
112
- if (text.length > 100_000) continue
113
- total += text.length
114
- if (total > 200_000) return
115
- files[next] = text
116
- }
117
- }
118
- walk(dir, '', 0)
119
- return files
120
- }
121
-
122
- function encodeSyncPayload(payload) {
123
- return CODE_PREFIX + deflateRawSync(Buffer.from(JSON.stringify(payload), 'utf8')).toString('base64url')
124
- }
125
-
126
- /** Compact sync code: manifest + (when it fits) text files of local plugins. */
127
- function buildSyncCode(plugins) {
128
- const entries = plugins
129
- .filter((plugin) => plugin.name !== name)
130
- .map((plugin) => ({
131
- name: plugin.name,
132
- version: plugin.version,
133
- hash: plugin.hash,
134
- relDir: plugin.relDir,
135
- depSpec: plugin.depSpec,
136
- kind: plugin.kind || null,
137
- files: safeDirName(plugin.relDir) && existsSync(plugin.dir)
138
- ? readPluginTextFiles(plugin.dir)
139
- : {},
140
- }))
141
- if (entries.length === 0) return { error: 'empty' }
142
- let code = encodeSyncPayload({ v: 2, t: 'dsh-go-plugin-sync', at: new Date().toISOString(), plugins: entries })
143
- let withFiles = entries.filter((entry) => Object.keys(entry.files).length > 0).length
144
- if (code.length > CODE_BUDGET) {
145
- code = encodeSyncPayload({
146
- v: 2,
147
- t: 'dsh-go-plugin-sync',
148
- at: new Date().toISOString(),
149
- plugins: entries.map(({ files, ...rest }) => rest),
150
- })
151
- withFiles = 0
152
- }
153
- if (code.length > 2000) return { error: 'too-large' }
154
- return { code, plugins: entries.length, withFiles }
155
- }
156
-
157
- function decodeSyncCode(text) {
158
- const trimmed = String(text || '').trim().replace(/\s+/g, '')
159
- if (!trimmed.startsWith(CODE_PREFIX)) return { error: '不是同步码' }
160
- const body = trimmed.slice(CODE_PREFIX.length)
161
- if (body.length > 100_000) return { error: '同步码太大' }
162
- let doc
163
- try {
164
- doc = JSON.parse(inflateRawSync(Buffer.from(body, 'base64url'), { maxOutputLength: 2 * 1024 * 1024 }).toString('utf8'))
165
- } catch {
166
- return { error: '同步码损坏或过大' }
167
- }
168
- if (!doc || doc.v !== 2 || doc.t !== 'dsh-go-plugin-sync' || !Array.isArray(doc.plugins)) return { error: '同步码版本不对' }
169
- const plugins = []
170
- for (const raw of doc.plugins.slice(0, 200)) {
171
- if (!raw || typeof raw.name !== 'string' || !safeName(raw.name)) continue
172
- const relDir = safeDirName(raw.relDir) ? raw.relDir : null
173
- const files = {}
174
- if (raw.files && typeof raw.files === 'object') {
175
- for (const [rel, content] of Object.entries(raw.files)) {
176
- if (!safeRel(rel) || typeof content !== 'string' || content.length > 100_000) continue
177
- files[rel] = content
178
- }
179
- }
180
- plugins.push({
181
- name: raw.name,
182
- version: typeof raw.version === 'string' ? raw.version : '0.0.0',
183
- hash: typeof raw.hash === 'string' ? raw.hash : null,
184
- relDir,
185
- depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
186
- kind: raw.kind === 'native' || raw.kind === 'bundle' || raw.kind === 'both' ? raw.kind : null,
187
- files,
188
- })
189
- }
190
- if (plugins.length === 0) return { error: '同步码里没有可同步插件' }
191
- return {
192
- plugins,
193
- manifest: {
194
- v: MANIFEST_V,
195
- generator: 'dsh-go-plugin-sync',
196
- exportedAt: typeof doc.at === 'string' ? doc.at : null,
197
- host: { profile: 'sync-code' },
198
- plugins: plugins.map(({ files, ...rest }) => rest),
199
- },
200
- }
201
- }
202
-
203
- /** Materialize text files for plugins this host does not have yet (never overwrites). */
204
- function writeCodeFiles(decoded) {
205
- let written = 0
206
- for (const plugin of decoded.plugins) {
207
- if (!safeDirName(plugin.relDir) || Object.keys(plugin.files).length === 0) continue
208
- const dir = join(pluginsRoot(), plugin.relDir)
209
- if (existsSync(dir)) continue
210
- try {
211
- mkdirSync(dir, { recursive: true })
212
- for (const [rel, content] of Object.entries(plugin.files)) {
213
- const target = join(dir, rel)
214
- mkdirSync(dirname(target), { recursive: true })
215
- writeFileSync(target, content)
216
- }
217
- written++
218
- } catch {}
219
- }
220
- return written
221
- }
222
-
223
- /** Read the pasted code from a v2 form submit (`event.value.values['data.paste.code']`). */
224
- function codeFromSubmit(value) {
225
- const values = value?.values
226
- if (values && typeof values === 'object') {
227
- const direct = values['data.paste.code']
228
- if (typeof direct === 'string') return direct.trim()
229
- for (const candidate of Object.values(values)) {
230
- if (typeof candidate === 'string' && candidate.trim().startsWith(CODE_PREFIX)) return candidate.trim()
231
- }
232
- }
233
- if (typeof value === 'string') return value.trim()
234
- return ''
235
- }
236
-
237
- /** Decode a sync code, materialize files, and preselect every row (all by default). */
238
- function applySyncCode(scope, text, sourceName, host = {}) {
239
- const decoded = decodeSyncCode(text)
240
- if (decoded.error) return { error: decoded.error }
241
- const state = stateFor(scope)
242
- state.manifest = decoded.manifest
243
- state.manifestSource = { kind: 'code' }
244
- state.importedAt = new Date().toISOString()
245
- state.sourceName = sourceName
246
- persistImported(state)
247
- writeCodeFiles(decoded)
248
- const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, host)
249
- const manifestNames = new Set(decoded.manifest.plugins.map((plugin) => plugin.name))
250
- state.selected.clear()
251
- let selected = 0
252
- for (const row of rows) {
253
- if (!manifestNames.has(row.name)) continue
254
- if (!row.action) continue
255
- if (host.dshGo === true && row.kind === 'bundle') continue
256
- state.selected.add(row.name)
257
- selected++
258
- }
259
- return {
260
- count: decoded.manifest.plugins.length,
261
- selected,
262
- installable: rows.filter((row) => row.action === 'install').length,
263
- }
264
- }
265
-
266
- // ---------------------------------------------------------------- config
267
-
268
- function expandHome(value) {
269
- if (typeof value !== 'string' || value === '') return ''
270
- if (value === '~') return process.env.HOME || '/root'
271
- if (value.startsWith('~/')) return join(process.env.HOME || '/root', value.slice(2))
272
- return value
273
- }
274
-
275
- function normalizeConfig(raw) {
276
- const relay = raw?.relay && typeof raw.relay === 'object' ? raw.relay : {}
277
- const ssh = raw?.ssh && typeof raw.ssh === 'object' ? raw.ssh : {}
278
- const port = Number(ssh.port)
279
- const profile = typeof ssh.profile === 'string' && SAFE_PROFILE.test(ssh.profile) ? ssh.profile : profileName()
280
- return {
281
- relay: {
282
- repo: typeof relay.repo === 'string' ? relay.repo.trim() : '',
283
- branch: typeof relay.branch === 'string' && relay.branch.trim() !== '' ? relay.branch.trim() : 'main',
284
- dir: typeof relay.dir === 'string' && SAFE_DIR.test(relay.dir) ? relay.dir : 'dsh-go-plugins',
285
- },
286
- ssh: {
287
- host: typeof ssh.host === 'string' ? ssh.host.trim() : '',
288
- port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 22,
289
- user: typeof ssh.user === 'string' ? ssh.user.trim() : '',
290
- identity: typeof ssh.identity === 'string' ? expandHome(ssh.identity.trim()) : '',
291
- remoteHome: typeof ssh.remoteHome === 'string' && ssh.remoteHome.trim() !== '' ? ssh.remoteHome.trim() : '~/.dsh',
292
- dshPath: typeof ssh.dshPath === 'string' && ssh.dshPath.trim() !== '' ? ssh.dshPath.trim() : 'dsh',
293
- nodePath: typeof ssh.nodePath === 'string' && ssh.nodePath.trim() !== '' ? ssh.nodePath.trim() : 'node',
294
- profile,
295
- },
296
- }
297
- }
298
-
299
- function loadConfig(ctx, scope) {
300
- const candidates = []
301
- const ws = writableDir(ctx, scope)
302
- if (ws) candidates.push(join(ws, CONFIG_FILE))
303
- candidates.push(join(storeDir(), CONFIG_FILE))
304
- for (const path of candidates) {
305
- const raw = readJson(path)
306
- if (raw && typeof raw === 'object') return normalizeConfig(raw)
307
- }
308
- return normalizeConfig({})
309
- }
310
-
311
- function configTemplate() {
312
- return JSON.stringify({
313
- relay: { repo: 'https://github.com/you/dsh-plugins.git', branch: 'main', dir: 'dsh-go-plugins' },
314
- ssh: { host: '192.168.1.10', port: 22, user: 'root', identity: '', remoteHome: '~/.dsh', dshPath: 'dsh', nodePath: 'node', profile: 'web' },
315
- }, null, 2) + '\n'
316
- }
317
-
318
- // ---------------------------------------------------------------- local scan
319
-
320
- function collectFiles(root, out, depth = 0) {
321
- if (depth > 6 || out.length >= MAX_FILES) return
322
- let entries
323
- try { entries = readdirSync(root, { withFileTypes: true }) } catch { return }
324
- for (const entry of entries) {
325
- if (out.length >= MAX_FILES) return
326
- const full = join(root, entry.name)
327
- if (entry.isDirectory()) collectFiles(full, out, depth + 1)
328
- else if (entry.isFile()) out.push(full)
329
- }
330
- }
331
-
332
- function shortHash(dir) {
333
- const hash = createHash('sha256')
334
- try { hash.update(readFileSync(join(dir, 'package.json'))) } catch { return null }
335
- const files = []
336
- collectFiles(join(dir, 'lib'), files)
337
- files.sort()
338
- let total = 0
339
- for (const file of files) {
340
- let bytes
341
- try { bytes = readFileSync(file) } catch { continue }
342
- if (bytes.length > MAX_FILE_BYTES) continue
343
- total += bytes.length
344
- if (total > MAX_TOTAL_BYTES) break
345
- hash.update(relative(dir, file).split(sep).join('/'))
346
- hash.update('\0')
347
- hash.update(bytes)
348
- hash.update('\0')
349
- }
350
- return hash.digest('hex').slice(0, 16)
351
- }
352
-
353
- /** A syncable plugin: a dsh-go native plugin or a Cordis bundle (official bundles excluded). */
354
- function syncablePkg(pkg) {
355
- if (!pkg || typeof pkg.name !== 'string') return false
356
- if (pkg.name === name || pkg.name.startsWith('@deepseek-ai/')) return false
357
- const native = pkg.dshGo && typeof pkg.dshGo === 'object'
358
- const bundle = pkg.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle
359
- return Boolean(native || bundle)
360
- }
361
-
362
- function titleOf(pkg) {
363
- const title = pkg?.dshGo?.title
364
- if (typeof title === 'string') return title
365
- if (title && typeof title === 'object') return title.zh || title.en || ''
366
- return typeof pkg?.displayName === 'string' ? pkg.displayName : ''
367
- }
368
-
369
- function pluginKind(pkg) {
370
- const native = Boolean(pkg?.dshGo && typeof pkg.dshGo === 'object')
371
- const bundle = Boolean(pkg?.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle)
372
- if (native && bundle) return 'both'
373
- if (native) return 'native'
374
- if (bundle) return 'bundle'
375
- return null
376
- }
377
-
378
- function makeEntry(pkg, dir, relDir, depSpec) {
379
- return {
380
- name: pkg.name,
381
- version: typeof pkg.version === 'string' ? pkg.version : '0.0.0',
382
- title: titleOf(pkg).slice(0, 40),
383
- hash: shortHash(dir),
384
- relDir: relDir || null,
385
- depSpec: depSpec || null,
386
- kind: pluginKind(pkg),
387
- dir,
388
- installed: false,
389
- }
390
- }
391
-
392
- function scanSourcePlugins() {
393
- const root = pluginsRoot()
394
- const out = []
395
- let entries
396
- try { entries = readdirSync(root, { withFileTypes: true }) } catch { return out }
397
- for (const entry of entries) {
398
- if (!entry.isDirectory() || entry.name.startsWith('.')) continue
399
- const dir = join(root, entry.name)
400
- const pkg = readJson(join(dir, 'package.json'))
401
- if (!syncablePkg(pkg)) continue
402
- out.push(makeEntry(pkg, dir, entry.name, null))
403
- }
404
- return out
405
- }
406
-
407
- function scanInstalledPlugins() {
408
- const profile = readJson(join(profileDir(), 'package.json'))
409
- const deps = profile?.dependencies
410
- if (!deps || typeof deps !== 'object') return []
411
- const out = []
412
- for (const [dep, spec] of Object.entries(deps)) {
413
- const dir = join(profileDir(), 'node_modules', dep)
414
- const pkg = readJson(join(dir, 'package.json'))
415
- if (!syncablePkg(pkg)) continue
416
- let relDir = null
417
- if (typeof spec === 'string' && (spec.startsWith('link:') || spec.startsWith('file:'))) {
418
- const raw = spec.slice(spec.indexOf(':') + 1)
419
- const rel = relative(pluginsRoot(), resolve(profileDir(), raw))
420
- if (rel && !rel.startsWith('..') && !rel.startsWith(sep) && !rel.includes('\0')) relDir = rel
421
- }
422
- const entry = makeEntry(pkg, dir, relDir, spec)
423
- entry.installed = true
424
- out.push(entry)
425
- }
426
- return out
427
- }
428
-
429
- function localPlugins() {
430
- const map = new Map()
431
- for (const plugin of scanSourcePlugins()) map.set(plugin.name, plugin)
432
- for (const plugin of scanInstalledPlugins()) {
433
- const previous = map.get(plugin.name)
434
- if (previous) {
435
- previous.installed = true
436
- previous.depSpec = plugin.depSpec
437
- if (!previous.relDir) previous.relDir = plugin.relDir
438
- } else {
439
- map.set(plugin.name, plugin)
440
- }
441
- }
442
- return [...map.values()]
443
- }
444
-
445
- function localPluginsCached() {
446
- const key = home()
447
- if (scanCache.key === key && Date.now() - scanCache.at < 2000) return scanCache.value
448
- const value = localPlugins()
449
- scanCache = { key, at: Date.now(), value }
450
- return value
451
- }
452
-
453
- // ---------------------------------------------------------------- manifest
454
-
455
- function buildManifest(plugins) {
456
- return {
457
- v: MANIFEST_V,
458
- generator: 'dsh-go-plugin-sync',
459
- exportedAt: new Date().toISOString(),
460
- host: { profile: profileName() },
461
- plugins: plugins.map((plugin) => ({
462
- name: plugin.name,
463
- version: plugin.version,
464
- title: plugin.title,
465
- hash: plugin.hash,
466
- relDir: plugin.relDir,
467
- depSpec: plugin.depSpec,
468
- kind: plugin.kind || null,
469
- installed: plugin.installed === true,
470
- })),
471
- }
472
- }
473
-
474
- function validManifest(doc) {
475
- if (!doc || typeof doc !== 'object' || doc.v !== MANIFEST_V || !Array.isArray(doc.plugins)) return undefined
476
- const plugins = []
477
- for (const raw of doc.plugins.slice(0, 200)) {
478
- if (!raw || typeof raw !== 'object' || typeof raw.name !== 'string' || raw.name.length > 120) continue
479
- if (raw.name === name) continue
480
- plugins.push({
481
- name: raw.name,
482
- version: typeof raw.version === 'string' ? raw.version : '0.0.0',
483
- title: typeof raw.title === 'string' ? raw.title.slice(0, 40) : '',
484
- hash: typeof raw.hash === 'string' ? raw.hash.slice(0, 64) : null,
485
- relDir: safeDirName(raw.relDir) ? raw.relDir : null,
486
- kind: raw.kind === 'native' || raw.kind === 'bundle' || raw.kind === 'both' ? raw.kind : null,
487
- depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
488
- installed: raw.installed === true,
489
- })
490
- }
491
- return {
492
- v: MANIFEST_V,
493
- generator: 'dsh-go-plugin-sync',
494
- exportedAt: typeof doc.exportedAt === 'string' ? doc.exportedAt : null,
495
- host: doc.host && typeof doc.host === 'object' ? { profile: String(doc.host.profile ?? '') } : undefined,
496
- plugins,
497
- }
498
- }
499
-
500
- /** A plain `name@version` registry spec, when the manifest has no local files. */
501
- function registrySpecOf(remote) {
502
- const version = String(remote?.version || '')
503
- if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) return null
504
- const spec = remote?.depSpec
505
- if (typeof spec === 'string' && spec !== '') {
506
- if (/^(file:|link:|workspace:|portal:|exec:|git\+|github:|https?:|\.{0,2}\/|~\/)/i.test(spec)) return null
507
- }
508
- return `${remote.name}@${version}`
509
- }
510
-
511
- function diffRows(local, manifest, source, host = {}) {
512
- const nativeHost = host.dshGo === true
513
- const localByName = new Map(local.map((plugin) => [plugin.name, plugin]))
514
- const manifestByName = new Map((manifest?.plugins ?? []).map((plugin) => [plugin.name, plugin]))
515
- const rows = []
516
- for (const remote of manifest?.plugins ?? []) {
517
- const here = localByName.get(remote.name)
518
- const remoteDir = remote.relDir || remote.name
519
- const kind = remote.kind || here?.kind || null
520
- if (!nativeHost && kind === 'native') {
521
- rows.push({ name: remote.name, version: remote.version, remoteVersion: remote.version, status: 'native-only', action: null, kind })
522
- continue
523
- }
524
- if (!here) {
525
- let action = null
526
- let localDir = null
527
- let registrySpec = null
528
- if (source?.kind === 'ssh') {
529
- if (safeDirName(remote.relDir)) {
530
- action = 'pull'
531
- } else {
532
- registrySpec = registrySpecOf(remote)
533
- if (registrySpec) action = 'install'
534
- }
535
- } else {
536
- if (source?.kind === 'relay') localDir = join(source.pluginsDir, remoteDir)
537
- else if (remote.relDir) localDir = join(pluginsRoot(), remote.relDir)
538
- if (localDir && existsSync(join(localDir, 'package.json'))) {
539
- action = 'install'
540
- } else {
541
- localDir = null
542
- registrySpec = registrySpecOf(remote)
543
- if (registrySpec) action = 'install'
544
- }
545
- }
546
- rows.push({
547
- name: remote.name,
548
- version: remote.version,
549
- remoteVersion: remote.version,
550
- status: action ? (nativeHost && kind === 'bundle' ? 'web-only' : 'installable') : 'missing',
551
- action,
552
- kind,
553
- localDir,
554
- registrySpec,
555
- dirName: remoteDir,
556
- })
557
- continue
558
- }
559
- const same = (!remote.hash || !here.hash || remote.hash === here.hash) && remote.version === here.version
560
- if (!same) {
561
- rows.push({ name: here.name, version: here.version, remoteVersion: remote.version, status: 'conflict', action: null, kind })
562
- } else if (!here.installed) {
563
- rows.push({ name: here.name, version: here.version, status: nativeHost && kind === 'bundle' ? 'web-only' : 'install', action: 'install', kind, localDir: here.dir })
564
- } else {
565
- rows.push({ name: here.name, version: here.version, status: 'same', action: null, kind })
566
- }
567
- }
568
- for (const here of local) {
569
- if (manifestByName.has(here.name)) continue
570
- if (source?.kind === 'ssh') {
571
- if (safeDirName(here.relDir)) {
572
- rows.push({ name: here.name, version: here.version, status: 'push', action: 'push', kind: here.kind || null, dirName: here.relDir })
573
- } else {
574
- const registrySpec = registrySpecOf({ name: here.name, version: here.version })
575
- rows.push(registrySpec
576
- ? { name: here.name, version: here.version, status: 'push', action: 'push-npm', kind: here.kind || null, registrySpec }
577
- : { name: here.name, version: here.version, status: 'extra', action: null, kind: here.kind || null })
578
- }
579
- } else {
580
- rows.push({ name: here.name, version: here.version, status: 'extra', action: null, kind: here.kind || null })
581
- }
582
- }
583
- const order = { conflict: 0, installable: 1, install: 2, push: 3, extra: 4, missing: 5, same: 6, 'native-only': 7, 'web-only': 8 }
584
- rows.sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9) || a.name.localeCompare(b.name))
585
- return rows
586
- }
587
-
588
- // ---------------------------------------------------------------- state
589
-
590
- function stateKey(scope) {
591
- return scope?.sessionId || 'global'
592
- }
593
-
594
- function loadImported() {
595
- const raw = readJson(importFile())
596
- const manifest = raw ? validManifest(raw.manifest) : undefined
597
- const usable = manifest && manifest.plugins.length > 0 ? manifest : null
598
- return {
599
- manifest: usable,
600
- manifestSource: usable ? { kind: 'file' } : null,
601
- importedAt: typeof raw?.importedAt === 'string' ? raw.importedAt : null,
602
- sourceName: typeof raw?.sourceName === 'string' ? raw.sourceName.slice(0, 120) : null,
603
- selected: new Set(),
604
- lastExportPath: null,
605
- lastPastedCode: null,
606
- relayLoadedAt: 0,
607
- sshLoadedAt: 0,
608
- }
609
- }
610
-
611
- function stateFor(scope) {
612
- const key = stateKey(scope)
613
- let state = STATE.get(key)
614
- if (!state) {
615
- state = loadImported()
616
- STATE.set(key, state)
617
- }
618
- return state
619
- }
620
-
621
- function persistImported(state) {
622
- try {
623
- ensureStore()
624
- writeFileSync(importFile(), JSON.stringify({
625
- importedAt: state.importedAt,
626
- sourceName: state.sourceName,
627
- manifest: state.manifest,
628
- }, null, 2) + '\n')
629
- } catch {}
630
- }
631
-
632
- function loadManifestFrom(path, kind, pluginsDir) {
633
- try {
634
- const stat = statSync(path)
635
- return { manifest: validManifest(readJson(path)), mtime: stat.mtimeMs, source: { kind, pluginsDir } }
636
- } catch {
637
- return null
638
- }
639
- }
640
-
641
- /** Refresh the state manifest from relay / ssh results when those files are newer. */
642
- function refreshManifests(state, cfg) {
643
- const relay = loadManifestFrom(relayManifestFile(), 'relay', join(relayWorkDir(), cfg.relay.dir, 'plugins'))
644
- if (relay?.manifest && relay.manifest.plugins.length > 0 && relay.mtime > state.relayLoadedAt) {
645
- state.manifest = relay.manifest
646
- state.manifestSource = relay.source
647
- state.importedAt = relay.manifest.exportedAt
648
- state.sourceName = 'Git 中转'
649
- state.relayLoadedAt = relay.mtime
650
- state.selected.clear()
651
- }
652
- const ssh = loadManifestFrom(sshManifestFile(), 'ssh', null)
653
- if (ssh?.manifest && ssh.manifest.plugins.length > 0 && ssh.mtime > state.sshLoadedAt) {
654
- state.manifest = ssh.manifest
655
- state.manifestSource = ssh.source
656
- state.importedAt = ssh.manifest.exportedAt
657
- state.sourceName = 'SSH 远端'
658
- state.sshLoadedAt = ssh.mtime
659
- state.selected.clear()
660
- }
661
- }
662
-
663
- // ---------------------------------------------------------------- run status
664
-
665
- function readTaskStatus() {
666
- try {
667
- const parts = readFileSync(taskStatusPath(), 'utf8').trim().split(/\s+/)
668
- const started = Number(parts[1]) || 0
669
- if (parts[0] === 'running') return { running: true, startedAt: started * 1000, kind: parts[2] || '' }
670
- if (parts[0] === 'done') {
671
- const failed = Number(parts[2]) || 0
672
- return { running: false, finishedAt: started * 1000, failed, kind: parts[3] || '', ok: failed === 0 }
673
- }
674
- } catch {}
675
- return null
676
- }
677
-
678
- function readLogTail(max = 4) {
679
- try {
680
- const lines = readFileSync(taskLogPath(), 'utf8').trim().split('\n').filter(Boolean)
681
- return lines.slice(-max).map((line) => line.length > 120 ? `${line.slice(0, 120)}…` : line)
682
- } catch {
683
- return []
684
- }
685
- }
686
-
687
- /** Per-item results of the last task, parsed from `@@ action name start|ok|fail` markers. */
688
- function readTaskResults() {
689
- let text
690
- try { text = readFileSync(taskLogPath(), 'utf8') } catch { return [] }
691
- const results = []
692
- let current
693
- for (const raw of text.split('\n')) {
694
- const marker = /^@@ (\S+) (\S+) (start|ok|fail)$/.exec(raw)
695
- if (marker) {
696
- const [, action, name, phase] = marker
697
- if (phase === 'start') {
698
- current = { action, name, lines: [] }
699
- continue
700
- }
701
- if (current && current.action === action && current.name === name) {
702
- results.push({
703
- action,
704
- name,
705
- ok: phase === 'ok',
706
- message: phase === 'fail' ? current.lines.slice(-2).join(' ').slice(0, 140) : '',
707
- })
708
- current = undefined
709
- }
710
- continue
711
- }
712
- if (current) current.lines.push(raw.trim())
713
- }
714
- return results
715
- }
716
-
717
- // ---------------------------------------------------------------- task runner
718
-
719
- function taskRunning() {
720
- const status = readTaskStatus()
721
- return Boolean(status?.running && Date.now() - status.startedAt < 15 * 60 * 1000)
722
- }
723
-
724
- /** Start one background task; returns `{ ok }` or an explanation of why it did not start. */
725
- function startTask(kind, lines, win) {
726
- if (taskRunning()) return { ok: false, error: '已有任务在运行,等它结束再试' }
727
- ensureStore()
728
- if (process.platform === 'win32') return startWindowsTask(kind, win)
729
- const script = [
730
- '#!/bin/sh',
731
- `LOG=${shQuote(taskLogPath())}`,
732
- `STATUS=${shQuote(taskStatusPath())}`,
733
- `PROFILE=${shQuote(profileName())}`,
734
- 'DSH_BIN="${DSH_BIN:-$(command -v dsh || echo /usr/local/bin/dsh)}"',
735
- ': > "$LOG"',
736
- 'failed=0',
737
- 'say() { echo "$@" >> "$LOG"; }',
738
- ...lines,
739
- `echo "done $(date +%s) $failed ${kind}" > "$STATUS"`,
740
- ].join('\n') + '\n'
741
- writeFileSync(taskScriptPath(), script, { mode: 0o755 })
742
- writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} ${kind}\n`)
743
- const child = spawn('/bin/sh', [taskScriptPath()], { detached: true, stdio: 'ignore', env: process.env })
744
- child.on('error', () => {})
745
- child.unref()
746
- return { ok: true }
747
- }
748
-
749
- /** `dsh` entry point that also works from a packaged Windows runtime. */
750
- function dshCommand() {
751
- const entry = typeof process.argv[1] === 'string' ? process.argv[1] : ''
752
- if (/\.(?:c|m)?js$/i.test(entry)) return { command: process.execPath, args: [entry] }
753
- const bin = process.env.DSH_BIN || ''
754
- if (/\.(?:c|m)?js$/i.test(bin)) return { command: process.execPath, args: [bin] }
755
- if (bin) return { command: bin, args: [] }
756
- return { command: process.execPath, args: [entry] }
757
- }
758
-
759
- /** Windows has no `/bin/sh`; install jobs run through Node instead of the POSIX task script. */
760
- function startWindowsTask(kind, win) {
761
- const installs = kind === 'apply' && Array.isArray(win?.installs)
762
- ? win.installs.filter((job) => job && typeof job.name === 'string' && typeof job.target === 'string' && job.target !== '')
763
- : []
764
- if (kind === 'apply' && (win?.other || 0) > 0) {
765
- return { ok: false, error: 'Windows 上暂不支持 SSH 推/拉,请先只选安装项' }
766
- }
767
- if (installs.length === 0) return { ok: false, error: 'Windows 上暂不支持 Git 中转 / SSH,请用同步码安装' }
768
- const dsh = dshCommand()
769
- const spec = {
770
- kind,
771
- log: taskLogPath(),
772
- status: taskStatusPath(),
773
- items: installs.map((job) => ({
774
- action: 'install',
775
- name: markerName(job.name),
776
- commands: [{ command: dsh.command, args: [...dsh.args, 'plugin', '--profile', profileName(), 'add', job.target] }],
777
- })),
778
- }
779
- writeFileSync(taskRunnerPath(), windowsTaskRunnerSource())
780
- writeFileSync(taskSpecPath(), JSON.stringify(spec, null, 2) + '\n')
781
- writeFileSync(taskLogPath(), '')
782
- writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} ${kind}\n`)
783
- try {
784
- const child = spawn(process.execPath, [taskRunnerPath(), taskSpecPath()], { detached: true, stdio: 'ignore', env: process.env })
785
- child.on('error', () => {})
786
- child.unref()
787
- } catch (error) {
788
- writeFileSync(taskStatusPath(), `done ${Math.floor(Date.now() / 1000)} ${installs.length} ${kind}\n`)
789
- return { ok: false, error: `启动安装任务失败:${String(error?.message || error)}` }
790
- }
791
- return { ok: true }
792
- }
793
-
794
- function windowsTaskRunnerSource() {
795
- return `'use strict'
796
- const { spawn } = require('node:child_process')
797
- const fs = require('node:fs')
798
- const spec = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'))
799
- const log = fs.openSync(spec.log, 'w')
800
- const say = (line) => fs.writeSync(log, line + '\\n')
801
- const status = (line) => fs.writeFileSync(spec.status, line + '\\n')
802
- status('running ' + Math.floor(Date.now() / 1000) + ' ' + spec.kind)
803
- function run(command, args) {
804
- return new Promise((resolve) => {
805
- let child
806
- try {
807
- child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], env: process.env })
808
- } catch (error) {
809
- say(String(error && error.message ? error.message : error))
810
- resolve(1)
811
- return
812
- }
813
- child.stdout.on('data', (chunk) => fs.writeSync(log, chunk))
814
- child.stderr.on('data', (chunk) => fs.writeSync(log, chunk))
815
- child.on('error', (error) => { say(String(error && error.message ? error.message : error)); resolve(1) })
816
- child.on('exit', (code) => resolve(code === 0 ? 0 : 1))
817
- })
818
- }
819
- ;(async () => {
820
- let failed = 0
821
- for (const item of spec.items) {
822
- say('@@ ' + item.action + ' ' + item.name + ' start')
823
- let code = 0
824
- for (const command of item.commands) {
825
- if (await run(command.command, command.args) !== 0) code = 1
826
- }
827
- if (code === 0) say('@@ ' + item.action + ' ' + item.name + ' ok')
828
- else { failed += 1; say('@@ ' + item.action + ' ' + item.name + ' fail') }
829
- }
830
- fs.closeSync(log)
831
- status('done ' + Math.floor(Date.now() / 1000) + ' ' + failed + ' ' + spec.kind)
832
- })().catch((error) => {
833
- try { say(String(error && error.stack ? error.stack : error)) } catch {}
834
- try { fs.closeSync(log) } catch {}
835
- try { status('done ' + Math.floor(Date.now() / 1000) + ' 1 ' + spec.kind) } catch {}
836
- })
837
- `
838
- }
839
-
840
- function localAddCommand(dir) {
841
- return `"$DSH_BIN" plugin --profile "$PROFILE" add ${shQuote(dir)}`
842
- }
843
-
844
- /** Install jobs through the host's own plugin manager (same path as the plugin market). */
845
- function startInstallTask(ctx, jobs) {
846
- const manager = ctx.get?.('pluginManager')
847
- if (!manager || typeof manager.installBundle !== 'function') return null
848
- if (taskRunning()) return { ok: false, error: '已有任务在运行,等它结束再试' }
849
- ensureStore()
850
- writeFileSync(taskLogPath(), '')
851
- writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} apply\n`)
852
- const installs = jobs.filter((job) => job.action === 'install')
853
- const say = (line) => { try { writeFileSync(taskLogPath(), `${line}\n`, { flag: 'a' }) } catch {} }
854
- ;(async () => {
855
- let failed = 0
856
- for (const job of installs) {
857
- const name = markerName(job.name)
858
- const target = job.localDir || job.registrySpec
859
- say(`@@ install ${name} start`)
860
- if (!target) {
861
- failed += 1
862
- say(`@@ install ${name} fail`)
863
- say('no install source')
864
- continue
865
- }
866
- try {
867
- const result = await manager.installBundle(target, { enabled: true })
868
- if (result && result.ok === false) {
869
- failed += 1
870
- say(String(result.error?.message || result.error || 'install failed').slice(0, 2000))
871
- say(`@@ install ${name} fail`)
872
- } else {
873
- say(`@@ install ${name} ok`)
874
- const value = result && result.value !== undefined ? result.value : result
875
- try { say(JSON.stringify(value).slice(0, 2000)) } catch {}
876
- }
877
- } catch (error) {
878
- failed += 1
879
- say(String(error && (error.stack || error.message) || error).slice(0, 2000))
880
- say(`@@ install ${name} fail`)
881
- }
882
- }
883
- try { writeFileSync(taskStatusPath(), `done ${Math.floor(Date.now() / 1000)} ${failed} apply\n`) } catch {}
884
- })()
885
- return { ok: true }
886
- }
887
-
888
- /** Prefer the plugin manager for pure installs; keep the shell path for SSH push/pull. */
889
- function startApplyTask(ctx, cfg, jobs) {
890
- if (jobs.every((job) => job.action === 'install')) {
891
- const started = startInstallTask(ctx, jobs)
892
- if (started) return started
893
- }
894
- return startTask('apply', buildApply(cfg, jobs), winTask(jobs))
895
- }
896
-
897
- /** One result-reporting item: start marker, commands, ok/fail marker. */
898
- function itemLines(action, name, commands) {
899
- const tag = `${action} ${markerName(name)}`
900
- const lines = [`say "@@ ${tag} start"`, 'itemfailed=0']
901
- for (const command of commands) {
902
- lines.push(`${command} >> "$LOG" 2>&1 || itemfailed=$((itemfailed + 1))`)
903
- }
904
- lines.push(`if [ "$itemfailed" -eq 0 ]; then say "@@ ${tag} ok"; else failed=$((failed + 1)); say "@@ ${tag} fail"; fi`)
905
- return lines
906
- }
907
-
908
- function sshPrelude(cfg) {
909
- const target = cfg.ssh.user ? `${cfg.ssh.user}@${cfg.ssh.host}` : cfg.ssh.host
910
- const keyOpt = cfg.ssh.identity ? `-i ${shQuote(cfg.ssh.identity)}` : ''
911
- return [
912
- `SSH_PORT=${shQuote(String(cfg.ssh.port))}`,
913
- `SSH_TARGET=${shQuote(target)}`,
914
- `SSH_KEY_OPT=${shQuote(keyOpt)}`,
915
- 'ssh_run() { ssh -p "$SSH_PORT" -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 $SSH_KEY_OPT "$@"; }',
916
- ]
917
- }
918
-
919
- function remotePaths(cfg) {
920
- const home = cfg.ssh.remoteHome
921
- const plugins = `${home}/dsh-go/plugins`
922
- return { home, plugins }
923
- }
924
-
925
- function buildRelayPush(cfg, plugins, manifestPath) {
926
- const work = relayWorkDir()
927
- const lines = [
928
- `RELAY_REPO=${shQuote(cfg.relay.repo)}`,
929
- `RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
930
- `RELAY_DIR=${shQuote(cfg.relay.dir)}`,
931
- `WORK=${shQuote(work)}`,
932
- 'if [ -d "$WORK/.git" ]; then',
933
- ' say "pull relay"',
934
- ' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
935
- 'else',
936
- ' rm -rf "$WORK"',
937
- ' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
938
- ' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
939
- 'fi',
940
- 'if [ "$failed" -eq 0 ]; then',
941
- ' rm -rf "$WORK/$RELAY_DIR/plugins"',
942
- ' mkdir -p "$WORK/$RELAY_DIR/plugins"',
943
- ]
944
- for (const plugin of plugins) {
945
- if (!safeDirName(plugin.relDir)) continue
946
- 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))`)
947
- }
948
- lines.push(
949
- ` cp ${shQuote(manifestPath)} "$WORK/$RELAY_DIR/manifest.json" >> "$LOG" 2>&1 || failed=$((failed + 1))`,
950
- ' git -C "$WORK" add -A >> "$LOG" 2>&1',
951
- ' git -C "$WORK" -c user.name=dsh-go -c user.email=dsh-go@local commit -m "plugin-sync $(date +%s)" >> "$LOG" 2>&1 || true',
952
- ' git -C "$WORK" push origin "$RELAY_BRANCH" >> "$LOG" 2>&1 || failed=$((failed + 1))',
953
- 'fi',
954
- )
955
- return lines
956
- }
957
-
958
- function buildRelayPull(cfg) {
959
- const work = relayWorkDir()
960
- const relayManifest = relayManifestFile()
961
- return [
962
- `RELAY_REPO=${shQuote(cfg.relay.repo)}`,
963
- `RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
964
- `RELAY_DIR=${shQuote(cfg.relay.dir)}`,
965
- `WORK=${shQuote(work)}`,
966
- 'if [ -d "$WORK/.git" ]; then',
967
- ' say "pull relay"',
968
- ' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
969
- 'else',
970
- ' rm -rf "$WORK"',
971
- ' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
972
- ' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
973
- 'fi',
974
- 'if [ "$failed" -eq 0 ] && [ -f "$WORK/$RELAY_DIR/manifest.json" ]; then',
975
- ` cp "$WORK/$RELAY_DIR/manifest.json" ${shQuote(relayManifest)} >> "$LOG" 2>&1 || failed=$((failed + 1))`,
976
- 'elif [ "$failed" -eq 0 ]; then',
977
- ' say "relay has no manifest"',
978
- ' failed=$((failed + 1))',
979
- 'fi',
980
- ]
981
- }
982
-
983
- function buildSshTest(cfg) {
984
- return [...sshPrelude(cfg), 'ssh_run "$SSH_TARGET" "true" >> "$LOG" 2>&1 || failed=$((failed + 1))']
985
- }
986
-
987
- function buildSshScan(cfg) {
988
- const { home } = remotePaths(cfg)
989
- const profileDir = `${home}/profiles/${cfg.ssh.profile}`
990
- const scanner = remoteScannerFile()
991
- writeFileSync(scanner, remoteScannerSource())
992
- return [
993
- ...sshPrelude(cfg),
994
- `ssh_run "$SSH_TARGET" "${cfg.ssh.nodePath} - ${home} ${profileDir}" < ${shQuote(scanner)} > ${shQuote(sshManifestFile())} 2>> "$LOG" || failed=$((failed + 1))`,
995
- ]
996
- }
997
-
998
- function buildSshPush(cfg, jobs) {
999
- const { home, plugins } = remotePaths(cfg)
1000
- const dsh = cfg.ssh.dshPath
1001
- const profile = cfg.ssh.profile
1002
- const lines = [...sshPrelude(cfg)]
1003
- for (const job of jobs.filter((item) => item.action === 'push' && safeName(item.dirName))) {
1004
- lines.push(...itemLines('push', job.name, [
1005
- `tar -C ${shQuote(pluginsRoot())} -czf - --exclude=node_modules --exclude=.git ${shQuote(job.dirName)} | ssh_run "$SSH_TARGET" "mkdir -p ${plugins} && tar -C ${plugins} -xzf -"`,
1006
- `ssh_run "$SSH_TARGET" "cd ${home} && ${dsh} plugin --profile ${profile} add ${plugins}/${job.dirName}"`,
1007
- ]))
1008
- }
1009
- for (const job of jobs.filter((item) => item.action === 'push-npm' && item.registrySpec)) {
1010
- lines.push(...itemLines('push', job.name, [
1011
- `ssh_run "$SSH_TARGET" "cd ${home} && ${dsh} plugin --profile ${profile} add ${shQuote(job.registrySpec)}"`,
1012
- ]))
1013
- }
1014
- return lines
1015
- }
1016
-
1017
- function buildSshPull(cfg, jobs) {
1018
- const { plugins } = remotePaths(cfg)
1019
- const lines = [...sshPrelude(cfg)]
1020
- for (const job of jobs.filter((item) => safeName(item.dirName))) {
1021
- lines.push(...itemLines('pull', job.name, [
1022
- `ssh_run "$SSH_TARGET" "tar -C ${plugins} -czf - ${job.dirName}" | tar -C ${shQuote(pluginsRoot())} -xzf -`,
1023
- localAddCommand(join(pluginsRoot(), job.dirName)),
1024
- ]))
1025
- }
1026
- return lines
1027
- }
1028
-
1029
- function installTargets(jobs) {
1030
- return jobs
1031
- .filter((job) => job.action === 'install')
1032
- .map((job) => ({ name: job.name, target: job.localDir || job.registrySpec }))
1033
- }
1034
-
1035
- /** Windows task payload: install jobs only, plus how many push/pull jobs were left out. */
1036
- function winTask(jobs) {
1037
- const installs = installTargets(jobs)
1038
- return { installs, other: jobs.length - installs.length }
1039
- }
1040
-
1041
- function buildApply(cfg, jobs) {
1042
- const lines = []
1043
- const installs = jobs.filter((job) => job.action === 'install')
1044
- const pushes = jobs.filter((job) => job.action === 'push' || job.action === 'push-npm')
1045
- const pulls = jobs.filter((job) => job.action === 'pull')
1046
- for (const job of installs) {
1047
- const target = job.localDir || job.registrySpec
1048
- if (target) lines.push(...itemLines('install', job.name, [localAddCommand(target)]))
1049
- }
1050
- if (pushes.length > 0) lines.push(...buildSshPush(cfg, pushes))
1051
- if (pulls.length > 0) lines.push(...buildSshPull(cfg, pulls))
1052
- return lines
1053
- }
1054
-
1055
- let SCANNER_CACHE
1056
- function remoteScannerSource() {
1057
- if (SCANNER_CACHE) return SCANNER_CACHE
1058
- SCANNER_CACHE = `const fs = require('fs')
1059
- const path = require('path')
1060
- const crypto = require('crypto')
1061
- const home = process.argv[2]
1062
- const profileDir = process.argv[3] || path.join(home, 'profiles', 'web')
1063
- const root = path.join(home, 'dsh-go', 'plugins')
1064
- const out = new Map()
1065
- function kind(pkg) {
1066
- const native = Boolean(pkg.dshGo && typeof pkg.dshGo === 'object')
1067
- const bundle = Boolean(pkg.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle)
1068
- if (native && bundle) return 'both'
1069
- if (native) return 'native'
1070
- if (bundle) return 'bundle'
1071
- return null
1072
- }
1073
- function usable(pkg) {
1074
- if (!pkg || typeof pkg.name !== 'string') return false
1075
- if (pkg.name.startsWith('@deepseek-ai/') || pkg.name === 'dsh-go-plugin-sync') return false
1076
- return kind(pkg) !== null
1077
- }
1078
- function walk(dir, acc, depth) {
1079
- if (depth > 6 || acc.length >= 300) return
1080
- let entries
1081
- try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
1082
- for (const e of entries) {
1083
- if (acc.length >= 300) return
1084
- const full = path.join(dir, e.name)
1085
- if (e.isDirectory()) walk(full, acc, depth + 1)
1086
- else if (e.isFile()) acc.push(full)
1087
- }
1088
- }
1089
- function hash(dir) {
1090
- const h = crypto.createHash('sha256')
1091
- try { h.update(fs.readFileSync(path.join(dir, 'package.json'))) } catch { return null }
1092
- const files = []
1093
- walk(path.join(dir, 'lib'), files, 0)
1094
- files.sort()
1095
- for (const f of files) {
1096
- let b
1097
- try { b = fs.readFileSync(f) } catch { continue }
1098
- if (b.length > 2097152) continue
1099
- h.update(path.relative(dir, f).split(path.sep).join('/'))
1100
- h.update(String.fromCharCode(0))
1101
- h.update(b)
1102
- }
1103
- return h.digest('hex').slice(0, 16)
1104
- }
1105
- try {
1106
- for (const e of fs.readdirSync(root, { withFileTypes: true })) {
1107
- if (!e.isDirectory() || e.name.startsWith('.')) continue
1108
- const dir = path.join(root, e.name)
1109
- let pkg
1110
- try { pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')) } catch { continue }
1111
- if (!usable(pkg)) continue
1112
- out.set(pkg.name, { name: pkg.name, version: String(pkg.version || '0.0.0'), hash: hash(dir), relDir: e.name, depSpec: null, kind: kind(pkg), installed: false })
1113
- }
1114
- } catch {}
1115
- try {
1116
- const profile = JSON.parse(fs.readFileSync(path.join(profileDir, 'package.json'), 'utf8'))
1117
- const deps = profile.dependencies || {}
1118
- for (const [dep, spec] of Object.entries(deps)) {
1119
- let pkg
1120
- try { pkg = JSON.parse(fs.readFileSync(path.join(profileDir, 'node_modules', dep, 'package.json'), 'utf8')) } catch { continue }
1121
- if (!usable(pkg)) continue
1122
- let relDir = null
1123
- if (typeof spec === 'string' && (spec.startsWith('link:') || spec.startsWith('file:'))) {
1124
- const raw = spec.slice(spec.indexOf(':') + 1)
1125
- const rel = path.relative(root, path.resolve(profileDir, raw))
1126
- if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) relDir = rel.split(path.sep).join('/')
1127
- }
1128
- const entry = { name: pkg.name, version: String(pkg.version || '0.0.0'), hash: hash(path.join(profileDir, 'node_modules', dep)), relDir, depSpec: typeof spec === 'string' ? spec : null, kind: kind(pkg), installed: true }
1129
- const existing = out.get(pkg.name)
1130
- if (existing) {
1131
- existing.installed = true
1132
- existing.depSpec = entry.depSpec
1133
- if (!existing.relDir) existing.relDir = entry.relDir
1134
- if (!existing.hash) existing.hash = entry.hash
1135
- if (!existing.kind) existing.kind = entry.kind
1136
- } else {
1137
- out.set(pkg.name, entry)
1138
- }
1139
- }
1140
- } catch {}
1141
- process.stdout.write(JSON.stringify({ v: 1, exportedAt: new Date().toISOString(), host: { profile: path.basename(profileDir) }, plugins: [...out.values()] }))
1142
- `
1143
- return SCANNER_CACHE
1144
- }
1145
-
1146
- // ---------------------------------------------------------------- workspace
1147
-
1148
- function workspaceCandidates(ctx, scope) {
1149
- const out = []
1150
- try {
1151
- const registry = ctx?.get?.('workspaceRegistry')
1152
- if (registry && typeof registry.list === 'function') {
1153
- const list = registry.list() || []
1154
- if (scope?.sessionId) {
1155
- const match = list.find((w) => Array.isArray(w.sessionIds) && w.sessionIds.includes(scope.sessionId))
1156
- if (match?.path) out.push(match.path)
1157
- }
1158
- for (const w of list) if (w?.path) out.push(w.path)
1159
- }
1160
- } catch {}
1161
- if (process.env.DSH_WORKSPACE) out.push(process.env.DSH_WORKSPACE)
1162
- out.push(process.cwd(), join(home(), 'workspace'))
1163
- return [...new Set(out)]
1164
- }
1165
-
1166
- function writableDir(ctx, scope) {
1167
- for (const dir of workspaceCandidates(ctx, scope)) {
1168
- try {
1169
- accessSync(dir, constants.W_OK)
1170
- if (statSync(dir).isDirectory()) return dir
1171
- } catch {}
1172
- }
1173
- return null
1174
- }
1175
-
1176
- function exportTarget(ctx, scope) {
1177
- const dir = writableDir(ctx, scope)
1178
- return dir ? join(dir, MANIFEST_FILE) : join(storeDir(), MANIFEST_FILE)
1179
- }
1180
-
1181
- // ---------------------------------------------------------------- view
1182
-
1183
- function enableText(caps) {
1184
- return String(caps?.locale || '').toLowerCase().startsWith('en')
1185
- }
1186
-
1187
- function statusLine(row, en) {
1188
- let text = {
1189
- same: en ? 'same' : '一致',
1190
- conflict: en ? 'conflict: local vs manifest differ' : '冲突:本机与清单不同',
1191
- install: en ? 'not installed yet' : '本机未安装',
1192
- installable: en ? 'can install from this manifest' : '可从这份清单安装',
1193
- missing: en ? 'files not on this host' : '本机缺少文件,需手动拷贝',
1194
- extra: en ? 'not in manifest' : '清单里没有',
1195
- push: en ? 'remote lacks it; can push' : '远端没有,可推送',
1196
- 'native-only': en ? 'phone-only native plugin; not supported here' : '手机端原生插件,电脑端不支持',
1197
- 'web-only': en ? 'desktop/web plugin; no native UI on the phone' : '电脑/网页端插件,手机无原生界面',
1198
- }[row.status] || row.status
1199
- if (row.status !== 'web-only' && row.status !== 'native-only') {
1200
- if (row.action === 'install' && row.registrySpec) text = en ? 'install from npm' : '可从 npm 安装'
1201
- else if (row.action === 'install' && row.localDir) text = en ? 'install from files' : '可从文件安装'
1202
- else if (row.action === 'pull') text = en ? 'pull from remote' : '可从远端拉取'
1203
- else if (row.action === 'push-npm') text = en ? 'remote installs it from npm' : '远端从 npm 安装'
1204
- }
1205
- const version = row.status === 'conflict' && row.remoteVersion && row.remoteVersion !== row.version
1206
- ? `${row.version} → ${row.remoteVersion}`
1207
- : row.version
1208
- return `${version} · ${text}`
1209
- }
1210
-
1211
- function statusTone(status) {
1212
- if (status === 'conflict' || status === 'extra') return 'warn'
1213
- if (status === 'installable' || status === 'install' || status === 'push') return 'info'
1214
- if (status === 'missing') return 'bad'
1215
- return undefined
1216
- }
1217
-
1218
- const TASK_LABELS = {
1219
- apply: ['应用所选', 'apply selected'],
1220
- 'relay-push': ['推送中转', 'push to relay'],
1221
- 'relay-pull': ['拉取中转', 'pull from relay'],
1222
- 'ssh-test': ['测试 SSH', 'test SSH'],
1223
- 'ssh-scan': ['拉远端清单', 'scan remote'],
1224
- }
1225
-
1226
- function taskLabel(kind, en) {
1227
- return TASK_LABELS[kind]?.[en ? 1 : 0] || kind
1228
- }
1229
-
1230
- function buildView(scope, caps, ctx) {
1231
- const en = enableText(caps)
1232
- const cfg = loadConfig(ctx, scope)
1233
- const state = stateFor(scope)
1234
- refreshManifests(state, cfg)
1235
- const local = localPluginsCached()
1236
- const rows = diffRows(local, state.manifest, state.manifestSource, { dshGo: true })
1237
- const components = Array.isArray(caps?.components) ? caps.components : []
1238
- const canForm = components.includes('form') && components.includes('textField')
1239
- const children = []
1240
-
1241
- children.push({ type: 'text', text: en
1242
- ? 'Copy a sync code (all or selected), or paste one below. Sync only installs missing plugins; it never touches what you already have.'
1243
- : '复制同步码(全部或选中),或在下面粘贴导入。同步只安装缺少的插件,不会动已有的。' })
1244
-
1245
- if (canForm) {
1246
- children.push({ type: 'form', submit: 'import-code', submitLabel: en ? 'Import code' : '导入同步码', children: [
1247
- {
1248
- type: 'textField',
1249
- label: en ? 'Sync code' : '同步码',
1250
- bind: 'data.paste.code',
1251
- multiline: true,
1252
- maxLines: 8,
1253
- maxLength: 2000,
1254
- placeholder: en ? 'Paste DSHSYNC1:… here' : '在这里粘贴 DSHSYNC1: 开头的同步码',
1255
- },
1256
- ] })
1257
- } else {
1258
- children.push({ type: 'callout', tone: 'info', text: en
1259
- ? 'This app version has no panel input; use the relay or file import.'
1260
- : '当前 App 版本不支持面板输入,请用中转或文件导入。' })
1261
- }
1262
-
1263
- children.push({ type: 'row', children: [
1264
- { type: 'metric', label: en ? 'Local' : '本机', value: String(local.length) },
1265
- { type: 'metric', label: en ? 'Manifest' : '清单', value: state.manifest ? String(state.manifest.plugins.length) : '—' },
1266
- { type: 'metric', label: en ? 'Selected' : '已选', value: String(state.selected.size) },
1267
- ] })
1268
-
1269
- children.push({ type: 'keyValue', items: [
1270
- [en ? 'Relay' : '中转', cfg.relay.repo || (en ? 'not configured' : '未配置')],
1271
- [en ? 'SSH' : 'SSH', cfg.ssh.host ? `${cfg.ssh.user ? `${cfg.ssh.user}@` : ''}${cfg.ssh.host}:${cfg.ssh.port}` : (en ? 'not configured' : '未配置')],
1272
- ] })
1273
-
1274
- const task = readTaskStatus()
1275
- if (task?.running) {
1276
- const stale = Date.now() - task.startedAt > 15 * 60 * 1000
1277
- children.push({ type: 'callout', tone: stale ? 'warn' : 'info', text: stale
1278
- ? (en ? 'A task started long ago; check the log.' : '任务开始很久了,看下日志。')
1279
- : (en ? `${taskLabel(task.kind, true)} running…` : `正在${taskLabel(task.kind, false)}…`) })
1280
- } else if (task && task.ok === false) {
1281
- children.push({ type: 'callout', tone: 'bad', text: en
1282
- ? `${taskLabel(task.kind, true)} failed (${task.failed}). Check the log.`
1283
- : `${taskLabel(task.kind, false)}失败(${task.failed} 项),看日志。` })
1284
- } else if (task?.ok) {
1285
- children.push({ type: 'callout', tone: 'good', text: en
1286
- ? `${taskLabel(task.kind, true)} finished.`
1287
- : `${taskLabel(task.kind, false)}完成。` })
1288
- if (task.kind === 'apply' || task.kind === 'ssh-push' || task.kind === 'ssh-scan') {
1289
- children.push({ type: 'callout', tone: 'warn', text: en
1290
- ? 'Installed plugins need an engine restart on that host.'
1291
- : '装了插件的主机要重启一次引擎才加载。' })
1292
- }
1293
- }
1294
-
1295
- const results = readTaskResults()
1296
- if (results.length > 0) {
1297
- const okCount = results.filter((result) => result.ok).length
1298
- const failed = results.filter((result) => !result.ok)
1299
- children.push({ type: 'text', text: en
1300
- ? `Last run: ${okCount} ok · ${failed.length} failed`
1301
- : `上次结果:成功 ${okCount} · 失败 ${failed.length}` })
1302
- if (failed.length > 0) {
1303
- children.push({ type: 'list', items: failed.slice(0, 8).map((result) => ({
1304
- title: result.name,
1305
- subtitle: result.message || (en ? 'failed' : '失败'),
1306
- tone: 'bad',
1307
- })) })
1308
- }
1309
- }
1310
-
1311
- if (!state.manifest) {
1312
- children.push({ type: 'callout', tone: 'info', text: en
1313
- ? 'Select plugins below, then Copy code; or import a manifest / pull the relay first.'
1314
- : '先在下面选中要同步的插件,再点复制同步码;也可以先导入清单或拉取中转。' })
1315
- if (local.length > 0) {
1316
- const shown = local.slice(0, 40)
1317
- children.push({ type: 'list', items: shown.map((plugin) => ({
1318
- title: plugin.name,
1319
- subtitle: `${plugin.version} · ${en ? 'tap to select' : '点选'}`,
1320
- trailing: state.selected.has(plugin.name) ? '✓' : '○',
1321
- action: { id: 'toggle', args: { name: plugin.name } },
1322
- })) })
1323
- if (local.length > shown.length) {
1324
- children.push({ type: 'text', text: en ? `…and ${local.length - shown.length} more` : `…还有 ${local.length - shown.length} 项` })
1325
- }
1326
- }
1327
- } else {
1328
- const when = state.manifest.exportedAt ? state.manifest.exportedAt.slice(0, 16).replace('T', ' ') : ''
1329
- const source = state.sourceName || state.manifest.host?.profile || ''
1330
- children.push({ type: 'text', text: en
1331
- ? `Manifest: ${source || 'imported'}${when ? ` · ${when}` : ''}`
1332
- : `清单来源:${source || '已导入'}${when ? ` · ${when}` : ''}` })
1333
-
1334
- if (rows.length === 0) {
1335
- children.push({ type: 'callout', tone: 'good', text: en ? 'The two hosts match.' : '两边完全一致。' })
1336
- } else {
1337
- const shown = rows.slice(0, 40)
1338
- children.push({ type: 'list', items: shown.map((row) => {
1339
- const item = {
1340
- title: row.name,
1341
- subtitle: statusLine(row, en),
1342
- trailing: state.selected.has(row.name) ? '✓' : '○',
1343
- action: { id: 'toggle', args: { name: row.name } },
1344
- }
1345
- const tone = statusTone(row.status)
1346
- if (tone) item.tone = tone
1347
- return item
1348
- }) })
1349
- if (rows.length > shown.length) {
1350
- children.push({ type: 'text', text: en ? `…and ${rows.length - shown.length} more` : `…还有 ${rows.length - shown.length} 项` })
1351
- }
1352
- }
1353
-
1354
- }
1355
-
1356
- const primary = [
1357
- { label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
1358
- { label: en ? 'Select all' : '全选', action: 'select-all' },
1359
- { label: en ? 'Clear' : '清空', action: 'clear' },
1360
- { label: en ? 'Refresh' : '刷新', action: 'refresh' },
1361
- ]
1362
- children.push({ type: 'actions', items: primary })
1363
-
1364
- children.push({ type: 'actions', items: [
1365
- { label: en ? 'Retry failed' : '重试失败', action: 'retry-failed' },
1366
- { label: en ? 'Export' : '导出清单', action: 'export' },
1367
- { label: en ? 'Read workspace' : '工作区导入', action: 'import-workspace' },
1368
- { label: en ? 'Guide' : '使用引导', action: 'guide' },
1369
- ] })
1370
-
1371
- if (state.manifest && state.selected.size > 0) {
1372
- children.push({ type: 'confirm', id: 'apply', confirmLabel: en ? 'Apply' : '应用所选', cancelLabel: en ? 'Cancel' : '取消' })
1373
- }
1374
-
1375
- const log = readLogTail()
1376
- if (log.length > 0) {
1377
- children.push({ type: 'keyValue', items: log.map((line, index) => [en ? `log ${index + 1}` : `日志 ${index + 1}`, line]) })
1378
- }
1379
-
1380
- const view = { type: 'stack', title: en ? 'Plugin sync' : '插件同步', children }
1381
- if (canForm) view.v = 2
1382
- return view
1383
- }
1384
-
1385
- function buildGuide(scope, caps, ctx) {
1386
- const en = enableText(caps)
1387
- const cfg = loadConfig(ctx, scope)
1388
- const configPath = join(writableDir(ctx, scope) || storeDir(), CONFIG_FILE)
1389
- return {
1390
- type: 'stack',
1391
- title: en ? 'Plugin sync guide' : '插件同步使用引导',
1392
- children: [
1393
- { type: 'text', text: en
1394
- ? 'A copies one string; on B open Sync, paste it into the code field and tap Import.'
1395
- : 'A 主机复制同步码;B 主机打开「插件同步」,把码粘进输入框点「导入同步码」。' },
1396
- { type: 'text', text: en
1397
- ? 'Both hosts need this plugin installed once (manual first time).'
1398
- : '两端都要先装好本插件(第一次手动装)。' },
1399
- { type: 'text', text: en
1400
- ? '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.'
1401
- : '同步只安装缺少的插件,不会卸载或覆盖你已经有的;版本对不上或者装不上的会标出来,但不会自动处理。' },
1402
- { type: 'steps', items: [
1403
- { label: en ? 'Copy on host A' : '在 A 主机复制', status: 'done', detail: en
1404
- ? 'Panel → Copy code'
1405
- : '插件同步面板 → 复制同步码' },
1406
- { label: en ? 'Paste and import on B' : '在 B 粘贴并导入', status: 'current', detail: en
1407
- ? 'Panel → code field → Import code'
1408
- : '面板「同步码」输入框 → 导入同步码' },
1409
- { label: en ? 'Select and apply on B' : '在 B 选中并应用', status: 'todo', detail: en
1410
- ? 'All selected by default; deselect what you do not want'
1411
- : '默认全选,可取消不要的项' },
1412
- { label: en ? 'Retry failures' : '失败项点重试', status: 'todo', detail: en
1413
- ? 'Retry failed in the panel'
1414
- : '面板「重试失败项」' },
1415
- { label: en ? 'Restart the engine' : '重启一次引擎', status: 'todo' },
1416
- ] },
1417
- { type: 'callout', tone: 'info', text: en
1418
- ? 'The code is compressed text: it carries text files. If too large it falls back to manifest only and tries npm versions.'
1419
- : '同步码是压缩文本,带的是文本文件;太大时退化为只带清单,本地插件会尝试按 npm 版本安装。' },
1420
- { type: 'callout', tone: 'warn', text: en
1421
- ? 'Only paste codes from a source you trust: plugin code runs on this host.'
1422
- : '只粘贴可信来源的同步码:插件代码会在本机运行。' },
1423
- { type: 'text', text: en
1424
- ? 'Cordis bundles may depend on the DSH version or platform; failures show in the failed list.'
1425
- : 'Cordis 插件可能依赖 DSH 版本或平台,装不上会进失败清单。' },
1426
- { type: 'callout', tone: 'info', text: en
1427
- ? `Config file: ${configPath}`
1428
- : `配置文件:${configPath}` },
1429
- { type: 'keyValue', items: [
1430
- ['relay.repo', cfg.relay.repo || '—'],
1431
- ['ssh.host', cfg.ssh.host || '—'],
1432
- ] },
1433
- { type: 'text', text: en
1434
- ? 'Advanced: large plugins or two-way file sync use the Git relay / SSH below.'
1435
- : '高级:大插件或双向文件同步用下面的 Git 中转 / SSH。' },
1436
- { type: 'actions', items: [
1437
- { label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
1438
- { label: en ? 'Config template' : '生成配置模板', action: 'copy-config' },
1439
- { label: en ? 'Back' : '返回同步', action: 'back' },
1440
- ] },
1441
- { type: 'actions', items: [
1442
- { label: en ? 'Push relay' : '推送中转', action: 'relay-push' },
1443
- { label: en ? 'Pull relay' : '拉取中转', action: 'relay-pull' },
1444
- { label: en ? 'Scan SSH' : '拉远端清单', action: 'ssh-scan' },
1445
- { label: en ? 'Test SSH' : '测试 SSH', action: 'ssh-test' },
1446
- ] },
1447
- ],
1448
- }
1449
- }
1450
-
1451
- function stripValue(scope, en) {
1452
- const task = readTaskStatus()
1453
- if (task?.running) return { text: en ? 'Syncing…' : '同步中…', icon: 'refresh', tone: 'info' }
1454
- if (task && task.ok === false) return { text: en ? `Sync failed: ${task.failed}` : `同步失败 ${task.failed} 项`, icon: 'warning', tone: 'bad' }
1455
- const state = stateFor(scope)
1456
- if (state.manifest) {
1457
- const rows = diffRows(localPluginsCached(), state.manifest, state.manifestSource, { dshGo: true })
1458
- const pending = rows.filter((row) => row.action).length
1459
- if (pending > 0) return { text: en ? `Sync ${pending} left` : `待同步 ${pending} 项`, icon: 'refresh', tone: 'warn' }
1460
- return { text: en ? 'Plugins in sync' : '插件已同步', icon: 'check', tone: 'good' }
1461
- }
1462
- return { text: en ? 'Plugin sync' : '插件同步', icon: 'refresh' }
1463
- }
1464
-
1465
- // ---------------------------------------------------------------- web ui
1466
-
1467
- function webJson(res, status, value) {
1468
- const body = JSON.stringify(value)
1469
- res.writeHead(status, {
1470
- 'content-type': 'application/json; charset=utf-8',
1471
- 'cache-control': 'no-store',
1472
- })
1473
- res.end(body)
1474
- }
1475
-
1476
- function webReadBody(req, limit = 1024 * 1024) {
1477
- return new Promise((resolve, reject) => {
1478
- let total = 0
1479
- const chunks = []
1480
- req.on('data', (chunk) => {
1481
- total += chunk.length
1482
- if (total > limit) { reject(new Error('body too large')); req.destroy(); return }
1483
- chunks.push(chunk)
1484
- })
1485
- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1486
- req.on('error', reject)
1487
- })
1488
- }
1489
-
1490
- function webSnapshot(ctx) {
1491
- const scope = { sessionId: 'web-ui' }
1492
- const state = stateFor(scope)
1493
- const cfg = loadConfig(ctx, scope)
1494
- refreshManifests(state, cfg)
1495
- const local = localPlugins()
1496
- const rows = diffRows(local, state.manifest, state.manifestSource, { dshGo: Boolean(ctx.get?.('dshGo')) })
1497
- return {
1498
- plugins: local.map((plugin) => ({
1499
- name: plugin.name,
1500
- version: plugin.version,
1501
- title: plugin.title,
1502
- installed: plugin.installed,
1503
- localFiles: Boolean(plugin.relDir),
1504
- })),
1505
- selected: [...state.selected],
1506
- manifest: state.manifest,
1507
- rows: rows.map((row) => ({
1508
- name: row.name,
1509
- version: row.version,
1510
- status: row.status,
1511
- action: row.action || null,
1512
- kind: row.kind || null,
1513
- subtitle: statusLine(row, false),
1514
- })),
1515
- task: readTaskStatus(),
1516
- results: readTaskResults(),
1517
- config: cfg,
1518
- configPath: configPathFor(ctx, scope),
1519
- }
1520
- }
1521
-
1522
- /** Where the next saved config will live: an existing workspace file, else the store. */
1523
- function configPathFor(ctx, scope) {
1524
- const ws = writableDir(ctx, scope)
1525
- if (ws) {
1526
- const path = join(ws, CONFIG_FILE)
1527
- if (existsSync(path)) return path
1528
- }
1529
- return join(storeDir(), CONFIG_FILE)
1530
- }
1531
-
1532
- // ---------------------------------------------------------------- plugin
1533
-
1534
- export function apply(ctx) {
1535
- ctx.inject(['dshGo'], (ctx) => {
1536
- const copyConfig = (scope) => {
1537
- const target = writableDir(ctx, scope) || storeDir()
1538
- const path = join(target, CONFIG_FILE)
1539
- try {
1540
- ensureStore()
1541
- mkdirSync(target, { recursive: true })
1542
- if (!existsSync(path)) writeFileSync(path, configTemplate())
1543
- } catch {
1544
- return { toast: '写配置模板失败' }
1545
- }
1546
- return [{ toast: '已生成配置模板,改完刷新' }, { copy: path }, { refresh: true }]
1547
- }
1548
-
1549
- const copyCode = (scope) => {
1550
- const all = localPlugins()
1551
- const state = stateFor(scope)
1552
- const chosen = state.selected.size > 0
1553
- ? all.filter((plugin) => state.selected.has(plugin.name))
1554
- : all
1555
- const result = buildSyncCode(chosen)
1556
- if (result.error === 'empty') return { toast: '除本插件外没有其他插件' }
1557
- if (result.error) return { toast: '同步码太大,改用导出清单' }
1558
- const label = state.selected.size > 0 ? '已复制选中' : '已复制全部'
1559
- return [{ copy: result.code }, { toast: `${label} ${result.plugins} 个插件` }, { refresh: true }]
1560
- }
1561
-
1562
- const relayPush = (scope) => {
1563
- const cfg = loadConfig(ctx, scope)
1564
- if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
1565
- const local = localPlugins()
1566
- const pushable = local.filter((plugin) => safeDirName(plugin.relDir))
1567
- if (pushable.length === 0) return { toast: '本机没有可推送的插件' }
1568
- const manifest = buildManifest(local)
1569
- try {
1570
- ensureStore()
1571
- writeFileSync(pushManifestFile(), JSON.stringify(manifest, null, 2) + '\n')
1572
- } catch {
1573
- return { toast: '写清单失败' }
1574
- }
1575
- const started = startTask('relay-push', buildRelayPush(cfg, pushable, pushManifestFile()))
1576
- if (!started.ok) return { toast: started.error }
1577
- return [{ toast: `已开始推送 ${pushable.length} 个插件` }, { refresh: true }]
1578
- }
1579
-
1580
- const relayPull = (scope) => {
1581
- const cfg = loadConfig(ctx, scope)
1582
- if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
1583
- const state = stateFor(scope)
1584
- state.relayLoadedAt = 0
1585
- const started = startTask('relay-pull', buildRelayPull(cfg))
1586
- if (!started.ok) return { toast: started.error }
1587
- return [{ toast: '已开始拉取中转' }, { refresh: true }]
1588
- }
1589
-
1590
- const sshTest = (scope) => {
1591
- const cfg = loadConfig(ctx, scope)
1592
- if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
1593
- const started = startTask('ssh-test', buildSshTest(cfg))
1594
- if (!started.ok) return { toast: started.error }
1595
- return [{ toast: '正在测试 SSH' }, { refresh: true }]
1596
- }
1597
-
1598
- const sshScan = (scope) => {
1599
- const cfg = loadConfig(ctx, scope)
1600
- if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
1601
- const state = stateFor(scope)
1602
- state.sshLoadedAt = 0
1603
- const started = startTask('ssh-scan', buildSshScan(cfg))
1604
- if (!started.ok) return { toast: started.error }
1605
- return [{ toast: '正在拉远端清单' }, { refresh: true }]
1606
- }
1607
-
1608
- const retryFailed = (scope) => {
1609
- const cfg = loadConfig(ctx, scope)
1610
- const state = stateFor(scope)
1611
- const failed = readTaskResults().filter((result) => !result.ok)
1612
- if (failed.length === 0) return { toast: '没有失败项' }
1613
- const names = new Set(failed.map((result) => result.name))
1614
- const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: true })
1615
- const jobs = rows.filter((row) => names.has(row.name) && row.action)
1616
- if (jobs.length === 0) return { toast: '失败项已不在列表' }
1617
- if (jobs.some((row) => row.action === 'push' || row.action === 'push-npm' || row.action === 'pull') && !cfg.ssh.host) {
1618
- return { toast: '先配置 ssh.host' }
1619
- }
1620
- const started = startApplyTask(ctx, cfg, jobs)
1621
- if (!started.ok) return { toast: started.error }
1622
- return [{ toast: `重试 ${jobs.length} 项` }, { refresh: true }]
1623
- }
1624
-
1625
- ctx.dshGo.panel('sync', {
1626
- view(scope, caps) {
1627
- try {
1628
- return buildView(scope, caps, ctx)
1629
- } catch (error) {
1630
- return {
1631
- type: 'stack',
1632
- title: '插件同步',
1633
- children: [{ type: 'text', text: `视图出错:${String(error?.message ?? error).slice(0, 100)}` }],
1634
- }
1635
- }
1636
- },
1637
-
1638
- data(scope, emit) {
1639
- emit({ paste: { code: '' } })
1640
- return () => {}
1641
- },
1642
-
1643
- actions: {
1644
- 'copy-code': copyCode,
1645
-
1646
- 'import-code'(scope, event) {
1647
- const text = codeFromSubmit(event?.value)
1648
- if (text === '') return { toast: '先粘贴同步码' }
1649
- const result = applySyncCode(scope, text, '面板粘贴', { dshGo: true })
1650
- if (result.error) return { toast: result.error }
1651
- const toast = result.count === 0
1652
- ? '已导入,没有插件'
1653
- : `已导入 ${result.count} 个插件,选中 ${result.selected} 个`
1654
- return [{ toast }, { patch: { paste: { code: '' } } }, { refresh: true }]
1655
- },
1656
-
1657
- export(scope) {
1658
- const local = localPlugins()
1659
- const manifest = buildManifest(local)
1660
- const target = exportTarget(ctx, scope)
1661
- try {
1662
- ensureStore()
1663
- mkdirSync(dirname(target), { recursive: true })
1664
- writeFileSync(target, JSON.stringify(manifest, null, 2) + '\n')
1665
- } catch {
1666
- return { toast: '导出失败,检查工作区权限' }
1667
- }
1668
- const state = stateFor(scope)
1669
- state.lastExportPath = target
1670
- return [{ toast: '已导出插件清单' }, { copy: target }, { refresh: true }]
1671
- },
1672
-
1673
- 'import-workspace'(scope) {
1674
- const candidates = []
1675
- const dir = writableDir(ctx, scope)
1676
- if (dir) candidates.push(join(dir, MANIFEST_FILE))
1677
- candidates.push(exportTarget(ctx, scope), join(storeDir(), MANIFEST_FILE))
1678
- for (const candidate of candidates) {
1679
- if (!existsSync(candidate)) continue
1680
- try {
1681
- return importBuffer(scope, readFileSync(candidate), candidate, 'file')
1682
- } catch {}
1683
- }
1684
- return { toast: `工作区没有 ${MANIFEST_FILE}` }
1685
- },
1686
-
1687
- toggle(scope, event) {
1688
- const target = event?.value
1689
- const name = typeof target === 'string' ? target : target?.name
1690
- if (typeof name !== 'string') return { toast: '没有找到这一项' }
1691
- const state = stateFor(scope)
1692
- if (state.selected.has(name)) state.selected.delete(name)
1693
- else state.selected.add(name)
1694
- return { refresh: true }
1695
- },
1696
-
1697
- 'select-all'(scope) {
1698
- const state = stateFor(scope)
1699
- if (!state.manifest) {
1700
- for (const plugin of localPlugins()) state.selected.add(plugin.name)
1701
- return { refresh: true }
1702
- }
1703
- const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: true })
1704
- for (const row of rows) state.selected.add(row.name)
1705
- return { refresh: true }
1706
- },
1707
-
1708
- clear(scope) {
1709
- stateFor(scope).selected.clear()
1710
- return { refresh: true }
1711
- },
1712
-
1713
- refresh() {
1714
- return { refresh: true }
1715
- },
1716
-
1717
- 'copy-config'(scope) {
1718
- return copyConfig(scope)
1719
- },
1720
-
1721
- 'relay-push': relayPush,
1722
- 'relay-pull': relayPull,
1723
- 'ssh-test': sshTest,
1724
- 'ssh-scan': sshScan,
1725
- 'retry-failed': retryFailed,
1726
-
1727
- guide() {
1728
- return { open: 'panel:guide' }
1729
- },
1730
-
1731
- apply(scope, event) {
1732
- if (event?.value?.confirmed !== true) return { toast: '已取消' }
1733
- const cfg = loadConfig(ctx, scope)
1734
- const state = stateFor(scope)
1735
- const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: true })
1736
- const jobs = rows.filter((row) => state.selected.has(row.name) && row.action)
1737
- if (jobs.length === 0) {
1738
- return { toast: state.selected.size > 0 ? '选中的都已安装' : '没有可执行的项' }
1739
- }
1740
- if (jobs.some((job) => job.action === 'install' && !job.localDir && !job.registrySpec)) {
1741
- return { toast: '有项找不到安装来源' }
1742
- }
1743
- if (jobs.some((job) => job.action === 'push' || job.action === 'push-npm' || job.action === 'pull') && !cfg.ssh.host) {
1744
- return { toast: '推/拉远端要先配置 ssh.host' }
1745
- }
1746
- const started = startApplyTask(ctx, cfg, jobs)
1747
- if (!started.ok) return { toast: started.error }
1748
- state.selected.clear()
1749
- return [{ toast: `已开始处理 ${jobs.length} 项` }, { refresh: true }]
1750
- },
1751
- },
1752
- })
1753
-
1754
- ctx.dshGo.panel('guide', {
1755
- view(scope, caps) {
1756
- try {
1757
- return buildGuide(scope, caps, ctx)
1758
- } catch {
1759
- return { type: 'stack', title: '使用引导', children: [{ type: 'text', text: '引导加载失败' }] }
1760
- }
1761
- },
1762
- actions: {
1763
- 'copy-config'(scope) {
1764
- return copyConfig(scope)
1765
- },
1766
- 'relay-push': relayPush,
1767
- 'relay-pull': relayPull,
1768
- 'ssh-test': sshTest,
1769
- 'ssh-scan': sshScan,
1770
- 'retry-failed': retryFailed,
1771
- back() {
1772
- return { open: 'panel:sync' }
1773
- },
1774
- },
1775
- })
1776
-
1777
- ctx.dshGo.strip('pending', (scope, emit, caps) => {
1778
- const en = String(caps?.locale || '').toLowerCase().startsWith('en')
1779
- const tick = () => {
1780
- try { emit(stripValue(scope, en)) } catch {}
1781
- }
1782
- tick()
1783
- const timer = setInterval(tick, 60_000)
1784
- timer.unref?.()
1785
- return () => clearInterval(timer)
1786
- })
1787
-
1788
- function importBuffer(scope, buffer, sourceName, kind) {
1789
- let doc
1790
- try {
1791
- doc = JSON.parse(Buffer.isBuffer(buffer) ? buffer.toString('utf8') : String(buffer))
1792
- } catch {
1793
- return { toast: '文件不是合法 JSON' }
1794
- }
1795
- const manifest = validManifest(doc)
1796
- if (!manifest) return { toast: '清单格式不对' }
1797
- if (manifest.plugins.length === 0) return { toast: '清单里没有可同步插件' }
1798
- const state = stateFor(scope)
1799
- state.manifest = manifest
1800
- state.manifestSource = { kind: kind || 'file' }
1801
- state.importedAt = new Date().toISOString()
1802
- state.sourceName = typeof sourceName === 'string' ? sourceName : null
1803
- state.selected.clear()
1804
- persistImported(state)
1805
- return [{ toast: `已导入 ${manifest.plugins.length} 个插件` }, { refresh: true }]
1806
- }
1807
- })
1808
-
1809
- ctx.inject(['webServer'], (webCtx) => {
1810
- const handler = async (req, res) => {
1811
- try {
1812
- let rejection
1813
- try { rejection = ctx.connection?.requestRejection?.(req) } catch {}
1814
- if (rejection !== undefined) { res.writeHead(rejection); res.end(); return }
1815
- const url = new URL(req.url || '/', 'http://dsh.local')
1816
- const path = url.pathname.replace(/\/+$/, '') || '/'
1817
- if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/state') {
1818
- webJson(res, 200, webSnapshot(ctx))
1819
- return
1820
- }
1821
- if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/status') {
1822
- webJson(res, 200, { task: readTaskStatus(), results: readTaskResults() })
1823
- return
1824
- }
1825
- if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/action') {
1826
- const body = JSON.parse((await webReadBody(req)) || '{}')
1827
- const action = typeof body.action === 'string' ? body.action : ''
1828
- const scope = { sessionId: 'web-ui' }
1829
- const cfg = loadConfig(ctx, scope)
1830
- const state = stateFor(scope)
1831
- if (action === 'relay-pull') {
1832
- if (!cfg.relay.repo) { webJson(res, 200, { error: '先配置中转仓' }); return }
1833
- state.relayLoadedAt = 0
1834
- const started = startTask('relay-pull', buildRelayPull(cfg))
1835
- webJson(res, 200, started.ok ? { ok: true } : { error: started.error })
1836
- return
1837
- }
1838
- if (action === 'relay-push') {
1839
- if (!cfg.relay.repo) { webJson(res, 200, { error: '先配置中转仓' }); return }
1840
- const local = localPlugins()
1841
- const pushable = local.filter((plugin) => safeDirName(plugin.relDir))
1842
- if (pushable.length === 0) { webJson(res, 200, { error: '本机没有可推送的插件' }); return }
1843
- try {
1844
- ensureStore()
1845
- writeFileSync(pushManifestFile(), JSON.stringify(buildManifest(local), null, 2) + '\n')
1846
- } catch {
1847
- webJson(res, 200, { error: '写清单失败' })
1848
- return
1849
- }
1850
- const started = startTask('relay-push', buildRelayPush(cfg, pushable, pushManifestFile()))
1851
- webJson(res, 200, started.ok ? { ok: true, count: pushable.length } : { error: started.error })
1852
- return
1853
- }
1854
- if (action === 'ssh-test') {
1855
- if (!cfg.ssh.host) { webJson(res, 200, { error: '先配置 ssh.host' }); return }
1856
- const started = startTask('ssh-test', buildSshTest(cfg))
1857
- webJson(res, 200, started.ok ? { ok: true } : { error: started.error })
1858
- return
1859
- }
1860
- if (action === 'ssh-scan') {
1861
- if (!cfg.ssh.host) { webJson(res, 200, { error: '先配置 ssh.host' }); return }
1862
- state.sshLoadedAt = 0
1863
- const started = startTask('ssh-scan', buildSshScan(cfg))
1864
- webJson(res, 200, started.ok ? { ok: true } : { error: started.error })
1865
- return
1866
- }
1867
- webJson(res, 200, { error: '未知操作' })
1868
- return
1869
- }
1870
- if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/config') {
1871
- const body = JSON.parse((await webReadBody(req)) || '{}')
1872
- const next = normalizeConfig(body.config || {})
1873
- const scope = { sessionId: 'web-ui' }
1874
- const target = configPathFor(ctx, scope)
1875
- try {
1876
- ensureStore()
1877
- mkdirSync(dirname(target), { recursive: true })
1878
- writeFileSync(target, JSON.stringify(next, null, 2) + '\n')
1879
- } catch {
1880
- webJson(res, 200, { error: '保存配置失败' })
1881
- return
1882
- }
1883
- webJson(res, 200, { ok: true, config: next, path: target })
1884
- return
1885
- }
1886
- if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/export') {
1887
- const body = JSON.parse((await webReadBody(req)) || '{}')
1888
- const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
1889
- const all = localPlugins()
1890
- const chosen = names.length > 0 ? all.filter((plugin) => names.includes(plugin.name)) : all
1891
- const result = buildSyncCode(chosen)
1892
- if (result.error === 'empty') { webJson(res, 200, { error: '没有可同步的插件' }); return }
1893
- if (result.error) { webJson(res, 200, { error: '同步码太大,请减少插件或改用中转' }); return }
1894
- webJson(res, 200, { code: result.code, count: result.plugins, withFiles: result.withFiles })
1895
- return
1896
- }
1897
- if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/import') {
1898
- const body = JSON.parse((await webReadBody(req)) || '{}')
1899
- const code = typeof body.code === 'string' ? body.code : ''
1900
- const result = applySyncCode({ sessionId: 'web-ui' }, code, '网页版', { dshGo: Boolean(ctx.get?.('dshGo')) })
1901
- if (result.error) { webJson(res, 200, { error: result.error }); return }
1902
- webJson(res, 200, { ok: true, count: result.count, selected: result.selected })
1903
- return
1904
- }
1905
- if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/apply') {
1906
- const body = JSON.parse((await webReadBody(req)) || '{}')
1907
- const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
1908
- const scope = { sessionId: 'web-ui' }
1909
- const cfg = loadConfig(ctx, scope)
1910
- const state = stateFor(scope)
1911
- const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: Boolean(ctx.get?.('dshGo')) })
1912
- const jobs = rows.filter((row) => names.includes(row.name) && row.action)
1913
- if (jobs.length === 0) { webJson(res, 200, { error: '没有可安装的项' }); return }
1914
- if (jobs.some((job) => job.action === 'push' || job.action === 'push-npm' || job.action === 'pull') && !cfg.ssh.host) {
1915
- webJson(res, 200, { error: '先配置 ssh.host' }); return
1916
- }
1917
- const started = startApplyTask(ctx, cfg, jobs)
1918
- if (!started.ok) { webJson(res, 200, { error: started.error }); return }
1919
- state.selected.clear()
1920
- webJson(res, 200, { ok: true, count: jobs.length })
1921
- return
1922
- }
1923
- res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
1924
- res.end('not found')
1925
- } catch (error) {
1926
- try { webJson(res, 500, { error: String(error?.message || error) }) } catch {}
1927
- }
1928
- }
1929
- ctx.effect(() => webCtx.webServer.register({ kind: 'prefix', path: '/dsh-go-plugin-sync', handler }), 'dsh-go-plugin-sync: web ui')
1930
- try {
1931
- const ws = webCtx.webServer
1932
- const host = String(ws.host || '127.0.0.1')
1933
- const shown = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host
1934
- const bracketed = shown.includes(':') ? `[${shown}]` : shown
1935
- console.log(`[dsh-go-plugin-sync] 设置页 API:${ws.protocol || 'http:'}//${bracketed}:${ws.port}/dsh-go-plugin-sync/api/`)
1936
- } catch {}
1937
- })
1938
- }
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, unlinkSync, writeFileSync,
19
+ } from 'node:fs'
20
+ import { homedir } from 'node:os'
21
+ import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path'
22
+ import { deflateRawSync, inflateRawSync } from 'node:zlib'
23
+
24
+ export const name = 'dsh-go-plugin-sync'
25
+
26
+ const MAX_FILES = 300
27
+ const MAX_FILE_BYTES = 2 * 1024 * 1024
28
+ const MAX_TOTAL_BYTES = 8 * 1024 * 1024
29
+ const MANIFEST_V = 1
30
+ const MANIFEST_FILE = 'plugin-sync-manifest.json'
31
+ const CONFIG_FILE = 'plugin-sync-config.json'
32
+ const CODE_PREFIX = 'DSHSYNC1:'
33
+ const CODE_BUDGET = 1900
34
+ const TEXT_EXT = new Set(['.js', '.mjs', '.cjs', '.json', '.yml', '.yaml', '.md', '.txt', '.css', '.html', '.svg', '.ts'])
35
+ const REL_RE = /^[A-Za-z0-9._@-]+(?:\/[A-Za-z0-9._@-]+)*$/
36
+ const PKG_NAME = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
37
+ const SAFE_DIR = /^[A-Za-z0-9._-]+$/
38
+ const SAFE_PROFILE = /^[a-z0-9-]+$/
39
+
40
+ const STATE = new Map()
41
+ let scanCache = { key: '', at: 0, value: [] }
42
+
43
+ // ---------------------------------------------------------------- paths
44
+
45
+ const home = () => process.env.DSH_HOME || join(process.env.HOME || homedir(), '.dsh')
46
+ const storeDir = () => join(home(), 'dsh-go', 'plugin-sync')
47
+ const pluginsRoot = () => join(home(), 'dsh-go', 'plugins')
48
+
49
+ /** The desktop host passes the profile it owns as an absolute `.../profiles/<name>` argument. */
50
+ function launchedProfileDir() {
51
+ for (const arg of process.argv) {
52
+ if (typeof arg !== 'string') continue
53
+ const dir = resolve(arg)
54
+ if (basename(dirname(dir)) !== 'profiles') continue
55
+ try { if (existsSync(join(dir, 'package.json'))) return dir } catch {}
56
+ }
57
+ return undefined
58
+ }
59
+
60
+ const activeProfileDir = () => process.env.DSH_PROFILE_DIR || launchedProfileDir()
61
+ const profileName = () => (activeProfileDir() && basename(activeProfileDir())) || process.env.DSH_PROFILE || 'web'
62
+ const profileDir = () => activeProfileDir() || join(home(), 'profiles', profileName())
63
+
64
+ const importFile = () => join(storeDir(), 'imported.json')
65
+ const uiStateFile = () => join(storeDir(), 'ui-state.json')
66
+ const relayWorkDir = () => join(storeDir(), 'relay-work')
67
+ const relayManifestFile = () => join(storeDir(), 'relay-manifest.json')
68
+ const sshManifestFile = () => join(storeDir(), 'ssh-manifest.json')
69
+ const pushManifestFile = () => join(storeDir(), 'push-manifest.json')
70
+ const remoteScannerFile = () => join(storeDir(), 'scan-remote.cjs')
71
+ const taskScriptPath = () => join(storeDir(), 'task.sh')
72
+ const taskRunnerPath = () => join(storeDir(), 'task-runner.cjs')
73
+ const taskSpecPath = () => join(storeDir(), 'task-spec.json')
74
+ const taskLogPath = () => join(storeDir(), 'task.log')
75
+ const taskStatusPath = () => join(storeDir(), 'task-status.txt')
76
+ const taskTotalPath = () => join(storeDir(), 'task-total.txt')
77
+
78
+ function readJson(path) {
79
+ try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return undefined }
80
+ }
81
+
82
+ function ensureStore() {
83
+ mkdirSync(storeDir(), { recursive: true })
84
+ }
85
+
86
+ /** UI-only flag: the pending list was cleared by hand. Reset when a new manifest arrives. */
87
+ function uiCleared() {
88
+ const raw = readJson(uiStateFile())
89
+ return Boolean(raw && typeof raw.clearedAt === 'string')
90
+ }
91
+
92
+ function clearUiState() {
93
+ try {
94
+ ensureStore()
95
+ writeFileSync(uiStateFile(), JSON.stringify({ clearedAt: new Date().toISOString() }) + '\n')
96
+ } catch {}
97
+ }
98
+
99
+ function resetUiState() {
100
+ try { unlinkSync(uiStateFile()) } catch {}
101
+ }
102
+
103
+ function shQuote(value) {
104
+ return `'${String(value).replace(/'/g, `'\\''`)}'`
105
+ }
106
+
107
+ function safeName(value) {
108
+ return typeof value === 'string' && (PKG_NAME.test(value) || SAFE_DIR.test(value))
109
+ }
110
+
111
+ /** A single directory name directly under the plugins root. */
112
+ function safeDirName(value) {
113
+ return typeof value === 'string' && value !== '.' && value !== '..' && SAFE_DIR.test(value)
114
+ }
115
+
116
+ /** Token used in task log markers; keeps `@@ action name start` one line and inert. */
117
+ function markerName(value) {
118
+ return String(value).replace(/[^A-Za-z0-9._@/-]/g, '_').slice(0, 80) || '_'
119
+ }
120
+
121
+ function safeRel(value) {
122
+ if (typeof value !== 'string' || value.length === 0 || value.length > 200) return false
123
+ if (value.includes('\\') || value.includes('\0') || value.startsWith('/') || value.includes('..')) return false
124
+ return REL_RE.test(value) && TEXT_EXT.has(extname(value).toLowerCase())
125
+ }
126
+
127
+ // ---------------------------------------------------------------- sync code
128
+
129
+ /** Text files of one plugin directory, relative paths -> contents. */
130
+ function readPluginTextFiles(dir) {
131
+ const files = {}
132
+ let total = 0
133
+ const walk = (base, rel, depth) => {
134
+ if (depth > 4 || total > 200_000) return
135
+ let entries
136
+ try { entries = readdirSync(base, { withFileTypes: true }) } catch { return }
137
+ for (const entry of entries) {
138
+ if (entry.name === 'node_modules' || entry.name === '.git') continue
139
+ const full = join(base, entry.name)
140
+ const next = rel ? `${rel}/${entry.name}` : entry.name
141
+ if (entry.isDirectory()) { walk(full, next, depth + 1); continue }
142
+ if (!entry.isFile() || !TEXT_EXT.has(extname(entry.name).toLowerCase())) continue
143
+ let text
144
+ try { text = readFileSync(full, 'utf8') } catch { continue }
145
+ if (text.length > 100_000) continue
146
+ total += text.length
147
+ if (total > 200_000) return
148
+ files[next] = text
149
+ }
150
+ }
151
+ walk(dir, '', 0)
152
+ return files
153
+ }
154
+
155
+ function encodeSyncPayload(payload) {
156
+ return CODE_PREFIX + deflateRawSync(Buffer.from(JSON.stringify(payload), 'utf8')).toString('base64url')
157
+ }
158
+
159
+ /** Compact sync code: manifest + (when it fits) text files of local plugins. */
160
+ function buildSyncCode(plugins) {
161
+ const entries = plugins
162
+ .filter((plugin) => plugin.name !== name)
163
+ .map((plugin) => ({
164
+ name: plugin.name,
165
+ version: plugin.version,
166
+ hash: plugin.hash,
167
+ relDir: plugin.relDir,
168
+ depSpec: plugin.depSpec,
169
+ kind: plugin.kind || null,
170
+ files: safeDirName(plugin.relDir) && existsSync(plugin.dir)
171
+ ? readPluginTextFiles(plugin.dir)
172
+ : {},
173
+ }))
174
+ if (entries.length === 0) return { error: 'empty' }
175
+ let code = encodeSyncPayload({ v: 2, t: 'dsh-go-plugin-sync', at: new Date().toISOString(), plugins: entries })
176
+ let withFiles = entries.filter((entry) => Object.keys(entry.files).length > 0).length
177
+ if (code.length > CODE_BUDGET) {
178
+ code = encodeSyncPayload({
179
+ v: 2,
180
+ t: 'dsh-go-plugin-sync',
181
+ at: new Date().toISOString(),
182
+ plugins: entries.map(({ files, ...rest }) => rest),
183
+ })
184
+ withFiles = 0
185
+ }
186
+ if (code.length > 2000) return { error: 'too-large' }
187
+ return { code, plugins: entries.length, withFiles }
188
+ }
189
+
190
+ function decodeSyncCode(text) {
191
+ const trimmed = String(text || '').trim().replace(/\s+/g, '')
192
+ if (!trimmed.startsWith(CODE_PREFIX)) return { error: '不是同步码' }
193
+ const body = trimmed.slice(CODE_PREFIX.length)
194
+ if (body.length > 100_000) return { error: '同步码太大' }
195
+ let doc
196
+ try {
197
+ doc = JSON.parse(inflateRawSync(Buffer.from(body, 'base64url'), { maxOutputLength: 2 * 1024 * 1024 }).toString('utf8'))
198
+ } catch {
199
+ return { error: '同步码损坏或过大' }
200
+ }
201
+ if (!doc || doc.v !== 2 || doc.t !== 'dsh-go-plugin-sync' || !Array.isArray(doc.plugins)) return { error: '同步码版本不对' }
202
+ const plugins = []
203
+ for (const raw of doc.plugins.slice(0, 200)) {
204
+ if (!raw || typeof raw.name !== 'string' || !safeName(raw.name)) continue
205
+ const relDir = safeDirName(raw.relDir) ? raw.relDir : null
206
+ const files = {}
207
+ if (raw.files && typeof raw.files === 'object') {
208
+ for (const [rel, content] of Object.entries(raw.files)) {
209
+ if (!safeRel(rel) || typeof content !== 'string' || content.length > 100_000) continue
210
+ files[rel] = content
211
+ }
212
+ }
213
+ plugins.push({
214
+ name: raw.name,
215
+ version: typeof raw.version === 'string' ? raw.version : '0.0.0',
216
+ hash: typeof raw.hash === 'string' ? raw.hash : null,
217
+ relDir,
218
+ depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
219
+ kind: raw.kind === 'native' || raw.kind === 'bundle' || raw.kind === 'both' ? raw.kind : null,
220
+ files,
221
+ })
222
+ }
223
+ if (plugins.length === 0) return { error: '同步码里没有可同步插件' }
224
+ return {
225
+ plugins,
226
+ manifest: {
227
+ v: MANIFEST_V,
228
+ generator: 'dsh-go-plugin-sync',
229
+ exportedAt: typeof doc.at === 'string' ? doc.at : null,
230
+ host: { profile: 'sync-code' },
231
+ plugins: plugins.map(({ files, ...rest }) => rest),
232
+ },
233
+ }
234
+ }
235
+
236
+ /** Materialize text files for plugins this host does not have yet (never overwrites). */
237
+ function writeCodeFiles(decoded) {
238
+ let written = 0
239
+ for (const plugin of decoded.plugins) {
240
+ if (!safeDirName(plugin.relDir) || Object.keys(plugin.files).length === 0) continue
241
+ const dir = join(pluginsRoot(), plugin.relDir)
242
+ if (existsSync(dir)) continue
243
+ try {
244
+ mkdirSync(dir, { recursive: true })
245
+ for (const [rel, content] of Object.entries(plugin.files)) {
246
+ const target = join(dir, rel)
247
+ mkdirSync(dirname(target), { recursive: true })
248
+ writeFileSync(target, content)
249
+ }
250
+ written++
251
+ } catch {}
252
+ }
253
+ return written
254
+ }
255
+
256
+ /** Read the pasted code from a v2 form submit (`event.value.values['data.paste.code']`). */
257
+ function codeFromSubmit(value) {
258
+ const values = value?.values
259
+ if (values && typeof values === 'object') {
260
+ const direct = values['data.paste.code']
261
+ if (typeof direct === 'string') return direct.trim()
262
+ for (const candidate of Object.values(values)) {
263
+ if (typeof candidate === 'string' && candidate.trim().startsWith(CODE_PREFIX)) return candidate.trim()
264
+ }
265
+ }
266
+ if (typeof value === 'string') return value.trim()
267
+ return ''
268
+ }
269
+
270
+ /** Decode a sync code, materialize files, and preselect every row (all by default). */
271
+ function applySyncCode(scope, text, sourceName, host = {}) {
272
+ const decoded = decodeSyncCode(text)
273
+ if (decoded.error) return { error: decoded.error }
274
+ const state = stateFor(scope)
275
+ state.manifest = decoded.manifest
276
+ state.manifestSource = { kind: 'code' }
277
+ state.importedAt = new Date().toISOString()
278
+ state.sourceName = sourceName
279
+ state.showAll = false
280
+ persistImported(state)
281
+ resetUiState()
282
+ writeCodeFiles(decoded)
283
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, host)
284
+ const manifestNames = new Set(decoded.manifest.plugins.map((plugin) => plugin.name))
285
+ state.selected.clear()
286
+ let selected = 0
287
+ for (const row of rows) {
288
+ if (!manifestNames.has(row.name)) continue
289
+ if (!row.action) continue
290
+ if (host.dshGo === true && row.kind === 'bundle') continue
291
+ state.selected.add(row.name)
292
+ selected++
293
+ }
294
+ return {
295
+ count: decoded.manifest.plugins.length,
296
+ selected,
297
+ installable: rows.filter((row) => row.action === 'install').length,
298
+ }
299
+ }
300
+
301
+ // ---------------------------------------------------------------- config
302
+
303
+ function expandHome(value) {
304
+ if (typeof value !== 'string' || value === '') return ''
305
+ if (value === '~') return process.env.HOME || '/root'
306
+ if (value.startsWith('~/')) return join(process.env.HOME || '/root', value.slice(2))
307
+ return value
308
+ }
309
+
310
+ function normalizeConfig(raw) {
311
+ const relay = raw?.relay && typeof raw.relay === 'object' ? raw.relay : {}
312
+ const ssh = raw?.ssh && typeof raw.ssh === 'object' ? raw.ssh : {}
313
+ const port = Number(ssh.port)
314
+ const profile = typeof ssh.profile === 'string' && SAFE_PROFILE.test(ssh.profile) ? ssh.profile : profileName()
315
+ return {
316
+ relay: {
317
+ repo: typeof relay.repo === 'string' ? relay.repo.trim() : '',
318
+ branch: typeof relay.branch === 'string' && relay.branch.trim() !== '' ? relay.branch.trim() : 'main',
319
+ dir: typeof relay.dir === 'string' && SAFE_DIR.test(relay.dir) ? relay.dir : 'dsh-go-plugins',
320
+ },
321
+ ssh: {
322
+ host: typeof ssh.host === 'string' ? ssh.host.trim() : '',
323
+ port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 22,
324
+ user: typeof ssh.user === 'string' ? ssh.user.trim() : '',
325
+ identity: typeof ssh.identity === 'string' ? expandHome(ssh.identity.trim()) : '',
326
+ remoteHome: typeof ssh.remoteHome === 'string' && ssh.remoteHome.trim() !== '' ? ssh.remoteHome.trim() : '~/.dsh',
327
+ dshPath: typeof ssh.dshPath === 'string' && ssh.dshPath.trim() !== '' ? ssh.dshPath.trim() : 'dsh',
328
+ nodePath: typeof ssh.nodePath === 'string' && ssh.nodePath.trim() !== '' ? ssh.nodePath.trim() : 'node',
329
+ profile,
330
+ },
331
+ }
332
+ }
333
+
334
+ function loadConfig(ctx, scope) {
335
+ const candidates = []
336
+ const ws = writableDir(ctx, scope)
337
+ if (ws) candidates.push(join(ws, CONFIG_FILE))
338
+ candidates.push(join(storeDir(), CONFIG_FILE))
339
+ for (const path of candidates) {
340
+ const raw = readJson(path)
341
+ if (raw && typeof raw === 'object') return normalizeConfig(raw)
342
+ }
343
+ return normalizeConfig({})
344
+ }
345
+
346
+ function configTemplate() {
347
+ return JSON.stringify({
348
+ relay: { repo: 'https://github.com/you/dsh-plugins.git', branch: 'main', dir: 'dsh-go-plugins' },
349
+ ssh: { host: '192.168.1.10', port: 22, user: 'root', identity: '', remoteHome: '~/.dsh', dshPath: 'dsh', nodePath: 'node', profile: 'web' },
350
+ }, null, 2) + '\n'
351
+ }
352
+
353
+ // ---------------------------------------------------------------- local scan
354
+
355
+ function collectFiles(root, out, depth = 0) {
356
+ if (depth > 6 || out.length >= MAX_FILES) return
357
+ let entries
358
+ try { entries = readdirSync(root, { withFileTypes: true }) } catch { return }
359
+ for (const entry of entries) {
360
+ if (out.length >= MAX_FILES) return
361
+ const full = join(root, entry.name)
362
+ if (entry.isDirectory()) collectFiles(full, out, depth + 1)
363
+ else if (entry.isFile()) out.push(full)
364
+ }
365
+ }
366
+
367
+ function shortHash(dir) {
368
+ const hash = createHash('sha256')
369
+ try { hash.update(readFileSync(join(dir, 'package.json'))) } catch { return null }
370
+ const files = []
371
+ collectFiles(join(dir, 'lib'), files)
372
+ files.sort()
373
+ let total = 0
374
+ for (const file of files) {
375
+ let bytes
376
+ try { bytes = readFileSync(file) } catch { continue }
377
+ if (bytes.length > MAX_FILE_BYTES) continue
378
+ total += bytes.length
379
+ if (total > MAX_TOTAL_BYTES) break
380
+ hash.update(relative(dir, file).split(sep).join('/'))
381
+ hash.update('\0')
382
+ hash.update(bytes)
383
+ hash.update('\0')
384
+ }
385
+ return hash.digest('hex').slice(0, 16)
386
+ }
387
+
388
+ /** A syncable plugin: a dsh-go native plugin or a Cordis bundle (official bundles excluded). */
389
+ function syncablePkg(pkg) {
390
+ if (!pkg || typeof pkg.name !== 'string') return false
391
+ if (pkg.name === name || pkg.name.startsWith('@deepseek-ai/')) return false
392
+ const native = pkg.dshGo && typeof pkg.dshGo === 'object'
393
+ const bundle = pkg.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle
394
+ return Boolean(native || bundle)
395
+ }
396
+
397
+ function titleOf(pkg) {
398
+ const title = pkg?.dshGo?.title
399
+ if (typeof title === 'string') return title
400
+ if (title && typeof title === 'object') return title.zh || title.en || ''
401
+ return typeof pkg?.displayName === 'string' ? pkg.displayName : ''
402
+ }
403
+
404
+ function pluginKind(pkg) {
405
+ const native = Boolean(pkg?.dshGo && typeof pkg.dshGo === 'object')
406
+ const bundle = Boolean(pkg?.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle)
407
+ if (native && bundle) return 'both'
408
+ if (native) return 'native'
409
+ if (bundle) return 'bundle'
410
+ return null
411
+ }
412
+
413
+ function makeEntry(pkg, dir, relDir, depSpec) {
414
+ return {
415
+ name: pkg.name,
416
+ version: typeof pkg.version === 'string' ? pkg.version : '0.0.0',
417
+ title: titleOf(pkg).slice(0, 40),
418
+ hash: shortHash(dir),
419
+ relDir: relDir || null,
420
+ depSpec: depSpec || null,
421
+ kind: pluginKind(pkg),
422
+ dir,
423
+ installed: false,
424
+ }
425
+ }
426
+
427
+ function scanSourcePlugins() {
428
+ const root = pluginsRoot()
429
+ const out = []
430
+ let entries
431
+ try { entries = readdirSync(root, { withFileTypes: true }) } catch { return out }
432
+ for (const entry of entries) {
433
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue
434
+ const dir = join(root, entry.name)
435
+ const pkg = readJson(join(dir, 'package.json'))
436
+ if (!syncablePkg(pkg)) continue
437
+ out.push(makeEntry(pkg, dir, entry.name, null))
438
+ }
439
+ return out
440
+ }
441
+
442
+ function scanInstalledPlugins() {
443
+ const profile = readJson(join(profileDir(), 'package.json'))
444
+ const deps = profile?.dependencies
445
+ if (!deps || typeof deps !== 'object') return []
446
+ const out = []
447
+ for (const [dep, spec] of Object.entries(deps)) {
448
+ const dir = join(profileDir(), 'node_modules', dep)
449
+ const pkg = readJson(join(dir, 'package.json'))
450
+ if (!syncablePkg(pkg)) continue
451
+ let relDir = null
452
+ if (typeof spec === 'string' && (spec.startsWith('link:') || spec.startsWith('file:'))) {
453
+ const raw = spec.slice(spec.indexOf(':') + 1)
454
+ const rel = relative(pluginsRoot(), resolve(profileDir(), raw))
455
+ if (rel && !rel.startsWith('..') && !rel.startsWith(sep) && !rel.includes('\0')) relDir = rel
456
+ }
457
+ const entry = makeEntry(pkg, dir, relDir, spec)
458
+ entry.installed = true
459
+ out.push(entry)
460
+ }
461
+ return out
462
+ }
463
+
464
+ function localPlugins() {
465
+ const map = new Map()
466
+ for (const plugin of scanSourcePlugins()) map.set(plugin.name, plugin)
467
+ for (const plugin of scanInstalledPlugins()) {
468
+ const previous = map.get(plugin.name)
469
+ if (previous) {
470
+ previous.installed = true
471
+ previous.depSpec = plugin.depSpec
472
+ if (!previous.relDir) previous.relDir = plugin.relDir
473
+ } else {
474
+ map.set(plugin.name, plugin)
475
+ }
476
+ }
477
+ return [...map.values()]
478
+ }
479
+
480
+ function localPluginsCached() {
481
+ const key = home()
482
+ if (scanCache.key === key && Date.now() - scanCache.at < 2000) return scanCache.value
483
+ const value = localPlugins()
484
+ scanCache = { key, at: Date.now(), value }
485
+ return value
486
+ }
487
+
488
+ // ---------------------------------------------------------------- manifest
489
+
490
+ function buildManifest(plugins) {
491
+ return {
492
+ v: MANIFEST_V,
493
+ generator: 'dsh-go-plugin-sync',
494
+ exportedAt: new Date().toISOString(),
495
+ host: { profile: profileName() },
496
+ plugins: plugins.map((plugin) => ({
497
+ name: plugin.name,
498
+ version: plugin.version,
499
+ title: plugin.title,
500
+ hash: plugin.hash,
501
+ relDir: plugin.relDir,
502
+ depSpec: plugin.depSpec,
503
+ kind: plugin.kind || null,
504
+ installed: plugin.installed === true,
505
+ })),
506
+ }
507
+ }
508
+
509
+ function validManifest(doc) {
510
+ if (!doc || typeof doc !== 'object' || doc.v !== MANIFEST_V || !Array.isArray(doc.plugins)) return undefined
511
+ const plugins = []
512
+ for (const raw of doc.plugins.slice(0, 200)) {
513
+ if (!raw || typeof raw !== 'object' || typeof raw.name !== 'string' || raw.name.length > 120) continue
514
+ if (raw.name === name) continue
515
+ plugins.push({
516
+ name: raw.name,
517
+ version: typeof raw.version === 'string' ? raw.version : '0.0.0',
518
+ title: typeof raw.title === 'string' ? raw.title.slice(0, 40) : '',
519
+ hash: typeof raw.hash === 'string' ? raw.hash.slice(0, 64) : null,
520
+ relDir: safeDirName(raw.relDir) ? raw.relDir : null,
521
+ kind: raw.kind === 'native' || raw.kind === 'bundle' || raw.kind === 'both' ? raw.kind : null,
522
+ depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
523
+ installed: raw.installed === true,
524
+ })
525
+ }
526
+ return {
527
+ v: MANIFEST_V,
528
+ generator: 'dsh-go-plugin-sync',
529
+ exportedAt: typeof doc.exportedAt === 'string' ? doc.exportedAt : null,
530
+ host: doc.host && typeof doc.host === 'object' ? { profile: String(doc.host.profile ?? '') } : undefined,
531
+ plugins,
532
+ }
533
+ }
534
+
535
+ /** A plain `name@version` registry spec, when the manifest has no local files. */
536
+ function registrySpecOf(remote) {
537
+ const version = String(remote?.version || '')
538
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) return null
539
+ const spec = remote?.depSpec
540
+ if (typeof spec === 'string' && spec !== '') {
541
+ if (/^(file:|link:|workspace:|portal:|exec:|git\+|github:|https?:|\.{0,2}\/|~\/)/i.test(spec)) return null
542
+ }
543
+ return `${remote.name}@${version}`
544
+ }
545
+
546
+ function diffRows(local, manifest, source, host = {}) {
547
+ const nativeHost = host.dshGo === true
548
+ const localByName = new Map(local.map((plugin) => [plugin.name, plugin]))
549
+ const manifestByName = new Map((manifest?.plugins ?? []).map((plugin) => [plugin.name, plugin]))
550
+ const rows = []
551
+ for (const remote of manifest?.plugins ?? []) {
552
+ const here = localByName.get(remote.name)
553
+ const remoteDir = remote.relDir || remote.name
554
+ const kind = remote.kind || here?.kind || null
555
+ if (!nativeHost && kind === 'native') {
556
+ rows.push({ name: remote.name, version: remote.version, remoteVersion: remote.version, status: 'native-only', action: null, kind })
557
+ continue
558
+ }
559
+ if (!here) {
560
+ let action = null
561
+ let localDir = null
562
+ let registrySpec = null
563
+ if (source?.kind === 'ssh') {
564
+ if (safeDirName(remote.relDir)) {
565
+ action = 'pull'
566
+ } else {
567
+ registrySpec = registrySpecOf(remote)
568
+ if (registrySpec) action = 'install'
569
+ }
570
+ } else {
571
+ if (source?.kind === 'relay') localDir = join(source.pluginsDir, remoteDir)
572
+ else if (remote.relDir) localDir = join(pluginsRoot(), remote.relDir)
573
+ if (localDir && existsSync(join(localDir, 'package.json'))) {
574
+ action = 'install'
575
+ } else {
576
+ localDir = null
577
+ registrySpec = registrySpecOf(remote)
578
+ if (registrySpec) action = 'install'
579
+ }
580
+ }
581
+ rows.push({
582
+ name: remote.name,
583
+ version: remote.version,
584
+ remoteVersion: remote.version,
585
+ status: action ? (nativeHost && kind === 'bundle' ? 'web-only' : 'installable') : 'missing',
586
+ action,
587
+ kind,
588
+ localDir,
589
+ registrySpec,
590
+ dirName: remoteDir,
591
+ })
592
+ continue
593
+ }
594
+ const same = (!remote.hash || !here.hash || remote.hash === here.hash) && remote.version === here.version
595
+ if (!same) {
596
+ rows.push({ name: here.name, version: here.version, remoteVersion: remote.version, status: 'conflict', action: null, kind })
597
+ } else if (!here.installed) {
598
+ rows.push({ name: here.name, version: here.version, status: nativeHost && kind === 'bundle' ? 'web-only' : 'install', action: 'install', kind, localDir: here.dir })
599
+ } else {
600
+ rows.push({ name: here.name, version: here.version, status: 'same', action: null, kind })
601
+ }
602
+ }
603
+ for (const here of local) {
604
+ if (manifestByName.has(here.name)) continue
605
+ if (source?.kind === 'ssh') {
606
+ if (safeDirName(here.relDir)) {
607
+ rows.push({ name: here.name, version: here.version, status: 'push', action: 'push', kind: here.kind || null, dirName: here.relDir })
608
+ } else {
609
+ const registrySpec = registrySpecOf({ name: here.name, version: here.version })
610
+ rows.push(registrySpec
611
+ ? { name: here.name, version: here.version, status: 'push', action: 'push-npm', kind: here.kind || null, registrySpec }
612
+ : { name: here.name, version: here.version, status: 'extra', action: null, kind: here.kind || null })
613
+ }
614
+ } else {
615
+ rows.push({ name: here.name, version: here.version, status: 'extra', action: null, kind: here.kind || null })
616
+ }
617
+ }
618
+ const order = { conflict: 0, installable: 1, install: 2, push: 3, extra: 4, missing: 5, same: 6, 'native-only': 7, 'web-only': 8 }
619
+ rows.sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9) || a.name.localeCompare(b.name))
620
+ return rows
621
+ }
622
+
623
+ // ---------------------------------------------------------------- state
624
+
625
+ function stateKey(scope) {
626
+ return scope?.sessionId || 'global'
627
+ }
628
+
629
+ function loadImported() {
630
+ const raw = readJson(importFile())
631
+ const manifest = raw ? validManifest(raw.manifest) : undefined
632
+ const usable = manifest && manifest.plugins.length > 0 ? manifest : null
633
+ return {
634
+ manifest: usable,
635
+ manifestSource: usable ? { kind: 'file' } : null,
636
+ importedAt: typeof raw?.importedAt === 'string' ? raw.importedAt : null,
637
+ sourceName: typeof raw?.sourceName === 'string' ? raw.sourceName.slice(0, 120) : null,
638
+ selected: new Set(),
639
+ showAll: false,
640
+ lastExportPath: null,
641
+ lastPastedCode: null,
642
+ relayLoadedAt: 0,
643
+ sshLoadedAt: 0,
644
+ }
645
+ }
646
+
647
+ function stateFor(scope) {
648
+ const key = stateKey(scope)
649
+ let state = STATE.get(key)
650
+ if (!state) {
651
+ state = loadImported()
652
+ STATE.set(key, state)
653
+ }
654
+ return state
655
+ }
656
+
657
+ function persistImported(state) {
658
+ try {
659
+ ensureStore()
660
+ writeFileSync(importFile(), JSON.stringify({
661
+ importedAt: state.importedAt,
662
+ sourceName: state.sourceName,
663
+ manifest: state.manifest,
664
+ }, null, 2) + '\n')
665
+ } catch {}
666
+ }
667
+
668
+ function loadManifestFrom(path, kind, pluginsDir) {
669
+ try {
670
+ const stat = statSync(path)
671
+ return { manifest: validManifest(readJson(path)), mtime: stat.mtimeMs, source: { kind, pluginsDir } }
672
+ } catch {
673
+ return null
674
+ }
675
+ }
676
+
677
+ /** Refresh the state manifest from relay / ssh results when those files are newer. */
678
+ function refreshManifests(state, cfg) {
679
+ const relay = loadManifestFrom(relayManifestFile(), 'relay', join(relayWorkDir(), cfg.relay.dir, 'plugins'))
680
+ if (relay?.manifest && relay.manifest.plugins.length > 0 && relay.mtime > state.relayLoadedAt) {
681
+ state.manifest = relay.manifest
682
+ state.manifestSource = relay.source
683
+ state.importedAt = relay.manifest.exportedAt
684
+ state.sourceName = 'Git 中转'
685
+ state.showAll = false
686
+ state.relayLoadedAt = relay.mtime
687
+ state.selected.clear()
688
+ }
689
+ const ssh = loadManifestFrom(sshManifestFile(), 'ssh', null)
690
+ if (ssh?.manifest && ssh.manifest.plugins.length > 0 && ssh.mtime > state.sshLoadedAt) {
691
+ state.manifest = ssh.manifest
692
+ state.manifestSource = ssh.source
693
+ state.importedAt = ssh.manifest.exportedAt
694
+ state.sourceName = 'SSH 远端'
695
+ state.showAll = false
696
+ state.sshLoadedAt = ssh.mtime
697
+ state.selected.clear()
698
+ }
699
+ }
700
+
701
+ // ---------------------------------------------------------------- run status
702
+
703
+ function readTaskStatus() {
704
+ try {
705
+ const parts = readFileSync(taskStatusPath(), 'utf8').trim().split(/\s+/)
706
+ const started = Number(parts[1]) || 0
707
+ if (parts[0] === 'running') return { running: true, startedAt: started * 1000, kind: parts[2] || '' }
708
+ if (parts[0] === 'done') {
709
+ const failed = Number(parts[2]) || 0
710
+ return { running: false, finishedAt: started * 1000, failed, kind: parts[3] || '', ok: failed === 0 }
711
+ }
712
+ } catch {}
713
+ return null
714
+ }
715
+
716
+ function readLogTail(max = 4) {
717
+ try {
718
+ const lines = readFileSync(taskLogPath(), 'utf8').trim().split('\n').filter(Boolean)
719
+ return lines.slice(-max).map((line) => line.length > 120 ? `${line.slice(0, 120)}…` : line)
720
+ } catch {
721
+ return []
722
+ }
723
+ }
724
+
725
+ /** The item currently running: last `@@ start` without a matching `ok`/`fail`. */
726
+ function readTaskCurrent() {
727
+ let text
728
+ try { text = readFileSync(taskLogPath(), 'utf8') } catch { return undefined }
729
+ let current
730
+ for (const raw of text.split('\n')) {
731
+ const marker = /^@@ (\S+) (\S+) (start|ok|fail)$/.exec(raw)
732
+ if (!marker) continue
733
+ const [, action, name, phase] = marker
734
+ if (phase === 'start') current = { action, name }
735
+ else if (current && current.action === action && current.name === name) current = undefined
736
+ }
737
+ return current
738
+ }
739
+
740
+ /** Per-item results of the last task, parsed from `@@ action name start|ok|fail` markers. */
741
+ function readTaskResults() {
742
+ let text
743
+ try { text = readFileSync(taskLogPath(), 'utf8') } catch { return [] }
744
+ const results = []
745
+ let current
746
+ for (const raw of text.split('\n')) {
747
+ const marker = /^@@ (\S+) (\S+) (start|ok|fail)$/.exec(raw)
748
+ if (marker) {
749
+ const [, action, name, phase] = marker
750
+ if (phase === 'start') {
751
+ current = { action, name, lines: [] }
752
+ continue
753
+ }
754
+ if (current && current.action === action && current.name === name) {
755
+ results.push({
756
+ action,
757
+ name,
758
+ ok: phase === 'ok',
759
+ message: phase === 'fail' ? current.lines.slice(-2).join(' ').slice(0, 140) : '',
760
+ })
761
+ current = undefined
762
+ }
763
+ continue
764
+ }
765
+ if (current) current.lines.push(raw.trim())
766
+ }
767
+ return results
768
+ }
769
+
770
+ // ---------------------------------------------------------------- task runner
771
+
772
+ /** How many items the current/last task planned to process (0 when unknown). */
773
+ function readTaskTotal() {
774
+ try {
775
+ const count = Number(readFileSync(taskTotalPath(), 'utf8').trim())
776
+ return Number.isFinite(count) && count > 0 ? count : 0
777
+ } catch {
778
+ return 0
779
+ }
780
+ }
781
+
782
+ /** "12 秒" / "2 分 05 秒" — coarse on purpose; progress refreshes on demand. */
783
+ function elapsedText(seconds, en) {
784
+ if (seconds < 60) return en ? `${seconds}s` : `${seconds} 秒`
785
+ const minutes = Math.floor(seconds / 60)
786
+ const rest = seconds % 60
787
+ return en ? `${minutes}m${rest}s` : `${minutes} 分 ${rest} 秒`
788
+ }
789
+
790
+ function taskRunning() {
791
+ const status = readTaskStatus()
792
+ return Boolean(status?.running && Date.now() - status.startedAt < 15 * 60 * 1000)
793
+ }
794
+
795
+ /** Start one background task; returns `{ ok }` or an explanation of why it did not start. */
796
+ function startTask(kind, lines, win) {
797
+ if (taskRunning()) return { ok: false, error: '已有任务在运行,等它结束再试' }
798
+ ensureStore()
799
+ try { writeFileSync(taskTotalPath(), '0\n') } catch {}
800
+ if (process.platform === 'win32') return startWindowsTask(kind, win)
801
+ const script = [
802
+ '#!/bin/sh',
803
+ `LOG=${shQuote(taskLogPath())}`,
804
+ `STATUS=${shQuote(taskStatusPath())}`,
805
+ `PROFILE=${shQuote(profileName())}`,
806
+ 'DSH_BIN="${DSH_BIN:-$(command -v dsh || echo /usr/local/bin/dsh)}"',
807
+ ': > "$LOG"',
808
+ 'failed=0',
809
+ 'say() { echo "$@" >> "$LOG"; }',
810
+ ...lines,
811
+ `echo "done $(date +%s) $failed ${kind}" > "$STATUS"`,
812
+ ].join('\n') + '\n'
813
+ writeFileSync(taskScriptPath(), script, { mode: 0o755 })
814
+ writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} ${kind}\n`)
815
+ const child = spawn('/bin/sh', [taskScriptPath()], { detached: true, stdio: 'ignore', env: process.env })
816
+ child.on('error', () => {})
817
+ child.unref()
818
+ return { ok: true }
819
+ }
820
+
821
+ /** `dsh` entry point that also works from a packaged Windows runtime. */
822
+ function dshCommand() {
823
+ const entry = typeof process.argv[1] === 'string' ? process.argv[1] : ''
824
+ if (/\.(?:c|m)?js$/i.test(entry)) return { command: process.execPath, args: [entry] }
825
+ const bin = process.env.DSH_BIN || ''
826
+ if (/\.(?:c|m)?js$/i.test(bin)) return { command: process.execPath, args: [bin] }
827
+ if (bin) return { command: bin, args: [] }
828
+ return { command: process.execPath, args: [entry] }
829
+ }
830
+
831
+ /** Windows has no `/bin/sh`; install jobs run through Node instead of the POSIX task script. */
832
+ function startWindowsTask(kind, win) {
833
+ const installs = kind === 'apply' && Array.isArray(win?.installs)
834
+ ? win.installs.filter((job) => job && typeof job.name === 'string' && typeof job.target === 'string' && job.target !== '')
835
+ : []
836
+ if (kind === 'apply' && (win?.other || 0) > 0) {
837
+ return { ok: false, error: 'Windows 上暂不支持 SSH 推/拉,请先只选安装项' }
838
+ }
839
+ if (installs.length === 0) return { ok: false, error: 'Windows 上暂不支持 Git 中转 / SSH,请用同步码安装' }
840
+ const dsh = dshCommand()
841
+ const spec = {
842
+ kind,
843
+ log: taskLogPath(),
844
+ status: taskStatusPath(),
845
+ items: installs.map((job) => ({
846
+ action: 'install',
847
+ name: markerName(job.name),
848
+ commands: [{ command: dsh.command, args: [...dsh.args, 'plugin', '--profile', profileName(), 'add', job.target] }],
849
+ })),
850
+ }
851
+ writeFileSync(taskRunnerPath(), windowsTaskRunnerSource())
852
+ writeFileSync(taskSpecPath(), JSON.stringify(spec, null, 2) + '\n')
853
+ writeFileSync(taskLogPath(), '')
854
+ writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} ${kind}\n`)
855
+ try {
856
+ const child = spawn(process.execPath, [taskRunnerPath(), taskSpecPath()], { detached: true, stdio: 'ignore', env: process.env })
857
+ child.on('error', () => {})
858
+ child.unref()
859
+ } catch (error) {
860
+ writeFileSync(taskStatusPath(), `done ${Math.floor(Date.now() / 1000)} ${installs.length} ${kind}\n`)
861
+ return { ok: false, error: `启动安装任务失败:${String(error?.message || error)}` }
862
+ }
863
+ return { ok: true }
864
+ }
865
+
866
+ function windowsTaskRunnerSource() {
867
+ return `'use strict'
868
+ const { spawn } = require('node:child_process')
869
+ const fs = require('node:fs')
870
+ const spec = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'))
871
+ const log = fs.openSync(spec.log, 'w')
872
+ const say = (line) => fs.writeSync(log, line + '\\n')
873
+ const status = (line) => fs.writeFileSync(spec.status, line + '\\n')
874
+ status('running ' + Math.floor(Date.now() / 1000) + ' ' + spec.kind)
875
+ function run(command, args) {
876
+ return new Promise((resolve) => {
877
+ let child
878
+ try {
879
+ child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], env: process.env })
880
+ } catch (error) {
881
+ say(String(error && error.message ? error.message : error))
882
+ resolve(1)
883
+ return
884
+ }
885
+ child.stdout.on('data', (chunk) => fs.writeSync(log, chunk))
886
+ child.stderr.on('data', (chunk) => fs.writeSync(log, chunk))
887
+ child.on('error', (error) => { say(String(error && error.message ? error.message : error)); resolve(1) })
888
+ child.on('exit', (code) => resolve(code === 0 ? 0 : 1))
889
+ })
890
+ }
891
+ ;(async () => {
892
+ let failed = 0
893
+ for (const item of spec.items) {
894
+ say('@@ ' + item.action + ' ' + item.name + ' start')
895
+ let code = 0
896
+ for (const command of item.commands) {
897
+ if (await run(command.command, command.args) !== 0) code = 1
898
+ }
899
+ if (code === 0) say('@@ ' + item.action + ' ' + item.name + ' ok')
900
+ else { failed += 1; say('@@ ' + item.action + ' ' + item.name + ' fail') }
901
+ }
902
+ fs.closeSync(log)
903
+ status('done ' + Math.floor(Date.now() / 1000) + ' ' + failed + ' ' + spec.kind)
904
+ })().catch((error) => {
905
+ try { say(String(error && error.stack ? error.stack : error)) } catch {}
906
+ try { fs.closeSync(log) } catch {}
907
+ try { status('done ' + Math.floor(Date.now() / 1000) + ' 1 ' + spec.kind) } catch {}
908
+ })
909
+ `
910
+ }
911
+
912
+ function localAddCommand(dir) {
913
+ return `"$DSH_BIN" plugin --profile "$PROFILE" add ${shQuote(dir)}`
914
+ }
915
+
916
+ /** The plugin manager reports a failed operation as `error` + `application:"failed"`, not `ok:false`. */
917
+ function installFailure(result) {
918
+ if (!result || typeof result !== 'object') return ''
919
+ if (!result.error && result.application !== 'failed' && result.ok !== false) return ''
920
+ const error = result.error || { message: 'install failed' }
921
+ const detail = error.diagnostic || error.message || error.code || result.application
922
+ return typeof detail === 'string' ? detail : JSON.stringify(detail)
923
+ }
924
+
925
+ function installTimedOut(result) {
926
+ const kind = String(result?.error?.kind || result?.packageResult?.kind || '')
927
+ return kind.toLowerCase().includes('timeout')
928
+ }
929
+
930
+ /** The desktop host runs `@deepseek-ai/dsh-desktop-host/lib/index.js`; its CLI is the sibling file. */
931
+ function dshCliEntry() {
932
+ const host = typeof process.argv[2] === 'string' ? process.argv[2] : ''
933
+ if (!/[\\/]dsh-desktop-host[\\/]lib[\\/]index\.(?:c|m)?js$/i.test(host)) return undefined
934
+ const cli = join(dirname(host), 'cli.js')
935
+ try { return existsSync(cli) ? cli : undefined } catch { return undefined }
936
+ }
937
+
938
+ /** Fallback when the host manager times out: its own CLI gives pnpm a 15-minute budget. */
939
+ function runCliInstall(target) {
940
+ const cli = dshCliEntry()
941
+ if (!cli) return Promise.resolve({ ok: false, output: '找不到 dsh 命令行,无法回退安装' })
942
+ return new Promise((resolvePromise) => {
943
+ let output = ''
944
+ let child
945
+ try {
946
+ child = spawn(process.execPath, ['--expose-internals', cli, 'plugin', '--profile', profileName(), 'add', target], {
947
+ cwd: profileDir(),
948
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
949
+ stdio: ['ignore', 'pipe', 'pipe'],
950
+ windowsHide: true,
951
+ })
952
+ } catch (error) {
953
+ resolvePromise({ ok: false, output: String(error?.message || error) })
954
+ return
955
+ }
956
+ const take = (chunk) => { output = (output + chunk).slice(-4000) }
957
+ child.stdout?.on('data', take)
958
+ child.stderr?.on('data', take)
959
+ const timer = setTimeout(() => { try { child.kill() } catch {} }, 15 * 60 * 1000)
960
+ child.on('error', (error) => { clearTimeout(timer); resolvePromise({ ok: false, output: `${output}\n${String(error?.message || error)}` }) })
961
+ child.on('close', (code) => { clearTimeout(timer); resolvePromise({ ok: code === 0, output }) })
962
+ })
963
+ }
964
+
965
+ /** Install jobs through the host's own plugin manager (same path as the plugin market). */
966
+ function startInstallTask(ctx, jobs) {
967
+ const manager = ctx.get?.('pluginManager')
968
+ if (!manager || typeof manager.installBundle !== 'function') return null
969
+ if (taskRunning()) return { ok: false, error: '已有任务在运行,等它结束再试' }
970
+ ensureStore()
971
+ try { writeFileSync(taskTotalPath(), '0\n') } catch {}
972
+ writeFileSync(taskLogPath(), '')
973
+ writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} apply\n`)
974
+ const installs = jobs.filter((job) => job.action === 'install')
975
+ const say = (line) => { try { writeFileSync(taskLogPath(), `${line}\n`, { flag: 'a' }) } catch {} }
976
+ ;(async () => {
977
+ let failed = 0
978
+ for (const job of installs) {
979
+ const name = markerName(job.name)
980
+ const target = job.localDir || job.registrySpec
981
+ say(`@@ install ${name} start`)
982
+ if (!target) {
983
+ failed += 1
984
+ say(`@@ install ${name} fail`)
985
+ say('no install source')
986
+ continue
987
+ }
988
+ try {
989
+ const result = await manager.installBundle(target, { enabled: true })
990
+ const failure = installFailure(result)
991
+ if (failure && installTimedOut(result)) {
992
+ say(`@@ install ${name} timeout, retry via dsh cli`)
993
+ const retry = await runCliInstall(target)
994
+ if (retry.ok) {
995
+ say(`@@ install ${name} ok`)
996
+ say('已通过 dsh CLI 安装')
997
+ say(retry.output.slice(-1000))
998
+ say('重启 DSH 后生效')
999
+ } else {
1000
+ failed += 1
1001
+ say(`@@ install ${name} cli failed`)
1002
+ say(retry.output.slice(-1500))
1003
+ say(`@@ install ${name} fail`)
1004
+ }
1005
+ } else if (failure) {
1006
+ failed += 1
1007
+ say(failure.slice(0, 2000))
1008
+ say(`@@ install ${name} fail`)
1009
+ } else {
1010
+ say(`@@ install ${name} ok`)
1011
+ const value = result && result.value !== undefined ? result.value : result
1012
+ try { say(JSON.stringify(value).slice(0, 2000)) } catch {}
1013
+ }
1014
+ } catch (error) {
1015
+ failed += 1
1016
+ say(String(error && (error.stack || error.message) || error).slice(0, 2000))
1017
+ say(`@@ install ${name} fail`)
1018
+ }
1019
+ }
1020
+ try { writeFileSync(taskStatusPath(), `done ${Math.floor(Date.now() / 1000)} ${failed} apply\n`) } catch {}
1021
+ })()
1022
+ return { ok: true }
1023
+ }
1024
+
1025
+ /** Prefer the plugin manager for pure installs; keep the shell path for SSH push/pull. */
1026
+ function startApplyTask(ctx, cfg, jobs) {
1027
+ const writeTotal = () => { try { writeFileSync(taskTotalPath(), `${jobs.length}\n`) } catch {} }
1028
+ if (jobs.every((job) => job.action === 'install')) {
1029
+ const started = startInstallTask(ctx, jobs)
1030
+ if (started) {
1031
+ if (started.ok) writeTotal()
1032
+ return started
1033
+ }
1034
+ }
1035
+ const started = startTask('apply', buildApply(cfg, jobs), winTask(jobs))
1036
+ if (started.ok) writeTotal()
1037
+ return started
1038
+ }
1039
+
1040
+ /** One result-reporting item: start marker, commands, ok/fail marker. */
1041
+ function itemLines(action, name, commands) {
1042
+ const tag = `${action} ${markerName(name)}`
1043
+ const lines = [`say "@@ ${tag} start"`, 'itemfailed=0']
1044
+ for (const command of commands) {
1045
+ lines.push(`${command} >> "$LOG" 2>&1 || itemfailed=$((itemfailed + 1))`)
1046
+ }
1047
+ lines.push(`if [ "$itemfailed" -eq 0 ]; then say "@@ ${tag} ok"; else failed=$((failed + 1)); say "@@ ${tag} fail"; fi`)
1048
+ return lines
1049
+ }
1050
+
1051
+ function sshPrelude(cfg) {
1052
+ const target = cfg.ssh.user ? `${cfg.ssh.user}@${cfg.ssh.host}` : cfg.ssh.host
1053
+ const keyOpt = cfg.ssh.identity ? `-i ${shQuote(cfg.ssh.identity)}` : ''
1054
+ return [
1055
+ `SSH_PORT=${shQuote(String(cfg.ssh.port))}`,
1056
+ `SSH_TARGET=${shQuote(target)}`,
1057
+ `SSH_KEY_OPT=${shQuote(keyOpt)}`,
1058
+ 'ssh_run() { ssh -p "$SSH_PORT" -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 $SSH_KEY_OPT "$@"; }',
1059
+ ]
1060
+ }
1061
+
1062
+ function remotePaths(cfg) {
1063
+ const home = cfg.ssh.remoteHome
1064
+ const plugins = `${home}/dsh-go/plugins`
1065
+ return { home, plugins }
1066
+ }
1067
+
1068
+ function buildRelayPush(cfg, plugins, manifestPath) {
1069
+ const work = relayWorkDir()
1070
+ const lines = [
1071
+ `RELAY_REPO=${shQuote(cfg.relay.repo)}`,
1072
+ `RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
1073
+ `RELAY_DIR=${shQuote(cfg.relay.dir)}`,
1074
+ `WORK=${shQuote(work)}`,
1075
+ 'if [ -d "$WORK/.git" ]; then',
1076
+ ' say "pull relay"',
1077
+ ' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
1078
+ 'else',
1079
+ ' rm -rf "$WORK"',
1080
+ ' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
1081
+ ' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
1082
+ 'fi',
1083
+ 'if [ "$failed" -eq 0 ]; then',
1084
+ ' rm -rf "$WORK/$RELAY_DIR/plugins"',
1085
+ ' mkdir -p "$WORK/$RELAY_DIR/plugins"',
1086
+ ]
1087
+ for (const plugin of plugins) {
1088
+ if (!safeDirName(plugin.relDir)) continue
1089
+ 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))`)
1090
+ }
1091
+ lines.push(
1092
+ ` cp ${shQuote(manifestPath)} "$WORK/$RELAY_DIR/manifest.json" >> "$LOG" 2>&1 || failed=$((failed + 1))`,
1093
+ ' git -C "$WORK" add -A >> "$LOG" 2>&1',
1094
+ ' git -C "$WORK" -c user.name=dsh-go -c user.email=dsh-go@local commit -m "plugin-sync $(date +%s)" >> "$LOG" 2>&1 || true',
1095
+ ' git -C "$WORK" push origin "$RELAY_BRANCH" >> "$LOG" 2>&1 || failed=$((failed + 1))',
1096
+ 'fi',
1097
+ )
1098
+ return lines
1099
+ }
1100
+
1101
+ function buildRelayPull(cfg) {
1102
+ const work = relayWorkDir()
1103
+ const relayManifest = relayManifestFile()
1104
+ return [
1105
+ `RELAY_REPO=${shQuote(cfg.relay.repo)}`,
1106
+ `RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
1107
+ `RELAY_DIR=${shQuote(cfg.relay.dir)}`,
1108
+ `WORK=${shQuote(work)}`,
1109
+ 'if [ -d "$WORK/.git" ]; then',
1110
+ ' say "pull relay"',
1111
+ ' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
1112
+ 'else',
1113
+ ' rm -rf "$WORK"',
1114
+ ' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
1115
+ ' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
1116
+ 'fi',
1117
+ 'if [ "$failed" -eq 0 ] && [ -f "$WORK/$RELAY_DIR/manifest.json" ]; then',
1118
+ ` cp "$WORK/$RELAY_DIR/manifest.json" ${shQuote(relayManifest)} >> "$LOG" 2>&1 || failed=$((failed + 1))`,
1119
+ 'elif [ "$failed" -eq 0 ]; then',
1120
+ ' say "relay has no manifest"',
1121
+ ' failed=$((failed + 1))',
1122
+ 'fi',
1123
+ ]
1124
+ }
1125
+
1126
+ function buildSshTest(cfg) {
1127
+ return [...sshPrelude(cfg), 'ssh_run "$SSH_TARGET" "true" >> "$LOG" 2>&1 || failed=$((failed + 1))']
1128
+ }
1129
+
1130
+ function buildSshScan(cfg) {
1131
+ const { home } = remotePaths(cfg)
1132
+ const profileDir = `${home}/profiles/${cfg.ssh.profile}`
1133
+ const scanner = remoteScannerFile()
1134
+ writeFileSync(scanner, remoteScannerSource())
1135
+ return [
1136
+ ...sshPrelude(cfg),
1137
+ `ssh_run "$SSH_TARGET" "${cfg.ssh.nodePath} - ${home} ${profileDir}" < ${shQuote(scanner)} > ${shQuote(sshManifestFile())} 2>> "$LOG" || failed=$((failed + 1))`,
1138
+ ]
1139
+ }
1140
+
1141
+ function buildSshPush(cfg, jobs) {
1142
+ const { home, plugins } = remotePaths(cfg)
1143
+ const dsh = cfg.ssh.dshPath
1144
+ const profile = cfg.ssh.profile
1145
+ const lines = [...sshPrelude(cfg)]
1146
+ for (const job of jobs.filter((item) => item.action === 'push' && safeName(item.dirName))) {
1147
+ lines.push(...itemLines('push', job.name, [
1148
+ `tar -C ${shQuote(pluginsRoot())} -czf - --exclude=node_modules --exclude=.git ${shQuote(job.dirName)} | ssh_run "$SSH_TARGET" "mkdir -p ${plugins} && tar -C ${plugins} -xzf -"`,
1149
+ `ssh_run "$SSH_TARGET" "cd ${home} && ${dsh} plugin --profile ${profile} add ${plugins}/${job.dirName}"`,
1150
+ ]))
1151
+ }
1152
+ for (const job of jobs.filter((item) => item.action === 'push-npm' && item.registrySpec)) {
1153
+ lines.push(...itemLines('push', job.name, [
1154
+ `ssh_run "$SSH_TARGET" "cd ${home} && ${dsh} plugin --profile ${profile} add ${shQuote(job.registrySpec)}"`,
1155
+ ]))
1156
+ }
1157
+ return lines
1158
+ }
1159
+
1160
+ function buildSshPull(cfg, jobs) {
1161
+ const { plugins } = remotePaths(cfg)
1162
+ const lines = [...sshPrelude(cfg)]
1163
+ for (const job of jobs.filter((item) => safeName(item.dirName))) {
1164
+ lines.push(...itemLines('pull', job.name, [
1165
+ `ssh_run "$SSH_TARGET" "tar -C ${plugins} -czf - ${job.dirName}" | tar -C ${shQuote(pluginsRoot())} -xzf -`,
1166
+ localAddCommand(join(pluginsRoot(), job.dirName)),
1167
+ ]))
1168
+ }
1169
+ return lines
1170
+ }
1171
+
1172
+ function installTargets(jobs) {
1173
+ return jobs
1174
+ .filter((job) => job.action === 'install')
1175
+ .map((job) => ({ name: job.name, target: job.localDir || job.registrySpec }))
1176
+ }
1177
+
1178
+ /** Windows task payload: install jobs only, plus how many push/pull jobs were left out. */
1179
+ function winTask(jobs) {
1180
+ const installs = installTargets(jobs)
1181
+ return { installs, other: jobs.length - installs.length }
1182
+ }
1183
+
1184
+ function buildApply(cfg, jobs) {
1185
+ const lines = []
1186
+ const installs = jobs.filter((job) => job.action === 'install')
1187
+ const pushes = jobs.filter((job) => job.action === 'push' || job.action === 'push-npm')
1188
+ const pulls = jobs.filter((job) => job.action === 'pull')
1189
+ for (const job of installs) {
1190
+ const target = job.localDir || job.registrySpec
1191
+ if (target) lines.push(...itemLines('install', job.name, [localAddCommand(target)]))
1192
+ }
1193
+ if (pushes.length > 0) lines.push(...buildSshPush(cfg, pushes))
1194
+ if (pulls.length > 0) lines.push(...buildSshPull(cfg, pulls))
1195
+ return lines
1196
+ }
1197
+
1198
+ let SCANNER_CACHE
1199
+ function remoteScannerSource() {
1200
+ if (SCANNER_CACHE) return SCANNER_CACHE
1201
+ SCANNER_CACHE = `const fs = require('fs')
1202
+ const path = require('path')
1203
+ const crypto = require('crypto')
1204
+ const home = process.argv[2]
1205
+ const profileDir = process.argv[3] || path.join(home, 'profiles', 'web')
1206
+ const root = path.join(home, 'dsh-go', 'plugins')
1207
+ const out = new Map()
1208
+ function kind(pkg) {
1209
+ const native = Boolean(pkg.dshGo && typeof pkg.dshGo === 'object')
1210
+ const bundle = Boolean(pkg.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle)
1211
+ if (native && bundle) return 'both'
1212
+ if (native) return 'native'
1213
+ if (bundle) return 'bundle'
1214
+ return null
1215
+ }
1216
+ function usable(pkg) {
1217
+ if (!pkg || typeof pkg.name !== 'string') return false
1218
+ if (pkg.name.startsWith('@deepseek-ai/') || pkg.name === 'dsh-go-plugin-sync') return false
1219
+ return kind(pkg) !== null
1220
+ }
1221
+ function walk(dir, acc, depth) {
1222
+ if (depth > 6 || acc.length >= 300) return
1223
+ let entries
1224
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
1225
+ for (const e of entries) {
1226
+ if (acc.length >= 300) return
1227
+ const full = path.join(dir, e.name)
1228
+ if (e.isDirectory()) walk(full, acc, depth + 1)
1229
+ else if (e.isFile()) acc.push(full)
1230
+ }
1231
+ }
1232
+ function hash(dir) {
1233
+ const h = crypto.createHash('sha256')
1234
+ try { h.update(fs.readFileSync(path.join(dir, 'package.json'))) } catch { return null }
1235
+ const files = []
1236
+ walk(path.join(dir, 'lib'), files, 0)
1237
+ files.sort()
1238
+ for (const f of files) {
1239
+ let b
1240
+ try { b = fs.readFileSync(f) } catch { continue }
1241
+ if (b.length > 2097152) continue
1242
+ h.update(path.relative(dir, f).split(path.sep).join('/'))
1243
+ h.update(String.fromCharCode(0))
1244
+ h.update(b)
1245
+ }
1246
+ return h.digest('hex').slice(0, 16)
1247
+ }
1248
+ try {
1249
+ for (const e of fs.readdirSync(root, { withFileTypes: true })) {
1250
+ if (!e.isDirectory() || e.name.startsWith('.')) continue
1251
+ const dir = path.join(root, e.name)
1252
+ let pkg
1253
+ try { pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')) } catch { continue }
1254
+ if (!usable(pkg)) continue
1255
+ out.set(pkg.name, { name: pkg.name, version: String(pkg.version || '0.0.0'), hash: hash(dir), relDir: e.name, depSpec: null, kind: kind(pkg), installed: false })
1256
+ }
1257
+ } catch {}
1258
+ try {
1259
+ const profile = JSON.parse(fs.readFileSync(path.join(profileDir, 'package.json'), 'utf8'))
1260
+ const deps = profile.dependencies || {}
1261
+ for (const [dep, spec] of Object.entries(deps)) {
1262
+ let pkg
1263
+ try { pkg = JSON.parse(fs.readFileSync(path.join(profileDir, 'node_modules', dep, 'package.json'), 'utf8')) } catch { continue }
1264
+ if (!usable(pkg)) continue
1265
+ let relDir = null
1266
+ if (typeof spec === 'string' && (spec.startsWith('link:') || spec.startsWith('file:'))) {
1267
+ const raw = spec.slice(spec.indexOf(':') + 1)
1268
+ const rel = path.relative(root, path.resolve(profileDir, raw))
1269
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) relDir = rel.split(path.sep).join('/')
1270
+ }
1271
+ const entry = { name: pkg.name, version: String(pkg.version || '0.0.0'), hash: hash(path.join(profileDir, 'node_modules', dep)), relDir, depSpec: typeof spec === 'string' ? spec : null, kind: kind(pkg), installed: true }
1272
+ const existing = out.get(pkg.name)
1273
+ if (existing) {
1274
+ existing.installed = true
1275
+ existing.depSpec = entry.depSpec
1276
+ if (!existing.relDir) existing.relDir = entry.relDir
1277
+ if (!existing.hash) existing.hash = entry.hash
1278
+ if (!existing.kind) existing.kind = entry.kind
1279
+ } else {
1280
+ out.set(pkg.name, entry)
1281
+ }
1282
+ }
1283
+ } catch {}
1284
+ process.stdout.write(JSON.stringify({ v: 1, exportedAt: new Date().toISOString(), host: { profile: path.basename(profileDir) }, plugins: [...out.values()] }))
1285
+ `
1286
+ return SCANNER_CACHE
1287
+ }
1288
+
1289
+ // ---------------------------------------------------------------- workspace
1290
+
1291
+ function workspaceCandidates(ctx, scope) {
1292
+ const out = []
1293
+ try {
1294
+ const registry = ctx?.get?.('workspaceRegistry')
1295
+ if (registry && typeof registry.list === 'function') {
1296
+ const list = registry.list() || []
1297
+ if (scope?.sessionId) {
1298
+ const match = list.find((w) => Array.isArray(w.sessionIds) && w.sessionIds.includes(scope.sessionId))
1299
+ if (match?.path) out.push(match.path)
1300
+ }
1301
+ for (const w of list) if (w?.path) out.push(w.path)
1302
+ }
1303
+ } catch {}
1304
+ if (process.env.DSH_WORKSPACE) out.push(process.env.DSH_WORKSPACE)
1305
+ out.push(process.cwd(), join(home(), 'workspace'))
1306
+ return [...new Set(out)]
1307
+ }
1308
+
1309
+ function writableDir(ctx, scope) {
1310
+ for (const dir of workspaceCandidates(ctx, scope)) {
1311
+ try {
1312
+ accessSync(dir, constants.W_OK)
1313
+ if (statSync(dir).isDirectory()) return dir
1314
+ } catch {}
1315
+ }
1316
+ return null
1317
+ }
1318
+
1319
+ function exportTarget(ctx, scope) {
1320
+ const dir = writableDir(ctx, scope)
1321
+ return dir ? join(dir, MANIFEST_FILE) : join(storeDir(), MANIFEST_FILE)
1322
+ }
1323
+
1324
+ // ---------------------------------------------------------------- view
1325
+
1326
+ function enableText(caps) {
1327
+ return String(caps?.locale || '').toLowerCase().startsWith('en')
1328
+ }
1329
+
1330
+ function statusLine(row, en) {
1331
+ let text = {
1332
+ same: en ? 'same' : '一致',
1333
+ conflict: en ? 'conflict: local vs manifest differ' : '冲突:本机与清单不同',
1334
+ install: en ? 'not installed yet' : '本机未安装',
1335
+ installable: en ? 'can install from this manifest' : '可从这份清单安装',
1336
+ missing: en ? 'files not on this host' : '本机缺少文件,需手动拷贝',
1337
+ extra: en ? 'not in manifest' : '清单里没有',
1338
+ push: en ? 'remote lacks it; can push' : '远端没有,可推送',
1339
+ 'native-only': en ? 'phone-only native plugin; not supported here' : '手机端原生插件,电脑端不支持',
1340
+ 'web-only': en ? 'desktop/web plugin; no native UI on the phone' : '电脑/网页端插件,手机无原生界面',
1341
+ }[row.status] || row.status
1342
+ if (row.status !== 'web-only' && row.status !== 'native-only') {
1343
+ if (row.action === 'install' && row.registrySpec) text = en ? 'install from npm' : '可从 npm 安装'
1344
+ else if (row.action === 'install' && row.localDir) text = en ? 'install from files' : '可从文件安装'
1345
+ else if (row.action === 'pull') text = en ? 'pull from remote' : '可从远端拉取'
1346
+ else if (row.action === 'push-npm') text = en ? 'remote installs it from npm' : '远端从 npm 安装'
1347
+ }
1348
+ const version = row.status === 'conflict' && row.remoteVersion && row.remoteVersion !== row.version
1349
+ ? `${row.version} → ${row.remoteVersion}`
1350
+ : row.version
1351
+ return `${version} · ${text}`
1352
+ }
1353
+
1354
+ function statusTone(status) {
1355
+ if (status === 'conflict' || status === 'extra') return 'warn'
1356
+ if (status === 'installable' || status === 'install' || status === 'push') return 'info'
1357
+ if (status === 'missing') return 'bad'
1358
+ return undefined
1359
+ }
1360
+
1361
+ const TASK_LABELS = {
1362
+ apply: ['应用所选', 'apply selected'],
1363
+ 'relay-push': ['推送中转', 'push to relay'],
1364
+ 'relay-pull': ['拉取中转', 'pull from relay'],
1365
+ 'ssh-test': ['测试 SSH', 'test SSH'],
1366
+ 'ssh-scan': ['拉远端清单', 'scan remote'],
1367
+ }
1368
+
1369
+ function taskLabel(kind, en) {
1370
+ return TASK_LABELS[kind]?.[en ? 1 : 0] || kind
1371
+ }
1372
+
1373
+ function buildView(scope, caps, ctx) {
1374
+ const en = enableText(caps)
1375
+ const cfg = loadConfig(ctx, scope)
1376
+ const state = stateFor(scope)
1377
+ refreshManifests(state, cfg)
1378
+ const local = localPluginsCached()
1379
+ const rows = diffRows(local, state.manifest, state.manifestSource, { dshGo: true })
1380
+ const components = Array.isArray(caps?.components) ? caps.components : []
1381
+ const canForm = components.includes('form') && components.includes('textField')
1382
+ const children = []
1383
+
1384
+ children.push({ type: 'text', text: en
1385
+ ? 'Copy a sync code (all or selected), or paste one below. Sync only installs missing plugins; it never touches what you already have.'
1386
+ : '复制同步码(全部或选中),或在下面粘贴导入。同步只安装缺少的插件,不会动已有的。' })
1387
+
1388
+ if (canForm) {
1389
+ children.push({ type: 'form', submit: 'import-code', submitLabel: en ? 'Import code' : '导入同步码', children: [
1390
+ {
1391
+ type: 'textField',
1392
+ label: en ? 'Sync code' : '同步码',
1393
+ bind: 'data.paste.code',
1394
+ multiline: true,
1395
+ maxLines: 8,
1396
+ maxLength: 2000,
1397
+ placeholder: en ? 'Paste DSHSYNC1:… here' : '在这里粘贴 DSHSYNC1: 开头的同步码',
1398
+ },
1399
+ ] })
1400
+ } else {
1401
+ children.push({ type: 'callout', tone: 'info', text: en
1402
+ ? 'This app version has no panel input; use the relay or file import.'
1403
+ : '当前 App 版本不支持面板输入,请用中转或文件导入。' })
1404
+ }
1405
+
1406
+ children.push({ type: 'row', children: [
1407
+ { type: 'metric', label: en ? 'Local' : '本机', value: String(local.length) },
1408
+ { type: 'metric', label: en ? 'Manifest' : '清单', value: state.manifest ? String(state.manifest.plugins.length) : '—' },
1409
+ { type: 'metric', label: en ? 'Selected' : '已选', value: String(state.selected.size) },
1410
+ ] })
1411
+
1412
+ children.push({ type: 'keyValue', items: [
1413
+ [en ? 'Relay' : '中转', cfg.relay.repo || (en ? 'not configured' : '未配置')],
1414
+ [en ? 'SSH' : 'SSH', cfg.ssh.host ? `${cfg.ssh.user ? `${cfg.ssh.user}@` : ''}${cfg.ssh.host}:${cfg.ssh.port}` : (en ? 'not configured' : '未配置')],
1415
+ ] })
1416
+
1417
+ const task = readTaskStatus()
1418
+ if (task?.running) {
1419
+ const stale = Date.now() - task.startedAt > 15 * 60 * 1000
1420
+ const current = readTaskCurrent()
1421
+ const done = readTaskResults().length
1422
+ const failedSoFar = readTaskResults().filter((result) => !result.ok).length
1423
+ const total = readTaskTotal()
1424
+ const elapsed = elapsedText(Math.max(0, Math.floor((Date.now() - task.startedAt) / 1000)), en)
1425
+ const progressText = [
1426
+ current ? (en ? `processing ${current.name}` : `正在处理 ${current.name}`) : '',
1427
+ en ? `done ${done}${total ? ` / ${total}` : ''}` : `已处理 ${done}${total ? ` / ${total}` : ''}`,
1428
+ failedSoFar > 0 ? (en ? `${failedSoFar} failed` : `失败 ${failedSoFar}`) : '',
1429
+ en ? `elapsed ${elapsed}` : `已用 ${elapsed}`,
1430
+ ].filter(Boolean).join(' · ')
1431
+ children.push({ type: 'callout', tone: stale ? 'warn' : 'info', text: stale
1432
+ ? (en ? `${taskLabel(task.kind, true)} running too long (${progressText}); check the log.` : `${taskLabel(task.kind, false)}运行太久(${progressText}),看下日志。`)
1433
+ : (en ? `${taskLabel(task.kind, true)} running: ${progressText}` : `${taskLabel(task.kind, false)}中:${progressText}`) })
1434
+ } else if (task && task.ok === false) {
1435
+ children.push({ type: 'callout', tone: 'bad', text: en
1436
+ ? `${taskLabel(task.kind, true)} failed (${task.failed}). Check the log.`
1437
+ : `${taskLabel(task.kind, false)}失败(${task.failed} 项),看日志。` })
1438
+ } else if (task?.ok) {
1439
+ children.push({ type: 'callout', tone: 'good', text: en
1440
+ ? `${taskLabel(task.kind, true)} finished.`
1441
+ : `${taskLabel(task.kind, false)}完成。` })
1442
+ if (task.kind === 'apply' || task.kind === 'ssh-push' || task.kind === 'ssh-scan') {
1443
+ children.push({ type: 'callout', tone: 'warn', text: en
1444
+ ? 'Installed plugins need an engine restart on that host.'
1445
+ : '装了插件的主机要重启一次引擎才加载。' })
1446
+ }
1447
+ }
1448
+
1449
+ const results = readTaskResults()
1450
+ if (results.length > 0) {
1451
+ const okCount = results.filter((result) => result.ok).length
1452
+ const failed = results.filter((result) => !result.ok)
1453
+ children.push({ type: 'text', text: en
1454
+ ? `Last run: ${okCount} ok · ${failed.length} failed`
1455
+ : `上次结果:成功 ${okCount} · 失败 ${failed.length}` })
1456
+ if (failed.length > 0) {
1457
+ children.push({ type: 'list', items: failed.slice(0, 8).map((result) => ({
1458
+ title: result.name,
1459
+ subtitle: result.message || (en ? 'failed' : '失败'),
1460
+ tone: 'bad',
1461
+ })) })
1462
+ }
1463
+ }
1464
+
1465
+ if (!state.manifest) {
1466
+ children.push({ type: 'callout', tone: 'info', text: en
1467
+ ? 'Select plugins below, then Copy code; or import a manifest / pull the relay first.'
1468
+ : '先在下面选中要同步的插件,再点复制同步码;也可以先导入清单或拉取中转。' })
1469
+ if (local.length > 0) {
1470
+ const shown = local.slice(0, 40)
1471
+ children.push({ type: 'list', items: shown.map((plugin) => ({
1472
+ title: plugin.name,
1473
+ subtitle: `${plugin.version} · ${en ? 'tap to select' : '点选'}`,
1474
+ trailing: state.selected.has(plugin.name) ? '✓' : '○',
1475
+ action: { id: 'toggle', args: { name: plugin.name } },
1476
+ })) })
1477
+ if (local.length > shown.length) {
1478
+ children.push({ type: 'text', text: en ? `…and ${local.length - shown.length} more` : `…还有 ${local.length - shown.length} 项` })
1479
+ }
1480
+ }
1481
+ } else {
1482
+ const when = state.manifest.exportedAt ? state.manifest.exportedAt.slice(0, 16).replace('T', ' ') : ''
1483
+ const source = state.sourceName || state.manifest.host?.profile || ''
1484
+ children.push({ type: 'text', text: en
1485
+ ? `Manifest: ${source || 'imported'}${when ? ` · ${when}` : ''}`
1486
+ : `清单来源:${source || '已导入'}${when ? ` · ${when}` : ''}` })
1487
+
1488
+ const pending = rows.filter((row) => row.status !== 'same')
1489
+ const installed = rows.filter((row) => row.status === 'same')
1490
+ const visible = state.showAll ? rows : pending
1491
+ if (rows.length === 0) {
1492
+ children.push({ type: 'callout', tone: 'good', text: en ? 'The two hosts match.' : '两边完全一致。' })
1493
+ } else {
1494
+ if (pending.length === 0) {
1495
+ children.push({ type: 'callout', tone: 'good', text: en ? 'Nothing pending; everything is in sync.' : '没有待处理项,已全部一致。' })
1496
+ }
1497
+ const shown = visible.slice(0, 40)
1498
+ if (shown.length > 0) {
1499
+ children.push({ type: 'list', items: shown.map((row) => {
1500
+ const item = {
1501
+ title: row.name,
1502
+ subtitle: statusLine(row, en),
1503
+ trailing: state.selected.has(row.name) ? '✓' : '○',
1504
+ action: { id: 'toggle', args: { name: row.name } },
1505
+ }
1506
+ const tone = statusTone(row.status)
1507
+ if (tone) item.tone = tone
1508
+ return item
1509
+ }) })
1510
+ }
1511
+ if (visible.length > shown.length) {
1512
+ children.push({ type: 'text', text: en ? `…and ${visible.length - shown.length} more` : `…还有 ${visible.length - shown.length} 项` })
1513
+ }
1514
+ if (!state.showAll && installed.length > 0) {
1515
+ children.push({ type: 'text', text: en
1516
+ ? `${installed.length} already installed (tap "Show all" to view)`
1517
+ : `已安装 ${installed.length} 个(点「显示全部」查看)` })
1518
+ }
1519
+ }
1520
+
1521
+ }
1522
+
1523
+ const primary = [
1524
+ { label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
1525
+ { label: en ? 'Select all' : '全选', action: 'select-all' },
1526
+ { label: en ? 'Clear' : '清空', action: 'clear' },
1527
+ { label: state.showAll ? (en ? 'Pending only' : '只看待处理') : (en ? 'Show all' : '显示全部'), action: 'toggle-show-all' },
1528
+ { label: en ? 'Refresh' : '刷新', action: 'refresh' },
1529
+ ]
1530
+ children.push({ type: 'actions', items: primary })
1531
+
1532
+ children.push({ type: 'actions', items: [
1533
+ { label: en ? 'Retry failed' : '重试失败', action: 'retry-failed' },
1534
+ { label: en ? 'Export' : '导出清单', action: 'export' },
1535
+ { label: en ? 'Read workspace' : '工作区导入', action: 'import-workspace' },
1536
+ { label: en ? 'Clear list' : '清空清单', action: 'clear-all' },
1537
+ { label: en ? 'Guide' : '使用引导', action: 'guide' },
1538
+ ] })
1539
+
1540
+ if (state.manifest && state.selected.size > 0) {
1541
+ children.push({ type: 'confirm', id: 'apply', confirmLabel: en ? 'Apply' : '应用所选', cancelLabel: en ? 'Cancel' : '取消' })
1542
+ }
1543
+
1544
+ const log = readLogTail()
1545
+ if (log.length > 0) {
1546
+ children.push({ type: 'keyValue', items: log.map((line, index) => [en ? `log ${index + 1}` : `日志 ${index + 1}`, line]) })
1547
+ }
1548
+
1549
+ const view = { type: 'stack', title: en ? 'Plugin sync' : '插件同步', children }
1550
+ if (canForm) view.v = 2
1551
+ return view
1552
+ }
1553
+
1554
+ function buildGuide(scope, caps, ctx) {
1555
+ const en = enableText(caps)
1556
+ const cfg = loadConfig(ctx, scope)
1557
+ const configPath = join(writableDir(ctx, scope) || storeDir(), CONFIG_FILE)
1558
+ return {
1559
+ type: 'stack',
1560
+ title: en ? 'Plugin sync guide' : '插件同步使用引导',
1561
+ children: [
1562
+ { type: 'text', text: en
1563
+ ? 'A copies one string; on B open Sync, paste it into the code field and tap Import.'
1564
+ : 'A 主机复制同步码;B 主机打开「插件同步」,把码粘进输入框点「导入同步码」。' },
1565
+ { type: 'text', text: en
1566
+ ? 'Both hosts need this plugin installed once (manual first time).'
1567
+ : '两端都要先装好本插件(第一次手动装)。' },
1568
+ { type: 'text', text: en
1569
+ ? '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.'
1570
+ : '同步只安装缺少的插件,不会卸载或覆盖你已经有的;版本对不上或者装不上的会标出来,但不会自动处理。' },
1571
+ { type: 'steps', items: [
1572
+ { label: en ? 'Copy on host A' : '在 A 主机复制', status: 'done', detail: en
1573
+ ? 'Panel → Copy code'
1574
+ : '插件同步面板 → 复制同步码' },
1575
+ { label: en ? 'Paste and import on B' : '在 B 粘贴并导入', status: 'current', detail: en
1576
+ ? 'Panel → code field → Import code'
1577
+ : '面板「同步码」输入框 → 导入同步码' },
1578
+ { label: en ? 'Select and apply on B' : '在 B 选中并应用', status: 'todo', detail: en
1579
+ ? 'All selected by default; deselect what you do not want'
1580
+ : '默认全选,可取消不要的项' },
1581
+ { label: en ? 'Retry failures' : '失败项点重试', status: 'todo', detail: en
1582
+ ? 'Retry failed in the panel'
1583
+ : '面板「重试失败项」' },
1584
+ { label: en ? 'Restart the engine' : '重启一次引擎', status: 'todo' },
1585
+ ] },
1586
+ { type: 'callout', tone: 'info', text: en
1587
+ ? 'The code is compressed text: it carries text files. If too large it falls back to manifest only and tries npm versions.'
1588
+ : '同步码是压缩文本,带的是文本文件;太大时退化为只带清单,本地插件会尝试按 npm 版本安装。' },
1589
+ { type: 'callout', tone: 'warn', text: en
1590
+ ? 'Only paste codes from a source you trust: plugin code runs on this host.'
1591
+ : '只粘贴可信来源的同步码:插件代码会在本机运行。' },
1592
+ { type: 'text', text: en
1593
+ ? 'Cordis bundles may depend on the DSH version or platform; failures show in the failed list.'
1594
+ : 'Cordis 插件可能依赖 DSH 版本或平台,装不上会进失败清单。' },
1595
+ { type: 'callout', tone: 'info', text: en
1596
+ ? `Config file: ${configPath}`
1597
+ : `配置文件:${configPath}` },
1598
+ { type: 'keyValue', items: [
1599
+ ['relay.repo', cfg.relay.repo || '—'],
1600
+ ['ssh.host', cfg.ssh.host || '—'],
1601
+ ] },
1602
+ { type: 'text', text: en
1603
+ ? 'Advanced: large plugins or two-way file sync use the Git relay / SSH below.'
1604
+ : '高级:大插件或双向文件同步用下面的 Git 中转 / SSH。' },
1605
+ { type: 'actions', items: [
1606
+ { label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
1607
+ { label: en ? 'Config template' : '生成配置模板', action: 'copy-config' },
1608
+ { label: en ? 'Back' : '返回同步', action: 'back' },
1609
+ ] },
1610
+ { type: 'actions', items: [
1611
+ { label: en ? 'Push relay' : '推送中转', action: 'relay-push' },
1612
+ { label: en ? 'Pull relay' : '拉取中转', action: 'relay-pull' },
1613
+ { label: en ? 'Scan SSH' : '拉远端清单', action: 'ssh-scan' },
1614
+ { label: en ? 'Test SSH' : '测试 SSH', action: 'ssh-test' },
1615
+ ] },
1616
+ ],
1617
+ }
1618
+ }
1619
+
1620
+ function stripValue(scope, en) {
1621
+ const task = readTaskStatus()
1622
+ if (task?.running) return { text: en ? 'Syncing…' : '同步中…', icon: 'refresh', tone: 'info' }
1623
+ if (task && task.ok === false) return { text: en ? `Sync failed: ${task.failed}` : `同步失败 ${task.failed} 项`, icon: 'warning', tone: 'bad' }
1624
+ const state = stateFor(scope)
1625
+ if (state.manifest) {
1626
+ const rows = diffRows(localPluginsCached(), state.manifest, state.manifestSource, { dshGo: true })
1627
+ const pending = rows.filter((row) => row.action).length
1628
+ if (pending > 0) return { text: en ? `Sync ${pending} left` : `待同步 ${pending} 项`, icon: 'refresh', tone: 'warn' }
1629
+ return { text: en ? 'Plugins in sync' : '插件已同步', icon: 'check', tone: 'good' }
1630
+ }
1631
+ return { text: en ? 'Plugin sync' : '插件同步', icon: 'refresh' }
1632
+ }
1633
+
1634
+ // ---------------------------------------------------------------- web ui
1635
+
1636
+ function webJson(res, status, value) {
1637
+ const body = JSON.stringify(value)
1638
+ res.writeHead(status, {
1639
+ 'content-type': 'application/json; charset=utf-8',
1640
+ 'cache-control': 'no-store',
1641
+ })
1642
+ res.end(body)
1643
+ }
1644
+
1645
+ function webReadBody(req, limit = 1024 * 1024) {
1646
+ return new Promise((resolve, reject) => {
1647
+ let total = 0
1648
+ const chunks = []
1649
+ req.on('data', (chunk) => {
1650
+ total += chunk.length
1651
+ if (total > limit) { reject(new Error('body too large')); req.destroy(); return }
1652
+ chunks.push(chunk)
1653
+ })
1654
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1655
+ req.on('error', reject)
1656
+ })
1657
+ }
1658
+
1659
+ function webSnapshot(ctx) {
1660
+ const scope = { sessionId: 'web-ui' }
1661
+ const state = stateFor(scope)
1662
+ const cfg = loadConfig(ctx, scope)
1663
+ refreshManifests(state, cfg)
1664
+ const local = localPlugins()
1665
+ const cleared = uiCleared()
1666
+ const rows = cleared
1667
+ ? []
1668
+ : diffRows(local, state.manifest, state.manifestSource, { dshGo: Boolean(ctx.get?.('dshGo')) })
1669
+ return {
1670
+ plugins: local.map((plugin) => ({
1671
+ name: plugin.name,
1672
+ version: plugin.version,
1673
+ title: plugin.title,
1674
+ installed: plugin.installed,
1675
+ localFiles: Boolean(plugin.relDir),
1676
+ })),
1677
+ selected: [...state.selected],
1678
+ manifest: state.manifest,
1679
+ rows: rows.map((row) => ({
1680
+ name: row.name,
1681
+ version: row.version,
1682
+ status: row.status,
1683
+ action: row.action || null,
1684
+ kind: row.kind || null,
1685
+ subtitle: statusLine(row, false),
1686
+ })),
1687
+ cleared,
1688
+ task: readTaskStatus(),
1689
+ results: readTaskResults(),
1690
+ log: readLogTail(3),
1691
+ config: cfg,
1692
+ configPath: configPathFor(ctx, scope),
1693
+ }
1694
+ }
1695
+
1696
+ /** Where the next saved config will live: an existing workspace file, else the store. */
1697
+ function configPathFor(ctx, scope) {
1698
+ const ws = writableDir(ctx, scope)
1699
+ if (ws) {
1700
+ const path = join(ws, CONFIG_FILE)
1701
+ if (existsSync(path)) return path
1702
+ }
1703
+ return join(storeDir(), CONFIG_FILE)
1704
+ }
1705
+
1706
+ // ---------------------------------------------------------------- plugin
1707
+
1708
+ export function apply(ctx) {
1709
+ ctx.inject(['dshGo'], (ctx) => {
1710
+ const copyConfig = (scope) => {
1711
+ const target = writableDir(ctx, scope) || storeDir()
1712
+ const path = join(target, CONFIG_FILE)
1713
+ try {
1714
+ ensureStore()
1715
+ mkdirSync(target, { recursive: true })
1716
+ if (!existsSync(path)) writeFileSync(path, configTemplate())
1717
+ } catch {
1718
+ return { toast: '写配置模板失败' }
1719
+ }
1720
+ return [{ toast: '已生成配置模板,改完刷新' }, { copy: path }, { refresh: true }]
1721
+ }
1722
+
1723
+ const copyCode = (scope) => {
1724
+ const all = localPlugins()
1725
+ const state = stateFor(scope)
1726
+ const chosen = state.selected.size > 0
1727
+ ? all.filter((plugin) => state.selected.has(plugin.name))
1728
+ : all
1729
+ const result = buildSyncCode(chosen)
1730
+ if (result.error === 'empty') return { toast: '除本插件外没有其他插件' }
1731
+ if (result.error) return { toast: '同步码太大,改用导出清单' }
1732
+ const label = state.selected.size > 0 ? '已复制选中' : '已复制全部'
1733
+ return [{ copy: result.code }, { toast: `${label} ${result.plugins} 个插件` }, { refresh: true }]
1734
+ }
1735
+
1736
+ const relayPush = (scope) => {
1737
+ const cfg = loadConfig(ctx, scope)
1738
+ if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
1739
+ const local = localPlugins()
1740
+ const pushable = local.filter((plugin) => safeDirName(plugin.relDir))
1741
+ if (pushable.length === 0) return { toast: '本机没有可推送的插件' }
1742
+ const manifest = buildManifest(local)
1743
+ try {
1744
+ ensureStore()
1745
+ writeFileSync(pushManifestFile(), JSON.stringify(manifest, null, 2) + '\n')
1746
+ } catch {
1747
+ return { toast: '写清单失败' }
1748
+ }
1749
+ const started = startTask('relay-push', buildRelayPush(cfg, pushable, pushManifestFile()))
1750
+ if (!started.ok) return { toast: started.error }
1751
+ return [{ toast: `已开始推送 ${pushable.length} 个插件` }, { refresh: true }]
1752
+ }
1753
+
1754
+ const relayPull = (scope) => {
1755
+ const cfg = loadConfig(ctx, scope)
1756
+ if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
1757
+ const state = stateFor(scope)
1758
+ state.relayLoadedAt = 0
1759
+ const started = startTask('relay-pull', buildRelayPull(cfg))
1760
+ if (!started.ok) return { toast: started.error }
1761
+ return [{ toast: '已开始拉取中转' }, { refresh: true }]
1762
+ }
1763
+
1764
+ const sshTest = (scope) => {
1765
+ const cfg = loadConfig(ctx, scope)
1766
+ if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
1767
+ const started = startTask('ssh-test', buildSshTest(cfg))
1768
+ if (!started.ok) return { toast: started.error }
1769
+ return [{ toast: '正在测试 SSH' }, { refresh: true }]
1770
+ }
1771
+
1772
+ const sshScan = (scope) => {
1773
+ const cfg = loadConfig(ctx, scope)
1774
+ if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
1775
+ const state = stateFor(scope)
1776
+ state.sshLoadedAt = 0
1777
+ const started = startTask('ssh-scan', buildSshScan(cfg))
1778
+ if (!started.ok) return { toast: started.error }
1779
+ return [{ toast: '正在拉远端清单' }, { refresh: true }]
1780
+ }
1781
+
1782
+ const retryFailed = (scope) => {
1783
+ const cfg = loadConfig(ctx, scope)
1784
+ const state = stateFor(scope)
1785
+ const failed = readTaskResults().filter((result) => !result.ok)
1786
+ if (failed.length === 0) return { toast: '没有失败项' }
1787
+ const names = new Set(failed.map((result) => result.name))
1788
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: true })
1789
+ const jobs = rows.filter((row) => names.has(row.name) && row.action)
1790
+ if (jobs.length === 0) return { toast: '失败项已不在列表' }
1791
+ if (jobs.some((row) => row.action === 'push' || row.action === 'push-npm' || row.action === 'pull') && !cfg.ssh.host) {
1792
+ return { toast: '先配置 ssh.host' }
1793
+ }
1794
+ const started = startApplyTask(ctx, cfg, jobs)
1795
+ if (!started.ok) return { toast: started.error }
1796
+ return [{ toast: `重试 ${jobs.length} 项` }, { refresh: true }]
1797
+ }
1798
+
1799
+ ctx.dshGo.panel('sync', {
1800
+ view(scope, caps) {
1801
+ try {
1802
+ return buildView(scope, caps, ctx)
1803
+ } catch (error) {
1804
+ return {
1805
+ type: 'stack',
1806
+ title: '插件同步',
1807
+ children: [{ type: 'text', text: `视图出错:${String(error?.message ?? error).slice(0, 100)}` }],
1808
+ }
1809
+ }
1810
+ },
1811
+
1812
+ data(scope, emit) {
1813
+ emit({ paste: { code: '' } })
1814
+ return () => {}
1815
+ },
1816
+
1817
+ actions: {
1818
+ 'copy-code': copyCode,
1819
+
1820
+ 'import-code'(scope, event) {
1821
+ const text = codeFromSubmit(event?.value)
1822
+ if (text === '') return { toast: '先粘贴同步码' }
1823
+ const result = applySyncCode(scope, text, '面板粘贴', { dshGo: true })
1824
+ if (result.error) return { toast: result.error }
1825
+ const toast = result.count === 0
1826
+ ? '已导入,没有插件'
1827
+ : `已导入 ${result.count} 个插件,选中 ${result.selected} 个`
1828
+ return [{ toast }, { patch: { paste: { code: '' } } }, { refresh: true }]
1829
+ },
1830
+
1831
+ export(scope) {
1832
+ const local = localPlugins()
1833
+ const manifest = buildManifest(local)
1834
+ const target = exportTarget(ctx, scope)
1835
+ try {
1836
+ ensureStore()
1837
+ mkdirSync(dirname(target), { recursive: true })
1838
+ writeFileSync(target, JSON.stringify(manifest, null, 2) + '\n')
1839
+ } catch {
1840
+ return { toast: '导出失败,检查工作区权限' }
1841
+ }
1842
+ const state = stateFor(scope)
1843
+ state.lastExportPath = target
1844
+ return [{ toast: '已导出插件清单' }, { copy: target }, { refresh: true }]
1845
+ },
1846
+
1847
+ 'import-workspace'(scope) {
1848
+ const candidates = []
1849
+ const dir = writableDir(ctx, scope)
1850
+ if (dir) candidates.push(join(dir, MANIFEST_FILE))
1851
+ candidates.push(exportTarget(ctx, scope), join(storeDir(), MANIFEST_FILE))
1852
+ for (const candidate of candidates) {
1853
+ if (!existsSync(candidate)) continue
1854
+ try {
1855
+ return importBuffer(scope, readFileSync(candidate), candidate, 'file')
1856
+ } catch {}
1857
+ }
1858
+ return { toast: `工作区没有 ${MANIFEST_FILE}` }
1859
+ },
1860
+
1861
+ toggle(scope, event) {
1862
+ const target = event?.value
1863
+ const name = typeof target === 'string' ? target : target?.name
1864
+ if (typeof name !== 'string') return { toast: '没有找到这一项' }
1865
+ const state = stateFor(scope)
1866
+ if (state.selected.has(name)) state.selected.delete(name)
1867
+ else state.selected.add(name)
1868
+ return { refresh: true }
1869
+ },
1870
+
1871
+ 'select-all'(scope) {
1872
+ const state = stateFor(scope)
1873
+ if (!state.manifest) {
1874
+ for (const plugin of localPlugins()) state.selected.add(plugin.name)
1875
+ return { refresh: true }
1876
+ }
1877
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: true })
1878
+ for (const row of rows) state.selected.add(row.name)
1879
+ return { refresh: true }
1880
+ },
1881
+
1882
+ clear(scope) {
1883
+ stateFor(scope).selected.clear()
1884
+ return { refresh: true }
1885
+ },
1886
+
1887
+ refresh() {
1888
+ return { refresh: true }
1889
+ },
1890
+
1891
+ 'copy-config'(scope) {
1892
+ return copyConfig(scope)
1893
+ },
1894
+
1895
+ 'relay-push': relayPush,
1896
+ 'relay-pull': relayPull,
1897
+ 'ssh-test': sshTest,
1898
+ 'ssh-scan': sshScan,
1899
+ 'retry-failed': retryFailed,
1900
+
1901
+ 'toggle-show-all'(scope) {
1902
+ const state = stateFor(scope)
1903
+ state.showAll = !state.showAll
1904
+ return { refresh: true }
1905
+ },
1906
+
1907
+ 'clear-all'(scope) {
1908
+ const state = stateFor(scope)
1909
+ state.manifest = null
1910
+ state.manifestSource = null
1911
+ state.sourceName = null
1912
+ state.importedAt = null
1913
+ state.selected.clear()
1914
+ try { unlinkSync(importFile()) } catch {}
1915
+ return [{ toast: '已清空清单,可重新导入同步码或拉取中转' }, { refresh: true }]
1916
+ },
1917
+
1918
+ guide() {
1919
+ return { open: 'panel:guide' }
1920
+ },
1921
+
1922
+ apply(scope, event) {
1923
+ if (event?.value?.confirmed !== true) return { toast: '已取消' }
1924
+ const cfg = loadConfig(ctx, scope)
1925
+ const state = stateFor(scope)
1926
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: true })
1927
+ const jobs = rows.filter((row) => state.selected.has(row.name) && row.action)
1928
+ if (jobs.length === 0) {
1929
+ return { toast: state.selected.size > 0 ? '选中的都已安装' : '没有可执行的项' }
1930
+ }
1931
+ if (jobs.some((job) => job.action === 'install' && !job.localDir && !job.registrySpec)) {
1932
+ return { toast: '有项找不到安装来源' }
1933
+ }
1934
+ if (jobs.some((job) => job.action === 'push' || job.action === 'push-npm' || job.action === 'pull') && !cfg.ssh.host) {
1935
+ return { toast: '推/拉远端要先配置 ssh.host' }
1936
+ }
1937
+ const started = startApplyTask(ctx, cfg, jobs)
1938
+ if (!started.ok) return { toast: started.error }
1939
+ state.selected.clear()
1940
+ return [{ toast: `已开始处理 ${jobs.length} 项` }, { refresh: true }]
1941
+ },
1942
+ },
1943
+ })
1944
+
1945
+ ctx.dshGo.panel('guide', {
1946
+ view(scope, caps) {
1947
+ try {
1948
+ return buildGuide(scope, caps, ctx)
1949
+ } catch {
1950
+ return { type: 'stack', title: '使用引导', children: [{ type: 'text', text: '引导加载失败' }] }
1951
+ }
1952
+ },
1953
+ actions: {
1954
+ 'copy-config'(scope) {
1955
+ return copyConfig(scope)
1956
+ },
1957
+ 'relay-push': relayPush,
1958
+ 'relay-pull': relayPull,
1959
+ 'ssh-test': sshTest,
1960
+ 'ssh-scan': sshScan,
1961
+ 'retry-failed': retryFailed,
1962
+ back() {
1963
+ return { open: 'panel:sync' }
1964
+ },
1965
+ },
1966
+ })
1967
+
1968
+ ctx.dshGo.strip('pending', (scope, emit, caps) => {
1969
+ const en = String(caps?.locale || '').toLowerCase().startsWith('en')
1970
+ const tick = () => {
1971
+ try { emit(stripValue(scope, en)) } catch {}
1972
+ }
1973
+ tick()
1974
+ const timer = setInterval(tick, 60_000)
1975
+ timer.unref?.()
1976
+ return () => clearInterval(timer)
1977
+ })
1978
+
1979
+ function importBuffer(scope, buffer, sourceName, kind) {
1980
+ let doc
1981
+ try {
1982
+ doc = JSON.parse(Buffer.isBuffer(buffer) ? buffer.toString('utf8') : String(buffer))
1983
+ } catch {
1984
+ return { toast: '文件不是合法 JSON' }
1985
+ }
1986
+ const manifest = validManifest(doc)
1987
+ if (!manifest) return { toast: '清单格式不对' }
1988
+ if (manifest.plugins.length === 0) return { toast: '清单里没有可同步插件' }
1989
+ const state = stateFor(scope)
1990
+ state.manifest = manifest
1991
+ state.manifestSource = { kind: kind || 'file' }
1992
+ state.importedAt = new Date().toISOString()
1993
+ state.sourceName = typeof sourceName === 'string' ? sourceName : null
1994
+ state.showAll = false
1995
+ state.selected.clear()
1996
+ persistImported(state)
1997
+ resetUiState()
1998
+ return [{ toast: `已导入 ${manifest.plugins.length} 个插件` }, { refresh: true }]
1999
+ }
2000
+ })
2001
+
2002
+ ctx.inject(['webServer'], (webCtx) => {
2003
+ const handler = async (req, res) => {
2004
+ try {
2005
+ let rejection
2006
+ try { rejection = ctx.connection?.requestRejection?.(req) } catch {}
2007
+ if (rejection !== undefined) { res.writeHead(rejection); res.end(); return }
2008
+ const url = new URL(req.url || '/', 'http://dsh.local')
2009
+ const path = url.pathname.replace(/\/+$/, '') || '/'
2010
+ if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/state') {
2011
+ webJson(res, 200, webSnapshot(ctx))
2012
+ return
2013
+ }
2014
+ if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/status') {
2015
+ webJson(res, 200, { task: readTaskStatus(), results: readTaskResults(), current: readTaskCurrent() })
2016
+ return
2017
+ }
2018
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/action') {
2019
+ const body = JSON.parse((await webReadBody(req)) || '{}')
2020
+ const action = typeof body.action === 'string' ? body.action : ''
2021
+ const scope = { sessionId: 'web-ui' }
2022
+ const cfg = loadConfig(ctx, scope)
2023
+ const state = stateFor(scope)
2024
+ if (action === 'clear') {
2025
+ clearUiState()
2026
+ webJson(res, 200, { ok: true })
2027
+ return
2028
+ }
2029
+ if (action === 'relay-pull') {
2030
+ if (!cfg.relay.repo) { webJson(res, 200, { error: '先配置中转仓' }); return }
2031
+ state.relayLoadedAt = 0
2032
+ resetUiState()
2033
+ const started = startTask('relay-pull', buildRelayPull(cfg))
2034
+ webJson(res, 200, started.ok ? { ok: true } : { error: started.error })
2035
+ return
2036
+ }
2037
+ if (action === 'relay-push') {
2038
+ if (!cfg.relay.repo) { webJson(res, 200, { error: '先配置中转仓' }); return }
2039
+ const local = localPlugins()
2040
+ const pushable = local.filter((plugin) => safeDirName(plugin.relDir))
2041
+ if (pushable.length === 0) { webJson(res, 200, { error: '本机没有可推送的插件' }); return }
2042
+ try {
2043
+ ensureStore()
2044
+ writeFileSync(pushManifestFile(), JSON.stringify(buildManifest(local), null, 2) + '\n')
2045
+ } catch {
2046
+ webJson(res, 200, { error: '写清单失败' })
2047
+ return
2048
+ }
2049
+ const started = startTask('relay-push', buildRelayPush(cfg, pushable, pushManifestFile()))
2050
+ webJson(res, 200, started.ok ? { ok: true, count: pushable.length } : { error: started.error })
2051
+ return
2052
+ }
2053
+ if (action === 'ssh-test') {
2054
+ if (!cfg.ssh.host) { webJson(res, 200, { error: '先配置 ssh.host' }); return }
2055
+ const started = startTask('ssh-test', buildSshTest(cfg))
2056
+ webJson(res, 200, started.ok ? { ok: true } : { error: started.error })
2057
+ return
2058
+ }
2059
+ if (action === 'ssh-scan') {
2060
+ if (!cfg.ssh.host) { webJson(res, 200, { error: '先配置 ssh.host' }); return }
2061
+ state.sshLoadedAt = 0
2062
+ resetUiState()
2063
+ const started = startTask('ssh-scan', buildSshScan(cfg))
2064
+ webJson(res, 200, started.ok ? { ok: true } : { error: started.error })
2065
+ return
2066
+ }
2067
+ webJson(res, 200, { error: '未知操作' })
2068
+ return
2069
+ }
2070
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/config') {
2071
+ const body = JSON.parse((await webReadBody(req)) || '{}')
2072
+ const next = normalizeConfig(body.config || {})
2073
+ const scope = { sessionId: 'web-ui' }
2074
+ const target = configPathFor(ctx, scope)
2075
+ try {
2076
+ ensureStore()
2077
+ mkdirSync(dirname(target), { recursive: true })
2078
+ writeFileSync(target, JSON.stringify(next, null, 2) + '\n')
2079
+ } catch {
2080
+ webJson(res, 200, { error: '保存配置失败' })
2081
+ return
2082
+ }
2083
+ webJson(res, 200, { ok: true, config: next, path: target })
2084
+ return
2085
+ }
2086
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/export') {
2087
+ const body = JSON.parse((await webReadBody(req)) || '{}')
2088
+ const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
2089
+ const all = localPlugins()
2090
+ const chosen = names.length > 0 ? all.filter((plugin) => names.includes(plugin.name)) : all
2091
+ const result = buildSyncCode(chosen)
2092
+ if (result.error === 'empty') { webJson(res, 200, { error: '没有可同步的插件' }); return }
2093
+ if (result.error) { webJson(res, 200, { error: '同步码太大,请减少插件或改用中转' }); return }
2094
+ webJson(res, 200, { code: result.code, count: result.plugins, withFiles: result.withFiles })
2095
+ return
2096
+ }
2097
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/import') {
2098
+ const body = JSON.parse((await webReadBody(req)) || '{}')
2099
+ const code = typeof body.code === 'string' ? body.code : ''
2100
+ const result = applySyncCode({ sessionId: 'web-ui' }, code, '网页版', { dshGo: Boolean(ctx.get?.('dshGo')) })
2101
+ if (result.error) { webJson(res, 200, { error: result.error }); return }
2102
+ webJson(res, 200, { ok: true, count: result.count, selected: result.selected })
2103
+ return
2104
+ }
2105
+ if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/apply') {
2106
+ const body = JSON.parse((await webReadBody(req)) || '{}')
2107
+ const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
2108
+ const scope = { sessionId: 'web-ui' }
2109
+ const cfg = loadConfig(ctx, scope)
2110
+ const state = stateFor(scope)
2111
+ const rows = diffRows(localPlugins(), state.manifest, state.manifestSource, { dshGo: Boolean(ctx.get?.('dshGo')) })
2112
+ const jobs = rows.filter((row) => names.includes(row.name) && row.action)
2113
+ if (jobs.length === 0) { webJson(res, 200, { error: '没有可安装的项' }); return }
2114
+ if (jobs.some((job) => job.action === 'push' || job.action === 'push-npm' || job.action === 'pull') && !cfg.ssh.host) {
2115
+ webJson(res, 200, { error: '先配置 ssh.host' }); return
2116
+ }
2117
+ const started = startApplyTask(ctx, cfg, jobs)
2118
+ if (!started.ok) { webJson(res, 200, { error: started.error }); return }
2119
+ state.selected.clear()
2120
+ webJson(res, 200, { ok: true, count: jobs.length })
2121
+ return
2122
+ }
2123
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
2124
+ res.end('not found')
2125
+ } catch (error) {
2126
+ try { webJson(res, 500, { error: String(error?.message || error) }) } catch {}
2127
+ }
2128
+ }
2129
+ ctx.effect(() => webCtx.webServer.register({ kind: 'prefix', path: '/dsh-go-plugin-sync', handler }), 'dsh-go-plugin-sync: web ui')
2130
+ try {
2131
+ const ws = webCtx.webServer
2132
+ const host = String(ws.host || '127.0.0.1')
2133
+ const shown = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host
2134
+ const bracketed = shown.includes(':') ? `[${shown}]` : shown
2135
+ console.log(`[dsh-go-plugin-sync] 设置页 API:${ws.protocol || 'http:'}//${bracketed}:${ws.port}/dsh-go-plugin-sync/api/`)
2136
+ } catch {}
2137
+ })
2138
+ }