@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,302 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+ var usersModule = require("./users");
4
+ var userPresence = require("./user-presence");
5
+ var { getCodexConfig } = require("./codex-defaults");
6
+
7
+ /**
8
+ * Attach connection/disconnection handlers to a project context.
9
+ *
10
+ * ctx fields:
11
+ * cwd, slug, isMate, osUsers, debug, dangerouslySkipPermissions,
12
+ * currentVersion, lanHost, sm, tm, nm, clients, send, sendTo,
13
+ * opts, loopState, loopRegistry, _loop, pushModule,
14
+ * hydrateImageRefs, broadcastClientCount, broadcastPresence,
15
+ * getProjectList, getHubSchedules, loadContextSources,
16
+ * handleMessage, handleDisconnection,
17
+ * stopFileWatch, stopAllDirWatches,
18
+ * getProjectOwnerId, setProjectOwnerId, getLatestVersion,
19
+ * getTitle, getProject
20
+ */
21
+ function attachConnection(ctx) {
22
+ var cwd = ctx.cwd;
23
+ var slug = ctx.slug;
24
+ var osUsers = ctx.osUsers;
25
+ var debug = ctx.debug;
26
+ var dangerouslySkipPermissions = ctx.dangerouslySkipPermissions;
27
+ var currentVersion = ctx.currentVersion;
28
+ var lanHost = ctx.lanHost;
29
+ var sm = ctx.sm;
30
+ var tm = ctx.tm;
31
+ var nm = ctx.nm;
32
+ var clients = ctx.clients;
33
+ var send = ctx.send;
34
+ var sendTo = ctx.sendTo;
35
+ var opts = ctx.opts;
36
+ var _loop = ctx._loop;
37
+ var _mcp = ctx._mcp;
38
+ var _notifications = ctx._notifications;
39
+ var hydrateImageRefs = ctx.hydrateImageRefs;
40
+ var broadcastClientCount = ctx.broadcastClientCount;
41
+ var broadcastPresence = ctx.broadcastPresence;
42
+ var getProjectList = ctx.getProjectList;
43
+ var getHubSchedules = ctx.getHubSchedules;
44
+ var loadContextSources = ctx.loadContextSources;
45
+ var stopFileWatch = ctx.stopFileWatch;
46
+ var stopAllDirWatches = ctx.stopAllDirWatches;
47
+ var getProjectOwnerId = ctx.getProjectOwnerId;
48
+ var setProjectOwnerId = ctx.setProjectOwnerId;
49
+ var getLatestVersion = ctx.getLatestVersion;
50
+ var getTitle = ctx.getTitle;
51
+ var getProject = ctx.getProject;
52
+ var warmup = ctx.warmup;
53
+
54
+ // Adapters are initialized lazily: the first websocket connection into
55
+ // this project triggers warmup. Without this guard we would either keep
56
+ // the old eager behavior (30+ Codex processes at daemon start) or run
57
+ // warmup once per reconnect.
58
+ var _warmedUp = false;
59
+
60
+ function findRestoredActiveSession(ws, wsUser, allSessions) {
61
+ var active = null;
62
+ var presenceKey = wsUser ? wsUser.id : "_default";
63
+ var storedPresence = userPresence.getPresence(slug, presenceKey);
64
+ if (storedPresence && storedPresence.sessionId) {
65
+ if (sm.sessions.has(storedPresence.sessionId)) {
66
+ active = sm.sessions.get(storedPresence.sessionId);
67
+ } else {
68
+ sm.sessions.forEach(function (s) {
69
+ if (s.cliSessionId && s.cliSessionId === storedPresence.sessionId) active = s;
70
+ });
71
+ }
72
+ if (active && usersModule.isMultiUser() && wsUser) {
73
+ if (!usersModule.canAccessSession(wsUser.id, active, { visibility: "public" })) active = null;
74
+ } else if (active && !usersModule.isMultiUser() && active.ownerId) {
75
+ active = null;
76
+ }
77
+ }
78
+ if (!active && allSessions.length > 0) {
79
+ active = allSessions[0];
80
+ for (var fi = 1; fi < allSessions.length; fi++) {
81
+ if ((allSessions[fi].lastActivity || 0) > (active.lastActivity || 0)) {
82
+ active = allSessions[fi];
83
+ }
84
+ }
85
+ }
86
+ return { active: active, storedPresence: storedPresence };
87
+ }
88
+
89
+ function handleConnection(ws, wsUser, handleMessage, handleDisconnection) {
90
+ ws._clayUser = wsUser || null;
91
+ clients.add(ws);
92
+ broadcastClientCount();
93
+
94
+ if (!_warmedUp) {
95
+ _warmedUp = true;
96
+ if (typeof warmup === "function") {
97
+ try { warmup(); }
98
+ catch (e) { console.error("[project-connection] warmup failed for " + slug + ":", e && e.message ? e.message : e); }
99
+ }
100
+ }
101
+
102
+ var loopState = _loop.loopState;
103
+ var loopRegistry = _loop.loopRegistry;
104
+
105
+ // Resume loop if server restarted mid-execution (deferred so client gets initial state first)
106
+ if (loopState._needsResume) {
107
+ delete loopState._needsResume;
108
+ setTimeout(function() { _loop.resumeLoop(); }, 500);
109
+ }
110
+
111
+ var projectOwnerId = getProjectOwnerId();
112
+
113
+ // Send cached state
114
+ var _userId = ws._clayUser ? ws._clayUser.id : null;
115
+ var _filteredProjects = getProjectList(_userId);
116
+ var title = getTitle();
117
+ var project = getProject();
118
+ var ownerLocked = !!(osUsers && osUsers.length > 0 && /^\/home\/[^/]+\//.test(cwd));
119
+ var allSessions = [].concat(Array.from(sm.sessions.values())).filter(function (s) { return !s.hidden; });
120
+ if (usersModule.isMultiUser() && wsUser) {
121
+ allSessions = allSessions.filter(function (s) {
122
+ return usersModule.canAccessSession(wsUser.id, s, { visibility: "public" });
123
+ });
124
+ } else if (!usersModule.isMultiUser()) {
125
+ allSessions = allSessions.filter(function (s) { return !s.ownerId; });
126
+ }
127
+ var restoredState = findRestoredActiveSession(ws, wsUser, allSessions);
128
+ var restoredActive = restoredState.active;
129
+ var initialVendor = (restoredActive && restoredActive.vendor) || sm.defaultVendor || "claude";
130
+ var initialModels = (sm.modelsByVendor && sm.modelsByVendor[initialVendor]) || sm.availableModels || [];
131
+ sendTo(ws, { type: "info", cwd: cwd, slug: slug, project: title || project, version: currentVersion, debug: !!debug, dangerouslySkipPermissions: dangerouslySkipPermissions, osUsers: osUsers, lanHost: lanHost, projectCount: _filteredProjects.length, projects: _filteredProjects, projectOwnerId: projectOwnerId, ownerLocked: ownerLocked });
132
+ // Update notifications are pushed on a scheduled interval (see
133
+ // scheduleUpdateBroadcast). We no longer push on connect to avoid
134
+ // re-triggering the banner on every page refresh.
135
+ if (sm.slashCommands) {
136
+ sendTo(ws, { type: "slash_commands", commands: sm.slashCommands });
137
+ }
138
+ if (sm.currentModel) {
139
+ sendTo(ws, { type: "model_info", model: sm.currentModel, models: initialModels, vendor: initialVendor, availableVendors: sm.availableVendors || [], installedVendors: sm.installedVendors || [] });
140
+ }
141
+ sendTo(ws, { 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 });
142
+ sendTo(ws, Object.assign({ type: "codex_config" }, getCodexConfig(sm)));
143
+ sendTo(ws, { type: "term_list", terminals: tm.list() });
144
+ // Context sources sent after session is resolved (per-session storage)
145
+ sendTo(ws, { type: "notes_list", notes: nm.list() });
146
+ sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules() });
147
+ _loop.sendConnectionState(ws);
148
+ if (_mcp) _mcp.sendConnectionState(ws);
149
+ if (_notifications) _notifications.sendConnectionState(ws, sendTo);
150
+
151
+ // Session list (filtered for access control)
152
+ sendTo(ws, {
153
+ type: "session_list",
154
+ sessions: allSessions.map(function (s) {
155
+ var loop = s.loop ? Object.assign({}, s.loop) : null;
156
+ if (loop && loop.loopId && loopRegistry) {
157
+ var rec = loopRegistry.getById(loop.loopId);
158
+ if (rec) {
159
+ if (rec.name) loop.name = rec.name;
160
+ if (rec.source) loop.source = rec.source;
161
+ }
162
+ }
163
+ return {
164
+ id: s.localId,
165
+ cliSessionId: s.cliSessionId || null,
166
+ title: s.title || "New Session",
167
+ active: s.localId === (restoredActive ? restoredActive.localId : sm.activeSessionId),
168
+ isProcessing: s.isProcessing,
169
+ lastActivity: s.lastActivity || s.createdAt || 0,
170
+ loop: loop,
171
+ ownerId: s.ownerId || null,
172
+ sessionVisibility: s.sessionVisibility || "shared",
173
+ bookmarked: !!s.bookmarked,
174
+ favoriteOrder: typeof s.favoriteOrder === "number" ? s.favoriteOrder : null,
175
+ // Keep this aligned with sessions.js:mapSessionForClient — fields
176
+ // omitted here vanish from the row when this connect-time path runs
177
+ // instead of the standard broadcast.
178
+ vendor: s.vendor || null,
179
+ agentName: s.agentName || null,
180
+ };
181
+ }),
182
+ });
183
+
184
+ // Restore active session for this client from server-side presence
185
+ var active = restoredState.active;
186
+ var presenceKey = wsUser ? wsUser.id : "_default";
187
+ var storedPresence = restoredState.storedPresence;
188
+ var autoCreated = false;
189
+ if (!active) {
190
+ var autoOpts = {};
191
+ if (wsUser && usersModule.isMultiUser()) autoOpts.ownerId = wsUser.id;
192
+ active = sm.createSession(autoOpts, ws);
193
+ autoCreated = true;
194
+ }
195
+ if (active && !autoCreated) {
196
+ if (!active.ownerId && wsUser && usersModule.isMultiUser()) {
197
+ active.ownerId = wsUser.id;
198
+ sm.saveSessionFile(active);
199
+ }
200
+ ws._clayActiveSession = active.localId;
201
+ var _vendorCaps = (sm.capabilitiesByVendor && sm.capabilitiesByVendor[active.vendor || sm.defaultVendor || "claude"]) || {};
202
+ sendTo(ws, { type: "session_switched", id: active.localId, cliSessionId: active.cliSessionId || null, loop: active.loop || null, vendor: active.vendor || null, hasHistory: (active.history && active.history.length > 0), capabilities: _vendorCaps });
203
+ // Send per-session context sources
204
+ var sessionSources = loadContextSources(slug, active.localId);
205
+ sendTo(ws, { type: "context_sources_state", active: sessionSources });
206
+
207
+ var total = active.history.length;
208
+ var fromIndex = 0;
209
+ if (total > sm.HISTORY_PAGE_SIZE) {
210
+ fromIndex = sm.findTurnBoundary(active.history, Math.max(0, total - sm.HISTORY_PAGE_SIZE));
211
+ }
212
+ sendTo(ws, { type: "history_meta", total: total, from: fromIndex });
213
+ for (var i = fromIndex; i < total; i++) {
214
+ sendTo(ws, hydrateImageRefs(active.history[i]));
215
+ }
216
+ var _lastUsage = null, _lastModelUsage = null, _lastCost = null, _lastStreamInputTokens = null;
217
+ for (var _ri = total - 1; _ri >= 0; _ri--) {
218
+ if (active.history[_ri].type === "result") {
219
+ var _r = active.history[_ri];
220
+ _lastUsage = _r.usage || null;
221
+ _lastModelUsage = _r.modelUsage || null;
222
+ _lastCost = _r.cost != null ? _r.cost : null;
223
+ _lastStreamInputTokens = _r.lastStreamInputTokens || null;
224
+ break;
225
+ }
226
+ }
227
+ sendTo(ws, { type: "history_done", lastUsage: _lastUsage, lastModelUsage: _lastModelUsage, lastCost: _lastCost, lastStreamInputTokens: _lastStreamInputTokens, contextUsage: active.lastContextUsage || null });
228
+
229
+ if (active.isProcessing) {
230
+ sendTo(ws, { type: "status", status: "processing" });
231
+ }
232
+ var pendingIds = Object.keys(active.pendingPermissions);
233
+ for (var pi = 0; pi < pendingIds.length; pi++) {
234
+ var p = active.pendingPermissions[pendingIds[pi]];
235
+ sendTo(ws, {
236
+ type: "permission_request_pending",
237
+ requestId: p.requestId,
238
+ toolName: p.toolName,
239
+ toolInput: p.toolInput,
240
+ toolUseId: p.toolUseId,
241
+ decisionReason: p.decisionReason,
242
+ mateId: p.mateId || undefined,
243
+ });
244
+ }
245
+ }
246
+
247
+ if (active) {
248
+ userPresence.setPresence(slug, presenceKey, active.localId, storedPresence ? storedPresence.mateDm : null);
249
+ // For auto-created sessions, apply project email defaults
250
+ if (autoCreated) {
251
+ var _emailMod = ctx._email;
252
+ var _saveCtx = ctx.saveContextSources;
253
+ if (_emailMod && _emailMod.getEmailDefaults && _saveCtx) {
254
+ var emailDefs = _emailMod.getEmailDefaults();
255
+ if (emailDefs.length > 0) {
256
+ var defSources = emailDefs.map(function (id) { return "email:" + id; });
257
+ _saveCtx(slug, active.localId, defSources);
258
+ sendTo(ws, { type: "context_sources_state", active: defSources });
259
+ } else {
260
+ sendTo(ws, { type: "context_sources_state", active: [] });
261
+ }
262
+ } else {
263
+ sendTo(ws, { type: "context_sources_state", active: [] });
264
+ }
265
+ }
266
+ }
267
+ broadcastPresence();
268
+
269
+ ws.on("message", function (raw) {
270
+ var msg;
271
+ try { msg = JSON.parse(raw.toString()); } catch (e) { return; }
272
+ handleMessage(ws, msg);
273
+ });
274
+
275
+ ws.on("close", function () {
276
+ handleDisconnection(ws);
277
+ });
278
+ }
279
+
280
+ function handleDisconnection(ws) {
281
+ if (ws._clayActiveSession) {
282
+ var dcPresKey = ws._clayUser ? ws._clayUser.id : "_default";
283
+ var dcExisting = userPresence.getPresence(slug, dcPresKey);
284
+ userPresence.setPresence(slug, dcPresKey, ws._clayActiveSession, dcExisting ? dcExisting.mateDm : null);
285
+ }
286
+ tm.detachAll(ws);
287
+ clients.delete(ws);
288
+ if (clients.size === 0) {
289
+ stopFileWatch();
290
+ stopAllDirWatches();
291
+ }
292
+ broadcastClientCount();
293
+ broadcastPresence();
294
+ }
295
+
296
+ return {
297
+ handleConnection: handleConnection,
298
+ handleDisconnection: handleDisconnection,
299
+ };
300
+ }
301
+
302
+ module.exports = { attachConnection: attachConnection };
@@ -0,0 +1,236 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+
4
+ // How long (ms) to keep processed trigger files before pruning on startup.
5
+ var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
6
+
7
+ /**
8
+ * External trigger watcher — global singleton.
9
+ *
10
+ * Watches ~/.clagentic/external-triggers/ for JSON files dropped by external
11
+ * processes (scripts, daemons, agents). When a valid trigger file appears,
12
+ * opens a new session in the named project with initialPrompt as the first
13
+ * user-turn. The file is moved to processed/ on success.
14
+ *
15
+ * Schema v1 (all fields except * are required):
16
+ * { version: 1, id, projectSlug, initialPrompt, contextNote*, cwd*, createdAt* }
17
+ *
18
+ * ctx fields:
19
+ * triggersDir — absolute path to ~/.clagentic/external-triggers/
20
+ * getProject — function(slug) -> project context | null
21
+ *
22
+ * Security: triggers dir is under the user's home. Any process running as
23
+ * the same OS user can write files. Acceptable for single-user self-hosted
24
+ * installs. Multi-user deployments should use per-user subdirs (future work).
25
+ *
26
+ * Daemon-down recovery: unprocessed files that predate the current process
27
+ * start are picked up via a startup scan (scanExisting). No file is lost
28
+ * if the daemon is restarted while triggers are pending.
29
+ */
30
+ function attachExternalTrigger(ctx) {
31
+ var triggersDir = ctx.triggersDir;
32
+ var getProject = ctx.getProject;
33
+
34
+ var processedDir = path.join(triggersDir, "processed");
35
+ var watcher = null;
36
+ var debounce = null;
37
+ // Track IDs already dispatched this session to guard against double-fire
38
+ // from the initial scan + watcher race.
39
+ var dispatched = {};
40
+
41
+ // --- Directory setup ---
42
+
43
+ function ensureDirs() {
44
+ try { fs.mkdirSync(triggersDir, { recursive: true }); } catch (e) {}
45
+ try { fs.mkdirSync(processedDir, { recursive: true }); } catch (e) {}
46
+ }
47
+
48
+ // --- Trigger file validation ---
49
+
50
+ function validateTrigger(obj) {
51
+ if (!obj || typeof obj !== "object") return "not an object";
52
+ if (obj.version !== 1) return "unsupported version: " + obj.version;
53
+ if (!obj.id || typeof obj.id !== "string") return "missing id";
54
+ if (!obj.projectSlug || typeof obj.projectSlug !== "string") return "missing projectSlug";
55
+ if (!obj.initialPrompt || typeof obj.initialPrompt !== "string") return "missing initialPrompt";
56
+ return null; // valid
57
+ }
58
+
59
+ // --- Session spawn ---
60
+
61
+ function spawnSession(project, trigger) {
62
+ var sm = project.sm;
63
+ var sdk = project.sdk;
64
+ var send = project.send;
65
+ var onProcessingChanged = project.onProcessingChanged;
66
+ var getLinuxUserForSession = project.getLinuxUserForSession;
67
+
68
+ if (!sm || !sdk || !send || !onProcessingChanged || !getLinuxUserForSession) {
69
+ console.error("[external-trigger] Project context missing required fields for slug:", trigger.projectSlug);
70
+ return false;
71
+ }
72
+
73
+ var sess = sm.createSession({});
74
+ sess.title = (trigger.contextNote || "External trigger") + " — " + trigger.id.substring(0, 12);
75
+ if (trigger.cwd) sess.cwd = trigger.cwd;
76
+ sm.saveSessionFile(sess);
77
+ sm.broadcastSessionList();
78
+
79
+ var userMsg = { type: "user_message", text: trigger.initialPrompt };
80
+ sess.history.push(userMsg);
81
+ sm.appendToSessionFile(sess, userMsg);
82
+
83
+ sess.isProcessing = true;
84
+ onProcessingChanged();
85
+ sess.sentToolResults = {};
86
+ // singleTurn=false (default): session stays open for human follow-up.
87
+ // The trigger JSON can set singleTurn:true for fire-and-forget agentic
88
+ // dispatches (not part of v1 schema, reserved for future use).
89
+ sess.acceptEditsAfterStart = true;
90
+
91
+ try {
92
+ sdk.startQuery(sess, trigger.initialPrompt, undefined, getLinuxUserForSession(sess));
93
+ } catch (e) {
94
+ console.error("[external-trigger] startQuery failed for trigger " + trigger.id + ":", e.message || e);
95
+ return false;
96
+ }
97
+
98
+ console.log("[external-trigger] Session spawned: project=" + trigger.projectSlug + " session=" + sess.localId + " trigger=" + trigger.id);
99
+ return true;
100
+ }
101
+
102
+ // --- Archive ---
103
+
104
+ function archiveTrigger(triggerPath, id) {
105
+ var dest = path.join(processedDir, id + ".json");
106
+ try {
107
+ fs.renameSync(triggerPath, dest);
108
+ } catch (e) {
109
+ // Cross-device or race — try copy+delete
110
+ try {
111
+ fs.copyFileSync(triggerPath, dest);
112
+ fs.unlinkSync(triggerPath);
113
+ } catch (e2) {
114
+ console.error("[external-trigger] Failed to archive trigger " + id + ":", e2.message || e2);
115
+ }
116
+ }
117
+ }
118
+
119
+ // --- File handler ---
120
+
121
+ function handleFile(filePath) {
122
+ var base = path.basename(filePath);
123
+ if (!base.endsWith(".json")) return;
124
+ // Skip processed/ subdir entries that might bubble up
125
+ if (filePath.indexOf(processedDir) === 0) return;
126
+
127
+ var raw;
128
+ try { raw = fs.readFileSync(filePath, "utf8"); } catch (e) { return; }
129
+
130
+ var obj;
131
+ try { obj = JSON.parse(raw); } catch (e) {
132
+ console.warn("[external-trigger] Malformed JSON in " + base + ":", e.message);
133
+ return;
134
+ }
135
+
136
+ var err = validateTrigger(obj);
137
+ if (err) {
138
+ console.warn("[external-trigger] Invalid trigger " + base + ": " + err);
139
+ return;
140
+ }
141
+
142
+ var id = obj.id;
143
+ if (dispatched[id]) return; // already handled this session
144
+ dispatched[id] = true;
145
+
146
+ var project = getProject(obj.projectSlug);
147
+ if (!project) {
148
+ console.warn("[external-trigger] Unknown projectSlug '" + obj.projectSlug + "' in trigger " + id + " — dropping");
149
+ return;
150
+ }
151
+
152
+ var ok = spawnSession(project, obj);
153
+ if (ok) {
154
+ archiveTrigger(filePath, id);
155
+ }
156
+ }
157
+
158
+ // --- Watcher ---
159
+
160
+ function onDirChange() {
161
+ clearTimeout(debounce);
162
+ debounce = setTimeout(function () {
163
+ var files;
164
+ try { files = fs.readdirSync(triggersDir); } catch (e) { return; }
165
+ for (var i = 0; i < files.length; i++) {
166
+ if (!files[i].endsWith(".json")) continue;
167
+ var fp = path.join(triggersDir, files[i]);
168
+ // Skip entries inside processed/ subdir
169
+ if (fp.indexOf(processedDir) === 0) continue;
170
+ handleFile(fp);
171
+ }
172
+ }, 200);
173
+ }
174
+
175
+ function startWatcher() {
176
+ ensureDirs();
177
+ pruneOldProcessed();
178
+ scanExisting(); // pick up files dropped while daemon was down
179
+ try {
180
+ watcher = fs.watch(triggersDir, function (eventType, filename) {
181
+ if (filename && !filename.endsWith(".json")) return;
182
+ onDirChange();
183
+ });
184
+ watcher.on("error", function (e) {
185
+ console.error("[external-trigger] Watcher error:", e.message || e);
186
+ stopWatcher();
187
+ });
188
+ console.log("[external-trigger] Watching:", triggersDir);
189
+ } catch (e) {
190
+ console.error("[external-trigger] Failed to start watcher:", e.message || e);
191
+ }
192
+ }
193
+
194
+ function stopWatcher() {
195
+ clearTimeout(debounce);
196
+ if (watcher) {
197
+ try { watcher.close(); } catch (e) {}
198
+ watcher = null;
199
+ }
200
+ }
201
+
202
+ // --- Startup scan (daemon-down recovery) ---
203
+
204
+ function scanExisting() {
205
+ var files;
206
+ try { files = fs.readdirSync(triggersDir); } catch (e) { return; }
207
+ for (var i = 0; i < files.length; i++) {
208
+ if (!files[i].endsWith(".json")) continue;
209
+ handleFile(path.join(triggersDir, files[i]));
210
+ }
211
+ }
212
+
213
+ // --- Processed file pruning ---
214
+
215
+ function pruneOldProcessed() {
216
+ var now = Date.now();
217
+ var files;
218
+ try { files = fs.readdirSync(processedDir); } catch (e) { return; }
219
+ for (var i = 0; i < files.length; i++) {
220
+ var fp = path.join(processedDir, files[i]);
221
+ try {
222
+ var stat = fs.statSync(fp);
223
+ if (now - stat.mtimeMs > PROCESSED_MAX_AGE_MS) {
224
+ fs.unlinkSync(fp);
225
+ }
226
+ } catch (e) {}
227
+ }
228
+ }
229
+
230
+ return {
231
+ startWatcher: startWatcher,
232
+ stopWatcher: stopWatcher,
233
+ };
234
+ }
235
+
236
+ module.exports = { attachExternalTrigger: attachExternalTrigger };
@@ -0,0 +1,120 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+
4
+ /**
5
+ * Attach file/directory watcher engine to a project context.
6
+ *
7
+ * ctx fields:
8
+ * cwd, send, safePath, BINARY_EXTS, FS_MAX_SIZE, IGNORED_DIRS
9
+ */
10
+ function attachFileWatch(ctx) {
11
+ var cwd = ctx.cwd;
12
+ var send = ctx.send;
13
+ var safePath = ctx.safePath;
14
+ var BINARY_EXTS = ctx.BINARY_EXTS;
15
+ var FS_MAX_SIZE = ctx.FS_MAX_SIZE;
16
+ var IGNORED_DIRS = ctx.IGNORED_DIRS;
17
+
18
+ // --- File watcher ---
19
+ var fileWatcher = null;
20
+ var watchedPath = null;
21
+ var watchDebounce = null;
22
+
23
+ function startFileWatch(relPath) {
24
+ var absPath = safePath(cwd, relPath);
25
+ if (!absPath) return;
26
+ if (watchedPath === relPath) return;
27
+ stopFileWatch();
28
+ watchedPath = relPath;
29
+ try {
30
+ fileWatcher = fs.watch(absPath, function () {
31
+ clearTimeout(watchDebounce);
32
+ watchDebounce = setTimeout(function () {
33
+ try {
34
+ var stat = fs.statSync(absPath);
35
+ var ext = path.extname(absPath).toLowerCase();
36
+ if (stat.size > FS_MAX_SIZE || BINARY_EXTS.has(ext)) return;
37
+ var content = fs.readFileSync(absPath, "utf8");
38
+ send({ type: "fs_file_changed", path: relPath, content: content, size: stat.size });
39
+ } catch (e) {
40
+ stopFileWatch();
41
+ }
42
+ }, 200);
43
+ });
44
+ fileWatcher.on("error", function () { stopFileWatch(); });
45
+ } catch (e) {
46
+ watchedPath = null;
47
+ }
48
+ }
49
+
50
+ function stopFileWatch() {
51
+ if (fileWatcher) {
52
+ try { fileWatcher.close(); } catch (e) {}
53
+ fileWatcher = null;
54
+ }
55
+ clearTimeout(watchDebounce);
56
+ watchDebounce = null;
57
+ watchedPath = null;
58
+ }
59
+
60
+ // --- Directory watcher ---
61
+ var dirWatchers = {}; // relPath -> { watcher, debounce }
62
+
63
+ function startDirWatch(relPath) {
64
+ if (dirWatchers[relPath]) return;
65
+ var absPath = safePath(cwd, relPath);
66
+ if (!absPath) return;
67
+ try {
68
+ var debounce = null;
69
+ var watcher = fs.watch(absPath, function () {
70
+ clearTimeout(debounce);
71
+ debounce = setTimeout(function () {
72
+ // Re-read directory and broadcast to all clients
73
+ try {
74
+ var items = fs.readdirSync(absPath, { withFileTypes: true });
75
+ var entries = [];
76
+ for (var i = 0; i < items.length; i++) {
77
+ if (items[i].isDirectory() && IGNORED_DIRS.has(items[i].name)) continue;
78
+ entries.push({
79
+ name: items[i].name,
80
+ type: items[i].isDirectory() ? "dir" : "file",
81
+ path: path.relative(cwd, path.join(absPath, items[i].name)).split(path.sep).join("/"),
82
+ });
83
+ }
84
+ send({ type: "fs_dir_changed", path: relPath, entries: entries });
85
+ } catch (e) {
86
+ stopDirWatch(relPath);
87
+ }
88
+ }, 300);
89
+ });
90
+ watcher.on("error", function () { stopDirWatch(relPath); });
91
+ dirWatchers[relPath] = { watcher: watcher, debounce: debounce };
92
+ } catch (e) {}
93
+ }
94
+
95
+ function stopDirWatch(relPath) {
96
+ var entry = dirWatchers[relPath];
97
+ if (entry) {
98
+ clearTimeout(entry.debounce);
99
+ try { entry.watcher.close(); } catch (e) {}
100
+ delete dirWatchers[relPath];
101
+ }
102
+ }
103
+
104
+ function stopAllDirWatches() {
105
+ var paths = Object.keys(dirWatchers);
106
+ for (var i = 0; i < paths.length; i++) {
107
+ stopDirWatch(paths[i]);
108
+ }
109
+ }
110
+
111
+ return {
112
+ startFileWatch: startFileWatch,
113
+ stopFileWatch: stopFileWatch,
114
+ startDirWatch: startDirWatch,
115
+ stopDirWatch: stopDirWatch,
116
+ stopAllDirWatches: stopAllDirWatches,
117
+ };
118
+ }
119
+
120
+ module.exports = { attachFileWatch: attachFileWatch };