@clagentic/console 1.0.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 (221) hide show
  1. package/CREDITS.md +3 -0
  2. package/LICENSE +21 -0
  3. package/README.md +250 -0
  4. package/bin/cli.js +2812 -0
  5. package/lib/agents-favorites.js +164 -0
  6. package/lib/agents.js +282 -0
  7. package/lib/ask-user-mcp-server.js +120 -0
  8. package/lib/browser-mcp-server.js +484 -0
  9. package/lib/build-user-env.js +63 -0
  10. package/lib/certs/fullchain.pem +47 -0
  11. package/lib/certs/privkey.pem +5 -0
  12. package/lib/cli-sessions.js +265 -0
  13. package/lib/codex-defaults.js +18 -0
  14. package/lib/config.js +332 -0
  15. package/lib/crisis-safety.js +60 -0
  16. package/lib/daemon-projects.js +164 -0
  17. package/lib/daemon.js +1602 -0
  18. package/lib/dm.js +128 -0
  19. package/lib/ipc.js +125 -0
  20. package/lib/ipv4-only.js +39 -0
  21. package/lib/mcp-local.js +385 -0
  22. package/lib/notes.js +141 -0
  23. package/lib/os-users.js +529 -0
  24. package/lib/pages.js +1325 -0
  25. package/lib/project-connection.js +302 -0
  26. package/lib/project-external-trigger.js +236 -0
  27. package/lib/project-file-watch.js +120 -0
  28. package/lib/project-filesystem.js +528 -0
  29. package/lib/project-http.js +753 -0
  30. package/lib/project-image.js +95 -0
  31. package/lib/project-knowledge.js +88 -0
  32. package/lib/project-loop.js +1304 -0
  33. package/lib/project-mcp.js +374 -0
  34. package/lib/project-memory.js +39 -0
  35. package/lib/project-notifications.js +262 -0
  36. package/lib/project-sessions.js +1581 -0
  37. package/lib/project-user-mention.js +193 -0
  38. package/lib/project-user-message.js +628 -0
  39. package/lib/project.js +1303 -0
  40. package/lib/public/app.js +1031 -0
  41. package/lib/public/apple-touch-icon.png +0 -0
  42. package/lib/public/claude-code-avatar.png +0 -0
  43. package/lib/public/codex-avatar.png +0 -0
  44. package/lib/public/console-icon.png +0 -0
  45. package/lib/public/css/admin.css +736 -0
  46. package/lib/public/css/agent-picker.css +119 -0
  47. package/lib/public/css/base.css +235 -0
  48. package/lib/public/css/channel-layout.css +441 -0
  49. package/lib/public/css/command-palette.css +559 -0
  50. package/lib/public/css/debate.css +1609 -0
  51. package/lib/public/css/diff.css +139 -0
  52. package/lib/public/css/filebrowser.css +1976 -0
  53. package/lib/public/css/highlight.css +144 -0
  54. package/lib/public/css/home-hub.css +545 -0
  55. package/lib/public/css/icon-strip.css +1856 -0
  56. package/lib/public/css/input.css +1349 -0
  57. package/lib/public/css/loop.css +1248 -0
  58. package/lib/public/css/mention.css +317 -0
  59. package/lib/public/css/menus.css +857 -0
  60. package/lib/public/css/messages.css +1833 -0
  61. package/lib/public/css/mobile-nav.css +1332 -0
  62. package/lib/public/css/notifications-center.css +296 -0
  63. package/lib/public/css/overlays.css +1273 -0
  64. package/lib/public/css/playbook.css +264 -0
  65. package/lib/public/css/profile.css +397 -0
  66. package/lib/public/css/rewind.css +671 -0
  67. package/lib/public/css/scheduler-modal.css +1495 -0
  68. package/lib/public/css/scheduler.css +1420 -0
  69. package/lib/public/css/server-settings.css +909 -0
  70. package/lib/public/css/session-search.css +159 -0
  71. package/lib/public/css/sidebar.css +2012 -0
  72. package/lib/public/css/skills.css +789 -0
  73. package/lib/public/css/sticky-notes.css +854 -0
  74. package/lib/public/css/stt.css +155 -0
  75. package/lib/public/css/title-bar.css +674 -0
  76. package/lib/public/css/tooltip.css +67 -0
  77. package/lib/public/css/user-settings.css +702 -0
  78. package/lib/public/emoji-data.json +1 -0
  79. package/lib/public/favicon-banded-32.png +0 -0
  80. package/lib/public/favicon-banded.png +0 -0
  81. package/lib/public/favicon-dark.svg +32 -0
  82. package/lib/public/favicon.svg +32 -0
  83. package/lib/public/icon-192.png +0 -0
  84. package/lib/public/icon-512.png +0 -0
  85. package/lib/public/icon-banded-76.png +0 -0
  86. package/lib/public/icon-banded-96.png +0 -0
  87. package/lib/public/icon-mono.svg +25 -0
  88. package/lib/public/icons/email/gmail.svg +7 -0
  89. package/lib/public/icons/email/outlook.svg +35 -0
  90. package/lib/public/icons/email/yahoo.svg +1 -0
  91. package/lib/public/index.html +1946 -0
  92. package/lib/public/manifest.json +27 -0
  93. package/lib/public/markdown-worker.js +43 -0
  94. package/lib/public/marked.min.js +6 -0
  95. package/lib/public/modules/admin.js +954 -0
  96. package/lib/public/modules/agent-picker.js +429 -0
  97. package/lib/public/modules/app-connection.js +216 -0
  98. package/lib/public/modules/app-cursors.js +492 -0
  99. package/lib/public/modules/app-dm.js +265 -0
  100. package/lib/public/modules/app-favicon.js +231 -0
  101. package/lib/public/modules/app-header.js +242 -0
  102. package/lib/public/modules/app-home-hub.js +432 -0
  103. package/lib/public/modules/app-loop-ui.js +691 -0
  104. package/lib/public/modules/app-loop-wizard.js +439 -0
  105. package/lib/public/modules/app-messages.js +1415 -0
  106. package/lib/public/modules/app-misc.js +463 -0
  107. package/lib/public/modules/app-notifications.js +651 -0
  108. package/lib/public/modules/app-panels.js +1061 -0
  109. package/lib/public/modules/app-projects.js +875 -0
  110. package/lib/public/modules/app-rate-limit.js +529 -0
  111. package/lib/public/modules/app-rendering.js +739 -0
  112. package/lib/public/modules/app-skills-install.js +285 -0
  113. package/lib/public/modules/avatar.js +36 -0
  114. package/lib/public/modules/command-palette.js +491 -0
  115. package/lib/public/modules/console-logo.js +162 -0
  116. package/lib/public/modules/context-sources.js +365 -0
  117. package/lib/public/modules/diff.js +412 -0
  118. package/lib/public/modules/dom-refs.js +21 -0
  119. package/lib/public/modules/emoji-picker.js +222 -0
  120. package/lib/public/modules/events.js +21 -0
  121. package/lib/public/modules/filebrowser.js +1966 -0
  122. package/lib/public/modules/fileicons.js +172 -0
  123. package/lib/public/modules/icons.js +80 -0
  124. package/lib/public/modules/input.js +1102 -0
  125. package/lib/public/modules/longpress.js +74 -0
  126. package/lib/public/modules/markdown.js +486 -0
  127. package/lib/public/modules/mcp-ui.js +295 -0
  128. package/lib/public/modules/mention.js +1093 -0
  129. package/lib/public/modules/notifications.js +613 -0
  130. package/lib/public/modules/playbook.js +578 -0
  131. package/lib/public/modules/profile.js +594 -0
  132. package/lib/public/modules/project-settings.js +849 -0
  133. package/lib/public/modules/project-switcher.js +375 -0
  134. package/lib/public/modules/qrcode.js +87 -0
  135. package/lib/public/modules/rewind.js +381 -0
  136. package/lib/public/modules/scheduler-config.js +1611 -0
  137. package/lib/public/modules/scheduler-history.js +131 -0
  138. package/lib/public/modules/scheduler.js +1689 -0
  139. package/lib/public/modules/server-settings.js +842 -0
  140. package/lib/public/modules/session-search.js +456 -0
  141. package/lib/public/modules/settings-defaults.js +253 -0
  142. package/lib/public/modules/sidebar-mobile.js +1425 -0
  143. package/lib/public/modules/sidebar-projects.js +2022 -0
  144. package/lib/public/modules/sidebar-sessions.js +1548 -0
  145. package/lib/public/modules/sidebar-users.js +449 -0
  146. package/lib/public/modules/sidebar.js +348 -0
  147. package/lib/public/modules/skills.js +793 -0
  148. package/lib/public/modules/state.js +3 -0
  149. package/lib/public/modules/sticky-notes.js +1221 -0
  150. package/lib/public/modules/store.js +34 -0
  151. package/lib/public/modules/stt.js +266 -0
  152. package/lib/public/modules/terminal.js +987 -0
  153. package/lib/public/modules/theme.js +812 -0
  154. package/lib/public/modules/tool-palette.js +562 -0
  155. package/lib/public/modules/tools.js +2285 -0
  156. package/lib/public/modules/tooltip.js +150 -0
  157. package/lib/public/modules/user-settings.js +544 -0
  158. package/lib/public/modules/utils.js +56 -0
  159. package/lib/public/modules/ws-ref.js +26 -0
  160. package/lib/public/style.css +34 -0
  161. package/lib/public/sw.js +159 -0
  162. package/lib/push.js +149 -0
  163. package/lib/scheduler.js +471 -0
  164. package/lib/sdk-bridge.js +1792 -0
  165. package/lib/sdk-message-processor.js +740 -0
  166. package/lib/sdk-message-queue.js +42 -0
  167. package/lib/sdk-skill-discovery.js +131 -0
  168. package/lib/sdk-worker.js +677 -0
  169. package/lib/server-admin.js +712 -0
  170. package/lib/server-auth.js +737 -0
  171. package/lib/server-dm.js +170 -0
  172. package/lib/server-palette.js +104 -0
  173. package/lib/server-settings.js +553 -0
  174. package/lib/server-skills.js +280 -0
  175. package/lib/server.js +1390 -0
  176. package/lib/session-search.js +693 -0
  177. package/lib/sessions.js +946 -0
  178. package/lib/smtp.js +221 -0
  179. package/lib/terminal-manager.js +219 -0
  180. package/lib/terminal.js +39 -0
  181. package/lib/themes/ayu-light.json +9 -0
  182. package/lib/themes/catppuccin-latte.json +9 -0
  183. package/lib/themes/catppuccin-mocha.json +9 -0
  184. package/lib/themes/clagentic-dark.json +10 -0
  185. package/lib/themes/clagentic-light.json +10 -0
  186. package/lib/themes/dracula.json +9 -0
  187. package/lib/themes/everforest-light.json +9 -0
  188. package/lib/themes/everforest.json +9 -0
  189. package/lib/themes/github-light.json +9 -0
  190. package/lib/themes/gruvbox-dark.json +9 -0
  191. package/lib/themes/gruvbox-light.json +9 -0
  192. package/lib/themes/monokai.json +9 -0
  193. package/lib/themes/nord-light.json +9 -0
  194. package/lib/themes/nord.json +9 -0
  195. package/lib/themes/one-dark.json +9 -0
  196. package/lib/themes/one-light.json +9 -0
  197. package/lib/themes/rose-pine-dawn.json +9 -0
  198. package/lib/themes/rose-pine.json +9 -0
  199. package/lib/themes/solarized-dark.json +9 -0
  200. package/lib/themes/solarized-light.json +9 -0
  201. package/lib/themes/tokyo-night-light.json +9 -0
  202. package/lib/themes/tokyo-night.json +9 -0
  203. package/lib/updater.js +124 -0
  204. package/lib/user-presence.js +92 -0
  205. package/lib/users-auth.js +146 -0
  206. package/lib/users-permissions.js +118 -0
  207. package/lib/users-preferences.js +254 -0
  208. package/lib/users.js +465 -0
  209. package/lib/utils.js +64 -0
  210. package/lib/worktree.js +134 -0
  211. package/lib/ws-schema.js +464 -0
  212. package/lib/yoke/adapters/claude-worker.js +759 -0
  213. package/lib/yoke/adapters/claude.js +1599 -0
  214. package/lib/yoke/adapters/codex.js +1559 -0
  215. package/lib/yoke/codex-app-server.js +352 -0
  216. package/lib/yoke/index.js +319 -0
  217. package/lib/yoke/instructions.js +61 -0
  218. package/lib/yoke/interface.js +98 -0
  219. package/lib/yoke/mcp-bridge-server.js +302 -0
  220. package/lib/yoke/package.json +7 -0
  221. package/package.json +72 -0
