@codebolt/agent 2.2.2 → 2.2.5

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 (141) hide show
  1. package/dist/builderpattern/agent.js +2 -2
  2. package/dist/builderpattern/followupquestionbuilder.js +1 -1
  3. package/dist/builderpattern/llmoutputhandler.js +7 -7
  4. package/dist/builderpattern/usermessage.d.ts +6 -1
  5. package/dist/composablepattern/document.js +2 -35
  6. package/dist/local-tools/fileTools.d.ts +26 -0
  7. package/dist/local-tools/fileTools.js +162 -0
  8. package/dist/processor/types/interfaces.d.ts +44 -21
  9. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +13 -0
  10. package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +68 -0
  11. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +15 -0
  12. package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +212 -0
  13. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +19 -0
  14. package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +110 -0
  15. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +23 -0
  16. package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +173 -0
  17. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +14 -0
  18. package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +93 -0
  19. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +30 -0
  20. package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +330 -0
  21. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +26 -0
  22. package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +269 -0
  23. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +38 -0
  24. package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +217 -0
  25. package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +34 -0
  26. package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +147 -0
  27. package/dist/processor-pieces/additionalModifiers/index.d.ts +12 -0
  28. package/dist/processor-pieces/additionalModifiers/index.js +28 -0
  29. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +29 -0
  30. package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +155 -0
  31. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +15 -0
  32. package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +129 -0
  33. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +25 -0
  34. package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +169 -0
  35. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +20 -0
  36. package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +152 -0
  37. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +7 -0
  38. package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +93 -0
  39. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +14 -5
  40. package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +41 -40
  41. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +9 -0
  42. package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +77 -0
  43. package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +5 -5
  44. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +5 -13
  45. package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +50 -58
  46. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +6 -8
  47. package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +66 -22
  48. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +19 -0
  49. package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +110 -0
  50. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +20 -0
  51. package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +124 -0
  52. package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +41 -0
  53. package/dist/processor-pieces/messageModifiers/environmentContext.js +355 -0
  54. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +3 -2
  55. package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +1 -2
  56. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +3 -2
  57. package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +1 -2
  58. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +23 -0
  59. package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +207 -0
  60. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +7 -0
  61. package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +26 -0
  62. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +18 -2
  63. package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +291 -93
  64. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +1 -0
  65. package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +2 -0
  66. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +7 -0
  67. package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +24 -0
  68. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +41 -0
  69. package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +197 -0
  70. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +26 -0
  71. package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +90 -0
  72. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +81 -0
  73. package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +329 -0
  74. package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +40 -0
  75. package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +272 -0
  76. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +49 -0
  77. package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +291 -0
  78. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +49 -0
  79. package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +293 -0
  80. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +47 -0
  81. package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +249 -0
  82. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +30 -0
  83. package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +137 -0
  84. package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +30 -0
  85. package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +228 -0
  86. package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +99 -0
  87. package/dist/processor-pieces/postToolCall/telemetryProcessor.js +278 -0
  88. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +37 -0
  89. package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +178 -0
  90. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +43 -0
  91. package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +207 -0
  92. package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +52 -0
  93. package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +264 -0
  94. package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +49 -0
  95. package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +293 -0
  96. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +7 -0
  97. package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +31 -0
  98. package/dist/processor-pieces/preToolCall/index.d.ts +9 -0
  99. package/dist/processor-pieces/preToolCall/index.js +18 -0
  100. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +58 -0
  101. package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +444 -0
  102. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +44 -0
  103. package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +367 -0
  104. package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +58 -0
  105. package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +391 -0
  106. package/dist/unified/agent/agent.js +2 -2
  107. package/dist/unified/agent/tool.d.ts +99 -0
  108. package/dist/unified/agent/tool.js +440 -0
  109. package/dist/unified/base/initialPromptGenerator.js +5 -5
  110. package/dist/unified/base/responseExecutor.js +6 -6
  111. package/dist/unified/examples/agentExample.d.ts +46 -0
  112. package/dist/unified/examples/agentExample.js +464 -0
  113. package/dist/unified/examples/documentationPatternExample.d.ts +10 -0
  114. package/dist/unified/examples/documentationPatternExample.js +385 -0
  115. package/dist/unified/examples/followUpProcessorsExample.d.ts +45 -0
  116. package/dist/unified/examples/followUpProcessorsExample.js +311 -0
  117. package/dist/unified/examples/orchestratorExample.d.ts +16 -0
  118. package/dist/unified/examples/orchestratorExample.js +415 -0
  119. package/dist/unified/examples/preToolCallProcessorsExample.d.ts +36 -0
  120. package/dist/unified/examples/preToolCallProcessorsExample.js +458 -0
  121. package/dist/unified/examples/workflowExample.d.ts +12 -0
  122. package/dist/unified/examples/workflowExample.js +497 -0
  123. package/dist/unified/orchestrator/orchestrator.d.ts +260 -0
  124. package/dist/unified/orchestrator/orchestrator.js +519 -0
  125. package/package.json +5 -5
  126. package/dist/agent.d.ts +0 -86
  127. package/dist/agent.js +0 -324
  128. package/dist/followupquestionbuilder.d.ts +0 -75
  129. package/dist/followupquestionbuilder.js +0 -197
  130. package/dist/index.d.ts +0 -14
  131. package/dist/index.js +0 -23
  132. package/dist/llmoutputhandler.d.ts +0 -102
  133. package/dist/llmoutputhandler.js +0 -452
  134. package/dist/promptbuilder.d.ts +0 -382
  135. package/dist/promptbuilder.js +0 -805
  136. package/dist/systemprompt.d.ts +0 -20
  137. package/dist/systemprompt.js +0 -48
  138. package/dist/taskInstruction.d.ts +0 -37
  139. package/dist/taskInstruction.js +0 -57
  140. package/dist/usermessage.d.ts +0 -70
  141. package/dist/usermessage.js +0 -123
