@lelouchhe/webagent 0.1.9 → 0.2.1
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/README.md +45 -268
- package/dist/index.html +2 -3
- package/dist/js/app.C4WRSLDF.js +10 -0
- package/dist/{styles.01a9ju9l.css → styles.01a6wdjv.css} +30 -5
- package/package.json +5 -4
- package/dist/js/app.IXP5KGP6.js +0 -8
- package/lib/bridge.js +0 -284
- package/lib/config.js +0 -62
- package/lib/daemon.js +0 -278
- package/lib/event-handler.js +0 -104
- package/lib/push-service.js +0 -168
- package/lib/routes.js +0 -929
- package/lib/server.js +0 -72
- package/lib/session-manager.js +0 -276
- package/lib/shared/constants.js +0 -16
- package/lib/sse-manager.js +0 -80
- package/lib/store.js +0 -174
- package/lib/title-service.js +0 -71
- package/lib/types.js +0 -13
package/lib/daemon.js
DELETED
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
import { spawn } from "node:child_process";
|
|
2
|
-
import { closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
-
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
-
import { fileURLToPath } from "node:url";
|
|
5
|
-
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
6
|
-
// ---------------------------------------------------------------------------
|
|
7
|
-
// Constants
|
|
8
|
-
// ---------------------------------------------------------------------------
|
|
9
|
-
const PID_FILE = "webagent.pid";
|
|
10
|
-
const LOG_FILE = "webagent.log";
|
|
11
|
-
const RESTART_DELAY_INITIAL = 1_000;
|
|
12
|
-
const RESTART_DELAY_MAX = 30_000;
|
|
13
|
-
const STABLE_THRESHOLD_MS = 60_000;
|
|
14
|
-
const KILL_GRACE_MS = 5_000;
|
|
15
|
-
const SUBCOMMANDS = ["start", "stop", "status", "restart"];
|
|
16
|
-
/** Read and validate the PID file at `filePath`. Returns null if missing or stale. */
|
|
17
|
-
export function readPidInfo(filePath) {
|
|
18
|
-
if (!existsSync(filePath))
|
|
19
|
-
return null;
|
|
20
|
-
try {
|
|
21
|
-
const info = JSON.parse(readFileSync(filePath, "utf8"));
|
|
22
|
-
if (typeof info.pid !== "number" || !Number.isFinite(info.pid))
|
|
23
|
-
return null;
|
|
24
|
-
process.kill(info.pid, 0); // existence check — throws if dead
|
|
25
|
-
return info;
|
|
26
|
-
}
|
|
27
|
-
catch {
|
|
28
|
-
// Process is dead or file corrupt — clean up
|
|
29
|
-
try {
|
|
30
|
-
unlinkSync(filePath);
|
|
31
|
-
}
|
|
32
|
-
catch { /* ignore */ }
|
|
33
|
-
return null;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
/** Write PID info to `filePath`. */
|
|
37
|
-
export function writePidInfo(filePath, info) {
|
|
38
|
-
writeFileSync(filePath, JSON.stringify(info) + "\n");
|
|
39
|
-
}
|
|
40
|
-
// ---------------------------------------------------------------------------
|
|
41
|
-
// Arg helpers
|
|
42
|
-
// ---------------------------------------------------------------------------
|
|
43
|
-
export function isSubcommand(arg) {
|
|
44
|
-
return SUBCOMMANDS.includes(arg);
|
|
45
|
-
}
|
|
46
|
-
/** Resolve relative `--config` values to absolute paths (based on cwd). */
|
|
47
|
-
export function resolveArgs(args) {
|
|
48
|
-
const result = [...args];
|
|
49
|
-
for (let i = 0; i < result.length; i++) {
|
|
50
|
-
if (result[i] === "--config" && i + 1 < result.length && !isAbsolute(result[i + 1])) {
|
|
51
|
-
result[i + 1] = resolve(result[i + 1]);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
return result;
|
|
55
|
-
}
|
|
56
|
-
// ---------------------------------------------------------------------------
|
|
57
|
-
// Command dispatch
|
|
58
|
-
// ---------------------------------------------------------------------------
|
|
59
|
-
export async function run(command, args) {
|
|
60
|
-
const pidFile = join(process.cwd(), PID_FILE);
|
|
61
|
-
const logFile = join(process.cwd(), LOG_FILE);
|
|
62
|
-
switch (command) {
|
|
63
|
-
case "start": return cmdStart(pidFile, logFile, args);
|
|
64
|
-
case "stop": return cmdStop(pidFile);
|
|
65
|
-
case "status": return cmdStatus(pidFile, logFile);
|
|
66
|
-
case "restart": return cmdRestart(pidFile, logFile);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
// ---------------------------------------------------------------------------
|
|
70
|
-
// Commands
|
|
71
|
-
// ---------------------------------------------------------------------------
|
|
72
|
-
async function cmdStart(pidFile, logFile, args) {
|
|
73
|
-
const existing = readPidInfo(pidFile);
|
|
74
|
-
if (existing) {
|
|
75
|
-
console.log(`webagent is already running (pid ${existing.pid})`);
|
|
76
|
-
process.exitCode = 1;
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
|
-
const serverJs = join(__dirname, "server.js");
|
|
80
|
-
if (!existsSync(serverJs)) {
|
|
81
|
-
console.error(`server not found: ${serverJs}`);
|
|
82
|
-
console.error('run "npx tsc -p tsconfig.build.json" first if developing from source');
|
|
83
|
-
process.exitCode = 1;
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
86
|
-
const resolved = resolveArgs(args);
|
|
87
|
-
const daemonJs = join(__dirname, "daemon.js");
|
|
88
|
-
const log = openSync(logFile, "a");
|
|
89
|
-
const child = spawn(process.execPath, [daemonJs, "__supervisor", ...resolved], { detached: true, stdio: ["ignore", log, log], cwd: process.cwd() });
|
|
90
|
-
child.unref();
|
|
91
|
-
closeSync(log);
|
|
92
|
-
// Poll for PID file (supervisor writes it on startup)
|
|
93
|
-
for (let i = 0; i < 6; i++) {
|
|
94
|
-
await sleep(500);
|
|
95
|
-
const info = readPidInfo(pidFile);
|
|
96
|
-
if (info) {
|
|
97
|
-
console.log(`webagent started (pid ${info.pid})`);
|
|
98
|
-
console.log(`log: ${logFile}`);
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
console.error("webagent failed to start");
|
|
103
|
-
console.error(`check log: ${logFile}`);
|
|
104
|
-
process.exitCode = 1;
|
|
105
|
-
}
|
|
106
|
-
async function cmdStop(pidFile) {
|
|
107
|
-
const info = readPidInfo(pidFile);
|
|
108
|
-
if (!info) {
|
|
109
|
-
console.log("webagent is not running");
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
try {
|
|
113
|
-
process.kill(info.pid, "SIGTERM");
|
|
114
|
-
}
|
|
115
|
-
catch {
|
|
116
|
-
console.log("webagent is not running (stale pid file removed)");
|
|
117
|
-
try {
|
|
118
|
-
unlinkSync(pidFile);
|
|
119
|
-
}
|
|
120
|
-
catch { /* ignore */ }
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
// Wait for exit
|
|
124
|
-
const deadline = Date.now() + 10_000;
|
|
125
|
-
while (Date.now() < deadline) {
|
|
126
|
-
await sleep(300);
|
|
127
|
-
try {
|
|
128
|
-
process.kill(info.pid, 0);
|
|
129
|
-
}
|
|
130
|
-
catch {
|
|
131
|
-
// Gone — supervisor cleans up PID file, but be safe
|
|
132
|
-
try {
|
|
133
|
-
unlinkSync(pidFile);
|
|
134
|
-
}
|
|
135
|
-
catch { /* ignore */ }
|
|
136
|
-
console.log("webagent stopped");
|
|
137
|
-
return;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
console.error(`webagent (pid ${info.pid}) did not stop within 10s`);
|
|
141
|
-
console.error(`try: kill -9 ${info.pid}`);
|
|
142
|
-
process.exitCode = 1;
|
|
143
|
-
}
|
|
144
|
-
async function cmdStatus(pidFile, logFile) {
|
|
145
|
-
const info = readPidInfo(pidFile);
|
|
146
|
-
if (!info) {
|
|
147
|
-
console.log("webagent is not running");
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
const uptimeMs = Date.now() - new Date(info.started).getTime();
|
|
151
|
-
const h = Math.floor(uptimeMs / 3_600_000);
|
|
152
|
-
const m = Math.floor((uptimeMs % 3_600_000) / 60_000);
|
|
153
|
-
console.log(`webagent is running (pid ${info.pid})`);
|
|
154
|
-
console.log(` started: ${info.started}`);
|
|
155
|
-
console.log(` uptime: ${h}h ${m}m`);
|
|
156
|
-
console.log(` args: ${info.args.join(" ") || "(none)"}`);
|
|
157
|
-
console.log(` log: ${logFile}`);
|
|
158
|
-
}
|
|
159
|
-
async function cmdRestart(pidFile, logFile) {
|
|
160
|
-
const info = readPidInfo(pidFile);
|
|
161
|
-
if (!info) {
|
|
162
|
-
console.log("webagent is not running");
|
|
163
|
-
process.exitCode = 1;
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
if (process.platform === "win32") {
|
|
167
|
-
// No SIGHUP on Windows — fall back to stop + start (non-atomic)
|
|
168
|
-
await cmdStop(pidFile);
|
|
169
|
-
await cmdStart(pidFile, logFile, info.args);
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
// Unix: atomic restart via SIGHUP to supervisor
|
|
173
|
-
try {
|
|
174
|
-
process.kill(info.pid, "SIGHUP");
|
|
175
|
-
}
|
|
176
|
-
catch {
|
|
177
|
-
console.error(`failed to signal webagent (pid ${info.pid})`);
|
|
178
|
-
process.exitCode = 1;
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
// Wait briefly and verify
|
|
182
|
-
await sleep(2000);
|
|
183
|
-
const newInfo = readPidInfo(pidFile);
|
|
184
|
-
if (newInfo) {
|
|
185
|
-
console.log(`webagent restarted (pid ${newInfo.pid})`);
|
|
186
|
-
}
|
|
187
|
-
else {
|
|
188
|
-
console.error("webagent may have failed to restart");
|
|
189
|
-
console.error(`check log: ${logFile}`);
|
|
190
|
-
process.exitCode = 1;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
// ---------------------------------------------------------------------------
|
|
194
|
-
// Supervisor (internal — launched by `start` as a detached process)
|
|
195
|
-
// ---------------------------------------------------------------------------
|
|
196
|
-
function runSupervisor(serverArgs) {
|
|
197
|
-
const serverJs = join(__dirname, "server.js");
|
|
198
|
-
const pidFile = join(process.cwd(), PID_FILE);
|
|
199
|
-
writePidInfo(pidFile, { pid: process.pid, args: serverArgs, started: new Date().toISOString() });
|
|
200
|
-
let child = null;
|
|
201
|
-
let stopping = false;
|
|
202
|
-
let lastStart = 0;
|
|
203
|
-
let delay = RESTART_DELAY_INITIAL;
|
|
204
|
-
let timer = null;
|
|
205
|
-
function spawnServer() {
|
|
206
|
-
lastStart = Date.now();
|
|
207
|
-
child = spawn(process.execPath, [serverJs, ...serverArgs], { stdio: "inherit" });
|
|
208
|
-
child.on("exit", onChildExit);
|
|
209
|
-
}
|
|
210
|
-
function onChildExit(code, signal) {
|
|
211
|
-
child = null;
|
|
212
|
-
if (stopping)
|
|
213
|
-
return;
|
|
214
|
-
if (Date.now() - lastStart > STABLE_THRESHOLD_MS) {
|
|
215
|
-
delay = RESTART_DELAY_INITIAL;
|
|
216
|
-
}
|
|
217
|
-
else {
|
|
218
|
-
delay = Math.min(delay * 2, RESTART_DELAY_MAX);
|
|
219
|
-
}
|
|
220
|
-
console.log(`[supervisor] server exited (code=${code} signal=${signal}), restarting in ${delay}ms`);
|
|
221
|
-
timer = setTimeout(spawnServer, delay);
|
|
222
|
-
}
|
|
223
|
-
function killChild() {
|
|
224
|
-
if (timer) {
|
|
225
|
-
clearTimeout(timer);
|
|
226
|
-
timer = null;
|
|
227
|
-
}
|
|
228
|
-
return new Promise((resolve) => {
|
|
229
|
-
if (!child) {
|
|
230
|
-
resolve();
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
const c = child;
|
|
234
|
-
c.once("exit", () => resolve());
|
|
235
|
-
c.kill("SIGTERM");
|
|
236
|
-
setTimeout(() => { try {
|
|
237
|
-
c.kill("SIGKILL");
|
|
238
|
-
}
|
|
239
|
-
catch { /* ignore */ } }, KILL_GRACE_MS);
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
async function shutdown() {
|
|
243
|
-
if (stopping)
|
|
244
|
-
return;
|
|
245
|
-
stopping = true;
|
|
246
|
-
await killChild();
|
|
247
|
-
try {
|
|
248
|
-
unlinkSync(pidFile);
|
|
249
|
-
}
|
|
250
|
-
catch { /* ignore */ }
|
|
251
|
-
process.exit(0);
|
|
252
|
-
}
|
|
253
|
-
process.on("SIGTERM", () => { shutdown(); });
|
|
254
|
-
process.on("SIGINT", () => { shutdown(); });
|
|
255
|
-
if (process.platform !== "win32") {
|
|
256
|
-
process.on("SIGHUP", async () => {
|
|
257
|
-
console.log("[supervisor] SIGHUP received, restarting server");
|
|
258
|
-
delay = RESTART_DELAY_INITIAL;
|
|
259
|
-
await killChild();
|
|
260
|
-
if (!stopping)
|
|
261
|
-
spawnServer();
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
console.log(`[supervisor] started (pid ${process.pid})`);
|
|
265
|
-
spawnServer();
|
|
266
|
-
}
|
|
267
|
-
// ---------------------------------------------------------------------------
|
|
268
|
-
// Utility
|
|
269
|
-
// ---------------------------------------------------------------------------
|
|
270
|
-
function sleep(ms) {
|
|
271
|
-
return new Promise((r) => setTimeout(r, ms));
|
|
272
|
-
}
|
|
273
|
-
// ---------------------------------------------------------------------------
|
|
274
|
-
// Direct execution: node daemon.js __supervisor [server args...]
|
|
275
|
-
// ---------------------------------------------------------------------------
|
|
276
|
-
if (process.argv[2] === "__supervisor") {
|
|
277
|
-
runSupervisor(process.argv.slice(3));
|
|
278
|
-
}
|
package/lib/event-handler.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
export function handleAgentEvent(event, sessions, store, bridge, config, sseManager, pushService) {
|
|
2
|
-
if ("sessionId" in event && event.sessionId && sessions.restoringSessions.has(event.sessionId))
|
|
3
|
-
return;
|
|
4
|
-
switch (event.type) {
|
|
5
|
-
case "connected":
|
|
6
|
-
event.cancelTimeout = config.cancelTimeout;
|
|
7
|
-
break;
|
|
8
|
-
case "session_created":
|
|
9
|
-
if (event.configOptions?.length)
|
|
10
|
-
sessions.cachedConfigOptions = event.configOptions;
|
|
11
|
-
for (const opt of event.configOptions ?? []) {
|
|
12
|
-
store.updateSessionConfig(event.sessionId, opt.id, opt.currentValue);
|
|
13
|
-
}
|
|
14
|
-
break;
|
|
15
|
-
case "config_option_update":
|
|
16
|
-
if (event.configOptions?.length)
|
|
17
|
-
sessions.cachedConfigOptions = event.configOptions;
|
|
18
|
-
for (const opt of event.configOptions ?? []) {
|
|
19
|
-
store.updateSessionConfig(event.sessionId, opt.id, opt.currentValue);
|
|
20
|
-
}
|
|
21
|
-
break;
|
|
22
|
-
case "message_chunk":
|
|
23
|
-
sessions.flushThinkingBuffer(event.sessionId);
|
|
24
|
-
sessions.appendAssistant(event.sessionId, event.text);
|
|
25
|
-
break;
|
|
26
|
-
case "thought_chunk":
|
|
27
|
-
sessions.flushAssistantBuffer(event.sessionId);
|
|
28
|
-
sessions.appendThinking(event.sessionId, event.text);
|
|
29
|
-
break;
|
|
30
|
-
case "tool_call":
|
|
31
|
-
sessions.flushBuffers(event.sessionId);
|
|
32
|
-
store.saveEvent(event.sessionId, event.type, { id: event.id, title: event.title, kind: event.kind, rawInput: event.rawInput });
|
|
33
|
-
break;
|
|
34
|
-
case "tool_call_update":
|
|
35
|
-
store.saveEvent(event.sessionId, event.type, { id: event.id, status: event.status, content: event.content });
|
|
36
|
-
break;
|
|
37
|
-
case "plan":
|
|
38
|
-
sessions.flushBuffers(event.sessionId);
|
|
39
|
-
store.saveEvent(event.sessionId, event.type, { entries: event.entries });
|
|
40
|
-
break;
|
|
41
|
-
case "permission_request": {
|
|
42
|
-
sessions.flushBuffers(event.sessionId);
|
|
43
|
-
store.saveEvent(event.sessionId, event.type, {
|
|
44
|
-
requestId: event.requestId, title: event.title, options: event.options,
|
|
45
|
-
});
|
|
46
|
-
sessions.pendingPermissions.set(event.requestId, {
|
|
47
|
-
requestId: event.requestId,
|
|
48
|
-
sessionId: event.sessionId,
|
|
49
|
-
title: event.title,
|
|
50
|
-
options: event.options.map((o) => ({ optionId: o.optionId, label: o.label ?? o.name ?? o.optionId })),
|
|
51
|
-
});
|
|
52
|
-
// Auto-approve permissions in autopilot mode (allow_once only to avoid persisting across mode switches)
|
|
53
|
-
const mode = store.getSession(event.sessionId)?.mode ?? "";
|
|
54
|
-
if (mode.includes("#autopilot")) {
|
|
55
|
-
const opt = event.options.find((o) => o.kind === "allow_once");
|
|
56
|
-
if (opt) {
|
|
57
|
-
bridge.resolvePermission(event.requestId, opt.optionId);
|
|
58
|
-
sessions.pendingPermissions.delete(event.requestId);
|
|
59
|
-
const optionName = opt.label ?? opt.optionId;
|
|
60
|
-
store.saveEvent(event.sessionId, "permission_response", {
|
|
61
|
-
requestId: event.requestId, optionName, denied: false,
|
|
62
|
-
});
|
|
63
|
-
// Broadcast both so the frontend can render then collapse the permission card
|
|
64
|
-
sseManager.broadcast(event);
|
|
65
|
-
const resolvedEvent = {
|
|
66
|
-
type: "permission_resolved",
|
|
67
|
-
sessionId: event.sessionId,
|
|
68
|
-
requestId: event.requestId,
|
|
69
|
-
optionName,
|
|
70
|
-
denied: false,
|
|
71
|
-
};
|
|
72
|
-
sseManager.broadcast(resolvedEvent);
|
|
73
|
-
return;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
break;
|
|
77
|
-
}
|
|
78
|
-
case "prompt_done":
|
|
79
|
-
sessions.activePrompts.delete(event.sessionId);
|
|
80
|
-
sessions.flushBuffers(event.sessionId);
|
|
81
|
-
store.saveEvent(event.sessionId, event.type, { stopReason: event.stopReason });
|
|
82
|
-
break;
|
|
83
|
-
case "error":
|
|
84
|
-
if (event.sessionId) {
|
|
85
|
-
sessions.activePrompts.delete(event.sessionId);
|
|
86
|
-
}
|
|
87
|
-
break;
|
|
88
|
-
}
|
|
89
|
-
sseManager.broadcast(event);
|
|
90
|
-
// Push notification check (after broadcast so clients get the event first)
|
|
91
|
-
if (pushService && "sessionId" in event && event.sessionId) {
|
|
92
|
-
const session = store.getSession(event.sessionId);
|
|
93
|
-
const eventData = {};
|
|
94
|
-
if (event.type === "permission_request") {
|
|
95
|
-
eventData.description = event.title;
|
|
96
|
-
}
|
|
97
|
-
if (pushService.maybeNotify(event.sessionId, session?.title ?? null, event.type, eventData)) {
|
|
98
|
-
const notification = pushService.formatNotification(event.sessionId, session?.title ?? null, event.type, eventData);
|
|
99
|
-
pushService.sendToAll(notification).catch((err) => {
|
|
100
|
-
console.error("[push] failed to send:", err);
|
|
101
|
-
});
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
package/lib/push-service.js
DELETED
|
@@ -1,168 +0,0 @@
|
|
|
1
|
-
import webpush from "web-push";
|
|
2
|
-
import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
const VAPID_FILE = "vapid.json";
|
|
5
|
-
/** Remove a subscription after this many consecutive send failures. */
|
|
6
|
-
const MAX_CONSECUTIVE_FAILURES = 5;
|
|
7
|
-
export class PushService {
|
|
8
|
-
store;
|
|
9
|
-
vapidKeys;
|
|
10
|
-
clientVisibility = new Map(); // clientId → visible
|
|
11
|
-
clientEndpoints = new Map(); // clientId → push endpoint
|
|
12
|
-
clientSessions = new Map(); // clientId → currently viewed sessionId
|
|
13
|
-
/** endpoint → consecutive failure count (absent or 0 = healthy) */
|
|
14
|
-
failureCounts = new Map();
|
|
15
|
-
constructor(store, dataDir, vapidSubject) {
|
|
16
|
-
this.store = store;
|
|
17
|
-
this.vapidKeys = this.loadOrGenerateKeys(dataDir);
|
|
18
|
-
webpush.setVapidDetails(vapidSubject, this.vapidKeys.publicKey, this.vapidKeys.privateKey);
|
|
19
|
-
}
|
|
20
|
-
// ---------------------------------------------------------------------------
|
|
21
|
-
// VAPID keys
|
|
22
|
-
// ---------------------------------------------------------------------------
|
|
23
|
-
loadOrGenerateKeys(dataDir) {
|
|
24
|
-
const filePath = join(dataDir, VAPID_FILE);
|
|
25
|
-
if (existsSync(filePath)) {
|
|
26
|
-
chmodSync(filePath, 0o600);
|
|
27
|
-
const keys = JSON.parse(readFileSync(filePath, "utf8"));
|
|
28
|
-
console.log("[push] loaded VAPID keys");
|
|
29
|
-
return keys;
|
|
30
|
-
}
|
|
31
|
-
const keys = webpush.generateVAPIDKeys();
|
|
32
|
-
writeFileSync(filePath, JSON.stringify(keys, null, 2) + "\n", { mode: 0o600 });
|
|
33
|
-
console.log("[push] generated new VAPID keys");
|
|
34
|
-
return keys;
|
|
35
|
-
}
|
|
36
|
-
getPublicKey() {
|
|
37
|
-
return this.vapidKeys.publicKey;
|
|
38
|
-
}
|
|
39
|
-
// ---------------------------------------------------------------------------
|
|
40
|
-
// Notification formatting
|
|
41
|
-
// ---------------------------------------------------------------------------
|
|
42
|
-
formatNotification(sessionId, sessionTitle, eventType, eventData) {
|
|
43
|
-
const title = sessionTitle || "WebAgent";
|
|
44
|
-
let body;
|
|
45
|
-
switch (eventType) {
|
|
46
|
-
case "permission_request":
|
|
47
|
-
body = `⚿ ${eventData.description ?? "Permission requested"}`;
|
|
48
|
-
break;
|
|
49
|
-
case "prompt_done":
|
|
50
|
-
body = "✓ Task complete";
|
|
51
|
-
break;
|
|
52
|
-
case "bash_done": {
|
|
53
|
-
const cmd = eventData.command ?? "command";
|
|
54
|
-
const code = eventData.exitCode ?? "?";
|
|
55
|
-
body = `$ ${cmd} — exit ${code}`;
|
|
56
|
-
break;
|
|
57
|
-
}
|
|
58
|
-
default:
|
|
59
|
-
body = eventType;
|
|
60
|
-
}
|
|
61
|
-
return { title, body, data: { sessionId } };
|
|
62
|
-
}
|
|
63
|
-
// ---------------------------------------------------------------------------
|
|
64
|
-
// Client visibility tracking
|
|
65
|
-
// ---------------------------------------------------------------------------
|
|
66
|
-
setClientVisibility(clientId, visible) {
|
|
67
|
-
this.clientVisibility.set(clientId, visible);
|
|
68
|
-
}
|
|
69
|
-
setClientSession(clientId, sessionId) {
|
|
70
|
-
this.clientSessions.set(clientId, sessionId);
|
|
71
|
-
}
|
|
72
|
-
registerClient(clientId, endpoint) {
|
|
73
|
-
this.clientEndpoints.set(clientId, endpoint);
|
|
74
|
-
}
|
|
75
|
-
removeClient(clientId) {
|
|
76
|
-
this.clientVisibility.delete(clientId);
|
|
77
|
-
this.clientEndpoints.delete(clientId);
|
|
78
|
-
this.clientSessions.delete(clientId);
|
|
79
|
-
}
|
|
80
|
-
hasVisibleClient() {
|
|
81
|
-
for (const visible of this.clientVisibility.values()) {
|
|
82
|
-
if (visible)
|
|
83
|
-
return true;
|
|
84
|
-
}
|
|
85
|
-
return false;
|
|
86
|
-
}
|
|
87
|
-
/** Check if a specific endpoint has at least one visible client. */
|
|
88
|
-
isEndpointVisible(endpoint) {
|
|
89
|
-
for (const [clientId, ep] of this.clientEndpoints) {
|
|
90
|
-
if (ep === endpoint && this.clientVisibility.get(clientId))
|
|
91
|
-
return true;
|
|
92
|
-
}
|
|
93
|
-
return false;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Check if a specific endpoint has a visible client viewing the given session.
|
|
97
|
-
* A client with no session set does not suppress any session's push.
|
|
98
|
-
*/
|
|
99
|
-
isEndpointVisibleForSession(endpoint, sessionId) {
|
|
100
|
-
for (const [clientId, ep] of this.clientEndpoints) {
|
|
101
|
-
if (ep === endpoint
|
|
102
|
-
&& this.clientVisibility.get(clientId)
|
|
103
|
-
&& this.clientSessions.get(clientId) === sessionId)
|
|
104
|
-
return true;
|
|
105
|
-
}
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
108
|
-
// ---------------------------------------------------------------------------
|
|
109
|
-
// High-level: decide whether to push, and if so, send
|
|
110
|
-
// ---------------------------------------------------------------------------
|
|
111
|
-
static NOTIFIABLE = new Set(["permission_request", "prompt_done", "bash_done"]);
|
|
112
|
-
/**
|
|
113
|
-
* Check if this event should trigger a push notification.
|
|
114
|
-
* Returns true if a notification should be sent (caller should then call sendToAll).
|
|
115
|
-
* Per-subscription visibility filtering happens inside sendToAll.
|
|
116
|
-
*/
|
|
117
|
-
maybeNotify(sessionId, sessionTitle, eventType, eventData) {
|
|
118
|
-
if (!PushService.NOTIFIABLE.has(eventType))
|
|
119
|
-
return false;
|
|
120
|
-
return true;
|
|
121
|
-
}
|
|
122
|
-
// ---------------------------------------------------------------------------
|
|
123
|
-
// Send push to all subscriptions
|
|
124
|
-
// ---------------------------------------------------------------------------
|
|
125
|
-
async sendToAll(notification) {
|
|
126
|
-
const subs = this.store.getAllSubscriptions();
|
|
127
|
-
if (subs.length === 0)
|
|
128
|
-
return;
|
|
129
|
-
const payload = JSON.stringify(notification);
|
|
130
|
-
// Per-subscription visibility: skip endpoints where a visible client is viewing this session
|
|
131
|
-
const targets = subs.filter((sub) => !this.isEndpointVisibleForSession(sub.endpoint, notification.data.sessionId));
|
|
132
|
-
if (targets.length === 0)
|
|
133
|
-
return;
|
|
134
|
-
const results = await Promise.allSettled(targets.map((sub) => this.sendOne({ endpoint: sub.endpoint, keys: { auth: sub.auth, p256dh: sub.p256dh } }, payload)));
|
|
135
|
-
for (let i = 0; i < results.length; i++) {
|
|
136
|
-
const result = results[i];
|
|
137
|
-
const endpoint = targets[i].endpoint;
|
|
138
|
-
if (result.status === "fulfilled") {
|
|
139
|
-
this.failureCounts.delete(endpoint);
|
|
140
|
-
}
|
|
141
|
-
else {
|
|
142
|
-
const err = result.reason;
|
|
143
|
-
if (err.statusCode === 410) {
|
|
144
|
-
// Subscription expired — clean up immediately
|
|
145
|
-
this.store.removeSubscription(endpoint);
|
|
146
|
-
this.failureCounts.delete(endpoint);
|
|
147
|
-
console.log(`[push] removed expired subscription (410): ${endpoint.slice(0, 60)}…`);
|
|
148
|
-
}
|
|
149
|
-
else {
|
|
150
|
-
const count = (this.failureCounts.get(endpoint) ?? 0) + 1;
|
|
151
|
-
if (count >= MAX_CONSECUTIVE_FAILURES) {
|
|
152
|
-
this.store.removeSubscription(endpoint);
|
|
153
|
-
this.failureCounts.delete(endpoint);
|
|
154
|
-
console.log(`[push] removed subscription after ${count} consecutive failures: ${endpoint.slice(0, 60)}…`);
|
|
155
|
-
}
|
|
156
|
-
else {
|
|
157
|
-
this.failureCounts.set(endpoint, count);
|
|
158
|
-
console.error(`[push] send failed (${count}/${MAX_CONSECUTIVE_FAILURES}) for ${endpoint.slice(0, 60)}…:`, result.reason);
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
/** Send a single push notification. Extracted for testability. */
|
|
165
|
-
sendOne(sub, payload) {
|
|
166
|
-
return webpush.sendNotification(sub, payload);
|
|
167
|
-
}
|
|
168
|
-
}
|