@codebolt/agent 5.0.2 → 5.0.6

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 (160) hide show
  1. package/dist/agent.d.ts +86 -0
  2. package/dist/agent.js +324 -0
  3. package/dist/builderpattern/agent.js +2 -2
  4. package/dist/builderpattern/followupquestionbuilder.js +1 -1
  5. package/dist/builderpattern/llmoutputhandler.js +7 -7
  6. package/dist/builderpattern/usermessage.d.ts +1 -6
  7. package/dist/composablepattern/document.js +35 -2
  8. package/dist/followupquestionbuilder.d.ts +75 -0
  9. package/dist/followupquestionbuilder.js +197 -0
  10. package/dist/index.d.ts +14 -0
  11. package/dist/index.js +23 -0
  12. package/dist/llmoutputhandler.d.ts +102 -0
  13. package/dist/llmoutputhandler.js +452 -0
  14. package/dist/processor/types/interfaces.d.ts +21 -44
  15. package/dist/processor-pieces/index.d.ts +3 -0
  16. package/dist/processor-pieces/index.js +3 -0
  17. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +5 -14
  18. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +40 -41
  19. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +13 -5
  20. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +58 -50
  21. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +8 -6
  22. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +22 -66
  23. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +2 -3
  24. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +2 -1
  25. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +2 -3
  26. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +2 -1
  27. package/dist/processor-pieces/messageModifiers/toolInjectionModifier.js +4 -1
  28. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +2 -18
  29. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +93 -291
  30. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.d.ts +18 -0
  31. package/dist/processor-pieces/postToolCallProcessors/conversationCompactorModifier.js +41 -0
  32. package/dist/processor-pieces/postToolCallProcessors/index.d.ts +2 -1
  33. package/dist/processor-pieces/postToolCallProcessors/index.js +5 -0
  34. package/dist/processor-pieces/preInferenceProcessors/index.d.ts +1 -1
  35. package/dist/processor-pieces/preInferenceProcessors/index.js +3 -0
  36. package/dist/processor-pieces/pretoolCallProcessors/index.d.ts +2 -1
  37. package/dist/processor-pieces/pretoolCallProcessors/index.js +5 -0
  38. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.d.ts +21 -0
  39. package/dist/processor-pieces/pretoolCallProcessors/toolParameterModifier.js +32 -0
  40. package/dist/processor-pieces/pretoolCallProcessors/toolValidationModifier.d.ts +16 -0
  41. package/dist/processor-pieces/pretoolCallProcessors/toolValidationModifier.js +37 -0
  42. package/dist/promptbuilder.d.ts +382 -0
  43. package/dist/promptbuilder.js +805 -0
  44. package/dist/systemprompt.d.ts +20 -0
  45. package/dist/systemprompt.js +48 -0
  46. package/dist/taskInstruction.d.ts +37 -0
  47. package/dist/taskInstruction.js +57 -0
  48. package/dist/unified/agent/agent.js +2 -2
  49. package/dist/unified/agent/codeboltAgent.d.ts +122 -0
  50. package/dist/unified/agent/codeboltAgent.js +210 -0
  51. package/dist/unified/base/initialPromptGenerator.js +18 -4
  52. package/dist/unified/base/responseExecutor.d.ts +3 -2
  53. package/dist/unified/base/responseExecutor.js +100 -56
  54. package/dist/unified/index.d.ts +4 -0
  55. package/dist/unified/index.js +12 -1
  56. package/dist/usermessage.d.ts +70 -0
  57. package/dist/usermessage.js +123 -0
  58. package/package.json +5 -5
  59. package/dist/local-tools/fileTools.d.ts +0 -26
  60. package/dist/local-tools/fileTools.js +0 -162
  61. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +0 -13
  62. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +0 -68
  63. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +0 -15
  64. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +0 -212
  65. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +0 -19
  66. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +0 -110
  67. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +0 -23
  68. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +0 -173
  69. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +0 -14
  70. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +0 -93
  71. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +0 -30
  72. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +0 -330
  73. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +0 -26
  74. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +0 -269
  75. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +0 -38
  76. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +0 -217
  77. package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +0 -34
  78. package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +0 -147
  79. package/dist/processor-pieces/additionalModifiers/index.d.ts +0 -12
  80. package/dist/processor-pieces/additionalModifiers/index.js +0 -28
  81. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +0 -29
  82. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +0 -155
  83. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +0 -15
  84. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +0 -129
  85. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +0 -25
  86. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +0 -169
  87. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +0 -20
  88. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +0 -152
  89. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +0 -7
  90. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +0 -93
  91. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +0 -9
  92. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +0 -77
  93. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +0 -19
  94. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +0 -110
  95. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +0 -20
  96. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +0 -124
  97. package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +0 -41
  98. package/dist/processor-pieces/messageModifiers/environmentContext.js +0 -355
  99. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +0 -23
  100. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +0 -207
  101. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +0 -7
  102. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +0 -26
  103. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +0 -1
  104. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +0 -2
  105. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +0 -7
  106. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +0 -24
  107. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +0 -41
  108. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +0 -197
  109. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +0 -26
  110. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +0 -90
  111. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +0 -81
  112. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +0 -329
  113. package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +0 -40
  114. package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +0 -272
  115. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +0 -49
  116. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +0 -291
  117. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +0 -49
  118. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +0 -293
  119. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +0 -47
  120. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +0 -249
  121. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +0 -30
  122. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +0 -137
  123. package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +0 -30
  124. package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +0 -228
  125. package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +0 -99
  126. package/dist/processor-pieces/postToolCall/telemetryProcessor.js +0 -278
  127. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +0 -37
  128. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +0 -178
  129. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +0 -43
  130. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +0 -207
  131. package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +0 -52
  132. package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +0 -264
  133. package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +0 -49
  134. package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +0 -293
  135. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +0 -7
  136. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +0 -31
  137. package/dist/processor-pieces/preToolCall/index.d.ts +0 -9
  138. package/dist/processor-pieces/preToolCall/index.js +0 -18
  139. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +0 -58
  140. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +0 -444
  141. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +0 -44
  142. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +0 -367
  143. package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +0 -58
  144. package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +0 -391
  145. package/dist/unified/agent/tool.d.ts +0 -99
  146. package/dist/unified/agent/tool.js +0 -440
  147. package/dist/unified/examples/agentExample.d.ts +0 -46
  148. package/dist/unified/examples/agentExample.js +0 -464
  149. package/dist/unified/examples/documentationPatternExample.d.ts +0 -10
  150. package/dist/unified/examples/documentationPatternExample.js +0 -385
  151. package/dist/unified/examples/followUpProcessorsExample.d.ts +0 -45
  152. package/dist/unified/examples/followUpProcessorsExample.js +0 -311
  153. package/dist/unified/examples/orchestratorExample.d.ts +0 -16
  154. package/dist/unified/examples/orchestratorExample.js +0 -415
  155. package/dist/unified/examples/preToolCallProcessorsExample.d.ts +0 -36
  156. package/dist/unified/examples/preToolCallProcessorsExample.js +0 -458
  157. package/dist/unified/examples/workflowExample.d.ts +0 -12
  158. package/dist/unified/examples/workflowExample.js +0 -497
  159. package/dist/unified/orchestrator/orchestrator.d.ts +0 -260
  160. package/dist/unified/orchestrator/orchestrator.js +0 -519
