@clagentic/console 1.11.0-beta.2 → 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
@@ -0,0 +1,151 @@
1
+ // notification-prefs.js - the user's per-type notification preferences.
2
+ //
3
+ // The preferences live on the server, with the user's account, so the phone and
4
+ // the desktop agree and push is filtered where it is sent. This module holds the
5
+ // last copy the server sent, answers "may this type alert / sound here?" and
6
+ // draws the settings card (a preset picker and a surface-by-type grid).
7
+ //
8
+ // Muting a type never hides it: the notification still lands in the panel and
9
+ // on the session's prompt card; only the banner, the sound and the push are
10
+ // suppressed.
11
+
12
+ import { getWs } from './ws-ref.js';
13
+
14
+ var LEGACY_MIGRATED_KEY = "notif-prefs-migrated";
15
+ var SURFACE_LABELS = { banner: "Banner", sound: "Sound", push: "Push" };
16
+ var SURFACE_ORDER = ["banner", "sound", "push"];
17
+
18
+ var current = null;
19
+
20
+ /** True once the server has sent the user's preferences. */
21
+ export function hasNotificationPrefs() {
22
+ return current !== null;
23
+ }
24
+
25
+ /**
26
+ * Whether a surface should alert for a category. Before the server has
27
+ * answered, and for a notification with no category, everything is wanted
28
+ * (today's behaviour).
29
+ */
30
+ export function isSurfaceWanted(surface, category) {
31
+ if (!current || !category) return true;
32
+ var row = current.prefs && current.prefs[surface];
33
+ return !row || row[category] !== false;
34
+ }
35
+
36
+ /**
37
+ * Whether a notification just created should chime. The turn-done chime has
38
+ * only ever played while the tab is hidden, so a notification chimes under that
39
+ * same rule AND when the user's sound preference for its type is on. The
40
+ * default preferences leave sound on for a finished turn only, so by default a
41
+ * reminder is silent. A finished turn's own handler plays its chime itself.
42
+ * @param {{type: string, category: ?string}} notif
43
+ * @param {boolean} soundSwitchOn the browser's global sound switch
44
+ */
45
+ export function shouldChimeForNotification(notif, soundSwitchOn) {
46
+ if (!notif || notif.type === "response_done") return false;
47
+ if (typeof document === "undefined" || !document.hidden) return false;
48
+ if (!soundSwitchOn) return false;
49
+ // No category: only the "everything wanted" fallback would say yes, which
50
+ // would chime for types that never did. Require a known category.
51
+ return !!notif.category && !!current && isSurfaceWanted("sound", notif.category);
52
+ }
53
+
54
+ function send(msg) {
55
+ var ws = getWs();
56
+ if (ws && ws.readyState === 1) ws.send(JSON.stringify(msg));
57
+ }
58
+
59
+ // The browser held global switches before the preferences moved to the server.
60
+ // The sound switch carries over, once; the alert and push switches describe
61
+ // this browser's permission and subscription and stay with it.
62
+ function migrateLegacyOnce(msg) {
63
+ if (msg.known) return;
64
+ var already = false;
65
+ try { already = localStorage.getItem(LEGACY_MIGRATED_KEY) === "1"; } catch (e) { already = false; }
66
+ if (already) return;
67
+ var sound = true;
68
+ try { sound = localStorage.getItem("notif-sound") !== "0"; } catch (e) { sound = true; }
69
+ send({ type: "notification_prefs_migrate", legacy: { sound: sound } });
70
+ try { localStorage.setItem(LEGACY_MIGRATED_KEY, "1"); } catch (e) { /* storage unavailable: the server default stands */ }
71
+ }
72
+
73
+ export function handleNotificationPrefs(msg) {
74
+ current = msg;
75
+ migrateLegacyOnce(msg);
76
+ render();
77
+ }
78
+
79
+ function render() {
80
+ var card = document.getElementById("notif-prefs-card");
81
+ if (!card || !current) return;
82
+ card.innerHTML = "";
83
+
84
+ var presetRow = document.createElement("div");
85
+ presetRow.className = "settings-field";
86
+ var presetLabel = document.createElement("label");
87
+ presetLabel.className = "settings-label";
88
+ presetLabel.setAttribute("for", "notif-prefs-preset");
89
+ presetLabel.textContent = "Notify me for";
90
+ var select = document.createElement("select");
91
+ select.id = "notif-prefs-preset";
92
+ select.className = "us-text-input";
93
+ (current.presets || []).forEach(function (p) {
94
+ var opt = document.createElement("option");
95
+ opt.value = p.id;
96
+ opt.textContent = p.label;
97
+ select.appendChild(opt);
98
+ });
99
+ var custom = document.createElement("option");
100
+ custom.value = "";
101
+ custom.textContent = "Custom";
102
+ custom.disabled = true;
103
+ select.appendChild(custom);
104
+ select.value = current.preset || "";
105
+ select.addEventListener("change", function () {
106
+ if (select.value) send({ type: "notification_prefs_set", preset: select.value });
107
+ });
108
+ presetRow.appendChild(presetLabel);
109
+ presetRow.appendChild(select);
110
+ var hint = document.createElement("div");
111
+ hint.className = "settings-hint";
112
+ hint.textContent = "A muted type still appears in the notifications panel and on the session's prompt card; only the banner, the sound and the push are suppressed.";
113
+ presetRow.appendChild(hint);
114
+ card.appendChild(presetRow);
115
+
116
+ var table = document.createElement("table");
117
+ table.className = "notif-prefs-grid";
118
+ var head = document.createElement("tr");
119
+ head.appendChild(document.createElement("th"));
120
+ SURFACE_ORDER.forEach(function (surface) {
121
+ var th = document.createElement("th");
122
+ th.textContent = SURFACE_LABELS[surface];
123
+ head.appendChild(th);
124
+ });
125
+ table.appendChild(head);
126
+ (current.categories || []).forEach(function (cat) {
127
+ var tr = document.createElement("tr");
128
+ var name = document.createElement("td");
129
+ name.textContent = cat.label;
130
+ tr.appendChild(name);
131
+ SURFACE_ORDER.forEach(function (surface) {
132
+ var td = document.createElement("td");
133
+ var box = document.createElement("input");
134
+ box.type = "checkbox";
135
+ box.checked = isSurfaceWanted(surface, cat.id);
136
+ box.setAttribute("data-surface", surface);
137
+ box.setAttribute("data-category", cat.id);
138
+ box.setAttribute("aria-label", cat.label + ": " + SURFACE_LABELS[surface]);
139
+ box.addEventListener("change", function () {
140
+ var patch = {};
141
+ patch[surface] = {};
142
+ patch[surface][cat.id] = box.checked;
143
+ send({ type: "notification_prefs_set", surfaces: patch });
144
+ });
145
+ td.appendChild(box);
146
+ tr.appendChild(td);
147
+ });
148
+ table.appendChild(tr);
149
+ });
150
+ card.appendChild(table);
151
+ }
@@ -0,0 +1,13 @@
1
+ // prompt-reminders-setting.js - the per-session switch for reminders about
2
+ // unanswered prompts (the server side is lib/prompt-reminders.js).
3
+
4
+ import { store } from './store.js';
5
+ import { getWs } from './ws-ref.js';
6
+
7
+ /** Asks the server to turn a session's prompt reminders on or off. */
8
+ export function sendSessionPromptReminders(sessionId, enabled) {
9
+ var ws = getWs();
10
+ if (ws && store.get('connected')) {
11
+ ws.send(JSON.stringify({ type: "set_session_prompt_reminders", sessionId: sessionId, enabled: !!enabled }));
12
+ }
13
+ }
@@ -499,6 +499,14 @@ function createMobileSessionItem(s) {
499
499
  el.appendChild(agentBadge);
500
500
  }
