@hailer/mcp 0.0.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 (163) hide show
  1. package/.claude/commands/tool-builder.md +37 -0
  2. package/.claude/commands/ws-pull.md +44 -0
  3. package/.claude/settings.json +8 -0
  4. package/.claude/settings.local.json +49 -0
  5. package/.claude/skills/activity-api/SKILL.md +96 -0
  6. package/.claude/skills/activity-api/references/activity-endpoints.md +845 -0
  7. package/.claude/skills/add-app-member-skill/SKILL.md +977 -0
  8. package/.claude/skills/agent-building/SKILL.md +243 -0
  9. package/.claude/skills/agent-building/references/architecture-patterns.md +446 -0
  10. package/.claude/skills/agent-building/references/code-examples.md +587 -0
  11. package/.claude/skills/agent-building/references/implementation-guide.md +619 -0
  12. package/.claude/skills/app-api/SKILL.md +219 -0
  13. package/.claude/skills/app-api/references/app-endpoints.md +759 -0
  14. package/.claude/skills/building-hailer-apps-skill/SKILL.md +548 -0
  15. package/.claude/skills/create-app-skill/SKILL.md +1101 -0
  16. package/.claude/skills/create-insight-skill/SKILL.md +1317 -0
  17. package/.claude/skills/get-insight-data-skill/SKILL.md +1053 -0
  18. package/.claude/skills/hailer-api/SKILL.md +283 -0
  19. package/.claude/skills/hailer-api/references/activities.md +620 -0
  20. package/.claude/skills/hailer-api/references/authentication.md +216 -0
  21. package/.claude/skills/hailer-api/references/datasets.md +437 -0
  22. package/.claude/skills/hailer-api/references/files.md +301 -0
  23. package/.claude/skills/hailer-api/references/insights.md +469 -0
  24. package/.claude/skills/hailer-api/references/workflows.md +720 -0
  25. package/.claude/skills/hailer-api/references/workspaces-users.md +445 -0
  26. package/.claude/skills/insight-api/SKILL.md +185 -0
  27. package/.claude/skills/insight-api/references/insight-endpoints.md +514 -0
  28. package/.claude/skills/install-workflow-skill/SKILL.md +1056 -0
  29. package/.claude/skills/list-apps-skill/SKILL.md +1010 -0
  30. package/.claude/skills/list-workflows-minimal-skill/SKILL.md +992 -0
  31. package/.claude/skills/local-first-skill/SKILL.md +570 -0
  32. package/.claude/skills/mcp-tools/SKILL.md +419 -0
  33. package/.claude/skills/mcp-tools/references/api-endpoints.md +499 -0
  34. package/.claude/skills/mcp-tools/references/data-structures.md +554 -0
  35. package/.claude/skills/mcp-tools/references/implementation-patterns.md +717 -0
  36. package/.claude/skills/preview-insight-skill/SKILL.md +1290 -0
  37. package/.claude/skills/publish-hailer-app-skill/SKILL.md +453 -0
  38. package/.claude/skills/remove-app-member-skill/SKILL.md +671 -0
  39. package/.claude/skills/remove-app-skill/SKILL.md +985 -0
  40. package/.claude/skills/remove-insight-skill/SKILL.md +1011 -0
  41. package/.claude/skills/remove-workflow-skill/SKILL.md +920 -0
  42. package/.claude/skills/scaffold-hailer-app-skill/SKILL.md +1034 -0
  43. package/.claude/skills/skill-testing/README.md +137 -0
  44. package/.claude/skills/skill-testing/SKILL.md +348 -0
  45. package/.claude/skills/skill-testing/references/test-patterns.md +705 -0
  46. package/.claude/skills/skill-testing/references/testing-guide.md +603 -0
  47. package/.claude/skills/skill-testing/references/validation-checklist.md +537 -0
  48. package/.claude/skills/tool-builder/SKILL.md +328 -0
  49. package/.claude/skills/update-app-skill/SKILL.md +970 -0
  50. package/.claude/skills/update-workflow-field-skill/SKILL.md +1098 -0
  51. package/.env.example +81 -0
  52. package/.mcp.json +13 -0
  53. package/README.md +297 -0
  54. package/dist/app.d.ts +4 -0
  55. package/dist/app.js +74 -0
  56. package/dist/cli.d.ts +3 -0
  57. package/dist/cli.js +5 -0
  58. package/dist/client/adaptive-documentation-bot.d.ts +108 -0
  59. package/dist/client/adaptive-documentation-bot.js +475 -0
  60. package/dist/client/adaptive-documentation-types.d.ts +66 -0
  61. package/dist/client/adaptive-documentation-types.js +9 -0
  62. package/dist/client/agent-activity-bot.d.ts +51 -0
  63. package/dist/client/agent-activity-bot.js +166 -0
  64. package/dist/client/agent-tracker.d.ts +499 -0
  65. package/dist/client/agent-tracker.js +659 -0
  66. package/dist/client/description-updater.d.ts +56 -0
  67. package/dist/client/description-updater.js +259 -0
  68. package/dist/client/log-parser.d.ts +72 -0
  69. package/dist/client/log-parser.js +387 -0
  70. package/dist/client/mcp-client.d.ts +50 -0
  71. package/dist/client/mcp-client.js +532 -0
  72. package/dist/client/message-processor.d.ts +35 -0
  73. package/dist/client/message-processor.js +352 -0
  74. package/dist/client/multi-bot-manager.d.ts +24 -0
  75. package/dist/client/multi-bot-manager.js +74 -0
  76. package/dist/client/providers/anthropic-provider.d.ts +19 -0
  77. package/dist/client/providers/anthropic-provider.js +631 -0
  78. package/dist/client/providers/llm-provider.d.ts +47 -0
  79. package/dist/client/providers/llm-provider.js +367 -0
  80. package/dist/client/providers/openai-provider.d.ts +23 -0
  81. package/dist/client/providers/openai-provider.js +621 -0
  82. package/dist/client/simple-llm-caller.d.ts +19 -0
  83. package/dist/client/simple-llm-caller.js +100 -0
  84. package/dist/client/skill-generator.d.ts +81 -0
  85. package/dist/client/skill-generator.js +386 -0
  86. package/dist/client/test-adaptive-bot.d.ts +9 -0
  87. package/dist/client/test-adaptive-bot.js +82 -0
  88. package/dist/client/token-pricing.d.ts +38 -0
  89. package/dist/client/token-pricing.js +127 -0
  90. package/dist/client/token-tracker.d.ts +232 -0
  91. package/dist/client/token-tracker.js +457 -0
  92. package/dist/client/token-usage-bot.d.ts +53 -0
  93. package/dist/client/token-usage-bot.js +153 -0
  94. package/dist/client/tool-executor.d.ts +69 -0
  95. package/dist/client/tool-executor.js +159 -0
  96. package/dist/client/tool-schema-loader.d.ts +60 -0
  97. package/dist/client/tool-schema-loader.js +178 -0
  98. package/dist/client/types.d.ts +69 -0
  99. package/dist/client/types.js +7 -0
  100. package/dist/config.d.ts +162 -0
  101. package/dist/config.js +296 -0
  102. package/dist/core.d.ts +26 -0
  103. package/dist/core.js +147 -0
  104. package/dist/lib/context-manager.d.ts +111 -0
  105. package/dist/lib/context-manager.js +431 -0
  106. package/dist/lib/logger.d.ts +74 -0
  107. package/dist/lib/logger.js +277 -0
  108. package/dist/lib/materialize.d.ts +3 -0
  109. package/dist/lib/materialize.js +101 -0
  110. package/dist/lib/normalizedName.d.ts +7 -0
  111. package/dist/lib/normalizedName.js +48 -0
  112. package/dist/lib/prompt-length-manager.d.ts +81 -0
  113. package/dist/lib/prompt-length-manager.js +457 -0
  114. package/dist/lib/terminal-prompt.d.ts +9 -0
  115. package/dist/lib/terminal-prompt.js +108 -0
  116. package/dist/mcp/UserContextCache.d.ts +56 -0
  117. package/dist/mcp/UserContextCache.js +163 -0
  118. package/dist/mcp/auth.d.ts +2 -0
  119. package/dist/mcp/auth.js +29 -0
  120. package/dist/mcp/hailer-clients.d.ts +42 -0
  121. package/dist/mcp/hailer-clients.js +246 -0
  122. package/dist/mcp/signal-handler.d.ts +45 -0
  123. package/dist/mcp/signal-handler.js +317 -0
  124. package/dist/mcp/tool-registry.d.ts +100 -0
  125. package/dist/mcp/tool-registry.js +306 -0
  126. package/dist/mcp/tools/activity.d.ts +15 -0
  127. package/dist/mcp/tools/activity.js +955 -0
  128. package/dist/mcp/tools/app.d.ts +20 -0
  129. package/dist/mcp/tools/app.js +1488 -0
  130. package/dist/mcp/tools/discussion.d.ts +19 -0
  131. package/dist/mcp/tools/discussion.js +950 -0
  132. package/dist/mcp/tools/file.d.ts +15 -0
  133. package/dist/mcp/tools/file.js +119 -0
  134. package/dist/mcp/tools/insight.d.ts +17 -0
  135. package/dist/mcp/tools/insight.js +806 -0
  136. package/dist/mcp/tools/skill.d.ts +10 -0
  137. package/dist/mcp/tools/skill.js +279 -0
  138. package/dist/mcp/tools/user.d.ts +10 -0
  139. package/dist/mcp/tools/user.js +108 -0
  140. package/dist/mcp/tools/workflow-template.d.ts +19 -0
  141. package/dist/mcp/tools/workflow-template.js +822 -0
  142. package/dist/mcp/tools/workflow.d.ts +18 -0
  143. package/dist/mcp/tools/workflow.js +1362 -0
  144. package/dist/mcp/utils/api-errors.d.ts +45 -0
  145. package/dist/mcp/utils/api-errors.js +160 -0
  146. package/dist/mcp/utils/data-transformers.d.ts +102 -0
  147. package/dist/mcp/utils/data-transformers.js +194 -0
  148. package/dist/mcp/utils/file-upload.d.ts +33 -0
  149. package/dist/mcp/utils/file-upload.js +148 -0
  150. package/dist/mcp/utils/hailer-api-client.d.ts +120 -0
  151. package/dist/mcp/utils/hailer-api-client.js +323 -0
  152. package/dist/mcp/utils/index.d.ts +13 -0
  153. package/dist/mcp/utils/index.js +39 -0
  154. package/dist/mcp/utils/logger.d.ts +42 -0
  155. package/dist/mcp/utils/logger.js +103 -0
  156. package/dist/mcp/utils/types.d.ts +286 -0
  157. package/dist/mcp/utils/types.js +7 -0
  158. package/dist/mcp/workspace-cache.d.ts +42 -0
  159. package/dist/mcp/workspace-cache.js +97 -0
  160. package/dist/mcp-server.d.ts +42 -0
  161. package/dist/mcp-server.js +280 -0
  162. package/package.json +56 -0
  163. package/tsconfig.json +23 -0
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ /**
3
+ * Unified Logger for Hailer MCP Server
4
+ * Based on backend logger pattern
5
+ * - Production: OpenTelemetry to Victoria Logs
6
+ * - Development: Console output only
7
+ * - Proper dependency injection pattern
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.Logger = exports.LogTag = exports.LogLevel = void 0;
11
+ exports.createLogger = createLogger;
12
+ exports.getDefaultLogger = getDefaultLogger;
13
+ // Import OpenTelemetry modules the same way as backend
14
+ const sdk_logs_1 = require("@opentelemetry/sdk-logs");
15
+ const exporter_logs_otlp_proto_1 = require("@opentelemetry/exporter-logs-otlp-proto");
16
+ const api_logs_1 = require("@opentelemetry/api-logs");
17
+ const resources_1 = require("@opentelemetry/resources");
18
+ var LogLevel;
19
+ (function (LogLevel) {
20
+ LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
21
+ LogLevel[LogLevel["INFO"] = 1] = "INFO";
22
+ LogLevel[LogLevel["WARN"] = 2] = "WARN";
23
+ LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
24
+ })(LogLevel || (exports.LogLevel = LogLevel = {}));
25
+ // Log tags for categorization
26
+ var LogTag;
27
+ (function (LogTag) {
28
+ LogTag["SYSTEM"] = "system";
29
+ LogTag["API_CALL"] = "api_call";
30
+ LogTag["TOOL_CALL"] = "tool_call";
31
+ LogTag["MCP_ACTIVITY"] = "mcp_activity";
32
+ LogTag["AUTH"] = "auth";
33
+ LogTag["WEBSOCKET"] = "websocket";
34
+ LogTag["ERROR"] = "error";
35
+ })(LogTag || (exports.LogTag = LogTag = {}));
36
+ /** Helper function to flatten objects for OTLP (from backend) */
37
+ const flatten = (obj, prefix = '') => {
38
+ return Object.keys(obj).reduce((acc, k) => {
39
+ const pre = prefix.length ? prefix + '.' : '';
40
+ if (typeof obj[k] === 'object' && obj[k] !== null && !Array.isArray(obj[k])) {
41
+ Object.assign(acc, flatten(obj[k], pre + k));
42
+ }
43
+ else if (Array.isArray(obj[k])) {
44
+ acc[pre + k] = JSON.stringify(obj[k]);
45
+ }
46
+ else {
47
+ acc[pre + k] = obj[k];
48
+ }
49
+ return acc;
50
+ }, {});
51
+ };
52
+ class Logger {
53
+ otelLogger;
54
+ level = LogLevel.DEBUG;
55
+ context = {};
56
+ isProduction;
57
+ constructor(context = {}, level = LogLevel.DEBUG) {
58
+ this.context = context;
59
+ this.level = level;
60
+ this.isProduction = process.env.NODE_ENV === 'production';
61
+ if (this.isProduction) {
62
+ this.initializeOtelLogger();
63
+ }
64
+ // Development mode: console logging only (no JSON files)
65
+ }
66
+ initializeOtelLogger() {
67
+ try {
68
+ const logExporter = new exporter_logs_otlp_proto_1.OTLPLogExporter({
69
+ url: process.env.LOG_URL || 'https://logs.hailer.local.gd/insert/opentelemetry/v1/logs',
70
+ concurrencyLimit: 1,
71
+ keepAlive: true,
72
+ // Ignore certificate when in DEVLOCAL mode
73
+ ...process.env.DEVLOCAL ? {
74
+ httpAgentOptions: {
75
+ rejectUnauthorized: false,
76
+ },
77
+ } : {},
78
+ });
79
+ const loggerProvider = new sdk_logs_1.LoggerProvider({
80
+ resource: new resources_1.Resource({ 'service.name': 'hailer-mcp-server' })
81
+ });
82
+ loggerProvider.addLogRecordProcessor(new sdk_logs_1.BatchLogRecordProcessor(logExporter));
83
+ this.otelLogger = loggerProvider.getLogger('hailer-mcp', '1.0.0');
84
+ }
85
+ catch (error) {
86
+ console.error('❌ Failed to initialize OTLP logger:', error);
87
+ // Fallback to console logging only
88
+ }
89
+ }
90
+ shouldLog(level) {
91
+ return level >= this.level;
92
+ }
93
+ generateRequestId() {
94
+ return `req-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
95
+ }
96
+ logToOtel(level, message, tag, context) {
97
+ if (!this.otelLogger)
98
+ return;
99
+ const fullContext = { ...this.context, ...context };
100
+ const severityMap = {
101
+ [LogLevel.DEBUG]: api_logs_1.SeverityNumber.DEBUG,
102
+ [LogLevel.INFO]: api_logs_1.SeverityNumber.INFO,
103
+ [LogLevel.WARN]: api_logs_1.SeverityNumber.WARN,
104
+ [LogLevel.ERROR]: api_logs_1.SeverityNumber.ERROR,
105
+ };
106
+ this.otelLogger.emit({
107
+ severityNumber: severityMap[level],
108
+ severityText: LogLevel[level].toLowerCase(),
109
+ body: message,
110
+ attributes: flatten({
111
+ 'log.tag': tag,
112
+ 'log.component': this.context.component || 'mcp-server',
113
+ ...fullContext
114
+ }),
115
+ });
116
+ }
117
+ log(level, message, tag = LogTag.SYSTEM, context = {}) {
118
+ if (!this.shouldLog(level))
119
+ return;
120
+ const fullContext = { ...this.context, ...context };
121
+ // Always log to console for immediate feedback
122
+ const emoji = this.getEmoji(level);
123
+ const levelName = LogLevel[level];
124
+ const contextStr = Object.keys(fullContext).length > 0
125
+ ? ` [${Object.entries(fullContext)
126
+ .filter(([_, value]) => value !== undefined && value !== null)
127
+ .map(([key, value]) => `${key}=${value}`)
128
+ .join(', ')}]`
129
+ : '';
130
+ const consoleMessage = `${emoji} ${levelName}: [${tag}] ${message}${contextStr}`;
131
+ if (level === LogLevel.ERROR) {
132
+ console.error(consoleMessage);
133
+ }
134
+ else if (level === LogLevel.WARN) {
135
+ console.warn(consoleMessage);
136
+ }
137
+ else {
138
+ console.log(consoleMessage);
139
+ }
140
+ // Log to OTLP in production (console only in development)
141
+ if (this.isProduction && this.otelLogger) {
142
+ this.logToOtel(level, message, tag, fullContext);
143
+ }
144
+ }
145
+ getEmoji(level) {
146
+ switch (level) {
147
+ case LogLevel.DEBUG: return '🔍';
148
+ case LogLevel.INFO: return '📡';
149
+ case LogLevel.WARN: return '⚠️';
150
+ case LogLevel.ERROR: return '❌';
151
+ default: return '📝';
152
+ }
153
+ }
154
+ // Core logging methods
155
+ debug(message, context, tag = LogTag.SYSTEM) {
156
+ this.log(LogLevel.DEBUG, message, tag, context);
157
+ }
158
+ info(message, context, tag = LogTag.SYSTEM) {
159
+ this.log(LogLevel.INFO, message, tag, context);
160
+ }
161
+ warn(message, context, tag = LogTag.SYSTEM) {
162
+ this.log(LogLevel.WARN, message, tag, context);
163
+ }
164
+ error(message, error, context, tag = LogTag.ERROR) {
165
+ let fullMessage = message;
166
+ let fullContext = { ...context };
167
+ if (error instanceof Error) {
168
+ fullMessage = `${message}: ${error.message}`;
169
+ fullContext.errorStack = error.stack;
170
+ fullContext.errorName = error.name;
171
+ }
172
+ else if (error) {
173
+ // Better error object handling - stringify objects properly
174
+ let errorString;
175
+ let errorData;
176
+ if (typeof error === 'object' && error !== null) {
177
+ try {
178
+ errorString = JSON.stringify(error, null, 2);
179
+ errorData = error; // Keep raw object for structured logging
180
+ }
181
+ catch {
182
+ errorString = String(error);
183
+ errorData = String(error);
184
+ }
185
+ }
186
+ else {
187
+ errorString = String(error);
188
+ errorData = errorString;
189
+ }
190
+ fullMessage = `${message}: ${errorString}`;
191
+ fullContext.errorData = errorData;
192
+ }
193
+ this.log(LogLevel.ERROR, fullMessage, tag, fullContext);
194
+ }
195
+ // Convenience methods for common operations
196
+ apiCall(operation, endpoint, params, context) {
197
+ this.debug(`API call: ${operation}`, {
198
+ operation,
199
+ endpoint,
200
+ params: params ? JSON.stringify(params) : undefined,
201
+ ...context
202
+ }, LogTag.API_CALL);
203
+ }
204
+ apiSuccess(operation, endpoint, duration, context) {
205
+ this.info(`API success: ${operation}`, {
206
+ operation,
207
+ endpoint,
208
+ duration,
209
+ ...context
210
+ }, LogTag.API_CALL);
211
+ }
212
+ apiError(operation, endpoint, error, duration, context) {
213
+ this.error(`API error: ${operation}`, error, {
214
+ operation,
215
+ endpoint,
216
+ duration,
217
+ ...context
218
+ }, LogTag.API_CALL);
219
+ }
220
+ toolCall(toolName, provider, args, context) {
221
+ this.debug(`Tool call: ${toolName}`, {
222
+ toolName,
223
+ provider,
224
+ arguments: args ? JSON.stringify(args) : undefined,
225
+ ...context
226
+ }, LogTag.TOOL_CALL);
227
+ }
228
+ toolSuccess(toolName, provider, duration, context) {
229
+ this.info(`Tool success: ${toolName}`, {
230
+ toolName,
231
+ provider,
232
+ duration,
233
+ ...context
234
+ }, LogTag.TOOL_CALL);
235
+ }
236
+ toolError(toolName, provider, error, duration, context) {
237
+ this.error(`Tool error: ${toolName}`, error, {
238
+ toolName,
239
+ provider,
240
+ duration,
241
+ ...context
242
+ }, LogTag.TOOL_CALL);
243
+ }
244
+ mcpActivity(activity, context) {
245
+ this.info(`MCP Activity: ${activity}`, context, LogTag.MCP_ACTIVITY);
246
+ }
247
+ socketFallback(operation, reason, context) {
248
+ this.warn(`Socket fallback: ${operation} - ${reason}`, { operation, ...context }, LogTag.WEBSOCKET);
249
+ }
250
+ auth(message, context) {
251
+ this.info(`Auth: ${message}`, context, LogTag.AUTH);
252
+ }
253
+ authError(message, error, context) {
254
+ this.error(`Auth error: ${message}`, error, context, LogTag.AUTH);
255
+ }
256
+ // Create child logger with additional context
257
+ child(additionalContext) {
258
+ return new Logger({ ...this.context, ...additionalContext }, this.level);
259
+ }
260
+ // Set log level
261
+ setLevel(level) {
262
+ this.level = level;
263
+ }
264
+ }
265
+ exports.Logger = Logger;
266
+ /**
267
+ * Logger factory function - replaces the old singleton pattern
268
+ * Use this to create loggers with specific context
269
+ */
270
+ function createLogger(context = {}) {
271
+ return new Logger(context);
272
+ }
273
+ // Default logger for backward compatibility (but prefer createLogger)
274
+ function getDefaultLogger() {
275
+ return new Logger({ component: 'default' });
276
+ }
277
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,3 @@
1
+ import { HailerV2CoreInitResponse } from "../mcp/utils";
2
+ export declare const materialize: (hailerResponse: any, init: HailerV2CoreInitResponse, authToken: string) => Promise<unknown>;
3
+ //# sourceMappingURL=materialize.d.ts.map
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.materialize = void 0;
4
+ const getMaterializedProcess = (init, value) => {
5
+ const process = init.processes.find((process) => process._id === value);
6
+ if (!process)
7
+ return value;
8
+ return {
9
+ _id: process?._id,
10
+ name: process.name,
11
+ phases: process?.phasesOrder
12
+ .filter((phaseId) => !process.phasesRemoved.includes(phaseId))
13
+ .map((phaseId) => {
14
+ const phase = process.phases[phaseId];
15
+ return {
16
+ _id: process._id,
17
+ name: phase.name,
18
+ ...(phase.description ? { description: phase.description } : {}),
19
+ };
20
+ }),
21
+ };
22
+ };
23
+ const getMaterializedCurrentPhase = (init, value) => {
24
+ const phase = init.processes
25
+ .flatMap((process) => Object.values(process.phases))
26
+ .find((phase) => phase._id === value);
27
+ if (!phase)
28
+ return value;
29
+ return {
30
+ _id: phase._id,
31
+ name: phase.name,
32
+ ...(phase.description ? { description: phase.description } : {}),
33
+ };
34
+ };
35
+ const getMaterializedUID = (init, value) => {
36
+ const user = init.users[value];
37
+ if (!user)
38
+ return value;
39
+ return {
40
+ _id: user._id,
41
+ name: `${user.firstname} ${user.lastname}`,
42
+ };
43
+ };
44
+ const getMaterializedTime = (epoch) => ({
45
+ epoch,
46
+ humanReadable: new Intl.DateTimeFormat("en-GB", {
47
+ day: "numeric",
48
+ month: "short",
49
+ year: "numeric",
50
+ hour: "2-digit",
51
+ minute: "2-digit",
52
+ second: "2-digit",
53
+ hour12: false,
54
+ }).format(new Date(epoch)),
55
+ });
56
+ const getMaterializedValue = (key, value, init) => {
57
+ if (key === "process" && typeof value === "string") {
58
+ return getMaterializedProcess(init, value);
59
+ }
60
+ if (key === "currentPhase" && typeof value === "string") {
61
+ return getMaterializedCurrentPhase(init, value);
62
+ }
63
+ if (key === "uid" && typeof value === "string") {
64
+ return getMaterializedUID(init, value);
65
+ }
66
+ if ((key === "created" || key === "updated") && typeof value === "number") {
67
+ return getMaterializedTime(value);
68
+ }
69
+ return value;
70
+ };
71
+ const mergeResponseWithDependencies = (rootNode, init) => {
72
+ const traverse = (node) => {
73
+ if (Array.isArray(node)) {
74
+ return node.map(traverse);
75
+ }
76
+ if (node !== null && typeof node === "object") {
77
+ return Object.entries(node).reduce((acc, [key, value]) => {
78
+ const traversedValue = traverse(value);
79
+ if ((typeof value === "string" && value.trim() === "") ||
80
+ (Array.isArray(value) && value.length === 0)) {
81
+ return acc;
82
+ }
83
+ return {
84
+ ...acc,
85
+ [key]: getMaterializedValue(key, traversedValue, init),
86
+ };
87
+ }, {});
88
+ }
89
+ return node;
90
+ };
91
+ return traverse(rootNode);
92
+ };
93
+ const materialize = async (hailerResponse, init, authToken) => {
94
+ // TODO:
95
+ // const { activityIds } = findDependencies();
96
+ // const { activities } = loadDependencies(authToken);
97
+ const hailerResponseWithDependencies = mergeResponseWithDependencies(hailerResponse, init);
98
+ return hailerResponseWithDependencies;
99
+ };
100
+ exports.materialize = materialize;
101
+ //# sourceMappingURL=materialize.js.map
@@ -0,0 +1,7 @@
1
+ export declare const getNormalizedName: (name: string) => string;
2
+ export declare const getNormalizedNames: (names: string[]) => string[];
3
+ export declare const getIdByNormalizedName: (name: string | undefined, options: {
4
+ name: string;
5
+ _id: string;
6
+ }[]) => string | undefined;
7
+ //# sourceMappingURL=normalizedName.d.ts.map
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getIdByNormalizedName = exports.getNormalizedNames = exports.getNormalizedName = void 0;
4
+ const logger_1 = require("./logger");
5
+ const logger = (0, logger_1.createLogger)({ component: 'normalizedName' });
6
+ const getNormalizedName = (name) => {
7
+ if (!name || typeof name !== "string") {
8
+ logger.warn("getNormalizedName called with invalid name", { name });
9
+ return "";
10
+ }
11
+ return name
12
+ .toLowerCase()
13
+ .normalize("NFKD")
14
+ .replace(/[\u0300-\u036f]/g, "")
15
+ .replace(/[^a-z0-9]+/g, "_")
16
+ .replace(/^_+|_+$/g, "");
17
+ };
18
+ exports.getNormalizedName = getNormalizedName;
19
+ const getNormalizedNames = (names) => names
20
+ .filter((name) => name && typeof name === "string")
21
+ .reduce((normalizedNames, name) => {
22
+ const normalizedName = (0, exports.getNormalizedName)(name);
23
+ if (normalizedNames.includes(normalizedName)) {
24
+ logger.error("Duplicate normalized name detected", { normalizedName, originalName: name });
25
+ return normalizedNames;
26
+ }
27
+ return [...normalizedNames, normalizedName];
28
+ }, []);
29
+ exports.getNormalizedNames = getNormalizedNames;
30
+ const getIdByNormalizedName = (name, options) => {
31
+ if (!name) {
32
+ logger.warn("getIdByNormalizedName called with invalid name", { name });
33
+ return undefined;
34
+ }
35
+ const idByNormalizedName = options.reduce((acc, { name: optionName, _id }) => {
36
+ const normalizedName = (0, exports.getNormalizedName)(optionName);
37
+ if (acc[normalizedName]) {
38
+ logger.error("Duplicate normalized name in options", { normalizedName, optionName, _id });
39
+ return acc;
40
+ }
41
+ return { ...acc, [normalizedName]: _id };
42
+ }, {});
43
+ const normalizedInputName = (0, exports.getNormalizedName)(name);
44
+ const id = idByNormalizedName[normalizedInputName];
45
+ return id;
46
+ };
47
+ exports.getIdByNormalizedName = getIdByNormalizedName;
48
+ //# sourceMappingURL=normalizedName.js.map
@@ -0,0 +1,81 @@
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