@clagentic/console 1.10.0-beta.1 → 1.10.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.
Files changed (94) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +10 -0
  3. package/lib/activity-clock.js +23 -0
  4. package/lib/agent-dispatch-tool.js +20 -0
  5. package/lib/build-changes.js +79 -0
  6. package/lib/build-identity.js +192 -0
  7. package/lib/build-monitor.js +125 -0
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-offer.js +141 -0
  10. package/lib/build-update-restart.js +142 -0
  11. package/lib/build-update-standing.js +184 -0
  12. package/lib/cli/daemon-launch.js +8 -5
  13. package/lib/cli/ipc-subcommands.js +6 -0
  14. package/lib/cli/session-subcommands.js +122 -0
  15. package/lib/cli-sessions.js +8 -1
  16. package/lib/cli-transcript-title.js +131 -0
  17. package/lib/codex-defaults.js +8 -2
  18. package/lib/daemon-projects.js +19 -0
  19. package/lib/daemon.js +166 -127
  20. package/lib/debug-log.js +17 -0
  21. package/lib/exit-flush.js +44 -0
  22. package/lib/grant-keys.js +179 -0
  23. package/lib/log-field.js +34 -0
  24. package/lib/memory-shed.js +13 -32
  25. package/lib/project-connection.js +14 -0
  26. package/lib/project-external-trigger.js +91 -123
  27. package/lib/project-http.js +2 -0
  28. package/lib/project-loop.js +5 -4
  29. package/lib/project-notifications.js +4 -0
  30. package/lib/project-prompt-responses.js +7 -5
  31. package/lib/project-session-grants.js +73 -0
  32. package/lib/project-sessions.js +55 -68
  33. package/lib/project-user-message.js +13 -25
  34. package/lib/project.js +25 -5
  35. package/lib/prompt-kinds/permission.js +18 -0
  36. package/lib/prompt-label.js +60 -0
  37. package/lib/prompt-registry.js +123 -13
  38. package/lib/prompt-source.js +65 -0
  39. package/lib/public/css/diagnostics.css +30 -0
  40. package/lib/public/css/notifications-center.css +15 -0
  41. package/lib/public/css/overlays.css +18 -0
  42. package/lib/public/css/rewind.css +8 -0
  43. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  44. package/lib/public/modules/app-messages.js +10 -2
  45. package/lib/public/modules/app-notifications.js +9 -1
  46. package/lib/public/modules/app-panels.js +0 -1
  47. package/lib/public/modules/build-update-detail.js +54 -0
  48. package/lib/public/modules/diagnostics.js +126 -20
  49. package/lib/public/modules/prompt-banner.js +12 -0
  50. package/lib/public/modules/prompt-kinds/permission-choices.js +6 -1
  51. package/lib/public/modules/prompt-kinds/permission.js +15 -0
  52. package/lib/public/modules/prompt-label.js +44 -0
  53. package/lib/public/modules/prompts.js +9 -0
  54. package/lib/public/modules/session-grants.js +131 -0
  55. package/lib/public/modules/sidebar-sessions.js +11 -0
  56. package/lib/public/modules/tools.js +14 -2
  57. package/lib/public/modules/vendor-picker.js +2 -2
  58. package/lib/public/modules/vendor-registry.js +11 -2
  59. package/lib/runtime-env.js +1 -1
  60. package/lib/sdk-bridge.js +114 -115
  61. package/lib/sdk-message-processor.js +25 -87
  62. package/lib/sdk-skill-discovery.js +65 -60
  63. package/lib/server.js +15 -2
  64. package/lib/session-ai-title.js +80 -0
  65. package/lib/session-id.js +33 -0
  66. package/lib/session-input-ipc.js +32 -0
  67. package/lib/session-input.js +409 -0
  68. package/lib/session-reclaim.js +284 -0
  69. package/lib/session-resume.js +172 -0
  70. package/lib/sessions.js +31 -21
  71. package/lib/supervisor.js +39 -0
  72. package/lib/turn-initiator.js +108 -0
  73. package/lib/utils.js +9 -47
  74. package/lib/vendor-registry-message.js +1 -0
  75. package/lib/ws-schema.js +9 -4
  76. package/lib/yoke/adapters/claude-vendor.js +0 -1
  77. package/lib/yoke/adapters/claude-worker.js +6 -4
  78. package/lib/yoke/adapters/claude.js +29 -86
  79. package/lib/yoke/adapters/codex-capabilities.js +9 -6
  80. package/lib/yoke/adapters/codex-vendor.js +15 -15
  81. package/lib/yoke/adapters/codex.js +125 -136
  82. package/lib/yoke/auth-checks.js +8 -21
  83. package/lib/yoke/codex-app-server.js +27 -71
  84. package/lib/yoke/codex-binary.js +254 -0
  85. package/lib/yoke/codex-command.js +122 -0
  86. package/lib/yoke/codex-protocol.js +96 -0
  87. package/lib/yoke/codex-version.js +135 -0
  88. package/lib/yoke/index.js +20 -4
  89. package/lib/yoke/install-probe.js +21 -6
  90. package/lib/yoke/interface.js +14 -12
  91. package/lib/yoke/registry.js +41 -4
  92. package/package.json +1 -2
  93. package/scripts/verify-installed-build.js +59 -17
  94. package/lib/lore-attestation.js +0 -73
