omni-notify-mcp 1.3.366 → 1.3.367
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.
- package/dist/agentGateway.js +296 -0
- package/dist/daemon.js +131 -0
- package/dist/gateway/chatPage.js +727 -0
- package/dist/gateway/conversations.js +792 -0
- package/dist/gateway/lanProbe.js +86 -0
- package/dist/gateway/mcpDoor.js +390 -0
- package/dist/gateway/mcpEvents.js +448 -0
- package/dist/gateway/nativeTerminalWorker.js +170 -0
- package/dist/gateway/notifyDoor.js +165 -0
- package/dist/gateway/oauthDoor.js +345 -0
- package/dist/gateway/opencodeEvents.mjs +13 -0
- package/dist/gateway/opencodeProvider.js +249 -0
- package/dist/gateway/panel.js +189 -0
- package/dist/gateway/panelPage.js +214 -0
- package/dist/gateway/providers.js +16 -0
- package/dist/gateway/publicAccess.js +374 -0
- package/dist/gateway/restDoor.js +283 -0
- package/dist/gateway/sessionDriver.js +1014 -0
- package/dist/gateway/terminalDoor.js +247 -0
- package/dist/gateway/terminalPage.js +306 -0
- package/dist/gateway/tunnel.js +166 -0
- package/dist/messaging/emailInbound.js +292 -0
- package/dist/notify.js +2846 -0
- package/dist/shared/webhost/autoSwitch.cjs +1762 -0
- package/dist/shared/webhost/bullseyeWebHost.js +1329 -0
- package/dist/shared/webhost/originHandover.js +552 -0
- package/dist/shared/webhost/package.json +1 -0
- package/dist/shared/webhost/webviewShim.js +342 -0
- package/dist/shared/webhost/workspaceList.js +633 -0
- package/package.json +1 -1
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode behind the provider seam (#3847, #3929): every turn of a conversation runs inside that conversation's OWN
|
|
3
|
+
* interactive OpenCode TUI on a pty — never a headless `opencode run` — so the browser and MCP reach ONE process. A turn
|
|
4
|
+
* is typed into it; what it took and how the turn ended are read off a log of the CLI's own bus events, which the plugin
|
|
5
|
+
* shipped beside this file (`opencodeEvents.mjs`) appends as they happen (measured on opencode 1.19.5: `session.created`
|
|
6
|
+
* with the session id, `message.updated` naming each message's role, `message.part.updated` with a user text part for a
|
|
7
|
+
* prompt taken and a text part carrying `time.end` for an assistant reply, `session.status` busy / idle / retry,
|
|
8
|
+
* `session.error`, then `session.idle` when the turn is over). Each CLI start writes a log of its own, so a log is never
|
|
9
|
+
* another CLI's and a resumed session reads only what this CLI wrote.
|
|
10
|
+
*
|
|
11
|
+
* The CLI runs on the key and store `opencodeRoute` names, chosen when its CLI opens. A key the vendor refuses — a
|
|
12
|
+
* refusing `session.error`, or the `retry` status the CLI reports while it retries a rate limit in silence — is recorded
|
|
13
|
+
* where every switcher reads it and the CLI is ended; the SAME turn then carries on in a fresh CLI that resumes the
|
|
14
|
+
* session with `-s` on a new route, which skips the refused key, told to carry on from the last message (Meni's ruling
|
|
15
|
+
* on Q808, #4079). With no key left to run on, the turn fails in the route's own words.
|
|
16
|
+
*/
|
|
17
|
+
import { randomUUID } from "crypto";
|
|
18
|
+
import { existsSync, mkdirSync, readdirSync, rmSync } from "fs";
|
|
19
|
+
import { homedir } from "os";
|
|
20
|
+
import { join } from "path";
|
|
21
|
+
import autoSwitch from "../shared/webhost/autoSwitch.cjs";
|
|
22
|
+
import { KEY_REFUSAL_STATUSES, KEY_REFUSAL_WORDS } from "../shared/agentSession.js";
|
|
23
|
+
import { CliEnded, LoggedCliSession } from "./cliSession.js";
|
|
24
|
+
import { CONFIG_DIR } from "../notify.js";
|
|
25
|
+
// GATE: the words of a retry status that mean the provider rate-limited THIS key; any other retry (a 5xx, a dropped connection) is the CLI riding out a fault the key did not cause
|
|
26
|
+
const RATE_LIMITED = /rate.?limit|too many requests/i;
|
|
27
|
+
const ROUTE_REFUSALS = new Set(["OPENCODE_NO_KEY", "KEYPLAN_UNREADABLE", "REFUSAL_UNREADABLE"]);
|
|
28
|
+
function routeOf(model, failure) {
|
|
29
|
+
try {
|
|
30
|
+
return autoSwitch.opencodeRoute(homedir(), model);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
if (!ROUTE_REFUSALS.has(err.code))
|
|
34
|
+
throw err;
|
|
35
|
+
throw failure(err.message);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** The plugin OpenCode loads in BN's CLI, shipped beside this module — in dist/gateway for a build, beside the bundled daemon in the extension. */
|
|
39
|
+
const EVENT_PLUGIN = new URL("./opencodeEvents.mjs", import.meta.url);
|
|
40
|
+
/** The folder each CLI start's own log goes in: this daemon's own config dir, so no other daemon on the machine clears a log this one is reading. */
|
|
41
|
+
const logDir = () => join(CONFIG_DIR, "opencode-logs");
|
|
42
|
+
/** The daemon starting: logs a CLI of an earlier daemon left behind belong to no CLI now. */
|
|
43
|
+
export function clearOpenCodeLogs() {
|
|
44
|
+
if (!existsSync(logDir()))
|
|
45
|
+
return;
|
|
46
|
+
for (const name of readdirSync(logDir()))
|
|
47
|
+
rmSync(join(logDir(), name), { force: true });
|
|
48
|
+
}
|
|
49
|
+
/** A string field an event must carry, or a SyntaxError naming the event: OpenCode writes every one of these as a string. */
|
|
50
|
+
function field(event, value, name) {
|
|
51
|
+
if (typeof value !== "string")
|
|
52
|
+
throw new SyntaxError(`an OpenCode ${String(event.type)} event carries no ${name}: ${JSON.stringify(event).slice(0, 200)}`);
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
/** The log of one OpenCode CLI start, read with what the prompt in flight has said so far. */
|
|
56
|
+
class OpenCodeLog {
|
|
57
|
+
file;
|
|
58
|
+
key;
|
|
59
|
+
/** The log is this CLI start's own: no other CLI writes into it. */
|
|
60
|
+
shared = false;
|
|
61
|
+
/** The session this log's turns belong to: a resumed session's own id, else the first session created without a parent. A sub-agent's session is never it. */
|
|
62
|
+
main;
|
|
63
|
+
roles = new Map();
|
|
64
|
+
taken = new Set();
|
|
65
|
+
/** The last reply text the CLI finished writing this turn. */
|
|
66
|
+
said;
|
|
67
|
+
failure;
|
|
68
|
+
constructor(file, resumedSession, key) {
|
|
69
|
+
this.file = file;
|
|
70
|
+
this.key = key;
|
|
71
|
+
this.main = resumedSession;
|
|
72
|
+
}
|
|
73
|
+
resumed() {
|
|
74
|
+
return existsSync(this.file) ? this.file : undefined;
|
|
75
|
+
}
|
|
76
|
+
finder() {
|
|
77
|
+
return { fresh: () => existsSync(this.file) ? [{ file: this.file, prompts: [] }] : [] };
|
|
78
|
+
}
|
|
79
|
+
ended() {
|
|
80
|
+
rmSync(this.file, { force: true });
|
|
81
|
+
}
|
|
82
|
+
/** The vendor refused the key this CLI runs on: it is recorded as refused, and the turn ends the CLI naming it so the session can carry the turn on the next key. */
|
|
83
|
+
refused(said) {
|
|
84
|
+
const why = `${this.key.named} was refused by the provider (${said}), so BN moves this turn on to the next key.`;
|
|
85
|
+
this.key.refuse(said);
|
|
86
|
+
return [{ kind: "failed", why, endsCli: true }];
|
|
87
|
+
}
|
|
88
|
+
read(row) {
|
|
89
|
+
const event = row;
|
|
90
|
+
const p = event.properties ?? {};
|
|
91
|
+
if (event.type === "session.created") {
|
|
92
|
+
if (p.info?.parentID !== undefined || this.main !== undefined)
|
|
93
|
+
return [{ kind: "busy" }];
|
|
94
|
+
this.main = field(event, p.info?.id, "info.id");
|
|
95
|
+
return [{ kind: "session", id: this.main }];
|
|
96
|
+
}
|
|
97
|
+
if (this.main === undefined || p.sessionID !== this.main)
|
|
98
|
+
return [{ kind: "busy" }];
|
|
99
|
+
switch (event.type) {
|
|
100
|
+
case "message.updated":
|
|
101
|
+
this.roles.set(field(event, p.info?.id, "info.id"), field(event, p.info?.role, "info.role"));
|
|
102
|
+
return [{ kind: "busy" }];
|
|
103
|
+
case "message.part.updated": {
|
|
104
|
+
if (typeof p.part !== "object" || p.part === null)
|
|
105
|
+
throw new SyntaxError(`an OpenCode message.part.updated event carries no part: ${JSON.stringify(event).slice(0, 200)}`);
|
|
106
|
+
const part = p.part;
|
|
107
|
+
if (part.type !== "text" || part.synthetic === true)
|
|
108
|
+
return [{ kind: "busy" }];
|
|
109
|
+
const message = field(event, part.messageID, "part.messageID");
|
|
110
|
+
const role = this.roles.get(message);
|
|
111
|
+
if (role === undefined)
|
|
112
|
+
throw new SyntaxError(`an OpenCode text part arrived before its message was named: ${JSON.stringify(event).slice(0, 200)}`);
|
|
113
|
+
if (role === "user") {
|
|
114
|
+
if (this.taken.has(message))
|
|
115
|
+
return [{ kind: "busy" }];
|
|
116
|
+
this.taken.add(message);
|
|
117
|
+
this.said = undefined;
|
|
118
|
+
this.failure = undefined;
|
|
119
|
+
return [{ kind: "taken", text: field(event, part.text, "part.text") }];
|
|
120
|
+
}
|
|
121
|
+
if (part.time?.end !== undefined)
|
|
122
|
+
this.said = field(event, part.text, "part.text");
|
|
123
|
+
return [{ kind: "busy" }];
|
|
124
|
+
}
|
|
125
|
+
case "session.status": {
|
|
126
|
+
const retrying = p.status?.type === "retry" ? p.status.message : undefined;
|
|
127
|
+
return typeof retrying === "string" && (RATE_LIMITED.test(retrying) || KEY_REFUSAL_WORDS.test(retrying)) ? this.refused(`rate-limited, being retried by the CLI: ${retrying}`) : [{ kind: "busy" }];
|
|
128
|
+
}
|
|
129
|
+
case "session.error": {
|
|
130
|
+
const said = field(event, p.error?.data?.message ?? p.error?.name, "error message");
|
|
131
|
+
const status = p.error?.data?.statusCode;
|
|
132
|
+
if ((typeof status === "number" && KEY_REFUSAL_STATUSES.has(status)) || KEY_REFUSAL_WORDS.test(said))
|
|
133
|
+
return this.refused(typeof status === "number" ? `${said} (HTTP ${status})` : said);
|
|
134
|
+
this.failure = `OpenCode reported: ${said}`;
|
|
135
|
+
return [{ kind: "busy" }];
|
|
136
|
+
}
|
|
137
|
+
case "permission.asked":
|
|
138
|
+
return [{ kind: "busy" }];
|
|
139
|
+
case "question.asked":
|
|
140
|
+
return [{ kind: "waiting" }];
|
|
141
|
+
case "session.idle": {
|
|
142
|
+
const [said, failure] = [this.said, this.failure];
|
|
143
|
+
[this.said, this.failure] = [undefined, undefined];
|
|
144
|
+
// NULL-OK: field failure is OPTIONAL and therefore it is ok to check for NULL
|
|
145
|
+
if (failure !== undefined)
|
|
146
|
+
return [{ kind: "failed", why: failure }];
|
|
147
|
+
// NULL-OK: field said is OPTIONAL and therefore it is ok to check for NULL
|
|
148
|
+
return said === undefined ? [{ kind: "silent" }] : [{ kind: "over", answer: said }];
|
|
149
|
+
}
|
|
150
|
+
default:
|
|
151
|
+
return [{ kind: "busy" }];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** How BN runs one OpenCode conversation's CLI: the route is read now, so a conversation with no key to run on is refused in words before any CLI starts. */
|
|
156
|
+
function opencodeCli(spec) {
|
|
157
|
+
const route = routeOf(spec.model, (message) => spec.failures.fail(message));
|
|
158
|
+
mkdirSync(logDir(), { recursive: true });
|
|
159
|
+
const file = join(logDir(), `${randomUUID()}.jsonl`);
|
|
160
|
+
const key = { named: route.named, refuse: (reason) => autoSwitch.markKeyRefused(homedir(), route.identityId, reason) };
|
|
161
|
+
return {
|
|
162
|
+
get provider() { return opencodeProvider; },
|
|
163
|
+
args: (_spec, resumes) => ["--auto", "-m", route.model, ...(resumes ? ["-s", spec.sessionId] : [])],
|
|
164
|
+
env: { ...route.env, BN_OPENCODE_LOG: file, OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugin: [EVENT_PLUGIN.href], autoupdate: false }) },
|
|
165
|
+
log: new OpenCodeLog(file, spec.started ? spec.sessionId : undefined, key),
|
|
166
|
+
refusal: () => undefined,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
const KEY_RETRY_PROMPT = "The provider refused the key your last reply was being written on, so that reply never arrived. Carry on from the last message.";
|
|
170
|
+
/**
|
|
171
|
+
* One OpenCode conversation: a LoggedCliSession on one key, and the same turn carried on to the next key when the vendor
|
|
172
|
+
* refuses that one — the refused CLI is ended and awaited, a fresh one resumes the session on a new route, and it is told
|
|
173
|
+
* to carry on (or given the original prompt when the refused CLI never wrote a session).
|
|
174
|
+
*/
|
|
175
|
+
class OpenCodeSession {
|
|
176
|
+
spec;
|
|
177
|
+
inner;
|
|
178
|
+
/** The session id the CLI wrote, or the record's own when it was already written. */
|
|
179
|
+
written;
|
|
180
|
+
carrying = false;
|
|
181
|
+
stopped = false;
|
|
182
|
+
/** The driver already heard that the CLI running now is gone, so no turn may be carried on in a CLI it no longer tracks. */
|
|
183
|
+
told = false;
|
|
184
|
+
constructor(spec) {
|
|
185
|
+
this.spec = spec;
|
|
186
|
+
this.written = spec.started ? spec.sessionId : undefined;
|
|
187
|
+
this.inner = this.launch();
|
|
188
|
+
}
|
|
189
|
+
launch() {
|
|
190
|
+
this.told = false;
|
|
191
|
+
const own = {
|
|
192
|
+
...this.spec,
|
|
193
|
+
// NULL-OK: field written is OPTIONAL and therefore it is ok to check for NULL
|
|
194
|
+
started: this.written !== undefined,
|
|
195
|
+
sessionId: this.written ?? this.spec.sessionId,
|
|
196
|
+
onGone: () => {
|
|
197
|
+
if (this.carrying)
|
|
198
|
+
return;
|
|
199
|
+
this.told = true;
|
|
200
|
+
this.spec.onGone();
|
|
201
|
+
},
|
|
202
|
+
learned: (id) => { this.written = id; this.spec.learned(id); },
|
|
203
|
+
};
|
|
204
|
+
return new LoggedCliSession(own, opencodeCli(own));
|
|
205
|
+
}
|
|
206
|
+
get pid() { return this.inner.pid; }
|
|
207
|
+
get working() { return this.inner.working; }
|
|
208
|
+
quiet() { return this.inner.quiet(); }
|
|
209
|
+
end() { this.stopped = true; return this.inner.end(); }
|
|
210
|
+
async ask(prompt, sink, timeoutMs, token) {
|
|
211
|
+
let said = prompt;
|
|
212
|
+
for (;;) {
|
|
213
|
+
try {
|
|
214
|
+
return await this.inner.ask(said, sink, timeoutMs, token);
|
|
215
|
+
}
|
|
216
|
+
catch (err) {
|
|
217
|
+
// OWNER: ITER/LOOP — a key the vendor refused already ended its CLI and is recorded; the same turn runs on the next key, and any other failure, a stop or a cancel is rethrown to the turn's caller
|
|
218
|
+
if (!(err instanceof CliEnded) || this.stopped || this.told || token.isCancellationRequested)
|
|
219
|
+
throw err;
|
|
220
|
+
sink.activity(err.message);
|
|
221
|
+
this.carrying = true;
|
|
222
|
+
try {
|
|
223
|
+
await this.inner.gone;
|
|
224
|
+
if (this.stopped)
|
|
225
|
+
throw err;
|
|
226
|
+
// NULL-OK: field written is OPTIONAL and therefore it is ok to check for NULL
|
|
227
|
+
const before = this.written !== undefined;
|
|
228
|
+
this.inner = this.launch();
|
|
229
|
+
said = before ? KEY_RETRY_PROMPT : prompt;
|
|
230
|
+
}
|
|
231
|
+
catch (failure) {
|
|
232
|
+
this.stopped = true;
|
|
233
|
+
this.spec.onGone();
|
|
234
|
+
throw failure;
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
this.carrying = false;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
export const opencodeProvider = {
|
|
244
|
+
name: "opencode",
|
|
245
|
+
label: "OpenCode",
|
|
246
|
+
command: "opencode",
|
|
247
|
+
nativeArgs: (model) => model ? ["-m", model] : [],
|
|
248
|
+
open: (spec) => new OpenCodeSession(spec),
|
|
249
|
+
};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Notify panel's logic, owned by the service (#3512): the settings the notify server reads, how a value
|
|
3
|
+
* is checked and written, the conversation On/Off switch, and the one-line state of the channels. The VS Code panel and
|
|
4
|
+
* the web page are thin clients of the routes in restDoor.ts — neither holds a copy of anything here, and neither needs
|
|
5
|
+
* a VS Code window for it.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
8
|
+
import { dirname, join } from "path";
|
|
9
|
+
import { CONFIG_DIR } from "../notify.js";
|
|
10
|
+
import { GatewayError, conversationEnabled, setConversationEnabled } from "./conversations.js";
|
|
11
|
+
const CHANNEL_KEYS = ["desktop", "telegram", "slack", "sms", "ntfy", "discord", "teams"];
|
|
12
|
+
const CONFIG_PATH = join(CONFIG_DIR, "config.json");
|
|
13
|
+
// Every config field the notify server reads, one editable row each. A field the server no longer reads is not listed: a control for it would change nothing.
|
|
14
|
+
export const SETTINGS = [
|
|
15
|
+
{ title: "🔕 Master", rows: [
|
|
16
|
+
{ path: ["muteAll"], label: "Mute everything", kind: "toggle", hint: "Master kill switch: On stops every channel at once, Off lets each enabled channel deliver." },
|
|
17
|
+
{ path: ["disabledClients"], label: "Muted clients (comma-separated ids)", kind: "list", hint: "Agent session ids whose notifications are dropped, e.g. @my-laptop-myproject-ea6d78. Leave empty to hear every agent." },
|
|
18
|
+
] },
|
|
19
|
+
{ guide: { summary: "Desktop banner", steps: ["Nothing to fill in: switch Enabled to On and notifications appear as desktop banners.", "Optional: turn Read aloud On to hear them."], need: [] }, title: "🖥️ Desktop", rows: [
|
|
20
|
+
{ path: ["desktop", "enabled"], label: "Enabled", kind: "toggle" },
|
|
21
|
+
{ path: ["desktop", "tts"], label: "Read aloud", kind: "toggle", hint: "On speaks each desktop notification out loud." },
|
|
22
|
+
{ path: ["desktop", "ttsVoice"], label: "Voice", kind: "text", hint: "Edge voice name, e.g. en-US-GuyNeural. Empty uses the default voice." },
|
|
23
|
+
] },
|
|
24
|
+
{ guide: { summary: "Create a bot (2 min)", steps: ["Open Telegram, search `@BotFather`.", "Send `/newbot` and follow the prompts; copy the token it gives you.", "From each chat or group you want notified, send your bot any message (add the bot to groups first).", "Paste the token below, then add each chat id (see the hint under Chat ids).", "Switch Enabled to On."], need: [["telegram.token"], ["telegram.chatIds"]] }, title: "✈️ Telegram", rows: [
|
|
25
|
+
{ path: ["telegram", "enabled"], label: "Enabled", kind: "toggle" },
|
|
26
|
+
{ path: ["telegram", "token"], label: "Bot token", kind: "secret", hint: "From @BotFather after /newbot, shaped like 123456:ABC-DEF..." },
|
|
27
|
+
{ path: ["telegram", "chatIds"], label: "Chat ids (comma-separated)", kind: "list", hint: "Numeric ids of the chats or groups to notify (group ids start with -). Send your bot a message, then open https://api.telegram.org/bot<TOKEN>/getUpdates and copy each \"chat\":{\"id\":...}." },
|
|
28
|
+
] },
|
|
29
|
+
{ guide: { summary: "Connect Slack", steps: ["Go to api.slack.com/apps, open your app (or Create New App).", "Easiest: Incoming Webhooks, Add New Webhook to Workspace, pick the channel, copy the URL into Webhook URL.", "Or: OAuth & Permissions, add the chat:write scope, install the app, copy the Bot User OAuth Token (xoxb-), invite the bot to the channel, and list the channel id.", "Switch Enabled to On."], need: [["slack.botToken", "slack.webhookUrl"]] }, title: "💬 Slack", rows: [
|
|
30
|
+
{ path: ["slack", "enabled"], label: "Enabled", kind: "toggle" },
|
|
31
|
+
{ path: ["slack", "botToken"], label: "Bot token", kind: "secret", hint: "Starts with xoxb-. api.slack.com/apps, your app, OAuth & Permissions, Bot User OAuth Token. Needs the chat:write scope. Use this with Channels, or use the Webhook URL instead." },
|
|
32
|
+
{ path: ["slack", "channels"], label: "Channels (comma-separated)", kind: "list", hint: "Channel ids like C0123ABCD (Slack: channel name, View channel details, bottom of the About tab). Invite the bot to each channel first." },
|
|
33
|
+
{ path: ["slack", "webhookUrl"], label: "Webhook URL", kind: "secret", hint: "Simplest option: https://hooks.slack.com/services/... from your app, Incoming Webhooks, Add New Webhook to Workspace." },
|
|
34
|
+
] },
|
|
35
|
+
{ guide: { summary: "AWS End User Messaging credentials", steps: ["AWS Console, IAM: create a user allowed `sms-voice:SendTextMessage`; copy its Access Key ID and Secret.", "AWS End User Messaging, Phone numbers, request a number; it becomes your From number.", "Paste the key, secret, region and From number below, then add recipients under Send to.", "Switch Enabled to On."], need: [["sms.accessKeyId"], ["sms.secretAccessKey"], ["sms.region"], ["sms.originationNumber"], ["sms.to"]] }, title: "📱 SMS (AWS)", rows: [
|
|
36
|
+
{ path: ["sms", "enabled"], label: "Enabled", kind: "toggle" },
|
|
37
|
+
{ path: ["sms", "accessKeyId"], label: "Access key id", kind: "text", hint: "Starts with AKIA. From the IAM user that is allowed sms-voice:SendTextMessage." },
|
|
38
|
+
{ path: ["sms", "secretAccessKey"], label: "Secret access key", kind: "secret", hint: "Shown once when the access key is created; paste it here." },
|
|
39
|
+
{ path: ["sms", "region"], label: "Region", kind: "text", hint: "The AWS region holding your number, e.g. us-east-1." },
|
|
40
|
+
{ path: ["sms", "originationNumber"], label: "From number", kind: "text", hint: "The number you requested in AWS End User Messaging, with country code, e.g. +12345678900." },
|
|
41
|
+
{ path: ["sms", "to"], label: "Send to (comma-separated)", kind: "list", hint: "Recipient phone numbers with country code, e.g. +12345678900, +12345678901." },
|
|
42
|
+
] },
|
|
43
|
+
{ guide: { summary: "Set up ntfy (1 min, free, private)", steps: ["Install the ntfy app on your phone (ntfy.sh).", "In the app tap +, then Use another server if you run your own, and enter the Server URL below.", "Pick a topic name and subscribe to it.", "Paste the same Server URL and Topic below, then switch Enabled to On."], need: [["ntfy.serverUrl"], ["ntfy.topic"]] }, title: "📣 ntfy", rows: [
|
|
44
|
+
{ path: ["ntfy", "enabled"], label: "Enabled", kind: "toggle" },
|
|
45
|
+
{ path: ["ntfy", "serverUrl"], label: "Server URL", kind: "text", hint: "The ntfy server your phone app points at, e.g. https://ntfy.sh or your own server." },
|
|
46
|
+
{ path: ["ntfy", "topic"], label: "Topic", kind: "text", hint: "Any private name, e.g. Claude_Alerts. Subscribe to the same name in the ntfy app. Whoever knows the name can read it." },
|
|
47
|
+
{ path: ["ntfy", "token"], label: "Access token", kind: "secret", hint: "Only for a protected topic or server: ntfy account, Settings, Access tokens. Leave empty otherwise." },
|
|
48
|
+
] },
|
|
49
|
+
{ guide: { summary: "Create a Discord webhook (1 min)", steps: ["Discord channel, Edit Channel, Integrations, Webhooks.", "New Webhook, then Copy Webhook URL.", "Paste it below and switch Enabled to On."], need: [["discord.webhookUrl"]] }, title: "🎮 Discord", rows: [
|
|
50
|
+
{ path: ["discord", "enabled"], label: "Enabled", kind: "toggle" },
|
|
51
|
+
{ path: ["discord", "webhookUrl"], label: "Webhook URL", kind: "secret", hint: "Discord channel, Edit Channel, Integrations, Webhooks, New Webhook, Copy Webhook URL (https://discord.com/api/webhooks/...)." },
|
|
52
|
+
{ path: ["discord", "username"], label: "Bot name", kind: "text", hint: "Optional display name on each message, e.g. Claude Notify." },
|
|
53
|
+
] },
|
|
54
|
+
{ guide: { summary: "Create a Teams webhook (2 min)", steps: ["In Teams, go to the channel, then ... , Workflows.", "Choose \"Post to a channel when a webhook request is received\".", "Follow the wizard and copy the webhook URL at the end.", "Paste it below and switch Enabled to On."], need: [["teams.webhookUrl"]] }, title: "👥 Teams", rows: [
|
|
55
|
+
{ path: ["teams", "enabled"], label: "Enabled", kind: "toggle" },
|
|
56
|
+
{ path: ["teams", "webhookUrl"], label: "Webhook URL", kind: "secret", hint: "The URL the Workflows wizard shows at its last step (https://...webhook.office.com/...)." },
|
|
57
|
+
] },
|
|
58
|
+
{ title: "🌙 Do not disturb", rows: [
|
|
59
|
+
{ path: ["dnd", "enabled"], label: "Do not disturb now", kind: "toggle", hint: "On holds every notification until you turn it Off." },
|
|
60
|
+
{ path: ["dnd", "schedule", "enabled"], label: "Quiet hours schedule", kind: "toggle", hint: "On holds notifications automatically between the times below." },
|
|
61
|
+
{ path: ["dnd", "schedule", "quietStart"], label: "Quiet from (HH:MM)", kind: "time", hint: "24-hour clock, e.g. 22:00." },
|
|
62
|
+
{ path: ["dnd", "schedule", "quietEnd"], label: "Quiet until (HH:MM)", kind: "time", hint: "24-hour clock, e.g. 07:00. An earlier time than Quiet from means the night wraps past midnight." },
|
|
63
|
+
{ path: ["dnd", "schedule", "days"], label: "Quiet on days", kind: "days", hint: "Click the days the schedule applies to." },
|
|
64
|
+
] },
|
|
65
|
+
{ title: "💤 Idle", rows: [
|
|
66
|
+
{ path: ["idle", "enabled"], label: "Hold remote channels while I am at the keyboard", kind: "toggle" },
|
|
67
|
+
{ path: ["idle", "thresholdSeconds"], label: "Away after (seconds)", kind: "number", hint: "No keyboard or mouse for this long counts as away; remote channels deliver only while away." },
|
|
68
|
+
{ path: ["idle", "alwaysDesktopWhenActive"], label: "Still show the desktop banner while I am here", kind: "toggle" },
|
|
69
|
+
] },
|
|
70
|
+
];
|
|
71
|
+
export function readConfig() {
|
|
72
|
+
return existsSync(CONFIG_PATH) ? JSON.parse(readFileSync(CONFIG_PATH, "utf8")) : {};
|
|
73
|
+
}
|
|
74
|
+
export function readAt(obj, p) {
|
|
75
|
+
return p.reduce((o, k) => (o !== null && typeof o === "object" ? o[k] : undefined), obj);
|
|
76
|
+
}
|
|
77
|
+
/** The one-line next step for a channel, decided from the same config the page shows: what is still empty, then the switch. */
|
|
78
|
+
function nextStep(group, cfg) {
|
|
79
|
+
const guide = group.guide;
|
|
80
|
+
const filled = (dotted) => {
|
|
81
|
+
const v = readAt(cfg, dotted.split("."));
|
|
82
|
+
return Array.isArray(v) ? v.length > 0 : typeof v === "string" ? v.trim() !== "" : v !== undefined && v !== null;
|
|
83
|
+
};
|
|
84
|
+
const label = (dotted) => group.rows.find((r) => r.path.join(".") === dotted).label.replace(/ \(.*\)$/, "");
|
|
85
|
+
const missing = guide.need.find((alts) => !alts.some(filled));
|
|
86
|
+
if (missing)
|
|
87
|
+
return `Next: fill in ${missing.map(label).join(" or ")}.`;
|
|
88
|
+
return readAt(cfg, [group.rows[0].path[0], "enabled"]) === true ? "Ready. Ask an agent to send a test notify to confirm it arrives." : "Next: switch Enabled to On.";
|
|
89
|
+
}
|
|
90
|
+
/** A value from the page is user input: it is checked against the row's kind here, at the boundary. */
|
|
91
|
+
function settingValue(row, value) {
|
|
92
|
+
const bad = (why) => { throw new GatewayError(400, `${row.path.join(".")}: ${why}`); };
|
|
93
|
+
switch (row.kind) {
|
|
94
|
+
case "toggle": return typeof value === "boolean" ? value : bad("expected on or off");
|
|
95
|
+
case "text":
|
|
96
|
+
case "secret": return typeof value === "string" ? value.trim() : bad("expected text");
|
|
97
|
+
case "list": return Array.isArray(value) && value.every((v) => typeof v === "string") ? value.map((v) => v.trim()).filter(Boolean) : bad("expected a list");
|
|
98
|
+
case "number": return Number.isInteger(value) && value > 0 ? value : bad("expected a whole number above 0");
|
|
99
|
+
case "time": return typeof value === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(value.trim()) ? value.trim() : bad("expected HH:MM, 00:00 to 23:59");
|
|
100
|
+
case "days": return Array.isArray(value) && value.every((d) => Number.isInteger(d) && d >= 0 && d <= 6) ? [...new Set(value)].sort() : bad("expected days 0-6");
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Writes one key of config.json as a staged file renamed over it, so the daemon never reads a half-written file, and reads it back: the write is done only when the re-read holds it. `undefined` removes the key. */
|
|
104
|
+
export function writeConfigValue(pathKeys, value) {
|
|
105
|
+
const cfg = readConfig();
|
|
106
|
+
let node = cfg;
|
|
107
|
+
for (const k of pathKeys.slice(0, -1)) {
|
|
108
|
+
if (node[k] === undefined)
|
|
109
|
+
node[k] = {};
|
|
110
|
+
node = node[k];
|
|
111
|
+
}
|
|
112
|
+
const last = pathKeys[pathKeys.length - 1];
|
|
113
|
+
if (value === undefined)
|
|
114
|
+
delete node[last];
|
|
115
|
+
else
|
|
116
|
+
node[last] = value;
|
|
117
|
+
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
|
|
118
|
+
const staged = `${CONFIG_PATH}.${process.pid}.tmp`;
|
|
119
|
+
writeFileSync(staged, JSON.stringify(cfg, null, 2));
|
|
120
|
+
renameSync(staged, CONFIG_PATH);
|
|
121
|
+
const reread = readAt(readConfig(), pathKeys);
|
|
122
|
+
if (JSON.stringify(reread) !== JSON.stringify(value))
|
|
123
|
+
throw new Error(`${pathKeys.join(".")} did not hold — wrote ${JSON.stringify(value)}, read back ${JSON.stringify(reread)}`);
|
|
124
|
+
}
|
|
125
|
+
/** One edit from the page: the path must be a row this page lists, and its value is checked against that row's kind. */
|
|
126
|
+
export function saveSetting(pathKeys, value) {
|
|
127
|
+
if (!Array.isArray(pathKeys) || !pathKeys.every((k) => typeof k === "string"))
|
|
128
|
+
throw new GatewayError(400, "path must be a list of keys");
|
|
129
|
+
const row = SETTINGS.flatMap((s) => s.rows).find((r) => r.path.join(".") === pathKeys.join("."));
|
|
130
|
+
if (!row)
|
|
131
|
+
throw new GatewayError(400, `${pathKeys.join(".")} is not a notify setting`);
|
|
132
|
+
const next = settingValue(row, value);
|
|
133
|
+
writeConfigValue(row.path, next);
|
|
134
|
+
return { path: row.path.join("."), kind: row.kind, value: next };
|
|
135
|
+
}
|
|
136
|
+
/** What the page shows is decided from the config FILE — the same source the notify server reads. */
|
|
137
|
+
function channelState(cfg, unreadable) {
|
|
138
|
+
if (unreadable !== undefined)
|
|
139
|
+
return { severity: "error", label: "Unreadable", icon: "⚠️", text: `The config file could not be read — ${unreadable}` };
|
|
140
|
+
const on = CHANNEL_KEYS.filter((key) => (readAt(cfg, [key, "enabled"])) === true);
|
|
141
|
+
if (on.length === 0)
|
|
142
|
+
return { severity: "error", label: "None enabled", icon: "⚠️", text: "No channel is enabled — every notify call reaches nobody." };
|
|
143
|
+
if (cfg?.muteAll === true)
|
|
144
|
+
return { severity: "warning", label: "Muted", icon: "🔕", text: `Master mute is ON — nothing is delivered. Enabled: ${on.join(", ")}.` };
|
|
145
|
+
return { severity: "good", label: "Enabled", icon: "🔔", text: `Enabled: ${on.join(", ")}. Whether each can carry is not measured here.` };
|
|
146
|
+
}
|
|
147
|
+
/** Everything the Settings page draws, in one reading: the channel state, every group with its rows' current values and next-step line, and the conversation switch. */
|
|
148
|
+
export function panelState() {
|
|
149
|
+
let cfg;
|
|
150
|
+
let unreadable;
|
|
151
|
+
try {
|
|
152
|
+
cfg = readConfig();
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
if (!(err instanceof SyntaxError))
|
|
156
|
+
throw err;
|
|
157
|
+
// OWNER: the page's read is this reading's trigger root — a config file that is not JSON is named in the state the page draws, and nothing is written over it.
|
|
158
|
+
unreadable = err.message;
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
state: channelState(cfg, unreadable),
|
|
162
|
+
configPath: CONFIG_PATH,
|
|
163
|
+
conversation: conversationSwitchRead(),
|
|
164
|
+
groups: unreadable !== undefined ? [] : SETTINGS.map((g) => ({
|
|
165
|
+
title: g.title,
|
|
166
|
+
guide: g.guide === undefined ? undefined : { summary: g.guide.summary, steps: g.guide.steps, next: nextStep(g, cfg) },
|
|
167
|
+
rows: g.rows.map((r) => ({ path: r.path, label: r.label, kind: r.kind, hint: r.hint, value: readAt(cfg, r.path) })),
|
|
168
|
+
})),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
/** The switch as the page and the extension read it: its value, or the reason the store cannot be read — a broken store is said, never taken for Off, and the next press of On or Off rewrites it whole. */
|
|
172
|
+
export function conversationSwitchRead() {
|
|
173
|
+
try {
|
|
174
|
+
return { enabled: conversationEnabled() };
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
if (!(err instanceof SyntaxError) && !(err instanceof TypeError))
|
|
178
|
+
throw err;
|
|
179
|
+
// OWNER: the read is made for a page or extension request, whose handler is the trigger root — a store that is not an On/Off value is answered with its reason instead of a 500, so the page that can repair it still draws.
|
|
180
|
+
return { unreadable: err.message };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** The conversation On/Off switch, flipped by the page and read back. */
|
|
184
|
+
export function saveConversationSwitch(enabled) {
|
|
185
|
+
if (typeof enabled !== "boolean")
|
|
186
|
+
throw new GatewayError(400, "expected on or off");
|
|
187
|
+
setConversationEnabled(enabled);
|
|
188
|
+
return { enabled };
|
|
189
|
+
}
|