@clagentic/console 1.9.0 → 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 (172) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +9 -3
  5. package/bin/cli.js +40 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/agent-dispatch-tool.js +20 -0
  8. package/lib/audit.js +3 -2
  9. package/lib/build-changes.js +79 -0
  10. package/lib/build-identity.js +192 -0
  11. package/lib/build-monitor.js +125 -0
  12. package/lib/build-sha.json +2 -2
  13. package/lib/build-update-check.js +138 -0
  14. package/lib/build-update-offer.js +141 -0
  15. package/lib/build-update-restart.js +142 -0
  16. package/lib/build-update-standing.js +184 -0
  17. package/lib/cli/daemon-launch.js +25 -22
  18. package/lib/cli/ipc-subcommands.js +6 -0
  19. package/lib/cli/session-subcommands.js +122 -0
  20. package/lib/cli-sessions.js +8 -1
  21. package/lib/codex-defaults.js +8 -2
  22. package/lib/config.js +32 -20
  23. package/lib/daemon-env-settings.js +84 -0
  24. package/lib/daemon-projects.js +57 -0
  25. package/lib/daemon.js +288 -205
  26. package/lib/drain.js +74 -17
  27. package/lib/env-compat.js +61 -0
  28. package/lib/extension-commands.js +45 -0
  29. package/lib/history-visibility.js +4 -0
  30. package/lib/idle-adapter-reaper.js +71 -0
  31. package/lib/link-trap.js +78 -0
  32. package/lib/mcp-local.js +8 -6
  33. package/lib/mcp-tool-input.js +116 -0
  34. package/lib/mcp-tool-schema.js +179 -0
  35. package/lib/memory-limits.js +61 -5
  36. package/lib/memory-setting-validate.js +65 -0
  37. package/lib/memory-shed.js +13 -32
  38. package/lib/new-work-gate.js +47 -0
  39. package/lib/os-users.js +5 -3
  40. package/lib/project-access.js +139 -0
  41. package/lib/project-connection.js +37 -22
  42. package/lib/project-external-trigger.js +166 -105
  43. package/lib/project-file-scope.js +172 -0
  44. package/lib/project-file-watch.js +86 -61
  45. package/lib/project-filesystem.js +144 -128
  46. package/lib/project-git.js +119 -0
  47. package/lib/project-http.js +44 -28
  48. package/lib/project-loop.js +17 -9
  49. package/lib/project-mcp.js +53 -72
  50. package/lib/project-message-gate.js +70 -0
  51. package/lib/project-notifications.js +31 -4
  52. package/lib/project-prompt-responses.js +217 -0
  53. package/lib/project-sessions.js +192 -355
  54. package/lib/project-user-message.js +27 -15
  55. package/lib/project.js +212 -147
  56. package/lib/projects-dir.js +90 -0
  57. package/lib/prompt-access.js +22 -0
  58. package/lib/prompt-kinds/answer-limits.js +15 -0
  59. package/lib/prompt-kinds/ask-user.js +58 -0
  60. package/lib/prompt-kinds/codecs.js +97 -0
  61. package/lib/prompt-kinds/elicitation.js +77 -0
  62. package/lib/prompt-kinds/extension.js +39 -0
  63. package/lib/prompt-kinds/index.js +68 -0
  64. package/lib/prompt-kinds/permission.js +114 -0
  65. package/lib/prompt-kinds/plan.js +79 -0
  66. package/lib/prompt-kinds/tool-call.js +38 -0
  67. package/lib/prompt-registry.js +680 -0
  68. package/lib/public/app.js +1 -1
  69. package/lib/public/css/diagnostics.css +80 -0
  70. package/lib/public/css/input.css +17 -3
  71. package/lib/public/css/menus.css +10 -0
  72. package/lib/public/css/messages.css +5 -0
  73. package/lib/public/css/rewind.css +22 -0
  74. package/lib/public/index.html +4 -12
  75. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  76. package/lib/public/modules/app-connection.js +7 -0
  77. package/lib/public/modules/app-cursors.js +7 -5
  78. package/lib/public/modules/app-messages.js +52 -47
  79. package/lib/public/modules/app-notifications.js +47 -71
  80. package/lib/public/modules/app-panels.js +61 -59
  81. package/lib/public/modules/app-projects.js +2 -1
  82. package/lib/public/modules/app-rendering.js +4 -10
  83. package/lib/public/modules/build-update-detail.js +54 -0
  84. package/lib/public/modules/diagnostics.js +170 -20
  85. package/lib/public/modules/filebrowser.js +18 -16
  86. package/lib/public/modules/history-visibility.js +4 -0
  87. package/lib/public/modules/mention.js +3 -2
  88. package/lib/public/modules/mode-options.js +38 -0
  89. package/lib/public/modules/project-settings.js +19 -8
  90. package/lib/public/modules/prompt-banner.js +78 -0
  91. package/lib/public/modules/prompt-card.js +201 -0
  92. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  93. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  94. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  95. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  96. package/lib/public/modules/prompt-kinds/index.js +18 -0
  97. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  98. package/lib/public/modules/prompt-kinds/package.json +3 -0
  99. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  100. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  101. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  102. package/lib/public/modules/prompt-state.js +142 -0
  103. package/lib/public/modules/prompts.js +134 -0
  104. package/lib/public/modules/rewind.js +4 -1
  105. package/lib/public/modules/server-settings.js +2 -4
  106. package/lib/public/modules/sidebar-mobile.js +19 -9
  107. package/lib/public/modules/sidebar-sessions.js +21 -14
  108. package/lib/public/modules/sticky-notes.js +3 -2
  109. package/lib/public/modules/team-panel.js +5 -4
  110. package/lib/public/modules/tools.js +81 -906
  111. package/lib/public/modules/vendor-picker.js +53 -0
  112. package/lib/public/modules/vendor-registry.js +142 -0
  113. package/lib/public/sw.js +3 -1
  114. package/lib/rc-migrate.js +44 -0
  115. package/lib/runtime-env-keys.js +109 -0
  116. package/lib/runtime-env.js +236 -0
  117. package/lib/sdk-bridge.js +348 -284
  118. package/lib/sdk-message-processor.js +117 -146
  119. package/lib/sdk-skill-discovery.js +65 -60
  120. package/lib/server-hub-sessions.js +13 -10
  121. package/lib/server-palette.js +28 -19
  122. package/lib/server.js +156 -115
  123. package/lib/service-install.js +96 -0
  124. package/lib/session-capabilities.js +76 -0
  125. package/lib/session-id.js +33 -0
  126. package/lib/session-input-ipc.js +32 -0
  127. package/lib/session-input.js +379 -0
  128. package/lib/session-reclaim.js +284 -0
  129. package/lib/session-resume.js +172 -0
  130. package/lib/sessions.js +61 -30
  131. package/lib/supervisor.js +39 -0
  132. package/lib/turn-initiator.js +108 -0
  133. package/lib/users-permissions.js +9 -6
  134. package/lib/users.js +9 -0
  135. package/lib/utils.js +4 -2
  136. package/lib/vendor-auth.js +22 -0
  137. package/lib/vendor-registry-message.js +66 -0
  138. package/lib/ws-origin.js +99 -0
  139. package/lib/ws-schema.js +36 -23
  140. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  141. package/lib/yoke/adapters/claude-vendor.js +34 -0
  142. package/lib/yoke/adapters/claude-worker.js +57 -87
  143. package/lib/yoke/adapters/claude.js +182 -88
  144. package/lib/yoke/adapters/codex-capabilities.js +40 -0
  145. package/lib/yoke/adapters/codex-vendor.js +46 -0
  146. package/lib/yoke/adapters/codex.js +462 -211
  147. package/lib/yoke/adapters/effort-control.js +34 -0
  148. package/lib/yoke/adapters/permission-relay.js +58 -0
  149. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  150. package/lib/yoke/auth-checks.js +91 -0
  151. package/lib/yoke/capabilities.js +49 -0
  152. package/lib/yoke/codex-app-server.js +30 -56
  153. package/lib/yoke/codex-binary.js +254 -0
  154. package/lib/yoke/codex-command.js +122 -0
  155. package/lib/yoke/codex-protocol.js +96 -0
  156. package/lib/yoke/codex-version.js +135 -0
  157. package/lib/yoke/env-ownership.js +40 -0
  158. package/lib/yoke/index.js +84 -174
  159. package/lib/yoke/install-probe.js +136 -0
  160. package/lib/yoke/instructions.js +7 -11
  161. package/lib/yoke/interface.js +206 -4
  162. package/lib/yoke/package.json +1 -1
  163. package/lib/yoke/provider-credentials.js +96 -0
  164. package/lib/yoke/registry.js +377 -0
  165. package/package.json +12 -9
  166. package/scripts/check-sdk-lock-drift.js +160 -0
  167. package/scripts/check-test-count.js +76 -1
  168. package/scripts/postinstall.js +218 -136
  169. package/scripts/prompt-harness-history.js +202 -0
  170. package/scripts/verify-installed-build.js +59 -17
  171. package/scripts/verify-installed.js +67 -0
  172. package/lib/sdk-permission-ownership.js +0 -136
