@clagentic/console 1.10.0 → 1.11.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +14 -0
  2. package/bin/cli.js +15 -3
  3. package/lib/agents.js +1 -55
  4. package/lib/bash-auto-approve.js +133 -0
  5. package/lib/build-identity.js +23 -5
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-check.js +0 -62
  8. package/lib/build-update-offer.js +23 -13
  9. package/lib/build-update-restart.js +59 -43
  10. package/lib/cli/schedule-input-subcommands.js +327 -0
  11. package/lib/cli/session-subcommands.js +100 -17
  12. package/lib/client-build-id.js +56 -0
  13. package/lib/daemon.js +20 -5
  14. package/lib/injected-sender.js +225 -0
  15. package/lib/message-sender-record.js +133 -0
  16. package/lib/pending-prompts.js +55 -0
  17. package/lib/permission-mode-policy.js +63 -0
  18. package/lib/permission-summary.js +67 -0
  19. package/lib/project-connection.js +2 -1
  20. package/lib/project-external-trigger.js +9 -1
  21. package/lib/project-loop.js +26 -20
  22. package/lib/project-prompt-responses.js +20 -14
  23. package/lib/project-sessions.js +73 -21
  24. package/lib/project-user-message.js +18 -47
  25. package/lib/project.js +36 -62
  26. package/lib/public/app.js +3 -5
  27. package/lib/public/css/channel-layout.css +20 -0
  28. package/lib/public/css/diagnostics.css +7 -0
  29. package/lib/public/css/input.css +78 -0
  30. package/lib/public/css/menus.css +17 -0
  31. package/lib/public/modules/app-connection.js +18 -1
  32. package/lib/public/modules/app-messages.js +19 -17
  33. package/lib/public/modules/app-panels.js +9 -2
  34. package/lib/public/modules/app-rate-limit.js +63 -87
  35. package/lib/public/modules/app-rendering.js +37 -6
  36. package/lib/public/modules/at-agents.js +8 -0
  37. package/lib/public/modules/build-guard.js +61 -0
  38. package/lib/public/modules/build-update-detail.js +1 -4
  39. package/lib/public/modules/diagnostics.js +98 -9
  40. package/lib/public/modules/injected-identity.js +78 -0
  41. package/lib/public/modules/injected-label.js +62 -0
  42. package/lib/public/modules/input.js +64 -114
  43. package/lib/public/modules/mode-options.js +19 -16
  44. package/lib/public/modules/rate-limit-state.js +47 -22
  45. package/lib/public/modules/schedule-panel.js +234 -0
  46. package/lib/public/modules/schedule-time.js +193 -0
  47. package/lib/public/modules/scheduled-input-actions.js +19 -0
  48. package/lib/runtime-env.js +4 -0
  49. package/lib/scheduled-input/ipc.js +92 -0
  50. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  51. package/lib/scheduled-input/records.js +350 -0
  52. package/lib/scheduled-input/service.js +743 -0
  53. package/lib/scheduled-input/store.js +132 -0
  54. package/lib/scheduled-input/ws.js +194 -0
  55. package/lib/sdk-bridge.js +137 -152
  56. package/lib/sdk-message-processor.js +13 -5
  57. package/lib/sdk-skill-discovery.js +17 -0
  58. package/lib/sender-ref.js +109 -0
  59. package/lib/server.js +28 -8
  60. package/lib/session-directory.js +224 -0
  61. package/lib/session-file-scan.js +55 -0
  62. package/lib/session-input-ipc.js +20 -0
  63. package/lib/session-input.js +355 -19
  64. package/lib/session-name-holder.js +82 -0
  65. package/lib/session-resume.js +1 -0
  66. package/lib/sessions.js +44 -0
  67. package/lib/turn-initiator.js +6 -2
  68. package/lib/ws-schema.js +15 -7
  69. package/lib/yoke/adapters/claude-worker.js +3 -1
  70. package/lib/yoke/adapters/claude.js +13 -7
  71. package/lib/yoke/adapters/codex.js +18 -5
  72. package/lib/yoke/adapters/permission-relay.js +9 -0
  73. package/lib/yoke/interface.js +7 -1
  74. package/package.json +1 -1
  75. package/scripts/check-test-count.js +1 -1
  76. package/scripts/install-local-test.js +45 -1
  77. package/scripts/postinstall.js +1 -0
package/README.md CHANGED
@@ -16,6 +16,18 @@
16
16
 
17
17
  Clagentic: Console is a self-hosted team workspace where human developers and named AI agents share the same interface. Multiple users connect to a single daemon, each with their own account and project access. Agents are first-class participants — not background processes you poll, but named entities with their own conversation history, context window, and session state, visible to the whole team. Every project, every session, every tool approval lives on your machine and stays there.
18
18
 
