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