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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -349,6 +349,7 @@ var a = {
349
349
  green: "\x1b[32m",
350
350
  yellow: "\x1b[33m",
351
351
  red: "\x1b[31m",
352
+ cyan: "\x1b[36m",
352
353
  };
353
354
 
354
355
  function gradient(text) {
package/lib/config.js CHANGED
@@ -170,12 +170,86 @@ function ensureConfigDir() {
170
170
  }
171
171
  }
172
172
  // external-triggers/
173
- if (fs.existsSync(OLD_EXTERNAL_TRIGGERS_DIR) && !fs.existsSync(EXTERNAL_TRIGGERS_DIR)) {
174
- try {
175
- fs.cpSync(OLD_EXTERNAL_TRIGGERS_DIR, EXTERNAL_TRIGGERS_DIR, { recursive: true });
176
- console.warn("[config] Migrated external-triggers/ → " + EXTERNAL_TRIGGERS_DIR);
177
- } catch (e) {
178
- console.error("[config] Migration of external-triggers/ failed (non-fatal):", e.message);
173
+ // Use lstatSync (not existsSync) so a pre-existing symlink at the old path is
174
+ // detected and skipped — we only act on a real directory.
175
+ var _oldTriggersIsRealDir = false;
176
+ try {
177
+ var _oldStat = fs.lstatSync(OLD_EXTERNAL_TRIGGERS_DIR);
178
+ _oldTriggersIsRealDir = _oldStat.isDirectory() && !_oldStat.isSymbolicLink();
179
+ } catch (_) {}
180
+ if (_oldTriggersIsRealDir) {
181
+ if (!fs.existsSync(EXTERNAL_TRIGGERS_DIR)) {
182
+ // Case 1: new dir absent — simple copy (existing behavior).
183
+ try {
184
+ fs.cpSync(OLD_EXTERNAL_TRIGGERS_DIR, EXTERNAL_TRIGGERS_DIR, { recursive: true });
185
+ console.warn("[config] Migrated external-triggers/ → " + EXTERNAL_TRIGGERS_DIR);
186
+ } catch (e) {
187
+ console.error("[config] Migration of external-triggers/ failed (non-fatal):", e.message);
188
+ }
189
+ } else {
190
+ // Case 2: both old and new exist — merge .json files from old that are not
191
+ // already present in new (by filename), then replace the old dir with a
192
+ // symlink → EXTERNAL_TRIGGERS_DIR so stale writers (e.g. an un-updated relay
193
+ // binary still writing to the old root path) are silently redirected.
194
+ try {
195
+ // Merge top-level .json files.
196
+ var _oldFiles = fs.readdirSync(OLD_EXTERNAL_TRIGGERS_DIR);
197
+ for (var _oi = 0; _oi < _oldFiles.length; _oi++) {
198
+ var _oldFile = _oldFiles[_oi];
199
+ if (_oldFile === "processed") continue; // handled separately below
200
+ if (path.extname(_oldFile) !== ".json") continue;
201
+ var _oldFilePath = path.join(OLD_EXTERNAL_TRIGGERS_DIR, _oldFile);
202
+ var _newFilePath = path.join(EXTERNAL_TRIGGERS_DIR, _oldFile);
203
+ if (!fs.existsSync(_newFilePath)) {
204
+ try {
205
+ fs.copyFileSync(_oldFilePath, _newFilePath);
206
+ console.warn("[config] Merged external-triggers/" + _oldFile + " → " + _newFilePath);
207
+ } catch (_ce) {
208
+ console.error("[config] Merge of " + _oldFile + " failed (non-fatal):", _ce.message);
209
+ }
210
+ }
211
+ }
212
+ // Merge processed/ subdir files.
213
+ var _oldProcessedDir = path.join(OLD_EXTERNAL_TRIGGERS_DIR, "processed");
214
+ var _newProcessedDir = path.join(EXTERNAL_TRIGGERS_DIR, "processed");
215
+ if (fs.existsSync(_oldProcessedDir)) {
216
+ try { fs.mkdirSync(_newProcessedDir, { recursive: true }); } catch (_) {}
217
+ var _oldProcessed = fs.readdirSync(_oldProcessedDir);
218
+ for (var _pi = 0; _pi < _oldProcessed.length; _pi++) {
219
+ var _pf = _oldProcessed[_pi];
220
+ if (path.extname(_pf) !== ".json") continue;
221
+ var _oldPfPath = path.join(_oldProcessedDir, _pf);
222
+ var _newPfPath = path.join(_newProcessedDir, _pf);
223
+ if (!fs.existsSync(_newPfPath)) {
224
+ try {
225
+ fs.copyFileSync(_oldPfPath, _newPfPath);
226
+ console.warn("[config] Merged external-triggers/processed/" + _pf + " → " + _newPfPath);
227
+ } catch (_ce2) {
228
+ console.error("[config] Merge of processed/" + _pf + " failed (non-fatal):", _ce2.message);
229
+ }
230
+ }
231
+ }
232
+ }
233
+ // Replace old dir with a symlink → EXTERNAL_TRIGGERS_DIR. Rename to a temp
234
+ // name first, create the symlink, then remove the temp. Non-fatal: on any
235
+ // failure we best-effort restore the original name and leave for manual cleanup.
236
+ var _oldTriggersTmp = OLD_EXTERNAL_TRIGGERS_DIR + ".migration-tmp";
237
+ try {
238
+ fs.renameSync(OLD_EXTERNAL_TRIGGERS_DIR, _oldTriggersTmp);
239
+ fs.symlinkSync(EXTERNAL_TRIGGERS_DIR, OLD_EXTERNAL_TRIGGERS_DIR);
240
+ fs.rmSync(_oldTriggersTmp, { recursive: true, force: true });
241
+ console.warn("[config] Replaced " + OLD_EXTERNAL_TRIGGERS_DIR + " with symlink → " + EXTERNAL_TRIGGERS_DIR);
242
+ } catch (_se) {
243
+ console.error("[config] Symlink replacement of external-triggers/ failed (non-fatal):", _se.message);
244
+ try {
245
+ if (!fs.existsSync(OLD_EXTERNAL_TRIGGERS_DIR)) {
246
+ fs.renameSync(_oldTriggersTmp, OLD_EXTERNAL_TRIGGERS_DIR);
247
+ }
248
+ } catch (_re) {}
249
+ }
250
+ } catch (e) {
251
+ console.error("[config] Migration merge of external-triggers/ failed (non-fatal):", e.message);
252
+ }
179
253
  }
180
254
  }
181
255
  // daemon.json / daemon-dev.json (lr-eb5a: moved into console/)
@@ -99,7 +99,7 @@ function rescanWorktrees(relay, parentPath, parentSlug, parentIcon, parentOwnerI
99
99
  relay.broadcastAll({
100
100
  type: "projects_updated",
101
101
  projects: relay.getProjects(),
102
- projectCount: config ? config.projects.length : 0,
102
+ projectCount: relay.getProjects().length,
103
103
  });
104
104
  }
105
105
  } finally {
package/lib/daemon.js CHANGED
@@ -31,7 +31,7 @@ var usersModule = require("./users");
31
31
  var { createWorktree, removeWorktree, isWorktree } = require("./worktree");
32
32
  var { isWorktreeSlug, scanAndRegisterWorktrees, rescanWorktrees, cleanupWorktreesForParent, getFilteredRemovedProjects, registerWorktreeSlug, unregisterWorktreeSlug } = require("./daemon-projects");
33
33
  var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
34
- var { DEFAULT_MEM_AVAILABLE_MIN_MB } = require("./sdk-bridge");
34
+ var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM } = require("./sdk-bridge");
35
35
  var liteDetect = require("./lite-detect");
36
36
  var { execFile: liteExecFile } = require("child_process");
37
37
 
@@ -86,6 +86,28 @@ console.log("[daemon] Users: " + usersModule.USERS_FILE);
86
86
  if (process.env.SUDO_USER) console.log("[daemon] SUDO_USER: " + process.env.SUDO_USER);
87
87
  console.log("[daemon] UID: " + (typeof process.getuid === "function" ? process.getuid() : "N/A"));
88
88
 
89
+ // Stale-code check: if this process holds deleted inodes, the on-disk JS was
90
+ // replaced by a newer install while we were running. Warn loudly so operators
91
+ // know a restart is needed to load the new code.
92
+ function checkStaleInodes() {
93
+ if (process.platform !== 'linux') return false;
94
+ try {
95
+ var mapsContent = fs.readFileSync('/proc/self/maps', 'utf8');
96
+ return mapsContent.split('\n').some(function(line) {
97
+ return line.includes(' (deleted)');
98
+ });
99
+ } catch (_) {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ if (checkStaleInodes()) {
105
+ console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
106
+ console.warn('[daemon] WARNING: restart the daemon to load the new build:');
107
+ console.warn('[daemon] WARNING: systemctl restart clagentic-console');
108
+ console.warn('[daemon] WARNING: — or — clagentic-console --restart');
109
+ }
110
+
89
111
 
90
112
  // --- Single-user migration hint ---
91
113
  if (config.pinHash && !usersModule.isMultiUser()) {
@@ -921,6 +943,7 @@ var relay = createServer({
921
943
  updateChannel: config.updateChannel || "stable",
922
944
  imageRetentionDays: config.imageRetentionDays !== undefined ? config.imageRetentionDays : 7,
923
945
  memAvailableMinMB: config.memAvailableMinMB !== undefined ? config.memAvailableMinMB : DEFAULT_MEM_AVAILABLE_MIN_MB,
946
+ tokensPerMbHeadroom: config.tokensPerMbHeadroom !== undefined ? config.tokensPerMbHeadroom : DEFAULT_TOKENS_PER_MB_HEADROOM,
924
947
  liteAutoEnroll: !!config.liteAutoEnroll,
925
948
  };
926
949
  },
@@ -998,6 +1021,15 @@ var relay = createServer({
998
1021
  console.log("[daemon] MemAvailable threshold:", val, "MB (web)");
999
1022
  return { ok: true, memAvailableMinMB: val };
1000
1023
  },
1024
+ onSetTokensPerMbHeadroom: function (tpm) {
1025
+ var val = parseInt(tpm, 10);
1026
+ // Valid range: 10–500 tokens/MB; outside that range reset to default.
1027
+ if (isNaN(val) || val < 10 || val > 500) val = DEFAULT_TOKENS_PER_MB_HEADROOM;
1028
+ config.tokensPerMbHeadroom = val;
1029
+ saveConfig(config);
1030
+ console.log("[daemon] Tokens per MB headroom:", val, "(web)");
1031
+ return { ok: true, tokensPerMbHeadroom: val };
1032
+ },
1001
1033
  onGetToolPalettes: function () {
1002
1034
  return config.toolPalettes || {};
1003
1035
  },
@@ -1163,6 +1195,20 @@ var relay = createServer({
1163
1195
  },
1164
1196
  });
1165
1197
 
1198
+ // Periodic stale-code check: re-emit the warning every 60 s so it appears in
1199
+ // journalctl even if the operator wasn't watching at startup time.
1200
+ var staleCheckHandle = setInterval(function () {
1201
+ if (checkStaleInodes()) {
1202
+ console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
1203
+ console.warn('[daemon] WARNING: restart the daemon to load the new build:');
1204
+ console.warn('[daemon] WARNING: systemctl restart clagentic-console');
1205
+ console.warn('[daemon] WARNING: — or — clagentic-console --restart');
1206
+ }
1207
+ }, 60 * 1000);
1208
+ if (staleCheckHandle && typeof staleCheckHandle.unref === "function") {
1209
+ staleCheckHandle.unref();
1210
+ }
1211
+
1166
1212
  var IDLE_MS = Number(process.env.CLAY_CODEX_IDLE_MS) || 5 * 60 * 1000;
1167
1213
  var REAP_MS = Number(process.env.CLAY_CODEX_REAPER_MS) || 60 * 1000;
1168
1214
  var reaperHandle = setInterval(function () {
@@ -1189,6 +1235,10 @@ function stopCodexReaper() {
1189
1235
  clearInterval(reaperHandle);
1190
1236
  reaperHandle = null;
1191
1237
  }
1238
+ if (staleCheckHandle) {
1239
+ clearInterval(staleCheckHandle);
1240
+ staleCheckHandle = null;
1241
+ }
1192
1242
  }
1193
1243
 
1194
1244
  function shutdownProjects() {
@@ -1406,6 +1456,15 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1406
1456
  return { ok: true, memAvailableMinMB: memMB };
1407
1457
  }
1408
1458
 
1459
+ case "set_tokens_per_mb_headroom": {
1460
+ var tpmVal = parseInt(msg.value, 10);
1461
+ if (isNaN(tpmVal) || tpmVal < 10 || tpmVal > 500) tpmVal = DEFAULT_TOKENS_PER_MB_HEADROOM;
1462
+ config.tokensPerMbHeadroom = tpmVal;
1463
+ saveConfig(config);
1464
+ console.log("[daemon] Tokens per MB headroom:", tpmVal, "(cli)");
1465
+ return { ok: true, tokensPerMbHeadroom: tpmVal };
1466
+ }
1467
+
1409
1468
  case "enable_recovery": {
1410
1469
  if (!msg.urlPath || !msg.password) return { ok: false, error: "missing urlPath or password" };
1411
1470
  relay.setRecovery(msg.urlPath, msg.password);
@@ -1642,7 +1701,16 @@ function spawnAndRestart() {
1642
1701
  child.unref();
1643
1702
  fs.closeSync(logFd);
1644
1703
  config.pid = child.pid;
1645
- saveConfig(config);
1704
+ // Write PID synchronously before exit so the config file is not
1705
+ // left with a stale PID during the restart window. saveConfig() is
1706
+ // async (fire-and-forget) and is frequently not flushed before
1707
+ // process.exit(120) fires.
1708
+ try {
1709
+ fs.writeFileSync(restartConfigPath(), JSON.stringify(config, null, 2), { mode: 0o600 });
1710
+ } catch (syncErr) {
1711
+ console.error("[daemon] Sync PID write failed (non-fatal):", syncErr.message);
1712
+ saveConfig(config);
1713
+ }
1646
1714
  console.log("[daemon] Spawned new daemon (PID " + child.pid + "), exiting.");
1647
1715
  process.exit(120);
1648
1716
  } catch (e) {
@@ -3,6 +3,8 @@ var path = require("path");
3
3
 
4
4
  // How long (ms) to keep processed trigger files before pruning on startup.
5
5
  var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
6
+ var POLL_INTERVAL_MS = 30 * 1000; // 30 s backstop scan
7
+ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
6
8
 
7
9
  /**
8
10
  * External trigger watcher — global singleton.
@@ -35,6 +37,14 @@ var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
35
37
  * Daemon-down recovery: unprocessed files that predate the current process
36
38
  * start are picked up via a startup scan (scanExisting). No file is lost
37
39
  * if the daemon is restarted while triggers are pending.
40
+ *
41
+ * Watcher hardening (three layers):
42
+ * Layer 1 — 30 s polling backstop: scanExisting() on an interval so files
43
+ * are never permanently missed if fs.watch silently dies.
44
+ * Layer 2 — 5 min periodic re-arm: close and re-open the fs.watch binding
45
+ * so the inotify registration is never more than 5 min stale.
46
+ * Layer 3 — health export: getHealth() returns watcher liveness, last-event
47
+ * timestamp, and poll-interval presence for external monitoring.
38
48
  */
39
49
  function attachExternalTrigger(ctx) {
40
50
  var triggersDir = ctx.triggersDir;
@@ -47,6 +57,11 @@ function attachExternalTrigger(ctx) {
47
57
  // from the initial scan + watcher race.
48
58
  var dispatched = {};
49
59
 
60
+ // Hardening state
61
+ var pollInterval = null;
62
+ var rearmTimer = null;
63
+ var watcherLastEventMs = 0;
64
+
50
65
  // --- Directory setup ---
51
66
 
52
67
  function ensureDirs() {
@@ -231,12 +246,16 @@ function attachExternalTrigger(ctx) {
231
246
  }, 200);
232
247
  }
233
248
 
234
- function startWatcher() {
235
- ensureDirs();
236
- pruneOldProcessed();
237
- scanExisting(); // pick up files dropped while daemon was down
249
+ // --- Layer 2: periodic watcher re-arm ---
250
+
251
+ function armWatcher() {
252
+ if (watcher) {
253
+ try { watcher.close(); } catch (e) {}
254
+ watcher = null;
255
+ }
238
256
  try {
239
257
  watcher = fs.watch(triggersDir, function (eventType, filename) {
258
+ watcherLastEventMs = Date.now();
240
259
  if (filename && !filename.endsWith(".json")) return;
241
260
  onDirChange();
242
261
  });
@@ -244,18 +263,47 @@ function attachExternalTrigger(ctx) {
244
263
  console.error("[external-trigger] Watcher error:", e.message || e);
245
264
  stopWatcher();
246
265
  });
247
- console.log("[external-trigger] Watching:", triggersDir);
248
266
  } catch (e) {
249
- console.error("[external-trigger] Failed to start watcher:", e.message || e);
267
+ console.error("[external-trigger] Failed to arm watcher:", e.message || e);
250
268
  }
251
269
  }
252
270
 
271
+ function startWatcher() {
272
+ ensureDirs();
273
+ pruneOldProcessed();
274
+ scanExisting(); // pick up files dropped while daemon was down
275
+
276
+ armWatcher();
277
+ console.log("[external-trigger] Watching:", triggersDir);
278
+
279
+ // Layer 1: polling backstop — catches files if fs.watch silently dies
280
+ pollInterval = setInterval(function () {
281
+ scanExisting();
282
+ }, POLL_INTERVAL_MS);
283
+ pollInterval.unref();
284
+
285
+ // Layer 2: periodic re-arm — keeps inotify registration fresh
286
+ rearmTimer = setInterval(function () {
287
+ armWatcher();
288
+ console.log("[external-trigger] Watcher re-armed");
289
+ }, WATCHER_REARM_INTERVAL_MS);
290
+ rearmTimer.unref();
291
+ }
292
+
253
293
  function stopWatcher() {
254
294
  clearTimeout(debounce);
255
295
  if (watcher) {
256
296
  try { watcher.close(); } catch (e) {}
257
297
  watcher = null;
258
298
  }
299
+ if (pollInterval) {
300
+ clearInterval(pollInterval);
301
+ pollInterval = null;
302
+ }
303
+ if (rearmTimer) {
304
+ clearInterval(rearmTimer);
305
+ rearmTimer = null;
306
+ }
259
307
  }
260
308
 
261
309
  // --- Startup scan (daemon-down recovery) ---
@@ -289,8 +337,15 @@ function attachExternalTrigger(ctx) {
289
337
  return {
290
338
  startWatcher: startWatcher,
291
339
  stopWatcher: stopWatcher,
340
+ // Layer 3: health export for external monitoring
341
+ getHealth: function () {
342
+ return {
343
+ watcherAlive: !!watcher,
344
+ lastEventMs: watcherLastEventMs,
345
+ pollActive: !!pollInterval,
346
+ };
347
+ },
292
348
  };
293
349
  }
294
350
 
295
351
  module.exports = { attachExternalTrigger: attachExternalTrigger };
296
-
@@ -26,8 +26,24 @@ var MAX_UPLOAD_BYTES = 50 * 1024 * 1024; // 50 MB
26
26
  function parseJsonBody(req) {
27
27
  return new Promise(function (resolve, reject) {
28
28
  var body = "";
29
- req.on("data", function (chunk) { body += chunk; });
29
+ var bodyBytes = 0;
30
+ // Hard cap: enforce limit while buffering, not only after full accumulation.
31
+ // 1.4x headroom covers base64-encoded payloads (base64 expands by ~4/3).
32
+ var hardCap = MAX_UPLOAD_BYTES * 1.4;
33
+ var rejected = false;
34
+ req.on("data", function (chunk) {
35
+ if (rejected) return;
36
+ bodyBytes += Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk);
37
+ if (bodyBytes > hardCap) {
38
+ rejected = true;
39
+ req.destroy();
40
+ reject(new Error("Request body too large"));
41
+ return;
42
+ }
43
+ body += chunk;
44
+ });
30
45
  req.on("end", function () {
46
+ if (rejected) return;
31
47
  try { resolve(JSON.parse(body)); }
32
48
  catch (e) { reject(e); }
33
49
  });
@@ -678,6 +678,7 @@ function attachLoop(ctx) {
678
678
  // Unlock the last coder session so users can continue interacting with it.
679
679
  // Capture owner before clearing state so push routing still works.
680
680
  var _loopOwnerUserId = null;
681
+ var _lastSessionId = loopState.currentSessionId;
681
682
  if (loopState.currentSessionId) {
682
683
  var lastCoderSession = sm.sessions.get(loopState.currentSessionId);
683
684
  if (lastCoderSession) {
@@ -737,7 +738,7 @@ function attachLoop(ctx) {
737
738
  name: loopState.name,
738
739
  iterations: loopState.iteration,
739
740
  maxIterations: loopState.maxIterations,
740
- sessionId: loopState.currentSessionId,
741
+ sessionId: _lastSessionId,
741
742
  });
742
743
  }
743
744
 
@@ -170,17 +170,55 @@ function attachSessions(ctx) {
170
170
  // Hidden client-side when active project is a Mate; we still answer here
171
171
  // because the daemon shouldn't make UX decisions that the client already
172
172
  // owns. UI gates the surface; daemon stays a data plane.
173
+ //
174
+ // Background refresh: respond immediately with the cached list, then kick
175
+ // off a refresh(). If the catalog changes, re-send to this client only.
176
+ // Cost is paid exactly when the user opens the agent picker — not on a timer.
173
177
  if (msg.type === "list_agents") {
174
178
  var favorites = [];
175
179
  var recents = [];
176
180
  try { favorites = agentsFavorites.listFavorites(); recents = agentsFavorites.listRecents(); }
177
181
  catch (e) { /* favorites are best-effort */ }
182
+ var cachedAgents = agentsModule.getAll();
178
183
  sendTo(ws, {
179
184
  type: "agents_list",
180
- agents: agentsModule.getAll(),
185
+ agents: cachedAgents,
181
186
  favorites: favorites,
182
187
  recents: recents,
183
188
  });
189
+ // Refresh in background; re-send only if the catalog changed.
190
+ var cachedJson = JSON.stringify(cachedAgents);
191
+ agentsModule.refresh().then(function () {
192
+ var freshAgents = agentsModule.getAll();
193
+ if (JSON.stringify(freshAgents) === cachedJson) return;
194
+ var favFresh = [];
195
+ var recFresh = [];
196
+ try { favFresh = agentsFavorites.listFavorites(); recFresh = agentsFavorites.listRecents(); }
197
+ catch (e) { /* best-effort */ }
198
+ sendTo(ws, { type: "agents_list", agents: freshAgents, favorites: favFresh, recents: recFresh });
199
+ }).catch(function (e) {
200
+ console.error("[project-sessions] background agent refresh failed:", e && e.message ? e.message : e);
201
+ });
202
+ return true;
203
+ }
204
+
205
+ // refresh_agents — explicit on-demand refresh triggered from the settings UI.
206
+ // Re-runs SDK discovery, then broadcasts the updated catalog to ALL connected
207
+ // clients. Responds immediately with ok:true (async broadcast follows).
208
+ if (msg.type === "refresh_agents") {
209
+ sendTo(ws, { type: "refresh_agents_result", ok: true });
210
+ agentsModule.refresh().then(function () {
211
+ var freshAgents = agentsModule.getAll();
212
+ var favFresh = [];
213
+ var recFresh = [];
214
+ try { favFresh = agentsFavorites.listFavorites(); recFresh = agentsFavorites.listRecents(); }
215
+ catch (e) { /* best-effort */ }
216
+ send({ type: "agents_list", agents: freshAgents, favorites: favFresh, recents: recFresh });
217
+ send({ type: "toast", level: "info", message: "Agent catalog refreshed — " + freshAgents.length + " agent" + (freshAgents.length === 1 ? "" : "s") + " found." });
218
+ }).catch(function (e) {
219
+ console.error("[project-sessions] refresh_agents failed:", e && e.message ? e.message : e);
220
+ send({ type: "toast", level: "error", message: "Agent catalog refresh failed." });
221
+ });
184
222
  return true;
185
223
  }
186
224
 
@@ -1555,6 +1593,7 @@ function attachSessions(ctx) {
1555
1593
  // --- Daemon config / server management (admin-only in multi-user mode) ---
1556
1594
  if (msg.type === "get_daemon_config" || msg.type === "set_pin" || msg.type === "set_keep_awake" ||
1557
1595
  msg.type === "set_auto_continue" || msg.type === "set_image_retention" || msg.type === "set_mem_available_threshold" ||
1596
+ msg.type === "set_tokens_per_mb_headroom" ||
1558
1597
  msg.type === "set_lite_auto_enroll" ||
1559
1598
  msg.type === "shutdown_server" || msg.type === "restart_server") {
1560
1599
  if (usersModule.isMultiUser()) {
@@ -1629,6 +1668,15 @@ function attachSessions(ctx) {
1629
1668
  return true;
1630
1669
  }
1631
1670
 
1671
+ if (msg.type === "set_tokens_per_mb_headroom") {
1672
+ if (typeof opts.onSetTokensPerMbHeadroom === "function") {
1673
+ var tpmResult = opts.onSetTokensPerMbHeadroom(msg.value);
1674
+ sendTo(ws, { type: "set_tokens_per_mb_headroom_result", ok: tpmResult.ok, tokensPerMbHeadroom: tpmResult.tokensPerMbHeadroom });
1675
+ send({ type: "tokens_per_mb_headroom_changed", tokensPerMbHeadroom: tpmResult.tokensPerMbHeadroom });
1676
+ }
1677
+ return true;
1678
+ }
1679
+
1632
1680
  if (msg.type === "shutdown_server") {
1633
1681
  if (typeof opts.onShutdown === "function") {
1634
1682
  sendTo(ws, { type: "shutdown_server_result", ok: true });