better-dsh-pet 0.2.5 → 0.3.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.
@@ -136,6 +136,13 @@ export class HelperProcess {
136
136
  child.kill()
137
137
  }
138
138
 
139
+ /** 用户主动关闭:只禁止退出后自动重启,不主动杀进程,让 Helper 自己优雅退出。 */
140
+ suppressRestart() {
141
+ this.restartSuppressed = true
142
+ if (this.restartTimer) clearTimeout(this.restartTimer)
143
+ this.restartTimer = undefined
144
+ }
145
+
139
146
  #scheduleRestart() {
140
147
  if (this.restartTimer || this.stopping || this.restartSuppressed) return
141
148
  const delay = this.options.restartDelayMs ?? 750
@@ -0,0 +1,148 @@
1
+ /**
2
+ * sensevoice.js —— 宿主端本地语音转写(SenseVoice + sherpa-onnx-node)。
3
+ *
4
+ * 参考 dsh-voice-local 的封装方式:
5
+ * - recognizer 单例复用,模型只加载一次
6
+ * - decode 串行化
7
+ * - 输入 WAV 统一转成 16kHz 单声道 float32
8
+ */
9
+ import { createRequire } from 'node:module'
10
+ import { homedir } from 'node:os'
11
+ import { join, isAbsolute } from 'node:path'
12
+ import { existsSync } from 'node:fs'
13
+
14
+ const require = createRequire(import.meta.url)
15
+ export const TARGET_SAMPLE_RATE = 16000
16
+
17
+ export function defaultModelDir() {
18
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
19
+ return join(home, 'voice', 'sensevoice')
20
+ }
21
+
22
+ export function resolveModelDir(dir) {
23
+ if (typeof dir === 'string' && dir.trim() !== '') {
24
+ return isAbsolute(dir) ? dir : join(process.cwd(), dir)
25
+ }
26
+ if (typeof process.env.DSH_VOICE_MODEL_DIR === 'string' && process.env.DSH_VOICE_MODEL_DIR.trim() !== '') {
27
+ return process.env.DSH_VOICE_MODEL_DIR.trim()
28
+ }
29
+ return defaultModelDir()
30
+ }
31
+
32
+ export function modelFiles(dir = resolveModelDir()) {
33
+ return {
34
+ model: join(dir, 'model.int8.onnx'),
35
+ tokens: join(dir, 'tokens.txt'),
36
+ }
37
+ }
38
+
39
+ export function modelReady(dir = resolveModelDir()) {
40
+ const { model, tokens } = modelFiles(dir)
41
+ return existsSync(model) && existsSync(tokens)
42
+ }
43
+
44
+ let recognizer = null
45
+ let recognizerDir = null
46
+ let queue = Promise.resolve()
47
+
48
+ function loadRecognizer(dir) {
49
+ const sherpa = require('sherpa-onnx-node/non-streaming-asr.js')
50
+ const { OfflineRecognizer } = sherpa
51
+ const { model, tokens } = modelFiles(dir)
52
+ return new OfflineRecognizer({
53
+ modelConfig: {
54
+ senseVoice: {
55
+ model,
56
+ language: 'auto',
57
+ useInverseTextNormalization: 1,
58
+ },
59
+ tokens,
60
+ provider: 'cpu',
61
+ numThreads: 4,
62
+ },
63
+ featConfig: { sampleRate: TARGET_SAMPLE_RATE, featureDim: 80 },
64
+ })
65
+ }
66
+
67
+ async function ensureRecognizer(dir = resolveModelDir()) {
68
+ if (recognizer !== null && recognizerDir === dir) return recognizer
69
+ if (!modelReady(dir)) {
70
+ throw new Error('SenseVoice 模型未就绪:请先运行 npm run download:sensevoice 或等待自动下载')
71
+ }
72
+ recognizer = loadRecognizer(dir)
73
+ recognizerDir = dir
74
+ return recognizer
75
+ }
76
+
77
+ /** 解析 WAV(支持 PCM16 单/双声道)为 16kHz 单声道 Float32Array。 */
78
+ export function wavToFloat32(buffer) {
79
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)
80
+ if (buffer.length < 44) throw new Error('invalid WAV: too short')
81
+ if (view.getUint32(0, true) !== 0x46464952) throw new Error('invalid WAV: not RIFF')
82
+ let channels = 1
83
+ let sampleRate = 16000
84
+ let bitsPerSample = 16
85
+ let dataOffset = -1
86
+ let dataLength = 0
87
+ let offset = 12
88
+ while (offset + 8 <= buffer.length) {
89
+ const id = String.fromCharCode(view.getUint8(offset), view.getUint8(offset + 1), view.getUint8(offset + 2), view.getUint8(offset + 3))
90
+ const size = view.getUint32(offset + 4, true)
91
+ if (id === 'fmt ') {
92
+ channels = view.getUint16(offset + 10, true)
93
+ sampleRate = view.getUint32(offset + 12, true)
94
+ bitsPerSample = view.getUint16(offset + 22, true)
95
+ } else if (id === 'data') {
96
+ dataOffset = offset + 8
97
+ dataLength = size
98
+ break
99
+ }
100
+ offset += 8 + size + (size % 2)
101
+ }
102
+ if (dataOffset < 0) throw new Error('invalid WAV: no data chunk')
103
+ if (bitsPerSample !== 16) throw new Error(`unsupported WAV bits: ${bitsPerSample}`)
104
+ const bytesPerSample = bitsPerSample / 8
105
+ const frameCount = Math.floor(dataLength / (bytesPerSample * channels))
106
+ const samples = new Float32Array(frameCount)
107
+ for (let i = 0; i < frameCount; i++) {
108
+ let sum = 0
109
+ for (let ch = 0; ch < channels; ch++) {
110
+ const byteIndex = dataOffset + (i * channels + ch) * bytesPerSample
111
+ const int16 = view.getInt16(byteIndex, true)
112
+ sum += int16 / 32768
113
+ }
114
+ samples[i] = channels > 1 ? sum / channels : sum
115
+ }
116
+ if (sampleRate === TARGET_SAMPLE_RATE) return samples
117
+ return resampleLinear(samples, sampleRate, TARGET_SAMPLE_RATE)
118
+ }
119
+
120
+ function resampleLinear(input, fromRate, toRate) {
121
+ if (input.length === 0) return new Float32Array(0)
122
+ const ratio = fromRate / toRate
123
+ const outputLength = Math.max(1, Math.round(input.length / ratio))
124
+ const output = new Float32Array(outputLength)
125
+ for (let i = 0; i < outputLength; i++) {
126
+ const pos = i * ratio
127
+ const index = Math.floor(pos)
128
+ const frac = pos - index
129
+ const a = input[Math.min(index, input.length - 1)]
130
+ const b = input[Math.min(index + 1, input.length - 1)]
131
+ output[i] = a + (b - a) * frac
132
+ }
133
+ return output
134
+ }
135
+
136
+ /** 转写 WAV Buffer,返回文本。 */
137
+ export async function transcribeWav(buffer, dir = resolveModelDir()) {
138
+ const samples = wavToFloat32(buffer)
139
+ const rec = await ensureRecognizer(dir)
140
+ const run = () => {
141
+ const stream = rec.createStream()
142
+ stream.acceptWaveform({ samples, sampleRate: TARGET_SAMPLE_RATE })
143
+ return rec.decodeAsync(stream)
144
+ }
145
+ const result = await (queue = queue.then(run, run))
146
+ const text = result?.text || ''
147
+ return text.trim()
148
+ }
@@ -1,49 +1,58 @@
1
- /**
2
- * ============================================================================
3
- * better-dsh-pet 浏览器半侧的类型声明(TypeScript)
4
- * ============================================================================
5
- *
6
- * 【用途】
7
- * 给 lib/client.js(浏览器半侧)提供类型信息。纯类型文件,不影响运行时。
8
- *
9
- * 【对应实现】
10
- * lib/client.js —— 不再渲染网页浮动宠物,只在 DSH 设置页注册“小宠物桌面伴侣”
11
- * 配置卡片,通过 /plugins/better-dsh-pet/config 读写宿主配置。
12
- *
13
- * ============================================================================
14
- * @module better-dsh-pet/client
15
- */
16
- import type { Context } from '@deepseek-ai/dsh-client-runtime';
17
-
18
- /** Cordis 插件名(loader 诊断用),与 lib/client.js 的 name 一致 */
19
- export declare const name = 'pet';
20
- /** 需要注入的服务列表(slots 槽位注册表),与 lib/client.js 的 inject 一致 */
21
- export declare const inject: string[];
22
-
23
- /** 客户端插件配置(目前只用于设置卡片展示,实际值由宿主 /config 提供) */
24
- export interface Config {
25
- enabled?: boolean;
26
- scale?: number;
27
- bubbleScale?: number;
28
- activityLevel?: 'quiet' | 'normal' | 'lively';
29
- reducedMotion?: boolean;
30
- bubbleMode?: 'always' | 'hidden' | 'custom';
31
- bubbleStates?: string[];
32
- includeSubagents?: boolean;
33
- workMinutes?: number;
34
- breakMinutes?: number;
35
- roastEnabled?: boolean;
36
- walkEnabled?: boolean;
37
- enabledActions?: string[];
38
- actionOrder?: string[];
39
- petSize?: number;
40
- moveChance?: number;
41
- actionDelayMs?: number;
42
- }
43
-
44
- /**
45
- * 客户端插件主体:注册设置卡片到 `settings.plugin.item`。
46
- * @param ctx - 客户端根上下文(ctx.slots 提供槽位注册)
47
- * @param config - 本行配置(来自 patch 树;当前实际为空对象)
48
- */
49
- export declare function apply(ctx: Context, config: Config): void;
1
+ /**
2
+ * ============================================================================
3
+ * better-dsh-pet 浏览器半侧的类型声明(TypeScript)
4
+ * ============================================================================
5
+ *
6
+ * 【用途】
7
+ * 给 lib/client.js(浏览器半侧)提供类型信息。纯类型文件,不影响运行时。
8
+ *
9
+ * 【对应实现】
10
+ * lib/client.js —— 不再渲染网页浮动宠物,只在 DSH 设置页注册“小宠物桌面伴侣”
11
+ * 配置卡片,通过 /plugins/better-dsh-pet/config 读写宿主配置。
12
+ *
13
+ * ============================================================================
14
+ * @module better-dsh-pet/client
15
+ */
16
+ import type { Context } from '@deepseek-ai/dsh-client-runtime';
17
+
18
+ /** Cordis 插件名(loader 诊断用),与 lib/client.js 的 name 一致 */
19
+ export declare const name = 'pet';
20
+ /** 需要注入的服务列表(slots 槽位注册表),与 lib/client.js 的 inject 一致 */
21
+ export declare const inject: string[];
22
+
23
+ /** 客户端插件配置(目前只用于设置卡片展示,实际值由宿主 /config 提供) */
24
+ export interface Config {
25
+ enabled?: boolean;
26
+ scale?: number;
27
+ bubbleScale?: number;
28
+ activityLevel?: 'quiet' | 'normal' | 'lively';
29
+ reducedMotion?: boolean;
30
+ bubbleMode?: 'always' | 'hidden' | 'custom';
31
+ bubbleStates?: string[];
32
+ includeSubagents?: boolean;
33
+ workMinutes?: number;
34
+ breakMinutes?: number;
35
+ roastEnabled?: boolean;
36
+ walkEnabled?: boolean;
37
+ enabledActions?: string[];
38
+ actionOrder?: string[];
39
+ petSize?: number;
40
+ moveChance?: number;
41
+ actionDelayMs?: number;
42
+ playbackRate?: number;
43
+ voiceEnabled?: boolean;
44
+ voiceWakeAutoStart?: boolean;
45
+ voiceSilenceMs?: number;
46
+ voiceAutoSend?: boolean;
47
+ voiceAutoRecord?: boolean;
48
+ holidayEnabled?: boolean;
49
+ wakeWord?: string;
50
+ taskCwd?: string;
51
+ }
52
+
53
+ /**
54
+ * 客户端插件主体:注册设置卡片到 `settings.plugin.item`。
55
+ * @param ctx - 客户端根上下文(ctx.slots 提供槽位注册)
56
+ * @param config - 本行配置(来自 patch 树;当前实际为空对象)
57
+ */
58
+ export declare function apply(ctx: Context, config: Config): void;
@@ -1,77 +1,97 @@
1
- /**
2
- * ============================================================================
3
- * better-dsh-pet 宿主半侧的类型声明(TypeScript)
4
- * ============================================================================
5
- *
6
- * 【用途】
7
- * 给 lib/index.js(宿主半侧)提供类型信息,让 TypeScript 用户/编辑器
8
- * 在 import 本包时获得智能提示和类型检查。纯类型文件,不影响运行时。
9
- *
10
- * 【对应实现】
11
- * lib/index.js —— 监听 DSH session 事件,驱动 Electron 桌面 Helper,
12
- * 并注册 /plugins/better-dsh-pet/config 设置端点与 /pet 静态资源路由。
13
- *
14
- * ============================================================================
15
- * @module better-dsh-pet
16
- */
17
- import type { Context } from '@deepseek-ai/cordis';
18
- import type { WebRoute } from '@deepseek-ai/dsh-host-webserver';
19
-
20
- /** Cordis 插件名(loader 诊断用),与 lib/index.js 的 name 一致 */
21
- export declare const name = 'pet';
22
- /** 需要注入的服务列表(sessions),与 lib/index.js 的 inject 一致 */
23
- export declare const inject: string[];
24
-
25
- /** 插件配置:桌面气泡与状态联动 */
26
- export interface Config {
27
- /** 是否启用桌面小宠物。默认 true。 */
28
- enabled?: boolean;
29
- /** 角色大小(0.7~1.4)。默认 1。 */
30
- scale?: number;
31
- /** 气泡大小(0.8~1.2)。默认 1。 */
32
- bubbleScale?: number;
33
- /** 空闲微动作频率:quiet / normal / lively。默认 normal。 */
34
- activityLevel?: 'quiet' | 'normal' | 'lively';
35
- /** 减少动态效果。默认 false。 */
36
- reducedMotion?: boolean;
37
- /** 气泡显示模式:always / hidden / custom。默认 always。 */
38
- bubbleMode?: 'always' | 'hidden' | 'custom';
39
- /** 自定义模式下显示气泡的状态。 */
40
- bubbleStates?: string[];
41
- /** 是否允许子 Agent 抢占宠物状态。默认 false。 */
42
- includeSubagents?: boolean;
43
- /** 番茄钟工作时长(分钟)。默认 25。 */
44
- workMinutes?: number;
45
- /** 番茄钟休息时长(分钟)。默认 5。 */
46
- breakMinutes?: number;
47
- /** 是否根据本次对话自动吐槽(会消耗 Token)。默认 false。 */
48
- roastEnabled?: boolean;
49
- /** 待机时是否允许走动。默认 true。 */
50
- walkEnabled?: boolean;
51
- /** 自定义待机动作(留空=全部动作)。 */
52
- enabledActions?: string[];
53
- /** 自定义待机动作播放顺序(留空=随机)。 */
54
- actionOrder?: string[];
55
- /** 宠物宽度(px)。默认 460。 */
56
- petSize?: number;
57
- /** 移动频繁度(百分比)。默认 20。 */
58
- moveChance?: number;
59
- /** 动作切换间隔(毫秒)。默认 0。 */
60
- actionDelayMs?: number;
61
- /** 旧版 /pet 路由的 full 资源根目录。 */
62
- fullRoot?: string;
63
- /** Helper 进程选项。 */
64
- helper?: {
65
- /** Electron 可执行文件路径;缺省时尝试 DSH_PET_ELECTRON_PATH / require('electron')。 */
66
- electronPath?: string;
67
- };
68
- }
69
-
70
- /**
71
- * 宿主插件主体:监听 DSH 状态并驱动桌面 Helper。
72
- * @param ctx - 插件上下文;ctx.sessions 提供会话事件
73
- * @param config - 本行配置(来自 patch 树)
74
- */
75
- export declare function apply(ctx: Context, config: Config): void;
76
-
77
- export type { WebRoute };
1
+ /**
2
+ * ============================================================================
3
+ * better-dsh-pet 宿主半侧的类型声明(TypeScript)
4
+ * ============================================================================
5
+ *
6
+ * 【用途】
7
+ * 给 lib/index.js(宿主半侧)提供类型信息,让 TypeScript 用户/编辑器
8
+ * 在 import 本包时获得智能提示和类型检查。纯类型文件,不影响运行时。
9
+ *
10
+ * 【对应实现】
11
+ * lib/index.js —— 监听 DSH session 事件,驱动 Electron 桌面 Helper,
12
+ * 并注册 /plugins/better-dsh-pet/config 设置端点、/plugins/better-dsh-pet/festival
13
+ * 节日播放端点与 /pet 静态资源路由。
14
+ *
15
+ * ============================================================================
16
+ * @module better-dsh-pet
17
+ */
18
+ import type { Context } from '@deepseek-ai/cordis';
19
+ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver';
20
+
21
+ /** Cordis 插件名(loader 诊断用),与 lib/index.js 的 name 一致 */
22
+ export declare const name = 'pet';
23
+ /** 需要注入的服务列表(sessions),与 lib/index.js 的 inject 一致 */
24
+ export declare const inject: string[];
25
+ export declare const FESTIVAL_PLAY_ENDPOINT: '/plugins/better-dsh-pet/festival';
26
+
27
+ /** 插件配置:桌面气泡与状态联动 */
28
+ export interface Config {
29
+ /** 是否启用桌面小宠物。默认 true。 */
30
+ enabled?: boolean;
31
+ /** 角色大小(0.7~1.4)。默认 1。 */
32
+ scale?: number;
33
+ /** 气泡大小(0.8~1.2)。默认 1。 */
34
+ bubbleScale?: number;
35
+ /** 空闲微动作频率:quiet / normal / lively。默认 normal。 */
36
+ activityLevel?: 'quiet' | 'normal' | 'lively';
37
+ /** 减少动态效果。默认 false。 */
38
+ reducedMotion?: boolean;
39
+ /** 气泡显示模式:always / hidden / custom。默认 always。 */
40
+ bubbleMode?: 'always' | 'hidden' | 'custom';
41
+ /** 自定义模式下显示气泡的状态。 */
42
+ bubbleStates?: string[];
43
+ /** 是否允许子 Agent 抢占宠物状态。默认 false。 */
44
+ includeSubagents?: boolean;
45
+ /** 番茄钟工作时长(分钟)。默认 25。 */
46
+ workMinutes?: number;
47
+ /** 番茄钟休息时长(分钟)。默认 5。 */
48
+ breakMinutes?: number;
49
+ /** 是否根据本次对话自动吐槽(会消耗 Token)。默认 false。 */
50
+ roastEnabled?: boolean;
51
+ /** 待机时是否允许走动。默认 true。 */
52
+ walkEnabled?: boolean;
53
+ /** 自定义待机动作(留空=全部动作)。 */
54
+ enabledActions?: string[];
55
+ /** 自定义待机动作播放顺序(留空=随机)。 */
56
+ actionOrder?: string[];
57
+ /** 宠物宽度(px)。默认 460。 */
58
+ petSize?: number;
59
+ /** 移动频繁度(百分比)。默认 20。 */
60
+ moveChance?: number;
61
+ /** 动作切换间隔(毫秒)。默认 0。 */
62
+ actionDelayMs?: number;
63
+ /** 动画播放速度(1.0~2.0)。默认 1。 */
64
+ playbackRate?: number;
65
+ /** 是否启用语音功能(麦克风)。默认 true。 */
66
+ voiceEnabled?: boolean;
67
+ /** 启动桌宠时自动开启语音唤醒(麦克风)。默认 false。 */
68
+ voiceWakeAutoStart?: boolean;
69
+ /** 语音断句静音时长(毫秒)。默认 1200。 */
70
+ voiceSilenceMs?: number;
71
+ /** 语音识别后自动发送。默认 true。 */
72
+ voiceAutoSend?: boolean;
73
+ /** 闲聊时说“大肥鱼”自动开始录音。默认 true。 */
74
+ voiceAutoRecord?: boolean;
75
+ /** 启用节日祝福识别(阳历与农历)。默认 false。 */
76
+ holidayEnabled?: boolean;
77
+ /** 语音唤醒词。默认“大肥鱼”。 */
78
+ wakeWord?: string;
79
+ /** 复杂任务工作目录(留空=用户主目录)。 */
80
+ taskCwd?: string;
81
+ /** 旧版 /pet 路由的 full 资源根目录。 */
82
+ fullRoot?: string;
83
+ /** Helper 进程选项。 */
84
+ helper?: {
85
+ /** Electron 可执行文件路径;缺省时尝试 DSH_PET_ELECTRON_PATH / require('electron')。 */
86
+ electronPath?: string;
87
+ };
88
+ }
89
+
90
+ /**
91
+ * 宿主插件主体:监听 DSH 状态并驱动桌面 Helper。
92
+ * @param ctx - 插件上下文;ctx.sessions 提供会话事件
93
+ * @param config - 本行配置(来自 patch 树)
94
+ */
95
+ export declare function apply(ctx: Context, config: Config): void;
96
+
97
+ export type { WebRoute };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "better-dsh-pet",
3
- "version": "0.2.5",
4
- "description": "A desktop-native pet bubble driven by DeepSeek Harness session events: transparent always-on-top Electron window, status-aware animations, balance, pomodoro, roast, and DSH settings card.",
3
+ "version": "0.3.0",
4
+ "description": "A desktop-native pet bubble driven by DeepSeek Harness session events: transparent always-on-top Electron window, status-aware animations, voice chat/wake, real DSH task execution, emotion, festival, balance, pomodoro, roast, and DSH settings card.",
5
5
  "keywords": [
6
6
  "dsh",
7
7
  "dsh-plugin",
@@ -9,6 +9,11 @@
9
9
  "desktop-pet",
10
10
  "pet",
11
11
  "floating-widget",
12
+ "voice",
13
+ "wake-word",
14
+ "task-execution",
15
+ "emotion",
16
+ "festival",
12
17
  "web-ui",
13
18
  "cordis",
14
19
  "react"
@@ -28,7 +33,7 @@
28
33
  "exports['./client'] —— 浏览器半侧入口,DSH 模块系统按它提供 /plugins/better-dsh-pet/client.js",
29
34
  "dsh.bundle.patch —— 声明本包是 bundle,patch 文件是 cordis.patch.yml(安装后自动进层栈)",
30
35
  "dsh.client —— 声明浏览器半侧的注入依赖和平台(web)",
31
- "files —— npm publish 只发这些目录/文件(assets/thumb 播放资源;assets/preview 的 GIF 仅 README 展示、不入包)",
36
+ "files —— npm publish 只发这些目录/文件(assets/thumb 播放资源;节日 GIF 仅按需纳入个别文件)",
32
37
  "scripts.encode:thumbs —— 转码管线(step03 母版 → assets/thumb 360×360)",
33
38
  "scripts.prepack —— 发布前自动健康检查",
34
39
  "peerDependencies —— 运行时由宿主(DSH)提供的模块,本包不打包它们",
@@ -52,16 +57,21 @@
52
57
  "lib",
53
58
  "runtime/electron-helper",
54
59
  "assets/thumb",
60
+ "assets/preview/zhongqiu-shangyue-chi-yuebing.gif",
55
61
  "assets/alarm.mp3",
62
+ "assets/tray-icon.png",
56
63
  "cordis.patch.yml",
57
- "scripts/ensure-electron.mjs"
64
+ "scripts/ensure-electron.mjs",
65
+ "scripts/download-sensevoice.mjs"
58
66
  ],
59
67
  "scripts": {
60
- "prepack": "node scripts/prepack-check.js"
68
+ "prepack": "node scripts/prepack-check.js",
69
+ "download:sensevoice": "node scripts/download-sensevoice.mjs"
61
70
  },
62
71
  "license": "MIT",
63
72
  "dependencies": {
64
- "@deepseek-ai/schemastery": "^3.18.1"
73
+ "@deepseek-ai/schemastery": "^3.18.1",
74
+ "sherpa-onnx-node": "1.13.5"
65
75
  },
66
76
  "dsh": {
67
77
  "bundle": {