19
+ ## Agents are first-class users
20
+
21
+ Agents do not need a browser. From a shell, or from inside a console session, an agent can:
22
+
23
+ - **Open sessions:** `clagentic-console open-session --to reviewer@my-project --prompt "Review the open change."`
24
+ - **Message sessions:** `clagentic-console send-input --to builder@my-project --prompt "The build passed."` The input is pushed into the session, which is resumed first if it was reaped.
25
+ - **Reply:** `clagentic-console send-input --reply --prompt "Done."` answers whoever last messaged the calling session.
26
+ - **List sessions:** `clagentic-console list-sessions --state live` shows each session's state and any prompts it is waiting on.
27
+ - **Schedule input:** `clagentic-console schedule-input create --session 12 --project my-project --every 30m --count 4 --prompt "Check the build."` sends text into a session later, once or on a repeat that always has an end. People do the same from the clock button next to the message box.
28
+
29
+ Every injected message records who sent it, and an agent's message is never recorded as a human's. See the [agents guide](docs/guides/AGENT-GUIDE.md) for every verb and flag.
30
+
19
31
  ## Install
20
32
 
21
33
  ```bash
@@ -40,6 +52,8 @@ npx @clagentic/console
40
52
 
41
53
  On Linux, a global npm install runs a postinstall script that registers and enables a `clagentic-console.service` systemd unit. The script never restarts an already-running daemon — active sessions are not interrupted. Self-updates triggered from inside the app skip the restart entirely and let systemd's `Restart=always` handle the handoff after graceful shutdown.
42
54
 
55
+ The install never reads or writes your Claude Code settings. To let agents run `list-sessions`, `send-input` and `open-session` without permission prompts, add the suggested rules to `permissions.allow` in your own Claude Code settings; see [Suggested allow rules](docs/guides/AGENT-GUIDE.md#suggested-allow-rules), which also carries the migration note for the 1.10.x installer (#468) that used to add the `list-sessions` rule.
56
+
43
57
  To skip the postinstall script:
44
58
 
45
59
  ```bash
package/bin/cli.js CHANGED
@@ -80,7 +80,7 @@ if (args[0] === "release") {
80
80
  }
81
81
  }
82
82
 
83
- // --- `open-session` / `send-input`: drive a session through the running daemon ---
83
+ // --- `open-session` / `send-input` / `list-sessions`: drive a session through the running daemon ---
84
84
  // Positional verbs, handled before flag parsing: `clagentic-console send-input --project <slug> ...`.
85
85
  var { SESSION_VERBS, runSessionVerb } = require("../lib/cli/session-subcommands");
