@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.
- package/bin/cli.js +12 -1
- package/lib/build-sha.json +2 -2
- package/lib/cli/arg-validation.js +1 -1
- package/lib/cli/ipc-subcommands.js +26 -0
- package/lib/daemon.js +20 -0
- package/lib/notification-prefs.js +255 -0
- package/lib/project-loop.js +3 -6
- package/lib/project-notifications.js +176 -34
- package/lib/project-sessions.js +28 -0
- package/lib/prompt-registry.js +18 -0
- package/lib/prompt-reminders.js +277 -0
- package/lib/public/css/input.css +93 -0
- package/lib/public/css/menus.css +22 -0
- package/lib/public/css/server-settings.css +24 -0
- package/lib/public/css/sidebar.css +17 -0
- package/lib/public/index.html +3 -0
- package/lib/public/modules/app-header.js +2 -0
- package/lib/public/modules/app-messages.js +6 -2
- package/lib/public/modules/app-notifications.js +29 -3
- package/lib/public/modules/app-rate-limit.js +12 -6
- package/lib/public/modules/app-rendering.js +16 -3
- package/lib/public/modules/collapsible-text.js +77 -0
- package/lib/public/modules/keep-alive.js +66 -0
- package/lib/public/modules/notification-prefs.js +151 -0
- package/lib/public/modules/prompt-reminders-setting.js +13 -0
- package/lib/public/modules/sidebar-mobile.js +8 -0
- package/lib/public/modules/sidebar-sessions.js +27 -0
- package/lib/public/sw.js +7 -1
- package/lib/push-audience.js +84 -0
- package/lib/push.js +24 -1
- package/lib/sdk-bridge.js +27 -12
- package/lib/sdk-message-processor.js +72 -14
- package/lib/sender-ref.js +3 -0
- package/lib/server.js +46 -2
- package/lib/session-input.js +7 -1
- package/lib/sessions.js +27 -0
- package/lib/usage-store.js +381 -0
- package/lib/ws-schema.js +6 -0
- package/lib/yoke/adapters/claude.js +10 -0
- package/lib/yoke/adapters/codex.js +5 -1
- package/package.json +1 -1
package/lib/sender-ref.js
CHANGED
|
@@ -94,6 +94,9 @@ function resolve(getProject, ref) {
|
|
|
94
94
|
// restart, so it can prove later that a console id still names this session.
|
|
95
95
|
cliSessionId: found.cliSessionId || null,
|
|
96
96
|
name: name,
|
|
97
|
+
// The console's own record of who owns the sending session; lets a session
|
|
98
|
+
// it opens inherit the owner.
|
|
99
|
+
ownerId: found.ownerId || null,
|
|
97
100
|
};
|
|
98
101
|
}
|
|
99
102
|
|
package/lib/server.js
CHANGED
|
@@ -372,11 +372,15 @@ function createServer(opts) {
|
|
|
372
372
|
projectAccess: projectAccess,
|
|
373
373
|
});
|
|
374
374
|
|
|
375
|
+
// --- Notification preferences (per user, on the server) ---
|
|
376
|
+
// Created before push so push can filter where it is sent.
|
|
377
|
+
var _prefsStore = require("./notification-prefs").createPrefsStore();
|
|
378
|
+
|
|
375
379
|
// --- Push module (global) ---
|
|
376
380
|
var pushModule = null;
|
|
377
381
|
try {
|
|
378
382
|
var { initPush } = require("./push");
|
|
379
|
-
pushModule = initPush();
|
|
383
|
+
pushModule = initPush({ prefs: _prefsStore });
|
|
380
384
|
} catch (e) {}
|
|
381
385
|
|
|
382
386
|
// --- Notifications module (global singleton, shared by all projects) ---
|
|
@@ -384,9 +388,37 @@ function createServer(opts) {
|
|
|
384
388
|
var _globalNotifications = _attachNotifications({
|
|
385
389
|
broadcastAll: function (msg) { broadcastAll(msg); },
|
|
386
390
|
sendToUser: function (userId, msg) { sendToUser(userId, msg); },
|
|
391
|
+
broadcastPerViewer: function (buildMsg) { broadcastPerViewer(buildMsg); },
|
|
387
392
|
pushModule: pushModule,
|
|
388
|
-
|
|
393
|
+
prefsStore: _prefsStore,
|
|
394
|
+
isMultiUser: users.isMultiUser,
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
// Reminders for prompts nobody has answered (lib/prompt-reminders.js): a
|
|
398
|
+
// sweep over every project's sessions and their prompt registries.
|
|
399
|
+
var { promptsFor: _promptsFor } = require("./prompt-registry");
|
|
400
|
+
var _promptReminders = require("./prompt-reminders").createPromptReminders({
|
|
401
|
+
notifications: _globalNotifications,
|
|
402
|
+
push: pushModule,
|
|
403
|
+
isMultiUser: users.isMultiUser,
|
|
404
|
+
getConfig: function () {
|
|
405
|
+
var cfg = require("./config").loadConfig();
|
|
406
|
+
return cfg ? cfg.promptReminders : null;
|
|
407
|
+
},
|
|
408
|
+
listSessions: function () {
|
|
409
|
+
var held = [];
|
|
410
|
+
projects.forEach(function (ctx, slug) {
|
|
411
|
+
if (!ctx.sm || !ctx.sm.sessions) return;
|
|
412
|
+
var prompts = _promptsFor(ctx.sm);
|
|
413
|
+
var projectName = ctx.getTitle ? ctx.getTitle() : slug;
|
|
414
|
+
ctx.sm.sessions.forEach(function (session) {
|
|
415
|
+
held.push({ slug: slug, project: projectName, session: session, prompts: prompts });
|
|
416
|
+
});
|
|
417
|
+
});
|
|
418
|
+
return held;
|
|
419
|
+
},
|
|
389
420
|
});
|
|
421
|
+
_promptReminders.start();
|
|
390
422
|
|
|
391
423
|
// --- External trigger watcher (global singleton) ---
|
|
392
424
|
// Watches ~/.clagentic/external-triggers/ for JSON files dropped by external
|
|
@@ -1749,6 +1781,17 @@ function createServer(opts) {
|
|
|
1749
1781
|
});
|
|
1750
1782
|
}
|
|
1751
1783
|
|
|
1784
|
+
// One message per live ws, built from that connection's user id.
|
|
1785
|
+
function broadcastPerViewer(buildMsg) {
|
|
1786
|
+
projects.forEach(function (ctx) {
|
|
1787
|
+
if (typeof ctx.forEachClient !== "function") return;
|
|
1788
|
+
ctx.forEachClient(function (ws) {
|
|
1789
|
+
if (ws.readyState !== 1) return;
|
|
1790
|
+
ws.send(JSON.stringify(buildMsg(ws._clagenticUser ? ws._clagenticUser.id : null)));
|
|
1791
|
+
});
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1752
1795
|
// True if the user has any live ws across any project.
|
|
1753
1796
|
function isUserOnline(userId) {
|
|
1754
1797
|
if (!userId) return false;
|
|
@@ -1773,6 +1816,7 @@ function createServer(opts) {
|
|
|
1773
1816
|
}
|
|
1774
1817
|
|
|
1775
1818
|
function destroyAll() {
|
|
1819
|
+
_promptReminders.stop();
|
|
1776
1820
|
_externalTrigger.stopWatcher();
|
|
1777
1821
|
_scheduledInput.stop();
|
|
1778
1822
|
var shutdowns = [];
|
package/lib/session-input.js
CHANGED
|
@@ -703,7 +703,13 @@ function createSessionInput(deps) {
|
|
|
703
703
|
// createSession emits already carries it (not the project default). It is
|
|
704
704
|
// saved with the session just below: a follow-up from a person, a resume
|
|
705
705
|
// and a restart all keep it.
|
|
706
|
-
|
|
706
|
+
// A session opened from a console session the daemon identified belongs to
|
|
707
|
+
// that session's owner, so its prompts push to a person who can read it. A
|
|
708
|
+
// declared or undeclared sender is a claim, never an inheritance.
|
|
709
|
+
var openedBy = senderRef.resolve(getProject, { project: req.senderProject, sessionId: req.senderSessionId });
|
|
710
|
+
var created = Object.assign({}, kind.options, { permissionMode: openMode.mode });
|
|
711
|
+
if (openedBy && openedBy.ownerId) created.ownerId = openedBy.ownerId;
|
|
712
|
+
var sess = sm.createSession(created);
|
|
707
713
|
var label = req.triggerId ? " — " + String(req.triggerId).substring(0, 12) : "";
|
|
708
714
|
sess.title = (req.contextNote || "External trigger") + label;
|
|
709
715
|
if (req.cwd) sess.cwd = req.cwd;
|
package/lib/sessions.js
CHANGED
|
@@ -163,6 +163,13 @@ function createSessionManager(opts) {
|
|
|
163
163
|
if (session.vendor) metaObj.vendor = session.vendor;
|
|
164
164
|
if (session.sessionVisibility) metaObj.sessionVisibility = session.sessionVisibility;
|
|
165
165
|
if (session.bookmarked) metaObj.bookmarked = true;
|
|
166
|
+
// Operator-set keep-alive: the idle reaper skips the session (see
|
|
167
|
+
// startIdleReaper in lib/sdk-bridge.js). Written only when on, so a
|
|
168
|
+
// session that was never pinned carries no field.
|
|
169
|
+
if (session.keepAlive) metaObj.keepAlive = true;
|
|
170
|
+
// Operator switch: no reminders for this session's unanswered prompts
|
|
171
|
+
// (lib/prompt-reminders.js). Written only when off.
|
|
172
|
+
if (session.promptRemindersOff) metaObj.promptRemindersOff = true;
|
|
166
173
|
if (typeof session.favoriteOrder === "number") metaObj.favoriteOrder = session.favoriteOrder;
|
|
167
174
|
if (session.lastRewindUuid) metaObj.lastRewindUuid = session.lastRewindUuid;
|
|
168
175
|
if (session.agentName) metaObj.agentName = session.agentName;
|
|
@@ -814,6 +821,8 @@ function createSessionManager(opts) {
|
|
|
814
821
|
if (m.ownerId) session.ownerId = m.ownerId;
|
|
815
822
|
session.sessionVisibility = m.sessionVisibility || "shared";
|
|
816
823
|
session.bookmarked = !!m.bookmarked;
|
|
824
|
+
session.keepAlive = m.keepAlive === true;
|
|
825
|
+
session.promptRemindersOff = m.promptRemindersOff === true;
|
|
817
826
|
session.favoriteOrder = typeof m.favoriteOrder === "number" ? m.favoriteOrder : null;
|
|
818
827
|
// lr-f36626: restore the durable AUTO-RESUME marker across a daemon
|
|
819
828
|
// restart — see buildMetaLine's write side for why this must persist.
|
|
@@ -885,6 +894,8 @@ function createSessionManager(opts) {
|
|
|
885
894
|
ownerId: s.ownerId || null,
|
|
886
895
|
sessionVisibility: s.sessionVisibility || "shared",
|
|
887
896
|
bookmarked: !!s.bookmarked,
|
|
897
|
+
keepAlive: !!s.keepAlive,
|
|
898
|
+
promptRemindersOff: !!s.promptRemindersOff,
|
|
888
899
|
favoriteOrder: typeof s.favoriteOrder === "number" ? s.favoriteOrder : null,
|
|
889
900
|
unread: unreadMap[s.localId] || 0,
|
|
890
901
|
vendor: s.vendor || null,
|
|
@@ -1890,6 +1901,22 @@ function createSessionManager(opts) {
|
|
|
1890
1901
|
broadcastSessionList();
|
|
1891
1902
|
return { ok: true };
|
|
1892
1903
|
},
|
|
1904
|
+
setSessionKeepAlive: function (localId, keepAlive) {
|
|
1905
|
+
var session = sessions.get(localId);
|
|
1906
|
+
if (!session) return { error: "Session not found" };
|
|
1907
|
+
session.keepAlive = !!keepAlive;
|
|
1908
|
+
saveSessionFile(session);
|
|
1909
|
+
broadcastSessionList();
|
|
1910
|
+
return { ok: true };
|
|
1911
|
+
},
|
|
1912
|
+
setSessionPromptReminders: function (localId, enabled) {
|
|
1913
|
+
var session = sessions.get(localId);
|
|
1914
|
+
if (!session) return { error: "Session not found" };
|
|
1915
|
+
session.promptRemindersOff = !enabled;
|
|
1916
|
+
saveSessionFile(session);
|
|
1917
|
+
broadcastSessionList();
|
|
1918
|
+
return { ok: true };
|
|
1919
|
+
},
|
|
1893
1920
|
reorderBookmarkedSessions: function (sourceId, targetId, insertBefore) {
|
|
1894
1921
|
var source = sessions.get(sourceId);
|
|
1895
1922
|
var target = sessions.get(targetId);
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
// usage-store.js — last-seen account usage per (vendor, bucket).
|
|
2
|
+
//
|
|
3
|
+
// Vendor-neutral: a bucket is whatever string the adapter reports as
|
|
4
|
+
// rateLimitType, kept verbatim. Records live in memory and, when a file is
|
|
5
|
+
// configured (the daemon's shared instance), are persisted to JSON and reloaded
|
|
6
|
+
// at start. Freshness is computed at read time and never stored, so a reloaded
|
|
7
|
+
// record reads stale/expired honestly and is never re-stamped as fresh.
|
|
8
|
+
//
|
|
9
|
+
// Two timestamps per bucket: observedAt (the last reported event, i.e. the last
|
|
10
|
+
// time the value changed) and confirmedAt (the last evidence the value still
|
|
11
|
+
// holds). Some adapters report only on change, so a steady value goes silent
|
|
12
|
+
// while sessions keep running; confirm() lets the caller say "a session whose
|
|
13
|
+
// process has already reported just completed a turn without a change". Age and
|
|
14
|
+
// state are computed from the newer of the two.
|
|
15
|
+
|
|
16
|
+
var fsDefault = require("fs");
|
|
17
|
+
var pathMod = require("path");
|
|
18
|
+
var { readConsoleEnv } = require("./env-compat");
|
|
19
|
+
|
|
20
|
+
var DEFAULT_STALE_SECONDS = 30 * 60;
|
|
21
|
+
// Buckets listed as "unknown" for every registered vendor even when unseen.
|
|
22
|
+
var ALWAYS_LISTED_BUCKETS = ["five_hour", "seven_day"];
|
|
23
|
+
var DEFAULT_THROTTLE_MS = 5000;
|
|
24
|
+
var STORE_FILE_NAME = "usage-store.json";
|
|
25
|
+
var STORE_FILE_VERSION = 1;
|
|
26
|
+
|
|
27
|
+
function staleAfterSeconds(env) {
|
|
28
|
+
var raw = readConsoleEnv("CLAGENTIC_CONSOLE_USAGE_STALE_SECONDS", { env: env });
|
|
29
|
+
var n = raw === undefined ? NaN : Number(raw);
|
|
30
|
+
return isFinite(n) && n > 0 ? n : DEFAULT_STALE_SECONDS;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function toIso(ms) {
|
|
34
|
+
return new Date(ms).toISOString();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isIsoOrNull(v) {
|
|
38
|
+
return v === null || (typeof v === "string" && isFinite(Date.parse(v)));
|
|
39
|
+
}
|
|
40
|
+
function isStrOrNull(v) {
|
|
41
|
+
return v === null || typeof v === "string";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Vendor and bucket names come from persisted JSON and CLI output, so they are
|
|
45
|
+
// untrusted. Internal maps have no prototype (a name like "constructor" or
|
|
46
|
+
// "toString" cannot resolve to an inherited member) and "__proto__" is refused
|
|
47
|
+
// outright because the snapshot output objects are plain.
|
|
48
|
+
function newMap() {
|
|
49
|
+
return Object.create(null);
|
|
50
|
+
}
|
|
51
|
+
function isUnsafeKey(k) {
|
|
52
|
+
return k === "__proto__";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Returns a normalised record, or null when the stored one is malformed.
|
|
56
|
+
function validRecord(r) {
|
|
57
|
+
if (!r || typeof r !== "object" || Array.isArray(r)) return null;
|
|
58
|
+
if (typeof r.observedAt !== "string" || !isFinite(Date.parse(r.observedAt))) return null;
|
|
59
|
+
if (!(r.utilization === null || (typeof r.utilization === "number" && isFinite(r.utilization)))) return null;
|
|
60
|
+
if (!isIsoOrNull(r.utilizationObservedAt) || !isIsoOrNull(r.resetsAt)) return null;
|
|
61
|
+
if (!isStrOrNull(r.status) || !isStrOrNull(r.source) || !isStrOrNull(r.sessionLocalId)) return null;
|
|
62
|
+
// confirmedAt is absent in files written before confirmation existed.
|
|
63
|
+
var confirmedAt = r.confirmedAt === undefined ? null : r.confirmedAt;
|
|
64
|
+
if (!isIsoOrNull(confirmedAt)) return null;
|
|
65
|
+
return {
|
|
66
|
+
utilization: r.utilization,
|
|
67
|
+
utilizationObservedAt: r.utilizationObservedAt,
|
|
68
|
+
resetsAt: r.resetsAt,
|
|
69
|
+
status: r.status,
|
|
70
|
+
observedAt: r.observedAt,
|
|
71
|
+
confirmedAt: confirmedAt,
|
|
72
|
+
source: r.source,
|
|
73
|
+
sessionLocalId: r.sessionLocalId,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function newestMs(rec) {
|
|
78
|
+
var o = Date.parse(rec.observedAt);
|
|
79
|
+
var c = rec.confirmedAt ? Date.parse(rec.confirmedAt) : -Infinity;
|
|
80
|
+
return Math.max(o, c);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// opts (all optional; no file means no I/O):
|
|
84
|
+
// file persistence path
|
|
85
|
+
// fs fs implementation (tests)
|
|
86
|
+
// log function(message), defaults to console.log
|
|
87
|
+
// throttleMs minimum spacing between writes
|
|
88
|
+
function createUsageStore(opts) {
|
|
89
|
+
opts = opts || {};
|
|
90
|
+
var file = opts.file || null;
|
|
91
|
+
var fsImpl = opts.fs || fsDefault;
|
|
92
|
+
var log = opts.log || function (m) { console.log(m); };
|
|
93
|
+
var throttleMs = opts.throttleMs !== undefined ? opts.throttleMs : DEFAULT_THROTTLE_MS;
|
|
94
|
+
var timer = null;
|
|
95
|
+
var dirty = false;
|
|
96
|
+
// vendor -> bucket -> record
|
|
97
|
+
var records = newMap();
|
|
98
|
+
// vendor -> session id -> { proc, bucket }: the bucket the session's current
|
|
99
|
+
// process last reported. In memory only; a process never outlives the daemon.
|
|
100
|
+
var emitters = newMap();
|
|
101
|
+
// vendors that produced any evidence since this store was created (not
|
|
102
|
+
// counting records loaded from the file)
|
|
103
|
+
var seenThisRun = newMap();
|
|
104
|
+
|
|
105
|
+
// dirty is cleared only once both the tmp write and the rename succeed, so a
|
|
106
|
+
// transient failure (ENOSPC, EACCES) leaves the change pending. A failed
|
|
107
|
+
// write schedules a retry through the same throttle timer, which bounds
|
|
108
|
+
// retries to one per throttle interval.
|
|
109
|
+
function writeNow() {
|
|
110
|
+
if (!file) return;
|
|
111
|
+
var tmp = file + ".tmp";
|
|
112
|
+
try {
|
|
113
|
+
fsImpl.mkdirSync(pathMod.dirname(file), { recursive: true, mode: 0o700 });
|
|
114
|
+
fsImpl.writeFileSync(tmp, JSON.stringify({ version: STORE_FILE_VERSION, vendors: records }), { mode: 0o600 });
|
|
115
|
+
fsImpl.renameSync(tmp, file);
|
|
116
|
+
dirty = false;
|
|
117
|
+
} catch (e) {
|
|
118
|
+
log("[usage-store] Clagentic: Console could not persist usage to " + file + ": " + (e && e.message ? e.message : e));
|
|
119
|
+
try {
|
|
120
|
+
if (typeof fsImpl.unlinkSync === "function") fsImpl.unlinkSync(tmp);
|
|
121
|
+
} catch (u) {
|
|
122
|
+
if (!u || u.code !== "ENOENT") {
|
|
123
|
+
log("[usage-store] Clagentic: Console could not remove " + tmp + ": " + (u && u.message ? u.message : u));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
armTimer();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function armTimer() {
|
|
131
|
+
if (timer) return;
|
|
132
|
+
timer = setTimeout(function () {
|
|
133
|
+
timer = null;
|
|
134
|
+
if (dirty) writeNow();
|
|
135
|
+
}, throttleMs);
|
|
136
|
+
if (timer && typeof timer.unref === "function") timer.unref();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function schedulePersist() {
|
|
140
|
+
if (!file) return;
|
|
141
|
+
dirty = true;
|
|
142
|
+
armTimer();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Write any pending change immediately (daemon shutdown, tests).
|
|
146
|
+
function flush() {
|
|
147
|
+
if (timer) { clearTimeout(timer); timer = null; }
|
|
148
|
+
if (dirty) writeNow();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Replace in-memory records from the file. A missing file is quiet; an
|
|
152
|
+
// unparseable or wrong-shape file is logged and set aside as <file>.corrupt.
|
|
153
|
+
function load() {
|
|
154
|
+
if (!file) return;
|
|
155
|
+
var raw;
|
|
156
|
+
try {
|
|
157
|
+
raw = fsImpl.readFileSync(file, "utf8");
|
|
158
|
+
} catch (e) {
|
|
159
|
+
if (e && e.code === "ENOENT") return;
|
|
160
|
+
log("[usage-store] Clagentic: Console could not read " + file + ", starting empty: " + (e && e.message ? e.message : e));
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
var parsed;
|
|
164
|
+
try { parsed = JSON.parse(raw); } catch (e) { parsed = undefined; }
|
|
165
|
+
var ok = parsed && typeof parsed === "object" && !Array.isArray(parsed) &&
|
|
166
|
+
parsed.vendors && typeof parsed.vendors === "object" && !Array.isArray(parsed.vendors);
|
|
167
|
+
if (!ok) {
|
|
168
|
+
var aside = file + ".corrupt";
|
|
169
|
+
var note = "";
|
|
170
|
+
try { fsImpl.renameSync(file, aside); note = "; kept as " + aside; } catch (e) { note = "; could not move it aside"; }
|
|
171
|
+
log("[usage-store] Clagentic: Console usage file " + file + " is unreadable or has the wrong shape, starting empty" + note);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
var loaded = newMap();
|
|
175
|
+
var dropped = 0;
|
|
176
|
+
Object.keys(parsed.vendors).forEach(function (vendor) {
|
|
177
|
+
var buckets = parsed.vendors[vendor];
|
|
178
|
+
if (isUnsafeKey(vendor)) { dropped++; return; }
|
|
179
|
+
if (!buckets || typeof buckets !== "object" || Array.isArray(buckets)) { dropped++; return; }
|
|
180
|
+
Object.keys(buckets).forEach(function (b) {
|
|
181
|
+
var rec = isUnsafeKey(b) ? null : validRecord(buckets[b]);
|
|
182
|
+
if (!rec) { dropped++; return; }
|
|
183
|
+
(loaded[vendor] || (loaded[vendor] = newMap()))[b] = rec;
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
records = loaded;
|
|
187
|
+
if (dropped > 0) log("[usage-store] Clagentic: Console dropped " + dropped + " malformed usage record(s) from " + file);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// info.resetsAt is epoch seconds, as the adapters report it.
|
|
191
|
+
//
|
|
192
|
+
// meta.processKey (optional) identifies the session's current process; with
|
|
193
|
+
// meta.sessionLocalId it registers the session as an emitter that confirm()
|
|
194
|
+
// may later act for.
|
|
195
|
+
function record(vendor, info, meta) {
|
|
196
|
+
if (!vendor || !info) return;
|
|
197
|
+
if (!info.rateLimitType) {
|
|
198
|
+
log("[usage-store] Clagentic: Console dropped a rate-limit event with no rateLimitType (vendor=" + vendor + " status=" + (info.status || "none") + ")");
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
if (isUnsafeKey(vendor) || isUnsafeKey(info.rateLimitType)) return;
|
|
202
|
+
meta = meta || {};
|
|
203
|
+
var now = meta.now !== undefined ? meta.now : Date.now();
|
|
204
|
+
var util = typeof info.utilization === "number" ? info.utilization : null;
|
|
205
|
+
var resetsAt = info.resetsAt ? toIso(info.resetsAt * 1000) : null;
|
|
206
|
+
var byBucket = records[vendor] || (records[vendor] = newMap());
|
|
207
|
+
var prev = byBucket[info.rateLimitType];
|
|
208
|
+
var utilizationObservedAt = util !== null ? toIso(now) : null;
|
|
209
|
+
|
|
210
|
+
// An event without a utilization must not erase a known one for the same
|
|
211
|
+
// reset window; the old value keeps its own observation time.
|
|
212
|
+
if (util === null && prev && prev.utilization !== null && prev.resetsAt === resetsAt) {
|
|
213
|
+
util = prev.utilization;
|
|
214
|
+
utilizationObservedAt = prev.utilizationObservedAt;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
byBucket[info.rateLimitType] = {
|
|
218
|
+
utilization: util,
|
|
219
|
+
utilizationObservedAt: utilizationObservedAt,
|
|
220
|
+
resetsAt: resetsAt,
|
|
221
|
+
status: info.status || null,
|
|
222
|
+
observedAt: toIso(now),
|
|
223
|
+
confirmedAt: null,
|
|
224
|
+
source: meta.source || null,
|
|
225
|
+
sessionLocalId: meta.sessionLocalId || null,
|
|
226
|
+
};
|
|
227
|
+
seenThisRun[vendor] = true;
|
|
228
|
+
if (meta.processKey && meta.sessionLocalId && !isUnsafeKey(String(meta.sessionLocalId))) {
|
|
229
|
+
var bySession = emitters[vendor] || (emitters[vendor] = newMap());
|
|
230
|
+
bySession[String(meta.sessionLocalId)] = { proc: meta.processKey, bucket: info.rateLimitType };
|
|
231
|
+
}
|
|
232
|
+
schedulePersist();
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// A session whose current process has reported at least once completed a
|
|
236
|
+
// turn: the bucket that process last reported still holds. Returns true when
|
|
237
|
+
// a bucket was confirmed. A session that has not reported, or whose process
|
|
238
|
+
// changed, confirms nothing.
|
|
239
|
+
function confirm(vendor, who, meta) {
|
|
240
|
+
if (!vendor || !who || !who.sessionLocalId || isUnsafeKey(vendor) || isUnsafeKey(String(who.sessionLocalId))) return false;
|
|
241
|
+
var entry = emitters[vendor] && emitters[vendor][String(who.sessionLocalId)];
|
|
242
|
+
if (!entry || entry.proc !== who.processKey) return false;
|
|
243
|
+
var rec = records[vendor] && records[vendor][entry.bucket];
|
|
244
|
+
if (!rec) return false;
|
|
245
|
+
var now = meta && meta.now !== undefined ? meta.now : Date.now();
|
|
246
|
+
rec.confirmedAt = toIso(now);
|
|
247
|
+
seenThisRun[vendor] = true;
|
|
248
|
+
schedulePersist();
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// The session's process ended or restarted. With processKey, only that
|
|
253
|
+
// process's entry is cleared, so a newer process of the same session keeps its own.
|
|
254
|
+
function endProcess(vendor, sessionLocalId, processKey) {
|
|
255
|
+
var by = emitters[vendor];
|
|
256
|
+
if (!by || sessionLocalId === undefined || sessionLocalId === null) return;
|
|
257
|
+
var id = String(sessionLocalId);
|
|
258
|
+
if (!by[id]) return;
|
|
259
|
+
if (processKey !== undefined && by[id].proc !== processKey) return;
|
|
260
|
+
delete by[id];
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function view(rec, now, staleSec) {
|
|
264
|
+
if (!rec) {
|
|
265
|
+
return { utilization: null, resetsAt: null, status: null, observedAt: null, confirmedAt: null, ageSeconds: null, state: "unknown", source: null, utilizationConfirmed: false };
|
|
266
|
+
}
|
|
267
|
+
var newest = newestMs(rec);
|
|
268
|
+
var ageSeconds = Math.max(0, Math.round((now - newest) / 1000));
|
|
269
|
+
var state = "fresh";
|
|
270
|
+
if (rec.resetsAt && Date.parse(rec.resetsAt) <= now) state = "expired";
|
|
271
|
+
else if (ageSeconds > staleSec) state = "stale";
|
|
272
|
+
// The adapter's change test covers utilization, so a confirmation also
|
|
273
|
+
// confirms it, but only when the latest event itself carried the value.
|
|
274
|
+
var utilizationConfirmed = rec.utilization !== null && rec.confirmedAt !== null &&
|
|
275
|
+
rec.utilizationObservedAt === rec.observedAt;
|
|
276
|
+
var out = {
|
|
277
|
+
utilization: rec.utilization,
|
|
278
|
+
utilizationObservedAt: rec.utilizationObservedAt,
|
|
279
|
+
utilizationConfirmed: utilizationConfirmed,
|
|
280
|
+
resetsAt: rec.resetsAt,
|
|
281
|
+
status: rec.status,
|
|
282
|
+
observedAt: rec.observedAt,
|
|
283
|
+
confirmedAt: rec.confirmedAt,
|
|
284
|
+
ageSeconds: ageSeconds,
|
|
285
|
+
state: state,
|
|
286
|
+
source: rec.source,
|
|
287
|
+
};
|
|
288
|
+
if (state === "stale") {
|
|
289
|
+
out.staleReason = "no rate-limit change reported and no confirming session result since " + toIso(newest);
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function freshness(vendor, seen, now, staleSec) {
|
|
295
|
+
var lastEvent = null;
|
|
296
|
+
var lastConfirmed = null;
|
|
297
|
+
Object.keys(seen).forEach(function (b) {
|
|
298
|
+
var o = Date.parse(seen[b].observedAt);
|
|
299
|
+
if (lastEvent === null || o > lastEvent) lastEvent = o;
|
|
300
|
+
if (seen[b].confirmedAt) {
|
|
301
|
+
var c = Date.parse(seen[b].confirmedAt);
|
|
302
|
+
if (lastConfirmed === null || c > lastConfirmed) lastConfirmed = c;
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
var active = emitters[vendor] ? Object.keys(emitters[vendor]).length : 0;
|
|
306
|
+
var newest = lastEvent === null ? null : Math.max(lastEvent, lastConfirmed === null ? -Infinity : lastConfirmed);
|
|
307
|
+
var reason;
|
|
308
|
+
if (!seenThisRun[vendor]) reason = "no_event_since_start";
|
|
309
|
+
else if (newest !== null && (now - newest) / 1000 > staleSec && active === 0) reason = "no_active_session";
|
|
310
|
+
else if (lastConfirmed !== null && lastConfirmed > lastEvent) reason = "confirmed_by_result";
|
|
311
|
+
else reason = "event";
|
|
312
|
+
return {
|
|
313
|
+
lastEventAt: lastEvent === null ? null : toIso(lastEvent),
|
|
314
|
+
lastConfirmedAt: lastConfirmed === null ? null : toIso(lastConfirmed),
|
|
315
|
+
activeSessions: active,
|
|
316
|
+
reason: reason,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// opts.vendorIds: registered vendors, always listed with the standard buckets.
|
|
321
|
+
function snapshot(opts) {
|
|
322
|
+
opts = opts || {};
|
|
323
|
+
var now = opts.now !== undefined ? opts.now : Date.now();
|
|
324
|
+
var staleSec = opts.staleSeconds !== undefined ? opts.staleSeconds : staleAfterSeconds(opts.env);
|
|
325
|
+
var ids = Object.keys(records);
|
|
326
|
+
(opts.vendorIds || []).forEach(function (id) { if (ids.indexOf(id) === -1) ids.push(id); });
|
|
327
|
+
var vendors = {};
|
|
328
|
+
ids.forEach(function (vendor) {
|
|
329
|
+
var seen = records[vendor] || newMap();
|
|
330
|
+
var names = ALWAYS_LISTED_BUCKETS.slice();
|
|
331
|
+
Object.keys(seen).forEach(function (b) { if (names.indexOf(b) === -1) names.push(b); });
|
|
332
|
+
var buckets = {};
|
|
333
|
+
names.forEach(function (b) { buckets[b] = view(seen[b], now, staleSec); });
|
|
334
|
+
vendors[vendor] = { freshness: freshness(vendor, seen, now, staleSec), buckets: buckets };
|
|
335
|
+
});
|
|
336
|
+
return { generatedAt: toIso(now), staleAfterSeconds: staleSec, vendors: vendors };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function reset() { records = newMap(); emitters = newMap(); seenThisRun = newMap(); }
|
|
340
|
+
|
|
341
|
+
return { record: record, confirm: confirm, endProcess: endProcess, snapshot: snapshot, reset: reset, load: load, flush: flush };
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// The shared instance does no file I/O until the daemon gives it a path.
|
|
345
|
+
var sharedOpts = {};
|
|
346
|
+
var shared = createUsageStore(sharedOpts);
|
|
347
|
+
|
|
348
|
+
// Returns a persistent store bound to `file`, loaded from it, and installs it
|
|
349
|
+
// as the shared instance's backend.
|
|
350
|
+
function enablePersistence(file, extra) {
|
|
351
|
+
var store = createUsageStore(Object.assign({ file: file }, extra || {}));
|
|
352
|
+
store.load();
|
|
353
|
+
shared = store;
|
|
354
|
+
module.exports.record = store.record;
|
|
355
|
+
module.exports.confirm = store.confirm;
|
|
356
|
+
module.exports.endProcess = store.endProcess;
|
|
357
|
+
module.exports.snapshot = store.snapshot;
|
|
358
|
+
module.exports.reset = store.reset;
|
|
359
|
+
module.exports.flush = store.flush;
|
|
360
|
+
return store;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// The vendor a session's usage is keyed under. One definition so record,
|
|
364
|
+
// confirm and endProcess can never disagree about it.
|
|
365
|
+
function usageVendorFor(session, adapter) {
|
|
366
|
+
return session.vendor || (adapter && adapter.vendor) || "claude";
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
module.exports = {
|
|
370
|
+
createUsageStore: createUsageStore,
|
|
371
|
+
usageVendorFor: usageVendorFor,
|
|
372
|
+
record: shared.record,
|
|
373
|
+
confirm: shared.confirm,
|
|
374
|
+
endProcess: shared.endProcess,
|
|
375
|
+
snapshot: shared.snapshot,
|
|
376
|
+
reset: shared.reset,
|
|
377
|
+
flush: shared.flush,
|
|
378
|
+
enablePersistence: enablePersistence,
|
|
379
|
+
STORE_FILE_NAME: STORE_FILE_NAME,
|
|
380
|
+
DEFAULT_STALE_SECONDS: DEFAULT_STALE_SECONDS,
|
|
381
|
+
};
|
package/lib/ws-schema.js
CHANGED
|
@@ -21,6 +21,7 @@ var schema = {
|
|
|
21
21
|
"delete_session": { direction: "c2s", handler: "lib/project-sessions.js", description: "Delete a session by ID" },
|
|
22
22
|
"rename_session": { direction: "c2s", handler: "lib/project-sessions.js", description: "Rename a session" },
|
|
23
23
|
"set_session_bookmark": { direction: "c2s", handler: "lib/project-sessions.js", description: "Bookmark or unbookmark a session in the sidebar" },
|
|
24
|
+
"set_session_keep_alive": { direction: "c2s", handler: "lib/project-sessions.js", description: "Pin or unpin a session so the idle reaper does not end it (memory pressure still can)" },
|
|
24
25
|
"reorder_session_bookmarks": { direction: "c2s", handler: "lib/project-sessions.js", description: "Reorder favorited sessions within the favorites area" },
|
|
25
26
|
"bulk_delete_sessions": { direction: "c2s", handler: "lib/project-sessions.js", description: "Delete a group of sessions at once" },
|
|
26
27
|
"mark_cross_project_read": { direction: "c2s", handler: "lib/project-sessions.js", description: "Clear the cross-project unread badge for a project slug without switching to it (lr-13c047)" },
|
|
@@ -77,6 +78,7 @@ var schema = {
|
|
|
77
78
|
// every real sendAndRecord(session, { type: "..." }) call site — these 4
|
|
78
79
|
// were live, sent types with no documentation entry.
|
|
79
80
|
"plan_content": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Plan-mode content for the plan card" },
|
|
81
|
+
"system_info": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Plain system notice in the timeline (e.g. a context compaction marker)" },
|
|
80
82
|
"sdk_notification": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Informational notification surfaced from the vendor SDK" },
|
|
81
83
|
"diagnostic": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Session-scoped diagnostic toast (settings preflight, memory shedding, adapter warnings). A message with refresh:true updates the entry the client already holds for the same source and action, and is ignored when the client holds none. A message with persistent:true is a state, not a notice: its toast has no timer and a repeat replaces the earlier card of the same source" },
|
|
82
84
|
|
|
@@ -237,6 +239,10 @@ var schema = {
|
|
|
237
239
|
// -----------------------------------------------------------------------
|
|
238
240
|
// Push notifications
|
|
239
241
|
// -----------------------------------------------------------------------
|
|
242
|
+
"set_session_prompt_reminders": { direction: "c2s", handler: "lib/project-sessions.js", description: "Turn reminders for a session's unanswered prompts on or off: {sessionId, enabled}" },
|
|
243
|
+
"notification_prefs": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "The user's per-type notification preferences ({prefs: {banner|sound|push: {category: boolean}}, preset, known, categories, presets}); sent on connect and to every connection of the user after a change" },
|
|
244
|
+
"notification_prefs_set": { direction: "c2s", handler: "lib/project-notifications.js", description: "Change the user's notification preferences by preset name or per-cell patch: {preset?, surfaces?}" },
|
|
245
|
+
"notification_prefs_migrate": { direction: "c2s", handler: "lib/project-notifications.js", description: "Seed the user's server-side preferences from what the browser held, once: {legacy: {sound}}" },
|
|
240
246
|
"push_subscribe": { direction: "c2s", handler: "lib/project-sessions.js", description: "Register a push notification subscription" },
|
|
241
247
|
|
|
242
248
|
// -----------------------------------------------------------------------
|
|
@@ -178,6 +178,15 @@ function flattenEvent(raw) {
|
|
|
178
178
|
base.status = raw.status;
|
|
179
179
|
return base;
|
|
180
180
|
}
|
|
181
|
+
if (raw.subtype === "compact_boundary") {
|
|
182
|
+
var cm = raw.compact_metadata || {};
|
|
183
|
+
base.yokeType = "compact_boundary";
|
|
184
|
+
base.trigger = cm.trigger === "manual" ? "manual" : "auto";
|
|
185
|
+
base.preTokens = typeof cm.pre_tokens === "number" ? cm.pre_tokens : null;
|
|
186
|
+
base.postTokens = typeof cm.post_tokens === "number" ? cm.post_tokens : null;
|
|
187
|
+
base.durationMs = typeof cm.duration_ms === "number" ? cm.duration_ms : null;
|
|
188
|
+
return base;
|
|
189
|
+
}
|
|
181
190
|
if (raw.subtype === "task_started") {
|
|
182
191
|
base.yokeType = "task_started";
|
|
183
192
|
base.parentToolId = raw.tool_use_id;
|
|
@@ -279,6 +288,7 @@ function flattenEvent(raw) {
|
|
|
279
288
|
if (raw.type === "rate_limit_event" && raw.rate_limit_info) {
|
|
280
289
|
base.yokeType = "rate_limit";
|
|
281
290
|
base.rateLimitInfo = raw.rate_limit_info;
|
|
291
|
+
base.rateLimitSource = "claude-cli:rate_limit_event";
|
|
282
292
|
return base;
|
|
283
293
|
}
|
|
284
294
|
|
|
@@ -296,12 +296,16 @@ function flattenEvent(notification, state) {
|
|
|
296
296
|
for (var wi = 0; wi < windows.length; wi++) {
|
|
297
297
|
var w = rl[windows[wi].key];
|
|
298
298
|
if (!w) continue;
|
|
299
|
-
|
|
299
|
+
// An absent usedPercent is unknown, not 0%: a fabricated zero would
|
|
300
|
+
// read as "plenty of headroom" to every consumer.
|
|
301
|
+
var hasUsed = typeof w.usedPercent === "number";
|
|
302
|
+
var utilization = hasUsed ? w.usedPercent / 100 : null;
|
|
300
303
|
var status = "allowed";
|
|
301
304
|
if (w.usedPercent >= 100) status = "rejected";
|
|
302
305
|
else if (w.usedPercent >= 80) status = "allowed_warning";
|
|
303
306
|
events.push({
|
|
304
307
|
yokeType: "rate_limit",
|
|
308
|
+
rateLimitSource: "codex:rateLimits",
|
|
305
309
|
rateLimitInfo: {
|
|
306
310
|
status: status,
|
|
307
311
|
resetsAt: w.resetsAt || null,
|
package/package.json
CHANGED