@@ -0,0 +1,497 @@
1
+ "use strict";
2
+ /**
3
+ * Comprehensive Workflow Example for Unified Agent Framework
4
+ *
5
+ * This example demonstrates how to create and execute complex workflows
6
+ * that integrate agents, tools, and control flow steps.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.runWorkflowExamples = runWorkflowExamples;
10
+ exports.contentCreationWorkflowExample = contentCreationWorkflowExample;
11
+ exports.multiAgentCollaborationExample = multiAgentCollaborationExample;
12
+ exports.iterativeImprovementExample = iterativeImprovementExample;
13
+ exports.agentWithWorkflowExample = agentWithWorkflowExample;
14
+ const zod_1 = require("zod");
15
+ const index_1 = require("../index");
16
+ // ================================
17
+ // Example: Content Creation Workflow
18
+ // ================================
19
+ async function contentCreationWorkflowExample() {
20
+ var _a;
21
+ console.log('=== Content Creation Workflow Example ===');
22
+ // Create specialized agents
23
+ const researchAgent = (0, index_1.createAgent)({
24
+ name: 'Research Agent',
25
+ instructions: 'You are a research specialist. Gather comprehensive information on given topics.',
26
+ tools: [
27
+ (0, index_1.createTool)({
28
+ id: 'web-search',
29
+ name: 'Web Search',
30
+ description: 'Search the web for information',
31
+ inputSchema: zod_1.z.object({
32
+ query: zod_1.z.string(),
33
+ maxResults: zod_1.z.number().optional()
34
+ }),
35
+ execute: async ({ input }) => {
36
+ // Simulate web search
37
+ return {
38
+ results: [
39
+ { title: `Research on ${input.query}`, content: `Detailed information about ${input.query}...` }
40
+ ]
41
+ };
42
+ }
43
+ })
44
+ ]
45
+ });
46
+ const writerAgent = (0, index_1.createAgent)({
47
+ name: 'Content Writer',
48
+ instructions: 'You are a skilled content writer. Create engaging and informative content based on research.',
49
+ tools: []
50
+ });
51
+ const editorAgent = (0, index_1.createAgent)({
52
+ name: 'Editor',
53
+ instructions: 'You are an editor. Review and improve content for clarity, grammar, and style.',
54
+ tools: []
55
+ });
56
+ // Create content validation tool
57
+ const contentValidator = (0, index_1.createTool)({
58
+ id: 'content-validator',
59
+ name: 'Content Validator',
60
+ description: 'Validate content quality and completeness',
61
+ inputSchema: zod_1.z.object({
62
+ content: zod_1.z.string(),
63
+ criteria: zod_1.z.array(zod_1.z.string())
64
+ }),
65
+ execute: async ({ input }) => {
66
+ const score = Math.random() * 100; // Simulate validation score
67
+ return {
68
+ score,
69
+ passed: score > 70,
70
+ feedback: score > 70 ? 'Content meets quality standards' : 'Content needs improvement'
71
+ };
72
+ }
73
+ });
74
+ // Define the content creation workflow
75
+ const contentWorkflowConfig = {
76
+ name: 'Content Creation Pipeline',
77
+ description: 'End-to-end content creation with research, writing, and editing',
78
+ initialData: {
79
+ topic: 'Artificial Intelligence in Healthcare',
80
+ targetAudience: 'Healthcare professionals',
81
+ contentType: 'blog post',
82
+ maxLength: 2000
83
+ },
84
+ steps: [
85
+ // Step 1: Research phase
86
+ (0, index_1.createAgentStep)({
87
+ id: 'research-phase',
88
+ name: 'Research Phase',
89
+ description: 'Gather information on the topic',
90
+ agent: researchAgent,
91
+ message: 'Research the topic: {{topic}} for {{targetAudience}}. Focus on recent developments and practical applications.',
92
+ outputMapping: {
93
+ researchData: 'agentResult.response',
94
+ researchSources: 'agentResult.toolResults'
95
+ }
96
+ }),
97
+ // Step 2: Content outline creation
98
+ (0, index_1.createTransformStep)({
99
+ id: 'create-outline',
100
+ name: 'Create Content Outline',
101
+ description: 'Generate content outline based on research',
102
+ transform: (data) => {
103
+ return {
104
+ outline: [
105
+ 'Introduction',
106
+ 'Current State of AI in Healthcare',
107
+ 'Key Applications and Benefits',
108
+ 'Challenges and Considerations',
109
+ 'Future Outlook',
110
+ 'Conclusion'
111
+ ],
112
+ estimatedLength: data.maxLength
113
+ };
114
+ }
115
+ }),
116
+ // Step 3: Content writing
117
+ (0, index_1.createAgentStep)({
118
+ id: 'writing-phase',
119
+ name: 'Content Writing',
120
+ description: 'Write the content based on research and outline',
121
+ agent: writerAgent,
122
+ message: 'Write a {{contentType}} about {{topic}} for {{targetAudience}}. Use this research: {{researchData}} and follow this outline: {{outline}}. Target length: {{maxLength}} words.',
123
+ outputMapping: {
124
+ firstDraft: 'agentResult.response'
125
+ }
126
+ }),
127
+ // Step 4: Content validation
128
+ (0, index_1.createToolStep)({
129
+ id: 'validate-content',
130
+ name: 'Validate Content Quality',
131
+ description: 'Check content quality and completeness',
132
+ tool: contentValidator,
133
+ input: (context) => ({
134
+ content: context.data.firstDraft,
135
+ criteria: ['clarity', 'accuracy', 'engagement', 'completeness']
136
+ }),
137
+ outputMapping: {
138
+ validationScore: 'toolResult.score',
139
+ validationPassed: 'toolResult.passed',
140
+ validationFeedback: 'toolResult.feedback'
141
+ }
142
+ }),
143
+ // Step 5: Conditional editing based on validation
144
+ (0, index_1.createConditionalStep)({
145
+ id: 'conditional-editing',
146
+ name: 'Conditional Editing',
147
+ description: 'Edit content if validation fails',
148
+ condition: (context) => !context.data.validationPassed,
149
+ trueSteps: [
150
+ (0, index_1.createAgentStep)({
151
+ id: 'editing-phase',
152
+ name: 'Content Editing',
153
+ description: 'Improve content based on feedback',
154
+ agent: editorAgent,
155
+ message: 'Edit and improve this content: {{firstDraft}}. Address this feedback: {{validationFeedback}}. Ensure it meets quality standards for {{targetAudience}}.',
156
+ outputMapping: {
157
+ editedContent: 'agentResult.response'
158
+ }
159
+ }),
160
+ // Re-validate after editing
161
+ (0, index_1.createToolStep)({
162
+ id: 'revalidate-content',
163
+ name: 'Re-validate Content',
164
+ description: 'Check improved content quality',
165
+ tool: contentValidator,
166
+ input: (context) => ({
167
+ content: context.data.editedContent || context.data.firstDraft,
168
+ criteria: ['clarity', 'accuracy', 'engagement', 'completeness']
169
+ }),
170
+ outputMapping: {
171
+ finalValidationScore: 'toolResult.score',
172
+ finalValidationPassed: 'toolResult.passed'
173
+ }
174
+ })
175
+ ]
176
+ }),
177
+ // Step 6: Finalize content
178
+ (0, index_1.createTransformStep)({
179
+ id: 'finalize-content',
180
+ name: 'Finalize Content',
181
+ description: 'Prepare final content for publication',
182
+ transform: (data) => {
183
+ const finalContent = data.editedContent || data.firstDraft;
184
+ return {
185
+ finalContent,
186
+ wordCount: finalContent.split(' ').length,
187
+ publicationReady: true,
188
+ metadata: {
189
+ topic: data.topic,
190
+ audience: data.targetAudience,
191
+ type: data.contentType,
192
+ createdAt: new Date().toISOString(),
193
+ validationScore: data.finalValidationScore || data.validationScore
194
+ }
195
+ };
196
+ }
197
+ })
198
+ ],
199
+ continueOnError: false,
200
+ timeout: 300000, // 5 minutes
201
+ maxParallelSteps: 2
202
+ };
203
+ // Create and execute the workflow
204
+ const workflow = (0, index_1.createWorkflow)(contentWorkflowConfig);
205
+ // Add agents to workflow context
206
+ workflow.addAgent('research-agent', researchAgent);
207
+ workflow.addAgent('writer-agent', writerAgent);
208
+ workflow.addAgent('editor-agent', editorAgent);
209
+ // Add tools to workflow context
210
+ workflow.addTool('content-validator', contentValidator);
211
+ console.log('Starting content creation workflow...');
212
+ const result = await workflow.execute();
213
+ console.log('Workflow completed:', {
214
+ success: result.success,
215
+ executionTime: result.executionTime,
216
+ totalSteps: result.stepResults.length,
217
+ finalContent: ((_a = result.data.finalContent) === null || _a === void 0 ? void 0 : _a.substring(0, 200)) + '...',
218
+ wordCount: result.data.wordCount,
219
+ validationScore: result.data.finalValidationScore || result.data.validationScore
220
+ });
221
+ return result;
222
+ }
223
+ // ================================
224
+ // Example: Multi-Agent Collaboration
225
+ // ================================
226
+ async function multiAgentCollaborationExample() {
227
+ var _a;
228
+ console.log('\n=== Multi-Agent Collaboration Example ===');
229
+ // Create specialized agents for different perspectives
230
+ const techAgent = (0, index_1.createAgent)({
231
+ name: 'Technical Expert',
232
+ instructions: 'You are a technical expert. Focus on technical feasibility, implementation details, and technical risks.'
233
+ });
234
+ const businessAgent = (0, index_1.createAgent)({
235
+ name: 'Business Analyst',
236
+ instructions: 'You are a business analyst. Focus on business value, market opportunities, and ROI.'
237
+ });
238
+ const designAgent = (0, index_1.createAgent)({
239
+ name: 'UX Designer',
240
+ instructions: 'You are a UX designer. Focus on user experience, usability, and design considerations.'
241
+ });
242
+ // Multi-agent collaboration workflow
243
+ const collaborationConfig = {
244
+ name: 'Product Feature Analysis',
245
+ description: 'Multi-agent analysis of a new product feature',
246
+ initialData: {
247
+ feature: 'AI-powered chatbot for customer support',
248
+ context: 'E-commerce platform with 1M+ users'
249
+ },
250
+ steps: [
251
+ // Parallel analysis by different agents
252
+ (0, index_1.createMultiAgentStep)({
253
+ id: 'parallel-analysis',
254
+ name: 'Parallel Feature Analysis',
255
+ description: 'Multiple agents analyze the feature from different perspectives',
256
+ agents: [
257
+ {
258
+ agent: techAgent,
259
+ role: 'technical',
260
+ message: 'Analyze the technical aspects of implementing {{feature}} for {{context}}. Consider architecture, scalability, and implementation challenges.'
261
+ },
262
+ {
263
+ agent: businessAgent,
264
+ role: 'business',
265
+ message: 'Analyze the business value of {{feature}} for {{context}}. Consider market impact, revenue potential, and competitive advantage.'
266
+ },
267
+ {
268
+ agent: designAgent,
269
+ role: 'design',
270
+ message: 'Analyze the UX/UI aspects of {{feature}} for {{context}}. Consider user journey, interface design, and accessibility.'
271
+ }
272
+ ],
273
+ collaborationMode: 'parallel'
274
+ }),
275
+ // Synthesis step
276
+ (0, index_1.createAgentStep)({
277
+ id: 'synthesis',
278
+ name: 'Synthesis and Recommendation',
279
+ description: 'Synthesize different perspectives into final recommendation',
280
+ agent: businessAgent, // Lead agent for synthesis
281
+ message: `Based on the following analyses, provide a comprehensive recommendation for implementing {{feature}}:
282
+
283
+ Technical Analysis: {{technical_result}}
284
+ Business Analysis: {{business_result}}
285
+ Design Analysis: {{design_result}}
286
+
287
+ Provide a final recommendation with priorities, timeline, and next steps.`,
288
+ outputMapping: {
289
+ finalRecommendation: 'agentResult.response',
290
+ confidence: 'agentResult.metadata.confidence'
291
+ }
292
+ })
293
+ ]
294
+ };
295
+ const collaborationWorkflow = (0, index_1.createWorkflow)(collaborationConfig);
296
+ // Add agents
297
+ collaborationWorkflow.addAgent('tech-agent', techAgent);
298
+ collaborationWorkflow.addAgent('business-agent', businessAgent);
299
+ collaborationWorkflow.addAgent('design-agent', designAgent);
300
+ console.log('Starting multi-agent collaboration...');
301
+ const result = await collaborationWorkflow.execute();
302
+ console.log('Collaboration completed:', {
303
+ success: result.success,
304
+ executionTime: result.executionTime,
305
+ recommendation: ((_a = result.data.finalRecommendation) === null || _a === void 0 ? void 0 : _a.substring(0, 300)) + '...'
306
+ });
307
+ return result;
308
+ }
309
+ // ================================
310
+ // Example: Iterative Improvement Loop
311
+ // ================================
312
+ async function iterativeImprovementExample() {
313
+ console.log('\n=== Iterative Improvement Example ===');
314
+ const optimizerAgent = (0, index_1.createAgent)({
315
+ name: 'Code Optimizer',
316
+ instructions: 'You are a code optimization expert. Analyze code and suggest improvements for performance, readability, and maintainability.'
317
+ });
318
+ // Quality checker tool
319
+ const qualityChecker = (0, index_1.createTool)({
320
+ id: 'quality-checker',
321
+ name: 'Code Quality Checker',
322
+ description: 'Check code quality metrics',
323
+ inputSchema: zod_1.z.object({
324
+ code: zod_1.z.string(),
325
+ language: zod_1.z.string()
326
+ }),
327
+ execute: async ({ input }) => {
328
+ // Simulate quality analysis
329
+ const score = Math.random() * 100;
330
+ return {
331
+ score,
332
+ issues: score < 80 ? ['Performance issues', 'Code complexity'] : [],
333
+ suggestions: score < 80 ? ['Optimize loops', 'Reduce complexity'] : []
334
+ };
335
+ }
336
+ });
337
+ const iterativeConfig = {
338
+ name: 'Iterative Code Improvement',
339
+ description: 'Iteratively improve code quality until threshold is met',
340
+ initialData: {
341
+ code: 'function fibonacci(n) { if(n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); }',
342
+ language: 'javascript',
343
+ targetQuality: 85,
344
+ maxIterations: 5
345
+ },
346
+ steps: [
347
+ (0, index_1.createLoopStep)({
348
+ id: 'improvement-loop',
349
+ name: 'Code Improvement Loop',
350
+ description: 'Iteratively improve code until quality threshold is met',
351
+ condition: async (context, iteration) => {
352
+ if (iteration >= context.data.maxIterations)
353
+ return false;
354
+ if (iteration === 0)
355
+ return true; // Always run first iteration
356
+ const currentQuality = context.data.currentQuality;
357
+ const targetQuality = context.data.targetQuality;
358
+ return currentQuality < targetQuality;
359
+ },
360
+ maxIterations: 5,
361
+ iterationVariable: 'currentIteration',
362
+ steps: [
363
+ // Check current quality
364
+ (0, index_1.createToolStep)({
365
+ id: 'check-quality',
366
+ name: 'Check Code Quality',
367
+ description: 'Analyze current code quality',
368
+ tool: qualityChecker,
369
+ input: (context) => ({
370
+ code: context.data.code,
371
+ language: context.data.language
372
+ }),
373
+ outputMapping: {
374
+ currentQuality: 'toolResult.score',
375
+ issues: 'toolResult.issues',
376
+ suggestions: 'toolResult.suggestions'
377
+ }
378
+ }),
379
+ // Improve code if needed
380
+ (0, index_1.createConditionalStep)({
381
+ id: 'improve-if-needed',
382
+ name: 'Improve Code If Needed',
383
+ description: 'Improve code if quality is below threshold',
384
+ condition: (context) => {
385
+ const currentQuality = context.data.currentQuality;
386
+ const targetQuality = context.data.targetQuality;
387
+ return currentQuality < targetQuality;
388
+ },
389
+ trueSteps: [
390
+ (0, index_1.createAgentStep)({
391
+ id: 'optimize-code',
392
+ name: 'Optimize Code',
393
+ description: 'Improve code based on quality issues',
394
+ agent: optimizerAgent,
395
+ message: `Improve this {{language}} code:
396
+
397
+ {{code}}
398
+
399
+ Current quality score: {{currentQuality}}
400
+ Target quality score: {{targetQuality}}
401
+ Issues found: {{issues}}
402
+ Suggestions: {{suggestions}}
403
+
404
+ Provide optimized code that addresses these issues.`,
405
+ outputMapping: {
406
+ code: 'agentResult.response'
407
+ }
408
+ })
409
+ ]
410
+ })
411
+ ]
412
+ }),
413
+ // Final validation
414
+ (0, index_1.createValidationStep)({
415
+ id: 'final-validation',
416
+ name: 'Final Code Validation',
417
+ description: 'Validate final code meets requirements',
418
+ schema: zod_1.z.object({
419
+ currentQuality: zod_1.z.number().min(80),
420
+ code: zod_1.z.string().min(10)
421
+ }),
422
+ stopOnFailure: false
423
+ })
424
+ ]
425
+ };
426
+ const iterativeWorkflow = (0, index_1.createWorkflow)(iterativeConfig);
427
+ iterativeWorkflow.addAgent('optimizer', optimizerAgent);
428
+ iterativeWorkflow.addTool('quality-checker', qualityChecker);
429
+ console.log('Starting iterative improvement...');
430
+ const result = await iterativeWorkflow.execute();
431
+ console.log('Iterative improvement completed:', {
432
+ success: result.success,
433
+ iterations: result.data.currentIteration,
434
+ finalQuality: result.data.currentQuality,
435
+ finalCode: result.data.code
436
+ });
437
+ return result;
438
+ }
439
+ // ================================
440
+ // Example: Agent with Workflow Tools
441
+ // ================================
442
+ async function agentWithWorkflowExample() {
443
+ var _a;
444
+ console.log('\n=== Agent with Workflow Tools Example ===');
445
+ // Create an agent that can execute workflows as tools
446
+ const orchestratorAgent = (0, index_1.createAgent)({
447
+ name: 'Workflow Orchestrator',
448
+ instructions: 'You are a workflow orchestrator. You can execute complex workflows to accomplish tasks.',
449
+ tools: []
450
+ });
451
+ // Add the content creation workflow as a tool
452
+ const contentCreationTool = (0, index_1.createTool)({
453
+ id: 'content-creation-workflow',
454
+ name: 'Content Creation Workflow',
455
+ description: 'Execute the complete content creation pipeline',
456
+ inputSchema: zod_1.z.object({
457
+ topic: zod_1.z.string(),
458
+ targetAudience: zod_1.z.string(),
459
+ contentType: zod_1.z.string().optional().default('blog post'),
460
+ maxLength: zod_1.z.number().optional().default(2000)
461
+ }),
462
+ execute: async ({ input }) => {
463
+ // This would execute the content creation workflow
464
+ // For demo purposes, we'll simulate it
465
+ return {
466
+ success: true,
467
+ content: `Generated content about ${input.topic} for ${input.targetAudience}`,
468
+ wordCount: input.maxLength * 0.8,
469
+ qualityScore: 85
470
+ };
471
+ }
472
+ });
473
+ orchestratorAgent.addTool(contentCreationTool);
474
+ // Test the agent with workflow capabilities
475
+ const result = await orchestratorAgent.execute('Create a comprehensive blog post about "Machine Learning in Finance" targeted at financial professionals. Make it around 1500 words.');
476
+ console.log('Agent with workflow completed:', {
477
+ success: result.success,
478
+ response: result.response.substring(0, 200) + '...',
479
+ toolsUsed: ((_a = result.toolResults) === null || _a === void 0 ? void 0 : _a.length) || 0
480
+ });
481
+ return result;
482
+ }
483
+ // ================================
484
+ // Run Examples
485
+ // ================================
486
+ async function runWorkflowExamples() {
487
+ try {
488
+ await contentCreationWorkflowExample();
489
+ await multiAgentCollaborationExample();
490
+ await iterativeImprovementExample();
491
+ await agentWithWorkflowExample();
492
+ console.log('\n✅ All workflow examples completed successfully!');
493
+ }
494
+ catch (error) {
495
+ console.error('❌ Workflow example failed:', error);
496
+ }
497
+ }