86
86
  if (SESSION_VERBS.indexOf(args[0]) !== -1) {
@@ -88,6 +88,11 @@ if (SESSION_VERBS.indexOf(args[0]) !== -1) {
88
88
  return;
89
89
  }
90
90
 
91
+ if (args[0] === "schedule-input") {
92
+ require("../lib/cli/schedule-input-subcommands").runScheduleInput(args.slice(1));
93
+ return;
94
+ }
95
+
91
96
  var port = _isDev ? 2635 : 2633;
92
97
  var useHttps = true;
93
98
  var forceMkcert = false;
@@ -172,8 +177,15 @@ for (var i = 0; i < args.length; i++) {
172
177
  console.log(" clagentic-console --list List registered projects");
173
178
  console.log(" clagentic-console --activity-diagnostics Print activity-divergence probe totals as JSON (agent-readable)");
174
179
  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)");
180
+ console.log(" clagentic-console open-session (--project <slug> | --to <address>) --prompt <text|-> [--vendor <id>] [--agent <name>] [--name <session-name>] [--visibility shared|private] [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>] Open a session and run a first prompt (prints JSON)");
181
+ console.log(" clagentic-console send-input (--project <slug> --session <id> | --to <address> | --reply) --prompt <text|-> [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>] Send input to a session, resuming it if needed (prints JSON; exit 3 ambiguous, 4 not found by address)");
182
+ console.log(" clagentic-console list-sessions [--project <slug>] [--agent <name>] [--vendor <id>] [--state live|idle|reaped|any] List the console's sessions (prints JSON)");
183
+ console.log(" clagentic-console schedule-input create --session <id> [--project <slug>] (--in <dur> | --at <time> | --every <dur> (--until <time> | --count <n>)) (--prompt <text|-> | --prompt-file <path>) Send text into a session later, once or on a repeat with an end (prints JSON)");
184
+ console.log(" clagentic-console schedule-input list [--session <id>] [--project <slug>] [--state armed|done|ended|any] List scheduled input, from the browser or the CLI (prints JSON)");
185
+ console.log(" clagentic-console schedule-input delete --id <id> [--project <slug>] Cancel a scheduled input");
186
+ console.log(" <dur> is minutes or parts like 90, 10m, 1h30m; <time> is a local HH:MM (a past one means tomorrow)");
187
+ console.log(" <address> is <agent>@<project>, <vendor>@<project> (a plain session) or @<project>, each with an optional /<session-name>");
188
+ console.log(" Several matches resolve live over idle over reaped; /<session-name> names one session exactly");
177
189
  console.log(" clagentic-console release list-betas List promotable beta versions (maintainer/release-engineering)");
178
190
  console.log(" clagentic-console daemon Run the daemon in the foreground (used by the systemd unit)");
179
191
  console.log("");
package/lib/agents.js CHANGED
@@ -76,58 +76,6 @@ function slugifyAgentName(name) {
76
76
  .slice(0, 64);
77
77
  }
78
78
 
79
- // lr-4c90 — Read the tools list for a named agent directly from its on-disk
80
- // frontmatter. The SDK AgentInfo surface (supportedAgents()) does not expose
81
- // the tools field — only name, description, and model are returned. Reading
82
- // the file directly is the only synchronous path for belt-and-suspenders
83
- // enforcement in the query setup path.
84
- //
85
- // agentName: the agent identity string (e.g. "agentic-director").
86
- // globalAgentsDir: optional override of AGENTS_SOURCE_DIR. On a shared
87
- // multi-user daemon, callers resolve the SESSION OWNER's home
88
- // (os-users.getLinuxUserHome(linuxUser)) and pass
89
- // path.join(thatHome, ".claude", "agents") here so the on-disk agent
90
- // definition is read from the invoking user's own home, not the daemon
91
- // process's REAL_HOME (lr-3ccc78 twin of the skill-discovery fix).
92
- // Returns: string[] of tool names if the tools field is a valid JSON array,
93
- // null if the file is absent, the frontmatter is missing, or the
94
- // tools field cannot be parsed.
95
- //
96
- // Failures are silent (logged at debug level) — callers treat null as "no
97
- // restriction from this source" and fall through to whatever the SDK applies
98
- // via claudeOpts.agent.
99
- function readAgentToolsFromFile(agentName, globalAgentsDir) {
100
- if (!agentName || typeof agentName !== "string") return null;
101
- var slug = slugifyAgentName(agentName);
102
- if (!slug) return null;
103
- var baseDir = (typeof globalAgentsDir === "string" && globalAgentsDir) ? globalAgentsDir : AGENTS_SOURCE_DIR;
104
- var filePath = path.join(baseDir, slug + ".md");
105
- var raw;
106
- try {
107
- raw = fs.readFileSync(filePath, "utf8");
108
- } catch (e) {
109
- // File not found is expected for agents with no on-disk definition.
110
- return null;
111
- }
112
- var parsed = parseFrontmatter(raw);
113
- if (!parsed || !parsed.meta) return null;
114
- var toolsVal = parsed.meta.tools;
115
- if (!toolsVal || typeof toolsVal !== "string") return null;
116
- var trimmed = toolsVal.trim();
117
- if (trimmed.charAt(0) !== "[") return null; // not a JSON array — skip
118
- try {
119
- var arr = JSON.parse(trimmed);
120
- if (!Array.isArray(arr)) return null;
121
- var result = [];
122
- for (var i = 0; i < arr.length; i++) {
123
- if (typeof arr[i] === "string" && arr[i]) result.push(arr[i]);
124
- }
125
- return result.length > 0 ? result : null;
126
- } catch (e) {
127
- return null;
128
- }
129
- }
130
-
131
79
  // --- SDK-backed discovery cache ---
132
80
 
133
81
  // Module-level cache. Populated by refresh(); read by getAll().
@@ -265,8 +213,7 @@ function _readAgentsFromDir(agentsDir) {
265
213
 
266
214
  // _globalAgentsDir is an optional override of the global agents directory.
267
215
  // Tests use it to point at a fixture dir; production callers on a shared
268
- // multi-user daemon pass the session owner's own ~/.claude/agents (see
269
- // readAgentToolsFromFile above, lr-3ccc78).
216
+ // multi-user daemon pass the session owner's own ~/.claude/agents.
270
217
  function readProjectAgents(projectDir, _globalAgentsDir) {
271
218
  if (!projectDir || typeof projectDir !== "string") return [];
272
219
 
@@ -299,7 +246,6 @@ module.exports = {
299
246
  AGENTS_SOURCE_DIR: AGENTS_SOURCE_DIR,
300
247
  parseFrontmatter: parseFrontmatter,
301
248
  slugifyAgentName: slugifyAgentName,
302
- readAgentToolsFromFile: readAgentToolsFromFile,
303
249
  readProjectAgents: readProjectAgents,
304
250
  // New SDK-backed surface:
305
251
  refresh: refresh,
@@ -0,0 +1,133 @@
1
+ // Per-command option ALLOWLISTS for the read-only Bash auto-approve.
2
+ //
3
+ // Every auto-approvable command declares the exact option tokens it accepts.
4
+ // A token that starts with "-" and is not exactly in the command's set means
5
+ // the call goes to the permission prompt. There is no prefix matching (GNU
6
+ // long options accept unique abbreviations, so "--outp" would reach "--output"
7
+ // if a denylist named only the full spelling) and a token like "-xyz" is never
8
+ // split into letters. A command that declares no options accepts none.
9
+ // Non-option tokens (paths, revisions) are allowed; the caller has already
10
+ // restricted every token to the character allowlist.
11
+ //
12
+ // When in doubt leave an option out: it only costs a prompt.
13
+
14
+ var DIGIT_OPTION_RE = /^-[0-9]+$/;
15
+
16
+ function opts(list) {
17
+ var set = {};
18
+ list.split(/\s+/).filter(Boolean).forEach(function (o) { set[o] = true; });
19
+ return set;
20
+ }
21
+
22
+ var GREP_OPTS = "-r -R -n -i -v -l -c -E -F -w -x -o -h -H -q -s -e -rn -ri -rl -rin -in -ni -nr -il -iv";
23
+
24
+ // name -> { opts: set, digits: true when "-<digits>" is accepted }
25
+ var COMMANDS = {
26
+ // Navigation
27
+ cd: {}, pushd: {}, popd: {},
28
+ // File and directory inspection
29
+ ls: { opts: opts("-l -a -la -al -h -lh -1 -R -t -r -A -lA -lah -ltr") },
30
+ cat: { opts: opts("-n") },
31
+ head: { opts: opts("-n -c"), digits: true },
32
+ wc: { opts: opts("-l -w -c -m") },
33
+ stat: {}, du: { opts: opts("-h -s -sh -c") }, df: { opts: opts("-h -T") },
34
+ readlink: {}, realpath: {}, basename: {}, dirname: {},
35
+ // Search
36
+ grep: { opts: opts(GREP_OPTS) },
37
+ fgrep: { opts: opts(GREP_OPTS) },
38
+ egrep: { opts: opts(GREP_OPTS) },
39
+ rg: { opts: opts("-n -i -l -c -w -F -v -t -e") },
40
+ // Lookup
41
+ which: { opts: opts("-a") }, type: { opts: opts("-a -t") }, whereis: {}, hash: {},
42
+ // Environment and system info
43
+ echo: { opts: opts("-n") }, printf: {}, printenv: {}, pwd: {},
44
+ whoami: {}, id: { opts: opts("-u -g -n") }, groups: {},
45
+ uname: { opts: opts("-a -r -m -s -n") }, uptime: { opts: opts("-p") }, arch: {},
46
+ nproc: {}, free: { opts: opts("-h -m -g") }, lsb_release: { opts: opts("-a") },
47
+ sw_vers: {}, locale: {},
48
+ // Text processing (stdin to stdout)
49
+ jq: { opts: opts("-r -c -s -n -e") },
50
+ cut: { opts: opts("-d -f -c -s") },
51
+ tr: { opts: opts("-d -s -c") },
52
+ paste: { opts: opts("-s -d") },
53
+ column: { opts: opts("-t -s") },
54
+ fold: { opts: opts("-w -s") },
55
+ rev: {}, tac: {}, nl: {}, expand: {}, unexpand: {},
56
+ fmt: {}, pr: {}, comm: { opts: opts("-1 -2 -3 -12 -13 -23") }, join: {},
57
+ // Comparison and hashing
58
+ diff: { opts: opts("-u -q -r -i -w -b") },
59
+ cmp: { opts: opts("-s -l") },
60
+ md5sum: { opts: opts("-c") }, sha256sum: { opts: opts("-c") }, sha1sum: { opts: opts("-c") },
61
+ shasum: { opts: opts("-c") }, cksum: {}, sum: {}, b2sum: { opts: opts("-c") },
62
+ base64: { opts: opts("-d") },
63
+ od: { opts: opts("-c -x") }, hexdump: { opts: opts("-C") },
64
+ // Misc read-only
65
+ test: { opts: opts("-e -f -d -r -w -x -s -z -n") }, "true": {}, "false": {}, seq: {},
66
+ sleep: {}, help: {}, apropos: {},
67
+ cal: { opts: opts("-y") }, bc: { opts: opts("-l") }, expr: {}, factor: {},
68
+ lsof: { opts: opts("-i -n -P") },
69
+ ps: { opts: opts("-e -f -ef -A") },
70
+ pgrep: { opts: opts("-f -l -a -x") },
71
+ netstat: { opts: opts("-a -n -l -t -u -p -r -tuln -tulnp -tlnp -an") },
72
+ dig: {}, nslookup: {}, host: {}, traceroute: {},
73
+ };
74
+
75
+ var GIT_SUBCOMMANDS = {
76
+ status: { opts: opts("-s --short -b --branch --porcelain") },
77
+ log: { opts: opts("--oneline -n --stat --graph --decorate"), digitsMax: 50 },
78
+ diff: { opts: opts("--stat --name-only --name-status --cached --staged") },
79
+ show: { opts: opts("--stat --name-only") },
80
+ };
81
+
82
+ // Whether every option token in args is declared by spec.
83
+ function optionsAllowed(args, spec, startIndex) {
84
+ var declared = spec.opts || {};
85
+ for (var i = startIndex; i < args.length; i++) {
86
+ var tok = args[i];
87
+ if (tok.charAt(0) !== "-") continue;
88
+ if (Object.prototype.hasOwnProperty.call(declared, tok)) continue;
89
+ if (DIGIT_OPTION_RE.test(tok)) {
90
+ if (spec.digitsMax) {
91
+ var n = parseInt(tok.slice(1), 10);
92
+ if (n >= 1 && n <= spec.digitsMax) continue;
93
+ } else if (spec.digits) {
94
+ continue;
95
+ }
96
+ }
97
+ return false;
98
+ }
99
+ return true;
100
+ }
101
+
102
+ // Commands whose whole argument form, not just the options, is fixed.
103
+ var EXACT_FORMS = {
104
+ // date -s sets the clock: only no argument or one +FORMAT.
105
+ date: function (args) {
106
+ return args.length === 0 || (args.length === 1 && args[0].charAt(0) === "+");
107
+ },
108
+ // hostname NAME renames the host; ifconfig with arguments configures an interface.
109
+ hostname: function (args) { return args.length === 0; },
110
+ ifconfig: function (args) { return args.length === 0; },
111
+ // "ip link set ..." and the rest write: only the two plain listings.
112
+ ip: function (args) {
113
+ return args.length === 1 && (args[0] === "addr" || args[0] === "route");
114
+ },
115
+ // Only the read-only subcommands; no remote, tag, branch (mutating forms).
116
+ git: function (args) {
117
+ if (args.length === 0) return false;
118
+ if (args[0] === "--version") return args.length === 1;
119
+ if (!Object.prototype.hasOwnProperty.call(GIT_SUBCOMMANDS, args[0])) return false;
120
+ return optionsAllowed(args, GIT_SUBCOMMANDS[args[0]], 1);
121
+ },
122
+ };
123
+
124
+ // tokens: the segment's words, command word first.
125
+ function isAutoApprovableSegment(tokens) {
126
+ var name = tokens[0];
127
+ if (!name) return false;
128
+ if (Object.prototype.hasOwnProperty.call(EXACT_FORMS, name)) return EXACT_FORMS[name](tokens.slice(1));
129
+ if (!Object.prototype.hasOwnProperty.call(COMMANDS, name)) return false;
130
+ return optionsAllowed(tokens.slice(1), COMMANDS[name], 0);
131
+ }
132
+
133
+ module.exports = { isAutoApprovableSegment: isAutoApprovableSegment };
@@ -66,12 +66,23 @@ function walkFiles(dir, relBase, fn) {
66
66
  }
67
67
  }
68
68
 
69
+ // lib/build-sha.json is the build's identity, compared by sha on its own. It also
70
+ // carries a `writtenAt` timestamp that prepack rewrites on every pack, so two
71
+ // packs of the same commit differ in exactly this file. Hashing it would make
72
+ // every same-sha reinstall look like a different build.
73
+ var IDENTITY_FILE = 'lib/build-sha.json';
74
+
69
75
  /**
70
76
  * 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
77
+ * package.json). `hash()` returns a hex digest of every file under lib/ (except
78
+ * the identity file above) plus package.json, or null when the tree cannot be read right now (an install in
73
79
  * progress removes files mid-walk). Per-file digests are remembered by
74
80
  * (inode, size, mtime), so a poll re-reads only files an install replaced.
81
+ *
82
+ * Known limit: a same-size rewrite of a file in place (same inode) that lands in
83
+ * the same filesystem timestamp tick as the previous hash() keeps the same
84
+ * key, so the old digest is reused. Real installs replace files with new
85
+ * inodes and are unaffected.
75
86
  */
76
87
  function createTreeHasher(packageRoot) {
77
88
  var known = new Map(); // abs path -> { key, digest }
@@ -98,7 +109,9 @@ function createTreeHasher(packageRoot) {
98
109
  seen.add(abs);
99
110
  outer.update(rel + '\0' + fileDigest(abs) + '\n');
100
111
  };
101
- walkFiles(path.join(packageRoot, 'lib'), 'lib', add);
112
+ walkFiles(path.join(packageRoot, 'lib'), 'lib', function (abs, rel) {
113
+ if (rel !== IDENTITY_FILE) add(abs, rel);
114
+ });
102
115
  add(path.join(packageRoot, 'package.json'), 'package.json');
103
116
  // Files that left the tree must not keep their remembered digest.
104
117
  known.forEach(function (_v, abs) { if (!seen.has(abs)) known.delete(abs); });
@@ -152,8 +165,13 @@ function assessBuild(loaded, installed) {
152
165
  return result(STATES.STALE, 'sha', 'the installed build (' + i.sha + ') is not the one this process loaded (' + l.sha + ')');
153
166
  }
154
167
  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);
168
+ // Same build id on both sides: a restart would load the build already
169
+ // running, so this is never offered. It is not "adopted" either (the files
170
+ // do differ), so it is reported as inconclusive, which the monitor journals
171
+ // and no client is told about.
172
+ return result(STATES.INCONCLUSIVE, 'same-sha-content-differs',
173
+ 'the installed files differ from the ones this process loaded, although both report build ' + l.sha +
174
+ '; a restart would load the same build id, so none is offered');
157
175
  }
158
176
  return result(STATES.ADOPTED, 'identical', 'the installed build is the one this process loaded');
159
177
  }
@@ -1,4 +1,4 @@
1
1
  {
2
- "sha": "3b16bd4528948b0e235f81c22553b390e1461821",
3
- "writtenAt": "2026-10-16T13:54:15.216Z"
2
+ "sha": "a4cb5e209eda16dbb89bf60fa906daf6c9ad402a",
3
+ "writtenAt": "2026-10-23T12:30:14.423Z"
4
4
  }
@@ -70,69 +70,7 @@ function checkForNewerInstalledBuild(opts) {
70
70
  };
71
71
  }
