@clagentic/console 1.7.1-beta.1 → 1.8.0-beta.2

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 (46) hide show
  1. package/bin/cli.js +199 -2545
  2. package/lib/build-sha.json +2 -2
  3. package/lib/cli/daemon-launch.js +797 -0
  4. package/lib/cli/ipc-subcommands.js +186 -0
  5. package/lib/cli/menus.js +847 -0
  6. package/lib/cli/net-detect.js +209 -0
  7. package/lib/cli/tui.js +589 -0
  8. package/lib/pages.js +13 -17
  9. package/lib/project-loop.js +10 -2
  10. package/lib/project.js +6 -0
  11. package/lib/public/css/base.css +14 -1
  12. package/lib/public/css/diagnostics.css +15 -0
  13. package/lib/public/css/home-hub.css +32 -15
  14. package/lib/public/css/overlays.css +19 -0
  15. package/lib/public/index.html +12 -11
  16. package/lib/public/manifest.json +1 -1
  17. package/lib/public/modules/app-connection.js +187 -4
  18. package/lib/public/modules/app-history-replay.js +155 -0
  19. package/lib/public/modules/app-home-hub.js +33 -30
  20. package/lib/public/modules/app-messages.js +1245 -1489
  21. package/lib/public/modules/app-notifications.js +4 -4
  22. package/lib/public/modules/command-palette.js +11 -22
  23. package/lib/public/modules/context-sources.js +1 -6
  24. package/lib/public/modules/filebrowser.js +25 -13
  25. package/lib/public/modules/mcp-ui.js +2 -2
  26. package/lib/public/modules/notifications.js +22 -1
  27. package/lib/public/modules/playbook.js +6 -6
  28. package/lib/public/modules/project-settings.js +5 -13
  29. package/lib/public/modules/qrcode.js +2 -2
  30. package/lib/public/modules/relative-time.js +27 -0
  31. package/lib/public/modules/scheduler-history.js +1 -5
  32. package/lib/public/modules/server-settings.js +28 -15
  33. package/lib/public/modules/sidebar-projects.js +1 -1
  34. package/lib/public/modules/sidebar-sessions.js +1 -15
  35. package/lib/public/modules/sidebar.js +3 -3
  36. package/lib/public/modules/utils.js +6 -1
  37. package/lib/public/sw.js +24 -4
  38. package/lib/server-auth.js +48 -2
  39. package/lib/server-settings.js +70 -4
  40. package/lib/server.js +269 -15
  41. package/lib/sessions.js +9 -2
  42. package/lib/smtp.js +6 -6
  43. package/lib/users.js +19 -10
  44. package/lib/worktree.js +73 -1
  45. package/lib/yoke/adapters/codex.js +1 -1
  46. package/package.json +1 -1
