@clagentic/console 1.0.5-beta.1 → 1.1.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/lib/audit.js ADDED
@@ -0,0 +1,57 @@
1
+ // audit.js — Append-only audit log for privileged actions.
2
+ // Writes JSON lines to ~/.clagentic/audit.log (mode 0o600).
3
+ // Never throws into callers: all errors are logged to stderr only.
4
+
5
+ var fs = require("fs");
6
+ var path = require("path");
7
+ var config = require("./config");
8
+
9
+ var AUDIT_LOG_PATH = path.join(config.CONFIG_DIR, "audit.log");
10
+ var _logFd = null;
11
+
12
+ function _getLogFd() {
13
+ if (_logFd !== null) return _logFd;
14
+ try {
15
+ _logFd = fs.openSync(AUDIT_LOG_PATH, "a", 0o600);
16
+ // Enforce mode on existing files — openSync mode flag may not apply when the file already exists.
17
+ try { fs.chmodSync(AUDIT_LOG_PATH, 0o600); } catch (_) {}
18
+ } catch (e) {
19
+ console.error("[audit] Failed to open audit log:", e.message);
20
+ }
21
+ return _logFd;
22
+ }
23
+
24
+ /**
25
+ * Log a privileged action.
26
+ *
27
+ * @param {string} action Action identifier, e.g. "user.create", "auth.lockout"
28
+ * @param {object} ctx Optional context fields:
29
+ * actorId {string} ID of the user performing the action (or "system")
30
+ * actorName {string} Username of the actor
31
+ * target {string} ID of the affected user/resource
32
+ * metadata {object} Additional non-secret metadata (never log passwords/tokens/PINs)
33
+ */
34
+ function log(action, ctx) {
35
+ ctx = ctx || {};
36
+ var entry = {
37
+ ts: new Date().toISOString(),
38
+ action: action,
39
+ actorId: ctx.actorId || null,
40
+ actorName: ctx.actorName || null,
41
+ target: ctx.target || null,
42
+ metadata: ctx.metadata || null,
43
+ };
44
+ var line = JSON.stringify(entry) + "\n";
45
+ // Non-blocking: defer write so callers are never stalled by I/O.
46
+ setImmediate(function () {
47
+ var fd = _getLogFd();
48
+ if (!fd) return;
49
+ try {
50
+ fs.writeSync(fd, line);
51
+ } catch (e) {
52
+ console.error("[audit] Failed to write audit entry:", e.message);
53
+ }
54
+ });
55
+ }
56
+
57
+ module.exports = { log: log };
package/lib/os-users.js CHANGED
@@ -5,6 +5,7 @@ var fs = require("fs");
5
5
  var path = require("path");
6
6
  var execFileSync = require("child_process").execFileSync;
7
7
  var _aclGrantCache = Object.create(null);
8
+ var audit = require("./audit");
8
9
 