72
72
 
73
- /**
74
- * Bounded wait for in-flight sessions to finish, then invoke `onIdle()`.
75
- * Extracted out of lib/daemon.js's onRestartForBuildUpdate so this timing
76
- * logic is unit-testable without spinning up a real daemon process (the
77
- * daemon script itself has no other exported surface — see
78
- * test/daemon-bootstrap-guard.test.js's subprocess-spawn approach for why
79
- * that path is reserved for bootstrap-only cases, not routine logic).
80
- *
81
- * This is the ONLY thing standing between "operator clicked restart" and
82
- * "daemon actually restarts" — it never fires without that click (see
83
- * lib/project-sessions.js's restart_for_build_update handler, which is the
84
- * sole caller of the onRestartForBuildUpdate that wraps this). It exists so
85
- * that click does not also mean "drop whatever is running right now" when
86
- * waiting a bounded amount of time can avoid that.
87
- *
88
- * @param {object} opts
89
- * @param {function(): number} opts.getActiveCount — same shape as
90
- * drain.js's opts.getActiveCount (lib/sdk-bridge.js's getActiveLiveCount).
91
- * @param {function(): void} opts.onIdle — called exactly once, either when
92
- * getActiveCount() reaches <= 0 or when the timeout elapses.
93
- * @param {number} [opts.timeoutMs] — defaults to DEFAULT_RESTART_WAIT_MS.
94
- * @param {number} [opts.pollIntervalMs] — defaults to 1000.
95
- * @param {function(function(): void, number): void} [opts.setTimeoutFn] —
96
- * injectable for tests (default: a thin wrapper over the global
97
- * setTimeout). Called as setTimeoutFn(fn, delayMs); must invoke fn with no
98
- * arguments after that delay, same contract as the global setTimeout.
99
- * @param {function(): number} [opts.nowMs] — injectable for tests (default
100
- * Date.now).
101
- */
102
- var DEFAULT_RESTART_WAIT_MS = 60 * 1000;
103
-
104
- function waitForIdleThenAct(opts) {
105
- var o = opts || {};
106
- if (typeof o.getActiveCount !== 'function') {
107
- throw new Error('waitForIdleThenAct: opts.getActiveCount must be a function');
108
- }
109
- if (typeof o.onIdle !== 'function') {
110
- throw new Error('waitForIdleThenAct: opts.onIdle must be a function');
111
- }
112
- var timeoutMs = (typeof o.timeoutMs === 'number' && o.timeoutMs > 0) ? o.timeoutMs : DEFAULT_RESTART_WAIT_MS;
113
- var pollIntervalMs = (typeof o.pollIntervalMs === 'number' && o.pollIntervalMs > 0) ? o.pollIntervalMs : 1000;
114
- var now = typeof o.nowMs === 'function' ? o.nowMs : Date.now;
115
- var scheduleFn = typeof o.setTimeoutFn === 'function' ? o.setTimeoutFn : function (fn, delay) { setTimeout(fn, delay); };
116
-
117
- var deadline = now() + timeoutMs;
118
- var acted = false;
119
-
120
- function tick() {
121
- if (acted) return; // idempotent — a stray extra tick must never double-fire
122
- if (o.getActiveCount() <= 0 || now() >= deadline) {
123
- acted = true;
124
- o.onIdle();
125
- return;
126
- }
127
- scheduleFn(tick, pollIntervalMs);
128
- }
129
-
130
- tick();
131
- }
132
-
133
73
  module.exports = {
134
74
  readInstalledBuildSha: readInstalledBuildSha,
135
75
  checkForNewerInstalledBuild: checkForNewerInstalledBuild,
136
- waitForIdleThenAct: waitForIdleThenAct,
137
- DEFAULT_RESTART_WAIT_MS: DEFAULT_RESTART_WAIT_MS,
138
76
  };
