@codebolt/agent 2.2.2 → 2.2.3
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.
- package/dist/builderpattern/agent.js +2 -2
- package/dist/builderpattern/followupquestionbuilder.js +1 -1
- package/dist/builderpattern/llmoutputhandler.js +7 -7
- package/dist/builderpattern/usermessage.d.ts +6 -1
- package/dist/composablepattern/document.js +2 -35
- package/dist/local-tools/fileTools.d.ts +26 -0
- package/dist/local-tools/fileTools.js +162 -0
- package/dist/processor/types/interfaces.d.ts +44 -21
- package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.d.ts +13 -0
- package/dist/processor-pieces/additionalModifiers/argumentProcessorModifier.js +68 -0
- package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.d.ts +15 -0
- package/dist/processor-pieces/additionalModifiers/atFileProcessorModifier.js +212 -0
- package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.d.ts +19 -0
- package/dist/processor-pieces/additionalModifiers/chatCompressionModifier.js +110 -0
- package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.d.ts +23 -0
- package/dist/processor-pieces/additionalModifiers/chatRecordingModifier.js +173 -0
- package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.d.ts +14 -0
- package/dist/processor-pieces/additionalModifiers/coreSystemPromptModifier.js +93 -0
- package/dist/processor-pieces/additionalModifiers/directoryContextModifier.d.ts +30 -0
- package/dist/processor-pieces/additionalModifiers/directoryContextModifier.js +330 -0
- package/dist/processor-pieces/additionalModifiers/environmentContextModifier.d.ts +26 -0
- package/dist/processor-pieces/additionalModifiers/environmentContextModifier.js +269 -0
- package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.d.ts +38 -0
- package/dist/processor-pieces/additionalModifiers/fallbackHandlerModifier.js +217 -0
- package/dist/processor-pieces/additionalModifiers/ideContextModifier.d.ts +34 -0
- package/dist/processor-pieces/additionalModifiers/ideContextModifier.js +147 -0
- package/dist/processor-pieces/additionalModifiers/index.d.ts +12 -0
- package/dist/processor-pieces/additionalModifiers/index.js +28 -0
- package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.d.ts +29 -0
- package/dist/processor-pieces/additionalModifiers/loopDetectionModifier.js +155 -0
- package/dist/processor-pieces/additionalModifiers/memoryImportModifier.d.ts +15 -0
- package/dist/processor-pieces/additionalModifiers/memoryImportModifier.js +129 -0
- package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.d.ts +25 -0
- package/dist/processor-pieces/additionalModifiers/shellProcessorModifier.js +169 -0
- package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.d.ts +20 -0
- package/dist/processor-pieces/additionalModifiers/toolInjectionModifier.js +152 -0
- package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.d.ts +7 -0
- package/dist/processor-pieces/messageModifiers/addCurrentDirectoryRootFilesModifier.js +93 -0
- package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.d.ts +14 -5
- package/dist/processor-pieces/messageModifiers/addToolsListMessageModifier.js +41 -40
- package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.d.ts +9 -0
- package/dist/processor-pieces/messageModifiers/advancedSystemInstructionMessageModifier.js +77 -0
- package/dist/processor-pieces/messageModifiers/atFileProcessorModifier.js +5 -5
- package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.d.ts +5 -13
- package/dist/processor-pieces/messageModifiers/baseContextMessageModifier.js +50 -58
- package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.d.ts +6 -8
- package/dist/processor-pieces/messageModifiers/baseSystemInstructionMessageModifier.js +66 -22
- package/dist/processor-pieces/messageModifiers/chatCompressionModifier.d.ts +19 -0
- package/dist/processor-pieces/messageModifiers/chatCompressionModifier.js +110 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.d.ts +20 -0
- package/dist/processor-pieces/messageModifiers/chatHistoryMessageModifier.example.js +124 -0
- package/dist/processor-pieces/messageModifiers/environmentContext.d.ts +41 -0
- package/dist/processor-pieces/messageModifiers/environmentContext.js +355 -0
- package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.d.ts +3 -2
- package/dist/processor-pieces/messageModifiers/handleUrlMessageModifier.js +1 -2
- package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.d.ts +3 -2
- package/dist/processor-pieces/messageModifiers/imageAttachmentMessageModifier.js +1 -2
- package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.d.ts +23 -0
- package/dist/processor-pieces/messageModifiers/mentionedFilesModifier.js +207 -0
- package/dist/processor-pieces/messageModifiers/simpleMessageModifier.d.ts +7 -0
- package/dist/processor-pieces/messageModifiers/simpleMessageModifier.js +26 -0
- package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.d.ts +18 -2
- package/dist/processor-pieces/messageModifiers/workingDirectoryMessageModifier.js +291 -93
- package/dist/processor-pieces/postInference/llmOutputValidityProcessor.d.ts +1 -0
- package/dist/processor-pieces/postInference/llmOutputValidityProcessor.js +2 -0
- package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.d.ts +7 -0
- package/dist/processor-pieces/postInferenceProcessors/checkForNoToolCall.js +24 -0
- package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.d.ts +41 -0
- package/dist/processor-pieces/postToolCall/advancedLoopDetectionProcessor.js +197 -0
- package/dist/processor-pieces/postToolCall/chatCompressionProcessor.d.ts +26 -0
- package/dist/processor-pieces/postToolCall/chatCompressionProcessor.js +90 -0
- package/dist/processor-pieces/postToolCall/chatRecordingProcessor.d.ts +81 -0
- package/dist/processor-pieces/postToolCall/chatRecordingProcessor.js +329 -0
- package/dist/processor-pieces/postToolCall/contextManagementProcessor.d.ts +40 -0
- package/dist/processor-pieces/postToolCall/contextManagementProcessor.js +272 -0
- package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.d.ts +49 -0
- package/dist/processor-pieces/postToolCall/conversationCompactorProcessor.js +291 -0
- package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.d.ts +49 -0
- package/dist/processor-pieces/postToolCall/conversationContinuityProcessor.js +293 -0
- package/dist/processor-pieces/postToolCall/followUpConversationProcessor.d.ts +47 -0
- package/dist/processor-pieces/postToolCall/followUpConversationProcessor.js +249 -0
- package/dist/processor-pieces/postToolCall/loopDetectionProcessor.d.ts +30 -0
- package/dist/processor-pieces/postToolCall/loopDetectionProcessor.js +137 -0
- package/dist/processor-pieces/postToolCall/responseValidationProcessor.d.ts +30 -0
- package/dist/processor-pieces/postToolCall/responseValidationProcessor.js +228 -0
- package/dist/processor-pieces/postToolCall/telemetryProcessor.d.ts +99 -0
- package/dist/processor-pieces/postToolCall/telemetryProcessor.js +278 -0
- package/dist/processor-pieces/postToolCall/tokenManagementProcessor.d.ts +37 -0
- package/dist/processor-pieces/postToolCall/tokenManagementProcessor.js +178 -0
- package/dist/processor-pieces/postToolCall/toolExecutionProcessor.d.ts +43 -0
- package/dist/processor-pieces/postToolCall/toolExecutionProcessor.js +207 -0
- package/dist/processor-pieces/preInference/conversationCompactorProcessor.d.ts +52 -0
- package/dist/processor-pieces/preInference/conversationCompactorProcessor.js +264 -0
- package/dist/processor-pieces/preInference/conversationContinuityProcessor.d.ts +49 -0
- package/dist/processor-pieces/preInference/conversationContinuityProcessor.js +293 -0
- package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.d.ts +7 -0
- package/dist/processor-pieces/preInferenceProcessors/conversationCompaction.js +31 -0
- package/dist/processor-pieces/preToolCall/index.d.ts +9 -0
- package/dist/processor-pieces/preToolCall/index.js +18 -0
- package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.d.ts +58 -0
- package/dist/processor-pieces/preToolCall/localToolInterceptorProcessor.js +444 -0
- package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.d.ts +44 -0
- package/dist/processor-pieces/preToolCall/toolParameterModifierProcessor.js +367 -0
- package/dist/processor-pieces/preToolCall/toolValidationProcessor.d.ts +58 -0
- package/dist/processor-pieces/preToolCall/toolValidationProcessor.js +391 -0
- package/dist/unified/agent/agent.js +2 -2
- package/dist/unified/agent/tool.d.ts +99 -0
- package/dist/unified/agent/tool.js +440 -0
- package/dist/unified/base/initialPromptGenerator.js +5 -5
- package/dist/unified/base/responseExecutor.js +6 -6
- package/dist/unified/examples/agentExample.d.ts +46 -0
- package/dist/unified/examples/agentExample.js +464 -0
- package/dist/unified/examples/documentationPatternExample.d.ts +10 -0
- package/dist/unified/examples/documentationPatternExample.js +385 -0
- package/dist/unified/examples/followUpProcessorsExample.d.ts +45 -0
- package/dist/unified/examples/followUpProcessorsExample.js +311 -0
- package/dist/unified/examples/orchestratorExample.d.ts +16 -0
- package/dist/unified/examples/orchestratorExample.js +415 -0
- package/dist/unified/examples/preToolCallProcessorsExample.d.ts +36 -0
- package/dist/unified/examples/preToolCallProcessorsExample.js +458 -0
- package/dist/unified/examples/workflowExample.d.ts +12 -0
- package/dist/unified/examples/workflowExample.js +497 -0
- package/dist/unified/orchestrator/orchestrator.d.ts +260 -0
- package/dist/unified/orchestrator/orchestrator.js +519 -0
- package/package.json +15 -15
- package/dist/agent.d.ts +0 -86
- package/dist/agent.js +0 -324
- package/dist/followupquestionbuilder.d.ts +0 -75
- package/dist/followupquestionbuilder.js +0 -197
- package/dist/index.d.ts +0 -14
- package/dist/index.js +0 -23
- package/dist/llmoutputhandler.d.ts +0 -102
- package/dist/llmoutputhandler.js +0 -452
- package/dist/promptbuilder.d.ts +0 -382
- package/dist/promptbuilder.js +0 -805
- package/dist/systemprompt.d.ts +0 -20
- package/dist/systemprompt.js +0 -48
- package/dist/taskInstruction.d.ts +0 -37
- package/dist/taskInstruction.js +0 -57
- package/dist/usermessage.d.ts +0 -70
- package/dist/usermessage.js +0 -123
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Unified Orchestrator for Multi-Agent, Multi-Workflow, Multi-Tool Coordination
|
|
4
|
+
*
|
|
5
|
+
* The Orchestrator can dynamically choose and execute agents, workflows, and tools
|
|
6
|
+
* in any order based on context and user input. Unlike workflows which have fixed
|
|
7
|
+
* execution order, the orchestrator makes intelligent decisions about what to execute.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.UnifiedOrchestrator = void 0;
|
|
11
|
+
exports.createOrchestrator = createOrchestrator;
|
|
12
|
+
exports.createRuntimeContext = createRuntimeContext;
|
|
13
|
+
const zod_1 = require("zod");
|
|
14
|
+
const agent_1 = require("../agent/agent");
|
|
15
|
+
const tool_1 = require("../agent/tool");
|
|
16
|
+
// ================================
|
|
17
|
+
// Orchestrator Implementation
|
|
18
|
+
// ================================
|
|
19
|
+
/**
|
|
20
|
+
* Main Orchestrator class for coordinating agents, workflows, and tools
|
|
21
|
+
*/
|
|
22
|
+
class UnifiedOrchestrator {
|
|
23
|
+
constructor(config, codebolt) {
|
|
24
|
+
this.config = {
|
|
25
|
+
limits: {
|
|
26
|
+
maxSteps: 20,
|
|
27
|
+
maxExecutionTime: 600000, // 10 minutes
|
|
28
|
+
maxMemoryUsage: 100 * 1024 * 1024 // 100MB
|
|
29
|
+
},
|
|
30
|
+
decisionConfig: {
|
|
31
|
+
explainDecisions: true,
|
|
32
|
+
confidenceThreshold: 0.7,
|
|
33
|
+
askConfirmation: false
|
|
34
|
+
},
|
|
35
|
+
memory: {
|
|
36
|
+
persistent: false,
|
|
37
|
+
maxSize: 1000,
|
|
38
|
+
ttl: 3600000 // 1 hour
|
|
39
|
+
},
|
|
40
|
+
...config
|
|
41
|
+
};
|
|
42
|
+
this.codebolt = codebolt;
|
|
43
|
+
// Create decision-making agent
|
|
44
|
+
this.decisionAgent = this.createDecisionAgent();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Create the internal decision-making agent
|
|
48
|
+
*/
|
|
49
|
+
createDecisionAgent() {
|
|
50
|
+
const decisionTool = (0, tool_1.createTool)({
|
|
51
|
+
id: 'make-orchestration-decision',
|
|
52
|
+
name: 'Make Orchestration Decision',
|
|
53
|
+
description: 'Decide what resource to execute next in the orchestration',
|
|
54
|
+
inputSchema: zod_1.z.object({
|
|
55
|
+
userMessage: zod_1.z.string(),
|
|
56
|
+
availableAgents: zod_1.z.array(zod_1.z.string()),
|
|
57
|
+
availableWorkflows: zod_1.z.array(zod_1.z.string()),
|
|
58
|
+
availableTools: zod_1.z.array(zod_1.z.string()),
|
|
59
|
+
executionHistory: zod_1.z.array(zod_1.z.object({
|
|
60
|
+
stepType: zod_1.z.string(),
|
|
61
|
+
resourceId: zod_1.z.string(),
|
|
62
|
+
success: zod_1.z.boolean(),
|
|
63
|
+
output: zod_1.z.unknown()
|
|
64
|
+
})),
|
|
65
|
+
contextData: zod_1.z.record(zod_1.z.unknown())
|
|
66
|
+
}),
|
|
67
|
+
execute: async ({ input }) => {
|
|
68
|
+
// This is a placeholder - in a real implementation, this would use
|
|
69
|
+
// sophisticated decision logic or ML models
|
|
70
|
+
const { userMessage, availableAgents, availableWorkflows, availableTools, executionHistory } = input;
|
|
71
|
+
// Simple heuristic-based decision making
|
|
72
|
+
if (executionHistory.length === 0) {
|
|
73
|
+
// First step - analyze what type of task this is
|
|
74
|
+
if (userMessage.toLowerCase().includes('workflow') || userMessage.toLowerCase().includes('process')) {
|
|
75
|
+
return {
|
|
76
|
+
resourceType: 'workflow',
|
|
77
|
+
resourceId: availableWorkflows[0],
|
|
78
|
+
reasoning: 'User mentioned workflow/process, starting with first available workflow',
|
|
79
|
+
confidence: 0.8,
|
|
80
|
+
isComplete: false
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
else if (availableAgents.length > 0) {
|
|
84
|
+
return {
|
|
85
|
+
resourceType: 'agent',
|
|
86
|
+
resourceId: availableAgents[0],
|
|
87
|
+
reasoning: 'Starting with first available agent for general task',
|
|
88
|
+
confidence: 0.7,
|
|
89
|
+
isComplete: false
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// Check if we have enough information to complete
|
|
94
|
+
const lastStep = executionHistory[executionHistory.length - 1];
|
|
95
|
+
if (lastStep && lastStep.success) {
|
|
96
|
+
return {
|
|
97
|
+
resourceType: 'complete',
|
|
98
|
+
reasoning: 'Task appears to be completed successfully',
|
|
99
|
+
confidence: 0.9,
|
|
100
|
+
isComplete: true
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
resourceType: 'complete',
|
|
105
|
+
reasoning: 'No clear next step identified',
|
|
106
|
+
confidence: 0.5,
|
|
107
|
+
isComplete: true
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
return new agent_1.Agent({
|
|
112
|
+
name: 'Orchestrator Decision Agent',
|
|
113
|
+
instructions: `${this.config.instructions}
|
|
114
|
+
|
|
115
|
+
You are the decision-making component of an orchestrator. Your job is to analyze the current situation and decide what resource (agent, workflow, or tool) should be executed next.
|
|
116
|
+
|
|
117
|
+
Available resources:
|
|
118
|
+
- Agents: ${Object.keys(this.config.agents).join(', ')}
|
|
119
|
+
- Workflows: ${Object.keys(this.config.workflows).join(', ')}
|
|
120
|
+
- Tools: ${Object.keys(this.config.tools || {}).join(', ')}
|
|
121
|
+
|
|
122
|
+
Consider:
|
|
123
|
+
1. The user's request and intent
|
|
124
|
+
2. What has already been executed
|
|
125
|
+
3. What information or capabilities are needed next
|
|
126
|
+
4. Whether the task is complete
|
|
127
|
+
|
|
128
|
+
Always use the make-orchestration-decision tool to provide structured decisions.`,
|
|
129
|
+
tools: [decisionTool],
|
|
130
|
+
llmConfig: this.config.llmConfig
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Execute orchestration loop
|
|
135
|
+
*/
|
|
136
|
+
async loop(userMessage, options = {}) {
|
|
137
|
+
const startTime = Date.now();
|
|
138
|
+
// Initialize runtime context
|
|
139
|
+
const context = this.initializeRuntimeContext(userMessage, options.runtimeContext);
|
|
140
|
+
try {
|
|
141
|
+
// Apply processors if configured
|
|
142
|
+
if (this.config.processors) {
|
|
143
|
+
await this.applyProcessors(userMessage, context);
|
|
144
|
+
}
|
|
145
|
+
// Main orchestration loop
|
|
146
|
+
while (!this.shouldStop(context)) {
|
|
147
|
+
const decision = await this.makeDecision(userMessage, context);
|
|
148
|
+
if (decision.isComplete) {
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
await this.executeDecision(decision, context);
|
|
152
|
+
context.currentStep++;
|
|
153
|
+
}
|
|
154
|
+
const totalExecutionTime = Date.now() - startTime;
|
|
155
|
+
return this.createSuccessResult(context, totalExecutionTime);
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
const totalExecutionTime = Date.now() - startTime;
|
|
159
|
+
return this.createErrorResult(context, error, totalExecutionTime);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Initialize runtime context
|
|
164
|
+
*/
|
|
165
|
+
initializeRuntimeContext(userMessage, partial) {
|
|
166
|
+
var _a;
|
|
167
|
+
return {
|
|
168
|
+
sessionId: (partial === null || partial === void 0 ? void 0 : partial.sessionId) || this.generateSessionId(),
|
|
169
|
+
userId: partial === null || partial === void 0 ? void 0 : partial.userId,
|
|
170
|
+
conversationState: (partial === null || partial === void 0 ? void 0 : partial.conversationState) || { userMessage },
|
|
171
|
+
executionHistory: (partial === null || partial === void 0 ? void 0 : partial.executionHistory) || [],
|
|
172
|
+
memory: (partial === null || partial === void 0 ? void 0 : partial.memory) || new Map(),
|
|
173
|
+
currentStep: (partial === null || partial === void 0 ? void 0 : partial.currentStep) || 0,
|
|
174
|
+
maxSteps: (partial === null || partial === void 0 ? void 0 : partial.maxSteps) || ((_a = this.config.limits) === null || _a === void 0 ? void 0 : _a.maxSteps) || 20,
|
|
175
|
+
startTime: new Date().toISOString(),
|
|
176
|
+
customData: (partial === null || partial === void 0 ? void 0 : partial.customData) || {}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Generate unique session ID
|
|
181
|
+
*/
|
|
182
|
+
generateSessionId() {
|
|
183
|
+
return `orch_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Apply orchestrator processors
|
|
187
|
+
*/
|
|
188
|
+
async applyProcessors(userMessage, context) {
|
|
189
|
+
if (!this.config.processors)
|
|
190
|
+
return;
|
|
191
|
+
for (const processor of this.config.processors) {
|
|
192
|
+
try {
|
|
193
|
+
const input = {
|
|
194
|
+
message: {
|
|
195
|
+
messages: [{
|
|
196
|
+
role: 'user',
|
|
197
|
+
content: userMessage
|
|
198
|
+
}],
|
|
199
|
+
metadata: {
|
|
200
|
+
sessionId: context.sessionId,
|
|
201
|
+
step: context.currentStep
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
context: context.conversationState
|
|
205
|
+
};
|
|
206
|
+
await processor.processInput(input);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
console.warn('Orchestrator processor failed:', error);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Make orchestration decision
|
|
215
|
+
*/
|
|
216
|
+
async makeDecision(userMessage, context) {
|
|
217
|
+
const decisionInput = {
|
|
218
|
+
userMessage,
|
|
219
|
+
availableAgents: Object.keys(this.config.agents),
|
|
220
|
+
availableWorkflows: Object.keys(this.config.workflows),
|
|
221
|
+
availableTools: Object.keys(this.config.tools || {}),
|
|
222
|
+
executionHistory: context.executionHistory.map(step => ({
|
|
223
|
+
stepType: step.stepType,
|
|
224
|
+
resourceId: step.resourceId,
|
|
225
|
+
success: step.success,
|
|
226
|
+
output: step.output
|
|
227
|
+
})),
|
|
228
|
+
contextData: context.conversationState
|
|
229
|
+
};
|
|
230
|
+
const result = await this.decisionAgent.execute(`Analyze the current situation and decide what to execute next: ${JSON.stringify(decisionInput)}`);
|
|
231
|
+
// Extract decision from agent response
|
|
232
|
+
// In a real implementation, this would parse the structured tool output
|
|
233
|
+
const decision = {
|
|
234
|
+
resourceType: 'agent', // Default fallback
|
|
235
|
+
resourceId: Object.keys(this.config.agents)[0],
|
|
236
|
+
reasoning: 'Default decision - execute first available agent',
|
|
237
|
+
confidence: 0.5,
|
|
238
|
+
isComplete: context.currentStep >= context.maxSteps,
|
|
239
|
+
input: { message: userMessage, context: context.conversationState }
|
|
240
|
+
};
|
|
241
|
+
// Record decision in execution history
|
|
242
|
+
context.executionHistory.push({
|
|
243
|
+
stepId: `decision_${context.currentStep}`,
|
|
244
|
+
stepType: 'decision',
|
|
245
|
+
resourceId: 'decision-agent',
|
|
246
|
+
resourceName: 'Decision Making',
|
|
247
|
+
input: decisionInput,
|
|
248
|
+
output: decision,
|
|
249
|
+
success: true,
|
|
250
|
+
executionTime: 0,
|
|
251
|
+
timestamp: new Date().toISOString(),
|
|
252
|
+
metadata: { confidence: decision.confidence }
|
|
253
|
+
});
|
|
254
|
+
return decision;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Execute orchestration decision
|
|
258
|
+
*/
|
|
259
|
+
async executeDecision(decision, context) {
|
|
260
|
+
var _a, _b;
|
|
261
|
+
const stepId = `step_${context.currentStep}`;
|
|
262
|
+
const startTime = Date.now();
|
|
263
|
+
try {
|
|
264
|
+
let result;
|
|
265
|
+
let resourceName;
|
|
266
|
+
switch (decision.resourceType) {
|
|
267
|
+
case 'agent':
|
|
268
|
+
if (!decision.resourceId || !this.config.agents[decision.resourceId]) {
|
|
269
|
+
throw new Error(`Agent not found: ${decision.resourceId}`);
|
|
270
|
+
}
|
|
271
|
+
const agent = this.config.agents[decision.resourceId];
|
|
272
|
+
resourceName = agent.config.name;
|
|
273
|
+
const agentInput = typeof decision.input === 'object' && decision.input && 'message' in decision.input
|
|
274
|
+
? decision.input.message
|
|
275
|
+
: String(decision.input);
|
|
276
|
+
result = await agent.execute(agentInput);
|
|
277
|
+
break;
|
|
278
|
+
case 'workflow':
|
|
279
|
+
if (!decision.resourceId || !this.config.workflows[decision.resourceId]) {
|
|
280
|
+
throw new Error(`Workflow not found: ${decision.resourceId}`);
|
|
281
|
+
}
|
|
282
|
+
const workflow = this.config.workflows[decision.resourceId];
|
|
283
|
+
resourceName = `Workflow: ${decision.resourceId}`;
|
|
284
|
+
// Update workflow context with current data
|
|
285
|
+
if (decision.input && typeof decision.input === 'object') {
|
|
286
|
+
workflow.updateContext(decision.input);
|
|
287
|
+
}
|
|
288
|
+
result = await workflow.execute();
|
|
289
|
+
break;
|
|
290
|
+
case 'tool':
|
|
291
|
+
if (!decision.resourceId || !((_a = this.config.tools) === null || _a === void 0 ? void 0 : _a[decision.resourceId])) {
|
|
292
|
+
throw new Error(`Tool not found: ${decision.resourceId}`);
|
|
293
|
+
}
|
|
294
|
+
const tool = this.config.tools[decision.resourceId];
|
|
295
|
+
resourceName = tool.function.name;
|
|
296
|
+
result = await (0, tool_1.executeTool)(tool, decision.input, this.codebolt);
|
|
297
|
+
break;
|
|
298
|
+
default:
|
|
299
|
+
throw new Error(`Unknown resource type: ${decision.resourceType}`);
|
|
300
|
+
}
|
|
301
|
+
// Record successful execution
|
|
302
|
+
const executionStep = {
|
|
303
|
+
stepId,
|
|
304
|
+
stepType: decision.resourceType,
|
|
305
|
+
resourceId: decision.resourceId,
|
|
306
|
+
resourceName,
|
|
307
|
+
input: decision.input,
|
|
308
|
+
output: result,
|
|
309
|
+
success: true,
|
|
310
|
+
executionTime: Date.now() - startTime,
|
|
311
|
+
timestamp: new Date().toISOString(),
|
|
312
|
+
metadata: {
|
|
313
|
+
reasoning: decision.reasoning,
|
|
314
|
+
confidence: decision.confidence
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
context.executionHistory.push(executionStep);
|
|
318
|
+
// Update conversation state with results
|
|
319
|
+
if (result && typeof result === 'object') {
|
|
320
|
+
context.conversationState = {
|
|
321
|
+
...context.conversationState,
|
|
322
|
+
[`${decision.resourceType}_${decision.resourceId}_result`]: result
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
// Update memory if configured
|
|
326
|
+
if ((_b = this.config.memory) === null || _b === void 0 ? void 0 : _b.persistent) {
|
|
327
|
+
context.memory.set(`step_${context.currentStep}`, result);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
// Record failed execution
|
|
332
|
+
const executionStep = {
|
|
333
|
+
stepId,
|
|
334
|
+
stepType: decision.resourceType,
|
|
335
|
+
resourceId: decision.resourceId || 'unknown',
|
|
336
|
+
resourceName: decision.resourceId || 'Unknown Resource',
|
|
337
|
+
input: decision.input,
|
|
338
|
+
output: null,
|
|
339
|
+
success: false,
|
|
340
|
+
error: error instanceof Error ? error.message : String(error),
|
|
341
|
+
executionTime: Date.now() - startTime,
|
|
342
|
+
timestamp: new Date().toISOString(),
|
|
343
|
+
metadata: {
|
|
344
|
+
reasoning: decision.reasoning,
|
|
345
|
+
confidence: decision.confidence
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
context.executionHistory.push(executionStep);
|
|
349
|
+
throw error; // Re-throw to be handled by main loop
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Check if orchestration should stop
|
|
354
|
+
*/
|
|
355
|
+
shouldStop(context) {
|
|
356
|
+
var _a, _b;
|
|
357
|
+
// Stop if max steps reached
|
|
358
|
+
if (context.currentStep >= context.maxSteps) {
|
|
359
|
+
return true;
|
|
360
|
+
}
|
|
361
|
+
// Stop if max execution time reached
|
|
362
|
+
const elapsed = Date.now() - new Date(context.startTime).getTime();
|
|
363
|
+
if (((_a = this.config.limits) === null || _a === void 0 ? void 0 : _a.maxExecutionTime) && elapsed > this.config.limits.maxExecutionTime) {
|
|
364
|
+
return true;
|
|
365
|
+
}
|
|
366
|
+
// Stop if memory limit reached
|
|
367
|
+
if ((_b = this.config.limits) === null || _b === void 0 ? void 0 : _b.maxMemoryUsage) {
|
|
368
|
+
const memoryUsage = this.estimateMemoryUsage(context);
|
|
369
|
+
if (memoryUsage > this.config.limits.maxMemoryUsage) {
|
|
370
|
+
return true;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return false;
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Estimate memory usage (simplified)
|
|
377
|
+
*/
|
|
378
|
+
estimateMemoryUsage(context) {
|
|
379
|
+
return JSON.stringify(context).length * 2; // Rough estimate
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Create successful orchestration result
|
|
383
|
+
*/
|
|
384
|
+
createSuccessResult(context, totalExecutionTime) {
|
|
385
|
+
const metrics = this.calculateMetrics(context);
|
|
386
|
+
// Generate final response based on execution history
|
|
387
|
+
const finalResponse = this.generateFinalResponse(context);
|
|
388
|
+
return {
|
|
389
|
+
sessionId: context.sessionId,
|
|
390
|
+
success: true,
|
|
391
|
+
response: finalResponse,
|
|
392
|
+
executionSteps: context.executionHistory,
|
|
393
|
+
finalContext: context,
|
|
394
|
+
totalExecutionTime,
|
|
395
|
+
metrics
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Create error orchestration result
|
|
400
|
+
*/
|
|
401
|
+
createErrorResult(context, error, totalExecutionTime) {
|
|
402
|
+
const metrics = this.calculateMetrics(context);
|
|
403
|
+
return {
|
|
404
|
+
sessionId: context.sessionId,
|
|
405
|
+
success: false,
|
|
406
|
+
response: `Orchestration failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
407
|
+
executionSteps: context.executionHistory,
|
|
408
|
+
finalContext: context,
|
|
409
|
+
totalExecutionTime,
|
|
410
|
+
error: error instanceof Error ? error.message : String(error),
|
|
411
|
+
metrics
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Calculate orchestration metrics
|
|
416
|
+
*/
|
|
417
|
+
calculateMetrics(context) {
|
|
418
|
+
const steps = context.executionHistory;
|
|
419
|
+
return {
|
|
420
|
+
totalSteps: steps.length,
|
|
421
|
+
agentsExecuted: steps.filter(s => s.stepType === 'agent').length,
|
|
422
|
+
workflowsExecuted: steps.filter(s => s.stepType === 'workflow').length,
|
|
423
|
+
toolsExecuted: steps.filter(s => s.stepType === 'tool').length,
|
|
424
|
+
decisionsMade: steps.filter(s => s.stepType === 'decision').length,
|
|
425
|
+
averageConfidence: this.calculateAverageConfidence(steps),
|
|
426
|
+
memoryOperations: context.memory.size
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Calculate average confidence from decisions
|
|
431
|
+
*/
|
|
432
|
+
calculateAverageConfidence(steps) {
|
|
433
|
+
const decisions = steps.filter(s => s.stepType === 'decision' && s.metadata.confidence);
|
|
434
|
+
if (decisions.length === 0)
|
|
435
|
+
return 0;
|
|
436
|
+
const totalConfidence = decisions.reduce((sum, step) => sum + step.metadata.confidence, 0);
|
|
437
|
+
return totalConfidence / decisions.length;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Generate final response based on execution history
|
|
441
|
+
*/
|
|
442
|
+
generateFinalResponse(context) {
|
|
443
|
+
const successfulSteps = context.executionHistory.filter(s => s.success && s.stepType !== 'decision');
|
|
444
|
+
if (successfulSteps.length === 0) {
|
|
445
|
+
return "I wasn't able to complete any tasks successfully.";
|
|
446
|
+
}
|
|
447
|
+
const lastStep = successfulSteps[successfulSteps.length - 1];
|
|
448
|
+
// Extract meaningful response from the last successful step
|
|
449
|
+
if (lastStep.output && typeof lastStep.output === 'object') {
|
|
450
|
+
const output = lastStep.output;
|
|
451
|
+
if ('response' in output && typeof output.response === 'string') {
|
|
452
|
+
return output.response;
|
|
453
|
+
}
|
|
454
|
+
if ('result' in output && typeof output.result === 'string') {
|
|
455
|
+
return output.result;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return `Completed orchestration with ${successfulSteps.length} successful steps. The final step was executed by ${lastStep.resourceName}.`;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Add agent to orchestrator
|
|
462
|
+
*/
|
|
463
|
+
addAgent(id, agent) {
|
|
464
|
+
this.config.agents[id] = agent;
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Add workflow to orchestrator
|
|
468
|
+
*/
|
|
469
|
+
addWorkflow(id, workflow) {
|
|
470
|
+
this.config.workflows[id] = workflow;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Add tool to orchestrator
|
|
474
|
+
*/
|
|
475
|
+
addTool(id, tool) {
|
|
476
|
+
if (!this.config.tools) {
|
|
477
|
+
this.config.tools = {};
|
|
478
|
+
}
|
|
479
|
+
this.config.tools[id] = tool;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Get orchestrator configuration
|
|
483
|
+
*/
|
|
484
|
+
getConfig() {
|
|
485
|
+
return { ...this.config };
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Update orchestrator configuration
|
|
489
|
+
*/
|
|
490
|
+
updateConfig(updates) {
|
|
491
|
+
this.config = { ...this.config, ...updates };
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
exports.UnifiedOrchestrator = UnifiedOrchestrator;
|
|
495
|
+
// ================================
|
|
496
|
+
// Factory Functions
|
|
497
|
+
// ================================
|
|
498
|
+
/**
|
|
499
|
+
* Create a new orchestrator instance
|
|
500
|
+
*/
|
|
501
|
+
function createOrchestrator(config, codebolt) {
|
|
502
|
+
return new UnifiedOrchestrator(config, codebolt);
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Create runtime context
|
|
506
|
+
*/
|
|
507
|
+
function createRuntimeContext(options = {}) {
|
|
508
|
+
return {
|
|
509
|
+
sessionId: options.sessionId || `ctx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
|
510
|
+
userId: options.userId,
|
|
511
|
+
conversationState: options.conversationState || {},
|
|
512
|
+
executionHistory: options.executionHistory || [],
|
|
513
|
+
memory: options.memory || new Map(),
|
|
514
|
+
currentStep: options.currentStep || 0,
|
|
515
|
+
maxSteps: options.maxSteps || 20,
|
|
516
|
+
startTime: options.startTime || new Date().toISOString(),
|
|
517
|
+
customData: options.customData || {}
|
|
518
|
+
};
|
|
519
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codebolt/agent",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.3",
|
|
4
4
|
"description": "CodeBolt Agent utilities for building and managing AI agents",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -9,6 +9,13 @@
|
|
|
9
9
|
"README.md",
|
|
10
10
|
"LICENSE"
|
|
11
11
|
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsc",
|
|
14
|
+
"clean": "rm -rf dist",
|
|
15
|
+
"dev": "tsc --watch",
|
|
16
|
+
"test": "echo \"No tests yet, but build passes\" && exit 0",
|
|
17
|
+
"lint:test": "eslint src/**/*.ts && tsc --noEmit"
|
|
18
|
+
},
|
|
12
19
|
"keywords": [
|
|
13
20
|
"ai",
|
|
14
21
|
"agent",
|
|
@@ -28,21 +35,21 @@
|
|
|
28
35
|
"directory": "packages/agent"
|
|
29
36
|
},
|
|
30
37
|
"dependencies": {
|
|
38
|
+
"@codebolt/types": "workspace:*",
|
|
31
39
|
"js-yaml": "^4.1.0",
|
|
32
|
-
"zod": "^3.22.4"
|
|
33
|
-
"@codebolt/types": "1.0.16"
|
|
40
|
+
"zod": "^3.22.4"
|
|
34
41
|
},
|
|
35
42
|
"peerDependencies": {
|
|
36
|
-
"@codebolt/codeboltjs": "
|
|
43
|
+
"@codebolt/codeboltjs": "workspace:*"
|
|
37
44
|
},
|
|
38
45
|
"devDependencies": {
|
|
46
|
+
"@codebolt/codeboltjs": "workspace:*",
|
|
47
|
+
"@codebolt/types": "workspace:*",
|
|
39
48
|
"@types/js-yaml": "^4.0.9",
|
|
40
49
|
"@types/node": "^20.14.2",
|
|
41
50
|
"@types/uri-templates": "^0.1.34",
|
|
42
51
|
"@types/ws": "^8.5.10",
|
|
43
|
-
"typescript": "^5.4.5"
|
|
44
|
-
"@codebolt/codeboltjs": "2.2.2",
|
|
45
|
-
"@codebolt/types": "1.0.16"
|
|
52
|
+
"typescript": "^5.4.5"
|
|
46
53
|
},
|
|
47
54
|
"exports": {
|
|
48
55
|
"./builder": {
|
|
@@ -65,12 +72,5 @@
|
|
|
65
72
|
"types": "./dist/unified/index.d.ts",
|
|
66
73
|
"default": "./dist/unified/index.js"
|
|
67
74
|
}
|
|
68
|
-
},
|
|
69
|
-
"scripts": {
|
|
70
|
-
"build": "tsc",
|
|
71
|
-
"clean": "rm -rf dist",
|
|
72
|
-
"dev": "tsc --watch",
|
|
73
|
-
"test": "echo \"No tests yet, but build passes\" && exit 0",
|
|
74
|
-
"lint:test": "eslint src/**/*.ts && tsc --noEmit"
|
|
75
75
|
}
|
|
76
|
-
}
|
|
76
|
+
}
|
package/dist/agent.d.ts
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { SystemPrompt } from "./systemprompt";
|
|
2
|
-
import { TaskInstruction } from "./taskInstruction";
|
|
3
|
-
/**
|
|
4
|
-
* Agent class that manages conversations with LLMs and tool executions.
|
|
5
|
-
* Handles the conversation flow, tool calls, and task completions.
|
|
6
|
-
*/
|
|
7
|
-
declare class Agent {
|
|
8
|
-
/** Available tools for the agent to use */
|
|
9
|
-
private tools;
|
|
10
|
-
/** Full conversation history for API calls */
|
|
11
|
-
private apiConversationHistory;
|
|
12
|
-
/** Maximum number of conversation turns (0 means unlimited) */
|
|
13
|
-
private maxRun;
|
|
14
|
-
/** System prompt that provides instructions to the model */
|
|
15
|
-
private systemPrompt;
|
|
16
|
-
/** Messages from the user */
|
|
17
|
-
private userMessage;
|
|
18
|
-
/** The next user message to be added to the conversation */
|
|
19
|
-
private nextUserMessage;
|
|
20
|
-
/**
|
|
21
|
-
* Creates a new Agent instance.
|
|
22
|
-
*
|
|
23
|
-
* @param tools - The tools available to the agent
|
|
24
|
-
* @param systemPrompt - The system prompt providing instructions to the LLM
|
|
25
|
-
* @param maxRun - Maximum number of conversation turns (0 means unlimited)
|
|
26
|
-
*/
|
|
27
|
-
constructor(tools: any | undefined, systemPrompt: SystemPrompt, maxRun?: number);
|
|
28
|
-
/**
|
|
29
|
-
* Runs the agent on a specific task until completion or max runs reached.
|
|
30
|
-
*
|
|
31
|
-
* @param task - The task instruction to be executed
|
|
32
|
-
* @param successCondition - Optional function to determine if the task is successful
|
|
33
|
-
* @returns Promise with success status, error (if any), and the last assistant message
|
|
34
|
-
*/
|
|
35
|
-
run(task: TaskInstruction, successCondition?: () => boolean): Promise<{
|
|
36
|
-
success: boolean;
|
|
37
|
-
error: string | null;
|
|
38
|
-
message: string | null;
|
|
39
|
-
}>;
|
|
40
|
-
/**
|
|
41
|
-
* Attempts to make a request to the LLM with conversation history and tools.
|
|
42
|
-
*
|
|
43
|
-
* @param apiConversationHistory - The current conversation history
|
|
44
|
-
* @param tools - The tools available to the LLM
|
|
45
|
-
* @returns Promise with the LLM response
|
|
46
|
-
*/
|
|
47
|
-
private attemptLlmRequest;
|
|
48
|
-
/**
|
|
49
|
-
* Executes a tool with given name and input.
|
|
50
|
-
*
|
|
51
|
-
* @param toolName - The name of the tool to execute
|
|
52
|
-
* @param toolInput - The input parameters for the tool
|
|
53
|
-
* @returns Promise with tuple [userRejected, result]
|
|
54
|
-
*/
|
|
55
|
-
private executeTool;
|
|
56
|
-
/**
|
|
57
|
-
* Starts a sub-agent to handle a specific task.
|
|
58
|
-
*
|
|
59
|
-
* @param agentName - The name of the sub-agent to start
|
|
60
|
-
* @param params - Parameters for the sub-agent
|
|
61
|
-
* @returns Promise with tuple [userRejected, result]
|
|
62
|
-
*/
|
|
63
|
-
private startSubAgent;
|
|
64
|
-
/**
|
|
65
|
-
* Extracts tool details from a tool call object.
|
|
66
|
-
*
|
|
67
|
-
* @param tool - The tool call object from the LLM response
|
|
68
|
-
* @returns ToolDetails object with name, input, and ID
|
|
69
|
-
*/
|
|
70
|
-
private getToolDetail;
|
|
71
|
-
/**
|
|
72
|
-
* Creates a tool result object from the tool execution response.
|
|
73
|
-
*
|
|
74
|
-
* @param tool_call_id - The ID of the tool call
|
|
75
|
-
* @param content - The content returned by the tool
|
|
76
|
-
* @returns ToolResult object
|
|
77
|
-
*/
|
|
78
|
-
private getToolResult;
|
|
79
|
-
/**
|
|
80
|
-
* Fallback method for API requests in case of failures.
|
|
81
|
-
*
|
|
82
|
-
* @throws Error API request fallback not implemented
|
|
83
|
-
*/
|
|
84
|
-
private attemptApiRequest;
|
|
85
|
-
}
|
|
86
|
-
export { Agent };
|