@hailer/mcp 0.1.16 → 0.2.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 (202) hide show
  1. package/dist/app.js +24 -20
  2. package/dist/core.d.ts +33 -9
  3. package/dist/core.js +279 -147
  4. package/dist/mcp/UserContextCache.js +18 -0
  5. package/dist/mcp/hailer-clients.d.ts +9 -1
  6. package/dist/mcp/hailer-clients.js +13 -3
  7. package/dist/mcp/signal-handler.js +1 -1
  8. package/dist/mcp/tool-registry.d.ts +3 -1
  9. package/dist/mcp/tool-registry.js +4 -1
  10. package/dist/mcp/tools/activity.js +43 -34
  11. package/dist/mcp/tools/bot-config/constants.d.ts +23 -0
  12. package/dist/mcp/tools/bot-config/constants.js +94 -0
  13. package/dist/mcp/tools/{bot-config.d.ts → bot-config/core.d.ts} +6 -6
  14. package/dist/mcp/tools/{bot-config.js → bot-config/core.js} +15 -15
  15. package/dist/mcp/tools/bot-config/index.d.ts +10 -0
  16. package/dist/mcp/tools/bot-config/index.js +59 -0
  17. package/dist/mcp/tools/bot-config/tools.d.ts +7 -0
  18. package/dist/mcp/tools/bot-config/tools.js +15 -0
  19. package/dist/mcp/tools/bot-config/types.d.ts +50 -0
  20. package/dist/mcp/tools/bot-config/types.js +6 -0
  21. package/dist/mcp/tools/bug-fixer-tools.d.ts +21 -0
  22. package/dist/mcp/tools/{giuseppe-tools.js → bug-fixer-tools.js} +61 -61
  23. package/dist/mcp/tools/user.js +10 -29
  24. package/dist/mcp/tools/workflow.js +36 -2
  25. package/dist/mcp/utils/data-transformers.d.ts +0 -8
  26. package/dist/mcp/utils/data-transformers.js +0 -28
  27. package/dist/mcp/utils/index.d.ts +4 -1
  28. package/dist/mcp/utils/index.js +17 -3
  29. package/dist/mcp/utils/pagination.d.ts +40 -0
  30. package/dist/mcp/utils/pagination.js +55 -0
  31. package/dist/mcp/utils/response-builder.d.ts +53 -0
  32. package/dist/mcp/utils/response-builder.js +110 -0
  33. package/dist/mcp/utils/tool-helpers.d.ts +0 -8
  34. package/dist/mcp/utils/tool-helpers.js +0 -24
  35. package/dist/mcp/utils/types.d.ts +1 -33
  36. package/dist/mcp/webhook-handler.d.ts +2 -2
  37. package/dist/mcp/webhook-handler.js +5 -3
  38. package/dist/mcp-server.d.ts +2 -2
  39. package/dist/mcp-server.js +167 -140
  40. package/package.json +1 -1
  41. package/REFACTOR_STATUS.md +0 -127
  42. package/dist/agents/bot-manager.d.ts +0 -48
  43. package/dist/agents/bot-manager.js +0 -254
  44. package/dist/agents/factory.d.ts +0 -150
  45. package/dist/agents/factory.js +0 -650
  46. package/dist/agents/giuseppe/ai.d.ts +0 -83
  47. package/dist/agents/giuseppe/ai.js +0 -466
  48. package/dist/agents/giuseppe/bot.d.ts +0 -110
  49. package/dist/agents/giuseppe/bot.js +0 -780
  50. package/dist/agents/giuseppe/config.d.ts +0 -25
  51. package/dist/agents/giuseppe/config.js +0 -227
  52. package/dist/agents/giuseppe/files.d.ts +0 -52
  53. package/dist/agents/giuseppe/files.js +0 -338
  54. package/dist/agents/giuseppe/git.d.ts +0 -48
  55. package/dist/agents/giuseppe/git.js +0 -298
  56. package/dist/agents/giuseppe/index.d.ts +0 -97
  57. package/dist/agents/giuseppe/index.js +0 -258
  58. package/dist/agents/giuseppe/lsp.d.ts +0 -113
  59. package/dist/agents/giuseppe/lsp.js +0 -485
  60. package/dist/agents/giuseppe/monitor.d.ts +0 -118
  61. package/dist/agents/giuseppe/monitor.js +0 -621
  62. package/dist/agents/giuseppe/prompt.d.ts +0 -5
  63. package/dist/agents/giuseppe/prompt.js +0 -94
  64. package/dist/agents/giuseppe/registries/pending-classification.d.ts +0 -28
  65. package/dist/agents/giuseppe/registries/pending-classification.js +0 -50
  66. package/dist/agents/giuseppe/registries/pending-fix.d.ts +0 -30
  67. package/dist/agents/giuseppe/registries/pending-fix.js +0 -42
  68. package/dist/agents/giuseppe/registries/pending.d.ts +0 -27
  69. package/dist/agents/giuseppe/registries/pending.js +0 -49
  70. package/dist/agents/giuseppe/specialist.d.ts +0 -47
  71. package/dist/agents/giuseppe/specialist.js +0 -237
  72. package/dist/agents/giuseppe/types.d.ts +0 -123
  73. package/dist/agents/giuseppe/types.js +0 -9
  74. package/dist/agents/hailer-expert/index.d.ts +0 -8
  75. package/dist/agents/hailer-expert/index.js +0 -14
  76. package/dist/agents/hal/daemon.d.ts +0 -142
  77. package/dist/agents/hal/daemon.js +0 -1103
  78. package/dist/agents/hal/definitions.d.ts +0 -55
  79. package/dist/agents/hal/definitions.js +0 -263
  80. package/dist/agents/hal/index.d.ts +0 -3
  81. package/dist/agents/hal/index.js +0 -8
  82. package/dist/agents/index.d.ts +0 -18
  83. package/dist/agents/index.js +0 -48
  84. package/dist/agents/shared/base.d.ts +0 -216
  85. package/dist/agents/shared/base.js +0 -846
  86. package/dist/agents/shared/services/agent-registry.d.ts +0 -107
  87. package/dist/agents/shared/services/agent-registry.js +0 -629
  88. package/dist/agents/shared/services/conversation-manager.d.ts +0 -50
  89. package/dist/agents/shared/services/conversation-manager.js +0 -136
  90. package/dist/agents/shared/services/mcp-client.d.ts +0 -56
  91. package/dist/agents/shared/services/mcp-client.js +0 -124
  92. package/dist/agents/shared/services/message-classifier.d.ts +0 -37
  93. package/dist/agents/shared/services/message-classifier.js +0 -187
  94. package/dist/agents/shared/services/message-formatter.d.ts +0 -89
  95. package/dist/agents/shared/services/message-formatter.js +0 -371
  96. package/dist/agents/shared/services/session-logger.d.ts +0 -106
  97. package/dist/agents/shared/services/session-logger.js +0 -446
  98. package/dist/agents/shared/services/tool-executor.d.ts +0 -41
  99. package/dist/agents/shared/services/tool-executor.js +0 -169
  100. package/dist/agents/shared/services/workspace-schema-cache.d.ts +0 -125
  101. package/dist/agents/shared/services/workspace-schema-cache.js +0 -578
  102. package/dist/agents/shared/specialist.d.ts +0 -91
  103. package/dist/agents/shared/specialist.js +0 -399
  104. package/dist/agents/shared/tool-schema-loader.d.ts +0 -62
  105. package/dist/agents/shared/tool-schema-loader.js +0 -232
  106. package/dist/agents/shared/types.d.ts +0 -327
  107. package/dist/agents/shared/types.js +0 -121
  108. package/dist/client/agents/base.d.ts +0 -207
  109. package/dist/client/agents/base.js +0 -744
  110. package/dist/client/agents/definitions.d.ts +0 -53
  111. package/dist/client/agents/definitions.js +0 -263
  112. package/dist/client/agents/orchestrator.d.ts +0 -141
  113. package/dist/client/agents/orchestrator.js +0 -1062
  114. package/dist/client/agents/specialist.d.ts +0 -86
  115. package/dist/client/agents/specialist.js +0 -340
  116. package/dist/client/bot-entrypoint.d.ts +0 -7
  117. package/dist/client/bot-entrypoint.js +0 -103
  118. package/dist/client/bot-manager.d.ts +0 -44
  119. package/dist/client/bot-manager.js +0 -173
  120. package/dist/client/bot-runner.d.ts +0 -35
  121. package/dist/client/bot-runner.js +0 -188
  122. package/dist/client/chat-agent-daemon.d.ts +0 -464
  123. package/dist/client/chat-agent-daemon.js +0 -1774
  124. package/dist/client/daemon-factory.d.ts +0 -106
  125. package/dist/client/daemon-factory.js +0 -301
  126. package/dist/client/factory.d.ts +0 -111
  127. package/dist/client/factory.js +0 -314
  128. package/dist/client/index.d.ts +0 -17
  129. package/dist/client/index.js +0 -38
  130. package/dist/client/multi-bot-manager.d.ts +0 -42
  131. package/dist/client/multi-bot-manager.js +0 -161
  132. package/dist/client/orchestrator-daemon.d.ts +0 -87
  133. package/dist/client/orchestrator-daemon.js +0 -444
  134. package/dist/client/server.d.ts +0 -8
  135. package/dist/client/server.js +0 -251
  136. package/dist/client/services/agent-registry.d.ts +0 -108
  137. package/dist/client/services/agent-registry.js +0 -630
  138. package/dist/client/services/conversation-manager.d.ts +0 -50
  139. package/dist/client/services/conversation-manager.js +0 -136
  140. package/dist/client/services/mcp-client.d.ts +0 -48
  141. package/dist/client/services/mcp-client.js +0 -105
  142. package/dist/client/services/message-classifier.d.ts +0 -37
  143. package/dist/client/services/message-classifier.js +0 -187
  144. package/dist/client/services/message-formatter.d.ts +0 -84
  145. package/dist/client/services/message-formatter.js +0 -353
  146. package/dist/client/services/session-logger.d.ts +0 -106
  147. package/dist/client/services/session-logger.js +0 -446
  148. package/dist/client/services/tool-executor.d.ts +0 -41
  149. package/dist/client/services/tool-executor.js +0 -169
  150. package/dist/client/services/workspace-schema-cache.d.ts +0 -149
  151. package/dist/client/services/workspace-schema-cache.js +0 -732
  152. package/dist/client/specialist-daemon.d.ts +0 -77
  153. package/dist/client/specialist-daemon.js +0 -197
  154. package/dist/client/specialists.d.ts +0 -53
  155. package/dist/client/specialists.js +0 -178
  156. package/dist/client/tool-schema-loader.d.ts +0 -62
  157. package/dist/client/tool-schema-loader.js +0 -232
  158. package/dist/client/types.d.ts +0 -327
  159. package/dist/client/types.js +0 -121
  160. package/dist/commands/seed-config.d.ts +0 -9
  161. package/dist/commands/seed-config.js +0 -372
  162. package/dist/lib/context-manager.d.ts +0 -111
  163. package/dist/lib/context-manager.js +0 -431
  164. package/dist/lib/prompt-length-manager.d.ts +0 -81
  165. package/dist/lib/prompt-length-manager.js +0 -457
  166. package/dist/mcp/tools/giuseppe-tools.d.ts +0 -21
  167. package/dist/modules/bug-reports/bug-config.d.ts +0 -25
  168. package/dist/modules/bug-reports/bug-config.js +0 -187
  169. package/dist/modules/bug-reports/bug-monitor.d.ts +0 -108
  170. package/dist/modules/bug-reports/bug-monitor.js +0 -510
  171. package/dist/modules/bug-reports/giuseppe-agent.d.ts +0 -58
  172. package/dist/modules/bug-reports/giuseppe-agent.js +0 -467
  173. package/dist/modules/bug-reports/giuseppe-ai.d.ts +0 -83
  174. package/dist/modules/bug-reports/giuseppe-ai.js +0 -466
  175. package/dist/modules/bug-reports/giuseppe-bot.d.ts +0 -110
  176. package/dist/modules/bug-reports/giuseppe-bot.js +0 -804
  177. package/dist/modules/bug-reports/giuseppe-daemon.d.ts +0 -80
  178. package/dist/modules/bug-reports/giuseppe-daemon.js +0 -617
  179. package/dist/modules/bug-reports/giuseppe-files.d.ts +0 -64
  180. package/dist/modules/bug-reports/giuseppe-files.js +0 -375
  181. package/dist/modules/bug-reports/giuseppe-git.d.ts +0 -48
  182. package/dist/modules/bug-reports/giuseppe-git.js +0 -298
  183. package/dist/modules/bug-reports/giuseppe-lsp.d.ts +0 -113
  184. package/dist/modules/bug-reports/giuseppe-lsp.js +0 -485
  185. package/dist/modules/bug-reports/giuseppe-prompt.d.ts +0 -5
  186. package/dist/modules/bug-reports/giuseppe-prompt.js +0 -94
  187. package/dist/modules/bug-reports/index.d.ts +0 -77
  188. package/dist/modules/bug-reports/index.js +0 -215
  189. package/dist/modules/bug-reports/pending-classification-registry.d.ts +0 -28
  190. package/dist/modules/bug-reports/pending-classification-registry.js +0 -50
  191. package/dist/modules/bug-reports/pending-fix-registry.d.ts +0 -30
  192. package/dist/modules/bug-reports/pending-fix-registry.js +0 -42
  193. package/dist/modules/bug-reports/pending-registry.d.ts +0 -27
  194. package/dist/modules/bug-reports/pending-registry.js +0 -49
  195. package/dist/modules/bug-reports/types.d.ts +0 -123
  196. package/dist/modules/bug-reports/types.js +0 -9
  197. package/dist/routes/agents.d.ts +0 -44
  198. package/dist/routes/agents.js +0 -311
  199. package/dist/services/agent-credential-store.d.ts +0 -73
  200. package/dist/services/agent-credential-store.js +0 -212
  201. package/dist/services/bug-monitor.d.ts +0 -23
  202. package/dist/services/bug-monitor.js +0 -275
