@clagentic/console 1.5.0-beta.2 → 1.5.0-beta.4

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 +18 -14
  2. package/bin/cli.js +1 -0
  3. package/lib/cli-sessions.js +71 -18
  4. package/lib/config.js +80 -6
  5. package/lib/daemon-projects.js +1 -1
  6. package/lib/daemon.js +142 -26
  7. package/lib/pages.js +1 -42
  8. package/lib/project-connection.js +4 -8
  9. package/lib/project-external-trigger.js +62 -7
  10. package/lib/project-http.js +17 -1
  11. package/lib/project-loop.js +3 -2
  12. package/lib/project-notifications.js +3 -18
  13. package/lib/project-sessions.js +68 -27
  14. package/lib/project-team.js +417 -0
  15. package/lib/project-user-message.js +5 -10
  16. package/lib/project.js +53 -53
  17. package/lib/public/app.js +7 -15
  18. package/lib/public/css/home-hub.css +36 -0
  19. package/lib/public/css/icon-strip.css +28 -126
  20. package/lib/public/css/menus.css +2 -2
  21. package/lib/public/css/team-panel.css +149 -0
  22. package/lib/public/index.html +72 -15
  23. package/lib/public/modules/admin.js +1 -52
  24. package/lib/public/modules/agent-picker.js +11 -3
  25. package/lib/public/modules/app-cursors.js +43 -47
  26. package/lib/public/modules/app-home-hub.js +12 -0
  27. package/lib/public/modules/app-messages.js +18 -12
  28. package/lib/public/modules/app-rendering.js +1 -2
  29. package/lib/public/modules/server-settings.js +74 -5
  30. package/lib/public/modules/sidebar-mobile.js +9 -88
  31. package/lib/public/modules/sidebar-projects.js +1 -1
  32. package/lib/public/modules/sidebar-sessions.js +6 -2
  33. package/lib/public/modules/sidebar-users.js +37 -307
  34. package/lib/public/modules/team-panel.js +331 -0
  35. package/lib/public/modules/tools.js +3 -0
  36. package/lib/public/modules/user-settings.js +0 -3
  37. package/lib/public/style.css +1 -0
  38. package/lib/sdk-bridge.js +121 -8
  39. package/lib/sdk-message-processor.js +39 -4
  40. package/lib/sdk-worker.js +2 -2
  41. package/lib/server-admin.js +1 -86
  42. package/lib/server-auth.js +13 -124
  43. package/lib/server-dm.js +2 -7
  44. package/lib/server-palette.js +9 -20
  45. package/lib/server-settings.js +41 -243
  46. package/lib/server-skills.js +11 -13
  47. package/lib/server.js +37 -60
  48. package/lib/sessions.js +16 -50
  49. package/lib/terminal-manager.js +13 -15
  50. package/lib/users-auth.js +0 -38
  51. package/lib/users.js +14 -11
  52. package/lib/ws-schema.js +12 -0
  53. package/lib/yoke/adapters/claude.js +5 -0
  54. package/package.json +1 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
  <img src="media/logo/console-lockup-256.png" alt="Clagentic: Console" width="260" />
3
3
  </p>
4
4
 
5
- <h4 align="center">AI tooling. Built for builders.</h4>
5
+ <h4 align="center">A shared workspace for humans and AI agents.</h4>
6
6
 
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>
@@ -13,7 +13,7 @@
13
13
  <a href="https://ko-fi.com/clagentic"><img src="https://img.shields.io/badge/Ko--fi-FF5E5B?style=flat&logo=ko-fi&logoColor=white&label=support" alt="Support on Ko-fi" /></a>
14
14
  </p>
15
15
 
16
- A self-hosted control plane for your AI runtimes. Clagentic: Console runs as a daemon on your machine and serves a full browser and mobile interface to Claude Code and ChatGPT Codex. Every project, every session, every tool approval — reachable from any device, all data staying on disk.
16
+ Clagentic: Console is a self-hosted team workspace where human developers and named AI agents share the same interface. Multiple users connect to a single daemon, each with their own account and project access. Agents are first-class participants — not background processes you poll, but named entities with their own conversation history, context window, and session state, visible to the whole team. Every project, every session, every tool approval lives on your machine and stays there.
17
17
 
18
18
  ## Install
19
19
 
@@ -47,23 +47,25 @@ npm install -g @clagentic/console --ignore-scripts
47
47
 
48
48
  ## What it does
49
49
 
50
- - **Named agent sessions.** Type `@` in the session input to launch any agent defined in `.claude/agents/` or `~/.claude/agents/` into its own session — with its own conversation history, context window, and state. Pick agents by name, switch mid-conversation.
50
+ - **Real team accounts.** Every team member gets their own login. Multiple users connect to the same Console daemon simultaneously — each with their own session history, project access, and tool approval flow. No shared credentials, no per-user installs.
51
51
 