501
501
 
502
+ if (s.keepAlive) {
503
+ var pinBadge = document.createElement("span");
504
+ pinBadge.className = "session-keepalive-badge";
505
+ pinBadge.title = "Kept alive: not ended when idle";
506
+ pinBadge.innerHTML = iconHtml("pin");
507
+ el.appendChild(pinBadge);
508
+ }
509
+
502
510
  var titleSpan = document.createElement("span");
503
511
  titleSpan.className = "mobile-session-title";
504
512
  titleSpan.appendChild(document.createTextNode(s.title || "New Session"));
@@ -10,6 +10,8 @@ import { capabilityGate } from './vendor-registry.js';
10
10
  import { getWs } from './ws-ref.js';
11
11
  import { openSessionGrants } from './session-grants.js';
12
12
  import { getSessionListEl } from './dom-refs.js';
13
+ import { keepAliveBadgeHtml, sendSessionKeepAlive } from './keep-alive.js';
14
+ import { sendSessionPromptReminders } from './prompt-reminders-setting.js';
13
15
  import { dismissOverlayPanels, closeSidebar, updatePageTitle, spawnDustParticles } from './sidebar.js';
14
16
  import { showConfirm } from './app-misc.js';
15
17
  import { getUpcomingSchedules } from './scheduler.js';
