@clagentic/console 1.4.0 → 1.5.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +56 -28
  2. package/bin/cli.js +163 -60
  3. package/deploy/clagentic-console.service +30 -0
  4. package/lib/agents-favorites.js +3 -1
  5. package/lib/agents.js +75 -5
  6. package/lib/browser-mcp-server.js +5 -5
  7. package/lib/clone-validate.js +44 -0
  8. package/lib/config.js +75 -0
  9. package/lib/daemon.js +119 -8
  10. package/lib/dm.js +12 -1
  11. package/lib/ipc.js +12 -0
  12. package/lib/lite-detect.js +92 -0
  13. package/lib/os-users.js +8 -8
  14. package/lib/project-connection.js +7 -1
  15. package/lib/project-external-trigger.js +65 -6
  16. package/lib/project-loop.js +44 -3
  17. package/lib/project-sessions.js +95 -37
  18. package/lib/project.js +6 -1
  19. package/lib/public/app.js +6 -3
  20. package/lib/public/css/at-agents.css +68 -0
  21. package/lib/public/index.html +60 -0
  22. package/lib/public/modules/app-messages.js +38 -4
  23. package/lib/public/modules/at-agents.js +248 -0
  24. package/lib/public/modules/escape-html.js +19 -0
  25. package/lib/public/modules/filebrowser.js +12 -9
  26. package/lib/public/modules/input.js +26 -4
  27. package/lib/public/modules/pending-navigate.js +28 -0
  28. package/lib/public/modules/playbook.js +1 -1
  29. package/lib/public/modules/project-settings.js +75 -0
  30. package/lib/public/modules/project-switcher.js +1 -1
  31. package/lib/public/modules/server-settings.js +33 -0
  32. package/lib/public/modules/sticky-notes-fmt.js +52 -0
  33. package/lib/public/modules/sticky-notes.js +23 -5
  34. package/lib/public/modules/theme.js +1 -1
  35. package/lib/public/modules/tool-palette.js +1 -1
  36. package/lib/public/modules/utils.js +1 -3
  37. package/lib/public/style.css +1 -0
  38. package/lib/push.js +13 -2
  39. package/lib/scheduler.js +26 -2
  40. package/lib/sdk-bridge.js +7 -4
  41. package/lib/server-dm.js +16 -0
  42. package/lib/server-settings.js +42 -0
  43. package/lib/server-skills.js +10 -7
  44. package/lib/server.js +14 -3
  45. package/lib/sessions.js +4 -0
  46. package/lib/ws-schema.js +11 -1
  47. package/lib/yoke/adapters/claude-worker.js +2 -2
  48. package/lib/yoke/adapters/claude.js +47 -10
  49. package/lib/yoke/adapters/codex.js +14 -3
  50. package/lib/yoke/mcp-bridge-server.js +7 -7
  51. package/package.json +5 -2
  52. package/scripts/check-client-imports.js +94 -0
  53. package/scripts/postinstall.js +150 -0
  54. package/lib/relay-agent-claims.js +0 -480
@@ -0,0 +1,30 @@
1
+ [Unit]
2
+ Description=Clagentic Console daemon
3
+ After=network.target
4
+
5
+ [Service]
6
+ Type=simple
7
+ ExecStart=/usr/local/bin/clagentic-daemon.sh
8
+ Restart=always
9
+ RestartSec=5
10
+ # EX_CONFIG (78) is a fatal configuration error (mis-set CLAGENTIC_HOME, unsupported Node) — do not restart-loop
11
+ RestartPreventExitStatus=78
12
+ KillMode=mixed
13
+ TimeoutStopSec=20
14
+ SendSIGKILL=yes
15
+ # Soft ceiling — kernel begins reclaiming memory early (requires systemd 240+; host runs systemd 255)
16
+ MemoryHigh=70%
17
+ # Hard ceiling — triggers per-service OOM so OOMPolicy fires instead of host-level OOM killer
18
+ MemoryMax=85%
19
+ # On OOM, kill all remaining cgroup members so no orphaned child processes survive
20
+ OOMPolicy=kill
21
+ StandardOutput=journal
22
+ StandardError=journal
23
+ SyslogIdentifier=clagentic-console
24
+ Environment=SHELL=/bin/bash
25
+ Environment=PATH=/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
26
+ # TODO(lr-9452): rename to CLAGENTIC_CONSOLE_MAX_CONCURRENT_SESSIONS once sdk-bridge.js is updated
27
+ Environment=CLAGENTIC_MAX_CONCURRENT_SESSIONS=50
28
+
29
+ [Install]
30
+ WantedBy=multi-user.target
@@ -150,8 +150,10 @@ function addFavorite(agent) {
150
150
  }
