@clagentic/console 1.11.0 → 1.12.0-beta.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.
Files changed (41) hide show
  1. package/bin/cli.js +12 -1
  2. package/lib/build-sha.json +2 -2
  3. package/lib/cli/arg-validation.js +1 -1
  4. package/lib/cli/ipc-subcommands.js +26 -0
  5. package/lib/daemon.js +20 -0
  6. package/lib/notification-prefs.js +255 -0
  7. package/lib/project-loop.js +3 -6
  8. package/lib/project-notifications.js +176 -34
  9. package/lib/project-sessions.js +28 -0
  10. package/lib/prompt-registry.js +18 -0
  11. package/lib/prompt-reminders.js +277 -0
  12. package/lib/public/css/input.css +93 -0
  13. package/lib/public/css/menus.css +22 -0
  14. package/lib/public/css/server-settings.css +24 -0
  15. package/lib/public/css/sidebar.css +17 -0
  16. package/lib/public/index.html +3 -0
  17. package/lib/public/modules/app-header.js +2 -0
  18. package/lib/public/modules/app-messages.js +6 -2
  19. package/lib/public/modules/app-notifications.js +29 -3
  20. package/lib/public/modules/app-rate-limit.js +12 -6
  21. package/lib/public/modules/app-rendering.js +16 -3
  22. package/lib/public/modules/collapsible-text.js +77 -0
  23. package/lib/public/modules/keep-alive.js +66 -0
  24. package/lib/public/modules/notification-prefs.js +151 -0
  25. package/lib/public/modules/prompt-reminders-setting.js +13 -0
  26. package/lib/public/modules/sidebar-mobile.js +8 -0
  27. package/lib/public/modules/sidebar-sessions.js +27 -0
  28. package/lib/public/sw.js +7 -1
  29. package/lib/push-audience.js +84 -0
  30. package/lib/push.js +24 -1
  31. package/lib/sdk-bridge.js +27 -12
  32. package/lib/sdk-message-processor.js +72 -14
  33. package/lib/sender-ref.js +3 -0
  34. package/lib/server.js +46 -2
  35. package/lib/session-input.js +7 -1
  36. package/lib/sessions.js +27 -0
  37. package/lib/usage-store.js +381 -0
  38. package/lib/ws-schema.js +6 -0
  39. package/lib/yoke/adapters/claude.js +10 -0
  40. package/lib/yoke/adapters/codex.js +5 -1
  41. package/package.json +1 -1
@@ -6,9 +6,10 @@ var fs = require("fs");
6
6
  var path = require("path");
7
7
  var config = require("./config");
8
8
  var yokeRegistry = require("./yoke").registry;
9
+ var notificationPrefs = require("./notification-prefs");
10
+ var audienceFor = require("./push-audience").audienceFor;
9
11
 
10
12
  var NOTIF_FILE = path.join(config.CONFIG_DIR, "notifications.json");
11
- var REMINDER_INTERVAL = 60 * 60 * 1000; // 1 hour
12
13
 
13
14
  function generateId() {
14
15
  var rand = Math.random().toString(36).substring(2, 8);
@@ -82,6 +83,25 @@ var formatters = {
82
83
  };
83
84
  },
84
85
 
