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
@@ -0,0 +1,483 @@
1
+ /**
2
+ * ============================================================================
3
+ * dsh-pet 宿主半侧(host half)—— 桌面宠物插件的 DSH 服务端入口
4
+ * ============================================================================
5
+ *
6
+ * 联动模型(桌面独立气泡版):
7
+ * - 插件由 DSH 启动/停止,不要求用户单独打开桌宠;
8
+ * - 监听 DSH 的 session/event,把真实 Agent 状态压缩成状态对象;
9
+ * - 通过 /plugins/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 } 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 = 'pet'
30
+ export const inject = ['sessions']
31
+ export const CONFIG_ENDPOINT = '/plugins/dsh-pet/config'
32
+ export const STATUS_ENDPOINT = '/plugins/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
+ }).description('由 DeepSeek Harness 状态驱动的桌面大肥鱼')
55
+
56
+ const defaults = Object.freeze({
57
+ enabled: true,
58
+ scale: 1,
59
+ bubbleScale: 1,
60
+ activityLevel: 'normal',
61
+ reducedMotion: false,
62
+ bubbleMode: 'always',
63
+ bubbleStates: ['SUCCESS', 'ERROR', 'WAITING'],
64
+ includeSubagents: false,
65
+ workMinutes: 25,
66
+ breakMinutes: 5,
67
+ })
68
+
69
+ function publicConfig(config = {}) {
70
+ return {
71
+ enabled: config.enabled ?? defaults.enabled,
72
+ scale: config.scale ?? defaults.scale,
73
+ bubbleScale: config.bubbleScale ?? defaults.bubbleScale,
74
+ activityLevel: config.activityLevel ?? defaults.activityLevel,
75
+ reducedMotion: config.reducedMotion ?? defaults.reducedMotion,
76
+ bubbleMode: config.bubbleMode ?? defaults.bubbleMode,
77
+ bubbleStates: Array.isArray(config.bubbleStates) ? config.bubbleStates : defaults.bubbleStates,
78
+ includeSubagents: config.includeSubagents ?? defaults.includeSubagents,
79
+ workMinutes: config.workMinutes ?? defaults.workMinutes,
80
+ breakMinutes: config.breakMinutes ?? defaults.breakMinutes,
81
+ }
82
+ }
83
+
84
+ function localSettingsScope(value) {
85
+ return {
86
+ get: () => value,
87
+ watch: () => () => {},
88
+ }
89
+ }
90
+
91
+ function jsonResponse(res, status, body) {
92
+ const payload = JSON.stringify(body)
93
+ res.writeHead(status, {
94
+ 'content-type': 'application/json; charset=utf-8',
95
+ 'cache-control': 'no-store',
96
+ 'content-length': Buffer.byteLength(payload),
97
+ })
98
+ res.end(payload)
99
+ }
100
+
101
+ function isLoopback(address) {
102
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
103
+ }
104
+
105
+ async function readPatch(req) {
106
+ const chunks = []
107
+ let bytes = 0
108
+ for await (const chunk of req) {
109
+ bytes += chunk.length
110
+ if (bytes > 8192) throw new Error('request body is too large')
111
+ chunks.push(chunk)
112
+ }
113
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
114
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('patch must be an object')
115
+ const allowed = new Set(Object.keys(defaults))
116
+ if (Object.keys(value).some((key) => !allowed.has(key))) throw new Error('patch contains an unknown setting')
117
+ return value
118
+ }
119
+
120
+ export function createConfigHandler(settings) {
121
+ return async (req, res) => {
122
+ if (!isLoopback(req.socket?.remoteAddress)) {
123
+ jsonResponse(res, 403, { error: 'local access only' })
124
+ return
125
+ }
126
+ const origin = req.headers?.origin
127
+ if (origin) {
128
+ let originHost
129
+ try { originHost = new URL(origin).host } catch {}
130
+ if (!originHost || originHost !== req.headers.host) {
131
+ jsonResponse(res, 403, { error: 'origin mismatch' })
132
+ return
133
+ }
134
+ }
135
+ if (req.method === 'GET') {
136
+ jsonResponse(res, 200, settings.get())
137
+ return
138
+ }
139
+ if (req.method !== 'PATCH') {
140
+ jsonResponse(res, 405, { error: 'method not allowed' })
141
+ return
142
+ }
143
+ try {
144
+ await settings.update(await readPatch(req))
145
+ jsonResponse(res, 200, settings.get())
146
+ } catch (error) {
147
+ jsonResponse(res, 400, { error: error instanceof Error ? error.message : String(error) })
148
+ }
149
+ }
150
+ }
151
+
152
+ /** 旧版 /pet 静态资源路由:服务插件包内 assets/thumb 下的 WebM。 */
153
+ function createAssetHandler(config = {}) {
154
+ const packageRoot = resolve(fileURLToPath(new URL('..', import.meta.url)))
155
+ const thumbRoot = join(packageRoot, 'assets', 'thumb')
156
+ const fullRoot = config.fullRoot ?? join(resolveDshHome(), 'pet-assets')
157
+ const MIME = {
158
+ '.webm': 'video/webm',
159
+ '.mp4': 'video/mp4',
160
+ '.png': 'image/png',
161
+ '.json': 'application/json; charset=utf-8',
162
+ }
163
+
164
+ const resolveAsset = (root, rel) => {
165
+ if (rel.length === 0) return undefined
166
+ const candidate = normalize(join(root, rel))
167
+ const rootWithSep = root.endsWith(sep) ? root : root + sep
168
+ if (candidate !== root && !candidate.startsWith(rootWithSep)) return undefined
169
+ return candidate
170
+ }
171
+
172
+ return async (req, res) => {
173
+ const url = new URL(req.url ?? '/', 'http://localhost')
174
+ const rest = decodeURIComponent(url.pathname.slice(ROUTE_PREFIX.length + 1))
175
+ const [scope, ...nameParts] = rest.split('/')
176
+ if (scope !== 'thumb' && scope !== 'full') {
177
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
178
+ res.end('dsh-pet: expected /pet/{thumb|full}/<file>')
179
+ return
180
+ }
181
+ const fileName = nameParts.join('/')
182
+ const root = scope === 'thumb' ? thumbRoot : fullRoot
183
+ const file = resolveAsset(root, fileName)
184
+ if (file === undefined) {
185
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
186
+ res.end('dsh-pet: invalid path')
187
+ return
188
+ }
189
+ if (!existsSync(file)) {
190
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
191
+ res.end(scope === 'full'
192
+ ? `dsh-pet: original asset not downloaded yet — run the fetch-assets script to populate ${fullRoot}`
193
+ : 'dsh-pet: asset not found')
194
+ return
195
+ }
196
+ const ext = file.slice(file.lastIndexOf('.')).toLowerCase()
197
+ const contentType = MIME[ext] ?? 'application/octet-stream'
198
+ const { size } = await stat(file)
199
+ res.writeHead(200, {
200
+ 'content-type': contentType,
201
+ 'content-length': size,
202
+ 'cache-control': 'public, max-age=3600',
203
+ })
204
+ const stream = createReadStream(file)
205
+ stream.on('error', () => { res.destroy() })
206
+ stream.pipe(res)
207
+ }
208
+ }
209
+
210
+ function mount(ctx, config = {}, eventCtx = ctx) {
211
+ const logger = ctx.logger ?? console
212
+ const base = publicConfig(config)
213
+ const settings = ctx.settings?.register?.('dsh-pet', Config, {
214
+ base,
215
+ applies: 'live',
216
+ }) ?? localSettingsScope(base)
217
+
218
+ let bridge
219
+ let reducer
220
+ let restartTimer
221
+ let statusUrl = config.webuiUrl
222
+ ? String(config.webuiUrl).replace(/\/$/, '') + STATUS_ENDPOINT
223
+ : undefined
224
+ let currentStatus = {
225
+ state: CompanionState.IDLE,
226
+ message: '大肥鱼在这儿等新任务哦~',
227
+ detail: '大肥鱼 · 等待下一次任务',
228
+ project: undefined,
229
+ task: undefined,
230
+ progress: undefined,
231
+ }
232
+ let pulse = undefined
233
+ let tasks = []
234
+ let tokenUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
235
+ let balance = null
236
+ let balanceTimer = null
237
+
238
+ const applyMessages = (messages) => {
239
+ for (const message of messages) {
240
+ if (!message?.kind) continue
241
+ if (message.kind === CompanionMessageKind.STATE) {
242
+ pulse = undefined
243
+ currentStatus = {
244
+ ...currentStatus,
245
+ state: message.state,
246
+ message: message.message || currentStatus.message,
247
+ detail: message.detail || currentStatus.detail,
248
+ project: message.project ?? currentStatus.project,
249
+ task: message.task ?? currentStatus.task,
250
+ progress: message.progress ?? currentStatus.progress,
251
+ }
252
+ } else if (message.kind === CompanionMessageKind.PULSE) {
253
+ const ttlMs = Number(message.ttlMs || 1800)
254
+ pulse = {
255
+ state: message.state,
256
+ message: message.message || '',
257
+ detail: message.detail || '',
258
+ ttlMs,
259
+ expiresAt: Date.now() + ttlMs,
260
+ resumeState: message.resumeState,
261
+ resumeMessage: message.resumeMessage,
262
+ resumeDetail: message.resumeDetail,
263
+ }
264
+ // 脉冲结束后应回到 resumeState。这里立即同步 currentStatus,
265
+ // 避免脉冲过期后状态接口回退到旧的“整理结果”等中间状态。
266
+ if (message.resumeState) {
267
+ currentStatus = {
268
+ ...currentStatus,
269
+ state: message.resumeState,
270
+ message: message.resumeMessage || currentStatus.message,
271
+ detail: message.resumeDetail || currentStatus.detail,
272
+ }
273
+ }
274
+ } else if (message.kind === CompanionMessageKind.TASK) {
275
+ currentStatus = {
276
+ ...currentStatus,
277
+ task: message.task ?? currentStatus.task,
278
+ progress: message.progress ?? currentStatus.progress,
279
+ project: message.project ?? currentStatus.project,
280
+ message: message.message || currentStatus.message,
281
+ detail: message.detail || currentStatus.detail,
282
+ }
283
+ } else if (message.kind === CompanionMessageKind.TASKS) {
284
+ tasks = Array.isArray(message.tasks) ? message.tasks : []
285
+ }
286
+ }
287
+ }
288
+
289
+ const refreshBalance = async () => {
290
+ let apiKey = process.env.DEEPSEEK_API_KEY
291
+ if (!apiKey && eventCtx.credentials?.resolve) {
292
+ try {
293
+ const resolved = await eventCtx.credentials.resolve('DEEPSEEK_API_KEY')
294
+ apiKey = resolved?.value
295
+ } catch {
296
+ apiKey = undefined
297
+ }
298
+ }
299
+ if (!apiKey) {
300
+ balance = null
301
+ return
302
+ }
303
+ try {
304
+ const response = await fetch('https://api.deepseek.com/user/balance', {
305
+ headers: { authorization: `Bearer ${apiKey}` },
306
+ cache: 'no-store',
307
+ })
308
+ if (!response.ok) {
309
+ balance = null
310
+ return
311
+ }
312
+ const data = await response.json()
313
+ const info = Array.isArray(data?.balance_infos) ? data.balance_infos[0] : undefined
314
+ if (info) {
315
+ balance = {
316
+ currency: info.currency || 'CNY',
317
+ total: info.total_balance,
318
+ granted: info.granted_balance,
319
+ toppedUp: info.topped_up_balance,
320
+ isAvailable: data.is_available !== false,
321
+ updatedAt: Date.now(),
322
+ }
323
+ } else {
324
+ balance = null
325
+ }
326
+ } catch {
327
+ balance = null
328
+ }
329
+ }
330
+
331
+ const getStatus = () => ({
332
+ ...currentStatus,
333
+ tasks,
334
+ pulse: pulse && pulse.expiresAt > Date.now() ? pulse : undefined,
335
+ tokenUsage,
336
+ balance,
337
+ config: publicConfig(settings.get()),
338
+ })
339
+
340
+ const stopRuntime = (reason = 'settings-change') => {
341
+ bridge?.stop(reason)
342
+ bridge = undefined
343
+ reducer = undefined
344
+ }
345
+
346
+ const restartRuntime = (next) => {
347
+ stopRuntime('settings-change')
348
+ startRuntime(next)
349
+ }
350
+
351
+ const scheduleRestart = (next) => {
352
+ if (restartTimer) clearTimeout(restartTimer)
353
+ restartTimer = setTimeout(() => {
354
+ restartTimer = undefined
355
+ restartRuntime(next)
356
+ }, 400)
357
+ restartTimer.unref?.()
358
+ }
359
+
360
+ const startRuntime = (resolved) => {
361
+ if (resolved.enabled === false) {
362
+ logger.info?.('dsh-pet is disabled')
363
+ return
364
+ }
365
+ if (bridge) return
366
+ const helperConfig = config.helper ?? {}
367
+ const resolvedStatusUrl = statusUrl
368
+ || String(config.webuiUrl ?? process.env.DSH_PET_WEBUI_URL ?? 'http://127.0.0.1:3080/').replace(/\/$/, '') + STATUS_ENDPOINT
369
+ bridge = new HelperProcess({
370
+ ...helperConfig,
371
+ env: {
372
+ ...helperConfig.env,
373
+ DSH_PET_SCALE: String(resolved.scale ?? defaults.scale),
374
+ DSH_PET_BUBBLE_SCALE: String(resolved.bubbleScale ?? defaults.bubbleScale),
375
+ DSH_PET_ACTIVITY_LEVEL: String(resolved.activityLevel ?? defaults.activityLevel),
376
+ DSH_PET_REDUCED_MOTION: resolved.reducedMotion === true ? '1' : '0',
377
+ DSH_PET_BUBBLE_MODE: String(resolved.bubbleMode ?? defaults.bubbleMode),
378
+ DSH_PET_BUBBLE_STATES: (Array.isArray(resolved.bubbleStates) ? resolved.bubbleStates : defaults.bubbleStates).join(','),
379
+ DSH_PET_WORK_MINUTES: String(resolved.workMinutes ?? defaults.workMinutes),
380
+ DSH_PET_BREAK_MINUTES: String(resolved.breakMinutes ?? defaults.breakMinutes),
381
+ DSH_PET_STATUS_URL: resolvedStatusUrl,
382
+ DSH_PET_WEBUI_URL: String(config.webuiUrl ?? process.env.DSH_PET_WEBUI_URL ?? 'http://127.0.0.1:3080/'),
383
+ },
384
+ }, logger)
385
+ reducer = new CompanionReducer({ includeSubagents: resolved.includeSubagents === true })
386
+ bridge.start()
387
+ void refreshBalance()
388
+ if (!balanceTimer) {
389
+ balanceTimer = setInterval(() => void refreshBalance(), 5 * 60 * 1000)
390
+ balanceTimer.unref?.()
391
+ }
392
+ logger.info?.(`dsh-pet desktop helper started (status: ${resolvedStatusUrl})`)
393
+ }
394
+
395
+ const offEvent = eventCtx.on('session/event', (session, event) => {
396
+ if (!bridge || !reducer) return
397
+ // 捕获 token 用量:assistant/message 会携带 adapter 上报的 usage。
398
+ if (event?.type === 'assistant/message') {
399
+ const usage = event.data?.usage ?? event.data?.message?.usage
400
+ if (usage) {
401
+ const input = Number(usage.inputTokens ?? usage.promptTokens ?? usage.input ?? 0) || 0
402
+ const output = Number(usage.outputTokens ?? usage.completionTokens ?? usage.output ?? 0) || 0
403
+ tokenUsage.inputTokens += input
404
+ tokenUsage.outputTokens += output
405
+ tokenUsage.totalTokens += input + output
406
+ }
407
+ }
408
+ applyMessages(reducer.handle(session, event))
409
+ }, { global: true })
410
+ const offDisposed = eventCtx.on('session/disposed', (session) => {
411
+ if (!bridge || !reducer) return
412
+ applyMessages(reducer.disposeSession(session))
413
+ }, { global: true })
414
+
415
+ const unwatch = settings.watch((next) => {
416
+ if (next.enabled === false) {
417
+ if (restartTimer) {
418
+ clearTimeout(restartTimer)
419
+ restartTimer = undefined
420
+ }
421
+ stopRuntime('settings-change')
422
+ return
423
+ }
424
+ if (!bridge) {
425
+ scheduleRestart(next)
426
+ return
427
+ }
428
+ if (restartTimer) {
429
+ clearTimeout(restartTimer)
430
+ restartTimer = undefined
431
+ }
432
+ // 非启用类配置通过 status 里的 config 实时下发给 Helper;这里不重启进程。
433
+ logger.debug?.('dsh-pet settings changed; Helper will pick it up on next poll')
434
+ })
435
+
436
+ if (typeof ctx.inject === 'function') {
437
+ ctx.inject(['webServer'], (httpCtx) => {
438
+ const origin = `http://${httpCtx.webServer.host}:${httpCtx.webServer.port}`
439
+ statusUrl = `${origin}${STATUS_ENDPOINT}`
440
+ httpCtx.effect(
441
+ () => httpCtx.webServer.register({ kind: 'exact', path: CONFIG_ENDPOINT, handler: createConfigHandler(settings) }),
442
+ 'dsh-pet: local settings endpoint',
443
+ )
444
+ httpCtx.effect(
445
+ () => httpCtx.webServer.register({ kind: 'exact', path: STATUS_ENDPOINT, handler: async (_req, res) => jsonResponse(res, 200, getStatus()) }),
446
+ 'dsh-pet: local status endpoint',
447
+ )
448
+ httpCtx.effect(
449
+ () => httpCtx.webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler: createAssetHandler(config) }),
450
+ 'dsh-pet: /pet asset route',
451
+ )
452
+ startRuntime(settings.get())
453
+ })
454
+ } else {
455
+ startRuntime(settings.get())
456
+ }
457
+
458
+ ctx.effect(() => () => {
459
+ if (restartTimer) clearTimeout(restartTimer)
460
+ restartTimer = undefined
461
+ if (balanceTimer) clearInterval(balanceTimer)
462
+ balanceTimer = undefined
463
+ offEvent?.()
464
+ offDisposed?.()
465
+ unwatch()
466
+ stopRuntime('dsh-host-stop')
467
+ })
468
+ }
469
+
470
+ export function apply(ctx, config = {}) {
471
+ if (typeof ctx.inject === 'function') {
472
+ ctx.inject(['settings'], (settingsCtx) => mount(settingsCtx, config, ctx))
473
+ return
474
+ }
475
+ mount(ctx, config)
476
+ }
477
+
478
+ export {
479
+ CompanionMessageKind,
480
+ CompanionReducer,
481
+ CompanionState,
482
+ HelperProcess,
483
+ }
@@ -0,0 +1,133 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { dirname, join, resolve } from 'node:path'
6
+
7
+ const require = createRequire(import.meta.url)
8
+ const here = dirname(fileURLToPath(import.meta.url))
9
+ const packageRoot = resolve(here, '..')
10
+ const defaultHelperMain = resolve(packageRoot, 'runtime', 'electron-helper', 'main.js')
11
+
12
+ /**
13
+ * 解析 Electron 可执行文件。
14
+ * 优先级:
15
+ * 1. options.electronPath / DSH_PET_ELECTRON_PATH
16
+ * 2. 本机已安装的 electron npm 包(require('electron') 返回二进制路径)
17
+ * 3. 常见本地开发目录(便于当前 DSH Desktop 环境直接使用)
18
+ */
19
+ function resolveElectronPath(candidates = []) {
20
+ const seen = new Set()
21
+ const list = []
22
+ const push = (value) => {
23
+ if (!value || seen.has(value)) return
24
+ seen.add(value)
25
+ list.push(value)
26
+ }
27
+ for (const value of candidates) push(value)
28
+ if (process.env.DSH_PET_ELECTRON_PATH) push(process.env.DSH_PET_ELECTRON_PATH)
29
+ try {
30
+ const resolved = require('electron')
31
+ if (typeof resolved === 'string' && resolved) push(resolved)
32
+ } catch {
33
+ /* electron 未安装时跳过 */
34
+ }
35
+ // 当前机器上的 dsh-desktop-electron 开发依赖,便于本地直接跑通。
36
+ const localCandidates = [
37
+ 'D:/deepseek harness/tools/desktop-eval/dsh-desktop-electron/node_modules/electron/dist/electron.exe',
38
+ 'D:/deepseek harness/tools/desktop-eval/dsh-desktop-electron/node_modules/electron/dist/electron',
39
+ join(process.env.USERPROFILE || '', '.dsh', 'electron', 'electron.exe'),
40
+ ]
41
+ for (const candidate of localCandidates) push(candidate)
42
+ return list.find((value) => existsSync(value))
43
+ }
44
+
45
+ function defaultLaunch(options = {}) {
46
+ const electronPath = resolveElectronPath([options.electronPath])
47
+ if (!electronPath) {
48
+ throw new Error('better-dsh-pet: cannot resolve Electron executable. Set DSH_PET_ELECTRON_PATH or install electron.')
49
+ }
50
+ const helperPath = options.helperPath || defaultHelperMain
51
+ return { command: electronPath, args: [helperPath] }
52
+ }
53
+
54
+ /**
55
+ * 桌面 Helper 进程管理器。
56
+ *
57
+ * 新架构下 Helper 不再通过 stdin 协议通信,而是轮询宿主暴露的
58
+ * /plugins/better-dsh-pet/status HTTP 端点;因此这里只负责拉起/守护 Electron 进程。
59
+ */
60
+ export class HelperProcess {
61
+ constructor(options = {}, logger = console) {
62
+ this.options = options
63
+ this.logger = logger
64
+ this.child = undefined
65
+ this.stopping = false
66
+ this.restartSuppressed = false
67
+ this.restartTimer = undefined
68
+ }
69
+
70
+ start() {
71
+ if (this.child || this.stopping || this.restartSuppressed) return this.child
72
+ const helperPath = this.options.helperPath || defaultHelperMain
73
+ const launch = this.options.command
74
+ ? { command: this.options.command, args: this.options.args || [helperPath] }
75
+ : defaultLaunch(this.options)
76
+ const command = launch.command
77
+ const args = this.options.args || launch.args
78
+
79
+ const child = spawn(command, args, {
80
+ cwd: this.options.cwd || packageRoot,
81
+ env: { ...process.env, ...this.options.env },
82
+ stdio: ['ignore', 'pipe', 'pipe'],
83
+ windowsHide: true,
84
+ })
85
+ this.child = child
86
+ child.once('error', (error) => {
87
+ this.logger.error?.(`better-dsh-pet helper failed to start: ${error.message}`)
88
+ })
89
+ child.once('exit', (code, signal) => {
90
+ if (this.child !== child) return
91
+ this.child = undefined
92
+ if (!this.stopping && !this.restartSuppressed) {
93
+ this.logger.warn?.(`better-dsh-pet helper exited (code=${String(code)}, signal=${String(signal)}); restarting`)
94
+ this.#scheduleRestart()
95
+ }
96
+ })
97
+ child.stdout.on('data', (chunk) => {
98
+ const line = String(chunk).trim()
99
+ if (line) this.logger.debug?.(`better-dsh-pet helper: ${line}`)
100
+ })
101
+ child.stderr.on('data', (chunk) => {
102
+ const line = String(chunk).trim()
103
+ if (line) this.logger.warn?.(`better-dsh-pet helper: ${line}`)
104
+ })
105
+ return child
106
+ }
107
+
108
+ stop(reason = 'plugin-disposed') {
109
+ this.stopping = true
110
+ if (this.restartTimer) clearTimeout(this.restartTimer)
111
+ this.restartTimer = undefined
112
+ const child = this.child
113
+ if (!child) return
114
+ child.kill()
115
+ }
116
+
117
+ #scheduleRestart() {
118
+ if (this.restartTimer || this.stopping || this.restartSuppressed) return
119
+ const delay = this.options.restartDelayMs ?? 750
120
+ this.restartTimer = setTimeout(() => {
121
+ this.restartTimer = undefined
122
+ this.start()
123
+ }, delay)
124
+ this.restartTimer.unref?.()
125
+ }
126
+ }
127
+
128
+ export {
129
+ defaultHelperMain,
130
+ defaultLaunch,
131
+ packageRoot,
132
+ resolveElectronPath,
133
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * better-dsh-pet 桌面助手协议 —— 与 dsh-dafeiyu 的 companion 协议保持一致。
3
+ *
4
+ * DSH 宿主半侧把 Agent 状态压缩成新行分隔的 JSON 消息,通过 stdin 写入
5
+ * 桌面 Helper;Helper 在 stdout 回 ready/pong/closed。
6
+ */
7
+ export const PROTOCOL_VERSION = 1
8
+
9
+ export const CompanionState = Object.freeze({
10
+ IDLE: 'IDLE',
11
+ THINKING: 'THINKING',
12
+ WORKING: 'WORKING',
13
+ WAITING: 'WAITING',
14
+ SUCCESS: 'SUCCESS',
15
+ ERROR: 'ERROR',
16
+ DISCONNECTED: 'DISCONNECTED',
17
+ })
18
+
19
+ export const CompanionMessageKind = Object.freeze({
20
+ READY: 'ready',
21
+ HELLO: 'hello',
22
+ STATE: 'state',
23
+ PULSE: 'pulse',
24
+ TASK: 'task',
25
+ TASKS: 'tasks',
26
+ CONFIG: 'config',
27
+ PING: 'ping',
28
+ PONG: 'pong',
29
+ CLOSED: 'closed',
30
+ SHUTDOWN: 'shutdown',
31
+ })
32
+
33
+ const states = new Set(Object.values(CompanionState))
34
+ const kinds = new Set(Object.values(CompanionMessageKind))
35
+
36
+ export function createMessage(kind, payload = {}) {
37
+ if (!kinds.has(kind)) throw new TypeError(`Unknown companion message kind: ${kind}`)
38
+ return {
39
+ protocolVersion: PROTOCOL_VERSION,
40
+ kind,
41
+ timestamp: Date.now(),
42
+ ...payload,
43
+ }
44
+ }
45
+
46
+ export function assertCompanionMessage(value) {
47
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
48
+ throw new TypeError('Companion message must be an object')
49
+ }
50
+ if (value.protocolVersion !== PROTOCOL_VERSION) {
51
+ throw new TypeError(`Unsupported protocol version: ${String(value.protocolVersion)}`)
52
+ }
53
+ if (!kinds.has(value.kind)) throw new TypeError(`Unknown companion message kind: ${String(value.kind)}`)
54
+ if ((value.kind === CompanionMessageKind.STATE || value.kind === CompanionMessageKind.PULSE)
55
+ && !states.has(value.state)) {
56
+ throw new TypeError(`Unknown companion state: ${String(value.state)}`)
57
+ }
58
+ return value
59
+ }
60
+
61
+ export function encodeMessage(message) {
62
+ assertCompanionMessage(message)
63
+ return `${JSON.stringify(message)}\n`
64
+ }