@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,114 @@
1
+ # DSH PackForge profile-switch progress window (packaged-build replacement for the electron popup).
2
+ #
3
+ # Spawned by the migration helper as:
4
+ # powershell -NoProfile -File progress-window.ps1 -ProgressFile <path>
5
+ # It polls progress.json and renders the step timeline; closes itself when phase is done/failed.
6
+ #
7
+ # MUST run under Windows PowerShell 5.1 (powershell.exe), which is STA and can show WPF windows.
8
+ # pwsh (PowerShell 7+) is MTA and will throw on window creation.
9
+ #
10
+ # Keep this file pure ASCII: Windows PowerShell 5.1 reads .ps1 in the ANSI codepage, so any
11
+ # non-ASCII literal (Chinese comments, symbols) would garble. Labels come from progress.json
12
+ # (read as UTF-8), so nothing non-ASCII is hardcoded here.
13
+ param([Parameter(Mandatory = $true)][string]$ProgressFile)
14
+
15
+ Add-Type -AssemblyName PresentationFramework
16
+ Add-Type -AssemblyName PresentationCore
17
+
18
+ function Read-Progress {
19
+ if (-not (Test-Path -LiteralPath $ProgressFile)) { return $null }
20
+ try {
21
+ $raw = [System.IO.File]::ReadAllText($ProgressFile)
22
+ return ($raw | ConvertFrom-Json)
23
+ } catch { return $null }
24
+ }
25
+
26
+ function New-Brush([string]$hex) {
27
+ return ([System.Windows.Media.BrushConverter]::new()).ConvertFromString($hex)
28
+ }
29
+
30
+ $window = New-Object System.Windows.Window
31
+ $window.Title = 'DSH PackForge'
32
+ $window.WindowStyle = [System.Windows.WindowStyle]::None
33
+ $window.ResizeMode = [System.Windows.ResizeMode]::NoResize
34
+ $window.Topmost = $true
35
+ $window.ShowInTaskbar = $false
36
+ $window.Width = 380
37
+ $window.Height = 272
38
+ $window.Background = New-Brush '#1e1f24'
39
+ $window.WindowStartupLocation = [System.Windows.WindowStartupLocation]::Manual
40
+ $wa = [System.Windows.SystemParameters]::WorkArea
41
+ $window.Left = $wa.Right - $window.Width - 20
42
+ $window.Top = $wa.Bottom - $window.Height - 20
43
+
44
+ $root = New-Object System.Windows.Controls.StackPanel
45
+ $root.Margin = New-Object System.Windows.Thickness(18)
46
+
47
+ $title = New-Object System.Windows.Controls.TextBlock
48
+ $title.FontSize = 14
49
+ $title.FontWeight = 'SemiBold'
50
+ $title.Foreground = New-Brush '#e6e6ea'
51
+ $title.Text = 'DSH PackForge'
52
+ $root.AddChild($title) | Out-Null
53
+
54
+ $subtitle = New-Object System.Windows.Controls.TextBlock
55
+ $subtitle.FontSize = 11
56
+ $subtitle.Foreground = New-Brush '#8b8c95'
57
+ $subtitle.Margin = New-Object System.Windows.Thickness(0, 2, 0, 0)
58
+ $root.AddChild($subtitle) | Out-Null
59
+
60
+ $stepsPanel = New-Object System.Windows.Controls.StackPanel
61
+ $stepsPanel.Margin = New-Object System.Windows.Thickness(0, 12, 0, 0)
62
+ $root.AddChild($stepsPanel) | Out-Null
63
+
64
+ $hint = New-Object System.Windows.Controls.TextBlock
65
+ $hint.FontSize = 11
66
+ $hint.Foreground = New-Brush '#8b8c95'
67
+ $hint.TextWrapping = [System.Windows.TextWrapping]::Wrap
68
+ $hint.Margin = New-Object System.Windows.Thickness(0, 12, 0, 0)
69
+ $root.AddChild($hint) | Out-Null
70
+
71
+ $window.Content = $root
72
+
73
+ $statusGlyph = @{
74
+ pending = ' '
75
+ running = [char]0x25D1
76
+ done = [char]0x25C9
77
+ failed = [char]0x00D7
78
+ }
79
+ $statusColor = @{
80
+ pending = '#5a5b63'
81
+ running = '#6ab7ff'
82
+ done = '#2ea44f'
83
+ failed = '#d3383a'
84
+ }
85
+
86
+ $timer = New-Object System.Windows.Threading.DispatcherTimer
87
+ $timer.Interval = [System.TimeSpan]::FromMilliseconds(200)
88
+ $timer.Add_Tick({
89
+ $p = Read-Progress
90
+ if ($null -eq $p) { return }
91
+ $subtitle.Text = "$($p.from) -> $($p.to)"
92
+ if ($null -ne $p.hint) { $hint.Text = [string]$p.hint } else { $hint.Text = '' }
93
+ $stepsPanel.Children.Clear()
94
+ foreach ($s in @($p.steps)) {
95
+ $line = New-Object System.Windows.Controls.TextBlock
96
+ $glyph = $statusGlyph[$s.status]
97
+ if ($null -eq $glyph) { $glyph = ' ' }
98
+ $line.Text = "$glyph $($s.label)"
99
+ $line.FontSize = 13
100
+ $line.Margin = New-Object System.Windows.Thickness(0, 4, 0, 0)
101
+ $col = $statusColor[$s.status]
102
+ if ($null -eq $col) { $col = '#9a9ba3' }
103
+ $line.Foreground = New-Brush $col
104
+ $stepsPanel.AddChild($line) | Out-Null
105
+ }
106
+ if ($p.phase -eq 'done' -or $p.phase -eq 'failed') {
107
+ $timer.Stop()
108
+ Start-Sleep -Milliseconds 700
109
+ $window.Close()
110
+ }
111
+ })
112
+ $timer.Start()
113
+
114
+ $window.ShowDialog() | Out-Null
@@ -0,0 +1,126 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>切换中</title>
6
+ <style>
7
+ :root { color-scheme: dark; }
8
+ * { box-sizing: border-box; }
9
+ html, body { margin: 0; }
10
+ body {
11
+ padding: 16px 18px 18px;
12
+ font-family: system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif;
13
+ background: #1e1f24; color: #e8e9ed;
14
+ user-select: none; -webkit-user-select: none;
15
+ }
16
+ .title { font-size: 15px; font-weight: 600; text-align: center; margin: 2px 0 12px; letter-spacing: 3px; }
17
+ .current {
18
+ text-align: center; font-size: 17px; font-weight: 700; color: #6ab7ff;
19
+ margin: 0 0 16px; min-height: 24px;
20
+ }
21
+ .current .dots { display: inline-block; animation: blink 1.2s steps(2, start) infinite; }
22
+ @keyframes blink { to { visibility: hidden; } }
23
+ .timeline { display: flex; flex-direction: column; gap: 10px; }
24
+ .step { display: flex; align-items: center; gap: 10px; }
25
+ .dot {
26
+ width: 22px; height: 22px; border-radius: 50%; flex: 0 0 auto;
27
+ display: flex; align-items: center; justify-content: center;
28
+ font-size: 12px; color: #fff; background: #3a3c43;
29
+ }
30
+ .step.done .dot { background: #2ea44f; }
31
+ .step.failed .dot { background: #d3383a; }
32
+ .step.pending .dot { background: #3a3c43; color: #6b6d76; }
33
+ .step.running .dot {
34
+ background: transparent;
35
+ border: 2px solid #6ab7ff; border-top-color: transparent;
36
+ animation: spin 0.8s linear infinite;
37
+ }
38
+ @keyframes spin { to { transform: rotate(360deg); } }
39
+ .label { font-size: 14px; line-height: 20px; }
40
+ .step.pending .label { color: #6b6d76; }
41
+ .step.done .label { color: #9aa0aa; }
42
+ .step.running .label { color: #e8e9ed; font-weight: 600; }
43
+ .step.failed .label { color: #ff8b8c; }
44
+ .mark { margin-left: auto; font-size: 12px; color: #6b6d76; }
45
+ .step.done .mark { color: #2ea44f; }
46
+ .step.failed .mark { color: #d3383a; }
47
+ .error { margin-top: 10px; font-size: 12px; line-height: 18px; color: #ff8b8c; word-break: break-all; }
48
+ .hint { margin-top: 14px; padding-top: 12px; border-top: 1px solid #2c2d33; font-size: 12px; line-height: 18px; color: #8b8c95; text-align: center; }
49
+ </style>
50
+ </head>
51
+ <body>
52
+ <div class="title">切换中</div>
53
+ <div class="current" id="current"></div>
54
+ <div class="timeline" id="timeline"></div>
55
+ <div class="hint" id="hint"></div>
56
+ <script>
57
+ const fs = require('node:fs');
58
+ const q = new URLSearchParams(location.search);
59
+ const file = q.get('file');
60
+ const currentEl = document.getElementById('current');
61
+ const timelineEl = document.getElementById('timeline');
62
+ const hintEl = document.getElementById('hint');
63
+ const DOT_MARK = { done: '✓', running: '', pending: '○', failed: '✗' };
64
+ const TAIL = { done: '完成', running: '进行中', failed: '失败', pending: '待办' };
65
+ let lastRaw = null;
66
+
67
+ function render(data) {
68
+ const steps = Array.isArray(data.steps) ? data.steps : [];
69
+ const running = steps.find((s) => s.status === 'running');
70
+ currentEl.innerHTML = running
71
+ ? '正在:' + escapeHtml(running.label) + '<span class="dots">…</span>'
72
+ : (data.phase === 'done' ? '完成' : data.phase === 'failed' ? '切换失败' : '准备中…');
73
+
74
+ timelineEl.textContent = '';
75
+ for (const s of steps) {
76
+ const st = s.status || 'pending';
77
+ const row = document.createElement('div');
78
+ row.className = 'step ' + st;
79
+
80
+ const dot = document.createElement('div');
81
+ dot.className = 'dot';
82
+ dot.textContent = st === 'running' ? '' : (DOT_MARK[st] || '○');
83
+
84
+ const label = document.createElement('div');
85
+ label.className = 'label';
86
+ label.textContent = s.label;
87
+
88
+ const mark = document.createElement('div');
89
+ mark.className = 'mark';
90
+ mark.textContent = TAIL[st] || '';
91
+
92
+ row.appendChild(dot);
93
+ row.appendChild(label);
94
+ row.appendChild(mark);
95
+ timelineEl.appendChild(row);
96
+ }
97
+ if (data.phase === 'failed' && data.error) {
98
+ const err = document.createElement('div');
99
+ err.className = 'error';
100
+ err.textContent = String(data.error);
101
+ timelineEl.appendChild(err);
102
+ }
103
+ hintEl.textContent = data.hint ? String(data.hint) : '';
104
+ }
105
+
106
+ function escapeHtml(s) {
107
+ return String(s).replace(/[&<>"']/g, (c) => (
108
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
109
+ ));
110
+ }
111
+
112
+ function tick() {
113
+ let raw = null;
114
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { /* 尚未写入 */ }
115
+ if (raw === lastRaw) return;
116
+ lastRaw = raw;
117
+ let data = null;
118
+ try { data = raw ? JSON.parse(raw) : null; } catch { return; }
119
+ if (data) render(data);
120
+ }
121
+
122
+ setInterval(tick, 200);
123
+ tick();
124
+ </script>
125
+ </body>
126
+ </html>
@@ -0,0 +1,132 @@
1
+ // 切换进度通道:host/helper 写 <home>/.dsh-pack/progress.json,进度窗口轮询渲染时间线。
2
+ //
3
+ // 时间线步骤顺序即显示顺序;firstTime 时在「杀进程」之后多一步「移动默认目录」。
4
+ // 步骤 label 直接写中文:进度窗口是独立进程、拿不到客户端 locale,且目标用户是中文场景。
5
+ import fsp from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { spawn } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { isPackagedBuild } from './packaged.js';
10
+
11
+ const FILE = 'progress.json';
12
+ const MAIN = fileURLToPath(new URL('./progress-main.cjs', import.meta.url));
13
+ const PS1 = fileURLToPath(new URL('./progress-window.ps1', import.meta.url));
14
+
15
+ const LABELS = {
16
+ install: '安装整合包插件',
17
+ kill: '杀掉原来的进程',
18
+ move: '移动默认目录',
19
+ link: '重新创建链接',
20
+ launch: '正在拉起客户端',
21
+ };
22
+
23
+ /** 进度窗底部固定提示(写进 progress.json,HTML 与 WPF 两个渲染器共用;PS1 因此保持纯 ASCII)。 */
24
+ export const HINT = '如长时间未自动重启,请手动拉起客户端。';
25
+
26
+ export function progressPath(home) {
27
+ return path.join(home, '.dsh-pack', FILE);
28
+ }
29
+
30
+ export async function readProgress(home) {
31
+ try {
32
+ return JSON.parse(await fsp.readFile(progressPath(home), 'utf8'));
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ // —— 写串行化 ——
39
+ // progress.json 是读-改-写(read-modify-write),多个调用方(onProgress 的 fire-and-forget setStep、
40
+ // main 的 await setStep/setPhase)并发时会产生竞态:后读到的旧快照覆盖先写的更新,导致「重新创建链接」
41
+ // 已 done 又被 running 覆盖、与「拉起」一起转圈。这里把所有写操作放进同一条 promise 链,读-改-写整体串行。
42
+ let chain = Promise.resolve();
43
+ function withLock(fn) {
44
+ const run = chain.then(fn, fn);
45
+ chain = run.then(() => {}, () => {});
46
+ return run;
47
+ }
48
+
49
+ async function commit(home, next) {
50
+ const file = progressPath(home);
51
+ await fsp.mkdir(path.dirname(file), { recursive: true });
52
+ const tmp = `${file}.tmp`;
53
+ await fsp.writeFile(tmp, JSON.stringify(next));
54
+ try {
55
+ await fsp.rename(tmp, file);
56
+ } catch {
57
+ // 窗口正读时 rename 可能 EPERM/EBUSY,回退直写(读端有 parse 容错,最多丢一帧)。
58
+ await fsp.writeFile(file, JSON.stringify(next));
59
+ }
60
+ return next;
61
+ }
62
+
63
+ export function writeProgress(home, patch) {
64
+ return withLock(async () => {
65
+ const cur = (await readProgress(home)) ?? {};
66
+ return commit(home, { ...cur, ...patch, updatedAt: Date.now() });
67
+ });
68
+ }
69
+
70
+ /** 时间线步骤(每次返回全新对象数组)。firstTime 时插入「移动默认目录」。 */
71
+ export function buildSteps(firstTime) {
72
+ const ids = ['install', 'kill'];
73
+ if (firstTime) ids.push('move');
74
+ ids.push('link', 'launch');
75
+ return ids.map((id) => ({ id, label: LABELS[id], status: 'pending' }));
76
+ }
77
+
78
+ /** 按 id 改一步状态;不存在的 id(如非首切的 move)静默跳过。读写全程在锁内,保证顺序。
79
+ * 注意:不能在锁内再调 writeProgress(它会再次 withLock 造成嵌套死锁),故直接 commit。 */
80
+ export function setStep(home, id, status) {
81
+ return withLock(async () => {
82
+ const p = await readProgress(home);
83
+ if (!p || !Array.isArray(p.steps)) return null;
84
+ let changed = false;
85
+ for (const s of p.steps) {
86
+ if (s.id === id && s.status !== status) {
87
+ s.status = status;
88
+ changed = true;
89
+ }
90
+ }
91
+ if (!changed) return p;
92
+ return commit(home, { ...p, updatedAt: Date.now() });
93
+ });
94
+ }
95
+
96
+ /** 收尾:phase 到 done/failed;failed 附 error 供窗口显示。 */
97
+ export async function setPhase(home, phase, error = null) {
98
+ return writeProgress(home, { phase, error });
99
+ }
100
+
101
+ /**
102
+ * 派生进度窗口(electron GUI,不带 ELECTRON_RUN_AS_NODE)。返回 pid 供 helper 的杀树脚本排除。
103
+ *
104
+ * 两个实测结论(Windows + electron@44):
105
+ * 1. 必须 detached:true —— 否则 host 被 helper 的 TerminateProcess 杀掉时,窗口作为 host 的
106
+ * 子进程会被 Windows 连带杀死(父进程一死窗口立即消失,杀树脚本排除再彻底也没用)。
107
+ * 2. 绝不能 windowsHide:true —— CREATE_NO_WINDOW 会让窗口进程活着但 GUI 不显示。
108
+ * 杀树脚本仍按 pid 排除本窗口整棵子树(见 migrate-helper.js 的 $skip),防止直接 Stop-Process 它。
109
+ */
110
+ export function spawnProgressWindow(home) {
111
+ const file = progressPath(home);
112
+ // 打包态:process.execPath 是 app 二进制,spawn 它只会拉起一个完整 app 副本(electron 独立
113
+ // 进度窗必死)。改走 PowerShell WPF(progress-window.ps1)。开发态仍用 electron GUI 小窗。
114
+ if (process.platform === 'win32' && isPackagedBuild()) {
115
+ const child = spawn('powershell.exe',
116
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', PS1, '-ProgressFile', file],
117
+ { detached: true, stdio: 'ignore', windowsHide: true });
118
+ child.on('error', () => {});
119
+ child.unref();
120
+ return child.pid;
121
+ }
122
+ const env = { ...process.env };
123
+ delete env.ELECTRON_RUN_AS_NODE; // 防御:绝不把 RUN_AS_NODE 漏给 GUI 进程
124
+ const child = spawn(process.execPath, [MAIN, `--progress-file=${file}`], {
125
+ detached: true,
126
+ stdio: 'ignore',
127
+ env,
128
+ });
129
+ child.on('error', () => {});
130
+ child.unref();
131
+ return child.pid;
132
+ }
package/src/rpc.js ADDED
@@ -0,0 +1,157 @@
1
+ // 宿主 RPC:在 webServer 上挂 /dsh-pack 前缀路由,自行解析 connection 的
2
+ // client-request 信封、分发到 endpoint、回对称的 server-response。
3
+ //
4
+ // 为什么不走 ctx.connection.rpc.handle(channel, handler):
5
+ // 官方 HostConnectionService.rpc.handle 内部把 owner 固定成 this.ctx(connection
6
+ // 插件自身 context,只 inject 了 credentials),register() 里访问 owner.webServer
7
+ // 会拿到 undefined → 抛 TypeError → fiber 直接 FAILED(插件列表显示「异常」)。
8
+ // 而 /api 拦截又被 gateway 独占(intercept 一条通道只允许一个 owner)。所以第三方
9
+ // bundle 唯一稳的直连通道,是自己 inject webServer 并注册一个前缀路由。
10
+ //
11
+ // 结果形状与客户端 ctx.connection.rpc.call 完全对称(官方 @deepseek-ai/dsh-client-connection 确证):
12
+ // { ok:true, value } | { ok:false, error:{ code, message, details } }
13
+ import { ENDPOINTS } from './endpoints.js';
14
+ import { CHANNEL } from './channel.js';
15
+ import { BALL_SCRIPT_PATH, readBallAsset } from './ball-host.js';
16
+
17
+ export const ok = (value) => ({ ok: true, value });
18
+ export const fail = (code, message, details = {}) => ({
19
+ ok: false,
20
+ error: { code, message, details: details ?? {} },
21
+ });
22
+
23
+ // 与官方 endpointFromPath 同构:去掉通道前缀取相对 endpoint(允许 profile/list 这类多段)。
24
+ const endpointFromPath = (url, channel) => {
25
+ let pathname;
26
+ try {
27
+ pathname = new URL(url, 'http://x').pathname;
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ if (!pathname.startsWith(`${channel}/`)) return undefined;
32
+ const endpoint = pathname.slice(channel.length + 1);
33
+ const segments = endpoint.split('/');
34
+ if (segments.some((s) => s === '' || s === '.' || s === '..' || !/^[A-Za-z0-9_$.-]+$/.test(s))) return undefined;
35
+ return endpoint;
36
+ };
37
+
38
+ // 读 POST 体(JSON),带 64 MiB 上限。
39
+ const readJsonBody = (req) => new Promise((resolve, reject) => {
40
+ let size = 0;
41
+ const chunks = [];
42
+ req.on('data', (c) => {
43
+ size += c.length;
44
+ if (size > 64 * 1024 * 1024) {
45
+ reject(new Error('请求体过大'));
46
+ req.destroy();
47
+ return;
48
+ }
49
+ chunks.push(c);
50
+ });
51
+ req.on('end', () => {
52
+ const raw = Buffer.concat(chunks).toString('utf8');
53
+ if (raw === '') return resolve({});
54
+ try {
55
+ resolve(JSON.parse(raw));
56
+ } catch (e) {
57
+ reject(e); // 坏 JSON 转成 reject,由外层统一回 400,绝不同步抛错崩宿主
58
+ }
59
+ });
60
+ req.on('error', reject);
61
+ });
62
+
63
+ const json = (res, status, body) => {
64
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
65
+ res.end(JSON.stringify(body));
66
+ };
67
+
68
+ /**
69
+ * 注册 '/dsh-pack' 通道:设置面板 UI 的静默直连入口(不经模型、不进聊天栏)。
70
+ * @returns 注销函数;webServer 服务不可用时返回 null。
71
+ */
72
+ export function registerRpc(ctx, runtime) {
73
+ const ws = ctx?.webServer;
74
+ if (!ws || typeof ws.register !== 'function') return null;
75
+
76
+ const route = {
77
+ kind: 'prefix',
78
+ path: CHANNEL,
79
+ handler: async (req, res) => {
80
+ // 复用 connection 的 Host/Origin + 浏览器鉴权栅栏(与 /api 同策略)。
81
+ const rejection = ctx?.connection?.requestRejection?.(req);
82
+ if (rejection) {
83
+ res.writeHead(rejection);
84
+ res.end(rejection === 401 ? 'unauthorized' : 'forbidden');
85
+ return;
86
+ }
87
+ // GET 只服务悬浮球脚本(同一 prefix 路由,不新增路由以免撞 duplicate 检查):
88
+ // /dsh-pack/ball.js → lib/ball.js 产物。no-store 避免升级后浏览器仍用旧球。
89
+ if (req.method === 'GET') {
90
+ const pathname = (() => {
91
+ try { return new URL(req.url ?? '', 'http://x').pathname; } catch { return ''; }
92
+ })();
93
+ if (pathname === BALL_SCRIPT_PATH) {
94
+ const asset = await readBallAsset();
95
+ if (!asset) {
96
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
97
+ res.end('ball.js 未构建:请先运行 npm run bundle');
98
+ return;
99
+ }
100
+ res.writeHead(200, {
101
+ 'content-type': 'application/javascript; charset=utf-8',
102
+ 'cache-control': 'no-store',
103
+ });
104
+ res.end(asset.bytes);
105
+ return;
106
+ }
107
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' });
108
+ res.end('method not allowed');
109
+ return;
110
+ }
111
+ if (req.method !== 'POST') {
112
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' });
113
+ res.end('method not allowed');
114
+ return;
115
+ }
116
+ const endpoint = endpointFromPath(req.url ?? '', CHANNEL);
117
+ let body;
118
+ try {
119
+ body = await readJsonBody(req);
120
+ } catch {
121
+ json(res, 400, {
122
+ type: 'server-response', rpcId: 'invalid-request',
123
+ result: fail('gateway/bad-request', 'invalid client-request message', { issues: [] }),
124
+ });
125
+ return;
126
+ }
127
+ const rpcId = typeof body?.rpcId === 'string' ? body.rpcId : 'invalid-request';
128
+ if (body?.type !== 'client-request' || typeof body?.method !== 'string') {
129
+ json(res, 200, {
130
+ type: 'server-response', rpcId,
131
+ result: fail('gateway/bad-request', 'invalid client-request message', { issues: [] }),
132
+ });
133
+ return;
134
+ }
135
+ const handler = ENDPOINTS[endpoint];
136
+ const payload = body?.payload ?? {};
137
+ let result;
138
+ if (endpoint === undefined || handler === undefined) {
139
+ result = fail('no-such-endpoint', `未知端点:${body.method}`);
140
+ } else if (body.method !== endpoint) {
141
+ result = fail('gateway/bad-request',
142
+ `method ${JSON.stringify(body.method)} does not match endpoint ${JSON.stringify(endpoint)}`, { issues: [] });
143
+ } else {
144
+ try {
145
+ result = ok(await handler({ ctx, runtime, payload, signal: undefined, peer: undefined }));
146
+ } catch (err) {
147
+ result = fail('endpoint-error', err?.message ?? String(err), { stack: err?.stack });
148
+ }
149
+ }
150
+ json(res, 200, { type: 'server-response', rpcId, result });
151
+ },
152
+ };
153
+
154
+ // 随 fiber 生命周期自动卸载(webserver.register 返回同步 disposer,effect 会接住)。
155
+ ctx.effect(() => ws.register(route), `dsh-pack: ${CHANNEL} rpc channel`);
156
+ return () => {};
157
+ }
package/src/runtime.js ADDED
@@ -0,0 +1,43 @@
1
+ // 运行时事实:home / profiles 目录 / 当前 profile。
2
+ //
3
+ // 0.1.7 起 ctx.profileContext 直接给出全部事实(零猜路径);旧版环境降级到环境变量兜底。
4
+ // 已从官方 @deepseek-ai/dsh-app-boot 源码确证:
5
+ // ProfileContext = { name, dir, patchPath, installAnchor, cwd, home, startedBundles, overlays, ... }
6
+ import path from 'node:path';
7
+ import os from 'node:os';
8
+
9
+ export const PROFILES_DIR = 'profiles';
10
+ // desktop 硬编码的激活 profile 名(官方 apps/desktop/src/paths.ts 源码确证,无 env 覆盖)。
11
+ export const ACTIVE_NAME = 'desktop';
12
+
13
+ export function resolveRuntime(ctx) {
14
+ const pc = ctx?.profileContext;
15
+ if (pc && typeof pc.home === 'string') {
16
+ return {
17
+ home: pc.home,
18
+ credentialCwd: pc.cwd ?? process.cwd(),
19
+ installAnchor: pc.installAnchor,
20
+ overlayPaths: pc.overlayPaths ?? [],
21
+ profilesDir: path.join(pc.home, PROFILES_DIR),
22
+ profileName: pc.name ?? ACTIVE_NAME,
23
+ profileDir: pc.dir ?? null,
24
+ patchPath: pc.patchPath ?? null,
25
+ startedBundles: Array.isArray(pc.startedBundles) ? [...pc.startedBundles] : [],
26
+ hasProfileContext: true,
27
+ source: 'profileContext',
28
+ };
29
+ }
30
+ // 兜底:非 dsh profile 启动(例如直接 node 跑测试),用环境变量。
31
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
32
+ return {
33
+ home,
34
+ credentialCwd: process.cwd(),
35
+ profilesDir: path.join(home, PROFILES_DIR),
36
+ profileName: ACTIVE_NAME,
37
+ profileDir: path.join(home, PROFILES_DIR, ACTIVE_NAME),
38
+ patchPath: null,
39
+ startedBundles: [],
40
+ hasProfileContext: false,
41
+ source: 'env',
42
+ };
43
+ }
@@ -0,0 +1,50 @@
1
+ // settings.section 注册闸门:让「整合包」这条设置入口在 DSH 插件热重载
2
+ // (关/开插件、装其他插件触发宿主重载)之后仍能重新注册,而不是被重载周期吞掉。
3
+ //
4
+ // 根因(已从 DSH slots 服务源码确证):
5
+ // SlotsService.inject 的回调绑在「slot 声明生命周期」(declaration epoch)上;
6
+ // SlotsService.register 底层是 ctx.effect(() => _register(...)),也挂在调用方 fiber。
7
+ // 若写 `slots.inject('settings.section', () => slots.register({id}, Comp))`,
8
+ // 热重载时 DSH 会「先跑新 apply(旧 id 注册尚未被 unload 清理)→ 再清旧 fiber」,
9
+ // 新 register 命中 SlotCore 对 list slot 的重复 id 校验
10
+ // (`already has an entry with id "${id}"`)直接 throw;该 throw 被 inject 的
11
+ // changed() 吞掉并 stop(),随后旧 fiber 清理把旧入口也带走——两个都没了。
12
+ // 因 throw 走 queueMicrotask 异步重抛,故无任何可见警告。
13
+ //
14
+ // 对策(照搬 dsh-market 的 section-gate 状态机,实测其重载不丢入口):
15
+ // register 只允许成功调用一次(幂等),disposer 被显式持有;
16
+ // inject 回调只负责置 available,返回 undefined,不把 register 绑成回调清理函数。
17
+ export function createSectionGate(register) {
18
+ let ready = false;
19
+ let removed = false;
20
+ let dispose = null;
21
+
22
+ const apply = () => {
23
+ if (!ready) return;
24
+ const shouldShow = !removed;
25
+ if (shouldShow && dispose === null) {
26
+ dispose = register();
27
+ return;
28
+ }
29
+ if (!shouldShow && dispose !== null) {
30
+ const stop = dispose;
31
+ dispose = null;
32
+ stop();
33
+ }
34
+ };
35
+
36
+ return {
37
+ /** slots 服务已就位(inject 回调触发)。幂等:重复调用不会二次 register。 */
38
+ available: () => {
39
+ ready = true;
40
+ apply();
41
+ },
42
+ /** 当前入口是否已注册。 */
43
+ visible: () => dispose !== null,
44
+ /** 本包被移除:永久注销,后续任何 available 都不再复活。 */
45
+ retire: () => {
46
+ removed = true;
47
+ apply();
48
+ },
49
+ };
50
+ }