@makooo/dsh-session-notifier 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +70 -2
- package/client.js +1074 -0
- package/cordis.patch.yml +25 -0
- package/icon.svg +5 -0
- package/index.js +601 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +59 -4
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# dsh-session-notifier: session status notifications via browser system notifications.
|
|
2
|
+
# Host half applies the policy (switches, quiet hours, dedupe, sub-agent
|
|
3
|
+
# classification); the Client half composes text, plays the tone and raises the
|
|
4
|
+
# system notification. Every field here is also editable from the bell panel.
|
|
5
|
+
- insert:
|
|
6
|
+
- id: dsh-session-notifier
|
|
7
|
+
name: '@makooo/dsh-session-notifier'
|
|
8
|
+
config:
|
|
9
|
+
enabled: true
|
|
10
|
+
notifyAssistant: true
|
|
11
|
+
notifyTurn: true
|
|
12
|
+
notifySessionDone: true
|
|
13
|
+
notifyApproval: true
|
|
14
|
+
notifyQuestion: true
|
|
15
|
+
notifyError: true
|
|
16
|
+
notifySubagent: false
|
|
17
|
+
notifyIdle: false
|
|
18
|
+
sound: true
|
|
19
|
+
summary: true
|
|
20
|
+
quietHours: false
|
|
21
|
+
quietStart: '22:00'
|
|
22
|
+
quietEnd: '08:00'
|
|
23
|
+
notifyOnlyWhenHidden: true
|
|
24
|
+
dedupeWindowMs: 5000
|
|
25
|
+
maxBodyChars: 96
|
package/icon.svg
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
|
|
2
|
+
<path d="M18 4c-6.1 0-11 4.9-11 11v8.2c0 .7-.2 1.4-.7 2L4.5 27.5c-.7.9-.1 2.2 1 2.2h25c1.2 0 1.7-1.4 1-2.2l-1.8-2.3c-.5-.6-.7-1.3-.7-2V15c0-6.1-4.9-11-11-11z" fill="none" stroke="#5b8def" stroke-width="2" stroke-linejoin="round"/>
|
|
3
|
+
<path d="M14.5 30.5c.6 1.6 2 2.5 3.5 2.5s2.9-.9 3.5-2.5" fill="none" stroke="#5b8def" stroke-width="2" stroke-linecap="round"/>
|
|
4
|
+
<circle cx="18" cy="15" r="3.5" fill="#5b8def"/>
|
|
5
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of @makooo/dsh-session-notifier.
|
|
3
|
+
*
|
|
4
|
+
* Observes durable session events, applies the notification policy (per-kind
|
|
5
|
+
* switches, quiet hours, dedupe windows, sub-agent classification), and queues
|
|
6
|
+
* structured notices for the Client half, which composes the text, plays the
|
|
7
|
+
* sound and raises the system notification.
|
|
8
|
+
*
|
|
9
|
+
* The Host never depends on the page being focused: the queue survives hidden
|
|
10
|
+
* tabs, minimized windows and tab switches.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const CHANNEL = '/dsh-session-notifier';
|
|
14
|
+
const MAX_EVENTS = 200;
|
|
15
|
+
|
|
16
|
+
const DEFAULTS = Object.freeze({
|
|
17
|
+
enabled: true,
|
|
18
|
+
notifyAssistant: true,
|
|
19
|
+
notifyTurn: true,
|
|
20
|
+
notifySessionDone: true,
|
|
21
|
+
notifyApproval: true,
|
|
22
|
+
notifyQuestion: true,
|
|
23
|
+
notifyError: true,
|
|
24
|
+
notifySubagent: false,
|
|
25
|
+
notifyIdle: false,
|
|
26
|
+
sound: true,
|
|
27
|
+
summary: true,
|
|
28
|
+
quietHours: false,
|
|
29
|
+
quietStart: '22:00',
|
|
30
|
+
quietEnd: '08:00',
|
|
31
|
+
notifyOnlyWhenHidden: true,
|
|
32
|
+
dedupeWindowMs: 5000,
|
|
33
|
+
maxBodyChars: 96,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/** Booleans the settings panel may toggle. */
|
|
37
|
+
const BOOLEAN_KEYS = Object.freeze([
|
|
38
|
+
'enabled',
|
|
39
|
+
'notifyAssistant',
|
|
40
|
+
'notifyTurn',
|
|
41
|
+
'notifySessionDone',
|
|
42
|
+
'notifyApproval',
|
|
43
|
+
'notifyQuestion',
|
|
44
|
+
'notifyError',
|
|
45
|
+
'notifySubagent',
|
|
46
|
+
'notifyIdle',
|
|
47
|
+
'sound',
|
|
48
|
+
'summary',
|
|
49
|
+
'quietHours',
|
|
50
|
+
'notifyOnlyWhenHidden',
|
|
51
|
+
]);
|
|
52
|
+
|
|
53
|
+
const STRING_KEYS = Object.freeze(['quietStart', 'quietEnd']);
|
|
54
|
+
|
|
55
|
+
const LIMITS = Object.freeze({
|
|
56
|
+
dedupeWindowMs: { min: 0, max: 60000 },
|
|
57
|
+
maxBodyChars: { min: 20, max: 400 },
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/** Legacy field names accepted on read so an older patch row keeps working. */
|
|
61
|
+
const ALIASES = Object.freeze({ notifyTurnEnd: 'notifyTurn' });
|
|
62
|
+
|
|
63
|
+
/** Blocking notices ask the user to act; they are never suppressed by quiet hours. */
|
|
64
|
+
const BLOCKING_KINDS = Object.freeze(['approval', 'question']);
|
|
65
|
+
|
|
66
|
+
function textOf(content) {
|
|
67
|
+
if (typeof content === 'string') return content;
|
|
68
|
+
if (!Array.isArray(content)) return '';
|
|
69
|
+
return content
|
|
70
|
+
.filter((block) => block && (block.type === 'text' || typeof block.text === 'string'))
|
|
71
|
+
.map((block) => String(block.text ?? ''))
|
|
72
|
+
.join('\n')
|
|
73
|
+
.trim();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function truncate(input, limit) {
|
|
77
|
+
const text = String(input ?? '').replace(/\s+/g, ' ').trim();
|
|
78
|
+
const max = Number(limit) > 0 ? Number(limit) : 96;
|
|
79
|
+
if (!text) return '';
|
|
80
|
+
// Truncate by code point so a surrogate pair is never split.
|
|
81
|
+
const points = Array.from(text);
|
|
82
|
+
return points.length > max ? `${points.slice(0, Math.max(1, max - 1)).join('')}…` : text;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function plainReason(reason) {
|
|
86
|
+
if (reason === undefined || reason === null) return '';
|
|
87
|
+
if (typeof reason === 'string') return reason;
|
|
88
|
+
if (typeof reason === 'object') {
|
|
89
|
+
if (typeof reason.kind === 'string') return reason.kind;
|
|
90
|
+
if (typeof reason.reason === 'string') return reason.reason;
|
|
91
|
+
}
|
|
92
|
+
return String(reason);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Coerce one raw settings value onto the declared default's type. */
|
|
96
|
+
function coerceValue(key, raw, current) {
|
|
97
|
+
const fallback = current;
|
|
98
|
+
if (typeof fallback === 'boolean') {
|
|
99
|
+
if (typeof raw === 'boolean') return raw;
|
|
100
|
+
if (raw === 'true') return true;
|
|
101
|
+
if (raw === 'false') return false;
|
|
102
|
+
return fallback;
|
|
103
|
+
}
|
|
104
|
+
if (typeof fallback === 'string') {
|
|
105
|
+
return typeof raw === 'string' ? raw.slice(0, 32) : fallback;
|
|
106
|
+
}
|
|
107
|
+
const limit = LIMITS[key];
|
|
108
|
+
const number = typeof raw === 'number' ? raw : Number(raw);
|
|
109
|
+
if (!Number.isFinite(number)) return fallback;
|
|
110
|
+
const minimum = limit ? limit.min : 0;
|
|
111
|
+
const maximum = limit ? limit.max : Number.MAX_SAFE_INTEGER;
|
|
112
|
+
return Math.min(maximum, Math.max(minimum, Math.round(number)));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** `HH:MM` -> minute of day, or undefined for a value we should ignore. */
|
|
116
|
+
function parseClockMinutes(value) {
|
|
117
|
+
if (typeof value !== 'string') return undefined;
|
|
118
|
+
const match = /^(\d{1,2}):(\d{2})/u.exec(value.trim());
|
|
119
|
+
if (match === null) return undefined;
|
|
120
|
+
const hour = Number(match[1]);
|
|
121
|
+
const minute = Number(match[2]);
|
|
122
|
+
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return undefined;
|
|
123
|
+
return hour * 60 + minute;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Whether the current wall clock falls inside the (possibly overnight) window. */
|
|
127
|
+
function quietHoursActive(nowMinutes, startMinutes, endMinutes) {
|
|
128
|
+
if (startMinutes === endMinutes) return false;
|
|
129
|
+
if (startMinutes < endMinutes) return nowMinutes >= startMinutes && nowMinutes < endMinutes;
|
|
130
|
+
return nowMinutes >= startMinutes || nowMinutes < endMinutes;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function priorityOf(kind) {
|
|
134
|
+
return BLOCKING_KINDS.includes(kind) ? 'blocking' : 'info';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function apply(ctx, rawConfig) {
|
|
138
|
+
const raw = rawConfig && typeof rawConfig === 'object' ? rawConfig : {};
|
|
139
|
+
const initial = { ...DEFAULTS };
|
|
140
|
+
for (const [alias, key] of Object.entries(ALIASES)) {
|
|
141
|
+
if (raw[alias] !== undefined && raw[key] === undefined) initial[key] = coerceValue(key, raw[alias], initial[key]);
|
|
142
|
+
}
|
|
143
|
+
for (const key of [...BOOLEAN_KEYS, ...STRING_KEYS, ...Object.keys(LIMITS)]) {
|
|
144
|
+
if (raw[key] !== undefined) initial[key] = coerceValue(key, raw[key], initial[key]);
|
|
145
|
+
}
|
|
146
|
+
const config = initial;
|
|
147
|
+
|
|
148
|
+
const events = [];
|
|
149
|
+
/** kind+session -> last emission time, for the generic dedupe window. */
|
|
150
|
+
const seen = new Map();
|
|
151
|
+
/** per-session last turn notice, so a reply plus its turn end stay one notice. */
|
|
152
|
+
const repliedSessions = new Map();
|
|
153
|
+
/** sessionId -> { label, subagent }, retained after the row disappears. */
|
|
154
|
+
const sessionFacts = new Map();
|
|
155
|
+
let seq = 0;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Persist one settings patch into the bundle row so the choice survives a
|
|
159
|
+
* reload. The editor refuses when a higher layer overrides the row, so the
|
|
160
|
+
* in-memory value still applies for this process.
|
|
161
|
+
*/
|
|
162
|
+
const persist = async (patch) => {
|
|
163
|
+
const entry = ctx.fiber && ctx.fiber.entry;
|
|
164
|
+
const editor = ctx.get('configEditor');
|
|
165
|
+
if (entry === undefined || entry === null || !editor || typeof editor.edit !== 'function') return false;
|
|
166
|
+
try {
|
|
167
|
+
await editor.edit(entry, (current) => ({ ...(current || {}), ...patch }));
|
|
168
|
+
return true;
|
|
169
|
+
} catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
const titleOf = (session) => {
|
|
175
|
+
try {
|
|
176
|
+
const service = ctx.get('sessionTitle');
|
|
177
|
+
const snapshot = service && typeof service.get === 'function' ? service.get(session) : undefined;
|
|
178
|
+
if (snapshot && typeof snapshot.title === 'string' && snapshot.title) return snapshot.title;
|
|
179
|
+
} catch {
|
|
180
|
+
/* title is cosmetic; never block a notification for it */
|
|
181
|
+
}
|
|
182
|
+
const id = session && typeof session.id === 'string' ? session.id : '';
|
|
183
|
+
return id ? `会话 ${id.slice(0, 8)}` : 'DSH 会话';
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/** Remember the label and sub-agent classification of one session. */
|
|
187
|
+
const remember = (session) => {
|
|
188
|
+
if (!session || typeof session.id !== 'string') return;
|
|
189
|
+
const label = titleOf(session);
|
|
190
|
+
const subagent = Boolean(session.header && session.header.origin === 'subagent');
|
|
191
|
+
sessionFacts.set(session.id, { label, subagent });
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const labelOf = (sessionId) => {
|
|
195
|
+
const facts = sessionFacts.get(sessionId);
|
|
196
|
+
if (facts) return facts.label;
|
|
197
|
+
return sessionId ? `会话 ${String(sessionId).slice(0, 8)}` : 'DSH 会话';
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
const isSubagent = (sessionId) => sessionFacts.get(sessionId)?.subagent === true;
|
|
201
|
+
|
|
202
|
+
/** Whether the current local time is inside a configured quiet window. */
|
|
203
|
+
const quietNow = (kind) => {
|
|
204
|
+
if (!config.quietHours) return false;
|
|
205
|
+
if (BLOCKING_KINDS.includes(kind) || kind === 'error') return false;
|
|
206
|
+
const start = parseClockMinutes(config.quietStart);
|
|
207
|
+
const end = parseClockMinutes(config.quietEnd);
|
|
208
|
+
if (start === undefined || end === undefined) return false;
|
|
209
|
+
const now = new Date();
|
|
210
|
+
return quietHoursActive(now.getHours() * 60 + now.getMinutes(), start, end);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/** Which per-event switch governs one kind. Sub-agent runs follow their own switch. */
|
|
214
|
+
const kindEnabled = (kind, sessionId) => {
|
|
215
|
+
if (config.enabled !== true) return false;
|
|
216
|
+
if (kind !== 'subagent' && isSubagent(sessionId)) return config.notifySubagent === true;
|
|
217
|
+
switch (kind) {
|
|
218
|
+
case 'assistant': return config.notifyAssistant === true;
|
|
219
|
+
case 'turn': return config.notifyTurn === true;
|
|
220
|
+
case 'sessionDone': return config.notifySessionDone === true;
|
|
221
|
+
case 'approval': return config.notifyApproval === true;
|
|
222
|
+
case 'question': return config.notifyQuestion === true;
|
|
223
|
+
case 'error': return config.notifyError === true;
|
|
224
|
+
case 'subagent': return config.notifySubagent === true;
|
|
225
|
+
case 'idle': return config.notifyIdle === true;
|
|
226
|
+
default: return false;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const enqueue = (notice) => {
|
|
231
|
+
const sessionId = String(notice.sessionId ?? '');
|
|
232
|
+
let kind = String(notice.kind ?? 'info');
|
|
233
|
+
if (kind !== 'subagent' && sessionId && isSubagent(sessionId)) kind = 'subagent';
|
|
234
|
+
if (!kindEnabled(kind, sessionId)) return;
|
|
235
|
+
if (quietNow(kind)) return;
|
|
236
|
+
|
|
237
|
+
const now = Date.now();
|
|
238
|
+
const dedupeKey = notice.dedupeKey || `${kind}:${sessionId}`;
|
|
239
|
+
const previous = seen.get(dedupeKey);
|
|
240
|
+
if (typeof previous === 'number' && now - previous < Number(config.dedupeWindowMs || 0)) return;
|
|
241
|
+
seen.set(dedupeKey, now);
|
|
242
|
+
if (seen.size > 500) {
|
|
243
|
+
for (const [key, at] of seen) if (now - at > 60000) seen.delete(key);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const priority = priorityOf(kind);
|
|
247
|
+
events.push({
|
|
248
|
+
id: ++seq,
|
|
249
|
+
kind,
|
|
250
|
+
priority,
|
|
251
|
+
sessionId,
|
|
252
|
+
label: truncate(notice.label || labelOf(sessionId), 80),
|
|
253
|
+
// Raw facts; the Client composes the localized text so one language
|
|
254
|
+
// decision lives in one place.
|
|
255
|
+
detail: notice.detail === undefined ? null : notice.detail,
|
|
256
|
+
at: now,
|
|
257
|
+
});
|
|
258
|
+
if (events.length > MAX_EVENTS) events.splice(0, events.length - MAX_EVENTS);
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// Durable events fire after commit; this is the notification source of truth.
|
|
262
|
+
ctx.on('session/event', (session, event) => {
|
|
263
|
+
if (!event || typeof event.type !== 'string') return;
|
|
264
|
+
const sessionId = session && typeof session.id === 'string' ? session.id : '';
|
|
265
|
+
remember(session);
|
|
266
|
+
|
|
267
|
+
switch (event.type) {
|
|
268
|
+
case 'assistant/message': {
|
|
269
|
+
const data = event.data || {};
|
|
270
|
+
if (data.interrupted === true) return;
|
|
271
|
+
const body = textOf(data.message && data.message.content);
|
|
272
|
+
if (!body) return;
|
|
273
|
+
// The closing summary of the same turn would otherwise raise a second
|
|
274
|
+
// notification for one reply.
|
|
275
|
+
repliedSessions.set(sessionId, Date.now());
|
|
276
|
+
enqueue({ kind: 'assistant', sessionId, label: titleOf(session), detail: { text: body } });
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
case 'turn/end': {
|
|
280
|
+
const reason = plainReason(event.data && event.data.reason);
|
|
281
|
+
if (reason === 'error') {
|
|
282
|
+
enqueue({ kind: 'error', sessionId, label: titleOf(session), detail: { text: 'turn-error' } });
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const repliedAt = repliedSessions.get(sessionId);
|
|
286
|
+
if (reason === 'completed' && typeof repliedAt === 'number' && Date.now() - repliedAt < 6000) {
|
|
287
|
+
repliedSessions.delete(sessionId);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
enqueue({
|
|
291
|
+
kind: 'turn',
|
|
292
|
+
sessionId,
|
|
293
|
+
label: titleOf(session),
|
|
294
|
+
detail: { reason },
|
|
295
|
+
dedupeKey: `turn:${sessionId}`,
|
|
296
|
+
});
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
case 'tool/call': {
|
|
300
|
+
const data = event.data || {};
|
|
301
|
+
if (data.name !== 'ask_user_question' && data.name !== 'dsh-user-questions/ask') return;
|
|
302
|
+
enqueue({
|
|
303
|
+
kind: 'question',
|
|
304
|
+
sessionId,
|
|
305
|
+
label: titleOf(session),
|
|
306
|
+
detail: { question: '' },
|
|
307
|
+
dedupeKey: `question:${sessionId}:${String(data.callId ?? '')}`,
|
|
308
|
+
});
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
default:
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
ctx.on('session/created', (session) => {
|
|
317
|
+
remember(session);
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
// Waterfall taps: observe only, always delegate. Never claim the decision.
|
|
321
|
+
ctx.on('approval/request', (request, next) => {
|
|
322
|
+
try {
|
|
323
|
+
if (request && request.agent) {
|
|
324
|
+
const session = request.agent.session;
|
|
325
|
+
remember(session);
|
|
326
|
+
enqueue({
|
|
327
|
+
kind: 'approval',
|
|
328
|
+
sessionId: session && typeof session.id === 'string' ? session.id : '',
|
|
329
|
+
label: titleOf(session),
|
|
330
|
+
detail: {
|
|
331
|
+
toolName: typeof request.toolName === 'string' ? request.toolName : '',
|
|
332
|
+
reason: typeof request.reason === 'string' ? request.reason : '',
|
|
333
|
+
displayReason: request.displayReason ?? null,
|
|
334
|
+
},
|
|
335
|
+
// Same request never notifies twice; different requests each do.
|
|
336
|
+
dedupeKey: `approval:${String(request.callId ?? '')}:${String(request.toolName ?? '')}`,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
} catch {
|
|
340
|
+
/* containment: notification must never affect approval dispatch */
|
|
341
|
+
}
|
|
342
|
+
return next();
|
|
343
|
+
}, { global: true, prepend: true });
|
|
344
|
+
|
|
345
|
+
ctx.on('user-questions/request', (request, next) => {
|
|
346
|
+
try {
|
|
347
|
+
if (request) {
|
|
348
|
+
const session = request.agent && request.agent.session;
|
|
349
|
+
if (session) remember(session);
|
|
350
|
+
const first = Array.isArray(request.questions) && request.questions[0] ? request.questions[0] : undefined;
|
|
351
|
+
enqueue({
|
|
352
|
+
kind: 'question',
|
|
353
|
+
sessionId: session && typeof session.id === 'string' ? session.id : '',
|
|
354
|
+
label: titleOf(session),
|
|
355
|
+
detail: {
|
|
356
|
+
question: typeof first?.question === 'string' ? first.question : '',
|
|
357
|
+
header: typeof first?.header === 'string' ? first.header : '',
|
|
358
|
+
planReview: first?.intent === 'plan-review',
|
|
359
|
+
},
|
|
360
|
+
dedupeKey: `question:${String(request.wait?.callId ?? '')}:${String(first?.id ?? '')}`,
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
} catch {
|
|
364
|
+
/* containment */
|
|
365
|
+
}
|
|
366
|
+
return next();
|
|
367
|
+
}, { global: true, prepend: true });
|
|
368
|
+
|
|
369
|
+
ctx.on('subagent/end', (info) => {
|
|
370
|
+
try {
|
|
371
|
+
const parent = info && typeof info.parentSessionId === 'string' ? info.parentSessionId : '';
|
|
372
|
+
const stop = info && info.stopReason;
|
|
373
|
+
enqueue({
|
|
374
|
+
kind: 'subagent',
|
|
375
|
+
sessionId: info && typeof info.id === 'string' ? info.id : '',
|
|
376
|
+
label: labelOf(info && typeof info.id === 'string' ? info.id : parent),
|
|
377
|
+
detail: { parentSessionId: parent, stopReason: plainReason(stop) },
|
|
378
|
+
dedupeKey: `subagent:${String(info?.runId ?? info?.id ?? '')}`,
|
|
379
|
+
});
|
|
380
|
+
} catch {
|
|
381
|
+
/* containment */
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
ctx.on('api-session/error', (sessionId, message) => {
|
|
386
|
+
const id = String(sessionId ?? '');
|
|
387
|
+
const text = truncate(message, 200);
|
|
388
|
+
enqueue({
|
|
389
|
+
kind: 'error',
|
|
390
|
+
sessionId: id,
|
|
391
|
+
label: labelOf(id),
|
|
392
|
+
detail: { text },
|
|
393
|
+
// Different errors in the same window each notify; repeats do not.
|
|
394
|
+
dedupeKey: `error:${id}:${text.slice(0, 96)}`,
|
|
395
|
+
});
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
ctx.on('api-session/status', (sessionId, running) => {
|
|
399
|
+
if (running !== false) return;
|
|
400
|
+
const id = String(sessionId ?? '');
|
|
401
|
+
enqueue({ kind: 'idle', sessionId: id, label: labelOf(id), detail: null });
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
// A session leaving the live registry has finished its work.
|
|
405
|
+
ctx.on('api-session/removed', (sessionId) => {
|
|
406
|
+
const id = String(sessionId ?? '');
|
|
407
|
+
enqueue({
|
|
408
|
+
kind: 'sessionDone',
|
|
409
|
+
sessionId: id,
|
|
410
|
+
label: labelOf(id),
|
|
411
|
+
detail: null,
|
|
412
|
+
dedupeKey: `sessionDone:${id}`,
|
|
413
|
+
});
|
|
414
|
+
sessionFacts.delete(id);
|
|
415
|
+
repliedSessions.delete(id);
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
// HTTP carriers: the page can be hidden and still receive frames.
|
|
419
|
+
ctx.inject(['connection', 'webServer'], (raw) => {
|
|
420
|
+
const scope = raw;
|
|
421
|
+
/** Open SSE pages, so a settings write reaches every tab. */
|
|
422
|
+
const settingsClients = new Set();
|
|
423
|
+
|
|
424
|
+
const send = (res, item) => {
|
|
425
|
+
try {
|
|
426
|
+
res.write(`data: ${JSON.stringify(item)}\n\n`);
|
|
427
|
+
} catch {
|
|
428
|
+
/* a closed socket is handled by the close listeners */
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
const serveEvents = (res, req) => {
|
|
433
|
+
res.writeHead(200, {
|
|
434
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
435
|
+
'cache-control': 'no-cache, no-transform',
|
|
436
|
+
connection: 'keep-alive',
|
|
437
|
+
'x-accel-buffering': 'no',
|
|
438
|
+
});
|
|
439
|
+
send(res, {
|
|
440
|
+
type: 'hello',
|
|
441
|
+
notifyOnlyWhenHidden: config.notifyOnlyWhenHidden === true,
|
|
442
|
+
sound: config.sound === true,
|
|
443
|
+
summary: config.summary === true,
|
|
444
|
+
now: Date.now(),
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
const client = { cursor: seq, res };
|
|
448
|
+
settingsClients.add(client);
|
|
449
|
+
|
|
450
|
+
const tick = () => {
|
|
451
|
+
if (client.cursor < seq) {
|
|
452
|
+
for (const item of events) {
|
|
453
|
+
if (item.id <= client.cursor) continue;
|
|
454
|
+
client.cursor = item.id;
|
|
455
|
+
send(res, item);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
try {
|
|
459
|
+
res.write(': ping\n\n');
|
|
460
|
+
} catch {
|
|
461
|
+
/* ignore */
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
const timer = setInterval(tick, 300);
|
|
465
|
+
let closed = false;
|
|
466
|
+
const cleanup = () => {
|
|
467
|
+
if (closed) return;
|
|
468
|
+
closed = true;
|
|
469
|
+
clearInterval(timer);
|
|
470
|
+
settingsClients.delete(client);
|
|
471
|
+
};
|
|
472
|
+
req.on('close', cleanup);
|
|
473
|
+
res.on('close', cleanup);
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
const settingsView = () => ({
|
|
477
|
+
config: {
|
|
478
|
+
enabled: config.enabled === true,
|
|
479
|
+
notifyAssistant: config.notifyAssistant === true,
|
|
480
|
+
notifyTurn: config.notifyTurn === true,
|
|
481
|
+
notifySessionDone: config.notifySessionDone === true,
|
|
482
|
+
notifyApproval: config.notifyApproval === true,
|
|
483
|
+
notifyQuestion: config.notifyQuestion === true,
|
|
484
|
+
notifyError: config.notifyError === true,
|
|
485
|
+
notifySubagent: config.notifySubagent === true,
|
|
486
|
+
notifyIdle: config.notifyIdle === true,
|
|
487
|
+
sound: config.sound === true,
|
|
488
|
+
summary: config.summary === true,
|
|
489
|
+
quietHours: config.quietHours === true,
|
|
490
|
+
quietStart: String(config.quietStart),
|
|
491
|
+
quietEnd: String(config.quietEnd),
|
|
492
|
+
notifyOnlyWhenHidden: config.notifyOnlyWhenHidden === true,
|
|
493
|
+
dedupeWindowMs: Number(config.dedupeWindowMs) || 0,
|
|
494
|
+
maxBodyChars: Number(config.maxBodyChars) || 96,
|
|
495
|
+
},
|
|
496
|
+
bounds: LIMITS,
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
const readJson = async (req) => {
|
|
500
|
+
const chunks = [];
|
|
501
|
+
let size = 0;
|
|
502
|
+
for await (const chunk of req) {
|
|
503
|
+
const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
|
|
504
|
+
size += buffer.length;
|
|
505
|
+
if (size > 65536) throw new Error('settings payload too large');
|
|
506
|
+
chunks.push(buffer);
|
|
507
|
+
}
|
|
508
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
const replyJson = (res, status, value) => {
|
|
512
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
|
|
513
|
+
res.end(JSON.stringify(value));
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
const handler = async (req, res) => {
|
|
517
|
+
let rejection;
|
|
518
|
+
try {
|
|
519
|
+
rejection = scope.connection.requestRejection(req);
|
|
520
|
+
} catch {
|
|
521
|
+
rejection = undefined;
|
|
522
|
+
}
|
|
523
|
+
if (rejection !== undefined) {
|
|
524
|
+
res.writeHead(rejection);
|
|
525
|
+
res.end(rejection === 401 ? 'unauthorized' : 'forbidden');
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const pathname = new URL(req.url || '/', 'http://localhost').pathname;
|
|
529
|
+
if (req.method === 'GET' && pathname === `${CHANNEL}/events`) {
|
|
530
|
+
serveEvents(res, req);
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
if (req.method === 'GET' && pathname === `${CHANNEL}/ping`) {
|
|
534
|
+
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
|
|
535
|
+
res.end(`ok ${events.length}`);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
if (pathname === `${CHANNEL}/config`) {
|
|
539
|
+
if (req.method === 'GET') {
|
|
540
|
+
replyJson(res, 200, settingsView());
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
if (req.method === 'POST') {
|
|
544
|
+
let body;
|
|
545
|
+
try {
|
|
546
|
+
body = await readJson(req);
|
|
547
|
+
} catch {
|
|
548
|
+
replyJson(res, 400, { ok: false, error: 'invalid JSON body' });
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
const patch = {};
|
|
552
|
+
for (const key of BOOLEAN_KEYS) {
|
|
553
|
+
if (body && Object.prototype.hasOwnProperty.call(body, key)) {
|
|
554
|
+
patch[key] = coerceValue(key, body[key], config[key]);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
for (const key of STRING_KEYS) {
|
|
558
|
+
if (body && Object.prototype.hasOwnProperty.call(body, key)) {
|
|
559
|
+
patch[key] = coerceValue(key, body[key], config[key]);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
for (const key of Object.keys(LIMITS)) {
|
|
563
|
+
if (body && Object.prototype.hasOwnProperty.call(body, key)) {
|
|
564
|
+
patch[key] = coerceValue(key, body[key], config[key]);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (Object.keys(patch).length === 0) {
|
|
568
|
+
replyJson(res, 400, { ok: false, error: 'no known settings in the request' });
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
Object.assign(config, patch);
|
|
572
|
+
// Answer first, persist afterwards. `configEditor.edit()` reconciles
|
|
573
|
+
// the profile patches, which hot-reloads and RESTARTS this plugin —
|
|
574
|
+
// awaiting it here would tear down the very route that owes the
|
|
575
|
+
// response, so every toggle would appear dead.
|
|
576
|
+
replyJson(res, 200, { ok: true, persisted: false, ...settingsView() });
|
|
577
|
+
// Every open page reflects the new settings without a reload.
|
|
578
|
+
for (const client of settingsClients) {
|
|
579
|
+
try {
|
|
580
|
+
send(client.res, { type: 'settings', config: settingsView().config });
|
|
581
|
+
} catch {
|
|
582
|
+
/* a closed page is removed by its own close listener */
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
// Keep the write off the response path; the reload it triggers is
|
|
586
|
+
// expected and the new config is what `apply` starts from.
|
|
587
|
+
void persist(patch);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
res.writeHead(404);
|
|
592
|
+
res.end('not found');
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
scope.effect(() => scope.webServer.register({
|
|
596
|
+
kind: 'prefix',
|
|
597
|
+
path: CHANNEL,
|
|
598
|
+
handler,
|
|
599
|
+
}), `${CHANNEL}: notification channel`);
|
|
600
|
+
});
|
|
601
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Session notifier",
|
|
4
|
+
"description": "Raises browser system notifications for DSH session replies, turn completion, session end, pending approvals and questions, errors and subagent completion, with per-event tones, quiet hours and a privacy switch. A bell in the session header opens the settings, so alerts still arrive while the browser is minimized or on another page."
|
|
5
|
+
}
|
|
6
|
+
}
|