@@ -0,0 +1,797 @@
1
+ // lib/cli/daemon-launch.js
2
+ //
3
+ // Daemon lifecycle for bin/cli.js: forking the daemon (fresh start + dev
4
+ // mode), restarting it (plain restart-from-config and restart-with-TLS), the
5
+ // daemon-liveness watcher, and crash-recovery/backoff. Extracted verbatim
6
+ // from bin/cli.js (lr-4e49 Part 1), no behavior change.
7
+ //
8
+ // This module and lib/cli/menus.js reference each other's exports (showing
9
+ // the main menu after a successful (re)start, and re-entering setup/fork from
10
+ // menu actions). Both requires are done lazily inside functions to avoid a
11
+ // load-time circular-require ordering issue; by the time either function
12
+ // actually runs, both modules have finished initializing.
13
+
14
+ var fs = require("fs");
15
+ var path = require("path");
16
+ var net = require("net");
17
+ var spawn = require("child_process").spawn;
18
+
19
+ var {
20
+ loadConfig, saveConfig, configPath, socketPath, logPath, ensureConfigDir,
21
+ isDaemonAliveAsync, checkOldDaemon, generateSlug, clearStaleConfig,
22
+ loadClayrc, readCrashInfo, CONFIG_DIR, CLAGENTIC_HOME,
23
+ } = require("../config");
24
+ var { sendIPCCommand } = require("../ipc");
25
+ var { hasAdmin, getSetupCode, hashPin } = require("../users");
26
+ var { log, sym, a } = require("./tui");
27
+ var { getLocalIP, ensureCerts, isPortFree } = require("./net-detect");
28
+
29
+ // --- Daemon watcher ---
30
+ // Polls daemon socket; if connection fails, the server is down.
31
+ var _daemonWatcher = null;
32
+ // Parsed CLI flags (port, useHttps, forceMkcert, noRestart, debugMode, ...)
33
+ // captured once at CLI startup via setDaemonWatcherOpts(), since bin/cli.js
34
+ // owns arg parsing but several async callbacks in this module (the crash
35
+ // watcher's onDaemonDied(), and lib/cli/menus.js's "re-run setup wizard"
36
+ // re-fork) fire long after parsing and have no other way to see the original
37
+ // flags. getCliOpts() exposes the same bundle read-only for other lib/cli/*
38
+ // modules.
39
+ var _watcherOpts = {};
40
+
41
+ function setDaemonWatcherOpts(opts) {
42
+ _watcherOpts = opts || {};
43
+ }
44
+
45
+ function getCliOpts() {
46
+ return _watcherOpts;
47
+ }
48
+
49
+ function startDaemonWatcher() {
50
+ if (_daemonWatcher) return;
51
+ _daemonWatcher = setInterval(function () {
52
+ var client = net.connect(socketPath());
53
+ var timer = setTimeout(function () {
54
+ client.destroy();
55
+ onDaemonDied(_watcherOpts);
56
+ }, 1500);
57
+ client.on("connect", function () {
58
+ clearTimeout(timer);
59
+ client.destroy();
60
+ });
61
+ client.on("error", function () {
62
+ clearTimeout(timer);
63
+ client.destroy();
64
+ onDaemonDied(_watcherOpts);
65
+ });
66
+ }, 3000);
67
+ }
68
+
69
+ function stopDaemonWatcher() {
70
+ if (_daemonWatcher) {
71
+ clearInterval(_daemonWatcher);
72
+ _daemonWatcher = null;
73
+ }
74
+ }
75
+
76
+ var _restartAttempts = 0;
77
+ var MAX_RESTART_ATTEMPTS = 5;
78
+ var _restartBackoffStart = 0;
79
+
80
+ /**
81
+ * Called when the daemon watcher detects the daemon has died. `opts` carries
82
+ * the CLI flags that shape recovery behavior (noRestart) — passed explicitly
83
+ * rather than read from module-level CLI state, since this module no longer
84
+ * owns arg parsing.
85
+ */
86
+ function onDaemonDied(opts) {
87
+ opts = opts || {};
88
+ stopDaemonWatcher();
89
+ // Clean up stdin in case a prompt is active
90
+ try {
91
+ process.stdin.setRawMode(false);
92
+ process.stdin.pause();
93
+ process.stdin.removeAllListeners("data");
94
+ } catch (e) {}
95
+
96
+ // Check if this was a crash (crash.json exists) vs intentional shutdown
97
+ var crashInfo = readCrashInfo();
98
+ if (!crashInfo) {
99
+ // Intentional shutdown, no restart
100
+ log("");
101
+ log(sym.warn + " " + a.yellow + "Server has been shut down." + a.reset);
102
+ log(a.dim + " Run " + a.reset + "npx @clagentic/console" + a.dim + " to start again." + a.reset);
103
+ log("");
104
+ process.exit(0);
105
+ return;
106
+ }
107
+
108
+ // --no-restart: leave the daemon dead so the developer can inspect crash state
109
+ if (opts.noRestart) {
110
+ log("");
111
+ log(sym.warn + " " + a.yellow + "Server crashed. --no-restart is set — not restarting." + a.reset);
112
+ if (crashInfo.reason) {
113
+ log(a.dim + " " + crashInfo.reason.split("\n")[0] + a.reset);
114
+ }
115
+ log(a.dim + " Check logs: " + a.reset + logPath());
116
+ log("");
117
+ process.exit(1);
118
+ return;
119
+ }
120
+
121
+ // Reset backoff counter if enough time has passed since last restart burst
122
+ var now = Date.now();
123
+ if (_restartBackoffStart && now - _restartBackoffStart > 60000) {
124
+ _restartAttempts = 0;
125
+ }
126
+
127
+ _restartAttempts++;
128
+ if (_restartAttempts > MAX_RESTART_ATTEMPTS) {
129
+ log("");
130
+ log(sym.warn + " " + a.red + "Server crashed too many times (" + MAX_RESTART_ATTEMPTS + " attempts). Giving up." + a.reset);
131
+ if (crashInfo.reason) {
132
+ log(a.dim + " " + crashInfo.reason.split("\n")[0] + a.reset);
133
+ }
134
+ log(a.dim + " Check logs: " + a.reset + logPath());
135
+ log("");
136
+ process.exit(1);
137
+ return;
138
+ }
139
+
140
+ if (_restartAttempts === 1) _restartBackoffStart = now;
141
+
142
+ log("");
143
+ log(sym.warn + " " + a.yellow + "Server crashed. Restarting... (" + _restartAttempts + "/" + MAX_RESTART_ATTEMPTS + ")" + a.reset);
144
+ if (crashInfo.reason) {
145
+ log(a.dim + " " + crashInfo.reason.split("\n")[0] + a.reset);
146
+ }
147
+
148
+ // Re-fork the daemon from saved config
149
+ restartDaemonFromConfig(opts);
150
+ }
151
+
152
+ /**
153
+ * `opts`: { port, debugMode }. port is the CLI's fallback port (used only if
154
+ * no saved config exists yet); debugMode mirrors the --debug flag.
155
+ */
156
+ async function restartDaemonFromConfig(opts) {
157
+ opts = opts || {};
158
+ var lastConfig = loadConfig();
159
+ if (!lastConfig || !lastConfig.projects) {
160
+ log(a.red + " No config found. Cannot restart." + a.reset);
161
+ process.exit(1);
162
+ return;
163
+ }
164
+
165
+ clearStaleConfig();
166
+
167
+ // Wait for port to be released
168
+ var targetPort = lastConfig.port || opts.port;
169
+ var waited = 0;
170
+ while (waited < 3000) {
171
+ var free = await isPortFree(targetPort);
172
+ if (free) break;
173
+ await new Promise(function (resolve) { setTimeout(resolve, 300); });
174
+ waited += 300;
175
+ }
176
+
177
+ // Rebuild config (preserve everything except pid)
178
+ var newConfig = Object.assign({}, lastConfig, {
179
+ pid: null,
180
+ port: targetPort,
181
+ projects: (lastConfig.projects || []).filter(function (p) {
182
+ return fs.existsSync(p.path);
183
+ })
184
+ });
185
+
186
+ ensureConfigDir();
187
+ saveConfig(newConfig);
188
+
189
+ var daemonScript = path.join(__dirname, "..", "..", "lib", "daemon.js");
190
+
191
+ // Debug mode: run in foreground with logs to stdout
192
+ if (opts.debugMode) {
193
+ process.env.CLAGENTIC_CONFIG = configPath();
194
+ process.env.CLAGENTIC_HOME = CLAGENTIC_HOME;
195
+ newConfig.pid = process.pid;
196
+ saveConfig(newConfig);
197
+ require(daemonScript);
198
+ return;
199
+ }
200
+
201
+ var logFile = logPath();
202
+ var logFd = fs.openSync(logFile, "a");
203
+
204
+ var child = spawn(process.execPath, [daemonScript], {
205
+ detached: true,
206
+ windowsHide: true,
207
+ stdio: ["ignore", logFd, logFd],
208
+ env: Object.assign({}, process.env, {
209
+ CLAGENTIC_CONFIG: configPath(),
210
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
211
+ }),
212
+ });
213
+ child.unref();
214
+ fs.closeSync(logFd);
215
+
216
+ newConfig.pid = child.pid;
217
+ saveConfig(newConfig);
218
+
219
+ // Wait and verify (retry up to 5 seconds)
220
+ var alive = false;
221
+ for (var rc = 0; rc < 10; rc++) {
222
+ await new Promise(function (resolve) { setTimeout(resolve, 500); });
223
+ alive = await isDaemonAliveAsync(newConfig);
224
+ if (alive) break;
225
+ }
226
+ if (!alive) {
227
+ log(a.red + " Restart failed. Check logs: " + a.reset + logFile);
228
+ process.exit(1);
229
+ return;
230
+ }
231
+ var ip = getLocalIP();
232
+ log(sym.done + " " + a.green + "Server restarted successfully." + a.reset);
233
+ log("");
234
+ var { showMainMenu } = require("./menus");
235
+ showMainMenu(newConfig, ip);
236
+ }
237
+
238
+ // ==============================
239
+ // Fork the daemon process
240
+ // ==============================
241
+ /**
242
+ * `cliOpts`: { port, useHttps, forceMkcert, debugMode, headlessMode,
243
+ * dangerouslySkipPermissions, osUsersMode, cliPin, cwd } — the subset of
244
+ * parsed CLI flags that shape daemon startup. Passed explicitly since this
245
+ * module no longer owns arg parsing (that stays in bin/cli.js).
246
+ */
247
+ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers, cliOpts) {
248
+ cliOpts = cliOpts || {};
249
+ var port = cliOpts.port;
250
+ var cwd = cliOpts.cwd;
251
+ var cliPin = cliOpts.cliPin;
252
+ var ip = getLocalIP();
253
+ var hasTls = false;
254
+ var mkcertDetected = false;
255
+
256
+ if (cliOpts.useHttps) {
257
+ var certPaths = ensureCerts(ip, CONFIG_DIR, cliOpts.forceMkcert);
258
+ if (certPaths) {
259
+ hasTls = true;
260
+ if (certPaths.mkcertDetected) mkcertDetected = true;
261
+ } else {
262
+ log(sym.warn + " " + a.yellow + "HTTPS unavailable" + a.reset + a.dim + " · mkcert not installed" + a.reset);
263
+ }
264
+ }
265
+
266
+ // Migration shim: detect and shut down a pre-1.5 daemon holding the old socket
267
+ // path. This prevents the port-in-use dead-end on upgrade. (lr-6ed3)
268
+ if (process.platform !== "win32") {
269
+ var oldCheck = await checkOldDaemon();
270
+ if (oldCheck && oldCheck.alive) {
271
+ log(sym.warn + " " + a.yellow + "Pre-1.5 daemon detected at " + oldCheck.sockPath + " — shutting it down..." + a.reset);
272
+ await sendIPCCommand(oldCheck.sockPath, { cmd: "shutdown" });
273
+ // Wait up to 5 s for the port to be released
274
+ var migWaited = 0;
275
+ while (migWaited < 5000) {
276
+ await new Promise(function (resolve) { setTimeout(resolve, 300); });
277
+ migWaited += 300;
278
+ if (await isPortFree(port)) break;
279
+ }
280
+ log(sym.done + " " + a.green + "Pre-1.5 daemon stopped. Continuing startup..." + a.reset);
281
+ } else if (oldCheck && !oldCheck.alive && fs.existsSync(oldCheck.sockPath)) {
282
+ // Stale socket not yet cleaned up by ensureConfigDir (e.g. ensureConfigDir not
283
+ // called yet on this path). Remove it now so nothing trips on it later.
284
+ try { fs.unlinkSync(oldCheck.sockPath); } catch (e) {}
285
+ }
286
+ }
287
+
288
+ // Check port availability
289
+ var portFree = await isPortFree(port);
290
+ if (!portFree) {
291
+ log(a.red + "Port " + port + " is already in use." + a.reset);
292
+ log(a.dim + "Another process is holding this port." + a.reset);
293
+ log(a.dim + "If a pre-1.5 daemon is running, clagentic-console --shutdown will stop it." + a.reset);
294
+ process.exit(1);
295
+ return;
296
+ }
297
+
298
+ var allProjects = [];
299
+ var usedSlugs = [];
300
+
301
+ // Load previous config to preserve per-project settings (visibility, allowedUsers)
302
+ var prevConfig = loadConfig();
303
+ var prevProjectMap = {};
304
+ if (prevConfig && prevConfig.projects) {
305
+ for (var pi = 0; pi < prevConfig.projects.length; pi++) {
306
+ prevProjectMap[prevConfig.projects[pi].path] = prevConfig.projects[pi];
307
+ }
308
+ }
309
+
310
+ // Only include cwd if explicitly requested
311
+ if (addCwd) {
312
+ var slug = generateSlug(cwd, []);
313
+ var cwdEntry = { path: cwd, slug: slug, addedAt: Date.now() };
314
+ // Restore title/icon from .clagentic-rc if available
315
+ var cwdRc = loadClayrc();
316
+ var cwdRecent = cwdRc.recentProjects || [];
317
+ for (var cr = 0; cr < cwdRecent.length; cr++) {
318
+ if (cwdRecent[cr].path === cwd) {
319
+ if (cwdRecent[cr].title) cwdEntry.title = cwdRecent[cr].title;
320
+ if (cwdRecent[cr].icon) cwdEntry.icon = cwdRecent[cr].icon;
321
+ break;
322
+ }
323
+ }
324
+ // Restore project-level settings from previous config
325
+ if (prevProjectMap[cwd]) {
326
+ cwdEntry = Object.assign({}, prevProjectMap[cwd], cwdEntry);
327
+ }
328
+ allProjects.push(cwdEntry);
329
+ usedSlugs.push(slug);
330
+ }
331
+
332
+ // Add restored projects (from ~/.clagentic-rc)
333
+ if (extraProjects && extraProjects.length > 0) {
334
+ for (var ep = 0; ep < extraProjects.length; ep++) {
335
+ var rp = extraProjects[ep];
336
+ if (rp.path === cwd) continue; // skip if same as cwd
337
+ if (!fs.existsSync(rp.path)) continue; // skip missing directories
338
+ var rpSlug = generateSlug(rp.path, usedSlugs);
339
+ usedSlugs.push(rpSlug);
340
+ var rpEntry = { path: rp.path, slug: rpSlug, title: rp.title || undefined, icon: rp.icon || undefined, addedAt: rp.addedAt || Date.now() };
341
+ // Restore project-level settings from previous config
342
+ if (prevProjectMap[rp.path]) {
343
+ rpEntry = Object.assign({}, prevProjectMap[rp.path], rpEntry);
344
+ }
345
+ allProjects.push(rpEntry);
346
+ }
347
+ }
348
+
349
+ var config = Object.assign({}, prevConfig || {}, {
350
+ pid: null,
351
+ port: port,
352
+ host: cliOpts.host,
353
+ pinHash: mode === "multi" && cliPin ? hashPin(cliPin) : (prevConfig && prevConfig.pinHash) || null,
354
+ tls: hasTls,
355
+ mkcertDetected: mkcertDetected,
356
+ debug: cliOpts.debugMode,
357
+ headless: cliOpts.headlessMode,
358
+ keepAwake: keepAwake,
359
+ dangerouslySkipPermissions: cliOpts.dangerouslySkipPermissions,
360
+ osUsers: wantOsUsers || cliOpts.osUsersMode,
361
+ mode: mode || "multi",
362
+ setupCompleted: true,
363
+ projects: allProjects,
364
+ });
365
+
366
+ ensureConfigDir();
367
+ saveConfig(config);
368
+
369
+ // Fork daemon
370
+ var daemonScript = path.join(__dirname, "..", "..", "lib", "daemon.js");
371
+
372
+ // Debug mode: run in foreground with logs to stdout
373
+ if (cliOpts.debugMode) {
374
+ process.env.CLAGENTIC_CONFIG = configPath();
375
+ process.env.CLAGENTIC_HOME = CLAGENTIC_HOME;
376
+ config.pid = process.pid;
377
+ saveConfig(config);
378
+ require(daemonScript);
379
+ return;
380
+ }
381
+
382
+ var logFile = logPath();
383
+ var logFd = fs.openSync(logFile, "a");
384
+
385
+ var child = spawn(process.execPath, [daemonScript], {
386
+ detached: true,
387
+ windowsHide: true,
388
+ stdio: ["ignore", logFd, logFd],
389
+ env: Object.assign({}, process.env, {
390
+ CLAGENTIC_CONFIG: configPath(),
391
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
392
+ }),
393
+ });
394
+ child.unref();
395
+ fs.closeSync(logFd);
396
+
397
+ // Update config with PID
398
+ config.pid = child.pid;
399
+ saveConfig(config);
400
+
401
+ // Wait for daemon to start (retry up to 5 seconds)
402
+ var alive = false;
403
+ for (var attempt = 0; attempt < 10; attempt++) {
404
+ await new Promise(function (resolve) { setTimeout(resolve, 500); });
405
+ alive = await isDaemonAliveAsync(config);
406
+ if (alive) break;
407
+ }
408
+ if (!alive) {
409
+ log(a.red + "Failed to start daemon. Check logs:" + a.reset);
410
+ log(a.dim + logFile + a.reset);
411
+ clearStaleConfig();
412
+ process.exit(1);
413
+ return;
414
+ }
415
+
416
+ // Multi-user mode is always on (single-user mode was removed, lr-ec2d).
417
+ // getSetupCode() auto-generates a code when there's no admin yet.
418
+ var _pendingSetupCode = hasAdmin() ? null : getSetupCode();
419
+
420
+ // Headless mode — print status and exit immediately
421
+ if (cliOpts.headlessMode) {
422
+ var protocol = config.tls ? "https" : "http";
423
+ var url = protocol + "://" + ip + ":" + config.port;
424
+ console.log(" " + sym.done + " Daemon started (PID " + config.pid + ")");
425
+ console.log(" " + sym.done + " " + url);
426
+ if (_pendingSetupCode) {
427
+ console.log("");
428
+ console.log(" " + sym.done + " " + a.green + "Multi-user mode enabled." + a.reset);
429
+ console.log(" " + sym.bar + " Setup code: " + a.bold + _pendingSetupCode + a.reset);
430
+ console.log(" " + sym.bar + " Open Clagentic: Console in your browser and enter this code to create the admin account.");
431
+ }
432
+ console.log(" " + sym.done + " Headless mode — exiting CLI");
433
+ process.exit(0);
434
+ return;
435
+ }
436
+
437
+ // Show success + QR
438
+ var { showServerStarted } = require("./menus");
439
+ showServerStarted(config, ip, _pendingSetupCode);
440
+ }
441
+
442
+ // ==============================
443
+ // Dev mode — foreground daemon with file watching
444
+ // ==============================
445
+ /**
446
+ * `cliOpts`: { port, useHttps, dangerouslySkipPermissions, watchMode,
447
+ * noRestart, cwd }.
448
+ */
449
+ async function devMode(mode, keepAwake, existingPinHash, wantOsUsers, cliOpts) {
450
+ cliOpts = cliOpts || {};
451
+ var port = cliOpts.port;
452
+ var cwd = cliOpts.cwd;
453
+ var ip = getLocalIP();
454
+ var hasTls = false;
455
+ var mkcertDetected = false;
456
+
457
+ if (cliOpts.useHttps) {
458
+ var certPaths = ensureCerts(ip, CONFIG_DIR, cliOpts.forceMkcert);
459
+ if (certPaths) {
460
+ hasTls = true;
461
+ if (certPaths.mkcertDetected) mkcertDetected = true;
462
+ }
463
+ }
464
+
465
+ // Migration shim: detect and shut down a pre-1.5 daemon on the old (dev) socket
466
+ // path before checking port availability — mirrors what forkDaemon() does. (lr-6ed3)
467
+ if (process.platform !== "win32") {
468
+ var devOldCheck = await checkOldDaemon();
469
+ if (devOldCheck && devOldCheck.alive) {
470
+ log(sym.warn + " " + a.yellow + "Pre-1.5 daemon detected at " + devOldCheck.sockPath + " — shutting it down..." + a.reset);
471
+ await sendIPCCommand(devOldCheck.sockPath, { cmd: "shutdown" });
472
+ var devMigWaited = 0;
473
+ while (devMigWaited < 5000) {
474
+ await new Promise(function (resolve) { setTimeout(resolve, 300); });
475
+ devMigWaited += 300;
476
+ if (await isPortFree(port)) break;
477
+ }
478
+ log(sym.done + " " + a.green + "Pre-1.5 daemon stopped. Continuing startup..." + a.reset);
479
+ } else if (devOldCheck && !devOldCheck.alive && fs.existsSync(devOldCheck.sockPath)) {
480
+ try { fs.unlinkSync(devOldCheck.sockPath); } catch (e) {}
481
+ }
482
+ }
483
+
484
+ var portFree = await isPortFree(port);
485
+ if (!portFree) {
486
+ console.log("\x1b[31m[dev] Port " + port + " is already in use.\x1b[0m");
487
+ process.exit(1);
488
+ return;
489
+ }
490
+
491
+ var slug = generateSlug(cwd, []);
492
+ var cwdDevEntry = { path: cwd, slug: slug, addedAt: Date.now() };
493
+
494
+ // Load previous config to preserve per-project settings (visibility, allowedUsers)
495
+ var prevDevConfig = loadConfig();
496
+ var prevDevProjectMap = {};
497
+ if (prevDevConfig && prevDevConfig.projects) {
498
+ for (var pdi = 0; pdi < prevDevConfig.projects.length; pdi++) {
499
+ prevDevProjectMap[prevDevConfig.projects[pdi].path] = prevDevConfig.projects[pdi];
500
+ }
501
+ }
502
+
503
+ // Restore previous projects
504
+ var rc = loadClayrc();
505
+ var restorable = (rc.recentProjects || []).filter(function (p) {
506
+ return p.path !== cwd && fs.existsSync(p.path);
507
+ });
508
+ // Restore title/icon for cwd from .clagentic-rc
509
+ var rcAll = rc.recentProjects || [];
510
+ for (var ci = 0; ci < rcAll.length; ci++) {
511
+ if (rcAll[ci].path === cwd) {
512
+ if (rcAll[ci].title) cwdDevEntry.title = rcAll[ci].title;
513
+ if (rcAll[ci].icon) cwdDevEntry.icon = rcAll[ci].icon;
514
+ break;
515
+ }
516
+ }
517
+ // Restore access settings for cwd from previous config
518
+ if (prevDevProjectMap[cwd]) {
519
+ cwdDevEntry = Object.assign({}, prevDevProjectMap[cwd], cwdDevEntry);
520
+ }
521
+ var allProjects = [cwdDevEntry];
522
+ var usedSlugs = [slug];
523
+ for (var ri = 0; ri < restorable.length; ri++) {
524
+ var rp = restorable[ri];
525
+ var rpSlug = generateSlug(rp.path, usedSlugs);
526
+ usedSlugs.push(rpSlug);
527
+ var rpDevEntry = { path: rp.path, slug: rpSlug, title: rp.title || undefined, icon: rp.icon || undefined, addedAt: rp.addedAt || Date.now() };
528
+ // Restore project-level settings from previous config
529
+ if (prevDevProjectMap[rp.path]) {
530
+ rpDevEntry = Object.assign({}, prevDevProjectMap[rp.path], rpDevEntry);
531
+ }
532
+ allProjects.push(rpDevEntry);
533
+ }
534
+
535
+ var config = Object.assign({}, prevDevConfig || {}, {
536
+ pid: null,
537
+ port: port,
538
+ host: cliOpts.host,
539
+ pinHash: existingPinHash || null,
540
+ tls: hasTls,
541
+ mkcertDetected: mkcertDetected,
542
+ debug: true,
543
+ keepAwake: keepAwake || false,
544
+ dangerouslySkipPermissions: cliOpts.dangerouslySkipPermissions,
545
+ mode: mode || "multi",
546
+ setupCompleted: true,
547
+ projects: allProjects,
548
+ osUsers: wantOsUsers || (prevDevConfig ? (prevDevConfig.osUsers || false) : false),
549
+ });
550
+
551
+ ensureConfigDir();
552
+ saveConfig(config);
553
+
554
+ // Multi-user mode is always on (single-user mode was removed, lr-ec2d).
555
+ // getSetupCode() auto-generates a code when there's no admin yet.
556
+ if (!hasAdmin()) {
557
+ var devSetupCode = getSetupCode();
558
+ if (devSetupCode) {
559
+ console.log("\x1b[38;2;0;183;133m[dev]\x1b[0m Multi-user mode enabled. Setup code: " + devSetupCode);
560
+ }
561
+ }
562
+
563
+ var daemonScript = path.join(__dirname, "..", "..", "lib", "daemon.js");
564
+ var libDir = path.join(__dirname, "..", "..", "lib");
565
+ var child = null;
566
+ var intentionalKill = false;
567
+ var debounceTimer = null;
568
+
569
+ function spawnDaemon() {
570
+ child = spawn(process.execPath, [daemonScript], {
571
+ stdio: ["ignore", "inherit", "inherit"],
572
+ env: Object.assign({}, process.env, {
573
+ CLAGENTIC_CONFIG: configPath(),
574
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
575
+ }),
576
+ });
577
+
578
+ child.on("exit", function (code) {
579
+ child = null;
580
+ if (intentionalKill) {
581
+ intentionalKill = false;
582
+ return;
583
+ }
584
+ // Exit code 120 = update restart — respawn daemon with current dev code
585
+ if (code === 120) {
586
+ console.log("\x1b[38;2;0;183;133m[dev]\x1b[0m Update restart — respawning daemon...");
587
+ console.log("");
588
+ setTimeout(spawnDaemon, 500);
589
+ return;
590
+ }
591
+ // Exit code 78 = fatal config error (e.g. Node version too old) — don't restart
592
+ if (code === 78) {
593
+ console.log("\x1b[31m[dev] Daemon exited with fatal error (code 78). Not restarting.\x1b[0m");
594
+ process.exit(78);
595
+ return;
596
+ }
597
+ // Unexpected exit — auto restart (suppressed when --no-restart is set)
598
+ if (cliOpts.noRestart) {
599
+ console.log("\x1b[33m[dev] Daemon exited (code " + code + "). --no-restart is set — not restarting.\x1b[0m");
600
+ process.exit(code || 1);
601
+ return;
602
+ }
603
+ console.log("\x1b[33m[dev] Daemon exited (code " + code + "), restarting...\x1b[0m");
604
+ setTimeout(spawnDaemon, 500);
605
+ });
606
+ }
607
+
608
+ function restartDaemon() {
609
+ intentionalKill = true;
610
+ if (child) {
611
+ child.kill("SIGTERM");
612
+ // Give it a moment to shut down, then spawn
613
+ setTimeout(spawnDaemon, 300);
614
+ } else {
615
+ intentionalKill = false;
616
+ spawnDaemon();
617
+ }
618
+ }
619
+
620
+ console.log("\x1b[38;2;0;183;133m[dev]\x1b[0m Starting relay on port " + port + "...");
621
+ if (cliOpts.watchMode) {
622
+ console.log("\x1b[38;2;0;183;133m[dev]\x1b[0m Watching lib/ for changes (excluding lib/public/)");
623
+ }
624
+ console.log("");
625
+
626
+ spawnDaemon();
627
+
628
+ // Wait for daemon to be ready, then show CLI menu
629
+ config.pid = child ? child.pid : null;
630
+ saveConfig(config);
631
+
632
+ var daemonReady = false;
633
+ for (var da = 0; da < 10; da++) {
634
+ await new Promise(function (resolve) { setTimeout(resolve, 500); });
635
+ daemonReady = await isDaemonAliveAsync(config);
636
+ if (daemonReady) break;
637
+ }
638
+ if (daemonReady) {
639
+ var { showServerStarted } = require("./menus");
640
+ showServerStarted(config, ip);
641
+ }
642
+
643
+ // Watch lib/ for server-side file changes (only with --watch)
644
+ var watcher = null;
645
+ if (cliOpts.watchMode) {
646
+ watcher = fs.watch(libDir, { recursive: true }, function (eventType, filename) {
647
+ if (!filename) return;
648
+ // Skip client-side files — they're served from disk
649
+ if (filename.startsWith("public" + path.sep) || filename.startsWith("public/")) return;
650
+ // Skip non-JS files
651
+ if (!filename.endsWith(".js")) return;
652
+
653
+ if (debounceTimer) clearTimeout(debounceTimer);
654
+ debounceTimer = setTimeout(function () {
655
+ console.log("\x1b[38;2;0;183;133m[dev]\x1b[0m File changed: lib/" + filename);
656
+ console.log("\x1b[38;2;0;183;133m[dev]\x1b[0m Restarting...");
657
+ console.log("");
658
+ restartDaemon();
659
+ }, 300);
660
+ });
661
+ }
662
+
663
+ // Clean exit on Ctrl+C
664
+ var shuttingDown = false;
665
+ process.on("SIGINT", function () {
666
+ if (shuttingDown) return;
667
+ shuttingDown = true;
668
+ console.log("\n\x1b[38;2;0;183;133m[dev]\x1b[0m Shutting down...");
669
+ if (watcher) watcher.close();
670
+ if (debounceTimer) clearTimeout(debounceTimer);
671
+ intentionalKill = true;
672
+ if (child) {
673
+ child.kill("SIGTERM");
674
+ child.on("exit", function () {
675
+ clearStaleConfig();
676
+ process.exit(0);
677
+ });
678
+ // Force kill after 3s
679
+ setTimeout(function () { process.exit(0); }, 3000);
680
+ } else {
681
+ clearStaleConfig();
682
+ process.exit(0);
683
+ }
684
+ });
685
+ }
686
+
687
+ // ==============================
688
+ // Restart daemon with TLS enabled
689
+ // ==============================
690
+ function restartDaemonWithTLS(config, callback, cliOpts) {
691
+ return _restartDaemonWithTLS(config, callback, cliOpts || {});
692
+ }
693
+
694
+ async function _restartDaemonWithTLS(config, callback, cliOpts) {
695
+ var ip = getLocalIP();
696
+ var certPaths = ensureCerts(ip, CONFIG_DIR, cliOpts.forceMkcert);
697
+ if (!certPaths) {
698
+ callback(config);
699
+ return;
700
+ }
701
+ var mkcertDetected = !!(certPaths && certPaths.mkcertDetected);
702
+
703
+ // Shut down old daemon
704
+ stopDaemonWatcher();
705
+ try {
706
+ await sendIPCCommand(socketPath(), { cmd: "shutdown" });
707
+ } catch (e) {}
708
+
709
+ // Wait for port to be released
710
+ var waited = 0;
711
+ while (waited < 5000) {
712
+ await new Promise(function (resolve) { setTimeout(resolve, 300); });
713
+ waited += 300;
714
+ var free = await isPortFree(config.port);
715
+ if (free) break;
716
+ }
717
+ clearStaleConfig();
718
+
719
+ // Re-fork with TLS (preserve all existing config fields)
720
+ var newConfig = Object.assign({}, config, {
721
+ pid: null,
722
+ tls: true,
723
+ mkcertDetected: mkcertDetected,
724
+ });
725
+
726
+ ensureConfigDir();
727
+ saveConfig(newConfig);
728
+
729
+ var daemonScript = path.join(__dirname, "..", "..", "lib", "daemon.js");
730
+ var logFile = logPath();
731
+ var logFd = fs.openSync(logFile, "a");
732
+
733
+ var child = spawn(process.execPath, [daemonScript], {
734
+ detached: true,
735
+ windowsHide: true,
736
+ stdio: ["ignore", logFd, logFd],
737
+ env: Object.assign({}, process.env, {
738
+ CLAGENTIC_CONFIG: configPath(),
739
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
740
+ }),
741
+ });
742
+ child.unref();
743
+ fs.closeSync(logFd);
744
+
745
+ newConfig.pid = child.pid;
746
+ saveConfig(newConfig);
747
+
748
+ var alive = false;
749
+ for (var ra = 0; ra < 10; ra++) {
750
+ await new Promise(function (resolve) { setTimeout(resolve, 500); });
751
+ alive = await isDaemonAliveAsync(newConfig);
752
+ if (alive) break;
753
+ }
754
+ if (!alive) {
755
+ log(sym.warn + " " + a.yellow + "Failed to restart with HTTPS, falling back to HTTP..." + a.reset);
756
+ // Re-fork without TLS so the server is at least running
757
+ newConfig.tls = false;
758
+ saveConfig(newConfig);
759
+ var logFd2 = fs.openSync(logFile, "a");
760
+ var child2 = spawn(process.execPath, [daemonScript], {
761
+ detached: true,
762
+ windowsHide: true,
763
+ stdio: ["ignore", logFd2, logFd2],
764
+ env: Object.assign({}, process.env, {
765
+ CLAGENTIC_CONFIG: configPath(),
766
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
767
+ }),
768
+ });
769
+ child2.unref();
770
+ fs.closeSync(logFd2);
771
+ newConfig.pid = child2.pid;
772
+ saveConfig(newConfig);
773
+ for (var rb = 0; rb < 10; rb++) {
774
+ await new Promise(function (resolve) { setTimeout(resolve, 500); });
775
+ var retryAlive = await isDaemonAliveAsync(newConfig);
776
+ if (retryAlive) break;
777
+ }
778
+ startDaemonWatcher();
779
+ callback(newConfig);
780
+ return;
781
+ }
782
+
783
+ startDaemonWatcher();
784
+ callback(newConfig);
785
+ }
786
+
787
+ module.exports = {
788
+ startDaemonWatcher: startDaemonWatcher,
789
+ stopDaemonWatcher: stopDaemonWatcher,
790
+ onDaemonDied: onDaemonDied,
791
+ restartDaemonFromConfig: restartDaemonFromConfig,
792
+ forkDaemon: forkDaemon,
793
+ devMode: devMode,
794
+ restartDaemonWithTLS: restartDaemonWithTLS,
795
+ setDaemonWatcherOpts: setDaemonWatcherOpts,
796
+ getCliOpts: getCliOpts,
797
+ };