@@ -0,0 +1,1581 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+ var { execFileSync } = require("child_process");
4
+ var { CODEX_DEFAULTS, getCodexConfig } = require("./codex-defaults");
5
+ var agentsModule = require("./agents");
6
+ var agentsFavorites = require("./agents-favorites");
7
+
8
+ // Format a user's answer to an ask_user_questions card as a plain user
9
+ // message so the MCP path can feed it back to the agent on the next turn.
10
+ // The agent sees: its own question text, then the selected answer(s).
11
+ function formatAskUserAnswerAsMessage(input, answers) {
12
+ var questions = (input && Array.isArray(input.questions)) ? input.questions : [];
13
+ if (questions.length === 0) {
14
+ // Shouldn't happen, but be defensive.
15
+ try { return "(answered with: " + JSON.stringify(answers || {}) + ")"; }
16
+ catch (e) { return "(answered)"; }
17
+ }
18
+ var lines = [];
19
+ for (var i = 0; i < questions.length; i++) {
20
+ var q = questions[i];
21
+ var qText = (q && q.question) ? q.question : ("Question " + (i + 1));
22
+ var ans = (answers && answers[i] != null) ? String(answers[i]) : "";
23
+ if (!ans) continue;
24
+ if (questions.length === 1) {
25
+ // Single question: keep it tight.
26
+ lines.push(ans);
27
+ } else {
28
+ lines.push("- " + qText + " → " + ans);
29
+ }
30
+ }
31
+ if (lines.length === 0) return "(no answer provided)";
32
+ return lines.join("\n");
33
+ }
34
+
35
+ /**
36
+ * Attach session management, config, project management, and mid-section
37
+ * message handlers to a project context.
38
+ *
39
+ * ctx fields:
40
+ * cwd, slug, isMate, osUsers, debug, dangerouslySkipPermissions, currentVersion,
41
+ * sm, sdk, tm, clients,
42
+ * send, sendTo, sendToAdmins, sendToSession, sendToSessionOthers,
43
+ * opts, usersModule, userPresence, matesModule, pushModule,
44
+ * getSessionForWs, getLinuxUserForSession, ensureProjectAccessForSession, getOsUserInfoForWs,
45
+ * hydrateImageRefs, onProcessingChanged, broadcastPresence,
46
+ * adapter, getProjectList, getProjectCount, getScheduleCount,
47
+ * moveScheduleToProject, moveAllSchedulesToProject, getHubSchedules,
48
+ * fetchVersion, isNewer, onCreateWorktree, IGNORED_DIRS,
49
+ * scheduleMessage, cancelScheduledMessage,
50
+ * getProjectOwnerId, setProjectOwnerId,
51
+ * getUpdateChannel, setUpdateChannel,
52
+ * getLatestVersion, setLatestVersion
53
+ */
54
+ function attachSessions(ctx) {
55
+ var cwd = ctx.cwd;
56
+ var slug = ctx.slug;
57
+ var osUsers = ctx.osUsers;
58
+ var currentVersion = ctx.currentVersion;
59
+ var sm = ctx.sm;
60
+ var sdk = ctx.sdk;
61
+ var tm = ctx.tm;
62
+ var clients = ctx.clients;
63
+ var send = ctx.send;
64
+ var sendTo = ctx.sendTo;
65
+ var sendToAdmins = ctx.sendToAdmins;
66
+ var sendToSession = ctx.sendToSession;
67
+ var sendToSessionOthers = ctx.sendToSessionOthers;
68
+ var opts = ctx.opts;
69
+ var usersModule = ctx.usersModule;
70
+ var userPresence = ctx.userPresence;
71
+ var pushModule = ctx.pushModule;
72
+ var getSessionForWs = ctx.getSessionForWs;
73
+ var getLinuxUserForSession = ctx.getLinuxUserForSession;
74
+ var ensureProjectAccessForSession = ctx.ensureProjectAccessForSession;
75
+ var getOsUserInfoForWs = ctx.getOsUserInfoForWs;
76
+ var hydrateImageRefs = ctx.hydrateImageRefs;
77
+ var onProcessingChanged = ctx.onProcessingChanged;
78
+ var broadcastPresence = ctx.broadcastPresence;
79
+ var adapter = ctx.adapter;
80
+ var getProjectList = ctx.getProjectList;
81
+ var getProjectCount = ctx.getProjectCount;
82
+ var getScheduleCount = ctx.getScheduleCount;
83
+ var moveScheduleToProject = ctx.moveScheduleToProject;
84
+ var moveAllSchedulesToProject = ctx.moveAllSchedulesToProject;
85
+ var getHubSchedules = ctx.getHubSchedules;
86
+ var fetchVersion = ctx.fetchVersion;
87
+ var isNewer = ctx.isNewer;
88
+ var onCreateWorktree = ctx.onCreateWorktree;
89
+ var IGNORED_DIRS = ctx.IGNORED_DIRS;
90
+ var scheduleMessage = ctx.scheduleMessage;
91
+ var cancelScheduledMessage = ctx.cancelScheduledMessage;
92
+ var getProjectOwnerId = ctx.getProjectOwnerId;
93
+ var setProjectOwnerId = ctx.setProjectOwnerId;
94
+ var getUpdateChannel = ctx.getUpdateChannel;
95
+ var setUpdateChannel = ctx.setUpdateChannel;
96
+ var getLatestVersion = ctx.getLatestVersion;
97
+ var setLatestVersion = ctx.setLatestVersion;
98
+ var loadContextSources = ctx.loadContextSources;
99
+ var saveContextSources = ctx.saveContextSources;
100
+
101
+ function handleSessionsMessage(ws, msg) {
102
+
103
+ if (msg.type === "push_subscribe") {
104
+ var _pushUserId = ws._clayUser ? ws._clayUser.id : null;
105
+ if (pushModule && msg.subscription) pushModule.addSubscription(msg.subscription, msg.replaceEndpoint, _pushUserId);
106
+ return true;
107
+ }
108
+
109
+ if (msg.type === "load_more_history") {
110
+ var session = getSessionForWs(ws);
111
+ if (!session || typeof msg.before !== "number") return true;
112
+ var before = msg.before;
113
+ var targetFrom = typeof msg.target === "number" ? msg.target : before - sm.HISTORY_PAGE_SIZE;
114
+ var from = sm.findTurnBoundary(session.history, Math.max(0, targetFrom));
115
+ var to = before;
116
+ var items = session.history.slice(from, to).map(hydrateImageRefs);
117
+ sendTo(ws, {
118
+ type: "history_prepend",
119
+ items: items,
120
+ meta: { from: from, to: to, hasMore: from > 0 },
121
+ });
122
+ return true;
123
+ }
124
+
125
+ if (msg.type === "new_session") {
126
+ var sessionOpts = {};
127
+ if (ws._clayUser && usersModule.isMultiUser()) sessionOpts.ownerId = ws._clayUser.id;
128
+ if (msg.sessionVisibility) sessionOpts.sessionVisibility = msg.sessionVisibility;
129
+ if (msg.vendor) sessionOpts.vendor = msg.vendor;
130
+ if (msg.agentName && typeof msg.agentName === "string") {
131
+ sessionOpts.agentName = msg.agentName;
132
+ try { agentsFavorites.touchRecent({ name: msg.agentName, kind: msg.agentKind || "user", pluginName: msg.agentPluginName || null }); }
133
+ catch (e) { /* recents are best-effort */ }
134
+ }
135
+ var newSess = sm.createSession(sessionOpts, ws);
136
+ // Seed per-session model/mode from project defaults so the first query
137
+ // uses the right values even before the user changes anything.
138
+ newSess.model = sm.currentModel || null;
139
+ newSess.permissionMode = sm.currentPermissionMode || null;
140
+ ws._clayActiveSession = newSess.localId;
141
+ // Apply project-level email defaults to new session
142
+ if (typeof ctx._email === "object" && ctx._email.getEmailDefaults) {
143
+ var emailDefaults = ctx._email.getEmailDefaults();
144
+ if (emailDefaults.length > 0) {
145
+ var defaultSources = emailDefaults.map(function (id) { return "email:" + id; });
146
+ saveContextSources(slug, newSess.localId, defaultSources);
147
+ sendTo(ws, { type: "context_sources_state", active: defaultSources });
148
+ }
149
+ }
150
+ var nsPresKey = ws._clayUser ? ws._clayUser.id : "_default";
151
+ userPresence.setPresence(slug, nsPresKey, newSess.localId, null);
152
+ if (usersModule.isMultiUser()) {
153
+ broadcastPresence();
154
+ }
155
+ return true;
156
+ }
157
+
158
+ // lr-7db0 — agent picker support.
159
+ //
160
+ // list_agents returns the discovered Claude agent catalog plus the user's
161
+ // favorites and recents (Clay-side state in ~/.clay/agents/chattable.json).
162
+ // Hidden client-side when active project is a Mate; we still answer here
163
+ // because the daemon shouldn't make UX decisions that the client already
164
+ // owns. UI gates the surface; daemon stays a data plane.
165
+ if (msg.type === "list_agents") {
166
+ var allAgents;
167
+ try { allAgents = agentsModule.discoverAllAgents(); }
168
+ catch (e) {
169
+ console.error("[project-sessions] list_agents discovery failed:", e.message);
170
+ allAgents = [];
171
+ }
172
+ var favorites = [];
173
+ var recents = [];
174
+ try { favorites = agentsFavorites.listFavorites(); recents = agentsFavorites.listRecents(); }
175
+ catch (e) { /* favorites are best-effort */ }
176
+ sendTo(ws, {
177
+ type: "agents_list",
178
+ agents: allAgents,
179
+ favorites: favorites,
180
+ recents: recents,
181
+ });
182
+ return true;
183
+ }
184
+
185
+ // toggle_agent_favorite flips an agent's membership in chattable.json.
186
+ // Required fields: name, kind. Optional: pluginName (for kind=plugin).
187
+ if (msg.type === "toggle_agent_favorite") {
188
+ if (!msg.name || !msg.kind) return true;
189
+ var entry = { name: msg.name, kind: msg.kind, pluginName: msg.pluginName || null };
190
+ var nowFav;
191
+ try { nowFav = agentsFavorites.toggleFavorite(entry); }
192
+ catch (e) {
193
+ console.error("[project-sessions] toggle_agent_favorite failed:", e.message);
194
+ return true;
195
+ }
196
+ // Re-broadcast updated catalog to the requesting client. Other clients
197
+ // pull on demand; favorites is per-machine state, not multi-user shared.
198
+ sendTo(ws, {
199
+ type: "agents_list",
200
+ agents: agentsModule.discoverAllAgents(),
201
+ favorites: agentsFavorites.listFavorites(),
202
+ recents: agentsFavorites.listRecents(),
203
+ });
204
+ sendTo(ws, { type: "agent_favorite_toggled", name: msg.name, kind: msg.kind, pluginName: msg.pluginName || null, favorite: nowFav });
205
+ return true;
206
+ }
207
+
208
+ // set_session_agent attaches/detaches a named agent on an existing session.
209
+ // Pass agentName="" (or null) to clear. Takes effect on the next turn —
210
+ // the SDK reads queryOpts at createQuery time, so a session that's mid-turn
211
+ // keeps its current identity for that turn.
212
+ if (msg.type === "set_session_agent") {
213
+ if (typeof msg.sessionId !== "number") return true;
214
+ var agentTarget = sm.sessions.get(msg.sessionId);
215
+ if (!agentTarget) return true;
216
+ if (usersModule.isMultiUser() && ws._clayUser) {
217
+ if (!usersModule.canAccessSession(ws._clayUser.id, agentTarget, { visibility: "public" })) return true;
218
+ }
219
+ var nextAgent = (msg.agentName && typeof msg.agentName === "string") ? msg.agentName : null;
220
+ agentTarget.agentName = nextAgent;
221
+ sm.saveSessionFile(agentTarget);
222
+ if (nextAgent) {
223
+ try { agentsFavorites.touchRecent({ name: nextAgent, kind: msg.agentKind || "user", pluginName: msg.agentPluginName || null }); }
224
+ catch (e) { /* best-effort */ }
225
+ }
226
+ sm.broadcastSessionList();
227
+ return true;
228
+ }
229
+
230
+ if (msg.type === "set_session_visibility") {
231
+ if (typeof msg.sessionId === "number" && (msg.visibility === "shared" || msg.visibility === "private")) {
232
+ sm.setSessionVisibility(msg.sessionId, msg.visibility);
233
+ }
234
+ return true;
235
+ }
236
+
237
+ if (msg.type === "set_session_bookmark") {
238
+ if (typeof msg.sessionId === "number") {
239
+ var bookmarkTarget = sm.sessions.get(msg.sessionId);
240
+ if (!bookmarkTarget) return true;
241
+ if (usersModule.isMultiUser() && ws._clayUser) {
242
+ if (!usersModule.canAccessSession(ws._clayUser.id, bookmarkTarget, { visibility: "public" })) return true;
243
+ }
244
+ sm.setSessionBookmarked(msg.sessionId, !!msg.bookmarked);
245
+ }
246
+ return true;
247
+ }
248
+
249
+ if (msg.type === "reorder_session_bookmarks") {
250
+ if (typeof msg.sourceId === "number" && typeof msg.targetId === "number" && msg.sourceId !== msg.targetId) {
251
+ var source = sm.sessions.get(msg.sourceId);
252
+ var target = sm.sessions.get(msg.targetId);
253
+ if (!source || !target) return true;
254
+ if (usersModule.isMultiUser() && ws._clayUser) {
255
+ if (!usersModule.canAccessSession(ws._clayUser.id, source, { visibility: "public" })) return true;
256
+ if (!usersModule.canAccessSession(ws._clayUser.id, target, { visibility: "public" })) return true;
257
+ }
258
+ sm.reorderBookmarkedSessions(msg.sourceId, msg.targetId, msg.insertBefore !== false);
259
+ }
260
+ return true;
261
+ }
262
+
263
+ if (msg.type === "bulk_delete_sessions") {
264
+ if (!Array.isArray(msg.sessionIds) || msg.sessionIds.length === 0) return true;
265
+ var deletableIds = [];
266
+ for (var di = 0; di < msg.sessionIds.length; di++) {
267
+ var bulkId = msg.sessionIds[di];
268
+ if (typeof bulkId !== "number") continue;
269
+ var bulkTarget = sm.sessions.get(bulkId);
270
+ if (!bulkTarget) continue;
271
+ if (usersModule.isMultiUser() && ws._clayUser) {
272
+ if (!usersModule.canAccessSession(ws._clayUser.id, bulkTarget, { visibility: "public" })) continue;
273
+ }
274
+ deletableIds.push(bulkId);
275
+ }
276
+ if (deletableIds.length > 0) {
277
+ sm.deleteSessionsBulk(deletableIds, ws);
278
+ }
279
+ return true;
280
+ }
281
+
282
+ if (msg.type === "transfer_project_owner") {
283
+ // Home directory projects: ownership is permanently locked
284
+ if (osUsers && osUsers.length > 0 && /^\/home\/[^/]+\//.test(cwd)) {
285
+ sendTo(ws, { type: "error", text: "Cannot transfer ownership of home directory projects." });
286
+ return true;
287
+ }
288
+ var projectOwnerId = getProjectOwnerId();
289
+ var isAdmin = ws._clayUser && ws._clayUser.role === "admin";
290
+ var isProjectOwner = ws._clayUser && projectOwnerId && ws._clayUser.id === projectOwnerId;
291
+ if (!ws._clayUser || (!isAdmin && !isProjectOwner)) {
292
+ sendTo(ws, { type: "error", text: "Only project owners or admins can transfer ownership." });
293
+ return true;
294
+ }
295
+ var targetUser = msg.userId ? usersModule.findUserById(msg.userId) : null;
296
+ if (!targetUser) {
297
+ sendTo(ws, { type: "error", text: "User not found." });
298
+ return true;
299
+ }
300
+ setProjectOwnerId(targetUser.id);
301
+ // Persist via daemon callback
302
+ if (opts.onProjectOwnerChanged) {
303
+ opts.onProjectOwnerChanged(slug, targetUser.id);
304
+ }
305
+ send({ type: "project_owner_changed", ownerId: targetUser.id, ownerName: targetUser.displayName || targetUser.username });
306
+ return true;
307
+ }
308
+
309
+ if (msg.type === "resume_session") {
310
+ if (!msg.cliSessionId) return true;
311
+ var cliSess = require("./cli-sessions");
312
+
313
+ // If Clay already has a persisted meta file for this cliSessionId, read
314
+ // its vendor so resumeSession doesn't silently default to the project's
315
+ // primary vendor (which would break codex sessions after server restart).
316
+ var persistedVendor = null;
317
+ try {
318
+ var _fsResume = require("fs");
319
+ var _pathResume = require("path");
320
+ var metaPath = _pathResume.join(sm.sessionsDir, msg.cliSessionId + ".jsonl");
321
+ if (_fsResume.existsSync(metaPath)) {
322
+ var firstLine = _fsResume.readFileSync(metaPath, "utf8").split("\n", 1)[0];
323
+ try {
324
+ var metaObj = JSON.parse(firstLine);
325
+ if (metaObj && metaObj.type === "meta" && metaObj.vendor) persistedVendor = metaObj.vendor;
326
+ } catch (e) {}
327
+ }
328
+ } catch (e) {}
329
+
330
+ // Try SDK for title first, then fall back to manual parsing
331
+ var titlePromise = adapter.getSessionInfo(msg.cliSessionId, { dir: cwd }).then(function(info) {
332
+ return (info && info.summary) ? info.summary.substring(0, 100) : null;
333
+ }).catch(function() { return null; });
334
+
335
+ Promise.all([
336
+ cliSess.readCliSessionHistory(cwd, msg.cliSessionId),
337
+ titlePromise
338
+ ]).then(function(results) {
339
+ var history = results[0];
340
+ var sdkTitle = results[1];
341
+ var title = sdkTitle || "Resumed session";
342
+ if (!sdkTitle) {
343
+ for (var i = 0; i < history.length; i++) {
344
+ if (history[i].type === "user_message" && history[i].text) {
345
+ title = history[i].text.substring(0, 50);
346
+ break;
347
+ }
348
+ }
349
+ }
350
+ var resumed = sm.resumeSession(msg.cliSessionId, { history: history, title: title, vendor: persistedVendor || undefined }, ws);
351
+ if (resumed) ws._clayActiveSession = resumed.localId;
352
+ }).catch(function() {
353
+ var resumed = sm.resumeSession(msg.cliSessionId, persistedVendor ? { vendor: persistedVendor } : undefined, ws);
354
+ if (resumed) ws._clayActiveSession = resumed.localId;
355
+ });
356
+ return true;
357
+ }
358
+
359
+ if (msg.type === "list_cli_sessions") {
360
+ var _fs = require("fs");
361
+ // Collect session IDs already in relay (in-memory + persisted on disk)
362
+ var relayIds = {};
363
+ sm.sessions.forEach(function (s) {
364
+ if (s.cliSessionId) relayIds[s.cliSessionId] = true;
365
+ });
366
+ try {
367
+ var sessDir = sm.sessionsDir;
368
+ var diskFiles = _fs.readdirSync(sessDir);
369
+ for (var fi = 0; fi < diskFiles.length; fi++) {
370
+ if (diskFiles[fi].endsWith(".jsonl")) {
371
+ relayIds[diskFiles[fi].replace(".jsonl", "")] = true;
372
+ }
373
+ }
374
+ } catch (e) {}
375
+
376
+ adapter.listSessions({ dir: cwd }).then(function(sdkSessions) {
377
+ var filtered = sdkSessions.filter(function(s) {
378
+ return !relayIds[s.sessionId];
379
+ }).map(function(s) {
380
+ return {
381
+ sessionId: s.sessionId,
382
+ firstPrompt: s.summary || s.firstPrompt || "",
383
+ model: null,
384
+ gitBranch: s.gitBranch || null,
385
+ startTime: s.createdAt ? new Date(s.createdAt).toISOString() : null,
386
+ lastActivity: s.lastModified ? new Date(s.lastModified).toISOString() : null,
387
+ };
388
+ });
389
+ sendTo(ws, { type: "cli_session_list", sessions: filtered });
390
+ }).catch(function() {
391
+ // Fallback to manual parsing if SDK fails
392
+ var cliSessions = require("./cli-sessions");
393
+ cliSessions.listCliSessions(cwd).then(function(sessions) {
394
+ var filtered = sessions.filter(function(s) {
395
+ return !relayIds[s.sessionId];
396
+ });
397
+ sendTo(ws, { type: "cli_session_list", sessions: filtered });
398
+ }).catch(function() {
399
+ sendTo(ws, { type: "cli_session_list", sessions: [] });
400
+ });
401
+ });
402
+ return true;
403
+ }
404
+
405
+ if (msg.type === "switch_session") {
406
+ if (msg.id && sm.sessions.has(msg.id)) {
407
+ // If the target session's vendor doesn't own the currently cached
408
+ // model, clear sm.currentModel so the UI and next query don't leak
409
+ // the previous session's vendor-specific model into this one.
410
+ var switchTargetSess = sm.sessions.get(msg.id);
411
+ if (switchTargetSess && sm.currentModel) {
412
+ var targetVendor = switchTargetSess.vendor || sm.defaultVendor || null;
413
+ var tvModels = (targetVendor && sm.modelsByVendor && sm.modelsByVendor[targetVendor]) || [];
414
+ var found = false;
415
+ var _curLc = sm.currentModel.toLowerCase();
416
+ for (var tvi = 0; tvi < tvModels.length; tvi++) {
417
+ var tvEntry = tvModels[tvi];
418
+ var tvVal = typeof tvEntry === "string" ? tvEntry : (tvEntry && (tvEntry.value || tvEntry.id)) || "";
419
+ if (tvVal === sm.currentModel || (tvVal && (tvVal.toLowerCase().indexOf(_curLc) !== -1 || _curLc.indexOf(tvVal.toLowerCase()) !== -1))) { found = true; break; }
420
+ }
421
+ if (tvModels.length > 0 && !found) {
422
+ sm.currentModel = "";
423
+ }
424
+ }
425
+ // Check access in multi-user mode
426
+ if (usersModule.isMultiUser() && ws._clayUser) {
427
+ var switchTarget = sm.sessions.get(msg.id);
428
+ if (!usersModule.canAccessSession(ws._clayUser.id, switchTarget, { visibility: "public" })) return true;
429
+ ws._clayActiveSession = msg.id;
430
+ sm.switchSession(msg.id, ws, hydrateImageRefs);
431
+ broadcastPresence();
432
+ } else {
433
+ ws._clayActiveSession = msg.id;
434
+ sm.switchSession(msg.id, ws, hydrateImageRefs);
435
+ }
436
+ // Send per-session context sources
437
+ if (typeof loadContextSources === "function") {
438
+ var switchedSources = loadContextSources(slug, msg.id);
439
+ sendTo(ws, { type: "context_sources_state", active: switchedSources });
440
+ }
441
+ // Re-sync chip state to the incoming session's own model/mode.
442
+ // Sessions track their own model/permissionMode so the chip shows
443
+ // per-session values rather than the shared project state.
444
+ var _swSess = sm.sessions.get(msg.id);
445
+ var _swModel = (_swSess && _swSess.model) || sm.currentModel || "";
446
+ var _swMode = (_swSess && _swSess.permissionMode) || sm.currentPermissionMode || "default";
447
+ sendTo(ws, { type: "config_state", model: _swModel, mode: _swMode, effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
448
+ var swPresKey = ws._clayUser ? ws._clayUser.id : "_default";
449
+ userPresence.setPresence(slug, swPresKey, msg.id, null);
450
+ }
451
+ return true;
452
+ }
453
+
454
+ if (msg.type === "set_mate_dm") {
455
+ // set_mate_dm is a no-op now that mates are removed (lr-316f)
456
+ return true;
457
+ }
458
+
459
+ if (msg.type === "delete_session") {
460
+ if (ws._clayUser) {
461
+ var sdPerms = usersModule.getEffectivePermissions(ws._clayUser, osUsers);
462
+ if (!sdPerms.sessionDelete) {
463
+ sendTo(ws, { type: "error", text: "You do not have permission to delete sessions" });
464
+ return true;
465
+ }
466
+ }
467
+ if (msg.id && sm.sessions.has(msg.id)) {
468
+ sm.deleteSession(msg.id, ws);
469
+ }
470
+ return true;
471
+ }
472
+
473
+ if (msg.type === "rename_session") {
474
+ if (msg.id && sm.sessions.has(msg.id) && msg.title) {
475
+ var s = sm.sessions.get(msg.id);
476
+ s.title = String(msg.title).substring(0, 100);
477
+ s.titleManuallySet = true;
478
+ sm.saveSessionFile(s);
479
+ sm.broadcastSessionList();
480
+ // Sync title to SDK session
481
+ if (s.cliSessionId) {
482
+ adapter.renameSession(s.cliSessionId, s.title, { dir: cwd }).catch(function(e) {
483
+ console.error("[project] SDK renameSession failed:", e.message);
484
+ });
485
+ }
486
+ }
487
+ return true;
488
+ }
489
+
490
+ if (msg.type === "search_sessions") {
491
+ var results = sm.searchSessions(msg.query || "");
492
+ sendTo(ws, { type: "search_results", query: msg.query || "", results: results });
493
+ return true;
494
+ }
495
+
496
+ if (msg.type === "search_session_content") {
497
+ var targetSession = msg.id ? sm.sessions.get(msg.id) : getSessionForWs(ws);
498
+ if (!targetSession) return true;
499
+ var contentResults = sm.searchSessionContent(targetSession.localId, msg.query || "");
500
+ var searchResp = { type: "search_content_results", query: msg.query || "", sessionId: targetSession.localId, hits: contentResults.hits, total: contentResults.total };
501
+ if (msg.source) searchResp.source = msg.source;
502
+ sendTo(ws, searchResp);
503
+ return true;
504
+ }
505
+
506
+ // Update checks disabled — fork, not on chadbyte/clay release track.
507
+ if (msg.type === "set_update_channel") { return true; }
508
+
509
+ if (msg.type === "check_update") {
510
+ sendTo(ws, { type: "up_to_date", version: currentVersion });
511
+ return true;
512
+ }
513
+
514
+ if (msg.type === "update_now") {
515
+ if (usersModule.isMultiUser() && (!ws._clayUser || ws._clayUser.role !== "admin")) return true;
516
+ send({ type: "update_started", version: getLatestVersion() || "" });
517
+ var _ipc = require("./ipc");
518
+ var _config = require("./config");
519
+ _ipc.sendIPCCommand(_config.socketPath(), { cmd: "update" });
520
+ return true;
521
+ }
522
+
523
+ if (msg.type === "process_stats") {
524
+ var sessionCount = sm.sessions.size;
525
+ var processingCount = 0;
526
+ sm.sessions.forEach(function (s) {
527
+ if (s.isProcessing) processingCount++;
528
+ });
529
+ var mem = process.memoryUsage();
530
+ sendTo(ws, {
531
+ type: "process_stats",
532
+ pid: process.pid,
533
+ uptime: process.uptime(),
534
+ memory: {
535
+ rss: mem.rss,
536
+ heapUsed: mem.heapUsed,
537
+ heapTotal: mem.heapTotal,
538
+ external: mem.external,
539
+ },
540
+ sessions: sessionCount,
541
+ processing: processingCount,
542
+ clients: clients.size,
543
+ terminals: tm.list().length,
544
+ });
545
+ return true;
546
+ }
547
+
548
+ if (msg.type === "stop") {
549
+ var session = getSessionForWs(ws);
550
+ if (session && session.isProcessing) {
551
+ session.taskStopRequested = true;
552
+ if (session.abortController) session.abortController.abort();
553
+ }
554
+ return true;
555
+ }
556
+
557
+ if (msg.type === "stop_task") {
558
+ if (msg.taskId) {
559
+ sdk.stopTask(msg.taskId);
560
+ }
561
+ return true;
562
+ }
563
+
564
+ if (msg.type === "kill_process") {
565
+ var pid = msg.pid;
566
+ if (!pid || typeof pid !== "number") return true;
567
+ // Verify target is actually a claude process before killing
568
+ if (!sdk.isClaudeProcess(pid)) {
569
+ console.error("[project] Refused to kill PID " + pid + ": not a claude process");
570
+ sendTo(ws, { type: "error", text: "Process " + pid + " is not a Claude process." });
571
+ return true;
572
+ }
573
+ try {
574
+ process.kill(pid, "SIGTERM");
575
+ console.log("[project] Sent SIGTERM to conflicting Claude process PID " + pid);
576
+ sendTo(ws, { type: "process_killed", pid: pid });
577
+ } catch (e) {
578
+ console.error("[project] Failed to kill PID " + pid + ":", e.message);
579
+ sendTo(ws, { type: "error", text: "Failed to kill process " + pid + ": " + (e.message || e) });
580
+ }
581
+ return true;
582
+ }
583
+
584
+ if (msg.type === "set_model" && msg.model) {
585
+ var session = getSessionForWs(ws);
586
+ if (session) {
587
+ sdk.setModel(session, msg.model).then(function () {
588
+ // Targeted reply — only this client's chip updates, not all sessions.
589
+ sendTo(ws, { type: "config_state", model: session.model || sm.currentModel || "", mode: session.permissionMode || sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
590
+ });
591
+ }
592
+ return true;
593
+ }
594
+
595
+ if (msg.type === "set_vendor" && msg.vendor) {
596
+ var vendorSession = getSessionForWs(ws);
597
+ if (vendorSession) {
598
+ // Refuse to rebind vendor on a session that is already bound to a
599
+ // different CLI (cliSessionId is vendor-specific). This prevents a
600
+ // stale client-side vendor state from clobbering the persisted vendor
601
+ // on page reload / server restart.
602
+ var alreadyBound = vendorSession.cliSessionId && vendorSession.vendor && vendorSession.vendor !== msg.vendor;
603
+ if (alreadyBound) {
604
+ console.warn("[project] set_vendor ignored: session " + vendorSession.localId +
605
+ " is bound to '" + vendorSession.vendor + "', refused rebind to '" + msg.vendor + "'");
606
+ } else {
607
+ vendorSession.vendor = msg.vendor;
608
+ // Clear the shared model so the next query uses the vendor's default
609
+ // instead of leaking the previous vendor's model into a fresh session.
610
+ if (sm.currentModel) {
611
+ sm.currentModel = "";
612
+ }
613
+ sm.saveSessionFile(vendorSession);
614
+ sm.broadcastSessionList();
615
+ }
616
+ }
617
+ if (msg.vendor) {
618
+ var vendorModels = (sm.modelsByVendor && sm.modelsByVendor[msg.vendor]) || [];
619
+ sendTo(ws, {
620
+ type: "model_info",
621
+ model: "",
622
+ models: vendorModels,
623
+ vendor: msg.vendor,
624
+ availableVendors: sm.availableVendors || [],
625
+ installedVendors: sm.installedVendors || [],
626
+ });
627
+ send({ 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 });
628
+ }
629
+ return true;
630
+ }
631
+
632
+ if (msg.type === "set_server_default_model" && msg.model) {
633
+ if (typeof opts.onSetServerDefaultModel === "function") {
634
+ opts.onSetServerDefaultModel(msg.model);
635
+ }
636
+ var session = getSessionForWs(ws);
637
+ if (session) {
638
+ sdk.setModel(session, msg.model);
639
+ }
640
+ return true;
641
+ }
642
+
643
+ if (msg.type === "set_project_default_model" && msg.model) {
644
+ if (typeof opts.onSetProjectDefaultModel === "function") {
645
+ opts.onSetProjectDefaultModel(slug, msg.model);
646
+ }
647
+ var session = getSessionForWs(ws);
648
+ if (session) {
649
+ sdk.setModel(session, msg.model);
650
+ }
651
+ return true;
652
+ }
653
+
654
+ if (msg.type === "set_permission_mode" && msg.mode) {
655
+ var session = getSessionForWs(ws);
656
+ if (session) {
657
+ sdk.setPermissionMode(session, msg.mode).then(function () {
658
+ // Targeted reply — only update the requesting client's chip.
659
+ sendTo(ws, { type: "config_state", model: session.model || sm.currentModel || "", mode: session.permissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [], thinking: sm.currentThinking || "adaptive", thinkingBudget: sm.currentThinkingBudget || 10000 });
660
+ });
661
+ }
662
+ return true;
663
+ }
664
+
665
+ if (msg.type === "set_server_default_mode" && msg.mode) {
666
+ if (typeof opts.onSetServerDefaultMode === "function") {
667
+ opts.onSetServerDefaultMode(msg.mode);
668
+ }
669
+ sm.currentPermissionMode = msg.mode;
670
+ var session = getSessionForWs(ws);
671
+ if (session) {
672
+ sdk.setPermissionMode(session, msg.mode);
673
+ }
674
+ 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 });
675
+ return true;
676
+ }
677
+
678
+ if (msg.type === "set_project_default_mode" && msg.mode) {
679
+ if (typeof opts.onSetProjectDefaultMode === "function") {
680
+ opts.onSetProjectDefaultMode(slug, msg.mode);
681
+ }
682
+ sm.currentPermissionMode = msg.mode;
683
+ // Apply to ALL active sessions in this project, not just the focused one.
684
+ // Without this, sessions that already started a query keep the old mode.
685
+ sm.sessions.forEach(function (s) {
686
+ sdk.setPermissionMode(s, msg.mode);
687
+ });
688
+ 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 });
689
+ return true;
690
+ }
691
+
692
+ if (msg.type === "set_effort" && msg.effort) {
693
+ sm.currentEffort = msg.effort;
694
+ var session = getSessionForWs(ws);
695
+ if (session) {
696
+ sdk.setEffort(session, msg.effort);
697
+ }
698
+ 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 });
699
+ return true;
700
+ }
701
+
702
+ if (msg.type === "set_server_default_effort" && msg.effort) {
703
+ if (typeof opts.onSetServerDefaultEffort === "function") {
704
+ opts.onSetServerDefaultEffort(msg.effort);
705
+ }
706
+ sm.currentEffort = msg.effort;
707
+ 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 });
708
+ return true;
709
+ }
710
+
711
+ if (msg.type === "set_project_default_effort" && msg.effort) {
712
+ if (typeof opts.onSetProjectDefaultEffort === "function") {
713
+ opts.onSetProjectDefaultEffort(slug, msg.effort);
714
+ }
715
+ sm.currentEffort = msg.effort;
716
+ 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 });
717
+ return true;
718
+ }
719
+
720
+ if (msg.type === "set_betas") {
721
+ sm.currentBetas = msg.betas || [];
722
+ send({ 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 });
723
+ return true;
724
+ }
725
+
726
+ if (msg.type === "set_server_default_betas") {
727
+ if (typeof opts.onSetServerDefaultBetas === "function") {
728
+ opts.onSetServerDefaultBetas(msg.betas || []);
729
+ }
730
+ sm.currentBetas = msg.betas || [];
731
+ send({ 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 });
732
+ return true;
733
+ }
734
+
735
+ if (msg.type === "set_project_default_betas") {
736
+ if (typeof opts.onSetProjectDefaultBetas === "function") {
737
+ opts.onSetProjectDefaultBetas(slug, msg.betas || []);
738
+ }
739
+ sm.currentBetas = msg.betas || [];
740
+ send({ 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 });
741
+ return true;
742
+ }
743
+
744
+ if (msg.type === "set_thinking") {
745
+ sm.currentThinking = msg.thinking || "adaptive";
746
+ if (msg.budgetTokens) sm.currentThinkingBudget = msg.budgetTokens;
747
+ send({ 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 });
748
+ return true;
749
+ }
750
+
751
+ // Codex-specific settings (stored on sessionManager, passed to adapter via adapterOptions)
752
+ if (msg.type === "set_codex_approval") {
753
+ sm.codexApproval = msg.approval || CODEX_DEFAULTS.approval;
754
+ send(Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
755
+ return true;
756
+ }
757
+ if (msg.type === "set_codex_sandbox") {
758
+ sm.codexSandbox = msg.sandbox || CODEX_DEFAULTS.sandbox;
759
+ send(Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
760
+ return true;
761
+ }
762
+ if (msg.type === "set_codex_websearch") {
763
+ sm.codexWebSearch = msg.webSearch || CODEX_DEFAULTS.webSearch;
764
+ send(Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
765
+ return true;
766
+ }
767
+
768
+ if (msg.type === "rewind_preview") {
769
+ var session = getSessionForWs(ws);
770
+ if (!session || !session.cliSessionId || !msg.uuid) return true;
771
+ if (session._rewindInProgress) return true;
772
+
773
+ (async function () {
774
+ try {
775
+ var r = await sdk.rewindPreview(session, msg.uuid);
776
+ sendTo(ws, { type: "rewind_preview_result", preview: r.preview, diffs: r.diffs, uuid: msg.uuid, chatOnly: r.chatOnly || false });
777
+ } catch (err) {
778
+ sendTo(ws, { type: "rewind_error", text: "Failed to preview rewind: " + err.message });
779
+ }
780
+ })();
781
+ return true;
782
+ }
783
+
784
+ if (msg.type === "rewind_execute") {
785
+ var session = getSessionForWs(ws);
786
+ if (!session || !session.cliSessionId || !msg.uuid) return true;
787
+ // Guard against concurrent rewind executions
788
+ if (session._rewindInProgress) {
789
+ sendTo(ws, { type: "rewind_error", text: "Rewind already in progress." });
790
+ return true;
791
+ }
792
+ session._rewindInProgress = true;
793
+ var mode = msg.mode || "both";
794
+
795
+ (async function () {
796
+ try {
797
+ // File restoration (delegated to adapter via sdk-bridge)
798
+ if (mode !== "chat") {
799
+ await sdk.rewindExecuteFiles(session, msg.uuid);
800
+ }
801
+
802
+ // Conversation rollback (skip for files-only mode)
803
+ if (mode !== "files") {
804
+ var targetIdx = -1;
805
+ for (var i = 0; i < session.messageUUIDs.length; i++) {
806
+ if (session.messageUUIDs[i].uuid === msg.uuid) {
807
+ targetIdx = i;
808
+ break;
809
+ }
810
+ }
811
+
812
+ // Count turns to roll back BEFORE trimming local history
813
+ var turnsToRollBack = 0;
814
+ if (targetIdx >= 0) {
815
+ for (var ri = targetIdx; ri < session.messageUUIDs.length; ri++) {
816
+ if (session.messageUUIDs[ri].type === "user") turnsToRollBack++;
817
+ }
818
+ }
819
+
820
+ if (targetIdx >= 0) {
821
+ var trimTo = session.messageUUIDs[targetIdx].historyIndex;
822
+ for (var k = trimTo - 1; k >= 0; k--) {
823
+ if (session.history[k].type === "user_message") {
824
+ trimTo = k;
825
+ break;
826
+ }
827
+ }
828
+ session.history = session.history.slice(0, trimTo);
829
+ session.messageUUIDs = session.messageUUIDs.slice(0, targetIdx);
830
+ // Reset digest checkpoint if it points past the trimmed history
831
+ if (typeof session._dmLastDigestedIndex === "number" && session._dmLastDigestedIndex > trimTo) {
832
+ session._dmLastDigestedIndex = trimTo;
833
+ }
834
+ }
835
+
836
+ // Notify adapter of conversation rollback (e.g. Codex thread/rollback)
837
+ if (turnsToRollBack > 0) {
838
+ try {
839
+ await sdk.rollbackConversation(session, turnsToRollBack);
840
+ } catch (rbErr) {
841
+ console.error("[project-sessions] conversation rollback failed:", rbErr.message || rbErr);
842
+ }
843
+ }
844
+
845
+ var kept = session.messageUUIDs;
846
+ session.lastRewindUuid = kept.length > 0 ? kept[kept.length - 1].uuid : null;
847
+ }
848
+
849
+ if (session.abortController) {
850
+ try { session.abortController.abort(); } catch (e) {}
851
+ }
852
+ if (session.messageQueue) {
853
+ try { session.messageQueue.end(); } catch (e) {}
854
+ }
855
+ session.queryInstance = null;
856
+ session.messageQueue = null;
857
+ session.abortController = null;
858
+ session.blocks = {};
859
+ session.sentToolResults = {};
860
+ session.pendingPermissions = {};
861
+ session.pendingAskUser = {};
862
+ session.isProcessing = false;
863
+ onProcessingChanged();
864
+
865
+ sm.saveSessionFile(session);
866
+ sm.switchSession(session.localId, ws, hydrateImageRefs);
867
+ sm.sendAndRecord(session, { type: "rewind_complete", mode: mode });
868
+ sm.broadcastSessionList();
869
+ } catch (err) {
870
+ sendTo(ws, { type: "rewind_error", text: "Rewind failed: " + err.message });
871
+ } finally {
872
+ session._rewindInProgress = false;
873
+ }
874
+ })();
875
+ return true;
876
+ }
877
+
878
+ if (msg.type === "fork_session" && msg.uuid) {
879
+ var session = getSessionForWs(ws);
880
+ if (!session || !session.cliSessionId) {
881
+ sendTo(ws, { type: "error", text: "Cannot fork: no CLI session" });
882
+ return true;
883
+ }
884
+ var forkTitle = (session.title || "New Session") + " (fork)";
885
+
886
+ sdk.forkSession(session, msg.uuid).then(function(result) {
887
+ if (result.useLocalHistory) {
888
+ // Copy local history up to the target UUID
889
+ var targetIdx = -1;
890
+ for (var fi = 0; fi < session.messageUUIDs.length; fi++) {
891
+ if (session.messageUUIDs[fi].uuid === msg.uuid) { targetIdx = fi; break; }
892
+ }
893
+ var forkHistory = [];
894
+ if (targetIdx >= 0) {
895
+ var trimTo = session.messageUUIDs[targetIdx].historyIndex;
896
+ forkHistory = session.history.slice(0, trimTo);
897
+ } else {
898
+ forkHistory = session.history.slice();
899
+ }
900
+ var forked = sm.createSession({ vendor: session.vendor, ownerId: session.ownerId || null }, ws);
901
+ forked.cliSessionId = result.sessionId;
902
+ forked.title = forkTitle;
903
+ forked.history = forkHistory;
904
+ forked.messageUUIDs = [];
905
+ for (var hi = 0; hi < forkHistory.length; hi++) {
906
+ if (forkHistory[hi].type === "message_uuid") {
907
+ forked.messageUUIDs.push({ uuid: forkHistory[hi].uuid, type: forkHistory[hi].messageType, historyIndex: hi });
908
+ }
909
+ }
910
+ sm.saveSessionFile(forked);
911
+ sm.switchSession(forked.localId, ws, hydrateImageRefs);
912
+ sendTo(ws, { type: "fork_complete", sessionId: forked.localId });
913
+ sm.broadcastSessionList();
914
+ } else {
915
+ // Read history from CLI session files
916
+ var cliSess = require("./cli-sessions");
917
+ return cliSess.readCliSessionHistory(cwd, result.sessionId).then(function(history) {
918
+ var forked = sm.resumeSession(result.sessionId, { history: history, title: forkTitle }, ws);
919
+ if (forked) {
920
+ ws._clayActiveSession = forked.localId;
921
+ sendTo(ws, { type: "fork_complete", sessionId: forked.localId });
922
+ }
923
+ });
924
+ }
925
+ }).catch(function(e) {
926
+ sendTo(ws, { type: "error", text: "Fork failed: " + (e.message || e) });
927
+ });
928
+ return true;
929
+ }
930
+
931
+ if (msg.type === "ask_user_response") {
932
+ var session = getSessionForWs(ws);
933
+ if (!session) return true;
934
+ var toolId = msg.toolId;
935
+ var answers = msg.answers || {};
936
+ var pending = session.pendingAskUser[toolId];
937
+ if (!pending) return true;
938
+ delete session.pendingAskUser[toolId];
939
+ sm.sendAndRecord(session, { type: "ask_user_answered", toolId: toolId, answers: answers });
940
+
941
+ if (pending.mode === "mcp") {
942
+ // Stateless MCP path: the tool already returned. Inject the user's
943
+ // answer as a new user message so the conversation continues
944
+ // naturally on the next turn. This matches how the mate would see
945
+ // any other user input.
946
+ var answerText = formatAskUserAnswerAsMessage(pending.input, answers);
947
+ var userMsg = { type: "user_message", text: answerText };
948
+ session.history.push(userMsg);
949
+ sm.appendToSessionFile(session, userMsg);
950
+ sendToSession(session.localId, userMsg);
951
+
952
+ if (!session.isProcessing) {
953
+ session.isProcessing = true;
954
+ onProcessingChanged();
955
+ session.sentToolResults = {};
956
+ sendToSession(session.localId, { type: "status", status: "processing" });
957
+ if (!session.queryInstance && !session.worker) {
958
+ sdk.startQuery(session, answerText, undefined, ensureProjectAccessForSession(session));
959
+ } else {
960
+ sdk.pushMessage(session, answerText);
961
+ }
962
+ } else {
963
+ // Turn is still running; queue for the next turn.
964
+ sdk.pushMessage(session, answerText);
965
+ }
966
+ } else {
967
+ // Claude native AskUserQuestion path (canUseTool). The SDK is
968
+ // synchronously blocked on the permission callback, so we must
969
+ // resolve it with the standard permission shape.
970
+ //
971
+ // The CLI's AskUserQuestion tool expects answers keyed by question
972
+ // TEXT (e.g. {"What is your goal?": "Build a widget"}), not by
973
+ // numeric index. Clay's client sends index-keyed answers
974
+ // ({"0": "Build a widget"}). Remap here before passing to the CLI.
975
+ //
976
+ // Both camelCase (updatedInput) and snake_case (updated_input) are
977
+ // included: the SDK passes the object through as-is and the stdio
978
+ // permission handler reads the snake_case key.
979
+ var questions = (pending.input && Array.isArray(pending.input.questions))
980
+ ? pending.input.questions : [];
981
+ var textKeyedAnswers = {};
982
+ for (var qi = 0; qi < questions.length; qi++) {
983
+ var qText = questions[qi] && questions[qi].question;
984
+ if (qText && answers[qi] != null) {
985
+ textKeyedAnswers[qText] = answers[qi];
986
+ }
987
+ }
988
+ var updatedInput = Object.assign({}, pending.input, { answers: textKeyedAnswers });
989
+ pending.resolve({
990
+ behavior: "allow",
991
+ updatedInput: updatedInput,
992
+ updated_input: updatedInput,
993
+ });
994
+ }
995
+ return true;
996
+ }
997
+
998
+ if (msg.type === "input_sync") {
999
+ sendToSessionOthers(ws, ws._clayActiveSession, msg);
1000
+ return true;
1001
+ }
1002
+
1003
+ if (msg.type === "cursor_move" || msg.type === "cursor_leave" || msg.type === "text_select") {
1004
+ if (!usersModule.isMultiUser() || !ws._clayUser) return true;
1005
+ var u = ws._clayUser;
1006
+ var p = u.profile || {};
1007
+ var cursorMsg = {
1008
+ type: msg.type,
1009
+ userId: u.id,
1010
+ displayName: p.name || u.displayName || u.username,
1011
+ avatarStyle: p.avatarStyle || "thumbs",
1012
+ avatarSeed: p.avatarSeed || u.username,
1013
+ avatarCustom: p.avatarCustom || "",
1014
+ };
1015
+ if (msg.type === "cursor_move") {
1016
+ cursorMsg.turn = msg.turn;
1017
+ if (msg.rx != null) cursorMsg.rx = msg.rx;
1018
+ if (msg.ry != null) cursorMsg.ry = msg.ry;
1019
+ }
1020
+ if (msg.type === "text_select") {
1021
+ cursorMsg.ranges = msg.ranges || [];
1022
+ }
1023
+ sendToSessionOthers(ws, ws._clayActiveSession, cursorMsg);
1024
+ return true;
1025
+ }
1026
+
1027
+ if (msg.type === "permission_response") {
1028
+ var requestId = msg.requestId;
1029
+ var decision = msg.decision;
1030
+ // Look up session by requestId index (O(1)), fall back to active session
1031
+ var sessionId = sm.permissionRequestIndex[requestId];
1032
+ var session = sessionId ? sm.sessions.get(sessionId) : getSessionForWs(ws);
1033
+ if (!session) return true;
1034
+ var pending = session.pendingPermissions[requestId];
1035
+ if (!pending) return true;
1036
+ delete sm.permissionRequestIndex[requestId];
1037
+ delete session.pendingPermissions[requestId];
1038
+ onProcessingChanged(); // update cross-project permission badge
1039
+
1040
+ // --- Plan approval: "allow_accept_edits" -- approve + switch to acceptEdits mode ---
1041
+ if (decision === "allow_accept_edits") {
1042
+ sdk.setPermissionMode(session, "acceptEdits");
1043
+ sm.currentPermissionMode = "acceptEdits";
1044
+ 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 });
1045
+ pending.resolve({ behavior: "allow", updatedInput: pending.toolInput });
1046
+ sm.sendAndRecord(session, { type: "permission_resolved", requestId: requestId, decision: decision });
1047
+ return true;
1048
+ }
1049
+
1050
+ // --- Plan approval: "allow_clear_context" -- new session + plan as first message + acceptEdits ---
1051
+ if (decision === "allow_clear_context") {
1052
+ // Deny current plan to end the turn
1053
+ pending.resolve({ behavior: "deny", message: "User chose to clear context and restart" });
1054
+ sm.sendAndRecord(session, { type: "permission_resolved", requestId: requestId, decision: decision });
1055
+
1056
+ // Abort the old session's query -- but defer to next tick so the SDK's
1057
+ // deny write (scheduled as microtask by pending.resolve) completes first.
1058
+ // Aborting synchronously would kill the subprocess before the write,
1059
+ // causing an "Operation aborted" crash in the SDK.
1060
+ session.isProcessing = false;
1061
+ onProcessingChanged();
1062
+ session.pendingPermissions = {};
1063
+ session.pendingAskUser = {};
1064
+ sm.broadcastSessionList();
1065
+ setImmediate(function () {
1066
+ if (session.abortController) {
1067
+ session.abortController.abort();
1068
+ }
1069
+ });
1070
+
1071
+ // Update permission mode for the new session
1072
+ sm.currentPermissionMode = "acceptEdits";
1073
+ 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 });
1074
+
1075
+ // Build prompt from plan content (sent from client) or plan file path
1076
+ var clientPlanContent = msg.planContent || "";
1077
+ var planPrompt;
1078
+ if (clientPlanContent) {
1079
+ planPrompt = "Execute the following plan. Do NOT re-enter plan mode -- just implement it step by step.\n\n" + clientPlanContent;
1080
+ } else {
1081
+ var planFilePath = (pending.toolInput && pending.toolInput.planFilePath) || "";
1082
+ planPrompt = "Execute the plan in " + planFilePath + ". Do NOT re-enter plan mode -- read the plan file and implement it step by step.";
1083
+ }
1084
+
1085
+ // Wait for old query stream to fully terminate, then create new session + send plan
1086
+ var oldStreamPromise = session.streamPromise || Promise.resolve();
1087
+ Promise.race([
1088
+ oldStreamPromise,
1089
+ new Promise(function (resolve) { setTimeout(resolve, 3000); }),
1090
+ ]).then(function () {
1091
+ try {
1092
+ var newSession = sm.createSession(null, ws);
1093
+ // Send the plan as the first user message (with planContent for UI rendering)
1094
+ var userMsg = { type: "user_message", text: planPrompt, planContent: clientPlanContent || null };
1095
+ newSession.history.push(userMsg);
1096
+ sm.appendToSessionFile(newSession, userMsg);
1097
+ newSession.title = "Plan execution (cleared context)";
1098
+ sm.saveSessionFile(newSession);
1099
+ sm.broadcastSessionList();
1100
+ sendToSession(newSession.localId, userMsg);
1101
+
1102
+ newSession.isProcessing = true;
1103
+ onProcessingChanged();
1104
+ newSession.sentToolResults = {};
1105
+ sendToSession(newSession.localId, { type: "status", status: "processing" });
1106
+ newSession.acceptEditsAfterStart = true;
1107
+ sdk.startQuery(newSession, planPrompt, undefined, ensureProjectAccessForSession(newSession));
1108
+ } catch (e) {
1109
+ console.error("[project] Error starting plan execution:", e);
1110
+ sendTo(ws, { type: "error", text: "Failed to start plan execution: " + (e.message || e) });
1111
+ }
1112
+ }).catch(function (e) {
1113
+ console.error("[project] Plan execution stream wait failed:", e.message || e);
1114
+ });
1115
+ return true;
1116
+ }
1117
+
1118
+ // --- Plan approval: "deny_with_feedback" -- deny + send feedback as follow-up message ---
1119
+ if (decision === "deny_with_feedback") {
1120
+ var feedback = msg.feedback || "";
1121
+ pending.resolve({ behavior: "deny", message: feedback || "User provided feedback" });
1122
+ sm.sendAndRecord(session, { type: "permission_resolved", requestId: requestId, decision: decision });
1123
+
1124
+ // Send feedback as next user message if there's text
1125
+ if (feedback) {
1126
+ setTimeout(function () {
1127
+ var userMsg = { type: "user_message", text: feedback };
1128
+ session.history.push(userMsg);
1129
+ sm.appendToSessionFile(session, userMsg);
1130
+ sendToSession(session.localId, userMsg);
1131
+
1132
+ if (!session.isProcessing) {
1133
+ session.isProcessing = true;
1134
+ onProcessingChanged();
1135
+ session.sentToolResults = {};
1136
+ sendToSession(session.localId, { type: "status", status: "processing" });
1137
+ if (!session.queryInstance && !session.worker) {
1138
+ sdk.startQuery(session, feedback, undefined, ensureProjectAccessForSession(session));
1139
+ } else {
1140
+ sdk.pushMessage(session, feedback);
1141
+ }
1142
+ } else {
1143
+ sdk.pushMessage(session, feedback);
1144
+ }
1145
+ }, 200);
1146
+ }
1147
+ return true;
1148
+ }
1149
+
1150
+ if (decision === "allow" || decision === "allow_always") {
1151
+ if (decision === "allow_always") {
1152
+ if (!session.allowedTools) session.allowedTools = {};
1153
+ session.allowedTools[pending.toolName] = true;
1154
+ }
1155
+ pending.resolve({ behavior: "allow", updatedInput: pending.toolInput });
1156
+ } else {
1157
+ pending.resolve({ behavior: "deny", message: "User denied permission" });
1158
+ }
1159
+
1160
+ sm.sendAndRecord(session, {
1161
+ type: "permission_resolved",
1162
+ requestId: requestId,
1163
+ decision: decision,
1164
+ });
1165
+ return true;
1166
+ }
1167
+
1168
+ // --- MCP elicitation response ---
1169
+ if (msg.type === "elicitation_response") {
1170
+ var session = getSessionForWs(ws);
1171
+ if (!session) return true;
1172
+ var pending = session.pendingElicitations && session.pendingElicitations[msg.requestId];
1173
+ if (!pending) return true;
1174
+ delete session.pendingElicitations[msg.requestId];
1175
+ if (msg.action === "accept") {
1176
+ pending.resolve({ action: "accept", content: msg.content || {} });
1177
+ } else {
1178
+ pending.resolve({ action: "reject" });
1179
+ }
1180
+ sm.sendAndRecord(session, {
1181
+ type: "elicitation_resolved",
1182
+ requestId: msg.requestId,
1183
+ action: msg.action,
1184
+ });
1185
+ return true;
1186
+ }
1187
+
1188
+ // --- Browse directories (for add-project autocomplete) ---
1189
+ if (msg.type === "browse_dir") {
1190
+ var rawPath = (msg.path || "").replace(/^~/, require("./config").REAL_HOME);
1191
+ var absTarget = path.resolve(rawPath);
1192
+ // Multi-user mode: non-admins can only browse their home directory
1193
+ if (osUsers && osUsers.length > 0 && ws._clayUser && ws._clayUser.role !== "admin") {
1194
+ var browseHome = ws._clayUser.linuxUser ? "/home/" + ws._clayUser.linuxUser : null;
1195
+ if (!browseHome || (absTarget !== browseHome && (absTarget + "/").indexOf(browseHome + "/") !== 0)) {
1196
+ sendTo(ws, { type: "browse_dir_result", path: msg.path, entries: [], error: "Access restricted to your home directory" });
1197
+ return true;
1198
+ }
1199
+ }
1200
+ var parentDir, prefix;
1201
+ try {
1202
+ var stat = fs.statSync(absTarget);
1203
+ if (stat.isDirectory()) {
1204
+ // Input is an existing directory -- list its children
1205
+ parentDir = absTarget;
1206
+ prefix = "";
1207
+ } else {
1208
+ parentDir = path.dirname(absTarget);
1209
+ prefix = path.basename(absTarget).toLowerCase();
1210
+ }
1211
+ } catch (e) {
1212
+ // Path doesn't exist -- list parent and filter by typed prefix
1213
+ parentDir = path.dirname(absTarget);
1214
+ prefix = path.basename(absTarget).toLowerCase();
1215
+ }
1216
+ try {
1217
+ var dirItems = fs.readdirSync(parentDir, { withFileTypes: true });
1218
+ var dirEntries = [];
1219
+ for (var di = 0; di < dirItems.length; di++) {
1220
+ var d = dirItems[di];
1221
+ if (!d.isDirectory()) continue;
1222
+ if (d.name.charAt(0) === ".") continue;
1223
+ if (IGNORED_DIRS.has(d.name)) continue;
1224
+ if (prefix && !d.name.toLowerCase().startsWith(prefix)) continue;
1225
+ dirEntries.push({ name: d.name, path: path.join(parentDir, d.name) });
1226
+ }
1227
+ dirEntries.sort(function (a, b) { return a.name.localeCompare(b.name); });
1228
+ sendTo(ws, { type: "browse_dir_result", path: msg.path, entries: dirEntries });
1229
+ } catch (e) {
1230
+ sendTo(ws, { type: "browse_dir_result", path: msg.path, entries: [], error: e.message });
1231
+ }
1232
+ return true;
1233
+ }
1234
+
1235
+ // --- Add project from web UI ---
1236
+ if (msg.type === "add_project") {
1237
+ var addPath = (msg.path || "").replace(/^~/, require("./config").REAL_HOME);
1238
+ var addAbs = path.resolve(addPath);
1239
+ // Multi-user mode: normal users restricted to their home directory
1240
+ if (osUsers && osUsers.length > 0 && ws._clayUser && ws._clayUser.role !== "admin") {
1241
+ if (!ws._clayUser.linuxUser) {
1242
+ sendTo(ws, { type: "add_project_result", ok: false, error: "No Linux user assigned" });
1243
+ return true;
1244
+ }
1245
+ var userHome = "/home/" + ws._clayUser.linuxUser;
1246
+ if (addAbs !== userHome && (addAbs + "/").indexOf(userHome + "/") !== 0) {
1247
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Path not allowed. You can only add directories under " + userHome });
1248
+ return true;
1249
+ }
1250
+ }
1251
+ try {
1252
+ var addStat = fs.statSync(addAbs);
1253
+ if (!addStat.isDirectory()) {
1254
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Not a directory" });
1255
+ return true;
1256
+ }
1257
+ } catch (e) {
1258
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Directory not found" });
1259
+ return true;
1260
+ }
1261
+ if (typeof opts.onAddProject === "function") {
1262
+ var result = opts.onAddProject(addAbs, ws._clayUser);
1263
+ sendTo(ws, { type: "add_project_result", ok: result.ok, slug: result.slug, error: result.error, existing: result.existing });
1264
+ } else {
1265
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Not supported" });
1266
+ }
1267
+ return true;
1268
+ }
1269
+
1270
+ // --- Create new empty project ---
1271
+ if (msg.type === "create_project" || msg.type === "clone_project") {
1272
+ if (ws._clayUser) {
1273
+ var cpPerms = usersModule.getEffectivePermissions(ws._clayUser, osUsers);
1274
+ if (!cpPerms.createProject) {
1275
+ sendTo(ws, { type: "add_project_result", ok: false, error: "You do not have permission to create projects" });
1276
+ return true;
1277
+ }
1278
+ }
1279
+ }
1280
+ if (msg.type === "create_project") {
1281
+ var createName = (msg.name || "").trim();
1282
+ if (!createName || !/^[a-zA-Z0-9_-]+$/.test(createName)) {
1283
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Invalid name. Use only letters, numbers, dashes, and underscores." });
1284
+ return true;
1285
+ }
1286
+ if (typeof opts.onCreateProject === "function") {
1287
+ var createResult = opts.onCreateProject(createName, ws._clayUser);
1288
+ sendTo(ws, { type: "add_project_result", ok: createResult.ok, slug: createResult.slug, error: createResult.error });
1289
+ } else {
1290
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Not supported" });
1291
+ }
1292
+ return true;
1293
+ }
1294
+
1295
+ // --- Clone project from GitHub ---
1296
+ if (msg.type === "clone_project") {
1297
+ var cloneUrl = (msg.url || "").trim();
1298
+ if (!cloneUrl || (!/^https?:\/\//.test(cloneUrl) && !/^git@/.test(cloneUrl))) {
1299
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Invalid URL. Use https:// or git@ format." });
1300
+ return true;
1301
+ }
1302
+ sendTo(ws, { type: "clone_project_progress", status: "cloning" });
1303
+ if (typeof opts.onCloneProject === "function") {
1304
+ opts.onCloneProject(cloneUrl, ws._clayUser, function (cloneResult) {
1305
+ sendTo(ws, { type: "add_project_result", ok: cloneResult.ok, slug: cloneResult.slug, error: cloneResult.error });
1306
+ });
1307
+ } else {
1308
+ sendTo(ws, { type: "add_project_result", ok: false, error: "Not supported" });
1309
+ }
1310
+ return true;
1311
+ }
1312
+
1313
+ // --- Create worktree from web UI ---
1314
+ if (msg.type === "create_worktree") {
1315
+ var wtBranch = (msg.branch || "").trim();
1316
+ var wtDirName = (msg.dirName || "").trim() || wtBranch.replace(/\//g, "-");
1317
+ var wtBase = (msg.baseBranch || "").trim() || null;
1318
+ if (!wtBranch || !/^[a-zA-Z0-9_\/.@-]+$/.test(wtBranch)) {
1319
+ sendTo(ws, { type: "create_worktree_result", ok: false, error: "Invalid branch name" });
1320
+ return true;
1321
+ }
1322
+ if (typeof onCreateWorktree === "function") {
1323
+ var wtResult = onCreateWorktree(slug, wtBranch, wtDirName, wtBase);
1324
+ sendTo(ws, { type: "create_worktree_result", ok: wtResult.ok, slug: wtResult.slug, error: wtResult.error });
1325
+ } else {
1326
+ sendTo(ws, { type: "create_worktree_result", ok: false, error: "Not supported" });
1327
+ }
1328
+ return true;
1329
+ }
1330
+
1331
+ // --- Pre-check: does the project have tasks/schedules? ---
1332
+ if (msg.type === "remove_project_check") {
1333
+ var checkSlug = msg.slug;
1334
+ if (!checkSlug) {
1335
+ sendTo(ws, { type: "remove_project_check_result", slug: checkSlug, name: msg.name || checkSlug, count: 0 });
1336
+ return true;
1337
+ }
1338
+ var schedCount = getScheduleCount(checkSlug);
1339
+ sendTo(ws, { type: "remove_project_check_result", slug: checkSlug, name: msg.name || checkSlug, count: schedCount });
1340
+ return true;
1341
+ }
1342
+
1343
+ // --- Remove project from web UI ---
1344
+ if (msg.type === "remove_project") {
1345
+ if (ws._clayUser) {
1346
+ var dpPerms = usersModule.getEffectivePermissions(ws._clayUser, osUsers);
1347
+ if (!dpPerms.deleteProject) {
1348
+ sendTo(ws, { type: "remove_project_result", ok: false, error: "You do not have permission to delete projects" });
1349
+ return true;
1350
+ }
1351
+ }
1352
+ var removeSlug = msg.slug;
1353
+ if (!removeSlug) {
1354
+ sendTo(ws, { type: "remove_project_result", ok: false, error: "Missing slug" });
1355
+ return true;
1356
+ }
1357
+ // If client chose to move tasks to another project before removing
1358
+ if (msg.moveTasksTo) {
1359
+ moveAllSchedulesToProject(removeSlug, msg.moveTasksTo);
1360
+ }
1361
+ if (typeof opts.onRemoveProject === "function") {
1362
+ // Send result before removing so the WS is still open
1363
+ sendTo(ws, { type: "remove_project_result", ok: true, slug: removeSlug });
1364
+ var removeUserId = ws._clayUser ? ws._clayUser.id : null;
1365
+ opts.onRemoveProject(removeSlug, removeUserId);
1366
+ } else {
1367
+ sendTo(ws, { type: "remove_project_result", ok: false, error: "Not supported" });
1368
+ }
1369
+ return true;
1370
+ }
1371
+
1372
+ // --- Move a single schedule to another project ---
1373
+ if (msg.type === "schedule_move") {
1374
+ var moveResult = moveScheduleToProject(msg.recordId, msg.fromSlug, msg.toSlug);
1375
+ if (moveResult.ok) {
1376
+ // Re-broadcast updated records to this project's clients
1377
+ send({ type: "loop_registry_updated", records: getHubSchedules() });
1378
+ }
1379
+ sendTo(ws, { type: "schedule_move_result", ok: moveResult.ok, error: moveResult.error });
1380
+ return true;
1381
+ }
1382
+
1383
+ // --- Reorder projects ---
1384
+ if (msg.type === "reorder_projects") {
1385
+ var slugs = msg.slugs;
1386
+ if (!Array.isArray(slugs) || slugs.length === 0) {
1387
+ sendTo(ws, { type: "reorder_projects_result", ok: false, error: "Missing slugs" });
1388
+ return true;
1389
+ }
1390
+ if (typeof opts.onReorderProjects === "function") {
1391
+ var reorderResult = opts.onReorderProjects(slugs);
1392
+ sendTo(ws, { type: "reorder_projects_result", ok: reorderResult.ok, error: reorderResult.error });
1393
+ } else {
1394
+ sendTo(ws, { type: "reorder_projects_result", ok: false, error: "Not supported" });
1395
+ }
1396
+ return true;
1397
+ }
1398
+
1399
+ // --- Set project title (rename) ---
1400
+ if (msg.type === "set_project_title") {
1401
+ if (!msg.slug) {
1402
+ sendTo(ws, { type: "set_project_title_result", ok: false, error: "Missing slug" });
1403
+ return true;
1404
+ }
1405
+ if (typeof opts.onSetProjectTitle === "function") {
1406
+ var titleResult = opts.onSetProjectTitle(msg.slug, msg.title || null);
1407
+ sendTo(ws, { type: "set_project_title_result", ok: titleResult.ok, slug: msg.slug, error: titleResult.error });
1408
+ } else {
1409
+ sendTo(ws, { type: "set_project_title_result", ok: false, error: "Not supported" });
1410
+ }
1411
+ return true;
1412
+ }
1413
+
1414
+ // --- Set project icon (emoji) ---
1415
+ if (msg.type === "set_project_icon") {
1416
+ if (!msg.slug) {
1417
+ sendTo(ws, { type: "set_project_icon_result", ok: false, error: "Missing slug" });
1418
+ return true;
1419
+ }
1420
+ if (typeof opts.onSetProjectIcon === "function") {
1421
+ var iconResult = opts.onSetProjectIcon(msg.slug, msg.icon || null);
1422
+ sendTo(ws, { type: "set_project_icon_result", ok: iconResult.ok, slug: msg.slug, error: iconResult.error });
1423
+ } else {
1424
+ sendTo(ws, { type: "set_project_icon_result", ok: false, error: "Not supported" });
1425
+ }
1426
+ return true;
1427
+ }
1428
+
1429
+ // --- Set project preferred agent ---
1430
+ if (msg.type === "set_project_preferred_agent") {
1431
+ if (!msg.slug) {
1432
+ sendTo(ws, { type: "set_project_preferred_agent_result", ok: false, error: "Missing slug" });
1433
+ return true;
1434
+ }
1435
+ if (typeof opts.onSetProjectPreferredAgent === "function") {
1436
+ // agent is null to clear, or { name, kind, pluginName } to set
1437
+ var agentVal = msg.agent || null;
1438
+ var paResult = opts.onSetProjectPreferredAgent(msg.slug, agentVal);
1439
+ sendTo(ws, { type: "set_project_preferred_agent_result", ok: paResult.ok, slug: msg.slug, error: paResult.error });
1440
+ } else {
1441
+ sendTo(ws, { type: "set_project_preferred_agent_result", ok: false, error: "Not supported" });
1442
+ }
1443
+ return true;
1444
+ }
1445
+
1446
+ // --- Set project folder ---
1447
+ if (msg.type === "set_project_folder") {
1448
+ if (!msg.slug) {
1449
+ sendTo(ws, { type: "set_project_folder_result", ok: false, error: "Missing slug" });
1450
+ return true;
1451
+ }
1452
+ if (typeof opts.onSetProjectFolder === "function") {
1453
+ var folderResult = opts.onSetProjectFolder(msg.slug, msg.folderName || null);
1454
+ sendTo(ws, { type: "set_project_folder_result", ok: folderResult.ok, slug: msg.slug, error: folderResult.error });
1455
+ } else {
1456
+ sendTo(ws, { type: "set_project_folder_result", ok: false, error: "Not supported" });
1457
+ }
1458
+ return true;
1459
+ }
1460
+
1461
+ // --- Rename project folder ---
1462
+ if (msg.type === "rename_project_folder") {
1463
+ if (!msg.oldName || !msg.newName) {
1464
+ sendTo(ws, { type: "rename_project_folder_result", ok: false, error: "Missing oldName or newName" });
1465
+ return true;
1466
+ }
1467
+ if (typeof opts.onRenameProjectFolder === "function") {
1468
+ var renameResult = opts.onRenameProjectFolder(msg.oldName, msg.newName);
1469
+ sendTo(ws, { type: "rename_project_folder_result", ok: renameResult.ok, error: renameResult.error });
1470
+ } else {
1471
+ sendTo(ws, { type: "rename_project_folder_result", ok: false, error: "Not supported" });
1472
+ }
1473
+ return true;
1474
+ }
1475
+
1476
+ // --- Set folder icon ---
1477
+ if (msg.type === "set_folder_icon") {
1478
+ if (!msg.folderName) {
1479
+ sendTo(ws, { type: "set_folder_icon_result", ok: false, error: "Missing folderName" });
1480
+ return true;
1481
+ }
1482
+ if (typeof opts.onSetFolderIcon === "function") {
1483
+ var fIconResult = opts.onSetFolderIcon(msg.folderName, msg.icon || null);
1484
+ sendTo(ws, { type: "set_folder_icon_result", ok: fIconResult.ok, error: fIconResult.error });
1485
+ } else {
1486
+ sendTo(ws, { type: "set_folder_icon_result", ok: false, error: "Not supported" });
1487
+ }
1488
+ return true;
1489
+ }
1490
+
1491
+ // --- Daemon config / server management (admin-only in multi-user mode) ---
1492
+ if (msg.type === "get_daemon_config" || msg.type === "set_pin" || msg.type === "set_keep_awake" ||
1493
+ msg.type === "set_auto_continue" || msg.type === "set_image_retention" || msg.type === "shutdown_server" || msg.type === "restart_server") {
1494
+ if (usersModule.isMultiUser()) {
1495
+ var _wsUser = ws._clayUser;
1496
+ if (!_wsUser || _wsUser.role !== "admin") {
1497
+ sendTo(ws, { type: "error", message: "Admin access required" });
1498
+ return true;
1499
+ }
1500
+ }
1501
+ }
1502
+
1503
+ if (msg.type === "get_daemon_config") {
1504
+ if (typeof opts.onGetDaemonConfig === "function") {
1505
+ var daemonConfig = opts.onGetDaemonConfig();
1506
+ sendTo(ws, { type: "daemon_config", config: daemonConfig });
1507
+ }
1508
+ return true;
1509
+ }
1510
+
1511
+ if (msg.type === "set_pin") {
1512
+ if (typeof opts.onSetPin === "function") {
1513
+ var pinResult = opts.onSetPin(msg.pin || null);
1514
+ sendTo(ws, { type: "set_pin_result", ok: pinResult.ok, pinEnabled: pinResult.pinEnabled });
1515
+ }
1516
+ return true;
1517
+ }
1518
+
1519
+ if (msg.type === "set_keep_awake") {
1520
+ if (typeof opts.onSetKeepAwake === "function") {
1521
+ var kaResult = opts.onSetKeepAwake(msg.value);
1522
+ sendTo(ws, { type: "set_keep_awake_result", ok: kaResult.ok, keepAwake: kaResult.keepAwake });
1523
+ send({ type: "keep_awake_changed", keepAwake: kaResult.keepAwake });
1524
+ }
1525
+ return true;
1526
+ }
1527
+
1528
+ if (msg.type === "set_auto_continue") {
1529
+ if (typeof opts.onSetAutoContinue === "function") {
1530
+ var acResult = opts.onSetAutoContinue(msg.value);
1531
+ sendTo(ws, { type: "set_auto_continue_result", ok: acResult.ok, autoContinueOnRateLimit: acResult.autoContinueOnRateLimit });
1532
+ send({ type: "auto_continue_changed", autoContinueOnRateLimit: acResult.autoContinueOnRateLimit });
1533
+ }
1534
+ return true;
1535
+ }
1536
+
1537
+ if (msg.type === "set_image_retention") {
1538
+ if (typeof opts.onSetImageRetention === "function") {
1539
+ var irResult = opts.onSetImageRetention(msg.days);
1540
+ sendTo(ws, { type: "set_image_retention_result", ok: irResult.ok, days: irResult.days });
1541
+ }
1542
+ return true;
1543
+ }
1544
+
1545
+ if (msg.type === "shutdown_server") {
1546
+ if (typeof opts.onShutdown === "function") {
1547
+ sendTo(ws, { type: "shutdown_server_result", ok: true });
1548
+ send({ type: "toast", level: "warn", message: "Server is shutting down..." });
1549
+ // Small delay so the response has time to reach clients
1550
+ setTimeout(function () {
1551
+ opts.onShutdown();
1552
+ }, 500);
1553
+ } else {
1554
+ sendTo(ws, { type: "shutdown_server_result", ok: false, error: "Shutdown not supported" });
1555
+ }
1556
+ return true;
1557
+ }
1558
+
1559
+ if (msg.type === "restart_server") {
1560
+ if (typeof opts.onRestart === "function") {
1561
+ sendTo(ws, { type: "restart_server_result", ok: true });
1562
+ send({ type: "toast", level: "info", message: "Server is restarting..." });
1563
+ // Small delay so the response has time to reach clients
1564
+ setTimeout(function () {
1565
+ opts.onRestart();
1566
+ }, 500);
1567
+ } else {
1568
+ sendTo(ws, { type: "restart_server_result", ok: false, error: "Restart not supported" });
1569
+ }
1570
+ return true;
1571
+ }
1572
+
1573
+ return false;
1574
+ }
1575
+
1576
+ return {
1577
+ handleSessionsMessage: handleSessionsMessage,
1578
+ };
1579
+ }
1580
+
1581
+ module.exports = { attachSessions: attachSessions };