@clagentic/console 1.0.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 (221) hide show
  1. package/CREDITS.md +3 -0
  2. package/LICENSE +21 -0
  3. package/README.md +250 -0
  4. package/bin/cli.js +2812 -0
  5. package/lib/agents-favorites.js +164 -0
  6. package/lib/agents.js +282 -0
  7. package/lib/ask-user-mcp-server.js +120 -0
  8. package/lib/browser-mcp-server.js +484 -0
  9. package/lib/build-user-env.js +63 -0
  10. package/lib/certs/fullchain.pem +47 -0
  11. package/lib/certs/privkey.pem +5 -0
  12. package/lib/cli-sessions.js +265 -0
  13. package/lib/codex-defaults.js +18 -0
  14. package/lib/config.js +332 -0
  15. package/lib/crisis-safety.js +60 -0
  16. package/lib/daemon-projects.js +164 -0
  17. package/lib/daemon.js +1602 -0
  18. package/lib/dm.js +128 -0
  19. package/lib/ipc.js +125 -0
  20. package/lib/ipv4-only.js +39 -0
  21. package/lib/mcp-local.js +385 -0
  22. package/lib/notes.js +141 -0
  23. package/lib/os-users.js +529 -0
  24. package/lib/pages.js +1325 -0
  25. package/lib/project-connection.js +302 -0
  26. package/lib/project-external-trigger.js +236 -0
  27. package/lib/project-file-watch.js +120 -0
  28. package/lib/project-filesystem.js +528 -0
  29. package/lib/project-http.js +753 -0
  30. package/lib/project-image.js +95 -0
  31. package/lib/project-knowledge.js +88 -0
  32. package/lib/project-loop.js +1304 -0
  33. package/lib/project-mcp.js +374 -0
  34. package/lib/project-memory.js +39 -0
  35. package/lib/project-notifications.js +262 -0
  36. package/lib/project-sessions.js +1581 -0
  37. package/lib/project-user-mention.js +193 -0
  38. package/lib/project-user-message.js +628 -0
  39. package/lib/project.js +1303 -0
  40. package/lib/public/app.js +1031 -0
  41. package/lib/public/apple-touch-icon.png +0 -0
  42. package/lib/public/claude-code-avatar.png +0 -0
  43. package/lib/public/codex-avatar.png +0 -0
  44. package/lib/public/console-icon.png +0 -0
  45. package/lib/public/css/admin.css +736 -0
  46. package/lib/public/css/agent-picker.css +119 -0
  47. package/lib/public/css/base.css +235 -0
  48. package/lib/public/css/channel-layout.css +441 -0
  49. package/lib/public/css/command-palette.css +559 -0
  50. package/lib/public/css/debate.css +1609 -0
  51. package/lib/public/css/diff.css +139 -0
  52. package/lib/public/css/filebrowser.css +1976 -0
  53. package/lib/public/css/highlight.css +144 -0
  54. package/lib/public/css/home-hub.css +545 -0
  55. package/lib/public/css/icon-strip.css +1856 -0
  56. package/lib/public/css/input.css +1349 -0
  57. package/lib/public/css/loop.css +1248 -0
  58. package/lib/public/css/mention.css +317 -0
  59. package/lib/public/css/menus.css +857 -0
  60. package/lib/public/css/messages.css +1833 -0
  61. package/lib/public/css/mobile-nav.css +1332 -0
  62. package/lib/public/css/notifications-center.css +296 -0
  63. package/lib/public/css/overlays.css +1273 -0
  64. package/lib/public/css/playbook.css +264 -0
  65. package/lib/public/css/profile.css +397 -0
  66. package/lib/public/css/rewind.css +671 -0
  67. package/lib/public/css/scheduler-modal.css +1495 -0
  68. package/lib/public/css/scheduler.css +1420 -0
  69. package/lib/public/css/server-settings.css +909 -0
  70. package/lib/public/css/session-search.css +159 -0
  71. package/lib/public/css/sidebar.css +2012 -0
  72. package/lib/public/css/skills.css +789 -0
  73. package/lib/public/css/sticky-notes.css +854 -0
  74. package/lib/public/css/stt.css +155 -0
  75. package/lib/public/css/title-bar.css +674 -0
  76. package/lib/public/css/tooltip.css +67 -0
  77. package/lib/public/css/user-settings.css +702 -0
  78. package/lib/public/emoji-data.json +1 -0
  79. package/lib/public/favicon-banded-32.png +0 -0
  80. package/lib/public/favicon-banded.png +0 -0
  81. package/lib/public/favicon-dark.svg +32 -0
  82. package/lib/public/favicon.svg +32 -0
  83. package/lib/public/icon-192.png +0 -0
  84. package/lib/public/icon-512.png +0 -0
  85. package/lib/public/icon-banded-76.png +0 -0
  86. package/lib/public/icon-banded-96.png +0 -0
  87. package/lib/public/icon-mono.svg +25 -0
  88. package/lib/public/icons/email/gmail.svg +7 -0
  89. package/lib/public/icons/email/outlook.svg +35 -0
  90. package/lib/public/icons/email/yahoo.svg +1 -0
  91. package/lib/public/index.html +1946 -0
  92. package/lib/public/manifest.json +27 -0
  93. package/lib/public/markdown-worker.js +43 -0
  94. package/lib/public/marked.min.js +6 -0
  95. package/lib/public/modules/admin.js +954 -0
  96. package/lib/public/modules/agent-picker.js +429 -0
  97. package/lib/public/modules/app-connection.js +216 -0
  98. package/lib/public/modules/app-cursors.js +492 -0
  99. package/lib/public/modules/app-dm.js +265 -0
  100. package/lib/public/modules/app-favicon.js +231 -0
  101. package/lib/public/modules/app-header.js +242 -0
  102. package/lib/public/modules/app-home-hub.js +432 -0
  103. package/lib/public/modules/app-loop-ui.js +691 -0
  104. package/lib/public/modules/app-loop-wizard.js +439 -0
  105. package/lib/public/modules/app-messages.js +1415 -0
  106. package/lib/public/modules/app-misc.js +463 -0
  107. package/lib/public/modules/app-notifications.js +651 -0
  108. package/lib/public/modules/app-panels.js +1061 -0
  109. package/lib/public/modules/app-projects.js +875 -0
  110. package/lib/public/modules/app-rate-limit.js +529 -0
  111. package/lib/public/modules/app-rendering.js +739 -0
  112. package/lib/public/modules/app-skills-install.js +285 -0
  113. package/lib/public/modules/avatar.js +36 -0
  114. package/lib/public/modules/command-palette.js +491 -0
  115. package/lib/public/modules/console-logo.js +162 -0
  116. package/lib/public/modules/context-sources.js +365 -0
  117. package/lib/public/modules/diff.js +412 -0
  118. package/lib/public/modules/dom-refs.js +21 -0
  119. package/lib/public/modules/emoji-picker.js +222 -0
  120. package/lib/public/modules/events.js +21 -0
  121. package/lib/public/modules/filebrowser.js +1966 -0
  122. package/lib/public/modules/fileicons.js +172 -0
  123. package/lib/public/modules/icons.js +80 -0
  124. package/lib/public/modules/input.js +1102 -0
  125. package/lib/public/modules/longpress.js +74 -0
  126. package/lib/public/modules/markdown.js +486 -0
  127. package/lib/public/modules/mcp-ui.js +295 -0
  128. package/lib/public/modules/mention.js +1093 -0
  129. package/lib/public/modules/notifications.js +613 -0
  130. package/lib/public/modules/playbook.js +578 -0
  131. package/lib/public/modules/profile.js +594 -0
  132. package/lib/public/modules/project-settings.js +849 -0
  133. package/lib/public/modules/project-switcher.js +375 -0
  134. package/lib/public/modules/qrcode.js +87 -0
  135. package/lib/public/modules/rewind.js +381 -0
  136. package/lib/public/modules/scheduler-config.js +1611 -0
  137. package/lib/public/modules/scheduler-history.js +131 -0
  138. package/lib/public/modules/scheduler.js +1689 -0
  139. package/lib/public/modules/server-settings.js +842 -0
  140. package/lib/public/modules/session-search.js +456 -0
  141. package/lib/public/modules/settings-defaults.js +253 -0
  142. package/lib/public/modules/sidebar-mobile.js +1425 -0
  143. package/lib/public/modules/sidebar-projects.js +2022 -0
  144. package/lib/public/modules/sidebar-sessions.js +1548 -0
  145. package/lib/public/modules/sidebar-users.js +449 -0
  146. package/lib/public/modules/sidebar.js +348 -0
  147. package/lib/public/modules/skills.js +793 -0
  148. package/lib/public/modules/state.js +3 -0
  149. package/lib/public/modules/sticky-notes.js +1221 -0
  150. package/lib/public/modules/store.js +34 -0
  151. package/lib/public/modules/stt.js +266 -0
  152. package/lib/public/modules/terminal.js +987 -0
  153. package/lib/public/modules/theme.js +812 -0
  154. package/lib/public/modules/tool-palette.js +562 -0
  155. package/lib/public/modules/tools.js +2285 -0
  156. package/lib/public/modules/tooltip.js +150 -0
  157. package/lib/public/modules/user-settings.js +544 -0
  158. package/lib/public/modules/utils.js +56 -0
  159. package/lib/public/modules/ws-ref.js +26 -0
  160. package/lib/public/style.css +34 -0
  161. package/lib/public/sw.js +159 -0
  162. package/lib/push.js +149 -0
  163. package/lib/scheduler.js +471 -0
  164. package/lib/sdk-bridge.js +1792 -0
  165. package/lib/sdk-message-processor.js +740 -0
  166. package/lib/sdk-message-queue.js +42 -0
  167. package/lib/sdk-skill-discovery.js +131 -0
  168. package/lib/sdk-worker.js +677 -0
  169. package/lib/server-admin.js +712 -0
  170. package/lib/server-auth.js +737 -0
  171. package/lib/server-dm.js +170 -0
  172. package/lib/server-palette.js +104 -0
  173. package/lib/server-settings.js +553 -0
  174. package/lib/server-skills.js +280 -0
  175. package/lib/server.js +1390 -0
  176. package/lib/session-search.js +693 -0
  177. package/lib/sessions.js +946 -0
  178. package/lib/smtp.js +221 -0
  179. package/lib/terminal-manager.js +219 -0
  180. package/lib/terminal.js +39 -0
  181. package/lib/themes/ayu-light.json +9 -0
  182. package/lib/themes/catppuccin-latte.json +9 -0
  183. package/lib/themes/catppuccin-mocha.json +9 -0
  184. package/lib/themes/clagentic-dark.json +10 -0
  185. package/lib/themes/clagentic-light.json +10 -0
  186. package/lib/themes/dracula.json +9 -0
  187. package/lib/themes/everforest-light.json +9 -0
  188. package/lib/themes/everforest.json +9 -0
  189. package/lib/themes/github-light.json +9 -0
  190. package/lib/themes/gruvbox-dark.json +9 -0
  191. package/lib/themes/gruvbox-light.json +9 -0
  192. package/lib/themes/monokai.json +9 -0
  193. package/lib/themes/nord-light.json +9 -0
  194. package/lib/themes/nord.json +9 -0
  195. package/lib/themes/one-dark.json +9 -0
  196. package/lib/themes/one-light.json +9 -0
  197. package/lib/themes/rose-pine-dawn.json +9 -0
  198. package/lib/themes/rose-pine.json +9 -0
  199. package/lib/themes/solarized-dark.json +9 -0
  200. package/lib/themes/solarized-light.json +9 -0
  201. package/lib/themes/tokyo-night-light.json +9 -0
  202. package/lib/themes/tokyo-night.json +9 -0
  203. package/lib/updater.js +124 -0
  204. package/lib/user-presence.js +92 -0
  205. package/lib/users-auth.js +146 -0
  206. package/lib/users-permissions.js +118 -0
  207. package/lib/users-preferences.js +254 -0
  208. package/lib/users.js +465 -0
  209. package/lib/utils.js +64 -0
  210. package/lib/worktree.js +134 -0
  211. package/lib/ws-schema.js +464 -0
  212. package/lib/yoke/adapters/claude-worker.js +759 -0
  213. package/lib/yoke/adapters/claude.js +1599 -0
  214. package/lib/yoke/adapters/codex.js +1559 -0
  215. package/lib/yoke/codex-app-server.js +352 -0
  216. package/lib/yoke/index.js +319 -0
  217. package/lib/yoke/instructions.js +61 -0
  218. package/lib/yoke/interface.js +98 -0
  219. package/lib/yoke/mcp-bridge-server.js +302 -0
  220. package/lib/yoke/package.json +7 -0
  221. package/package.json +72 -0
