@clagentic/console 1.9.0 → 1.10.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 (146) 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 +8 -2
  5. package/bin/cli.js +30 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/audit.js +3 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-check.js +138 -0
  10. package/lib/cli/daemon-launch.js +17 -17
  11. package/lib/config.js +32 -20
  12. package/lib/daemon-env-settings.js +84 -0
  13. package/lib/daemon-projects.js +38 -0
  14. package/lib/daemon.js +202 -158
  15. package/lib/drain.js +74 -17
  16. package/lib/env-compat.js +61 -0
  17. package/lib/extension-commands.js +45 -0
  18. package/lib/history-visibility.js +4 -0
  19. package/lib/idle-adapter-reaper.js +71 -0
  20. package/lib/link-trap.js +78 -0
  21. package/lib/lore-attestation.js +73 -0
  22. package/lib/mcp-local.js +8 -6
  23. package/lib/mcp-tool-input.js +116 -0
  24. package/lib/mcp-tool-schema.js +179 -0
  25. package/lib/memory-limits.js +61 -5
  26. package/lib/memory-setting-validate.js +65 -0
  27. package/lib/new-work-gate.js +47 -0
  28. package/lib/os-users.js +5 -3
  29. package/lib/project-access.js +139 -0
  30. package/lib/project-connection.js +23 -22
  31. package/lib/project-external-trigger.js +103 -10
  32. package/lib/project-file-scope.js +172 -0
  33. package/lib/project-file-watch.js +86 -61
  34. package/lib/project-filesystem.js +144 -128
  35. package/lib/project-git.js +119 -0
  36. package/lib/project-http.js +44 -28
  37. package/lib/project-loop.js +12 -5
  38. package/lib/project-mcp.js +53 -72
  39. package/lib/project-message-gate.js +70 -0
  40. package/lib/project-notifications.js +31 -4
  41. package/lib/project-prompt-responses.js +216 -0
  42. package/lib/project-sessions.js +164 -302
  43. package/lib/project-user-message.js +36 -11
  44. package/lib/project.js +189 -142
  45. package/lib/projects-dir.js +90 -0
  46. package/lib/prompt-access.js +22 -0
  47. package/lib/prompt-kinds/answer-limits.js +15 -0
  48. package/lib/prompt-kinds/ask-user.js +58 -0
  49. package/lib/prompt-kinds/codecs.js +97 -0
  50. package/lib/prompt-kinds/elicitation.js +77 -0
  51. package/lib/prompt-kinds/extension.js +39 -0
  52. package/lib/prompt-kinds/index.js +68 -0
  53. package/lib/prompt-kinds/permission.js +114 -0
  54. package/lib/prompt-kinds/plan.js +79 -0
  55. package/lib/prompt-kinds/tool-call.js +38 -0
  56. package/lib/prompt-registry.js +673 -0
  57. package/lib/public/app.js +1 -1
  58. package/lib/public/css/diagnostics.css +50 -0
  59. package/lib/public/css/input.css +17 -3
  60. package/lib/public/css/menus.css +10 -0
  61. package/lib/public/css/messages.css +5 -0
  62. package/lib/public/css/rewind.css +22 -0
  63. package/lib/public/index.html +4 -12
  64. package/lib/public/modules/app-connection.js +7 -0
  65. package/lib/public/modules/app-cursors.js +7 -5
  66. package/lib/public/modules/app-messages.js +45 -45
  67. package/lib/public/modules/app-notifications.js +47 -71
  68. package/lib/public/modules/app-panels.js +61 -58
  69. package/lib/public/modules/app-projects.js +2 -1
  70. package/lib/public/modules/app-rendering.js +4 -10
  71. package/lib/public/modules/diagnostics.js +60 -16
  72. package/lib/public/modules/filebrowser.js +18 -16
  73. package/lib/public/modules/history-visibility.js +4 -0
  74. package/lib/public/modules/mention.js +3 -2
  75. package/lib/public/modules/mode-options.js +38 -0
  76. package/lib/public/modules/project-settings.js +19 -8
  77. package/lib/public/modules/prompt-banner.js +78 -0
  78. package/lib/public/modules/prompt-card.js +201 -0
  79. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  80. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  81. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  82. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  83. package/lib/public/modules/prompt-kinds/index.js +18 -0
  84. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  85. package/lib/public/modules/prompt-kinds/package.json +3 -0
  86. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  87. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  88. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  89. package/lib/public/modules/prompt-state.js +142 -0
  90. package/lib/public/modules/prompts.js +134 -0
  91. package/lib/public/modules/rewind.js +4 -1
  92. package/lib/public/modules/server-settings.js +2 -4
  93. package/lib/public/modules/sidebar-mobile.js +19 -9
  94. package/lib/public/modules/sidebar-sessions.js +21 -14
  95. package/lib/public/modules/sticky-notes.js +3 -2
  96. package/lib/public/modules/team-panel.js +5 -4
  97. package/lib/public/modules/tools.js +67 -904
  98. package/lib/public/modules/vendor-picker.js +53 -0
  99. package/lib/public/modules/vendor-registry.js +133 -0
  100. package/lib/public/sw.js +3 -1
  101. package/lib/rc-migrate.js +44 -0
  102. package/lib/runtime-env-keys.js +109 -0
  103. package/lib/runtime-env.js +236 -0
  104. package/lib/sdk-bridge.js +290 -273
  105. package/lib/sdk-message-processor.js +125 -145
  106. package/lib/server-hub-sessions.js +13 -10
  107. package/lib/server-palette.js +28 -19
  108. package/lib/server.js +141 -113
  109. package/lib/service-install.js +96 -0
  110. package/lib/session-capabilities.js +76 -0
  111. package/lib/sessions.js +45 -28
  112. package/lib/users-permissions.js +9 -6
  113. package/lib/users.js +9 -0
  114. package/lib/utils.js +4 -2
  115. package/lib/vendor-auth.js +22 -0
  116. package/lib/vendor-registry-message.js +65 -0
  117. package/lib/ws-origin.js +99 -0
  118. package/lib/ws-schema.js +33 -22
  119. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  120. package/lib/yoke/adapters/claude-vendor.js +35 -0
  121. package/lib/yoke/adapters/claude-worker.js +55 -87
  122. package/lib/yoke/adapters/claude.js +156 -62
  123. package/lib/yoke/adapters/codex-capabilities.js +37 -0
  124. package/lib/yoke/adapters/codex-vendor.js +46 -0
  125. package/lib/yoke/adapters/codex.js +347 -156
  126. package/lib/yoke/adapters/effort-control.js +34 -0
  127. package/lib/yoke/adapters/permission-relay.js +58 -0
  128. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  129. package/lib/yoke/auth-checks.js +104 -0
  130. package/lib/yoke/capabilities.js +49 -0
  131. package/lib/yoke/codex-app-server.js +23 -5
  132. package/lib/yoke/env-ownership.js +40 -0
  133. package/lib/yoke/index.js +67 -173
  134. package/lib/yoke/install-probe.js +121 -0
  135. package/lib/yoke/instructions.js +7 -11
  136. package/lib/yoke/interface.js +199 -3
  137. package/lib/yoke/package.json +1 -1
  138. package/lib/yoke/provider-credentials.js +96 -0
  139. package/lib/yoke/registry.js +340 -0
  140. package/package.json +12 -8
  141. package/scripts/check-sdk-lock-drift.js +160 -0
  142. package/scripts/check-test-count.js +76 -1
  143. package/scripts/postinstall.js +218 -136
  144. package/scripts/prompt-harness-history.js +202 -0
  145. package/scripts/verify-installed.js +67 -0
  146. 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];
