@dsh-plugin/dsh-pack-plugin 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +178 -3
  3. package/cordis.patch.yml +9 -0
  4. package/icons/folder-zip-line.svg +1 -0
  5. package/lib/ball.js +597 -0
  6. package/lib/client.js +2934 -0
  7. package/lib/host.js +51745 -0
  8. package/lib/migrate-helper.js +35346 -0
  9. package/lib/progress-main.cjs +79 -0
  10. package/lib/progress-window.ps1 +114 -0
  11. package/lib/progress.html +126 -0
  12. package/lib/publish-to-github/SKILL.md +132 -0
  13. package/package.json +77 -4
  14. package/src/ball-entry.js +5 -0
  15. package/src/ball-host.js +99 -0
  16. package/src/ball-settings.js +352 -0
  17. package/src/ball.js +418 -0
  18. package/src/channel.js +12 -0
  19. package/src/client-plugin.js +58 -0
  20. package/src/client-rpc.js +14 -0
  21. package/src/client.js +5 -0
  22. package/src/core/discovery.js +192 -0
  23. package/src/core/dspack.js +93 -0
  24. package/src/core/extension-files.js +102 -0
  25. package/src/core/extension-install.js +295 -0
  26. package/src/core/extension-patch.js +369 -0
  27. package/src/core/extension-skills.js +164 -0
  28. package/src/core/extension-validate.js +127 -0
  29. package/src/core/extensions.js +207 -0
  30. package/src/core/home-store.js +32 -0
  31. package/src/core/host.js +149 -0
  32. package/src/core/index.js +59 -0
  33. package/src/core/inspect.js +162 -0
  34. package/src/core/install.js +775 -0
  35. package/src/core/managed-install.js +84 -0
  36. package/src/core/manifest.js +717 -0
  37. package/src/core/market.js +268 -0
  38. package/src/core/mcp-composition.js +189 -0
  39. package/src/core/mcp-install.js +112 -0
  40. package/src/core/mcp-transport.js +116 -0
  41. package/src/core/pack.js +371 -0
  42. package/src/core/plugin-metadata.js +355 -0
  43. package/src/core/registry.js +316 -0
  44. package/src/core/repo.js +339 -0
  45. package/src/core/scan.js +78 -0
  46. package/src/core/security.js +101 -0
  47. package/src/core/special.js +50 -0
  48. package/src/core/tar.js +103 -0
  49. package/src/core/update-config.js +234 -0
  50. package/src/core/update.js +792 -0
  51. package/src/core/vendored.js +715 -0
  52. package/src/core/workspace.js +95 -0
  53. package/src/endpoints.js +455 -0
  54. package/src/ensure-manager.js +186 -0
  55. package/src/host-node.js +625 -0
  56. package/src/host.js +17 -0
  57. package/src/index.d.ts +7 -0
  58. package/src/index.js +39 -0
  59. package/src/junction.js +142 -0
  60. package/src/migrate-helper.js +225 -0
  61. package/src/migrate.js +56 -0
  62. package/src/packaged.js +9 -0
  63. package/src/profiles.js +106 -0
  64. package/src/progress-main.cjs +79 -0
  65. package/src/progress-window.ps1 +114 -0
  66. package/src/progress.html +126 -0
  67. package/src/progress.js +132 -0
  68. package/src/rpc.js +157 -0
  69. package/src/runtime.js +43 -0
  70. package/src/section-gate.js +50 -0
  71. package/src/settings-nav-icon.js +188 -0
  72. package/src/settings.js +1611 -0
  73. package/src/skills/index.js +90 -0
  74. package/src/skills/publish-to-github/SKILL.md +132 -0
  75. package/src/tasks.js +145 -0
  76. package/src/v6-dialogs.js +312 -0
