@clagentic/console 1.12.0-beta.1 → 1.12.0-beta.2

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 (82) hide show
  1. package/README.md +1 -0
  2. package/bin/cli.js +2 -1
  3. package/lib/build-changes.js +8 -2
  4. package/lib/build-sha.json +2 -2
  5. package/lib/build-update-offer.js +31 -7
  6. package/lib/claude-settings-env.js +142 -0
  7. package/lib/cli/duration.js +27 -0
  8. package/lib/cli/schedule-input-subcommands.js +1 -22
  9. package/lib/cli/session-subcommands.js +38 -7
  10. package/lib/daemon.js +6 -0
  11. package/lib/notification-prefs.js +2 -0
  12. package/lib/notify/core.js +175 -0
  13. package/lib/notify/index.js +31 -0
  14. package/lib/notify/live-prompts.js +36 -0
  15. package/lib/notify/payload.js +63 -0
  16. package/lib/notify/target.js +5 -0
  17. package/lib/notify/type-registry.js +64 -0
  18. package/lib/notify/types.js +20 -0
  19. package/lib/open-sockets.js +27 -0
  20. package/lib/outbound-access.js +74 -0
  21. package/lib/outbound-entry.js +109 -0
  22. package/lib/outbound-ledger.js +306 -0
  23. package/lib/outbound-query.js +153 -0
  24. package/lib/pending-prompts.js +31 -16
  25. package/lib/project-connection.js +40 -1
  26. package/lib/project-filesystem.js +20 -5
  27. package/lib/project-http.js +9 -1
  28. package/lib/project-loop.js +22 -7
  29. package/lib/project-notifications.js +54 -32
  30. package/lib/project-prompt-responses.js +1 -1
  31. package/lib/project-sessions.js +2 -1
  32. package/lib/project.js +15 -1
  33. package/lib/prompt-registry.js +74 -24
  34. package/lib/prompt-reminders.js +38 -33
  35. package/lib/prompt-source.js +43 -8
  36. package/lib/public/app.js +1 -0
  37. package/lib/public/css/diagnostics.css +28 -0
  38. package/lib/public/css/home-hub.css +12 -0
  39. package/lib/public/css/icon-strip.css +9 -0
  40. package/lib/public/css/mobile-nav.css +11 -0
  41. package/lib/public/css/sidebar.css +7 -0
  42. package/lib/public/index.html +3 -0
  43. package/lib/public/modules/activity-state.js +20 -4
  44. package/lib/public/modules/app-connection.js +22 -5
  45. package/lib/public/modules/app-notifications.js +47 -48
  46. package/lib/public/modules/app-projects.js +3 -1
  47. package/lib/public/modules/app-rendering.js +10 -0
  48. package/lib/public/modules/build-update-sessions.js +81 -0
  49. package/lib/public/modules/diagnostics.js +9 -2
  50. package/lib/public/modules/env-shadow-notice.js +34 -0
  51. package/lib/public/modules/notify-client.js +153 -0
  52. package/lib/public/modules/project-settings.js +5 -0
  53. package/lib/public/modules/prompt-state.js +3 -3
  54. package/lib/public/modules/prompts.js +1 -1
  55. package/lib/public/modules/server-settings.js +3 -0
  56. package/lib/public/modules/terminal-links.js +175 -0
  57. package/lib/public/modules/terminal.js +19 -103
  58. package/lib/public/notify-sw-logic.js +300 -0
  59. package/lib/public/notify-target.js +97 -0
  60. package/lib/public/sw.js +15 -68
  61. package/lib/push.js +63 -19
  62. package/lib/runtime-env.js +1 -0
  63. package/lib/sdk-bridge.js +62 -30
  64. package/lib/sdk-message-processor.js +78 -37
  65. package/lib/server.js +34 -2
  66. package/lib/session-directory.js +6 -4
  67. package/lib/session-input-ipc.js +11 -1
  68. package/lib/session-input.js +89 -14
  69. package/lib/session-liveness.js +53 -0
  70. package/lib/session-reclaim.js +37 -2
  71. package/lib/sessions.js +31 -4
  72. package/lib/usage-store.js +29 -7
  73. package/lib/vendor-auth.js +33 -2
  74. package/lib/ws-schema.js +6 -1
  75. package/lib/yoke/adapters/claude-vendor.js +11 -1
  76. package/lib/yoke/adapters/claude.js +7 -0
  77. package/lib/yoke/auth-checks.js +17 -2
  78. package/lib/yoke/index.js +21 -3
  79. package/lib/yoke/provider-credentials.js +24 -0
  80. package/lib/yoke/registry.js +8 -1
  81. package/package.json +2 -2
  82. package/scripts/check-test-count.js +14 -0
