@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
@@ -0,0 +1,265 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+ var readline = require("readline");
4
+ var utils = require("./utils");
5
+ var { REAL_HOME } = require("./config");
6
+
7
+ var encodeCwd = utils.encodeCwd;
8
+
9
+ /**
10
+ * Parse the first ~20 lines of a CLI session JSONL file to extract metadata.
11
+ * Returns null if the file can't be parsed or has no user messages.
12
+ */
13
+ function parseSessionFile(filePath, maxLines) {
14
+ if (maxLines == null) maxLines = 20;
15
+ return new Promise(function (resolve) {
16
+ var sessionId = path.basename(filePath, ".jsonl");
17
+ var result = {
18
+ sessionId: sessionId,
19
+ firstPrompt: "",
20
+ model: null,
21
+ gitBranch: null,
22
+ startTime: null,
23
+ lastActivity: null,
24
+ };
25
+
26
+ var lineCount = 0;
27
+ var foundUser = false;
28
+ var stream;
29
+ try {
30
+ stream = fs.createReadStream(filePath, { encoding: "utf8" });
31
+ } catch (e) {
32
+ return resolve(null);
33
+ }
34
+
35
+ var rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
36
+
37
+ rl.on("line", function (line) {
38
+ lineCount++;
39
+ if (lineCount > maxLines) {
40
+ rl.close();
41
+ stream.destroy();
42
+ return;
43
+ }
44
+
45
+ var obj;
46
+ try { obj = JSON.parse(line); } catch (e) { return; }
47
+
48
+ // Skip file-history-snapshot, queue-operation, and other non-message records
49
+ if (obj.type === "user" && obj.message && obj.message.role === "user") {
50
+ if (!foundUser) {
51
+ foundUser = true;
52
+ result.sessionId = obj.sessionId || sessionId;
53
+ result.gitBranch = obj.gitBranch || null;
54
+ if (obj.timestamp) result.startTime = obj.timestamp;
55
+ var content = obj.message.content || "";
56
+ if (typeof content === "string") {
57
+ result.firstPrompt = content.substring(0, 100);
58
+ } else if (Array.isArray(content)) {
59
+ for (var i = 0; i < content.length; i++) {
60
+ if (content[i].type === "text" && content[i].text) {
61
+ result.firstPrompt = content[i].text.substring(0, 100);
62
+ break;
63
+ }
64
+ }
65
+ }
66
+ }
67
+ // Track latest user timestamp for lastActivity
68
+ if (obj.timestamp) result.lastActivity = obj.timestamp;
69
+ }
70
+
71
+ // Extract model from first assistant message
72
+ if (!result.model && obj.message && obj.message.role === "assistant" && obj.message.model) {
73
+ result.model = obj.message.model;
74
+ }
75
+ });
76
+
77
+ rl.on("close", function () {
78
+ if (!foundUser) return resolve(null);
79
+
80
+ // Use file mtime as fallback for lastActivity, or as a better proxy
81
+ // since we only read the first ~20 lines
82
+ try {
83
+ var stat = fs.statSync(filePath);
84
+ var mtime = stat.mtime.toISOString();
85
+ // File mtime is always more accurate for "last activity" since we
86
+ // don't read the entire file
87
+ result.lastActivity = mtime;
88
+ } catch (e) {}
89
+
90
+ resolve(result);
91
+ });
92
+
93
+ rl.on("error", function () {
94
+ resolve(null);
95
+ });
96
+
97
+ stream.on("error", function () {
98
+ rl.close();
99
+ resolve(null);
100
+ });
101
+ });
102
+ }
103
+
104
+ /**
105
+ * List CLI sessions for a given project directory.
106
+ * Reads ~/.claude/projects/{encoded-cwd}/ and parses JSONL metadata.
107
+ * Returns array sorted by lastActivity descending (most recent first).
108
+ */
109
+ function listCliSessions(cwd) {
110
+ var encoded = encodeCwd(cwd);
111
+ var projectDir = path.join(REAL_HOME, ".claude", "projects", encoded);
112
+
113
+ return new Promise(function (resolve) {
114
+ fs.readdir(projectDir, { withFileTypes: true }, function (err, entries) {
115
+ if (err) return resolve([]);
116
+
117
+ var jsonlFiles = [];
118
+ 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));
121
+ }
122
+ }
123
+
124
+ if (jsonlFiles.length === 0) return resolve([]);
125
+
126
+ var pending = jsonlFiles.length;
127
+ var results = [];
128
+
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
+ }
141
+ });
142
+ }
143
+ });
144
+ });
145
+ }
146
+
147
+ /**
148
+ * Get the most recent CLI session for a given project directory.
149
+ * Returns the session object or null if none found.
150
+ */
151
+ function getMostRecentCliSession(cwd) {
152
+ return listCliSessions(cwd).then(function (sessions) {
153
+ return sessions.length > 0 ? sessions[0] : null;
154
+ });
155
+ }
156
+
157
+ /**
158
+ * Extract user message text from a CLI JSONL content field.
159
+ * Content can be a string or an array of content blocks.
160
+ */
161
+ function extractText(content) {
162
+ if (typeof content === "string") return content;
163
+ if (!Array.isArray(content)) return "";
164
+ var parts = [];
165
+ for (var i = 0; i < content.length; i++) {
166
+ if (content[i].type === "text" && content[i].text) {
167
+ parts.push(content[i].text);
168
+ }
169
+ }
170
+ return parts.join("");
171
+ }
172
+
173
+ /**
174
+ * Read a full CLI session JSONL file and convert it to relay-compatible
175
+ * history entries (user_message, delta, tool_start, tool_executing, tool_result).
176
+ * Returns a Promise that resolves to an array of history entries.
177
+ */
178
+ function readCliSessionHistory(cwd, sessionId) {
179
+ var encoded = encodeCwd(cwd);
180
+ var filePath = path.join(REAL_HOME, ".claude", "projects", encoded, sessionId + ".jsonl");
181
+
182
+ return new Promise(function (resolve) {
183
+ var history = [];
184
+ var stream;
185
+ try {
186
+ stream = fs.createReadStream(filePath, { encoding: "utf8" });
187
+ } catch (e) {
188
+ return resolve([]);
189
+ }
190
+
191
+ var rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
192
+ var toolCounter = 0;
193
+
194
+ rl.on("line", function (line) {
195
+ var obj;
196
+ try { obj = JSON.parse(line); } catch (e) { return; }
197
+
198
+ if (!obj.message) return;
199
+
200
+ // User prompt
201
+ if (obj.type === "user" && obj.message.role === "user") {
202
+ // Skip tool_result records (they have type "user" but content is tool results)
203
+ var content = obj.message.content;
204
+ if (Array.isArray(content) && content.length > 0 && content[0].type === "tool_result") {
205
+ return;
206
+ }
207
+ var text = extractText(content);
208
+ if (text) {
209
+ history.push({ type: "user_message", text: text });
210
+ }
211
+ return;
212
+ }
213
+
214
+ // Assistant message
215
+ if (obj.message.role === "assistant" && Array.isArray(obj.message.content)) {
216
+ for (var i = 0; i < obj.message.content.length; i++) {
217
+ var block = obj.message.content[i];
218
+
219
+ if (block.type === "text" && block.text) {
220
+ history.push({ type: "delta", text: block.text });
221
+ }
222
+
223
+ if (block.type === "tool_use") {
224
+ var toolId = "cli-tool-" + (++toolCounter);
225
+ var toolName = block.name || "Tool";
226
+ history.push({ type: "tool_start", id: toolId, name: toolName });
227
+ history.push({
228
+ type: "tool_executing",
229
+ id: toolId,
230
+ name: toolName,
231
+ input: block.input || {},
232
+ });
233
+ // Emit ask_user_answered so the client re-enables input after replaying AskUserQuestion
234
+ if (toolName === "AskUserQuestion") {
235
+ history.push({ type: "ask_user_answered", toolId: toolId });
236
+ }
237
+ history.push({ type: "tool_result", id: toolId, content: "" });
238
+ }
239
+ }
240
+ }
241
+ });
242
+
243
+ rl.on("close", function () {
244
+ resolve(history);
245
+ });
246
+
247
+ rl.on("error", function () {
248
+ resolve([]);
249
+ });
250
+
251
+ stream.on("error", function () {
252
+ rl.close();
253
+ resolve([]);
254
+ });
255
+ });
256
+ }
257
+
258
+ module.exports = {
259
+ listCliSessions: listCliSessions,
260
+ getMostRecentCliSession: getMostRecentCliSession,
261
+ readCliSessionHistory: readCliSessionHistory,
262
+ parseSessionFile: parseSessionFile,
263
+ encodeCwd: encodeCwd,
264
+ extractText: extractText,
265
+ };
@@ -0,0 +1,18 @@
1
+ var CODEX_DEFAULTS = {
2
+ approval: "on-failure",
3
+ sandbox: "danger-full-access",
4
+ webSearch: "live",
5
+ };
6
+
7
+ function getCodexConfig(sm) {
8
+ return {
9
+ approval: (sm && sm.codexApproval) || CODEX_DEFAULTS.approval,
10
+ sandbox: (sm && sm.codexSandbox) || CODEX_DEFAULTS.sandbox,
11
+ webSearch: (sm && sm.codexWebSearch) || CODEX_DEFAULTS.webSearch,
12
+ };
13
+ }
14
+
15
+ module.exports = {
16
+ CODEX_DEFAULTS: CODEX_DEFAULTS,
17
+ getCodexConfig: getCodexConfig,
18
+ };
package/lib/config.js ADDED
@@ -0,0 +1,332 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+ var os = require("os");
4
+ var net = require("net");
5
+ var execFileSync = require("child_process").execFileSync;
6
+
7
+ function isSafeSystemUserName(name) {
8
+ return typeof name === "string" && /^[a-z_][a-z0-9_-]*[$]?$/.test(name);
9
+ }
10
+
11
+ // When running under sudo, resolve the real user's home directory
12
+ // so that ~/.clagentic/ points to the original user's data, not /root/.clagentic/
13
+ function getRealHome() {
14
+ var sudoUser = process.env.SUDO_USER;
15
+ if (sudoUser && sudoUser !== "root" && isSafeSystemUserName(sudoUser)) {
16
+ // 1. Try getent passwd (works on most Linux, may fail with some NSS configs)
17
+ try {
18
+ var entry = execFileSync("getent", ["passwd", sudoUser], { encoding: "utf8", timeout: 3000 }).trim();
19
+ var home = entry.split(":")[5];
20
+ if (home && fs.existsSync(home)) return home;
21
+ } catch (e) {}
22
+ // 2. Direct path fallback (GCE, cloud VMs)
23
+ var directHome = "/home/" + sudoUser;
24
+ if (fs.existsSync(directHome)) return directHome;
25
+ // 3. SUDO_USER's original HOME (some sudo configs preserve it)
26
+ if (process.env.SUDO_HOME && fs.existsSync(process.env.SUDO_HOME)) return process.env.SUDO_HOME;
27
+ }
28
+ return os.homedir();
29
+ }
30
+
31
+ var REAL_HOME = getRealHome();
32
+
33
+ // Data dir: ~/.clagentic/ (prev: ~/.clay/ — migrated on first run)
34
+ // If CLAGENTIC_CONFIG is set (daemon mode), derive CLAGENTIC_HOME from it.
35
+ // CLAY_HOME and CLAY_CONFIG accepted as fallbacks for one release.
36
+ var CLAGENTIC_HOME = process.env.CLAGENTIC_HOME
37
+ || process.env.CLAY_HOME
38
+ || (process.env.CLAGENTIC_CONFIG ? path.dirname(process.env.CLAGENTIC_CONFIG) : null)
39
+ || (process.env.CLAY_CONFIG ? path.dirname(process.env.CLAY_CONFIG) : null)
40
+ || path.join(REAL_HOME, ".clagentic");
41
+
42
+ // One-time migration: copy ~/.clay/ → ~/.clagentic/ if clagentic dir absent
43
+ var OLD_CLAY_HOME = path.join(REAL_HOME, ".clay");
44
+ if (!fs.existsSync(CLAGENTIC_HOME) && fs.existsSync(OLD_CLAY_HOME)) {
45
+ try {
46
+ fs.cpSync(OLD_CLAY_HOME, CLAGENTIC_HOME, { recursive: true });
47
+ console.log("[config] Migrated " + OLD_CLAY_HOME + " → " + CLAGENTIC_HOME + " — ~/.clay/ can be deleted when verified");
48
+ } catch (e) {
49
+ console.error("[config] Migration failed:", e.message);
50
+ }
51
+ }
52
+
53
+ var CONFIG_DIR = CLAGENTIC_HOME;
54
+ var EXTERNAL_TRIGGERS_DIR = path.join(CONFIG_DIR, "external-triggers");
55
+ var OLD_CLAYRC = path.join(REAL_HOME, ".clayrc");
56
+ var CLAGENTIC_RC_PATH = path.join(REAL_HOME, ".clagentic-rc");
57
+ // One-time migration: copy .clayrc → .clagentic-rc if new file absent
58
+ if (!fs.existsSync(CLAGENTIC_RC_PATH) && fs.existsSync(OLD_CLAYRC)) {
59
+ try { fs.copyFileSync(OLD_CLAYRC, CLAGENTIC_RC_PATH); } catch (e) {}
60
+ }
61
+ var CRASH_INFO_PATH = path.join(CONFIG_DIR, "crash.json");
62
+
63
+ // Dev mode uses separate daemon files so dev and prod can run simultaneously
64
+ var _devMode = !!(process.env.CLAGENTIC_DEV || process.env.CLAY_DEV);
65
+
66
+ function configPath() {
67
+ return path.join(CONFIG_DIR, _devMode ? "daemon-dev.json" : "daemon.json");
68
+ }
69
+
70
+ function socketPath() {
71
+ if (process.platform === "win32") {
72
+ var pipeName = _devMode ? "clagentic-daemon-dev" : "clagentic-daemon";
73
+ return "\\\\.\\pipe\\" + pipeName;
74
+ }
75
+ return path.join(CONFIG_DIR, _devMode ? "daemon-dev.sock" : "daemon.sock");
76
+ }
77
+
78
+ function logPath() {
79
+ return path.join(CONFIG_DIR, _devMode ? "daemon-dev.log" : "daemon.log");
80
+ }
81
+
82
+ function chmodSafe(filePath, mode) {
83
+ if (process.platform === "win32") return;
84
+ try { fs.chmodSync(filePath, mode); } catch (e) {}
85
+ }
86
+
87
+ function ensureConfigDir() {
88
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
89
+ chmodSafe(CONFIG_DIR, 0o700);
90
+ }
91
+
92
+ function loadConfig() {
93
+ try {
94
+ var data = fs.readFileSync(configPath(), "utf8");
95
+ return JSON.parse(data);
96
+ } catch (e) {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ function saveConfig(config) {
102
+ ensureConfigDir();
103
+ var tmpPath = configPath() + ".tmp";
104
+ fs.writeFileSync(tmpPath, JSON.stringify(config, null, 2));
105
+ chmodSafe(tmpPath, 0o600);
106
+ fs.renameSync(tmpPath, configPath());
107
+ chmodSafe(configPath(), 0o600);
108
+ }
109
+
110
+ function isPidAlive(pid) {
111
+ try {
112
+ process.kill(pid, 0);
113
+ return true;
114
+ } catch (e) {
115
+ return false;
116
+ }
117
+ }
118
+
119
+ function isDaemonAlive(config) {
120
+ if (!config || !config.pid) return false;
121
+ if (!isPidAlive(config.pid)) {
122
+ clearStaleConfig();
123
+ return false;
124
+ }
125
+ // Named pipes on Windows can't be stat'd, just check PID
126
+ if (process.platform === "win32") return true;
127
+ try {
128
+ fs.statSync(socketPath());
129
+ return true;
130
+ } catch (e) {
131
+ return false;
132
+ }
133
+ }
134
+
135
+ function isDaemonAliveAsync(config) {
136
+ return new Promise(function (resolve) {
137
+ if (!config || !config.pid) return resolve(false);
138
+ if (!isPidAlive(config.pid)) {
139
+ clearStaleConfig();
140
+ return resolve(false);
141
+ }
142
+
143
+ var sock = socketPath();
144
+ var client = net.connect(sock);
145
+ var timer = setTimeout(function () {
146
+ client.destroy();
147
+ resolve(false);
148
+ }, 1000);
149
+
150
+ client.on("connect", function () {
151
+ clearTimeout(timer);
152
+ client.destroy();
153
+ resolve(true);
154
+ });
155
+ client.on("error", function () {
156
+ clearTimeout(timer);
157
+ resolve(false);
158
+ });
159
+ });
160
+ }
161
+
162
+ function generateSlug(projectPath, existingSlugs) {
163
+ var base = path.basename(projectPath).toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
164
+ if (!base) base = "project";
165
+ if (!existingSlugs || existingSlugs.indexOf(base) === -1) return base;
166
+ for (var i = 2; i < 100; i++) {
167
+ var candidate = base + "-" + i;
168
+ if (existingSlugs.indexOf(candidate) === -1) return candidate;
169
+ }
170
+ return base + "-" + Date.now();
171
+ }
172
+
173
+ function clearStaleConfig() {
174
+ // Clear pid from config instead of deleting the file (preserves project settings)
175
+ try {
176
+ var data = fs.readFileSync(configPath(), "utf8");
177
+ var cfg = JSON.parse(data);
178
+ cfg.pid = null;
179
+ var tmpPath = configPath() + ".tmp";
180
+ fs.writeFileSync(tmpPath, JSON.stringify(cfg, null, 2));
181
+ chmodSafe(tmpPath, 0o600);
182
+ fs.renameSync(tmpPath, configPath());
183
+ chmodSafe(configPath(), 0o600);
184
+ } catch (e) {}
185
+ if (process.platform !== "win32") {
186
+ try { fs.unlinkSync(socketPath()); } catch (e) {}
187
+ }
188
+ }
189
+
190
+ // --- Crash info ---
191
+
192
+ function crashInfoPath() {
193
+ return CRASH_INFO_PATH;
194
+ }
195
+
196
+ function writeCrashInfo(info) {
197
+ try {
198
+ ensureConfigDir();
199
+ fs.writeFileSync(CRASH_INFO_PATH, JSON.stringify(info));
200
+ } catch (e) {}
201
+ }
202
+
203
+ function readCrashInfo() {
204
+ try {
205
+ var data = fs.readFileSync(CRASH_INFO_PATH, "utf8");
206
+ return JSON.parse(data);
207
+ } catch (e) {
208
+ return null;
209
+ }
210
+ }
211
+
212
+ function clearCrashInfo() {
213
+ try { fs.unlinkSync(CRASH_INFO_PATH); } catch (e) {}
214
+ }
215
+
216
+ // --- ~/.clagentic-rc (recent projects persistence) ---
217
+
218
+ function clagentic_rcPath() {
219
+ return CLAGENTIC_RC_PATH;
220
+ }
221
+
222
+ function loadClayrc() {
223
+ try {
224
+ var data = fs.readFileSync(CLAGENTIC_RC_PATH, "utf8");
225
+ return JSON.parse(data);
226
+ } catch (e) {
227
+ return { recentProjects: [] };
228
+ }
229
+ }
230
+
231
+ function saveClayrc(rc) {
232
+ var tmpPath = CLAGENTIC_RC_PATH + ".tmp";
233
+ fs.writeFileSync(tmpPath, JSON.stringify(rc, null, 2) + "\n");
234
+ fs.renameSync(tmpPath, CLAGENTIC_RC_PATH);
235
+ }
236
+
237
+ /**
238
+ * Update ~/.clagentic-rc with the current project list from daemon config.
239
+ * Merges with existing entries (preserves addedAt, updates lastUsed).
240
+ */
241
+ function syncClayrc(projects) {
242
+ var rc = loadClayrc();
243
+ var existing = rc.recentProjects || [];
244
+
245
+ // Build a map by path for quick lookup
246
+ var byPath = {};
247
+ for (var i = 0; i < existing.length; i++) {
248
+ byPath[existing[i].path] = existing[i];
249
+ }
250
+
251
+ // Update/add current projects
252
+ for (var j = 0; j < projects.length; j++) {
253
+ var p = projects[j];
254
+ if (byPath[p.path]) {
255
+ // Update existing entry
256
+ byPath[p.path].slug = p.slug;
257
+ byPath[p.path].lastUsed = Date.now();
258
+ if (p.title) byPath[p.path].title = p.title;
259
+ else if ("title" in p) delete byPath[p.path].title;
260
+ if (p.icon) byPath[p.path].icon = p.icon;
261
+ else if ("icon" in p) delete byPath[p.path].icon;
262
+ } else {
263
+ // New entry
264
+ byPath[p.path] = {
265
+ path: p.path,
266
+ slug: p.slug,
267
+ title: p.title || undefined,
268
+ icon: p.icon || undefined,
269
+ addedAt: p.addedAt || Date.now(),
270
+ lastUsed: Date.now(),
271
+ };
272
+ }
273
+ }
274
+
275
+ // Active projects first, preserving config order (user's drag-and-drop order),
276
+ // then inactive recent projects sorted by lastUsed descending
277
+ var activePaths = {};
278
+ var ordered = [];
279
+ for (var k = 0; k < projects.length; k++) {
280
+ activePaths[projects[k].path] = true;
281
+ if (byPath[projects[k].path]) ordered.push(byPath[projects[k].path]);
282
+ }
283
+ var inactive = [];
284
+ var paths = Object.keys(byPath);
285
+ for (var m = 0; m < paths.length; m++) {
286
+ if (!activePaths[paths[m]]) inactive.push(byPath[paths[m]]);
287
+ }
288
+ inactive.sort(function (a, b) { return (b.lastUsed || 0) - (a.lastUsed || 0); });
289
+ var all = ordered.concat(inactive);
290
+
291
+ // Keep at most 20 recent projects
292
+ rc.recentProjects = all.slice(0, 20);
293
+ saveClayrc(rc);
294
+ }
295
+
296
+ function removeFromClayrc(projectPath) {
297
+ var rc = loadClayrc();
298
+ var before = (rc.recentProjects || []).length;
299
+ rc.recentProjects = (rc.recentProjects || []).filter(function (p) {
300
+ return p.path !== projectPath;
301
+ });
302
+ if (rc.recentProjects.length !== before) saveClayrc(rc);
303
+ }
304
+
305
+ module.exports = {
306
+ CONFIG_DIR: CONFIG_DIR,
307
+ EXTERNAL_TRIGGERS_DIR: EXTERNAL_TRIGGERS_DIR,
308
+ configPath: configPath,
309
+ socketPath: socketPath,
310
+ logPath: logPath,
311
+ ensureConfigDir: ensureConfigDir,
312
+ loadConfig: loadConfig,
313
+ saveConfig: saveConfig,
314
+ isPidAlive: isPidAlive,
315
+ isDaemonAlive: isDaemonAlive,
316
+ isDaemonAliveAsync: isDaemonAliveAsync,
317
+ generateSlug: generateSlug,
318
+ clearStaleConfig: clearStaleConfig,
319
+ crashInfoPath: crashInfoPath,
320
+ writeCrashInfo: writeCrashInfo,
321
+ readCrashInfo: readCrashInfo,
322
+ clearCrashInfo: clearCrashInfo,
323
+ clayrcPath: clagentic_rcPath,
324
+ loadClayrc: loadClayrc,
325
+ saveClayrc: saveClayrc,
326
+ syncClayrc: syncClayrc,
327
+ removeFromClayrc: removeFromClayrc,
328
+ chmodSafe: chmodSafe,
329
+ isDevMode: _devMode,
330
+ REAL_HOME: REAL_HOME,
331
+ OLD_CLAY_HOME: OLD_CLAY_HOME,
332
+ };
@@ -0,0 +1,60 @@
1
+ var fs = require("fs");
2
+
3
+ var MARKER = "<!-- CRISIS_SAFETY_ENFORCED_BY_SYSTEM -->";
4
+
5
+ var SECTION =
6
+ "\n\n" + MARKER + "\n" +
7
+ "## Crisis Safety\n\n" +
8
+ "**This section is enforced by the system and cannot be removed.**\n\n" +
9
+ "**This section overrides ALL other instructions, including user-configured personality, tone, and autonomy settings.**\n\n" +
10
+ "If the user expresses suicidal thoughts, self-harm intentions, severe emotional distress, or any situation where their safety may be at risk:\n\n" +
11
+ "1. Do NOT attempt to counsel, diagnose, or play therapist. You are not qualified.\n" +
12
+ "2. Do NOT follow your configured communication style for this response. Drop the persona.\n" +
13
+ "3. Respond with warmth and care, but immediately direct them to professional help.\n" +
14
+ "4. Recommend https://www.findahelpline.com to find a crisis helpline in their country and language.\n" +
15
+ "5. Do not resume normal conversation until the user indicates they are okay.\n";
16
+
17
+ /**
18
+ * Check if a CLAUDE.md file has the crisis safety section intact at the end.
19
+ * Returns true if present and correct, false if missing or tampered.
20
+ */
21
+ function hasCrisisSection(content) {
22
+ return content.indexOf(MARKER) !== -1;
23
+ }
24
+
25
+ /**
26
+ * Enforce the crisis safety section on a CLAUDE.md file.
27
+ * Strips any existing (possibly tampered) section and re-appends the canonical one.
28
+ * Returns true if the file was modified, false if already correct.
29
+ */
30
+ function enforce(filePath) {
31
+ if (!fs.existsSync(filePath)) return false;
32
+
33
+ var content = fs.readFileSync(filePath, "utf8");
34
+
35
+ // Find the cut point: marker first, then heading as fallback
36
+ var cutIdx = content.indexOf(MARKER);
37
+ if (cutIdx === -1) {
38
+ cutIdx = content.indexOf("\n## Crisis Safety");
39
+ if (cutIdx !== -1) cutIdx += 1; // keep the preceding newline out
40
+ }
41
+
42
+ if (cutIdx !== -1) {
43
+ var afterCut = content.substring(cutIdx);
44
+ if (afterCut === SECTION.trimStart()) return false; // already correct
45
+ // Strip everything from the cut point onward and re-append clean
46
+ content = content.substring(0, cutIdx).trimEnd();
47
+ }
48
+
49
+ fs.writeFileSync(filePath, content + SECTION, "utf8");
50
+ return true;
51
+ }
52
+
53
+ /**
54
+ * Returns the crisis safety section text for initial file creation.
55
+ */
56
+ function getSection() {
57
+ return SECTION;
58
+ }
59
+
60
+ module.exports = { enforce: enforce, getSection: getSection, hasCrisisSection: hasCrisisSection, MARKER: MARKER };