@@ -5,9 +5,15 @@ var { execFileSync, execFile } = require("child_process");
5
5
  var { CODEX_DEFAULTS, getCodexConfig } = require("./codex-defaults");
6
6
  var liteDetect = require("./lite-detect");
7
7
  var { readMemAvailableMB } = require("./sdk-bridge");
8
+ var { getNewWorkRefusal } = require("./new-work-gate");
8
9
  var agentsModule = require("./agents");
9
10
  var agentsFavorites = require("./agents-favorites");
10
11
  var sessionActivity = require("./session-activity");
12
+ var { promptsFor } = require("./prompt-registry");
13
+ var { attachPromptResponses } = require("./project-prompt-responses");
14
+ var { ownValue } = require("./prompt-kinds/codecs");
15
+ var { isKnownVendor } = require("./yoke");
16
+ var sessionCapabilities = require("./session-capabilities");
11
17
  // Kick off SDK agent discovery in the background at module load.
12
18
  // Errors are swallowed inside refresh(); the cache starts empty and fills
13
19
  // when the SDK subprocess completes initialization (~9s on this box).
@@ -31,33 +37,6 @@ if (!process.env.NODE_TEST_CONTEXT) {
31
37
  });
32
38
  }
33
39
 
34
- // Format a user's answer to an ask_user_questions card as a plain user
35
- // message so the MCP path can feed it back to the agent on the next turn.
36
- // Always use "- Q → A" form and prefix with a header so the model can
37
- // connect the answer to its earlier AskUserQuestion call even across a
38
- // turn break. A bare answer with no context reads as a non-sequitur and
39
- // triggers "I don't see an answer" responses from the model.
40
- function formatAskUserAnswerAsMessage(input, answers) {
41
- var questions = (input && Array.isArray(input.questions)) ? input.questions : [];
42
- if (questions.length === 0) {
43
- // Shouldn't happen, but be defensive.
44
- try { return "(answered with: " + JSON.stringify(answers || {}) + ")"; }
45
- catch (e) { return "(answered)"; }
46
- }
47
- var lines = [];
48
- for (var i = 0; i < questions.length; i++) {
49
- var q = questions[i];
50
- var qText = (q && q.question) ? q.question : ("Question " + (i + 1));
51
- var ans = (answers && answers[i] != null) ? String(answers[i]) : "";
52
- if (!ans) continue;
53
- lines.push("- " + qText + " → " + ans);
54
- }
55
- if (lines.length === 0) return "(no answer provided)";
56
- // Prefix tells the model this is a structured answer to its previous
57
- // AskUserQuestion call — unambiguous even when read out of turn context.
58
- return "[Answer to your AskUserQuestion]\n" + lines.join("\n");
59
- }
60
-
61
40
  /**
62
41
  * Attach session management, config, project management, and mid-section
63
42
  * message handlers to a project context.
@@ -99,6 +78,13 @@ var PROCESS_STATS_BASE_FIELD_KEYS = [
99
78
  "memAvailableMB",
100
79
  ];
101
80
 
81
+ // auto and dontAsk are permission modes only a vendor that lists them in
82
+ // capabilities.permissionModes can run. A session whose vendor does not
83
+ // declare them (or whose capabilities are not known yet) cannot, so a request
84
+ // for one is refused rather than handed to a vendor that would reject or
85
+ // ignore it.
86
+ var CAPABILITY_GATED_MODES = { auto: true, dontAsk: true };
87
+
102
88
  function attachSessions(ctx) {
103
89
  var cwd = ctx.cwd;
104
90
  var slug = ctx.slug;
@@ -115,6 +101,7 @@ function attachSessions(ctx) {
115
101
  var sendToSessionOthers = ctx.sendToSessionOthers;
116
102
  var opts = ctx.opts;
117
103
  var usersModule = ctx.usersModule;
104
+ var projectAccess = ctx.projectAccess;
118
105
  var userPresence = ctx.userPresence;
119
106
  var pushModule = ctx.pushModule;
120
107
  var getSessionForWs = ctx.getSessionForWs;
@@ -124,6 +111,13 @@ function attachSessions(ctx) {
124
111
  var hydrateImageRefs = ctx.hydrateImageRefs;
125
112
  var onProcessingChanged = ctx.onProcessingChanged;
126
113
  var broadcastPresence = ctx.broadcastPresence;
114
+
115
+ // The Linux user a connection runs as, or null for the daemon's own account
116
+ // (OS users off, or a user with no Linux account).
117
+ function osIdentityOf(socket) {
118
+ if (!osUsers || !socket._clagenticUser || !socket._clagenticUser.linuxUser) return null;
119
+ return socket._clagenticUser.linuxUser;
120
+ }
127
121
  var adapter = ctx.adapter;
128
122
  var getProjectList = ctx.getProjectList;
129
123
  var getProjectCount = ctx.getProjectCount;
@@ -145,9 +139,27 @@ function attachSessions(ctx) {
145
139
  var setLatestVersion = ctx.setLatestVersion;
146
140
  var loadContextSources = ctx.loadContextSources;
147
141
  var saveContextSources = ctx.saveContextSources;
142
+ var promptResponses = attachPromptResponses({
143
+ sm: sm,
144
+ sdk: sdk,
145
+ send: send,
146
+ sendTo: sendTo,
147
+ sendToSession: sendToSession,
148
+ getSessionForWs: getSessionForWs,
149
+ onProcessingChanged: onProcessingChanged,
150
+ ensureProjectAccessForSession: ensureProjectAccessForSession,
151
+ });
152
+
153
+ function sessionAcceptsMode(session, mode) {
154
+ if (!ownValue(CAPABILITY_GATED_MODES, mode)) return true;
155
+ var vendor = sessionCapabilities.effectiveVendorId(sm, session, adapter && adapter.vendor);
156
+ return sessionCapabilities.capabilitiesFor(sm, vendor).permissionModes.indexOf(mode) !== -1;
157
+ }
148
158
 
149
159
  function handleSessionsMessage(ws, msg) {
150
160
 
161
+ if (promptResponses.handlePromptMessage(ws, msg)) return true;
162
+
151
163
  if (msg.type === "push_subscribe") {
152
164
  var _pushUserId = ws._clagenticUser ? ws._clagenticUser.id : null;
153
165
  if (pushModule && msg.subscription) pushModule.addSubscription(msg.subscription, msg.replaceEndpoint, _pushUserId);
@@ -185,14 +197,20 @@ function attachSessions(ctx) {
185
197
  heapFrom = sm.extendWindowForVisibility(session.history, heapFrom, heapBefore);
186
198
  from = baseIndex + heapFrom;
187
199
  to = before;
188
- items = session.history.slice(heapFrom, heapBefore).map(hydrateImageRefs);
200
+ var annotateHeap = promptsFor(sm).replayAnnotator(session, session.history, heapFrom);
201
+ items = session.history.slice(heapFrom, heapBefore).map(function (it) {
202
+ return hydrateImageRefs(annotateHeap(it));
203
+ });
189
204
  } else {
190
205
  var diskHistory = sm.readSessionHistoryFromDisk(session);
191
206
  var diskFrom = sm.findTurnBoundary(diskHistory, Math.max(0, targetFrom));
192
207
  diskFrom = sm.extendWindowForVisibility(diskHistory, diskFrom, before);
193
208
  from = diskFrom;
194
209
  to = before;
195
- items = diskHistory.slice(diskFrom, before).map(hydrateImageRefs);
210
+ var annotateDisk = promptsFor(sm).replayAnnotator(session, diskHistory, diskFrom);
211
+ items = diskHistory.slice(diskFrom, before).map(function (it) {
212
+ return hydrateImageRefs(annotateDisk(it));
213
+ });
196
214
  }
197
215
  sendTo(ws, {
198
216
  type: "history_prepend",
@@ -203,10 +221,15 @@ function attachSessions(ctx) {
203
221
  }
204
222
 
205
223
  if (msg.type === "new_session") {
224
+ var newSessionRefusal = getNewWorkRefusal();
225
+ if (newSessionRefusal) {
226
+ sendTo(ws, { type: "toast", level: "warn", message: newSessionRefusal, duration: 8000 });
227
+ return true;
228
+ }
206
229
  var sessionOpts = {};
207
230
  if (ws._clagenticUser) sessionOpts.ownerId = ws._clagenticUser.id;
208
231
  if (msg.sessionVisibility) sessionOpts.sessionVisibility = msg.sessionVisibility;
209
- if (msg.vendor) sessionOpts.vendor = msg.vendor;
232
+ if (isKnownVendor(msg.vendor)) sessionOpts.vendor = msg.vendor;
210
233
  if (msg.agentName && typeof msg.agentName === "string") {
211
234
  sessionOpts.agentName = msg.agentName;
212
235
  try { agentsFavorites.touchRecent({ name: msg.agentName }); }
@@ -411,6 +434,14 @@ function attachSessions(ctx) {
411
434
 
412
435
  if (msg.type === "bulk_delete_sessions") {
413
436
  if (!Array.isArray(msg.sessionIds) || msg.sessionIds.length === 0) return true;
437
+ // Same permission as delete_session; the per-session access check below is not a substitute.
438
+ if (ws._clagenticUser) {
439
+ var bulkPerms = usersModule.getEffectivePermissions(ws._clagenticUser, osUsers);
440
+ if (!bulkPerms.sessionDelete) {
441
+ sendTo(ws, { type: "error", text: "You do not have permission to delete sessions" });
442
+ return true;
443
+ }
444
+ }
414
445
  var deletableIds = [];
415
446
  for (var di = 0; di < msg.sessionIds.length; di++) {
416
447
  var bulkId = msg.sessionIds[di];
@@ -457,60 +488,13 @@ function attachSessions(ctx) {
457
488
 
458
489
  if (msg.type === "resume_session") {
459
490
  if (!msg.cliSessionId) return true;
460
- var cliSess = require("./cli-sessions");
461
-
462
- // If Clay already has a persisted meta file for this cliSessionId, read
463
- // its vendor so resumeSession doesn't silently default to the project's
464
- // primary vendor (which would break codex sessions after server restart).
465
- // Also read allowedTools (lr-8b2e) so a previously-granted "allow for
466
- // session" decision survives this rehydration path instead of
467
- // re-prompting — resumeSession() itself defaults to {} when absent.
468
- var persistedVendor = null;
469
- var persistedAllowedTools = null;
470
- try {
471
- var _fsResume = require("fs");
472
- var _pathResume = require("path");
473
- var metaPath = _pathResume.join(sm.sessionsDir, msg.cliSessionId + ".jsonl");
474
- if (_fsResume.existsSync(metaPath)) {
475
- var firstLine = _fsResume.readFileSync(metaPath, "utf8").split("\n", 1)[0];
476
- try {
477
- var metaObj = JSON.parse(firstLine);
478
- if (metaObj && metaObj.type === "meta" && metaObj.vendor) persistedVendor = metaObj.vendor;
479
- // Sanitize before it ever reaches resumeSession() (lr-8b2e
480
- // hardening) — a crafted meta record must not be able to
481
- // auto-approve a tool with no operator click.
482
- if (metaObj && metaObj.type === "meta" && metaObj.allowedTools) {
483
- persistedAllowedTools = utils.sanitizeAllowedTools(metaObj.allowedTools);
484
- }
485
- } catch (e) {}
486
- }
487
- } catch (e) {}
488
-
489
- // Try SDK for title first, then fall back to manual parsing
490
- var titlePromise = adapter.getSessionInfo(msg.cliSessionId, { dir: cwd }).then(function(info) {
491
- return (info && info.summary) ? info.summary.substring(0, 100) : null;
492
- }).catch(function() { return null; });
493
-
494
- Promise.all([
495
- cliSess.readCliSessionHistory(cwd, msg.cliSessionId),
496
- titlePromise
497
- ]).then(function(results) {
498
- var history = results[0];
499
- var sdkTitle = results[1];
500
- var title = sdkTitle || "Resumed session";
501
- if (!sdkTitle) {
502
- for (var i = 0; i < history.length; i++) {
503
- if (history[i].type === "user_message" && history[i].text) {
504
- title = history[i].text.substring(0, 50);
505
- break;
506
- }
507
- }
508
- }
509
- var resumed = sm.resumeSession(msg.cliSessionId, { history: history, title: title, vendor: persistedVendor || undefined, allowedTools: persistedAllowedTools || undefined }, ws);
510
- if (resumed) ws._clagenticActiveSession = resumed.localId;
511
- }).catch(function() {
512
- var resumed = sm.resumeSession(msg.cliSessionId, (persistedVendor || persistedAllowedTools) ? { vendor: persistedVendor, allowedTools: persistedAllowedTools } : undefined, ws);
491
+ // The resume that injected input uses too (session-resume.js): vendor,
492
+ // agent and granted tools come from the stored meta record, so a resume
493
+ // never silently falls back to the project's default vendor.
494
+ require("./session-resume").resumeStoredSession({ sm: sm, adapter: adapter, cwd: cwd }, msg.cliSessionId, { ws: ws }).then(function (resumed) {
513
495
  if (resumed) ws._clagenticActiveSession = resumed.localId;
496
+ }, function (err) {
497
+ sendTo(ws, { type: "error", text: "Could not resume this session: " + (err && err.message ? err.message : err) });
514
498
  });
515
499
  return true;
516
500
  }
@@ -569,7 +553,7 @@ function attachSessions(ctx) {
569
553
  var switchTargetSess = sm.sessions.get(msg.id);
570
554
  if (switchTargetSess && sm.currentModel) {
571
555
  var targetVendor = switchTargetSess.vendor || sm.defaultVendor || null;
572
- var tvModels = (targetVendor && sm.modelsByVendor && sm.modelsByVendor[targetVendor]) || [];
556
+ var tvModels = (targetVendor && sm.modelsByVendor && ownValue(sm.modelsByVendor, targetVendor)) || [];
573
557
  var found = false;
574
558
  var _curLc = sm.currentModel.toLowerCase();
575
559
  for (var tvi = 0; tvi < tvModels.length; tvi++) {
@@ -620,14 +604,15 @@ function attachSessions(ctx) {
620
604
  return true;
621
605
  }
622
606
  }
623
- if (msg.id && sm.sessions.has(msg.id)) {
607
+ // The permission to delete is not access to this particular session.
608
+ if (msg.id && sm.sessions.has(msg.id) && projectAccess.canReadSession(ws._clagenticUser, sm.sessions.get(msg.id), projectAccess.authOf(ws))) {
624
609
  sm.deleteSession(msg.id, ws);
625
610
  }
626
611
  return true;
627
612
  }
628
613
 
629
614
  if (msg.type === "rename_session") {
630
- if (msg.id && sm.sessions.has(msg.id) && msg.title) {
615
+ if (msg.id && sm.sessions.has(msg.id) && msg.title && projectAccess.canReadSession(ws._clagenticUser, sm.sessions.get(msg.id), projectAccess.authOf(ws))) {
631
616
  var s = sm.sessions.get(msg.id);
632
617
  s.title = String(msg.title).substring(0, 100);
633
618
  s.titleManuallySet = true;
@@ -644,17 +629,25 @@ function attachSessions(ctx) {
644
629
  }
645
630
 
646
631
  if (msg.type === "search_sessions") {
647
- var results = sm.searchSessions(msg.query || "");
648
- sendTo(ws, { type: "search_results", query: msg.query || "", results: results });
632
+ // Sessions the caller cannot read are skipped before anything is read from
633
+ // them, so neither their titles nor whether their content matches is revealed.
634
+ var searchQuery = typeof msg.query === "string" ? msg.query : "";
635
+ var results = sm.searchSessions(searchQuery, function (candidate) {
636
+ return projectAccess.canReadSession(ws._clagenticUser, candidate, projectAccess.authOf(ws));
637
+ });
638
+ sendTo(ws, { type: "search_results", query: searchQuery, results: results });
649
639
  return true;
650
640
  }
651
641
 
652
642
  if (msg.type === "search_session_content") {
653
643
  var targetSession = msg.id ? sm.sessions.get(msg.id) : getSessionForWs(ws);
654
644
  if (!targetSession) return true;
655
- var contentResults = sm.searchSessionContent(targetSession.localId, msg.query || "");
656
- var searchResp = { type: "search_content_results", query: msg.query || "", sessionId: targetSession.localId, hits: contentResults.hits, total: contentResults.total };
657
- if (msg.source) searchResp.source = msg.source;
645
+ if (!projectAccess.canReadSession(ws._clagenticUser, targetSession, projectAccess.authOf(ws))) return true;
646
+ // Same coercion as search_sessions: only a string query is searched or echoed.
647
+ var contentQuery = typeof msg.query === "string" ? msg.query : "";
648
+ var contentResults = sm.searchSessionContent(targetSession.localId, contentQuery);
649
+ var searchResp = { type: "search_content_results", query: contentQuery, sessionId: targetSession.localId, hits: contentResults.hits, total: contentResults.total };
650
+ if (typeof msg.source === "string" && msg.source) searchResp.source = msg.source;
658
651
  sendTo(ws, searchResp);
659
652
  return true;
660
653
  }
@@ -838,7 +831,26 @@ function attachSessions(ctx) {
838
831
  return true;
839
832
  }
840
833
 
834
+ // The user installed or signed in to an agent while the daemon was running.
835
+ // Install state belongs to an OS identity: the lookup runs as the requester,
836
+ // and the refreshed registry goes to every client of that same identity
837
+ // (every client of the project when OS users are off), never to another.
838
+ if (msg.type === "recheck_vendors") {
839
+ var recheckIdentity = osIdentityOf(ws);
840
+ var refreshed = sdk.recheckVendors(recheckIdentity);
841
+ clients.forEach(function (client) {
842
+ if (osIdentityOf(client) === recheckIdentity) sendTo(client, refreshed);
843
+ });
844
+ return true;
845
+ }
846
+
841
847
  if (msg.type === "set_vendor" && msg.vendor) {
848
+ // A vendor the daemon cannot build is no vendor: nothing is bound,
849
+ // looked up or echoed for it.
850
+ if (!isKnownVendor(msg.vendor)) {
851
+ sendTo(ws, { type: "error", text: "Unknown vendor" });
852
+ return true;
853
+ }
842
854
  var vendorSession = getSessionForWs(ws);
843
855
  if (vendorSession) {
844
856
  // Refuse to rebind vendor on a session that is already bound to a
@@ -863,12 +875,15 @@ function attachSessions(ctx) {
863
875
  if (sm.currentModel) {
864
876
  sm.currentModel = "";
865
877
  }
866
- // Agent sessions are Claude Code-only. If the user somehow switches
867
- // vendor to Codex on a session that carries agentName (e.g. via a
868
- // direct WS message), clear the agent identity so the badge doesn't
869
- // misrepresent an identity that Codex cannot apply.
870
- if (msg.vendor === "codex" && vendorSession.agentName) {
871
- console.warn("[project] set_vendor to codex on agent session " + vendorSession.localId +
878
+ // A named agent identity needs the agentInjection capability. If the
879
+ // user somehow switches to a vendor without it on a session that
880
+ // carries agentName (e.g. via a direct WS message), clear the agent
881
+ // identity so the badge doesn't misrepresent an identity that vendor
882
+ // cannot apply.
883
+ // Decided on the resolved capabilities, the same set the agent
884
+ // injection guard in sdk-bridge reads, so the two cannot disagree.
885
+ if (vendorSession.agentName && !sessionCapabilities.capabilitiesFor(sm, msg.vendor).agentInjection) {
886
+ console.warn("[project] set_vendor to " + msg.vendor + " on agent session " + vendorSession.localId +
872
887
  " — clearing agentName '" + vendorSession.agentName + "'");
873
888
  vendorSession.agentName = null;
874
889
  }
@@ -877,14 +892,13 @@ function attachSessions(ctx) {
877
892
  }
878
893
  }
879
894
  if (msg.vendor) {
880
- var vendorModels = (sm.modelsByVendor && sm.modelsByVendor[msg.vendor]) || [];
895
+ var vendorModels = (sm.modelsByVendor && ownValue(sm.modelsByVendor, msg.vendor)) || [];
881
896
  sendTo(ws, {
882
897
  type: "model_info",
883
898
  model: "",
884
899
  models: vendorModels,
885
900
  vendor: msg.vendor,
886
901
  availableVendors: sm.availableVendors || [],
887
- installedVendors: sm.installedVendors || [],
888
902
  });
889
903
  // lr-041af8: targeted, not broadcast — set_vendor acts on the
890
904
  // requesting client's own session (vendorSession above); broadcasting
@@ -929,6 +943,11 @@ function attachSessions(ctx) {
929
943
 
930
944
  if (msg.type === "set_permission_mode" && msg.mode) {
931
945
  var session = getSessionForWs(ws);
946
+ if (session && !sessionAcceptsMode(session, msg.mode)) {
947
+ sendTo(ws, { type: "error", text: "This session's agent does not support the " + String(msg.mode).slice(0, 40) + " permission mode" });
948
+ sendTo(ws, { type: "config_state", model: sm.effectiveSessionModel(session), mode: session.permissionMode || sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
949
+ return true;
950
+ }
932
951
  if (session) {
933
952
  sdk.setPermissionMode(session, msg.mode).then(function () {
934
953
  // Targeted reply — only update the requesting client's chip.
@@ -967,12 +986,23 @@ function attachSessions(ctx) {
967
986
  }
968
987
 
969
988
  if (msg.type === "set_effort" && msg.effort) {
970
- sm.currentEffort = msg.effort;
971
989
  var session = getSessionForWs(ws);
972
- if (session) {
973
- sdk.setEffort(session, msg.effort);
990
+ if (!session) {
991
+ sm.currentEffort = msg.effort;
992
+ send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
993
+ return true;
974
994
  }
975
- send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort, betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
995
+ // The effort is recorded only once the running query has taken it
996
+ // (sdk.setEffort announces it then). A refused change is reported by the
997
+ // bridge as an error; the requester's picker is put back on the effort
998
+ // the session still runs at.
999
+ sdk.setEffort(session, msg.effort).then(function (result) {
1000
+ var state = { type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 };
1001
+ if (result && result.ok === false) sendTo(ws, state);
1002
+ else send(state);
1003
+ }).catch(function (err) {
1004
+ console.error("[project-sessions] set_effort failed:", (err && err.message) || err);
1005
+ });
976
1006
  return true;
977
1007
  }
978
1008
 
@@ -1105,6 +1135,19 @@ function attachSessions(ctx) {
1105
1135
  }
1106
1136
  }
1107
1137
 
1138
+ // Notify adapter of conversation rollback (e.g. Codex, which refuses)
1139
+ // BEFORE trimming: when the adapter cannot roll its thread back, the
1140
+ // rewind fails (the catch below reports it) and the local history is
1141
+ // left as it was, so the two never disagree.
1142
+ if (turnsToRollBack > 0) {
1143
+ try {
1144
+ await sdk.rollbackConversation(session, turnsToRollBack);
1145
+ } catch (rbErr) {
1146
+ sm.retrimHistory(session);
1147
+ throw rbErr;
1148
+ }
1149
+ }
1150
+
1108
1151
  if (targetIdx >= 0) {
1109
1152
  var trimTo = session.messageUUIDs[targetIdx].historyIndex;
1110
1153
  for (var k = trimTo - 1; k >= 0; k--) {
@@ -1126,15 +1169,6 @@ function attachSessions(ctx) {
1126
1169
  // extra bookkeeping needed here.
1127
1170
  }
1128
1171
 
1129
- // Notify adapter of conversation rollback (e.g. Codex thread/rollback)
1130
- if (turnsToRollBack > 0) {
1131
- try {
1132
- await sdk.rollbackConversation(session, turnsToRollBack);
1133
- } catch (rbErr) {
1134
- console.error("[project-sessions] conversation rollback failed:", rbErr.message || rbErr);
1135
- }
1136
- }
1137
-
1138
1172
  var kept = session.messageUUIDs;
1139
1173
  session.lastRewindUuid = kept.length > 0 ? kept[kept.length - 1].uuid : null;
1140
1174
  // lr-2ea2a7: re-apply the bounded tail cap now that the trim/save
@@ -1153,8 +1187,7 @@ function attachSessions(ctx) {
1153
1187
  session.abortController = null;
1154
1188
  session.blocks = {};
1155
1189
  session.sentToolResults = {};
1156
- session.pendingPermissions = {};
1157
- session.pendingAskUser = {};
1190
+ promptsFor(sm).cancelSession(session, "rewind");
1158
1191
  // lr-9bcd7b: a rewind destroys the in-flight query outright (the
1159
1192
  // queryInstance null-out above), so nothing can genuinely still be
1160
1193
  // running for this session afterward. Unlike the reconciliation
@@ -1258,74 +1291,6 @@ function attachSessions(ctx) {
1258
1291
  return true;
1259
1292
  }
1260
1293
 
1261
- if (msg.type === "ask_user_response") {
1262
- var session = getSessionForWs(ws);
1263
- if (!session) return true;
1264
- var toolId = msg.toolId;
1265
- var answers = msg.answers || {};
1266
- var pending = session.pendingAskUser[toolId];
1267
- if (!pending) return true;
1268
- delete session.pendingAskUser[toolId];
1269
- sm.sendAndRecord(session, { type: "ask_user_answered", toolId: toolId, answers: answers });
1270
-
1271
- if (pending.mode === "mcp") {
1272
- // Stateless MCP path: the tool already returned. Inject the user's
1273
- // answer as a new user message so the conversation continues
1274
- // naturally on the next turn. This matches how the mate would see
1275
- // any other user input.
1276
- var answerText = formatAskUserAnswerAsMessage(pending.input, answers);
1277
- var userMsg = { type: "user_message", text: answerText };
1278
- // lr-2ea2a7: routes through the shared history-cap helper (see grep-guard test).
1279
- sm.recordHistoryEntry(session, userMsg, true);
1280
- sm.appendToSessionFile(session, userMsg);
1281
- sendToSession(session.localId, userMsg);
1282
-
1283
- if (!session.isProcessing) {
1284
- session.isProcessing = true;
1285
- onProcessingChanged();
1286
- session.sentToolResults = {};
1287
- sendToSession(session.localId, { type: "status", status: "processing" });
1288
- if (!session.queryInstance && !session.worker) {
1289
- sdk.startQuery(session, answerText, undefined, ensureProjectAccessForSession(session));
1290
- } else {
1291
- sdk.pushMessage(session, answerText);
1292
- }
1293
- } else {
1294
- // Turn is still running; queue for the next turn.
1295
- sdk.pushMessage(session, answerText);
1296
- }
1297
- } else {
1298
- // Claude native AskUserQuestion path (canUseTool). The SDK is
1299
- // synchronously blocked on the permission callback, so we must
1300
- // resolve it with the standard permission shape.
1301
- //
1302
- // The CLI's AskUserQuestion tool expects answers keyed by question
1303
- // TEXT (e.g. {"What is your goal?": "Build a widget"}), not by
1304
- // numeric index. Clay's client sends index-keyed answers
1305
- // ({"0": "Build a widget"}). Remap here before passing to the CLI.
1306
- //
1307
- // Both camelCase (updatedInput) and snake_case (updated_input) are
1308
- // included: the SDK passes the object through as-is and the stdio
1309
- // permission handler reads the snake_case key.
1310
- var questions = (pending.input && Array.isArray(pending.input.questions))
1311
- ? pending.input.questions : [];
1312
- var textKeyedAnswers = {};
1313
- for (var qi = 0; qi < questions.length; qi++) {
1314
- var qText = questions[qi] && questions[qi].question;
1315
- if (qText && answers[qi] != null) {
1316
- textKeyedAnswers[qText] = answers[qi];
1317
- }
1318
- }
1319
- var updatedInput = Object.assign({}, pending.input, { answers: textKeyedAnswers });
1320
- pending.resolve({
1321
- behavior: "allow",
1322
- updatedInput: updatedInput,
1323
- updated_input: updatedInput,
1324
- });
1325
- }
1326
- return true;
1327
- }
1328
-
1329
1294
  if (msg.type === "input_sync") {
1330
1295
  sendToSessionOthers(ws, ws._clagenticActiveSession, msg);
1331
1296
  return true;
@@ -1355,177 +1320,6 @@ function attachSessions(ctx) {
1355
1320
  return true;
1356
1321
  }
1357
1322
 
1358
- if (msg.type === "permission_response") {
1359
- var requestId = msg.requestId;
1360
- var decision = msg.decision;
1361
- // Look up session by requestId index (O(1)), fall back to active session
1362
- var sessionId = sm.permissionRequestIndex[requestId];
1363
- var session = sessionId ? sm.sessions.get(sessionId) : getSessionForWs(ws);
1364
- if (!session) return true;
1365
- var pending = session.pendingPermissions[requestId];
1366
- if (!pending) return true;
1367
- delete sm.permissionRequestIndex[requestId];
1368
- delete session.pendingPermissions[requestId];
1369
- onProcessingChanged(); // update cross-project permission badge
1370
-
1371
- // --- Plan approval: "allow_accept_edits" -- approve + switch to acceptEdits mode ---
1372
- if (decision === "allow_accept_edits") {
1373
- sdk.setPermissionMode(session, "acceptEdits");
1374
- sm.currentPermissionMode = "acceptEdits";
1375
- send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode, effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
1376
- pending.resolve({ behavior: "allow", updatedInput: pending.toolInput });
1377
- sm.sendAndRecord(session, { type: "permission_resolved", requestId: requestId, decision: decision });
1378
- return true;
1379
- }
1380
-
1381
- // --- Plan approval: "allow_clear_context" -- new session + plan as first message + acceptEdits ---
1382
- if (decision === "allow_clear_context") {
1383
- // Deny current plan to end the turn
1384
- pending.resolve({ behavior: "deny", message: "User chose to clear context and restart" });
1385
- sm.sendAndRecord(session, { type: "permission_resolved", requestId: requestId, decision: decision });
1386
-
1387
- // Abort the old session's query -- but defer to next tick so the SDK's
1388
- // deny write (scheduled as microtask by pending.resolve) completes first.
1389
- // Aborting synchronously would kill the subprocess before the write,
1390
- // causing an "Operation aborted" crash in the SDK.
1391
- session.isProcessing = false;
1392
- onProcessingChanged();
1393
- session.pendingPermissions = {};
1394
- session.pendingAskUser = {};
1395
- sm.broadcastSessionList();
1396
- setImmediate(function () {
1397
- if (session.abortController) {
1398
- session.abortController.abort();
1399
- }
1400
- });
1401
-
1402
- // Update permission mode for the new session
1403
- sm.currentPermissionMode = "acceptEdits";
1404
- send({ type: "config_state", model: sm.currentModel || "", mode: sm.currentPermissionMode, effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
1405
-
1406
- // Build prompt from plan content (sent from client) or plan file path
1407
- var clientPlanContent = msg.planContent || "";
1408
- var planPrompt;
1409
- if (clientPlanContent) {
1410
- planPrompt = "Execute the following plan. Do NOT re-enter plan mode -- just implement it step by step.\n\n" + clientPlanContent;
1411
- } else {
1412
- var planFilePath = (pending.toolInput && pending.toolInput.planFilePath) || "";
1413
- planPrompt = "Execute the plan in " + planFilePath + ". Do NOT re-enter plan mode -- read the plan file and implement it step by step.";
1414
- }
1415
-
1416
- // Wait for old query stream to fully terminate, then create new session + send plan
1417
- var oldStreamPromise = session.streamPromise || Promise.resolve();
1418
- Promise.race([
1419
- oldStreamPromise,
1420
- new Promise(function (resolve) { setTimeout(resolve, 3000); }),
1421
- ]).then(function () {
1422
- try {
1423
- var newSession = sm.createSession(null, ws);
1424
- // Send the plan as the first user message (with planContent for UI rendering)
1425
- var userMsg = { type: "user_message", text: planPrompt, planContent: clientPlanContent || null };
1426
- // lr-2ea2a7: routes through the shared history-cap helper (see grep-guard test).
1427
- sm.recordHistoryEntry(newSession, userMsg, true);
1428
- sm.appendToSessionFile(newSession, userMsg);
1429
- newSession.title = "Plan execution (cleared context)";
1430
- sm.saveSessionFile(newSession);
1431
- sm.broadcastSessionList();
1432
- sendToSession(newSession.localId, userMsg);
1433
-
1434
- newSession.isProcessing = true;
1435
- onProcessingChanged();
1436
- newSession.sentToolResults = {};
1437
- sendToSession(newSession.localId, { type: "status", status: "processing" });
1438
- newSession.acceptEditsAfterStart = true;
1439
- sdk.startQuery(newSession, planPrompt, undefined, ensureProjectAccessForSession(newSession));
1440
- } catch (e) {
1441
- console.error("[project] Error starting plan execution:", e);
1442
- sendTo(ws, { type: "error", text: "Failed to start plan execution: " + (e.message || e) });
1443
- }
1444
- }).catch(function (e) {
1445
- console.error("[project] Plan execution stream wait failed:", e.message || e);
1446
- });
1447
- return true;
1448
- }
1449
-
1450
- // --- Plan approval: "deny_with_feedback" -- deny + send feedback as follow-up message ---
1451
- if (decision === "deny_with_feedback") {
1452
- var feedback = msg.feedback || "";
1453
- pending.resolve({ behavior: "deny", message: feedback || "User provided feedback" });
1454
- sm.sendAndRecord(session, { type: "permission_resolved", requestId: requestId, decision: decision });
1455
-
1456
- // Send feedback as next user message if there's text
1457
- if (feedback) {
1458
- setTimeout(function () {
1459
- var userMsg = { type: "user_message", text: feedback };
1460
- // lr-2ea2a7: routes through the shared history-cap helper (see grep-guard test).
1461
- sm.recordHistoryEntry(session, userMsg, true);
1462
- sm.appendToSessionFile(session, userMsg);
1463
- sendToSession(session.localId, userMsg);
1464
-
1465
- if (!session.isProcessing) {
1466
- session.isProcessing = true;
1467
- onProcessingChanged();
1468
- session.sentToolResults = {};
1469
- sendToSession(session.localId, { type: "status", status: "processing" });
1470
- if (!session.queryInstance && !session.worker) {
1471
- sdk.startQuery(session, feedback, undefined, ensureProjectAccessForSession(session));
1472
- } else {
1473
- sdk.pushMessage(session, feedback);
1474
- }
1475
- } else {
1476
- sdk.pushMessage(session, feedback);
1477
- }
1478
- }, 200);
1479
- }
1480
- return true;
1481
- }
1482
-
1483
- if (decision === "allow" || decision === "allow_always") {
1484
- if (decision === "allow_always") {
1485
- if (!session.allowedTools) session.allowedTools = {};
1486
- // lr-f969dc: keyed on toolName + input discriminator (not bare
1487
- // toolName) so a Skill grant scopes to the specific skill that was
1488
- // actually approved rather than silently authorizing every skill.
1489
- session.allowedTools[utils.permissionGrantKey(pending.toolName, pending.toolInput)] = true;
1490
- // Flush immediately (lr-8b2e) so the grant survives daemon restart /
1491
- // resume-by-cliSessionId rehydration even without a later save
1492
- // trigger — previously this lived only in the in-memory session
1493
- // object and was lost on rebuild, causing a spurious re-prompt.
1494
- sm.saveSessionFile(session);
1495
- }
1496
- pending.resolve({ behavior: "allow", updatedInput: pending.toolInput });
1497
- } else {
1498
- pending.resolve({ behavior: "deny", message: "User denied permission" });
1499
- }
1500
-
1501
- sm.sendAndRecord(session, {
1502
- type: "permission_resolved",
1503
- requestId: requestId,
1504
- decision: decision,
1505
- });
1506
- return true;
1507
- }
1508
-
1509
- // --- MCP elicitation response ---
1510
- if (msg.type === "elicitation_response") {
1511
- var session = getSessionForWs(ws);
1512
- if (!session) return true;
1513
- var pending = session.pendingElicitations && session.pendingElicitations[msg.requestId];
1514
- if (!pending) return true;
1515
- delete session.pendingElicitations[msg.requestId];
1516
- if (msg.action === "accept") {
1517
- pending.resolve({ action: "accept", content: msg.content || {} });
1518
- } else {
1519
- pending.resolve({ action: "reject" });
1520
- }
1521
- sm.sendAndRecord(session, {
1522
- type: "elicitation_resolved",
1523
- requestId: msg.requestId,
1524
- action: msg.action,
1525
- });
1526
- return true;
1527
- }
1528
-
1529
1323
  // --- Browse directories (for add-project autocomplete) ---
1530
1324
  if (msg.type === "browse_dir") {
1531
1325
  var rawPath = (msg.path || "").replace(/^~/, require("./config").REAL_HOME);
@@ -1728,7 +1522,8 @@ function attachSessions(ctx) {
1728
1522
  var moveResult = moveScheduleToProject(msg.recordId, msg.fromSlug, msg.toSlug);
1729
1523
  if (moveResult.ok) {
1730
1524
  // Re-broadcast updated records to this project's clients
1731
- send({ type: "loop_registry_updated", records: getHubSchedules() });
1525
+ if (typeof ctx.broadcastHubSchedules === "function") ctx.broadcastHubSchedules();
1526
+ else send({ type: "loop_registry_updated", records: getHubSchedules(null) });
1732
1527
  }
1733
1528
  sendTo(ws, { type: "schedule_move_result", ok: moveResult.ok, error: moveResult.error });
1734
1529
  return true;
@@ -1873,7 +1668,7 @@ function attachSessions(ctx) {
1873
1668
  msg.type === "set_auto_continue" || msg.type === "set_image_retention" || msg.type === "set_mem_available_threshold" ||
1874
1669
  msg.type === "set_tokens_per_mb_headroom" ||
1875
1670
  msg.type === "set_lite_auto_enroll" ||
1876
- msg.type === "shutdown_server" || msg.type === "restart_server") {
1671
+ msg.type === "shutdown_server" || msg.type === "restart_server" || msg.type === "restart_for_build_update") {
1877
1672
  var _wsUser = ws._clagenticUser;
1878
1673
  if (!_wsUser || _wsUser.role !== "admin") {
1879
1674
  // lr-93e3c8 (fnd-66af4e, item 7): app-messages.js's client-side
@@ -1998,6 +1793,48 @@ function attachSessions(ctx) {
1998
1793
  return true;
1999
1794
  }
2000
1795
 
1796
+ // Operator-initiated adoption of an installed-but-not-yet-running build.
1797
+ // Same admin gate as restart_server above, but two steps, because this
1798
+ // restart ends sessions the operator may not be thinking about. A message
1799
+ // without confirmToken only asks for the offer: the reply names both
1800
+ // builds, the commits between them and the live sessions and background
1801
+ // agents a restart would end, and nothing restarts. The restart is
1802
+ // scheduled only by a message carrying the token of an offer the daemon
1803
+ // issued, and only if that offer is still true (lib/build-update-restart.js).
1804
+ if (msg.type === "restart_for_build_update") {
1805
+ if (typeof opts.onRestartForBuildUpdate !== "function") {
1806
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, error: "Restart not supported" });
1807
+ return true;
1808
+ }
1809
+ var buildToken = typeof msg.confirmToken === "string" ? msg.confirmToken : null;
1810
+ Promise.resolve(opts.onRestartForBuildUpdate(buildToken)).then(function (outcome) {
1811
+ if (outcome.status === "not_stale") {
1812
+ var nothingToApply = "No newer build is installed, so there is nothing to apply.";
1813
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, error: nothingToApply });
1814
+ sendTo(ws, { type: "error", text: nothingToApply });
1815
+ } else if (outcome.status === "confirm") {
1816
+ var offer = outcome.offer;
1817
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, needsConfirmation: true });
1818
+ sendTo(ws, {
1819
+ type: "diagnostic",
1820
+ severity: "warning",
1821
+ source: "build-update",
1822
+ message: (outcome.note ? outcome.note + "\n" : "") + offer.interruptionText,
1823
+ buildUpdate: offer,
1824
+ actionable: { label: "Restart now", action: "confirm_build_update_restart" },
1825
+ });
1826
+ } else {
1827
+ sendTo(ws, { type: "restart_for_build_update_result", ok: true });
1828
+ send({ type: "toast", level: "info", message: "Restarting to apply the installed update. Running turns get up to " + (outcome.waitSeconds || 60) + " seconds to finish first." });
1829
+ }
1830
+ }).catch(function (e) {
1831
+ console.error("[project] restart_for_build_update failed:", e && e.message ? e.message : e);
1832
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, error: "Could not prepare the restart offer" });
1833
+ sendTo(ws, { type: "error", text: "Could not prepare the restart offer. Nothing was restarted." });
1834
+ });
1835
+ return true;
1836
+ }
1837
+
2001
1838
  // --- Clagentic: Lite integration WS messages ---
2002
1839
 
2003
1840
  // get_lite_project_status — responds with lite_project_status { enrolled: bool }