@@ -0,0 +1,306 @@
1
+ // outbound-ledger.js - the sender-side record of what a session sent out.
2
+ //
3
+ // Every open-session and send-input request (CLI verb or file drop) leaves one
4
+ // line here, written by the sender: the delivery, or the refusal or failure.
5
+ // The target's own history holds a delivered prompt too, but nothing there lists
6
+ // what one sender sent, and a refused request leaves no trace at all.
7
+ //
8
+ // Location: <console data dir>/outbound/ (0700; files 0600)
9
+ // sessions/<project>/<sender>.jsonl a sender the console identified from its
10
+ // own records (senderKind "extracted")
11
+ // unattributed/declared/<name>.jsonl a sender that only named itself (--from)
12
+ // unattributed/undeclared/undeclared.jsonl a sender that named nobody
13
+ // Unattributed lines are self-reported and unverified; they are kept apart so a
14
+ // reader never mistakes one for an identified sender.
15
+ //
16
+ // One JSON object per line, appended with a single write; a reader skips a line
17
+ // it cannot parse. The line holds the full prompt text, so the files are as
18
+ // private as the session history and are removed after the retention period
19
+ // (default 30 days, daemon.json "outboundRetentionDays"; 0 turns the ledger off).
20
+ //
21
+ // Writing never fails the request it describes: record() logs and returns.
22
+
23
+ var crypto = require("crypto");
24
+ var fs = require("fs");
25
+ var path = require("path");
26
+
27
+ var FORMAT_VERSION = 1;
28
+ var DIR_NAME = "outbound";
29
+ var DEFAULT_RETENTION_DAYS = 30;
30
+ var MAX_RETENTION_DAYS = 3650;
31
+ var DAY_MS = 24 * 60 * 60 * 1000;
32
+ var PRUNE_INTERVAL_MS = 6 * 60 * 60 * 1000;
33
+
34
+ var SENDER_DIR = "sessions";
35
+ var UNATTRIBUTED_DIR = "unattributed";
36
+
37
+ // The retention in days a configured value means. A missing value is the
38
+ // default; anything that is not a whole number of days from 0 to 3650 is the
39
+ // default too, and { invalid: true } says so, so a typo is not silently kept.
40
+ function retentionDaysFrom(raw) {
41
+ if (raw === undefined || raw === null) return { days: DEFAULT_RETENTION_DAYS };
42
+ if (typeof raw === "number" && Number.isInteger(raw) && raw >= 0 && raw <= MAX_RETENTION_DAYS) return { days: raw };
43
+ return { days: DEFAULT_RETENTION_DAYS, invalid: true };
44
+ }
45
+
46
+ // A name that is safe as one path component. A value that is not a plain id is
47
+ // replaced by a hash of itself, so two different values never share a file and
48
+ // nothing a sender chose can name a path.
49
+ function segment(raw) {
50
+ var s = String(raw);
51
+ if (/^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/.test(s)) return s;
52
+ return "x-" + crypto.createHash("sha256").update(s).digest("hex").slice(0, 16);
53
+ }
54
+
55
+ // The file an entry belongs in, relative to the ledger root.
56
+ function relativePathFor(entry) {
57
+ var sender = entry.sender || {};
58
+ if (sender.attribution === "extracted" && sender.project && (sender.cliSessionId || sender.sessionId)) {
59
+ // The vendor session id survives a daemon restart; the console id is
60
+ // renumbered, so it names a sender only until the vendor has named it.
61
+ var key = sender.cliSessionId ? segment(sender.cliSessionId) : "console-" + segment(sender.sessionId);
62
+ return path.join(SENDER_DIR, segment(sender.project), key + ".jsonl");
63
+ }
64
+ if (sender.kind === "declared" && sender.name) {
65
+ return path.join(UNATTRIBUTED_DIR, "declared", segment(sender.name) + ".jsonl");
66
+ }
67
+ return path.join(UNATTRIBUTED_DIR, "undeclared", "undeclared.jsonl");
68
+ }
69
+
70
+ function parseLines(text) {
71
+ var out = [];
72
+ var lines = text.split("\n");
73
+ for (var i = 0; i < lines.length; i++) {
74
+ if (!lines[i]) continue;
75
+ try {
76
+ var obj = JSON.parse(lines[i]);
77
+ if (obj && typeof obj === "object" && !Array.isArray(obj)) out.push({ line: lines[i], entry: obj });
78
+ } catch (e) {
79
+ // A torn final line after a crash, or a damaged one: not readable, skipped.
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+
85
+ function tsOf(entry) {
86
+ var ms = typeof entry.ts === "string" ? Date.parse(entry.ts) : NaN;
87
+ return isFinite(ms) ? ms : null;
88
+ }
89
+
90
+ function errorText(e) {
91
+ return e && e.message ? e.message : String(e);
92
+ }
93
+
94
+ // A ledger path that is not there holds no entries; any other failure to read
95
+ // it (permissions, a file where a directory belongs, I/O) is an error the
96
+ // reader must report, never an empty list that looks like "nothing was sent".
97
+ function isAbsent(e) {
98
+ return !!e && e.code === "ENOENT";
99
+ }
100
+
101
+ function unreadable(file, e) {
102
+ var err = new Error("the outbound ledger cannot be read: " + file + " (" + ((e && e.code) || errorText(e)) + ")");
103
+ err.code = (e && e.code) || "EIO";
104
+ err.path = file;
105
+ return err;
106
+ }
107
+
108
+ // opts:
109
+ // getBaseDir() the console data directory (read at use)
110
+ // getRetentionDays() the configured value, or undefined (read at use, so a
111
+ // change in daemon.json applies without a restart)
112
+ // now() ms clock (default Date.now), for tests
113
+ // log console-like (default console)
114
+ function createOutboundLedger(opts) {
115
+ var getBaseDir = opts.getBaseDir;
116
+ var getRetentionDays = opts.getRetentionDays || function () { return undefined; };
117
+ var now = opts.now || Date.now;
118
+ var log = opts.log || console;
119
+ var timer = null;
120
+ var warnedInvalid = null;
121
+
122
+ function root() {
123
+ return path.join(getBaseDir(), DIR_NAME);
124
+ }
125
+
126
+ function retentionDays() {
127
+ var raw = getRetentionDays();
128
+ var r = retentionDaysFrom(raw);
129
+ if (r.invalid && warnedInvalid !== JSON.stringify(raw)) {
130
+ warnedInvalid = JSON.stringify(raw);
131
+ log.warn("[outbound-ledger] outboundRetentionDays must be a whole number of days from 0 to " + MAX_RETENTION_DAYS + "; using " + DEFAULT_RETENTION_DAYS);
132
+ }
133
+ return r.days;
134
+ }
135
+
136
+ // Appends one entry. Never throws: the request it describes is already
137
+ // decided, and a ledger that cannot be written must not change that.
138
+ function record(entry) {
139
+ try {
140
+ if (retentionDays() === 0) return false;
141
+ var file = path.join(root(), relativePathFor(entry));
142
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
143
+ fs.appendFileSync(file, JSON.stringify(entry) + "\n", { mode: 0o600 });
144
+ return true;
145
+ } catch (e) {
146
+ log.error("[outbound-ledger] could not write the entry:", errorText(e));
147
+ return false;
148
+ }
149
+ }
150
+
151
+ // The ledger files under a subdirectory: [{ file, dir }] (dir is the
152
+ // component under it, the project or the unattributed kind). A directory that
153
+ // is absent has none; one that cannot be read throws (see unreadable()).
154
+ function filesUnder(sub, onlyDir) {
155
+ var base = path.join(root(), sub);
156
+ var dirs;
157
+ try { dirs = fs.readdirSync(base); } catch (e) {
158
+ if (isAbsent(e)) return [];
159
+ throw unreadable(base, e);
160
+ }
161
+ var out = [];
162
+ dirs.forEach(function (d) {
163
+ if (onlyDir !== undefined && d !== onlyDir) return;
164
+ var names;
165
+ // Absent here means a prune removed the directory after the listing above.
166
+ try { names = fs.readdirSync(path.join(base, d)); } catch (e) {
167
+ if (isAbsent(e)) return;
168
+ throw unreadable(path.join(base, d), e);
169
+ }
170
+ names.forEach(function (n) {
171
+ if (n.endsWith(".jsonl")) out.push({ file: path.join(base, d, n), dir: d });
172
+ });
173
+ });
174
+ return out;
175
+ }
176
+
177
+ // Entries at or after sinceMs and within the retention, oldest first.
178
+ // A file last written before the cut-off holds nothing newer and is not read.
179
+ // Throws (see unreadable()) when a file that exists cannot be read.
180
+ function readFiles(files, sinceMs) {
181
+ var days = retentionDays();
182
+ if (days === 0) return [];
183
+ var cutoff = Math.max(typeof sinceMs === "number" ? sinceMs : 0, now() - days * DAY_MS);
184
+ var out = [];
185
+ files.forEach(function (f) {
186
+ var text;
187
+ try {
188
+ if (fs.statSync(f.file).mtimeMs < cutoff) return;
189
+ text = fs.readFileSync(f.file, "utf8");
190
+ } catch (e) {
191
+ // Absent: pruned between the listing and this read.
192
+ if (isAbsent(e)) return;
193
+ log.error("[outbound-ledger] could not read " + path.basename(f.file) + ":", errorText(e));
194
+ throw unreadable(f.file, e);
195
+ }
196
+ parseLines(text).forEach(function (l) {
197
+ var ts = tsOf(l.entry);
198
+ if (ts !== null && ts >= cutoff) out.push(l.entry);
199
+ });
200
+ });
201
+ out.sort(function (a, b) { return tsOf(a) - tsOf(b); });
202
+ return out;
203
+ }
204
+
205
+ // Entries of identified senders, optionally of one project.
206
+ function readAttributed(query) {
207
+ query = query || {};
208
+ var only = query.project === undefined ? undefined : segment(query.project);
209
+ return readFiles(filesUnder(SENDER_DIR, only), query.sinceMs);
210
+ }
211
+
212
+ // Entries of senders that only named themselves, or nobody.
213
+ function readUnattributed(query) {
214
+ query = query || {};
215
+ return readFiles(filesUnder(UNATTRIBUTED_DIR), query.sinceMs);
216
+ }
217
+
218
+ // Rewrites a file without its expired lines, through a temporary file and a
219
+ // rename; removes it when nothing is left. Returns the number of lines dropped.
220
+ function pruneFile(file, cutoff) {
221
+ var text = fs.readFileSync(file, "utf8");
222
+ var all = text.split("\n").filter(function (l) { return l; });
223
+ var kept = parseLines(text).filter(function (l) {
224
+ var ts = tsOf(l.entry);
225
+ return ts !== null && ts >= cutoff;
226
+ });
227
+ if (kept.length === all.length) return 0;
228
+ if (!kept.length) {
229
+ fs.unlinkSync(file);
230
+ return all.length;
231
+ }
232
+ var tmp = file + ".tmp";
233
+ fs.writeFileSync(tmp, kept.map(function (l) { return l.line; }).join("\n") + "\n", { mode: 0o600 });
234
+ fs.renameSync(tmp, file);
235
+ return all.length - kept.length;
236
+ }
237
+
238
+ // ENOTEMPTY (a file is still there) and ENOENT (already gone) are expected;
239
+ // anything else is logged once per path and errno.
240
+ var warnedRmdir = new Set();
241
+ function removeIfEmpty(dir) {
242
+ try { fs.rmdirSync(dir); } catch (e) {
243
+ if (e && (e.code === "ENOTEMPTY" || e.code === "ENOENT")) return;
244
+ var key = dir + "|" + (e && e.code);
245
+ if (warnedRmdir.has(key)) return;
246
+ warnedRmdir.add(key);
247
+ log.error("[outbound-ledger] could not remove the directory " + dir + " (" + ((e && e.code) || errorText(e)) + ")");
248
+ }
249
+ }
250
+
251
+ // Removes every entry older than the retention. Synchronous end to end, so no
252
+ // append interleaves with a rewrite. Returns { files, removed }.
253
+ function prune() {
254
+ var cutoff = now() - retentionDays() * DAY_MS;
255
+ var removed = 0;
256
+ var files = 0;
257
+ [SENDER_DIR, UNATTRIBUTED_DIR].forEach(function (sub) {
258
+ filesUnder(sub).forEach(function (f) {
259
+ try {
260
+ var n = pruneFile(f.file, cutoff);
261
+ if (n) { removed += n; files++; }
262
+ // An emptied directory is removed; one still holding files is left.
263
+ removeIfEmpty(path.dirname(f.file));
264
+ } catch (e) {
265
+ log.error("[outbound-ledger] could not prune " + path.basename(f.file) + ":", errorText(e));
266
+ }
267
+ });
268
+ });
269
+ if (removed) log.log("[outbound-ledger] pruned " + removed + " expired entr" + (removed === 1 ? "y" : "ies") + " from " + files + " file(s)");
270
+ return { files: files, removed: removed };
271
+ }
272
+
273
+ // Prunes now and then every few hours. The timer never keeps the process up.
274
+ function start() {
275
+ try { prune(); } catch (e) { log.error("[outbound-ledger] prune failed:", errorText(e)); }
276
+ if (timer) return;
277
+ timer = setInterval(function () {
278
+ try { prune(); } catch (e) { log.error("[outbound-ledger] prune failed:", errorText(e)); }
279
+ }, PRUNE_INTERVAL_MS);
280
+ if (typeof timer.unref === "function") timer.unref();
281
+ }
282
+
283
+ function stop() {
284
+ if (timer) clearInterval(timer);
285
+ timer = null;
286
+ }
287
+
288
+ return {
289
+ record: record,
290
+ readAttributed: readAttributed,
291
+ readUnattributed: readUnattributed,
292
+ prune: prune,
293
+ start: start,
294
+ stop: stop,
295
+ retentionDays: retentionDays,
296
+ };
297
+ }
298
+
299
+ module.exports = {
300
+ FORMAT_VERSION: FORMAT_VERSION,
301
+ DIR_NAME: DIR_NAME,
302
+ DEFAULT_RETENTION_DAYS: DEFAULT_RETENTION_DAYS,
303
+ MAX_RETENTION_DAYS: MAX_RETENTION_DAYS,
304
+ retentionDaysFrom: retentionDaysFrom,
305
+ createOutboundLedger: createOutboundLedger,
306
+ };
@@ -0,0 +1,153 @@
1
+ // outbound-query.js - the read side of the outbound ledger: what one session
2
+ // sent out through open-session and send-input, for the `list-outbound` verb.
3
+ //
4
+ // Read-only. Returns the outbound calls only (target, prompt, time, initiator,
5
+ // result), never any transcript content. A prompt is returned only when the
6
+ // caller may read the target session (lib/outbound-access.js); otherwise the
7
+ // entry carries its metadata, `prompt: null` and the reason it was withheld.
8
+ // For a target that runs as another OS user the text was never stored (the
9
+ // writer, lib/outbound-entry.js, withholds it), so the entry already carries
10
+ // promptWithheld, contextNoteWithheld and the reason as stored.
11
+
12
+ var { isSafeSessionId } = require("./session-id");
13
+ var { VERB } = require("./outbound-entry");
14
+
15
+ var KIND_TO_VERB = Object.freeze({ sent: VERB.SEND_INPUT, opens: VERB.OPEN_SESSION });
16
+ var KIND_OF_VERB = Object.freeze({ send_input: "sent", open_session: "opens" });
17
+
18
+ function refused(reason) {
19
+ return { ok: false, result: "refused", reason: reason };
20
+ }
21
+
22
+ // A ledger that cannot be read is an error result, not an empty list.
23
+ function unreadable(err) {
24
+ return { ok: false, result: "error", reason: err && err.message ? err.message : String(err), code: (err && err.code) || null };
25
+ }
26
+
27
+ function shape(entry, verdict) {
28
+ var out = {};
29
+ for (var k in entry) if (k !== "prompt" && k !== "formatVersion") out[k] = entry[k];
30
+ out.kind = KIND_OF_VERB[entry.verb] || null;
31
+ // The context note is message content the caller wrote alongside the prompt,
32
+ // so it is shown only when the prompt may be. The other free-text fields
33
+ // (reason, sender and target names, addresses) are console-made or are names
34
+ // and addresses, not message content.
35
+ if (!verdict.allowed && typeof entry.contextNote === "string") {
36
+ delete out.contextNote;
37
+ out.contextNoteWithheld = true;
38
+ }
39
+ if (typeof entry.prompt !== "string") {
40
+ out.prompt = null;
41
+ } else if (verdict.allowed) {
42
+ out.prompt = entry.prompt;
43
+ } else {
44
+ out.prompt = null;
45
+ out.promptWithheld = true;
46
+ out.promptWithheldReason = verdict.reason;
47
+ }
48
+ return out;
49
+ }
50
+
51
+ // deps:
52
+ // ledger lib/outbound-ledger.js createOutboundLedger() result
53
+ // access lib/outbound-access.js createOutboundAccess() result
54
+ // caller { user, authenticated } the principal behind this transport
55
+ function createOutboundQuery(deps) {
56
+ var ledger = deps.ledger;
57
+ var access = deps.access;
58
+ var caller = deps.caller;
59
+
60
+ function present(entries) {
61
+ return entries.map(function (e) { return shape(e, access.canReadPrompt(e, caller)); });
62
+ }
63
+
64
+ // req: { sessionId, projectSlug?, sinceMs?, kind? }
65
+ // sessionId the vendor's own session id of the sender (never a console id)
66
+ // sinceMs only entries at or after this time (epoch ms)
67
+ // kind "sent" (send-input) or "opens" (open-session)
68
+ function list(req) {
69
+ req = req || {};
70
+ if (typeof req.sessionId !== "string" || !isSafeSessionId(req.sessionId)) {
71
+ return refused("a session id is required and must be a plain id (letters, digits, _ and -)");
72
+ }
73
+ // A console id is renumbered at a daemon restart, so one number can name
74
+ // different sessions over the ledger's retention; it is never an identity.
75
+ if (/^[0-9]+$/.test(req.sessionId)) {
76
+ return refused("--session takes the vendor session id, not a console id: console ids are renumbered when the daemon restarts, so one can name different sessions over time. The vendor id is shown by list-sessions (sessionId).");
77
+ }
78
+ if (req.projectSlug !== undefined && (typeof req.projectSlug !== "string" || !req.projectSlug)) {
79
+ return refused("project must be a non-empty string");
80
+ }
81
+ if (req.sinceMs !== undefined && !(typeof req.sinceMs === "number" && isFinite(req.sinceMs))) {
82
+ return refused("since must be a time");
83
+ }
84
+ var verb = null;
85
+ if (req.kind !== undefined) {
86
+ verb = Object.prototype.hasOwnProperty.call(KIND_TO_VERB, req.kind) ? KIND_TO_VERB[req.kind] : null;
87
+ if (!verb) return refused("unknown kind " + JSON.stringify(String(req.kind).slice(0, 32)) + " (accepted: sent, opens)");
88
+ }
89
+
90
+ var days = ledger.retentionDays();
91
+ var base = { ok: true, result: "listed", retentionDays: days };
92
+ if (days === 0) {
93
+ return Object.assign(base, { count: 0, messages: [], unattributed: [], note: "the outbound ledger is turned off (outboundRetentionDays is 0)" });
94
+ }
95
+
96
+ var id = req.sessionId;
97
+ var mine;
98
+ try {
99
+ mine = ledger.readAttributed({ project: req.projectSlug, sinceMs: req.sinceMs }).filter(function (e) {
100
+ return (e.sender || {}).cliSessionId === id;
101
+ });
102
+ } catch (e) {
103
+ return unreadable(e);
104
+ }
105
+
106
+ // Vendor ids are unique, but a ledger written by hand or by an older
107
+ // writer could repeat one across projects; never merge those silently.
108
+ // A Set, not an object: a slug such as __proto__ must count as a key.
109
+ var projects = new Set();
110
+ mine.forEach(function (e) { projects.add(e.sender.project); });
111
+ var projectNames = Array.from(projects);
112
+ if (projectNames.length > 1) {
113
+ return {
114
+ ok: false,
115
+ result: "ambiguous",
116
+ reason: "the session id " + JSON.stringify(id) + " names a sender in " + projectNames.length + " projects; send again with --project",
117
+ projects: projectNames.sort(),
118
+ };
119
+ }
120
+
121
+ // The vendor ids this sender has used, to find calls that only named it.
122
+ var vendorIds = new Set([id]);
123
+ mine.forEach(function (e) { if (e.sender.cliSessionId) vendorIds.add(e.sender.cliSessionId); });
124
+
125
+ // Self-reported: a declared sender names the session it claims to be. Kept
126
+ // apart and labelled, never merged into the identified senders' list.
127
+ var claimed;
128
+ try {
129
+ claimed = ledger.readUnattributed({ sinceMs: req.sinceMs }).filter(function (e) {
130
+ return e.sender && typeof e.sender.fromSession === "string" && vendorIds.has(e.sender.fromSession);
131
+ });
132
+ } catch (e) {
133
+ return unreadable(e);
134
+ }
135
+
136
+ function wanted(e) { return !verb || e.verb === verb; }
137
+ var messages = mine.filter(wanted);
138
+ var unattributed = claimed.filter(wanted);
139
+
140
+ return Object.assign(base, {
141
+ session: { id: id, project: projectNames[0] || req.projectSlug || null },
142
+ count: messages.length,
143
+ messages: present(messages),
144
+ unattributedCount: unattributed.length,
145
+ unattributed: present(unattributed),
146
+ unattributedNote: "Calls whose sender only named itself (--from-session). The console cannot verify them; they are listed so they are not lost, not as this session's own calls.",
147
+ });
148
+ }
149
+
150
+ return { list: list };
151
+ }
152
+
153
+ module.exports = { createOutboundQuery: createOutboundQuery, KIND_TO_VERB: KIND_TO_VERB };
@@ -24,11 +24,9 @@ function ageSeconds(createdAt, now) {
24
24
  return Math.max(0, Math.floor((now - createdAt) / 1000));
25
25
  }
26
26
 
27
- // Returns [{ requestId, kind, tool, summary, ageSeconds }], oldest first;
28
- // empty when the session waits on nothing. Only operator-facing prompts count
29
- // (kind.journal), the ones a banner is raised for.
30
- function pendingPrompts(session, now) {
31
- var out = [];
27
+ // Calls visit(id, record, kind) for every operator-facing prompt (kind.journal,
28
+ // the ones a banner is raised for) a session holds in the registry's maps.
29
+ function eachPending(session, visit) {
32
30
  STORES.forEach(function (store) {
33
31
  var map = session && session[store];
34
32
  if (!map) return;
@@ -37,19 +35,36 @@ function pendingPrompts(session, now) {
37
35
  if (!record) return;
38
36
  var kind = promptKinds.kindOfRecord(record, store);
39
37
  if (!kind || !kind.journal) return;
40
- out.push({
41
- createdAt: typeof record.createdAt === "number" ? record.createdAt : 0,
42
- view: {
43
- requestId: id,
44
- kind: kind.name,
45
- tool: typeof record.toolName === "string" ? record.toolName : null,
46
- summary: TOOL_KINDS[kind.name] ? summarize(record.toolName, record.toolInput) : "",
47
- ageSeconds: ageSeconds(record.createdAt, now),
48
- },
49
- });
38
+ visit(id, record, kind);
39
+ });
40
+ });
41
+ }
42
+
43
+ // How many operator prompts the session waits on. Cheap: no summary is built,
44
+ // so the session list can ask it of every session on every broadcast.
45
+ function countPending(session) {
46
+ var n = 0;
47
+ eachPending(session, function () { n += 1; });
48
+ return n;
49
+ }
50
+
51
+ // Returns [{ requestId, kind, tool, summary, ageSeconds }], oldest first;
52
+ // empty when the session waits on nothing.
53
+ function pendingPrompts(session, now) {
54
+ var out = [];
55
+ eachPending(session, function (id, record, kind) {
56
+ out.push({
57
+ createdAt: typeof record.createdAt === "number" ? record.createdAt : 0,
58
+ view: {
59
+ requestId: id,
60
+ kind: kind.name,
61
+ tool: typeof record.toolName === "string" ? record.toolName : null,
62
+ summary: TOOL_KINDS[kind.name] ? summarize(record.toolName, record.toolInput) : "",
63
+ ageSeconds: ageSeconds(record.createdAt, now),
64
+ },
50
65
  });
51
66
  });
52
67
  return out.sort(function (a, b) { return a.createdAt - b.createdAt; }).map(function (e) { return e.view; });
53
68
  }
54
69
 
55
- module.exports = { pendingPrompts: pendingPrompts };
70
+ module.exports = { pendingPrompts: pendingPrompts, countPending: countPending };
@@ -5,11 +5,15 @@ var userPresence = require("./user-presence");
5
5
  var { authOf } = require("./project-access");
6
6
  var { getCodexConfig } = require("./codex-defaults");
7
7
  var { promptsFor } = require("./prompt-registry");
8
+ var { snapshotLivePrompts } = require("./notify/live-prompts");
8
9
  var { settingsMessage } = require("./permission-settings");
9
10
  var { effectiveSessionMode } = require("./sessions");
10
11
  var sessionReclaim = require("./session-reclaim");
11
12
  var clientBuildId = require("./client-build-id");
12
13
  var { buildVendorRegistryMessage } = require("./vendor-registry-message");
14
+ var { logField } = require("./log-field");
15
+ var { clientIdOf } = require("./prompt-source");
16
+ var openSockets = require("./open-sockets");
13
17
  // detectLite is cached per-project in project.js and passed via ctx.liteStatus.
14
18
  // This import is retained only for backward compat if ctx.liteStatus is absent.
15
19
  var { detectLite } = require("./lite-detect");
@@ -181,7 +185,14 @@ function attachConnection(ctx) {
181
185
  sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules(_userId, authOf(ws)) });
182
186
  _loop.sendConnectionState(ws);
183
187
  if (_mcp) _mcp.sendConnectionState(ws);
184
- if (_notifications) _notifications.sendConnectionState(ws, sendTo);
188
+ if (_notifications) {
189
+ _notifications.sendConnectionState(ws, sendTo, snapshotLivePrompts({
190
+ slug: slug,
191
+ sessions: sm.sessions,
192
+ prompts: promptsFor(sm),
193
+ viewerId: wsUser ? wsUser.id : null,
194
+ }));
195
+ }
185
196
  // A client that connects is told the current offer state: the held offer, or
186
197
  // an explicit retraction when none stands, so a missed retraction cannot
187
198
  // leave a dead restart action on screen.
@@ -306,6 +317,16 @@ function attachConnection(ctx) {
306
317
  }
307
318
  broadcastPresence();
308
319
 
320
+ // One journal line per socket, so a tab holding more than one is visible
321
+ // from the daemon. Identifiers only: never the ticket, cookies, headers or
322
+ // remote address. The client id is the same label prompt sources carry.
323
+ ws._clagenticConnectedAt = Date.now();
324
+ openSockets.opened(slug);
325
+ console.log("[connection] connect: project=" + logField(slug)
326
+ + " client=" + logField(clientIdOf(ws))
327
+ + " user=" + logField(_userId)
328
+ + " session=" + logField(ws._clagenticActiveSession));
329
+
309
330
  ws.on("message", function (raw) {
310
331
  var msg;
311
332
  try { msg = JSON.parse(raw.toString()); } catch (e) { return; }
@@ -329,7 +350,24 @@ function attachConnection(ctx) {
329
350
  });
330
351
  }
331
352
 
353
+ // Logs the disconnect and leaves the open-socket count, once per socket, so
354
+ // a repeated close cannot drive the count below the truth. Project destroy
355
+ // calls it too: its ws.close() only starts the handshake, and the close
356
+ // event can arrive long after the project is gone.
357
+ function recordDisconnect(ws) {
358
+ if (!ws._clagenticConnectedAt) return;
359
+ var _seconds = Math.round((Date.now() - ws._clagenticConnectedAt) / 1000);
360
+ ws._clagenticConnectedAt = 0;
361
+ openSockets.closed(slug);
362
+ console.log("[connection] disconnect: project=" + logField(slug)
363
+ + " client=" + logField(clientIdOf(ws))
364
+ + " user=" + logField(ws._clagenticUser ? ws._clagenticUser.id : null)
365
+ + " session=" + logField(ws._clagenticActiveSession)
366
+ + " duration_s=" + _seconds);
367
+ }
368
+
332
369
  function handleDisconnection(ws) {
370
+ recordDisconnect(ws);
333
371
  if (ws._clagenticActiveSession) {
334
372
  var dcPresKey = ws._clagenticUser ? ws._clagenticUser.id : "_default";
335
373
  var dcExisting = userPresence.getPresence(slug, dcPresKey);
@@ -347,6 +385,7 @@ function attachConnection(ctx) {
347
385
  return {
348
386
  handleConnection: handleConnection,
349
387
  handleDisconnection: handleDisconnection,
388
+ recordDisconnect: recordDisconnect,
350
389
  };
351
390
  }
352
391
 
@@ -2,6 +2,9 @@ var fs = require("fs");
2
2
  var path = require("path");
3
3
  var fileScope = require("./project-file-scope");
4
4
  var projectGit = require("./project-git");
5
+ var claudeSettingsEnv = require("./claude-settings-env");
6
+ var runtimeEnv = require("./runtime-env");
7
+ var { REAL_HOME } = require("./config");
5
8
 
6
9
  // Settings that act on the whole machine (not on this project), so the
7
10
  // per-user projectSettings permission is not enough: administrators only.
@@ -56,6 +59,18 @@ function attachFilesystem(ctx) {
56
59
  var IMAGE_EXTS = ctx.IMAGE_EXTS;
57
60
  var fileAccess = ctx.fileAccess;
58
61
 
62
+ // Names a Settings text sets that the daemon user's Claude settings file
63
+ // sets too; the file wins at the runtime, so the editor says so. The one file
64
+ // is located from the daemon's own environment (claude-settings-env.js), never
65
+ // from the text, and os-users mode reads none. configDirNote tells the editor
66
+ // to say the check covers that file only when the text sets CLAUDE_CONFIG_DIR.
67
+ function shadowInfoFor(text) {
68
+ return {
69
+ shadowedKeys: claudeSettingsEnv.shadowedKeys(text, { homeDir: REAL_HOME, osUsers: !!osUsers }),
70
+ shadowConfigDirNote: claudeSettingsEnv.setsConfigDir(text),
71
+ };
72
+ }
73
+
59
74
  // In multi-user mode the project's environment text applies to the project
60
75
  // owner's sessions (lib/runtime-env.js projectEnvApplies), so only the owner
61
76
  // or an administrator may read or change it: anyone else would be writing
@@ -242,10 +257,10 @@ function attachFilesystem(ctx) {
242
257
  } catch (e) {}
243
258
  // appliesTo tells the Settings page whom the text reaches; canEdit that
244
259
  // this user may see and change it. No value goes to a user who may not.
245
- sendTo(ws, {
260
+ sendTo(ws, Object.assign({
246
261
  type: "project_env_result", slug: slug, envrc: envrc, hasEnvrc: hasEnvrc,
247
262
  appliesTo: envMultiUser ? "owner" : "everyone", canEdit: canManageEnv,
248
- });
263
+ }, canManageEnv ? shadowInfoFor(envrc) : { shadowedKeys: [] }));
249
264
  return true;
250
265
  }
251
266
 
@@ -266,7 +281,7 @@ function attachFilesystem(ctx) {
266
281
  return true;
267
282
  }
268
283
  var setResult = opts.onSetProjectEnv(envSlug, envText);
269
- sendTo(ws, { type: "set_project_env_result", ok: setResult.ok, slug: slug, error: setResult.error });
284
+ sendTo(ws, Object.assign({ type: "set_project_env_result", ok: setResult.ok, slug: slug, error: setResult.error }, setResult.ok ? shadowInfoFor(envText) : { shadowedKeys: [] }));
270
285
  } else {
271
286
  sendTo(ws, { type: "set_project_env_result", ok: false, error: "Not supported" });
272
287
  }
@@ -307,7 +322,7 @@ function attachFilesystem(ctx) {
307
322
  var sharedResult = opts.onGetSharedEnv();
308
323
  sharedEnvrc = sharedResult.envrc || "";
309
324
  }
310
- sendTo(ws, { type: "shared_env_result", envrc: sharedEnvrc });
325
+ sendTo(ws, Object.assign({ type: "shared_env_result", envrc: sharedEnvrc }, shadowInfoFor(sharedEnvrc)));
311
326
  return true;
312
327
  }
313
328
 
@@ -323,7 +338,7 @@ function attachFilesystem(ctx) {
323
338
  return true;
324
339
  }
325
340
  var sharedSetResult = opts.onSetSharedEnv(msg.envrc || "");
326
- sendTo(ws, { type: "set_shared_env_result", ok: sharedSetResult.ok, error: sharedSetResult.error });
341
+ sendTo(ws, Object.assign({ type: "set_shared_env_result", ok: sharedSetResult.ok, error: sharedSetResult.error }, sharedSetResult.ok ? shadowInfoFor(msg.envrc || "") : { shadowedKeys: [] }));
327
342
  } else {
328
343
  sendTo(ws, { type: "set_shared_env_result", ok: false, error: "Not supported" });
329
344
  }