package/README.md CHANGED
@@ -34,7 +34,7 @@ Or try without installing:
34
34
  npx @clagentic/console
35
35
  ```
36
36
 
37
- **Requirements:** Node.js 20+. Authenticated Claude Code CLI, Codex CLI, or both.
37
+ **Requirements:** Node.js 20+. Authenticated Claude Code CLI, Codex CLI, or both. Codex is not bundled: install it yourself (`npm install -g @openai/codex`, version 0.148.0 or newer). The console runs the one it finds from `CLAGENTIC_CONSOLE_CODEX_PATH` (an absolute path), then `codex` on `PATH`, then the usual install locations, and shows the path and version in the agent picker.
38
38
 
39
39
  ### Postinstall / systemd
40
40
 
package/bin/cli.js CHANGED
@@ -80,6 +80,14 @@ if (args[0] === "release") {
80
80
  }
81
81
  }
82
82
 
83
+ // --- `open-session` / `send-input`: drive a session through the running daemon ---
84
+ // Positional verbs, handled before flag parsing: `clagentic-console send-input --project <slug> ...`.
85
+ var { SESSION_VERBS, runSessionVerb } = require("../lib/cli/session-subcommands");
86
+ if (SESSION_VERBS.indexOf(args[0]) !== -1) {
87
+ runSessionVerb(args[0], args.slice(1));
88
+ return;
89
+ }
90
+
83
91
  var port = _isDev ? 2635 : 2633;
84
92
  var useHttps = true;
85
93
  var forceMkcert = false;
@@ -164,6 +172,8 @@ for (var i = 0; i < args.length; i++) {
164
172
  console.log(" clagentic-console --list List registered projects");
165
173
  console.log(" clagentic-console --activity-diagnostics Print activity-divergence probe totals as JSON (agent-readable)");
166
174
  console.log(" clagentic-console --process-build-status Print the running process's loaded build SHA as JSON (agent-readable)");
175
+ console.log(" clagentic-console open-session --project <slug> --prompt <text|-> [--vendor <id>] [--agent <name>] Open a session and run a first prompt (prints JSON)");
176
+ console.log(" clagentic-console send-input --project <slug> --session <id> --prompt <text|-> Send input to a session, resuming it if needed (prints JSON)");
167
177
  console.log(" clagentic-console release list-betas List promotable beta versions (maintainer/release-engineering)");
168
178
  console.log(" clagentic-console daemon Run the daemon in the foreground (used by the systemd unit)");
169
179
  console.log("");
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+
3
+ // The one writer of session.lastActivityAt, the clock the idle reaper compares
4
+ // against (startIdleReaper in lib/sdk-bridge.js). Every bump names its source
5
+ // and, with CLAGENTIC_CONSOLE_DEBUG set, logs it, so a session that is never
6
+ // reaped can be traced to the event that kept resetting its clock.
7
+
8
+ var { debugLog } = require("./debug-log");
9
+ var { logField } = require("./log-field");
10
+
11
+ /**
12
+ * @param {object} session
13
+ * @param {string} source - what moved the clock (a fixed vocabulary at the call
14
+ * sites, e.g. "turn-result", "subagent-stream", "task_progress").
15
+ * @param {string} slug - the owning project; console session ids repeat across
16
+ * projects.
17
+ */
18
+ function bumpLastActivity(session, source, slug) {
19
+ session.lastActivityAt = Date.now();
20
+ debugLog("[activity] lastActivityAt bump: project=" + logField(slug) + " session=" + logField(session.localId) + " source=" + logField(source));
21
+ }
22
+
23
+ module.exports = { bumpLastActivity: bumpLastActivity };
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+
3
+ // The claude CLI has named the tool that dispatches a sub-agent both "Task"
4
+ // (older builds) and "Agent" (current builds). Every place that recognises a
5
+ // dispatch by tool name asks this predicate, so a rename cannot silently turn
6
+ // background-agent tracking off again.
7
+ //
8
+ // lib/public/modules/tools.js keeps a browser-side copy of this name set (the
9
+ // frontend is ESM and cannot require this file); a test asserts both accept
10
+ // the same names.
11
+ var AGENT_DISPATCH_TOOL_NAMES = ["Task", "Agent"];
12
+
13
+ function isAgentDispatchTool(name) {
14
+ return typeof name === "string" && AGENT_DISPATCH_TOOL_NAMES.indexOf(name) !== -1;
15
+ }
16
+
17
+ module.exports = {
18
+ AGENT_DISPATCH_TOOL_NAMES: AGENT_DISPATCH_TOOL_NAMES,
19
+ isAgentDispatchTool: isAgentDispatchTool,
20
+ };
@@ -0,0 +1,79 @@
1
+ 'use strict';
2
+
3
+ // build-changes.js — the commits between the build a daemon is running and the
4
+ // build installed over it, for the operator deciding whether to restart.
5
+ //
6
+ // Git history is optional: an npm install carries none, a checkout or an
7
+ // operator-named source repository (daemon.json `buildSourceRepo`) does. When
8
+ // it cannot be read the answer says so; it never invents a list.
9
+
10
+ var fs = require('fs');
11
+ var path = require('path');
12
+ var { execFile } = require('child_process');
13
+
14
+ var SHA_RE = /^[0-9a-f]{7,40}$/i;
15
+ var DEFAULT_LIMIT = 30;
16
+ var SUBJECT_MAX = 200;
17
+ var GIT_TIMEOUT_MS = 5000;
18
+
19
+ /** The repository to read history from, or null when there is none to try. */
20
+ function resolveHistoryRepo(configured, packageRoot) {
21
+ if (typeof configured === 'string' && path.isAbsolute(configured)) return configured;
22
+ try {
23
+ if (fs.existsSync(path.join(packageRoot, '.git'))) return packageRoot;
24
+ } catch (_) {
25
+ // unreadable package root: no history to offer
26
+ }
27
+ return null;
28
+ }
29
+
30
+ function oneLine(text) {
31
+ var line = String(text).replace(/\s+/g, ' ').trim();
32
+ return line.length > SUBJECT_MAX ? line.slice(0, SUBJECT_MAX - 3) + '...' : line;
33
+ }
34
+
35
+ /**
36
+ * @param {object} o
37
+ * @param {?string} o.repo — result of resolveHistoryRepo
38
+ * @param {string} o.fromSha — the build the process loaded
39
+ * @param {string} o.toSha — the build installed over it
40
+ * @param {number} [o.limit]
41
+ * @param {function} [o.execFileFn] — injectable for tests
42
+ * @returns {Promise<{available: boolean, commits: Array<{sha: string, subject: string}>, truncated: boolean, reason: ?string}>}
43
+ */
44
+ function listBuildChanges(o) {
45
+ var limit = o.limit > 0 ? o.limit : DEFAULT_LIMIT;
46
+ var run = o.execFileFn || execFile;
47
+ function unavailable(reason) {
48
+ return { available: false, commits: [], truncated: false, reason: reason };
49
+ }
50
+ if (!o.repo) return Promise.resolve(unavailable('no git history is available for this install'));
51
+ // Only hex revisions reach git, so a value can never be read as an option.
52
+ if (!SHA_RE.test(String(o.fromSha)) || !SHA_RE.test(String(o.toSha))) {
53
+ return Promise.resolve(unavailable('a build sha is not a git revision'));
54
+ }
55
+ var args = [
56
+ '-C', o.repo,
57
+ '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null',
58
+ 'log', '--no-ext-diff', '--no-textconv',
59
+ '--format=%h%x09%s', '-n', String(limit + 1),
60
+ o.fromSha + '..' + o.toSha,
61
+ ];
62
+ return new Promise(function (resolve) {
63
+ run('git', args, { timeout: GIT_TIMEOUT_MS, maxBuffer: 1024 * 1024, encoding: 'utf8' }, function (err, stdout) {
64
+ if (err) {
65
+ resolve(unavailable('git could not list the commits between these builds'));
66
+ return;
67
+ }
68
+ var lines = String(stdout).split('\n').filter(function (l) { return l.length > 0; });
69
+ var truncated = lines.length > limit;
70
+ var commits = lines.slice(0, limit).map(function (l) {
71
+ var tab = l.indexOf('\t');
72
+ return { sha: l.slice(0, tab), subject: oneLine(l.slice(tab + 1)) };
73
+ });
74
+ resolve({ available: true, commits: commits, truncated: truncated, reason: null });
75
+ });
76
+ });
77
+ }
78
+
79
+ module.exports = { listBuildChanges: listBuildChanges, resolveHistoryRepo: resolveHistoryRepo, DEFAULT_LIMIT: DEFAULT_LIMIT };
@@ -0,0 +1,192 @@
1
+ 'use strict';
2
+
3
+ // build-identity.js — what build is this process running, and is it still the
4
+ // build installed on disk?
5
+ //
6
+ // An install replaces the package's files. A running Node process keeps what
7
+ // it already loaded, so "adopted" means two things must both hold: the sha the
8
+ // process recorded at startup equals the sha of the installed build, and the
9
+ // installed files are byte-for-byte what the process started from. The second
10
+ // half is what tells an identical reinstall (same sha, same bytes, new inodes)
11
+ // apart from a genuinely different build with an unchanged sha.
12
+ //
13
+ // The kernel's "(deleted)" mapping marker is NOT part of this decision: an
14
+ // identical reinstall unlinks the native module the daemon keeps mapped, so
15
+ // that marker appears and never clears, although nothing the daemon runs
16
+ // differs from what is installed.
17
+
18
+ var crypto = require('crypto');
19
+ var fs = require('fs');
20
+ var path = require('path');
21
+
22
+ // This module must not require another lib/ module: the daemon loads it first
23
+ // so the loaded identity is captured before any other lib code is read from
24
+ // disk. An install landing between those reads would otherwise label old
25
+ // cached code with the new tree's identity.
26
+
27
+ // A file absent or half-written during an install is expected and means
28
+ // "unknown, not stale". Anything else (permissions, I/O, a bug) is not, so it is
29
+ // journaled with the path and surfaced to the verdict instead of vanishing.
30
+ function isExpectedReadFailure(err, allowParse) {
31
+ return !!err && (err.code === 'ENOENT' || (allowParse && err instanceof SyntaxError));
32
+ }
33
+
34
+ function describeFailure(what, target, err) {
35
+ var message = what + ' ' + target + ': ' + (err && err.message ? err.message : String(err));
36
+ try { console.error('[build-identity] ' + message); } catch (_) { /* a closed stdio must not mask the verdict */ }
37
+ return message;
38
+ }
39
+
40
+ /** @returns {{sha: ?string, error: ?string}} error is set only for an unexpected failure */
41
+ function readInstalledBuildSha(buildShaPath) {
42
+ try {
43
+ var parsed = JSON.parse(fs.readFileSync(buildShaPath, 'utf8'));
44
+ return { sha: parsed && typeof parsed.sha === 'string' ? parsed.sha : null, error: null };
45
+ } catch (err) {
46
+ if (isExpectedReadFailure(err, true)) return { sha: null, error: null };
47
+ return { sha: null, error: describeFailure('could not read the build identity at', buildShaPath, err) };
48
+ }
49
+ }
50
+
51
+ var STATES = { ADOPTED: 'adopted', STALE: 'stale', INCONCLUSIVE: 'inconclusive' };
52
+
53
+ /**
54
+ * Walks `dir` and calls fn(absPath, relPath) for every regular file, in a
55
+ * stable order. Symlinks and special files are not content of the build.
56
+ */
57
+ function walkFiles(dir, relBase, fn) {
58
+ var entries = fs.readdirSync(dir, { withFileTypes: true });
59
+ entries.sort(function (a, b) { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; });
60
+ for (var i = 0; i < entries.length; i++) {
61
+ var entry = entries[i];
62
+ var abs = path.join(dir, entry.name);
63
+ var rel = relBase ? relBase + '/' + entry.name : entry.name;
64
+ if (entry.isDirectory()) walkFiles(abs, rel, fn);
65
+ else if (entry.isFile()) fn(abs, rel);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * A hasher over one package root (the directory holding lib/ and
71
+ * package.json). `hash()` returns a hex digest of every file under lib/ plus
72
+ * package.json, or null when the tree cannot be read right now (an install in
73
+ * progress removes files mid-walk). Per-file digests are remembered by
74
+ * (inode, size, mtime), so a poll re-reads only files an install replaced.
75
+ */
76
+ function createTreeHasher(packageRoot) {
77
+ var known = new Map(); // abs path -> { key, digest }
78
+ var lastError = null; // set only when the last hash() failed for a reason an install does not explain
79
+
80
+ function fileDigest(abs) {
81
+ var st = fs.statSync(abs);
82
+ // ctime moves on any in-place rewrite even when mtime is restored with
83
+ // utimes, so a same-size rewrite cannot reuse the old digest.
84
+ var key = st.dev + ':' + st.ino + ':' + st.size + ':' + st.mtimeMs + ':' + st.ctimeMs;
85
+ var cached = known.get(abs);
86
+ if (cached && cached.key === key) return cached.digest;
87
+ var digest = crypto.createHash('sha256').update(fs.readFileSync(abs)).digest('hex');
88
+ known.set(abs, { key: key, digest: digest });
89
+ return digest;
90
+ }
91
+
92
+ function hash() {
93
+ lastError = null;
94
+ try {
95
+ var outer = crypto.createHash('sha256');
96
+ var seen = new Set();
97
+ var add = function (abs, rel) {
98
+ seen.add(abs);
99
+ outer.update(rel + '\0' + fileDigest(abs) + '\n');
100
+ };
101
+ walkFiles(path.join(packageRoot, 'lib'), 'lib', add);
102
+ add(path.join(packageRoot, 'package.json'), 'package.json');
103
+ // Files that left the tree must not keep their remembered digest.
104
+ known.forEach(function (_v, abs) { if (!seen.has(abs)) known.delete(abs); });
105
+ return outer.digest('hex');
106
+ } catch (err) {
107
+ if (!isExpectedReadFailure(err, false)) {
108
+ lastError = describeFailure('could not hash the installed tree under', packageRoot, err);
109
+ }
110
+ return null;
111
+ }
112
+ }
113
+
114
+ return { hash: hash, lastError: function () { return lastError; } };
115
+ }
116
+
117
+ /**
118
+ * Pure comparison of what the process loaded against what is installed.
119
+ * Exactly one of adopted / stale / inconclusive, never a guess: a missing
120
+ * piece on either side is inconclusive with the reason, not stale.
121
+ *
122
+ * @param {{sha: ?string, contentHash: ?string}} loaded
123
+ * @param {{sha: ?string, contentHash: ?string}} installed
124
+ */
125
+ function assessBuild(loaded, installed) {
126
+ var l = loaded || {};
127
+ var i = installed || {};
128
+ var base = {
129
+ loadedBuildSha: l.sha || null,
130
+ installedBuildSha: i.sha || null,
131
+ loadedContentHash: l.contentHash || null,
132
+ installedContentHash: i.contentHash || null,
133
+ };
134
+ function result(state, reason, detail) {
135
+ return Object.assign({ state: state, reason: reason, detail: detail }, base);
136
+ }
137
+ if (!l.sha) {
138
+ return result(STATES.INCONCLUSIVE, 'no-loaded-sha',
139
+ l.shaError || 'this process has no embedded build sha (a checkout that never ran npm pack)');
140
+ }
141
+ if (!i.sha) {
142
+ return result(STATES.INCONCLUSIVE, 'no-installed-sha',
143
+ i.shaError || 'the installed build-sha.json is missing or unreadable');
144
+ }
145
+ // A partial install can change build-sha.json before the files are whole, so
146
+ // an unreadable tree is inconclusive whatever the shas say.
147
+ if (!l.contentHash || !i.contentHash) {
148
+ return result(STATES.INCONCLUSIVE, 'hash-unavailable',
149
+ l.hashError || i.hashError || 'the installed files could not be read to compare their content');
150
+ }
151
+ if (l.sha !== i.sha) {
152
+ return result(STATES.STALE, 'sha', 'the installed build (' + i.sha + ') is not the one this process loaded (' + l.sha + ')');
153
+ }
154
+ if (l.contentHash !== i.contentHash) {
155
+ return result(STATES.STALE, 'content',
156
+ 'the installed files differ from the ones this process loaded, although both report build ' + l.sha);
157
+ }
158
+ return result(STATES.ADOPTED, 'identical', 'the installed build is the one this process loaded');
159
+ }
160
+
161
+ /**
162
+ * Captures the running build once, at startup, and reads the installed one on
163
+ * demand. `libDir` is the lib/ directory this process was loaded from.
164
+ */
165
+ function createBuildIdentity(libDir) {
166
+ var packageRoot = path.resolve(libDir, '..');
167
+ var buildShaPath = path.join(libDir, 'build-sha.json');
168
+ var hasher = createTreeHasher(packageRoot);
169
+ function snapshot() {
170
+ var s = readInstalledBuildSha(buildShaPath);
171
+ var contentHash = hasher.hash();
172
+ return { sha: s.sha, shaError: s.error, contentHash: contentHash, hashError: contentHash ? null : hasher.lastError() };
173
+ }
174
+ var loaded = snapshot();
175
+
176
+ function readInstalled() {
177
+ return snapshot();
178
+ }
179
+
180
+ return {
181
+ loaded: loaded,
182
+ readInstalled: readInstalled,
183
+ assess: function () { return assessBuild(loaded, readInstalled()); },
184
+ };
185
+ }
186
+
187
+ module.exports = {
188
+ STATES: STATES,
189
+ assessBuild: assessBuild,
190
+ createBuildIdentity: createBuildIdentity,
191
+ createTreeHasher: createTreeHasher,
192
+ };
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+
3
+ // build-monitor.js — turns repeated build assessments into a confirmed verdict
4
+ // and the journal lines that go with it.
5
+ //
6
+ // It only observes and logs. It does not talk to clients and it does not know
7
+ // whether an offer is shown: the offer is derived from `confirmedStale()` by
8
+ // lib/build-update-standing.js after every poll. Nothing here restarts anything;
9
+ // the one actuator is the operator's confirmed click handled in
10
+ // lib/build-update-restart.js.
11
+ //
12
+ // Rules:
13
+ // - A stale verdict must be seen for the same installed build on
14
+ // `confirmations` consecutive checks before it is confirmed, so a poll that
15
+ // lands in the middle of an install (files half-replaced) never offers a
16
+ // restart for a build that is not there yet.
17
+ // - An inconclusive poll always breaks a streak that is not yet confirmed,
18
+ // even while an older build stays confirmed. It never touches the confirmed
19
+ // verdict: it neither clears it nor counts toward a reminder.
20
+ // - An adopted verdict clears the confirmation.
21
+ // - The journal gets a warning when a streak is first confirmed and a reminder
22
+ // every `reminderEvery` stale checks for the same build, from a counter of
23
+ // its own.
24
+
25
+ var DEFAULT_CONFIRMATIONS = 2;
26
+ // A confirmed stale build is repeated in the journal at this many checks, so a
27
+ // reader of the log sees it without it filling the log every minute.
28
+ var DEFAULT_REMINDER_EVERY = 30;
29
+
30
+ /**
31
+ * @param {object} o
32
+ * @param {function(): object} o.assess — returns an assessBuild() result
33
+ * @param {function(string): void} [o.log]
34
+ * @param {number} [o.confirmations]
35
+ * @param {number} [o.reminderEvery]
36
+ */
37
+ function createBuildMonitor(o) {
38
+ var confirmations = o.confirmations > 0 ? o.confirmations : DEFAULT_CONFIRMATIONS;
39
+ var reminderEvery = o.reminderEvery > 0 ? o.reminderEvery : DEFAULT_REMINDER_EVERY;
40
+ var log = typeof o.log === 'function' ? o.log : function () {};
41
+
42
+ var pendingKey = null;
43
+ var seen = 0;
44
+ var confirmedKey = null;
45
+ var confirmed = null;
46
+ var sinceConfirm = 0;
47
+ var lastInconclusive = null;
48
+ var current = null;
49
+
50
+ function keyOf(a) { return a.installedBuildSha + ':' + a.installedContentHash; }
51
+
52
+ function check() {
53
+ var a = o.assess();
54
+ current = a;
55
+
56
+ if (a.state === 'inconclusive') {
57
+ // Unknown is not stale and not adopted. Samples on either side of it are
58
+ // not consecutive evidence, so the unconfirmed candidate is always dropped.
59
+ // The confirmed verdict and its reminder counter are not touched.
60
+ pendingKey = null;
61
+ seen = 0;
62
+ if (lastInconclusive !== a.reason) {
63
+ lastInconclusive = a.reason;
64
+ log('Build check inconclusive (' + a.reason + '): ' + a.detail);
65
+ }
66
+ return a;
67
+ }
68
+ lastInconclusive = null;
69
+
70
+ if (a.state === 'adopted') {
71
+ pendingKey = null;
72
+ seen = 0;
73
+ if (confirmedKey !== null) {
74
+ confirmedKey = null;
75
+ confirmed = null;
76
+ sinceConfirm = 0;
77
+ log('The installed build is the one this process loaded.');
78
+ }
79
+ return a;
80
+ }
81
+
82
+ var key = keyOf(a);
83
+ if (key === confirmedKey) {
84
+ // Still the confirmed build: keep its latest assessment and count a reminder.
85
+ pendingKey = key;
86
+ seen = confirmations;
87
+ confirmed = a;
88
+ sinceConfirm += 1;
89
+ if (sinceConfirm % reminderEvery === 0) {
90
+ log('Still serving build ' + a.loadedBuildSha + '; build ' + a.installedBuildSha +
91
+ ' is installed. The Clagentic: Console UI offers the restart.');
92
+ }
93
+ return a;
94
+ }
95
+
96
+ if (key !== pendingKey) {
97
+ pendingKey = key;
98
+ seen = 1;
99
+ } else {
100
+ seen += 1;
101
+ }
102
+ if (seen >= confirmations) {
103
+ confirmedKey = key;
104
+ confirmed = a;
105
+ sinceConfirm = 0;
106
+ log('WARNING: this process is serving STALE code: ' + a.detail + '.');
107
+ log('WARNING: restarting is your decision. Use "Restart to apply update" in the Clagentic: Console UI, or restart the service yourself.');
108
+ }
109
+ return a;
110
+ }
111
+
112
+ return {
113
+ check: check,
114
+ /** The last assessment, or null before the first check. */
115
+ current: function () { return current; },
116
+ /**
117
+ * The confirmed stale assessment, or null when none is confirmed. This is
118
+ * the desired offer state: it survives inconclusive polls and is replaced
119
+ * only by adoption or by another confirmed stale build.
120
+ */
121
+ confirmedStale: function () { return confirmed; },
122
+ };
123
+ }
124
+
125
+ module.exports = { createBuildMonitor: createBuildMonitor, DEFAULT_CONFIRMATIONS: DEFAULT_CONFIRMATIONS };
@@ -1,4 +1,4 @@
1
1
  {
2
- "sha": "60b156cfc4df1ac7c46a48c98bd3ba448c132c03",
3
- "writtenAt": "2026-10-11T22:53:13.001Z"
2
+ "sha": "fed91a544d850e066830fd24c98e9f4a28d85422",
3
+ "writtenAt": "2026-10-15T11:55:56.872Z"
4
4
  }
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ // build-update-offer.js — what the operator is told before a restart to adopt
4
+ // an installed build: which build is running, which is installed, and exactly
5
+ // what the restart will end.
6
+ //
7
+ // "Live" is the same notion the shutdown path uses: a session that holds a
8
+ // running agent process (queryInstance or worker). That process dies with the
9
+ // daemon, and with it any background agent the session dispatched.
10
+
11
+ var SESSION_TITLE_MAX = 80;
12
+ var liveAgentTasks = require('./session-reclaim').liveAgentTasks;
13
+
14
+ function oneLine(text, max, fallback) {
15
+ if (typeof text !== 'string') return fallback;
16
+ var line = text.replace(/\s+/g, ' ').trim();
17
+ if (!line) return fallback;
18
+ return line.length > max ? line.slice(0, max - 3) + '...' : line;
19
+ }
20
+
21
+ function isLive(session) {
22
+ return !!(session && (session.queryInstance || session.worker));
23
+ }
24
+
25
+ /**
26
+ * Everything a restart now would end, across every project.
27
+ *
28
+ * @param {Array<{slug: string, sm: {sessions: Map}}>} projects
29
+ * @returns {{sessions: Array<object>, sessionCount: number, processingCount: number, agentCount: number, keys: string[]}}
30
+ */
31
+ function collectInterruptions(projects) {
32
+ var sessions = [];
33
+ var keys = [];
34
+ var agentCount = 0;
35
+ var processingCount = 0;
36
+ (projects || []).forEach(function (proj) {
37
+ if (!proj || !proj.sm || !proj.sm.sessions) return;
38
+ proj.sm.sessions.forEach(function (session) {
39
+ if (!isLive(session)) return;
40
+ var key = proj.slug + '#' + session.localId;
41
+ var agents = liveAgentTasks(session);
42
+ var processing = !!session.isProcessing;
43
+ keys.push(key);
44
+ // Busy state is part of what the operator was shown: a session offered as
45
+ // idle that starts a turn afterwards is not covered.
46
+ if (processing) keys.push(key + '#busy');
47
+ agents.forEach(function (a) { keys.push(key + '#' + a.id); });
48
+ agentCount += agents.length;
49
+ if (processing) processingCount += 1;
50
+ sessions.push({
51
+ key: key,
52
+ slug: proj.slug,
53
+ localId: session.localId,
54
+ title: oneLine(session.title, SESSION_TITLE_MAX, 'Untitled session'),
55
+ processing: processing,
56
+ agents: agents.map(function (a) { return a.label; }),
57
+ });
58
+ });
59
+ });
60
+ return {
61
+ sessions: sessions,
62
+ sessionCount: sessions.length,
63
+ processingCount: processingCount,
64
+ agentCount: agentCount,
65
+ keys: keys,
66
+ };
67
+ }
68
+
69
+ /** True when every key in `current` was already in `offered`. */
70
+ function coveredBy(current, offered) {
71
+ var have = new Set(offered);
72
+ return current.every(function (k) { return have.has(k); });
73
+ }
74
+
75
+ function plural(n, word) {
76
+ return n + ' ' + word + (n === 1 ? '' : 's');
77
+ }
78
+
79
+ /** The operator-facing statement of what a restart ends. */
80
+ function describeInterruptions(i, waitSeconds) {
81
+ if (i.sessionCount === 0) {
82
+ return 'No session is live, so the restart ends nothing that is running.';
83
+ }
84
+ var lines = [
85
+ 'Restarting Clagentic: Console now ends ' + plural(i.sessionCount, 'live session') +
86
+ (i.agentCount > 0 ? ' and ' + plural(i.agentCount, 'background agent') : '') + '.',
87
+ ];
88
+ i.sessions.forEach(function (s) {
89
+ var state = s.processing ? 'running a turn' : 'idle';
90
+ var agents = s.agents.length > 0
91
+ ? '; background agents: ' + s.agents.map(function (l) { return '"' + l + '"'; }).join(', ')
92
+ : '';
93
+ lines.push('- [' + s.slug + '] ' + s.title + ' (' + state + agents + ')');
94
+ });
95
+ lines.push('Running turns and agents get up to ' + waitSeconds + ' seconds to finish first. ' +
96
+ 'Ended sessions resume when you send them a message.');
97
+ return lines.join('\n');
98
+ }
99
+
100
+ /**
101
+ * The offer shown for a stale build. `interruptions` is included only for the
102
+ * admin who is about to confirm; the version that goes to every connected
103
+ * client leaves it out because session titles and agent names are session
104
+ * content.
105
+ */
106
+ function buildOffer(o) {
107
+ var a = o.assessment;
108
+ var offer = {
109
+ loadedBuildSha: a.loadedBuildSha,
110
+ installedBuildSha: a.installedBuildSha,
111
+ reason: a.reason,
112
+ changes: o.changes || { available: false, commits: [], truncated: false, reason: null },
113
+ };
114
+ if (o.interruptions) {
115
+ offer.interruptions = {
116
+ sessions: o.interruptions.sessions,
117
+ sessionCount: o.interruptions.sessionCount,
118
+ agentCount: o.interruptions.agentCount,
119
+ };
120
+ offer.interruptionText = describeInterruptions(o.interruptions, o.waitSeconds);
121
+ }
122
+ if (o.token) offer.token = o.token;
123
+ return offer;
124
+ }
125
+
126
+ /** One line naming both builds, for the notice and the log. */
127
+ function summarizeOffer(a) {
128
+ var short = function (s) { return s ? s.slice(0, 12) : '(unknown)'; };
129
+ return a.reason === 'content'
130
+ ? 'Build ' + short(a.installedBuildSha) + ' is installed with different files than the running process loaded.'
131
+ : 'Running build ' + short(a.loadedBuildSha) + '; installed build ' + short(a.installedBuildSha) + '.';
132
+ }
133
+
134
+ module.exports = {
135
+ collectInterruptions: collectInterruptions,
136
+ coveredBy: coveredBy,
137
+ describeInterruptions: describeInterruptions,
138
+ buildOffer: buildOffer,
139
+ summarizeOffer: summarizeOffer,
140
+ liveAgentTasks: liveAgentTasks,
141
+ };