-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode-plugin.ts
More file actions
200 lines (178 loc) · 6.06 KB
/
opencode-plugin.ts
File metadata and controls
200 lines (178 loc) · 6.06 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
import type { Plugin } from "@opencode-ai/plugin"
import { readFileSync } from "fs"
import { join, basename } from "path"
import { homedir } from "os"
interface Config {
enabled: boolean
webhookUrl: string
debounceSeconds: number
}
// Module-level client ref for logging — set on plugin init
let _client: any = null
const DEBUG = process.env.SLACK_NOTIFICATIONS_DEBUG === "1" || process.env.SLACK_NOTIFICATIONS_DEBUG === "true"
function pluginLog(level: "info" | "warn" | "error", message: string) {
if (_client) {
_client.app.log({ body: { service: "slack-notifications", level, message } })
}
}
function debugLog(message: string) {
if (!DEBUG) return
// Log to stderr so it doesn't interfere with plugin protocol
console.error(`[DEBUG] ${message}`)
pluginLog("info", `[DEBUG] ${message}`)
}
function loadConfig(): Config {
const config: Config = {
enabled: false,
webhookUrl: "",
debounceSeconds: 10,
}
const configPath =
process.env.AGENT_NOTIFY_CONFIG ??
join(homedir(), ".config", "slack-notifications", "notify.yaml")
debugLog(`Loading config from: ${configPath}`)
try {
const content = readFileSync(configPath, "utf-8")
for (const line of content.split("\n")) {
if (/^\s*#/.test(line) || !line.trim()) continue
const match = line.match(/^(\w+)\s*:\s*(.+)$/)
if (!match) continue
const [, key, raw] = match
const value = raw.replace(/^['"]|['"]$/g, "").trim()
switch (key) {
case "enabled": config.enabled = value !== "false"; break
case "webhook_url": config.webhookUrl = value; break
case "debounce_seconds": config.debounceSeconds = parseInt(value, 10) || 10; break
}
}
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
pluginLog("error", `Failed to read config: ${err}`)
}
}
// Env vars override config
config.webhookUrl = process.env.SLACK_NOTIFICATIONS_WEBHOOK ?? config.webhookUrl
debugLog(`Config loaded: enabled=${config.enabled}, webhookUrl=${config.webhookUrl ? "set" : "empty"}, debounce=${config.debounceSeconds}s`)
return config
}
async function getLastAssistantMessage(client: any, sessionId: string): Promise<string> {
try {
const response = await client.session.messages({ path: { id: sessionId } })
const messages = response.data ?? response
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]
const role = msg.role ?? msg.info?.role
if (role !== "assistant") continue
const textParts = (msg.parts ?? []).filter((p: any) => p.type === "text")
if (textParts.length > 0) {
return textParts.map((p: any) => p.text ?? p.content ?? "").join("\n").trim()
}
}
} catch (err) {
pluginLog("error", `Failed to fetch session messages: ${err}`)
}
return ""
}
function truncate(text: string, max = 300): string {
return text.length > max ? text.slice(0, max) + "..." : text
}
const EVENT_ICONS: Record<string, string> = {
"session.idle": "\u2705",
"session.error": "\u274C",
"permission.asked": "\u{1F4AC}",
}
const DEFAULT_ICON = "\u{1F514}"
async function notify(title: string, event: any, client?: any) {
const config = loadConfig()
if (!config.enabled || !config.webhookUrl) {
debugLog(`notify() skipped: enabled=${config.enabled}, webhookUrl=${config.webhookUrl ? "set" : "empty"}`)
return
}
debugLog(`notify() sending: title="${title}", event.type="${event.type}"`)
try {
const project = basename(process.cwd())
const sessionId = event.properties?.sessionId ?? event.properties?.sessionID
const icon = EVENT_ICONS[event.type] ?? DEFAULT_ICON
let summary = ""
if (client && sessionId) {
const lastMessage = await getLastAssistantMessage(client, sessionId)
if (lastMessage) {
summary = truncate(lastMessage)
}
}
const blocks: any[] = [
{ type: "divider" },
{
type: "section",
fields: [
{ type: "mrkdwn", text: `${icon} *${title}*` },
{ type: "mrkdwn", text: project },
],
},
]
if (summary) {
blocks.push({
type: "section",
text: { type: "mrkdwn", text: `\`\`\`${summary}\`\`\`` }
})
}
const resp = await fetch(config.webhookUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
text: `${title}: ${project}`,
blocks,
})
})
if (!resp.ok) {
throw new Error(`Slack returned ${resp.status}: ${await resp.text()}`)
}
} catch (err) {
pluginLog("error", `Failed to send notification: ${err}`)
}
}
let debounceTimer: ReturnType<typeof setTimeout> | null = null
function cancelDebounce() {
if (debounceTimer) {
debugLog("cancelDebounce() clearing pending timer")
clearTimeout(debounceTimer)
debounceTimer = null
}
}
function debouncedNotify(title: string, event: any, client?: any) {
const config = loadConfig()
cancelDebounce()
debugLog(`debouncedNotify() queued: title="${title}", delay=${config.debounceSeconds}s`)
debounceTimer = setTimeout(() => {
debugLog(`debouncedNotify() timer fired: title="${title}"`)
debounceTimer = null
notify(title, event, client)
}, config.debounceSeconds * 1000)
}
export const SlackNotificationsPlugin: Plugin = async ({ client }) => {
_client = client
debugLog("Plugin initializing")
pluginLog("info", "Plugin initialized")
return {
event: async ({ event }) => {
switch (event.type) {
case "session.idle":
debouncedNotify("OpenCode Session Completed", event, client)
break
case "session.error":
debouncedNotify("OpenCode Error", event, client)
break
case "permission.asked":
debouncedNotify("OpenCode Needs Permission", event, client)
break
case "message.created":
// Only cancel if it's a user message (agent resuming work)
if (event.properties?.role === "user") {
debugLog("User message detected, cancelling debounce")
cancelDebounce()
}
break
}
},
}
}