@@ -66,18 +66,12 @@ function collectInterruptions(projects) {
66
66
  };
67
67
  }
68
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
69
  function plural(n, word) {
76
70
  return n + ' ' + word + (n === 1 ? '' : 's');
77
71
  }
78
72
 
79
73
  /** The operator-facing statement of what a restart ends. */
80
- function describeInterruptions(i, waitSeconds) {
74
+ function describeInterruptions(i) {
81
75
  if (i.sessionCount === 0) {
82
76
  return 'No session is live, so the restart ends nothing that is running.';
83
77
  }
@@ -92,7 +86,7 @@ function describeInterruptions(i, waitSeconds) {
92
86
  : '';
93
87
  lines.push('- [' + s.slug + '] ' + s.title + ' (' + state + agents + ')');
94
88
  });
95
- lines.push('Running turns and agents get up to ' + waitSeconds + ' seconds to finish first. ' +
89
+ lines.push('Restarting ends these sessions and any that start before the restart happens. ' +
96
90
  'Ended sessions resume when you send them a message.');
97
91
  return lines.join('\n');
98
92
  }
@@ -117,7 +111,7 @@ function buildOffer(o) {
117
111
  sessionCount: o.interruptions.sessionCount,
118
112
  agentCount: o.interruptions.agentCount,
119
113
  };
120
- offer.interruptionText = describeInterruptions(o.interruptions, o.waitSeconds);
114
+ offer.interruptionText = describeInterruptions(o.interruptions);
121
115
  }
