@sonicloud/dsh-sonicloud-device 0.0.0-stage → 0.1.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 (64) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/CHANGELOG.zh.md +35 -0
  3. package/LICENSE +25 -0
  4. package/README.md +139 -2
  5. package/cordis.patch.yml +3 -0
  6. package/dist/build.json +5 -0
  7. package/dist/client.js +20621 -0
  8. package/docs/contributing/development.md +200 -0
  9. package/docs/specs/ci-cd.md +128 -0
  10. package/docs/specs/mouse-settings.md +255 -0
  11. package/docs/specs/smart-mouse-plugin.md +239 -0
  12. package/native/COPYING.LGPLv2.1 +502 -0
  13. package/native/LICENSE.hidapi-bsd +26 -0
  14. package/native/README.md +15 -0
  15. package/native/SOURCE.json +16 -0
  16. package/native/THIRD_PARTY_LICENSES.txt +69 -0
  17. package/native/darwin-arm64/README.md +71 -0
  18. package/native/darwin-arm64/libavcodec.62.28.102.dylib +0 -0
  19. package/native/darwin-arm64/libavcodec.62.dylib +0 -0
  20. package/native/darwin-arm64/libavutil.60.26.102.dylib +0 -0
  21. package/native/darwin-arm64/libavutil.60.dylib +0 -0
  22. package/native/darwin-arm64/libuMouseSdk.0.4.20.dylib +0 -0
  23. package/native/darwin-arm64/libuMouseSdk.0.dylib +0 -0
  24. package/native/darwin-arm64/libuMouseSdk.dylib +0 -0
  25. package/native/desktop/CompatibilityPolicy.swift +17 -0
  26. package/native/desktop/VoicePanel.cs +197 -0
  27. package/native/desktop/VoicePanel.swift +322 -0
  28. package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/Info.plist +10 -0
  29. package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
  30. package/native/desktop/windows.ps1 +9 -0
  31. package/native/win32-x64/README.md +70 -0
  32. package/native/win32-x64/avcodec-58.dll +0 -0
  33. package/native/win32-x64/avutil-56.dll +0 -0
  34. package/native/win32-x64/msvcp140.dll +0 -0
  35. package/native/win32-x64/uMouseSdk.dll +0 -0
  36. package/native/win32-x64/vcruntime140.dll +0 -0
  37. package/native/win32-x64/vcruntime140_1.dll +0 -0
  38. package/package.json +74 -4
  39. package/src/asr/auth.mjs +80 -0
  40. package/src/asr/config.mjs +6 -0
  41. package/src/asr/languages.mjs +28 -0
  42. package/src/asr/stream.mjs +149 -0
  43. package/src/client/assets/contact-wechat.jpg +0 -0
  44. package/src/client/assets/sonicloud.png +0 -0
  45. package/src/client/assets/sonicloud.svg +3 -0
  46. package/src/desktop/presentation.mjs +87 -0
  47. package/src/devices/actions.mjs +46 -0
  48. package/src/devices/config.mjs +9 -0
  49. package/src/devices/diagnostics.mjs +52 -0
  50. package/src/devices/manager.mjs +335 -0
  51. package/src/devices/native-worker.mjs +64 -0
  52. package/src/devices/native.mjs +86 -0
  53. package/src/devices/queue.mjs +32 -0
  54. package/src/devices/recognition.mjs +23 -0
  55. package/src/devices/store.mjs +44 -0
  56. package/src/devices/translate.mjs +44 -0
  57. package/src/host/ai-conversation.mjs +83 -0
  58. package/src/host/index.mjs +96 -0
  59. package/src/host/store.mjs +24 -0
  60. package/src/shared/devices.mjs +69 -0
  61. package/src/shared/languages.mjs +111 -0
  62. package/src/shared/mouse-settings.mjs +22 -0
  63. package/src/shared/remote.mjs +55 -0
  64. package/src/shared/transcript.mjs +16 -0
