@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,431 +0,0 @@
1
- "use strict";
2
- /**
3
- * Context Manager
4
- *
5
- * Handles token counting and automatic summarization to prevent "prompt too long" errors.
6
- * Uses character-based token estimation and provider-specific limits with safety margins.
7
- */
8
- var __importDefault = (this && this.__importDefault) || function (mod) {
9
- return (mod && mod.__esModule) ? mod : { "default": mod };
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.ContextManager = void 0;
13
- exports.getContextManager = getContextManager;
14
- const logger_1 = require("./logger");
15
- const sdk_1 = __importDefault(require("@anthropic-ai/sdk"));
16
- const openai_1 = __importDefault(require("openai"));
17
- // ================================================================================
18
- // CONTEXT MANAGER
19
- // ================================================================================
20
- class ContextManager {
21
- logger;
22
- config;
23
- // Provider limits (max context window)
24
- PROVIDER_LIMITS = {
25
- anthropic: 200_000, // Claude Sonnet 4
26
- openai: 128_000, // GPT-4o
27
- };
28
- constructor(config = {}) {
29
- this.config = {
30
- safetyMarginPercent: 25,
31
- enableAutoSummarization: true,
32
- maxSummarizationChunks: 10,
33
- ...config,
34
- };
35
- this.logger = (0, logger_1.createLogger)({ component: "ContextManager" });
36
- this.logger.info("ContextManager initialized", {
37
- safetyMargin: `${this.config.safetyMarginPercent}%`,
38
- autoSummarization: this.config.enableAutoSummarization,
39
- maxChunks: this.config.maxSummarizationChunks,
40
- });
41
- }
42
- // ================================================================================
43
- // TOKEN COUNTING
44
- // ================================================================================
45
- /**
46
- * Estimate tokens from text using character-based approximation
47
- * Formula: 1 token ≈ 4 characters
48
- */
49
- estimateTokens(text) {
50
- return Math.ceil(text.length / 4);
51
- }
52
- /**
53
- * Calculate token limits for a provider with safety margin
54
- */
55
- getTokenLimits(provider) {
56
- const maxTokens = this.PROVIDER_LIMITS[provider];
57
- const safetyMargin = this.config.safetyMarginPercent / 100;
58
- const safeTokens = Math.floor(maxTokens * (1 - safetyMargin));
59
- return { maxTokens, safeTokens, safetyMargin };
60
- }
61
- /**
62
- * Count tokens for system prompt
63
- */
64
- countSystemPromptTokens(systemPrompt) {
65
- if (typeof systemPrompt === 'string') {
66
- return this.estimateTokens(systemPrompt);
67
- }
68
- // Handle array or complex system prompt formats
69
- const text = JSON.stringify(systemPrompt);
70
- return this.estimateTokens(text);
71
- }
72
- /**
73
- * Count tokens for messages array
74
- */
75
- countMessagesTokens(messages) {
76
- let total = 0;
77
- for (const message of messages) {
78
- // Handle different message formats
79
- if (typeof message.content === 'string') {
80
- total += this.estimateTokens(message.content);
81
- }
82
- else if (Array.isArray(message.content)) {
83
- // Anthropic format with content blocks
84
- for (const block of message.content) {
85
- if (block.type === 'text' && block.text) {
86
- total += this.estimateTokens(block.text);
87
- }
88
- else if (block.type === 'tool_result' && block.content) {
89
- total += this.estimateTokens(typeof block.content === 'string' ? block.content : JSON.stringify(block.content));
90
- }
91
- else {
92
- // Other content types (tool_use, etc.)
93
- total += this.estimateTokens(JSON.stringify(block));
94
- }
95
- }
96
- }
97
- else if (message.content) {
98
- // Fallback: stringify the content
99
- total += this.estimateTokens(JSON.stringify(message.content));
100
- }
101
- // Add overhead for role and metadata (~10 tokens per message)
102
- total += 10;
103
- }
104
- return total;
105
- }
106
- /**
107
- * Count tokens for tools definitions
108
- */
109
- countToolsTokens(tools) {
110
- if (!tools || tools.length === 0) {
111
- return 0;
112
- }
113
- // Estimate tools definition size
114
- const toolsText = JSON.stringify(tools);
115
- return this.estimateTokens(toolsText);
116
- }
117
- /**
118
- * Count total tokens for a complete prompt
119
- */
120
- countTokens(systemPrompt, messages, tools, provider) {
121
- const limits = this.getTokenLimits(provider);
122
- const systemPromptTokens = this.countSystemPromptTokens(systemPrompt);
123
- const messagesTokens = this.countMessagesTokens(messages);
124
- const toolsTokens = this.countToolsTokens(tools);
125
- const totalTokens = systemPromptTokens + messagesTokens + toolsTokens;
126
- const exceedsLimit = totalTokens > limits.safeTokens;
127
- return {
128
- totalTokens,
129
- systemPromptTokens,
130
- messagesTokens,
131
- toolsTokens,
132
- exceedsLimit,
133
- provider,
134
- limit: limits,
135
- };
136
- }
137
- // ================================================================================
138
- // MESSAGE SPLITTING
139
- // ================================================================================
140
- /**
141
- * Split messages into logical groups based on tool call patterns
142
- * Groups together: assistant message with tool_use -> tool results
143
- */
144
- splitIntoToolResultGroups(messages, provider) {
145
- const groups = [];
146
- let currentGroup = [];
147
- let startIndex = 0;
148
- for (let i = 0; i < messages.length; i++) {
149
- const message = messages[i];
150
- currentGroup.push(message);
151
- // Check if this completes a tool call cycle
152
- const isToolResult = provider === 'anthropic'
153
- ? (Array.isArray(message.content) && message.content.some((c) => c.type === 'tool_result'))
154
- : message.role === 'tool';
155
- if (isToolResult) {
156
- // End current group
157
- const tokens = this.countMessagesTokens(currentGroup);
158
- groups.push({
159
- messages: [...currentGroup],
160
- tokens,
161
- startIndex,
162
- endIndex: i,
163
- });
164
- currentGroup = [];
165
- startIndex = i + 1;
166
- }
167
- }
168
- // Add any remaining messages as final group
169
- if (currentGroup.length > 0) {
170
- const tokens = this.countMessagesTokens(currentGroup);
171
- groups.push({
172
- messages: currentGroup,
173
- tokens,
174
- startIndex,
175
- endIndex: messages.length - 1,
176
- });
177
- }
178
- return groups;
179
- }
180
- /**
181
- * Split tool result groups into chunks that fit within safe limits
182
- */
183
- splitIntoChunks(groups, systemPromptTokens, userQueryTokens, provider) {
184
- const limits = this.getTokenLimits(provider);
185
- const baseTokens = systemPromptTokens + userQueryTokens + 1000; // +1000 for overhead and instructions
186
- const availableTokens = limits.safeTokens - baseTokens;
187
- const chunks = [];
188
- let currentChunk = [];
189
- let currentChunkTokens = 0;
190
- for (const group of groups) {
191
- if (currentChunkTokens + group.tokens > availableTokens && currentChunk.length > 0) {
192
- // Current chunk is full, start new chunk
193
- chunks.push([...currentChunk]);
194
- currentChunk = [group];
195
- currentChunkTokens = group.tokens;
196
- }
197
- else {
198
- // Add to current chunk
199
- currentChunk.push(group);
200
- currentChunkTokens += group.tokens;
201
- }
202
- }
203
- // Add final chunk
204
- if (currentChunk.length > 0) {
205
- chunks.push(currentChunk);
206
- }
207
- return chunks;
208
- }
209
- // ================================================================================
210
- // SUMMARIZATION
211
- // ================================================================================
212
- /**
213
- * Summarize a chunk of tool results using the LLM
214
- */
215
- async summarizeChunk(systemPrompt, userQuery, toolResultGroups, provider, chunkIndex, totalChunks) {
216
- // Flatten groups into messages
217
- const messages = toolResultGroups.flatMap(group => group.messages);
218
- const summarizationInstruction = `You are analyzing tool call results to condense them while preserving all relevant information.
219
-
220
- Context: This is chunk ${chunkIndex + 1} of ${totalChunks} being processed.
221
-
222
- Instructions:
223
- 1. Review the tool calls and their results below
224
- 2. Extract and preserve ALL relevant information, data, and insights
225
- 3. Remove redundant or unnecessary details
226
- 4. Maintain the logical flow and relationships between data
227
- 5. Keep important identifiers (IDs, names, dates, etc.)
228
- 6. Provide a concise summary that captures everything important
229
-
230
- Output your condensed analysis focusing on the key information needed to answer the user's question.`;
231
- try {
232
- if (provider === 'anthropic') {
233
- return await this.summarizeWithAnthropic(systemPrompt, userQuery, messages, summarizationInstruction);
234
- }
235
- else {
236
- return await this.summarizeWithOpenAI(systemPrompt, userQuery, messages, summarizationInstruction);
237
- }
238
- }
239
- catch (error) {
240
- this.logger.error("Failed to summarize chunk", error, {
241
- chunkIndex,
242
- totalChunks,
243
- provider,
244
- });
245
- // Fallback: return truncated messages
246
- const fallback = messages
247
- .map(m => JSON.stringify(m).substring(0, 1000))
248
- .join('\n')
249
- .substring(0, 10000);
250
- return `[Summarization failed, showing truncated results]\n${fallback}`;
251
- }
252
- }
253
- /**
254
- * Summarize using Anthropic
255
- */
256
- async summarizeWithAnthropic(systemPrompt, userQuery, messages, instruction) {
257
- if (!this.config.anthropicApiKey) {
258
- throw new Error("Anthropic API key not configured");
259
- }
260
- const client = new sdk_1.default({ apiKey: this.config.anthropicApiKey });
261
- // Build prompt for summarization
262
- const summarizationMessages = [
263
- {
264
- role: "user",
265
- content: userQuery,
266
- },
267
- ...messages,
268
- {
269
- role: "user",
270
- content: instruction,
271
- },
272
- ];
273
- const response = await client.messages.create({
274
- model: "claude-sonnet-4-20250514",
275
- max_tokens: 4000,
276
- temperature: 0.3, // Lower temperature for more focused summarization
277
- system: systemPrompt,
278
- messages: summarizationMessages,
279
- });
280
- const text = response.content
281
- .filter(content => content.type === "text")
282
- .map(content => content.text)
283
- .join("\n");
284
- return text;
285
- }
286
- /**
287
- * Summarize using OpenAI
288
- */
289
- async summarizeWithOpenAI(systemPrompt, userQuery, messages, instruction) {
290
- if (!this.config.openaiApiKey) {
291
- throw new Error("OpenAI API key not configured");
292
- }
293
- const client = new openai_1.default({ apiKey: this.config.openaiApiKey });
294
- // Build prompt for summarization
295
- const summarizationMessages = [
296
- { role: "system", content: systemPrompt },
297
- { role: "user", content: userQuery },
298
- ...messages,
299
- { role: "user", content: instruction },
300
- ];
301
- const response = await client.chat.completions.create({
302
- model: "gpt-4o",
303
- max_tokens: 4000,
304
- temperature: 0.3,
305
- messages: summarizationMessages,
306
- });
307
- return response.choices[0]?.message?.content || "[No summary generated]";
308
- }
309
- /**
310
- * Main summarization orchestration
311
- */
312
- async summarizeContext(systemPrompt, messages, provider, userQuery) {
313
- if (!this.config.enableAutoSummarization) {
314
- throw new Error("Auto-summarization is disabled");
315
- }
316
- const startTime = Date.now();
317
- this.logger.info("Starting context summarization", {
318
- provider,
319
- messageCount: messages.length,
320
- originalTokens: this.countMessagesTokens(messages),
321
- });
322
- // Extract user query from first user message if not provided
323
- if (!userQuery) {
324
- const firstUserMessage = messages.find(m => m.role === 'user');
325
- userQuery = firstUserMessage?.content || "Process the tool results";
326
- }
327
- const systemPromptTokens = this.countSystemPromptTokens(systemPrompt);
328
- const userQueryTokens = this.estimateTokens(userQuery || "");
329
- // Split messages into logical groups
330
- const groups = this.splitIntoToolResultGroups(messages, provider);
331
- this.logger.info("Split messages into tool result groups", {
332
- groupCount: groups.length,
333
- groups: groups.map(g => ({
334
- messageCount: g.messages.length,
335
- tokens: g.tokens,
336
- range: `${g.startIndex}-${g.endIndex}`,
337
- })),
338
- });
339
- // Split groups into chunks that fit within limits
340
- const chunks = this.splitIntoChunks(groups, systemPromptTokens, userQueryTokens, provider);
341
- if (chunks.length > this.config.maxSummarizationChunks) {
342
- this.logger.warn("Too many chunks required", {
343
- chunksNeeded: chunks.length,
344
- maxAllowed: this.config.maxSummarizationChunks,
345
- });
346
- throw new Error(`Context too large: requires ${chunks.length} chunks but max is ${this.config.maxSummarizationChunks}`);
347
- }
348
- this.logger.info("Split groups into chunks for summarization", {
349
- chunkCount: chunks.length,
350
- chunks: chunks.map((chunk, i) => ({
351
- index: i,
352
- groupCount: chunk.length,
353
- tokens: chunk.reduce((sum, g) => sum + g.tokens, 0),
354
- })),
355
- });
356
- // Summarize chunks in parallel
357
- const summarizationPromises = chunks.map((chunk, index) => this.summarizeChunk(systemPrompt, userQuery, chunk, provider, index, chunks.length));
358
- const summaries = await Promise.all(summarizationPromises);
359
- // Build summarized messages
360
- const summarizedMessages = summaries.map((summary, index) => {
361
- if (provider === 'anthropic') {
362
- return {
363
- role: "user",
364
- content: `[Summarized tool results ${index + 1}/${summaries.length}]\n${summary}`,
365
- };
366
- }
367
- else {
368
- return {
369
- role: "assistant",
370
- content: `[Summarized tool results ${index + 1}/${summaries.length}]\n${summary}`,
371
- };
372
- }
373
- });
374
- const originalTokens = this.countMessagesTokens(messages);
375
- const summarizedTokens = this.countMessagesTokens(summarizedMessages);
376
- const reductionPercent = Math.round(((originalTokens - summarizedTokens) / originalTokens) * 100);
377
- const duration = Date.now() - startTime;
378
- this.logger.info("Context summarization complete", {
379
- duration,
380
- chunksProcessed: chunks.length,
381
- originalTokens,
382
- summarizedTokens,
383
- reductionPercent: `${reductionPercent}%`,
384
- originalMessages: messages.length,
385
- summarizedMessages: summarizedMessages.length,
386
- });
387
- return {
388
- summarizedMessages,
389
- originalTokens,
390
- summarizedTokens,
391
- chunksProcessed: chunks.length,
392
- reductionPercent,
393
- };
394
- }
395
- // ================================================================================
396
- // HELPER METHODS
397
- // ================================================================================
398
- /**
399
- * Check if token count exceeds safe limit
400
- */
401
- exceedsLimit(tokenCount, provider) {
402
- const limits = this.getTokenLimits(provider);
403
- return tokenCount > limits.safeTokens;
404
- }
405
- /**
406
- * Get warning threshold (80% of safe limit)
407
- */
408
- approachingLimit(tokenCount, provider) {
409
- const limits = this.getTokenLimits(provider);
410
- return tokenCount > limits.safeTokens * 0.8;
411
- }
412
- /**
413
- * Get provider limits info
414
- */
415
- getProviderLimits(provider) {
416
- return this.getTokenLimits(provider);
417
- }
418
- }
419
- exports.ContextManager = ContextManager;
420
- // ================================================================================
421
- // EXPORTS
422
- // ================================================================================
423
- // Export singleton instance
424
- let contextManagerInstance = null;
425
- function getContextManager(config) {
426
- if (!contextManagerInstance) {
427
- contextManagerInstance = new ContextManager(config);
428
- }
429
- return contextManagerInstance;
430
- }
431
- //# sourceMappingURL=context-manager.js.map
@@ -1,81 +0,0 @@
1
- /**
2
- * Prompt Length Manager
3
- * Handles prompt length validation, truncation, and debugging
4
- */
5
- export interface PromptComponent {
6
- type: 'system' | 'user' | 'assistant' | 'tool_result' | 'tool_call';
7
- content: string;
8
- source?: string;
9
- originalLength?: number;
10
- truncated?: boolean;
11
- originalContent?: string;
12
- truncatedAt?: number;
13
- truncationReason?: string;
14
- }
15
- export interface PromptAnalysis {
16
- totalCharacters: number;
17
- estimatedTokens: number;
18
- components: PromptComponent[];
19
- truncationApplied: boolean;
20
- warnings: string[];
21
- }
22
- export interface TruncationConfig {
23
- maxTotalTokens: number;
24
- maxUserMessagesTokens: number;
25
- maxTotalCharacters: number;
26
- maxUserMessagesCharacters: number;
27
- anthropicContextWindow: number;
28
- openaiContextWindow: number;
29
- preserveSystemPrompt: boolean;
30
- preserveUserMessages: boolean;
31
- preserveAssistantResponses: boolean;
32
- truncateToolResponsesFirst: boolean;
33
- }
34
- export declare const DEFAULT_TRUNCATION_CONFIG: TruncationConfig;
35
- export declare class PromptLengthManager {
36
- private logger;
37
- private config;
38
- constructor(config?: Partial<TruncationConfig>);
39
- /**
40
- * Estimate token count from character count
41
- * Rough approximation: 1 token ≈ 4 characters for English text
42
- */
43
- private estimateTokens;
44
- /**
45
- * Count exact characters and estimate tokens for a text
46
- */
47
- private analyzeText;
48
- /**
49
- * Truncate text intelligently, preserving structure when possible
50
- */
51
- private truncateText;
52
- /**
53
- * Analyze prompt components and build analysis
54
- */
55
- analyzePrompt(components: PromptComponent[]): PromptAnalysis;
56
- /**
57
- * No longer truncate individual tool responses - only when total prompt exceeds limits
58
- * This method now just passes through content unchanged and logs for monitoring
59
- * TEMPORARILY DISABLED - Even monitoring/logging is disabled
60
- */
61
- truncateToolResponse(content: string, toolName: string): string;
62
- /**
63
- * Apply smart token-based truncation optimized for Claude 4
64
- * TEMPORARILY DISABLED - All truncation logic commented out for testing
65
- */
66
- truncatePrompt(analysis: PromptAnalysis): PromptAnalysis;
67
- /**
68
- * Check if a provider-specific error indicates prompt too long
69
- */
70
- isPromptTooLongError(error: Error, provider: 'anthropic' | 'openai'): boolean;
71
- /**
72
- * Log comprehensive debug information about prompt structure
73
- */
74
- logPromptDebugInfo(analysis: PromptAnalysis, provider: string, botId?: string): void;
75
- /**
76
- * Generate a quick truncation summary for debugging
77
- */
78
- generateTruncationSummary(analysis: PromptAnalysis): string;
79
- }
80
- export declare const promptLengthManager: PromptLengthManager;
81
- //# sourceMappingURL=prompt-length-manager.d.ts.map