122
116
  if (o.token) offer.token = o.token;
123
117
  return offer;
@@ -126,9 +120,7 @@ function buildOffer(o) {
126
120
  /** One line naming both builds, for the notice and the log. */
127
121
  function summarizeOffer(a) {
128
122
  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) + '.';
123
+ return 'Running build ' + short(a.loadedBuildSha) + '; installed build ' + short(a.installedBuildSha) + '.';
132
124
  }
133
125
 
134
126
  var DEFAULT_NOTICE_COOLDOWN_MS = 60 * 60 * 1000;
@@ -157,12 +149,30 @@ function composeNotice(assessment, changes, cooldownMs) {
157
149
  };
158
150
  }
159
151
 
152
+ // The restart-pending state is its own source so withdrawing the offer
153
+ // (source build-update) never removes it. `persistent` tells the client not to
154
+ // close it on a timer: it stays until the restarted daemon replaces the page.
155
+ var RESTARTING_SOURCE = 'build-update-restart';
156
+
157
+ /** The one message that stands in for the offer while a confirmed restart is pending. */
158
+ function composeRestartingNotice() {
159
+ return {
160
+ type: 'diagnostic',
161
+ severity: 'warning',
162
+ source: RESTARTING_SOURCE,
163
+ persistent: true,
164
+ message: 'Restarting Clagentic: Console to apply the installed update. This page reconnects when ' +
165
+ 'it is back. Nothing more to confirm.',
166
+ };
167
+ }
168
+
160
169
  module.exports = {
170
+ RESTARTING_SOURCE: RESTARTING_SOURCE,
171
+ composeRestartingNotice: composeRestartingNotice,
161
172
  DEFAULT_NOTICE_COOLDOWN_MS: DEFAULT_NOTICE_COOLDOWN_MS,
162
173
  noticeCooldownFrom: noticeCooldownFrom,
163
174
  composeNotice: composeNotice,
164
175
  collectInterruptions: collectInterruptions,
165
- coveredBy: coveredBy,
166
176
  describeInterruptions: describeInterruptions,
167
177
  buildOffer: buildOffer,
168
178
  summarizeOffer: summarizeOffer,
@@ -7,18 +7,18 @@
7
7
  // 1. request() with no token answers with the offer: both builds, the commits
8
8
  // between them, and the live sessions and background agents a restart now
9
9
  // would end. It restarts nothing.
10
- // 2. request(token) with the token from that offer. The restart is scheduled
11
- // only when the offer is still true: the installed build is the one
12
- // offered, and nothing is live now that the operator was not shown. If
13
- // anything changed, a fresh offer is returned instead and the operator
14
- // confirms again.
15
- // A running turn is given a bounded time to finish; when the restart finally
16
- // fires, it re-checks the same condition and cancels if a session started
17
- // after the operator confirmed.
10
+ // 2. request(token) with the token from that offer. A known, unexpired,
11
+ // unspent token schedules the restart. The confirm card is the consent and
12
+ // says that sessions and turns starting before the restart end with it, so
13
+ // a changed session set is journaled and does not refuse the click.
14
+ // The confirmed restart fires at once. The second step's card already names the
15
+ // sessions and agents it ends, so that card is the guard; there is no further
16
+ // wait. From the confirm until the process exits the restart is pending and a
17
+ // repeat request returns that state instead of offering again.
18
18
 
19
19
  var crypto = require('crypto');
20
20
 
21
- var { collectInterruptions, coveredBy, buildOffer } = require('./build-update-offer');
21
+ var { collectInterruptions, buildOffer } = require('./build-update-offer');
22
22
 
23
23
  var OFFER_TTL_MS = 10 * 60 * 1000;
24
24
  var MAX_OUTSTANDING_OFFERS = 20;
@@ -29,16 +29,14 @@ var MAX_OUTSTANDING_OFFERS = 20;
29
29
  * @param {function(): Array<{slug: string, sm: object}>} o.getProjects
30
30
  * @param {function(object): Promise<object>} o.listChanges — ({fromSha, toSha}) -> changes
31
31
  * @param {function(): void} o.restart — performs the restart; called only after confirmation
32
- * @param {function(function, object): void} o.waitForIdleThenAct — build-update-check's
33
- * @param {function(string): void} o.announce — tells every client why a confirmed restart was cancelled
32
+ * @param {function(): void} [o.onScheduled] — called once, just before the restart
33
+ * is performed, so clients can swap the offer for the restarting state
34
34
  * @param {function(string): void} [o.log]
35
- * @param {number} [o.waitMs] — how long running turns get to finish
36
35
  * @param {function(): number} [o.nowMs]
37
36
  */
38
37
  function createBuildUpdateRestart(o) {
39
38
  var log = typeof o.log === 'function' ? o.log : function () {};
40
39
  var now = typeof o.nowMs === 'function' ? o.nowMs : Date.now;
41
- var waitMs = o.waitMs > 0 ? o.waitMs : 60 * 1000;
42
40
  var offers = new Map(); // token -> { keys, installedKey, expires }
43
41
  var restarting = false;
44
42
 
@@ -76,16 +74,23 @@ function createBuildUpdateRestart(o) {
76
74
  assessment: assessment,
77
75
  changes: changes,
78
76
  interruptions: interruptions,
79
- waitSeconds: Math.round(waitMs / 1000),
80
77
  token: token,
81
78
  });
82
79
  return { status: 'confirm', offer: offer, note: note || null };
83
80
  }