@@ -569,7 +600,7 @@ function attachSessions(ctx) {
569
600
  var switchTargetSess = sm.sessions.get(msg.id);
570
601
  if (switchTargetSess && sm.currentModel) {
571
602
  var targetVendor = switchTargetSess.vendor || sm.defaultVendor || null;
572
- var tvModels = (targetVendor && sm.modelsByVendor && sm.modelsByVendor[targetVendor]) || [];
603
+ var tvModels = (targetVendor && sm.modelsByVendor && ownValue(sm.modelsByVendor, targetVendor)) || [];
573
604
  var found = false;
574
605
  var _curLc = sm.currentModel.toLowerCase();
575
606
  for (var tvi = 0; tvi < tvModels.length; tvi++) {
@@ -620,14 +651,15 @@ function attachSessions(ctx) {
620
651
  return true;
621
652
  }
622
653
  }
623
- if (msg.id && sm.sessions.has(msg.id)) {
654
+ // The permission to delete is not access to this particular session.
655
+ if (msg.id && sm.sessions.has(msg.id) && projectAccess.canReadSession(ws._clagenticUser, sm.sessions.get(msg.id), projectAccess.authOf(ws))) {
624
656
  sm.deleteSession(msg.id, ws);
625
657
  }
626
658
  return true;
627
659
  }
628
660
 
629
661
  if (msg.type === "rename_session") {
630
- if (msg.id && sm.sessions.has(msg.id) && msg.title) {
662
+ if (msg.id && sm.sessions.has(msg.id) && msg.title && projectAccess.canReadSession(ws._clagenticUser, sm.sessions.get(msg.id), projectAccess.authOf(ws))) {
631
663
  var s = sm.sessions.get(msg.id);
632
664
  s.title = String(msg.title).substring(0, 100);
633
665
  s.titleManuallySet = true;
@@ -644,17 +676,25 @@ function attachSessions(ctx) {
644
676
  }
645
677
 
646
678
  if (msg.type === "search_sessions") {
647
- var results = sm.searchSessions(msg.query || "");
648
- sendTo(ws, { type: "search_results", query: msg.query || "", results: results });
679
+ // Sessions the caller cannot read are skipped before anything is read from
680
+ // them, so neither their titles nor whether their content matches is revealed.
681
+ var searchQuery = typeof msg.query === "string" ? msg.query : "";
682
+ var results = sm.searchSessions(searchQuery, function (candidate) {
683
+ return projectAccess.canReadSession(ws._clagenticUser, candidate, projectAccess.authOf(ws));
684
+ });
685
+ sendTo(ws, { type: "search_results", query: searchQuery, results: results });
649
686
  return true;
650
687
  }
651
688
 
652
689
  if (msg.type === "search_session_content") {
653
690
  var targetSession = msg.id ? sm.sessions.get(msg.id) : getSessionForWs(ws);
654
691
  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;
692
+ if (!projectAccess.canReadSession(ws._clagenticUser, targetSession, projectAccess.authOf(ws))) return true;
693
+ // Same coercion as search_sessions: only a string query is searched or echoed.
694
+ var contentQuery = typeof msg.query === "string" ? msg.query : "";
695
+ var contentResults = sm.searchSessionContent(targetSession.localId, contentQuery);
696
+ var searchResp = { type: "search_content_results", query: contentQuery, sessionId: targetSession.localId, hits: contentResults.hits, total: contentResults.total };
697
+ if (typeof msg.source === "string" && msg.source) searchResp.source = msg.source;
658
698
  sendTo(ws, searchResp);
659
699
  return true;
660
700
  }
@@ -838,7 +878,26 @@ function attachSessions(ctx) {
838
878
  return true;
839
879
  }
840
880
 
881
+ // The user installed or signed in to an agent while the daemon was running.
882
+ // Install state belongs to an OS identity: the lookup runs as the requester,
883
+ // and the refreshed registry goes to every client of that same identity
884
+ // (every client of the project when OS users are off), never to another.
885
+ if (msg.type === "recheck_vendors") {
886
+ var recheckIdentity = osIdentityOf(ws);
887
+ var refreshed = sdk.recheckVendors(recheckIdentity);
888
+ clients.forEach(function (client) {
889
+ if (osIdentityOf(client) === recheckIdentity) sendTo(client, refreshed);
890
+ });
891
+ return true;
892
+ }
893
+
841
894
  if (msg.type === "set_vendor" && msg.vendor) {
895
+ // A vendor the daemon cannot build is no vendor: nothing is bound,
896
+ // looked up or echoed for it.
897
+ if (!isKnownVendor(msg.vendor)) {
898
+ sendTo(ws, { type: "error", text: "Unknown vendor" });
899
+ return true;
900
+ }
842
901
  var vendorSession = getSessionForWs(ws);
843
902
  if (vendorSession) {
844
903
  // Refuse to rebind vendor on a session that is already bound to a
@@ -863,12 +922,15 @@ function attachSessions(ctx) {
863
922
  if (sm.currentModel) {
864
923
  sm.currentModel = "";
865
924
  }
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 +
925
+ // A named agent identity needs the agentInjection capability. If the
926
+ // user somehow switches to a vendor without it on a session that
927
+ // carries agentName (e.g. via a direct WS message), clear the agent
928
+ // identity so the badge doesn't misrepresent an identity that vendor
929
+ // cannot apply.
930
+ // Decided on the resolved capabilities, the same set the agent
931
+ // injection guard in sdk-bridge reads, so the two cannot disagree.
932
+ if (vendorSession.agentName && !sessionCapabilities.capabilitiesFor(sm, msg.vendor).agentInjection) {
933
+ console.warn("[project] set_vendor to " + msg.vendor + " on agent session " + vendorSession.localId +
872
934
  " — clearing agentName '" + vendorSession.agentName + "'");
873
935
  vendorSession.agentName = null;
874
936
  }
@@ -877,14 +939,13 @@ function attachSessions(ctx) {
877
939
  }
878
940
  }
879
941
  if (msg.vendor) {
880
- var vendorModels = (sm.modelsByVendor && sm.modelsByVendor[msg.vendor]) || [];
942
+ var vendorModels = (sm.modelsByVendor && ownValue(sm.modelsByVendor, msg.vendor)) || [];
881
943
  sendTo(ws, {
882
944
  type: "model_info",
883
945
  model: "",
884
946
  models: vendorModels,
885
947
  vendor: msg.vendor,
886
948
  availableVendors: sm.availableVendors || [],
887
- installedVendors: sm.installedVendors || [],
888
949
  });
889
950
  // lr-041af8: targeted, not broadcast — set_vendor acts on the
890
951
  // requesting client's own session (vendorSession above); broadcasting
@@ -929,6 +990,11 @@ function attachSessions(ctx) {
929
990
 
930
991
  if (msg.type === "set_permission_mode" && msg.mode) {
931
992
  var session = getSessionForWs(ws);
993
+ if (session && !sessionAcceptsMode(session, msg.mode)) {
994
+ sendTo(ws, { type: "error", text: "This session's agent does not support the " + String(msg.mode).slice(0, 40) + " permission mode" });
995
+ 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 });
996
+ return true;
997
+ }
932
998
  if (session) {
933
999
  sdk.setPermissionMode(session, msg.mode).then(function () {
934
1000
  // Targeted reply — only update the requesting client's chip.
@@ -967,12 +1033,23 @@ function attachSessions(ctx) {
967
1033
  }
968
1034
 
969
1035
  if (msg.type === "set_effort" && msg.effort) {
970
- sm.currentEffort = msg.effort;
971
1036
  var session = getSessionForWs(ws);
972
- if (session) {
973
- sdk.setEffort(session, msg.effort);
1037
+ if (!session) {
1038
+ sm.currentEffort = msg.effort;
1039
+ 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 });
1040
+ return true;
974
1041
  }
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 });
1042
+ // The effort is recorded only once the running query has taken it
1043
+ // (sdk.setEffort announces it then). A refused change is reported by the
1044
+ // bridge as an error; the requester's picker is put back on the effort
1045
+ // the session still runs at.
1046
+ sdk.setEffort(session, msg.effort).then(function (result) {
1047
+ 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 };
1048
+ if (result && result.ok === false) sendTo(ws, state);
1049
+ else send(state);
1050
+ }).catch(function (err) {
1051
+ console.error("[project-sessions] set_effort failed:", (err && err.message) || err);
1052
+ });
976
1053
  return true;
977
1054
  }
978
1055
 
@@ -1105,6 +1182,19 @@ function attachSessions(ctx) {
1105
1182
  }
1106
1183
  }
1107
1184
 
1185
+ // Notify adapter of conversation rollback (e.g. Codex thread/rollback)
1186
+ // BEFORE trimming: when the adapter cannot roll its thread back, the
1187
+ // rewind fails (the catch below reports it) and the local history is
1188
+ // left as it was, so the two never disagree.
1189
+ if (turnsToRollBack > 0) {
1190
+ try {
1191
+ await sdk.rollbackConversation(session, turnsToRollBack);
1192
+ } catch (rbErr) {
1193
+ sm.retrimHistory(session);
1194
+ throw rbErr;
1195
+ }
1196
+ }
1197
+
1108
1198
  if (targetIdx >= 0) {
1109
1199
  var trimTo = session.messageUUIDs[targetIdx].historyIndex;
1110
1200
  for (var k = trimTo - 1; k >= 0; k--) {
@@ -1126,15 +1216,6 @@ function attachSessions(ctx) {
1126
1216
  // extra bookkeeping needed here.
1127
1217
  }
1128
1218
 
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
1219
  var kept = session.messageUUIDs;
1139
1220
  session.lastRewindUuid = kept.length > 0 ? kept[kept.length - 1].uuid : null;
1140
1221
  // lr-2ea2a7: re-apply the bounded tail cap now that the trim/save
@@ -1153,8 +1234,7 @@ function attachSessions(ctx) {
1153
1234
  session.abortController = null;
1154
1235
  session.blocks = {};
1155
1236
  session.sentToolResults = {};
1156
- session.pendingPermissions = {};
1157
- session.pendingAskUser = {};
1237
+ promptsFor(sm).cancelSession(session, "rewind");
1158
1238
  // lr-9bcd7b: a rewind destroys the in-flight query outright (the
1159
1239
  // queryInstance null-out above), so nothing can genuinely still be
1160
1240
  // running for this session afterward. Unlike the reconciliation
@@ -1258,74 +1338,6 @@ function attachSessions(ctx) {
1258
1338
  return true;
1259
1339
  }
1260
1340
 
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
1341
  if (msg.type === "input_sync") {
1330
1342
  sendToSessionOthers(ws, ws._clagenticActiveSession, msg);
1331
1343
  return true;
@@ -1355,177 +1367,6 @@ function attachSessions(ctx) {
1355
1367
  return true;
1356
1368
  }
1357
1369
 
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
1370
  // --- Browse directories (for add-project autocomplete) ---
1530
1371
  if (msg.type === "browse_dir") {
1531
1372
  var rawPath = (msg.path || "").replace(/^~/, require("./config").REAL_HOME);
@@ -1728,7 +1569,8 @@ function attachSessions(ctx) {
1728
1569
  var moveResult = moveScheduleToProject(msg.recordId, msg.fromSlug, msg.toSlug);
1729
1570
  if (moveResult.ok) {
1730
1571
  // Re-broadcast updated records to this project's clients
1731
- send({ type: "loop_registry_updated", records: getHubSchedules() });
1572
+ if (typeof ctx.broadcastHubSchedules === "function") ctx.broadcastHubSchedules();
1573
+ else send({ type: "loop_registry_updated", records: getHubSchedules(null) });
1732
1574
  }
1733
1575
  sendTo(ws, { type: "schedule_move_result", ok: moveResult.ok, error: moveResult.error });
1734
1576
  return true;
@@ -1873,7 +1715,7 @@ function attachSessions(ctx) {
1873
1715
  msg.type === "set_auto_continue" || msg.type === "set_image_retention" || msg.type === "set_mem_available_threshold" ||
1874
1716
  msg.type === "set_tokens_per_mb_headroom" ||
1875
1717
  msg.type === "set_lite_auto_enroll" ||
1876
- msg.type === "shutdown_server" || msg.type === "restart_server") {
1718
+ msg.type === "shutdown_server" || msg.type === "restart_server" || msg.type === "restart_for_build_update") {
1877
1719
  var _wsUser = ws._clagenticUser;
1878
1720
  if (!_wsUser || _wsUser.role !== "admin") {
1879
1721
  // lr-93e3c8 (fnd-66af4e, item 7): app-messages.js's client-side
@@ -1998,6 +1840,26 @@ function attachSessions(ctx) {
1998
1840
  return true;
1999
1841
  }
2000
1842
 
1843
+ // lr-e85fec: operator-initiated adoption of an installed-but-not-yet-
1844
+ // running build (the "Restart to apply update" action offered by the
1845
+ // build-update diagnostic). Same admin gate and same in-process wiring
1846
+ // pattern as restart_server above — the only difference is
1847
+ // onRestartForBuildUpdate waits for in-flight sessions to finish (bounded)
1848
+ // before restarting, since this restart is a maintenance action the
1849
+ // operator chose at a moment of their own choosing, not an emergency.
1850
+ if (msg.type === "restart_for_build_update") {
1851
+ if (typeof opts.onRestartForBuildUpdate === "function") {
1852
+ sendTo(ws, { type: "restart_for_build_update_result", ok: true });
1853
+ send({ type: "toast", level: "info", message: "Restarting to apply the installed update..." });
1854
+ setTimeout(function () {
1855
+ opts.onRestartForBuildUpdate();
1856
+ }, 500);
1857
+ } else {
1858
+ sendTo(ws, { type: "restart_for_build_update_result", ok: false, error: "Restart not supported" });
1859
+ }
1860
+ return true;
1861
+ }
1862
+
2001
1863
  // --- Clagentic: Lite integration WS messages ---
2002
1864
 
2003
1865
  // get_lite_project_status — responds with lite_project_status { enrolled: bool }