52
- - **Context injection.** Pin running terminals, live browser tabs, and sticky notes as active context sources. Their content flows into every message automatically: terminal output as a delta since your last message, browser tabs as full snapshots. No manual copy-paste. No extra prompting.
53
-
54
- - **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.
52
+ - **Agents as first-class participants.** Named agents defined in `.claude/agents/` or `~/.claude/agents/` are not background scripts — they're full participants. Each runs in its own session with its own conversation history, context window, and state. Team members can favorite agents, DM them directly, and see which agents are active. Type `@` in the session input to launch one by name.
55
53
 
56
- - **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 Claude into scripts, CI pipelines, or other AI processes — no API, no polling, just a file drop.
54
+ - **Team panel.** A dedicated Team surface lists every human user and named agent connected to the Console. Direct-message any participant, see who's online, and manage the agent roster — all from the same sidebar that shows your projects.
57
55
 
58
- - **Cross-vendor instruction injection.** YOKE (the vendor adapter layer) scans `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, `COPILOT.md`, and `.github/copilot-instructions.md` and cross-injects whichever ones the active vendor doesn't read natively. Switch from Claude to Codex in a session — your project instructions still reach the model.
56
+ - **Vendor-agnostic via YOKE.** The YOKE adapter layer treats Claude Code (Claude Agent SDK), ChatGPT Codex (codex app-server JSON-RPC), and future local models as interchangeable backends. Switch vendors per session; sessions remember their choice. YOKE also cross-injects instruction files — `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, `COPILOT.md`, `.github/copilot-instructions.md` — so project context reaches whichever model is running.
59
57
 
60
58
  - **Multi-project dashboard.** Every repo registered with the daemon in one sidebar. Jump between projects, run sessions in parallel, see live status at a glance.
61
59
 
62
- - **Mobile PWA + push notifications.** Installable on iOS and Android. Approve tool calls from your phone. Push fires on approval requests, errors, and task completion.
60
+ - **Context injection.** Pin running terminals, live browser tabs, and sticky notes as active context sources. Their content flows into every message automatically: terminal output as a delta since your last message, browser tabs as full snapshots. No manual copy-paste. No extra prompting.
63
61
 
64
- - **Multi-user with OS isolation.** On Linux, opt in: each user maps to a real system account, file ACLs via `setfacl`, processes spawn under the correct UID/GID.
62
+ - **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
+ - **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
65
 
66
- - **Vendor flexibility.** Claude Code (Claude Agent SDK) and ChatGPT Codex (codex app-server protocol). Switch per session. Sessions remember their vendor.
66
+ - **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
+ - **OS-level isolation (Linux).** On Linux, opt in: each user maps to a real system account, file ACLs via `setfacl`, processes spawn under the correct UID/GID.
67
69
 
68
70
  - **MCP servers.** Built-in ask-user and browser servers. User-configured MCPs via `~/.clagentic/mcp.json`. Works in both Claude and Codex sessions.
69
71
 
@@ -73,7 +75,9 @@ npm install -g @clagentic/console --ignore-scripts
73
75
 
74
76
  ## Getting Started
75
77
 
76
- On first run you'll be asked for a port and prompted to create your admin account. Open the URL from any device on your network.
78
+ On first run you'll be asked for a port and prompted to create your admin account. Open the URL from any device on your network — team members can log in with their own accounts from their own machines.
79
+
80
+ Enable multi-user mode in System Settings to activate OS-level isolation (Linux) and the team-management panel. Additional accounts are created from the admin UI or CLI; each user gets independent session history and project access.
77
81
 
78
82
  For remote access, use a tunnel — Tailscale, Cloudflare Tunnel, or your existing VPN.
79
83
 
@@ -173,7 +177,7 @@ Run the suite: `npm test`
173
177
  No. Clagentic: Console drives Claude Code through the Claude Agent SDK and Codex through the Codex app-server protocol. It adds multi-session orchestration, named agent sessions, scheduled agents, multi-user support, built-in MCP servers, context injection, external triggers, and a full browser UI on top.
174
178
 
175
179
  **"What are named agents?"**
176
- Agents defined in your Claude Code config (`.claude/agents/` or `~/.claude/agents/`) become first-class sessions. Type `@` in the session input to see every installed agent and launch one directly — its own conversation history, context window, and session state.
180
+ Agents defined in your Claude Code config (`.claude/agents/` or `~/.claude/agents/`) are first-class team participants. Type `@` in the session input to see every installed agent and launch one directly — its own conversation history, context window, and session state. Team members can favorite agents and DM them from the Team panel alongside human users.
177
181
 
178
182
  Named agents are **currently Claude Code only.** The Codex adapter has no equivalent API for per-session agent identity injection. When you're in a Codex session, the agent entry point is hidden. Partial Codex parity (system-prompt prepend) is planned.
179
183
 
@@ -208,7 +212,7 @@ Yes. Install as a PWA on iOS or Android. Push notifications for approvals, error
208
212
  Yes. User-configured MCPs from `~/.clagentic/mcp.json` plus built-in ask-user and browser servers work in both Claude and Codex sessions.
209
213
 
210
214
  **"Multi-user support?"**