84
81
 
85
- function stillCovered(offered, assessment) {
86
- var a = assessment;
87
- return a.state === 'stale' && installedKeyOf(a) === offered.installedKey
88
- && coveredBy(collectInterruptions(o.getProjects()).keys, offered.keys);
82
+ // Names what differs between the offer the operator saw and now, for the journal.
83
+ function describeChange(offered, assessment) {
84
+ var parts = [];
85
+ if (installedKeyOf(assessment) !== offered.installedKey) parts.push('a different build was installed');
86
+ var was = new Set(offered.keys);
87
+ var nowKeys = collectInterruptions(o.getProjects()).keys;
88
+ var is = new Set(nowKeys);
89
+ var added = nowKeys.filter(function (k) { return !was.has(k); });
90
+ var gone = offered.keys.filter(function (k) { return !is.has(k); });
91
+ if (added.length) parts.push('now live and not offered: ' + added.join(', '));
92
+ if (gone.length) parts.push('offered and no longer live: ' + gone.join(', '));
93
+ return parts.join('; ');
89
94
  }
90
95
 
91
96
  /**
@@ -94,6 +99,15 @@ function createBuildUpdateRestart(o) {
94
99
  * status: 'not_stale' | 'confirm' | 'restarting'
95
100
  */
96
101
  async function request(token) {
102
+ // A restart is a one-way door: once confirmed, any further request (a second
103
+ // tab, a card that was still on screen, a replayed frame) gets the pending
104
+ // state back. It never issues another offer, so the operator is not asked to
105
+ // confirm twice, and it never restarts a second time.
106
+ if (restarting) {
107
+ offers.delete(token);
108
+ log('Restart request ignored: a confirmed restart is already pending');
109
+ return { status: 'restarting', already: true };
110
+ }
97
111
  var assessment = o.assess();
98
112
  if (assessment.state !== 'stale') {
99
113
  return { status: 'not_stale', assessment: assessment };
@@ -103,37 +117,39 @@ function createBuildUpdateRestart(o) {
103
117
 
104
118
  var offered = offers.get(token);
105
119
  offers.delete(token); // one confirmation per offer
120
+ // A confirmation that restarts nothing must leave a journal line: without
121
+ // one, a click answered by a fresh offer is indistinguishable from a click
122
+ // that never arrived.
106
123
  if (!offered || offered.expires <= now()) {
124
+ log('Restart confirmation not applied: the offer was unknown or expired; issuing a fresh one');
107
125
  return issueOffer(assessment, 'That offer expired. Review the current one.');
108
126
  }
109
- if (!stillCovered(offered, assessment)) {
110
- return issueOffer(assessment,
111
- 'Something changed since you opened the offer (a build or a live session). Review the current one.');
112
- }
113
- if (restarting) return { status: 'restarting' };
114
127
  restarting = true;
128
+ // The confirm card is the consent, and it says sessions and turns that start
129
+ // before the restart end with it. A changed set is journaled, never refused.
130
+ var changed = describeChange(offered, assessment);
131
+ if (changed) log('Restart confirmed after the offer changed (' + changed + '); proceeding');
115
132
  log('Operator confirmed restart to adopt build ' + assessment.installedBuildSha +
116
- '; waiting up to ' + Math.round(waitMs / 1000) + 's for running turns');
133
+ '; restarting now');
117
134
 
118
- o.waitForIdleThenAct({
119
- getActiveCount: function () {
120
- var i = collectInterruptions(o.getProjects());
121
- return i.processingCount + i.agentCount;
122
- },
123
- timeoutMs: waitMs,
124
- onIdle: function () {
125
- var fresh = o.assess();
126
- if (!stillCovered(offered, fresh)) {
127
- restarting = false;
128
- log('Confirmed restart cancelled: the installed build or the live sessions changed after confirmation');
129
- o.announce('The restart you confirmed was cancelled because the installed build or the live ' +
130
- 'sessions changed while it waited. Nothing was restarted. Open the update offer again to review it.');
131
- return;
132
- }
133
- o.restart();
134
- },
135
- });
136
- return { status: 'restarting', waitSeconds: Math.round(waitMs / 1000) };
135
+ // Everyone's restart card is withdrawn and replaced by the one pending state
136
+ // before the restart begins.
137
+ if (typeof o.onScheduled === 'function') {
138
+ try {
139
+ o.onScheduled();
140
+ } catch (e) {
141
+ log('Could not announce the pending restart: ' + (e && e.message ? e.message : e));
142
+ }
143
+ }
144
+ // The pending guard stays set until the process exits. A restart that throws
145
+ // leaves nothing pending, so the operator can ask again.
146
+ try {
147
+ o.restart();
148
+ } catch (e) {
149
+ restarting = false;
150
+ throw e;
151
+ }
152
+ return { status: 'restarting' };
137
153
  }
138
154
 
139
155
  return { request: request };