86
+ // The one live reminder of a session's unanswered prompts (see
87
+ // lib/prompt-reminders.js). Not actionable: it names what waits, and a click
88
+ // goes to the session, where the prompt card answers.
89
+ permission_reminder: function (data) {
90
+ return {
91
+ type: "permission_reminder",
92
+ title: data.title || "Prompts waiting",
93
+ body: data.body || "",
94
+ meta: {
95
+ reminderKey: data.reminderKey || null,
96
+ requestIds: data.requestIds || [],
97
+ count: data.count || 0,
98
+ ageMs: data.ageMs || 0,
99
+ agents: data.agents || [],
100
+ tools: data.tools || [],
101
+ },
102
+ };
103
+ },
104
+
85
105
  mate_dm: function (data) {
86
106
  return {
87
107
  type: "mate_dm",
@@ -124,19 +144,27 @@ var formatters = {
124
144
  function attachNotifications(ctx) {
125
145
  var broadcastAll = ctx.broadcastAll;
126
146
  var sendToUser = ctx.sendToUser || null; // (userId, msg) -> void; iterates all project clients
147
+ // (buildMsg(viewerId) -> msg) -> void; one message per live connection, so a
148
+ // count can differ by viewer. Absent: the global count goes to everyone.
149
+ var broadcastPerViewer = ctx.broadcastPerViewer || null;
127
150
  var pushModule = ctx.pushModule;
128
151
  var notifications = loadNotifications();
129
- var reminderTimer = null;
130
-
131
- // A prompt notification is actionable only while its prompt's resolver
132
- // lives in this process; none survives a restart, so a persisted one would
133
- // offer buttons for a prompt nothing can answer.
152
+ var prefsStore = ctx.prefsStore || null;
153
+ var reconcileReminders = null;
154
+ var isMultiUser = ctx.isMultiUser || null;
155
+ var listAdmins = ctx.listAdmins || null;
156
+
157
+ // A prompt notification (and the reminder about it) is actionable only while
158
+ // its prompt's resolver lives in this process; none survives a restart, so a
159
+ // persisted one would offer buttons for a prompt nothing can answer.
134
160
  function loadNotifications() {
135
161
  try {
136
162
  var raw = fs.readFileSync(NOTIF_FILE, "utf8");
137
163
  var parsed = JSON.parse(raw);
138
164
  if (Array.isArray(parsed)) {
139
- return parsed.filter(function (n) { return !(n && n.type === "permission_request"); });
165
+ return parsed.filter(function (n) {
166
+ return !(n && (n.type === "permission_request" || n.type === "permission_reminder"));
167
+ });
140
168
  }
141
169
  } catch (e) {}
142
170
  return [];
@@ -156,6 +184,23 @@ function attachNotifications(ctx) {
156
184
  return notifications.length;
157
185
  }
158
186
 
187
+ // The badge counts what this viewer is shown, never a banner withheld from
188
+ // them (a larger count would reveal that it exists).
189
+ function unreadCountFor(viewer) {
190
+ return notifications.filter(function (n) { return visibleTo(n, viewer); }).length;
191
+ }
192
+
193
+ // Sends buildMsg(viewer) to the given user ids, or to every connection.
194
+ function deliver(userIds, buildMsg) {
195
+ if (userIds && typeof sendToUser === "function") {
196
+ userIds.forEach(function (id) { sendToUser(id, buildMsg(id)); });
197
+ } else if (broadcastPerViewer) {
198
+ broadcastPerViewer(buildMsg);
199
+ } else {
200
+ broadcastAll(buildMsg(null));
201
+ }
202
+ }
203
+
159
204
  // --- Core API ---
160
205
 
161
206
  function notify(event, data) {
@@ -168,9 +213,21 @@ function attachNotifications(ctx) {
168
213
  var formatted = formatter(data || {});
169
214
  if (!formatted) return null;
170
215
 
216
+ // A prompt banner carries tool input, so it follows the push audience
217
+ // (lib/push-audience.js): the owner, or the admins for an ownerless session
218
+ // in multi-user mode, never every client.
219
+ if (event === "permission_request" && !data.targetUserId && !Array.isArray(data.targetUserIds)) {
220
+ var audience = audienceFor(data.ownerId, isMultiUser, listAdmins);
221
+ data = Object.assign({}, data, {
222
+ targetUserId: audience.kind === "owner" ? audience.userIds[0] : null,
223
+ targetUserIds: audience.kind === "admins" ? audience.userIds : null,
224
+ });
225
+ }
226
+
171
227
  var notif = {
172
228
  id: generateId(),
173
229
  type: formatted.type || event,
230
+ category: notificationPrefs.categoryOfNotification(formatted.type || event),
174
231
  title: formatted.title || "",
175
232
  body: formatted.body || "",
176
233
  slug: data.slug || "",
@@ -178,23 +235,24 @@ function attachNotifications(ctx) {
178
235
  mateId: data.mateId || null,
179
236
  ownerId: data.ownerId || null,
180
237
  targetUserId: data.targetUserId || null,
238
+ targetUserIds: Array.isArray(data.targetUserIds) ? data.targetUserIds : null,
181
239
  createdAt: Date.now(),
182
240
  meta: formatted.meta || {},
183
241
  };
184
242
  notifications.unshift(notif);
185
243
  saveNotifications();
186
- var payload = {
187
- type: "notification_created",
188
- notification: notif,
189
- unreadCount: getUnreadCount(),
190
- };
191
- // If targeted at a specific user, deliver only to that user's connections.
192
- // Otherwise broadcast to everyone (existing behavior).
193
- if (notif.targetUserId && typeof sendToUser === "function") {
194
- sendToUser(notif.targetUserId, payload);
195
- } else {
196
- broadcastAll(payload);
197
- }
244
+ // Targeted at specific users: only their connections hear it. Otherwise
245
+ // every connection does.
246
+ var recipients = null;
247
+ if (notif.targetUserIds && typeof sendToUser === "function") recipients = notif.targetUserIds;
248
+ else if (notif.targetUserId && typeof sendToUser === "function") recipients = [notif.targetUserId];
249
+ deliver(recipients, function (viewer) {
250
+ return {
251
+ type: "notification_created",
252
+ notification: notif,
253
+ unreadCount: recipients || broadcastPerViewer ? unreadCountFor(viewer) : getUnreadCount(),
254
+ };
255
+ });
198
256
  return notif;
199
257
  }
200
258
 
@@ -203,10 +261,12 @@ function attachNotifications(ctx) {
203
261
  notifications = notifications.filter(function(n) { return ids.indexOf(n.id) === -1; });
204
262
  if (notifications.length !== before) {
205
263
  saveNotifications();
206
- broadcastAll({
207
- type: "notification_dismissed",
208
- ids: ids,
209
- unreadCount: getUnreadCount(),
264
+ deliver(null, function (viewer) {
265
+ return {
266
+ type: "notification_dismissed",
267
+ ids: ids,
268
+ unreadCount: broadcastPerViewer ? unreadCountFor(viewer) : getUnreadCount(),
269
+ };
210
270
  });
211
271
  }
212
272
  }
@@ -220,6 +280,8 @@ function attachNotifications(ctx) {
220
280
  return n.type === "permission_request" && n.meta && n.meta.requestId === requestId;
221
281
  }).map(function (n) { return n.id; });
222
282
  if (ids.length) dismiss(ids);
283
+ // A reminder that names this prompt is now wrong, or gone.
284
+ reconcileRemindersNow();
223
285
  }
224
286
 
225
287
  function dismissAll() {
@@ -230,29 +292,93 @@ function attachNotifications(ctx) {
230
292
  }
231
293
  }
232
294
 
233
- // --- Periodic reminder ---
295
+ // --- Prompt reminders (scheduling lives in lib/prompt-reminders.js) ---
234
296
 
235
- function startReminder() {
236
- // Reminder push is suppressed in multi-user mode: the unread count is
237
- // per-project state that would leak to all push subscribers regardless of
238
- // which user owns the notifications.
297
+ function reminderIds(key) {
298
+ return notifications.filter(function (n) {
299
+ return n.type === "permission_reminder" && n.meta && n.meta.reminderKey === key;
300
+ }).map(function (n) { return n.id; });
239
301
  }
240
302
 
241
- function stopReminder() {
242
- if (reminderTimer) { clearInterval(reminderTimer); reminderTimer = null; }
303
+ // A session has at most one live reminder: the new one replaces the old on
304
+ // every surface (the dismissal and the new notification travel together).
305
+ function replaceReminder(key, data) {
306
+ var old = reminderIds(key);
307
+ if (old.length) dismiss(old);
308
+ return notify("permission_reminder", Object.assign({}, data, { reminderKey: key }));
243
309
  }
244
310
 
245
- startReminder();
311
+ function dismissReminder(key) {
312
+ var ids = reminderIds(key);
313
+ if (ids.length) dismiss(ids);
314
+ }
315
+
316
+ function setReminderReconciler(fn) {
317
+ reconcileReminders = typeof fn === "function" ? fn : null;
318
+ }
319
+
320
+ // Recounts or clears live reminders after a prompt settled or a session's
321
+ // reminders were switched. A fault here must not undo the settle that
322
+ // called it.
323
+ function reconcileRemindersNow() {
324
+ if (!reconcileReminders) return;
325
+ try {
326
+ reconcileReminders();
327
+ } catch (e) {
328
+ console.error("[notifications] reminder reconcile failed:", e && e.message ? e.message : e);
329
+ }
330
+ }
331
+
332
+ var PROMPT_TYPES = { permission_request: true, permission_reminder: true };
333
+
334
+ function visibleTo(n, viewer) {
335
+ if (Array.isArray(n.targetUserIds)) return n.targetUserIds.indexOf(viewer) !== -1;
336
+ if (PROMPT_TYPES[n.type] && n.targetUserId) return n.targetUserId === viewer;
337
+ return true;
338
+ }
246
339
 
247
340
  // --- Connection state (called per-client with sendTo) ---
248
341
 
249
342
  function sendConnectionState(ws, sendTo) {
250
343
  if (!sendTo) return;
344
+ // A notification aimed at admins only, or a prompt banner aimed at its
345
+ // owner, is not handed to anyone else on connect, as it is not live.
346
+ var viewer = userIdOf(ws);
251
347
  sendTo(ws, {
252
348
  type: "notifications_state",
253
- notifications: notifications,
254
- unreadCount: getUnreadCount(),
349
+ notifications: notifications.filter(function (n) { return visibleTo(n, viewer); }),
350
+ unreadCount: unreadCountFor(viewer),
255
351
  });
352
+ if (prefsStore) sendTo(ws, prefsMessage(userIdOf(ws)));
353
+ }
354
+
355
+ // --- Per-user preferences (lib/notification-prefs.js) ---
356
+
357
+ function userIdOf(ws) {
358
+ return ws && ws._clagenticUser ? ws._clagenticUser.id : null;
359
+ }
360
+
361
+ function prefsMessage(userId) {
362
+ var v = prefsStore.view(userId);
363
+ return {
364
+ type: "notification_prefs",
365
+ prefs: v.prefs,
366
+ preset: v.preset,
367
+ known: v.known,
368
+ categories: notificationPrefs.CATEGORIES.map(function (id) {
369
+ return { id: id, label: notificationPrefs.CATEGORY_LABELS[id] };
370
+ }),
371
+ presets: Object.keys(notificationPrefs.PRESETS).map(function (id) {
372
+ return { id: id, label: notificationPrefs.PRESETS[id].label };
373
+ }),
374
+ };
375
+ }
376
+
377
+ // Every connection of the user (the phone and the desktop) hears the change.
378
+ function sendPrefsToUser(userId) {
379
+ var msg = prefsMessage(userId);
380
+ if (userId && typeof sendToUser === "function") sendToUser(userId, msg);
381
+ else broadcastAll(msg);
256
382
  }
257
383
 
258
384
  // --- Message handler ---
@@ -266,16 +392,32 @@ function attachNotifications(ctx) {
266
392
  dismissAll();
267
393
  return true;
268
394
  }
395
+ if (prefsStore && msg.type === "notification_prefs_set") {
396
+ prefsStore.set(userIdOf(ws), { preset: msg.preset, surfaces: msg.surfaces });
397
+ sendPrefsToUser(userIdOf(ws));
398
+ return true;
399
+ }
400
+ if (prefsStore && msg.type === "notification_prefs_migrate") {
401
+ // First load after the preferences moved to the server: carry what this
402
+ // browser held, once.
403
+ var legacy = msg.legacy && typeof msg.legacy === "object" ? { sound: msg.legacy.sound !== false } : null;
404
+ prefsStore.migrateLegacy(userIdOf(ws), legacy);
405
+ sendPrefsToUser(userIdOf(ws));
406
+ return true;
407
+ }
269
408
  return false;
270
409
  }
271
410
 
272
411
  return {
273
412
  notify: notify,
274
413
  dismissByRequestId: dismissByRequestId,
414
+ replaceReminder: replaceReminder,
415
+ dismissReminder: dismissReminder,
416
+ setReminderReconciler: setReminderReconciler,
417
+ reconcileReminders: reconcileRemindersNow,
275
418
  getUnreadCount: getUnreadCount,
276
419
  sendConnectionState: sendConnectionState,
277
420
  handleNotificationMessage: handleNotificationMessage,
278
- stopReminder: stopReminder,
279
421
  };
280
422
  }
281
423
 
@@ -102,6 +102,7 @@ function attachSessions(ctx) {
102
102
  var projectAccess = ctx.projectAccess;
103
103
  var userPresence = ctx.userPresence;
104
104
  var pushModule = ctx.pushModule;
105
+ var getNotificationsModule = ctx.getNotificationsModule || function () { return null; };
105
106
  var getSessionForWs = ctx.getSessionForWs;
106
107
  var getLinuxUserForSession = ctx.getLinuxUserForSession;
107
108
  var ensureProjectAccessForSession = ctx.ensureProjectAccessForSession;
@@ -509,6 +510,33 @@ function attachSessions(ctx) {
509
510
  return true;
510
511
  }
511
512
 
513
+ if (msg.type === "set_session_keep_alive") {
514
+ if (typeof msg.sessionId === "number") {
515
+ var keepAliveTarget = sm.sessions.get(msg.sessionId);
516
+ if (!keepAliveTarget) return true;
517
+ if (ws._clagenticUser) {
518
+ if (!usersModule.canAccessSession(ws._clagenticUser.id, keepAliveTarget, { visibility: "public" })) return true;
519
+ }
520
+ sm.setSessionKeepAlive(msg.sessionId, msg.keepAlive === true);
521
+ }
522
+ return true;
523
+ }
524
+
525
+ if (msg.type === "set_session_prompt_reminders") {
526
+ if (typeof msg.sessionId === "number") {
527
+ var reminderTarget = sm.sessions.get(msg.sessionId);
528
+ if (!reminderTarget) return true;
529
+ if (ws._clagenticUser) {
530
+ if (!usersModule.canAccessSession(ws._clagenticUser.id, reminderTarget, { visibility: "public" })) return true;
531
+ }
532
+ sm.setSessionPromptReminders(msg.sessionId, msg.enabled !== false);
533
+ // A live reminder of a session just switched off goes now, not at the next tick.
534
+ var reminderNm = getNotificationsModule();
535
+ if (reminderNm && typeof reminderNm.reconcileReminders === "function") reminderNm.reconcileReminders();
536
+ }
537
+ return true;
538
+ }
539
+
512
540
  if (msg.type === "reorder_session_bookmarks") {
513
541
  if (typeof msg.sourceId === "number" && typeof msg.targetId === "number" && msg.sourceId !== msg.targetId) {
514
542
  var source = sm.sessions.get(msg.sourceId);
@@ -670,6 +670,23 @@ function createPromptRegistry(deps) {
670
670
  return entries(session).filter(function (e) { return e.kind.journal; }).length;
671
671
  }
672
672
 
673
+ /**
674
+ * What the reminder sweep needs to know of each operator-facing pending
675
+ * prompt of a session: when it opened, what it gates and for which
676
+ * background agent. Read-only facts; never the record or its resolver.
677
+ */
678
+ function pendingInfo(session) {
679
+ return entries(session).filter(function (e) { return e.kind.journal; }).map(function (e) {
680
+ return {
681
+ requestId: e.id,
682
+ kind: e.kind.name,
683
+ toolName: typeof e.record.toolName === "string" ? e.record.toolName : null,
684
+ agent: (e.record.label && e.record.label.agent) || "",
685
+ createdAt: typeof e.record.createdAt === "number" ? e.record.createdAt : 0,
686
+ };
687
+ });
688
+ }
689
+
673
690
  /**
674
691
  * Returns a mapper for replayed history items that stamps every item
675
692
  * opening a prompt with its authoritative promptState, so a client renders
@@ -736,6 +753,7 @@ function createPromptRegistry(deps) {
736
753
  revokeGrant: revokeGrant,
737
754
  pendingMessages: pendingMessages,
738
755
  pendingCount: pendingCount,
756
+ pendingInfo: pendingInfo,
739
757
  replayAnnotator: replayAnnotator,
740
758
  };
741
759
  }
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+
3
+ // Reminders for operator prompts nobody has answered.
4
+ //
5
+ // A permission prompt has no timeout, so a prompt the operator never saw (their
6
+ // own, or a background agent's) waits for ever and pins its session. A reminder
7
+ // is the notification that closes that: it repeats at growing intervals, through
8
+ // the notification paths that already exist (the in-app banner and push).
9
+ //
10
+ // Derived, not timed: nothing is scheduled per prompt. A sweep reads the pending
11
+ // prompts from each session's prompt registry (lib/prompt-registry.js) and
12
+ // decides from their opening times what is due:
13
+ // - the schedule is offsets from the oldest pending prompt's opening: the
14
+ // configured steps, then one more every `repeatMs`;
15
+ // - a session has at most ONE live reminder; the next one replaces it, with
16
+ // the current count, the oldest age, and the waiting agents and tools;
17
+ // - a prompt that settles (an answer, a cancel, an end of turn) clears or
18
+ // recounts the reminder at once, through the notifications module's
19
+ // reconcile hook, not at the next tick;
20
+ // - the sweep only reads. A reminder never opens, settles or touches a prompt,
21
+ // and nothing here is consulted by the idle reaper.
22
+ // Nothing survives a restart because no prompt does (the registry ends every
23
+ // prompt at shutdown): a prompt that is pending again after one (the agent
24
+ // asked once more) starts its own schedule from its own opening time.
25
+ //
26
+ // Per-session switch: session.promptRemindersOff (persisted with the session).
27
+ // Configuration: daemon.json `promptReminders` { enabled, scheduleMinutes,
28
+ // repeatMinutes }. The schedule is read on every sweep, so a change needs no
29
+ // restart. The sweep tick is a constant, not configuration: a timer period taken
30
+ // from a config file is a value that can be set to nothing. A `tickSeconds` key
31
+ // left in daemon.json is ignored.
32
+
33
+ var { pushForSession, audienceFor } = require("./push-audience");
34
+
35
+ var DEFAULT_SCHEDULE_MINUTES = [5, 15, 30];
36
+ var DEFAULT_REPEAT_MINUTES = 60;
37
+ var SWEEP_TICK_MS = 30000;
38
+ var MAX_NAMED = 3;
39
+
40
+ // A configured interval is at least one whole minute once rounded to
41
+ // milliseconds. Anything smaller would round the repeat step to 0 and make the
42
+ // due count divide by zero.
43
+ var MIN_INTERVAL_MS = 60000;
44
+
45
+ // The one validator for every configurable interval: the minutes, or null.
46
+ function intervalMinutes(v) {
47
+ var ms = typeof v === "number" && isFinite(v) && v > 0 ? Math.round(v * 60000) : 0;
48
+ return ms >= MIN_INTERVAL_MS ? v : null;
49
+ }
50
+
51
+ var warned = Object.create(null);
52
+
53
+ // One warning per key and value, not one per sweep: the schedule is re-read on
54
+ // every tick.
55
+ function warnOnce(key, value) {
56
+ var id = key + "=" + JSON.stringify(value);
57
+ if (warned[id]) return;
58
+ warned[id] = true;
59
+ console.warn("[prompt-reminders] promptReminders." + key + " must be at least 1 minute; using the default");
60
+ }
61
+
62
+ function repeatMinutes(v) {
63
+ var ok = intervalMinutes(v);
64
+ if (ok !== null) return ok;
65
+ if (v !== undefined) warnOnce("repeatMinutes", v);
66
+ return DEFAULT_REPEAT_MINUTES;
67
+ }
68
+
69
+ /**
70
+ * The schedule daemon.json asks for, with the defaults wherever it is silent
71
+ * or malformed.
72
+ * @param {?object} cfg the daemon.json `promptReminders` value
73
+ * @returns {{enabled: boolean, offsetsMs: number[], repeatMs: number}}
74
+ */
75
+ function resolveSchedule(cfg) {
76
+ cfg = cfg && typeof cfg === "object" ? cfg : {};
77
+ var minutes = Array.isArray(cfg.scheduleMinutes) ? cfg.scheduleMinutes.map(intervalMinutes) : null;
78
+ if (!minutes || minutes.length === 0 || minutes.indexOf(null) !== -1) {
79
+ if (cfg.scheduleMinutes !== undefined) warnOnce("scheduleMinutes", cfg.scheduleMinutes);
80
+ minutes = DEFAULT_SCHEDULE_MINUTES;
81
+ }
82
+ // Increasing, so "due" is a count.
83
+ minutes = minutes.slice().sort(function (a, b) { return a - b; });
84
+ return {
85
+ enabled: cfg.enabled !== false,
86
+ offsetsMs: minutes.map(function (m) { return Math.round(m * 60000); }),
87
+ repeatMs: Math.round(repeatMinutes(cfg.repeatMinutes) * 60000),
88
+ };
89
+ }
90
+
91
+ /** How many reminders a prompt this old has earned. */
92
+ function dueCount(ageMs, schedule) {
93
+ var offsets = schedule.offsetsMs;
94
+ var n = 0;
95
+ while (n < offsets.length && ageMs >= offsets[n]) n++;
96
+ if (n < offsets.length) return n;
97
+ return n + Math.floor((ageMs - offsets[offsets.length - 1]) / schedule.repeatMs);
98
+ }
99
+
100
+ function waitingFor(ageMs) {
101
+ // Under a minute only a short configured schedule gets here.
102
+ if (ageMs < 60000) return Math.max(1, Math.floor(ageMs / 1000)) + " sec";
103
+ var min = Math.floor(ageMs / 60000);
104
+ return min >= 120 ? Math.floor(min / 60) + " h" : min + " min";
105
+ }
106
+
107
+ function uniqueNamed(values) {
108
+ var seen = Object.create(null);
109
+ var out = [];
110
+ values.forEach(function (v) {
111
+ if (v && !seen[v]) { seen[v] = true; out.push(v); }
112
+ });
113
+ return out;
114
+ }
115
+
116
+ function nameList(values) {
117
+ var shown = values.slice(0, MAX_NAMED).join(", ");
118
+ return values.length > MAX_NAMED ? shown + " +" + (values.length - MAX_NAMED) + " more" : shown;
119
+ }
120
+
121
+ /**
122
+ * The reminder's text for one session's pending prompts.
123
+ * @param {{project: string, session: string, infos: object[], ageMs: number}} s
124
+ */
125
+ function describe(s) {
126
+ var count = s.infos.length;
127
+ var agents = uniqueNamed(s.infos.map(function (i) { return i.agent; }));
128
+ var tools = uniqueNamed(s.infos.map(function (i) { return i.toolName; }));
129
+ var parts = [];
130
+ if (s.project) parts.push("Project: " + s.project);
131
+ if (s.session) parts.push("Session: " + s.session);
132
+ if (agents.length) parts.push("Agent: " + nameList(agents));
133
+ if (tools.length) parts.push("Tool: " + nameList(tools));
134
+ return {
135
+ title: count + (count === 1 ? " prompt" : " prompts") + " waiting, oldest " + waitingFor(s.ageMs),
136
+ body: parts.join(" | "),
137
+ agents: agents,
138
+ tools: tools,
139
+ };
140
+ }
141
+
142
+ /**
143
+ * @param {object} deps
144
+ * @param {function(): Array<{slug: string, project: string, session: object, prompts: object}>} deps.listSessions
145
+ * every session of every project with its prompt registry.
146
+ * @param {object} deps.notifications the notifications module (replaceReminder,
147
+ * dismissReminder, setReminderReconciler).
148
+ * @param {?object} [deps.push] the push module.
149
+ * @param {function(): ?object} [deps.getConfig] daemon.json `promptReminders`.
150
+ * @param {function(): boolean} [deps.isMultiUser] true when the daemon has
151
+ * accounts; absent means single-user. A throw reads as multi-user, the
152
+ * stricter mode.
153
+ * @param {function(): number} [deps.now]
154
+ */
155
+ function createPromptReminders(deps) {
156
+ var notifications = deps.notifications;
157
+ var push = deps.push || null;
158
+ var getConfig = deps.getConfig || function () { return null; };
159
+ var now = deps.now || Date.now;
160
+ var isMultiUser = deps.isMultiUser || function () { return false; };
161
+ var listAdmins = deps.listAdmins;
162
+ // sessionKey -> { sent: reminders already sent, live: a reminder is showing,
163
+ // sig: the prompts it names }
164
+ var states = Object.create(null);
165
+ var timer = null;
166
+
167
+ // What a live reminder says about the set of waiting prompts; a change in it
168
+ // (one answered, one more opened) recounts the reminder, no change leaves it.
169
+ function signature(infos) {
170
+ return infos.map(function (i) { return i.requestId; }).join(",");
171
+ }
172
+
173
+ function keyOf(slug, session) {
174
+ return slug + ":" + session.localId;
175
+ }
176
+
177
+ function sendPush(entry, key, text) {
178
+ if (!push) return;
179
+ var payload = {
180
+ type: "permission_reminder",
181
+ slug: entry.slug,
182
+ requestId: entry.requestId,
183
+ title: text.title,
184
+ body: text.body,
185
+ tag: "prompt-reminder-" + key,
186
+ };
187
+ pushForSession(push, entry.session.ownerId, payload, isMultiUser, listAdmins);
188
+ }
189
+
190
+ function raise(entry, infos, ageMs, key, withPush) {
191
+ states[key].sig = signature(infos);
192
+ var text = describe({ project: entry.project, session: entry.session.title, infos: infos, ageMs: ageMs });
193
+ // The banner follows the push audience: the owner, or the admins for a
194
+ // session with no owner in multi-user mode, so no one else reads its title.
195
+ var audience = audienceFor(entry.session.ownerId, isMultiUser, listAdmins);
196
+ notifications.replaceReminder(key, {
197
+ title: text.title,
198
+ body: text.body,
199
+ slug: entry.slug,
200
+ sessionId: entry.session.localId,
201
+ ownerId: entry.session.ownerId || null,
202
+ targetUserId: audience.kind === "owner" ? audience.userIds[0] : null,
203
+ targetUserIds: audience.kind === "admins" ? audience.userIds : null,
204
+ requestIds: infos.map(function (i) { return i.requestId; }),
205
+ count: infos.length,
206
+ ageMs: ageMs,
207
+ agents: text.agents,
208
+ tools: text.tools,
209
+ });
210
+ if (withPush) sendPush({ slug: entry.slug, session: entry.session, requestId: infos[0].requestId }, key, text);
211
+ }
212
+
213
+ function clear(key) {
214
+ if (states[key]) {
215
+ delete states[key];
216
+ notifications.dismissReminder(key);
217
+ }
218
+ }
219
+
220
+ /**
221
+ * One pass over every pending prompt.
222
+ * @param {boolean} sendDue true on the clock: send what the schedule says is
223
+ * due. false when a prompt settled: only clear or recount a live reminder.
224
+ */
225
+ function sweep(sendDue) {
226
+ var schedule = resolveSchedule(getConfig());
227
+ var t = now();
228
+ var seen = Object.create(null);
229
+ deps.listSessions().forEach(function (entry) {
230
+ var session = entry.session;
231
+ var key = keyOf(entry.slug, session);
232
+ var infos = entry.prompts.pendingInfo(session);
233
+ if (!infos.length || session.promptRemindersOff === true || !schedule.enabled) return;
234
+ seen[key] = true;
235
+ infos.sort(function (a, b) { return a.createdAt - b.createdAt; });
236
+ var ageMs = Math.max(0, t - infos[0].createdAt);
237
+ var state = states[key] || (states[key] = { sent: 0, live: false, sig: "" });
238
+ var due = dueCount(ageMs, schedule);
239
+ // The oldest prompt was answered and a newer one remains: its schedule
240
+ // starts from its own opening.
241
+ if (due < state.sent) state.sent = due;
242
+ if (sendDue && due > state.sent) {
243
+ state.sent = due;
244
+ state.live = true;
245
+ raise(entry, infos, ageMs, key, true);
246
+ } else if (state.live && state.sig !== signature(infos)) {
247
+ raise(entry, infos, ageMs, key, false);
248
+ }
249
+ });
250
+ Object.keys(states).forEach(function (key) {
251
+ if (!seen[key]) clear(key);
252
+ });
253
+ }
254
+
255
+ function start() {
256
+ if (timer) return;
257
+ notifications.setReminderReconciler(function () { sweep(false); });
258
+ timer = setInterval(function () { sweep(true); }, SWEEP_TICK_MS);
259
+ // The sweep must not keep a daemon that is going away alive.
260
+ if (timer.unref) timer.unref();
261
+ }
262
+
263
+ function stop() {
264
+ if (timer) { clearInterval(timer); timer = null; }
265
+ notifications.setReminderReconciler(null);
266
+ }
267
+
268
+ return { start: start, stop: stop, sweep: sweep };
269
+ }
270
+
271
+ module.exports = {
272
+ createPromptReminders: createPromptReminders,
273
+ resolveSchedule: resolveSchedule,
274
+ dueCount: dueCount,
275
+ SWEEP_TICK_MS: SWEEP_TICK_MS,
276
+ describe: describe,
277
+ };