@tavlo-dsh/dsh-plugin-hooks 0.0.0-stage → 0.1.3

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.
@@ -0,0 +1,486 @@
1
+ /**
2
+ * Redacts hook events and coordinates in-app SSE, OS system notifications,
3
+ * custom WAV playback, Windows taskbar flashing, and async third-party dispatch.
4
+ */
5
+
6
+ import { randomUUID } from 'node:crypto'
7
+ import { CATEGORY_META, getMountPoint } from './hook-catalog.js'
8
+ import { getCustomSoundInfo, getCustomSoundPath, playNativeSound } from './sound-manager.js'
9
+ import { clearTaskbarAttention, flashTaskbar, sendSystemNotification } from './system-notifier.js'
10
+ import { sendToProvider } from './third-party-providers.js'
11
+
12
+ export const QUEUE_CAPACITY = 64
13
+ export const MAX_CONCURRENCY = 4
14
+ export const MAX_THIRD_PARTY_TARGETS_PER_JOB = 20
15
+
16
+ const MAX_SUMMARY_CHARS = 160
17
+ const MAX_TITLE_CHARS = 200
18
+ const MAX_PROJECT_CHARS = 80
19
+
20
+ const WIN_DRIVE_PATH_RE = /[A-Za-z]:\\[^\s]+/g
21
+ const WIN_SLASH_PATH_RE = /[A-Za-z]:\/[^\s]+/g
22
+ const UNC_PATH_RE = /\\\\[^\s\\]+\\[^\s]+/g
23
+ const POSIX_ABS_PATH_RE = /\/(?:Users|home|tmp|var|etc|opt|mnt|root|private)\/[^\s]+/g
24
+
25
+ function truncateCodepoints(str, max) {
26
+ const chars = Array.from(str)
27
+ return chars.length <= max ? str : chars.slice(0, max).join('')
28
+ }
29
+
30
+ function stripPathsAndControlChars(raw) {
31
+ if (typeof raw !== 'string') return ''
32
+ return raw
33
+ .replace(WIN_DRIVE_PATH_RE, '[path]')
34
+ .replace(WIN_SLASH_PATH_RE, '[path]')
35
+ .replace(UNC_PATH_RE, '[path]')
36
+ .replace(POSIX_ABS_PATH_RE, '[path]')
37
+ .replace(/[\r\n\t\x00-\x1f\x7f]+/g, ' ')
38
+ .replace(/\s+/g, ' ')
39
+ .trim()
40
+ }
41
+
42
+ function extractSafeProjectName(hookEvent = {}) {
43
+ const candidates = [hookEvent.projectName, hookEvent.project, hookEvent.cwd]
44
+ for (const raw of candidates) {
45
+ if (typeof raw !== 'string' || !raw.trim()) continue
46
+ let val = raw.trim().replace(/[\\/]+$/, '')
47
+ if (!val) continue
48
+ if (val.includes('/') || val.includes('\\')) {
49
+ const segments = val.split(/[\\/]+/).filter(Boolean)
50
+ val = segments.length > 0 ? segments[segments.length - 1] : ''
51
+ }
52
+ if (!val || /^[A-Za-z]:$/.test(val)) continue
53
+ const clean = stripPathsAndControlChars(val)
54
+ if (clean && clean !== '[path]') {
55
+ return truncateCodepoints(clean, MAX_PROJECT_CHARS)
56
+ }
57
+ }
58
+ return 'DSH Workspace'
59
+ }
60
+
61
+ function formatLocalTimestamp(rawTimestamp) {
62
+ let date = rawTimestamp ? new Date(rawTimestamp) : new Date()
63
+ if (Number.isNaN(date.getTime())) {
64
+ date = new Date()
65
+ }
66
+ const pad = (n) => String(n).padStart(2, '0')
67
+ return (
68
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
69
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
70
+ )
71
+ }
72
+
73
+ /**
74
+ * Redact absolute filesystem paths, control chars, and raw tool/prompt content into
75
+ * a safe, unified notification message payload.
76
+ * @param {Record<string, unknown>} [hookEvent]
77
+ */
78
+ export function formatRedactedMessage(hookEvent = {}) {
79
+ const mountPointId = hookEvent.hookPoint || hookEvent.mountPointId
80
+ const mpMeta = mountPointId ? getMountPoint(mountPointId) : undefined
81
+ const rawCategory = hookEvent.category || hookEvent.event || mpMeta?.category || 'Notification'
82
+ const meta = CATEGORY_META[rawCategory] || CATEGORY_META.Notification
83
+ const event = CATEGORY_META[rawCategory] ? rawCategory : 'Notification'
84
+
85
+ const icon = meta.icon
86
+ const eventLabel = meta.labelZh
87
+ const variant = meta.variant
88
+ const project = extractSafeProjectName(hookEvent)
89
+ const id = typeof hookEvent.id === 'string' && hookEvent.id.trim()
90
+ ? hookEvent.id.trim()
91
+ : typeof hookEvent.eventId === 'string' && hookEvent.eventId.trim()
92
+ ? hookEvent.eventId.trim()
93
+ : randomUUID()
94
+ const localTime = formatLocalTimestamp(hookEvent.timestamp ?? hookEvent.time)
95
+
96
+ const rawSummary =
97
+ typeof hookEvent.summary === 'string' && hookEvent.summary.trim()
98
+ ? hookEvent.summary
99
+ : typeof hookEvent.reason === 'string' && hookEvent.reason.trim()
100
+ ? hookEvent.reason
101
+ : ''
102
+
103
+ let safeSummary = truncateCodepoints(stripPathsAndControlChars(rawSummary), MAX_SUMMARY_CHARS)
104
+ if (!safeSummary || safeSummary === '[path]') {
105
+ safeSummary = truncateCodepoints(`${project} - ${eventLabel}`, MAX_SUMMARY_CHARS)
106
+ }
107
+
108
+ const title = `DSH ${icon} ${eventLabel}`
109
+ const body = [
110
+ `🏷️ 类型:${icon} ${eventLabel}`,
111
+ '🧰 来源:DSH',
112
+ `📁 项目:${project}`,
113
+ `🕒 时间:${localTime}`,
114
+ `🆔 通知:${id}`,
115
+ `📌 内容:${safeSummary}`,
116
+ ].join('\n')
117
+
118
+ return {
119
+ id,
120
+ event,
121
+ eventLabel,
122
+ icon,
123
+ source: 'DSH',
124
+ project,
125
+ time: localTime,
126
+ title,
127
+ body,
128
+ summary: safeSummary,
129
+ variant,
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Create the multi-channel notification dispatcher.
135
+ */
136
+ export function createNotificationDispatcher({
137
+ getConfig,
138
+ getResolvedSecrets,
139
+ getDataDir,
140
+ eventHub,
141
+ logger,
142
+ fetchImpl = globalThis.fetch,
143
+ spawnImpl,
144
+ platform = process.platform,
145
+ } = {}) {
146
+ const queue = []
147
+ const inFlight = new Set()
148
+ const disposeController = new AbortController()
149
+ let activeWorkers = 0
150
+ let disposed = false
151
+
152
+ async function resolveSecretsForTarget(targetId) {
153
+ if (typeof getResolvedSecrets !== 'function' || !targetId) return {}
154
+ try {
155
+ const res = await getResolvedSecrets(targetId)
156
+ if (!res || typeof res !== 'object') return {}
157
+ if (res[targetId] && typeof res[targetId] === 'object' && !Array.isArray(res[targetId])) {
158
+ return res[targetId]
159
+ }
160
+ return res
161
+ } catch {
162
+ return {}
163
+ }
164
+ }
165
+
166
+ function scheduleQueueDrain() {
167
+ if (disposed) return
168
+ while (activeWorkers < MAX_CONCURRENCY && queue.length > 0) {
169
+ const item = queue.shift()
170
+ if (!item) break
171
+ activeWorkers++
172
+ const task = (async () => {
173
+ try {
174
+ const mergedConfig = {
175
+ ...(item.target.config || {}),
176
+ ...(item.secrets || {}),
177
+ }
178
+ const result = await sendToProvider(item.target.provider, mergedConfig, item.message, {
179
+ fetchImpl,
180
+ signal: disposeController.signal,
181
+ })
182
+ if (!result.accepted && !disposed) {
183
+ logger?.warn?.(
184
+ `tavlo-hooks: third-party delivery failed (${item.target.provider}/${item.target.id}): ${result.errorCode || 'rejected'} ${result.message}`,
185
+ )
186
+ }
187
+ } catch (error) {
188
+ if (!disposed) {
189
+ logger?.warn?.(
190
+ `tavlo-hooks: third-party delivery error (${item.target?.provider}/${item.target?.id}): ${error?.message || 'unknown'}`,
191
+ )
192
+ }
193
+ } finally {
194
+ activeWorkers--
195
+ inFlight.delete(task)
196
+ scheduleQueueDrain()
197
+ }
198
+ })()
199
+ inFlight.add(task)
200
+ }
201
+ }
202
+
203
+ async function enqueueThirdPartyBatch(message, targets) {
204
+ if (disposed || targets.length === 0) return { queued: 0, dropped: 0 }
205
+ let queued = 0
206
+ let dropped = 0
207
+ const boundedTargets = targets.slice(0, MAX_THIRD_PARTY_TARGETS_PER_JOB)
208
+ for (const target of boundedTargets) {
209
+ if (queue.length >= QUEUE_CAPACITY) {
210
+ dropped++
211
+ logger?.warn?.(
212
+ `tavlo-hooks: third-party queue full (${QUEUE_CAPACITY}); dropping notification for ${target.provider}/${target.id}`,
213
+ )
214
+ continue
215
+ }
216
+ const secrets = await resolveSecretsForTarget(target.id)
217
+ if (disposed) break
218
+ queue.push({ target, secrets, message })
219
+ queued++
220
+ }
221
+ scheduleQueueDrain()
222
+ return { queued, dropped }
223
+ }
224
+
225
+ /**
226
+ * Dispatch a hook event across in-app SSE, native sound, OS system notifications,
227
+ * Windows taskbar flashing, and third-party webhook providers.
228
+ */
229
+ async function dispatch(hookEvent = {}, directive) {
230
+ if (disposed) return { dispatched: false, reason: 'disposed' }
231
+ if (directive?.suppress === true || directive?.notify === false) {
232
+ return { dispatched: false, suppressed: true }
233
+ }
234
+
235
+ const enrichedEvent =
236
+ typeof directive?.summary === 'string' && directive.summary.trim()
237
+ ? { ...hookEvent, summary: directive.summary }
238
+ : hookEvent
239
+
240
+ const msg = formatRedactedMessage(enrichedEvent)
241
+ if (typeof directive?.title === 'string' && directive.title.trim()) {
242
+ const safeTitle = truncateCodepoints(stripPathsAndControlChars(directive.title), MAX_TITLE_CHARS)
243
+ if (safeTitle && safeTitle !== '[path]') {
244
+ msg.title = safeTitle
245
+ }
246
+ }
247
+
248
+ const allowedChannels = Array.isArray(directive?.channels) ? new Set(directive.channels) : null
249
+ const allowsChannel = (name) => !allowedChannels || allowedChannels.has(name)
250
+
251
+ const config = (await getConfig?.()) || {}
252
+ const dataDir = typeof getDataDir === 'function' ? getDataDir() : undefined
253
+ const mountPointId = hookEvent.hookPoint || hookEvent.mountPointId
254
+ const mpMeta = mountPointId ? getMountPoint(mountPointId) : undefined
255
+ const mpCfg = mountPointId ? config?.mountPoints?.[mountPointId] : undefined
256
+
257
+ const bellEnabled =
258
+ mpCfg !== undefined
259
+ ? Boolean(mpCfg.bellEnabled)
260
+ : hookEvent.bellEnabled !== undefined
261
+ ? Boolean(hookEvent.bellEnabled)
262
+ : Boolean(mpMeta?.defaultBell ?? true)
263
+
264
+ const connectedClients = eventHub?.getConnectedClientCount?.() ?? 0
265
+ const hasFocusedVisible = Boolean(eventHub?.hasFocusedVisibleClient?.())
266
+ const suppressWhenFocused = config?.systemNotifications?.suppressWhenFocused !== false
267
+ const isFocusedSuppressed = suppressWhenFocused && hasFocusedVisible
268
+
269
+ const customSoundInfo = dataDir ? await getCustomSoundInfo(dataDir) : null
270
+
271
+ const shouldSendSystem = Boolean(
272
+ config?.systemNotifications?.enabled &&
273
+ bellEnabled &&
274
+ !isFocusedSuppressed &&
275
+ allowsChannel('system'),
276
+ )
277
+
278
+ let customSoundPlayed = false
279
+ let systemResult = { ok: false, channel: 'none' }
280
+
281
+ if (shouldSendSystem) {
282
+ if (customSoundInfo && dataDir) {
283
+ const soundRes = await playNativeSound(getCustomSoundPath(dataDir), { platform, spawnImpl })
284
+ customSoundPlayed = Boolean(soundRes?.played)
285
+ if (!customSoundPlayed) {
286
+ logger?.warn?.(`tavlo-hooks: native WAV playback failed: ${soundRes?.reason || 'unknown'}`)
287
+ }
288
+ }
289
+ const urgency =
290
+ msg.event === 'PermissionRequest' || msg.event === 'StopFailure' ? 'critical' : 'normal'
291
+ systemResult = await sendSystemNotification({
292
+ title: msg.title,
293
+ body: msg.body,
294
+ urgency,
295
+ silent: customSoundPlayed,
296
+ platform,
297
+ spawnImpl,
298
+ })
299
+ if (!systemResult.ok) {
300
+ logger?.warn?.(
301
+ `tavlo-hooks: system notification failed (${systemResult.channel}): ${systemResult.error || 'unknown'}`,
302
+ )
303
+ }
304
+ }
305
+
306
+ const shouldFlashTaskbar = Boolean(
307
+ config?.systemNotifications?.taskbarAttentionEnabled &&
308
+ bellEnabled &&
309
+ !hasFocusedVisible &&
310
+ allowsChannel('taskbar'),
311
+ )
312
+
313
+ let taskbarResult = { ok: true, skipped: true }
314
+ if (shouldFlashTaskbar) {
315
+ taskbarResult = await flashTaskbar({
316
+ mode: config?.systemNotifications?.taskbarAttentionMode || 'finite',
317
+ flashCount: config?.systemNotifications?.taskbarAttentionFlashCount ?? 5,
318
+ platform,
319
+ spawnImpl,
320
+ })
321
+ }
322
+
323
+ const inAppEnabled = config?.inApp?.enabled !== false && allowsChannel('inApp')
324
+ const playWebAudio = Boolean(shouldSendSystem && customSoundInfo && !customSoundPlayed && connectedClients > 0)
325
+ const shouldWebNotify = Boolean(shouldSendSystem && !systemResult.ok && connectedClients > 0)
326
+
327
+ if (inAppEnabled && typeof eventHub?.broadcast === 'function') {
328
+ eventHub.broadcast('notification', {
329
+ ...msg,
330
+ category: msg.event,
331
+ sessionId: hookEvent.sessionId,
332
+ sessionTitle: hookEvent.sessionTitle,
333
+ hookPoint: mountPointId,
334
+ approvalId: hookEvent.approvalId,
335
+ timestamp: hookEvent.timestamp || new Date().toISOString(),
336
+ soundUrl: customSoundInfo ? '/api/tavlo-hooks/sound/current' : null,
337
+ playWebAudio,
338
+ shouldWebNotify,
339
+ hostSystemNotified: Boolean(systemResult.ok),
340
+ systemNotified: Boolean(systemResult.ok),
341
+ autoCloseEnabled: config?.inApp?.autoCloseEnabled !== false,
342
+ autoCloseSeconds: config?.inApp?.autoCloseSeconds ?? 60,
343
+ })
344
+ }
345
+
346
+ let thirdPartySummary = { queued: 0, dropped: 0 }
347
+ if (config?.thirdParty?.enabled && allowsChannel('thirdParty')) {
348
+ const targets = Array.isArray(config.thirdParty.targets) ? config.thirdParty.targets : []
349
+ const matching = targets.filter((t) => t && t.enabled && t.events?.[msg.event])
350
+ if (matching.length > 0) {
351
+ thirdPartySummary = await enqueueThirdPartyBatch(msg, matching)
352
+ }
353
+ }
354
+
355
+ return {
356
+ dispatched: true,
357
+ id: msg.id,
358
+ inAppBroadcast: inAppEnabled,
359
+ systemNotification: systemResult,
360
+ customSoundPlayed,
361
+ taskbar: taskbarResult,
362
+ thirdParty: thirdPartySummary,
363
+ }
364
+ }
365
+
366
+ function dismissApproval(approvalId) {
367
+ if (disposed || !approvalId) return
368
+ eventHub?.broadcast?.('dismiss', { approvalId: String(approvalId) })
369
+ }
370
+
371
+ async function testThirdPartyTarget(target, resolvedSecrets, { signal } = {}) {
372
+ const sampleMessage = formatRedactedMessage({
373
+ event: 'Stop',
374
+ projectName: 'demo-project',
375
+ summary: '测试通知:Hook 通知通道连接正常',
376
+ })
377
+
378
+ let secretBag = {}
379
+ if (resolvedSecrets && typeof resolvedSecrets === 'object') {
380
+ if (
381
+ target?.id &&
382
+ resolvedSecrets[target.id] &&
383
+ typeof resolvedSecrets[target.id] === 'object' &&
384
+ !Array.isArray(resolvedSecrets[target.id])
385
+ ) {
386
+ secretBag = resolvedSecrets[target.id]
387
+ } else {
388
+ secretBag = resolvedSecrets
389
+ }
390
+ }
391
+
392
+ const mergedConfig = {
393
+ ...(target?.config || {}),
394
+ ...secretBag,
395
+ }
396
+
397
+ const startedAt = Date.now()
398
+ const result = await sendToProvider(target?.provider, mergedConfig, sampleMessage, {
399
+ fetchImpl,
400
+ signal,
401
+ })
402
+ return {
403
+ ...result,
404
+ provider: target?.provider,
405
+ targetId: target?.id,
406
+ elapsedMs: Math.max(0, Date.now() - startedAt),
407
+ }
408
+ }
409
+
410
+ async function testSystemNotification() {
411
+ const sample = formatRedactedMessage({
412
+ event: 'Notification',
413
+ projectName: 'DSH',
414
+ summary: '系统通知与提示音测试',
415
+ })
416
+ const dataDir = typeof getDataDir === 'function' ? getDataDir() : undefined
417
+ const customSoundInfo = dataDir ? await getCustomSoundInfo(dataDir) : null
418
+
419
+ let soundPlayed = false
420
+ if (customSoundInfo && dataDir) {
421
+ const soundRes = await playNativeSound(getCustomSoundPath(dataDir), { platform, spawnImpl })
422
+ soundPlayed = Boolean(soundRes?.played)
423
+ }
424
+
425
+ const sysRes = await sendSystemNotification({
426
+ title: sample.title,
427
+ body: sample.body,
428
+ urgency: 'normal',
429
+ silent: soundPlayed,
430
+ platform,
431
+ spawnImpl,
432
+ })
433
+
434
+ return {
435
+ ok: sysRes.ok,
436
+ channel: sysRes.channel,
437
+ soundPlayed,
438
+ ...(sysRes.error ? { error: sysRes.error } : {}),
439
+ }
440
+ }
441
+
442
+ async function testTaskbarFlash(overrides = {}) {
443
+ let config = {}
444
+ try {
445
+ config = (await getConfig?.()) || {}
446
+ } catch {
447
+ config = {}
448
+ }
449
+ const mode = overrides?.mode ?? config?.systemNotifications?.taskbarAttentionMode ?? 'finite'
450
+ const flashCount = overrides?.flashCount ?? config?.systemNotifications?.taskbarAttentionFlashCount ?? 5
451
+ return flashTaskbar({
452
+ mode,
453
+ flashCount,
454
+ targetPid: overrides?.targetPid,
455
+ windowTitleHint: overrides?.windowTitleHint,
456
+ platform,
457
+ spawnImpl,
458
+ })
459
+ }
460
+
461
+ async function clearAttention(overrides = {}) {
462
+ return clearTaskbarAttention({
463
+ targetPid: overrides?.targetPid,
464
+ windowTitleHint: overrides?.windowTitleHint,
465
+ platform,
466
+ spawnImpl,
467
+ })
468
+ }
469
+
470
+ async function dispose() {
471
+ disposed = true
472
+ queue.length = 0
473
+ disposeController.abort()
474
+ await Promise.allSettled([...inFlight])
475
+ }
476
+
477
+ return {
478
+ dispatch,
479
+ dismissApproval,
480
+ testThirdPartyTarget,
481
+ testSystemNotification,
482
+ testTaskbarFlash,
483
+ clearTaskbarAttention: clearAttention,
484
+ dispose,
485
+ }
486
+ }