@@ -0,0 +1,70 @@
1
+ # uMouseSdk 0.4.20 —— 声云智能鼠标设备接入 SDK(Windows x64)
2
+
3
+ 从系统层接入 uMouse 家族设备(USB 2.4G 接收器 / BLE 蓝牙,自动偏好 USB),
4
+ 完成 SN 识别、多设备管理、按键/语音音频/电量/会议事件解析与上抛。
5
+ 内置 SBC / SyPcm / YiChip / ADPCM(TLW 包格式 + 连续流双模式自识别)音频解码。
6
+
7
+ 权威接口文档:`include/umouse_sdk.h`(含完整注释与**事件 JSON 协议规范**,
8
+ 集成前必读其头部协议说明段——deviceInfo / keyEvent / dpiChanged / meeting 系列 /
9
+ lavalierMicStatus/Battery(领夹麦 0x12/0x13)/ warning 信封的格式定义都在其中)。
10
+ 完整接入文档(C/C++、C#、Python、Electron/Node.js)与 C 示例见 SDK 发布仓库。
11
+
12
+ ## 文件清单
13
+
14
+ - `uMouseSdk.dll`(主库)+ `uMouseSdk.lib`(导入库,链接期加载用;
15
+ `LoadLibrary` 动态加载方式可忽略 .lib)
16
+ - FFmpeg 编解码闭包:`avcodec-58.dll` / `avutil-56.dll`——与主库同目录
17
+ - VC 运行库副本:`msvcp140.dll` / `vcruntime140.dll` / `vcruntime140_1.dll`
18
+ (14.51.36231.0)
19
+
20
+ ## 加载方式(重要)
21
+
22
+ 本目录不在系统默认 DLL 搜索路径内,两种方式二选一:
23
+
24
+ 1. **PATH 前插**:在首次加载任何 SDK DLL 之前,将本目录加入进程 `PATH`
25
+ (`SetEnvironmentVariableW` 修改进程环境即可,无需系统级配置);
26
+ 2. **显式加载**:对每个 DLL 用
27
+ `LoadLibraryExW(绝对路径, NULL, LOAD_WITH_ALTERED_SEARCH_PATH)`。
28
+
29
+ **VC 运行库注意**:系统搜索序中 System32 先于 PATH——若目标机 System32 内存有
30
+ 旧版 / 测试版 CRT(例如 14.29 一带的云测试版本),会覆盖本目录副本导致崩溃。
31
+ 稳妥做法:加载 SDK 之前,按 `vcruntime140.dll → vcruntime140_1.dll → msvcp140.dll`
32
+ 顺序以**绝对路径**预载本目录三个 CRT(同进程内已加载的模块优先,后到的同名
33
+ DLL 会被忽略)。目标机已安装 VC++ Redistributable 时亦可直接依赖系统版本。
34
+
35
+ ## 最小集成流程(C ABI)
36
+
37
+ ```c
38
+ #include "umouse_sdk.h"
39
+
40
+ um_sdk_init(1); // 装载默认设备规则(debug 日志开关)
41
+ um_register_connected(on_connected); // 设备上线(device_id = SN)
42
+ um_register_disconnected(on_disconnected);
43
+ um_register_message(on_message); // 事件 JSON(协议见头文件)
44
+ um_register_audio(on_audio); // 解码后 PCM(16k mono s16le)
45
+ um_sdk_start(); // 启动监测(可省略,init 后自动)
46
+
47
+ // 语音链路由调用方实现:audio 回调 PCM → 自有识别管线;
48
+ // keyEvent(语音键抬起) → 结束识别。
49
+ ```
50
+
51
+ ## 关键 API 组
52
+
53
+ - 生命周期:`um_sdk_init` / `um_sdk_start` / `um_sdk_close` / `um_sdk_version`
54
+ - 事件注册:`um_register_connected/disconnected/message/audio/raw_frame`
55
+ - 设备规则(RAW 接入自定义硬件):`um_device_rule_*` / `um_set_usb_config` /
56
+ `um_set_ble_config` / `um_usb_add_match` / `um_register_ble_match_device`
57
+ - 运行时控制:`um_set_work_mode[_for]`(RAW/FULL)、`um_set_channel_pref[_for]`
58
+ (0=自动 USB 优先 / 1=仅 USB / 2=仅 BLE)、`um_set_device_limit`、
59
+ `um_set_audio_source`(多设备音频出口选定)、`um_meeting_create/pause/resume`
60
+ - 诊断:`um_enable_crash_report`
61
+
62
+ ## 平台行为要点(Windows)
63
+
64
+ - 通道:USB/2.4G 接收器走 HID;BLE 走 WinRT Bluetooth LE API(系统栈),
65
+ 自动偏好 USB,同 SN 双通道在线时按 channel_pref 策略择路。
66
+ - 无系统授权弹窗;BLE 配对在 Windows 系统蓝牙设置完成,接收器免配对即插即用。
67
+ - 多设备:默认每规则 4 台、全局 8 台;BLE 多活链超过 2 条会上抛 bleLinkHigh
68
+ 预警(射频调度劣化预警;实测 Windows 约 2 条并发起明显劣化、macOS 1 条即显,
69
+ 预警阈值取保守值)。
70
+ - 日志:`cpp_modules.log` 落宿主进程当前工作目录(cwd)。
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@sonicloud/dsh-sonicloud-device",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "DeepSeek Harness 智能鼠标、多设备设置与共享语音服务",
5
+ "icon": "./src/client/assets/sonicloud.png",
6
+ "type": "module",
7
+ "main": "src/host/index.mjs",
8
+ "exports": {
9
+ ".": "./src/host/index.mjs",
10
+ "./client": "./dist/client.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "src/asr",
15
+ "src/host",
16
+ "src/shared",
17
+ "src/client/assets",
18
+ "dist",
19
+ "cordis.patch.yml",
20
+ "README.md",
21
+ "src/devices",
22
+ "src/desktop",
23
+ "native",
24
+ "docs",
25
+ "CHANGELOG.md",
26
+ "CHANGELOG.zh.md"
27
+ ],
28
+ "dsh": {
29
+ "bundle": {
30
+ "patch": "./cordis.patch.yml"
31
+ },
32
+ "client": {
33
+ "platform": "web"
34
+ }
35
+ },
36
+ "scripts": {
37
+ "build": "node scripts/build.mjs",
38
+ "dev": "node scripts/dev.mjs",
39
+ "dev:setup": "node scripts/dev/setup.mjs",
40
+ "pretest": "npm run build",
41
+ "test": "node --test tests/*.test.mjs",
42
+ "check": "npm test",
43
+ "probe": "node scripts/probe.mjs",
44
+ "prepack": "npm run build"
45
+ },
46
+ "engines": {
47
+ "node": ">=22",
48
+ "dsh": ">=0.2.1-rc.5"
49
+ },
50
+ "dependencies": {
51
+ "koffi": "^2.15.2",
52
+ "ws": "^8.18.0",
53
+ "zod": "^4.0.0"
54
+ },
55
+ "peerDependencies": {
56
+ "@deepseek-ai/cordis": "~4.0.5",
57
+ "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.5"
58
+ },
59
+ "devDependencies": {
60
+ "@deepseek-ai/dsh-api-gateway": "^0.2.1-rc.5",
61
+ "@deepseek-ai/dsh-typert-registry": "^0.2.1-rc.5",
62
+ "esbuild": "^0.25.0",
63
+ "jsdom": "^26.0.0",
64
+ "react": "^19.0.0",
65
+ "react-dom": "^19.0.0"
66
+ },
67
+ "license": "MIT",
68
+ "repository": {
69
+ "type": "git",
70
+ "url": "git+https://github.com/SonicloudTech/dsh-sonicloud-device.git"
71
+ },
72
+ "publishConfig": {
73
+ "access": "public",
74
+ "registry": "https://registry.npmjs.org/"
75
+ }
76
+ }
@@ -0,0 +1,80 @@
1
+ import { BUILTIN_ASR } from './config.mjs';
2
+ import { isStableSn } from '../shared/devices.mjs';
3
+
4
+ export function createTokenRequest({ sn }) {
5
+ if (!isStableSn(sn)) throw new Error('设备身份未确认,请重新连接鼠标');
6
+ return { sn };
7
+ }
8
+
9
+ // 每个设备独立缓存;最后一个等待者取消时中止请求,迟到响应不能写回缓存。
10
+ export function createTokenProvider(config, fetchImpl = globalThis.fetch, lifetime) {
11
+ const service = { ...BUILTIN_ASR, ...config };
12
+ let cachedToken, expiresAt = 0, pending, generation = 0;
13
+ const invalidate = expected => {
14
+ if (expected !== undefined && cachedToken !== expected) return;
15
+ generation++; cachedToken = undefined; expiresAt = 0;
16
+ pending?.abort.abort(); pending = undefined;
17
+ };
18
+ async function requestToken(entry) {
19
+ const signal = AbortSignal.any([entry.abort.signal, AbortSignal.timeout(10_000), ...(lifetime ? [lifetime] : [])]);
20
+ signal.throwIfAborted();
21
+ let response, payload;
22
+ try {
23
+ response = await fetchImpl(service.tokenUrl, {
24
+ method: 'POST', headers: { 'Content-Type': 'application/json; charset=utf-8' },
25
+ body: JSON.stringify(createTokenRequest(service)), signal, redirect: 'error',
26
+ });
27
+ payload = await response.json();
28
+ } catch (error) {
29
+ if (signal.aborted && !entry.abort.signal.aborted && !lifetime?.aborted) throw new Error('Token 获取超时,请稍后重试');
30
+ signal.throwIfAborted();
31
+ if (!isStableSn(service.sn)) throw error;
32
+ throw new Error('Token 获取失败,请检查网络后重试');
33
+ }
34
+ signal.throwIfAborted();
35
+ if (!response.ok || payload?.code !== 0) {
36
+ const messages = {
37
+ 4001: '设备身份无效,请重新连接鼠标', 1001: '设备鉴权参数错误,请联系服务方',
38
+ 1002: '设备鉴权失败,请联系服务方', 1008: 'License 设备数量已达上限',
39
+ };
40
+ throw new Error(messages[payload?.code] ?? 'Token 获取失败,请稍后重试');
41
+ }
42
+ const { token, expire_time: expiry } = payload.data ?? {};
43
+ if (typeof token !== 'string' || !token.trim() || !Number.isSafeInteger(expiry) || expiry <= Date.now() / 1000) {
44
+ throw new Error('Token 响应无效或已过期,请稍后重试');
45
+ }
46
+ if (entry.generation !== generation) throw new Error('Token 请求已失效');
47
+ cachedToken = token; expiresAt = expiry * 1000;
48
+ return token;
49
+ }
50
+ const getToken = async (signal) => {
51
+ lifetime?.throwIfAborted(); signal?.throwIfAborted();
52
+ createTokenRequest(service);
53
+ if (cachedToken && Date.now() < expiresAt) return cachedToken;
54
+ if (!pending) {
55
+ const entry = { abort: new AbortController(), generation, users: 0 };
56
+ pending = entry;
57
+ entry.promise = requestToken(entry).finally(() => { if (pending === entry) pending = undefined; });
58
+ }
59
+ const entry = pending;
60
+ entry.users++;
61
+ return new Promise((resolve, reject) => {
62
+ const combined = AbortSignal.any([entry.abort.signal, ...(signal ? [signal] : []), ...(lifetime ? [lifetime] : [])]);
63
+ let settled = false;
64
+ const finish = (handler, value) => {
65
+ if (settled) return;
66
+ settled = true; combined.removeEventListener('abort', abort);
67
+ entry.users--;
68
+ if (!entry.users && pending === entry) { pending = undefined; generation++; entry.abort.abort(); }
69
+ handler(value);
70
+ };
71
+ const abort = () => finish(reject, combined.reason);
72
+ combined.addEventListener('abort', abort, { once: true });
73
+ entry.promise.then(value => finish(resolve, value), error => finish(reject, error));
74
+ if (combined.aborted) abort();
75
+ });
76
+ };
77
+ getToken.invalidate = invalidate;
78
+ lifetime?.addEventListener('abort', () => invalidate(), { once: true });
79
+ return getToken;
80
+ }
@@ -0,0 +1,6 @@
1
+ export const BUILTIN_ASR = Object.freeze({
2
+ name: '声云 ASR',
3
+ streamUrl: 'wss://openapi.sinicloud.com/talentStreamAsr',
4
+ tokenUrl: 'https://dsh_device.sonicrhino.cc/api/open.sign/generate',
5
+ translateUrl: 'https://openapi.sinicloud.com/v1/translate/text',
6
+ });
@@ -0,0 +1,28 @@
1
+ import { REC_LANG_LIST } from '../shared/languages.mjs';
2
+
3
+ // 来源:https://open.sinicloud.com/documents/webapi/stream-asr
4
+ // 显式映射完整三元组;不把方言、混合语种或简繁体折叠为中文默认值。
5
+ // 2026-11-04 实测:普通话繁体使用 100;控制台标注的 99 仍输出简体。
6
+ const foreign = {
7
+ en_us: 1, ja_jp: 2, ko_kr: 3, 'ru-ru': 5, ar_il: 6,
8
+ es_es: 7, it_IT: 8, vi_VN: 9, fr_fr: 10, de_DE: 11,
9
+ pt_PT: 12, tr_TR: 13, pl_pl: 14, nl_NL: 16, sv_SE: 17,
10
+ id_ID: 18, hi_in: 19, fi_fi: 20, he_il: 21, el_GR: 23,
11
+ ms_MY: 24, cs_CZ: 25, da_DK: 27, th_TH: 31, fa_IR: 42,
12
+ km_KH: 65, uz_UZ: 79,
13
+ };
14
+ const dialects = {
15
+ mandarin: 0, cantonese: 4, minnanese: 101, lmz: 102,
16
+ henannese: 105, shanxinese: 106, dongbeiese: 107, tianjinese: 108,
17
+ gansunese: 109, guizhounese: 110, yunnanese: 111, ningxianese: 114,
18
+ shandongnese: 116, shanghainese: 119, hebeinese: 122,
19
+ };
20
+ export const DEFAULT_LANGUAGES = REC_LANG_LIST.flatMap(({ language, accent, rlang }) => {
21
+ let lanid;
22
+ if (language === 'zh_cn') {
23
+ if (rlang === 'zh-hk' && accent === 'mandarin') lanid = 100;
24
+ else if (rlang === '') lanid = dialects[accent];
25
+ } else if (accent === 'mandarin' && rlang === '') lanid = foreign[language];
26
+ if (lanid === undefined) return [];
27
+ return [{ language, accent, rlang, query: { lid: '0', lanid: String(lanid), role: '0' } }];
28
+ });
@@ -0,0 +1,149 @@
1
+ import WebSocket from 'ws';
2
+
3
+ class Queue {
4
+ items = [];
5
+ ended = false;
6
+ push(item) {
7
+ if (this.ended) return;
8
+ if (this.items.length >= 256) { this.items = [{ type: 'error', message: '识别结果接收过慢,请重新录音' }]; this.end(); return; }
9
+ this.items.push(item); this.wake?.();
10
+ }
11
+ end() { this.ended = true; this.wake?.(); }
12
+ async *[Symbol.asyncIterator]() {
13
+ while (true) {
14
+ if (this.items.length) yield this.items.shift();
15
+ else if (this.ended) return;
16
+ else await new Promise(resolve => { this.wake = resolve; });
17
+ }
18
+ }
19
+ }
20
+
21
+ const errors = {
22
+ '4010': 'Token 认证失败,请稍后重试',
23
+ '4011': 'ASR 额度不足,请充值后重试',
24
+ '4012': 'ASR 应用不存在、未认证或已下线',
25
+ '4013': 'ASR 并发连接已达上限,请稍后重试',
26
+ '4014': 'License 设备未注册', '4015': 'License 设备已被其他会话占用',
27
+ '-1': '语音太短,请重新录音', '16': '未识别到语音',
28
+ };
29
+
30
+ // The live service also uses numeric strings and code 3 interim / code 10 final frames.
31
+ function timestamp(value) {
32
+ if (typeof value !== 'number' && !(typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value))) return undefined;
33
+ const number = Number(value);
34
+ return Number.isFinite(number) && number >= 0 ? number : undefined;
35
+ }
36
+
37
+ /** The end marker is authoritative; upstream may keep its WebSocket open afterwards. */
38
+ export async function* streamRecognition({ service, token, uplink, signal, onAuthFailure = () => {}, WebSocketImpl = WebSocket,
39
+ connectTimeout = 10_000, finalTimeout = 5_000, idleTimeout = 15_000 }) {
40
+ signal.throwIfAborted();
41
+ const queue = new Queue();
42
+ const url = new URL(service.streamUrl);
43
+ for (const [key, value] of Object.entries(service.recognitionQuery ?? { lanid: '0', lid: '0', role: '0' })) url.searchParams.set(key, String(value));
44
+ // Credentials stay out of connection URLs and browser storage.
45
+ const socket = new WebSocketImpl(url, {
46
+ headers: { 'X-SC-Authorization': token, 'X-SC-User-Id': service.userId },
47
+ handshakeTimeout: connectTimeout, maxPayload: 128 * 1024, followRedirects: false,
48
+ });
49
+ let ready = false, ended = false, complete = false, timer, connectTimer, totalBytes = 0;
50
+ let settleReady;
51
+ const readiness = new Promise(resolve => { settleReady = resolve; });
52
+ const fail = (message, code) => {
53
+ if (queue.ended) return;
54
+ queue.push({ type: 'error', message, ...(code ? { code, retryable: code === '4010' && !ready } : {}) }); queue.end();
55
+ settleReady(false);
56
+ socket.terminate();
57
+ };
58
+ const arm = (delay, message) => { clearTimeout(timer); timer = setTimeout(() => fail(message), delay); };
59
+ connectTimer = setTimeout(() => fail('ASR 连接超时,请检查网络后重试'), connectTimeout);
60
+ const abort = () => { queue.end(); settleReady(false); socket.terminate(); };
61
+ signal.addEventListener('abort', abort, { once: true });
62
+ if (signal.aborted) abort();
63
+ socket.on('error', () => fail('ASR 连接失败,请检查服务地址与网络'));
64
+ const transcript = (message, forcedFinal) => {
65
+ const begin = timestamp(message.Begin), end = timestamp(message.End);
66
+ if (!ready || complete || typeof message.result !== 'string' || message.result.length > 4096 ||
67
+ begin === undefined || end === undefined || (end > 0 && end < begin)) {
68
+ fail('ASR 返回了无效识别结果'); return false;
69
+ }
70
+ queue.push({ type: 'transcript', text: message.result, begin, end, final: forcedFinal ?? end > 0 });
71
+ return true;
72
+ };
73
+ socket.on('message', data => {
74
+ if (queue.ended) return;
75
+ let message;
76
+ try { message = JSON.parse(data.toString()); } catch { fail('ASR 返回了无效数据'); return; }
77
+ const code = String(message?.errCode);
78
+ if (code === '1000') {
79
+ if (ready) return;
80
+ ready = true; clearTimeout(connectTimer);
81
+ arm(idleTimeout, '录音数据中断,请重新录音'); queue.push({ type: 'ready' });
82
+ settleReady(true);
83
+ } else if (code === '1001') queue.push({ type: 'warning', message: 'ASR 余额较低,请及时充值' });
84
+ else if (code === '0') transcript(message);
85
+ else if (code === '3') {
86
+ // End can be nonzero on live rolling results; code 3 is never a final sentence.
87
+ if (Object.hasOwn(message, 'Begin') || Object.hasOwn(message, 'End')) transcript(message, false);
88
+ } else if (code === '10') {
89
+ if (!ended) { fail('ASR 服务提前结束了录音'); return; }
90
+ // Older responses send the final sentence separately with code 0. Newer ones
91
+ // include it in code 10. Do not treat an untimed status message as transcript.
92
+ if ((Object.hasOwn(message, 'Begin') || Object.hasOwn(message, 'End')) && !transcript(message, true)) return;
93
+ complete = true;
94
+ clearTimeout(timer);
95
+ queue.push({ type: 'complete' }); queue.end();
96
+ }
97
+ else {
98
+ if (code === '4010') onAuthFailure();
99
+ fail(errors[code] ?? (code.startsWith('400') ? 'ASR 连接参数无效,请检查配置' : 'ASR 识别失败,请稍后重试'), code);
100
+ }
101
+ });
102
+ socket.on('close', () => {
103
+ if (queue.ended) return;
104
+ fail('ASR 连接中断,识别结果未完成');
105
+ });
106
+ const input = uplink[Symbol.asyncIterator]();
107
+ const upload = async () => {
108
+ try {
109
+ // Hardware can produce audio (and release the key) before the handshake.
110
+ // Keep it in the device's bounded queue until the service accepts audio.
111
+ if (!await readiness || queue.ended || signal.aborted) return;
112
+ while (!queue.ended) {
113
+ const { done, value } = await input.next();
114
+ if (queue.ended || signal.aborted) return;
115
+ if (done) {
116
+ ended = true;
117
+ arm(finalTimeout, '最终识别结果超时,可复制已有预览后重试');
118
+ queue.push({ type: 'finishing' });
119
+ socket.send('end'); return;
120
+ }
121
+ if (typeof value !== 'string' || value.length > 4400) throw new Error('音频包无效');
122
+ const bytes = Buffer.from(value, 'base64');
123
+ if (bytes.toString('base64') !== value || bytes.length <= 80 || bytes.length > 3200 || bytes.length % 2) throw new Error('音频包无效');
124
+ totalBytes += bytes.length;
125
+ if (totalBytes > 16_000 * 2 * 600) throw new Error('单次录音最长 10 分钟');
126
+ if (socket.bufferedAmount > 320_000) throw new Error('网络发送过慢,请重新录音');
127
+ socket.send(bytes); arm(idleTimeout, '录音数据中断,请重新录音');
128
+ }
129
+ } catch (error) {
130
+ if (!signal.aborted) fail(error.message === '音频包无效' || error.message === '单次录音最长 10 分钟' || error.message === '网络发送过慢,请重新录音'
131
+ ? error.message : '音频上传中断,请重新录音');
132
+ }
133
+ };
134
+ void upload();
135
+ try { yield* queue; }
136
+ finally {
137
+ clearTimeout(timer); clearTimeout(connectTimer); queue.end(); settleReady(false);
138
+ signal.removeEventListener('abort', abort);
139
+ if (complete && socket.readyState === WebSocket.OPEN) {
140
+ // Finish locally after code 10; a missing server close handshake cannot delay insertion.
141
+ const closing = setTimeout(() => socket.terminate(), 1000);
142
+ closing.unref?.();
143
+ socket.once('close', () => clearTimeout(closing));
144
+ socket.close();
145
+ } else socket.terminate();
146
+ // Carrier cancellation owns completion of an input.next() still in flight.
147
+ if (ready) void Promise.resolve(input.return?.()).catch(() => {});
148
+ }
149
+ }
Binary file
@@ -0,0 +1,3 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="100%" height="100%" fill="currentColor" aria-hidden="true">
2
+ <path d="M138.00,31.82 127.00,33.69 115.00,37.64 103.00,43.84 91.00,52.87 81.51,63.00 74.66,73.00 69.70,83.00 65.59,97.00 52.00,101.74 45.00,105.83 41.00,108.90 33.77,116.00 28.70,123.00 25.86,128.00 21.63,139.00 19.74,149.00 19.74,161.00 21.73,171.00 25.80,181.00 31.76,190.00 41.00,199.21 49.00,204.41 59.00,208.39 70.00,210.06 111.00,210.19 111.82,209.00 111.80,150.00 111.00,147.03 109.00,144.71 106.00,143.63 96.00,143.86 92.00,145.61 89.75,148.00 88.70,150.00 87.83,155.00 87.80,189.00 87.00,189.92 75.00,189.90 69.00,189.34 60.00,186.18 54.00,182.18 48.92,177.00 44.55,170.00 41.85,162.00 41.19,154.00 41.81,147.00 44.85,138.00 48.55,132.00 54.24,126.00 60.00,121.79 67.00,118.70 76.00,116.78 85.00,116.58 85.74,116.00 86.71,104.00 87.69,99.00 89.82,92.00 93.54,84.00 96.63,79.00 102.00,72.36 108.00,66.79 115.00,61.93 121.00,58.81 129.00,55.89 141.00,53.71 152.00,53.84 162.00,55.71 168.00,57.74 176.00,61.63 182.00,65.70 191.31,75.00 198.21,86.00 201.33,94.00 203.25,102.00 204.00,102.66 224.00,102.68 225.34,102.00 224.37,95.00 222.32,87.00 217.28,75.00 209.50,63.00 204.38,57.00 198.00,50.93 186.00,42.53 179.00,38.99 171.00,35.80 164.00,33.79 153.00,31.91Z M136.00,114.87 132.13,116.00 129.00,118.38 126.93,122.00 126.43,125.00 126.33,215.00 126.82,217.00 128.33,219.00 132.00,220.41 137.00,219.44 145.00,215.13 148.14,212.00 149.36,210.00 150.47,206.00 150.28,120.00 149.41,118.00 147.00,115.66 144.00,114.77Z M172.00,95.69 169.26,97.00 167.00,99.18 165.71,102.00 165.48,104.00 165.40,235.00 166.00,235.90 183.00,222.24 189.36,216.00 189.20,105.00 188.31,102.00 187.09,100.00 183.00,96.55 179.00,95.46Z M211.00,131.66 208.39,133.00 206.00,135.23 204.58,138.00 203.98,141.00 203.84,198.00 203.90,200.00 205.00,200.62 213.00,195.24 222.00,187.78 226.27,183.00 227.34,181.00 227.90,178.00 227.92,139.00 227.28,135.00 225.00,132.36 223.00,131.45Z"/>
3
+ </svg>
@@ -0,0 +1,87 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createInterface } from 'node:readline';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ // Private stdio IPC: transcripts never appear in process arguments, files, or logs.
6
+ export class DesktopPresentation {
7
+ constructor({ platform = process.platform, arch = process.arch, launch = spawn, timeoutMs = 10000 } = {}) {
8
+ Object.assign(this, { platform, arch, launch, timeoutMs });
9
+ this.requests = new Map(); this.sequence = 0;
10
+ }
11
+ start() {
12
+ if (this.closed) throw new Error('桌面语音浮层已关闭');
13
+ if (this.child) return;
14
+ const root = new URL('../../native/desktop/', import.meta.url);
15
+ let file, args = [];
16
+ if (this.platform === 'darwin') file = fileURLToPath(new URL(`darwin-${this.arch}/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice`, root));
17
+ else if (this.platform === 'win32') {
18
+ file = 'powershell.exe'; args = ['-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', fileURLToPath(new URL('windows.ps1', root))];
19
+ } else throw new Error('当前平台不支持桌面语音浮层');
20
+ const child = this.launch(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
21
+ this.child = child;
22
+ const lines = createInterface({ input: child.stdout });
23
+ lines.on('line', line => {
24
+ if (this.child !== child || line.length > 300000) return;
25
+ let message; try { message = JSON.parse(line); } catch { return; }
26
+ if (message.event === 'cancel' && message.sessionId === this.sessionId) this.onCancel?.(message.sessionId);
27
+ const pending = this.requests.get(message.id);
28
+ if (pending) {
29
+ clearTimeout(pending.timer); this.requests.delete(message.id);
30
+ if (message.ok) pending.resolve(message.value);
31
+ else pending.reject(new Error('桌面语音浮层操作失败'));
32
+ }
33
+ });
34
+ const failed = () => {
35
+ if (this.child !== child) return;
36
+ this.child = undefined; lines.close();
37
+ for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('桌面语音浮层不可用,请检查安装并重试')); }
38
+ this.requests.clear();
39
+ if (!this.closed) this.onFault?.();
40
+ };
41
+ child.once('error', failed); child.once('exit', failed);
42
+ child.stdin.on('error', failed);
43
+ child.stderr.resume();
44
+ }
45
+ send(message) {
46
+ if (!this.child || this.closed) return;
47
+ this.child.stdin.write(JSON.stringify(message) + '\n');
48
+ }
49
+ request(message) {
50
+ this.start();
51
+ const id = ++this.sequence;
52
+ return new Promise((resolve, reject) => {
53
+ const timer = setTimeout(() => {
54
+ this.requests.delete(id); reject(new Error('桌面语音浮层响应超时,请重试'));
55
+ this.child?.kill();
56
+ }, this.timeoutMs);
57
+ this.requests.set(id, { resolve, reject, timer }); this.send({ ...message, id });
58
+ });
59
+ }
60
+ async begin(run) {
61
+ this.sessionId = run.id;
62
+ await this.request({ command: 'begin', sessionId: run.id, action: run.action });
63
+ }
64
+ event(event) {
65
+ if (event.type === 'devices' || event.type === 'request' || event.type === 'result') return;
66
+ if (event.sessionId && event.sessionId !== this.sessionId) return;
67
+ // Do not launch a native window for background device discovery messages.
68
+ if (!this.child) return;
69
+ this.send({ command: 'event', ...event });
70
+ }
71
+ async complete(run, text) {
72
+ return this.request({ command: 'result', sessionId: run.id, text });
73
+ }
74
+ async close() {
75
+ this.closed = true;
76
+ for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('桌面语音浮层已关闭')); }
77
+ this.requests.clear();
78
+ const child = this.child; this.child = undefined;
79
+ if (child) await new Promise(resolve => {
80
+ const done = () => { clearTimeout(timer); child.off('exit', done); resolve(); };
81
+ const timer = setTimeout(() => { child.kill(); done(); }, 1000);
82
+ child.once('exit', done);
83
+ // EOF lets the native helper restore a temporary clipboard before it exits.
84
+ child.stdin.end();
85
+ });
86
+ }
87
+ }
@@ -0,0 +1,46 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { webUrl } from '../shared/devices.mjs';
4
+ const run = promisify(execFile);
5
+ const commandOptions = { timeout: 8000, windowsHide: true, maxBuffer: 8192 };
6
+ export async function systemAction(action, value, { platform = process.platform, execute = run } = {}) {
7
+ let file, args;
8
+ if (action === 'openUrl') {
9
+ const url = webUrl(value);
10
+ if (platform === 'darwin') {
11
+ file = '/usr/bin/open'; args = [url];
12
+ if (!/^https?:\/\//i.test(url)) {
13
+ // Pass a bare address as a browser argument, not as a local file or a rewritten URL.
14
+ try {
15
+ const result = await execute('/usr/bin/osascript', ['-l', 'JavaScript', '-e',
16
+ "ObjC.import('CoreServices'); ObjC.unwrap(ObjC.castRefToObject($.LSCopyDefaultHandlerForURLScheme($('http'))));"], commandOptions);
17
+ const browser = result.stdout.trim();
18
+ if (!/^[a-z\d][a-z\d.-]+$/i.test(browser)) throw new Error('默认浏览器不可用');
19
+ args = ['-n', '-b', browser, '--args', url];
20
+ } catch { throw new Error('浏览器打开失败,请检查默认浏览器'); }
21
+ }
22
+ }
23
+ else if (platform === 'win32') { file = 'rundll32.exe'; args = ['url.dll,FileProtocolHandler', url]; }
24
+ else { file = 'xdg-open'; args = [url]; }
25
+ } else if (platform === 'darwin') {
26
+ file = '/usr/bin/osascript';
27
+ const scripts = {
28
+ enter: 'tell application "System Events" to key code 36',
29
+ backspace: 'tell application "System Events" to key code 51',
30
+ openAi: 'tell application "DeepSeek Harness" to activate',
31
+ };
32
+ if (!scripts[action]) throw new Error('不支持此按键动作');
33
+ args = ['-e', scripts[action]];
34
+ } else if (platform === 'win32') {
35
+ file = 'powershell.exe';
36
+ const scripts = {
37
+ enter: '$s=New-Object -ComObject WScript.Shell; $s.SendKeys("{ENTER}")',
38
+ backspace: '$s=New-Object -ComObject WScript.Shell; $s.SendKeys("{BACKSPACE}")',
39
+ openAi: '$s=New-Object -ComObject WScript.Shell; if(-not $s.AppActivate("DeepSeek Harness")){exit 1}',
40
+ };
41
+ if (!scripts[action]) throw new Error('不支持此按键动作');
42
+ args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(scripts[action], 'utf16le').toString('base64')];
43
+ } else throw new Error('当前平台尚不支持此系统按键动作');
44
+ try { await execute(file, args, commandOptions); }
45
+ catch { throw new Error(action === 'openUrl' ? '浏览器打开失败,请检查默认浏览器' : '系统动作执行失败,请检查辅助功能权限及宿主运行状态'); }
46
+ }
@@ -0,0 +1,9 @@
1
+ import { z } from 'zod';
2
+ const query = z.partialRecord(z.enum(['lid', 'lanid', 'role', 'language', 'accent', 'rlang']), z.union([z.string().max(128), z.number()])).refine(value => Object.keys(value).length > 0, '识别参数不能为空');
3
+ export const pluginConfigSchema = z.object({
4
+ native: z.object({ libraryPath: z.string().min(1).max(4096).optional() }).strict().optional(),
5
+ dpiLevels: z.partialRecord(z.enum(['800', '1200', '1600', '2400']), z.number().int().min(0).max(255)).optional(),
6
+ dpiReportLevels: z.partialRecord(z.enum(['800', '1200', '1600', '2400']), z.number().int().min(0).max(255)).optional(),
7
+ recognitionLanguages: z.array(z.object({ language: z.string(), accent: z.string(), rlang: z.string(), query }).strict()).max(100).optional(),
8
+ translation: z.object({ timeoutMs: z.number().int().min(1000).max(60000).default(15000) }).strict().optional(), tailMs: z.number().int().min(0).max(1000).default(150),
9
+ }).strict();
@@ -0,0 +1,52 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const run = promisify(execFile);
5
+
6
+ // Read only the production receiver's vendor data interface; keyboard/mouse clients
7
+ // and non-exclusive HID observers (such as Logitech Options) are not blockers.
8
+ export function parseUsbOwners(output, workerPid) {
9
+ let receiver, iface, client;
10
+ const receivers = [], owners = [];
11
+ for (const line of output.split('\n')) {
12
+ const node = line.indexOf('+-o ');
13
+ if (node >= 0) {
14
+ client = undefined;
15
+ if (node === 0) { receiver = {}; receivers.push(receiver); iface = undefined; }
16
+ if (line.includes('<class IOUSBHostInterface,')) iface = undefined;
17
+ if (line.includes('<class IOHIDLibUserClient,')) client = { receiver, iface };
18
+ continue;
19
+ }
20
+ let match;
21
+ if (receiver && (match = line.match(/"idVendor" = (\d+)/))) receiver.vid = Number(match[1]);
22
+ if (receiver && (match = line.match(/"idProduct" = (\d+)/))) receiver.pid = Number(match[1]);
23
+ if ((match = line.match(/"bInterfaceNumber" = (\d+)/))) iface = Number(match[1]);
24
+ if (!client) continue;
25
+ if ((match = line.match(/"IOUserClientCreator" = "pid (\d+), ([^"]+)"/))) {
26
+ client.pid = Number(match[1]); client.name = match[2].replace(/[\x00-\x1f\x7f]/g, '').slice(0, 80);
27
+ }
28
+ if ((match = line.match(/"ClientOptions"=(\d+)/))) {
29
+ client.exclusive = (Number(match[1]) & 1) !== 0 && /"ClientOpened"=Yes/.test(line);
30
+ }
31
+ if (client.exclusive && client.pid && !client.recorded) { owners.push(client); client.recorded = true; }
32
+ }
33
+ const matches = item => item?.vid === 0xabc9 && item?.pid === 0xca89;
34
+ return {
35
+ receiverPresent: receivers.some(matches),
36
+ owners: owners.filter(item => matches(item.receiver) && item.iface === 1 && item.pid !== workerPid)
37
+ .map(({ pid, name }) => ({ pid, name })),
38
+ };
39
+ }
40
+
41
+ export async function diagnoseUsb(workerPid, { platform = process.platform, execute = run } = {}) {
42
+ if (platform !== 'darwin') return '';
43
+ const { stdout } = await execute('/usr/sbin/ioreg', ['-r', '-n', 'uMouse', '-l', '-w', '0'], { timeout: 2000, maxBuffer: 8 * 1024 * 1024 });
44
+ const result = parseUsbOwners(stdout, workerPid);
45
+ if (result.owners.length) {
46
+ const names = [...new Set(result.owners.map(item => item.name))].join('、');
47
+ return `鼠标 USB 数据接口被 ${names} 占用,请退出该应用;释放后会自动重试连接。`;
48
+ }
49
+ return result.receiverPresent
50
+ ? '已检测到 2.4G 接收器,正在等待鼠标响应。请确认鼠标已开机并切到 2.4G 模式。'
51
+ : '正在查找智能鼠标,请插入 2.4G 接收器或连接蓝牙。';
52
+ }