211
- Yes. On Linux, opt in to OS-level isolation: each user maps to a real Linux account, file ACLs via `setfacl`, processes spawn under the correct UID/GID.
215
+ 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.
212
216
 
213
217
  **"Does it integrate with Clagentic: Lite?"**
214
218
  Yes, optionally. [Clagentic: Lite](https://clagentic.ai/tools) adds agentic gates, session memory, and audit trails to any repo. If Lite is installed (`~/.clagentic/lite/`), Console detects it automatically and shows an enrollment panel in each project's settings. Enable auto-enroll in system settings to wire up every project on add. Lite is never required — Console works normally without it.
package/bin/cli.js CHANGED
@@ -349,6 +349,7 @@ var a = {
349
349
  green: "\x1b[32m",
350
350
  yellow: "\x1b[33m",
351
351
  red: "\x1b[31m",
352
+ cyan: "\x1b[36m",
352
353
  };
353
354
 
354
355
  function gradient(text) {
@@ -6,6 +6,19 @@ var { REAL_HOME } = require("./config");
6
6
 
7
7
  var encodeCwd = utils.encodeCwd;
8
8
 
9
+ // Maximum number of sessions returned by listCliSessions().
10
+ // Prevents OOM on installs with large session archives (e.g. 30K+ files).
11
+ // Tunable: raise if users need deeper history in the session picker.
12
+ var MAX_CLI_SESSIONS = 200;
13
+
14
+ // Sessions older than this are excluded before any file I/O.
15
+ // 90 days keeps the session picker relevant without opening stale files.
16
+ var CLI_SESSION_MAX_AGE_MS = 90 * 24 * 60 * 60 * 1000;
17
+
18
+ // Max simultaneous parseSessionFile() calls inside listCliSessions().
19
+ // Caps readline stream count; too high → fd exhaustion; too low → slow.
20
+ var PARSE_CONCURRENCY = 20;
21
+
9
22
  /**
10
23
  * Parse the first ~20 lines of a CLI session JSONL file to extract metadata.
11
24
  * Returns null if the file can't be parsed or has no user messages.
@@ -105,6 +118,12 @@ function parseSessionFile(filePath, maxLines) {
105
118
  * List CLI sessions for a given project directory.
106
119
  * Reads ~/.claude/projects/{encoded-cwd}/ and parses JSONL metadata.
107
120
  * Returns array sorted by lastActivity descending (most recent first).
121
+ *
122
+ * Two-stage to prevent OOM on large session archives:
123
+ * Stage 1 — stat + cap: filter by recency (CLI_SESSION_MAX_AGE_MS), sort by
124
+ * mtime descending, slice to MAX_CLI_SESSIONS.
125
+ * Stage 2 — promise pool: parse the capped list with at most
126
+ * PARSE_CONCURRENCY simultaneous parseSessionFile() calls.
108
127
  */
109
128
  function listCliSessions(cwd) {
110
129
  var encoded = encodeCwd(cwd);
@@ -114,32 +133,66 @@ function listCliSessions(cwd) {
114
133
  fs.readdir(projectDir, { withFileTypes: true }, function (err, entries) {
115
134
  if (err) return resolve([]);
116
135
 
117
- var jsonlFiles = [];
136
+ var now = Date.now();
137
+ var cutoff = now - CLI_SESSION_MAX_AGE_MS;
138
+
139
+ // Stage 1: stat every .jsonl file, drop stale entries, sort and cap.
140
+ var candidates = [];
118
141
  for (var i = 0; i < entries.length; i++) {
119
- if (entries[i].isFile() && entries[i].name.endsWith(".jsonl")) {
120
- jsonlFiles.push(path.join(projectDir, entries[i].name));
142
+ if (!entries[i].isFile() || !entries[i].name.endsWith(".jsonl")) continue;
143
+ var filePath = path.join(projectDir, entries[i].name);
144
+ try {
145
+ var st = fs.statSync(filePath);
146
+ if (st.mtimeMs >= cutoff) {
147
+ candidates.push({ filePath: filePath, mtimeMs: st.mtimeMs });
148
+ }
149
+ } catch (e) {
150
+ // File disappeared between readdir and stat — skip it.
121
151
  }
122
152
  }
123
153
 
124
- if (jsonlFiles.length === 0) return resolve([]);
154
+ if (candidates.length === 0) return resolve([]);
125
155
 
126
- var pending = jsonlFiles.length;
127
- var results = [];
156
+ // Sort newest-first, then cap.
157
+ candidates.sort(function (a, b) { return b.mtimeMs - a.mtimeMs; });
158
+ if (candidates.length > MAX_CLI_SESSIONS) {
159
+ candidates = candidates.slice(0, MAX_CLI_SESSIONS);
160
+ }
128
161
 
129
- for (var j = 0; j < jsonlFiles.length; j++) {
130
- parseSessionFile(jsonlFiles[j]).then(function (session) {
131
- if (session) results.push(session);
132
- pending--;
133
- if (pending === 0) {
134
- results.sort(function (a, b) {
135
- var ta = a.lastActivity || "";
136
- var tb = b.lastActivity || "";
137
- return ta < tb ? 1 : ta > tb ? -1 : 0;
138
- });
139
- resolve(results);
140
- }
162
+ // Stage 2: promise pool — at most PARSE_CONCURRENCY concurrent parses.
163
+ var results = [];
164
+ var index = 0; // next candidate to start
165
+ var active = 0; // currently running parseSessionFile calls
166
+ var total = candidates.length;
167
+ var done = 0; // completed calls
168
+
169
+ function finish() {
170
+ results.sort(function (a, b) {
171
+ var ta = a.lastActivity || "";
172
+ var tb = b.lastActivity || "";
173
+ return ta < tb ? 1 : ta > tb ? -1 : 0;
141
174
  });
175
+ resolve(results);
142
176
  }
177
+
178
+ function schedule() {
179
+ while (active < PARSE_CONCURRENCY && index < total) {
180
+ var item = candidates[index++];
181
+ active++;
182
+ parseSessionFile(item.filePath).then(function (session) {
183
+ if (session) results.push(session);
184
+ active--;
185
+ done++;
186
+ if (done === total) {
187
+ finish();
188
+ } else {
189
+ schedule();
190
+ }
191
+ });
192
+ }
193
+ }
194
+
195
+ schedule();
143
196
  });
144
197
  });
145
198
  }
package/lib/config.js CHANGED
@@ -170,12 +170,86 @@ function ensureConfigDir() {
170
170
  }
171
171
  }
172
172
  // external-triggers/
173
- if (fs.existsSync(OLD_EXTERNAL_TRIGGERS_DIR) && !fs.existsSync(EXTERNAL_TRIGGERS_DIR)) {
174
- try {
175
- fs.cpSync(OLD_EXTERNAL_TRIGGERS_DIR, EXTERNAL_TRIGGERS_DIR, { recursive: true });
176
- console.warn("[config] Migrated external-triggers/ → " + EXTERNAL_TRIGGERS_DIR);
177
- } catch (e) {
178
- console.error("[config] Migration of external-triggers/ failed (non-fatal):", e.message);
173
+ // Use lstatSync (not existsSync) so a pre-existing symlink at the old path is
174
+ // detected and skipped — we only act on a real directory.
175
+ var _oldTriggersIsRealDir = false;
176
+ try {
177
+ var _oldStat = fs.lstatSync(OLD_EXTERNAL_TRIGGERS_DIR);
178
+ _oldTriggersIsRealDir = _oldStat.isDirectory() && !_oldStat.isSymbolicLink();
179
+ } catch (_) {}
180
+ if (_oldTriggersIsRealDir) {
181
+ if (!fs.existsSync(EXTERNAL_TRIGGERS_DIR)) {
182
+ // Case 1: new dir absent — simple copy (existing behavior).
183
+ try {
184
+ fs.cpSync(OLD_EXTERNAL_TRIGGERS_DIR, EXTERNAL_TRIGGERS_DIR, { recursive: true });
185
+ console.warn("[config] Migrated external-triggers/ → " + EXTERNAL_TRIGGERS_DIR);
186
+ } catch (e) {
187
+ console.error("[config] Migration of external-triggers/ failed (non-fatal):", e.message);
188
+ }
189
+ } else {
190
+ // Case 2: both old and new exist — merge .json files from old that are not
191
+ // already present in new (by filename), then replace the old dir with a
192
+ // symlink → EXTERNAL_TRIGGERS_DIR so stale writers (e.g. an un-updated relay
193
+ // binary still writing to the old root path) are silently redirected.
194
+ try {
195
+ // Merge top-level .json files.
196
+ var _oldFiles = fs.readdirSync(OLD_EXTERNAL_TRIGGERS_DIR);
197
+ for (var _oi = 0; _oi < _oldFiles.length; _oi++) {
198
+ var _oldFile = _oldFiles[_oi];
199
+ if (_oldFile === "processed") continue; // handled separately below
200
+ if (path.extname(_oldFile) !== ".json") continue;
201
+ var _oldFilePath = path.join(OLD_EXTERNAL_TRIGGERS_DIR, _oldFile);
202
+ var _newFilePath = path.join(EXTERNAL_TRIGGERS_DIR, _oldFile);
203
+ if (!fs.existsSync(_newFilePath)) {
204
+ try {
205
+ fs.copyFileSync(_oldFilePath, _newFilePath);
206
+ console.warn("[config] Merged external-triggers/" + _oldFile + " → " + _newFilePath);
207
+ } catch (_ce) {
208
+ console.error("[config] Merge of " + _oldFile + " failed (non-fatal):", _ce.message);
209
+ }
210
+ }
211
+ }
212
+ // Merge processed/ subdir files.
213
+ var _oldProcessedDir = path.join(OLD_EXTERNAL_TRIGGERS_DIR, "processed");
214
+ var _newProcessedDir = path.join(EXTERNAL_TRIGGERS_DIR, "processed");
215
+ if (fs.existsSync(_oldProcessedDir)) {
216
+ try { fs.mkdirSync(_newProcessedDir, { recursive: true }); } catch (_) {}
217
+ var _oldProcessed = fs.readdirSync(_oldProcessedDir);
218
+ for (var _pi = 0; _pi < _oldProcessed.length; _pi++) {
219
+ var _pf = _oldProcessed[_pi];
220
+ if (path.extname(_pf) !== ".json") continue;
221
+ var _oldPfPath = path.join(_oldProcessedDir, _pf);
222
+ var _newPfPath = path.join(_newProcessedDir, _pf);
223
+ if (!fs.existsSync(_newPfPath)) {
224
+ try {
225
+ fs.copyFileSync(_oldPfPath, _newPfPath);
226
+ console.warn("[config] Merged external-triggers/processed/" + _pf + " → " + _newPfPath);
227
+ } catch (_ce2) {
228
+ console.error("[config] Merge of processed/" + _pf + " failed (non-fatal):", _ce2.message);
229
+ }
230
+ }
231
+ }
232
+ }
233
+ // Replace old dir with a symlink → EXTERNAL_TRIGGERS_DIR. Rename to a temp
234
+ // name first, create the symlink, then remove the temp. Non-fatal: on any
235
+ // failure we best-effort restore the original name and leave for manual cleanup.
236
+ var _oldTriggersTmp = OLD_EXTERNAL_TRIGGERS_DIR + ".migration-tmp";
237
+ try {
238
+ fs.renameSync(OLD_EXTERNAL_TRIGGERS_DIR, _oldTriggersTmp);
239
+ fs.symlinkSync(EXTERNAL_TRIGGERS_DIR, OLD_EXTERNAL_TRIGGERS_DIR);
240
+ fs.rmSync(_oldTriggersTmp, { recursive: true, force: true });
241
+ console.warn("[config] Replaced " + OLD_EXTERNAL_TRIGGERS_DIR + " with symlink → " + EXTERNAL_TRIGGERS_DIR);
242
+ } catch (_se) {
243
+ console.error("[config] Symlink replacement of external-triggers/ failed (non-fatal):", _se.message);
244
+ try {
245
+ if (!fs.existsSync(OLD_EXTERNAL_TRIGGERS_DIR)) {
246
+ fs.renameSync(_oldTriggersTmp, OLD_EXTERNAL_TRIGGERS_DIR);
247
+ }
248
+ } catch (_re) {}
249
+ }
250
+ } catch (e) {
251
+ console.error("[config] Migration merge of external-triggers/ failed (non-fatal):", e.message);
252
+ }
179
253
  }
180
254
  }
181
255
  // daemon.json / daemon-dev.json (lr-eb5a: moved into console/)
@@ -99,7 +99,7 @@ function rescanWorktrees(relay, parentPath, parentSlug, parentIcon, parentOwnerI
99
99
  relay.broadcastAll({
100
100
  type: "projects_updated",
101
101
  projects: relay.getProjects(),
102
- projectCount: config ? config.projects.length : 0,
102
+ projectCount: relay.getProjects().length,
103
103
  });
104
104
  }
105
105
  } finally {
package/lib/daemon.js CHANGED
@@ -25,13 +25,13 @@ var fs = require("fs");
25
25
  var path = require("path");
26
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
- var { createServer, generateAuthToken } = require("./server");
28
+ var { createServer } = 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
33
  var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
34
- var { DEFAULT_MEM_AVAILABLE_MIN_MB } = require("./sdk-bridge");
34
+ var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM } = require("./sdk-bridge");
35
35
  var liteDetect = require("./lite-detect");
36
36
  var { execFile: liteExecFile } = require("child_process");
37
37
 
@@ -86,14 +86,99 @@ console.log("[daemon] Users: " + usersModule.USERS_FILE);
86
86
  if (process.env.SUDO_USER) console.log("[daemon] SUDO_USER: " + process.env.SUDO_USER);
87
87
  console.log("[daemon] UID: " + (typeof process.getuid === "function" ? process.getuid() : "N/A"));
88
88
 
89
+ // Stale-code check: if this process holds deleted inodes, the on-disk JS was
90
+ // replaced by a newer install while we were running. Warn loudly so operators
91
+ // know a restart is needed to load the new code.
92
+ function checkStaleInodes() {
93
+ if (process.platform !== 'linux') return false;
94
+ try {
95
+ var mapsContent = fs.readFileSync('/proc/self/maps', 'utf8');
96
+ return mapsContent.split('\n').some(function(line) {
97
+ return line.includes(' (deleted)');
98
+ });
99
+ } catch (_) {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ if (checkStaleInodes()) {
105
+ console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
106
+ console.warn('[daemon] WARNING: restart the daemon to load the new build:');
107
+ console.warn('[daemon] WARNING: systemctl restart clagentic-console');
108
+ console.warn('[daemon] WARNING: — or — clagentic-console --restart');
109
+ }
110
+
89
111
 
90
- // --- Single-user migration hint ---
91
- if (config.pinHash && !usersModule.isMultiUser()) {
92
- var userData = usersModule.loadUsers();
93
- if (userData.users.length === 0) {
94
- console.log("[daemon] Single-user PIN mode active. Visit Settings → Users to migrate to multi-user mode.");
112
+ // --- Single-user to multi-user migration (lr-ec2d) ---
113
+ function migrateSingleUserToMultiUser(cfg, data) {
114
+ if (data.multiUser) return; // already migrated, no-op
115
+
116
+ var fsMig = require("fs");
117
+ var pathMig = require("path");
118
+ var cryptoMig = require("crypto");
119
+ var usersFilePath = usersModule.USERS_FILE;
120
+
121
+ var hasPin = !!(cfg && cfg.pinHash);
122
+ var hasAdmin = data.users && data.users.some(function (u) { return u.role === "admin"; });
123
+
124
+ data.multiUser = true;
125
+
126
+ // Generate setup code using the users module's exported function
127
+ var setupCode = cryptoMig.randomBytes(4).toString("hex").toUpperCase();
128
+ data.setupCode = setupCode;
129
+
130
+ // Case A: PIN set, no users — create admin stub (PIN cannot be transferred, incompatible hash formats)
131
+ if (hasPin && (!data.users || data.users.length === 0)) {
132
+ var adminId = cryptoMig.randomUUID();
133
+ data.users = [{
134
+ id: adminId,
135
+ username: "admin",
136
+ email: null,
137
+ displayName: "Admin",
138
+ pinHash: null, // PIN cannot be transferred — incompatible hash formats (lr-ec2d spec §7 risk 1)
139
+ role: "admin",
140
+ createdAt: Date.now(),
141
+ mustChangePin: false,
142
+ linuxUser: null,
143
+ profile: {
144
+ name: "Admin",
145
+ lang: "en-US",
146
+ avatarColor: "#7c3aed",
147
+ avatarStyle: "thumbs",
148
+ avatarSeed: cryptoMig.randomBytes(4).toString("hex"),
149
+ },
150
+ }];
95
151
  }
152
+ // Case B: users present but no admin — set setupCode, keep existing users (done above)
153
+ // Case C: no PIN, no users — set setupCode, users stay empty (done above)
154
+
155
+ // Atomic synchronous write
156
+ var tmpFile = usersFilePath + ".tmp." + process.pid;
157
+ fsMig.writeFileSync(tmpFile, JSON.stringify(data, null, 2), { mode: 0o600 });
158
+ fsMig.renameSync(tmpFile, usersFilePath);
159
+
160
+ // Prominent banner
161
+ var port = (cfg && cfg.port) || 3000;
162
+ var url = "http://localhost:" + port + "/auth/setup?setupCode=" + setupCode;
163
+ console.log("");
164
+ console.log("┌─────────────────────────────────────────────────────────────┐");
165
+ console.log("│ Clagentic: Console — one-time upgrade step required │");
166
+ console.log("│ │");
167
+ console.log("│ Your install has been migrated to multi-user mode. │");
168
+ console.log("│ Open this URL to set your admin PIN: │");
169
+ console.log("│ │");
170
+ console.log("│ " + url.padEnd(61) + "│");
171
+ console.log("│ │");
172
+ console.log("│ Setup code also stored in ~/.clagentic/users.json │");
173
+ console.log("│ Your previous PIN cannot be transferred (format change). │");
174
+ console.log("│ Set a new PIN via the setup URL above. │");
175
+ console.log("└─────────────────────────────────────────────────────────────┘");
176
+ console.log("");
96
177
  }
178
+
179
+ var _usersDataForMigration = usersModule.loadUsers();
180
+ migrateSingleUserToMultiUser(config, _usersDataForMigration);
181
+
97
182
  // --- OS users mode: check required system dependencies ---
98
183
  if (config.osUsers) {
99
184
  var checkExec = require("child_process").execFileSync;
@@ -169,7 +254,6 @@ var relay = createServer({
169
254
  tlsOptions: tlsOptions,
170
255
  caPath: caRoot,
171
256
  builtinCert: config.builtinCert || false,
172
- pinHash: config.pinHash || null,
173
257
  port: config.port,
174
258
  debug: config.debug || false,
175
259
  dangerouslySkipPermissions: config.dangerouslySkipPermissions || false,
@@ -921,6 +1005,7 @@ var relay = createServer({
921
1005
  updateChannel: config.updateChannel || "stable",
922
1006
  imageRetentionDays: config.imageRetentionDays !== undefined ? config.imageRetentionDays : 7,
923
1007
  memAvailableMinMB: config.memAvailableMinMB !== undefined ? config.memAvailableMinMB : DEFAULT_MEM_AVAILABLE_MIN_MB,
1008
+ tokensPerMbHeadroom: config.tokensPerMbHeadroom !== undefined ? config.tokensPerMbHeadroom : DEFAULT_TOKENS_PER_MB_HEADROOM,
924
1009
  liteAutoEnroll: !!config.liteAutoEnroll,
925
1010
  };
926
1011
  },
@@ -945,23 +1030,9 @@ var relay = createServer({
945
1030
  console.log("[daemon] Update channel:", config.updateChannel, "(web)");
946
1031
  return { ok: true, updateChannel: config.updateChannel };
947
1032
  },
948
- onSetPin: function (pin) {
949
- if (pin) {
950
- config.pinHash = generateAuthToken(pin);
951
- } else {
952
- config.pinHash = null;
953
- }
954
- relay.setAuthToken(config.pinHash);
955
- saveConfig(config);
956
- console.log("[daemon] PIN", pin ? "set" : "removed", "(web)");
957
- return { ok: true, pinEnabled: !!config.pinHash };
958
- },
959
- onUpgradePin: function (newHash) {
960
- config.pinHash = newHash;
961
- relay.setAuthToken(newHash);
962
- saveConfig(config);
963
- console.log("[daemon] PIN hash auto-upgraded to scrypt");
964
- },
1033
+ // onSetPin intentionally removed — single-user PIN mode no longer exists (lr-ec2d).
1034
+ // Individual user PINs are managed via users.js / server-admin.js.
1035
+ onSetPin: null,
965
1036
  onSetChatLayout: function (layout) {
966
1037
  var val = (layout === "bubble") ? "bubble" : "channel";
967
1038
  config.chatLayout = val;
@@ -998,6 +1069,15 @@ var relay = createServer({
998
1069
  console.log("[daemon] MemAvailable threshold:", val, "MB (web)");
999
1070
  return { ok: true, memAvailableMinMB: val };
1000
1071
  },
1072
+ onSetTokensPerMbHeadroom: function (tpm) {
1073
+ var val = parseInt(tpm, 10);
1074
+ // Valid range: 10–500 tokens/MB; outside that range reset to default.
1075
+ if (isNaN(val) || val < 10 || val > 500) val = DEFAULT_TOKENS_PER_MB_HEADROOM;
1076
+ config.tokensPerMbHeadroom = val;
1077
+ saveConfig(config);
1078
+ console.log("[daemon] Tokens per MB headroom:", val, "(web)");
1079
+ return { ok: true, tokensPerMbHeadroom: val };
1080
+ },
1001
1081
  onGetToolPalettes: function () {
1002
1082
  return config.toolPalettes || {};
1003
1083
  },
@@ -1163,6 +1243,20 @@ var relay = createServer({
1163
1243
  },
1164
1244
  });
1165
1245
 
1246
+ // Periodic stale-code check: re-emit the warning every 60 s so it appears in
1247
+ // journalctl even if the operator wasn't watching at startup time.
1248
+ var staleCheckHandle = setInterval(function () {
1249
+ if (checkStaleInodes()) {
1250
+ console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
1251
+ console.warn('[daemon] WARNING: restart the daemon to load the new build:');
1252
+ console.warn('[daemon] WARNING: systemctl restart clagentic-console');
1253
+ console.warn('[daemon] WARNING: — or — clagentic-console --restart');
1254
+ }
1255
+ }, 60 * 1000);
1256
+ if (staleCheckHandle && typeof staleCheckHandle.unref === "function") {
1257
+ staleCheckHandle.unref();
1258
+ }
1259
+
1166
1260
  var IDLE_MS = Number(process.env.CLAY_CODEX_IDLE_MS) || 5 * 60 * 1000;
1167
1261
  var REAP_MS = Number(process.env.CLAY_CODEX_REAPER_MS) || 60 * 1000;
1168
1262
  var reaperHandle = setInterval(function () {
@@ -1189,6 +1283,10 @@ function stopCodexReaper() {
1189
1283
  clearInterval(reaperHandle);
1190
1284
  reaperHandle = null;
1191
1285
  }
1286
+ if (staleCheckHandle) {
1287
+ clearInterval(staleCheckHandle);
1288
+ staleCheckHandle = null;
1289
+ }
1192
1290
  }
1193
1291
 
1194
1292
  function shutdownProjects() {
@@ -1406,6 +1504,15 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1406
1504
  return { ok: true, memAvailableMinMB: memMB };
1407
1505
  }
1408
1506
 
1507
+ case "set_tokens_per_mb_headroom": {
1508
+ var tpmVal = parseInt(msg.value, 10);
1509
+ if (isNaN(tpmVal) || tpmVal < 10 || tpmVal > 500) tpmVal = DEFAULT_TOKENS_PER_MB_HEADROOM;
1510
+ config.tokensPerMbHeadroom = tpmVal;
1511
+ saveConfig(config);
1512
+ console.log("[daemon] Tokens per MB headroom:", tpmVal, "(cli)");
1513
+ return { ok: true, tokensPerMbHeadroom: tpmVal };
1514
+ }
1515
+
1409
1516
  case "enable_recovery": {
1410
1517
  if (!msg.urlPath || !msg.password) return { ok: false, error: "missing urlPath or password" };
1411
1518
  relay.setRecovery(msg.urlPath, msg.password);
@@ -1642,7 +1749,16 @@ function spawnAndRestart() {
1642
1749
  child.unref();
1643
1750
  fs.closeSync(logFd);
1644
1751
  config.pid = child.pid;
1645
- saveConfig(config);
1752
+ // Write PID synchronously before exit so the config file is not
1753
+ // left with a stale PID during the restart window. saveConfig() is
1754
+ // async (fire-and-forget) and is frequently not flushed before
1755
+ // process.exit(120) fires.
1756
+ try {
1757
+ fs.writeFileSync(restartConfigPath(), JSON.stringify(config, null, 2), { mode: 0o600 });
1758
+ } catch (syncErr) {
1759
+ console.error("[daemon] Sync PID write failed (non-fatal):", syncErr.message);
1760
+ saveConfig(config);
1761
+ }
1646
1762
  console.log("[daemon] Spawned new daemon (PID " + child.pid + "), exiting.");
1647
1763
  process.exit(120);
1648
1764
  } catch (e) {
package/lib/pages.js CHANGED
@@ -1,44 +1,3 @@
1
- function pinPageHtml() {
2
- return '<!DOCTYPE html><html lang="en"><head>' +
3
- '<meta charset="UTF-8">' +
4
- '<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">' +
5
- '<meta name="mobile-web-app-capable" content="yes">' +
6
- '<link rel="icon" type="image/png" href="/favicon-banded.png">' +
7
- '<link rel="apple-touch-icon" href="/apple-touch-icon.png">' +
8
- '<title>Clagentic:Console</title>' +
9
- '<style>' + authPageStyles + '</style></head><body><div class="c">' +
10
- '<h1 id="greeting"></h1>' +
11
- '<div class="sub">Enter your PIN to continue</div>' +
12
- pinBoxesHtml +
13
- '<div class="err" id="err"></div>' +
14
- '<script>' +
15
- '(function(){' +
16
- 'var h=document.getElementById("greeting");' +
17
- 'var visited=localStorage.getItem("clay_visited");' +
18
- 'if(visited){h.textContent="Welcome back"}' +
19
- 'else{h.textContent="Welcome to Clagentic:Console";localStorage.setItem("clay_visited","1")}' +
20
- '})();' +
21
- pinBoxScript +
22
- 'var err=document.getElementById("err");' +
23
- 'function submitPin(){' +
24
- 'var pin=document.getElementById("pin").value;' +
25
- 'var boxes=document.querySelectorAll(".pin-digit");' +
26
- 'fetch("/auth",{method:"POST",headers:{"Content-Type":"application/json"},' +
27
- 'body:JSON.stringify({pin:pin})})' +
28
- '.then(function(r){return r.json()})' +
29
- '.then(function(d){' +
30
- 'if(d.ok){location.reload();return}' +
31
- 'if(d.locked){for(var i=0;i<boxes.length;i++)boxes[i].disabled=true;' +
32
- 'err.textContent="Too many attempts. Try again in "+Math.ceil(d.retryAfter/60)+" min";' +
33
- 'setTimeout(function(){for(var i=0;i<boxes.length;i++)boxes[i].disabled=false;' +
34
- 'err.textContent="";resetPinBoxes()},d.retryAfter*1000);return}' +
35
- 'var msg="Wrong PIN";if(typeof d.attemptsLeft==="number"&&d.attemptsLeft<=3)msg+=" ("+d.attemptsLeft+" left)";' +
36
- 'err.textContent=msg;resetPinBoxes()})' +
37
- '.catch(function(){err.textContent="Connection error"})}' +
38
- 'initPinBoxes("pin-boxes","pin",submitPin);' +
39
- '</script></div></body></html>';
40
- }
41
-
42
1
  function setupPageHtml(httpsUrl, httpUrl, hasCert, lanMode) {
43
2
  return `<!DOCTYPE html><html lang="en"><head>
44
3
  <meta charset="UTF-8">
@@ -1259,4 +1218,4 @@ function noProjectsPageHtml() {
1259
1218
  '</div></body></html>';
1260
1219
  }
1261
1220
 
1262
- module.exports = { pinPageHtml: pinPageHtml, setupPageHtml: setupPageHtml, adminSetupPageHtml: adminSetupPageHtml, multiUserLoginPageHtml: multiUserLoginPageHtml, smtpLoginPageHtml: smtpLoginPageHtml, invitePageHtml: invitePageHtml, smtpInvitePageHtml: smtpInvitePageHtml, noProjectsPageHtml: noProjectsPageHtml };
1221
+ module.exports = { setupPageHtml: setupPageHtml, adminSetupPageHtml: adminSetupPageHtml, multiUserLoginPageHtml: multiUserLoginPageHtml, smtpLoginPageHtml: smtpLoginPageHtml, invitePageHtml: invitePageHtml, smtpInvitePageHtml: smtpInvitePageHtml, noProjectsPageHtml: noProjectsPageHtml };