@clagentic/console 1.5.0-beta.4 → 1.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,6 +7,7 @@
7
7
  <p align="center">
8
8
  <a href="https://clagentic.ai"><img src="https://img.shields.io/badge/-clagentic.ai-00CFFF?style=flat&logoColor=white" alt="clagentic.ai" /></a>
9
9
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow?style=flat" alt="License: MIT" /></a>
10
+ <a href="https://github.com/clagentic/clagentic-console/actions/workflows/pr-checks.yml"><img src="https://github.com/clagentic/clagentic-console/actions/workflows/pr-checks.yml/badge.svg?branch=main" alt="CI" /></a>
10
11
  <img src="https://img.shields.io/badge/Node.js-20+-339933?style=flat&logo=node.js&logoColor=white" alt="Node.js 20+" />
11
12
  <a href="https://www.npmjs.com/package/@clagentic/console"><img src="https://img.shields.io/npm/v/@clagentic/console?style=flat&label=npm" alt="npm version" /></a>
12
13
  <a href="https://www.npmjs.com/package/@clagentic/console"><img src="https://img.shields.io/npm/dw/@clagentic/console?style=flat&label=downloads" alt="npm downloads" /></a>
@@ -61,7 +62,7 @@ npm install -g @clagentic/console --ignore-scripts
61
62
 
62
63
  - **Loop automation.** Write a `PROMPT.md`, start a loop. Clagentic: Console runs the prompt, evaluates the result, and retries until done or capped. Schedule loops with standard cron syntax to run unattended.
63
64
 
64
- - **External triggers.** Drop a JSON file into `~/.clagentic/external-triggers/` to spawn a new AI session or inject a message into an existing one. Use this to wire agents into scripts, CI pipelines, or other AI processes — no API, no polling, just a file drop.
65
+ - **External triggers.** Drop a JSON file into `~/.clagentic/console/external-triggers/` to spawn a new AI session or inject a message into an existing one. Use this to wire agents into scripts, CI pipelines, or other AI processes — no API, no polling, just a file drop.
65
66
 
66
67
  - **Mobile PWA + push notifications.** Installable on iOS and Android. Approve tool calls from your phone. Push fires on approval requests, errors, and task completion.
67
68
 
@@ -146,7 +147,7 @@ These are implementation-level properties, not configuration options — they ap
146
147
 
147
148
  - **Atomic writes, mode 0o600.** All config and state files (`users.json`, `auth-tokens.json`, and similar) are written via rename-after-write: data goes to a `.tmp.<pid>` path, then `rename()` atomically replaces the target. After rename, `chmod 0o600` is applied. Concurrent writes to the same file are serialized in call order.
148
149
 
149
- - **Append-only audit log.** Privileged actions — user creation, lockouts, token revocation, multi-user enable/disable — are written as newline-delimited JSON to `~/.clagentic/audit.log` (mode 0o600, opened with `O_APPEND`).
150
+ - **Append-only audit log.** Privileged actions — user creation, lockouts, token revocation, multi-user enable/disable — are written as newline-delimited JSON to `~/.clagentic/console/audit.log` (mode 0o600, opened with `O_APPEND`).
150
151
 
151
152
  - **Progressive lockout.** Failed login attempts trigger escalating per-username backoff: 1s, 5s, 30s, 5 min. Reaching the threshold results in permanent lockout until an admin explicitly unlocks the account. Per-IP rate limiting runs in parallel.
152
153
 
@@ -185,7 +186,7 @@ Named agents are **currently Claude Code only.** The Codex adapter has no equiva
185
186
  Open the Context panel in the session input area. Pin a running terminal, a browser tab (requires the Clagentic: Console Chrome extension), or a sticky note. From that point on, every message you send automatically includes the latest content from those sources — terminal output as a delta since the last message, browser tabs as a full page snapshot. The injection happens before your message reaches the model; you don't need to mention the sources in your prompt.
186
187
 
187
188
  **"What's the external trigger system?"**
188
- Drop a JSON file into `~/.clagentic/external-triggers/`. The daemon picks it up within seconds. A v1 trigger spawns a new session with an `initialPrompt`. A v2 trigger can either spawn a session or inject a message into an existing session by `sessionId`. The file is archived to `processed/` on success. Unprocessed files survive daemon restarts. Use this to wire Claude into scripts, CI pipelines, cron jobs, or other AI processes.
189
+ Drop a JSON file into `~/.clagentic/console/external-triggers/`. The daemon picks it up within seconds. A v1 trigger spawns a new session with an `initialPrompt`. A v2 trigger can either spawn a session or inject a message into an existing session by `sessionId`. The file is archived to `processed/` on success. Unprocessed files survive daemon restarts. Use this to wire Claude into scripts, CI pipelines, cron jobs, or other AI processes.
189
190
 