151
151
 
152
152
  // Remove an agent from favorites. Returns true if removed, false if not present.
153
+ // Note: schema v2 entries have only {name, addedAt} — no kind field — so we
154
+ // guard on name only (matching addFavorite and sameAgent).
153
155
  function removeFavorite(agent) {
154
- if (!agent || !agent.name || !agent.kind) return false;
156
+ if (!agent || !agent.name) return false;
155
157
  var store = readStore();
156
158
  var before = store.favorites.length;
157
159
  store.favorites = store.favorites.filter(function (f) { return !sameAgent(f, agent); });
package/lib/agents.js CHANGED
@@ -28,11 +28,8 @@
28
28
 
29
29
  var fs = require("fs");
30
30
  var path = require("path");
31
- var os = require("os");
32
-
33
- var REAL_HOME = process.env.SUDO_USER
34
- ? path.join("/home", process.env.SUDO_USER)
35
- : os.homedir();
31
+ // Use config.js REAL_HOME — it handles sudo/getent/root-reject uniformly.
32
+ var { REAL_HOME } = require("./config");
36
33
 
37
34
  // Still exported for callers that referenced them (backwards compat).
38
35
  var AGENTS_SOURCE_DIR = path.join(REAL_HOME, ".claude", "agents");
@@ -223,12 +220,85 @@ function discoverAllAgents() {
223
220
  return getAll();
224
221
  }
225
222
 
223
+ // Read all named-agent definitions from a project-local .claude/agents/ directory,
224
+ // merged with the global ~/.claude/agents/ directory.
225
+ //
226
+ // Claude Code resolves agents from both locations. Project-local definitions
227
+ // take precedence: if the same slug appears in both directories, the
228
+ // project-local entry wins.
229
+ //
230
+ // projectDir: absolute path to the project root (cwd).
231
+ // Returns: array of { name, slug, description } objects, sorted by name.
232
+ // Returns [] if neither directory exists or is readable — callers treat
233
+ // an empty array as "no agents" and degrade gracefully.
234
+ //
235
+ // This reads the filesystem directly (no SDK subprocess) — it is synchronous
236
+ // and cheap. Each agents directory is small (typically 0–20 files).
237
+ function _readAgentsFromDir(agentsDir) {
238
+ var entries;
239
+ try {
240
+ entries = fs.readdirSync(agentsDir);
241
+ } catch (e) {
242
+ // Directory absent or unreadable — not an error.
243
+ return [];
244
+ }
245
+ var results = [];
246
+ for (var i = 0; i < entries.length; i++) {
247
+ var entry = entries[i];
248
+ if (!entry || !entry.endsWith(".md")) continue;
249
+ var slug = entry.slice(0, -3); // strip .md
250
+ if (!slug) continue;
251
+ var filePath = path.join(agentsDir, entry);
252
+ var raw;
253
+ try {
254
+ raw = fs.readFileSync(filePath, "utf8");
255
+ } catch (e) {
256
+ continue;
257
+ }
258
+ var parsed = parseFrontmatter(raw);
259
+ var name = (parsed && parsed.meta && parsed.meta.name) ? String(parsed.meta.name) : slug;
260
+ var description = (parsed && parsed.meta && parsed.meta.description) ? String(parsed.meta.description) : "";
261
+ results.push({ name: name, slug: slug, description: description });
262
+ }
263
+ return results;
264
+ }
265
+
266
+ // _globalAgentsDir is an optional override used in tests; callers must not pass it.
267
+ function readProjectAgents(projectDir, _globalAgentsDir) {
268
+ if (!projectDir || typeof projectDir !== "string") return [];
269
+
270
+ var localDir = path.join(projectDir, ".claude", "agents");
271
+ var globalDir = (typeof _globalAgentsDir === "string" && _globalAgentsDir)
272
+ ? _globalAgentsDir
273
+ : path.join(REAL_HOME, ".claude", "agents");
274
+
275
+ var localEntries = _readAgentsFromDir(localDir);
276
+ var globalEntries = _readAgentsFromDir(globalDir);
277
+
278
+ // Build a slug-keyed map from global entries, then overlay local entries.
279
+ // Local definitions win when the same slug appears in both directories.
280
+ var bySlug = Object.create(null);
281
+ for (var i = 0; i < globalEntries.length; i++) {
282
+ bySlug[globalEntries[i].slug] = globalEntries[i];
283
+ }
284
+ for (var j = 0; j < localEntries.length; j++) {
285
+ bySlug[localEntries[j].slug] = localEntries[j];
286
+ }
287
+
288
+ var results = Object.keys(bySlug).map(function (slug) { return bySlug[slug]; });
289
+ results.sort(function (a, b) {
290
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
291
+ });
292
+ return results;
293
+ }
294
+
226
295
  module.exports = {
227
296
  AGENTS_SOURCE_DIR: AGENTS_SOURCE_DIR,
228
297
  PLUGINS_CACHE_DIR: PLUGINS_CACHE_DIR,
229
298
  parseFrontmatter: parseFrontmatter,
230
299
  slugifyAgentName: slugifyAgentName,
231
300
  readAgentToolsFromFile: readAgentToolsFromFile,
301
+ readProjectAgents: readProjectAgents,
232
302
  // New SDK-backed surface:
233
303
  refresh: refresh,
234
304
  getAll: getAll,
@@ -320,10 +320,10 @@ function getToolDefs(sendCommand, getTabList, contextOps) {
320
320
  function (args) {
321
321
  var script = "(function() {" +
322
322
  "var el = document.querySelector(" + JSON.stringify(args.selector) + ");" +
323
- "if (!el) return 'Element not found: " + args.selector.replace(/'/g, "\\'") + "';" +
323
+ "if (!el) return 'Element not found: ' + " + JSON.stringify(args.selector) + ";" +
324
324
  "el.scrollIntoView({ block: 'center', behavior: 'instant' });" +
325
325
  "el.click();" +
326
- "return 'Clicked: " + args.selector.replace(/'/g, "\\'") + "';" +
326
+ "return 'Clicked: ' + " + JSON.stringify(args.selector) + ";" +
327
327
  "})()";
328
328
  return sendCommand("tab_evaluate", { tabId: args.tabId, script: script }).then(function (result) {
329
329
  return { content: [{ type: "text", text: result.value || "Click executed" }] };
@@ -343,14 +343,14 @@ function getToolDefs(sendCommand, getTabList, contextOps) {
343
343
  function (args) {
344
344
  var script = "(function() {" +
345
345
  "var el = document.querySelector(" + JSON.stringify(args.selector) + ");" +
346
- "if (!el) return 'Element not found: " + args.selector.replace(/'/g, "\\'") + "';" +
346
+ "if (!el) return 'Element not found: ' + " + JSON.stringify(args.selector) + ";" +
347
347
  "el.focus();" +
348
348
  "var nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value') || Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value');" +
349
349
  "if (nativeSetter && nativeSetter.set) { nativeSetter.set.call(el, " + JSON.stringify(args.text) + "); }" +
350
350
  "else { el.value = " + JSON.stringify(args.text) + "; }" +
351
351
  "el.dispatchEvent(new Event('input', { bubbles: true }));" +
352
352
  "el.dispatchEvent(new Event('change', { bubbles: true }));" +
353
- "return 'Typed into: " + args.selector.replace(/'/g, "\\'") + "';" +
353
+ "return 'Typed into: ' + " + JSON.stringify(args.selector) + ";" +
354
354
  "})()";
355
355
  return sendCommand("tab_evaluate", { tabId: args.tabId, script: script }).then(function (result) {
356
356
  return { content: [{ type: "text", text: result.value || "Type executed" }] };
@@ -375,7 +375,7 @@ function getToolDefs(sendCommand, getTabList, contextOps) {
375
375
  "var el = document.querySelector(" + JSON.stringify(args.selector) + ");" +
376
376
  "if (!el) return 'Element not found';" +
377
377
  "el.scrollIntoView({ block: 'center', behavior: 'smooth' });" +
378
- "return 'Scrolled to: " + args.selector.replace(/'/g, "\\'") + "';" +
378
+ "return 'Scrolled to: ' + " + JSON.stringify(args.selector) + ";" +
379
379
  "})()";
380
380
  } else {
381
381
  var x = args.x || 0;
@@ -0,0 +1,44 @@
1
+ // clone-validate.js — URL validation and spawn-arg hardening for git clone (lr-28b5).
2
+ //
3
+ // Extracted from daemon.js onCloneProject so this logic is directly testable.
4
+ // Daemon.js calls validateCloneUrl() and buildCloneArgs() rather than inlining.
5
+
6
+ var CLONE_ALLOWED_SCHEMES = ["https://", "http://", "git://", "ssh://", "git@"];
7
+
8
+ // Validate a git clone URL.
9
+ // Returns null on success, or an error string describing the rejection.
10
+ function validateCloneUrl(cloneUrl) {
11
+ // Reject leading-dash values: option injection vector (e.g. --upload-pack=<cmd>).
12
+ if (cloneUrl.startsWith("-")) {
13
+ return "Invalid clone URL: URL must not start with '-'";
14
+ }
15
+ // Scheme allow-list: only permit safe transports.
16
+ for (var i = 0; i < CLONE_ALLOWED_SCHEMES.length; i++) {
17
+ if (cloneUrl.startsWith(CLONE_ALLOWED_SCHEMES[i])) {
18
+ return null; // allowed
19
+ }
20
+ }
21
+ return "Invalid clone URL: unsupported scheme. Allowed: https, http, git, ssh, git@";
22
+ }
23
+
24
+ // Build the argv and env overrides for the git clone subprocess.
25
+ //
26
+ // The "--" argv terminator (argv[1]) prevents cloneUrl from being parsed as a
27
+ // git option even if validation is somehow bypassed.
28
+ //
29
+ // GIT_ALLOW_PROTOCOL restricts git's transport layer to safe protocols,
30
+ // blocking ext:: and file:: transports at the git level as a second line of
31
+ // defence in case future validation regressions let through a bad URL.
32
+ //
33
+ // Returns { args: string[], envOverrides: Object } — callers merge envOverrides
34
+ // into the spawn env.
35
+ function buildCloneArgs(cloneUrl, targetDir) {
36
+ return {
37
+ args: ["clone", "--", cloneUrl, targetDir],
38
+ envOverrides: {
39
+ GIT_ALLOW_PROTOCOL: "https:http:git:ssh",
40
+ },
41
+ };
42
+ }
43
+
44
+ module.exports = { validateCloneUrl: validateCloneUrl, buildCloneArgs: buildCloneArgs, CLONE_ALLOWED_SCHEMES: CLONE_ALLOWED_SCHEMES };
package/lib/config.js CHANGED
@@ -73,6 +73,13 @@ function socketPath() {
73
73
  var pipeName = _devMode ? "clagentic-daemon-dev" : "clagentic-daemon";
74
74
  return "\\\\.\\pipe\\" + pipeName;
75
75
  }
76
+ return path.join(CONFIG_DIR, "console", _devMode ? "daemon-dev.sock" : "daemon.sock");
77
+ }
78
+
79
+ // Path used by pre-1.5 daemons (before lr-88fe moved the socket into console/).
80
+ // Only meaningful on Unix — Windows named pipes were unchanged by lr-88fe.
81
+ function oldSocketPath() {
82
+ if (process.platform === "win32") return null;
76
83
  return path.join(CONFIG_DIR, _devMode ? "daemon-dev.sock" : "daemon.sock");
77
84
  }
78
85
 
@@ -88,6 +95,72 @@ function chmodSafe(filePath, mode) {
88
95
  function ensureConfigDir() {
89
96
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
90
97
  chmodSafe(CONFIG_DIR, 0o700);
98
+ fs.mkdirSync(path.join(CONFIG_DIR, "console"), { recursive: true });
99
+ chmodSafe(path.join(CONFIG_DIR, "console"), 0o700);
100
+ // Guard stale old socket cleanup: only unlink when the old-path daemon is
101
+ // dead. If a live pre-1.5 daemon is still on that path we must not yank its
102
+ // socket out from under it — warn instead so the operator can shut it down
103
+ // cleanly. (lr-6ed3)
104
+ //
105
+ // checkOldDaemon() is async; we use a fire-and-forget approach here because
106
+ // ensureConfigDir() is sync in several call sites. The probe resolves quickly
107
+ // (connect or 1 s timeout) and the unlink/warn runs as a microtask.
108
+ if (process.platform !== "win32") {
109
+ var oldSock = oldSocketPath();
110
+ if (oldSock && fs.existsSync(oldSock)) {
111
+ checkOldDaemon().then(function (result) {
112
+ if (!result) return; // Windows guard inside checkOldDaemon()
113
+ if (result.alive) {
114
+ // A live pre-1.5 daemon is still using this socket — leave it alone.
115
+ console.warn("[config] Pre-1.5 daemon is still running at " + oldSock + " — socket not removed. Run clagentic-console --shutdown to stop it.");
116
+ } else {
117
+ try {
118
+ fs.unlinkSync(oldSock);
119
+ console.warn("[config] Removed stale pre-1.5 socket at " + oldSock + " (moved to " + socketPath() + ")");
120
+ } catch (e) {
121
+ console.warn("[config] Could not remove stale socket at " + oldSock + ": " + e.message);
122
+ }
123
+ }
124
+ });
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Check whether a pre-1.5 daemon is still live on the old socket path.
131
+ *
132
+ * Returns a Promise resolving to:
133
+ * { alive: true, sockPath: <oldSocketPath> } — live old daemon listening
134
+ * { alive: false, sockPath: <oldSocketPath> } — old socket file absent or dead
135
+ * null — Windows (old path unchanged, skip)
136
+ *
137
+ * Caller is responsible for acting on the result (shutdown + wait, or unlink).
138
+ */
139
+ function checkOldDaemon() {
140
+ if (process.platform === "win32") return Promise.resolve(null);
141
+ var oldSock = oldSocketPath();
142
+ if (!oldSock) return Promise.resolve(null);
143
+
144
+ return new Promise(function (resolve) {
145
+ if (!fs.existsSync(oldSock)) return resolve({ alive: false, sockPath: oldSock });
146
+
147
+ var client = net.connect(oldSock);
148
+ var timer = setTimeout(function () {
149
+ client.destroy();
150
+ resolve({ alive: false, sockPath: oldSock });
151
+ }, 1000);
152
+
153
+ client.on("connect", function () {
154
+ clearTimeout(timer);
155
+ client.destroy();
156
+ resolve({ alive: true, sockPath: oldSock });
157
+ });
158
+
159
+ client.on("error", function () {
160
+ clearTimeout(timer);
161
+ resolve({ alive: false, sockPath: oldSock });
162
+ });
163
+ });
91
164
  }
92
165
 
93
166
  function loadConfig() {
@@ -307,6 +380,7 @@ module.exports = {
307
380
  EXTERNAL_TRIGGERS_DIR: EXTERNAL_TRIGGERS_DIR,
308
381
  configPath: configPath,
309
382
  socketPath: socketPath,
383
+ oldSocketPath: oldSocketPath,
310
384
  logPath: logPath,
311
385
  ensureConfigDir: ensureConfigDir,
312
386
  loadConfig: loadConfig,
@@ -314,6 +388,7 @@ module.exports = {
314
388
  isPidAlive: isPidAlive,
315
389
  isDaemonAlive: isDaemonAlive,
316
390
  isDaemonAliveAsync: isDaemonAliveAsync,
391
+ checkOldDaemon: checkOldDaemon,
317
392
  generateSlug: generateSlug,
318
393
  clearStaleConfig: clearStaleConfig,
319
394
  crashInfoPath: crashInfoPath,
package/lib/daemon.js CHANGED
@@ -3,8 +3,8 @@
3
3
  // --- Node version check ---
4
4
  var nodeMajor = parseInt(process.versions.node.split(".")[0], 10);
5
5
  if (nodeMajor < 20) {
6
- console.error("\x1b[31m[clay] Node.js 20+ is required (current: " + process.version + ")\x1b[0m");
7
- console.error("[clay] The Claude Agent SDK 0.2.40+ requires Node 20 for Symbol.dispose support.");
6
+ console.error("\x1b[31m[clagentic-console] Node.js 20+ is required (current: " + process.version + ")\x1b[0m");
7
+ console.error("[clagentic-console] The Claude Agent SDK 0.2.40+ requires Node 20 for Symbol.dispose support.");
8
8
  console.error("");
9
9
  console.error(" Upgrade Node: nvm install 22 && nvm use 22");
10
10
  process.exit(78); // EX_CONFIG — fatal config error, don't auto-restart
@@ -23,24 +23,64 @@ delete process.env.CLAUDECODE;
23
23
 
24
24
  var fs = require("fs");
25
25
  var path = require("path");
26
- var { loadConfig, saveConfig, socketPath, generateSlug, syncClayrc, removeFromClayrc, writeCrashInfo, readCrashInfo, clearCrashInfo, isPidAlive, clearStaleConfig, REAL_HOME } = require("./config");
26
+ var { loadConfig, saveConfig, socketPath, ensureConfigDir, generateSlug, syncClayrc, removeFromClayrc, writeCrashInfo, readCrashInfo, clearCrashInfo, isPidAlive, clearStaleConfig, REAL_HOME } = require("./config");
27
27
  var { createIPCServer } = require("./ipc");
28
28
  var { createServer, generateAuthToken } = require("./server");
29
29
  var { checkAclSupport, grantProjectAccess, revokeProjectAccess, provisionAllUsers, provisionLinuxUser, grantAllUsersAccess, deactivateLinuxUser, ensureProjectsDir } = require("./os-users");
30
30
  var usersModule = require("./users");
31
31
  var { createWorktree, removeWorktree, isWorktree } = require("./worktree");
32
32
  var { isWorktreeSlug, scanAndRegisterWorktrees, rescanWorktrees, cleanupWorktreesForParent, getFilteredRemovedProjects, registerWorktreeSlug, unregisterWorktreeSlug } = require("./daemon-projects");
33
+ var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
33
34
  var { DEFAULT_MEM_AVAILABLE_MIN_MB } = require("./sdk-bridge");
35
+ var liteDetect = require("./lite-detect");
36
+ var { execFile: liteExecFile } = require("child_process");
34
37
 
35
38
  var daemonVersion = require("../package.json").version;
36
39
  var configFile = process.env.CLAGENTIC_CONFIG || process.env.CLAY_CONFIG || require("./config").configPath();
37
40
  var config;
38
41
 
42
+ // Ensure dirs exist before any file access — daemon must be self-sufficient when
43
+ // launched directly by systemd/supervisor with no prior CLI run.
44
+ ensureConfigDir();
45
+
39
46
  try {
40
47
  config = JSON.parse(fs.readFileSync(configFile, "utf8"));
41
48
  } catch (e) {
42
- console.error("[daemon] Failed to read config:", e.message);
43
- process.exit(1);
49
+ if (e.code === "ENOENT") {
50
+ // Guard: detect CLAGENTIC_HOME mis-pointed at the socket subdirectory.
51
+ //
52
+ // Symptom: CLAGENTIC_HOME=~/.clagentic/console → CONFIG_DIR ends in
53
+ // ".clagentic/console" and configFile = CONFIG_DIR/daemon.json (absent),
54
+ // but the real config lives one level up at ../daemon.json. If we
55
+ // bootstrap here we silently write projects:[] and the user loses all
56
+ // their projects with no obvious error. Refuse loudly instead. (lr-dec3)
57
+ var _configBasename = path.basename(path.dirname(configFile));
58
+ var _configGrandparent = path.basename(path.dirname(path.dirname(configFile)));
59
+ var _siblingConfig = path.join(path.dirname(path.dirname(configFile)), path.basename(configFile));
60
+ if (_configBasename === "console" && _configGrandparent === ".clagentic" && fs.existsSync(_siblingConfig)) {
61
+ console.error("[daemon] ERROR: config file not found at " + configFile + " but a config exists at " + _siblingConfig + ".");
62
+ console.error("[daemon] CLAGENTIC_HOME appears to be set to the socket subdirectory (~/.clagentic/console).");
63
+ console.error("[daemon] Do NOT set CLAGENTIC_HOME to ~/.clagentic/console — that directory holds the");
64
+ console.error("[daemon] Unix socket, not the config. Relocating CLAGENTIC_HOME there moves daemon.json");
65
+ console.error("[daemon] out of reach and causes your project list to be wiped on next bootstrap.");
66
+ console.error("[daemon] Fix: unset CLAGENTIC_HOME (or set it back to ~/.clagentic) and restart.");
67
+ process.exit(78); // EX_CONFIG — fatal config error, don't auto-restart
68
+ }
69
+ // No config file yet (fresh install, systemd-only start). Bootstrap minimal defaults.
70
+ console.warn("[daemon] No config file found at " + configFile + " — bootstrapping defaults. Run clagentic-console to configure projects.");
71
+ var _isDev = !!(process.env.CLAGENTIC_DEV || process.env.CLAY_DEV);
72
+ config = { port: _isDev ? 2635 : 2633, projects: [], mode: "single", setupCompleted: false };
73
+ // Persist so subsequent reads succeed.
74
+ try {
75
+ fs.writeFileSync(configFile, JSON.stringify(config, null, 2), { mode: 0o600 });
76
+ } catch (writeErr) {
77
+ console.error("[daemon] Failed to persist bootstrap config:", writeErr.message);
78
+ process.exit(1);
79
+ }
80
+ } else {
81
+ console.error("[daemon] Failed to read config:", e.message);
82
+ process.exit(1);
83
+ }
44
84
  }
45
85
  console.log("[daemon] v" + daemonVersion + " PID " + process.pid + " config " + configFile);
46
86
 
@@ -175,6 +215,19 @@ var relay = createServer({
175
215
  }
176
216
  // Discover and register worktrees for the new project
177
217
  scanAndRegisterWorktrees(relay, absPath, slug, null, wsUser && wsUser.id && wsUser.role !== "admin" ? wsUser.id : null);
218
+ // Auto-enroll in Clagentic: Lite if enabled and Lite is installed
219
+ if (config.liteAutoEnroll) {
220
+ var liteStatus = liteDetect.detectLite();
221
+ if (liteStatus.installed && !liteDetect.isProjectEnrolled(absPath)) {
222
+ liteExecFile("clagentic-lite", ["enroll", absPath], { timeout: 30000 }, function (err) {
223
+ if (err) {
224
+ console.warn("[daemon] Lite auto-enroll failed for " + absPath + ":", err.message);
225
+ } else {
226
+ console.log("[daemon] Lite auto-enrolled project:", absPath);
227
+ }
228
+ });
229
+ }
230
+ }
178
231
  // Broadcast updated project list to all clients
179
232
  relay.broadcastAll({
180
233
  type: "projects_updated",
@@ -260,6 +313,19 @@ var relay = createServer({
260
313
  } else if (config.osUsers) {
261
314
  console.log("[daemon] Skipping ACL grant: osUsers=true but linuxUser=", wsUser && wsUser.linuxUser);
262
315
  }
316
+ // Auto-enroll in Clagentic: Lite if enabled and Lite is installed
317
+ if (config.liteAutoEnroll) {
318
+ var liteStatus = liteDetect.detectLite();
319
+ if (liteStatus.installed && !liteDetect.isProjectEnrolled(targetDir)) {
320
+ liteExecFile("clagentic-lite", ["enroll", targetDir], { timeout: 30000 }, function (err) {
321
+ if (err) {
322
+ console.warn("[daemon] Lite auto-enroll failed for " + targetDir + ":", err.message);
323
+ } else {
324
+ console.log("[daemon] Lite auto-enrolled project:", targetDir);
325
+ }
326
+ });
327
+ }
328
+ }
263
329
  relay.broadcastAll({
264
330
  type: "projects_updated",
265
331
  projects: relay.getProjects(),
@@ -324,7 +390,18 @@ var relay = createServer({
324
390
  return;
325
391
  }
326
392
  }
327
- var proc = spawn("git", ["clone", cloneUrl, targetDir], spawnOpts);
393
+ // Security: validate cloneUrl before passing to git spawn (lr-28b5).
394
+ // validateCloneUrl rejects leading-dash (option injection) and non-allow-listed schemes.
395
+ // buildCloneArgs adds the "--" argv terminator and GIT_ALLOW_PROTOCOL env restriction
396
+ // as defence-in-depth even if future validation regressions let a bad URL through.
397
+ var urlErr = validateCloneUrl(cloneUrl);
398
+ if (urlErr) {
399
+ callback({ ok: false, error: urlErr });
400
+ return;
401
+ }
402
+ var cloneArgSpec = buildCloneArgs(cloneUrl, targetDir);
403
+ spawnOpts.env = Object.assign({}, spawnOpts.env || process.env, cloneArgSpec.envOverrides);
404
+ var proc = spawn("git", cloneArgSpec.args, spawnOpts);
328
405
  var stderrBuf = "";
329
406
  proc.stderr.on("data", function (chunk) { stderrBuf += chunk.toString(); });
330
407
  // 5 minute timeout
@@ -847,8 +924,16 @@ var relay = createServer({
847
924
  updateChannel: config.updateChannel || "stable",
848
925
  imageRetentionDays: config.imageRetentionDays !== undefined ? config.imageRetentionDays : 7,
849
926
  memAvailableMinMB: config.memAvailableMinMB !== undefined ? config.memAvailableMinMB : DEFAULT_MEM_AVAILABLE_MIN_MB,
927
+ liteAutoEnroll: !!config.liteAutoEnroll,
850
928
  };
851
929
  },
930
+ onSetLiteAutoEnroll: function (value) {
931
+ var want = !!value;
932
+ config.liteAutoEnroll = want;
933
+ saveConfig(config);
934
+ console.log("[daemon] Lite auto-enroll:", want, "(web)");
935
+ return { ok: true, liteAutoEnroll: want };
936
+ },
852
937
  onSetImageRetention: function (days) {
853
938
  var d = parseInt(days, 10);
854
939
  if (isNaN(d) || d < 0) d = 7;
@@ -969,7 +1054,7 @@ var relay = createServer({
969
1054
  if (config.osUsers) {
970
1055
  var projectPath = config.projects[i].path;
971
1056
  var ownerId = config.projects[i].ownerId || null;
972
- // When switching to public: grant ACL to ALL clay users
1057
+ // When switching to public: grant ACL to ALL users
973
1058
  if (visibility === "public" && prevVisibility !== "public") {
974
1059
  grantAllUsersAccess(projectPath, usersModule);
975
1060
  }
@@ -1051,7 +1136,7 @@ var relay = createServer({
1051
1136
  }
1052
1137
  },
1053
1138
  onUserDeleted: function (userId, linuxUser) {
1054
- // Deactivate the Linux account when a Clay user is deleted
1139
+ // Deactivate the Linux account when a user is deleted
1055
1140
  if (!config.osUsers || !linuxUser) return;
1056
1141
  deactivateLinuxUser(linuxUser);
1057
1142
  },
@@ -1141,6 +1226,29 @@ for (var i = 0; i < projects.length; i++) {
1141
1226
  // Sync ~/.clayrc on startup
1142
1227
  try { syncClayrc(config.projects); } catch (e) {}
1143
1228
 
1229
+ // Auto-enroll in Clagentic: Lite at startup if liteAutoEnroll is enabled
1230
+ if (config.liteAutoEnroll) {
1231
+ (function () {
1232
+ var liteStatus = liteDetect.detectLite();
1233
+ if (!liteStatus.installed) return;
1234
+ var registeredProjects = config.projects || [];
1235
+ for (var li = 0; li < registeredProjects.length; li++) {
1236
+ var lp = registeredProjects[li];
1237
+ if (lp.path && !liteDetect.isProjectEnrolled(lp.path)) {
1238
+ (function (projectPath) {
1239
+ liteExecFile("clagentic-lite", ["enroll", projectPath], { timeout: 30000 }, function (err) {
1240
+ if (err) {
1241
+ console.warn("[daemon] Lite startup auto-enroll failed for " + projectPath + ":", err.message);
1242
+ } else {
1243
+ console.log("[daemon] Lite startup auto-enrolled:", projectPath);
1244
+ }
1245
+ });
1246
+ })(lp.path);
1247
+ }
1248
+ }
1249
+ })();
1250
+ }
1251
+
1144
1252
  // --- IPC server ---
1145
1253
  // Clean up stale socket/config left by a previously killed daemon
1146
1254
  var existingConfig = loadConfig();
@@ -1381,6 +1489,9 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1381
1489
  stdio: ["ignore", "pipe", "pipe"],
1382
1490
  timeout: 120000,
1383
1491
  encoding: "utf8",
1492
+ // CLAGENTIC_SELF_UPDATE=1 tells postinstall.js not to restart the
1493
+ // service — gracefulShutdown() below hands off to systemd Restart=always.
1494
+ env: Object.assign({}, process.env, { CLAGENTIC_SELF_UPDATE: "1" }),
1384
1495
  });
1385
1496
  console.log("[daemon] Global install complete. Shutting down for supervised restart.");
1386
1497
  updOk = true;
package/lib/dm.js CHANGED
@@ -18,7 +18,17 @@ function dmKey(userId1, userId2) {
18
18
  // File path for a DM conversation
19
19
  function dmFilePath(key) {
20
20
  // Replace : with _ for safe filename
21
- return path.join(DM_DIR, key.replace(/:/g, "_") + ".jsonl");
21
+ var resolved = path.join(DM_DIR, key.replace(/:/g, "_") + ".jsonl");
22
+ // Defense-in-depth: assert the resolved path stays within DM_DIR.
23
+ // path.resolve is used to canonicalize both sides before comparison so that
24
+ // any surviving .. segments (e.g. from a malformed key that slipped through
25
+ // caller-side validation) cannot escape the directory.
26
+ var dmDirResolved = path.resolve(DM_DIR);
27
+ if (!path.resolve(resolved).startsWith(dmDirResolved + path.sep) &&
28
+ path.resolve(resolved) !== dmDirResolved) {
29
+ throw new Error("dm: path traversal detected for key: " + key);
30
+ }
31
+ return resolved;
22
32
  }
23
33
 
24
34
  // Load DM history from JSONL file
@@ -120,6 +130,7 @@ function getDmList(userId) {
120
130
 
121
131
  module.exports = {
122
132
  dmKey: dmKey,
133
+ dmFilePath: dmFilePath,
123
134
  openDm: openDm,
124
135
  sendMessage: sendMessage,
125
136
  getDmList: getDmList,
package/lib/ipc.js CHANGED
@@ -6,6 +6,12 @@ var fs = require("fs");
6
6
  * handler(msg) should return a response object (or a Promise of one).
7
7
  */
8
8
  function createIPCServer(sockPath, handler) {
9
+ // Ensure the socket's parent directory exists (e.g. ~/.clagentic/console/).
10
+ // The daemon may start without a prior CLI invocation, so it must be self-sufficient.
11
+ if (process.platform !== "win32") {
12
+ try { fs.mkdirSync(require("path").dirname(sockPath), { recursive: true }); } catch (e) {}
13
+ }
14
+
9
15
  // Remove stale socket file (not needed for Windows named pipes)
10
16
  if (process.platform !== "win32") {
11
17
  try { fs.unlinkSync(sockPath); } catch (e) {}
@@ -53,6 +59,12 @@ function createIPCServer(sockPath, handler) {
53
59
  console.log("[ipc] Socket in use, removing stale socket and retrying...");
54
60
  try { fs.unlinkSync(sockPath); } catch (e) {}
55
61
  server.listen(sockPath);
62
+ } else if (err.code === "ENOENT" && !retried) {
63
+ // Parent directory missing — create it and retry once.
64
+ retried = true;
65
+ console.log("[ipc] Socket directory missing, creating and retrying...");
66
+ try { fs.mkdirSync(require("path").dirname(sockPath), { recursive: true }); } catch (e) {}
67
+ server.listen(sockPath);
56
68
  } else {
57
69
  console.error("[ipc] Failed to bind socket:", err.message);
58
70
  process.exit(1);