@@ -0,0 +1,625 @@
1
+ // Node 宿主:实现 src/core 的 Host 契约(以 node:fs 等内建能力注入)。
2
+ // 供 CLI / Electron / server 使用。
3
+ import fs from 'node:fs';
4
+ import fsp from 'node:fs/promises';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import crypto from 'node:crypto';
8
+ import http from 'node:http';
9
+ import https from 'node:https';
10
+ import { applyEntryPatches } from '@deepseek-ai/cordis-plugin-include';
11
+ import { execFile, spawn, spawnSync } from 'node:child_process';
12
+ import { ProxyAgent } from 'proxy-agent';
13
+ import { getProxyForUrl } from 'proxy-from-env';
14
+
15
+ // 下载超时策略:连接/响应头阶段 30s 无数据即判死;响应体阶段放宽到 5 分钟(慢速但持续有数据不误杀)。
16
+ const DOWNLOAD_CONNECT_MS = 30_000;
17
+ const DOWNLOAD_STALL_MS = 300_000;
18
+ const DOWNLOAD_MAX_RETRIES = 2; // 瞬时失败(超时/断连)额外重试次数,共最多 3 次
19
+ const DOWNLOAD_RETRY_BACKOFF_MS = 800;
20
+
21
+ /**
22
+ * 解析 DSH 自带 pnpm 运行时的入口(`pnpm.mjs`)——桌面端把 node+pnpm 一起打包进
23
+ * `resources/runtime/`,用它跑 `pnpm install` 即可不依赖用户机器 PATH 上的 node/pnpm。
24
+ * 优先级:显式 env 覆盖(DSH 自身也认这个)> Electron `resourcesPath` 标准布局;均无 → null(回退 PATH)。
25
+ * 纯函数,便于脱离 Electron 单测。
26
+ * @param {{ env?: object, resourcesPath?: string }} [ctx]
27
+ * @returns {string|null}
28
+ */
29
+ export function resolvePnpmEntry({ env = process.env, resourcesPath = process.resourcesPath } = {}) {
30
+ const override = env?.DSH_DESKTOP_PNPM_ENTRY;
31
+ if (typeof override === 'string' && override.trim()) return override.trim();
32
+ if (typeof resourcesPath === 'string' && resourcesPath) {
33
+ return path.join(resourcesPath, 'runtime', 'pnpm', 'bin', 'pnpm.mjs');
34
+ }
35
+ return null;
36
+ }
37
+
38
+ export class NodeHost {
39
+ #rootCAs;
40
+ #proxyUrl = null; // 显式配置的代理(设置项,覆盖环境变量);null = 未配置
41
+ #direct = false; // 强制直连(设置项 'direct'),跳过环境变量与系统代理
42
+ #proxyAgent = null; // 缓存的 ProxyAgent(记录其 proxy URL,变更即重建)
43
+ #sysProxy = undefined; // Windows 系统代理缓存(undefined=未探测 / null=无 / {http,https,...}=有)
44
+
45
+ joinPath(...parts) {
46
+ return path.join(...parts);
47
+ }
48
+
49
+ /** 以随本工具分发的 Cordis 实现组合独立的补丁副本。 */
50
+ composePackEntries(patches) {
51
+ const result = applyEntryPatches([], patches, () => {});
52
+ return Array.isArray(result) ? result : result.data;
53
+ }
54
+
55
+ resolvePath(...parts) {
56
+ return path.resolve(...parts);
57
+ }
58
+
59
+ cwd() {
60
+ return process.cwd();
61
+ }
62
+
63
+ homedir() {
64
+ return os.homedir();
65
+ }
66
+
67
+ env(name) {
68
+ return process.env[name] ?? null;
69
+ }
70
+
71
+ basename(abs) {
72
+ return path.basename(abs);
73
+ }
74
+
75
+ async readTextFile(abs) {
76
+ try {
77
+ return await fsp.readFile(abs, 'utf8');
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ async writeTextFile(abs, text) {
84
+ await fsp.mkdir(path.dirname(abs), { recursive: true });
85
+ await fsp.writeFile(abs, text, 'utf8'); // 无 BOM
86
+ }
87
+
88
+ async readFile(abs) {
89
+ try {
90
+ return new Uint8Array(await fsp.readFile(abs));
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ async writeFile(abs, data) {
97
+ await fsp.mkdir(path.dirname(abs), { recursive: true });
98
+ await fsp.writeFile(abs, data);
99
+ }
100
+
101
+ async stat(abs) {
102
+ try {
103
+ const s = await fsp.stat(abs);
104
+ return {
105
+ size: s.size,
106
+ isFile: s.isFile(),
107
+ isDirectory: s.isDirectory(),
108
+ isSymbolicLink: s.isSymbolicLink(),
109
+ };
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ async readdir(abs) {
116
+ try {
117
+ const entries = await fsp.readdir(abs, { withFileTypes: true });
118
+ return entries.map((e) => ({
119
+ name: e.name,
120
+ abs: path.join(abs, e.name),
121
+ type: e.isSymbolicLink() ? 'symlink' : e.isDirectory() ? 'dir' : e.isFile() ? 'file' : 'other',
122
+ }));
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ async mkdir(abs) {
129
+ await fsp.mkdir(abs, { recursive: true });
130
+ }
131
+
132
+ async rm(abs, opts = {}) {
133
+ await fsp.rm(abs, { recursive: opts.recursive !== false, force: opts.force !== false });
134
+ }
135
+
136
+ async mkdtemp(prefix) {
137
+ return await fsp.mkdtemp(path.join(os.tmpdir(), prefix));
138
+ }
139
+
140
+ async sha256(data) {
141
+ return crypto.createHash('sha256').update(data).digest('hex');
142
+ }
143
+
144
+ async sha256File(abs) {
145
+ try {
146
+ return await new Promise((resolve, reject) => {
147
+ const hash = crypto.createHash('sha256');
148
+ const stream = fs.createReadStream(abs);
149
+ stream.on('data', (chunk) => hash.update(chunk));
150
+ stream.on('end', () => resolve(hash.digest('hex')));
151
+ stream.on('error', reject);
152
+ });
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+
158
+ async writeCredentialStore(dest, text) {
159
+ await fsp.mkdir(path.dirname(dest), {recursive:true});
160
+ let file, created = false;
161
+ try {
162
+ file = await fsp.open(dest, 'wx+', 0o600);
163
+ created = true;
164
+ } catch (error) {
165
+ if (error.code !== 'EEXIST') throw error;
166
+ file = await fsp.open(dest, 'r+');
167
+ }
168
+ try {
169
+ if (process.platform !== 'win32') await file.chmod(0o600);
170
+ else if (created) {
171
+ const current = spawnSync('whoami.exe', ['/user','/fo','csv','/nh'], {encoding:'utf8',windowsHide:true,timeout:5000});
172
+ const sid = current.stdout?.match(/S-1-(?:\d+-)+\d+/i)?.[0];
173
+ const acl = sid && spawnSync('icacls.exe', [dest,'/inheritance:r','/grant:r','*'+sid+':F'], {windowsHide:true,timeout:5000});
174
+ if (!acl || acl.status !== 0) throw new Error('无法限制凭据文件的 Windows 访问权限');
175
+ }
176
+ await file.truncate(0);
177
+ await file.writeFile(text, 'utf8');
178
+ } finally { await file.close(); }
179
+ }
180
+
181
+ async git(args, { cwd } = {}) {
182
+ return new Promise((resolve) => {
183
+ execFile('git', args, {
184
+ cwd, windowsHide: true, timeout: 120000, maxBuffer: 1024 * 1024,
185
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ALLOW_PROTOCOL: 'https:ssh' },
186
+ }, (error, stdout) => resolve({ status: error ? 1 : 0, stdout: String(stdout).trim() }));
187
+ });
188
+ }
189
+
190
+ async exec(cmd, args, opts = {}) {
191
+ // 用异步 spawn(而非 spawnSync):避免在 Electron 主进程同步阻塞导致界面卡死;
192
+ // stdin 置 ignore 防止 pnpm/git 在无人输入时卡在交互提示;可选 timeoutMs 兜底防永久卡住。
193
+ // 传 opts.onOutput(chunk) 时 stdout/stderr 改 pipe 并逐块回调(任务中心日志),否则 inherit 直通终端。
194
+ return await this.#spawnRun(cmd, args, {
195
+ cwd: opts.cwd,
196
+ timeoutMs: opts.timeoutMs,
197
+ onOutput: opts.onOutput,
198
+ shell: process.platform === 'win32',
199
+ });
200
+ }
201
+
202
+ /**
203
+ * 运行 pnpm。桌面端自带 node+pnpm 运行时(`resources/runtime/`),复用它可以不依赖用户
204
+ * 机器 PATH 上的 node/pnpm;找不到自带运行时(CLI / 测试 / 旧版 DSH)则回退 PATH 上的 pnpm。
205
+ * 返回与 exec 相同的 `{ status, error? }`。
206
+ */
207
+ async pnpm(args, opts = {}) {
208
+ // 显式代理/'direct' 对两条路径一致生效:先构造一次带代理的基准 env,再各自补充。
209
+ const baseEnv = { ...process.env };
210
+ this.#applyProxyEnv(baseEnv);
211
+ // 安装日志里写清「用了哪一级」:环境变量指定入口 / DSH 自带运行时 / PATH 回退。
212
+ const emit = (s) => { if (typeof opts.onOutput === 'function') opts.onOutput(String(s) + '\n'); };
213
+ const runPathPnpm = () => this.#spawnRun('pnpm', args, {
214
+ cwd: opts.cwd,
215
+ timeoutMs: opts.timeoutMs,
216
+ onOutput: opts.onOutput,
217
+ env: baseEnv,
218
+ shell: process.platform === 'win32',
219
+ });
220
+
221
+ const entry = resolvePnpmEntry();
222
+ const overridden = typeof process.env.DSH_DESKTOP_PNPM_ENTRY === 'string' && process.env.DSH_DESKTOP_PNPM_ENTRY.trim() !== '';
223
+ if (entry && fs.existsSync(entry)) {
224
+ emit(overridden ? '使用 pnpm:DSH_DESKTOP_PNPM_ENTRY 指定入口' : '使用 DSH 自带 pnpm 运行时');
225
+ // process.execPath 即桌面端可执行文件(electron),加 ELECTRON_RUN_AS_NODE=1 让其以纯 node
226
+ // 模式跑 pnpm.mjs——与 DSH 自身 node.cmd 的做法一致;非 Electron(node 直跑)时该变量无害。
227
+ const env = { ...baseEnv, ELECTRON_RUN_AS_NODE: '1' };
228
+ const r = await this.#spawnRun(process.execPath, [entry, ...(args ?? [])], {
229
+ cwd: opts.cwd,
230
+ timeoutMs: opts.timeoutMs,
231
+ onOutput: opts.onOutput,
232
+ env,
233
+ });
234
+ // 降级:自带运行时「根本没启动起来」(spawn 失败/被替换,status 为 null)才回退 PATH;
235
+ // 超时或 pnpm 已运行但退出码非 0(真实安装失败)则不回退,避免换版本重跑造成二次报错/翻倍等待。
236
+ if (r.status === null && !r.timedOut) {
237
+ emit('自带运行时启动失败,回退 PATH pnpm');
238
+ return await runPathPnpm();
239
+ }
240
+ return r;
241
+ }
242
+ emit('使用 PATH 上的 pnpm');
243
+ return await runPathPnpm();
244
+ }
245
+
246
+ /** 把显式代理配置透传给子进程(pnpm 原生认 HTTP(S)_PROXY)。'direct' 清除代理变量强制直连;
247
+ * 有显式代理地址则覆盖;两者皆无则保留继承的环境变量。 */
248
+ #applyProxyEnv(env) {
249
+ const keys = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'];
250
+ if (this.#direct) {
251
+ for (const k of keys) delete env[k];
252
+ return;
253
+ }
254
+ if (!this.#proxyUrl) return;
255
+ for (const k of keys) env[k] = this.#proxyUrl;
256
+ }
257
+
258
+ /** 共享的 spawn + 流式输出 + 超时杀进程树实现(exec / pnpm 复用)。 */
259
+ #spawnRun(cmd, args, opts = {}) {
260
+ return new Promise((resolve) => {
261
+ const capture = typeof opts.onOutput === 'function';
262
+ let child;
263
+ try {
264
+ child = spawn(cmd, args, {
265
+ cwd: opts.cwd,
266
+ stdio: ['ignore', capture ? 'pipe' : 'inherit', capture ? 'pipe' : 'inherit'],
267
+ shell: opts.shell === true,
268
+ env: opts.env ?? process.env,
269
+ windowsHide: true,
270
+ });
271
+ } catch (err) {
272
+ return resolve({ status: null, error: err.message });
273
+ }
274
+
275
+ if (capture) {
276
+ const onData = (chunk) => opts.onOutput(String(chunk));
277
+ child.stdout.on('data', onData);
278
+ child.stderr.on('data', onData);
279
+ }
280
+
281
+ let settled = false;
282
+ let timer = null;
283
+ let timedOut = false;
284
+ const finish = (status, error) => {
285
+ if (settled) return;
286
+ settled = true;
287
+ if (timer) clearTimeout(timer);
288
+ resolve({ status, error, timedOut });
289
+ };
290
+
291
+ if (opts.timeoutMs > 0) {
292
+ timer = setTimeout(() => {
293
+ timedOut = true;
294
+ // 结束整个进程树:Windows 下 shell:true 时 child 是 cmd.exe,需 taskkill /T
295
+ if (child.pid) {
296
+ if (process.platform === 'win32') {
297
+ try { spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true }); } catch { /* 忽略 */ }
298
+ } else {
299
+ try { process.kill(child.pid, 'SIGTERM'); } catch { /* 忽略 */ }
300
+ }
301
+ }
302
+ finish(null, `命令超时(${opts.timeoutMs}ms):${cmd} ${(args ?? []).join(' ')}`);
303
+ }, opts.timeoutMs);
304
+ }
305
+
306
+ child.on('error', (err) => finish(null, err.message));
307
+ child.on('close', (code) => finish(code ?? 0, undefined));
308
+ });
309
+ }
310
+
311
+ /** 显式设置代理(设置项,最高优先级)。`'direct'` 强制直连;空值清除、回落环境变量/系统代理;否则为代理地址。 */
312
+ setProxy(url) {
313
+ const u = typeof url === 'string' ? url.trim() : '';
314
+ this.#direct = u === 'direct';
315
+ this.#proxyUrl = u && u !== 'direct' ? u : null;
316
+ this.#proxyAgent = null; // 失效缓存
317
+ }
318
+
319
+ /** 描述当前对某 URL 的代理决策(供安装日志展示)。默认以 pnpm 必访问的 registry 为探测目标。 */
320
+ proxyStatus(target = 'https://registry.npmjs.org/') {
321
+ if (this.#direct) return { kind: 'direct', url: null };
322
+ if (this.#proxyUrl) return { kind: 'manual', url: this.#proxyUrl };
323
+ let u;
324
+ try { u = new URL(target); } catch { return { kind: 'auto-direct', url: null }; }
325
+ const envProxy = getProxyForUrl(u);
326
+ if (envProxy) return { kind: 'auto-env', url: envProxy };
327
+ const sys = this.#sysProxyFor(u);
328
+ if (sys) return { kind: 'auto-system', url: sys };
329
+ return { kind: 'auto-direct', url: null };
330
+ }
331
+
332
+ async download(url, destAbs, { headers = {}, redirectHeaders } = {}) {
333
+ let lastErr = null;
334
+ for (let attempt = 0; attempt <= DOWNLOAD_MAX_RETRIES; attempt += 1) {
335
+ try {
336
+ await this.#downloadOnce(url, destAbs, null, headers, redirectHeaders);
337
+ return;
338
+ } catch (e) {
339
+ lastErr = e;
340
+ }
341
+ // Windows 上部分站点(如 github.com)的证书链只认系统根 CA,Node bundled CA 认不到时
342
+ // 自动加载系统根 CA 重试一次(信任系统信任存储,而非禁用校验)。
343
+ if (this.#isCertError(lastErr)) {
344
+ const cas = await this.#systemRootCAs();
345
+ if (cas && cas.length) {
346
+ try {
347
+ await this.#downloadOnce(url, destAbs, cas, headers, redirectHeaders);
348
+ return;
349
+ } catch (e2) {
350
+ lastErr = e2;
351
+ }
352
+ }
353
+ }
354
+ // 瞬时失败(超时 / 断连)退避后重试;非瞬时(4xx / 证书 / 无效地址)直接抛。
355
+ if (attempt < DOWNLOAD_MAX_RETRIES && this.#isRetryable(lastErr)) {
356
+ this.#sysProxy = undefined; // 重试时重新探测系统代理(用户可能刚开关代理)
357
+ await new Promise((r) => setTimeout(r, DOWNLOAD_RETRY_BACKOFF_MS * (attempt + 1)));
358
+ continue;
359
+ }
360
+ throw lastErr;
361
+ }
362
+ throw lastErr;
363
+ }
364
+
365
+ /** 解析目标 URL 应走的代理 agent:显式配置 > 环境变量(含 NO_PROXY)> Windows 系统代理;均无 → null(直连)。
366
+ * proxy-agent v8 的 ProxyAgent 不再接受 URL 字符串入参,需用 getProxyForUrl 回调固定返回代理地址。 */
367
+ #agentFor(url) {
368
+ if (this.#direct) return null; // 强制直连
369
+ const proxy = this.#proxyUrl || getProxyForUrl(url) || this.#sysProxyFor(url) || null;
370
+ if (!proxy) return null;
371
+ if (!this.#proxyAgent || this.#proxyAgent.url !== proxy) {
372
+ this.#proxyAgent = { url: proxy, agent: new ProxyAgent({ getProxyForUrl: () => proxy }) };
373
+ }
374
+ return this.#proxyAgent.agent;
375
+ }
376
+
377
+ /** 取 Windows 系统代理中适用于该 URL 协议的地址(http 代理可经 CONNECT 透传 https,故 https 回落 http)。
378
+ * 命中 ProxyOverride 旁路列表或回环地址时返回 null(直连)。 */
379
+ #sysProxyFor(url) {
380
+ const s = this.#windowsSystemProxy();
381
+ if (!s || this.#sysProxyBypasses(s.bypass, url)) return null;
382
+ const proto = url.protocol === 'https:' ? 'https' : 'http';
383
+ return s.map[proto] || s.map.http || s.map.socks5 || s.map.socks || null;
384
+ }
385
+
386
+ /** 读 Windows 系统代理(WinINET 注册表 HKCU\...\Internet Settings),返回 { map, bypass } 或 null;缓存一次。 */
387
+ #windowsSystemProxy() {
388
+ if (this.#sysProxy !== undefined) return this.#sysProxy;
389
+ this.#sysProxy = null;
390
+ if (process.platform !== 'win32') return this.#sysProxy;
391
+ try {
392
+ const r = spawnSync('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'], {
393
+ encoding: 'utf8', timeout: 5000, windowsHide: true,
394
+ });
395
+ const out = String(r.stdout ?? '');
396
+ const en = /ProxyEnable\s+REG_DWORD\s+0x([0-9a-fA-F]+)/i.exec(out);
397
+ if (!en || parseInt(en[1], 16) === 0) return this.#sysProxy; // 未启用系统代理
398
+ const sv = /ProxyServer\s+REG_SZ\s+(.+)/i.exec(out);
399
+ if (!sv) return this.#sysProxy;
400
+ const raw = sv[1].trim();
401
+ if (!raw) return this.#sysProxy;
402
+ const map = this.#parseWinProxy(raw);
403
+ if (!map) return this.#sysProxy;
404
+ const ov = /ProxyOverride\s+REG_SZ\s+(.+)/i.exec(out);
405
+ this.#sysProxy = { map, bypass: ov ? ov[1].trim() : '' };
406
+ } catch {
407
+ this.#sysProxy = null;
408
+ }
409
+ return this.#sysProxy;
410
+ }
411
+
412
+ /** ProxyOverride 旁路匹配:回环地址恒直连;`<local>` 匹配无点主机名;其余按精确或 `*` 通配匹配。 */
413
+ #sysProxyBypasses(bypass, url) {
414
+ const h = (url.hostname ?? '').toLowerCase();
415
+ if (h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]') return true;
416
+ if (!bypass) return false;
417
+ for (const raw of String(bypass).split(';')) {
418
+ const it = raw.trim().toLowerCase();
419
+ if (!it) continue;
420
+ if (it === '<local>') { if (!h.includes('.')) return true; continue; }
421
+ if (it.includes('*')) {
422
+ const re = new RegExp('^' + it.split('*').map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$');
423
+ if (re.test(h)) return true;
424
+ } else if (it === h) {
425
+ return true;
426
+ }
427
+ }
428
+ return false;
429
+ }
430
+
431
+ /** 解析 ProxyServer:单条裸 host:port(所有协议共用)或 proto=host:port 分号列表(各协议各自取)。 */
432
+ #parseWinProxy(raw) {
433
+ const map = {};
434
+ for (const part of String(raw).split(';')) {
435
+ const seg = part.trim();
436
+ if (!seg) continue;
437
+ const eq = seg.indexOf('=');
438
+ const proto = eq >= 0 ? seg.slice(0, eq).trim().toLowerCase() : 'http';
439
+ const addr = (eq >= 0 ? seg.slice(eq + 1) : seg).trim();
440
+ if (!addr) continue;
441
+ map[proto] = /^[a-z0-9]+:\/\//i.test(addr) ? addr : `${proto}://${addr}`;
442
+ }
443
+ return Object.keys(map).length ? map : null;
444
+ }
445
+
446
+ async #downloadOnce(url, destAbs, extraCa, headers, redirectHeaders, redirects = 0) {
447
+ await new Promise((resolve, reject) => {
448
+ let u;
449
+ try {
450
+ u = new URL(url);
451
+ } catch {
452
+ return reject(new Error(`无效的下载地址`));
453
+ }
454
+ const lib = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
455
+ if (!lib) return reject(new Error(`仅支持 HTTP 或 HTTPS`));
456
+ const options = { headers: { ...headers, 'user-agent': 'dspack/0.3.0' } };
457
+ if (extraCa) options.ca = extraCa;
458
+ const agent = this.#agentFor(u);
459
+ if (agent) options.agent = agent;
460
+
461
+ let settled = false;
462
+ let phase = 'connect'; // 'connect':连接 + 等响应头;'body':响应体流式下载
463
+ const fail = (err) => { if (!settled) { settled = true; reject(err); } };
464
+
465
+ const req = lib.get(url, options, (res) => {
466
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
467
+ res.resume();
468
+ // 跟随重定向:每一跳独立重新走(各自超时 / 重试由 download 兜底)。
469
+ if (redirects >= 8) return reject(new Error('下载重定向次数超限'));
470
+ let next;
471
+ try { next = new URL(res.headers.location, u); } catch { return reject(new Error('下载重定向地址无效')); }
472
+ if (next.username || next.password) return reject(new Error('下载地址不得包含凭据'));
473
+ const sameOrigin = next.origin === u.origin;
474
+ const authorize = sameOrigin ? redirectHeaders : undefined;
475
+ const nextHeaders = authorize ? authorize(next.href) : sameOrigin && next.pathname === u.pathname ? headers : {};
476
+ return resolve(Promise.resolve(nextHeaders).then(scoped =>
477
+ this.#downloadOnce(next.href, destAbs, extraCa, scoped, authorize, redirects + 1),
478
+ ));
479
+ }
480
+ if (res.statusCode !== 200) {
481
+ res.resume();
482
+ return fail(new Error(`下载失败:HTTP ${res.statusCode}`));
483
+ }
484
+ // 响应头已到:把「连接/响应头」超时放宽为「停滞」超时,慢速但活跃的大文件不误杀。
485
+ phase = 'body';
486
+ req.setTimeout(DOWNLOAD_STALL_MS);
487
+ const out = fs.createWriteStream(destAbs);
488
+ res.on('error', fail); // req.destroy 中断响应体时,避免 res 抛未处理的 'error'
489
+ res.pipe(out);
490
+ out.on('finish', () => out.close(() => { if (!settled) { settled = true; resolve(); } }));
491
+ out.on('error', fail);
492
+ });
493
+
494
+ const onTimeout = () => {
495
+ const msg = phase === 'connect'
496
+ ? `连接超时(${DOWNLOAD_CONNECT_MS / 1000}s 无响应):${u.origin}`
497
+ : `下载停滞(${DOWNLOAD_STALL_MS / 1000}s 无数据):${u.origin}`;
498
+ req.destroy(new Error(msg));
499
+ };
500
+ req.on('timeout', onTimeout);
501
+ req.on('error', fail);
502
+ req.setTimeout(DOWNLOAD_CONNECT_MS);
503
+ });
504
+ }
505
+
506
+ #isCertError(e) {
507
+ const m = String(e?.code ?? '') + ' ' + String(e?.message ?? '');
508
+ return /UNABLE_TO_VERIFY|SELF_SIGNED|CERT_HAS_EXPIRED|UNABLE_TO_GET_ISSUER|verify the first certificate|ERR_TLS_CERT/i.test(m);
509
+ }
510
+
511
+ /** 瞬时网络失败(超时 / 断连 / 解析失败)可重试;4xx/证书错不重试。 */
512
+ #isRetryable(e) {
513
+ const m = String(e?.code ?? '') + ' ' + String(e?.message ?? '');
514
+ return /ETIMEDOUT|ESOCKETTIMEDOUT|ECONNRESET|ECONNREFUSED|EPIPE|ENOTFOUND|socket hang up|超时|停滞/i.test(m);
515
+ }
516
+
517
+ async #systemRootCAs() {
518
+ if (this.#rootCAs !== undefined) return this.#rootCAs;
519
+ this.#rootCAs = null;
520
+ if (process.platform !== 'win32') return this.#rootCAs;
521
+ try {
522
+ const script = "[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-ChildItem Cert:\\LocalMachine\\Root, Cert:\\CurrentUser\\Root | ForEach-Object { '-----BEGIN CERTIFICATE-----'; [System.Convert]::ToBase64String($_.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert), 'InsertLineBreaks'); '-----END CERTIFICATE-----' }";
523
+ const r = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
524
+ encoding: 'utf8', timeout: 15000, windowsHide: true, maxBuffer: 16 * 1024 * 1024,
525
+ });
526
+ const cas = [...String(r.stdout ?? '').matchAll(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)].map((m) => m[0]);
527
+ if (cas.length) this.#rootCAs = cas;
528
+ } catch {
529
+ this.#rootCAs = null;
530
+ }
531
+ return this.#rootCAs;
532
+ }
533
+
534
+ /** 竞争者分别登记进程和随机标识,崩溃遗留的登记由下一次操作清理。 */
535
+ async withPackLock(directory, action) {
536
+ const locks = path.join(directory, 'locks');
537
+ await fsp.mkdir(locks, { recursive: true, mode: 0o700 });
538
+ const id = String(process.pid) + '-' + crypto.randomUUID();
539
+ const claim = path.join(locks, id);
540
+ await fsp.writeFile(claim, '', { flag: 'wx', mode: 0o600 });
541
+ try {
542
+ for (const peer of await fsp.readdir(locks)) {
543
+ if (peer === id) {
544
+ continue;
545
+ }
546
+ const match = /^([1-9][0-9]*)-[\da-f-]{36}$/.exec(peer);
547
+ if (!match) {
548
+ throw new Error('更新锁目录中存在无法识别的记录');
549
+ }
550
+ try {
551
+ process.kill(Number(match[1]), 0);
552
+ } catch (error) {
553
+ if (error.code === 'ESRCH') {
554
+ await fsp.rm(path.join(locks, peer), { force: true });
555
+ continue;
556
+ }
557
+ if (error.code !== 'EPERM') {
558
+ throw error;
559
+ }
560
+ }
561
+ throw new Error('另一项整合包操作正在使用此 DSH_HOME,请稍后重试');
562
+ }
563
+ return await action();
564
+ } finally {
565
+ await fsp.rm(claim, { force: true });
566
+ }
567
+ }
568
+
569
+ /** 更新前必须区分路径缺失、权限错误与符号链接。 */
570
+ /** 返回普通文件的 POSIX 权限;Windows 无法表达 Git 执行位。 */
571
+ async packFileMode(abs) {
572
+ if (process.platform === 'win32') return null;
573
+ const stat = await fsp.lstat(abs);
574
+ if (!stat.isFile()) throw new Error('权限目标必须是普通文件');
575
+ return stat.mode & 0o777;
576
+ }
577
+
578
+ /** 仅在具有 POSIX 权限的文件系统设置普通文件的访问位。 */
579
+ async chmodPackFile(abs, mode) {
580
+ if (!Number.isInteger(mode) || mode < 0 || mode > 0o777) throw new Error('无效的文件权限');
581
+ if (process.platform === 'win32') return;
582
+ if (!(await fsp.lstat(abs)).isFile()) throw new Error('权限目标必须是普通文件');
583
+ await fsp.chmod(abs, mode);
584
+ }
585
+
586
+ async packEntryType(abs) {
587
+ try {
588
+ const entry = await fsp.lstat(abs);
589
+ if (entry.isSymbolicLink()) {
590
+ return 'symlink';
591
+ }
592
+ return entry.isFile() ? 'file' : entry.isDirectory() ? 'dir' : 'other';
593
+ } catch (error) {
594
+ if (error.code === 'ENOENT') {
595
+ return null;
596
+ }
597
+ throw error;
598
+ }
599
+ }
600
+
601
+ /** 回滚时只移除本次创建且仍为空的目录。 */
602
+ async removePackDirIfEmpty(abs) {
603
+ try {
604
+ await fsp.rmdir(abs);
605
+ } catch (error) {
606
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) {
607
+ throw error;
608
+ }
609
+ }
610
+ }
611
+
612
+ /** 复制受管文件时保留普通文件权限,凭据备份仅向当前用户开放。 */
613
+ async copyPackFile(from, to, privateCopy = false) {
614
+ await fsp.mkdir(path.dirname(to), { recursive: true, mode: 0o700 });
615
+ await fsp.copyFile(from, to);
616
+ if (privateCopy) {
617
+ await fsp.chmod(to, 0o600);
618
+ }
619
+ }
620
+
621
+ async move(from, to) {
622
+ await fsp.mkdir(path.dirname(to), { recursive: true });
623
+ await fsp.rename(from, to);
624
+ }
625
+ }
package/src/host.js ADDED
@@ -0,0 +1,17 @@
1
+ // 宿主 I/O:Node 侧的 Host 实现(@dsh-packforge/core 的唯一依赖注入边界)。
2
+ //
3
+ // core 自己不做任何 node:fs / node:crypto / child_process 操作,全部经 Host 注入;
4
+ // 宿主插件跑在 Node 里,用收编进来的 NodeHost(见 ./host-node.js)即可。
5
+ import { NodeHost } from './host-node.js';
6
+
7
+ let host;
8
+
9
+ /** 惰性单例;测试可注入替身(setHost)。 */
10
+ export function getHost() {
11
+ if (!host) host = new NodeHost();
12
+ return host;
13
+ }
14
+
15
+ export function setHost(h) {
16
+ host = h;
17
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ // 类型声明:让 desktop-host(TypeScript)能 import 这个纯 JS 包。
2
+ // 实际实现见 ./index.js。
3
+ export const name: string;
4
+ export const inject: string[];
5
+ // Cordis 插件的 apply 签名;ctx 由 Cordis 注入,这里不引入 @deepseek-ai/* 类型依赖。
6
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
+ export function apply(ctx: any): void;
package/src/index.js ADDED
@@ -0,0 +1,39 @@
1
+ // DSH host 插件入口(cordis 面)—— 纯方案 B:仅 UI + 后端,不做 AI 驱动。
2
+ //
3
+ // 契约(已从官方源码确证):
4
+ // - 第三方 bundle 的宿主→客户端直连 RPC 只能自己 inject webServer 挂前缀路由
5
+ // (ctx.connection.rpc.handle 在官方实现里 owner 绑死 connection 自身 ctx,拿不到
6
+ // webServer,会抛错;/api 拦截又被 gateway 独占)—— 详见 rpc.js 顶部注释。
7
+ // - ctx.profileContext 直接给出 home/当前 profile 事实(零猜路径)。
8
+ import { resolveRuntime } from './runtime.js';
9
+ import { registerRpc } from './rpc.js';
10
+ import { registerBall } from './ball-host.js';
11
+ import { getHost } from './host.js';
12
+ import { readState } from './profiles.js';
13
+ import { createDspackSkillProvider } from './skills/index.js';
14
+
15
+ export const name = 'dspack-host';
16
+
17
+ export const inject = ['connection', 'webServer', 'skills'];
18
+
19
+ export function apply(ctx) {
20
+ // UI ↔ 后端直连 RPC(设置面板按钮走这里,静默、不进聊天栏)。
21
+ const runtime = resolveRuntime(ctx);
22
+ registerRpc(ctx, runtime);
23
+ // 悬浮球:绕过设置页/侧边栏的独立入口(整合包把侧边栏搞坏时仍进得来)。
24
+ // 注入行须尽早注册 —— 桌面壳的注入表是宿主启动时一次性收集的。
25
+ registerBall(ctx);
26
+ // 启动时把已存配置里的代理地址应用到 NodeHost(设置项覆盖环境变量);读不到/异常不阻塞启动。
27
+ void (async () => {
28
+ try {
29
+ const state = await readState(runtime.home);
30
+ getHost().setProxy(state?.config?.proxy);
31
+ } catch { /* 忽略 */ }
32
+ })();
33
+ // 注册自定义 skill 提供者:把 publish-to-github 送进模型 skill catalog(不走磁盘)。
34
+ // registerProvider 返回 disposer,yield 给 effect 以在插件卸载时反注册。
35
+ ctx.effect(
36
+ () => ctx.skills.registerProvider(() => createDspackSkillProvider()),
37
+ 'dspack: skill',
38
+ );
39
+ }