better-dsh-pet 0.2.6 → 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.
- package/README.md +272 -36
- package/assets/preview/zhongqiu-shangyue-chi-yuebing.gif +0 -0
- package/assets/tray-icon.png +0 -0
- package/cordis.patch.yml +51 -42
- package/lib/client.js +161 -1
- package/lib/index.js +1073 -636
- package/lib/pet-helper-process.js +7 -0
- package/lib/sensevoice.js +148 -0
- package/lib/types/client/index.d.ts +58 -49
- package/lib/types/index.d.ts +97 -77
- package/package.json +16 -6
- package/runtime/electron-helper/index.html +256 -0
- package/runtime/electron-helper/main.js +740 -206
- package/runtime/electron-helper/preload.js +47 -0
- package/runtime/electron-helper/renderer.js +2792 -1349
- package/scripts/download-sensevoice.mjs +92 -0
package/lib/index.js
CHANGED
|
@@ -1,636 +1,1073 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* ============================================================================
|
|
3
|
-
* better-dsh-pet 宿主半侧(host half)—— 桌面宠物插件的 DSH 服务端入口
|
|
4
|
-
* ============================================================================
|
|
5
|
-
*
|
|
6
|
-
* 联动模型(桌面独立气泡版):
|
|
7
|
-
* - 插件由 DSH 启动/停止,不要求用户单独打开桌宠;
|
|
8
|
-
* - 监听 DSH 的 session/event,把真实 Agent 状态压缩成状态对象;
|
|
9
|
-
* - 通过 /plugins/better-dsh-pet/status HTTP 端点暴露给 Electron 桌面 Helper;
|
|
10
|
-
* - Electron Helper 轮询该端点,驱动透明置顶气泡窗口播放对应动画;
|
|
11
|
-
* - 在 DSH 设置页暴露配置项(大小、气泡、活跃度等)。
|
|
12
|
-
*
|
|
13
|
-
* 本文件同时保留 /pet/thumb 静态资源路由,方便需要直接访问动画的旧版页面。
|
|
14
|
-
* ============================================================================
|
|
15
|
-
*/
|
|
16
|
-
import Schema from '@deepseek-ai/schemastery'
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
export const
|
|
34
|
-
export const
|
|
35
|
-
|
|
36
|
-
export const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
return
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
}
|
|
381
|
-
})
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
const
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
const
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
const
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
()
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
1
|
+
/**
|
|
2
|
+
* ============================================================================
|
|
3
|
+
* better-dsh-pet 宿主半侧(host half)—— 桌面宠物插件的 DSH 服务端入口
|
|
4
|
+
* ============================================================================
|
|
5
|
+
*
|
|
6
|
+
* 联动模型(桌面独立气泡版):
|
|
7
|
+
* - 插件由 DSH 启动/停止,不要求用户单独打开桌宠;
|
|
8
|
+
* - 监听 DSH 的 session/event,把真实 Agent 状态压缩成状态对象;
|
|
9
|
+
* - 通过 /plugins/better-dsh-pet/status HTTP 端点暴露给 Electron 桌面 Helper;
|
|
10
|
+
* - Electron Helper 轮询该端点,驱动透明置顶气泡窗口播放对应动画;
|
|
11
|
+
* - 在 DSH 设置页暴露配置项(大小、气泡、活跃度等)。
|
|
12
|
+
*
|
|
13
|
+
* 本文件同时保留 /pet/thumb 静态资源路由,方便需要直接访问动画的旧版页面。
|
|
14
|
+
* ============================================================================
|
|
15
|
+
*/
|
|
16
|
+
import Schema from '@deepseek-ai/schemastery'
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
18
|
+
import { createReadStream, existsSync, readFileSync } from 'node:fs'
|
|
19
|
+
import { homedir } from 'node:os'
|
|
20
|
+
import { stat } from 'node:fs/promises'
|
|
21
|
+
import { join, normalize, resolve, sep } from 'node:path'
|
|
22
|
+
import { fileURLToPath } from 'node:url'
|
|
23
|
+
import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
|
|
24
|
+
import { CompanionReducer } from './pet-reducer.js'
|
|
25
|
+
import { HelperProcess } from './pet-helper-process.js'
|
|
26
|
+
import { modelReady, transcribeWav } from './sensevoice.js'
|
|
27
|
+
import {
|
|
28
|
+
CompanionMessageKind,
|
|
29
|
+
CompanionState,
|
|
30
|
+
} from './pet-protocol.js'
|
|
31
|
+
const PACKAGE_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)))
|
|
32
|
+
|
|
33
|
+
export const name = 'better-dsh-pet'
|
|
34
|
+
export const inject = ['sessions', 'subagents', 'agents', 'workspaceRegistry']
|
|
35
|
+
export const CONFIG_ENDPOINT = '/plugins/better-dsh-pet/config'
|
|
36
|
+
export const STATUS_ENDPOINT = '/plugins/better-dsh-pet/status'
|
|
37
|
+
export const CLOSE_ENDPOINT = '/plugins/better-dsh-pet/close'
|
|
38
|
+
export const CHAT_ENDPOINT = '/plugins/better-dsh-pet/chat'
|
|
39
|
+
export const TRANSCRIBE_ENDPOINT = '/plugins/better-dsh-pet/transcribe'
|
|
40
|
+
export const FESTIVAL_PLAY_ENDPOINT = '/plugins/better-dsh-pet/festival'
|
|
41
|
+
export const INTENT_ENDPOINT = '/plugins/better-dsh-pet/intent'
|
|
42
|
+
export const TASK_ENDPOINT = '/plugins/better-dsh-pet/task'
|
|
43
|
+
export const ROUTE_PREFIX = '/pet'
|
|
44
|
+
|
|
45
|
+
export const Config = Schema.object({
|
|
46
|
+
enabled: Schema.boolean().default(true).description('启用桌面小宠物'),
|
|
47
|
+
scale: Schema.number().min(0.7).max(1.4).step(0.05).default(1).role('slider').description('角色大小'),
|
|
48
|
+
bubbleScale: Schema.number().min(0.8).max(1.2).step(0.05).default(1).role('slider').description('气泡大小'),
|
|
49
|
+
activityLevel: Schema.union([
|
|
50
|
+
Schema.const('quiet').description('安静'),
|
|
51
|
+
Schema.const('normal').description('标准'),
|
|
52
|
+
Schema.const('lively').description('活泼'),
|
|
53
|
+
]).default('normal').description('空闲微动作频率'),
|
|
54
|
+
reducedMotion: Schema.boolean().default(false).description('减少走动、循环帧和程序化晃动'),
|
|
55
|
+
bubbleMode: Schema.union([
|
|
56
|
+
Schema.const('always').description('常驻显示'),
|
|
57
|
+
Schema.const('hidden').description('完全隐藏'),
|
|
58
|
+
Schema.const('custom').description('自定义显示状态'),
|
|
59
|
+
]).default('always').description('气泡显示模式'),
|
|
60
|
+
bubbleStates: Schema.array(Schema.string()).default(['SUCCESS', 'ERROR', 'WAITING']).description('自定义模式下显示气泡的状态'),
|
|
61
|
+
includeSubagents: Schema.boolean().default(false).description('允许子 Agent 抢占宠物状态'),
|
|
62
|
+
workMinutes: Schema.number().min(1).max(120).step(1).default(25).description('番茄钟工作时长(分钟)'),
|
|
63
|
+
breakMinutes: Schema.number().min(1).max(60).step(1).default(5).description('番茄钟休息时长(分钟)'),
|
|
64
|
+
roastEnabled: Schema.boolean().default(false).description('根据本次对话自动吐槽(会消耗 Token)'),
|
|
65
|
+
walkEnabled: Schema.boolean().default(true).description('待机时是否允许走动'),
|
|
66
|
+
enabledActions: Schema.array(Schema.string()).default([]).description('自定义待机动作(留空=全部动作)'),
|
|
67
|
+
actionOrder: Schema.array(Schema.string()).default([]).description('自定义待机动作播放顺序(留空=随机)'),
|
|
68
|
+
petSize: Schema.number().min(100).max(1000).step(10).default(460).description('宠物宽度(px)'),
|
|
69
|
+
moveChance: Schema.number().min(0).max(100).step(1).default(20).description('移动频繁度(百分比)'),
|
|
70
|
+
actionDelayMs: Schema.number().min(0).max(5000).step(100).default(0).description('动作切换间隔(毫秒)'),
|
|
71
|
+
playbackRate: Schema.number().min(1).max(2).step(0.1).default(1).role('slider').description('动画播放速度(1.0x~2.0x)'),
|
|
72
|
+
voiceEnabled: Schema.boolean().default(true).description('是否启用语音功能(麦克风)'),
|
|
73
|
+
voiceWakeAutoStart: Schema.boolean().default(false).description('启动桌宠时自动开启语音唤醒(麦克风)'),
|
|
74
|
+
voiceSilenceMs: Schema.number().min(300).max(5000).step(100).default(1200).description('语音断句静音时长(毫秒)'),
|
|
75
|
+
voiceAutoSend: Schema.boolean().default(true).description('语音识别后自动发送'),
|
|
76
|
+
voiceAutoRecord: Schema.boolean().default(true).description('闲聊时说“大肥鱼”自动开始录音'),
|
|
77
|
+
holidayEnabled: Schema.boolean().default(false).description('启用节日祝福识别(阳历与农历)'),
|
|
78
|
+
wakeWord: Schema.string().default('大肥鱼').description('语音唤醒词(例如:大肥鱼)'),
|
|
79
|
+
taskCwd: Schema.string().default('').description('复杂任务工作目录(留空=用户主目录)'),
|
|
80
|
+
}).description('由 DeepSeek Harness 状态驱动的桌面大肥鱼')
|
|
81
|
+
|
|
82
|
+
const defaults = Object.freeze({
|
|
83
|
+
enabled: true,
|
|
84
|
+
scale: 1,
|
|
85
|
+
bubbleScale: 1,
|
|
86
|
+
activityLevel: 'normal',
|
|
87
|
+
reducedMotion: false,
|
|
88
|
+
bubbleMode: 'always',
|
|
89
|
+
bubbleStates: ['SUCCESS', 'ERROR', 'WAITING'],
|
|
90
|
+
includeSubagents: false,
|
|
91
|
+
workMinutes: 25,
|
|
92
|
+
breakMinutes: 5,
|
|
93
|
+
roastEnabled: false,
|
|
94
|
+
walkEnabled: true,
|
|
95
|
+
enabledActions: [],
|
|
96
|
+
actionOrder: [],
|
|
97
|
+
petSize: 460,
|
|
98
|
+
moveChance: 20,
|
|
99
|
+
actionDelayMs: 0,
|
|
100
|
+
playbackRate: 1,
|
|
101
|
+
voiceEnabled: true,
|
|
102
|
+
voiceWakeAutoStart: false,
|
|
103
|
+
voiceSilenceMs: 1200,
|
|
104
|
+
voiceAutoSend: true,
|
|
105
|
+
voiceAutoRecord: true,
|
|
106
|
+
holidayEnabled: false,
|
|
107
|
+
wakeWord: '大肥鱼',
|
|
108
|
+
taskCwd: '',
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
function publicConfig(config = {}) {
|
|
112
|
+
return {
|
|
113
|
+
enabled: config.enabled ?? defaults.enabled,
|
|
114
|
+
scale: config.scale ?? defaults.scale,
|
|
115
|
+
bubbleScale: config.bubbleScale ?? defaults.bubbleScale,
|
|
116
|
+
activityLevel: config.activityLevel ?? defaults.activityLevel,
|
|
117
|
+
reducedMotion: config.reducedMotion ?? defaults.reducedMotion,
|
|
118
|
+
bubbleMode: config.bubbleMode ?? defaults.bubbleMode,
|
|
119
|
+
bubbleStates: Array.isArray(config.bubbleStates) ? config.bubbleStates : defaults.bubbleStates,
|
|
120
|
+
includeSubagents: config.includeSubagents ?? defaults.includeSubagents,
|
|
121
|
+
workMinutes: config.workMinutes ?? defaults.workMinutes,
|
|
122
|
+
breakMinutes: config.breakMinutes ?? defaults.breakMinutes,
|
|
123
|
+
roastEnabled: config.roastEnabled ?? defaults.roastEnabled,
|
|
124
|
+
walkEnabled: config.walkEnabled ?? defaults.walkEnabled,
|
|
125
|
+
enabledActions: Array.isArray(config.enabledActions) ? config.enabledActions : defaults.enabledActions,
|
|
126
|
+
actionOrder: Array.isArray(config.actionOrder) ? config.actionOrder : defaults.actionOrder,
|
|
127
|
+
petSize: config.petSize ?? defaults.petSize,
|
|
128
|
+
moveChance: config.moveChance ?? defaults.moveChance,
|
|
129
|
+
actionDelayMs: config.actionDelayMs ?? defaults.actionDelayMs,
|
|
130
|
+
playbackRate: config.playbackRate ?? defaults.playbackRate,
|
|
131
|
+
voiceEnabled: config.voiceEnabled ?? defaults.voiceEnabled,
|
|
132
|
+
voiceWakeAutoStart: config.voiceWakeAutoStart ?? defaults.voiceWakeAutoStart,
|
|
133
|
+
voiceSilenceMs: config.voiceSilenceMs ?? defaults.voiceSilenceMs,
|
|
134
|
+
voiceAutoSend: config.voiceAutoSend ?? defaults.voiceAutoSend,
|
|
135
|
+
voiceAutoRecord: config.voiceAutoRecord ?? defaults.voiceAutoRecord,
|
|
136
|
+
holidayEnabled: config.holidayEnabled ?? defaults.holidayEnabled,
|
|
137
|
+
wakeWord: config.wakeWord || defaults.wakeWord,
|
|
138
|
+
taskCwd: config.taskCwd || defaults.taskCwd,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function localSettingsScope(value) {
|
|
143
|
+
return {
|
|
144
|
+
get: () => value,
|
|
145
|
+
watch: () => () => {},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function jsonResponse(res, status, body) {
|
|
150
|
+
const payload = JSON.stringify(body)
|
|
151
|
+
res.writeHead(status, {
|
|
152
|
+
'content-type': 'application/json; charset=utf-8',
|
|
153
|
+
'cache-control': 'no-store',
|
|
154
|
+
'content-length': Buffer.byteLength(payload),
|
|
155
|
+
})
|
|
156
|
+
res.end(payload)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function isLoopback(address) {
|
|
160
|
+
return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function readPatch(req) {
|
|
164
|
+
const chunks = []
|
|
165
|
+
let bytes = 0
|
|
166
|
+
for await (const chunk of req) {
|
|
167
|
+
bytes += chunk.length
|
|
168
|
+
if (bytes > 8192) throw new Error('request body is too large')
|
|
169
|
+
chunks.push(chunk)
|
|
170
|
+
}
|
|
171
|
+
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
172
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('patch must be an object')
|
|
173
|
+
const allowed = new Set(Object.keys(defaults))
|
|
174
|
+
if (Object.keys(value).some((key) => !allowed.has(key))) throw new Error('patch contains an unknown setting')
|
|
175
|
+
return value
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function readJsonBody(req) {
|
|
179
|
+
const chunks = []
|
|
180
|
+
let bytes = 0
|
|
181
|
+
for await (const chunk of req) {
|
|
182
|
+
bytes += chunk.length
|
|
183
|
+
if (bytes > 64 * 1024) throw new Error('request body is too large')
|
|
184
|
+
chunks.push(chunk)
|
|
185
|
+
}
|
|
186
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function createConfigHandler(settings) {
|
|
190
|
+
return async (req, res) => {
|
|
191
|
+
if (!isLoopback(req.socket?.remoteAddress)) {
|
|
192
|
+
jsonResponse(res, 403, { error: 'local access only' })
|
|
193
|
+
return
|
|
194
|
+
}
|
|
195
|
+
const origin = req.headers?.origin
|
|
196
|
+
if (origin) {
|
|
197
|
+
let originHost
|
|
198
|
+
try { originHost = new URL(origin).host } catch {}
|
|
199
|
+
if (!originHost || originHost !== req.headers.host) {
|
|
200
|
+
jsonResponse(res, 403, { error: 'origin mismatch' })
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (req.method === 'GET') {
|
|
205
|
+
jsonResponse(res, 200, settings.get())
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
if (req.method !== 'PATCH') {
|
|
209
|
+
jsonResponse(res, 405, { error: 'method not allowed' })
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
await settings.update(await readPatch(req))
|
|
214
|
+
jsonResponse(res, 200, settings.get())
|
|
215
|
+
} catch (error) {
|
|
216
|
+
jsonResponse(res, 400, { error: error instanceof Error ? error.message : String(error) })
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 旧版 /pet 静态资源路由:服务插件包内 assets/thumb 下的 WebM。 */
|
|
222
|
+
function createAssetHandler(config = {}) {
|
|
223
|
+
const packageRoot = resolve(fileURLToPath(new URL('..', import.meta.url)))
|
|
224
|
+
const thumbRoot = join(packageRoot, 'assets', 'thumb')
|
|
225
|
+
const fullRoot = config.fullRoot ?? join(resolveDshHome(), 'pet-assets')
|
|
226
|
+
const MIME = {
|
|
227
|
+
'.webm': 'video/webm',
|
|
228
|
+
'.mp4': 'video/mp4',
|
|
229
|
+
'.png': 'image/png',
|
|
230
|
+
'.json': 'application/json; charset=utf-8',
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const resolveAsset = (root, rel) => {
|
|
234
|
+
if (rel.length === 0) return undefined
|
|
235
|
+
const candidate = normalize(join(root, rel))
|
|
236
|
+
const rootWithSep = root.endsWith(sep) ? root : root + sep
|
|
237
|
+
if (candidate !== root && !candidate.startsWith(rootWithSep)) return undefined
|
|
238
|
+
return candidate
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return async (req, res) => {
|
|
242
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
243
|
+
const rest = decodeURIComponent(url.pathname.slice(ROUTE_PREFIX.length + 1))
|
|
244
|
+
const [scope, ...nameParts] = rest.split('/')
|
|
245
|
+
if (scope !== 'thumb' && scope !== 'full') {
|
|
246
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
247
|
+
res.end('better-dsh-pet: expected /pet/{thumb|full}/<file>')
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
const fileName = nameParts.join('/')
|
|
251
|
+
const root = scope === 'thumb' ? thumbRoot : fullRoot
|
|
252
|
+
const file = resolveAsset(root, fileName)
|
|
253
|
+
if (file === undefined) {
|
|
254
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
|
|
255
|
+
res.end('better-dsh-pet: invalid path')
|
|
256
|
+
return
|
|
257
|
+
}
|
|
258
|
+
if (!existsSync(file)) {
|
|
259
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
260
|
+
res.end(scope === 'full'
|
|
261
|
+
? `better-dsh-pet: original asset not downloaded yet — run the fetch-assets script to populate ${fullRoot}`
|
|
262
|
+
: 'better-dsh-pet: asset not found')
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
const ext = file.slice(file.lastIndexOf('.')).toLowerCase()
|
|
266
|
+
const contentType = MIME[ext] ?? 'application/octet-stream'
|
|
267
|
+
const { size } = await stat(file)
|
|
268
|
+
res.writeHead(200, {
|
|
269
|
+
'content-type': contentType,
|
|
270
|
+
'content-length': size,
|
|
271
|
+
'cache-control': 'public, max-age=3600',
|
|
272
|
+
})
|
|
273
|
+
const stream = createReadStream(file)
|
|
274
|
+
stream.on('error', () => { res.destroy() })
|
|
275
|
+
stream.pipe(res)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function mount(ctx, config = {}, eventCtx = ctx) {
|
|
280
|
+
const logger = ctx.logger ?? console
|
|
281
|
+
const base = publicConfig(config)
|
|
282
|
+
const settings = ctx.settings?.register?.('better-dsh-pet', Config, {
|
|
283
|
+
base,
|
|
284
|
+
applies: 'live',
|
|
285
|
+
}) ?? localSettingsScope(base)
|
|
286
|
+
|
|
287
|
+
let bridge
|
|
288
|
+
let reducer
|
|
289
|
+
let restartTimer
|
|
290
|
+
let statusUrl = config.webuiUrl
|
|
291
|
+
? String(config.webuiUrl).replace(/\/$/, '') + STATUS_ENDPOINT
|
|
292
|
+
: undefined
|
|
293
|
+
let currentStatus = {
|
|
294
|
+
state: CompanionState.IDLE,
|
|
295
|
+
message: '大肥鱼在这儿等新任务哦~',
|
|
296
|
+
detail: '大肥鱼 · 等待下一次任务',
|
|
297
|
+
project: undefined,
|
|
298
|
+
task: undefined,
|
|
299
|
+
progress: undefined,
|
|
300
|
+
}
|
|
301
|
+
let pulse = undefined
|
|
302
|
+
let tasks = []
|
|
303
|
+
let tokenUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
|
|
304
|
+
let balance = null
|
|
305
|
+
let balanceTimer = null
|
|
306
|
+
let transcript = []
|
|
307
|
+
let chatHistory = []
|
|
308
|
+
let roast = null
|
|
309
|
+
let roastTimer = null
|
|
310
|
+
let festivalPlayRequest = null
|
|
311
|
+
let userClosed = false
|
|
312
|
+
let lastEnabled = base.enabled !== false
|
|
313
|
+
const taskHandles = new Map()
|
|
314
|
+
let taskArchiveTimer = null
|
|
315
|
+
let helperWatchdogTimer = null
|
|
316
|
+
|
|
317
|
+
const getFestivalPlayRequest = () => {
|
|
318
|
+
if (!festivalPlayRequest) return null
|
|
319
|
+
if (festivalPlayRequest.expiresAt <= Date.now()) {
|
|
320
|
+
festivalPlayRequest = null
|
|
321
|
+
return null
|
|
322
|
+
}
|
|
323
|
+
return festivalPlayRequest
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const queueFestivalPlayRequest = (festivalId) => {
|
|
327
|
+
festivalPlayRequest = {
|
|
328
|
+
token: randomUUID(),
|
|
329
|
+
festivalId,
|
|
330
|
+
requestedAt: Date.now(),
|
|
331
|
+
expiresAt: Date.now() + 10000,
|
|
332
|
+
}
|
|
333
|
+
return festivalPlayRequest
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const applyMessages = (messages) => {
|
|
337
|
+
for (const message of messages) {
|
|
338
|
+
if (!message?.kind) continue
|
|
339
|
+
if (message.kind === CompanionMessageKind.STATE) {
|
|
340
|
+
pulse = undefined
|
|
341
|
+
currentStatus = {
|
|
342
|
+
...currentStatus,
|
|
343
|
+
state: message.state,
|
|
344
|
+
message: message.message || currentStatus.message,
|
|
345
|
+
detail: message.detail || currentStatus.detail,
|
|
346
|
+
project: message.project ?? currentStatus.project,
|
|
347
|
+
task: message.task ?? currentStatus.task,
|
|
348
|
+
progress: message.progress ?? currentStatus.progress,
|
|
349
|
+
}
|
|
350
|
+
} else if (message.kind === CompanionMessageKind.PULSE) {
|
|
351
|
+
const ttlMs = Number(message.ttlMs || 1800)
|
|
352
|
+
pulse = {
|
|
353
|
+
state: message.state,
|
|
354
|
+
message: message.message || '',
|
|
355
|
+
detail: message.detail || '',
|
|
356
|
+
ttlMs,
|
|
357
|
+
expiresAt: Date.now() + ttlMs,
|
|
358
|
+
resumeState: message.resumeState,
|
|
359
|
+
resumeMessage: message.resumeMessage,
|
|
360
|
+
resumeDetail: message.resumeDetail,
|
|
361
|
+
}
|
|
362
|
+
// 脉冲结束后应回到 resumeState。这里立即同步 currentStatus,
|
|
363
|
+
// 避免脉冲过期后状态接口回退到旧的“整理结果”等中间状态。
|
|
364
|
+
if (message.resumeState) {
|
|
365
|
+
currentStatus = {
|
|
366
|
+
...currentStatus,
|
|
367
|
+
state: message.resumeState,
|
|
368
|
+
message: message.resumeMessage || currentStatus.message,
|
|
369
|
+
detail: message.resumeDetail || currentStatus.detail,
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
} else if (message.kind === CompanionMessageKind.TASK) {
|
|
373
|
+
currentStatus = {
|
|
374
|
+
...currentStatus,
|
|
375
|
+
task: message.task ?? currentStatus.task,
|
|
376
|
+
progress: message.progress ?? currentStatus.progress,
|
|
377
|
+
project: message.project ?? currentStatus.project,
|
|
378
|
+
message: message.message || currentStatus.message,
|
|
379
|
+
detail: message.detail || currentStatus.detail,
|
|
380
|
+
}
|
|
381
|
+
} else if (message.kind === CompanionMessageKind.TASKS) {
|
|
382
|
+
tasks = Array.isArray(message.tasks) ? message.tasks : []
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const resolveApiKey = async () => {
|
|
388
|
+
let apiKey = process.env.DEEPSEEK_API_KEY
|
|
389
|
+
if (!apiKey) {
|
|
390
|
+
try {
|
|
391
|
+
if (eventCtx.credentials?.resolve) {
|
|
392
|
+
const resolved = await eventCtx.credentials.resolve('DEEPSEEK_API_KEY')
|
|
393
|
+
apiKey = resolved?.value
|
|
394
|
+
}
|
|
395
|
+
} catch {
|
|
396
|
+
apiKey = undefined
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
if (!apiKey) {
|
|
400
|
+
try {
|
|
401
|
+
const home = resolveDshHome()
|
|
402
|
+
const text = readFileSync(join(home, '.credentials.yaml'), 'utf8')
|
|
403
|
+
const match = text.match(/^\s*DEEPSEEK_API_KEY:\s*(.+?)\s*$/m)
|
|
404
|
+
if (match) apiKey = match[1].trim()
|
|
405
|
+
} catch {
|
|
406
|
+
apiKey = undefined
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return apiKey
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const appendTranscript = (role, content) => {
|
|
413
|
+
const text = Array.isArray(content)
|
|
414
|
+
? content.map((part) => {
|
|
415
|
+
if (typeof part === 'string') return part
|
|
416
|
+
if (part?.type === 'text') return part.text || ''
|
|
417
|
+
if (part?.text) return part.text
|
|
418
|
+
return ''
|
|
419
|
+
}).filter(Boolean).join(' ')
|
|
420
|
+
: typeof content === 'string' ? content : ''
|
|
421
|
+
if (!text.trim()) return
|
|
422
|
+
transcript.push({ role, content: text.trim() })
|
|
423
|
+
// 只保留最近 10 条,避免上下文无限增长。
|
|
424
|
+
if (transcript.length > 10) transcript = transcript.slice(-10)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const generateRoast = async (force = false) => {
|
|
428
|
+
const enabled = settings.get().roastEnabled === true
|
|
429
|
+
if (!force && !enabled) return
|
|
430
|
+
const apiKey = await resolveApiKey()
|
|
431
|
+
if (!apiKey || transcript.length === 0) return
|
|
432
|
+
// 只取最近 5 条,且每条截断到 150 字,降低 Token 消耗。
|
|
433
|
+
const recent = transcript.slice(-5).map((item) => {
|
|
434
|
+
const content = item.content.length > 150 ? `${item.content.slice(0, 150)}…` : item.content
|
|
435
|
+
return `${item.role === 'user' ? '用户' : '大肥鱼'}: ${content}`
|
|
436
|
+
}).join('\n')
|
|
437
|
+
try {
|
|
438
|
+
const response = await fetch('https://api.deepseek.com/chat/completions', {
|
|
439
|
+
method: 'POST',
|
|
440
|
+
headers: {
|
|
441
|
+
'content-type': 'application/json',
|
|
442
|
+
authorization: `Bearer ${apiKey}`,
|
|
443
|
+
},
|
|
444
|
+
body: JSON.stringify({
|
|
445
|
+
model: 'deepseek-chat',
|
|
446
|
+
messages: [
|
|
447
|
+
{ role: 'system', content: '你是一只住在 DeepSeek Harness 里的大肥鱼桌宠。请根据用户和 AI 的对话,用一句简短、可爱、俏皮的话吐槽/点评这次对话。要求:中文,不超过30个字,语气像大肥鱼,不要解释,不要引号。' },
|
|
448
|
+
{ role: 'user', content: `对话内容:\n${recent}` },
|
|
449
|
+
],
|
|
450
|
+
max_tokens: 80,
|
|
451
|
+
temperature: 1.1,
|
|
452
|
+
stream: false,
|
|
453
|
+
}),
|
|
454
|
+
})
|
|
455
|
+
if (!response.ok) return
|
|
456
|
+
const data = await response.json()
|
|
457
|
+
const text = data?.choices?.[0]?.message?.content
|
|
458
|
+
if (typeof text === 'string' && text.trim()) {
|
|
459
|
+
roast = text.trim().replace(/^["“”]+|["“”]+$/g, '')
|
|
460
|
+
}
|
|
461
|
+
} catch {
|
|
462
|
+
// 吐槽失败时静默,不影响主功能。
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const generateChatReply = async (userMessage) => {
|
|
467
|
+
const apiKey = await resolveApiKey()
|
|
468
|
+
if (!apiKey) return '我还没连上 DeepSeek API,暂时不能闲聊哦~'
|
|
469
|
+
const text = String(userMessage || '').trim()
|
|
470
|
+
if (!text) return '你说什么?我没听清~'
|
|
471
|
+
chatHistory.push({ role: 'user', content: text.slice(0, 500) })
|
|
472
|
+
if (chatHistory.length > 20) chatHistory = chatHistory.slice(-20)
|
|
473
|
+
const messages = [
|
|
474
|
+
{ role: 'system', content: '你是一只住在 DeepSeek Harness 里的大肥鱼桌宠,名字叫大肥鱼。你性格可爱、俏皮、有点懒,喜欢用短句和颜文字。请用中文简短回复,一般不超过60字。' },
|
|
475
|
+
...chatHistory,
|
|
476
|
+
]
|
|
477
|
+
try {
|
|
478
|
+
const response = await fetch('https://api.deepseek.com/chat/completions', {
|
|
479
|
+
method: 'POST',
|
|
480
|
+
headers: {
|
|
481
|
+
'content-type': 'application/json',
|
|
482
|
+
authorization: `Bearer ${apiKey}`,
|
|
483
|
+
},
|
|
484
|
+
body: JSON.stringify({
|
|
485
|
+
model: 'deepseek-chat',
|
|
486
|
+
messages,
|
|
487
|
+
max_tokens: 200,
|
|
488
|
+
temperature: 0.9,
|
|
489
|
+
stream: false,
|
|
490
|
+
}),
|
|
491
|
+
})
|
|
492
|
+
if (!response.ok) {
|
|
493
|
+
chatHistory.pop()
|
|
494
|
+
return `DeepSeek 接口出错了(${response.status}),稍后再试吧~`
|
|
495
|
+
}
|
|
496
|
+
const data = await response.json()
|
|
497
|
+
const reply = data?.choices?.[0]?.message?.content
|
|
498
|
+
if (typeof reply === 'string' && reply.trim()) {
|
|
499
|
+
const clean = reply.trim().replace(/^["“”]+|["“”]+$/g, '')
|
|
500
|
+
chatHistory.push({ role: 'assistant', content: clean })
|
|
501
|
+
return clean
|
|
502
|
+
}
|
|
503
|
+
chatHistory.pop()
|
|
504
|
+
return '我好像走神了,再说一遍好吗?'
|
|
505
|
+
} catch {
|
|
506
|
+
chatHistory.pop()
|
|
507
|
+
return '网络开小差了,等会儿再聊吧~'
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const classifyIntent = async (text) => {
|
|
512
|
+
const apiKey = await resolveApiKey()
|
|
513
|
+
if (!apiKey) return { type: 'chat' }
|
|
514
|
+
const input = String(text || '').trim().slice(0, 200)
|
|
515
|
+
if (!input) return { type: 'chat' }
|
|
516
|
+
const system = `你是命令分类器。判断用户这句话是“闲聊”还是“任务命令”。只输出 JSON,不要解释。
|
|
517
|
+
可用 action:pomodoro_start, pomodoro_stop, feed, hide, close, balance, roast, settings, open_web, remind, move_pet。
|
|
518
|
+
move_pet 的 args 用 {"position":"left|right|center|top|bottom"}。
|
|
519
|
+
输出示例:
|
|
520
|
+
{"type":"chat"}
|
|
521
|
+
{"type":"command","action":"pomodoro_start","args":{}}
|
|
522
|
+
{"type":"command","action":"open_web","args":{"url":"https://..."}}
|
|
523
|
+
{"type":"command","action":"move_pet","args":{"position":"left"}}
|
|
524
|
+
{"type":"command","action":"remind","args":{"text":"喝水","minutes":10}}
|
|
525
|
+
{"type":"task","task":"帮我在项目里搜索 xxx 并总结"}
|
|
526
|
+
{"type":"task","task":"查一下今天的天气然后提醒我"}`
|
|
527
|
+
try {
|
|
528
|
+
const response = await fetch('https://api.deepseek.com/chat/completions', {
|
|
529
|
+
method: 'POST',
|
|
530
|
+
headers: {
|
|
531
|
+
'content-type': 'application/json',
|
|
532
|
+
authorization: `Bearer ${apiKey}`,
|
|
533
|
+
},
|
|
534
|
+
body: JSON.stringify({
|
|
535
|
+
model: 'deepseek-chat',
|
|
536
|
+
messages: [
|
|
537
|
+
{ role: 'system', content: system },
|
|
538
|
+
{ role: 'user', content: input },
|
|
539
|
+
],
|
|
540
|
+
max_tokens: 120,
|
|
541
|
+
temperature: 0,
|
|
542
|
+
stream: false,
|
|
543
|
+
}),
|
|
544
|
+
})
|
|
545
|
+
if (!response.ok) return { type: 'chat' }
|
|
546
|
+
const data = await response.json()
|
|
547
|
+
const raw = data?.choices?.[0]?.message?.content || ''
|
|
548
|
+
const match = raw.match(/\{[\s\S]*\}/)
|
|
549
|
+
if (!match) return { type: 'chat' }
|
|
550
|
+
const parsed = JSON.parse(match[0])
|
|
551
|
+
if (parsed?.type === 'command') return { type: 'command', action: parsed.action, args: parsed.args || {} }
|
|
552
|
+
if (parsed?.type === 'task') return { type: 'task', task: parsed.task || input }
|
|
553
|
+
return { type: 'chat' }
|
|
554
|
+
} catch {
|
|
555
|
+
return { type: 'chat' }
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
const executeTask = async (taskText) => {
|
|
560
|
+
const apiKey = await resolveApiKey()
|
|
561
|
+
if (!apiKey) return '我还没连上 DeepSeek API,暂时无法执行任务~'
|
|
562
|
+
const input = String(taskText || '').trim().slice(0, 500)
|
|
563
|
+
if (!input) return '任务内容为空~'
|
|
564
|
+
// 优先在 DSH 内打开一个新的真实对话,把任务作为首条消息,cwd 为当前工作目录
|
|
565
|
+
try {
|
|
566
|
+
const agents = eventCtx.agents
|
|
567
|
+
if (agents?.create) {
|
|
568
|
+
const parent = agents.roots?.()[0] || agents.list?.()[0]
|
|
569
|
+
const sessionId = crypto.randomUUID()
|
|
570
|
+
const cwd = settings.get().taskCwd?.trim() || homedir()
|
|
571
|
+
const handle = await agents.create({
|
|
572
|
+
sessionId,
|
|
573
|
+
meta: { cwd },
|
|
574
|
+
agentOptions: parent?.options,
|
|
575
|
+
})
|
|
576
|
+
taskHandles.set(sessionId, handle)
|
|
577
|
+
handle.agent.followup({
|
|
578
|
+
role: 'user',
|
|
579
|
+
content: [{ type: 'text', text: `请实际执行以下任务(可以使用文件系统/命令/工具):\n${input}` }],
|
|
580
|
+
source: { kind: 'user' },
|
|
581
|
+
})
|
|
582
|
+
return `已在 DSH 中打开新对话并开始执行任务,会话 ID:${sessionId}`
|
|
583
|
+
}
|
|
584
|
+
} catch {
|
|
585
|
+
// 创建新会话失败时走下面的独立 LLM fallback
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
try {
|
|
590
|
+
const response = await fetch('https://api.deepseek.com/chat/completions', {
|
|
591
|
+
method: 'POST',
|
|
592
|
+
headers: {
|
|
593
|
+
'content-type': 'application/json',
|
|
594
|
+
authorization: `Bearer ${apiKey}`,
|
|
595
|
+
},
|
|
596
|
+
body: JSON.stringify({
|
|
597
|
+
model: 'deepseek-chat',
|
|
598
|
+
messages: [
|
|
599
|
+
{ role: 'system', content: '你是 better-dsh-pet 桌宠的任务执行助手。用户会给你一个任务请求。请在独立上下文中完成推理,并返回简短的结果摘要(不超过80字),不要询问额外问题,直接给出结果或明确的下一步建议。' },
|
|
600
|
+
{ role: 'user', content: input },
|
|
601
|
+
],
|
|
602
|
+
max_tokens: 300,
|
|
603
|
+
temperature: 0.7,
|
|
604
|
+
stream: false,
|
|
605
|
+
}),
|
|
606
|
+
})
|
|
607
|
+
if (!response.ok) return `任务执行接口出错了(${response.status})`
|
|
608
|
+
const data = await response.json()
|
|
609
|
+
const reply = data?.choices?.[0]?.message?.content
|
|
610
|
+
if (typeof reply === 'string' && reply.trim()) {
|
|
611
|
+
return reply.trim().replace(/^["“”]+|["“”]+$/g, '')
|
|
612
|
+
}
|
|
613
|
+
return '任务执行完成,但没有返回结果~'
|
|
614
|
+
} catch {
|
|
615
|
+
return '任务执行时网络开小差了,稍后再试~'
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const refreshBalance = async () => {
|
|
620
|
+
const apiKey = await resolveApiKey()
|
|
621
|
+
if (!apiKey) {
|
|
622
|
+
balance = null
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
try {
|
|
626
|
+
const response = await fetch('https://api.deepseek.com/user/balance', {
|
|
627
|
+
headers: { authorization: `Bearer ${apiKey}` },
|
|
628
|
+
cache: 'no-store',
|
|
629
|
+
})
|
|
630
|
+
if (!response.ok) {
|
|
631
|
+
balance = null
|
|
632
|
+
return
|
|
633
|
+
}
|
|
634
|
+
const data = await response.json()
|
|
635
|
+
const info = Array.isArray(data?.balance_infos) ? data.balance_infos[0] : undefined
|
|
636
|
+
if (info) {
|
|
637
|
+
balance = {
|
|
638
|
+
currency: info.currency || 'CNY',
|
|
639
|
+
total: info.total_balance,
|
|
640
|
+
granted: info.granted_balance,
|
|
641
|
+
toppedUp: info.topped_up_balance,
|
|
642
|
+
isAvailable: data.is_available !== false,
|
|
643
|
+
updatedAt: Date.now(),
|
|
644
|
+
}
|
|
645
|
+
} else {
|
|
646
|
+
balance = null
|
|
647
|
+
}
|
|
648
|
+
} catch {
|
|
649
|
+
balance = null
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
const getStatus = () => ({
|
|
654
|
+
...currentStatus,
|
|
655
|
+
tasks,
|
|
656
|
+
pulse: pulse && pulse.expiresAt > Date.now() ? pulse : undefined,
|
|
657
|
+
festivalPlay: getFestivalPlayRequest(),
|
|
658
|
+
tokenUsage,
|
|
659
|
+
balance,
|
|
660
|
+
roast,
|
|
661
|
+
config: publicConfig(settings.get()),
|
|
662
|
+
})
|
|
663
|
+
|
|
664
|
+
const stopRuntime = (reason = 'settings-change') => {
|
|
665
|
+
bridge?.stop(reason)
|
|
666
|
+
bridge = undefined
|
|
667
|
+
reducer = undefined
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
const restartRuntime = (next) => {
|
|
671
|
+
stopRuntime('settings-change')
|
|
672
|
+
startRuntime(next)
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
const scheduleRestart = (next) => {
|
|
676
|
+
if (restartTimer) clearTimeout(restartTimer)
|
|
677
|
+
restartTimer = setTimeout(() => {
|
|
678
|
+
restartTimer = undefined
|
|
679
|
+
restartRuntime(next)
|
|
680
|
+
}, 400)
|
|
681
|
+
restartTimer.unref?.()
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const startRuntime = (resolved) => {
|
|
685
|
+
if (resolved.enabled === false) {
|
|
686
|
+
logger.info?.('better-dsh-pet is disabled')
|
|
687
|
+
return
|
|
688
|
+
}
|
|
689
|
+
if (bridge) return
|
|
690
|
+
const helperConfig = config.helper ?? {}
|
|
691
|
+
const resolvedStatusUrl = statusUrl
|
|
692
|
+
|| String(config.webuiUrl ?? process.env.DSH_PET_WEBUI_URL ?? 'http://127.0.0.1:3080/').replace(/\/$/, '') + STATUS_ENDPOINT
|
|
693
|
+
bridge = new HelperProcess({
|
|
694
|
+
...helperConfig,
|
|
695
|
+
env: {
|
|
696
|
+
...helperConfig.env,
|
|
697
|
+
DSH_PET_SCALE: String(resolved.scale ?? defaults.scale),
|
|
698
|
+
DSH_PET_BUBBLE_SCALE: String(resolved.bubbleScale ?? defaults.bubbleScale),
|
|
699
|
+
DSH_PET_ACTIVITY_LEVEL: String(resolved.activityLevel ?? defaults.activityLevel),
|
|
700
|
+
DSH_PET_REDUCED_MOTION: resolved.reducedMotion === true ? '1' : '0',
|
|
701
|
+
DSH_PET_BUBBLE_MODE: String(resolved.bubbleMode ?? defaults.bubbleMode),
|
|
702
|
+
DSH_PET_BUBBLE_STATES: (Array.isArray(resolved.bubbleStates) ? resolved.bubbleStates : defaults.bubbleStates).join(','),
|
|
703
|
+
DSH_PET_WORK_MINUTES: String(resolved.workMinutes ?? defaults.workMinutes),
|
|
704
|
+
DSH_PET_BREAK_MINUTES: String(resolved.breakMinutes ?? defaults.breakMinutes),
|
|
705
|
+
DSH_PET_STATUS_URL: resolvedStatusUrl,
|
|
706
|
+
DSH_PET_WEBUI_URL: String(config.webuiUrl ?? process.env.DSH_PET_WEBUI_URL ?? 'http://127.0.0.1:3080/'),
|
|
707
|
+
DSH_PET_PLAYBACK_RATE: String(resolved.playbackRate ?? defaults.playbackRate),
|
|
708
|
+
DSH_PET_VOICE_ENABLED: resolved.voiceEnabled === false ? '0' : '1',
|
|
709
|
+
DSH_PET_VOICE_WAKE_AUTO_START: resolved.voiceWakeAutoStart === true ? '1' : '0',
|
|
710
|
+
DSH_PET_VOICE_SILENCE_MS: String(resolved.voiceSilenceMs ?? defaults.voiceSilenceMs),
|
|
711
|
+
DSH_PET_VOICE_AUTO_SEND: resolved.voiceAutoSend === false ? '0' : '1',
|
|
712
|
+
DSH_PET_VOICE_AUTO_RECORD: resolved.voiceAutoRecord === false ? '0' : '1',
|
|
713
|
+
DSH_PET_HOLIDAY_ENABLED: resolved.holidayEnabled === true ? '1' : '0',
|
|
714
|
+
DSH_PET_WAKE_WORD: resolved.wakeWord || defaults.wakeWord,
|
|
715
|
+
DSH_PET_TASK_CWD: resolved.taskCwd || '',
|
|
716
|
+
},
|
|
717
|
+
}, logger)
|
|
718
|
+
reducer = new CompanionReducer({ includeSubagents: resolved.includeSubagents === true })
|
|
719
|
+
bridge.start()
|
|
720
|
+
void refreshBalance()
|
|
721
|
+
if (!balanceTimer) {
|
|
722
|
+
balanceTimer = setInterval(() => void refreshBalance(), 5 * 60 * 1000)
|
|
723
|
+
balanceTimer.unref?.()
|
|
724
|
+
}
|
|
725
|
+
logger.info?.(`better-dsh-pet desktop helper started (status: ${resolvedStatusUrl})`)
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
const ensureHelperRunning = () => {
|
|
729
|
+
try {
|
|
730
|
+
if (settings.get().enabled === false) return
|
|
731
|
+
if (userClosed) return
|
|
732
|
+
if (!bridge) startRuntime(settings.get())
|
|
733
|
+
} catch {
|
|
734
|
+
// 启动失败时静默,等下一个周期再试。
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
const stopTaskSession = async (sessionId, reason = 'session archived') => {
|
|
739
|
+
const handle = taskHandles.get(sessionId)
|
|
740
|
+
if (!handle) return
|
|
741
|
+
taskHandles.delete(sessionId)
|
|
742
|
+
try {
|
|
743
|
+
// 先优雅取消:停止当前回合,保留会话内容,用户取消归档后还能继续看/用。
|
|
744
|
+
handle.agent?.cancel?.({ kind: 'hook', reason: `better-dsh-pet: ${reason}` })
|
|
745
|
+
// 如果取消后仍然在跑(例如正在执行外部命令/子代理),3 秒后强制销毁,杜绝“看似关了还在跑”。
|
|
746
|
+
const forceTimer = setTimeout(() => {
|
|
747
|
+
if (handle.agent?.status === 'running') {
|
|
748
|
+
void handle.dispose?.().catch?.(() => {})
|
|
749
|
+
}
|
|
750
|
+
}, 3000)
|
|
751
|
+
forceTimer.unref?.()
|
|
752
|
+
} catch {
|
|
753
|
+
// 取消失败时直接销毁,避免后台继续烧 token。
|
|
754
|
+
try { await handle.dispose?.() } catch { /* ignore */ }
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const checkTaskArchived = () => {
|
|
759
|
+
const archived = new Set(eventCtx.workspaceRegistry?.archivedSessionIds || [])
|
|
760
|
+
for (const [sessionId, handle] of taskHandles) {
|
|
761
|
+
if (archived.has(sessionId)) {
|
|
762
|
+
void stopTaskSession(sessionId, 'session archived')
|
|
763
|
+
} else if (!eventCtx.agents?.get?.(sessionId)) {
|
|
764
|
+
// 会话已不在 live registry(被删除/销毁),直接清理引用。
|
|
765
|
+
taskHandles.delete(sessionId)
|
|
766
|
+
try { void handle.dispose?.().catch?.(() => {}) } catch { /* ignore */ }
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const offEvent = eventCtx.on('session/event', (session, event) => {
|
|
772
|
+
if (!bridge || !reducer) return
|
|
773
|
+
// 捕获 token 用量:assistant/message 会携带 adapter 上报的 usage。
|
|
774
|
+
if (event?.type === 'assistant/message') {
|
|
775
|
+
const usage = event.data?.usage ?? event.data?.message?.usage
|
|
776
|
+
if (usage) {
|
|
777
|
+
const input = Number(usage.inputTokens ?? usage.promptTokens ?? usage.input ?? 0) || 0
|
|
778
|
+
const output = Number(usage.outputTokens ?? usage.completionTokens ?? usage.output ?? 0) || 0
|
|
779
|
+
tokenUsage.inputTokens += input
|
|
780
|
+
tokenUsage.outputTokens += output
|
|
781
|
+
tokenUsage.totalTokens += input + output
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
// 记录本次对话文本,供“吐槽”功能使用。
|
|
785
|
+
if (event?.type === 'user/message') {
|
|
786
|
+
appendTranscript('user', event.data?.content)
|
|
787
|
+
} else if (event?.type === 'assistant/message') {
|
|
788
|
+
appendTranscript('assistant', event.data?.message?.content)
|
|
789
|
+
}
|
|
790
|
+
// 每轮对话结束后自动刷新一次余额。
|
|
791
|
+
if (event?.type === 'turn/end') {
|
|
792
|
+
void refreshBalance()
|
|
793
|
+
}
|
|
794
|
+
// 自动吐槽:每轮对话结束后,如果开启了吐槽,则延迟生成一条。
|
|
795
|
+
if (event?.type === 'turn/end' && settings.get().roastEnabled === true) {
|
|
796
|
+
if (roastTimer) clearTimeout(roastTimer)
|
|
797
|
+
roastTimer = setTimeout(() => {
|
|
798
|
+
roastTimer = undefined
|
|
799
|
+
void generateRoast()
|
|
800
|
+
}, 1500)
|
|
801
|
+
roastTimer.unref?.()
|
|
802
|
+
}
|
|
803
|
+
applyMessages(reducer.handle(session, event))
|
|
804
|
+
}, { global: true })
|
|
805
|
+
const offDisposed = eventCtx.on('session/disposed', (session) => {
|
|
806
|
+
if (taskHandles.has(session.id)) {
|
|
807
|
+
const handle = taskHandles.get(session.id)
|
|
808
|
+
taskHandles.delete(session.id)
|
|
809
|
+
try { void handle?.dispose?.().catch?.(() => {}) } catch { /* ignore */ }
|
|
810
|
+
}
|
|
811
|
+
if (!bridge || !reducer) return
|
|
812
|
+
applyMessages(reducer.disposeSession(session))
|
|
813
|
+
}, { global: true })
|
|
814
|
+
|
|
815
|
+
if (!taskArchiveTimer) {
|
|
816
|
+
taskArchiveTimer = setInterval(() => {
|
|
817
|
+
try { checkTaskArchived() } catch { /* ignore */ }
|
|
818
|
+
}, 2000)
|
|
819
|
+
taskArchiveTimer.unref?.()
|
|
820
|
+
}
|
|
821
|
+
if (!helperWatchdogTimer) {
|
|
822
|
+
helperWatchdogTimer = setInterval(() => ensureHelperRunning(), 5000)
|
|
823
|
+
helperWatchdogTimer.unref?.()
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const unwatch = settings.watch((next) => {
|
|
827
|
+
const wasEnabled = lastEnabled
|
|
828
|
+
lastEnabled = next.enabled !== false
|
|
829
|
+
if (next.enabled === false) {
|
|
830
|
+
if (restartTimer) {
|
|
831
|
+
clearTimeout(restartTimer)
|
|
832
|
+
restartTimer = undefined
|
|
833
|
+
}
|
|
834
|
+
userClosed = true
|
|
835
|
+
stopRuntime('settings-change')
|
|
836
|
+
return
|
|
837
|
+
}
|
|
838
|
+
// 用户从右键菜单“本次关闭”后,只有显式从“禁用”切回“启用”才复活;
|
|
839
|
+
// 其他设置变化不应把已经手动关闭的桌宠又拉起来。
|
|
840
|
+
if (userClosed) {
|
|
841
|
+
if (!(wasEnabled === false && next.enabled === true)) return
|
|
842
|
+
userClosed = false
|
|
843
|
+
}
|
|
844
|
+
if (!bridge) {
|
|
845
|
+
scheduleRestart(next)
|
|
846
|
+
return
|
|
847
|
+
}
|
|
848
|
+
if (restartTimer) {
|
|
849
|
+
clearTimeout(restartTimer)
|
|
850
|
+
restartTimer = undefined
|
|
851
|
+
}
|
|
852
|
+
// 非启用类配置通过 status 里的 config 实时下发给 Helper;这里不重启进程。
|
|
853
|
+
logger.debug?.('better-dsh-pet settings changed; Helper will pick it up on next poll')
|
|
854
|
+
})
|
|
855
|
+
|
|
856
|
+
if (typeof ctx.inject === 'function') {
|
|
857
|
+
ctx.inject(['webServer'], (httpCtx) => {
|
|
858
|
+
const origin = `http://${httpCtx.webServer.host}:${httpCtx.webServer.port}`
|
|
859
|
+
statusUrl = `${origin}${STATUS_ENDPOINT}`
|
|
860
|
+
httpCtx.effect(
|
|
861
|
+
() => httpCtx.webServer.register({ kind: 'exact', path: CONFIG_ENDPOINT, handler: createConfigHandler(settings) }),
|
|
862
|
+
'better-dsh-pet: local settings endpoint',
|
|
863
|
+
)
|
|
864
|
+
httpCtx.effect(
|
|
865
|
+
() => httpCtx.webServer.register({ kind: 'exact', path: STATUS_ENDPOINT, handler: async (_req, res) => jsonResponse(res, 200, getStatus()) }),
|
|
866
|
+
'better-dsh-pet: local status endpoint',
|
|
867
|
+
)
|
|
868
|
+
httpCtx.effect(
|
|
869
|
+
() => httpCtx.webServer.register({
|
|
870
|
+
kind: 'exact',
|
|
871
|
+
path: FESTIVAL_PLAY_ENDPOINT,
|
|
872
|
+
handler: async (req, res) => {
|
|
873
|
+
if (!isLoopback(req.socket?.remoteAddress)) {
|
|
874
|
+
jsonResponse(res, 403, { error: 'local access only' })
|
|
875
|
+
return
|
|
876
|
+
}
|
|
877
|
+
const origin = req.headers?.origin
|
|
878
|
+
if (origin) {
|
|
879
|
+
let originHost
|
|
880
|
+
try { originHost = new URL(origin).host } catch {}
|
|
881
|
+
if (!originHost || originHost !== req.headers.host) {
|
|
882
|
+
jsonResponse(res, 403, { error: 'origin mismatch' })
|
|
883
|
+
return
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
if (req.method !== 'POST') {
|
|
887
|
+
jsonResponse(res, 405, { error: 'method not allowed' })
|
|
888
|
+
return
|
|
889
|
+
}
|
|
890
|
+
try {
|
|
891
|
+
const body = await readJsonBody(req)
|
|
892
|
+
const festivalId = typeof body?.festivalId === 'string' ? body.festivalId.trim() : ''
|
|
893
|
+
if (!festivalId) {
|
|
894
|
+
jsonResponse(res, 400, { error: 'festivalId is required' })
|
|
895
|
+
return
|
|
896
|
+
}
|
|
897
|
+
if (settings.get().holidayEnabled !== true) {
|
|
898
|
+
jsonResponse(res, 409, { error: 'holidayEnabled is disabled' })
|
|
899
|
+
return
|
|
900
|
+
}
|
|
901
|
+
const festival = queueFestivalPlayRequest(festivalId)
|
|
902
|
+
jsonResponse(res, 200, { ok: true, festival })
|
|
903
|
+
} catch (error) {
|
|
904
|
+
jsonResponse(res, 400, { error: error instanceof Error ? error.message : String(error) })
|
|
905
|
+
}
|
|
906
|
+
},
|
|
907
|
+
}),
|
|
908
|
+
'better-dsh-pet: local festival play endpoint',
|
|
909
|
+
)
|
|
910
|
+
httpCtx.effect(
|
|
911
|
+
() => httpCtx.webServer.register({
|
|
912
|
+
kind: 'exact',
|
|
913
|
+
path: '/plugins/better-dsh-pet/roast',
|
|
914
|
+
handler: async (_req, res) => {
|
|
915
|
+
await generateRoast(true)
|
|
916
|
+
jsonResponse(res, 200, { ok: true, roast })
|
|
917
|
+
},
|
|
918
|
+
}),
|
|
919
|
+
'better-dsh-pet: local roast endpoint',
|
|
920
|
+
)
|
|
921
|
+
httpCtx.effect(
|
|
922
|
+
() => httpCtx.webServer.register({
|
|
923
|
+
kind: 'exact',
|
|
924
|
+
path: '/plugins/better-dsh-pet/refresh-balance',
|
|
925
|
+
handler: async (_req, res) => {
|
|
926
|
+
await refreshBalance()
|
|
927
|
+
jsonResponse(res, 200, { ok: true, balance })
|
|
928
|
+
},
|
|
929
|
+
}),
|
|
930
|
+
'better-dsh-pet: local refresh-balance endpoint',
|
|
931
|
+
)
|
|
932
|
+
httpCtx.effect(
|
|
933
|
+
() => httpCtx.webServer.register({
|
|
934
|
+
kind: 'exact',
|
|
935
|
+
path: CHAT_ENDPOINT,
|
|
936
|
+
handler: async (req, res) => {
|
|
937
|
+
try {
|
|
938
|
+
const body = await readJsonBody(req)
|
|
939
|
+
const message = typeof body?.message === 'string' ? body.message : ''
|
|
940
|
+
const reply = await generateChatReply(message)
|
|
941
|
+
jsonResponse(res, 200, { ok: true, reply })
|
|
942
|
+
} catch (error) {
|
|
943
|
+
jsonResponse(res, 400, { error: error instanceof Error ? error.message : String(error) })
|
|
944
|
+
}
|
|
945
|
+
},
|
|
946
|
+
}),
|
|
947
|
+
'better-dsh-pet: local chat endpoint',
|
|
948
|
+
)
|
|
949
|
+
httpCtx.effect(
|
|
950
|
+
() => httpCtx.webServer.register({
|
|
951
|
+
kind: 'exact',
|
|
952
|
+
path: TRANSCRIBE_ENDPOINT,
|
|
953
|
+
handler: async (req, res) => {
|
|
954
|
+
try {
|
|
955
|
+
const chunks = []
|
|
956
|
+
let bytes = 0
|
|
957
|
+
for await (const chunk of req) {
|
|
958
|
+
bytes += chunk.length
|
|
959
|
+
if (bytes > 24 * 1024 * 1024) throw new Error('audio too large')
|
|
960
|
+
chunks.push(chunk)
|
|
961
|
+
}
|
|
962
|
+
const wav = Buffer.concat(chunks)
|
|
963
|
+
if (!modelReady()) {
|
|
964
|
+
jsonResponse(res, 400, { ok: false, error: 'SenseVoice 模型未就绪,请先运行 npm run download:sensevoice' })
|
|
965
|
+
return
|
|
966
|
+
}
|
|
967
|
+
const text = await transcribeWav(wav)
|
|
968
|
+
jsonResponse(res, 200, { ok: true, text })
|
|
969
|
+
} catch (error) {
|
|
970
|
+
jsonResponse(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
971
|
+
}
|
|
972
|
+
},
|
|
973
|
+
}),
|
|
974
|
+
'better-dsh-pet: local transcribe endpoint',
|
|
975
|
+
)
|
|
976
|
+
httpCtx.effect(
|
|
977
|
+
() => httpCtx.webServer.register({
|
|
978
|
+
kind: 'exact',
|
|
979
|
+
path: INTENT_ENDPOINT,
|
|
980
|
+
handler: async (req, res) => {
|
|
981
|
+
try {
|
|
982
|
+
const body = await readJsonBody(req)
|
|
983
|
+
const text = typeof body?.text === 'string' ? body.text : ''
|
|
984
|
+
const result = await classifyIntent(text)
|
|
985
|
+
jsonResponse(res, 200, { ok: true, ...result })
|
|
986
|
+
} catch (error) {
|
|
987
|
+
jsonResponse(res, 400, { ok: false, type: 'chat', error: error instanceof Error ? error.message : String(error) })
|
|
988
|
+
}
|
|
989
|
+
},
|
|
990
|
+
}),
|
|
991
|
+
'better-dsh-pet: local intent endpoint',
|
|
992
|
+
)
|
|
993
|
+
httpCtx.effect(
|
|
994
|
+
() => httpCtx.webServer.register({
|
|
995
|
+
kind: 'exact',
|
|
996
|
+
path: TASK_ENDPOINT,
|
|
997
|
+
handler: async (req, res) => {
|
|
998
|
+
try {
|
|
999
|
+
const body = await readJsonBody(req)
|
|
1000
|
+
const task = typeof body?.task === 'string' ? body.task : ''
|
|
1001
|
+
const result = await executeTask(task)
|
|
1002
|
+
jsonResponse(res, 200, { ok: true, result })
|
|
1003
|
+
} catch (error) {
|
|
1004
|
+
jsonResponse(res, 400, { ok: false, result: error instanceof Error ? error.message : String(error) })
|
|
1005
|
+
}
|
|
1006
|
+
},
|
|
1007
|
+
}),
|
|
1008
|
+
'better-dsh-pet: local task endpoint',
|
|
1009
|
+
)
|
|
1010
|
+
httpCtx.effect(
|
|
1011
|
+
() => httpCtx.webServer.register({
|
|
1012
|
+
kind: 'exact',
|
|
1013
|
+
path: CLOSE_ENDPOINT,
|
|
1014
|
+
handler: async (_req, res) => {
|
|
1015
|
+
// 用户从右键菜单选择“本次关闭”时,先通知宿主停止守护,
|
|
1016
|
+
// 避免 Helper 进程退出后被 HelperProcess 自动拉起。
|
|
1017
|
+
// 这里不主动 kill,让 Electron 自己 app.quit() 优雅退出。
|
|
1018
|
+
userClosed = true
|
|
1019
|
+
if (bridge) {
|
|
1020
|
+
bridge.suppressRestart()
|
|
1021
|
+
bridge = undefined
|
|
1022
|
+
}
|
|
1023
|
+
jsonResponse(res, 200, { ok: true })
|
|
1024
|
+
},
|
|
1025
|
+
}),
|
|
1026
|
+
'better-dsh-pet: local close endpoint',
|
|
1027
|
+
)
|
|
1028
|
+
httpCtx.effect(
|
|
1029
|
+
() => httpCtx.webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler: createAssetHandler(config) }),
|
|
1030
|
+
'better-dsh-pet: /pet asset route',
|
|
1031
|
+
)
|
|
1032
|
+
startRuntime(settings.get())
|
|
1033
|
+
})
|
|
1034
|
+
} else {
|
|
1035
|
+
startRuntime(settings.get())
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
ctx.effect(() => () => {
|
|
1039
|
+
if (restartTimer) clearTimeout(restartTimer)
|
|
1040
|
+
restartTimer = undefined
|
|
1041
|
+
if (balanceTimer) clearInterval(balanceTimer)
|
|
1042
|
+
balanceTimer = undefined
|
|
1043
|
+
if (roastTimer) clearTimeout(roastTimer)
|
|
1044
|
+
roastTimer = undefined
|
|
1045
|
+
if (taskArchiveTimer) clearInterval(taskArchiveTimer)
|
|
1046
|
+
taskArchiveTimer = undefined
|
|
1047
|
+
if (helperWatchdogTimer) clearInterval(helperWatchdogTimer)
|
|
1048
|
+
helperWatchdogTimer = undefined
|
|
1049
|
+
for (const handle of taskHandles.values()) {
|
|
1050
|
+
try { void handle?.dispose?.().catch?.(() => {}) } catch { /* ignore */ }
|
|
1051
|
+
}
|
|
1052
|
+
taskHandles.clear()
|
|
1053
|
+
offEvent?.()
|
|
1054
|
+
offDisposed?.()
|
|
1055
|
+
unwatch()
|
|
1056
|
+
stopRuntime('dsh-host-stop')
|
|
1057
|
+
})
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
export function apply(ctx, config = {}) {
|
|
1061
|
+
if (typeof ctx.inject === 'function') {
|
|
1062
|
+
ctx.inject(['settings'], (settingsCtx) => mount(settingsCtx, config, ctx))
|
|
1063
|
+
return
|
|
1064
|
+
}
|
|
1065
|
+
mount(ctx, config)
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
export {
|
|
1069
|
+
CompanionMessageKind,
|
|
1070
|
+
CompanionReducer,
|
|
1071
|
+
CompanionState,
|
|
1072
|
+
HelperProcess,
|
|
1073
|
+
}
|