@@ -668,6 +670,28 @@ function showSessionCtxMenu(anchorBtn, sessionId, title, cliSid, sessionData) {
668
670
  });
669
671
  menu.appendChild(bookmarkItem);
670
672
 
673
+ var keepAliveItem = document.createElement("button");
674
+ keepAliveItem.className = "session-ctx-item";
675
+ var keepAliveOn = !!(sessionData && sessionData.keepAlive);
676
+ keepAliveItem.innerHTML = iconHtml("pin") + " <span>" + (keepAliveOn ? "Allow idle ending" : "Keep alive when idle") + "</span>";
677
+ keepAliveItem.addEventListener("click", function (e) {
678
+ e.stopPropagation();
679
+ closeSessionCtxMenu();
680
+ sendSessionKeepAlive(sessionId, !keepAliveOn);
681
+ });
682
+ menu.appendChild(keepAliveItem);
683
+
684
+ var remindersItem = document.createElement("button");
685
+ remindersItem.className = "session-ctx-item";
686
+ var remindersOff = !!(sessionData && sessionData.promptRemindersOff);
687
+ remindersItem.innerHTML = iconHtml("bell") + " <span>" + (remindersOff ? "Remind me of waiting prompts" : "Stop reminders for waiting prompts") + "</span>";
688
+ remindersItem.addEventListener("click", function (e) {
689
+ e.stopPropagation();
690
+ closeSessionCtxMenu();
691
+ sendSessionPromptReminders(sessionId, remindersOff);
692
+ });
693
+ menu.appendChild(remindersItem);
694
+
671
695
  var renameItem = document.createElement("button");
672
696
  renameItem.className = "session-ctx-item";
673
697
  renameItem.innerHTML = iconHtml("pencil") + " <span>Rename</span>";
@@ -1282,6 +1306,7 @@ function renderSessionItem(s) {
1282
1306
  textHtml += '<span class="session-agent-badge" title="Agent: ' + escapeHtml(s.agentName) + '">'
1283
1307
  + iconHtml("bot") + '</span>';
1284
1308
  }
1309
+ textHtml += keepAliveBadgeHtml(s);
1285
1310
  textHtml += highlightMatch(s.title || "New Session", searchQuery);
1286
1311
  textSpan.innerHTML = textHtml;
1287
1312
  el.appendChild(textSpan);
