-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathnotify.ts
More file actions
620 lines (523 loc) · 16.6 KB
/
notify.ts
File metadata and controls
620 lines (523 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/**
* notify
* Native OS notifications for OpenCode
*
* Philosophy: "Notify the human when the AI needs them back, not for every micro-event."
*
* Features:
* - Uses cmux native notifications when running inside cmux
* - Auto-detects terminal emulator (Ghostty, Kitty, iTerm, WezTerm, etc.)
* - Suppresses notifications when terminal is focused (like Ghostty does)
* - Click notification to focus terminal
* - Parent session only by default (no spam from sub-tasks)
*
* Uses cmux CLI first (if available), then node-notifier fallback:
* - cmux: `cmux notify --title ... --subtitle ... --body ...`
* - macOS: terminal-notifier (native NSUserNotificationCenter)
* - Windows: SnoreToast (native toast notifications)
* - Linux: notify-send (native desktop notifications)
*/
import * as fs from "node:fs/promises"
import * as os from "node:os"
import * as path from "node:path"
import type { Plugin } from "@opencode-ai/plugin"
import type { Event } from "@opencode-ai/sdk"
// @ts-expect-error - installed at runtime by OCX
import detectTerminal from "detect-terminal"
// @ts-expect-error - installed at runtime by OCX
import notifier from "node-notifier"
import type { OpencodeClient } from "./kdco-primitives/types"
import { sendNotificationWithFallback } from "./notify/backend"
import { canUseCmuxNotification, sendCmuxNotification } from "./notify/cmux"
interface NotifyConfig {
/** Notify for child/sub-session events (default: false) */
notifyChildSessions: boolean
/** Sound configuration per event type */
sounds: {
idle: string
error: string
permission: string
question?: string
}
/** Quiet hours configuration */
quietHours: {
enabled: boolean
start: string // "HH:MM" format
end: string // "HH:MM" format
}
/** Override terminal detection (optional) */
terminal?: string
}
interface TerminalInfo {
name: string | null
bundleId: string | null
processName: string | null
}
const DEFAULT_CONFIG: NotifyConfig = {
notifyChildSessions: false,
sounds: {
idle: "Glass",
error: "Basso",
permission: "Submarine",
},
quietHours: {
enabled: false,
start: "22:00",
end: "08:00",
},
}
// Terminal name to macOS process name mapping (for focus detection)
const TERMINAL_PROCESS_NAMES: Record<string, string> = {
ghostty: "Ghostty",
kitty: "kitty",
iterm: "iTerm2",
iterm2: "iTerm2",
wezterm: "WezTerm",
alacritty: "Alacritty",
terminal: "Terminal",
apple_terminal: "Terminal",
hyper: "Hyper",
warp: "Warp",
vscode: "Code",
"vscode-insiders": "Code - Insiders",
}
// ==========================================
// CONFIGURATION
// ==========================================
async function loadConfig(): Promise<NotifyConfig> {
const configPath = path.join(os.homedir(), ".config", "opencode", "kdco-notify.json")
try {
const content = await fs.readFile(configPath, "utf8")
const userConfig = JSON.parse(content) as Partial<NotifyConfig>
// Merge with defaults
return {
...DEFAULT_CONFIG,
...userConfig,
sounds: {
...DEFAULT_CONFIG.sounds,
...userConfig.sounds,
},
quietHours: {
...DEFAULT_CONFIG.quietHours,
...userConfig.quietHours,
},
}
} catch {
// Config doesn't exist or is invalid, use defaults
return DEFAULT_CONFIG
}
}
// ==========================================
// TERMINAL DETECTION (macOS)
// ==========================================
async function runOsascript(script: string): Promise<string | null> {
if (process.platform !== "darwin") return null
try {
const proc = Bun.spawn(["osascript", "-e", script], {
stdout: "pipe",
stderr: "pipe",
})
const output = await new Response(proc.stdout).text()
return output.trim()
} catch {
return null
}
}
async function getBundleId(appName: string): Promise<string | null> {
return runOsascript(`id of application "${appName}"`)
}
async function getFrontmostApp(): Promise<string | null> {
return runOsascript(
'tell application "System Events" to get name of first application process whose frontmost is true',
)
}
async function detectTerminalInfo(config: NotifyConfig): Promise<TerminalInfo> {
// Use config override if provided
const terminalName = config.terminal || detectTerminal() || null
if (!terminalName) {
return { name: null, bundleId: null, processName: null }
}
// Get process name for focus detection
const processName = TERMINAL_PROCESS_NAMES[terminalName.toLowerCase()] || terminalName
// Dynamically get bundle ID from macOS (no hardcoding!)
const bundleId = await getBundleId(processName)
return {
name: terminalName,
bundleId,
processName,
}
}
async function isTerminalFocused(terminalInfo: TerminalInfo): Promise<boolean> {
if (!terminalInfo.processName) return false
if (process.platform !== "darwin") return false
const frontmost = await getFrontmostApp()
if (!frontmost) return false
// Case-insensitive comparison
return frontmost.toLowerCase() === terminalInfo.processName.toLowerCase()
}
// ==========================================
// QUIET HOURS CHECK
// ==========================================
function isQuietHours(config: NotifyConfig): boolean {
if (!config.quietHours.enabled) return false
const now = new Date()
const currentMinutes = now.getHours() * 60 + now.getMinutes()
const [startHour, startMin] = config.quietHours.start.split(":").map(Number)
const [endHour, endMin] = config.quietHours.end.split(":").map(Number)
const startMinutes = startHour * 60 + startMin
const endMinutes = endHour * 60 + endMin
// Handle overnight quiet hours (e.g., 22:00 - 08:00)
if (startMinutes > endMinutes) {
return currentMinutes >= startMinutes || currentMinutes < endMinutes
}
return currentMinutes >= startMinutes && currentMinutes < endMinutes
}
// ==========================================
// PARENT SESSION DETECTION
// ==========================================
async function isParentSession(client: OpencodeClient, sessionID: string): Promise<boolean> {
try {
const session = await client.session.get({ path: { id: sessionID } })
// No parentID means this IS the parent/root session
return !session.data?.parentID
} catch {
// If we can't fetch, assume it's a parent to be safe (notify rather than miss)
return true
}
}
// ==========================================
// NOTIFICATION SENDER
// ==========================================
interface NotificationOptions {
title: string
message: string
subtitle?: string
cmuxBody?: string
sound: string
terminalInfo: TerminalInfo
}
interface NotificationRuntime {
preferCmux: boolean
}
const QUESTION_DEDUPE_WINDOW_MS = 1500
const READY_DEDUPE_WINDOW_MS = 1500
const PERMISSION_DEDUPE_WINDOW_MS = 1500
type RecentNotifications = Map<string, number>
function toNonEmptyString(value: unknown): string | null {
if (typeof value !== "string") return null
const normalized = value.trim()
if (!normalized) return null
return normalized
}
function shouldSendDedupedNotification(
recentNotifications: RecentNotifications,
dedupeKey: string,
windowMs: number,
nowMs = Date.now(),
): boolean {
for (const [key, timestamp] of recentNotifications) {
if (nowMs - timestamp >= windowMs) {
recentNotifications.delete(key)
}
}
const lastSentAt = recentNotifications.get(dedupeKey)
if (lastSentAt !== undefined && nowMs - lastSentAt < windowMs) {
return false
}
recentNotifications.set(dedupeKey, nowMs)
return true
}
function buildQuestionToolDedupeKey(sessionID: unknown, callID: unknown): string | null {
const normalizedSessionID = toNonEmptyString(sessionID)
if (!normalizedSessionID) return null
const normalizedCallID = toNonEmptyString(callID)
if (!normalizedCallID) return null
return `question:${normalizedSessionID}:${normalizedCallID}`
}
function buildQuestionEventDedupeKey(properties: unknown): string | null {
if (!properties || typeof properties !== "object") return null
const record = properties as Record<string, unknown>
const normalizedSessionID = toNonEmptyString(record.sessionID)
if (!normalizedSessionID) return null
const toolInfo =
record.tool && typeof record.tool === "object"
? (record.tool as Record<string, unknown>)
: undefined
const normalizedCallID = toNonEmptyString(toolInfo?.callID)
if (normalizedCallID) {
return `question:${normalizedSessionID}:${normalizedCallID}`
}
const normalizedRequestID = toNonEmptyString(record.id)
if (normalizedRequestID) {
return `question:${normalizedSessionID}:request:${normalizedRequestID}`
}
return null
}
function buildSessionReadyDedupeKey(sessionID: unknown): string | null {
const normalizedSessionID = toNonEmptyString(sessionID)
if (!normalizedSessionID) return null
return `session-ready:${normalizedSessionID}`
}
function buildPermissionEventDedupeKey(properties: unknown): string | null {
if (!properties || typeof properties !== "object") return null
const record = properties as Record<string, unknown>
const normalizedRequestID = toNonEmptyString(record.id)
if (!normalizedRequestID) return null
return `permission:request:${normalizedRequestID}`
}
function sendNodeNotification(options: NotificationOptions): void {
const { title, message, sound, terminalInfo } = options
// Base notification options
const notifyOptions: Record<string, unknown> = {
title,
message,
sound,
}
// macOS-specific: click notification to focus terminal
if (process.platform === "darwin" && terminalInfo.bundleId) {
notifyOptions.activate = terminalInfo.bundleId
}
notifier.notify(notifyOptions)
}
async function sendNotification(
options: NotificationOptions,
runtime: NotificationRuntime,
): Promise<void> {
await sendNotificationWithFallback({
preferCmux: runtime.preferCmux,
tryCmuxNotify: () =>
sendCmuxNotification({
title: options.title,
subtitle: options.subtitle,
body: options.cmuxBody ?? options.message,
}),
sendNodeNotify: () => sendNodeNotification(options),
})
}
// ==========================================
// EVENT HANDLERS
// ==========================================
async function handleSessionIdle(
client: OpencodeClient,
sessionID: string,
config: NotifyConfig,
terminalInfo: TerminalInfo,
notificationRuntime: NotificationRuntime,
): Promise<void> {
// Check if we should notify for this session
if (!config.notifyChildSessions) {
const isParent = await isParentSession(client, sessionID)
if (!isParent) return
}
// Check quiet hours
if (isQuietHours(config)) return
// Check if terminal is focused (suppress notification if user is already looking)
if (await isTerminalFocused(terminalInfo)) return
// Get session info for context
let sessionTitle = "Task"
try {
const session = await client.session.get({ path: { id: sessionID } })
if (session.data?.title) {
sessionTitle = session.data.title.slice(0, 50)
}
} catch {
// Use default title
}
await sendNotification(
{
title: "Ready for review",
message: sessionTitle,
subtitle: sessionTitle,
cmuxBody: "OpenCode task is ready for review",
sound: config.sounds.idle,
terminalInfo,
},
notificationRuntime,
)
}
async function handleSessionError(
client: OpencodeClient,
sessionID: string,
error: string | undefined,
config: NotifyConfig,
terminalInfo: TerminalInfo,
notificationRuntime: NotificationRuntime,
): Promise<void> {
// Check if we should notify for this session
if (!config.notifyChildSessions) {
const isParent = await isParentSession(client, sessionID)
if (!isParent) return
}
// Check quiet hours
if (isQuietHours(config)) return
// Check if terminal is focused (suppress notification if user is already looking)
if (await isTerminalFocused(terminalInfo)) return
const errorMessage = error?.slice(0, 100) || "Something went wrong"
await sendNotification(
{
title: "Something went wrong",
message: errorMessage,
sound: config.sounds.error,
terminalInfo,
},
notificationRuntime,
)
}
async function handlePermissionUpdated(
config: NotifyConfig,
terminalInfo: TerminalInfo,
notificationRuntime: NotificationRuntime,
): Promise<void> {
// Always notify for permission events - AI is blocked waiting for human
// No parent check needed: permissions always need human attention
// Check quiet hours
if (isQuietHours(config)) return
// Check if terminal is focused (suppress notification if user is already looking)
if (await isTerminalFocused(terminalInfo)) return
await sendNotification(
{
title: "Waiting for you",
message: "OpenCode needs your input",
sound: config.sounds.permission,
terminalInfo,
},
notificationRuntime,
)
}
async function handleQuestionAsked(
config: NotifyConfig,
terminalInfo: TerminalInfo,
notificationRuntime: NotificationRuntime,
): Promise<void> {
// Guard: quiet hours only (no focus check for questions - tmux workflow)
if (isQuietHours(config)) return
const sound = config.sounds.question ?? config.sounds.permission
await sendNotification(
{
title: "Question for you",
message: "OpenCode needs your input",
sound,
terminalInfo,
},
notificationRuntime,
)
}
// ==========================================
// PLUGIN EXPORT
// ==========================================
export const NotifyPlugin: Plugin = async (ctx) => {
// When invoked programmatically from a harness, suppress all notifications
if (process.env.OPENCODE_NO_NOTIFY === "1" || process.env.OPENCODE_NO_NOTIFY === "true") {
return {}
}
const { client } = ctx
// Load config once at startup
const config = await loadConfig()
// Detect terminal once at startup (cached for performance)
const terminalInfo = await detectTerminalInfo(config)
const notificationRuntime: NotificationRuntime = {
preferCmux: canUseCmuxNotification(),
}
const recentQuestionNotifications: RecentNotifications = new Map()
const recentReadyNotifications: RecentNotifications = new Map()
const recentPermissionNotifications: RecentNotifications = new Map()
const notifyQuestionIfNeeded = async (dedupeKey: string | null): Promise<void> => {
if (
dedupeKey &&
!shouldSendDedupedNotification(
recentQuestionNotifications,
dedupeKey,
QUESTION_DEDUPE_WINDOW_MS,
)
) {
return
}
await handleQuestionAsked(config, terminalInfo, notificationRuntime)
}
const notifySessionReadyIfNeeded = async (sessionID: unknown): Promise<void> => {
const normalizedSessionID = toNonEmptyString(sessionID)
if (!normalizedSessionID) return
const dedupeKey = buildSessionReadyDedupeKey(normalizedSessionID)
if (!dedupeKey) return
if (
!shouldSendDedupedNotification(recentReadyNotifications, dedupeKey, READY_DEDUPE_WINDOW_MS)
) {
return
}
await handleSessionIdle(
client as OpencodeClient,
normalizedSessionID,
config,
terminalInfo,
notificationRuntime,
)
}
const notifyPermissionIfNeeded = async (properties: unknown): Promise<void> => {
const dedupeKey = buildPermissionEventDedupeKey(properties)
if (
dedupeKey &&
!shouldSendDedupedNotification(
recentPermissionNotifications,
dedupeKey,
PERMISSION_DEDUPE_WINDOW_MS,
)
) {
return
}
await handlePermissionUpdated(config, terminalInfo, notificationRuntime)
}
return {
"tool.execute.before": async (input: { tool: string; sessionID: string; callID: string }) => {
if (input.tool === "question") {
await notifyQuestionIfNeeded(buildQuestionToolDedupeKey(input.sessionID, input.callID))
}
},
event: async ({ event }: { event: Event }): Promise<void> => {
const runtimeEvent = event as { type: string; properties: Record<string, unknown> }
switch (runtimeEvent.type) {
case "session.status": {
const sessionID = runtimeEvent.properties.sessionID
const statusType =
runtimeEvent.properties.status && typeof runtimeEvent.properties.status === "object"
? ((runtimeEvent.properties.status as { type?: string }).type ?? undefined)
: undefined
if (sessionID && statusType === "idle") {
await notifySessionReadyIfNeeded(sessionID)
}
break
}
case "session.idle": {
await notifySessionReadyIfNeeded(runtimeEvent.properties.sessionID)
break
}
case "session.error": {
const sessionID = toNonEmptyString(runtimeEvent.properties.sessionID)
const error = runtimeEvent.properties.error
const errorMessage = typeof error === "string" ? error : error ? String(error) : undefined
if (sessionID) {
await handleSessionError(
client as OpencodeClient,
sessionID,
errorMessage,
config,
terminalInfo,
notificationRuntime,
)
}
break
}
case "permission.updated":
case "permission.asked": {
await notifyPermissionIfNeeded(runtimeEvent.properties)
break
}
case "question.asked": {
const dedupeKey = buildQuestionEventDedupeKey(runtimeEvent.properties)
await notifyQuestionIfNeeded(dedupeKey)
break
}
}
},
}
}
export default NotifyPlugin