-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
213 lines (178 loc) · 5.16 KB
/
index.js
File metadata and controls
213 lines (178 loc) · 5.16 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
import fs from "node:fs/promises";
import path from "node:path";
export const id = "opencode-host-notify-bridge";
const DEFAULT_EVENTS = new Set([
"permission.asked",
"question.asked",
"session.idle",
]);
const DEFAULT_COOLDOWN_MS = 1500;
const DEFAULT_TIMEOUT_MS = 1200;
const DEFAULT_ENDPOINTS = [
"http://host.docker.internal:8765/notify",
"http://gateway.docker.internal:8765/notify",
];
function bell() {
process.stdout.write("\x07");
}
function isProbablyContainer() {
return Boolean(
process.env.container ||
process.env.REMOTE_CONTAINERS ||
process.env.DEVCONTAINER ||
process.env.CODESPACES
);
}
function normalizeEvents(events) {
if (!Array.isArray(events)) {
return DEFAULT_EVENTS;
}
const normalized = events
.filter((event) => typeof event === "string")
.map((event) => event.trim())
.filter((event) => event.length > 0);
return normalized.length > 0 ? new Set(normalized) : DEFAULT_EVENTS;
}
function normalizeNumber(value, fallback) {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
return fallback;
}
return value;
}
function eventMessage(event) {
switch (event?.type) {
case "permission.asked":
return "OpenCode needs permission";
case "question.asked":
return "OpenCode needs your input";
case "session.idle":
return "OpenCode is waiting for you";
default:
return "OpenCode needs attention";
}
}
function configPath() {
const explicit = process.env.OPENCODE_HOST_NOTIFY_BRIDGE_CONFIG;
if (explicit) {
return explicit;
}
const home = process.env.HOME;
if (!home) {
return null;
}
return path.join(home, ".config", "opencode", "host-notify-bridge.json");
}
async function readBridgeConfig() {
const filePath = configPath();
if (!filePath) {
return {};
}
try {
const raw = await fs.readFile(filePath, "utf8");
const parsed = JSON.parse(raw);
return parsed && typeof parsed === "object" ? parsed : {};
} catch {
return {};
}
}
function normalizeEndpoints(config, options) {
if (Array.isArray(options.endpoints)) {
const values = options.endpoints.filter((value) => typeof value === "string" && value.trim().length > 0);
if (values.length > 0) {
return values;
}
}
if (typeof options.endpoint === "string" && options.endpoint.trim().length > 0) {
return [options.endpoint.trim()];
}
if (Array.isArray(config.endpoints)) {
const values = config.endpoints.filter((value) => typeof value === "string" && value.trim().length > 0);
if (values.length > 0) {
return values;
}
}
if (typeof config.endpoint === "string" && config.endpoint.trim().length > 0) {
return [config.endpoint.trim()];
}
return DEFAULT_ENDPOINTS;
}
async function postNotification(url, token, payload, timeoutMs) {
const headers = {
"content-type": "application/json",
};
if (typeof token === "string" && token.length > 0) {
headers["x-opencode-token"] = token;
}
const signal = AbortSignal.timeout(timeoutMs);
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(payload),
signal,
});
if (!response.ok) {
throw new Error(`notify bridge returned ${response.status}`);
}
}
export async function server(_input, options = {}) {
const config = await readBridgeConfig();
const enabled = typeof options.enabled === "boolean"
? options.enabled
: typeof config.enabled === "boolean"
? config.enabled
: isProbablyContainer();
const events = normalizeEvents(options.events ?? config.events);
const cooldownMs = normalizeNumber(options.cooldownMs ?? config.cooldownMs, DEFAULT_COOLDOWN_MS);
const timeoutMs = normalizeNumber(options.timeoutMs ?? config.timeoutMs, DEFAULT_TIMEOUT_MS);
const endpoints = normalizeEndpoints(config, options);
const token = typeof options.token === "string"
? options.token
: typeof config.token === "string"
? config.token
: "";
const title = typeof options.title === "string"
? options.title
: typeof config.title === "string"
? config.title
: "OpenCode";
const bellOnFailure = options.bellOnFailure !== false && config.bellOnFailure !== false;
const bellOnEveryEvent = options.bellOnEveryEvent === true || config.bellOnEveryEvent === true;
let lastBellAt = 0;
return {
event: async ({ event, sessionID }) => {
if (!enabled || !event || !events.has(event.type)) {
return;
}
const now = Date.now();
if (now - lastBellAt < cooldownMs) {
return;
}
lastBellAt = now;
if (bellOnEveryEvent) {
bell();
}
const payload = {
eventType: event.type,
title,
body: eventMessage(event),
sessionID: typeof sessionID === "string" ? sessionID : null,
timestamp: new Date(now).toISOString(),
};
for (const endpoint of endpoints) {
try {
await postNotification(endpoint, token, payload, timeoutMs);
return;
} catch {
// Try the next endpoint.
}
}
if (bellOnFailure && !bellOnEveryEvent) {
bell();
}
},
};
}
export default {
id,
server,
};