/** * Notification output dispatchers. Each output is off by default and * fails closed when its credential or setting is missing. */ import postMessage from 'kody:@kody/discord/post-message' import { loadSettings } from '../lib/settings.ts' import type { Notification, NotificationRule } from './types.ts' import { routeWake } from '../events/wake-transport.ts' export type OutputResult = { output: string sent: boolean error?: string } /** * Dispatch a notification to Discord via @kody/discord/post-message. * Off by default. Fails closed when: * - discordNotificationsEnabled is false in settings * - discordNotificationsChannelId is empty * - The @kody/discord credential is not mapped on this package * - The post-message call throws * * Never sends a real message when the output is off. */ export async function dispatchDiscord(notification: Notification, rule: NotificationRule): Promise { if (!rule.discordEnabled) { return { output: 'discord', sent: false, error: 'Discord output is off for this project' } } const settings = await loadSettings() if (!settings.discordNotificationsEnabled) { return { output: 'discord', sent: false, error: 'discordNotificationsEnabled is false in factory settings' } } const channelId = settings.discordNotificationsChannelId?.trim() if (!channelId) { return { output: 'discord', sent: false, error: 'discordNotificationsChannelId is not set in factory settings' } } try { const content = `**[${notification.severity.toUpperCase()}]** ${notification.title}\n${notification.body}` await postMessage({ channelId, content }) return { output: 'discord', sent: true } } catch (err) { return { output: 'discord', sent: false, error: err instanceof Error ? err.message : String(err) } } } /** * Dispatch a notification as a bot wake (Patch) through `@kody/wake-relay`. * Off by default. The factory holds no wake credentials. */ export async function dispatchWake(notification: Notification, rule: NotificationRule): Promise { if (!rule.wakeEnabled) { return { output: 'wake', sent: false, error: 'Wake output is off for this project' } } try { const prompt = `Factory notification (${notification.severity}): ${notification.title}\n\n${notification.body}` const r = await routeWake({ source: 'notification', role: 'notification', bot: 'patch', prompt, reason: `factory notification (${notification.severity}): ${notification.title}`, ref: String((notification as { id?: unknown }).id ?? notification.title), }) return r.ok ? { output: 'wake', sent: true } : { output: 'wake', sent: false, error: r.detail ?? 'wake request failed' } } catch (err) { return { output: 'wake', sent: false, error: err instanceof Error ? err.message : String(err) } } }