@@ -1,391 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ToolValidationProcessor = void 0;
4
- const processor_1 = require("../../processor");
5
- /**
6
- * Processor that validates tool calls before execution, checking parameters,
7
- * security constraints, and tool availability.
8
- */
9
- class ToolValidationProcessor extends processor_1.BaseProcessor {
10
- constructor(options = {}) {
11
- super(options);
12
- this.enableParameterValidation = options.enableParameterValidation !== false;
13
- this.enableSecurityValidation = options.enableSecurityValidation !== false;
14
- this.enableTypeValidation = options.enableTypeValidation !== false;
15
- this.strictMode = options.strictMode || false;
16
- this.allowedTools = new Set(options.allowedTools || []);
17
- this.blockedTools = new Set(options.blockedTools || []);
18
- this.maxParameterSize = options.maxParameterSize || 1024 * 1024; // 1MB
19
- this.enableLogging = options.enableLogging !== false;
20
- }
21
- async processInput(input) {
22
- var _a;
23
- try {
24
- const { message, context } = input;
25
- // Check if this is a pre-tool call processing
26
- if (!(context === null || context === void 0 ? void 0 : context.preToolCallProcessing)) {
27
- return [this.createEvent('ToolValidationSkipped', {
28
- reason: 'Not a pre-tool call processing context'
29
- })];
30
- }
31
- const toolName = context.toolName;
32
- const toolInput = context.toolInput;
33
- const toolUseId = context.toolUseId;
34
- // Perform validation
35
- const validationResult = await this.validateTool(toolName, toolInput, context);
36
- if (!validationResult.isValid) {
37
- // Tool validation failed - intercept and return error
38
- const errorMessage = this.formatValidationErrors(validationResult);
39
- return [
40
- this.createEvent('ToolValidationFailed', validationResult),
41
- this.createEvent('ToolIntercepted', {
42
- result: errorMessage,
43
- toolName,
44
- userRejected: false,
45
- validationFailed: true
46
- })
47
- ];
48
- }
49
- // Validation passed
50
- return [
51
- this.createEvent('ToolValidationPassed', validationResult)
52
- ];
53
- }
54
- catch (error) {
55
- console.error('Error in ToolValidationProcessor:', error);
56
- return [this.createEvent('ToolValidationError', {
57
- error: error instanceof Error ? error.message : String(error),
58
- toolName: (_a = input.context) === null || _a === void 0 ? void 0 : _a.toolName
59
- })];
60
- }
61
- }
62
- async validateTool(toolName, toolInput, context) {
63
- const validationResult = {
64
- toolName,
65
- isValid: true,
66
- validationErrors: [],
67
- validationWarnings: [],
68
- parameterValidation: {
69
- required: [],
70
- missing: [],
71
- invalid: []
72
- },
73
- securityChecks: {
74
- passed: true,
75
- issues: []
76
- }
77
- };
78
- // Tool availability validation
79
- if (!this.validateToolAvailability(toolName, validationResult)) {
80
- validationResult.isValid = false;
81
- }
82
- // Parameter validation
83
- if (this.enableParameterValidation) {
84
- if (!this.validateParameters(toolName, toolInput, validationResult)) {
85
- validationResult.isValid = false;
86
- }
87
- }
88
- // Security validation
89
- if (this.enableSecurityValidation) {
90
- if (!this.validateSecurity(toolName, toolInput, validationResult)) {
91
- validationResult.isValid = false;
92
- }
93
- }
94
- // Type validation
95
- if (this.enableTypeValidation) {
96
- if (!this.validateTypes(toolName, toolInput, validationResult)) {
97
- validationResult.isValid = false;
98
- }
99
- }
100
- // Size validation
101
- if (!this.validateSize(toolInput, validationResult)) {
102
- validationResult.isValid = false;
103
- }
104
- return validationResult;
105
- }
106
- validateToolAvailability(toolName, result) {
107
- let isValid = true;
108
- // Check if tool is explicitly blocked
109
- if (this.blockedTools.has(toolName)) {
110
- result.validationErrors.push(`Tool '${toolName}' is blocked and cannot be executed`);
111
- isValid = false;
112
- }
113
- // Check if tool is in allowed list (if allowlist is configured)
114
- if (this.allowedTools.size > 0 && !this.allowedTools.has(toolName)) {
115
- result.validationErrors.push(`Tool '${toolName}' is not in the allowed tools list`);
116
- isValid = false;
117
- }
118
- // Check for dangerous tool patterns
119
- const dangerousPatterns = [
120
- /^(rm|del|delete)$/i,
121
- /^(format|fdisk)$/i,
122
- /^(sudo|su)$/i,
123
- /^(chmod|chown).*777/i,
124
- /eval|exec|system/i
125
- ];
126
- if (dangerousPatterns.some(pattern => pattern.test(toolName))) {
127
- result.validationWarnings.push(`Tool '${toolName}' matches potentially dangerous pattern`);
128
- if (this.strictMode) {
129
- result.validationErrors.push(`Tool '${toolName}' is considered dangerous in strict mode`);
130
- isValid = false;
131
- }
132
- }
133
- return isValid;
134
- }
135
- validateParameters(toolName, toolInput, result) {
136
- let isValid = true;
137
- // Get expected parameters for known tools
138
- const expectedParams = this.getExpectedParameters(toolName);
139
- if (expectedParams) {
140
- result.parameterValidation.required = expectedParams.required || [];
141
- // Check required parameters
142
- for (const requiredParam of expectedParams.required || []) {
143
- if (!toolInput || !(requiredParam in toolInput)) {
144
- result.parameterValidation.missing.push(requiredParam);
145
- result.validationErrors.push(`Required parameter '${requiredParam}' is missing for tool '${toolName}'`);
146
- isValid = false;
147
- }
148
- }
149
- // Check parameter types
150
- if (expectedParams.types && toolInput) {
151
- for (const [paramName, expectedType] of Object.entries(expectedParams.types)) {
152
- if (paramName in toolInput) {
153
- const actualType = typeof toolInput[paramName];
154
- if (actualType !== expectedType) {
155
- result.parameterValidation.invalid.push(paramName);
156
- result.validationErrors.push(`Parameter '${paramName}' should be of type '${expectedType}' but got '${actualType}'`);
157
- isValid = false;
158
- }
159
- }
160
- }
161
- }
162
- // Check for unexpected parameters in strict mode
163
- if (this.strictMode && expectedParams.allowed && toolInput) {
164
- for (const paramName of Object.keys(toolInput)) {
165
- if (!expectedParams.allowed.includes(paramName)) {
166
- result.validationWarnings.push(`Unexpected parameter '${paramName}' for tool '${toolName}'`);
167
- }
168
- }
169
- }
170
- }
171
- return isValid;
172
- }
173
- validateSecurity(toolName, toolInput, result) {
174
- let isValid = true;
175
- // Check for injection patterns in parameters
176
- if (toolInput && typeof toolInput === 'object') {
177
- for (const [key, value] of Object.entries(toolInput)) {
178
- if (typeof value === 'string') {
179
- // SQL injection patterns
180
- const sqlInjectionPatterns = [
181
- /('|\\'|;|\\;|--|\s*or\s+|union\s+select)/i,
182
- /(drop\s+table|delete\s+from|insert\s+into)/i
183
- ];
184
- // Command injection patterns
185
- const commandInjectionPatterns = [
186
- /[;&|`$(){}[\]]/,
187
- /(rm\s+-rf)|(sudo\s+)|(chmod\s+)/i
188
- ];
189
- // Path traversal patterns
190
- const pathTraversalPatterns = [
191
- /\.\.\//,
192
- /\.\.\\/, // fixed: properly closed regex for Windows path traversal
193
- /%2[eE]%2[eE]%2[fF]/i
194
- ];
195
- const allPatterns = [
196
- ...sqlInjectionPatterns,
197
- ...commandInjectionPatterns,
198
- ...pathTraversalPatterns
199
- ];
200
- for (const pattern of allPatterns) {
201
- if (pattern.test(value)) {
202
- result.securityChecks.issues.push(`Potential security issue in parameter '${key}': suspicious pattern detected`);
203
- result.securityChecks.passed = false;
204
- if (this.strictMode) {
205
- result.validationErrors.push(`Security validation failed for parameter '${key}' in tool '${toolName}'`);
206
- isValid = false;
207
- }
208
- else {
209
- result.validationWarnings.push(`Security warning for parameter '${key}' in tool '${toolName}'`);
210
- }
211
- }
212
- }
213
- }
214
- }
215
- }
216
- // Check for sensitive file operations
217
- if (toolName.includes('file') || toolName.includes('read') || toolName.includes('write')) {
218
- const sensitiveFiles = [
219
- '/etc/passwd',
220
- '/etc/shadow',
221
- '~/.ssh/',
222
- '.env',
223
- 'config.json',
224
- 'secrets.json'
225
- ];
226
- const filePath = (toolInput === null || toolInput === void 0 ? void 0 : toolInput.filePath) || (toolInput === null || toolInput === void 0 ? void 0 : toolInput.path) || (toolInput === null || toolInput === void 0 ? void 0 : toolInput.file);
227
- if (typeof filePath === 'string') {
228
- for (const sensitiveFile of sensitiveFiles) {
229
- if (filePath.includes(sensitiveFile)) {
230
- result.securityChecks.issues.push(`Attempt to access sensitive file: ${filePath}`);
231
- result.securityChecks.passed = false;
232
- if (this.strictMode) {
233
- result.validationErrors.push(`Access to sensitive file '${filePath}' is not allowed`);
234
- isValid = false;
235
- }
236
- else {
237
- result.validationWarnings.push(`Warning: accessing potentially sensitive file '${filePath}'`);
238
- }
239
- }
240
- }
241
- }
242
- }
243
- return isValid;
244
- }
245
- validateTypes(toolName, toolInput, result) {
246
- let isValid = true;
247
- if (toolInput === null || toolInput === undefined) {
248
- if (this.strictMode) {
249
- result.validationErrors.push(`Tool input cannot be null or undefined for '${toolName}'`);
250
- isValid = false;
251
- }
252
- return isValid;
253
- }
254
- // Validate input is serializable
255
- try {
256
- JSON.stringify(toolInput);
257
- }
258
- catch (error) {
259
- result.validationErrors.push(`Tool input for '${toolName}' is not serializable`);
260
- isValid = false;
261
- }
262
- // Check for circular references
263
- if (typeof toolInput === 'object' && this.hasCircularReference(toolInput)) {
264
- result.validationErrors.push(`Tool input for '${toolName}' contains circular references`);
265
- isValid = false;
266
- }
267
- return isValid;
268
- }
269
- validateSize(toolInput, result) {
270
- try {
271
- const serialized = JSON.stringify(toolInput);
272
- const size = new Blob([serialized]).size;
273
- if (size > this.maxParameterSize) {
274
- result.validationErrors.push(`Tool input size (${size} bytes) exceeds maximum allowed size (${this.maxParameterSize} bytes)`);
275
- return false;
276
- }
277
- }
278
- catch (error) {
279
- result.validationWarnings.push('Could not determine tool input size');
280
- }
281
- return true;
282
- }
283
- getExpectedParameters(toolName) {
284
- // Define expected parameters for common tools
285
- const toolSchemas = {
286
- 'file_read': {
287
- required: ['filePath'],
288
- types: { filePath: 'string' },
289
- allowed: ['filePath', 'encoding']
290
- },
291
- 'file_write': {
292
- required: ['filePath', 'content'],
293
- types: { filePath: 'string', content: 'string' },
294
- allowed: ['filePath', 'content', 'encoding', 'append']
295
- },
296
- 'execute_command': {
297
- required: ['command'],
298
- types: { command: 'string' },
299
- allowed: ['command', 'args', 'cwd', 'timeout']
300
- },
301
- 'http_request': {
302
- required: ['url'],
303
- types: { url: 'string' },
304
- allowed: ['url', 'method', 'headers', 'body', 'timeout']
305
- },
306
- 'database_query': {
307
- required: ['query'],
308
- types: { query: 'string' },
309
- allowed: ['query', 'parameters', 'database']
310
- }
311
- };
312
- return toolSchemas[toolName] || null;
313
- }
314
- hasCircularReference(obj, seen = new WeakSet()) {
315
- if (obj === null || typeof obj !== 'object') {
316
- return false;
317
- }
318
- if (seen.has(obj)) {
319
- return true;
320
- }
321
- seen.add(obj);
322
- for (const value of Object.values(obj)) {
323
- if (this.hasCircularReference(value, seen)) {
324
- return true;
325
- }
326
- }
327
- seen.delete(obj);
328
- return false;
329
- }
330
- formatValidationErrors(result) {
331
- const errors = result.validationErrors;
332
- const warnings = result.validationWarnings;
333
- let message = `Tool validation failed for '${result.toolName}':\n`;
334
- if (errors.length > 0) {
335
- message += '\nErrors:\n' + errors.map(error => `- ${error}`).join('\n');
336
- }
337
- if (warnings.length > 0) {
338
- message += '\nWarnings:\n' + warnings.map(warning => `- ${warning}`).join('\n');
339
- }
340
- if (result.parameterValidation.missing.length > 0) {
341
- message += `\nMissing required parameters: ${result.parameterValidation.missing.join(', ')}`;
342
- }
343
- if (result.securityChecks.issues.length > 0) {
344
- message += '\nSecurity issues:\n' + result.securityChecks.issues.map(issue => `- ${issue}`).join('\n');
345
- }
346
- return message;
347
- }
348
- // Public methods for configuration
349
- addAllowedTool(toolName) {
350
- this.allowedTools.add(toolName);
351
- if (this.enableLogging) {
352
- console.log(`[ToolValidation] Added allowed tool: ${toolName}`);
353
- }
354
- }
355
- removeAllowedTool(toolName) {
356
- const removed = this.allowedTools.delete(toolName);
357
- if (removed && this.enableLogging) {
358
- console.log(`[ToolValidation] Removed allowed tool: ${toolName}`);
359
- }
360
- return removed;
361
- }
362
- addBlockedTool(toolName) {
363
- this.blockedTools.add(toolName);
364
- if (this.enableLogging) {
365
- console.log(`[ToolValidation] Added blocked tool: ${toolName}`);
366
- }
367
- }
368
- removeBlockedTool(toolName) {
369
- const removed = this.blockedTools.delete(toolName);
370
- if (removed && this.enableLogging) {
371
- console.log(`[ToolValidation] Removed blocked tool: ${toolName}`);
372
- }
373
- return removed;
374
- }
375
- getAllowedTools() {
376
- return Array.from(this.allowedTools);
377
- }
378
- getBlockedTools() {
379
- return Array.from(this.blockedTools);
380
- }
381
- isToolAllowed(toolName) {
382
- if (this.blockedTools.has(toolName)) {
383
- return false;
384
- }
385
- if (this.allowedTools.size > 0) {
386
- return this.allowedTools.has(toolName);
387
- }
388
- return true;
389
- }
390
- }
391
- exports.ToolValidationProcessor = ToolValidationProcessor;
@@ -1,99 +0,0 @@
1
- /**
2
- * Tool creation utilities for the Unified Agent Framework
3
- */
4
- import { z } from 'zod';
5
- import type { OpenAITool } from '../types/libTypes';
6
- import type { Tool, ToolConfig } from './agent';
7
- /**
8
- * Creates a new tool with input/output validation and execution logic
9
- *
10
- * @template TInput - Type for tool input parameters
11
- * @template TOutput - Type for tool output
12
- * @param config - Tool configuration object
13
- * @returns Fully configured tool with validation methods
14
- *
15
- * @example
16
- * ```typescript
17
- * const calculatorTool = createTool({
18
- * id: 'calculator',
19
- * name: 'Calculator',
20
- * description: 'Performs basic mathematical calculations',
21
- * inputSchema: z.object({
22
- * expression: z.string().describe('Mathematical expression to evaluate'),
23
- * }),
24
- * outputSchema: z.object({
25
- * result: z.number(),
26
- * expression: z.string(),
27
- * }),
28
- * execute: async ({ input }) => {
29
- * const result = eval(input.expression); // Note: eval is dangerous, use a proper parser
30
- * return { result, expression: input.expression };
31
- * },
32
- * });
33
- * ```
34
- */
35
- export declare function createTool<TInput = any, TOutput = any>(config: ToolConfig<TInput, TOutput>): Tool<TInput, TOutput>;
36
- /**
37
- * Creates a simple text-based tool
38
- */
39
- export declare function createTextTool(config: {
40
- id: string;
41
- name: string;
42
- description: string;
43
- execute: (text: string, context?: Record<string, any>) => Promise<string> | string;
44
- timeout?: number;
45
- }): Tool<{
46
- text: string;
47
- }, string>;
48
- /**
49
- * Creates a file operation tool
50
- */
51
- export declare function createFileTool(config: {
52
- id: string;
53
- name: string;
54
- description: string;
55
- operation: 'read' | 'write' | 'delete' | 'list';
56
- execute: (params: any, context?: Record<string, any>) => Promise<any> | any;
57
- }): Tool;
58
- /**
59
- * Creates an HTTP request tool
60
- */
61
- export declare function createHttpTool(config: {
62
- id: string;
63
- name: string;
64
- description: string;
65
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
66
- baseUrl?: string;
67
- defaultHeaders?: Record<string, string>;
68
- execute?: (params: any, context?: Record<string, any>) => Promise<any> | any;
69
- }): Tool;
70
- /**
71
- * Creates a validation tool
72
- */
73
- export declare function createValidationTool<T>(config: {
74
- id: string;
75
- name: string;
76
- description: string;
77
- schema: z.ZodType<T>;
78
- onValid?: (data: T) => Promise<any> | any;
79
- onInvalid?: (errors: string[]) => Promise<any> | any;
80
- }): Tool;
81
- /**
82
- * Creates a transformation tool
83
- */
84
- export declare function createTransformTool<TInput, TOutput>(config: {
85
- id: string;
86
- name: string;
87
- description: string;
88
- inputSchema: z.ZodType<TInput>;
89
- outputSchema?: z.ZodType<TOutput>;
90
- transform: (input: TInput, context?: Record<string, any>) => Promise<TOutput> | TOutput;
91
- }): Tool<TInput, TOutput>;
92
- /**
93
- * Utility to convert multiple tools to OpenAI format
94
- */
95
- export declare function toolsToOpenAIFormat(tools: Tool[]): OpenAITool[];
96
- /**
97
- * Utility to execute a tool with validation
98
- */
99
- export declare function executeTool<TInput, TOutput>(tool: Tool<TInput, TOutput>, input: unknown, context?: Record<string, any>, agent?: any): Promise<TOutput>;