@@ -1343,6 +1368,8 @@ function _fingerprintSessions(list, expanded, expandedRuns) {
1343
1368
  (s.active ? "1" : "0") + "," +
1344
1369
  indicatorClass(sessionActivity(s, myUserId)) + "," +
1345
1370
  (s.bookmarked ? "1" : "0") + "," +
1371
+ (s.keepAlive ? "1" : "0") + "," +
1372
+ (s.promptRemindersOff ? "1" : "0") + "," +
1346
1373
  // favoriteOrder drives sort order within the favorites section
1347
1374
  // (compareSessionListItems) and unread drives the badge — both must be
1348
1375
  // in the fingerprint or a bookmark reorder / unread-count change with
package/lib/public/sw.js CHANGED
@@ -131,6 +131,12 @@ self.addEventListener("push", function (event) {
131
131
  if (data.type === "permission_request") {
132
132
  options.requireInteraction = true;
133
133
  options.tag = "perm-" + data.requestId;
134
+ } else if (data.type === "permission_reminder") {
135
+ // One reminder per session: the tag makes a new one replace the last, and
136
+ // renotify makes the replacement alert again.
137
+ options.requireInteraction = true;
138
+ options.tag = data.tag || "prompt-reminder";
139
+ options.renotify = true;
134
140
  } else if (data.type === "done") {
135
141
  options.tag = data.tag || "claude-done";
136
142
  } else if (data.type === "ask_user") {
@@ -147,7 +153,7 @@ self.addEventListener("push", function (event) {
147
153
  self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (clientList) {
148
154
  // Always show permission requests, questions, and errors
149
155
  // Only suppress "done" notifications when app is in foreground
150
- if (data.type !== "permission_request" && data.type !== "ask_user" && data.type !== "error") {
156
+ if (data.type !== "permission_request" && data.type !== "permission_reminder" && data.type !== "ask_user" && data.type !== "error") {
151
157
  for (var i = 0; i < clientList.length; i++) {
152
158
  if (clientList[i].focused || clientList[i].visibilityState === "visible") return;
153
159
  }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+
3
+ // Who a session's push notification (and its in-app reminder) goes to. The one
4
+ // rule behind every session-scoped push (permission request, elicitation,
5
+ // ask_user, response done, loop done, prompt reminders):
6
+ // - an owned session pushes to its owner only;
7
+ // - an ownerless session in single-user mode broadcasts (there is one person);
8
+ // - an ownerless session in multi-user mode pushes to the admins only. An
9
+ // admin can already read every ownerless session (canAccessSession admits
10
+ // only admins to one), so tool input in the payload crosses no visibility
11
+ // boundary. It is never a broadcast to every subscriber, and a session
12
+ // opened from a console session inherits that session's owner instead
13
+ // (lib/session-input.js), so it is rarely ownerless at all;
14
+ // - a mode that cannot be read counts as multi-user, the stricter mode.
15
+
16
+ var usersModule = require("./users");
17
+
18
+ function multiUserMode(isMultiUser) {
19
+ try {
20
+ return isMultiUser() !== false;
21
+ } catch (e) {
22
+ return true;
23
+ }
24
+ }
25
+
26
+ function defaultListAdmins() {
27
+ return usersModule.getAllUsers().filter(function (u) {
28
+ return u.role === "admin";
29
+ }).map(function (u) {
30
+ return u.id;
31
+ });
32
+ }
33
+
34
+ // The admin ids, or [] when the user store cannot be read: no audience beats a
35
+ // wider one.
36
+ function adminIds(listAdmins) {
37
+ try {
38
+ return (listAdmins || defaultListAdmins)() || [];
39
+ } catch (e) {
40
+ return [];
41
+ }
42
+ }
43
+
44
+ /**
45
+ * @param {?string} ownerId the session's owner, if any.
46
+ * @param {function(): boolean} [isMultiUser] the daemon's mode; defaults to the
47
+ * users store.
48
+ * @param {function(): string[]} [listAdmins] the admin user ids; defaults to
49
+ * the users store.
50
+ * @returns {{kind: "owner"|"admins"|"broadcast", userIds: string[]}} kind
51
+ * "broadcast" has no ids: it means every subscriber (single-user mode).
52
+ * "admins" with no ids reaches no one.
53
+ */
54
+ function audienceFor(ownerId, isMultiUser, listAdmins) {
55
+ if (ownerId) return { kind: "owner", userIds: [ownerId] };
56
+ if (multiUserMode(isMultiUser || usersModule.isMultiUser)) {
57
+ return { kind: "admins", userIds: adminIds(listAdmins) };
58
+ }
59
+ return { kind: "broadcast", userIds: [] };
60
+ }
61
+
62
+ /**
63
+ * @param {?object} pushModule the push module (sendPush, sendPushToUser).
64
+ * @param {?string} ownerId the session's owner, if any.
65
+ * @param {object} payload the push payload.
66
+ * @param {function(): boolean} [isMultiUser] see audienceFor.
67
+ * @param {function(): string[]} [listAdmins] see audienceFor.
68
+ * @returns {"owner"|"admins"|"broadcast"|"none"} where the push went.
69
+ */
70
+ function pushForSession(pushModule, ownerId, payload, isMultiUser, listAdmins) {
71
+ if (!pushModule) return "none";
72
+ var audience = audienceFor(ownerId, isMultiUser, listAdmins);
73
+ if (audience.kind === "broadcast") {
74
+ pushModule.sendPush(payload);
75
+ return "broadcast";
76
+ }
77
+ if (typeof pushModule.sendPushToUser !== "function" || !audience.userIds.length) return "none";
78
+ audience.userIds.forEach(function (id) {
79
+ pushModule.sendPushToUser(id, payload);
80
+ });
81
+ return audience.kind;
82
+ }
83
+
84
+ module.exports = { audienceFor: audienceFor, pushForSession: pushForSession };
package/lib/push.js CHANGED
@@ -3,6 +3,7 @@ var fs = require("fs");
3
3
  var path = require("path");
4
4
  var config = require("./config");
5
5
  var store = require("./store");
6
+ var { categoryOfPush } = require("./notification-prefs");
6
7
 
7
8
  function loadOrCreateVapidKeys() {
8
9
  var dir = config.CONFIG_DIR;
@@ -23,7 +24,17 @@ function loadOrCreateVapidKeys() {
23
24
  return keys;
24
25
  }
25
26
 
26
- function initPush() {
27
+ /**
28
+ * @param {object} [opts]
29
+ * @param {{allows: function(?string, string, ?string): boolean}} [opts.prefs]
30
+ * the per-user notification preferences (lib/notification-prefs.js). A push a
31
+ * user has muted is not sent to that user's subscriptions; this is the one
32
+ * place push is filtered, so a muted type never reaches the phone whichever
33
+ * caller raised it.
34
+ */
35
+ function initPush(opts) {
36
+ var prefs = opts && opts.prefs ? opts.prefs : null;
37
+
27
38
  var keys = loadOrCreateVapidKeys();
28
39
 
29
40
  var vapidDetails = {
@@ -116,9 +127,20 @@ function initPush() {
116
127
  save();
117
128
  }
118
129
 
130
+ // One journal line per decision: identifiers and the type only, never the
131
+ // title or body (they carry tool input and response text).
132
+ function wanted(sub, payload) {
133
+ var category = categoryOfPush(payload);
134
+ var userId = sub._userId || null;
135
+ var allowed = !prefs || prefs.allows(userId, "push", category);
136
+ console.log("[push] " + (allowed ? "sending" : "muted") + " type=" + payload.type + " category=" + (category || "none") + " user=" + (userId || "default"));
137
+ return allowed;
138
+ }
139
+
119
140
  function sendPush(payload) {
120
141
  var json = JSON.stringify(payload);
121
142
  subscriptions.forEach(function (sub, endpoint) {
143
+ if (!wanted(sub, payload)) return;
122
144
  webpush.sendNotification(sub, json, { vapidDetails: vapidDetails })
123
145
  .then(function () {})
124
146
  .catch(function (err) {
@@ -135,6 +157,7 @@ function initPush() {
135
157
  var json = JSON.stringify(payload);
136
158
  subscriptions.forEach(function (sub, endpoint) {
137
159
  if (sub._userId !== userId) return;
160
+ if (!wanted(sub, payload)) return;
138
161
  webpush.sendNotification(sub, json, { vapidDetails: vapidDetails })
139
162
  .then(function () {})
140
163
  .catch(function (err) {
package/lib/sdk-bridge.js CHANGED
@@ -3,6 +3,7 @@ var path = require("path");
3
3
  var execSync = require("child_process").execSync;
4
4
  var execFileSync = require("child_process").execFileSync;
5
5
  var usersModule = require("./users");
6
+ var { pushForSession } = require("./push-audience");
6
7
  var { getCodexConfig } = require("./codex-defaults");
7
8
  var { isAutoApprovableSegment } = require("./bash-auto-approve");
8
9
  var { splitShellSegments, hasUnapprovableShellSyntax, attachSkillDiscovery, discoverSkillsWithMeta, mergeSkillsWithMeta } = require("./sdk-skill-discovery");
@@ -16,6 +17,7 @@ var { promptsFor } = require("./prompt-registry");
16
17
  var { toolApprovalKind } = require("./prompt-kinds");
17
18
  var sessionActivity = require("./session-activity");
18
19
  var sessionReclaim = require("./session-reclaim");
20
+ var usageStore = require("./usage-store");
19
21
  var { withPromptLabel } = require("./prompt-label");
20
22
  var { isAgentDispatchTool } = require("./agent-dispatch-tool");
21
23
  var permissionSummary = require("./permission-summary");
@@ -28,6 +30,7 @@ var { buildVendorRegistryMessage, recordInstallState } = require("./vendor-regis
28
30
  var { authRequiredFacts } = require("./vendor-auth");
29
31
  var { bumpLastActivity } = require("./activity-clock");
30
32
  var { logField } = require("./log-field");
33
+ var { debugLog } = require("./debug-log");
31
34
  var { checkPermissionMode } = require("./permission-mode-policy");
32
35
  var { reserveNameOnRevival } = require("./session-name-holder");
33
36
  var { createAiTitleRefresher } = require("./session-ai-title");
@@ -704,6 +707,7 @@ function createSDKBridge(opts) {
704
707
  _idleReaperTimer = setInterval(function () {
705
708
  var now = Date.now();
706
709
  var skippedForPrompt = [];
710
+ var skippedForKeepAlive = [];
707
711
  sm.sessions.forEach(function (session) {
708
712
  if (session.destroying) return;
709
713
 
@@ -744,6 +748,16 @@ function createSDKBridge(opts) {
744
748
  if (!session.queryInstance) return;
745
749
  if (session.singleTurn) return;
746
750
 
751
+ // Operator-set keep-alive: a coordinator that idles waiting on other
752
+ // sessions' messages emits nothing, so its silence is not evidence it
753
+ // is abandoned. Only the operator unpinning it (or memory pressure,
754
+ // lib/memory-shed.js, which does not read this flag) ends it.
755
+ if (session.keepAlive) {
756
+ skippedForKeepAlive.push(logField(session.localId)
757
+ + ":idle=" + Math.round((now - (session.lastActivityAt || 0)) / 60000) + "min");
758
+ return;
759
+ }
760
+
747
761
  // A session with an open prompt (its own, or a background agent's) is
748
762
  // waiting on the operator, not idle: an agent blocked on a prompt
749
763
  // emits no stream events, so the activity clock cannot tell. Ending
@@ -783,6 +797,11 @@ function createSDKBridge(opts) {
783
797
  }
784
798
  }
785
799
  });
800
+ if (skippedForKeepAlive.length) {
801
+ debugLog("[sdk-bridge] Idle reaper: skipped " + skippedForKeepAlive.length
802
+ + " keep-alive session(s): project=" + logField(slug)
803
+ + " sessions=" + skippedForKeepAlive.join(","));
804
+ }
786
805
  // One line per sweep, so "a session with an open prompt is never reaped"
787
806
  // can be read from the journal rather than inferred from its absence.
788
807
  if (skippedForPrompt.length) {
@@ -874,12 +893,8 @@ function createSDKBridge(opts) {
874
893
  body: withPromptLabel(opened.label, request.message || "Waiting for your response"),
875
894
  tag: "claude-elicitation",
876
895
  };
877
- // Route to session owner only — body carries MCP message text.
878
- if (session.ownerId && pushModule.sendPushToUser) {
879
- pushModule.sendPushToUser(session.ownerId, _elicitPayload);
880
- } else {
881
- pushModule.sendPush(_elicitPayload);
882
- }
896
+ // Body carries MCP message text: owner only, never a blind broadcast.
897
+ pushForSession(pushModule, session.ownerId, _elicitPayload);
883
898
  }
884
899
 
885
900
  return opened.answer;
@@ -1185,12 +1200,9 @@ function createSDKBridge(opts) {
1185
1200
  title: agentPrefix + permissionPushTitle(toolName, input),
1186
1201
  body: withPromptLabel(opened.label, permissionPushBody(toolName, input)),
1187
1202
  };
1188
- // Route to session owner only — body carries tool name and input (may contain paths/code).
1189
- if (session.ownerId && pushModule.sendPushToUser) {
1190
- pushModule.sendPushToUser(session.ownerId, _permPayload);
1191
- } else {
1192
- pushModule.sendPush(_permPayload);
1193
- }
1203
+ // Body carries tool name and input (may contain paths/code): owner only,
1204
+ // never a blind broadcast.
1205
+ pushForSession(pushModule, session.ownerId, _permPayload);
1194
1206
  }
1195
1207
 
1196
1208
  return opened.answer;
@@ -1435,6 +1447,9 @@ function createSDKBridge(opts) {
1435
1447
  sm.broadcastSessionList();
1436
1448
  }
1437
1449
  } finally {
1450
+ // Unguarded on purpose: our process is gone even if a newer query replaced it,
1451
+ // so this session can no longer confirm account usage.
1452
+ usageStore.endProcess(usageStore.usageVendorFor(session, adapter), session.localId, myQueryInstance);
1438
1453
  // Close the SDK query to terminate the underlying claude child process.
1439
1454
  // Without this, the process stays alive indefinitely (single-user mode).
1440
1455
  // Only clean up if the session still references OUR resources.
@@ -1,15 +1,30 @@
1
1
  var usersModule = require("./users");
2
+ var { pushForSession } = require("./push-audience");
2
3
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
3
4
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
4
5
  var { promptsFor } = require("./prompt-registry");
5
6
  var sessionActivity = require("./session-activity");
6
7
  var yokeRegistry = require("./yoke").registry;
8
+ var usageStore = require("./usage-store");
9
+
7
10
  var { authRequiredFacts } = require("./vendor-auth");
8
11
  var sessionReclaim = require("./session-reclaim");
9
12
  var { withPromptLabel } = require("./prompt-label");
10
13
  var { isAgentDispatchTool } = require("./agent-dispatch-tool");
11
14
  var { bumpLastActivity } = require("./activity-clock");
12
15
 
16
+ // Only the Claude CLI is known to report rate limits on change alone; for any
17
+ // other vendor the absence of an event says nothing about the value.
18
+ function confirmsUsageByResult(vendor) {
19
+ return vendor === "claude";
20
+ }
21
+
22
+ // Only a successful result counts as confirmation: a failed or interrupted turn
23
+ // is weak evidence that the CLI saw a fresh rate-limit response.
24
+ function isSuccessfulResult(parsed) {
25
+ return !!parsed && parsed.subtype === "success";
26
+ }
27
+
13
28
  // Source names of the activity tokens an agent with the activityTokens
14
29
  // trait holds for its own tool and thinking blocks.
15
30
  var TOOL_ACTIVITY_SOURCE = "agent-tool";
@@ -22,6 +37,20 @@ function sessionHasTrait(session, trait) {
22
37
  return yokeRegistry.traitOf(session.vendor, trait);
23
38
  }
24
39
 
40
+ function formatTokens(n) {
41
+ return n >= 1000 ? Math.round(n / 1000) + "k" : String(n);
42
+ }
43
+
44
+ function compactionNoticeText(ev) {
45
+ var text = "Context compacted (" + (ev.trigger === "manual" ? "manual" : "automatic") + ")";
46
+ if (typeof ev.preTokens === "number" && typeof ev.postTokens === "number") {
47
+ text += ": " + formatTokens(ev.preTokens) + " to " + formatTokens(ev.postTokens) + " tokens";
48
+ } else if (typeof ev.preTokens === "number") {
49
+ text += ": was " + formatTokens(ev.preTokens) + " tokens";
50
+ }
51
+ return text + ".";
52
+ }
53
+
25
54
  function attachMessageProcessor(ctx) {
26
55
  var sm = ctx.sm;
27
56
  var send = ctx.send;
@@ -138,6 +167,20 @@ function attachMessageProcessor(ctx) {
138
167
  // rather than either fully retiring session.isProcessing (too large a diff
139
168
  // for this pass) or leaving this specific site unconditionally wrong (the
140
169
  // one residual this task exists to fix).
170
+ // A turn's 'result' is the boundary after which no tool call of that turn can
171
+ // still be running; only a tracked background agent outlives it. A tool call
172
+ // that never got its tool_result (denied, or cut off in a query that stays
173
+ // open across turns) left a current-generation token that nothing else
174
+ // releases before the next query, and the re-derivation below then reported
175
+ // an idle session as running a turn on every surface that reads the flag.
176
+ function releaseTurnActivity(session) {
177
+ var live = session.activeTaskToolIds || {};
178
+ var sources = sessionActivity.listActiveSources(session);
179
+ for (var i = 0; i < sources.length; i++) {
180
+ if (!live[sources[i].token]) releaseActivity(session, sources[i].token);
181
+ }
182
+ }
183
+
141
184
  function setIsProcessingFromRegistry(session) {
142
185
  session.isProcessing = sessionActivity.isSessionActive(session);
143
186
  }
@@ -315,7 +358,7 @@ function attachMessageProcessor(ctx) {
315
358
  }
316
359
  if (parsed.model) {
317
360
  sm.currentModel = sm.currentModel || sm._savedDefaultModel || parsed.model;
318
- var initVendor = session.vendor || (adapter && adapter.vendor) || "claude";
361
+ var initVendor = usageStore.usageVendorFor(session, adapter);
319
362
  send({
320
363
  type: "model_info",
321
364
  model: sm.currentModel,
@@ -511,12 +554,8 @@ function attachMessageProcessor(ctx) {
511
554
  body: withPromptLabel(promptsFor(sm).labelFor(session, block.id), q ? q.question : "Waiting for your response"),
512
555
  tag: "claude-ask",
513
556
  };
514
- // Route to session owner only — content carries prompt text.
515
- if (session.ownerId && pushModule.sendPushToUser) {
516
- pushModule.sendPushToUser(session.ownerId, _askPayload);
517
- } else {
518
- pushModule.sendPush(_askPayload);
519
- }
557
+ // Content carries prompt text: owner only, never a blind broadcast.
558
+ pushForSession(pushModule, session.ownerId, _askPayload);
520
559
  }
521
560
  } else if (block && block.type === "thinking") {
522
561
  var duration = block.startTime ? (Date.now() - block.startTime) / 1000 : 0;
@@ -639,6 +678,7 @@ function attachMessageProcessor(ctx) {
639
678
  // bump, which already covers the harder case of abort/interrupt ending
640
679
  // the stream before 'result' is ever reached at all).
641
680
  if (sessionHasTrait(session, "activityTokens")) releaseAllAgentActivity(session);
681
+ releaseTurnActivity(session);
642
682
  // Turn boundary: the turn's own prompts, of every kind, end here; a
643
683
  // tracked sub-agent keeps its own (the registry decides which).
644
684
  promptsFor(sm).endTurn(session);
@@ -649,6 +689,12 @@ function attachMessageProcessor(ctx) {
649
689
  if (parsed.cost && parsed.cost > 0) {
650
690
  session.rateLimitResetsAt = null;
651
691
  }
692
+ // The Claude CLI reports rate limits only when they change, so a turn that
693
+ // completes without a new event is the evidence the value still holds.
694
+ var resultVendor = usageStore.usageVendorFor(session, adapter);
695
+ if (confirmsUsageByResult(resultVendor) && isSuccessfulResult(parsed)) {
696
+ usageStore.confirm(resultVendor, { sessionLocalId: session.localId, processKey: session.queryInstance });
697
+ }
652
698
  console.log("[sdk-bridge] result handler: project " + slug + " session " + session.localId + " cost=" + parsed.cost + " rateLimitResetsAt=" + session.rateLimitResetsAt);
653
699
 
654
700
  // Handle SDK execution errors: show the error to the user instead of
@@ -748,12 +794,8 @@ function attachMessageProcessor(ctx) {
748
794
  body: _donePreviewText || "Response ready",
749
795
  tag: "claude-done",
750
796
  };
751
- // Route to session owner only — body carries response preview text.
752
- if (session.ownerId && pushModule.sendPushToUser) {
753
- pushModule.sendPushToUser(session.ownerId, _donePayload);
754
- } else {
755
- pushModule.sendPush(_donePayload);
756
- }
797
+ // Body carries response preview text: owner only, never a blind broadcast.
798
+ pushForSession(pushModule, session.ownerId, _donePayload);
757
799
  }
758
800
 
759
801
  var _nm = getNotificationsModule();
@@ -805,6 +847,13 @@ function attachMessageProcessor(ctx) {
805
847
  }
806
848
  session.compacting = parsed.status === "compacting";
807
849
 
850
+ } else if (parsed.yokeType === "compact_boundary") {
851
+ // The vendor finished compacting this session's context. Recorded as a
852
+ // system notice so the operator, and anyone replaying the session, can
853
+ // see when it happened. Deliberately not a lastActivityAt bump: a
854
+ // compaction is the vendor's housekeeping, not operator or agent work.
855
+ sendAndRecord(session, { type: "system_info", text: compactionNoticeText(parsed) });
856
+
808
857
  } else if (parsed.yokeType === "task_started") {
809
858
  var parentId = parsed.parentToolId;
810
859
  if (parentId) {
@@ -911,7 +960,16 @@ function attachMessageProcessor(ctx) {
911
960
 
912
961
  } else if (parsed.yokeType === "rate_limit") {
913
962
  var info = parsed.rateLimitInfo;
914
- console.log("[sdk-bridge] rate_limit_event for session " + session.localId + ": status=" + info.status + " resetsAt=" + info.resetsAt + " isUsingOverage=" + info.isUsingOverage + " isProcessing=" + session.isProcessing);
963
+ console.log("[sdk-bridge] rate_limit_event for session " + session.localId + ": status=" + info.status + " rateLimitType=" + info.rateLimitType + " utilization=" + info.utilization + " resetsAt=" + info.resetsAt + " isUsingOverage=" + info.isUsingOverage + " isProcessing=" + session.isProcessing);
964
+
965
+ // Retain the last value per (vendor, bucket) for the --usage verb. Every
966
+ // event is recorded, not only warning/rejected ones.
967
+ var usageVendor = usageStore.usageVendorFor(session, adapter);
968
+ usageStore.record(usageVendor, info, {
969
+ source: parsed.rateLimitSource,
970
+ sessionLocalId: session.localId,
971
+ processKey: confirmsUsageByResult(usageVendor) ? session.queryInstance : null,
972
+ });
915
973
 
916
974
  // Broadcast reset time for top-bar usage link. This is a project-wide
917
975
  // broadcast (not sendAndRecord), but still stamp localId so a client