@clagentic/console 1.0.5-beta.1 → 1.1.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.
- package/bin/cli.js +5 -1
- package/lib/audit.js +57 -0
- package/lib/os-users.js +5 -0
- package/lib/project-connection.js +11 -22
- package/lib/public/app.js +8 -2
- package/lib/public/modules/app-projects.js +14 -0
- package/lib/public/modules/markdown.js +5 -2
- package/lib/public/modules/sidebar-sessions.js +12 -0
- package/lib/sdk-bridge.js +2 -0
- package/lib/sdk-worker.js +11 -2
- package/lib/server-admin.js +69 -0
- package/lib/server-auth.js +120 -7
- package/lib/server-settings.js +5 -0
- package/lib/sessions.js +264 -38
- package/lib/updater.js +18 -4
- package/lib/yoke/adapters/claude-worker.js +10 -2
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -2606,7 +2606,11 @@ var { checkAndUpdate } = require("../lib/updater");
|
|
|
2606
2606
|
var currentVersion = require("../package.json").version;
|
|
2607
2607
|
|
|
2608
2608
|
(async function () {
|
|
2609
|
-
|
|
2609
|
+
// Read update channel from saved config (best-effort — may not exist yet on first run)
|
|
2610
|
+
var _startupConfig = null;
|
|
2611
|
+
try { _startupConfig = loadConfig(); } catch (e) {}
|
|
2612
|
+
var _updateChannel = (_startupConfig && _startupConfig.updateChannel) || (currentVersion.includes("-") ? "beta" : "stable");
|
|
2613
|
+
var updated = await checkAndUpdate(currentVersion, skipUpdate, _updateChannel);
|
|
2610
2614
|
if (updated) return;
|
|
2611
2615
|
|
|
2612
2616
|
// Dev mode — foreground daemon with file watching
|
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
|
}
|
|
@@ -181,32 +184,18 @@ function attachConnection(ctx) {
|
|
|
181
184
|
}
|
|
182
185
|
ws._clayActiveSession = active.localId;
|
|
183
186
|
var _vendorCaps = (sm.capabilitiesByVendor && sm.capabilitiesByVendor[active.vendor || sm.defaultVendor || "claude"]) || {};
|
|
184
|
-
|
|
187
|
+
// Load history from disk before checking hasHistory — the session may have
|
|
188
|
+
// been evicted from the LRU cache (lr-f311 lazy load), in which case
|
|
189
|
+
// active.history is [] in memory even though the session file has content.
|
|
190
|
+
sm.loadSessionHistory(active);
|
|
191
|
+
sendTo(ws, { type: "session_switched", id: active.localId, cliSessionId: active.cliSessionId || null, loop: active.loop || null, vendor: active.vendor || null, hasHistory: (active.history.length > 0), capabilities: _vendorCaps, agentName: active.agentName || null });
|
|
185
192
|
// Send per-session context sources
|
|
186
193
|
var sessionSources = loadContextSources(slug, active.localId);
|
|
187
194
|
sendTo(ws, { type: "context_sources_state", active: sessionSources });
|
|
188
195
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
fromIndex = sm.findTurnBoundary(active.history, Math.max(0, total - sm.HISTORY_PAGE_SIZE));
|
|
193
|
-
}
|
|
194
|
-
sendTo(ws, { type: "history_meta", total: total, from: fromIndex });
|
|
195
|
-
for (var i = fromIndex; i < total; i++) {
|
|
196
|
-
sendTo(ws, hydrateImageRefs(active.history[i]));
|
|
197
|
-
}
|
|
198
|
-
var _lastUsage = null, _lastModelUsage = null, _lastCost = null, _lastStreamInputTokens = null;
|
|
199
|
-
for (var _ri = total - 1; _ri >= 0; _ri--) {
|
|
200
|
-
if (active.history[_ri].type === "result") {
|
|
201
|
-
var _r = active.history[_ri];
|
|
202
|
-
_lastUsage = _r.usage || null;
|
|
203
|
-
_lastModelUsage = _r.modelUsage || null;
|
|
204
|
-
_lastCost = _r.cost != null ? _r.cost : null;
|
|
205
|
-
_lastStreamInputTokens = _r.lastStreamInputTokens || null;
|
|
206
|
-
break;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
sendTo(ws, { type: "history_done", lastUsage: _lastUsage, lastModelUsage: _lastModelUsage, lastCost: _lastCost, lastStreamInputTokens: _lastStreamInputTokens, contextUsage: active.lastContextUsage || null });
|
|
196
|
+
// Use sm.replayHistory so history is guaranteed loaded from disk (handles
|
|
197
|
+
// LRU eviction) and the replay logic stays in one place.
|
|
198
|
+
sm.replayHistory(active, undefined, ws, hydrateImageRefs);
|
|
210
199
|
|
|
211
200
|
if (active.isProcessing) {
|
|
212
201
|
sendTo(ws, { type: "status", status: "processing" });
|
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';
|
|
@@ -625,6 +625,11 @@ import { initMention, handleMentionStart, handleMentionStream, handleMentionDone
|
|
|
625
625
|
basePath = "/p/" + newSlug + "/";
|
|
626
626
|
wsPath = "/p/" + newSlug + "/ws";
|
|
627
627
|
store.set({ basePath: basePath, wsPath: wsPath });
|
|
628
|
+
// Clear session list before connecting so the sidebar doesn't show
|
|
629
|
+
// the previous project's sessions. Must be called here (not inside
|
|
630
|
+
// resetClientState) because resetClientState is also called from
|
|
631
|
+
// session_switched where the list must be preserved.
|
|
632
|
+
resetSessionList();
|
|
628
633
|
resetClientState();
|
|
629
634
|
connect();
|
|
630
635
|
}
|
|
@@ -1006,6 +1011,7 @@ import { initMention, handleMentionStart, handleMentionStream, handleMentionDone
|
|
|
1006
1011
|
// --- Projects module ---
|
|
1007
1012
|
initProjects();
|
|
1008
1013
|
onProjectListUpdated(function (projects) { updateMobileProjectsTabBadge(projects); });
|
|
1014
|
+
onResetClientState(function () { resetSessionList(); });
|
|
1009
1015
|
|
|
1010
1016
|
// --- Home Hub module ---
|
|
1011
1017
|
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,11 @@ 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
|
+
// NOTE: session list reset is NOT done here. resetClientState() is also called
|
|
430
|
+
// from session_switched (within-project session switching) where the session
|
|
431
|
+
// list must be preserved. Session list clearing is done only in switchProject()
|
|
432
|
+
// and the popstate handler via _onResetClientState, which are the only paths
|
|
433
|
+
// that actually change projects.
|
|
426
434
|
}
|
|
427
435
|
|
|
428
436
|
export function switchProject(slug) {
|
|
@@ -454,6 +462,12 @@ export function switchProject(slug) {
|
|
|
454
462
|
} else {
|
|
455
463
|
history.pushState(null, "", "/p/" + slug + "/");
|
|
456
464
|
}
|
|
465
|
+
// Clear the session list immediately so the sidebar shows blank (not the
|
|
466
|
+
// previous project's sessions) while waiting for the new project's
|
|
467
|
+
// session_list. Must happen here, NOT in resetClientState(), because
|
|
468
|
+
// resetClientState() is also called from session_switched (within-project
|
|
469
|
+
// session switch) where the session list must stay intact.
|
|
470
|
+
if (typeof _onResetClientState === "function") _onResetClientState();
|
|
457
471
|
resetClientState();
|
|
458
472
|
connect();
|
|
459
473
|
}
|
|
@@ -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
|
-
|
|
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,18 @@ 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 immediately wipes the DOM so the sidebar is blank while waiting
|
|
587
|
+
// for the new project's session_list. Bypasses the fingerprint guard on
|
|
588
|
+
// purpose — when both old and new fingerprints are "" (empty list) the guard
|
|
589
|
+
// would return early before clearing innerHTML, leaving stale sessions visible.
|
|
590
|
+
export function resetSessionList() {
|
|
591
|
+
cachedSessions = [];
|
|
592
|
+
_sessionListFingerprint = "__reset__";
|
|
593
|
+
var listEl = getSessionListEl();
|
|
594
|
+
if (listEl) listEl.innerHTML = "";
|
|
595
|
+
}
|
|
596
|
+
|
|
585
597
|
export function getSearchQuery() {
|
|
586
598
|
return searchQuery;
|
|
587
599
|
}
|
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
|
-
|
|
368
|
-
|
|
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.
|
package/lib/server-admin.js
CHANGED
|
@@ -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
|
|
package/lib/server-auth.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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)
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
package/lib/server-settings.js
CHANGED
|
@@ -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
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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
|
-
|
|
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
|
-
|
|
107
|
-
|
|
108
|
-
var
|
|
109
|
-
|
|
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(
|
|
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,
|
|
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
|
-
|
|
151
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
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 ? "
|
|
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 ? "
|
|
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,
|
package/lib/updater.js
CHANGED
|
@@ -99,16 +99,30 @@ function reExec() {
|
|
|
99
99
|
});
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
async function checkAndUpdate(currentVersion, skipUpdate) {
|
|
102
|
+
async function checkAndUpdate(currentVersion, skipUpdate, channel) {
|
|
103
103
|
if (skipUpdate) return false;
|
|
104
104
|
|
|
105
|
-
|
|
105
|
+
// Determine which npm tag(s) to check. When the current version is a pre-release
|
|
106
|
+
// (e.g. 1.0.5-beta.1) or the saved channel is "beta", check the beta tag.
|
|
107
|
+
// Always also check latest so a stable release is never missed.
|
|
108
|
+
var isBeta = channel === "beta" || (currentVersion && currentVersion.includes("-"));
|
|
109
|
+
var tags = isBeta ? ["beta", "latest"] : ["latest"];
|
|
110
|
+
|
|
111
|
+
var latest = null;
|
|
112
|
+
for (var ti = 0; ti < tags.length; ti++) {
|
|
113
|
+
var candidate = await fetchVersion(tags[ti]);
|
|
114
|
+
if (candidate && (!latest || isNewer(candidate, latest))) {
|
|
115
|
+
latest = candidate;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
106
119
|
if (!latest || !isNewer(latest, currentVersion)) return false;
|
|
107
120
|
|
|
121
|
+
var tag = (isBeta && latest.includes("-")) ? "beta" : "latest";
|
|
108
122
|
log(sym.pointer + " " + a.bold + "Update available" + a.reset + " " + a.dim + currentVersion + " -> " + latest + a.reset);
|
|
109
123
|
log(sym.bar + " Installing...");
|
|
110
124
|
|
|
111
|
-
if (performUpdate()) {
|
|
125
|
+
if (performUpdate(tag === "beta" ? "beta" : "stable")) {
|
|
112
126
|
log(sym.done + " Updated to " + a.green + latest + a.reset);
|
|
113
127
|
log("");
|
|
114
128
|
reExec();
|
|
@@ -116,7 +130,7 @@ async function checkAndUpdate(currentVersion, skipUpdate) {
|
|
|
116
130
|
}
|
|
117
131
|
|
|
118
132
|
log(sym.warn + " " + a.yellow + "Update failed" + a.reset + a.dim + " (permission denied?)" + a.reset);
|
|
119
|
-
log(sym.bar + " " + a.dim + "Run manually: npm install -g @clagentic/console@
|
|
133
|
+
log(sym.bar + " " + a.dim + "Run manually: npm install -g @clagentic/console@" + tag + a.reset);
|
|
120
134
|
log("");
|
|
121
135
|
return false;
|
|
122
136
|
}
|
|
@@ -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
|
-
|
|
420
|
-
|
|
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