190
191
  **"What instruction files does it read?"**
191
192
  YOKE scans the project directory for `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, `COPILOT.md`, and `.github/copilot-instructions.md`. Each vendor reads some of these natively — Claude reads `CLAUDE.md`, Codex reads `AGENTS.md`. Files the active vendor doesn't read natively are merged and injected as additional context, so your project instructions reach the model regardless of which vendor is running.
@@ -209,7 +210,7 @@ Yes. CLI sessions appear in the sidebar and can be picked up in the CLI.
209
210
  Yes. Install as a PWA on iOS or Android. Push notifications for approvals, errors, and task completion.
210
211
 
211
212
  **"Does it work with MCP servers?"**
212
- Yes. User-configured MCPs from `~/.clagentic/mcp.json` plus built-in ask-user and browser servers work in both Claude and Codex sessions.
213
+ Yes. User-configured MCPs from `~/.clagentic/console/mcp.json` plus built-in ask-user and browser servers work in both Claude and Codex sessions.
213
214
 
214
215
  **"Multi-user support?"**
215
216
  Yes — it is a core design goal, not an add-on. Real accounts, independent session history, and a Team panel that shows every human user and agent connected to the Console. On Linux, enable OS-level isolation: each user maps to a real Linux account, file ACLs via `setfacl`, processes spawn under the correct UID/GID.
package/bin/cli.js CHANGED
@@ -51,7 +51,6 @@ var args = process.argv.slice(2);
51
51
  var port = _isDev ? 2635 : 2633;
52
52
  var useHttps = true;
53
53
  var forceMkcert = false;
54
- var forceBuiltin = false;
55
54
  var skipUpdate = false;
56
55
  var debugMode = false;
57
56
  var autoYes = false;
@@ -84,8 +83,6 @@ for (var i = 0; i < args.length; i++) {
84
83
  useHttps = false;
85
84
  } else if (args[i] === "--local-cert") {
86
85
  forceMkcert = true;
87
- } else if (args[i] === "--builtin-cert") {
88
- forceBuiltin = true;
89
86
  } else if (args[i] === "--no-update" || args[i] === "--skip-update") {
90
87
  skipUpdate = true;
91
88
  } else if (args[i] === "--dev") {
@@ -133,7 +130,6 @@ for (var i = 0; i < args.length; i++) {
133
130
  console.log(" --host <address> Address to bind to (default: 0.0.0.0)");
134
131
  console.log(" --no-https Disable HTTPS (enabled by default)");
135
132
  console.log(" --local-cert Use local certificate (mkcert), suppress migration notice");
136
- console.log(" --builtin-cert Use builtin certificate even if mkcert is installed");
137
133
  console.log(" --no-update Skip auto-update check on startup");
138
134
  console.log(" --debug Enable debug panel in the web UI");
139
135
  console.log(" -y, --yes Skip interactive prompts (accept defaults)");
@@ -632,45 +628,10 @@ function getAllIPs() {
632
628
  return ips;
633
629
  }
634
630
 
635
- function getBuiltinCert() {
636
- try {
637
- var certDir = path.join(__dirname, "..", "lib", "certs");
638
- var keyPath = path.join(certDir, "privkey.pem");
639
- var certPath = path.join(certDir, "fullchain.pem");
640
- if (!fs.existsSync(keyPath) || !fs.existsSync(certPath)) return null;
641
-
642
- // Check expiry
643
- var certText = execFileSync("openssl", [
644
- "x509", "-in", certPath, "-noout", "-enddate"
645
- ], { encoding: "utf8" });
646
- var m = certText.match(/notAfter=(.+)/);
647
- if (m) {
648
- var expiry = new Date(m[1]);
649
- var now = new Date();
650
- // Skip if expiring within 7 days
651
- if (expiry.getTime() - now.getTime() < 7 * 24 * 60 * 60 * 1000) return null;
652
- }
653
-
654
- return { key: keyPath, cert: certPath, caRoot: null, builtin: true };
655
- } catch (e) {
656
- return null;
657
- }
658
- }
659
-
660
- function toClayStudioUrl(ip, port, protocol) {
661
- var dashed = ip.replace(/\./g, "-");
662
- return protocol + "://" + dashed + ".d.clay.studio:" + port;
663
- }
664
-
665
631
  function ensureCerts(ip) {
666
- // --builtin-cert: skip mkcert entirely, go straight to builtin
667
- if (forceBuiltin) {
668
- var builtin = getBuiltinCert();
669
- if (builtin) return builtin;
670
- return null;
671
- }
672
-
673
- var certDir = path.join(process.env.CLAGENTIC_HOME || process.env.CLAY_HOME || path.join(REAL_HOME, ".clagentic"), "certs");
632
+ // certs/ now lives under CONFIG_DIR (= ~/.clagentic/console/).
633
+ // Old location was ~/.clagentic/certs/ — migration runs in daemon.js on startup.
634
+ var certDir = path.join(CONFIG_DIR, "certs");
674
635
  var keyPath = path.join(certDir, "key.pem");
675
636
  var certPath = path.join(certDir, "cert.pem");
676
637
 
@@ -726,7 +687,7 @@ function ensureCerts(ip) {
726
687
  var mkcertArgs = ["-key-file", keyPath, "-cert-file", certPath].concat(domains);
727
688
  execFileSync("mkcert", mkcertArgs, { stdio: "pipe" });
728
689
  } catch (err) {
729
- // mkcert generation failed, fall through to builtin
690
+ // mkcert generation failed
730
691
  }
731
692
 
732
693
  if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
@@ -734,28 +695,20 @@ function ensureCerts(ip) {
734
695
  }
735
696
  }
736
697
 
737
- // Fallback: builtin cert (unless --local-cert forces mkcert-only)
738
- if (!forceMkcert) {
739
- var builtin = getBuiltinCert();
740
- if (builtin) return builtin;
741
- }
742
-
743
698
  return null;
744
699
  }
745
700
 
746
701
  // --- Logo ---
747
702
  function printLogo() {
748
703
  var r = a.reset;
704
+ // Clagentic: Console — startup banner (lr-5e26)
749
705
  var lines = [
750
- "________/\\\\\\\\\\\\\\\\\\__/\\\\\\_________________/\\\\\\\\\\\\\\\\\\_____/\\\\\\________/\\\\\\",
751
- " _____/\\\\\\////////__\\/\\\\\\_______________/\\\\\\\\\\\\\\\\\\\\\\\\\\__\\///\\\\\\____/\\\\\\/_",
752
- " ___/\\\\\\/___________\\/\\\\\\______________/\\\\\\/////////\\\\\\___\\///\\\\\\/\\\\\\/___",
753
- " __/\\\\\\_____________\\/\\\\\\_____________\\/\\\\\\_______\\/\\\\\\_____\\///\\\\\\/_____",
754
- " _\\/\\\\\\_____________\\/\\\\\\_____________\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_______\\/\\\\\\______",
755
- " _\\//\\\\\\____________\\/\\\\\\_____________\\/\\\\\\/////////\\\\\\_______\\/\\\\\\______",
756
- " __\\///\\\\\\__________\\/\\\\\\_____________\\/\\\\\\_______\\/\\\\\\_______\\/\\\\\\______",
757
- " ____\\////\\\\\\\\\\\\\\\\\\_\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_\\/\\\\\\_______\\/\\\\\\_______\\/\\\\\\______",
758
- " _______\\/////////__\\///////////////__\\///________\\///________\\///_______",
706
+ " ____ _ _ ____ _____ _ _ _____ ___ ____ ",
707
+ " / ___| | / \\ / ___| ____| \\ | |_ _|_ _/ ___| ",
708
+ "| | | | / _ \\| | _| _| | \\| | | | | | | ",
709
+ "| |___| |___ / ___ \\ |_| | |___| |\\ | | | | | |___ ",
710
+ " \\____|_____/_/ \\_\\____|_____|_| \\_| |_| |___\\____| ",
711
+ " : Console ",
759
712
  ];
760
713
  console.log("");
761
714
  if (isBasicTerm) {
@@ -1503,14 +1456,12 @@ function setup(callback) {
1503
1456
  async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers) {
1504
1457
  var ip = getLocalIP();
1505
1458
  var hasTls = false;
1506
- var hasBuiltinCert = false;
1507
1459
  var mkcertDetected = false;
1508
1460
 
1509
1461
  if (useHttps) {
1510
1462
  var certPaths = ensureCerts(ip);
1511
1463
  if (certPaths) {
1512
1464
  hasTls = true;
1513
- if (certPaths.builtin) hasBuiltinCert = true;
1514
1465
  if (certPaths.mkcertDetected) mkcertDetected = true;
1515
1466
  } else {
1516
1467
  log(sym.warn + " " + a.yellow + "HTTPS unavailable" + a.reset + a.dim + " · mkcert not installed" + a.reset);
@@ -1606,14 +1557,13 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers) {
1606
1557
  host: host,
1607
1558
  pinHash: mode === "multi" && cliPin ? generateAuthToken(cliPin) : (prevConfig && prevConfig.pinHash) || null,
1608
1559
  tls: hasTls,
1609
- builtinCert: hasBuiltinCert,
1610
1560
  mkcertDetected: mkcertDetected,
1611
1561
  debug: debugMode,
1612
1562
  headless: headlessMode,
1613
1563
  keepAwake: keepAwake,
1614
1564
  dangerouslySkipPermissions: dangerouslySkipPermissions,
1615
1565
  osUsers: wantOsUsers || osUsersMode,
1616
- mode: mode || "single",
1566
+ mode: mode || "multi",
1617
1567
  setupCompleted: true,
1618
1568
  projects: allProjects,
1619
1569
  });
@@ -1682,12 +1632,9 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers) {
1682
1632
  // Headless mode — print status and exit immediately
1683
1633
  if (headlessMode) {
1684
1634
  var protocol = config.tls ? "https" : "http";
1685
- var url = config.builtinCert
1686
- ? toClayStudioUrl(ip, config.port, protocol)
1687
- : protocol + "://" + ip + ":" + config.port;
1635
+ var url = protocol + "://" + ip + ":" + config.port;
1688
1636
  console.log(" " + sym.done + " Daemon started (PID " + config.pid + ")");
1689
1637
  console.log(" " + sym.done + " " + url);
1690
- if (config.mkcertDetected) console.log(" " + sym.warn + " Clagentic: Console now ships with a builtin HTTPS certificate. To use it, pass --builtin-cert or uninstall mkcert.");
1691
1638
  if (_pendingSetupCode) {
1692
1639
  console.log("");
1693
1640
  console.log(" " + sym.done + " " + a.green + "Multi-user mode enabled." + a.reset);
@@ -1709,14 +1656,12 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers) {
1709
1656
  async function devMode(mode, keepAwake, existingPinHash, wantOsUsers) {
1710
1657
  var ip = getLocalIP();
1711
1658
  var hasTls = false;
1712
- var hasBuiltinCert = false;
1713
1659
  var mkcertDetected = false;
1714
1660
 
1715
1661
  if (useHttps) {
1716
1662
  var certPaths = ensureCerts(ip);
1717
1663
  if (certPaths) {
1718
1664
  hasTls = true;
1719
- if (certPaths.builtin) hasBuiltinCert = true;
1720
1665
  if (certPaths.mkcertDetected) mkcertDetected = true;
1721
1666
  }
1722
1667
  }
@@ -1797,12 +1742,11 @@ async function devMode(mode, keepAwake, existingPinHash, wantOsUsers) {
1797
1742
  host: host,
1798
1743
  pinHash: existingPinHash || null,
1799
1744
  tls: hasTls,
1800
- builtinCert: hasBuiltinCert,
1801
1745
  mkcertDetected: mkcertDetected,
1802
1746
  debug: true,
1803
1747
  keepAwake: keepAwake || false,
1804
1748
  dangerouslySkipPermissions: dangerouslySkipPermissions,
1805
- mode: mode || "single",
1749
+ mode: mode || "multi",
1806
1750
  setupCompleted: true,
1807
1751
  projects: allProjects,
1808
1752
  osUsers: wantOsUsers || (prevDevConfig ? (prevDevConfig.osUsers || false) : false),
@@ -1954,7 +1898,6 @@ async function restartDaemonWithTLS(config, callback) {
1954
1898
  callback(config);
1955
1899
  return;
1956
1900
  }
1957
- var hasBuiltinCert = !!(certPaths && certPaths.builtin);
1958
1901
  var mkcertDetected = !!(certPaths && certPaths.mkcertDetected);
1959
1902
 
1960
1903
  // Shut down old daemon
@@ -1977,7 +1920,6 @@ async function restartDaemonWithTLS(config, callback) {
1977
1920
  var newConfig = Object.assign({}, config, {
1978
1921
  pid: null,
1979
1922
  tls: true,
1980
- builtinCert: hasBuiltinCert,
1981
1923
  mkcertDetected: mkcertDetected,
1982
1924
  });
1983
1925
 
@@ -2055,9 +1997,7 @@ function showServerStarted(config, ip, setupCode) {
2055
1997
  function showMainMenu(config, ip, setupCode) {
2056
1998
  startDaemonWatcher();
2057
1999
  var protocol = config.tls ? "https" : "http";
2058
- var url = config.builtinCert
2059
- ? toClayStudioUrl(ip, config.port, protocol)
2060
- : protocol + "://" + ip + ":" + config.port;
2000
+ var url = protocol + "://" + ip + ":" + config.port;
2061
2001
 
2062
2002
  sendIPCCommand(socketPath(), { cmd: "get_status" }).then(function (status) {
2063
2003
  var projs = (status && status.projects) || [];
@@ -2086,13 +2026,6 @@ function showMainMenu(config, ip, setupCode) {
2086
2026
  log(" Press " + a.bold + "o" + a.reset + " to open in browser");
2087
2027
  log("");
2088
2028
 
2089
- if (config.mkcertDetected) {
2090
- log(" " + sym.warn + " " + a.yellow + "Clagentic: Console now ships with a builtin HTTPS certificate." + a.reset);
2091
- log(" " + a.dim + "No more CA setup on each device." + a.reset);
2092
- log(" " + a.dim + "To use it, pass --builtin-cert or uninstall mkcert." + a.reset);
2093
- log("");
2094
- }
2095
-
2096
2029
  showMenuItems();
2097
2030
  }
2098
2031
 
@@ -22,12 +22,27 @@
22
22
  var fs = require("fs");
23
23
  var path = require("path");
24
24
  var os = require("os");
25
-
26
- var REAL_HOME = process.env.SUDO_USER
27
- ? path.join("/home", process.env.SUDO_USER)
28
- : os.homedir();
29
-
30
- var FAVORITES_PATH = path.join(REAL_HOME, ".clagentic", "agents", "chattable.json");
25
+ var { CONFIG_DIR } = require("./config");
26
+
27
+ // chattable.json lives under the Console data dir (CONFIG_DIR = ~/.clagentic/console/).
28
+ // One-time migration: if the old root-level file exists and the new one does not,
29
+ // copy it so favorites/recents are preserved on upgrade.
30
+ var FAVORITES_PATH = path.join(CONFIG_DIR, "agents", "chattable.json");
31
+ (function migrateFavorites() {
32
+ var _realHome = process.env.SUDO_USER
33
+ ? path.join("/home", process.env.SUDO_USER)
34
+ : os.homedir();
35
+ var oldPath = path.join(_realHome, ".clagentic", "agents", "chattable.json");
36
+ try {
37
+ if (fs.existsSync(oldPath) && !fs.existsSync(FAVORITES_PATH)) {
38
+ fs.mkdirSync(path.dirname(FAVORITES_PATH), { recursive: true });
39
+ fs.copyFileSync(oldPath, FAVORITES_PATH);
40
+ console.log("[agents-favorites] Migrated chattable.json → " + FAVORITES_PATH + " — root copy can be removed when verified");
41
+ }
42
+ } catch (e) {
43
+ // Non-fatal — favorites will start fresh
44
+ }
45
+ }());
31
46
  var SCHEMA_VERSION = 2;
32
47
  var RECENTS_LIMIT = 8;
33
48
 
package/lib/config.js CHANGED
@@ -31,7 +31,7 @@ function getRealHome() {
31
31
 
32
32
  var REAL_HOME = getRealHome();
33
33
 
34
- // Data dir: ~/.clagentic/ (prev: ~/.clay/ — migrated on first run)
34
+ // Data dir: ~/.clagentic/console/ (prev: ~/.clagentic/ root → moved to console/ subdir by lr-12d0; prev: ~/.clay/ — migrated on first run)
35
35
  // If CLAGENTIC_CONFIG is set (daemon mode), derive CLAGENTIC_HOME from it.
36
36
  // CLAY_HOME and CLAY_CONFIG accepted as fallbacks for one release.
37
37
  var CLAGENTIC_HOME = process.env.CLAGENTIC_HOME
package/lib/daemon.js CHANGED
@@ -23,7 +23,7 @@ delete process.env.CLAUDECODE;
23
23
 
24
24
  var fs = require("fs");
25
25
  var path = require("path");
26
- var { loadConfig, saveConfig, socketPath, ensureConfigDir, 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, CONFIG_DIR, CLAGENTIC_HOME } = require("./config");
27
27
  var { createIPCServer } = require("./ipc");
28
28
  var { createServer } = require("./server");
29
29
  var { checkAclSupport, grantProjectAccess, revokeProjectAccess, provisionAllUsers, provisionLinuxUser, grantAllUsersAccess, deactivateLinuxUser, ensureProjectsDir } = require("./os-users");
@@ -31,7 +31,9 @@ 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
33
  var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
34
- var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM } = require("./sdk-bridge");
34
+ var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount } = require("./sdk-bridge");
35
+ var { startMemoryHighWatcher } = require("./memory-limits");
36
+ var { createDrain } = require("./drain");
35
37
  var liteDetect = require("./lite-detect");
36
38
  var { execFile: liteExecFile } = require("child_process");
37
39
 
@@ -169,7 +171,7 @@ function migrateSingleUserToMultiUser(cfg, data) {
169
171
  console.log("│ │");
170
172
  console.log("│ " + url.padEnd(61) + "│");
171
173
  console.log("│ │");
172
- console.log("│ Setup code also stored in ~/.clagentic/users.json │");
174
+ console.log("│ Setup code also stored in ~/.clagentic/console/users.json │");
173
175
  console.log("│ Your previous PIN cannot be transferred (format change). │");
174
176
  console.log("│ Set a new PIN via the setup URL above. │");
175
177
  console.log("└─────────────────────────────────────────────────────────────┘");
@@ -194,27 +196,28 @@ if (config.osUsers) {
194
196
  }
195
197
 
196
198
  // --- TLS ---
199
+ // One-time migration: certs dir moved from ~/.clagentic/certs/ → CONFIG_DIR/certs/ (lr-6204).
200
+ // Copy-not-rename: the old location stays so a rollback is safe.
201
+ // We run this before reading certs so a fresh start after upgrade picks them up immediately.
202
+ (function migrateCertsDir() {
203
+ var oldCerts = path.join(CLAGENTIC_HOME, "certs");
204
+ var newCerts = path.join(CONFIG_DIR, "certs");
205
+ try {
206
+ if (fs.existsSync(oldCerts) && !fs.existsSync(newCerts)) {
207
+ fs.cpSync(oldCerts, newCerts, { recursive: true, preserveTimestamps: true });
208
+ console.log("[daemon] Migrated certs/ → " + newCerts + " — root copy can be removed when verified");
209
+ }
210
+ } catch (e) {
211
+ console.error("[daemon] Certs migration failed (non-fatal):", e.message);
212
+ }
213
+ }());
197
214
  var tlsOptions = null;
198
215
  if (config.tls) {
199
- // 1. Check builtin cert (shipped with package)
200
- var builtinKeyPath = path.join(__dirname, "certs", "privkey.pem");
201
- var builtinCertPath = path.join(__dirname, "certs", "fullchain.pem");
202
-
203
- // 2. User cert (mkcert, etc.)
204
- var os = require("os");
205
- var certDir = path.join(process.env.CLAGENTIC_HOME || process.env.CLAY_HOME || path.join(REAL_HOME, ".clagentic"), "certs");
206
- var userKeyPath = path.join(certDir, "key.pem");
207
- var userCertPath = path.join(certDir, "cert.pem");
208
-
209
- var keyPath, certPath;
210
- if (config.builtinCert !== false && fs.existsSync(builtinKeyPath) && fs.existsSync(builtinCertPath)) {
211
- keyPath = builtinKeyPath;
212
- certPath = builtinCertPath;
213
- config.builtinCert = true;
214
- } else {
215
- keyPath = userKeyPath;
216
- certPath = userCertPath;
217
- }
216
+ // User cert (CONFIG_DIR/certs/key.pem + cert.pem, generated by mkcert or supplied manually).
217
+ // Old location was ~/.clagentic/certs/ — migrated above on first run.
218
+ var certDir = path.join(CONFIG_DIR, "certs");
219
+ var keyPath = path.join(certDir, "key.pem");
220
+ var certPath = path.join(certDir, "cert.pem");
218
221
 
219
222
  try {
220
223
  tlsOptions = {
@@ -1287,6 +1290,10 @@ function stopCodexReaper() {
1287
1290
  clearInterval(staleCheckHandle);
1288
1291
  staleCheckHandle = null;
1289
1292
  }
1293
+ if (_memoryWatcher) {
1294
+ _memoryWatcher.stop();
1295
+ _memoryWatcher = null;
1296
+ }
1290
1297
  }
1291
1298
 
1292
1299
  function shutdownProjects() {
@@ -1632,6 +1639,30 @@ function startListening() {
1632
1639
  config.pid = process.pid;
1633
1640
  saveConfig(config);
1634
1641
 
1642
+ // Drain controller (lr-6b30): manages graceful drain state.
1643
+ // Must be created after gracefulShutdown is defined (which is true here —
1644
+ // gracefulShutdown is a hoisted function declared before startListening).
1645
+ var drainTimeoutMs = (config.drainTimeoutMs != null && config.drainTimeoutMs > 0)
1646
+ ? config.drainTimeoutMs
1647
+ : undefined;
1648
+ _drain = createDrain({
1649
+ gracefulShutdown: gracefulShutdown,
1650
+ getActiveCount: getActiveLiveCount,
1651
+ drainTimeoutMs: drainTimeoutMs,
1652
+ });
1653
+ _drain.registerSignals();
1654
+ // Expose the drain controller on the relay so server.js can gate new connections.
1655
+ relay.setDrain(_drain);
1656
+
1657
+ // Start MemoryHigh watermark watcher (lr-de07).
1658
+ // Detects soft memory ceiling crossings and emits structured log events;
1659
+ // onCrossing notifies the drain controller (lr-6b30) to enter drain state.
1660
+ if (process.platform === "linux") {
1661
+ _memoryWatcher = startMemoryHighWatcher(config, {
1662
+ onCrossing: function (detail) { _drain.onMemoryHighCrossing(detail); },
1663
+ });
1664
+ }
1665
+
1635
1666
  // Auto-provision Linux accounts on startup if OS users mode is enabled.
1636
1667
  // ACLs are NOT re-applied on every startup (too slow with recursive setfacl).
1637
1668
  // ACLs are set when: projects are added, users are added, or visibility changes.
@@ -1712,6 +1743,12 @@ if (relay.onboardingServer) {
1712
1743
  });
1713
1744
  }
1714
1745
 
1746
+ // MemoryHigh watcher handle (lr-de07) — started after the server is listening.
1747
+ var _memoryWatcher = null;
1748
+
1749
+ // Drain controller (lr-6b30) — initialized in startListening after gracefulShutdown is defined.
1750
+ var _drain = null;
1751
+
1715
1752
  // --- Caffeinate (macOS) ---
1716
1753
  var caffeinateProc = null;
1717
1754
  if (config.keepAwake && process.platform === "darwin") {
package/lib/drain.js ADDED
@@ -0,0 +1,213 @@
1
+ // drain.js — graceful drain state for the daemon (lr-6b30).
2
+ //
3
+ // Drain is entered when either:
4
+ // A. The lr-de07 MemoryHigh watermark watcher fires an onCrossing callback.
5
+ // B. An operator sends SIGUSR1 or SIGUSR2 (manual drain/restart signal).
6
+ //
7
+ // While draining:
8
+ // - New WebSocket session connections are rejected with a structured error.
9
+ // - In-flight sessions are allowed to complete. The drain controller checks
10
+ // the live query count via opts.getActiveCount() and exits once it hits zero.
11
+ // - A configurable drain timeout (default 60 s) forces exit if sessions do
12
+ // not complete in time.
13
+ //
14
+ // The module exports createDrain(opts), which returns a controller object used
15
+ // by daemon.js and the WebSocket gate in server.js.
16
+ //
17
+ // Design constraints:
18
+ // - No second memory poller; consume startMemoryHighWatcher's signal only.
19
+ // - Reuse gracefulShutdown() from daemon.js; do not invent a parallel path.
20
+ // - One drain state machine; both trigger paths set the same state.
21
+
22
+ 'use strict';
23
+
24
+ // Default drain timeout in milliseconds.
25
+ var DEFAULT_DRAIN_TIMEOUT_MS = 60 * 1000;
26
+
27
+ // How often to check the live-query count after entering drain state.
28
+ var DRAIN_POLL_INTERVAL_MS = 1000;
29
+
30
+ /**
31
+ * Create a drain controller.
32
+ *
33
+ * @param {object} opts
34
+ * @param {function(): void} opts.gracefulShutdown
35
+ * Called when all in-flight sessions complete (or timeout expires).
36
+ * @param {function(): number} opts.getActiveCount
37
+ * Returns the current number of in-flight queries. Provided by daemon.js
38
+ * from sdk-bridge's getActiveLiveCount(). Queried on a 1-second interval
39
+ * after drain is entered.
40
+ * @param {number} [opts.drainTimeoutMs]
41
+ * Maximum ms to wait for in-flight sessions before forcing exit.
42
+ * Reads from config.drainTimeoutMs if provided; defaults to 60000.
43
+ * @param {function(object): void} [opts.log]
44
+ * Structured log emitter. Receives a plain object; default emits JSON to
45
+ * stderr so journald captures it alongside other daemon output.
46
+ *
47
+ * @returns {DrainController}
48
+ */
49
+ function createDrain(opts) {
50
+ if (!opts || typeof opts.gracefulShutdown !== 'function') {
51
+ throw new Error('drain.createDrain: opts.gracefulShutdown must be a function');
52
+ }
53
+ if (typeof opts.getActiveCount !== 'function') {
54
+ throw new Error('drain.createDrain: opts.getActiveCount must be a function');
55
+ }
56
+
57
+ var gracefulShutdown = opts.gracefulShutdown;
58
+ var getActiveCount = opts.getActiveCount;
59
+ var drainTimeoutMs = (opts.drainTimeoutMs != null && opts.drainTimeoutMs > 0)
60
+ ? opts.drainTimeoutMs
61
+ : DEFAULT_DRAIN_TIMEOUT_MS;
62
+
63
+ var _log = opts.log || function (event) {
64
+ try {
65
+ process.stderr.write('[drain] ' + JSON.stringify(event) + '\n');
66
+ } catch (_) {}
67
+ };
68
+
69
+ // --- State ---
70
+ var _isDraining = false;
71
+ var _drainReason = null;
72
+ var _drainTimeout = null;
73
+ var _drainPollHandle = null;
74
+ var _signalsRegistered = false;
75
+ var _exitCalled = false;
76
+
77
+ // --- Internal helpers ---
78
+
79
+ function _emitLog(event) {
80
+ try { _log(event); } catch (_) {}
81
+ }
82
+
83
+ function _callExit(reason) {
84
+ if (_exitCalled) return;
85
+ _exitCalled = true;
86
+ _clearTimers();
87
+ _emitLog({
88
+ event: 'drain_exit',
89
+ reason: reason,
90
+ activeCount: getActiveCount(),
91
+ timestamp: new Date().toISOString(),
92
+ });
93
+ gracefulShutdown();
94
+ }
95
+
96
+ function _clearTimers() {
97
+ if (_drainTimeout) {
98
+ clearTimeout(_drainTimeout);
99
+ _drainTimeout = null;
100
+ }
101
+ if (_drainPollHandle) {
102
+ clearInterval(_drainPollHandle);
103
+ _drainPollHandle = null;
104
+ }
105
+ }
106
+
107
+ function _checkActiveCount() {
108
+ if (!_isDraining || _exitCalled) return;
109
+ var count = getActiveCount();
110
+ if (count <= 0) {
111
+ _callExit('active_count_zero');
112
+ }
113
+ }
114
+
115
+ function _forceExit() {
116
+ _callExit('timeout_forced');
117
+ }
118
+
119
+ // --- Public API ---
120
+
121
+ /**
122
+ * Enter drain state. Idempotent: subsequent calls from either trigger path
123
+ * are no-ops — only the first crossing matters.
124
+ *
125
+ * @param {string} reason — 'memory_high_watermark' | 'signal_usr1' | 'signal_usr2'
126
+ * @param {object} [detail] — optional extra fields for the log event
127
+ */
128
+ function enterDrain(reason, detail) {
129
+ if (_isDraining) return; // already draining — idempotent
130
+ _isDraining = true;
131
+ _drainReason = reason;
132
+
133
+ var activeCount = getActiveCount();
134
+ var logEvent = Object.assign({
135
+ event: 'drain_enter',
136
+ reason: reason,
137
+ activeCount: activeCount,
138
+ drainTimeoutMs: drainTimeoutMs,
139
+ timestamp: new Date().toISOString(),
140
+ }, detail || {});
141
+ _emitLog(logEvent);
142
+
143
+ // If no sessions are currently active, exit immediately.
144
+ if (activeCount <= 0) {
145
+ _callExit('active_count_zero');
146
+ return;
147
+ }
148
+
149
+ // Arm the timeout guard so a stuck session cannot hold the daemon up forever.
150
+ _drainTimeout = setTimeout(_forceExit, drainTimeoutMs);
151
+ // Unref so the timeout alone does not prevent other exit paths.
152
+ if (_drainTimeout && typeof _drainTimeout.unref === 'function') {
153
+ _drainTimeout.unref();
154
+ }
155
+
156
+ // Poll the live-query count every second so we exit as soon as sessions finish.
157
+ _drainPollHandle = setInterval(_checkActiveCount, DRAIN_POLL_INTERVAL_MS);
158
+ if (_drainPollHandle && typeof _drainPollHandle.unref === 'function') {
159
+ _drainPollHandle.unref();
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Returns true when the daemon is in drain state.
165
+ *
166
+ * @returns {boolean}
167
+ */
168
+ function isDraining() {
169
+ return _isDraining;
170
+ }
171
+
172
+ /**
173
+ * Register SIGUSR1 and SIGUSR2 as manual drain triggers.
174
+ *
175
+ * Idempotent: safe to call multiple times.
176
+ */
177
+ function registerSignals() {
178
+ if (_signalsRegistered) return;
179
+ _signalsRegistered = true;
180
+
181
+ // SIGUSR1 is used by Node.js built-in debugger on some platforms — we still
182
+ // register it because this daemon does not use the built-in debugger in
183
+ // production, and operator-initiated drain is the intended use case here.
184
+ process.on('SIGUSR1', function () {
185
+ enterDrain('signal_usr1');
186
+ });
187
+ process.on('SIGUSR2', function () {
188
+ enterDrain('signal_usr2');
189
+ });
190
+ }
191
+
192
+ /**
193
+ * Called by the MemoryHigh watcher's onCrossing callback.
194
+ * Enters drain state with the watermark event detail attached to the log.
195
+ *
196
+ * @param {object} [detail] — fields from the watermark event (source, currentBytes, etc.)
197
+ */
198
+ function onMemoryHighCrossing(detail) {
199
+ enterDrain('memory_high_watermark', detail || {});
200
+ }
201
+
202
+ return {
203
+ isDraining: isDraining,
204
+ enterDrain: enterDrain,
205
+ registerSignals: registerSignals,
206
+ onMemoryHighCrossing: onMemoryHighCrossing,
207
+ // Exposed for testing only.
208
+ _DEFAULT_DRAIN_TIMEOUT_MS: DEFAULT_DRAIN_TIMEOUT_MS,
209
+ _DRAIN_POLL_INTERVAL_MS: DRAIN_POLL_INTERVAL_MS,
210
+ };
211
+ }
212
+
213
+ module.exports = { createDrain: createDrain, DEFAULT_DRAIN_TIMEOUT_MS: DEFAULT_DRAIN_TIMEOUT_MS };