@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,946 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+ var config = require("./config");
4
+ var utils = require("./utils");
5
+ var users = require("./users");
6
+ var { CODEX_DEFAULTS } = require("./codex-defaults");
7
+
8
+ function createSessionManager(opts) {
9
+ var cwd = opts.cwd;
10
+ var send = opts.send; // function(obj) - broadcast to all clients
11
+ var sendTo = opts.sendTo || null; // function(ws, obj) - send to specific client
12
+ var sendEach = opts.sendEach || null; // function(fn) - call fn(ws) for each connected client
13
+ var sendAndRecord = null; // set after init via setSendAndRecord
14
+ var onSessionDone = opts.onSessionDone || function () {};
15
+
16
+ // --- Multi-session state ---
17
+ var nextLocalId = 1;
18
+ var sessions = new Map(); // localId -> session object
19
+ var activeSessionId = null; // currently active local ID
20
+ var slashCommands = null; // shared across sessions (deprecated, use slashCommandsByVendor)
21
+ var slashCommandsByVendor = {}; // vendor -> array of slash commands
22
+ var skillNames = null; // Claude-only skills to filter from slash menu
23
+ var singleUserUnread = {}; // sessionLocalId -> unread count (single-user mode)
24
+ var permissionRequestIndex = {}; // requestId -> sessionLocalId (O(1) lookup)
25
+ var capabilitiesByVendor = null; // set by sdk-bridge after adapter init
26
+ var defaultVendor = null; // set by sdk-bridge
27
+ var codexApproval = CODEX_DEFAULTS.approval;
28
+ var codexSandbox = CODEX_DEFAULTS.sandbox;
29
+ var codexWebSearch = CODEX_DEFAULTS.webSearch;
30
+
31
+ // --- Session persistence (centralized in ~/.clagentic/sessions/{encoded-cwd}/) ---
32
+ var sessionsBase = path.join(config.CONFIG_DIR, "sessions");
33
+ var encodedCwd = utils.resolveEncodedDir(sessionsBase, cwd);
34
+ var sessionsDir = path.join(sessionsBase, encodedCwd);
35
+ fs.mkdirSync(sessionsDir, { recursive: true });
36
+
37
+ function sessionFilePath(cliSessionId) {
38
+ return path.join(sessionsDir, cliSessionId + ".jsonl");
39
+ }
40
+
41
+ function saveSessionFile(session) {
42
+ if (!session.cliSessionId) return;
43
+ try {
44
+ var metaObj = {
45
+ type: "meta",
46
+ localId: session.localId,
47
+ cliSessionId: session.cliSessionId,
48
+ title: session.title,
49
+ createdAt: session.createdAt,
50
+ };
51
+ if (session.ownerId) metaObj.ownerId = session.ownerId;
52
+ if (session.vendor) metaObj.vendor = session.vendor;
53
+ if (session.sessionVisibility) metaObj.sessionVisibility = session.sessionVisibility;
54
+ if (session.bookmarked) metaObj.bookmarked = true;
55
+ if (typeof session.favoriteOrder === "number") metaObj.favoriteOrder = session.favoriteOrder;
56
+ if (session.lastRewindUuid) metaObj.lastRewindUuid = session.lastRewindUuid;
57
+ if (session.agentName) metaObj.agentName = session.agentName;
58
+ if (session.loop) metaObj.loop = session.loop;
59
+ var meta = JSON.stringify(metaObj);
60
+ var lines = [meta];
61
+ for (var i = 0; i < session.history.length; i++) {
62
+ lines.push(JSON.stringify(session.history[i]));
63
+ }
64
+ var sfPath = sessionFilePath(session.cliSessionId);
65
+ // Atomic write: write to temp file then rename, so a crash mid-write
66
+ // cannot leave a truncated/corrupted session file.
67
+ var tmpPath = sfPath + ".tmp." + process.pid;
68
+ fs.writeFileSync(tmpPath, lines.join("\n") + "\n");
69
+ if (process.platform !== "win32") {
70
+ try { fs.chmodSync(tmpPath, 0o600); } catch (chmodErr) {}
71
+ }
72
+ fs.renameSync(tmpPath, sfPath);
73
+ } catch(e) {
74
+ console.error("[session] Failed to save session file:", e.message);
75
+ }
76
+ }
77
+
78
+ function appendToSessionFile(session, obj) {
79
+ if (!session.cliSessionId) return;
80
+ session.lastActivity = Date.now();
81
+ try {
82
+ var afPath = sessionFilePath(session.cliSessionId);
83
+ fs.appendFileSync(afPath, JSON.stringify(obj) + "\n");
84
+ if (process.platform !== "win32") {
85
+ try { fs.chmodSync(afPath, 0o600); } catch (chmodErr) {}
86
+ }
87
+ } catch(e) {
88
+ console.error("[session] Failed to append to session file:", e.message);
89
+ }
90
+ }
91
+
92
+ function loadSessions() {
93
+ var files;
94
+ try { files = fs.readdirSync(sessionsDir); } catch { return; }
95
+
96
+ // Clean up stale temp files from interrupted atomic writes
97
+ for (var ti = 0; ti < files.length; ti++) {
98
+ if (files[ti].indexOf(".tmp.") !== -1) {
99
+ try { fs.unlinkSync(path.join(sessionsDir, files[ti])); } catch (e) {}
100
+ }
101
+ }
102
+
103
+ var loaded = [];
104
+ for (var i = 0; i < files.length; i++) {
105
+ if (!files[i].endsWith(".jsonl")) continue;
106
+ var content;
107
+ try { content = fs.readFileSync(path.join(sessionsDir, files[i]), "utf8"); } catch { continue; }
108
+ var lines = content.trim().split("\n");
109
+ if (lines.length === 0) continue;
110
+
111
+ var meta;
112
+ try { meta = JSON.parse(lines[0]); } catch { continue; }
113
+ if (meta.type !== "meta" || !meta.cliSessionId) continue;
114
+
115
+ var history = [];
116
+ for (var j = 1; j < lines.length; j++) {
117
+ try { history.push(JSON.parse(lines[j])); } catch {}
118
+ }
119
+
120
+ var fileMtime = 0;
121
+ try { fileMtime = fs.statSync(path.join(sessionsDir, files[i])).mtimeMs; } catch {}
122
+ loaded.push({ meta: meta, history: history, mtime: fileMtime });
123
+ }
124
+
125
+ loaded.sort(function(a, b) { return a.meta.createdAt - b.meta.createdAt; });
126
+
127
+ for (var i = 0; i < loaded.length; i++) {
128
+ var m = loaded[i].meta;
129
+ var localId = nextLocalId++;
130
+ // Reconstruct messageUUIDs from history
131
+ var messageUUIDs = [];
132
+ for (var k = 0; k < loaded[i].history.length; k++) {
133
+ if (loaded[i].history[k].type === "message_uuid") {
134
+ messageUUIDs.push({ uuid: loaded[i].history[k].uuid, type: loaded[i].history[k].messageType, historyIndex: k });
135
+ }
136
+ }
137
+ var session = {
138
+ localId: localId,
139
+ queryInstance: null,
140
+ messageQueue: null,
141
+ cliSessionId: m.cliSessionId,
142
+ blocks: {},
143
+ sentToolResults: {},
144
+ pendingPermissions: {},
145
+ pendingAskUser: {},
146
+ isProcessing: false,
147
+ title: m.title || "",
148
+ createdAt: m.createdAt || Date.now(),
149
+ lastActivity: loaded[i].mtime || m.createdAt || Date.now(),
150
+ history: loaded[i].history,
151
+ messageUUIDs: messageUUIDs,
152
+ lastRewindUuid: m.lastRewindUuid || null,
153
+ };
154
+ if (m.vendor) session.vendor = m.vendor;
155
+ if (m.agentName) session.agentName = m.agentName;
156
+ if (m.loop) session.loop = m.loop;
157
+ if (m.ownerId) session.ownerId = m.ownerId;
158
+ session.sessionVisibility = m.sessionVisibility || "shared";
159
+ session.bookmarked = !!m.bookmarked;
160
+ session.favoriteOrder = typeof m.favoriteOrder === "number" ? m.favoriteOrder : null;
161
+ sessions.set(localId, session);
162
+ }
163
+ }
164
+
165
+ // Load persisted sessions from disk
166
+ loadSessions();
167
+
168
+ function getActiveSession() {
169
+ return sessions.get(activeSessionId) || null;
170
+ }
171
+
172
+ var resolveLoopInfo = null; // optional callback: (loopId) => { name, source } or null
173
+
174
+ function setResolveLoopInfo(fn) {
175
+ resolveLoopInfo = fn;
176
+ }
177
+
178
+ function mapSessionForClient(s, clientActiveId, wsUnread) {
179
+ var loop = s.loop ? Object.assign({}, s.loop) : null;
180
+ if (loop && loop.loopId && resolveLoopInfo) {
181
+ var info = resolveLoopInfo(loop.loopId);
182
+ if (info) {
183
+ if (info.name) loop.name = info.name;
184
+ if (info.source) loop.source = info.source;
185
+ }
186
+ }
187
+ var isActive = (typeof clientActiveId === "number") ? s.localId === clientActiveId : s.localId === activeSessionId;
188
+ var unreadMap = wsUnread || singleUserUnread;
189
+ return {
190
+ id: s.localId,
191
+ cliSessionId: s.cliSessionId || null,
192
+ title: s.title || "New Session",
193
+ active: isActive,
194
+ isProcessing: s.isProcessing,
195
+ lastActivity: s.lastActivity || s.createdAt || 0,
196
+ loop: loop,
197
+ ownerId: s.ownerId || null,
198
+ sessionVisibility: s.sessionVisibility || "shared",
199
+ bookmarked: !!s.bookmarked,
200
+ favoriteOrder: typeof s.favoriteOrder === "number" ? s.favoriteOrder : null,
201
+ unread: unreadMap[s.localId] || 0,
202
+ vendor: s.vendor || null,
203
+ agentName: s.agentName || null,
204
+ };
205
+ }
206
+
207
+ function getVisibleSessions() {
208
+ var multiUser = users.isMultiUser();
209
+ return [...sessions.values()].filter(function (s) {
210
+ if (s.hidden) return false;
211
+ if (!multiUser) {
212
+ return !s.ownerId;
213
+ }
214
+ return true;
215
+ });
216
+ }
217
+
218
+ function broadcastSessionList() {
219
+ var allVisible = getVisibleSessions();
220
+ if (sendEach) {
221
+ // Per-client filtering (multi-user mode)
222
+ sendEach(function (ws, filterFn) {
223
+ var filtered = filterFn ? allVisible.filter(filterFn) : allVisible;
224
+ var clientActiveId = ws._clayActiveSession;
225
+ var wsUnread = ws._clayUnread || {};
226
+ if (ws.readyState === 1) {
227
+ ws.send(JSON.stringify({
228
+ type: "session_list",
229
+ sessions: filtered.map(function (s) { return mapSessionForClient(s, clientActiveId, wsUnread); }),
230
+ }));
231
+ }
232
+ });
233
+ } else {
234
+ send({
235
+ type: "session_list",
236
+ sessions: allVisible.map(function (s) { return mapSessionForClient(s); }),
237
+ });
238
+ }
239
+ }
240
+
241
+ function createSession(sessionOpts, targetWs) {
242
+ var localId = nextLocalId++;
243
+ var session = {
244
+ localId: localId,
245
+ queryInstance: null,
246
+ messageQueue: null,
247
+ cliSessionId: null,
248
+ blocks: {},
249
+ sentToolResults: {},
250
+ pendingPermissions: {},
251
+ pendingAskUser: {},
252
+ allowedTools: {},
253
+ isProcessing: false,
254
+ title: "",
255
+ titleAutoGenerated: false,
256
+ turnCount: 0,
257
+ createdAt: Date.now(),
258
+ lastActivity: Date.now(),
259
+ history: [],
260
+ messageUUIDs: [],
261
+ ownerId: (sessionOpts && sessionOpts.ownerId) || null,
262
+ sessionVisibility: (sessionOpts && sessionOpts.sessionVisibility) || "shared",
263
+ bookmarked: false,
264
+ favoriteOrder: null,
265
+ vendor: (sessionOpts && sessionOpts.vendor) || null,
266
+ agentName: (sessionOpts && sessionOpts.agentName) || null,
267
+ };
268
+ sessions.set(localId, session);
269
+ switchSession(localId, targetWs);
270
+ return session;
271
+ }
272
+
273
+ // Create a session without switching to it (used for mate/background sessions)
274
+ function createSessionRaw(sessionOpts) {
275
+ var localId = nextLocalId++;
276
+ var session = {
277
+ localId: localId,
278
+ queryInstance: null,
279
+ messageQueue: null,
280
+ cliSessionId: null,
281
+ blocks: {},
282
+ sentToolResults: {},
283
+ pendingPermissions: {},
284
+ pendingAskUser: {},
285
+ allowedTools: {},
286
+ isProcessing: false,
287
+ title: "",
288
+ titleAutoGenerated: false,
289
+ turnCount: 0,
290
+ createdAt: Date.now(),
291
+ lastActivity: Date.now(),
292
+ history: [],
293
+ messageUUIDs: [],
294
+ ownerId: (sessionOpts && sessionOpts.ownerId) || null,
295
+ sessionVisibility: (sessionOpts && sessionOpts.sessionVisibility) || "shared",
296
+ bookmarked: false,
297
+ favoriteOrder: null,
298
+ vendor: (sessionOpts && sessionOpts.vendor) || null,
299
+ agentName: (sessionOpts && sessionOpts.agentName) || null,
300
+ };
301
+ sessions.set(localId, session);
302
+ return session;
303
+ }
304
+
305
+ // Initial replay payload size. Lowered from 200 to reduce client-side
306
+ // layout work on resume — older items are loaded progressively on
307
+ // scroll-up via the existing pagination path.
308
+ var HISTORY_PAGE_SIZE = 100;
309
+
310
+ function findTurnBoundary(history, targetIndex) {
311
+ for (var i = targetIndex; i >= 0; i--) {
312
+ if (history[i] && history[i].type === "user_message") return i;
313
+ }
314
+ return 0;
315
+ }
316
+
317
+ function replayHistory(session, fromIndex, targetWs, transform) {
318
+ var _send = (targetWs && sendTo) ? function (obj) { sendTo(targetWs, obj); } : send;
319
+ var total = session.history.length;
320
+ if (typeof fromIndex !== "number") {
321
+ if (total <= HISTORY_PAGE_SIZE) {
322
+ fromIndex = 0;
323
+ } else {
324
+ fromIndex = findTurnBoundary(session.history, Math.max(0, total - HISTORY_PAGE_SIZE));
325
+ }
326
+ }
327
+
328
+ _send({ type: "history_meta", total: total, from: fromIndex });
329
+
330
+ for (var i = fromIndex; i < total; i++) {
331
+ var _item = session.history[i];
332
+ // Skip internal bookkeeping entries not meant for the UI
333
+ if (_item && _item.type === "digest_checkpoint") continue;
334
+ if (_item && (_item.type === "mention_user" || _item.type === "mention_response")) {
335
+ console.log("[DEBUG replayHistory] sending mention at index=" + i + " from=" + fromIndex + " total=" + total + " type=" + _item.type + " mate=" + (_item.mateName || ""));
336
+ }
337
+ _send(transform ? transform(_item) : _item);
338
+ }
339
+
340
+ // Find the last result message in the full history for accurate context data
341
+ var lastUsage = null;
342
+ var lastModelUsage = null;
343
+ var lastCost = null;
344
+ var lastStreamInputTokens = null;
345
+ for (var j = total - 1; j >= 0; j--) {
346
+ if (session.history[j].type === "result") {
347
+ var r = session.history[j];
348
+ lastUsage = r.usage || null;
349
+ lastModelUsage = r.modelUsage || null;
350
+ lastCost = r.cost != null ? r.cost : null;
351
+ lastStreamInputTokens = r.lastStreamInputTokens || null;
352
+ break;
353
+ }
354
+ }
355
+
356
+ _send({ type: "history_done", lastUsage: lastUsage, lastModelUsage: lastModelUsage, lastCost: lastCost, lastStreamInputTokens: lastStreamInputTokens, contextUsage: session.lastContextUsage || null });
357
+ }
358
+
359
+ function switchSession(localId, targetWs, transform) {
360
+ var session = sessions.get(localId);
361
+ if (!session) return;
362
+
363
+ activeSessionId = localId;
364
+ if (targetWs) {
365
+ targetWs._clayActiveSession = localId;
366
+ // Clear unread for this session (multi-user)
367
+ if (targetWs._clayUnread) targetWs._clayUnread[localId] = 0;
368
+ } else if (sendEach) {
369
+ // No specific target: update all connected clients (server-initiated switch)
370
+ sendEach(function (ws) {
371
+ ws._clayActiveSession = localId;
372
+ });
373
+ }
374
+ // Clear unread for single-user mode
375
+ singleUserUnread[localId] = 0;
376
+
377
+ // In multi-user mode with a specific client, only send to that client
378
+ var _send = (targetWs && sendTo) ? function (obj) { sendTo(targetWs, obj); } : send;
379
+
380
+ var _capsByVendor = capabilitiesByVendor || {};
381
+ var _sessionVendor = session.vendor || defaultVendor || "claude";
382
+ var _vendorCaps = _capsByVendor[_sessionVendor] || {};
383
+ _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, hasHistory: (session.history && session.history.length > 0), capabilities: _vendorCaps, isProcessing: !!session.isProcessing });
384
+ // Send vendor-specific slash commands
385
+ var _vendorCmds = slashCommandsByVendor[_sessionVendor] || slashCommands || [];
386
+ _send({ type: "slash_commands", commands: _vendorCmds, vendor: _sessionVendor });
387
+ broadcastSessionList();
388
+ replayHistory(session, undefined, targetWs, transform);
389
+
390
+ if (session.isProcessing) {
391
+ _send({ type: "status", status: "processing" });
392
+ }
393
+
394
+ // Re-send any pending permission requests
395
+ var pendingIds = Object.keys(session.pendingPermissions);
396
+ for (var i = 0; i < pendingIds.length; i++) {
397
+ var p = session.pendingPermissions[pendingIds[i]];
398
+ _send({
399
+ type: "permission_request_pending",
400
+ requestId: p.requestId,
401
+ toolName: p.toolName,
402
+ toolInput: p.toolInput,
403
+ toolUseId: p.toolUseId,
404
+ decisionReason: p.decisionReason,
405
+ });
406
+ }
407
+
408
+ // Re-send active mention indicator so returning clients restore the mate avatar state
409
+ if (session._mentionInProgress && session._mentionActiveMateId) {
410
+ _send({ type: "mention_processing", mateId: session._mentionActiveMateId, active: true });
411
+ }
412
+ }
413
+
414
+ function cleanupMentionSessions(session) {
415
+ if (session._mentionSessions) {
416
+ var mateIds = Object.keys(session._mentionSessions);
417
+ for (var mi = 0; mi < mateIds.length; mi++) {
418
+ try { session._mentionSessions[mateIds[mi]].close(); } catch (e) {}
419
+ }
420
+ session._mentionSessions = {};
421
+ }
422
+ }
423
+
424
+ function deleteSession(localId, targetWs) {
425
+ var session = sessions.get(localId);
426
+ if (!session) return;
427
+
428
+ // Clean up unread tracking
429
+ delete singleUserUnread[localId];
430
+
431
+ cleanupMentionSessions(session);
432
+
433
+ if (session.abortController) {
434
+ try { session.abortController.abort(); } catch(e) {}
435
+ }
436
+ // Close SDK query to terminate the underlying claude child process
437
+ if (session.queryInstance && typeof session.queryInstance.close === "function") {
438
+ try { session.queryInstance.close(); } catch(e) {}
439
+ }
440
+ session.queryInstance = null;
441
+ if (session.messageQueue) {
442
+ try { session.messageQueue.end(); } catch(e) {}
443
+ }
444
+ if (session.worker) {
445
+ try { session.worker.kill(); } catch(e) {}
446
+ session.worker = null;
447
+ }
448
+
449
+ if (session.cliSessionId) {
450
+ try { fs.unlinkSync(sessionFilePath(session.cliSessionId)); } catch(e) {}
451
+ }
452
+
453
+ sessions.delete(localId);
454
+
455
+ if (activeSessionId === localId) {
456
+ var remaining = [...sessions.keys()];
457
+ if (remaining.length > 0) {
458
+ switchSession(remaining[remaining.length - 1], targetWs);
459
+ } else {
460
+ createSession(null, targetWs);
461
+ }
462
+ } else {
463
+ broadcastSessionList();
464
+ }
465
+ }
466
+
467
+ function deleteSessionQuiet(localId) {
468
+ var session = sessions.get(localId);
469
+ if (!session) return;
470
+ delete singleUserUnread[localId];
471
+ cleanupMentionSessions(session);
472
+ if (session.abortController) {
473
+ try { session.abortController.abort(); } catch(e) {}
474
+ }
475
+ // Close SDK query to terminate the underlying claude child process
476
+ if (session.queryInstance && typeof session.queryInstance.close === "function") {
477
+ try { session.queryInstance.close(); } catch(e) {}
478
+ }
479
+ session.queryInstance = null;
480
+ if (session.messageQueue) {
481
+ try { session.messageQueue.end(); } catch(e) {}
482
+ }
483
+ if (session.worker) {
484
+ try { session.worker.kill(); } catch(e) {}
485
+ session.worker = null;
486
+ }
487
+ if (session.cliSessionId) {
488
+ try { fs.unlinkSync(sessionFilePath(session.cliSessionId)); } catch(e) {}
489
+ }
490
+ sessions.delete(localId);
491
+ }
492
+
493
+ function deleteSessionsBulk(localIds, targetWs) {
494
+ if (!Array.isArray(localIds) || localIds.length === 0) return;
495
+
496
+ var seen = {};
497
+ var ids = [];
498
+ for (var i = 0; i < localIds.length; i++) {
499
+ var id = localIds[i];
500
+ if (typeof id !== "number" || seen[id] || !sessions.has(id)) continue;
501
+ seen[id] = true;
502
+ ids.push(id);
503
+ }
504
+ if (ids.length === 0) return;
505
+
506
+ var deletedActive = false;
507
+ for (var j = 0; j < ids.length; j++) {
508
+ if (ids[j] === activeSessionId) deletedActive = true;
509
+ deleteSessionQuiet(ids[j]);
510
+ }
511
+
512
+ if (sessions.size === 0) {
513
+ createSession(null, targetWs);
514
+ return;
515
+ }
516
+
517
+ if (deletedActive) {
518
+ var remaining = [...sessions.keys()];
519
+ switchSession(remaining[remaining.length - 1], targetWs);
520
+ } else {
521
+ broadcastSessionList();
522
+ }
523
+ }
524
+
525
+ function doSendToSession(session, obj) {
526
+ // Send to active clients without recording to history/disk (ephemeral data)
527
+ if (sendEach) {
528
+ var data = JSON.stringify(obj);
529
+ sendEach(function (ws) {
530
+ if (ws._clayActiveSession === session.localId && ws.readyState === 1) {
531
+ ws.send(data);
532
+ }
533
+ });
534
+ } else if (session.localId === activeSessionId) {
535
+ send(obj);
536
+ }
537
+ }
538
+
539
+ function doSendAndRecord(session, obj) {
540
+ // Stamp every recorded message so history replay preserves original times
541
+ if (!obj._ts) obj._ts = Date.now();
542
+ session.history.push(obj);
543
+ appendToSessionFile(session, obj);
544
+ if (sendEach) {
545
+ // Multi-user: send to clients whose active session matches this one
546
+ var data = JSON.stringify(obj);
547
+ var ioData = null;
548
+ sendEach(function (ws) {
549
+ if (ws._clayActiveSession === session.localId) {
550
+ if (ws.readyState === 1) ws.send(data);
551
+ } else if (session.isProcessing && !session._ioThrottle) {
552
+ if (!ioData) ioData = JSON.stringify({ type: "session_io", id: session.localId });
553
+ if (ws.readyState === 1) ws.send(ioData);
554
+ }
555
+ // Track unread: increment on "done" for clients not viewing this session
556
+ // Only count if session has no owner (my session) or owner matches this client
557
+ if (obj.type === "done" && ws._clayActiveSession !== session.localId) {
558
+ var _isMySession = !session.ownerId || (ws._clayUser && ws._clayUser.id === session.ownerId);
559
+ if (_isMySession) {
560
+ if (!ws._clayUnread) ws._clayUnread = {};
561
+ ws._clayUnread[session.localId] = (ws._clayUnread[session.localId] || 0) + 1;
562
+ if (ws.readyState === 1) {
563
+ ws.send(JSON.stringify({ type: "session_unread", id: session.localId, count: ws._clayUnread[session.localId] }));
564
+ }
565
+ }
566
+ }
567
+ });
568
+ if (session.isProcessing && !session._ioThrottle && ioData) {
569
+ session._ioThrottle = true;
570
+ setTimeout(function () { session._ioThrottle = false; }, 80);
571
+ }
572
+ } else if (session.localId === activeSessionId) {
573
+ send(obj);
574
+ } else {
575
+ // Track unread for single-user mode on "done"
576
+ if (obj.type === "done") {
577
+ singleUserUnread[session.localId] = (singleUserUnread[session.localId] || 0) + 1;
578
+ send({ type: "session_unread", id: session.localId, count: singleUserUnread[session.localId] });
579
+ }
580
+ if (session.isProcessing && !session._ioThrottle) {
581
+ session._ioThrottle = true;
582
+ send({ type: "session_io", id: session.localId });
583
+ setTimeout(function () { session._ioThrottle = false; }, 80);
584
+ }
585
+ }
586
+ // Notify server for cross-project unread tracking
587
+ if (obj.type === "done") onSessionDone();
588
+ }
589
+
590
+ function resumeSession(cliSessionId, opts, targetWs) {
591
+ // If a session with this cliSessionId already exists, just switch to it
592
+ var existing = null;
593
+ sessions.forEach(function (s) {
594
+ if (s.cliSessionId === cliSessionId) existing = s;
595
+ });
596
+ if (existing) {
597
+ existing.lastActivity = Date.now();
598
+ switchSession(existing.localId, targetWs);
599
+ return existing;
600
+ }
601
+
602
+ var cliHistory = (opts && opts.history) || [];
603
+ var title = (opts && opts.title) || "Resumed session";
604
+ var localId = nextLocalId++;
605
+ var session = {
606
+ localId: localId,
607
+ queryInstance: null,
608
+ messageQueue: null,
609
+ cliSessionId: cliSessionId,
610
+ blocks: {},
611
+ sentToolResults: {},
612
+ pendingPermissions: {},
613
+ pendingAskUser: {},
614
+ allowedTools: {},
615
+ isProcessing: false,
616
+ title: title,
617
+ createdAt: Date.now(),
618
+ lastActivity: Date.now(),
619
+ history: cliHistory,
620
+ messageUUIDs: [],
621
+ bookmarked: false,
622
+ favoriteOrder: null,
623
+ };
624
+ if (opts && opts.vendor) session.vendor = opts.vendor;
625
+ if (opts && opts.ownerId) session.ownerId = opts.ownerId;
626
+ sessions.set(localId, session);
627
+ saveSessionFile(session);
628
+ switchSession(localId, targetWs);
629
+ return session;
630
+ }
631
+
632
+ // --- Spawn initial session only if no persisted sessions ---
633
+ if (sessions.size === 0) {
634
+ createSession();
635
+ } else {
636
+ // Activate the most recently used session
637
+ var allSessions = [...sessions.values()];
638
+ var mostRecent = allSessions[0];
639
+ for (var i = 1; i < allSessions.length; i++) {
640
+ if ((allSessions[i].lastActivity || 0) > (mostRecent.lastActivity || 0)) {
641
+ mostRecent = allSessions[i];
642
+ }
643
+ }
644
+ activeSessionId = mostRecent.localId;
645
+ }
646
+
647
+ function searchSessions(query) {
648
+ if (!query) return [];
649
+ var q = query.toLowerCase();
650
+ var results = [];
651
+ sessions.forEach(function (session) {
652
+ var titleMatch = (session.title || "New Session").toLowerCase().indexOf(q) !== -1;
653
+ var contentMatch = false;
654
+ for (var i = 0; i < session.history.length; i++) {
655
+ var entry = session.history[i];
656
+ if ((entry.type === "delta" || entry.type === "user_message" || entry.type === "mention_user" || entry.type === "mention_response") && entry.text) {
657
+ if (entry.text.toLowerCase().indexOf(q) !== -1) {
658
+ contentMatch = true;
659
+ break;
660
+ }
661
+ }
662
+ }
663
+ if (titleMatch || contentMatch) {
664
+ results.push({
665
+ id: session.localId,
666
+ cliSessionId: session.cliSessionId || null,
667
+ title: session.title || "New Session",
668
+ active: session.localId === activeSessionId,
669
+ isProcessing: session.isProcessing,
670
+ lastActivity: session.lastActivity || session.createdAt || 0,
671
+ matchType: titleMatch && contentMatch ? "both" : titleMatch ? "title" : "content",
672
+ });
673
+ }
674
+ });
675
+ return results;
676
+ }
677
+
678
+ function searchSessionContent(localId, query) {
679
+ if (!query) return { hits: [], total: 0 };
680
+ var session = sessions.get(localId);
681
+ if (!session) return { hits: [], total: 0 };
682
+ var q = query.toLowerCase();
683
+ var qLen = query.length;
684
+ var history = session.history;
685
+ var hits = [];
686
+
687
+ // Assistant turns can consist of many streaming deltas (especially Codex,
688
+ // where agentMessage/delta fragments arrive in small chunks). We accumulate
689
+ // delta text per turn, scan for ALL occurrences of the query across the
690
+ // accumulated buffer, then map each occurrence back to the historyIndex of
691
+ // the delta that contains its starting offset. This catches multiple
692
+ // matches within a single turn and also matches that straddle delta
693
+ // boundaries.
694
+ var turnBuffer = "";
695
+ var turnSegments = []; // [{ start, end, historyIndex, ts }]
696
+
697
+ function pushScalarHits(text, historyIndex, role, ts) {
698
+ if (!text) return;
699
+ var lower = text.toLowerCase();
700
+ var from = 0;
701
+ while (true) {
702
+ var idx = lower.indexOf(q, from);
703
+ if (idx === -1) break;
704
+ var s = Math.max(0, idx - 15);
705
+ var e = Math.min(text.length, idx + qLen + 15);
706
+ var snippet = (s > 0 ? "\u2026" : "") + text.substring(s, e) + (e < text.length ? "\u2026" : "");
707
+ hits.push({ historyIndex: historyIndex, snippet: snippet, role: role, ts: ts });
708
+ from = idx + qLen;
709
+ }
710
+ }
711
+
712
+ function flushTurn() {
713
+ if (!turnBuffer || turnSegments.length === 0) {
714
+ turnBuffer = "";
715
+ turnSegments = [];
716
+ return;
717
+ }
718
+ var lowerBuf = turnBuffer.toLowerCase();
719
+ var from = 0;
720
+ var segCursor = 0;
721
+ while (true) {
722
+ var idx = lowerBuf.indexOf(q, from);
723
+ if (idx === -1) break;
724
+ // Advance segCursor to the segment containing idx.
725
+ while (segCursor < turnSegments.length - 1 && turnSegments[segCursor].end <= idx) {
726
+ segCursor++;
727
+ }
728
+ var seg = turnSegments[segCursor];
729
+ var s = Math.max(0, idx - 15);
730
+ var e = Math.min(turnBuffer.length, idx + qLen + 15);
731
+ var snippet = (s > 0 ? "\u2026" : "") + turnBuffer.substring(s, e) + (e < turnBuffer.length ? "\u2026" : "");
732
+ hits.push({ historyIndex: seg.historyIndex, snippet: snippet, role: "assistant", ts: seg.ts });
733
+ from = idx + qLen;
734
+ }
735
+ turnBuffer = "";
736
+ turnSegments = [];
737
+ }
738
+
739
+ for (var i = 0; i < history.length; i++) {
740
+ var entry = history[i];
741
+ var t = entry.type;
742
+ if (t === "user_message" || t === "mention_user") {
743
+ flushTurn();
744
+ pushScalarHits(entry.text, i, t === "user_message" ? "user" : "assistant", entry._ts || null);
745
+ } else if (t === "delta" && entry.text) {
746
+ turnSegments.push({
747
+ start: turnBuffer.length,
748
+ end: turnBuffer.length + entry.text.length,
749
+ historyIndex: i,
750
+ ts: entry._ts || null,
751
+ });
752
+ turnBuffer += entry.text;
753
+ } else if (t === "mention_response" && entry.text) {
754
+ flushTurn();
755
+ pushScalarHits(entry.text, i, "assistant", entry._ts || null);
756
+ }
757
+ }
758
+ flushTurn();
759
+ return { hits: hits, total: history.length };
760
+ }
761
+
762
+ var _migrationFailedIds = {};
763
+ function migrateSessionTitles(adapter, migrateCwd) {
764
+ var candidates = [];
765
+ sessions.forEach(function(s) {
766
+ if (s.cliSessionId && s.title && s.title !== "New Session" && s.title !== "Resumed session"
767
+ && !_migrationFailedIds[s.cliSessionId]) {
768
+ candidates.push({ cliSessionId: s.cliSessionId, title: s.title });
769
+ }
770
+ });
771
+ if (candidates.length === 0) return;
772
+ adapter.listSessions({ dir: migrateCwd }).then(function(sdkSessions) {
773
+ var sdkTitles = {};
774
+ for (var i = 0; i < sdkSessions.length; i++) {
775
+ if (sdkSessions[i].customTitle) {
776
+ sdkTitles[sdkSessions[i].sessionId] = sdkSessions[i].customTitle;
777
+ }
778
+ }
779
+ var toMigrate = candidates.filter(function(item) {
780
+ var relayTitle = (item.title || "").trim();
781
+ var sdkTitle = (sdkTitles[item.cliSessionId] || "").trim();
782
+ return sdkTitle !== relayTitle;
783
+ });
784
+ if (toMigrate.length === 0) return;
785
+ var migrated = 0;
786
+ var failed = 0;
787
+ var chain = Promise.resolve();
788
+ for (var j = 0; j < toMigrate.length; j++) {
789
+ (function(item) {
790
+ chain = chain.then(function() {
791
+ return adapter.renameSession(item.cliSessionId, item.title.trim(), { dir: migrateCwd }).then(function() {
792
+ migrated++;
793
+ }).catch(function(e) {
794
+ failed++;
795
+ _migrationFailedIds[item.cliSessionId] = true;
796
+ });
797
+ });
798
+ })(toMigrate[j]);
799
+ }
800
+ chain.then(function() {
801
+ if (migrated > 0) {
802
+ console.log("[session] Migrated " + migrated + " session title(s) to SDK format");
803
+ }
804
+ if (failed > 0) {
805
+ console.log("[session] Skipped " + failed + " session(s) (CLI session not found for current user)");
806
+ }
807
+ }).catch(function(e) {
808
+ console.error("[session] Migration chain failed:", e.message || e);
809
+ });
810
+ }).catch(function() {});
811
+ }
812
+
813
+ return {
814
+ get activeSessionId() { return activeSessionId; },
815
+ get nextLocalId() { return nextLocalId; },
816
+ get slashCommands() { return slashCommands; },
817
+ set slashCommands(v) { slashCommands = v; },
818
+ get slashCommandsByVendor() { return slashCommandsByVendor; },
819
+ setSlashCommandsForVendor: function(vendor, cmds) {
820
+ slashCommandsByVendor[vendor] = cmds || [];
821
+ },
822
+ getSlashCommandsForVendor: function(vendor) {
823
+ return slashCommandsByVendor[vendor] || [];
824
+ },
825
+ get skillNames() { return skillNames; },
826
+ set skillNames(v) { skillNames = v; },
827
+ get capabilitiesByVendor() { return capabilitiesByVendor; },
828
+ set capabilitiesByVendor(v) { capabilitiesByVendor = v; },
829
+ get defaultVendor() { return defaultVendor; },
830
+ set defaultVendor(v) { defaultVendor = v; },
831
+ get codexApproval() { return codexApproval; },
832
+ set codexApproval(v) { codexApproval = v; },
833
+ get codexSandbox() { return codexSandbox; },
834
+ set codexSandbox(v) { codexSandbox = v; },
835
+ get codexWebSearch() { return codexWebSearch; },
836
+ set codexWebSearch(v) { codexWebSearch = v; },
837
+ sessions: sessions,
838
+ sessionsDir: sessionsDir,
839
+ HISTORY_PAGE_SIZE: HISTORY_PAGE_SIZE,
840
+ getActiveSession: getActiveSession,
841
+ createSession: createSession,
842
+ createSessionRaw: createSessionRaw,
843
+ switchSession: switchSession,
844
+ deleteSession: deleteSession,
845
+ deleteSessionQuiet: deleteSessionQuiet,
846
+ deleteSessionsBulk: deleteSessionsBulk,
847
+ resumeSession: resumeSession,
848
+ broadcastSessionList: broadcastSessionList,
849
+ getTotalUnread: function (ws) {
850
+ var unreadMap = ws && ws._clayUnread ? ws._clayUnread : singleUserUnread;
851
+ var total = 0;
852
+ var keys = Object.keys(unreadMap);
853
+ for (var i = 0; i < keys.length; i++) {
854
+ total += unreadMap[keys[i]] || 0;
855
+ }
856
+ return total;
857
+ },
858
+ saveSessionFile: saveSessionFile,
859
+ appendToSessionFile: appendToSessionFile,
860
+ sendAndRecord: doSendAndRecord,
861
+ sendToSession: doSendToSession,
862
+ findTurnBoundary: findTurnBoundary,
863
+ replayHistory: replayHistory,
864
+ searchSessions: searchSessions,
865
+ searchSessionContent: searchSessionContent,
866
+ setResolveLoopInfo: setResolveLoopInfo,
867
+ migrateSessionTitles: migrateSessionTitles,
868
+ setSessionVisibility: function (localId, visibility) {
869
+ var session = sessions.get(localId);
870
+ if (!session) return { error: "Session not found" };
871
+ session.sessionVisibility = visibility;
872
+ saveSessionFile(session);
873
+ broadcastSessionList();
874
+ return { ok: true };
875
+ },
876
+ setSessionBookmarked: function (localId, bookmarked) {
877
+ var session = sessions.get(localId);
878
+ if (!session) return { error: "Session not found" };
879
+ session.bookmarked = !!bookmarked;
880
+ if (session.bookmarked) {
881
+ var maxOrder = -1;
882
+ sessions.forEach(function (s) {
883
+ if (s.bookmarked && typeof s.favoriteOrder === "number" && s.favoriteOrder > maxOrder) {
884
+ maxOrder = s.favoriteOrder;
885
+ }
886
+ });
887
+ session.favoriteOrder = maxOrder + 1;
888
+ } else {
889
+ session.favoriteOrder = null;
890
+ }
891
+ saveSessionFile(session);
892
+ broadcastSessionList();
893
+ return { ok: true };
894
+ },
895
+ reorderBookmarkedSessions: function (sourceId, targetId, insertBefore) {
896
+ var source = sessions.get(sourceId);
897
+ var target = sessions.get(targetId);
898
+ if (!source || !target) return { error: "Session not found" };
899
+ if (!source.bookmarked || !target.bookmarked) return { error: "Only favorites can be reordered" };
900
+
901
+ var favorites = [];
902
+ sessions.forEach(function (s) {
903
+ if (s.bookmarked) favorites.push(s);
904
+ });
905
+ favorites.sort(function (a, b) {
906
+ var ao = typeof a.favoriteOrder === "number" ? a.favoriteOrder : Number.MAX_SAFE_INTEGER;
907
+ var bo = typeof b.favoriteOrder === "number" ? b.favoriteOrder : Number.MAX_SAFE_INTEGER;
908
+ if (ao !== bo) return ao - bo;
909
+ return (b.lastActivity || 0) - (a.lastActivity || 0);
910
+ });
911
+
912
+ var reordered = [];
913
+ for (var i = 0; i < favorites.length; i++) {
914
+ if (favorites[i].localId !== sourceId) reordered.push(favorites[i]);
915
+ }
916
+
917
+ var targetIdx = -1;
918
+ for (var j = 0; j < reordered.length; j++) {
919
+ if (reordered[j].localId === targetId) {
920
+ targetIdx = j;
921
+ break;
922
+ }
923
+ }
924
+ if (targetIdx === -1) return { error: "Target favorite not found" };
925
+ if (!insertBefore) targetIdx++;
926
+ reordered.splice(targetIdx, 0, source);
927
+
928
+ for (var k = 0; k < reordered.length; k++) {
929
+ reordered[k].favoriteOrder = k;
930
+ saveSessionFile(reordered[k]);
931
+ }
932
+ broadcastSessionList();
933
+ return { ok: true };
934
+ },
935
+ setSessionOwner: function (localId, ownerId) {
936
+ var session = sessions.get(localId);
937
+ if (!session) return { error: "Session not found" };
938
+ session.ownerId = ownerId;
939
+ saveSessionFile(session);
940
+ return { ok: true };
941
+ },
942
+ permissionRequestIndex: permissionRequestIndex,
943
+ };
944
+ }
945
+
946
+ module.exports = { createSessionManager };