@clagentic/console 1.10.0-beta.1 → 1.10.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 (68) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +10 -0
  3. package/lib/agent-dispatch-tool.js +20 -0
  4. package/lib/build-changes.js +79 -0
  5. package/lib/build-identity.js +192 -0
  6. package/lib/build-monitor.js +125 -0
  7. package/lib/build-sha.json +2 -2
  8. package/lib/build-update-offer.js +141 -0
  9. package/lib/build-update-restart.js +142 -0
  10. package/lib/build-update-standing.js +184 -0
  11. package/lib/cli/daemon-launch.js +8 -5
  12. package/lib/cli/ipc-subcommands.js +6 -0
  13. package/lib/cli/session-subcommands.js +122 -0
  14. package/lib/cli-sessions.js +8 -1
  15. package/lib/codex-defaults.js +8 -2
  16. package/lib/daemon-projects.js +19 -0
  17. package/lib/daemon.js +166 -127
  18. package/lib/memory-shed.js +13 -32
  19. package/lib/project-connection.js +14 -0
  20. package/lib/project-external-trigger.js +91 -123
  21. package/lib/project-loop.js +5 -4
  22. package/lib/project-prompt-responses.js +5 -4
  23. package/lib/project-sessions.js +43 -68
  24. package/lib/project-user-message.js +7 -20
  25. package/lib/project.js +23 -5
  26. package/lib/prompt-registry.js +7 -0
  27. package/lib/public/css/diagnostics.css +30 -0
  28. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  29. package/lib/public/modules/app-messages.js +7 -2
  30. package/lib/public/modules/app-panels.js +0 -1
  31. package/lib/public/modules/build-update-detail.js +54 -0
  32. package/lib/public/modules/diagnostics.js +126 -20
  33. package/lib/public/modules/tools.js +14 -2
  34. package/lib/public/modules/vendor-picker.js +2 -2
  35. package/lib/public/modules/vendor-registry.js +11 -2
  36. package/lib/sdk-bridge.js +62 -15
  37. package/lib/sdk-message-processor.js +11 -20
  38. package/lib/sdk-skill-discovery.js +65 -60
  39. package/lib/server.js +15 -2
  40. package/lib/session-id.js +33 -0
  41. package/lib/session-input-ipc.js +32 -0
  42. package/lib/session-input.js +379 -0
  43. package/lib/session-reclaim.js +284 -0
  44. package/lib/session-resume.js +172 -0
  45. package/lib/sessions.js +16 -2
  46. package/lib/supervisor.js +39 -0
  47. package/lib/turn-initiator.js +108 -0
  48. package/lib/vendor-registry-message.js +1 -0
  49. package/lib/ws-schema.js +3 -1
  50. package/lib/yoke/adapters/claude-vendor.js +0 -1
  51. package/lib/yoke/adapters/claude-worker.js +6 -4
  52. package/lib/yoke/adapters/claude.js +34 -34
  53. package/lib/yoke/adapters/codex-capabilities.js +9 -6
  54. package/lib/yoke/adapters/codex-vendor.js +15 -15
  55. package/lib/yoke/adapters/codex.js +121 -61
  56. package/lib/yoke/auth-checks.js +8 -21
  57. package/lib/yoke/codex-app-server.js +27 -71
  58. package/lib/yoke/codex-binary.js +254 -0
  59. package/lib/yoke/codex-command.js +122 -0
  60. package/lib/yoke/codex-protocol.js +96 -0
  61. package/lib/yoke/codex-version.js +135 -0
  62. package/lib/yoke/index.js +20 -4
  63. package/lib/yoke/install-probe.js +21 -6
  64. package/lib/yoke/interface.js +11 -5
  65. package/lib/yoke/registry.js +41 -4
  66. package/package.json +1 -2
  67. package/scripts/verify-installed-build.js +59 -17
  68. package/lib/lore-attestation.js +0 -73
package/lib/daemon.js CHANGED
@@ -23,6 +23,9 @@ delete process.env.CLAUDECODE;
23
23
 
24
24
  var fs = require("fs");
25
25
  var path = require("path");
26
+ // What this process loaded is recorded before anything else is required from
27
+ // lib/, so an install landing during startup is seen as a change afterwards.
28
+ var buildIdentity = require("./build-identity").createBuildIdentity(__dirname);
26
29
  var { loadConfig, saveConfig, socketPath, ensureConfigDir, generateSlug, syncClayrc, removeFromClayrc, writeCrashInfo, readCrashInfo, clearCrashInfo, isPidAlive, clearStaleConfig, REAL_HOME, CONFIG_DIR, CLAGENTIC_HOME } = require("./config");
