@xiaojingyuai/dsh 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -2
- package/client.js +398 -0
- package/companion.mjs +272 -0
- package/cordis.patch.yml +3 -0
- package/index.mjs +74 -0
- package/package.json +32 -4
- package/runtime.mjs +203 -0
- package/session-id.cjs +9 -0
- package/update.mjs +166 -0
package/README.md
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 一只小鲸鱼AI · DeepSeek Harness 插件
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
这个单文件包内含小鲸鱼的 Windows 运行时。保留 Live2D 桌宠、核心终端及 Python 语音管线。音频由 Python 播放并进入 AEC。
|
|
4
|
+
|
|
5
|
+
## 使用
|
|
6
|
+
|
|
7
|
+
1. 在 DeepSeek Harness 的「插件」中安装 `@xiaojingyuai/dsh` 并启用。npm 包只包含接入代码,Windows 运行时首次启动时从 OSS 下载并校验。
|
|
8
|
+
2. 打开一个普通 DSH 会话。小鲸鱼自动准备运行时、启动并接入当前会话。也可在「设置 → 一只小鲸鱼AI」中点「接入当前会话」,或让智能体调用 `xiaojingyu_connect`。
|
|
9
|
+
3. 首次使用在小鲸鱼窗口完成隐私确认、账号登录和语音设备设置。语音模型按需下载。
|
|
10
|
+
4. 用「自动接入」开关管理启动行为。原桌面托盘不显示;打开核心终端、重启、初始化、关于、使用引导与 Pro、退出等操作统一在「设置 → 一只小鲸鱼AI」中完成。
|
|
11
|
+
5. 关闭插件或退出 DSH 会结束插件启动的小鲸鱼桌面程序。
|
|
12
|
+
|
|
13
|
+
## 更新
|
|
14
|
+
|
|
15
|
+
「设置 → 一只小鲸鱼AI → 插件更新」会从 `dafeiyu-download` OSS 检查新版本。更新清单使用 Ed25519 签名,更新包同时校验大小和 SHA-256。npm 安装可继续通过 DSH 插件管理更新;OSS 更新入口保留下载并导入的兼容路径。
|
|
16
|
+
|
|
17
|
+
## 运行目录
|
|
18
|
+
|
|
19
|
+
插件从签名清单指定的 OSS 地址下载 Windows 运行时,校验大小与 SHA-256 后在本机用户目录解包。运行时缓存于 `%LOCALAPPDATA%\XiaojingyuAI\DSH\r`,后续启动复用缓存。小鲸鱼设置保存在 `%APPDATA%\XiaojingyuAI\HarnessCompanion`。模型由当前 DeepSeek Harness 会话管理。
|
|
20
|
+
|
|
21
|
+
支持 Windows x64 的本机 DeepSeek Harness Desktop。小鲸鱼沿用 Windows 10 1809 及以上的项目要求。
|
|
22
|
+
|
package/client.js
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: 'xiaojingyuai-dsh',
|
|
3
|
+
factory(require) {
|
|
4
|
+
const { createElement: h, useEffect, useId, useState, useSyncExternalStore } = require('react');
|
|
5
|
+
const settingsKey = 'xiaojingyu.dsh.auto-connect';
|
|
6
|
+
const path = '/api/xiaojingyu/companion';
|
|
7
|
+
const { protocol, hostname } = window.location;
|
|
8
|
+
const desktop = protocol === 'dsh-app:' && hostname === 'app' && Boolean(window.dshDesktop);
|
|
9
|
+
const loopback = ['http:', 'https:'].includes(protocol) && ['127.0.0.1', 'localhost', '[::1]'].includes(hostname);
|
|
10
|
+
const phases = {
|
|
11
|
+
idle: ['待接入', 'neutral'],
|
|
12
|
+
preparing: ['正在接入', 'pending'],
|
|
13
|
+
starting: ['正在接入', 'pending'],
|
|
14
|
+
connected: ['已接入', 'success'],
|
|
15
|
+
stopping: ['正在退出', 'pending'],
|
|
16
|
+
};
|
|
17
|
+
const settingsStyle = `
|
|
18
|
+
.xjy-settings {
|
|
19
|
+
max-width: 620px;
|
|
20
|
+
color: var(--dsw-alias-label-primary, CanvasText);
|
|
21
|
+
}
|
|
22
|
+
.xjy-settings__card {
|
|
23
|
+
border: 1px solid var(--dsw-alias-settings-card-stroke, color-mix(in srgb, currentColor 14%, transparent));
|
|
24
|
+
border-radius: var(--dsw-radius-xl, 16px);
|
|
25
|
+
background: var(--dsw-alias-settings-card-fill, Canvas);
|
|
26
|
+
padding: 0 clamp(14px, 3vw, 20px);
|
|
27
|
+
}
|
|
28
|
+
.xjy-settings__card + .xjy-settings__card { margin-top: 12px; }
|
|
29
|
+
.xjy-settings__row {
|
|
30
|
+
min-height: 58px;
|
|
31
|
+
box-sizing: border-box;
|
|
32
|
+
display: flex;
|
|
33
|
+
align-items: center;
|
|
34
|
+
justify-content: space-between;
|
|
35
|
+
gap: 12px;
|
|
36
|
+
padding: 14px 0;
|
|
37
|
+
}
|
|
38
|
+
.xjy-settings__row + .xjy-settings__row {
|
|
39
|
+
border-top: 1px solid var(--dsw-alias-settings-card-stroke, color-mix(in srgb, currentColor 14%, transparent));
|
|
40
|
+
}
|
|
41
|
+
.xjy-settings__title { margin: 0; font-size: 14px; font-weight: 550; line-height: 22px; }
|
|
42
|
+
.xjy-settings__note {
|
|
43
|
+
margin: 3px 0 0;
|
|
44
|
+
overflow-wrap: anywhere;
|
|
45
|
+
color: var(--dsw-alias-label-secondary, GrayText);
|
|
46
|
+
font-size: 12px;
|
|
47
|
+
line-height: 18px;
|
|
48
|
+
}
|
|
49
|
+
.xjy-settings__status {
|
|
50
|
+
--xjy-dot: var(--dsw-alias-label-tertiary, GrayText);
|
|
51
|
+
display: inline-flex;
|
|
52
|
+
align-items: center;
|
|
53
|
+
gap: 6px;
|
|
54
|
+
flex: none;
|
|
55
|
+
padding: 4px 9px;
|
|
56
|
+
border-radius: 999px;
|
|
57
|
+
background: color-mix(in srgb, var(--xjy-dot) 10%, transparent);
|
|
58
|
+
font-size: 12px;
|
|
59
|
+
line-height: 18px;
|
|
60
|
+
white-space: nowrap;
|
|
61
|
+
}
|
|
62
|
+
.xjy-settings__status::before {
|
|
63
|
+
content: '';
|
|
64
|
+
width: 6px;
|
|
65
|
+
height: 6px;
|
|
66
|
+
border-radius: 50%;
|
|
67
|
+
background: var(--xjy-dot);
|
|
68
|
+
}
|
|
69
|
+
.xjy-settings__status[data-tone='success'] { --xjy-dot: var(--dsw-alias-state-success-primary, #24a45b); }
|
|
70
|
+
.xjy-settings__status[data-tone='pending'] { --xjy-dot: var(--dsw-alias-state-business-primary, Highlight); }
|
|
71
|
+
.xjy-settings__status[data-tone='error'] { --xjy-dot: var(--dsw-alias-state-error-primary, #d53535); }
|
|
72
|
+
.xjy-settings__switch {
|
|
73
|
+
appearance: none;
|
|
74
|
+
flex: none;
|
|
75
|
+
width: 38px;
|
|
76
|
+
height: 22px;
|
|
77
|
+
padding: 3px;
|
|
78
|
+
border: 0;
|
|
79
|
+
border-radius: 99px;
|
|
80
|
+
background: var(--dsw-alias-border-l1, GrayText);
|
|
81
|
+
cursor: pointer;
|
|
82
|
+
}
|
|
83
|
+
.xjy-settings__switch[aria-checked='true'] { background: var(--dsw-alias-state-business-primary, Highlight); }
|
|
84
|
+
.xjy-settings__switch::before {
|
|
85
|
+
content: '';
|
|
86
|
+
display: block;
|
|
87
|
+
width: 16px;
|
|
88
|
+
height: 16px;
|
|
89
|
+
border-radius: 50%;
|
|
90
|
+
background: var(--dsw-alias-switch-thumb, white);
|
|
91
|
+
transition: transform 140ms ease-out;
|
|
92
|
+
}
|
|
93
|
+
.xjy-settings__switch[aria-checked='true']::before { transform: translateX(16px); }
|
|
94
|
+
.xjy-settings__footer { justify-content: flex-end; flex-wrap: wrap; }
|
|
95
|
+
.xjy-settings__footer .xjy-settings__note { flex: 1 1 150px; margin: 0; }
|
|
96
|
+
.xjy-settings__note--error { color: var(--dsw-alias-label-error, #d53535); }
|
|
97
|
+
.xjy-settings__actions { display: flex; flex: none; gap: 8px; }
|
|
98
|
+
.xjy-settings__action {
|
|
99
|
+
appearance: none;
|
|
100
|
+
box-sizing: border-box;
|
|
101
|
+
border: 1px solid var(--dsw-alias-settings-card-stroke, color-mix(in srgb, currentColor 19%, transparent));
|
|
102
|
+
border-radius: var(--dsw-radius-sm, 8px);
|
|
103
|
+
padding: 6px 12px;
|
|
104
|
+
background: var(--dsw-alias-button-elevated-fill, Canvas);
|
|
105
|
+
color: inherit;
|
|
106
|
+
font: inherit;
|
|
107
|
+
font-size: 13px;
|
|
108
|
+
line-height: 20px;
|
|
109
|
+
cursor: pointer;
|
|
110
|
+
}
|
|
111
|
+
.xjy-settings__action:not(:disabled):hover { background: var(--dsw-alias-interactive-bg-hover, ButtonFace); }
|
|
112
|
+
.xjy-settings__action--danger { color: var(--dsw-alias-label-error, #d53535); }
|
|
113
|
+
.xjy-settings__action--danger:not(:disabled):hover {
|
|
114
|
+
background: color-mix(in srgb, var(--dsw-alias-state-error-primary, #d53535) 10%, transparent);
|
|
115
|
+
}
|
|
116
|
+
.xjy-settings__action:disabled { cursor: default; opacity: .55; }
|
|
117
|
+
.xjy-settings button:focus-visible {
|
|
118
|
+
outline: 2px solid var(--dsw-focus-ring-color, Highlight);
|
|
119
|
+
outline-offset: 3px;
|
|
120
|
+
}
|
|
121
|
+
@media (prefers-reduced-motion: reduce) {
|
|
122
|
+
.xjy-settings__switch::before { transition: none; }
|
|
123
|
+
}
|
|
124
|
+
@media (forced-colors: active) {
|
|
125
|
+
.xjy-settings__switch { border: 1px solid ButtonText; padding: 2px; }
|
|
126
|
+
.xjy-settings__switch::before { background: ButtonText; }
|
|
127
|
+
}
|
|
128
|
+
`;
|
|
129
|
+
|
|
130
|
+
async function request(body, signal) {
|
|
131
|
+
const options = { signal, credentials: 'same-origin', cache: 'no-store' };
|
|
132
|
+
if (body) Object.assign(options, {
|
|
133
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
|
|
134
|
+
});
|
|
135
|
+
const response = await fetch(path, options);
|
|
136
|
+
if (!response.ok && !response.headers.get('content-type')?.includes('json')) throw new Error('小鲸鱼连接服务不可用');
|
|
137
|
+
const result = await response.json();
|
|
138
|
+
if (!response.ok) throw new Error(result.error || '小鲸鱼连接失败');
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
name: 'xiaojingyuai-client',
|
|
144
|
+
inject: ['slots', 'uiSession'],
|
|
145
|
+
apply(ctx) {
|
|
146
|
+
if ((!desktop && !loopback) || !/Windows/i.test(navigator.userAgent)) return;
|
|
147
|
+
const active = ctx.uiSession.adapter.current;
|
|
148
|
+
const lifetime = new AbortController();
|
|
149
|
+
const listeners = new Set();
|
|
150
|
+
let snapshot = {
|
|
151
|
+
enabled: localStorage.getItem(settingsKey) !== 'off',
|
|
152
|
+
selectedId: null, linkedId: null, phase: 'idle', busy: false, error: null,
|
|
153
|
+
actionBusy: null, actionMessage: null, actionError: null,
|
|
154
|
+
updateSource: null, updateInfo: null, updateBusy: false, updateError: null,
|
|
155
|
+
};
|
|
156
|
+
let attempted;
|
|
157
|
+
let currentRequest = 0;
|
|
158
|
+
const subscribe = listener => { listeners.add(listener); return () => listeners.delete(listener); };
|
|
159
|
+
const publish = change => {
|
|
160
|
+
if (Object.keys(change).every(key => snapshot[key] === change[key])) return;
|
|
161
|
+
snapshot = { ...snapshot, ...change };
|
|
162
|
+
for (const listener of listeners) listener();
|
|
163
|
+
};
|
|
164
|
+
const connection = result => ({ phase: phases[result.phase] ? result.phase : 'idle', linkedId: result.sessionId || null });
|
|
165
|
+
async function perform(action, sessionId) {
|
|
166
|
+
const turn = ++currentRequest;
|
|
167
|
+
publish({ busy: true, error: null, phase: action === 'connect' ? 'preparing' : 'stopping' });
|
|
168
|
+
try {
|
|
169
|
+
const result = await request({ action, sessionId }, lifetime.signal);
|
|
170
|
+
if (turn === currentRequest) publish(connection(result));
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (turn === currentRequest && !lifetime.signal.aborted) publish({ phase: 'idle', error: error.message });
|
|
173
|
+
} finally {
|
|
174
|
+
if (turn === currentRequest) publish({ busy: false });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
async function connect(manual = false) {
|
|
178
|
+
const id = active.getSnapshot().key || null;
|
|
179
|
+
publish({ selectedId: id });
|
|
180
|
+
if (!id) return;
|
|
181
|
+
if (!manual && (!snapshot.enabled || document.visibilityState !== 'visible' || !document.hasFocus() || attempted === id)) return;
|
|
182
|
+
attempted = id;
|
|
183
|
+
await perform('connect', id);
|
|
184
|
+
}
|
|
185
|
+
async function toggle() {
|
|
186
|
+
const enabled = !snapshot.enabled;
|
|
187
|
+
localStorage.setItem(settingsKey, enabled ? 'on' : 'off');
|
|
188
|
+
publish({ enabled });
|
|
189
|
+
attempted = undefined;
|
|
190
|
+
if (enabled) return connect(true);
|
|
191
|
+
await perform('stop');
|
|
192
|
+
}
|
|
193
|
+
async function runAction(command) {
|
|
194
|
+
if (!snapshot.linkedId || snapshot.phase !== 'connected' || snapshot.actionBusy) return;
|
|
195
|
+
publish({ actionBusy: command, actionMessage: null, actionError: null });
|
|
196
|
+
try {
|
|
197
|
+
const relaunch = command === 'restart' || command === 'reset';
|
|
198
|
+
const result = await request(relaunch
|
|
199
|
+
? { action: 'relaunch', command, sessionId: snapshot.linkedId }
|
|
200
|
+
: { action: 'control', command }, lifetime.signal);
|
|
201
|
+
publish({ ...connection(result), actionMessage: {
|
|
202
|
+
terminal: '核心终端已打开',
|
|
203
|
+
restart: '小鲸鱼已重启并重新接入',
|
|
204
|
+
reset: '初始化已完成并重新接入',
|
|
205
|
+
about: '关于窗口已打开',
|
|
206
|
+
license: '使用引导与 Pro 已打开',
|
|
207
|
+
quit: '小鲸鱼正在退出',
|
|
208
|
+
}[command] || '操作已完成' });
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (!lifetime.signal.aborted) publish({ actionError: error.message || '桌面操作失败' });
|
|
211
|
+
} finally {
|
|
212
|
+
if (!lifetime.signal.aborted) publish({ actionBusy: null });
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
let updateAttempted = false;
|
|
216
|
+
async function runUpdate(manual = false) {
|
|
217
|
+
if (snapshot.updateBusy || (!manual && updateAttempted)) return;
|
|
218
|
+
updateAttempted = true;
|
|
219
|
+
publish({ updateBusy: true, updateError: null });
|
|
220
|
+
try {
|
|
221
|
+
const result = await request({ action: 'check-update' }, lifetime.signal);
|
|
222
|
+
publish({ updateSource: result.updateSource || snapshot.updateSource, updateInfo: result.update });
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if (!lifetime.signal.aborted) publish({ updateError: error.message || '检查更新失败' });
|
|
225
|
+
} finally {
|
|
226
|
+
if (!lifetime.signal.aborted) publish({ updateBusy: false });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async function downloadLatest() {
|
|
230
|
+
if (snapshot.updateBusy || !snapshot.updateInfo?.available) return;
|
|
231
|
+
publish({ updateBusy: true, updateError: null });
|
|
232
|
+
try {
|
|
233
|
+
const result = await request({ action: 'download-update' }, lifetime.signal);
|
|
234
|
+
publish({ updateInfo: result.update });
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (!lifetime.signal.aborted) publish({ updateError: error.message || '下载更新失败' });
|
|
237
|
+
} finally {
|
|
238
|
+
if (!lifetime.signal.aborted) publish({ updateBusy: false });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const sync = () => { void connect(); };
|
|
242
|
+
const onPreference = event => {
|
|
243
|
+
if (event.key !== settingsKey) return;
|
|
244
|
+
attempted = undefined;
|
|
245
|
+
publish({ enabled: event.newValue !== 'off' });
|
|
246
|
+
sync();
|
|
247
|
+
};
|
|
248
|
+
ctx.effect(() => {
|
|
249
|
+
const unsubscribe = active.subscribe(sync);
|
|
250
|
+
window.addEventListener('focus', sync);
|
|
251
|
+
window.addEventListener('storage', onPreference);
|
|
252
|
+
document.addEventListener('visibilitychange', sync);
|
|
253
|
+
sync();
|
|
254
|
+
return () => {
|
|
255
|
+
lifetime.abort();
|
|
256
|
+
unsubscribe();
|
|
257
|
+
window.removeEventListener('focus', sync);
|
|
258
|
+
window.removeEventListener('storage', onPreference);
|
|
259
|
+
document.removeEventListener('visibilitychange', sync);
|
|
260
|
+
};
|
|
261
|
+
}, 'xiaojingyuai: current session');
|
|
262
|
+
|
|
263
|
+
function Settings() {
|
|
264
|
+
const state = useSyncExternalStore(subscribe, () => snapshot);
|
|
265
|
+
const preferenceId = useId();
|
|
266
|
+
const [confirmReset, setConfirmReset] = useState(false);
|
|
267
|
+
useEffect(() => {
|
|
268
|
+
let mounted = true;
|
|
269
|
+
async function refresh() {
|
|
270
|
+
if (snapshot.busy || snapshot.actionBusy) return;
|
|
271
|
+
const turn = currentRequest;
|
|
272
|
+
try {
|
|
273
|
+
const result = await request(undefined, lifetime.signal);
|
|
274
|
+
if (mounted && turn === currentRequest && !snapshot.busy && !snapshot.actionBusy) {
|
|
275
|
+
publish({
|
|
276
|
+
...connection(result),
|
|
277
|
+
updateSource: result.updateSource || snapshot.updateSource,
|
|
278
|
+
error: result.phase === 'connected' ? null : snapshot.error,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
} catch { /* Keep the launch error visible and allow the user to retry. */ }
|
|
282
|
+
}
|
|
283
|
+
void refresh();
|
|
284
|
+
const timer = setInterval(refresh, 2000);
|
|
285
|
+
return () => { mounted = false; clearInterval(timer); };
|
|
286
|
+
}, []);
|
|
287
|
+
useEffect(() => { void runUpdate(); }, []);
|
|
288
|
+
const current = state.phase === 'connected' && state.linkedId === state.selectedId && !!state.selectedId;
|
|
289
|
+
const other = state.phase === 'connected' && state.selectedId && !current;
|
|
290
|
+
const [label, tone] = state.error ? ['接入失败', 'error'] : other ? ['已接入其他会话', 'neutral'] : phases[state.phase];
|
|
291
|
+
const canConnect = !!state.selectedId && !current;
|
|
292
|
+
const note = state.error || (!state.selectedId && state.phase !== 'connected' ? '打开一个 DSH 会话后即可接入。' : '');
|
|
293
|
+
const controlsReady = state.phase === 'connected' && !!state.linkedId;
|
|
294
|
+
const currentVersion = state.updateSource?.currentVersion ? 'v' + state.updateSource.currentVersion : '';
|
|
295
|
+
const [updateLabel, updateTone] = state.updateBusy
|
|
296
|
+
? ['检查中', 'pending']
|
|
297
|
+
: state.updateError ? ['检查失败', 'error']
|
|
298
|
+
: state.updateInfo?.available ? ['发现新版本', 'pending']
|
|
299
|
+
: state.updateInfo ? ['已是最新', 'success'] : ['待检查', 'neutral'];
|
|
300
|
+
const actions = [
|
|
301
|
+
{ id: 'terminal', title: '打开核心终端', note: '打开语音终端与小鲸鱼应用设置。', button: '打开' },
|
|
302
|
+
{ id: 'restart', title: '重启小鲸鱼', note: '重新启动桌面程序并保持当前会话接入。', button: '重启' },
|
|
303
|
+
{ id: 'reset', title: '初始化', note: '清除本地设置和自定义唤醒词后重新接入,账号不受影响。', button: '初始化', danger: true },
|
|
304
|
+
{ id: 'about', title: '关于一只小鲸鱼AI', note: '查看桌面运行时版本与版权信息。', button: '查看' },
|
|
305
|
+
{ id: 'license', title: '使用引导与 Pro', note: '打开账号登录、使用引导和订阅信息。', button: '打开' },
|
|
306
|
+
{ id: 'quit', title: '退出小鲸鱼', note: '结束桌面程序,DeepSeek Harness 保持运行。', button: '退出', danger: true },
|
|
307
|
+
];
|
|
308
|
+
const activate = id => {
|
|
309
|
+
if (id === 'reset') {
|
|
310
|
+
setConfirmReset(true);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
void runAction(id);
|
|
314
|
+
};
|
|
315
|
+
return h('section', { className: 'xjy-settings', 'aria-label': '小鲸鱼会话设置' },
|
|
316
|
+
h('style', null, settingsStyle),
|
|
317
|
+
h('div', { className: 'xjy-settings__card' },
|
|
318
|
+
h('div', { className: 'xjy-settings__row' },
|
|
319
|
+
h('h3', { className: 'xjy-settings__title' }, '会话连接'),
|
|
320
|
+
h('span', { className: 'xjy-settings__status', role: 'status', 'data-tone': tone }, label)),
|
|
321
|
+
h('div', { className: 'xjy-settings__row' },
|
|
322
|
+
h('div', null,
|
|
323
|
+
h('p', { className: 'xjy-settings__title', id: preferenceId }, '自动接入'),
|
|
324
|
+
h('p', { className: 'xjy-settings__note', id: preferenceId + '-hint' }, '随当前 DSH 会话启动并连接小鲸鱼')),
|
|
325
|
+
h('button', {
|
|
326
|
+
className: 'xjy-settings__switch', type: 'button', role: 'switch', 'aria-checked': state.enabled,
|
|
327
|
+
'aria-labelledby': preferenceId, 'aria-describedby': preferenceId + '-hint', onClick: toggle,
|
|
328
|
+
})),
|
|
329
|
+
(note || canConnect) ? h('div', { className: 'xjy-settings__row xjy-settings__footer' },
|
|
330
|
+
note ? h('p', { className: 'xjy-settings__note' + (state.error ? ' xjy-settings__note--error' : ''), role: state.error ? 'alert' : undefined }, note) : null,
|
|
331
|
+
canConnect ? h('button', {
|
|
332
|
+
className: 'xjy-settings__action', type: 'button', disabled: state.busy, onClick: () => connect(true),
|
|
333
|
+
}, state.error ? '重试接入' : '接入当前会话') : null) : null,
|
|
334
|
+
h('div', { className: 'xjy-settings__row xjy-settings__heading' },
|
|
335
|
+
h('div', null,
|
|
336
|
+
h('h3', { className: 'xjy-settings__title' }, '桌面控制'),
|
|
337
|
+
h('p', { className: 'xjy-settings__note' }, controlsReady ? '原桌面托盘功能已迁入此处。' : '接入小鲸鱼后可操作。'))),
|
|
338
|
+
...actions.map(action => h('div', { className: 'xjy-settings__row', key: action.id },
|
|
339
|
+
h('div', null,
|
|
340
|
+
h('p', { className: 'xjy-settings__title' }, action.title),
|
|
341
|
+
h('p', { className: 'xjy-settings__note' }, action.note)),
|
|
342
|
+
h('button', {
|
|
343
|
+
className: 'xjy-settings__action' + (action.danger ? ' xjy-settings__action--danger' : ''),
|
|
344
|
+
type: 'button',
|
|
345
|
+
disabled: !controlsReady || !!state.actionBusy,
|
|
346
|
+
onClick: () => activate(action.id),
|
|
347
|
+
}, state.actionBusy === action.id ? '处理中' : action.button))),
|
|
348
|
+
confirmReset ? h('div', { className: 'xjy-settings__row xjy-settings__footer xjy-settings__confirm', role: 'alert' },
|
|
349
|
+
h('p', { className: 'xjy-settings__note' }, '确认清除本地设置并重新接入?'),
|
|
350
|
+
h('div', { className: 'xjy-settings__actions' },
|
|
351
|
+
h('button', { className: 'xjy-settings__action', type: 'button', onClick: () => setConfirmReset(false) }, '取消'),
|
|
352
|
+
h('button', {
|
|
353
|
+
className: 'xjy-settings__action xjy-settings__action--danger', type: 'button',
|
|
354
|
+
disabled: !!state.actionBusy,
|
|
355
|
+
onClick: () => { setConfirmReset(false); void runAction('reset'); },
|
|
356
|
+
}, '确认初始化'))) : null,
|
|
357
|
+
(state.actionMessage || state.actionError) ? h('div', {
|
|
358
|
+
className: 'xjy-settings__row xjy-settings__footer',
|
|
359
|
+
}, h('p', {
|
|
360
|
+
className: 'xjy-settings__note' + (state.actionError ? ' xjy-settings__note--error' : ''),
|
|
361
|
+
role: state.actionError ? 'alert' : 'status',
|
|
362
|
+
'aria-live': 'polite',
|
|
363
|
+
}, state.actionError || state.actionMessage)) : null),
|
|
364
|
+
h('div', { className: 'xjy-settings__card' },
|
|
365
|
+
h('div', { className: 'xjy-settings__row' },
|
|
366
|
+
h('h3', { className: 'xjy-settings__title' }, '插件更新 ' + currentVersion),
|
|
367
|
+
h('span', { className: 'xjy-settings__status', role: 'status', 'data-tone': updateTone }, updateLabel)),
|
|
368
|
+
h('div', { className: 'xjy-settings__row' },
|
|
369
|
+
h('div', null,
|
|
370
|
+
h('p', { className: 'xjy-settings__title' }, '更新源'),
|
|
371
|
+
h('p', { className: 'xjy-settings__note' }, state.updateSource?.manifestUrl || '小鲸鱼 OSS')),
|
|
372
|
+
h('button', {
|
|
373
|
+
className: 'xjy-settings__action', type: 'button', disabled: state.updateBusy,
|
|
374
|
+
onClick: () => { updateAttempted = false; void runUpdate(true); },
|
|
375
|
+
}, state.updateBusy ? '检查中' : '检查更新')),
|
|
376
|
+
state.updateError ? h('div', { className: 'xjy-settings__row xjy-settings__footer' },
|
|
377
|
+
h('p', { className: 'xjy-settings__note xjy-settings__note--error', role: 'alert' }, state.updateError)) : null,
|
|
378
|
+
state.updateInfo?.available ? h('div', { className: 'xjy-settings__row' },
|
|
379
|
+
h('div', null,
|
|
380
|
+
h('p', { className: 'xjy-settings__title' }, '新版本 v' + state.updateInfo.latestVersion),
|
|
381
|
+
h('p', { className: 'xjy-settings__note' }, state.updateInfo.notes || '可从小鲸鱼 OSS 下载并校验更新包。')),
|
|
382
|
+
h('button', {
|
|
383
|
+
className: 'xjy-settings__action', type: 'button', disabled: state.updateBusy,
|
|
384
|
+
onClick: downloadLatest,
|
|
385
|
+
}, state.updateInfo.file ? '重新下载' : '下载更新包')) : null,
|
|
386
|
+
state.updateInfo?.file ? h('div', { className: 'xjy-settings__row' },
|
|
387
|
+
h('div', null,
|
|
388
|
+
h('p', { className: 'xjy-settings__title' }, '更新包已校验'),
|
|
389
|
+
h('p', { className: 'xjy-settings__note' }, state.updateInfo.file),
|
|
390
|
+
h('p', { className: 'xjy-settings__note' }, '在 DSH「插件」中移除旧版后导入此包。'))) : null));
|
|
391
|
+
}
|
|
392
|
+
ctx.slots.inject('settings.section', () => ctx.slots.register({
|
|
393
|
+
name: 'settings.section', id: 'xiaojingyuai', order: 35, label: () => '一只小鲸鱼AI',
|
|
394
|
+
}, Settings));
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
},
|
|
398
|
+
});
|
package/companion.mjs
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { createServer } from 'node:http';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { prepareRuntime } from './runtime.mjs';
|
|
7
|
+
import sessionIds from './session-id.cjs';
|
|
8
|
+
|
|
9
|
+
const { isDshPluginSessionId } = sessionIds;
|
|
10
|
+
|
|
11
|
+
const COMMAND_ACTIONS = new Set(['terminal', 'about', 'license', 'quit', 'restart', 'reset']);
|
|
12
|
+
const COMMAND_TTL_MS = 15000;
|
|
13
|
+
|
|
14
|
+
async function readJson(req, limit = 1024) {
|
|
15
|
+
let body = '';
|
|
16
|
+
for await (const chunk of req) {
|
|
17
|
+
body += chunk;
|
|
18
|
+
if (body.length > limit) throw new Error('Invalid request');
|
|
19
|
+
}
|
|
20
|
+
return JSON.parse(body);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function startCompanionBridge(makeBinding, options = {}) {
|
|
24
|
+
const env = options.env || process.env;
|
|
25
|
+
const spawnProcess = options.spawn || spawn;
|
|
26
|
+
const prepare = options.prepare || prepareRuntime;
|
|
27
|
+
const lifetime = new AbortController();
|
|
28
|
+
let activation = new AbortController();
|
|
29
|
+
const token = randomBytes(32).toString('hex');
|
|
30
|
+
const bearer = Buffer.from('Bearer ' + token);
|
|
31
|
+
let running;
|
|
32
|
+
let binding;
|
|
33
|
+
let acknowledged;
|
|
34
|
+
let pending;
|
|
35
|
+
let queue = Promise.resolve();
|
|
36
|
+
let phase = 'idle';
|
|
37
|
+
let commandQueue = [];
|
|
38
|
+
let currentCommand = null;
|
|
39
|
+
const commandWaiters = new Map();
|
|
40
|
+
|
|
41
|
+
const sanitizedEnv = { ...env };
|
|
42
|
+
for (const name of Object.keys(sanitizedEnv)) {
|
|
43
|
+
if (/^(DSH_|DEEPSEEK_)|(?:API_?KEY|SECRET|ACCESS_TOKEN|AUTH_TOKEN|PASSWORD)$|^(?:ELECTRON_RUN_AS_NODE|NODE_OPTIONS)$/i.test(name)) {
|
|
44
|
+
delete sanitizedEnv[name];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const server = createServer(async (req, res) => {
|
|
49
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
50
|
+
const actual = Buffer.from(req.headers.authorization || '');
|
|
51
|
+
if (req.headers.host !== host || actual.length !== bearer.length || !timingSafeEqual(actual, bearer)) {
|
|
52
|
+
return res.writeHead(403).end();
|
|
53
|
+
}
|
|
54
|
+
if (!binding) return res.writeHead(409).end();
|
|
55
|
+
if (req.method === 'GET' && req.url === '/connection') {
|
|
56
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
57
|
+
return res.end(JSON.stringify(binding));
|
|
58
|
+
}
|
|
59
|
+
if (req.method === 'POST' && req.url === '/connection/ack') {
|
|
60
|
+
try {
|
|
61
|
+
const { requestId } = await readJson(req);
|
|
62
|
+
if (typeof requestId !== 'string' || requestId !== binding?.requestId) return res.writeHead(409).end();
|
|
63
|
+
acknowledged = requestId;
|
|
64
|
+
phase = 'connected';
|
|
65
|
+
return res.writeHead(204).end();
|
|
66
|
+
} catch {
|
|
67
|
+
return res.writeHead(400).end();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (req.method === 'GET' && req.url === '/connection/command') {
|
|
71
|
+
const command = takeCommand();
|
|
72
|
+
if (!command) return res.writeHead(204).end();
|
|
73
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
74
|
+
return res.end(JSON.stringify({ id: command.id, action: command.action }));
|
|
75
|
+
}
|
|
76
|
+
if (req.method === 'POST' && req.url === '/connection/command/ack') {
|
|
77
|
+
try {
|
|
78
|
+
const { id } = await readJson(req);
|
|
79
|
+
if (typeof id !== 'string' || id !== currentCommand?.id) return res.writeHead(409).end();
|
|
80
|
+
settleCommand(id);
|
|
81
|
+
currentCommand = null;
|
|
82
|
+
return res.writeHead(204).end();
|
|
83
|
+
} catch {
|
|
84
|
+
return res.writeHead(400).end();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
res.writeHead(404).end();
|
|
88
|
+
});
|
|
89
|
+
server.requestTimeout = 5000;
|
|
90
|
+
await new Promise((resolve, reject) => {
|
|
91
|
+
server.once('error', reject);
|
|
92
|
+
server.listen(0, '127.0.0.1', resolve);
|
|
93
|
+
});
|
|
94
|
+
const host = '127.0.0.1:' + server.address().port;
|
|
95
|
+
server.unref();
|
|
96
|
+
|
|
97
|
+
function rejectCommandWaiters(error) {
|
|
98
|
+
for (const waiter of [...commandWaiters.values()]) waiter.finish(error);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function settleCommand(id) {
|
|
102
|
+
const waiter = commandWaiters.get(id);
|
|
103
|
+
if (!waiter) return;
|
|
104
|
+
waiter.finish();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function takeCommand() {
|
|
108
|
+
if (currentCommand && Date.now() - currentCommand.issuedAt >= COMMAND_TTL_MS) {
|
|
109
|
+
const staleId = currentCommand.id;
|
|
110
|
+
currentCommand = null;
|
|
111
|
+
const waiter = commandWaiters.get(staleId);
|
|
112
|
+
waiter?.finish(new Error('小鲸鱼未响应桌面操作,请重试'));
|
|
113
|
+
}
|
|
114
|
+
if (!currentCommand) currentCommand = commandQueue.shift() || null;
|
|
115
|
+
return currentCommand;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function queueCommand(action) {
|
|
119
|
+
if (!COMMAND_ACTIONS.has(action)) throw new Error('不支持的桌面操作');
|
|
120
|
+
if (phase !== 'connected' || !running || !binding) throw new Error('请先接入小鲸鱼');
|
|
121
|
+
if (commandQueue.length >= 16) throw new Error('桌面操作排队过多,请稍后重试');
|
|
122
|
+
const command = { id: randomBytes(16).toString('hex'), action, issuedAt: Date.now() };
|
|
123
|
+
commandQueue.push(command);
|
|
124
|
+
return command;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function waitForCommand(id, signal, timeoutMs = 5000) {
|
|
128
|
+
signal ||= new AbortController().signal;
|
|
129
|
+
signal.throwIfAborted();
|
|
130
|
+
return new Promise((resolve, reject) => {
|
|
131
|
+
const abort = () => finish(new Error('桌面操作已取消'));
|
|
132
|
+
const finish = error => {
|
|
133
|
+
const waiter = commandWaiters.get(id);
|
|
134
|
+
if (!waiter) return;
|
|
135
|
+
commandWaiters.delete(id);
|
|
136
|
+
clearTimeout(waiter.timer);
|
|
137
|
+
signal.removeEventListener('abort', abort);
|
|
138
|
+
if (error) reject(error); else resolve();
|
|
139
|
+
};
|
|
140
|
+
const timer = setTimeout(() => finish(new Error('小鲸鱼未响应桌面操作,请重试')), timeoutMs);
|
|
141
|
+
commandWaiters.set(id, { resolve, reject, timer, abort, finish });
|
|
142
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function enqueueControl(fn) {
|
|
147
|
+
const job = queue.catch(() => {}).then(fn);
|
|
148
|
+
queue = job;
|
|
149
|
+
return job;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function bridgeSignal(signal) {
|
|
153
|
+
const signals = [lifetime.signal, activation.signal];
|
|
154
|
+
if (signal) signals.push(signal);
|
|
155
|
+
return AbortSignal.any(signals);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function connect(sessionId, signal) {
|
|
159
|
+
signal ||= bridgeSignal();
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
if (running && binding?.sessionId === sessionId && acknowledged === binding.requestId) return;
|
|
162
|
+
if (!env.APPDATA || !path.isAbsolute(env.APPDATA)) throw new Error('找不到 Windows 用户数据目录');
|
|
163
|
+
if (running && !binding) {
|
|
164
|
+
const until = Date.now() + 8000;
|
|
165
|
+
while (running && Date.now() < until) await delay(150, undefined, { signal });
|
|
166
|
+
if (running) throw new Error('小鲸鱼正在退出,请稍后重试');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (!running) {
|
|
170
|
+
phase = 'preparing';
|
|
171
|
+
const executable = await prepare(env, signal);
|
|
172
|
+
signal.throwIfAborted();
|
|
173
|
+
phase = 'starting';
|
|
174
|
+
binding = { ...makeBinding(sessionId), requestId: randomBytes(16).toString('hex') };
|
|
175
|
+
acknowledged = undefined;
|
|
176
|
+
const child = spawnProcess(executable, [], {
|
|
177
|
+
cwd: path.dirname(executable), windowsHide: false, stdio: 'ignore',
|
|
178
|
+
env: {
|
|
179
|
+
...sanitizedEnv,
|
|
180
|
+
XIAOJINGYU_USER_DATA_DIR: path.join(env.APPDATA, 'XiaojingyuAI', 'HarnessCompanion'),
|
|
181
|
+
XIAOJINGYU_DSH_PLUGIN_ENDPOINT: 'http://' + host + '/connection',
|
|
182
|
+
XIAOJINGYU_DSH_PLUGIN_TOKEN: token,
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
running = child;
|
|
186
|
+
const onExit = () => {
|
|
187
|
+
if (running !== child) return;
|
|
188
|
+
running = binding = acknowledged = undefined;
|
|
189
|
+
commandQueue = [];
|
|
190
|
+
currentCommand = null;
|
|
191
|
+
rejectCommandWaiters(new Error('小鲸鱼已退出'));
|
|
192
|
+
phase = 'idle';
|
|
193
|
+
};
|
|
194
|
+
child.once('error', onExit);
|
|
195
|
+
child.once('exit', onExit);
|
|
196
|
+
child.unref?.();
|
|
197
|
+
} else if (binding?.sessionId !== sessionId) {
|
|
198
|
+
binding = { ...makeBinding(sessionId), requestId: randomBytes(16).toString('hex') };
|
|
199
|
+
phase = 'starting';
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const requestId = binding.requestId;
|
|
203
|
+
const until = Date.now() + (options.readyTimeoutMs || 35000);
|
|
204
|
+
while (acknowledged !== requestId && Date.now() < until) {
|
|
205
|
+
if (!running) throw new Error('小鲸鱼启动后退出,请检查桌面提示或关闭旧版小鲸鱼后重试');
|
|
206
|
+
await delay(150, undefined, { signal });
|
|
207
|
+
}
|
|
208
|
+
if (acknowledged !== requestId) throw new Error('桌面程序尚未确认接入,请查看桌面后重试');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
connect(sessionId, signal) {
|
|
213
|
+
if (!isDshPluginSessionId(sessionId)) return Promise.reject(new Error('请先在 DSH 中打开普通会话'));
|
|
214
|
+
if (pending?.sessionId === sessionId) return pending.promise;
|
|
215
|
+
const combined = bridgeSignal(signal);
|
|
216
|
+
const job = { sessionId };
|
|
217
|
+
job.promise = queue.catch(() => {}).then(() => connect(sessionId, combined)).catch(error => {
|
|
218
|
+
if (!running) {
|
|
219
|
+
binding = acknowledged = undefined;
|
|
220
|
+
phase = 'idle';
|
|
221
|
+
}
|
|
222
|
+
throw error;
|
|
223
|
+
}).finally(() => { if (pending === job) pending = undefined; });
|
|
224
|
+
queue = job.promise;
|
|
225
|
+
pending = job;
|
|
226
|
+
return job.promise;
|
|
227
|
+
},
|
|
228
|
+
status() { return { phase, sessionId: binding?.sessionId || null }; },
|
|
229
|
+
control(action, signal) {
|
|
230
|
+
const combined = bridgeSignal(signal);
|
|
231
|
+
return enqueueControl(async () => {
|
|
232
|
+
const command = queueCommand(action);
|
|
233
|
+
await waitForCommand(command.id, combined);
|
|
234
|
+
return { ok: true, action };
|
|
235
|
+
});
|
|
236
|
+
},
|
|
237
|
+
relaunch(action, sessionId, signal) {
|
|
238
|
+
if ((action !== 'restart' && action !== 'reset') || !isDshPluginSessionId(sessionId)) {
|
|
239
|
+
return Promise.reject(new Error('请先在 DSH 中打开普通会话'));
|
|
240
|
+
}
|
|
241
|
+
const combined = bridgeSignal(signal);
|
|
242
|
+
return enqueueControl(async () => {
|
|
243
|
+
const command = queueCommand(action);
|
|
244
|
+
await waitForCommand(command.id, combined);
|
|
245
|
+
const until = Date.now() + 10000;
|
|
246
|
+
while (running && Date.now() < until) await delay(150, undefined, { signal: combined });
|
|
247
|
+
if (running) throw new Error('小鲸鱼未能退出,请稍后重试');
|
|
248
|
+
await connect(sessionId, combined);
|
|
249
|
+
return { ok: true, action };
|
|
250
|
+
});
|
|
251
|
+
},
|
|
252
|
+
stop() {
|
|
253
|
+
activation.abort();
|
|
254
|
+
activation = new AbortController();
|
|
255
|
+
pending = binding = acknowledged = undefined;
|
|
256
|
+
commandQueue = [];
|
|
257
|
+
currentCommand = null;
|
|
258
|
+
rejectCommandWaiters(new Error('小鲸鱼连接已关闭'));
|
|
259
|
+
phase = running ? 'stopping' : 'idle';
|
|
260
|
+
},
|
|
261
|
+
close() {
|
|
262
|
+
lifetime.abort();
|
|
263
|
+
binding = acknowledged = undefined;
|
|
264
|
+
commandQueue = [];
|
|
265
|
+
currentCommand = null;
|
|
266
|
+
rejectCommandWaiters(new Error('小鲸鱼连接已关闭'));
|
|
267
|
+
server.close();
|
|
268
|
+
server.closeAllConnections();
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
package/cordis.patch.yml
ADDED
package/index.mjs
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
2
|
+
import { startCompanionBridge } from './companion.mjs';
|
|
3
|
+
import { CURRENT_VERSION, UPDATE_MANIFEST_URL, checkForUpdate, downloadUpdate } from './update.mjs';
|
|
4
|
+
|
|
5
|
+
export const name = 'xiaojingyuai';
|
|
6
|
+
export const inject = ['tools', 'webServer', 'connection', 'sessions'];
|
|
7
|
+
|
|
8
|
+
const CONTROL_PATH = '/api/xiaojingyu/companion';
|
|
9
|
+
const loopback = /^(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/i;
|
|
10
|
+
const CONTROLS = new Set(['terminal', 'about', 'license', 'quit']);
|
|
11
|
+
const RELAUNCH = new Set(['restart', 'reset']);
|
|
12
|
+
|
|
13
|
+
export async function apply(ctx) {
|
|
14
|
+
const tool = defineTool({
|
|
15
|
+
name: 'xiaojingyu_connect',
|
|
16
|
+
description: '用户要求打开或连接小鲸鱼时,自动启动本机小鲸鱼桌面程序并接入当前 DSH 会话。首次启动时自动准备应用运行时。',
|
|
17
|
+
parameters: {},
|
|
18
|
+
timeoutMs: 360000,
|
|
19
|
+
output: {
|
|
20
|
+
schema: {
|
|
21
|
+
type: 'object',
|
|
22
|
+
additionalProperties: false,
|
|
23
|
+
properties: { message: { type: 'string', required: true } },
|
|
24
|
+
},
|
|
25
|
+
render: (_args, value) => [{ type: 'text', text: value.message }],
|
|
26
|
+
},
|
|
27
|
+
async execute(_args, execution) {
|
|
28
|
+
await bridge.connect(execution.agent?.session?.id, execution.signal);
|
|
29
|
+
return { message: '小鲸鱼桌面程序已确认接入当前 DSH 会话。首次使用请在小鲸鱼窗口完成隐私确认、账号登录和语音设备设置。' };
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
const bridge = await startCompanionBridge(sessionId => ({
|
|
33
|
+
sessionId,
|
|
34
|
+
readyUrl: ctx.connection.authenticatedUrl(ctx.webServer.protocol + '//127.0.0.1:' + ctx.webServer.port),
|
|
35
|
+
}));
|
|
36
|
+
ctx.on('dispose', () => bridge.close());
|
|
37
|
+
ctx.connection.fetch.register({
|
|
38
|
+
path: CONTROL_PATH,
|
|
39
|
+
methods: ['GET', 'POST'],
|
|
40
|
+
requestBody: 'buffered',
|
|
41
|
+
async fetch(request) {
|
|
42
|
+
const host = request.headers.get('host');
|
|
43
|
+
if (!loopback.test(host || '')) return new Response('forbidden', { status: 403 });
|
|
44
|
+
const respond = (data, status = 200) => Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } });
|
|
45
|
+
const updateSource = { currentVersion: CURRENT_VERSION, manifestUrl: UPDATE_MANIFEST_URL };
|
|
46
|
+
if (request.method === 'GET') return respond({ ...bridge.status(), updateSource });
|
|
47
|
+
if (!request.headers.get('content-type')?.startsWith('application/json')) return respond({ error: '无效请求' }, 415);
|
|
48
|
+
try {
|
|
49
|
+
const { action, sessionId, command } = await request.json();
|
|
50
|
+
if (action === 'stop') bridge.stop();
|
|
51
|
+
else if (action === 'check-update') {
|
|
52
|
+
const update = await checkForUpdate({ signal: request.signal });
|
|
53
|
+
return respond({ ...bridge.status(), update });
|
|
54
|
+
} else if (action === 'download-update') {
|
|
55
|
+
const update = await downloadUpdate({ signal: request.signal });
|
|
56
|
+
return respond({ ...bridge.status(), update });
|
|
57
|
+
}
|
|
58
|
+
else if (action === 'control' && CONTROLS.has(command)) {
|
|
59
|
+
await bridge.control(command, request.signal);
|
|
60
|
+
} else if (action === 'relaunch' && RELAUNCH.has(command)
|
|
61
|
+
&& typeof sessionId === 'string' && ctx.sessions.get(sessionId)) {
|
|
62
|
+
await bridge.relaunch(command, sessionId, request.signal);
|
|
63
|
+
}
|
|
64
|
+
else if (action === 'connect' && typeof sessionId === 'string' && ctx.sessions.get(sessionId)) {
|
|
65
|
+
await bridge.connect(sessionId, request.signal);
|
|
66
|
+
} else return respond({ error: '请在 DSH 中打开普通会话' }, 400);
|
|
67
|
+
return respond(bridge.status());
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return respond({ error: error.message || '小鲸鱼启动失败' }, 409);
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
ctx.tools.register(tool);
|
|
74
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xiaojingyuai/dsh",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "一只小鲸鱼AI DeepSeek Harness 插件",
|
|
5
|
+
"private": false,
|
|
6
|
+
"license": "UNLICENSED",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./index.mjs",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./index.mjs",
|
|
11
|
+
"./client": "./client.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"index.mjs",
|
|
15
|
+
"companion.mjs",
|
|
16
|
+
"runtime.mjs",
|
|
17
|
+
"client.js",
|
|
18
|
+
"update.mjs",
|
|
19
|
+
"session-id.cjs",
|
|
20
|
+
"cordis.patch.yml",
|
|
21
|
+
"README.md",
|
|
22
|
+
"payload/**"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public",
|
|
26
|
+
"registry": "https://registry.npmjs.org/"
|
|
27
|
+
},
|
|
28
|
+
"dsh": {
|
|
29
|
+
"client": { "platform": "web" },
|
|
30
|
+
"bundle": {
|
|
31
|
+
"patch": "./cordis.patch.yml"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
package/runtime.mjs
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createHash, verify } from 'node:crypto';
|
|
3
|
+
import { createReadStream, createWriteStream } from 'node:fs';
|
|
4
|
+
import fs from 'node:fs/promises';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { Readable, Transform } from 'node:stream';
|
|
8
|
+
import { pipeline } from 'node:stream/promises';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { promisify } from 'node:util';
|
|
11
|
+
import { UPDATE_PUBLIC_KEY } from './update.mjs';
|
|
12
|
+
|
|
13
|
+
const exec = promisify(execFile);
|
|
14
|
+
const rawFs = process.versions.electron ? createRequire(import.meta.url)('original-fs').promises : fs;
|
|
15
|
+
const EXE = '一只小鲸鱼AI.exe';
|
|
16
|
+
const ASAR = path.join('resources', 'app.asar');
|
|
17
|
+
const PYTHON = path.join('resources', 'app.asar.unpacked', 'runtime', 'python', '一只小鲸鱼-语音.exe');
|
|
18
|
+
const FILES = [EXE, ASAR, PYTHON];
|
|
19
|
+
const bundledArchive = fileURLToPath(new URL('./payload/runtime.7z', import.meta.url));
|
|
20
|
+
const bundledMetadata = fileURLToPath(new URL('./payload/runtime.json', import.meta.url));
|
|
21
|
+
const REMOTE_MANIFEST_URL = 'https://dafeiyu-download.oss-cn-beijing.aliyuncs.com/updates/plugins/dsh/runtime/manifest.json';
|
|
22
|
+
const REMOTE_ORIGIN = 'https://dafeiyu-download.oss-cn-beijing.aliyuncs.com';
|
|
23
|
+
const REMOTE_PREFIX = '/updates/plugins/dsh/runtime/';
|
|
24
|
+
|
|
25
|
+
async function existsFile(file) {
|
|
26
|
+
try {
|
|
27
|
+
return (await fs.lstat(file)).isFile();
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function validRuntime(dir, manifest) {
|
|
34
|
+
try {
|
|
35
|
+
if (!(await fs.lstat(dir)).isDirectory()) return false;
|
|
36
|
+
return (await Promise.all(FILES.map(async name => {
|
|
37
|
+
const file = await rawFs.lstat(path.join(dir, name));
|
|
38
|
+
return file.isFile() && file.size === manifest.sizes[name.replaceAll('\\', '/')];
|
|
39
|
+
}))).every(Boolean);
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function sha256File(file) {
|
|
46
|
+
const hash = createHash('sha256');
|
|
47
|
+
for await (const chunk of createReadStream(file)) hash.update(chunk);
|
|
48
|
+
return hash.digest('hex');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function verifyArchive(file, expected) {
|
|
52
|
+
if (await sha256File(file) !== expected) throw new Error('小鲸鱼运行时校验失败,请重新安装插件');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function normalizeManifest(value) {
|
|
56
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
57
|
+
|| value.schema !== 1 || value.name !== 'xiaojingyuai-dsh-runtime'
|
|
58
|
+
|| value.platform !== 'win32-x64' || !/^\d+\.\d+\.\d+$/.test(String(value.version || ''))
|
|
59
|
+
|| !/^[0-9a-f]{64}$/i.test(String(value.sha256 || '')) || !value.sizes) {
|
|
60
|
+
throw new Error('小鲸鱼运行时清单无效');
|
|
61
|
+
}
|
|
62
|
+
if (FILES.some(name => !(value.sizes[name.replaceAll('\\', '/')] > 0))) {
|
|
63
|
+
throw new Error('小鲸鱼运行时文件清单不完整');
|
|
64
|
+
}
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function bundledRuntimeSource() {
|
|
69
|
+
if (!(await existsFile(bundledArchive)) || !(await existsFile(bundledMetadata))) return null;
|
|
70
|
+
const raw = JSON.parse(await fs.readFile(bundledMetadata, 'utf8'));
|
|
71
|
+
const manifest = normalizeManifest(raw.schema === undefined ? {
|
|
72
|
+
...raw,
|
|
73
|
+
schema: 1,
|
|
74
|
+
name: 'xiaojingyuai-dsh-runtime',
|
|
75
|
+
version: '0.0.0',
|
|
76
|
+
platform: 'win32-x64',
|
|
77
|
+
} : raw);
|
|
78
|
+
return { archive: bundledArchive, manifest, remote: false };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function remoteRuntimePackage(value) {
|
|
82
|
+
let url;
|
|
83
|
+
try { url = new URL(value); } catch { throw new Error('小鲸鱼运行时下载地址无效'); }
|
|
84
|
+
if (url.protocol !== 'https:' || url.origin !== REMOTE_ORIGIN
|
|
85
|
+
|| url.username || url.password || url.search || url.hash
|
|
86
|
+
|| !url.pathname.startsWith(REMOTE_PREFIX) || !/^runtime-\d+\.\d+\.\d+\.7z$/.test(path.posix.basename(url.pathname))) {
|
|
87
|
+
throw new Error('小鲸鱼运行时下载地址不在允许的 OSS 目录');
|
|
88
|
+
}
|
|
89
|
+
return url;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function remoteRuntimeSource(signal) {
|
|
93
|
+
const response = await fetch(REMOTE_MANIFEST_URL, {
|
|
94
|
+
headers: { Accept: 'application/json' },
|
|
95
|
+
redirect: 'error',
|
|
96
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15000)]) : AbortSignal.timeout(15000),
|
|
97
|
+
});
|
|
98
|
+
if (!response.ok) throw new Error(`无法获取小鲸鱼运行时清单(HTTP ${response.status})`);
|
|
99
|
+
const text = await response.text();
|
|
100
|
+
if (Buffer.byteLength(text, 'utf8') > 65536) throw new Error('小鲸鱼运行时清单过大');
|
|
101
|
+
let data;
|
|
102
|
+
try { data = JSON.parse(text); } catch { throw new Error('小鲸鱼运行时清单格式无效'); }
|
|
103
|
+
if (!/^[0-9a-f]{128}$/i.test(String(data.signature || ''))) throw new Error('小鲸鱼运行时清单缺少签名');
|
|
104
|
+
const signed = { ...data };
|
|
105
|
+
delete signed.signature;
|
|
106
|
+
const valid = verify(
|
|
107
|
+
null,
|
|
108
|
+
Buffer.from(JSON.stringify(signed), 'utf8'),
|
|
109
|
+
{ key: Buffer.from(UPDATE_PUBLIC_KEY, 'hex'), format: 'der', type: 'spki' },
|
|
110
|
+
Buffer.from(data.signature, 'hex'),
|
|
111
|
+
);
|
|
112
|
+
if (!valid) throw new Error('小鲸鱼运行时清单签名校验失败');
|
|
113
|
+
const object = data.package;
|
|
114
|
+
if (!object || typeof object !== 'object' || Array.isArray(object)) throw new Error('小鲸鱼运行时包信息缺失');
|
|
115
|
+
const url = remoteRuntimePackage(object.url);
|
|
116
|
+
if (!Number.isSafeInteger(object.bytes) || object.bytes < 50 * 1024 * 1024 || object.bytes > 1024 * 1024 * 1024) {
|
|
117
|
+
throw new Error('小鲸鱼运行时包大小无效');
|
|
118
|
+
}
|
|
119
|
+
const manifest = normalizeManifest({ ...data, sha256: object.sha256, sizes: data.sizes });
|
|
120
|
+
return { archive: null, manifest, remote: true, url: url.href, bytes: object.bytes };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function resolveRuntimeSource(signal) {
|
|
124
|
+
return await bundledRuntimeSource() || await remoteRuntimeSource(signal);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function downloadRuntime(source, env, signal) {
|
|
128
|
+
const dir = path.join(env.LOCALAPPDATA, 'XiaojingyuAI', 'DSH', 'archives');
|
|
129
|
+
const file = path.join(dir, `runtime-${source.manifest.version}.7z`);
|
|
130
|
+
try {
|
|
131
|
+
if ((await fs.stat(file)).size === source.bytes && await sha256File(file) === source.manifest.sha256) return file;
|
|
132
|
+
} catch { /* Download a verified copy below. */ }
|
|
133
|
+
await fs.mkdir(dir, { recursive: true });
|
|
134
|
+
const timeout = AbortSignal.timeout(30 * 60 * 1000);
|
|
135
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
136
|
+
const response = await fetch(source.url, { redirect: 'error', signal: combined });
|
|
137
|
+
if (!response.ok || !response.body) throw new Error(`小鲸鱼运行时下载失败(HTTP ${response.status})`);
|
|
138
|
+
const length = Number(response.headers.get('content-length') || 0);
|
|
139
|
+
if (length && length !== source.bytes) throw new Error('小鲸鱼运行时下载大小不符');
|
|
140
|
+
const hash = createHash('sha256');
|
|
141
|
+
let received = 0;
|
|
142
|
+
const digest = new Transform({
|
|
143
|
+
transform(chunk, _encoding, callback) {
|
|
144
|
+
hash.update(chunk);
|
|
145
|
+
received += chunk.length;
|
|
146
|
+
callback(null, chunk);
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
try {
|
|
150
|
+
await fs.rm(file, { force: true });
|
|
151
|
+
await pipeline(Readable.fromWeb(response.body), digest, createWriteStream(file));
|
|
152
|
+
if (received !== source.bytes || hash.digest('hex') !== source.manifest.sha256) {
|
|
153
|
+
throw new Error('小鲸鱼运行时下载校验失败');
|
|
154
|
+
}
|
|
155
|
+
return file;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
await fs.rm(file, { force: true }).catch(() => {});
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export async function prepareRuntime(env, signal) {
|
|
163
|
+
if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('完整桌面组件需要 Windows x64 本机 DSH');
|
|
164
|
+
const local = env.LOCALAPPDATA;
|
|
165
|
+
if (!local || !path.isAbsolute(local)) throw new Error('找不到 Windows 用户缓存目录');
|
|
166
|
+
const source = await resolveRuntimeSource(signal);
|
|
167
|
+
const manifest = source.manifest;
|
|
168
|
+
|
|
169
|
+
const cache = path.join(local, 'XiaojingyuAI', 'DSH', 'r');
|
|
170
|
+
const target = path.join(cache, manifest.sha256.slice(0, 24));
|
|
171
|
+
if (await validRuntime(target, manifest)) return path.join(target, EXE);
|
|
172
|
+
|
|
173
|
+
const archive = source.remote ? await downloadRuntime(source, env, signal) : source.archive;
|
|
174
|
+
await verifyArchive(archive, manifest.sha256);
|
|
175
|
+
await fs.mkdir(cache, { recursive: true });
|
|
176
|
+
const stage = await fs.mkdtemp(path.join(cache, 'unpack-'));
|
|
177
|
+
try {
|
|
178
|
+
const payload = path.join(stage, 'runtime');
|
|
179
|
+
await fs.mkdir(payload);
|
|
180
|
+
const tar = path.join(env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe');
|
|
181
|
+
try {
|
|
182
|
+
await exec(tar, ['-xf', archive, '-C', payload], { signal, timeout: 240000, windowsHide: true });
|
|
183
|
+
} catch (error) {
|
|
184
|
+
signal?.throwIfAborted();
|
|
185
|
+
throw new Error('无法解包小鲸鱼运行时,请检查用户目录剩余空间后重试', { cause: error });
|
|
186
|
+
}
|
|
187
|
+
if (!(await validRuntime(payload, manifest))) throw new Error('小鲸鱼运行时文件不完整');
|
|
188
|
+
signal?.throwIfAborted();
|
|
189
|
+
try {
|
|
190
|
+
await fs.rename(payload, target);
|
|
191
|
+
} catch (error) {
|
|
192
|
+
if (!(await validRuntime(target, manifest))) {
|
|
193
|
+
await fs.rename(target, path.join(stage, 'previous')).catch(e => { if (e.code !== 'ENOENT') throw e; });
|
|
194
|
+
try { await fs.rename(payload, target); } catch (renameError) {
|
|
195
|
+
if (!(await validRuntime(target, manifest))) throw renameError;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return path.join(target, EXE);
|
|
200
|
+
} finally {
|
|
201
|
+
await fs.rm(stage, { recursive: true, force: true, maxRetries: 4, retryDelay: 125 }).catch(() => {});
|
|
202
|
+
}
|
|
203
|
+
}
|
package/session-id.cjs
ADDED
package/update.mjs
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { createHash, verify } from 'node:crypto';
|
|
2
|
+
import { createReadStream, createWriteStream, readFileSync } from 'node:fs';
|
|
3
|
+
import { mkdir, rm, stat } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { Readable, Transform } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
|
|
8
|
+
export const PLUGIN_NAME = 'xiaojingyuai-dsh';
|
|
9
|
+
export const NPM_PACKAGE_NAME = '@xiaojingyuai/dsh';
|
|
10
|
+
export const PACKAGE_BASENAME = 'xiaojingyuai-dsh';
|
|
11
|
+
export const UPDATE_CHANNEL = 'internal';
|
|
12
|
+
export const UPDATE_MANIFEST_URL = 'https://dafeiyu-download.oss-cn-beijing.aliyuncs.com/updates/plugins/dsh/manifest.json';
|
|
13
|
+
export const UPDATE_PUBLIC_KEY = '302a300506032b65700321004b82928e7478af55ad7c761ec3c8fa6d4c9750ea70df7e99d5359eabb0013e1a';
|
|
14
|
+
export const CURRENT_VERSION = JSON.parse(
|
|
15
|
+
readFileSync(new URL('./package.json', import.meta.url), 'utf8'),
|
|
16
|
+
).version;
|
|
17
|
+
|
|
18
|
+
const UPDATE_ORIGIN = 'https://dafeiyu-download.oss-cn-beijing.aliyuncs.com';
|
|
19
|
+
const UPDATE_PREFIX = '/updates/plugins/dsh/';
|
|
20
|
+
const MAX_MANIFEST_BYTES = 65536;
|
|
21
|
+
const MAX_PACKAGE_BYTES = 1024 * 1024 * 1024;
|
|
22
|
+
|
|
23
|
+
function versionParts(value) {
|
|
24
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(String(value || ''));
|
|
25
|
+
if (!match) throw new Error('更新版本格式无效');
|
|
26
|
+
return match.slice(1).map(Number);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function compareVersions(left, right) {
|
|
30
|
+
const a = versionParts(left);
|
|
31
|
+
const b = versionParts(right);
|
|
32
|
+
for (let index = 0; index < a.length; index++) {
|
|
33
|
+
if (a[index] !== b[index]) return a[index] > b[index] ? 1 : -1;
|
|
34
|
+
}
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function packageUrl(value, version) {
|
|
39
|
+
let url;
|
|
40
|
+
try { url = new URL(value); } catch { throw new Error('更新包地址无效'); }
|
|
41
|
+
if (url.protocol !== 'https:' || url.origin !== UPDATE_ORIGIN
|
|
42
|
+
|| url.username || url.password || url.search || url.hash
|
|
43
|
+
|| !url.pathname.startsWith(UPDATE_PREFIX)
|
|
44
|
+
|| path.posix.basename(url.pathname) !== `${PACKAGE_BASENAME}-${version}.tgz`) {
|
|
45
|
+
throw new Error('更新包地址不在允许的 OSS 目录');
|
|
46
|
+
}
|
|
47
|
+
return url;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function parseUpdateManifest(text, publicKeyHex = UPDATE_PUBLIC_KEY) {
|
|
51
|
+
if (Buffer.byteLength(text, 'utf8') > MAX_MANIFEST_BYTES) throw new Error('更新清单过大');
|
|
52
|
+
let manifest;
|
|
53
|
+
try { manifest = JSON.parse(text); } catch { throw new Error('更新清单格式无效'); }
|
|
54
|
+
if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('更新清单格式无效');
|
|
55
|
+
if (!/^[0-9a-f]{128}$/i.test(String(manifest.signature || ''))) throw new Error('更新清单缺少有效签名');
|
|
56
|
+
|
|
57
|
+
const signed = { ...manifest };
|
|
58
|
+
delete signed.signature;
|
|
59
|
+
const publicKey = {
|
|
60
|
+
key: Buffer.from(publicKeyHex, 'hex'),
|
|
61
|
+
format: 'der',
|
|
62
|
+
type: 'spki',
|
|
63
|
+
};
|
|
64
|
+
const valid = verify(
|
|
65
|
+
null,
|
|
66
|
+
Buffer.from(JSON.stringify(signed), 'utf8'),
|
|
67
|
+
publicKey,
|
|
68
|
+
Buffer.from(manifest.signature, 'hex'),
|
|
69
|
+
);
|
|
70
|
+
if (!valid) throw new Error('更新清单签名校验失败');
|
|
71
|
+
|
|
72
|
+
if (manifest.schema !== 1 || manifest.name !== PLUGIN_NAME || manifest.channel !== UPDATE_CHANNEL) {
|
|
73
|
+
throw new Error('更新清单不属于当前插件');
|
|
74
|
+
}
|
|
75
|
+
const latestVersion = String(manifest.version || '');
|
|
76
|
+
versionParts(latestVersion);
|
|
77
|
+
const pkg = manifest.package;
|
|
78
|
+
if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) throw new Error('更新清单缺少安装包');
|
|
79
|
+
const url = packageUrl(pkg.url, latestVersion);
|
|
80
|
+
if (!Number.isSafeInteger(pkg.bytes) || pkg.bytes <= 0 || pkg.bytes > MAX_PACKAGE_BYTES) {
|
|
81
|
+
throw new Error('更新包大小无效');
|
|
82
|
+
}
|
|
83
|
+
if (!/^[0-9a-f]{64}$/i.test(String(pkg.sha256 || ''))) throw new Error('更新包哈希无效');
|
|
84
|
+
const notes = typeof manifest.notes === 'string' ? manifest.notes.trim().slice(0, 4000) : '';
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
currentVersion: CURRENT_VERSION,
|
|
88
|
+
latestVersion,
|
|
89
|
+
available: compareVersions(latestVersion, CURRENT_VERSION) > 0,
|
|
90
|
+
notes,
|
|
91
|
+
releasedAt: typeof manifest.releasedAt === 'string' ? manifest.releasedAt : '',
|
|
92
|
+
downloadUrl: url.href,
|
|
93
|
+
bytes: pkg.bytes,
|
|
94
|
+
sha256: String(pkg.sha256).toLowerCase(),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function checkForUpdate(options = {}) {
|
|
99
|
+
const fetchImpl = options.fetchImpl || fetch;
|
|
100
|
+
const signal = options.signal
|
|
101
|
+
? AbortSignal.any([options.signal, AbortSignal.timeout(15000)])
|
|
102
|
+
: AbortSignal.timeout(15000);
|
|
103
|
+
const response = await fetchImpl(UPDATE_MANIFEST_URL, {
|
|
104
|
+
headers: { Accept: 'application/json' },
|
|
105
|
+
redirect: 'error',
|
|
106
|
+
signal,
|
|
107
|
+
});
|
|
108
|
+
if (!response.ok) throw new Error(`更新服务不可用(HTTP ${response.status})`);
|
|
109
|
+
const text = await response.text();
|
|
110
|
+
return parseUpdateManifest(text);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function updateDirectory(env) {
|
|
114
|
+
if (!env.LOCALAPPDATA || !path.isAbsolute(env.LOCALAPPDATA)) throw new Error('找不到当前用户下载目录');
|
|
115
|
+
return path.join(env.LOCALAPPDATA, 'XiaojingyuAI', 'DSH', 'updates');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function sha256File(file) {
|
|
119
|
+
const hash = createHash('sha256');
|
|
120
|
+
for await (const chunk of createReadStream(file)) hash.update(chunk);
|
|
121
|
+
return hash.digest('hex');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export async function downloadUpdate(options = {}) {
|
|
125
|
+
const fetchImpl = options.fetchImpl || fetch;
|
|
126
|
+
const env = options.env || process.env;
|
|
127
|
+
const current = options.update || await checkForUpdate({ fetchImpl, signal: options.signal });
|
|
128
|
+
if (!current.available) return current;
|
|
129
|
+
const dir = updateDirectory(env);
|
|
130
|
+
const file = path.join(dir, path.basename(new URL(current.downloadUrl).pathname));
|
|
131
|
+
await mkdir(dir, { recursive: true });
|
|
132
|
+
try {
|
|
133
|
+
const existing = await stat(file);
|
|
134
|
+
if (existing.size === current.bytes && await sha256File(file) === current.sha256) {
|
|
135
|
+
return { ...current, file };
|
|
136
|
+
}
|
|
137
|
+
} catch { /* Download a fresh verified copy. */ }
|
|
138
|
+
|
|
139
|
+
const signal = options.signal
|
|
140
|
+
? AbortSignal.any([options.signal, AbortSignal.timeout(10 * 60 * 1000)])
|
|
141
|
+
: AbortSignal.timeout(10 * 60 * 1000);
|
|
142
|
+
let response;
|
|
143
|
+
try {
|
|
144
|
+
response = await fetchImpl(current.downloadUrl, { redirect: 'error', signal });
|
|
145
|
+
if (!response.ok || !response.body) throw new Error(`更新包下载失败(HTTP ${response.status})`);
|
|
146
|
+
const length = Number(response.headers.get('content-length') || 0);
|
|
147
|
+
if (length && length !== current.bytes) throw new Error('更新包下载大小不符');
|
|
148
|
+
const hash = createHash('sha256');
|
|
149
|
+
let received = 0;
|
|
150
|
+
const digest = new Transform({
|
|
151
|
+
transform(chunk, _encoding, callback) {
|
|
152
|
+
hash.update(chunk);
|
|
153
|
+
received += chunk.length;
|
|
154
|
+
callback(null, chunk);
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
await rm(file, { force: true });
|
|
158
|
+
await pipeline(Readable.fromWeb(response.body), digest, createWriteStream(file));
|
|
159
|
+
if (received !== current.bytes) throw new Error('更新包下载大小不符');
|
|
160
|
+
if (hash.digest('hex') !== current.sha256) throw new Error('更新包 SHA-256 校验失败');
|
|
161
|
+
return { ...current, file };
|
|
162
|
+
} catch (error) {
|
|
163
|
+
try { await rm(file, { force: true }); } catch { /* Ignore cleanup failure. */ }
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
}
|