9
10
  function aclCacheKey(projectPath, linuxUser) {
10
11
  return path.resolve(projectPath) + "::" + linuxUser;
@@ -407,6 +408,10 @@ function provisionLinuxUser(clayUsername) {
407
408
  ensureLinger(linuxName);
408
409
  console.log("[os-users] Provisioned Linux user: " + linuxName + " (Clay user: " + clayUsername + ")");
409
410
  installClaudeCli(linuxName);
411
+ audit.log("osuser.create", {
412
+ actorId: "system",
413
+ metadata: { clayUsername: clayUsername, linuxUser: linuxName },
414
+ });
410
415
  return { ok: true, linuxUser: linuxName };
411
416
  } catch (e) {
412
417
  var msg = (e.stderr || e.message || "").trim();
@@ -171,6 +171,9 @@ function attachConnection(ctx) {
171
171
  if (!active) {
172
172
  var autoOpts = {};
173
173
  if (wsUser && usersModule.isMultiUser()) autoOpts.ownerId = wsUser.id;
174
+ // TODO(lr-f311): defer createSession until first user message — every
175
+ // network blip or browser reload creates an empty session file here.
176
+ // The reconnect/presence path is subtle; fix deferred to a follow-up PR.
174
177
  active = sm.createSession(autoOpts, ws);
175
178
  autoCreated = true;
176
179
  }
package/lib/public/app.js CHANGED
@@ -5,7 +5,7 @@ import { renderMarkdown, highlightCodeBlocks, renderMermaidBlocks, closeMermaidM
5
5
  import { initSidebar, updatePageTitle, spawnDustParticles } from './modules/sidebar.js';
6
6
  import {
7
7
  renderSessionList, handleSearchResults, updateSessionPresence,
8
- updateSessionBadge, populateCliSessionList
8
+ updateSessionBadge, populateCliSessionList, resetSessionList
9
9
  } from './modules/sidebar-sessions.js';
10
10
  import {
11
11
  renderIconStrip, updateProjectBadge
@@ -59,7 +59,7 @@ import { initLoopWizard, openRalphWizard as _loopOpenRalphWizard, closeRalphWiza
59
59
  import { initAppNotifications, handleNotificationsState as _notifHandleState, handleNotificationCreated as _notifHandleCreated, handleNotificationDismissed as _notifHandleDismissed, handleNotificationDismissedAll as _notifHandleDismissedAll } from './modules/app-notifications.js';
60
60
  import { createStore, store } from './modules/store.js';
61
61
  import { initPanels, updateConfigChip as _panUpdateConfigChip, getModelEffortLevels as _panGetModelEffortLevels, accumulateUsage as _panAccumulateUsage, updateUsagePanel as _panUpdateUsagePanel, resetUsage as _panResetUsage, toggleUsagePanel as _panToggleUsagePanel, formatTokens as _panFormatTokens, updateStatusPanel as _panUpdateStatusPanel, requestProcessStats as _panRequestProcessStats, toggleStatusPanel as _panToggleStatusPanel, accumulateContext as _panAccumulateContext, updateContextPanel as _panUpdateContextPanel, resetContext as _panResetContext, resetContextData as _panResetContextData, minimizeContext as _panMinimizeContext, expandContext as _panExpandContext, toggleContextPanel as _panToggleContextPanel, getContextView as _panGetContextView, renderCtxPopover as _panRenderCtxPopover, hideCtxPopover as _panHideCtxPopover, formatBytes as _panFormatBytes, formatUptime as _panFormatUptime, getModelSupportsEffort as _panGetModelSupportsEffort, getSessionUsage, setSessionUsage, getContextData, setContextData, setContextView as _panSetContextView, applyContextView as _panApplyContextView } from './modules/app-panels.js';
62
- import { initProjects, onProjectListUpdated, updateProjectList as _projUpdateProjectList, renderProjectList as _projRenderProjectList, renderTopbarPresence as _projRenderTopbarPresence, switchProject as _projSwitchProject, resetClientState as _projResetClientState, confirmRemoveProject as _projConfirmRemoveProject, handleRemoveProjectCheckResult as _projHandleRemoveProjectCheckResult, handleRemoveProjectResult as _projHandleRemoveProjectResult, openAddProjectModal as _projOpenAddProjectModal, closeAddProjectModal as _projCloseAddProjectModal, handleBrowseDirResult as _projHandleBrowseDirResult, handleAddProjectResult as _projHandleAddProjectResult, handleCloneProgress as _projHandleCloneProgress, showUpdateAvailable as _projShowUpdateAvailable, getCachedProjects, setCachedProjects, getCachedProjectCount, getCachedRemovedProjects, setCachedRemovedProjects } from './modules/app-projects.js';
62
+ import { initProjects, onProjectListUpdated, onResetClientState, updateProjectList as _projUpdateProjectList, renderProjectList as _projRenderProjectList, renderTopbarPresence as _projRenderTopbarPresence, switchProject as _projSwitchProject, resetClientState as _projResetClientState, confirmRemoveProject as _projConfirmRemoveProject, handleRemoveProjectCheckResult as _projHandleRemoveProjectCheckResult, handleRemoveProjectResult as _projHandleRemoveProjectResult, openAddProjectModal as _projOpenAddProjectModal, closeAddProjectModal as _projCloseAddProjectModal, handleBrowseDirResult as _projHandleBrowseDirResult, handleAddProjectResult as _projHandleAddProjectResult, handleCloneProgress as _projHandleCloneProgress, showUpdateAvailable as _projShowUpdateAvailable, getCachedProjects, setCachedProjects, getCachedProjectCount, getCachedRemovedProjects, setCachedRemovedProjects } from './modules/app-projects.js';
63
63
  import { initRendering, addToMessages as _renAddToMessages, scrollToBottom as _renScrollToBottom, forceScrollToBottom as _renForceScrollToBottom, addUserMessage as _renAddUserMessage, getMsgTime as _renGetMsgTime, shouldGroupMessage as _renShouldGroupMessage, ensureAssistantBlock as _renEnsureAssistantBlock, addCopyHandler as _renAddCopyHandler, appendDelta as _renAppendDelta, flushStreamBuffer as _renFlushStreamBuffer, finalizeAssistantBlock as _renFinalizeAssistantBlock, addSystemMessage as _renAddSystemMessage, addConflictMessage as _renAddConflictMessage, addContextOverflowMessage as _renAddContextOverflowMessage, showClaudePreThinking as _renShowClaudePreThinking, showSuggestionChips as _renShowSuggestionChips, hideSuggestionChips as _renHideSuggestionChips, getGhostSuggestion as _renGetGhostSuggestion, getTurnCounter, setTurnCounter, getPrependAnchor, setPrependAnchor, getActivityEl, setActivityEl, getIsUserScrolledUp, setIsUserScrolledUp, getStickyBottom, armStickyBottom, disarmStickyBottom } from './modules/app-rendering.js';
64
64
  import { initDm, openDm as _dmOpenDm, enterDmMode as _dmEnterDmMode, exitDmMode as _dmExitDmMode, appendDmMessage as _dmAppendDmMessage, showDmTypingIndicator as _dmShowDmTypingIndicator, handleDmSend as _dmHandleDmSend } from './modules/app-dm.js';
65
65
  import { initMention, handleMentionStart, handleMentionStream, handleMentionDone, handleMentionError, handleMentionActivity, renderMentionUser, renderMentionResponse } from './modules/mention.js';
@@ -1006,6 +1006,7 @@ import { initMention, handleMentionStart, handleMentionStream, handleMentionDone
1006
1006
  // --- Projects module ---
1007
1007
  initProjects();
1008
1008
  onProjectListUpdated(function (projects) { updateMobileProjectsTabBadge(projects); });
1009
+ onResetClientState(function () { resetSessionList(); });
1009
1010
 
1010
1011
  // --- Home Hub module ---
1011
1012
  initHomeHub();
@@ -33,6 +33,9 @@ import { closeSessionInfoPopover } from './app-header.js';
33
33
  var _onProjectListUpdated = null;
34
34
  export function onProjectListUpdated(fn) { _onProjectListUpdated = fn; }
35
35
 
36
+ var _onResetClientState = null;
37
+ export function onResetClientState(fn) { _onResetClientState = fn; }
38
+
36
39
  var cachedProjects = [];
37
40
  var cachedProjectCount = 0;
38
41
  var cachedRemovedProjects = [];
@@ -423,6 +426,10 @@ export function resetClientState() {
423
426
  // Clear vendor state so the incoming model_info for the new project is never
424
427
  // blocked by a lock that was set during the previous project's session.
425
428
  store.set({ currentVendor: null, vendorSelectionLocked: false, codexApproval: null, codexSandbox: null, codexWebSearch: null });
429
+ // Clear the session list immediately so the sidebar doesn't show the previous
430
+ // project's sessions while waiting for the new project's session_list from
431
+ // the server. Resets the fingerprint too so the incoming list is never skipped.
432
+ if (typeof _onResetClientState === "function") _onResetClientState();
426
433
  }
427
434
 
428
435
  export function switchProject(slug) {
@@ -181,7 +181,7 @@ export function renderMermaidBlocks(el) {
181
181
 
182
182
  try {
183
183
  mermaid.render(id, source.trim()).then(function (result) {
184
- container.innerHTML = result.svg;
184
+ container.innerHTML = DOMPurify.sanitize(result.svg, { USE_PROFILES: { svg: true, svgFilters: true } });
185
185
  container.addEventListener("click", function () {
186
186
  showMermaidModal(container.innerHTML);
187
187
  });
@@ -238,7 +238,10 @@ export function showMermaidModal(svgHtml) {
238
238
  var modal = document.getElementById("mermaid-modal");
239
239
  var body = document.getElementById("mermaid-modal-body");
240
240
  if (!modal || !body) return;
241
- body.innerHTML = svgHtml;
241
+ // svgHtml originates from container.innerHTML after mermaid render — sanitize
242
+ // defensively here too since showMermaidModal is also exported and callable
243
+ // from other paths.
244
+ body.innerHTML = DOMPurify.sanitize(svgHtml, { USE_PROFILES: { svg: true, svgFilters: true } });
242
245
  modal.classList.remove("hidden");
243
246
  refreshIcons();
244
247
 
@@ -582,6 +582,15 @@ export function getCachedSessions() {
582
582
  return cachedSessions;
583
583
  }
584
584
 
585
+ // Called by resetClientState() on project switch. Clears the cached session
586
+ // list and resets the fingerprint so the next session_list from the new
587
+ // project is always rendered (never skipped by the fingerprint guard).
588
+ export function resetSessionList() {
589
+ cachedSessions = [];
590
+ _sessionListFingerprint = "";
591
+ renderSessionList(null);
592
+ }
593
+
585
594
  export function getSearchQuery() {
586
595
  return searchQuery;
587
596
  }
package/lib/sdk-bridge.js CHANGED
@@ -1420,6 +1420,8 @@ function createSDKBridge(opts) {
1420
1420
  var result = [];
1421
1421
 
1422
1422
  function tryLookup(name) {
1423
+ // name MUST be a value from the allowlist below — shell injection risk if dynamic
1424
+ if (!["claude", "codex"].includes(name)) throw new Error("Disallowed binary name: " + name);
1423
1425
  try {
1424
1426
  if (linuxUser) {
1425
1427
  execFileSync("su", ["-", linuxUser, "-c", "which " + name], { timeout: 3000, stdio: ["pipe", "pipe", "pipe"] });
package/lib/sdk-worker.js CHANGED
@@ -20,6 +20,8 @@ try { require("fs").writeSync(2, "[sdk-worker] BOOT pid=" + process.pid + " uid=
20
20
  var net = require("net");
21
21
  var crypto = require("crypto");
22
22
  var path = require("path");
23
+ var fs = require("fs");
24
+ var os = require("os");
23
25
 
24
26
  var socketPath = process.argv[2];
25
27
  if (!socketPath) {
@@ -364,8 +366,15 @@ async function handleQueryStart(msg) {
364
366
  var options = msg.options || {};
365
367
  if (_mcpServers) options.mcpServers = _mcpServers;
366
368
  options.abortController = abortController;
367
- options.debug = true;
368
- options.debugFile = "/tmp/clagentic-cli-debug-" + process.pid + ".log";
369
+ if (process.env.CLAGENTIC_DEBUG === "1") {
370
+ var _logDir = path.join(os.homedir(), ".clagentic", "worker-logs");
371
+ fs.mkdirSync(_logDir, { recursive: true, mode: 0o700 });
372
+ var _logFile = path.join(_logDir, process.pid + ".log");
373
+ // Create with 0o600 before passing to the SDK so the file is never world-readable
374
+ fs.writeFileSync(_logFile, "", { flag: "a", mode: 0o600 });
375
+ options.debug = true;
376
+ options.debugFile = _logFile;
377
+ }
369
378
  // Override CLI subprocess spawn to inject NODE_OPTIONS for IPv4-first DNS.
370
379
  // The SDK constructs its own env for the CLI process, so worker env vars
371
380
  // like NODE_OPTIONS are not inherited. We intercept the spawn to fix this.
@@ -1,6 +1,8 @@
1
1
  // Admin API endpoints (multi-user mode only)
2
2
  // Extracted from server.js
3
3
 
4
+ var audit = require("./audit");
5
+
4
6
  function attachAdmin(ctx) {
5
7
  var users = ctx.users;
6
8
  var smtp = ctx.smtp;
@@ -84,6 +86,12 @@ function attachAdmin(ctx) {
84
86
  if (onUserDeleted && targetLinuxUser) {
85
87
  onUserDeleted(targetUserId, targetLinuxUser);
86
88
  }
89
+ audit.log("user.delete", {
90
+ actorId: mu.id,
91
+ actorName: mu.username,
92
+ target: targetUserId,
93
+ metadata: targetUser ? { username: targetUser.username, role: targetUser.role } : null,
94
+ });
87
95
  res.writeHead(200, { "Content-Type": "application/json" });
88
96
  res.end('{"ok":true}');
89
97
  return true;
@@ -131,6 +139,12 @@ function attachAdmin(ctx) {
131
139
  if (onUserProvisioned) onUserProvisioned(result.user.id, provision.linuxUser);
132
140
  }
133
141
  }
142
+ audit.log("user.create", {
143
+ actorId: mu.id,
144
+ actorName: mu.username,
145
+ target: result.user.id,
146
+ metadata: { username: result.user.username, role: result.user.role },
147
+ });
134
148
  res.writeHead(200, { "Content-Type": "application/json" });
135
149
  res.end(JSON.stringify({
136
150
  ok: true,
@@ -187,6 +201,12 @@ function attachAdmin(ctx) {
187
201
  break;
188
202
  }
189
203
  }
204
+ audit.log("user.pin.reset", {
205
+ actorId: mu.id,
206
+ actorName: mu.username,
207
+ target: targetUserId,
208
+ metadata: { username: targetUser.username },
209
+ });
190
210
  res.writeHead(200, { "Content-Type": "application/json" });
191
211
  res.end(JSON.stringify({ ok: true, tempPin: newPin }));
192
212
  return true;
@@ -421,6 +441,11 @@ function attachAdmin(ctx) {
421
441
  // Allow clearing SMTP config by sending empty fields
422
442
  if (!data.host && !data.user && !data.pass && !data.from) {
423
443
  smtp.saveSmtpConfig(null);
444
+ audit.log("settings.smtp.update", {
445
+ actorId: mu.id,
446
+ actorName: mu.username,
447
+ metadata: { cleared: true },
448
+ });
424
449
  res.writeHead(200, { "Content-Type": "application/json" });
425
450
  res.end('{"ok":true}');
426
451
  return;
@@ -445,6 +470,12 @@ function attachAdmin(ctx) {
445
470
  from: data.from,
446
471
  emailLoginEnabled: !!data.emailLoginEnabled,
447
472
  });
473
+ audit.log("settings.smtp.update", {
474
+ actorId: mu.id,
475
+ actorName: mu.username,
476
+ // Log field names only — never log host credentials, passwords, or secrets.
477
+ metadata: { fieldsUpdated: ["host", "port", "secure", "user", "from", "emailLoginEnabled"] },
478
+ });
448
479
  res.writeHead(200, { "Content-Type": "application/json" });
449
480
  res.end('{"ok":true}');
450
481
  } catch (e) {
@@ -701,6 +732,44 @@ function attachAdmin(ctx) {
701
732
  return true;
702
733
  }
703
734
 
735
+ // GET /api/admin/audit — tail the audit log (admin only, read-only)
736
+ if (req.method === "GET" && fullUrl.indexOf("/api/admin/audit") === 0) {
737
+ if (!users.isMultiUser()) {
738
+ res.writeHead(404, { "Content-Type": "application/json" });
739
+ res.end('{"error":"Not found"}');
740
+ return true;
741
+ }
742
+ var mu = getMultiUserFromReq(req);
743
+ if (!mu || mu.role !== "admin") {
744
+ res.writeHead(403, { "Content-Type": "application/json" });
745
+ res.end('{"error":"Admin access required"}');
746
+ return true;
747
+ }
748
+ var auditPath = require("path").join(require("./config").CONFIG_DIR, "audit.log");
749
+ var fs = require("fs");
750
+ try {
751
+ var raw = fs.readFileSync(auditPath, "utf8");
752
+ var allLines = raw.split("\n").filter(function (l) { return l.trim().length > 0; });
753
+ var N = 200;
754
+ var tail = allLines.slice(-N);
755
+ var entries = [];
756
+ for (var li = 0; li < tail.length; li++) {
757
+ try { entries.push(JSON.parse(tail[li])); } catch (_) {}
758
+ }
759
+ res.writeHead(200, { "Content-Type": "application/json" });
760
+ res.end(JSON.stringify({ entries: entries, total_lines: allLines.length }));
761
+ } catch (e) {
762
+ if (e.code === "ENOENT") {
763
+ res.writeHead(200, { "Content-Type": "application/json" });
764
+ res.end('{"entries":[],"total_lines":0}');
765
+ } else {
766
+ res.writeHead(500, { "Content-Type": "application/json" });
767
+ res.end(JSON.stringify({ error: "Failed to read audit log" }));
768
+ }
769
+ }
770
+ return true;
771
+ }
772
+
704
773
  return false;
705
774
  }
706
775
 
@@ -4,6 +4,11 @@ var path = require("path");
4
4
  var { CONFIG_DIR } = require("./config");
5
5
  var _isDevMode = require("./config").isDevMode;
6
6
  var store = require("./store");
7
+ var audit = require("./audit");
8
+
9
+ // Default token TTL: 30 days. Tokens issued before expiry support was added are
10
+ // treated as valid for one additional TTL cycle to avoid forced logouts on upgrade.
11
+ var TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
7
12
 
8
13
  // --- PIN hashing ---
9
14
 
@@ -76,7 +81,23 @@ function attachAuth(ctx) {
76
81
  var raw = fs.readFileSync(path.join(CONFIG_DIR, TOKENS_NAME), "utf8");
77
82
  var data = JSON.parse(raw);
78
83
  if (data && typeof data === "object") {
84
+ // Migration: tokens stored as plain userId strings (legacy format) or as
85
+ // objects with {userId, issuedAt, expiresAt}. Upgrade legacy entries in
86
+ // place so they are valid for one TTL cycle, then require the field.
87
+ var now = Date.now();
88
+ var migrated = false;
89
+ for (var tok in data) {
90
+ var entry = data[tok];
91
+ if (typeof entry === "string") {
92
+ data[tok] = { userId: entry, issuedAt: now, expiresAt: now + TOKEN_TTL_MS };
93
+ migrated = true;
94
+ } else if (entry && typeof entry === "object" && !entry.expiresAt) {
95
+ entry.expiresAt = (entry.issuedAt || now) + TOKEN_TTL_MS;
96
+ migrated = true;
97
+ }
98
+ }
79
99
  multiUserTokens = data;
100
+ if (migrated) saveTokens();
80
101
  }
81
102
  } catch (e) {
82
103
  multiUserTokens = {};
@@ -94,7 +115,8 @@ function attachAuth(ctx) {
94
115
 
95
116
  function createMultiUserSession(userId) {
96
117
  var token = users.generateUserAuthToken(userId);
97
- multiUserTokens[token] = userId;
118
+ var now = Date.now();
119
+ multiUserTokens[token] = { userId: userId, issuedAt: now, expiresAt: now + TOKEN_TTL_MS };
98
120
  saveTokens();
99
121
  var cookie = MULTI_USER_COOKIE + "=" + token + "; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000" + (tlsOptions ? "; Secure" : "");
100
122
  return { token: token, cookie: cookie };
@@ -104,8 +126,16 @@ function attachAuth(ctx) {
104
126
  var cookies = parseCookies(req);
105
127
  var token = cookies[MULTI_USER_COOKIE];
106
128
  if (!token) return null;
107
- var userId = multiUserTokens[token];
129
+ var entry = multiUserTokens[token];
130
+ if (!entry) return null;
131
+ var userId = typeof entry === "object" ? entry.userId : entry;
108
132
  if (!userId) return null;
133
+ // Reject expired tokens
134
+ if (entry.expiresAt && Date.now() > entry.expiresAt) {
135
+ delete multiUserTokens[token];
136
+ saveTokens();
137
+ return null;
138
+ }
109
139
  var user = users.findUserById(userId);
110
140
  return user || null;
111
141
  }
@@ -117,17 +147,48 @@ function attachAuth(ctx) {
117
147
  function revokeUserTokens(userId) {
118
148
  var changed = false;
119
149
  for (var token in multiUserTokens) {
120
- if (multiUserTokens[token] === userId) {
150
+ var entry = multiUserTokens[token];
151
+ var entryUserId = typeof entry === "object" ? entry.userId : entry;
152
+ if (entryUserId === userId) {
121
153
  delete multiUserTokens[token];
122
154
  changed = true;
123
155
  }
124
156
  }
125
- if (changed) saveTokens();
157
+ if (changed) {
158
+ saveTokens();
159
+ audit.log("auth.token.revoke_all", {
160
+ actorId: "system",
161
+ target: userId,
162
+ });
163
+ }
126
164
  }
127
165
 
128
166
  // --- PIN rate limiting (per-instance state) ---
129
167
  var pinAttempts = {};
130
168
 
169
+ // Per-username failure tracking with progressive backoff.
170
+ // Backoff thresholds (cumulative failures): 1s, 5s, 30s, 5min, permanent lockout.
171
+ var PIN_USER_BACKOFF_MS = [1000, 5000, 30000, 5 * 60 * 1000];
172
+ var PIN_USER_PERMANENT_THRESHOLD = PIN_USER_BACKOFF_MS.length + 1;
173
+ var pinAttemptsUser = {};
174
+ var lockedUsers = new Set();
175
+
176
+ function isUserLockedOut(username) {
177
+ return lockedUsers.has(username);
178
+ }
179
+
180
+ function unlockUser(username) {
181
+ lockedUsers.delete(username);
182
+ delete pinAttemptsUser[username];
183
+ }
184
+
185
+ function getUserBackoffMs(username) {
186
+ var entry = pinAttemptsUser[username];
187
+ if (!entry) return 0;
188
+ var idx = Math.min(entry.count - 1, PIN_USER_BACKOFF_MS.length - 1);
189
+ return idx >= 0 ? PIN_USER_BACKOFF_MS[idx] : 0;
190
+ }
191
+
131
192
  function checkPinRateLimit(ip) {
132
193
  var entry = pinAttempts[ip];
133
194
  if (!entry) return null;
@@ -141,16 +202,54 @@ function attachAuth(ctx) {
141
202
  return null;
142
203
  }
143
204
 
205
+ // Check both IP and username lockouts. Returns seconds to wait, or null if clear.
206
+ function checkPinRateLimitWithUser(ip, username) {
207
+ var ipResult = checkPinRateLimit(ip);
208
+ if (ipResult !== null) return ipResult;
209
+ if (username && isUserLockedOut(username)) {
210
+ // Permanent lockout — signal with a large sentinel value (admin must unlock)
211
+ return -1;
212
+ }
213
+ if (username) {
214
+ var entry = pinAttemptsUser[username];
215
+ if (entry && entry.count > 0) {
216
+ var backoff = getUserBackoffMs(username);
217
+ if (backoff > 0) {
218
+ var elapsed = Date.now() - entry.lastAttempt;
219
+ if (elapsed < backoff) return Math.ceil((backoff - elapsed) / 1000);
220
+ }
221
+ }
222
+ }
223
+ return null;
224
+ }
225
+
144
226
  function recordPinFailure(ip) {
145
227
  if (!pinAttempts[ip]) pinAttempts[ip] = { count: 0, lastAttempt: 0 };
146
228
  pinAttempts[ip].count++;
147
229
  pinAttempts[ip].lastAttempt = Date.now();
148
230
  }
149
231
 
232
+ function recordPinFailureWithUser(ip, username) {
233
+ recordPinFailure(ip);
234
+ if (username) {
235
+ if (!pinAttemptsUser[username]) pinAttemptsUser[username] = { count: 0, lastAttempt: 0 };
236
+ pinAttemptsUser[username].count++;
237
+ pinAttemptsUser[username].lastAttempt = Date.now();
238
+ if (pinAttemptsUser[username].count >= PIN_USER_PERMANENT_THRESHOLD) {
239
+ lockedUsers.add(username);
240
+ }
241
+ }
242
+ }
243
+
150
244
  function clearPinFailures(ip) {
151
245
  delete pinAttempts[ip];
152
246
  }
153
247
 
248
+ function clearPinFailuresWithUser(ip, username) {
249
+ clearPinFailures(ip);
250
+ if (username) delete pinAttemptsUser[username];
251
+ }
252
+
154
253
  // --- Admin password recovery (in-memory, one-time) ---
155
254
  var recovery = null;
156
255
 
@@ -453,8 +552,12 @@ function attachAuth(ctx) {
453
552
  return true;
454
553
  }
455
554
  var ip = req.socket.remoteAddress || "";
555
+ // IP-only pre-check (username not yet known — body not read)
456
556
  var remaining = checkPinRateLimit(ip);
457
557
  if (remaining !== null) {
558
+ audit.log("auth.lockout", {
559
+ metadata: { ip: ip, retryAfterSeconds: remaining },
560
+ });
458
561
  res.writeHead(429, { "Content-Type": "application/json" });
459
562
  res.end(JSON.stringify({ ok: false, locked: true, retryAfter: remaining }));
460
563
  return true;
@@ -464,15 +567,23 @@ function attachAuth(ctx) {
464
567
  req.on("end", function () {
465
568
  try {
466
569
  var data = JSON.parse(body);
467
- var user = users.authenticateUser(data.username, data.pin);
570
+ var username = data.username || null;
571
+ // Per-username lockout check (after body is available)
572
+ var userRemaining = checkPinRateLimitWithUser(ip, username);
573
+ if (userRemaining !== null) {
574
+ res.writeHead(429, { "Content-Type": "application/json" });
575
+ res.end(JSON.stringify({ ok: false, locked: true, retryAfter: userRemaining }));
576
+ return;
577
+ }
578
+ var user = users.authenticateUser(username, data.pin);
468
579
  if (!user) {
469
- recordPinFailure(ip);
580
+ recordPinFailureWithUser(ip, username);
470
581
  var attemptsLeft = PIN_MAX_ATTEMPTS - (pinAttempts[ip] ? pinAttempts[ip].count : 0);
471
582
  res.writeHead(401, { "Content-Type": "application/json" });
472
583
  res.end(JSON.stringify({ ok: false, error: "Invalid username or PIN", attemptsLeft: Math.max(attemptsLeft, 0) }));
473
584
  return;
474
585
  }
475
- clearPinFailures(ip);
586
+ clearPinFailuresWithUser(ip, user.username);
476
587
  var session = createMultiUserSession(user.id);
477
588
  var loginResp = { ok: true, user: { id: user.id, username: user.username, role: user.role } };
478
589
  if (user.mustChangePin) loginResp.mustChangePin = true;
@@ -732,6 +843,8 @@ function attachAuth(ctx) {
732
843
  setAuthToken: setAuthToken,
733
844
  getAuthPage: getAuthPage,
734
845
  createMultiUserSession: createMultiUserSession,
846
+ isUserLockedOut: isUserLockedOut,
847
+ unlockUser: unlockUser,
735
848
  };
736
849
  }
737
850
 
@@ -1,5 +1,6 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
+ var audit = require("./audit");
3
4
 
4
5
  function attachSettings(ctx) {
5
6
  var users = ctx.users;
@@ -540,6 +541,10 @@ function attachSettings(ctx) {
540
541
  res.end(JSON.stringify({ error: result.error }));
541
542
  return true;
542
543
  }
544
+ audit.log("settings.multiuser.enable", {
545
+ actorId: "system",
546
+ metadata: null,
547
+ });
543
548
  res.writeHead(200, { "Content-Type": "application/json" });
544
549
  res.end(JSON.stringify({ ok: true, setupCode: result.setupCode }));
545
550
  return true;
package/lib/sessions.js CHANGED
@@ -13,6 +13,11 @@ function createSessionManager(opts) {
13
13
  var sendAndRecord = null; // set after init via setSendAndRecord
14
14
  var onSessionDone = opts.onSessionDone || function () {};
15
15
 
16
+ // --- LRU eviction limit: max sessions with in-memory history ---
17
+ var LRU_HISTORY_LIMIT = 50;
18
+ // Access order for loaded sessions: most-recently-accessed localId is last.
19
+ var lruOrder = [];
20
+
16
21
  // --- Multi-session state ---
17
22
  var nextLocalId = 1;
18
23
  var sessions = new Map(); // localId -> session object
@@ -67,26 +72,163 @@ function createSessionManager(opts) {
67
72
  var tmpPath = sfPath + ".tmp." + process.pid;
68
73
  fs.writeFileSync(tmpPath, lines.join("\n") + "\n");
69
74
  if (process.platform !== "win32") {
75
+ // chmod 0o600 once at file creation; appendToSessionFile skips it
76
+ // after _fileModeSet is true.
70
77
  try { fs.chmodSync(tmpPath, 0o600); } catch (chmodErr) {}
71
78
  }
72
79
  fs.renameSync(tmpPath, sfPath);
80
+ // Mark that the file mode has been set so appendToSessionFile skips chmod.
81
+ session._fileModeSet = true;
73
82
  } catch(e) {
74
83
  console.error("[session] Failed to save session file:", e.message);
75
84
  }
76
85
  }
77
86
 
87
+ // --- Write buffer state for async append (Finding 1) ---
88
+ // Per-session write buffer: localId -> { lines: string[], timer: Timeout|null }
89
+ var _writeBuffers = {};
90
+
91
+ // Flush all pending lines for a session synchronously. Called on session
92
+ // end and process exit — must be synchronous so no lines are lost.
93
+ function flushSessionBuffer(session) {
94
+ var buf = _writeBuffers[session.localId];
95
+ if (!buf || buf.lines.length === 0) return;
96
+ if (buf.timer) {
97
+ clearTimeout(buf.timer);
98
+ buf.timer = null;
99
+ }
100
+ if (!session.cliSessionId) {
101
+ buf.lines = [];
102
+ return;
103
+ }
104
+ try {
105
+ var afPath = sessionFilePath(session.cliSessionId);
106
+ fs.appendFileSync(afPath, buf.lines.join(""));
107
+ } catch(e) {
108
+ console.error("[session] Failed to flush session buffer:", e.message);
109
+ }
110
+ buf.lines = [];
111
+ }
112
+
113
+ // Flush asynchronously (non-blocking hot path).
114
+ function _flushBufferAsync(session) {
115
+ var buf = _writeBuffers[session.localId];
116
+ if (!buf || buf.lines.length === 0) return;
117
+ if (buf.timer) {
118
+ clearTimeout(buf.timer);
119
+ buf.timer = null;
120
+ }
121
+ if (!session.cliSessionId) {
122
+ buf.lines = [];
123
+ return;
124
+ }
125
+ var toWrite = buf.lines.join("");
126
+ buf.lines = [];
127
+ var afPath = sessionFilePath(session.cliSessionId);
128
+ fs.promises.appendFile(afPath, toWrite).catch(function(e) {
129
+ console.error("[session] Failed to async-flush session buffer:", e.message);
130
+ });
131
+ }
132
+
78
133
  function appendToSessionFile(session, obj) {
79
134
  if (!session.cliSessionId) return;
80
135
  session.lastActivity = Date.now();
81
- try {
82
- var afPath = sessionFilePath(session.cliSessionId);
83
- fs.appendFileSync(afPath, JSON.stringify(obj) + "\n");
84
- if (process.platform !== "win32") {
85
- try { fs.chmodSync(afPath, 0o600); } catch (chmodErr) {}
136
+
137
+ // Ensure a buffer entry exists for this session.
138
+ if (!_writeBuffers[session.localId]) {
139
+ _writeBuffers[session.localId] = { lines: [], timer: null };
140
+ }
141
+ var buf = _writeBuffers[session.localId];
142
+ buf.lines.push(JSON.stringify(obj) + "\n");
143
+
144
+ // Set file mode exactly once at first append if saveSessionFile hasn't
145
+ // done it yet (e.g. for sessions that receive appends before their first
146
+ // full save).
147
+ if (!session._fileModeSet && process.platform !== "win32") {
148
+ try { fs.chmodSync(sessionFilePath(session.cliSessionId), 0o600); } catch (chmodErr) {}
149
+ session._fileModeSet = true;
150
+ }
151
+
152
+ // Flush immediately if threshold reached; otherwise arm the 50ms timer.
153
+ if (buf.lines.length >= 20) {
154
+ _flushBufferAsync(session);
155
+ } else if (!buf.timer) {
156
+ buf.timer = setTimeout(function() {
157
+ buf.timer = null;
158
+ _flushBufferAsync(session);
159
+ }, 50);
160
+ }
161
+ }
162
+
163
+ // --- Lazy history load and LRU eviction (Findings 2 & 3) ---
164
+
165
+ // Remove a localId from lruOrder (helper used by eviction and delete).
166
+ function _lruRemove(localId) {
167
+ var idx = lruOrder.indexOf(localId);
168
+ if (idx !== -1) lruOrder.splice(idx, 1);
169
+ }
170
+
171
+ // Touch a session in the LRU order: move it to the most-recently-used end.
172
+ function _lruTouch(localId) {
173
+ _lruRemove(localId);
174
+ lruOrder.push(localId);
175
+ }
176
+
177
+ // Evict the least-recently-used loaded session if we are over the limit.
178
+ // Never evicts the active session or one that is currently processing.
179
+ function _lruEvictIfNeeded() {
180
+ if (lruOrder.length <= LRU_HISTORY_LIMIT) return;
181
+ for (var ei = 0; ei < lruOrder.length; ei++) {
182
+ var candidateId = lruOrder[ei];
183
+ if (candidateId === activeSessionId) continue;
184
+ var candidate = sessions.get(candidateId);
185
+ if (!candidate || candidate.isProcessing) continue;
186
+ // Unload history from memory; disk file is the source of truth.
187
+ candidate.history = [];
188
+ candidate._historyLoaded = false;
189
+ _lruRemove(candidateId);
190
+ return;
191
+ }
192
+ }
193
+
194
+ // Synchronously load a session's history from disk if it has not been loaded.
195
+ // Reconstructs messageUUIDs from the history lines.
196
+ function loadSessionHistory(session) {
197
+ if (session._historyLoaded) {
198
+ _lruTouch(session.localId);
199
+ return;
200
+ }
201
+ if (!session.cliSessionId) {
202
+ // Brand-new session with no file yet — history is already [] and that is correct.
203
+ session._historyLoaded = true;
204
+ return;
205
+ }
206
+
207
+ // Flush any buffered appends first so we read the full on-disk state.
208
+ flushSessionBuffer(session);
209
+
210
+ var filePath = sessionFilePath(session.cliSessionId);
211
+ var content;
212
+ try { content = fs.readFileSync(filePath, "utf8"); } catch { content = ""; }
213
+ var lines = content.trim().split("\n");
214
+ var history = [];
215
+ var messageUUIDs = [];
216
+ // Skip line 0 — it's the meta record, already loaded at startup.
217
+ for (var j = 1; j < lines.length; j++) {
218
+ if (!lines[j]) continue;
219
+ var entry;
220
+ try { entry = JSON.parse(lines[j]); } catch { continue; }
221
+ if (entry.type === "message_uuid") {
222
+ messageUUIDs.push({ uuid: entry.uuid, type: entry.messageType, historyIndex: history.length });
86
223
  }
87
- } catch(e) {
88
- console.error("[session] Failed to append to session file:", e.message);
224
+ history.push(entry);
89
225
  }
226
+ session.history = history;
227
+ session.messageUUIDs = messageUUIDs;
228
+ session._historyLoaded = true;
229
+
230
+ _lruTouch(session.localId);
231
+ _lruEvictIfNeeded();
90
232
  }
91
233
 
92
234
  function loadSessions() {
@@ -103,23 +245,27 @@ function createSessionManager(opts) {
103
245
  var loaded = [];
104
246
  for (var i = 0; i < files.length; i++) {
105
247
  if (!files[i].endsWith(".jsonl")) continue;
106
- var content;
107
- try { content = fs.readFileSync(path.join(sessionsDir, files[i]), "utf8"); } catch { continue; }
108
- var lines = content.trim().split("\n");
109
- if (lines.length === 0) continue;
248
+ // Read only the first line (meta record) — history is lazy-loaded on demand.
249
+ var fd;
250
+ var firstLine = "";
251
+ try {
252
+ fd = fs.openSync(path.join(sessionsDir, files[i]), "r");
253
+ var buf = Buffer.alloc(4096);
254
+ var bytesRead = fs.readSync(fd, buf, 0, 4096, 0);
255
+ var chunk = buf.toString("utf8", 0, bytesRead);
256
+ var nl = chunk.indexOf("\n");
257
+ firstLine = nl !== -1 ? chunk.substring(0, nl) : chunk;
258
+ } catch { continue; } finally {
259
+ if (fd !== undefined) try { fs.closeSync(fd); } catch (e) {}
260
+ }
110
261
 
111
262
  var meta;
112
- try { meta = JSON.parse(lines[0]); } catch { continue; }
263
+ try { meta = JSON.parse(firstLine); } catch { continue; }
113
264
  if (meta.type !== "meta" || !meta.cliSessionId) continue;
114
265
 
115
- var history = [];
116
- for (var j = 1; j < lines.length; j++) {
117
- try { history.push(JSON.parse(lines[j])); } catch {}
118
- }
119
-
120
266
  var fileMtime = 0;
121
267
  try { fileMtime = fs.statSync(path.join(sessionsDir, files[i])).mtimeMs; } catch {}
122
- loaded.push({ meta: meta, history: history, mtime: fileMtime });
268
+ loaded.push({ meta: meta, mtime: fileMtime });
123
269
  }
124
270
 
125
271
  loaded.sort(function(a, b) { return a.meta.createdAt - b.meta.createdAt; });
@@ -127,13 +273,6 @@ function createSessionManager(opts) {
127
273
  for (var i = 0; i < loaded.length; i++) {
128
274
  var m = loaded[i].meta;
129
275
  var localId = nextLocalId++;
130
- // Reconstruct messageUUIDs from history
131
- var messageUUIDs = [];
132
- for (var k = 0; k < loaded[i].history.length; k++) {
133
- if (loaded[i].history[k].type === "message_uuid") {
134
- messageUUIDs.push({ uuid: loaded[i].history[k].uuid, type: loaded[i].history[k].messageType, historyIndex: k });
135
- }
136
- }
137
276
  var session = {
138
277
  localId: localId,
139
278
  queryInstance: null,
@@ -147,9 +286,13 @@ function createSessionManager(opts) {
147
286
  title: m.title || "",
148
287
  createdAt: m.createdAt || Date.now(),
149
288
  lastActivity: loaded[i].mtime || m.createdAt || Date.now(),
150
- history: loaded[i].history,
151
- messageUUIDs: messageUUIDs,
289
+ // History is not loaded yet; populated lazily by loadSessionHistory().
290
+ history: [],
291
+ _historyLoaded: false,
292
+ messageUUIDs: [],
152
293
  lastRewindUuid: m.lastRewindUuid || null,
294
+ // File mode already correct on disk — skip chmod on first append.
295
+ _fileModeSet: true,
153
296
  };
154
297
  if (m.vendor) session.vendor = m.vendor;
155
298
  if (m.agentName) session.agentName = m.agentName;
@@ -165,6 +308,14 @@ function createSessionManager(opts) {
165
308
  // Load persisted sessions from disk
166
309
  loadSessions();
167
310
 
311
+ // Drain all write buffers synchronously on process exit to prevent trailing
312
+ // event loss when the daemon shuts down cleanly.
313
+ process.on("exit", function() {
314
+ sessions.forEach(function(session) {
315
+ flushSessionBuffer(session);
316
+ });
317
+ });
318
+
168
319
  function getActiveSession() {
169
320
  return sessions.get(activeSessionId) || null;
170
321
  }
@@ -257,6 +408,7 @@ function createSessionManager(opts) {
257
408
  createdAt: Date.now(),
258
409
  lastActivity: Date.now(),
259
410
  history: [],
411
+ _historyLoaded: true, // new in-memory session — nothing to load from disk
260
412
  messageUUIDs: [],
261
413
  ownerId: (sessionOpts && sessionOpts.ownerId) || null,
262
414
  sessionVisibility: (sessionOpts && sessionOpts.sessionVisibility) || "shared",
@@ -290,6 +442,7 @@ function createSessionManager(opts) {
290
442
  createdAt: Date.now(),
291
443
  lastActivity: Date.now(),
292
444
  history: [],
445
+ _historyLoaded: true, // new in-memory session — nothing to load from disk
293
446
  messageUUIDs: [],
294
447
  ownerId: (sessionOpts && sessionOpts.ownerId) || null,
295
448
  sessionVisibility: (sessionOpts && sessionOpts.sessionVisibility) || "shared",
@@ -315,6 +468,9 @@ function createSessionManager(opts) {
315
468
  }
316
469
 
317
470
  function replayHistory(session, fromIndex, targetWs, transform) {
471
+ // Ensure history is in memory before replaying.
472
+ loadSessionHistory(session);
473
+
318
474
  var _send = (targetWs && sendTo) ? function (obj) { sendTo(targetWs, obj); } : send;
319
475
  var total = session.history.length;
320
476
  if (typeof fromIndex !== "number") {
@@ -357,8 +513,45 @@ function createSessionManager(opts) {
357
513
  }
358
514
 
359
515
  function switchSession(localId, targetWs, transform) {
516
+ if (!sessions.has(localId)) {
517
+ // Only send structured error when a client ws is the initiator. Internal
518
+ // callers (createSession, deleteSession, resumeSession, project-loop) pass
519
+ // targetWs=null and are always trusted.
520
+ if (targetWs && sendTo) {
521
+ sendTo(targetWs, { type: "error", error: "Session not found" });
522
+ }
523
+ return;
524
+ }
360
525
  var session = sessions.get(localId);
361
- if (!session) return;
526
+
527
+ // Access check for client-initiated switches. In single-user mode, sessions
528
+ // with an ownerId are user-scoped and should not be visible without auth;
529
+ // in multi-user mode defer to users.canAccessSession (same rules as
530
+ // getVisibleSessions / server-palette). Internal callers (targetWs=null)
531
+ // bypass this gate — they operate on already-validated session references.
532
+ if (targetWs) {
533
+ var multiUser = users.isMultiUser();
534
+ if (multiUser) {
535
+ var requestingUser = targetWs._clayUser || null;
536
+ if (!requestingUser) {
537
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
538
+ return;
539
+ }
540
+ // Use { visibility: "public" } so canAccessProject passes and the
541
+ // session-level ownership/visibility rules do the real work.
542
+ if (!users.canAccessSession(requestingUser.id, session, { visibility: "public" })) {
543
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
544
+ return;
545
+ }
546
+ } else {
547
+ // Single-user mode: sessions with an ownerId were created in a multi-user
548
+ // context; block access to prevent cross-context leakage.
549
+ if (session.ownerId) {
550
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
551
+ return;
552
+ }
553
+ }
554
+ }
362
555
 
363
556
  activeSessionId = localId;
364
557
  if (targetWs) {
@@ -374,13 +567,16 @@ function createSessionManager(opts) {
374
567
  // Clear unread for single-user mode
375
568
  singleUserUnread[localId] = 0;
376
569
 
570
+ // Update LRU when a session is switched to (history will be loaded in replayHistory).
571
+ _lruTouch(localId);
572
+
377
573
  // In multi-user mode with a specific client, only send to that client
378
574
  var _send = (targetWs && sendTo) ? function (obj) { sendTo(targetWs, obj); } : send;
379
575
 
380
576
  var _capsByVendor = capabilitiesByVendor || {};
381
577
  var _sessionVendor = session.vendor || defaultVendor || "claude";
382
578
  var _vendorCaps = _capsByVendor[_sessionVendor] || {};
383
- _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, hasHistory: (session.history && session.history.length > 0), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null });
579
+ _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, hasHistory: (session._historyLoaded ? session.history.length > 0 : !!session.cliSessionId), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null });
384
580
  // Send vendor-specific slash commands
385
581
  var _vendorCmds = slashCommandsByVendor[_sessionVendor] || slashCommands || [];
386
582
  _send({ type: "slash_commands", commands: _vendorCmds, vendor: _sessionVendor });
@@ -425,6 +621,11 @@ function createSessionManager(opts) {
425
621
  var session = sessions.get(localId);
426
622
  if (!session) return;
427
623
 
624
+ // Drain any pending write buffer before removing the session.
625
+ flushSessionBuffer(session);
626
+ delete _writeBuffers[localId];
627
+ _lruRemove(localId);
628
+
428
629
  // Clean up unread tracking
429
630
  delete singleUserUnread[localId];
430
631
 
@@ -467,6 +668,12 @@ function createSessionManager(opts) {
467
668
  function deleteSessionQuiet(localId) {
468
669
  var session = sessions.get(localId);
469
670
  if (!session) return;
671
+
672
+ // Drain any pending write buffer before removing the session.
673
+ flushSessionBuffer(session);
674
+ delete _writeBuffers[localId];
675
+ _lruRemove(localId);
676
+
470
677
  delete singleUserUnread[localId];
471
678
  cleanupMentionSessions(session);
472
679
  if (session.abortController) {
@@ -539,7 +746,12 @@ function createSessionManager(opts) {
539
746
  function doSendAndRecord(session, obj) {
540
747
  // Stamp every recorded message so history replay preserves original times
541
748
  if (!obj._ts) obj._ts = Date.now();
542
- session.history.push(obj);
749
+ // If history has not been loaded from disk yet, do not trigger a load just
750
+ // to append — the append path writes directly to the file buffer. History
751
+ // will be loaded lazily on the next switchSession/replayHistory call.
752
+ if (session._historyLoaded) {
753
+ session.history.push(obj);
754
+ }
543
755
  appendToSessionFile(session, obj);
544
756
  if (sendEach) {
545
757
  // Multi-user: send to clients whose active session matches this one
@@ -617,6 +829,7 @@ function createSessionManager(opts) {
617
829
  createdAt: Date.now(),
618
830
  lastActivity: Date.now(),
619
831
  history: cliHistory,
832
+ _historyLoaded: true, // caller provided history directly
620
833
  messageUUIDs: [],
621
834
  bookmarked: false,
622
835
  favoriteOrder: null,
@@ -651,12 +864,19 @@ function createSessionManager(opts) {
651
864
  sessions.forEach(function (session) {
652
865
  var titleMatch = (session.title || "New Session").toLowerCase().indexOf(q) !== -1;
653
866
  var contentMatch = false;
654
- for (var i = 0; i < session.history.length; i++) {
655
- var entry = session.history[i];
656
- if ((entry.type === "delta" || entry.type === "user_message" || entry.type === "mention_user" || entry.type === "mention_response") && entry.text) {
657
- if (entry.text.toLowerCase().indexOf(q) !== -1) {
658
- contentMatch = true;
659
- break;
867
+ if (titleMatch) {
868
+ // Skip content search when title already matches — avoids loading history
869
+ // for sessions that are guaranteed to appear in results anyway.
870
+ } else {
871
+ // Lazy-load history to enable content search.
872
+ loadSessionHistory(session);
873
+ for (var i = 0; i < session.history.length; i++) {
874
+ var entry = session.history[i];
875
+ if ((entry.type === "delta" || entry.type === "user_message" || entry.type === "mention_user" || entry.type === "mention_response") && entry.text) {
876
+ if (entry.text.toLowerCase().indexOf(q) !== -1) {
877
+ contentMatch = true;
878
+ break;
879
+ }
660
880
  }
661
881
  }
662
882
  }
@@ -679,6 +899,10 @@ function createSessionManager(opts) {
679
899
  if (!query) return { hits: [], total: 0 };
680
900
  var session = sessions.get(localId);
681
901
  if (!session) return { hits: [], total: 0 };
902
+
903
+ // Lazy-load history for the target session before searching.
904
+ loadSessionHistory(session);
905
+
682
906
  var q = query.toLowerCase();
683
907
  var qLen = query.length;
684
908
  var history = session.history;
@@ -703,7 +927,7 @@ function createSessionManager(opts) {
703
927
  if (idx === -1) break;
704
928
  var s = Math.max(0, idx - 15);
705
929
  var e = Math.min(text.length, idx + qLen + 15);
706
- var snippet = (s > 0 ? "\u2026" : "") + text.substring(s, e) + (e < text.length ? "\u2026" : "");
930
+ var snippet = (s > 0 ? "…" : "") + text.substring(s, e) + (e < text.length ? "…" : "");
707
931
  hits.push({ historyIndex: historyIndex, snippet: snippet, role: role, ts: ts });
708
932
  from = idx + qLen;
709
933
  }
@@ -728,7 +952,7 @@ function createSessionManager(opts) {
728
952
  var seg = turnSegments[segCursor];
729
953
  var s = Math.max(0, idx - 15);
730
954
  var e = Math.min(turnBuffer.length, idx + qLen + 15);
731
- var snippet = (s > 0 ? "\u2026" : "") + turnBuffer.substring(s, e) + (e < turnBuffer.length ? "\u2026" : "");
955
+ var snippet = (s > 0 ? "…" : "") + turnBuffer.substring(s, e) + (e < turnBuffer.length ? "…" : "");
732
956
  hits.push({ historyIndex: seg.historyIndex, snippet: snippet, role: "assistant", ts: seg.ts });
733
957
  from = idx + qLen;
734
958
  }
@@ -858,6 +1082,8 @@ function createSessionManager(opts) {
858
1082
  },
859
1083
  saveSessionFile: saveSessionFile,
860
1084
  appendToSessionFile: appendToSessionFile,
1085
+ loadSessionHistory: loadSessionHistory,
1086
+ flushSessionBuffer: flushSessionBuffer,
861
1087
  sendAndRecord: doSendAndRecord,
862
1088
  sendToSession: doSendToSession,
863
1089
  findTurnBoundary: findTurnBoundary,
@@ -17,6 +17,7 @@ var net = require("net");
17
17
  var crypto = require("crypto");
18
18
  var path = require("path");
19
19
  var fs = require("fs");
20
+ var os = require("os");
20
21
 
21
22
  var socketPath = process.argv[2];
22
23
  if (!socketPath) {
@@ -416,8 +417,15 @@ async function handleQueryStart(msg) {
416
417
  // Build query options (callbacks are local, everything else from daemon)
417
418
  var options = msg.options || {};
418
419
  options.abortController = abortController;
419
- options.debug = true;
420
- options.debugFile = "/tmp/clagentic-cli-debug-" + process.pid + ".log";
420
+ if (process.env.CLAGENTIC_DEBUG === "1") {
421
+ var _logDir = path.join(os.homedir(), ".clagentic", "worker-logs");
422
+ fs.mkdirSync(_logDir, { recursive: true, mode: 0o700 });
423
+ var _logFile = path.join(_logDir, process.pid + ".log");
424
+ // Create with 0o600 before passing to the SDK so the file is never world-readable
425
+ fs.writeFileSync(_logFile, "", { flag: "a", mode: 0o600 });
426
+ options.debug = true;
427
+ options.debugFile = _logFile;
428
+ }
421
429
  applyWorkerClaudeBinary(options);
422
430
  if (options.mcpServerDescriptors && options.mcpServerDescriptors.length) {
423
431
  try {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.0.5-beta.1",
6
+ "version": "1.1.0-beta.1",
7
7
  "description": "Self-hosted console for Claude Code and Codex. Multi-user, browser-based, persistent AI sessions.",
8
8
  "bin": {
9
9
  "clagentic": "./bin/cli.js",