@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
package/lib/ws-schema.js CHANGED
@@ -460,7 +460,17 @@ var schema = {
460
460
  "ralph_phase": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Current ralph wizard phase" },
461
461
  "ralph_crafting_started": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "File crafting session started" },
462
462
  "ralph_files_status": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Prompt/judge file readiness status" },
463
- "ralph_files_content": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Loop file contents (prompt and judge)" }
463
+ "ralph_files_content": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Loop file contents (prompt and judge)" },
464
+
465
+ // -----------------------------------------------------------------------
466
+ // Agents (SDK catalog + project-local)
467
+ // -----------------------------------------------------------------------
468
+ "list_agents": { direction: "c2s", handler: "lib/project-sessions.js", description: "Request SDK agent catalog with favorites and recents" },
469
+ "agents_list": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Full agent catalog with favorites and recents" },
470
+ "toggle_agent_favorite": { direction: "c2s", handler: "lib/project-sessions.js", description: "Toggle an agent in/out of favorites" },
471
+ "agent_favorite_toggled": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Favorite toggle confirmation" },
472
+ "get_agents": { direction: "c2s", handler: "lib/project-sessions.js", description: "Request project-local agents from .claude/agents/ (lr-c1a2)" },
473
+ "project_agents_list": { direction: "s2c", handler: "lib/public/modules/app-messages.js", description: "Project-local agent list for @ mention dropdown (lr-c1a2)" }
464
474
  };
465
475
 
466
476
  module.exports = { schema: schema };
@@ -1,6 +1,6 @@
1
1
  // sdk-worker.js — Standalone worker process for OS-level user isolation.
2
2
  // Runs as a target Linux user, loads the Claude Agent SDK, and communicates
3
- // with the main Clay daemon over a Unix domain socket using JSON lines.
3
+ // with the main daemon over a Unix domain socket using JSON lines.
4
4
  //
5
5
  // Usage: node sdk-worker.js <socket-path>
6
6
 