package/lib/notes.js ADDED
@@ -0,0 +1,141 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+ var crypto = require("crypto");
4
+ var config = require("./config");
5
+ var utils = require("./utils");
6
+
7
+ function createNotesManager(opts) {
8
+ var cwd = opts.cwd;
9
+
10
+ // Storage path: ~/.clay/notes/{encodedCwd}.json
11
+ var notesDir = path.join(config.CONFIG_DIR, "notes");
12
+ var encodedCwd = utils.resolveEncodedFile(notesDir, cwd, ".json");
13
+ var notesFile = path.join(notesDir, encodedCwd + ".json");
14
+
15
+ // In-memory cache
16
+ var notes = loadFromDisk();
17
+
18
+ function generateId() {
19
+ return "n_" + Date.now() + "_" + crypto.randomBytes(3).toString("hex");
20
+ }
21
+
22
+ function loadFromDisk() {
23
+ try {
24
+ var data = fs.readFileSync(notesFile, "utf8");
25
+ var parsed = JSON.parse(data);
26
+ return parsed.notes || [];
27
+ } catch (e) {
28
+ return [];
29
+ }
30
+ }
31
+
32
+ function saveToDisk() {
33
+ try {
34
+ fs.mkdirSync(notesDir, { recursive: true });
35
+ var tmpPath = notesFile + ".tmp";
36
+ fs.writeFileSync(tmpPath, JSON.stringify({ notes: notes }, null, 2));
37
+ fs.renameSync(tmpPath, notesFile);
38
+ } catch (e) {
39
+ console.error("[notes] Failed to save:", e.message);
40
+ }
41
+ }
42
+
43
+ function list() {
44
+ return notes;
45
+ }
46
+
47
+ function create(data) {
48
+ var now = Date.now();
49
+ var note = {
50
+ id: generateId(),
51
+ text: data.text || "",
52
+ x: typeof data.x === "number" ? data.x : 100,
53
+ y: typeof data.y === "number" ? data.y : 100,
54
+ w: typeof data.w === "number" ? data.w : 240,
55
+ h: typeof data.h === "number" ? data.h : 180,
56
+ color: data.color || "yellow",
57
+ minimized: false,
58
+ zIndex: notes.length + 1,
59
+ createdAt: now,
60
+ updatedAt: now,
61
+ };
62
+ notes.push(note);
63
+ saveToDisk();
64
+ return note;
65
+ }
66
+
67
+ function update(id, changes) {
68
+ for (var i = 0; i < notes.length; i++) {
69
+ if (notes[i].id === id) {
70
+ var allowed = ["text", "x", "y", "w", "h", "color", "minimized", "hidden", "zIndex", "opacity"];
71
+ for (var j = 0; j < allowed.length; j++) {
72
+ var key = allowed[j];
73
+ if (changes[key] !== undefined) {
74
+ notes[i][key] = changes[key];
75
+ }
76
+ }
77
+ notes[i].updatedAt = Date.now();
78
+ saveToDisk();
79
+ return notes[i];
80
+ }
81
+ }
82
+ return null;
83
+ }
84
+
85
+ function remove(id) {
86
+ for (var i = 0; i < notes.length; i++) {
87
+ if (notes[i].id === id) {
88
+ notes.splice(i, 1);
89
+ saveToDisk();
90
+ return true;
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+
96
+ function bringToFront(id) {
97
+ var maxZ = 0;
98
+ for (var i = 0; i < notes.length; i++) {
99
+ if (notes[i].zIndex > maxZ) maxZ = notes[i].zIndex;
100
+ }
101
+ // Normalize if z-index grows too large
102
+ if (maxZ > 10000) {
103
+ notes.sort(function (a, b) { return a.zIndex - b.zIndex; });
104
+ for (var k = 0; k < notes.length; k++) {
105
+ notes[k].zIndex = k + 1;
106
+ }
107
+ maxZ = notes.length;
108
+ }
109
+ return update(id, { zIndex: maxZ + 1 });
110
+ }
111
+
112
+ /**
113
+ * Return formatted text of all active (non-hidden) notes.
114
+ * Used to inject into mate CLAUDE.md so the mate can read them.
115
+ */
116
+ function getActiveNotesText() {
117
+ var active = [];
118
+ for (var i = 0; i < notes.length; i++) {
119
+ if (!notes[i].hidden && notes[i].text) active.push(notes[i]);
120
+ }
121
+ if (active.length === 0) return "";
122
+ var lines = [];
123
+ for (var j = 0; j < active.length; j++) {
124
+ var n = active[j];
125
+ var label = n.color ? "[" + n.color + "]" : "";
126
+ lines.push("- " + label + " " + n.text.trim());
127
+ }
128
+ return lines.join("\n");
129
+ }
130
+
131
+ return {
132
+ list: list,
133
+ create: create,
134
+ update: update,
135
+ remove: remove,
136
+ bringToFront: bringToFront,
137
+ getActiveNotesText: getActiveNotesText,
138
+ };
139
+ }
140
+
141
+ module.exports = { createNotesManager: createNotesManager };
@@ -0,0 +1,529 @@
1
+ // os-users.js — Shared utility for resolving Linux OS user information.
2
+ // Used by sdk-bridge.js (worker spawning), terminal-manager.js, and project.js (file ops).
3
+
4
+ var fs = require("fs");
5
+ var path = require("path");
6
+ var execFileSync = require("child_process").execFileSync;
7
+ var _aclGrantCache = Object.create(null);
8
+
9
+ function aclCacheKey(projectPath, linuxUser) {
10
+ return path.resolve(projectPath) + "::" + linuxUser;
11
+ }
12
+
13
+ function isSafeLinuxUsername(username) {
14
+ return typeof username === "string" && /^[a-z_][a-z0-9_-]*[$]?$/.test(username);
15
+ }
16
+
17
+ /**
18
+ * Resolve Linux user info from username via getent passwd.
19
+ * Returns { uid, gid, home, user, shell } or throws on failure.
20
+ */
21
+ function resolveOsUserInfo(username) {
22
+ if (!isSafeLinuxUsername(username)) throw new Error("Invalid Linux username");
23
+ var output = execFileSync("getent", ["passwd", username], { encoding: "utf8", timeout: 5000, stdio: "pipe" }).trim();
24
+ // getent passwd format: username:x:uid:gid:gecos:home:shell
25
+ var parts = output.split(":");
26
+ if (parts.length < 7) throw new Error("Unexpected getent output for user " + username);
27
+ return {
28
+ uid: parseInt(parts[2], 10),
29
+ gid: parseInt(parts[3], 10),
30
+ home: parts[5],
31
+ user: parts[0],
32
+ shell: parts[6] || "/bin/bash",
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Run a file system operation as a specific OS user via a helper subprocess.
38
+ * op: "list", "read", "write", "stat"
39
+ * args: operation-specific arguments
40
+ * osUserInfo: { uid, gid } from resolveOsUserInfo
41
+ * Returns the result object or throws.
42
+ */
43
+ function fsAsUser(op, args, osUserInfo) {
44
+ // Build a small inline Node script to run as the target user
45
+ var script;
46
+ if (op === "list") {
47
+ script = [
48
+ "var fs = require('fs');",
49
+ "var p = require('path');",
50
+ "var dir = " + JSON.stringify(args.dir) + ";",
51
+ "var entries = fs.readdirSync(dir, { withFileTypes: true });",
52
+ "var result = [];",
53
+ "for (var i = 0; i < entries.length; i++) {",
54
+ " var e = entries[i];",
55
+ " var stat;",
56
+ " try { stat = fs.statSync(p.join(dir, e.name)); } catch(err) { continue; }",
57
+ " result.push({ name: e.name, isDir: e.isDirectory(), size: stat.size, mtime: stat.mtimeMs });",
58
+ "}",
59
+ "process.stdout.write(JSON.stringify(result));",
60
+ ].join(" ");
61
+ } else if (op === "read") {
62
+ script = [
63
+ "var fs = require('fs');",
64
+ "var f = " + JSON.stringify(args.file) + ";",
65
+ "var stat = fs.statSync(f);",
66
+ "var result = { size: stat.size };",
67
+ "if (" + JSON.stringify(!!args.readContent) + ") {",
68
+ " result.content = fs.readFileSync(f, 'utf8');",
69
+ "}",
70
+ "process.stdout.write(JSON.stringify(result));",
71
+ ].join(" ");
72
+ } else if (op === "stat") {
73
+ script = [
74
+ "var fs = require('fs');",
75
+ "var f = " + JSON.stringify(args.file) + ";",
76
+ "var stat = fs.statSync(f);",
77
+ "process.stdout.write(JSON.stringify({ size: stat.size, isDir: stat.isDirectory(), mtime: stat.mtimeMs }));",
78
+ ].join(" ");
79
+ } else if (op === "read_binary") {
80
+ // Read file as base64 for binary content (images, etc.)
81
+ script = [
82
+ "var fs = require('fs');",
83
+ "var f = " + JSON.stringify(args.file) + ";",
84
+ "var buf = fs.readFileSync(f);",
85
+ "process.stdout.write(buf.toString('base64'));",
86
+ ].join(" ");
87
+ var binOutput = execFileSync(process.execPath, ["-e", script], {
88
+ encoding: "utf8",
89
+ timeout: 10000,
90
+ uid: osUserInfo.uid,
91
+ gid: osUserInfo.gid,
92
+ maxBuffer: 50 * 1024 * 1024,
93
+ });
94
+ return { buffer: Buffer.from(binOutput.trim(), "base64") };
95
+ } else if (op === "write") {
96
+ script = [
97
+ "var fs = require('fs');",
98
+ "var f = " + JSON.stringify(args.file) + ";",
99
+ "var content = " + JSON.stringify(args.content || "") + ";",
100
+ "fs.writeFileSync(f, content, 'utf8');",
101
+ "process.stdout.write(JSON.stringify({ ok: true }));",
102
+ ].join(" ");
103
+ } else {
104
+ throw new Error("Unknown fsAsUser operation: " + op);
105
+ }
106
+
107
+ var output = execFileSync(process.execPath, ["-e", script], {
108
+ encoding: "utf8",
109
+ timeout: 10000,
110
+ uid: osUserInfo.uid,
111
+ gid: osUserInfo.gid,
112
+ });
113
+
114
+ return JSON.parse(output.trim());
115
+ }
116
+
117
+ /**
118
+ * Detect the Linux distribution family for package manager guidance.
119
+ * Returns "debian", "rhel", "alpine", "suse", "arch", or "unknown".
120
+ */
121
+ function detectDistroFamily() {
122
+ try {
123
+ var release = fs.readFileSync("/etc/os-release", "utf8");
124
+ var idLike = "";
125
+ var id = "";
126
+ var lines = release.split("\n");
127
+ for (var i = 0; i < lines.length; i++) {
128
+ if (lines[i].indexOf("ID_LIKE=") === 0) idLike = lines[i].substring(8).replace(/"/g, "").toLowerCase();
129
+ if (lines[i].indexOf("ID=") === 0 && lines[i].indexOf("ID_LIKE=") !== 0) id = lines[i].substring(3).replace(/"/g, "").toLowerCase();
130
+ }
131
+ var all = id + " " + idLike;
132
+ if (all.indexOf("debian") !== -1 || all.indexOf("ubuntu") !== -1) return "debian";
133
+ if (all.indexOf("rhel") !== -1 || all.indexOf("centos") !== -1 || all.indexOf("fedora") !== -1 || all.indexOf("amzn") !== -1 || all.indexOf("amazon") !== -1) return "rhel";
134
+ if (all.indexOf("alpine") !== -1) return "alpine";
135
+ if (all.indexOf("suse") !== -1 || all.indexOf("opensuse") !== -1) return "suse";
136
+ if (all.indexOf("arch") !== -1 || all.indexOf("manjaro") !== -1) return "arch";
137
+ return "unknown";
138
+ } catch (e) {
139
+ return "unknown";
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Build a user-friendly install command for the ACL package based on distro.
145
+ */
146
+ function getAclInstallCommand() {
147
+ var distro = detectDistroFamily();
148
+ switch (distro) {
149
+ case "debian": return "sudo apt install -y acl";
150
+ case "rhel": return "sudo yum install -y acl";
151
+ case "alpine": return "sudo apk add acl";
152
+ case "suse": return "sudo zypper install -y acl";
153
+ case "arch": return "sudo pacman -S --noconfirm acl";
154
+ default: return "Install the 'acl' package using your distribution's package manager (apt, yum, apk, etc.)";
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Check if setfacl is available on the system.
160
+ * Returns { available: true } or { available: false, installCmd: "..." }.
161
+ */
162
+ function checkAclSupport() {
163
+ try {
164
+ execFileSync("which", ["setfacl"], { encoding: "utf8", timeout: 5000, stdio: "pipe" });
165
+ return { available: true };
166
+ } catch (e) {
167
+ return { available: false, installCmd: getAclInstallCommand() };
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Check if a path is a user's home directory (e.g. /home/chad, /root).
173
+ * Running recursive setfacl on a home dir is dangerous and slow.
174
+ */
175
+ function isHomeDirectory(dirPath) {
176
+ var resolved = path.resolve(dirPath);
177
+ // /root
178
+ if (resolved === "/root") return true;
179
+ // /home/username (exactly two levels)
180
+ var parts = resolved.split("/");
181
+ if (parts.length === 3 && parts[0] === "" && parts[1] === "home" && parts[2]) return true;
182
+ return false;
183
+ }
184
+
185
+ /**
186
+ * Grant a Linux user ACL access (rwX) to a project directory.
187
+ * Uses setfacl to add recursive + default ACL entries.
188
+ * Skips home directories to avoid slow recursive ACL on large trees.
189
+ */
190
+ function grantProjectAccess(projectPath, linuxUser) {
191
+ if (isHomeDirectory(projectPath)) {
192
+ console.log("[os-users] Skipping ACL for home directory: " + projectPath);
193
+ return;
194
+ }
195
+ if (!isSafeLinuxUsername(linuxUser)) {
196
+ console.error("[os-users] Invalid Linux username for ACL grant: " + linuxUser);
197
+ return;
198
+ }
199
+ var cacheKey = aclCacheKey(projectPath, linuxUser);
200
+ if (_aclGrantCache[cacheKey]) {
201
+ return;
202
+ }
203
+ try {
204
+ // Recursive ACL for existing files
205
+ execFileSync("setfacl", ["-R", "-m", "u:" + linuxUser + ":rwX", projectPath], {
206
+ encoding: "utf8",
207
+ timeout: 30000,
208
+ stdio: "pipe",
209
+ });
210
+ // Default ACL so new files also inherit access
211
+ execFileSync("setfacl", ["-R", "-d", "-m", "u:" + linuxUser + ":rwX", projectPath], {
212
+ encoding: "utf8",
213
+ timeout: 30000,
214
+ stdio: "pipe",
215
+ });
216
+ _aclGrantCache[cacheKey] = true;
217
+ console.log("[os-users] Granted ACL access for " + linuxUser + " on " + projectPath);
218
+ } catch (e) {
219
+ delete _aclGrantCache[cacheKey];
220
+ var errMsg = (e.stderr || e.message || "").toString();
221
+ if (errMsg.indexOf("not found") !== -1 || errMsg.indexOf("ENOENT") !== -1) {
222
+ var cmd = getAclInstallCommand();
223
+ console.error("[os-users] setfacl is not installed. ACL support is required for OS user isolation.");
224
+ console.error("[os-users] Install it with: " + cmd);
225
+ } else {
226
+ console.error("[os-users] Failed to grant ACL access for " + linuxUser + " on " + projectPath + ": " + errMsg);
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Revoke a Linux user's ACL access from a project directory.
233
+ */
234
+ function revokeProjectAccess(projectPath, linuxUser) {
235
+ if (isHomeDirectory(projectPath)) {
236
+ console.log("[os-users] Skipping ACL revoke for home directory: " + projectPath);
237
+ return;
238
+ }
239
+ if (!isSafeLinuxUsername(linuxUser)) {
240
+ console.error("[os-users] Invalid Linux username for ACL revoke: " + linuxUser);
241
+ return;
242
+ }
243
+ var cacheKey = aclCacheKey(projectPath, linuxUser);
244
+ try {
245
+ execFileSync("setfacl", ["-R", "-x", "u:" + linuxUser, projectPath], {
246
+ encoding: "utf8",
247
+ timeout: 30000,
248
+ stdio: "pipe",
249
+ });
250
+ execFileSync("setfacl", ["-R", "-d", "-x", "u:" + linuxUser, projectPath], {
251
+ encoding: "utf8",
252
+ timeout: 30000,
253
+ stdio: "pipe",
254
+ });
255
+ delete _aclGrantCache[cacheKey];
256
+ console.log("[os-users] Revoked ACL access for " + linuxUser + " on " + projectPath);
257
+ } catch (e) {
258
+ var errMsg = (e.stderr || e.message || "").toString();
259
+ if (errMsg.indexOf("not found") !== -1 || errMsg.indexOf("ENOENT") !== -1) {
260
+ var cmd = getAclInstallCommand();
261
+ console.error("[os-users] setfacl is not installed. ACL support is required for OS user isolation.");
262
+ console.error("[os-users] Install it with: " + cmd);
263
+ } else {
264
+ console.error("[os-users] Failed to revoke ACL access for " + linuxUser + " on " + projectPath + ": " + errMsg);
265
+ }
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Sanitize a Clay username into a valid Linux username.
271
+ * Prefixes with "clay-", lowercases, replaces invalid chars with hyphens.
272
+ * Linux usernames: start with [a-z_], then [a-z0-9_-], max 32 chars.
273
+ */
274
+ function toLinuxUsername(clayUsername) {
275
+ var sanitized = clayUsername.toLowerCase().replace(/[^a-z0-9_-]/g, "-");
276
+ // Remove leading hyphens/digits after prefix
277
+ sanitized = sanitized.replace(/^[-0-9]+/, "");
278
+ if (!sanitized) sanitized = "user";
279
+ var name = "clay-" + sanitized;
280
+ // Truncate to 32 chars (Linux limit)
281
+ if (name.length > 32) name = name.substring(0, 32);
282
+ // Remove trailing hyphens
283
+ name = name.replace(/-+$/, "");
284
+ return name;
285
+ }
286
+
287
+ /**
288
+ * Ensure linger is enabled for a Linux user so systemd creates /run/user/<uid>.
289
+ * Required for CLI tools like gcloud and gh that need XDG_RUNTIME_DIR.
290
+ */
291
+ function ensureLinger(username) {
292
+ try {
293
+ if (!isSafeLinuxUsername(username)) throw new Error("Invalid Linux username");
294
+ var uid = execFileSync("id", ["-u", username], { encoding: "utf8", timeout: 5000, stdio: "pipe" }).trim();
295
+ var lingerFile = "/var/lib/systemd/linger/" + username;
296
+ if (fs.existsSync(lingerFile)) return;
297
+ execFileSync("loginctl", ["enable-linger", username], {
298
+ encoding: "utf8",
299
+ timeout: 10000,
300
+ stdio: "pipe",
301
+ });
302
+ console.log("[os-users] Enabled linger for " + username + " (uid " + uid + ")");
303
+ } catch (e) {
304
+ console.warn("[os-users] Failed to enable linger for " + username + ": " + (e.stderr || e.message || "").trim());
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Check if a Linux user already exists.
310
+ */
311
+ function linuxUserExists(username) {
312
+ try {
313
+ if (!isSafeLinuxUsername(username)) return false;
314
+ execFileSync("id", [username], { encoding: "utf8", timeout: 5000, stdio: "pipe" });
315
+ return true;
316
+ } catch (e) {
317
+ return false;
318
+ }
319
+ }
320
+
321
+ function getLinuxUserHome(username) {
322
+ try {
323
+ if (!isSafeLinuxUsername(username)) return "/home/" + (username || "");
324
+ var line = execFileSync("getent", ["passwd", username], { encoding: "utf8", timeout: 5000, stdio: "pipe" }).trim();
325
+ var parts = line.split(":");
326
+ return parts[5] || "/home/" + username;
327
+ } catch (e) {
328
+ return "/home/" + username;
329
+ }
330
+ }
331
+
332
+ function getLinuxUserUid(username) {
333
+ try {
334
+ if (!isSafeLinuxUsername(username)) return null;
335
+ var uid = execFileSync("id", ["-u", username], { encoding: "utf8", timeout: 5000, stdio: "pipe" }).trim();
336
+ return parseInt(uid, 10);
337
+ } catch (e) {
338
+ return null;
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Install Claude CLI for a Linux user account.
344
+ * Downloads and runs the install script, then ensures PATH is configured.
345
+ * Non-fatal: logs errors but does not throw.
346
+ */
347
+ function installClaudeCli(linuxName) {
348
+ try {
349
+ if (!isSafeLinuxUsername(linuxName)) throw new Error("Invalid Linux username");
350
+ // Download and run the Claude CLI install script as the target user
351
+ execFileSync("su", ["-", linuxName, "-c", "curl -fsSL https://claude.ai/install.sh | bash"], {
352
+ encoding: "utf8",
353
+ timeout: 60000,
354
+ stdio: "pipe",
355
+ });
356
+ console.log("[os-users] Claude CLI installed for " + linuxName);
357
+ } catch (e) {
358
+ var msg = (e.stderr || e.message || "").trim();
359
+ console.error("[os-users] Failed to install Claude CLI for " + linuxName + ": " + msg);
360
+ return;
361
+ }
362
+
363
+ // Append PATH export to the user's shell config if not already present
364
+ try {
365
+ var userInfo = resolveOsUserInfo(linuxName);
366
+ var home = userInfo.home || ("/home/" + linuxName);
367
+ var rcPath = fs.existsSync(path.join(home, ".zshrc")) ? path.join(home, ".zshrc") : path.join(home, ".bashrc");
368
+ var exportLine = 'export PATH="$HOME/.local/bin:$PATH"';
369
+ var existing = "";
370
+ try { existing = fs.readFileSync(rcPath, "utf8"); } catch (e2) {}
371
+ if (existing.indexOf(exportLine) === -1) {
372
+ var prefix = existing && !/\n$/.test(existing) ? "\n" : "";
373
+ fs.appendFileSync(rcPath, prefix + exportLine + "\n", "utf8");
374
+ try { fs.chownSync(rcPath, userInfo.uid, userInfo.gid); } catch (e3) {}
375
+ console.log("[os-users] PATH export appended to " + rcPath + " for " + linuxName);
376
+ } else {
377
+ console.log("[os-users] PATH already configured in " + rcPath + " for " + linuxName);
378
+ }
379
+ } catch (e) {
380
+ var rcMsg = (e.stderr || e.message || "").trim();
381
+ console.error("[os-users] Failed to configure PATH for " + linuxName + ": " + rcMsg);
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Provision a Linux user account for a Clay user.
387
+ * Creates the account via useradd with a home directory.
388
+ * Returns { ok: true, linuxUser: "clay-xxx" } or { error: "..." }.
389
+ */
390
+ function provisionLinuxUser(clayUsername) {
391
+ var linuxName = toLinuxUsername(clayUsername);
392
+
393
+ // Handle name collisions by appending a number
394
+ if (linuxUserExists(linuxName)) {
395
+ // Check if this is a clay-managed user (reuse it)
396
+ // Otherwise find an available name
397
+ console.log("[os-users] Linux user " + linuxName + " already exists, reusing.");
398
+ return { ok: true, linuxUser: linuxName };
399
+ }
400
+
401
+ try {
402
+ execFileSync("useradd", ["-m", "-s", "/bin/bash", linuxName], {
403
+ encoding: "utf8",
404
+ timeout: 15000,
405
+ stdio: "pipe",
406
+ });
407
+ ensureLinger(linuxName);
408
+ console.log("[os-users] Provisioned Linux user: " + linuxName + " (Clay user: " + clayUsername + ")");
409
+ installClaudeCli(linuxName);
410
+ return { ok: true, linuxUser: linuxName };
411
+ } catch (e) {
412
+ var msg = (e.stderr || e.message || "").trim();
413
+ console.error("[os-users] Failed to provision Linux user " + linuxName + ": " + msg);
414
+ return { error: "Failed to create Linux user " + linuxName + ": " + msg };
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Provision Linux accounts for all Clay users that don't have one yet.
420
+ * usersModule: the users.js module (getAllUsers, updateLinuxUser, etc.)
421
+ * Returns { provisioned: [...], skipped: [...], errors: [...] }.
422
+ */
423
+ function provisionAllUsers(usersModule) {
424
+ var users = usersModule.getAllUsers();
425
+ var result = { provisioned: [], skipped: [], errors: [] };
426
+
427
+ for (var i = 0; i < users.length; i++) {
428
+ var user = users[i];
429
+ if (user.linuxUser) {
430
+ // Already mapped, verify the Linux user still exists
431
+ if (linuxUserExists(user.linuxUser)) {
432
+ // Ensure Claude CLI is installed for existing users
433
+ var cliPath = "/home/" + user.linuxUser + "/.local/bin/claude";
434
+ if (!fs.existsSync(cliPath)) {
435
+ console.log("[os-users] Claude CLI missing for " + user.linuxUser + ", installing...");
436
+ installClaudeCli(user.linuxUser);
437
+ }
438
+ // Ensure linger is enabled for existing users
439
+ ensureLinger(user.linuxUser);
440
+ result.skipped.push({ id: user.id, username: user.username, linuxUser: user.linuxUser });
441
+ continue;
442
+ }
443
+ // Linux user was deleted externally, re-provision
444
+ console.log("[os-users] Linux user " + user.linuxUser + " no longer exists, re-provisioning for " + user.username);
445
+ }
446
+
447
+ var provision = provisionLinuxUser(user.username);
448
+ if (provision.ok) {
449
+ // Update the Clay user record with the Linux username
450
+ var data = usersModule.loadUsers();
451
+ for (var j = 0; j < data.users.length; j++) {
452
+ if (data.users[j].id === user.id) {
453
+ data.users[j].linuxUser = provision.linuxUser;
454
+ usersModule.saveUsers(data);
455
+ break;
456
+ }
457
+ }
458
+ result.provisioned.push({ id: user.id, username: user.username, linuxUser: provision.linuxUser });
459
+ } else {
460
+ result.errors.push({ id: user.id, username: user.username, error: provision.error });
461
+ }
462
+ }
463
+
464
+ return result;
465
+ }
466
+
467
+ /**
468
+ * Grant ACL access on a project directory to ALL Clay users with linuxUser mappings.
469
+ * Used when a project becomes public.
470
+ * usersModule: the users.js module (getAllUsers, etc.)
471
+ */
472
+ function grantAllUsersAccess(projectPath, usersModule) {
473
+ var allUsers = usersModule.getAllUsers();
474
+ for (var i = 0; i < allUsers.length; i++) {
475
+ if (allUsers[i].linuxUser) {
476
+ grantProjectAccess(projectPath, allUsers[i].linuxUser);
477
+ }
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Deactivate (lock) a Linux user account.
483
+ * The account and home directory are preserved, but login is disabled.
484
+ */
485
+ function deactivateLinuxUser(linuxUsername) {
486
+ try {
487
+ if (!isSafeLinuxUsername(linuxUsername)) throw new Error("Invalid Linux username");
488
+ execFileSync("usermod", ["-L", linuxUsername], { encoding: "utf8", timeout: 5000, stdio: "pipe" });
489
+ console.log("[os-users] Deactivated Linux user: " + linuxUsername);
490
+ return { ok: true };
491
+ } catch (e) {
492
+ var msg = (e.stderr || e.message || "").trim();
493
+ console.error("[os-users] Failed to deactivate Linux user " + linuxUsername + ": " + msg);
494
+ return { error: "Failed to deactivate Linux user " + linuxUsername + ": " + msg };
495
+ }
496
+ }
497
+
498
+ /**
499
+ * Ensure the shared projects directory exists.
500
+ */
501
+ function ensureProjectsDir() {
502
+ var dir = "/var/clagentic/projects";
503
+ if (!fs.existsSync(dir)) {
504
+ fs.mkdirSync(dir, { recursive: true, mode: 0o711 });
505
+ } else {
506
+ // Tighten permissions if directory already exists (prevent listing by other users)
507
+ try { fs.chmodSync(dir, 0o711); } catch (e) {}
508
+ }
509
+ }
510
+
511
+ module.exports = {
512
+ checkAclSupport: checkAclSupport,
513
+ resolveOsUserInfo: resolveOsUserInfo,
514
+ fsAsUser: fsAsUser,
515
+ grantProjectAccess: grantProjectAccess,
516
+ revokeProjectAccess: revokeProjectAccess,
517
+ toLinuxUsername: toLinuxUsername,
518
+ linuxUserExists: linuxUserExists,
519
+ provisionLinuxUser: provisionLinuxUser,
520
+ provisionAllUsers: provisionAllUsers,
521
+ grantAllUsersAccess: grantAllUsersAccess,
522
+ installClaudeCli: installClaudeCli,
523
+ deactivateLinuxUser: deactivateLinuxUser,
524
+ ensureProjectsDir: ensureProjectsDir,
525
+ isHomeDirectory: isHomeDirectory,
526
+ getLinuxUserHome: getLinuxUserHome,
527
+ getLinuxUserUid: getLinuxUserUid,
528
+ isSafeLinuxUsername: isSafeLinuxUsername,
529
+ };