27
30
  var { createIPCServer } = require("./ipc");
28
31
  var { createEnvSettings, removeEnvrcOnOwnerChange } = require("./daemon-env-settings");
@@ -32,7 +35,7 @@ var promptRegistry = require("./prompt-registry");
32
35
  var { checkAclSupport, grantProjectAccess, revokeProjectAccess, provisionAllUsers, provisionLinuxUser, grantAllUsersAccess, deactivateLinuxUser, ensureProjectsDir } = require("./os-users");
33
36
  var usersModule = require("./users");
34
37
  var { createWorktree, removeWorktree, isWorktree } = require("./worktree");
35
- var { isWorktreeSlug, scanAndRegisterWorktrees, rescanWorktrees, cleanupWorktreesForParent, getFilteredRemovedProjects, registerWorktreeSlug, unregisterWorktreeSlug, getProjectAccessRecord } = require("./daemon-projects");
38
+ var { isWorktreeSlug, scanAndRegisterWorktrees, rescanWorktrees, stopWorktreeRescans, cleanupWorktreesForParent, getFilteredRemovedProjects, registerWorktreeSlug, unregisterWorktreeSlug, getProjectAccessRecord } = require("./daemon-projects");
36
39
  var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
37
40
  var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount, buildActivityDiagnosticsResponse } = require("./sdk-bridge");
38
41
  var { validateMemAvailableThresholdMB, validateTokensPerMbHeadroom } = require("./memory-setting-validate");
@@ -41,7 +44,13 @@ var { createDrain } = require("./drain");
41
44
  var { setNewWorkGate } = require("./new-work-gate");
42
45
  var { shedMemory } = require("./memory-shed");
43
46
  var { dropSkillsCache } = require("./server-skills");
44
- var { readInstalledBuildSha, checkForNewerInstalledBuild, waitForIdleThenAct } = require("./build-update-check");
47
+ var { waitForIdleThenAct } = require("./build-update-check");
48
+ var { createBuildMonitor } = require("./build-monitor");
49
+ var { createBuildUpdateRestart } = require("./build-update-restart");
50
+ var { buildOffer, summarizeOffer } = require("./build-update-offer");
51
+ var { createStandingOffer } = require("./build-update-standing");
52
+ var { listBuildChanges, resolveHistoryRepo } = require("./build-changes");
53
+ var { RESTART_EXIT_CODE, isSupervised, unsupervisedEnv } = require("./supervisor");
45
54
  var liteDetect = require("./lite-detect");
46
55
  var { execFile: liteExecFile } = require("child_process");
47
56
  var { SLUG_RE: CUSTOM_ICON_SLUG_RE, CUSTOM_EMOJI_CT } = require("./server-settings");
@@ -101,9 +110,11 @@ if (_projectsDirNotice) console.log(_projectsDirNotice);
101
110
  if (process.env.SUDO_USER) console.log("[daemon] SUDO_USER: " + process.env.SUDO_USER);
102
111
  console.log("[daemon] UID: " + (typeof process.getuid === "function" ? process.getuid() : "N/A"));
103
112
 