@@ -27,7 +27,7 @@ if (!socketPath) {
27
27
 
28
28
  // --- Per-user Claude binary resolver ---
29
29
  // In OS-level multi-user mode, the worker runs as a different OS user than the
30
- // Clay daemon. Each user may have their own `claude` install (nvm, asdf,
30
+ // The daemon. Each user may have their own `claude` install (nvm, asdf,
31
31
  // ~/.npm-global, etc.), and the daemon's resolved path may not be executable
32
32
  // by the worker user. Resolve from the worker's own environment, falling back
33
33
  // to whatever the daemon passed in.
@@ -310,7 +310,7 @@ function createQueryHandle(rawQuery, messageQueue, abortController) {
310
310
 
311
311
  setEffort: function(effort) {
312
312
  // Claude SDK has no setEffort on active query.
313
- // Stored at Clay level for next query.
313
+ // Stored at the console level for next query.
314
314
  return Promise.resolve();
315
315
  },
316
316
 
@@ -454,8 +454,9 @@ function spawnWorker(linuxUser, workerScriptPath, cwd) {
454
454
  buffer: "",
455
455
  };
456
456
 
457
- worker.readyPromise = new Promise(function(resolve) {
457
+ worker.readyPromise = new Promise(function(resolve, reject) {
458
458
  worker._readyResolve = resolve;
459
+ worker._readyReject = reject;
459
460
  });
460
461
 
461
462
  // Resolves when the worker process actually exits.
@@ -542,11 +543,9 @@ function spawnWorker(linuxUser, workerScriptPath, cwd) {
542
543
 
543
544
  worker.process.on("exit", function(code, signal) {
544
545
  console.log("[yoke/claude] Worker for " + linuxUser + " exited (code=" + code + ", signal=" + signal + ")" + (worker._stderrBuf ? " stderr: " + worker._stderrBuf.trim() : ""));
545
- // Reject readyPromise if worker dies before becoming ready
546
- if (!worker.ready && worker._readyResolve) {
547
- worker._readyResolve = null;
548
- // Let the readyPromise hang; the query_error handler will clean up
549
- }
546
+ // Reject readyPromise if worker dies before becoming ready so callers
547
+ // awaiting it surface an error instead of hanging forever.
548
+ _test_handleWorkerEarlyExit(worker, code, signal);
550
549
  // Notify message handlers about unexpected exit so sessions don't hang.
551
550
  // Always dispatch a fallback query_error. The handler is idempotent:
552
551
  // it checks isProcessing before taking action, and cleanupSessionWorker
@@ -639,6 +638,23 @@ function spawnWorker(linuxUser, workerScriptPath, cwd) {
639
638
  return worker;
640
639
  }
641
640
 
641
+ // Testable seam: the exact logic the exit handler uses to reject readyPromise
642
+ // and build the error object when the worker dies before becoming ready.
643
+ // Exported as _test_handleWorkerEarlyExit so tests can call the real function
644
+ // rather than inlining a copy — reverting the _readyReject call in the exit
645
+ // handler will break those tests. (lr-a7e7)
646
+ function _test_handleWorkerEarlyExit(worker, code, signal) {
647
+ if (!worker.ready && worker._readyReject) {
648
+ var readyErr = new Error(
649
+ "Worker exited before ready (code=" + code + ", signal=" + signal + ")" +
650
+ (worker._stderrBuf ? ". stderr: " + worker._stderrBuf.trim() : "")
651
+ );
652
+ worker._readyReject(readyErr);
653
+ worker._readyResolve = null;
654
+ worker._readyReject = null;
655
+ }
656
+ }
657
+
642
658
  function cleanupWorker(worker) {
643
659
  console.log("[yoke/claude] cleanupWorker() called, pid=" + (worker.process ? worker.process.pid : "?") + " stack=" + new Error().stack.split("\n").slice(1, 4).join(" | "));
644
660
  if (worker._abortTimeout) { clearTimeout(worker._abortTimeout); worker._abortTimeout = null; }
@@ -1369,9 +1385,21 @@ function createClaudeAdapter(opts) {
1369
1385
  // Create the worker query handle (sets up message handler on worker)
1370
1386
  var handle = createWorkerQueryHandle(worker, queryOpts.canUseTool, queryOpts.onElicitation, queryOpts.callMcpTool);
1371
1387
 
1372
- // Wait for worker to be ready before sending query_start
1388
+ // Wait for worker to be ready before sending query_start.
1389
+ // A 30s timeout ensures spawn failures surface as errors rather than
1390
+ // hanging forever (worker._readyReject fires on early exit, but the
1391
+ // timeout guards against silent stalls such as a socket that never
1392
+ // connects without the process dying).
1373
1393
  if (!reusingWorker) {
1374
- await worker.readyPromise;
1394
+ await Promise.race([
1395
+ worker.readyPromise,
1396
+ new Promise(function(_, reject) {
1397
+ setTimeout(function() {
1398
+ console.warn("[yoke/claude] Worker ready timeout (30s) for " + linuxUser + " — spawn may have stalled");
1399
+ reject(new Error("Worker ready timeout: worker did not become ready within 30s"));
1400
+ }, 30000);
1401
+ }),
1402
+ ]);
1375
1403
  }
1376
1404
 
1377
1405
  // Build serializable query options (no callbacks, no AbortController)
@@ -1500,7 +1528,15 @@ function createClaudeAdapter(opts) {
1500
1528
  }
1501
1529
 
1502
1530
  try {
1503
- await worker.readyPromise;
1531
+ await Promise.race([
1532
+ worker.readyPromise,
1533
+ new Promise(function(_, reject) {
1534
+ setTimeout(function() {
1535
+ console.warn("[yoke/claude] Warmup worker ready timeout (30s) for " + linuxUser + " — spawn may have stalled");
1536
+ reject(new Error("Warmup worker ready timeout: worker did not become ready within 30s"));
1537
+ }, 30000);
1538
+ }),
1539
+ ]);
1504
1540
  } catch (e) {
1505
1541
  cleanupWorker(worker);
1506
1542
  throw new Error("Warmup worker failed to connect: " + (e.message || e));
@@ -1558,5 +1594,6 @@ function createClaudeAdapter(opts) {
1558
1594
  module.exports = {
1559
1595
  createClaudeAdapter: createClaudeAdapter,
1560
1596
  createMessageQueue: createMessageQueue,
1597
+ _test_handleWorkerEarlyExit: _test_handleWorkerEarlyExit,
1561
1598
  };
1562
1599
 
@@ -567,6 +567,15 @@ function flattenEvent(notification, state) {
567
567
 
568
568
  // --- QueryHandle ---
569
569
 
570
+ // Testable seam: the exact expression used to resolve model in
571
+ // createCodexQueryHandle (both state.model and threadParams.model).
572
+ // Exported so tests import and call the real function rather than
573
+ // inlining a copy — reverting the || queryOpts.defaultModel term
574
+ // in codex.js will break those tests. (lr-a7e7)
575
+ function _test_resolveModel(queryOpts) {
576
+ return queryOpts.model || queryOpts.defaultModel || "gpt-5.5";
577
+ }
578
+
570
579
  function createCodexQueryHandle(appServer, queryOpts) {
571
580
  var abortController = queryOpts.abortController;
572
581
  var systemPrompt = queryOpts.systemPrompt || "";
@@ -588,7 +597,7 @@ function createCodexQueryHandle(appServer, queryOpts) {
588
597
  done: false,
589
598
  aborted: false,
590
599
  loopStarted: false,
591
- model: queryOpts.model || _defaultModel,
600
+ model: _test_resolveModel(queryOpts),
592
601
  // Track incremental text deltas
593
602
  textBlocks: {}, // itemId -> true (text_start sent)
594
603
  textLengths: {}, // itemId -> last sent length
@@ -836,7 +845,7 @@ function createCodexQueryHandle(appServer, queryOpts) {
836
845
  try {
837
846
  // Start or resume thread
838
847
  var threadParams = {
839
- model: queryOpts.model || _defaultModel,
848
+ model: _test_resolveModel(queryOpts),
840
849
  sandbox: queryOpts.sandboxMode || "workspace-write",
841
850
  approvalPolicy: queryOpts.approvalPolicy || "on-failure",
842
851
  cwd: queryOpts.cwd,
@@ -1344,7 +1353,7 @@ function createCodexAdapter(opts) {
1344
1353
  if (co.config) serverOpts.config = co.config;
1345
1354
  }
1346
1355
 
1347
- // Track 1: Read local MCP server definitions from ~/.clay/mcp.json
1356
+ // Track 1: Read local MCP server definitions from ~/.clagentic/mcp.json
1348
1357
  // and inject into Codex config so Codex manages them natively.
1349
1358
  var mcpServerConfig = {};
1350
1359
  try {
@@ -1553,6 +1562,7 @@ function createCodexAdapter(opts) {
1553
1562
 
1554
1563
  var handleOpts = {
1555
1564
  model: model,
1565
+ defaultModel: _defaultModel,
1556
1566
  cwd: queryOpts.cwd || _cwd,
1557
1567
  systemPrompt: queryOpts.systemPrompt || "",
1558
1568
  abortController: ac,
@@ -1697,4 +1707,5 @@ function createCodexAdapter(opts) {
1697
1707
 
1698
1708
  module.exports = {
1699
1709
  createCodexAdapter: createCodexAdapter,
1710
+ _test_resolveModel: _test_resolveModel,
1700
1711
  };
@@ -3,7 +3,7 @@
3
3
  // --------------------------------------------------
4
4
  // Codex spawns this as a native MCP server via config.mcp_servers["clay-tools"].
5
5
  // It implements the MCP protocol on stdio (JSON-RPC) and proxies tool
6
- // list/call requests to Clay's project-scoped HTTP endpoint
6
+ // list/call requests to the project-scoped HTTP endpoint
7
7
  // (/p/{slug}/api/mcp-bridge) when a slug is provided.
8
8
  //
9
9
  // Usage: node mcp-bridge-server.js --port 2633 --slug my-project
@@ -11,9 +11,9 @@
11
11
  // Lifecycle:
12
12
  // 1. Codex spawns this process
13
13
  // 2. Codex sends MCP "initialize" request on stdin
14
- // 3. We respond, then fetch tool list from Clay
14
+ // 3. We respond, then fetch tool list from the server
15
15
  // 4. Codex sends "tools/list" -> we return cached tools
16
- // 5. Codex sends "tools/call" -> we proxy to Clay and return result
16
+ // 5. Codex sends "tools/call" -> we proxy to the server and return result
17
17
  // 6. When stdin closes (Codex exits), we exit too
18
18
 
19
19
  var http = require("http");
@@ -62,7 +62,7 @@ function postJson(urlPath, body) {
62
62
  "Content-Type": "application/json",
63
63
  "Content-Length": Buffer.byteLength(data),
64
64
  };
65
- // Include auth cookie if available (required for authenticated Clay servers)
65
+ // Include auth cookie if available (required for authenticated servers)
66
66
  if (clayAuthToken) {
67
67
  headers["Cookie"] = "relay_auth=" + clayAuthToken;
68
68
  }
@@ -109,7 +109,7 @@ function postJson(urlPath, body) {
109
109
  });
110
110
  }
111
111
 
112
- // --- Fetch tools from Clay ---
112
+ // --- Fetch tools from the server ---
113
113
  function fetchTools() {
114
114
  return postJson(CLAY_MCP_PATH, { action: "list_tools" }).then(function (resp) {
115
115
  if (resp.error) {
@@ -122,7 +122,7 @@ function fetchTools() {
122
122
  for (var i = 0; i < _tools.length; i++) {
123
123
  serverNames[_tools[i].server] = (serverNames[_tools[i].server] || 0) + 1;
124
124
  }
125
- log("Fetched " + _tools.length + " tools from Clay: " + Object.keys(serverNames).map(function(s) { return s + "(" + serverNames[s] + ")"; }).join(", "));
125
+ log("Fetched " + _tools.length + " tools: " + Object.keys(serverNames).map(function(s) { return s + "(" + serverNames[s] + ")"; }).join(", "));
126
126
  return _tools;
127
127
  }).catch(function (err) {
128
128
  log("Error fetching tools: " + err.message);
@@ -130,7 +130,7 @@ function fetchTools() {
130
130
  });
131
131
  }
132
132
 
133
- // --- Call a tool via Clay ---
133
+ // --- Call a tool via the server ---
134
134
  function callTool(serverName, toolName, args) {
135
135
  return postJson(CLAY_MCP_PATH, {
136
136
  action: "call_tool",
package/package.json CHANGED
@@ -3,19 +3,22 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.4.0",
6
+ "version": "1.5.0-beta.1",
7
7
  "description": "Self-hosted console for Claude Code and Codex. Multi-user, browser-based, persistent AI sessions.",
8
8
  "bin": {
9
9
  "clagentic-console": "./bin/cli.js"
10
10
  },
11
11
  "scripts": {
12
12
  "dev": "node bin/cli.js --dev",
13
+ "postinstall": "node scripts/postinstall.js",
13
14
  "test": "node --test --test-force-exit test/*.test.js",
14
15
  "semantic-release": "semantic-release"
15
16
  },
16
17
  "files": [
17
18
  "bin/",
18
19
  "lib/",
20
+ "scripts/",
21
+ "deploy/",
19
22
  "CREDITS.md"
20
23
  ],
21
24
  "keywords": [
@@ -45,7 +48,7 @@
45
48
  "bugs": {
46
49
  "url": "https://github.com/clagentic/clagentic-console/issues"
47
50
  },
48
- "homepage": "https://github.com/clagentic/clagentic-console#readme",
51
+ "homepage": "https://clagentic.ai/tools",
49
52
  "author": "Andy Kuehner",
50
53
  "contributors": [
51
54
  "Chad (original Clay author)"
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ // Verify that every relative ES module import under lib/public/ resolves to
3
+ // an existing file. Catches accidentally-included imports that point at
4
+ // files which don't exist in this branch (e.g. PR #342 imported
5
+ // './agent-picker.js', which would have broken the client at runtime).
6
+ //
7
+ // Scope: only checks relative imports (./ or ../). Bare specifiers and
8
+ // absolute URLs are ignored — those are not what this guard is about.
9
+ //
10
+ // Exit code 0 on success, 1 on any unresolved import.
11
+
12
+ var fs = require('fs');
13
+ var path = require('path');
14
+
15
+ var ROOT = path.resolve(__dirname, '..', 'lib', 'public');
16
+
17
+ function walk(dir, out) {
18
+ var entries = fs.readdirSync(dir, { withFileTypes: true });
19
+ for (var i = 0; i < entries.length; i++) {
20
+ var e = entries[i];
21
+ var full = path.join(dir, e.name);
22
+ if (e.isDirectory()) walk(full, out);
23
+ else if (e.isFile() && e.name.endsWith('.js')) out.push(full);
24
+ }
25
+ return out;
26
+ }
27
+
28
+ // Match `import ... from '...'`, `import '...'`, and `export ... from '...'`.
29
+ // Skips dynamic import() — those can take runtime expressions and aren't
30
+ // reliably resolvable statically.
31
+ var IMPORT_RE = /(?:^|\s)(?:import|export)(?:[\s\S]*?from\s*)?['"]([^'"]+)['"]/g;
32
+
33
+ function extractSpecifiers(src) {
34
+ var specs = [];
35
+ var m;
36
+ IMPORT_RE.lastIndex = 0;
37
+ while ((m = IMPORT_RE.exec(src)) !== null) specs.push(m[1]);
38
+ return specs;
39
+ }
40
+
41
+ function isRelative(spec) {
42
+ return spec.startsWith('./') || spec.startsWith('../');
43
+ }
44
+
45
+ function resolveTarget(fromFile, spec) {
46
+ var base = path.resolve(path.dirname(fromFile), spec);
47
+ // Exact path as written.
48
+ if (fs.existsSync(base) && fs.statSync(base).isFile()) return base;
49
+ // Try with .js appended (some imports may omit the extension).
50
+ if (fs.existsSync(base + '.js')) return base + '.js';
51
+ // Directory with index.js.
52
+ var idx = path.join(base, 'index.js');
53
+ if (fs.existsSync(idx)) return idx;
54
+ return null;
55
+ }
56
+
57
+ var files = walk(ROOT, []);
58
+ var errors = [];
59
+
60
+ for (var i = 0; i < files.length; i++) {
61
+ var file = files[i];
62
+ var src;
63
+ try {
64
+ src = fs.readFileSync(file, 'utf8');
65
+ } catch (e) {
66
+ errors.push({ file: file, spec: '<read error>', detail: e.message });
67
+ continue;
68
+ }
69
+ var specs = extractSpecifiers(src);
70
+ for (var j = 0; j < specs.length; j++) {
71
+ var spec = specs[j];
72
+ if (!isRelative(spec)) continue;
73
+ var target = resolveTarget(file, spec);
74
+ if (!target) {
75
+ errors.push({
76
+ file: path.relative(process.cwd(), file),
77
+ spec: spec,
78
+ detail: 'unresolved relative import',
79
+ });
80
+ }
81
+ }
82
+ }
83
+
84
+ if (errors.length) {
85
+ console.error('Unresolved client imports:');
86
+ for (var k = 0; k < errors.length; k++) {
87
+ var err = errors[k];
88
+ console.error(' ' + err.file + ' -> ' + err.spec + ' (' + err.detail + ')');
89
+ }
90
+ console.error('\nTotal: ' + errors.length + ' unresolved import(s).');
91
+ process.exit(1);
92
+ }
93
+
94
+ console.log('OK: all ' + files.length + ' client modules have resolvable relative imports.');
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // postinstall.js — installs/updates the systemd service unit on Linux global npm installs.
5
+ // Runs automatically after `npm install -g @clagentic/console`.
6
+ // Silently exits on non-Linux platforms and non-root invocations.
7
+
8
+ const { execFileSync } = require('child_process');
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ const PREFIX = '[clagentic-console postinstall]';
13
+
14
+ function log(msg) {
15
+ console.log(`${PREFIX} ${msg}`);
16
+ }
17
+
18
+ function runCmd(cmd, args) {
19
+ // Returns stdout string on success, throws on failure.
20
+ // stderr is captured in err.stderr on failure.
21
+ return execFileSync(cmd, args, { stdio: 'pipe' }).toString().trim();
22
+ }
23
+
24
+ function errMsg(err) {
25
+ // execFileSync puts detail in err.stderr; fall back to err.message.
26
+ const stderr = err.stderr && err.stderr.toString().trim();
27
+ return stderr || err.message;
28
+ }
29
+
30
+ // Skip silently on non-Linux platforms.
31
+ if (process.platform !== 'linux') {
32
+ process.exit(0);
33
+ }
34
+
35
+ // Skip silently when not running as root — cannot write to /etc/systemd/system/.
36
+ if (process.getuid() !== 0) {
37
+ log('skipping (not root)');
38
+ process.exit(0);
39
+ }
40
+
41
+ // When the daemon triggers its own in-app update it passes CLAGENTIC_SELF_UPDATE=1.
42
+ // In that case, skip restarting the service — the daemon calls gracefulShutdown()
43
+ // immediately after npm install completes, and systemd Restart=always handles the
44
+ // supervised restart. Issuing systemctl restart here would race with gracefulShutdown
45
+ // and tear down sessions before state is flushed.
46
+ const selfUpdate = process.env.CLAGENTIC_SELF_UPDATE === '1';
47
+ if (selfUpdate) {
48
+ log('self-update detected (CLAGENTIC_SELF_UPDATE=1) — skipping service restart');
49
+ }
50
+
51
+ const SYSTEMD_DIR = '/etc/systemd/system';
52
+ const NEW_UNIT = 'clagentic-console.service';
53
+ const OLD_UNIT = 'clagentic.service';
54
+ const NEW_UNIT_DEST = path.join(SYSTEMD_DIR, NEW_UNIT);
55
+ const OLD_UNIT_PATH = path.join(SYSTEMD_DIR, OLD_UNIT);
56
+ const UNIT_SRC = path.join(__dirname, '..', 'deploy', 'clagentic-console.service');
57
+
58
+ // Step 1: Copy the new unit file.
59
+ log(`installing unit file -> ${NEW_UNIT_DEST}`);
60
+ try {
61
+ fs.copyFileSync(UNIT_SRC, NEW_UNIT_DEST);
62
+ } catch (err) {
63
+ log(`ERROR copying unit file: ${errMsg(err)}`);
64
+ // Cannot continue without the unit file in place.
65
+ process.exit(0);
66
+ }
67
+
68
+ // Step 2: daemon-reload to pick up the new unit file.
69
+ log('running systemctl daemon-reload');
70
+ try {
71
+ runCmd('systemctl', ['daemon-reload']);
72
+ } catch (err) {
73
+ log(`WARNING: daemon-reload failed: ${errMsg(err)}`);
74
+ }
75
+
76
+ // Step 3: Enable the new unit if not already enabled.
77
+ log(`enabling ${NEW_UNIT}`);
78
+ try {
79
+ runCmd('systemctl', ['enable', NEW_UNIT]);
80
+ } catch (err) {
81
+ log(`WARNING: enable ${NEW_UNIT} failed: ${errMsg(err)}`);
82
+ }
83
+
84
+ // Step 4: Handle rename — migrate from old clagentic.service if present.
85
+ let wasRunningUnderOldUnit = false;
86
+ if (fs.existsSync(OLD_UNIT_PATH)) {
87
+ log(`old unit file detected: ${OLD_UNIT_PATH} — performing rename cutover`);
88
+
89
+ // Detect whether the old unit is currently active before stopping it.
90
+ try {
91
+ const activeState = runCmd('systemctl', ['is-active', OLD_UNIT]);
92
+ if (activeState === 'active') {
93
+ wasRunningUnderOldUnit = true;
94
+ }
95
+ } catch (_) {
96
+ // is-active exits non-zero when not active — not an error.
97
+ }
98
+
99
+ // Disable the old unit.
100
+ log(`disabling ${OLD_UNIT}`);
101
+ try {
102
+ runCmd('systemctl', ['disable', OLD_UNIT]);
103
+ } catch (err) {
104
+ log(`WARNING: disable ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
105
+ }
106
+
107
+ // Stop the old unit.
108
+ log(`stopping ${OLD_UNIT}`);
109
+ try {
110
+ runCmd('systemctl', ['stop', OLD_UNIT]);
111
+ } catch (err) {
112
+ log(`WARNING: stop ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
113
+ }
114
+
115
+ // Remove the old unit file.
116
+ log(`removing ${OLD_UNIT_PATH}`);
117
+ try {
118
+ fs.unlinkSync(OLD_UNIT_PATH);
119
+ } catch (err) {
120
+ log(`WARNING: remove ${OLD_UNIT_PATH} failed: ${errMsg(err)}`);
121
+ }
122
+
123
+ // daemon-reload again to clear the old unit from systemd's view.
124
+ log('running systemctl daemon-reload (post-rename)');
125
+ try {
126
+ runCmd('systemctl', ['daemon-reload']);
127
+ } catch (err) {
128
+ log(`WARNING: daemon-reload (post-rename) failed: ${errMsg(err)}`);
129
+ }
130
+ }
131
+
132
+ // Step 5: Start clagentic-console.service only if it was running under the old unit
133
+ // and needs to be moved to the new one. Never restart a running service — that kills
134
+ // live sessions. Never auto-start on a fresh install — the daemon needs configuration.
135
+ // Self-updates use gracefulShutdown() + Restart=always; postinstall must not interfere.
136
+ if (selfUpdate) {
137
+ log('skipping start (self-update — gracefulShutdown will hand off to systemd)');
138
+ } else if (wasRunningUnderOldUnit) {
139
+ // Stopped the old unit during rename cutover — start under the new one now.
140
+ log(`starting ${NEW_UNIT} (was running under ${OLD_UNIT})`);
141
+ try {
142
+ runCmd('systemctl', ['start', NEW_UNIT]);
143
+ } catch (err) {
144
+ log(`WARNING: start ${NEW_UNIT} failed: ${errMsg(err)}`);
145
+ }
146
+ } else {
147
+ log(`skipping start (daemon was not running or is already running — operator controls restarts)`);
148
+ }
149
+
150
+ log('done');