dsh-go-plugin-sync 0.3.4 → 0.3.6

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