@@ -1,371 +0,0 @@
1
- "use strict";
2
- /**
3
- * Message Formatter Service
4
- *
5
- * Handles formatting of messages for Hailer:
6
- * - Converting @mentions and #activity tags to Hailer tags
7
- * - Resolving user/activity IDs via API
8
- * - Extracting tag links for messenger.send
9
- */
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- exports.MessageFormatterService = void 0;
12
- class MessageFormatterService {
13
- botClient;
14
- logger;
15
- callMcpTool;
16
- constructor(botClient, logger, callMcpTool) {
17
- this.botClient = botClient;
18
- this.logger = logger;
19
- this.callMcpTool = callMcpTool;
20
- }
21
- /**
22
- * Sanitize display name to prevent tag injection attacks
23
- * Removes/escapes characters that could break the tag format
24
- */
25
- sanitizeDisplayName(name) {
26
- if (!name || typeof name !== 'string') {
27
- return 'Unknown';
28
- }
29
- // Remove or escape characters that could break the tag format:
30
- // [ ] | ( ) could break markdown-style tag parsing
31
- // Control characters and ZWNBSP could cause rendering issues
32
- return name
33
- .replace(/[\[\]|()]/g, '') // Remove tag-breaking characters
34
- .replace(/[\u0000-\u001F\uFEFF]/g, '') // Remove control chars and ZWNBSP
35
- .replace(/\s+/g, ' ') // Normalize whitespace
36
- .trim()
37
- .slice(0, 100) || 'Unknown'; // Limit length
38
- }
39
- /**
40
- * Validate that targetId is a valid MongoDB ObjectId format
41
- */
42
- isValidTargetId(id) {
43
- return /^[a-f0-9]{24}$/i.test(id);
44
- }
45
- /**
46
- * Format a Hailer tag for mentioning a user or activity
47
- * Hailer requires ZWNBSP (U+FEFF) around the tag
48
- */
49
- formatHailerTag(targetId, displayName) {
50
- // Validate targetId format
51
- if (!this.isValidTargetId(targetId)) {
52
- this.logger.warn('Invalid targetId format for Hailer tag', { targetId });
53
- return displayName; // Return plain text if ID is invalid
54
- }
55
- const sanitizedName = this.sanitizeDisplayName(displayName);
56
- const ZWNBSP = '\uFEFF';
57
- return `${ZWNBSP}[hailerTag|${sanitizedName}](${targetId})${ZWNBSP}`;
58
- }
59
- /**
60
- * Look up user by ID and create a Hailer tag
61
- */
62
- createUserTagById(userId) {
63
- const cache = this.botClient.workspaceCache;
64
- if (!cache)
65
- return null;
66
- const user = cache.usersById[userId];
67
- if (!user)
68
- return null;
69
- const displayName = user.fullName || `${user.firstname} ${user.lastname}`.trim();
70
- return this.formatHailerTag(userId, displayName);
71
- }
72
- /**
73
- * Look up user by name and create a Hailer tag
74
- */
75
- createUserTagByName(name) {
76
- const cache = this.botClient.workspaceCache;
77
- if (!cache)
78
- return null;
79
- const nameLower = name.toLowerCase();
80
- const user = cache.users.find(u => {
81
- const fullName = u.fullName || `${u.firstname} ${u.lastname}`.trim();
82
- return fullName.toLowerCase() === nameLower ||
83
- u.firstname?.toLowerCase() === nameLower ||
84
- u.lastname?.toLowerCase() === nameLower;
85
- });
86
- if (!user)
87
- return null;
88
- const displayName = user.fullName || `${user.firstname} ${user.lastname}`.trim();
89
- return this.formatHailerTag(user.id, displayName);
90
- }
91
- /**
92
- * Convert @mentions and #activity tags in response to Hailer tags
93
- * Supports:
94
- * - @userId (24-char hex MongoDB ID) → user tag
95
- * - @"Full Name" (quoted name lookup) → user tag
96
- * - @FirstName (single word name lookup) → user tag
97
- * - #activityId (24-char hex) → activity tag
98
- * - #"Activity Name" (quoted) → activity tag (requires lookup)
99
- */
100
- convertMentionsToTags(content) {
101
- // User mentions (from cache)
102
- const cache = this.botClient.workspaceCache;
103
- if (cache) {
104
- // Pattern 1: @userId (24-char hex)
105
- content = content.replace(/@([a-f0-9]{24})\b/gi, (match, userId) => {
106
- const tag = this.createUserTagById(userId);
107
- return tag || match;
108
- });
109
- // Pattern 2: @"Full Name" (quoted)
110
- content = content.replace(/@"([^"]+)"/g, (match, name) => {
111
- const tag = this.createUserTagByName(name);
112
- return tag || match;
113
- });
114
- // Pattern 3: @FirstName (single word, capitalized)
115
- content = content.replace(/@([A-Z][a-z]+)\b/g, (match, name) => {
116
- const tag = this.createUserTagByName(name);
117
- return tag || match;
118
- });
119
- }
120
- // Activity tags (#activityId and #"Name") are handled by
121
- // resolveActivityTags (async) which runs before this
122
- return content;
123
- }
124
- /**
125
- * Resolve user tags - look up names for IDs via API when not in cache
126
- * Handles @userId (24-char hex) format
127
- */
128
- async resolveUserTags(content) {
129
- const pattern = /@([a-f0-9]{24})\b/gi;
130
- const matches = [...content.matchAll(pattern)];
131
- for (const match of matches) {
132
- const userId = match[1];
133
- // Try cache first
134
- const cachedTag = this.createUserTagById(userId);
135
- if (cachedTag) {
136
- content = content.replace(match[0], cachedTag);
137
- this.logger.debug("User tag from cache", { userId });
138
- continue;
139
- }
140
- // Fallback to API
141
- try {
142
- this.logger.info("Resolving user tag via API", { userId });
143
- const result = await this.callMcpTool("search_workspace_users", { query: userId });
144
- const resultText = result?.content?.[0]?.text;
145
- if (resultText) {
146
- // Parse the JSON array from the response
147
- // Response format: "Found X users:\n\n```json\n[...]\n```"
148
- const jsonMatch = resultText.match(/```json\s*([\s\S]*?)\s*```/);
149
- if (jsonMatch) {
150
- const users = JSON.parse(jsonMatch[1]);
151
- const user = users.find((u) => u._id === userId);
152
- if (user) {
153
- const displayName = `${user.firstname || ''} ${user.lastname || ''}`.trim() || user.fullName || userId;
154
- const tag = this.formatHailerTag(userId, displayName);
155
- content = content.replace(match[0], tag);
156
- this.logger.info("Created user tag from API", { userId, displayName });
157
- }
158
- }
159
- }
160
- }
161
- catch (error) {
162
- this.logger.warn("Failed to resolve user tag", { userId, error });
163
- // Leave as @userId - won't be clickable but visible
164
- }
165
- }
166
- return content;
167
- }
168
- /**
169
- * Resolve activity tags - look up names for IDs and IDs for names
170
- * Handles both #activityId and #"Activity Name" formats
171
- */
172
- async resolveActivityTags(content) {
173
- // Pattern 1: #activityId (24-char hex) - need to look up the name
174
- const activityIdPattern = /#([a-f0-9]{24})\b/gi;
175
- const idMatches = [...content.matchAll(activityIdPattern)];
176
- for (const match of idMatches) {
177
- const activityId = match[1];
178
- try {
179
- this.logger.info("Resolving activity tag by ID", { activityId });
180
- // Fetch activity by ID to get its name
181
- const result = await this.callMcpTool("show_activity_by_id", {
182
- activityId: activityId,
183
- });
184
- const resultText = result?.content?.[0]?.text;
185
- this.logger.debug("show_activity_by_id response", {
186
- hasResult: !!resultText,
187
- preview: resultText?.substring(0, 200)
188
- });
189
- if (resultText) {
190
- // Response format: "✅ Loaded activity with ID "xxx":\n\n{ JSON }"
191
- // Extract the JSON part after the header
192
- const jsonMatch = resultText.match(/\{[\s\S]*\}/);
193
- if (jsonMatch) {
194
- const parsed = JSON.parse(jsonMatch[0]);
195
- const activityName = parsed.name;
196
- this.logger.info("Extracted activity name", { activityId, activityName });
197
- if (activityName) {
198
- const tag = this.formatHailerTag(activityId, activityName);
199
- content = content.replace(match[0], tag);
200
- this.logger.info("Created activity tag", { tag });
201
- }
202
- }
203
- else {
204
- this.logger.warn("Could not extract JSON from response", { preview: resultText.substring(0, 100) });
205
- }
206
- }
207
- }
208
- catch (error) {
209
- this.logger.warn("Failed to resolve activity ID tag", { activityId, error });
210
- // Leave as #id - won't be clickable but at least visible
211
- }
212
- }
213
- // Pattern 2: #"Activity Name" - need to look up the ID
214
- // This is harder because list_activities requires workflowId/phaseId
215
- // For now, search in each workflow until we find a match
216
- const activityNamePattern = /#"([^"]+)"/g;
217
- const nameMatches = [...content.matchAll(activityNamePattern)];
218
- for (const match of nameMatches) {
219
- const activityName = match[1];
220
- try {
221
- // Get list of workflows first
222
- const workflowsResult = await this.callMcpTool("list_workflows_minimal", {});
223
- const workflowsText = workflowsResult?.content?.[0]?.text;
224
- if (workflowsText) {
225
- // Extract workflow IDs from the response (format varies)
226
- const workflowIdMatches = workflowsText.matchAll(/"_id":\s*"([a-f0-9]{24})"/gi);
227
- const workflowIds = [...workflowIdMatches].map(m => m[1]);
228
- // Search each workflow for the activity
229
- for (const workflowId of workflowIds.slice(0, 5)) { // Limit to first 5 workflows
230
- try {
231
- const phasesResult = await this.callMcpTool("list_workflow_phases", { workflowId });
232
- const phasesText = phasesResult?.content?.[0]?.text;
233
- if (phasesText) {
234
- const phaseIdMatches = phasesText.matchAll(/"_id":\s*"([a-f0-9]{24})"/gi);
235
- const phaseIds = [...phaseIdMatches].map(m => m[1]);
236
- for (const phaseId of phaseIds.slice(0, 3)) { // Limit to first 3 phases
237
- const activitiesResult = await this.callMcpTool("list_activities", {
238
- workflowId,
239
- phaseId,
240
- search: activityName,
241
- limit: 1,
242
- });
243
- const activitiesText = activitiesResult?.content?.[0]?.text;
244
- if (activitiesText) {
245
- // Look for activity ID and name in the response
246
- const activityIdMatch = activitiesText.match(/"_id":\s*"([a-f0-9]{24})"/i);
247
- if (activityIdMatch) {
248
- const foundId = activityIdMatch[1];
249
- const tag = this.formatHailerTag(foundId, activityName);
250
- content = content.replace(match[0], tag);
251
- break; // Found it, stop searching
252
- }
253
- }
254
- }
255
- }
256
- }
257
- catch {
258
- // Continue to next workflow
259
- }
260
- }
261
- }
262
- }
263
- catch (error) {
264
- this.logger.warn("Failed to resolve activity name tag", { activityName, error });
265
- // Leave the original #"Name" in place
266
- }
267
- }
268
- return content;
269
- }
270
- /**
271
- * Convert Hailer URLs to Hailer tags
272
- * Handles:
273
- * - https://app.hailer.com/#/activities/{activityId}
274
- * - https://app.hailer.com/#/discussions/{discussionId}
275
- */
276
- async resolveHailerUrls(content) {
277
- // Pattern for activity URLs
278
- const activityUrlPattern = /https?:\/\/app\.hailer\.com\/#\/activities\/([a-f0-9]{24})/gi;
279
- const activityMatches = [...content.matchAll(activityUrlPattern)];
280
- for (const match of activityMatches) {
281
- const activityId = match[1];
282
- try {
283
- const result = await this.callMcpTool("show_activity_by_id", { activityId });
284
- const resultText = result?.content?.[0]?.text;
285
- if (resultText) {
286
- const jsonMatch = resultText.match(/\{[\s\S]*\}/);
287
- if (jsonMatch) {
288
- const parsed = JSON.parse(jsonMatch[0]);
289
- const activityName = parsed.name;
290
- if (activityName) {
291
- const tag = this.formatHailerTag(activityId, activityName);
292
- content = content.replace(match[0], tag);
293
- this.logger.debug("Converted activity URL to tag", { activityId, activityName });
294
- }
295
- }
296
- }
297
- }
298
- catch (error) {
299
- this.logger.debug("Failed to resolve activity URL", { activityId, error });
300
- // Leave URL as-is
301
- }
302
- }
303
- // Pattern for discussion URLs - need to look up the linked activity
304
- const discussionUrlPattern = /https?:\/\/app\.hailer\.com\/#\/discussions\/([a-f0-9]{24})/gi;
305
- const discussionMatches = [...content.matchAll(discussionUrlPattern)];
306
- for (const match of discussionMatches) {
307
- const discussionId = match[1];
308
- try {
309
- // Load discussion to get linked activity
310
- const discussionResponse = await this.botClient.client.socket.request("messenger.load_discussions", [[discussionId]]);
311
- if (discussionResponse && discussionResponse[discussionId]) {
312
- const discData = discussionResponse[discussionId];
313
- const linkedActivityId = discData.linked_activity;
314
- const discussionName = discData.name;
315
- if (linkedActivityId) {
316
- // It's an activity discussion - use the activity ID for the tag
317
- const tag = this.formatHailerTag(linkedActivityId, discussionName || "Activity");
318
- content = content.replace(match[0], tag);
319
- this.logger.debug("Converted discussion URL to activity tag", { discussionId, linkedActivityId, discussionName });
320
- }
321
- else if (discussionName) {
322
- // It's a standalone discussion - use discussion name but discussion ID
323
- const tag = this.formatHailerTag(discussionId, discussionName);
324
- content = content.replace(match[0], tag);
325
- this.logger.debug("Converted discussion URL to discussion tag", { discussionId, discussionName });
326
- }
327
- }
328
- }
329
- catch (error) {
330
- this.logger.debug("Failed to resolve discussion URL", { discussionId, error });
331
- // Leave URL as-is
332
- }
333
- }
334
- return content;
335
- }
336
- /**
337
- * Extract link metadata from hailerTag formatted content
338
- * Returns array of links for the messenger.send API
339
- */
340
- extractTagLinks(content) {
341
- const links = [];
342
- // Match all hailerTag patterns: [hailerTag|Name](id)
343
- const tagPattern = /\[hailerTag\|[^\]]+\]\(([a-f0-9]{24})\)/gi;
344
- const matches = content.matchAll(tagPattern);
345
- for (const match of matches) {
346
- const targetId = match[1];
347
- // Determine if it's a user or activity based on context
348
- // For now, check if it's in the user cache
349
- const isUser = this.botClient.workspaceCache?.usersById[targetId];
350
- links.push({
351
- target: targetId,
352
- targetType: isUser ? 'user' : 'activity',
353
- type: 'linked-to'
354
- });
355
- }
356
- return links;
357
- }
358
- /**
359
- * Format incoming message for LLM consumption
360
- */
361
- formatIncomingMessage(message) {
362
- const priorityTag = message.priority === "high" ? " priority=\"high\"" : "";
363
- const reasonAttr = message.priority === "high" ? ` reason="${message.priorityReason}"` : "";
364
- const activityAttr = message.linkedActivityId ? ` activity_id="${message.linkedActivityId}"` : "";
365
- return `<incoming discussion="${message.discussionId}"${activityAttr} from="${message.senderName}" user_id="${message.senderId}" timestamp="${new Date(message.timestamp).toISOString()}"${priorityTag}${reasonAttr}>
366
- ${message.content}
367
- </incoming>`;
368
- }
369
- }
370
- exports.MessageFormatterService = MessageFormatterService;
371
- //# sourceMappingURL=message-formatter.js.map
@@ -1,106 +0,0 @@
1
- /**
2
- * Session Logger Service
3
- *
4
- * Manages per-activity session tracking and logging to Hailer workflows:
5
- * - Tracks metrics (tokens, tool calls, messages)
6
- * - Logs completed sessions to SESSION_LOG workflow
7
- * - Manages idle session detection and flushing
8
- */
9
- import Anthropic from "@anthropic-ai/sdk";
10
- import { Logger } from "../../../lib/logger";
11
- import { ActivitySession, McpToolCallback } from "../../shared/types";
12
- import { WorkspaceSchemaCacheService } from "./workspace-schema-cache";
13
- /** Memory entry loaded from SESSION_LOG */
14
- export interface MemoryEntry {
15
- sessionId: string;
16
- timestamp: number;
17
- summary: string;
18
- linkedActivityId?: string;
19
- }
20
- export declare class SessionLoggerService {
21
- private agentDirectoryId;
22
- private logger;
23
- private callMcpTool;
24
- private getDefaultTeamId;
25
- private activitySessions;
26
- private lastGlobalLogId;
27
- private idleCheckTimer;
28
- private anthropicClient;
29
- private schemaCache;
30
- private _currentWorkspaceId;
31
- constructor(agentDirectoryId: string | null, logger: Logger, callMcpTool: McpToolCallback, getDefaultTeamId: () => string | undefined);
32
- /**
33
- * Set the workspace schema cache for dynamic ID lookup
34
- */
35
- setSchemaCache(cache: WorkspaceSchemaCacheService, workspaceId: string): void;
36
- /**
37
- * Get Session Log schema from cache for a specific workspace
38
- */
39
- private getSessionLogSchema;
40
- /**
41
- * Set Anthropic client for generating summaries
42
- */
43
- setAnthropicClient(client: Anthropic): void;
44
- /**
45
- * Get or create an activity session for tracking
46
- * Multi-tenant: workspaceId is required for proper schema lookup
47
- */
48
- getOrCreateActivitySession(message: {
49
- linkedActivityId?: string;
50
- linkedActivityName?: string;
51
- discussionId: string;
52
- workspaceId: string;
53
- }): ActivitySession;
54
- /**
55
- * Get session by key
56
- */
57
- getSession(key: string): ActivitySession | undefined;
58
- /**
59
- * Get all active sessions
60
- */
61
- getActiveSessions(): Map<string, ActivitySession>;
62
- /**
63
- * Check for idle sessions and flush them
64
- * Called periodically by timer
65
- */
66
- checkAndFlushIdleSessions(): Promise<void>;
67
- /**
68
- * Flush a single activity session to the session log
69
- */
70
- flushActivitySession(_key: string, session: ActivitySession): Promise<void>;
71
- /**
72
- * Flush all active sessions (called on shutdown)
73
- */
74
- flushAllSessions(): Promise<void>;
75
- /**
76
- * Build summary for an activity session
77
- * Now includes conversation summary for memory recall
78
- */
79
- private buildActivitySessionSummary;
80
- /**
81
- * Start periodic idle session checking
82
- */
83
- startIdleCheckTimer(intervalMs?: number): void;
84
- /**
85
- * Stop idle check timer
86
- */
87
- stopIdleCheckTimer(): void;
88
- /**
89
- * Generate a conversation summary using LLM
90
- * Creates a condensed memory of what was discussed
91
- */
92
- private generateConversationSummary;
93
- /**
94
- * Load memory entries for an activity from SESSION_LOG
95
- * Returns past conversation summaries for context injection
96
- *
97
- * NOTE: ActivityLink fields store objects {_id, name}, so we fetch recent
98
- * session logs and filter client-side by checking the nested _id.
99
- */
100
- loadMemoryForActivity(activityId: string, workspaceId: string, limit?: number): Promise<MemoryEntry[]>;
101
- /**
102
- * Format memory entries for injection into conversation context
103
- */
104
- formatMemoryForContext(entries: MemoryEntry[]): string;
105
- }
106
- //# sourceMappingURL=session-logger.d.ts.map