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.
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 { createReadStream, existsSync, readFileSync } from 'node:fs'
18
- import { stat } from 'node:fs/promises'
19
- import { join, normalize, resolve, sep } from 'node:path'
20
- import { fileURLToPath } from 'node:url'
21
- import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
22
- import { CompanionReducer } from './pet-reducer.js'
23
- import { HelperProcess } from './pet-helper-process.js'
24
- import {
25
- CompanionMessageKind,
26
- CompanionState,
27
- } from './pet-protocol.js'
28
-
29
- export const name = 'better-dsh-pet'
30
- export const inject = ['sessions']
31
- export const CONFIG_ENDPOINT = '/plugins/better-dsh-pet/config'
32
- export const STATUS_ENDPOINT = '/plugins/better-dsh-pet/status'
33
- export const CLOSE_ENDPOINT = '/plugins/better-dsh-pet/close'
34
- export const ROUTE_PREFIX = '/pet'
35
-
36
- export const Config = Schema.object({
37
- enabled: Schema.boolean().default(true).description('启用桌面小宠物'),
38
- scale: Schema.number().min(0.7).max(1.4).step(0.05).default(1).role('slider').description('角色大小'),
39
- bubbleScale: Schema.number().min(0.8).max(1.2).step(0.05).default(1).role('slider').description('气泡大小'),
40
- activityLevel: Schema.union([
41
- Schema.const('quiet').description('安静'),
42
- Schema.const('normal').description('标准'),
43
- Schema.const('lively').description('活泼'),
44
- ]).default('normal').description('空闲微动作频率'),
45
- reducedMotion: Schema.boolean().default(false).description('减少走动、循环帧和程序化晃动'),
46
- bubbleMode: Schema.union([
47
- Schema.const('always').description('常驻显示'),
48
- Schema.const('hidden').description('完全隐藏'),
49
- Schema.const('custom').description('自定义显示状态'),
50
- ]).default('always').description('气泡显示模式'),
51
- bubbleStates: Schema.array(Schema.string()).default(['SUCCESS', 'ERROR', 'WAITING']).description('自定义模式下显示气泡的状态'),
52
- includeSubagents: Schema.boolean().default(false).description('允许子 Agent 抢占宠物状态'),
53
- workMinutes: Schema.number().min(1).max(120).step(1).default(25).description('番茄钟工作时长(分钟)'),
54
- breakMinutes: Schema.number().min(1).max(60).step(1).default(5).description('番茄钟休息时长(分钟)'),
55
- roastEnabled: Schema.boolean().default(false).description('根据本次对话自动吐槽(会消耗 Token)'),
56
- walkEnabled: Schema.boolean().default(true).description('待机时是否允许走动'),
57
- enabledActions: Schema.array(Schema.string()).default([]).description('自定义待机动作(留空=全部动作)'),
58
- actionOrder: Schema.array(Schema.string()).default([]).description('自定义待机动作播放顺序(留空=随机)'),
59
- petSize: Schema.number().min(100).max(1000).step(10).default(460).description('宠物宽度(px)'),
60
- moveChance: Schema.number().min(0).max(100).step(1).default(20).description('移动频繁度(百分比)'),
61
- actionDelayMs: Schema.number().min(0).max(5000).step(100).default(0).description('动作切换间隔(毫秒)'),
62
- }).description('由 DeepSeek Harness 状态驱动的桌面大肥鱼')
63
-
64
- const defaults = Object.freeze({
65
- enabled: true,
66
- scale: 1,
67
- bubbleScale: 1,
68
- activityLevel: 'normal',
69
- reducedMotion: false,
70
- bubbleMode: 'always',
71
- bubbleStates: ['SUCCESS', 'ERROR', 'WAITING'],
72
- includeSubagents: false,
73
- workMinutes: 25,
74
- breakMinutes: 5,
75
- roastEnabled: false,
76
- walkEnabled: true,
77
- enabledActions: [],
78
- actionOrder: [],
79
- petSize: 460,
80
- moveChance: 20,
81
- actionDelayMs: 0,
82
- })
83
-
84
- function publicConfig(config = {}) {
85
- return {
86
- enabled: config.enabled ?? defaults.enabled,
87
- scale: config.scale ?? defaults.scale,
88
- bubbleScale: config.bubbleScale ?? defaults.bubbleScale,
89
- activityLevel: config.activityLevel ?? defaults.activityLevel,
90
- reducedMotion: config.reducedMotion ?? defaults.reducedMotion,
91
- bubbleMode: config.bubbleMode ?? defaults.bubbleMode,
92
- bubbleStates: Array.isArray(config.bubbleStates) ? config.bubbleStates : defaults.bubbleStates,
93
- includeSubagents: config.includeSubagents ?? defaults.includeSubagents,
94
- workMinutes: config.workMinutes ?? defaults.workMinutes,
95
- breakMinutes: config.breakMinutes ?? defaults.breakMinutes,
96
- roastEnabled: config.roastEnabled ?? defaults.roastEnabled,
97
- walkEnabled: config.walkEnabled ?? defaults.walkEnabled,
98
- enabledActions: Array.isArray(config.enabledActions) ? config.enabledActions : defaults.enabledActions,
99
- actionOrder: Array.isArray(config.actionOrder) ? config.actionOrder : defaults.actionOrder,
100
- petSize: config.petSize ?? defaults.petSize,
101
- moveChance: config.moveChance ?? defaults.moveChance,
102
- actionDelayMs: config.actionDelayMs ?? defaults.actionDelayMs,
103
- }
104
- }
105
-
106
- function localSettingsScope(value) {
107
- return {
108
- get: () => value,
109
- watch: () => () => {},
110
- }
111
- }
112
-
113
- function jsonResponse(res, status, body) {
114
- const payload = JSON.stringify(body)
115
- res.writeHead(status, {
116
- 'content-type': 'application/json; charset=utf-8',
117
- 'cache-control': 'no-store',
118
- 'content-length': Buffer.byteLength(payload),
119
- })
120
- res.end(payload)
121
- }
122
-
123
- function isLoopback(address) {
124
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
125
- }
126
-
127
- async function readPatch(req) {
128
- const chunks = []
129
- let bytes = 0
130
- for await (const chunk of req) {
131
- bytes += chunk.length
132
- if (bytes > 8192) throw new Error('request body is too large')
133
- chunks.push(chunk)
134
- }
135
- const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
136
- if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('patch must be an object')
137
- const allowed = new Set(Object.keys(defaults))
138
- if (Object.keys(value).some((key) => !allowed.has(key))) throw new Error('patch contains an unknown setting')
139
- return value
140
- }
141
-
142
- export function createConfigHandler(settings) {
143
- return async (req, res) => {
144
- if (!isLoopback(req.socket?.remoteAddress)) {
145
- jsonResponse(res, 403, { error: 'local access only' })
146
- return
147
- }
148
- const origin = req.headers?.origin
149
- if (origin) {
150
- let originHost
151
- try { originHost = new URL(origin).host } catch {}
152
- if (!originHost || originHost !== req.headers.host) {
153
- jsonResponse(res, 403, { error: 'origin mismatch' })
154
- return
155
- }
156
- }
157
- if (req.method === 'GET') {
158
- jsonResponse(res, 200, settings.get())
159
- return
160
- }
161
- if (req.method !== 'PATCH') {
162
- jsonResponse(res, 405, { error: 'method not allowed' })
163
- return
164
- }
165
- try {
166
- await settings.update(await readPatch(req))
167
- jsonResponse(res, 200, settings.get())
168
- } catch (error) {
169
- jsonResponse(res, 400, { error: error instanceof Error ? error.message : String(error) })
170
- }
171
- }
172
- }
173
-
174
- /** 旧版 /pet 静态资源路由:服务插件包内 assets/thumb 下的 WebM。 */
175
- function createAssetHandler(config = {}) {
176
- const packageRoot = resolve(fileURLToPath(new URL('..', import.meta.url)))
177
- const thumbRoot = join(packageRoot, 'assets', 'thumb')
178
- const fullRoot = config.fullRoot ?? join(resolveDshHome(), 'pet-assets')
179
- const MIME = {
180
- '.webm': 'video/webm',
181
- '.mp4': 'video/mp4',
182
- '.png': 'image/png',
183
- '.json': 'application/json; charset=utf-8',
184
- }
185
-
186
- const resolveAsset = (root, rel) => {
187
- if (rel.length === 0) return undefined
188
- const candidate = normalize(join(root, rel))
189
- const rootWithSep = root.endsWith(sep) ? root : root + sep
190
- if (candidate !== root && !candidate.startsWith(rootWithSep)) return undefined
191
- return candidate
192
- }
193
-
194
- return async (req, res) => {
195
- const url = new URL(req.url ?? '/', 'http://localhost')
196
- const rest = decodeURIComponent(url.pathname.slice(ROUTE_PREFIX.length + 1))
197
- const [scope, ...nameParts] = rest.split('/')
198
- if (scope !== 'thumb' && scope !== 'full') {
199
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
200
- res.end('better-dsh-pet: expected /pet/{thumb|full}/<file>')
201
- return
202
- }
203
- const fileName = nameParts.join('/')
204
- const root = scope === 'thumb' ? thumbRoot : fullRoot
205
- const file = resolveAsset(root, fileName)
206
- if (file === undefined) {
207
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
208
- res.end('better-dsh-pet: invalid path')
209
- return
210
- }
211
- if (!existsSync(file)) {
212
- res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
213
- res.end(scope === 'full'
214
- ? `better-dsh-pet: original asset not downloaded yet — run the fetch-assets script to populate ${fullRoot}`
215
- : 'better-dsh-pet: asset not found')
216
- return
217
- }
218
- const ext = file.slice(file.lastIndexOf('.')).toLowerCase()
219
- const contentType = MIME[ext] ?? 'application/octet-stream'
220
- const { size } = await stat(file)
221
- res.writeHead(200, {
222
- 'content-type': contentType,
223
- 'content-length': size,
224
- 'cache-control': 'public, max-age=3600',
225
- })
226
- const stream = createReadStream(file)
227
- stream.on('error', () => { res.destroy() })
228
- stream.pipe(res)
229
- }
230
- }
231
-
232
- function mount(ctx, config = {}, eventCtx = ctx) {
233
- const logger = ctx.logger ?? console
234
- const base = publicConfig(config)
235
- const settings = ctx.settings?.register?.('better-dsh-pet', Config, {
236
- base,
237
- applies: 'live',
238
- }) ?? localSettingsScope(base)
239
-
240
- let bridge
241
- let reducer
242
- let restartTimer
243
- let statusUrl = config.webuiUrl
244
- ? String(config.webuiUrl).replace(/\/$/, '') + STATUS_ENDPOINT
245
- : undefined
246
- let currentStatus = {
247
- state: CompanionState.IDLE,
248
- message: '大肥鱼在这儿等新任务哦~',
249
- detail: '大肥鱼 · 等待下一次任务',
250
- project: undefined,
251
- task: undefined,
252
- progress: undefined,
253
- }
254
- let pulse = undefined
255
- let tasks = []
256
- let tokenUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
257
- let balance = null
258
- let balanceTimer = null
259
- let transcript = []
260
- let roast = null
261
- let roastTimer = null
262
-
263
- const applyMessages = (messages) => {
264
- for (const message of messages) {
265
- if (!message?.kind) continue
266
- if (message.kind === CompanionMessageKind.STATE) {
267
- pulse = undefined
268
- currentStatus = {
269
- ...currentStatus,
270
- state: message.state,
271
- message: message.message || currentStatus.message,
272
- detail: message.detail || currentStatus.detail,
273
- project: message.project ?? currentStatus.project,
274
- task: message.task ?? currentStatus.task,
275
- progress: message.progress ?? currentStatus.progress,
276
- }
277
- } else if (message.kind === CompanionMessageKind.PULSE) {
278
- const ttlMs = Number(message.ttlMs || 1800)
279
- pulse = {
280
- state: message.state,
281
- message: message.message || '',
282
- detail: message.detail || '',
283
- ttlMs,
284
- expiresAt: Date.now() + ttlMs,
285
- resumeState: message.resumeState,
286
- resumeMessage: message.resumeMessage,
287
- resumeDetail: message.resumeDetail,
288
- }
289
- // 脉冲结束后应回到 resumeState。这里立即同步 currentStatus,
290
- // 避免脉冲过期后状态接口回退到旧的“整理结果”等中间状态。
291
- if (message.resumeState) {
292
- currentStatus = {
293
- ...currentStatus,
294
- state: message.resumeState,
295
- message: message.resumeMessage || currentStatus.message,
296
- detail: message.resumeDetail || currentStatus.detail,
297
- }
298
- }
299
- } else if (message.kind === CompanionMessageKind.TASK) {
300
- currentStatus = {
301
- ...currentStatus,
302
- task: message.task ?? currentStatus.task,
303
- progress: message.progress ?? currentStatus.progress,
304
- project: message.project ?? currentStatus.project,
305
- message: message.message || currentStatus.message,
306
- detail: message.detail || currentStatus.detail,
307
- }
308
- } else if (message.kind === CompanionMessageKind.TASKS) {
309
- tasks = Array.isArray(message.tasks) ? message.tasks : []
310
- }
311
- }
312
- }
313
-
314
- const resolveApiKey = async () => {
315
- let apiKey = process.env.DEEPSEEK_API_KEY
316
- if (!apiKey) {
317
- try {
318
- if (eventCtx.credentials?.resolve) {
319
- const resolved = await eventCtx.credentials.resolve('DEEPSEEK_API_KEY')
320
- apiKey = resolved?.value
321
- }
322
- } catch {
323
- apiKey = undefined
324
- }
325
- }
326
- if (!apiKey) {
327
- try {
328
- const home = resolveDshHome()
329
- const text = readFileSync(join(home, '.credentials.yaml'), 'utf8')
330
- const match = text.match(/^\s*DEEPSEEK_API_KEY:\s*(.+?)\s*$/m)
331
- if (match) apiKey = match[1].trim()
332
- } catch {
333
- apiKey = undefined
334
- }
335
- }
336
- return apiKey
337
- }
338
-
339
- const appendTranscript = (role, content) => {
340
- const text = Array.isArray(content)
341
- ? content.map((part) => {
342
- if (typeof part === 'string') return part
343
- if (part?.type === 'text') return part.text || ''
344
- if (part?.text) return part.text
345
- return ''
346
- }).filter(Boolean).join(' ')
347
- : typeof content === 'string' ? content : ''
348
- if (!text.trim()) return
349
- transcript.push({ role, content: text.trim() })
350
- // 只保留最近 10 条,避免上下文无限增长。
351
- if (transcript.length > 10) transcript = transcript.slice(-10)
352
- }
353
-
354
- const generateRoast = async (force = false) => {
355
- const enabled = settings.get().roastEnabled === true
356
- if (!force && !enabled) return
357
- const apiKey = await resolveApiKey()
358
- if (!apiKey || transcript.length === 0) return
359
- // 只取最近 5 条,且每条截断到 150 字,降低 Token 消耗。
360
- const recent = transcript.slice(-5).map((item) => {
361
- const content = item.content.length > 150 ? `${item.content.slice(0, 150)}…` : item.content
362
- return `${item.role === 'user' ? '用户' : '大肥鱼'}: ${content}`
363
- }).join('\n')
364
- try {
365
- const response = await fetch('https://api.deepseek.com/chat/completions', {
366
- method: 'POST',
367
- headers: {
368
- 'content-type': 'application/json',
369
- authorization: `Bearer ${apiKey}`,
370
- },
371
- body: JSON.stringify({
372
- model: 'deepseek-chat',
373
- messages: [
374
- { role: 'system', content: '你是一只住在 DeepSeek Harness 里的大肥鱼桌宠。请根据用户和 AI 的对话,用一句简短、可爱、俏皮的话吐槽/点评这次对话。要求:中文,不超过30个字,语气像大肥鱼,不要解释,不要引号。' },
375
- { role: 'user', content: `对话内容:\n${recent}` },
376
- ],
377
- max_tokens: 80,
378
- temperature: 1.1,
379
- stream: false,
380
- }),
381
- })
382
- if (!response.ok) return
383
- const data = await response.json()
384
- const text = data?.choices?.[0]?.message?.content
385
- if (typeof text === 'string' && text.trim()) {
386
- roast = text.trim().replace(/^["“”]+|["“”]+$/g, '')
387
- }
388
- } catch {
389
- // 吐槽失败时静默,不影响主功能。
390
- }
391
- }
392
-
393
- const refreshBalance = async () => {
394
- const apiKey = await resolveApiKey()
395
- if (!apiKey) {
396
- balance = null
397
- return
398
- }
399
- try {
400
- const response = await fetch('https://api.deepseek.com/user/balance', {
401
- headers: { authorization: `Bearer ${apiKey}` },
402
- cache: 'no-store',
403
- })
404
- if (!response.ok) {
405
- balance = null
406
- return
407
- }
408
- const data = await response.json()
409
- const info = Array.isArray(data?.balance_infos) ? data.balance_infos[0] : undefined
410
- if (info) {
411
- balance = {
412
- currency: info.currency || 'CNY',
413
- total: info.total_balance,
414
- granted: info.granted_balance,
415
- toppedUp: info.topped_up_balance,
416
- isAvailable: data.is_available !== false,
417
- updatedAt: Date.now(),
418
- }
419
- } else {
420
- balance = null
421
- }
422
- } catch {
423
- balance = null
424
- }
425
- }
426
-
427
- const getStatus = () => ({
428
- ...currentStatus,
429
- tasks,
430
- pulse: pulse && pulse.expiresAt > Date.now() ? pulse : undefined,
431
- tokenUsage,
432
- balance,
433
- roast,
434
- config: publicConfig(settings.get()),
435
- })
436
-
437
- const stopRuntime = (reason = 'settings-change') => {
438
- bridge?.stop(reason)
439
- bridge = undefined
440
- reducer = undefined
441
- }
442
-
443
- const restartRuntime = (next) => {
444
- stopRuntime('settings-change')
445
- startRuntime(next)
446
- }
447
-
448
- const scheduleRestart = (next) => {
449
- if (restartTimer) clearTimeout(restartTimer)
450
- restartTimer = setTimeout(() => {
451
- restartTimer = undefined
452
- restartRuntime(next)
453
- }, 400)
454
- restartTimer.unref?.()
455
- }
456
-
457
- const startRuntime = (resolved) => {
458
- if (resolved.enabled === false) {
459
- logger.info?.('better-dsh-pet is disabled')
460
- return
461
- }
462
- if (bridge) return
463
- const helperConfig = config.helper ?? {}
464
- const resolvedStatusUrl = statusUrl
465
- || String(config.webuiUrl ?? process.env.DSH_PET_WEBUI_URL ?? 'http://127.0.0.1:3080/').replace(/\/$/, '') + STATUS_ENDPOINT
466
- bridge = new HelperProcess({
467
- ...helperConfig,
468
- env: {
469
- ...helperConfig.env,
470
- DSH_PET_SCALE: String(resolved.scale ?? defaults.scale),
471
- DSH_PET_BUBBLE_SCALE: String(resolved.bubbleScale ?? defaults.bubbleScale),
472
- DSH_PET_ACTIVITY_LEVEL: String(resolved.activityLevel ?? defaults.activityLevel),
473
- DSH_PET_REDUCED_MOTION: resolved.reducedMotion === true ? '1' : '0',
474
- DSH_PET_BUBBLE_MODE: String(resolved.bubbleMode ?? defaults.bubbleMode),
475
- DSH_PET_BUBBLE_STATES: (Array.isArray(resolved.bubbleStates) ? resolved.bubbleStates : defaults.bubbleStates).join(','),
476
- DSH_PET_WORK_MINUTES: String(resolved.workMinutes ?? defaults.workMinutes),
477
- DSH_PET_BREAK_MINUTES: String(resolved.breakMinutes ?? defaults.breakMinutes),
478
- DSH_PET_STATUS_URL: resolvedStatusUrl,
479
- DSH_PET_WEBUI_URL: String(config.webuiUrl ?? process.env.DSH_PET_WEBUI_URL ?? 'http://127.0.0.1:3080/'),
480
- },
481
- }, logger)
482
- reducer = new CompanionReducer({ includeSubagents: resolved.includeSubagents === true })
483
- bridge.start()
484
- void refreshBalance()
485
- if (!balanceTimer) {
486
- balanceTimer = setInterval(() => void refreshBalance(), 5 * 60 * 1000)
487
- balanceTimer.unref?.()
488
- }
489
- logger.info?.(`better-dsh-pet desktop helper started (status: ${resolvedStatusUrl})`)
490
- }
491
-
492
- const offEvent = eventCtx.on('session/event', (session, event) => {
493
- if (!bridge || !reducer) return
494
- // 捕获 token 用量:assistant/message 会携带 adapter 上报的 usage。
495
- if (event?.type === 'assistant/message') {
496
- const usage = event.data?.usage ?? event.data?.message?.usage
497
- if (usage) {
498
- const input = Number(usage.inputTokens ?? usage.promptTokens ?? usage.input ?? 0) || 0
499
- const output = Number(usage.outputTokens ?? usage.completionTokens ?? usage.output ?? 0) || 0
500
- tokenUsage.inputTokens += input
501
- tokenUsage.outputTokens += output
502
- tokenUsage.totalTokens += input + output
503
- }
504
- }
505
- // 记录本次对话文本,供“吐槽”功能使用。
506
- if (event?.type === 'user/message') {
507
- appendTranscript('user', event.data?.content)
508
- } else if (event?.type === 'assistant/message') {
509
- appendTranscript('assistant', event.data?.message?.content)
510
- }
511
- // 每轮对话结束后自动刷新一次余额。
512
- if (event?.type === 'turn/end') {
513
- void refreshBalance()
514
- }
515
- // 自动吐槽:每轮对话结束后,如果开启了吐槽,则延迟生成一条。
516
- if (event?.type === 'turn/end' && settings.get().roastEnabled === true) {
517
- if (roastTimer) clearTimeout(roastTimer)
518
- roastTimer = setTimeout(() => {
519
- roastTimer = undefined
520
- void generateRoast()
521
- }, 1500)
522
- roastTimer.unref?.()
523
- }
524
- applyMessages(reducer.handle(session, event))
525
- }, { global: true })
526
- const offDisposed = eventCtx.on('session/disposed', (session) => {
527
- if (!bridge || !reducer) return
528
- applyMessages(reducer.disposeSession(session))
529
- }, { global: true })
530
-
531
- const unwatch = settings.watch((next) => {
532
- if (next.enabled === false) {
533
- if (restartTimer) {
534
- clearTimeout(restartTimer)
535
- restartTimer = undefined
536
- }
537
- stopRuntime('settings-change')
538
- return
539
- }
540
- if (!bridge) {
541
- scheduleRestart(next)
542
- return
543
- }
544
- if (restartTimer) {
545
- clearTimeout(restartTimer)
546
- restartTimer = undefined
547
- }
548
- // 非启用类配置通过 status 里的 config 实时下发给 Helper;这里不重启进程。
549
- logger.debug?.('better-dsh-pet settings changed; Helper will pick it up on next poll')
550
- })
551
-
552
- if (typeof ctx.inject === 'function') {
553
- ctx.inject(['webServer'], (httpCtx) => {
554
- const origin = `http://${httpCtx.webServer.host}:${httpCtx.webServer.port}`
555
- statusUrl = `${origin}${STATUS_ENDPOINT}`
556
- httpCtx.effect(
557
- () => httpCtx.webServer.register({ kind: 'exact', path: CONFIG_ENDPOINT, handler: createConfigHandler(settings) }),
558
- 'better-dsh-pet: local settings endpoint',
559
- )
560
- httpCtx.effect(
561
- () => httpCtx.webServer.register({ kind: 'exact', path: STATUS_ENDPOINT, handler: async (_req, res) => jsonResponse(res, 200, getStatus()) }),
562
- 'better-dsh-pet: local status endpoint',
563
- )
564
- httpCtx.effect(
565
- () => httpCtx.webServer.register({
566
- kind: 'exact',
567
- path: '/plugins/better-dsh-pet/roast',
568
- handler: async (_req, res) => {
569
- await generateRoast(true)
570
- jsonResponse(res, 200, { ok: true, roast })
571
- },
572
- }),
573
- 'better-dsh-pet: local roast endpoint',
574
- )
575
- httpCtx.effect(
576
- () => httpCtx.webServer.register({
577
- kind: 'exact',
578
- path: '/plugins/better-dsh-pet/refresh-balance',
579
- handler: async (_req, res) => {
580
- await refreshBalance()
581
- jsonResponse(res, 200, { ok: true, balance })
582
- },
583
- }),
584
- 'better-dsh-pet: local refresh-balance endpoint',
585
- )
586
- httpCtx.effect(
587
- () => httpCtx.webServer.register({
588
- kind: 'exact',
589
- path: CLOSE_ENDPOINT,
590
- handler: async (_req, res) => {
591
- // 用户从右键菜单选择“本次关闭”时,先通知宿主停止守护,
592
- // 避免 Helper 进程退出后被 HelperProcess 自动拉起。
593
- stopRuntime('user-close')
594
- jsonResponse(res, 200, { ok: true })
595
- },
596
- }),
597
- 'better-dsh-pet: local close endpoint',
598
- )
599
- httpCtx.effect(
600
- () => httpCtx.webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler: createAssetHandler(config) }),
601
- 'better-dsh-pet: /pet asset route',
602
- )
603
- startRuntime(settings.get())
604
- })
605
- } else {
606
- startRuntime(settings.get())
607
- }
608
-
609
- ctx.effect(() => () => {
610
- if (restartTimer) clearTimeout(restartTimer)
611
- restartTimer = undefined
612
- if (balanceTimer) clearInterval(balanceTimer)
613
- balanceTimer = undefined
614
- if (roastTimer) clearTimeout(roastTimer)
615
- roastTimer = undefined
616
- offEvent?.()
617
- offDisposed?.()
618
- unwatch()
619
- stopRuntime('dsh-host-stop')
620
- })
621
- }
622
-
623
- export function apply(ctx, config = {}) {
624
- if (typeof ctx.inject === 'function') {
625
- ctx.inject(['settings'], (settingsCtx) => mount(settingsCtx, config, ctx))
626
- return
627
- }
628
- mount(ctx, config)
629
- }
630
-
631
- export {
632
- CompanionMessageKind,
633
- CompanionReducer,
634
- CompanionState,
635
- HelperProcess,
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
+ }