104
- // Stale-code check: if this process holds deleted inodes, the on-disk JS was
105
- // replaced by a newer install while we were running. Warn loudly so operators
106
- // know a restart is needed to load the new code.
113
+ // Whether this process maps a file an install has since unlinked. Reported by
114
+ // get_build_status for diagnosis only: an identical reinstall also unlinks the
115
+ // native module this process keeps mapped, and the marker never clears, so it
116
+ // cannot say whether the installed build differs from the loaded one. That
117
+ // verdict comes from buildIdentity (sha plus content hash).
107
118
  function checkStaleInodes() {
108
119
  if (process.platform !== 'linux') return false;
109
120
  try {
@@ -116,31 +127,15 @@ function checkStaleInodes() {
116
127
  }
117
128
  }
118
129
 
119
- // lr-dc9a3b: the SHA this process actually loaded lib/build-sha.json with at
120
- // startup, captured once here so a later re-read of the on-disk file (after
121
- // an install replaces it) can never be confused with what THIS process is
122
- // running. Read defensively — a dev checkout that has never run `npm pack`
123
- // (prepack writes this file, and it is gitignored) will not have it, and
124
- // that is a legitimate "no build-identity signal available" state, not an
125
- // error.
130
+ // The SHA this process loaded lib/build-sha.json with at startup (captured by
131
+ // buildIdentity at the top of this file), never re-read, so a later install
132
+ // replacing the file on disk can never be confused with what THIS process is
133
+ // running. null for a checkout that has never run `npm pack` (prepack writes
134
+ // the file and it is gitignored): "no build-identity signal", not an error.
126
135
  var loadedBuildSha = null;
127
- try {
128
- var _buildShaContents = fs.readFileSync(path.join(__dirname, 'build-sha.json'), 'utf8');
129
- var _buildShaParsed = JSON.parse(_buildShaContents);
130
- if (_buildShaParsed && typeof _buildShaParsed.sha === 'string') {
131
- loadedBuildSha = _buildShaParsed.sha;
132
- }
133
- } catch (_) {
134
- // lib/build-sha.json missing/unreadable/malformed — loadedBuildSha stays
135
- // null, which get_build_status reports honestly rather than guessing.
136
- }
137
-
138
- if (checkStaleInodes()) {
139
- console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
140
- console.warn('[daemon] WARNING: restart the daemon to load the new build:');
141
- console.warn('[daemon] WARNING: systemctl restart clagentic-console');
142
- console.warn('[daemon] WARNING: — or — clagentic-console --restart');
143
- }
136
+ loadedBuildSha = buildIdentity.loaded.sha;
137
+ console.log("[daemon] Build: sha=" + (loadedBuildSha || "(none)") +
138
+ " files=" + (buildIdentity.loaded.contentHash ? buildIdentity.loaded.contentHash.slice(0, 12) : "(unreadable)"));
144
139
 
145
140
 
146
141
  // --- Single-user to multi-user migration (lr-ec2d) ---
@@ -1253,25 +1248,19 @@ var relay = createServer({
1253
1248
  console.log("[daemon] Restart requested via web UI");
1254
1249
  spawnAndRestart();
1255
1250
  },
1256
- // lr-e85fec: operator clicked "Restart to apply update" on the
1257
- // build-adoption diagnostic above. Unlike onRestart (immediate —
1258
- // restart_server is already an explicit admin action with no reason to
1259
- // delay further), this waits for in-flight sessions to finish first, the
1260
- // same signal drain.js's memory-pressure path already keys off
1261
- // (getActiveLiveCount()) — an operator asking to "apply the update" is not
1262
- // also asking to drop whatever is running right now. Still bounded: a
1263
- // stuck session cannot hold this open forever. See
1264
- // build-update-check.js's waitForIdleThenAct for the (unit-tested) timing
1265
- // logic itself.
1266
- onRestartForBuildUpdate: function () {
1267
- console.log("[daemon] Restart-for-build-update requested via web UI — waiting for in-flight sessions to finish");
1268
- waitForIdleThenAct({
1269
- getActiveCount: getActiveLiveCount,
1270
- onIdle: function () {
1271
- console.log("[daemon] Restarting to adopt new build (activeCount=" + getActiveLiveCount() + ")");
1272
- spawnAndRestart();
1273
- },
1274
- });
1251
+ // The operator's click on "Restart to apply update". Without a token it
1252
+ // answers with the offer (both builds, the commits between them, what a
1253
+ // restart would end) and restarts nothing; with the token of an offer the
1254
+ // operator was shown it schedules the restart, which waits a bounded time
1255
+ // for running turns and re-checks that nothing unseen is live. See
1256
+ // lib/build-update-restart.js. Resolves { status, offer?, note? }.
1257
+ onRestartForBuildUpdate: function (token) {
1258
+ return buildUpdateRestart.request(token);
1259
+ },
1260
+ // The standing offer state for a client that connects: the held offer, or an
1261
+ // explicit "no offer" so a client that missed a retraction drops a dead action.
1262
+ onGetBuildUpdateDiagnostic: function () {
1263
+ return buildStandingOffer.forNewClient();
1275
1264
  },
1276
1265
  onSetProjectVisibility: function (slug, visibility) {
1277
1266
  for (var i = 0; i < config.projects.length; i++) {
@@ -1385,19 +1374,89 @@ var relay = createServer({
1385
1374
  },
1386
1375
  });
1387
1376
 
1388
- // Periodic stale-code check: re-emit the warning every 60 s so it appears in
1389
- // journalctl even if the operator wasn't watching at startup time.
1390
- var staleCheckHandle = setInterval(function () {
1391
- if (checkStaleInodes()) {
1392
- console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
1393
- console.warn('[daemon] WARNING: restart the daemon to load the new build:');
1394
- console.warn('[daemon] WARNING: systemctl restart clagentic-console');
1395
- console.warn('[daemon] WARNING: — or — clagentic-console --restart');
1377
+ // --- Build adoption: is the installed build the one this process loaded? ---
1378
+ // The verdict is buildIdentity.assess() (sha plus content hash), not the
1379
+ // kernel's deleted-mapping marker. Only a stale verdict seen on consecutive
1380
+ // checks is announced: in the journal, and as an offer in the UI. Announcing
1381
+ // restarts nothing; the one path to a restart is the operator's confirmed
1382
+ // click handled by buildUpdateRestart (lib/build-update-restart.js).
1383
+ var buildHistoryRepo = resolveHistoryRepo(config.buildSourceRepo, path.join(__dirname, ".."));
1384
+
1385
+ function listChangesBetweenBuilds(range) {
1386
+ return listBuildChanges({ repo: buildHistoryRepo, fromSha: range.fromSha, toSha: range.toSha });
1387
+ }
1388
+
1389
+ function liveProjectsForOffer() {
1390
+ var out = [];
1391
+ relay.forEachProject(function (ctx, slug) {
1392
+ if (ctx && ctx.sm) out.push({ slug: slug, sm: ctx.sm });
1393
+ });
1394
+ return out;
1395
+ }
1396
+
1397
+ var BUILD_CHECK_MS = Number(readConsoleEnv("CLAGENTIC_CONSOLE_BUILD_CHECK_MS")) || 60 * 1000;
1398
+ // A failed change-list read is retried no more often than the journal reminder.
1399
+ var BUILD_REMINDER_EVERY = 30;
1400
+
1401
+ // The offer clients hold is reconciled against the monitor's confirmed stale
1402
+ // assessment after every poll (lib/build-update-standing.js): it is shown,
1403
+ // refreshed or retracted to match, and only when that differs from what was
1404
+ // last shown.
1405
+ var buildStandingOffer = createStandingOffer({
1406
+ listChanges: listChangesBetweenBuilds,
1407
+ desired: function () { return buildMonitor.confirmedStale(); },
1408
+ retryAfterMs: BUILD_CHECK_MS * BUILD_REMINDER_EVERY,
1409
+ broadcast: function (message) { relay.broadcastAll(message); },
1410
+ compose: function (a, changes) {
1411
+ return {
1412
+ type: "diagnostic",
1413
+ severity: "warning",
1414
+ source: "build-update",
1415
+ message: summarizeOffer(a) + " Restart to apply it when it suits you; nothing restarts on its own.",
1416
+ buildUpdate: buildOffer({ assessment: a, changes: changes }),
1417
+ actionable: { label: "Restart to apply update", action: "restart_for_build_update" },
1418
+ };
1419
+ },
1420
+ log: function (line) { console.log("[daemon] " + line); },
1421
+ });
1422
+
1423
+ var buildUpdateRestart = createBuildUpdateRestart({
1424
+ assess: function () { return buildIdentity.assess(); },
1425
+ getProjects: liveProjectsForOffer,
1426
+ listChanges: listChangesBetweenBuilds,
1427
+ restart: function () {
1428
+ console.log("[daemon] Restarting to adopt the installed build, as the operator confirmed");
1429
+ spawnAndRestart();
1430
+ },
1431
+ waitForIdleThenAct: waitForIdleThenAct,
1432
+ announce: function (message) {
1433
+ relay.broadcastAll({ type: "diagnostic", severity: "warning", source: "build-update", message: message });
1434
+ },
1435
+ log: function (line) { console.log("[daemon] " + line); },
1436
+ });
1437
+
1438
+ var buildMonitor = createBuildMonitor({
1439
+ assess: function () { return buildIdentity.assess(); },
1440
+ log: function (line) { console.log("[daemon] " + line); },
1441
+ reminderEvery: BUILD_REMINDER_EVERY,
1442
+ });
1443
+
1444
+ function runBuildCheck() {
1445
+ try {
1446
+ buildMonitor.check();
1447
+ } catch (e) {
1448
+ // A failed check is only a missed nudge; it must never take the daemon down.
1449
+ console.error("[daemon] Build check failed (non-fatal):", e && e.message ? e.message : e);
1396
1450
  }
1397
- }, 60 * 1000);
1398
- if (staleCheckHandle && typeof staleCheckHandle.unref === "function") {
1399
- staleCheckHandle.unref();
1451
+ // Reconciled after every poll, including one whose check failed: the desired
1452
+ // state is whatever the monitor last confirmed. It does not throw.
1453
+ buildStandingOffer.reconcile(buildMonitor.confirmedStale());
1400
1454
  }
1455
+ var buildCheckHandle = setInterval(runBuildCheck, BUILD_CHECK_MS);
1456
+ var buildFirstCheckHandle = setTimeout(runBuildCheck, Math.min(10000, BUILD_CHECK_MS));
1457
+ [buildCheckHandle, buildFirstCheckHandle].forEach(function (h) {
1458
+ if (h && typeof h.unref === "function") h.unref();
1459
+ });
1401
1460
 
1402
1461
  var IDLE_MS = Number(readConsoleEnv("CLAGENTIC_CONSOLE_IDLE_RUNTIME_MS")) || 5 * 60 * 1000;
1403
1462
  var REAP_MS = Number(readConsoleEnv("CLAGENTIC_CONSOLE_IDLE_REAPER_MS")) || 60 * 1000;
@@ -1408,9 +1467,10 @@ function stopCodexReaper() {
1408
1467
  stopIdleReaper();
1409
1468
  stopIdleReaper = null;
1410
1469
  }
1411
- if (staleCheckHandle) {
1412
- clearInterval(staleCheckHandle);
1413
- staleCheckHandle = null;
1470
+ if (buildCheckHandle) {
1471
+ clearInterval(buildCheckHandle);
1472
+ clearTimeout(buildFirstCheckHandle);
1473
+ buildCheckHandle = null;
1414
1474
  }
1415
1475
  if (_memoryWatcher) {
1416
1476
  _memoryWatcher.stop();
@@ -1419,6 +1479,9 @@ function stopCodexReaper() {
1419
1479
  }
1420
1480
 
1421
1481
  function shutdownProjects() {
1482
+ // First, before any project is destroyed: a rescan firing mid-shutdown would
1483
+ // re-add worktrees to projects that are being torn down.
1484
+ stopWorktreeRescans();
1422
1485
  stopCodexReaper();
1423
1486
  try {
1424
1487
  var result = relay.destroyAll();
@@ -1592,13 +1655,34 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1592
1655
  //
1593
1656
  // Read-only, mutates nothing, same OS-level socket gate as every other
1594
1657
  // command on this connection (CONFIG_DIR is chmod 0700).
1595
- case "get_build_status":
1658
+ case "get_build_status": {
1659
+ // state is exactly one of adopted / stale / inconclusive (with the
1660
+ // reason), from the sha and a content hash of the installed files. An
1661
+ // identical reinstall over this process is adopted; staleInodes is
1662
+ // reported for diagnosis and is not what decides it.
1663
+ var buildAssessment = buildIdentity.assess();
1596
1664
  return {
1597
1665
  ok: true,
1598
1666
  loadedBuildSha: loadedBuildSha,
1667
+ installedBuildSha: buildAssessment.installedBuildSha,
1668
+ state: buildAssessment.state,
1669
+ reason: buildAssessment.reason,
1670
+ detail: buildAssessment.detail,
1671
+ loadedContentHash: buildAssessment.loadedContentHash,
1672
+ installedContentHash: buildAssessment.installedContentHash,
1599
1673
  staleInodes: checkStaleInodes(),
1600
1674
  pid: process.pid,
1601
1675
  };
1676
+ }
1677
+
1678
+ // Open a session, or send input to one, from a caller that is not the
1679
+ // browser. The same lib/session-input.js code the external-trigger file
1680
+ // drop runs, so a request gets the same result either way. Same OS-level
1681
+ // socket gate as every command here (CONFIG_DIR is chmod 0700); input never
1682
+ // counts as a human turn (session-input.js refuses that initiator).
1683
+ case "open_session":
1684
+ case "send_session_input":
1685
+ return require("./session-input-ipc").handleSessionCommand(relay.sessionInput, msg);
1602
1686
 
1603
1687
  case "set_pin": {
1604
1688
  config.pinHash = msg.pinHash || null;
@@ -1930,64 +2014,6 @@ function startListening() {
1930
2014
  }
1931
2015
  }
1932
2016
 
1933
- // --- lr-e85fec: build-adoption diagnostic ---
1934
- // Polls whether the on-disk build (lib/build-sha.json, rewritten by every
1935
- // `npm install -g`) has moved past what THIS process loaded at startup
1936
- // (loadedBuildSha, captured once above and never re-read). lr-22e8's
1937
- // stale-inode/journald warning already surfaces this on the log, but
1938
- // nothing acted on it (see lr-e85fec's task description — the same
1939
- // warning fired 403 times before anyone noticed). This turns the
1940
- // detector into an OFFERED, operator-initiated affordance instead of a
1941
- // passive log line: a diagnostic with an actionable "restart to apply"
1942
- // button the operator can act on when THEY choose, never an automatic
1943
- // restart (see onRestartForBuildUpdate below — restart only ever fires
1944
- // in direct response to that click).
1945
- //
1946
- // Only fires once per detected staleness (edge-triggered on
1947
- // _buildUpdateAnnounced), not on every poll — a 5-minute interval would
1948
- // otherwise re-toast the same condition indefinitely until the operator
1949
- // actually restarts.
1950
- var _buildUpdateAnnounced = false;
1951
- var BUILD_UPDATE_POLL_MS = 5 * 60 * 1000;
1952
- var _buildShaPath = path.join(__dirname, "build-sha.json");
1953
- function _pollBuildUpdate() {
1954
- try {
1955
- var installedSha = readInstalledBuildSha(_buildShaPath);
1956
- var result = checkForNewerInstalledBuild({
1957
- loadedBuildSha: loadedBuildSha,
1958
- installedBuildSha: installedSha,
1959
- });
1960
- if (result.stale && !_buildUpdateAnnounced) {
1961
- _buildUpdateAnnounced = true;
1962
- console.log("[daemon] Newer build installed on disk (" + result.installedBuildSha +
1963
- ") than this process loaded (" + result.loadedBuildSha + ") — offering restart in UI.");
1964
- relay.broadcastAll({
1965
- type: "diagnostic",
1966
- severity: "warning",
1967
- source: "build-update",
1968
- message: "A newer build has been installed but is not yet running. Restart to apply it.",
1969
- actionable: { label: "Restart to apply update", action: "restart_for_build_update" },
1970
- });
1971
- } else if (!result.stale) {
1972
- // Covers the (rare) case of a manual downgrade/rollback reinstalling
1973
- // the same SHA this process already has — re-arm so a subsequent
1974
- // genuine update is announced again rather than staying suppressed
1975
- // forever from one earlier announcement.
1976
- _buildUpdateAnnounced = false;
1977
- }
1978
- } catch (e) {
1979
- // A detection failure must never crash the daemon — this is a
1980
- // best-effort UI nudge, not a load-bearing control path.
1981
- console.error("[daemon] Build-update check failed (non-fatal):", e && e.message ? e.message : e);
1982
- }
1983
- }
1984
- var _buildUpdateTimer = setInterval(_pollBuildUpdate, BUILD_UPDATE_POLL_MS);
1985
- if (_buildUpdateTimer && typeof _buildUpdateTimer.unref === "function") _buildUpdateTimer.unref();
1986
- // Run once shortly after startup too — otherwise an install that lands
1987
- // moments after this process started would sit undetected for a full
1988
- // poll interval before the operator sees anything.
1989
- setTimeout(_pollBuildUpdate, 10000);
1990
-
1991
2017
  // Auto-provision Linux accounts on startup if OS users mode is enabled.
1992
2018
  // ACLs are NOT re-applied on every startup (too slow with recursive setfacl).
1993
2019
  // ACLs are set when: projects are added, users are added, or visibility changes.
@@ -2091,6 +2117,17 @@ if (config.keepAwake && process.platform === "darwin") {
2091
2117
 
2092
2118
  // --- Spawn new daemon and graceful restart ---
2093
2119
  function spawnAndRestart() {
2120
+ // Under a supervisor the restart is an exit and nothing more. A replacement
2121
+ // spawned here is not the unit's main process, so the unit kills it with the
2122
+ // rest of its cgroup and then starts its own: one extra process killed, the
2123
+ // restart working only by accident. Self-respawn is for unsupervised starts.
2124
+ if (isSupervised()) {
2125
+ console.log("[daemon] Running under a supervisor: exiting with code " + RESTART_EXIT_CODE +
2126
+ " for it to start the replacement; not spawning one");
2127
+ updateHandoff = true;
2128
+ gracefulShutdown();
2129
+ return;
2130
+ }
2094
2131
  try {
2095
2132
  updateHandoff = true;
2096
2133
  ipc.close();
@@ -2108,13 +2145,14 @@ function spawnAndRestart() {
2108
2145
  detached: true,
2109
2146
  windowsHide: true,
2110
2147
  stdio: ["ignore", logFd, logFd],
2111
- env: Object.assign({}, process.env, {
2148
+ env: Object.assign(unsupervisedEnv(), {
2112
2149
  CLAGENTIC_CONSOLE_CONFIG: restartConfigPath(),
2113
2150
  CLAGENTIC_CONSOLE_HOME: restartClagenticHome,
2114
2151
  }),
2115
2152
  });
2116
2153
  child.unref();
2117
2154
  fs.closeSync(logFd);
2155
+ successorSpawned = true;
2118
2156
  config.pid = child.pid;
2119
2157
  // Write PID synchronously before exit so the config file is not
2120
2158
  // left with a stale PID during the restart window. saveConfig() is
@@ -2127,7 +2165,7 @@ function spawnAndRestart() {
2127
2165
  saveConfig(config);
2128
2166
  }
2129
2167
  console.log("[daemon] Spawned new daemon (PID " + child.pid + "), exiting.");
2130
- process.exit(120);
2168
+ process.exit(RESTART_EXIT_CODE);
2131
2169
  } catch (e) {
2132
2170
  console.error("[daemon] Restart failed:", e.message);
2133
2171
  process.exit(1);
@@ -2154,14 +2192,15 @@ function spawnAndRestart() {
2154
2192
  }
2155
2193
 
2156
2194
  // --- Graceful shutdown ---
2157
- var updateHandoff = false; // true when shutting down for update (new daemon already spawned)
2195
+ var updateHandoff = false; // true when shutting down to be replaced (exit code RESTART_EXIT_CODE)
2196
+ var successorSpawned = false; // true once a self-spawned replacement has its pid saved in the config
2158
2197
  var shutdownStarted = false;
2159
2198
 
2160
2199
  function gracefulShutdown() {
2161
2200
  try { console.log("[daemon] Shutting down..."); } catch (e) {}
2162
2201
  if (shutdownStarted) return;
2163
2202
  shutdownStarted = true;
2164
- var exitCode = updateHandoff ? 120 : 0; // 120 = update handoff, don't auto-restart
2203
+ var exitCode = updateHandoff ? RESTART_EXIT_CODE : 0;
2165
2204
 
2166
2205
  if (caffeinateProc) {
2167
2206
  try { caffeinateProc.kill(); } catch (e) {}
@@ -2169,8 +2208,8 @@ function gracefulShutdown() {
2169
2208
 
2170
2209
  ipc.close();
2171
2210
 
2172
- // Remove PID from config (skip if update handoff — new daemon PID is already saved)
2173
- if (!updateHandoff) {
2211
+ // Remove PID from config (skip when a self-spawned replacement's PID is already saved)
2212
+ if (!successorSpawned) {
2174
2213
  try {
2175
2214
  var c = loadConfig();
2176
2215
  if (c && c.pid === process.pid) {
@@ -35,6 +35,8 @@
35
35
 
36
36
  'use strict';
37
37
 
38
+ var sessionReclaim = require('./session-reclaim');
39
+
38
40
  // Minimum interval between shedding passes (ms). A crossing that arrives
39
41
  // inside this window returns immediately with skipped=true rather than
40
42
  // running a second pass.
@@ -241,38 +243,17 @@ function shedMemory(opts) {
241
243
  // replays correctly on reconnect like any other history entry.
242
244
  for (var li = 0; li < liveChildReclaims.length; li++) {
243
245
  var reclaim = liveChildReclaims[li];
244
- var rSession = reclaim.session;
245
- if (!rSession) continue;
246
- try {
247
- rSession.pendingAutoResume = true;
248
- rSession.pendingAutoResumeReason = 'memory_pressure_reclaim';
249
- if (reclaim.sm && typeof reclaim.sm.saveSessionFile === 'function') {
250
- reclaim.sm.saveSessionFile(rSession);
251
- }
252
- } catch (e) {
253
- // Marker persistence failing must not block the notification below —
254
- // the operator still needs to see the reclaim happened.
255
- }
256
-
257
- var reclaimMessage = 'Memory pressure reclaimed this session while a background task was still running. '
258
- + 'It will auto-resume; if it does not, resume it manually.';
259
-
260
- if (reclaim.send) {
261
- try {
262
- reclaim.send({
263
- type: 'diagnostic',
264
- severity: 'warning',
265
- source: 'memory-reclaim',
266
- message: (reclaim.slug ? '[' + reclaim.slug + '] ' : '') + reclaimMessage,
267
- });
268
- } catch (e) { /* one client's send failure must not block others */ }
269
- }
270
-
271
- if (reclaim.sm && typeof reclaim.sm.sendAndRecord === 'function') {
272
- try {
273
- reclaim.sm.sendAndRecord(rSession, { type: 'error', text: reclaimMessage });
274
- } catch (e) { /* inline marker failing must not block the rest of the pass */ }
275
- }
246
+ // The idle reaper announces through the same helper, so both paths name
247
+ // the interrupted agents and mark the session the same way.
248
+ sessionReclaim.announceLiveAgentReclaim({
249
+ session: reclaim.session,
250
+ sm: reclaim.sm,
251
+ send: reclaim.send,
252
+ slug: reclaim.slug,
253
+ reason: 'memory_pressure_reclaim',
254
+ source: 'memory-reclaim',
255
+ cause: 'Memory pressure reclaimed this session while a background task was still running.',
256
+ });
276
257
  }
277
258
 
278
259
  return summary;
@@ -5,6 +5,7 @@ var userPresence = require("./user-presence");
5
5
  var { authOf } = require("./project-access");
6
6
  var { getCodexConfig } = require("./codex-defaults");
7
7
  var { promptsFor } = require("./prompt-registry");
8
+ var sessionReclaim = require("./session-reclaim");
8
9
  var { buildVendorRegistryMessage } = require("./vendor-registry-message");
9
10
  // detectLite is cached per-project in project.js and passed via ctx.liteStatus.
10
11
  // This import is retained only for backward compat if ctx.liteStatus is absent.
@@ -147,6 +148,11 @@ function attachConnection(ctx) {
147
148
  infoMsg.dangerouslySkipPermissionsBlocked = true;
148
149
  }
149
150
  sendTo(ws, infoMsg);
151
+ // Background agents the last shutdown interrupted: nobody was connected
152
+ // to be told then.
153
+ sessionReclaim.restartDiagnostics(sm, slug, wsUser ? function (s) {
154
+ return usersModule.canAccessSession(wsUser.id, s, { visibility: "public" });
155
+ } : function () { return true; }).forEach(function (d) { sendTo(ws, d); });
150
156
  // Update notifications are pushed on a scheduled interval (see
151
157
  // scheduleUpdateBroadcast). We no longer push on connect to avoid
152
158
  // re-triggering the banner on every page refresh.
@@ -177,6 +183,13 @@ function attachConnection(ctx) {
177
183
  _loop.sendConnectionState(ws);
178
184
  if (_mcp) _mcp.sendConnectionState(ws);
179
185
  if (_notifications) _notifications.sendConnectionState(ws, sendTo);
186
+ // A client that connects is told the current offer state: the held offer, or
187
+ // an explicit retraction when none stands, so a missed retraction cannot
188
+ // leave a dead restart action on screen.
189
+ if (typeof opts.onGetBuildUpdateDiagnostic === "function") {
190
+ var _buildUpdateDiag = opts.onGetBuildUpdateDiagnostic();
191
+ if (_buildUpdateDiag) sendTo(ws, _buildUpdateDiag);
192
+ }
180
193
 
181
194
  // Session list (filtered for access control)
182
195
  // Use the canonical mapper from sessions.js
@@ -228,6 +241,7 @@ function attachConnection(ctx) {
228
241
  // subsequent reconnect to the same session.
229
242
  if (active.pendingAutoResume) {
230
243
  active.pendingAutoResume = false;
244
+ active.restartNoticeAgents = null;
231
245
  sm.saveSessionFile(active);
232
246
  }
233
247
  // lr-2ea2a7: hasHistory uses the ABSOLUTE count (_historyBaseIndex +