@minded-ai/mindedjs 1.0.128 → 1.0.130
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/agent.d.ts +7 -4
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +45 -72
- package/dist/agent.js.map +1 -1
- package/dist/browserTask/executeBrowserTask.d.ts +2 -13
- package/dist/browserTask/executeBrowserTask.d.ts.map +1 -1
- package/dist/browserTask/executeBrowserTask.js +9 -180
- package/dist/browserTask/executeBrowserTask.js.map +1 -1
- package/dist/debugging/index.d.ts +2 -0
- package/dist/debugging/index.d.ts.map +1 -0
- package/dist/debugging/index.js +6 -0
- package/dist/debugging/index.js.map +1 -0
- package/dist/debugging/llmCallbackHandler.d.ts +83 -0
- package/dist/debugging/llmCallbackHandler.d.ts.map +1 -0
- package/dist/debugging/llmCallbackHandler.js +102 -0
- package/dist/debugging/llmCallbackHandler.js.map +1 -0
- package/dist/nodes/addBrowserTaskNode.d.ts.map +1 -1
- package/dist/nodes/addBrowserTaskNode.js +2 -1
- package/dist/nodes/addBrowserTaskNode.js.map +1 -1
- package/dist/nodes/addBrowserTaskRunNode.d.ts +1 -1
- package/dist/nodes/addBrowserTaskRunNode.d.ts.map +1 -1
- package/dist/nodes/addBrowserTaskRunNode.js +10 -2
- package/dist/nodes/addBrowserTaskRunNode.js.map +1 -1
- package/dist/platform/mindedConnectionTypes.d.ts +28 -1
- package/dist/platform/mindedConnectionTypes.d.ts.map +1 -1
- package/dist/platform/mindedConnectionTypes.js +2 -0
- package/dist/platform/mindedConnectionTypes.js.map +1 -1
- package/dist/platform/toolExecutor.d.ts +29 -0
- package/dist/platform/toolExecutor.d.ts.map +1 -0
- package/dist/platform/toolExecutor.js +95 -0
- package/dist/platform/toolExecutor.js.map +1 -0
- package/dist/platform/utils/tools.d.ts +6 -0
- package/dist/platform/utils/tools.d.ts.map +1 -0
- package/dist/platform/utils/tools.js +57 -0
- package/dist/platform/utils/tools.js.map +1 -0
- package/dist/types/Flows.types.d.ts +1 -0
- package/dist/types/Flows.types.d.ts.map +1 -1
- package/dist/types/Flows.types.js.map +1 -1
- package/dist/types/LangGraph.types.d.ts +2 -0
- package/dist/types/LangGraph.types.d.ts.map +1 -1
- package/dist/types/LangGraph.types.js +5 -0
- package/dist/types/LangGraph.types.js.map +1 -1
- package/dist/types/Tools.types.d.ts +3 -2
- package/dist/types/Tools.types.d.ts.map +1 -1
- package/dist/utils/agentUtils.d.ts +5 -0
- package/dist/utils/agentUtils.d.ts.map +1 -0
- package/dist/utils/agentUtils.js +86 -0
- package/dist/utils/agentUtils.js.map +1 -0
- package/dist/utils/history.d.ts +1 -0
- package/dist/utils/history.d.ts.map +1 -1
- package/dist/utils/history.js +20 -0
- package/dist/utils/history.js.map +1 -1
- package/docs/SUMMARY.md +1 -0
- package/docs/sdk/agent-api.md +524 -0
- package/docs/sdk/debugging.md +42 -306
- package/package.json +2 -2
- package/src/agent.ts +53 -103
- package/src/browserTask/executeBrowserTask.ts +11 -215
- package/src/debugging/index.ts +1 -0
- package/src/debugging/llmCallbackHandler.ts +126 -0
- package/src/nodes/addBrowserTaskNode.ts +3 -2
- package/src/nodes/addBrowserTaskRunNode.ts +21 -2
- package/src/platform/mindedConnectionTypes.ts +33 -1
- package/src/platform/toolExecutor.ts +118 -0
- package/src/platform/utils/tools.ts +55 -0
- package/src/types/Flows.types.ts +1 -0
- package/src/types/LangGraph.types.ts +5 -0
- package/src/types/Tools.types.ts +2 -1
- package/src/utils/agentUtils.ts +68 -0
- package/src/utils/history.ts +29 -1
package/docs/sdk/debugging.md
CHANGED
|
@@ -2,14 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
MindedJS provides comprehensive debugging capabilities to help you understand and troubleshoot your agent's behavior during development and production. This guide covers various debugging techniques and tools available in the SDK.
|
|
4
4
|
|
|
5
|
+
## Debug Logging
|
|
6
|
+
|
|
7
|
+
Set the log level to debug in your environment:
|
|
8
|
+
|
|
9
|
+
```env
|
|
10
|
+
LOG_LEVEL=debug
|
|
11
|
+
```
|
|
12
|
+
|
|
5
13
|
## Debugging Logical Conditions
|
|
6
14
|
|
|
7
|
-
|
|
15
|
+
You can debug and breakpoint on logical conditions during development:
|
|
8
16
|
|
|
9
17
|
```typescript
|
|
10
|
-
// Enable debug logging
|
|
11
|
-
// Set LOG_LEVEL=debug in your .env file
|
|
12
|
-
|
|
13
18
|
// Listen to condition evaluation events
|
|
14
19
|
import { AgentEvents } from 'mindedjs';
|
|
15
20
|
|
|
@@ -24,319 +29,50 @@ agent.on(AgentEvents.ON_LOGICAL_CONDITION_RESULT, async ({ condition, result, ex
|
|
|
24
29
|
});
|
|
25
30
|
```
|
|
26
31
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
#### 1. Trace Condition Evaluation
|
|
30
|
-
|
|
31
|
-
```typescript
|
|
32
|
-
// Log all condition evaluations with context
|
|
33
|
-
agent.on(AgentEvents.ON_LOGICAL_CONDITION, async ({ edge, state, condition }) => {
|
|
34
|
-
logger.debug('Evaluating edge condition', {
|
|
35
|
-
source: edge.source,
|
|
36
|
-
target: edge.target,
|
|
37
|
-
condition: condition,
|
|
38
|
-
memory: state.memory,
|
|
39
|
-
messageCount: state.messages.length,
|
|
40
|
-
});
|
|
41
|
-
});
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
#### 2. Debug Failed Conditions
|
|
45
|
-
|
|
46
|
-
```typescript
|
|
47
|
-
agent.on(AgentEvents.ON_LOGICAL_CONDITION_RESULT, async ({ condition, result, edge }) => {
|
|
48
|
-
if (!result) {
|
|
49
|
-
logger.warn('Condition failed', {
|
|
50
|
-
condition: condition,
|
|
51
|
-
edge: `${edge.source} -> ${edge.target}`,
|
|
52
|
-
// Log specific memory values referenced in the condition
|
|
53
|
-
relevantMemory: extractRelevantMemory(condition, state.memory),
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
});
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
#### 3. Performance Monitoring
|
|
60
|
-
|
|
61
|
-
```typescript
|
|
62
|
-
agent.on(AgentEvents.ON_LOGICAL_CONDITION_RESULT, async ({ condition, executionTimeMs }) => {
|
|
63
|
-
if (executionTimeMs > 10) {
|
|
64
|
-
logger.warn('Slow condition detected', {
|
|
65
|
-
condition: condition,
|
|
66
|
-
executionTimeMs: executionTimeMs,
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
});
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
## General Debugging Strategies
|
|
73
|
-
|
|
74
|
-
### 1. Enable Debug Logging
|
|
75
|
-
|
|
76
|
-
Set the log level to debug in your environment:
|
|
77
|
-
|
|
78
|
-
```env
|
|
79
|
-
LOG_LEVEL=debug
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
This will enable detailed logging throughout the MindedJS framework.
|
|
83
|
-
|
|
84
|
-
### 2. Use Structured Logging
|
|
85
|
-
|
|
86
|
-
Always use structured logging for better observability:
|
|
87
|
-
|
|
88
|
-
```typescript
|
|
89
|
-
import { logger } from 'mindedjs';
|
|
90
|
-
|
|
91
|
-
// Good: Structured logging with context
|
|
92
|
-
logger.debug('Processing user request', {
|
|
93
|
-
sessionId: state.sessionId,
|
|
94
|
-
userId: state.memory.userId,
|
|
95
|
-
requestType: 'order_inquiry',
|
|
96
|
-
timestamp: new Date().toISOString(),
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
// Avoid: Unstructured string logging
|
|
100
|
-
console.log('Processing request for user ' + userId);
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
### 3. Event-Driven Debugging
|
|
104
|
-
|
|
105
|
-
Leverage MindedJS events for comprehensive debugging:
|
|
106
|
-
|
|
107
|
-
```typescript
|
|
108
|
-
// Debug flow execution
|
|
109
|
-
agent.on(AgentEvents.NODE_START, async ({ nodeId, nodeType }) => {
|
|
110
|
-
logger.debug('Node execution started', { nodeId, nodeType });
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
// Debug tool calls
|
|
114
|
-
agent.on(AgentEvents.TOOL_START, async ({ toolName, input }) => {
|
|
115
|
-
logger.debug('Tool execution started', {
|
|
116
|
-
toolName,
|
|
117
|
-
input,
|
|
118
|
-
timestamp: Date.now(),
|
|
119
|
-
});
|
|
120
|
-
});
|
|
121
|
-
|
|
122
|
-
// Debug errors
|
|
123
|
-
agent.on(AgentEvents.ERROR, async ({ error, state }) => {
|
|
124
|
-
logger.error('Agent error', {
|
|
125
|
-
error: error.message,
|
|
126
|
-
stack: error.stack,
|
|
127
|
-
sessionId: state.sessionId,
|
|
128
|
-
lastNode: state.history[state.history.length - 1],
|
|
129
|
-
});
|
|
130
|
-
});
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
### 4. Memory State Inspection
|
|
134
|
-
|
|
135
|
-
Create helper functions to inspect memory state:
|
|
136
|
-
|
|
137
|
-
```typescript
|
|
138
|
-
function debugMemory(memory: any, path?: string) {
|
|
139
|
-
logger.debug('Memory state', {
|
|
140
|
-
path: path || 'root',
|
|
141
|
-
value: memory,
|
|
142
|
-
type: typeof memory,
|
|
143
|
-
keys: memory && typeof memory === 'object' ? Object.keys(memory) : null,
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
// Use in tools or event handlers
|
|
148
|
-
debugMemory(state.memory, 'full');
|
|
149
|
-
debugMemory(state.memory.user, 'user');
|
|
150
|
-
debugMemory(state.memory.order?.items, 'order.items');
|
|
151
|
-
```
|
|
32
|
+
## LLM Debug Callback Handler
|
|
152
33
|
|
|
153
|
-
|
|
34
|
+
A good practice is to periodically inspect the actual messages being sent to the LLM to ensure they match your expectations.
|
|
35
|
+
You can breakpoint and view the final prompt messages after compilation using `LLMDebugCallbackHandler`.
|
|
154
36
|
|
|
155
|
-
|
|
37
|
+
### Using the LLM Debug Callback Handler
|
|
156
38
|
|
|
157
39
|
```typescript
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
// Log trace on error or completion
|
|
179
|
-
agent.on(AgentEvents.ERROR, async () => {
|
|
180
|
-
logger.error('Execution trace at error', { trace: executionTrace });
|
|
181
|
-
});
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
## Development Tools
|
|
185
|
-
|
|
186
|
-
### 1. Local Testing Environment
|
|
187
|
-
|
|
188
|
-
Create a test harness for your agent:
|
|
189
|
-
|
|
190
|
-
```typescript
|
|
191
|
-
// test-agent.ts
|
|
192
|
-
import { Agent } from 'mindedjs';
|
|
193
|
-
import { config, tools, memorySchema } from './src';
|
|
194
|
-
|
|
195
|
-
async function testAgent() {
|
|
196
|
-
const agent = new Agent({ config, tools, memorySchema });
|
|
197
|
-
|
|
198
|
-
// Enable all debug events
|
|
199
|
-
Object.values(AgentEvents).forEach((event) => {
|
|
200
|
-
agent.on(event, async (data) => {
|
|
201
|
-
console.log(`[${event}]`, JSON.stringify(data, null, 2));
|
|
202
|
-
});
|
|
203
|
-
});
|
|
204
|
-
|
|
205
|
-
// Test with sample input
|
|
206
|
-
await agent.trigger('test-trigger', {
|
|
207
|
-
message: 'Test message',
|
|
208
|
-
userId: 'test-user',
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
testAgent().catch(console.error);
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
### 2. Memory Validation
|
|
216
|
-
|
|
217
|
-
Validate memory updates during development:
|
|
218
|
-
|
|
219
|
-
```typescript
|
|
220
|
-
import { z } from 'zod';
|
|
221
|
-
|
|
222
|
-
agent.on(AgentEvents.MEMORY_UPDATE, async ({ before, after, update }) => {
|
|
223
|
-
try {
|
|
224
|
-
// Validate against schema
|
|
225
|
-
memorySchema.parse(after);
|
|
226
|
-
|
|
227
|
-
// Log the changes
|
|
228
|
-
logger.debug('Memory updated', {
|
|
229
|
-
before: before,
|
|
230
|
-
update: update,
|
|
231
|
-
after: after,
|
|
232
|
-
});
|
|
233
|
-
} catch (error) {
|
|
234
|
-
logger.error('Invalid memory state after update', {
|
|
235
|
-
error: error.message,
|
|
236
|
-
update: update,
|
|
237
|
-
currentState: after,
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
});
|
|
241
|
-
```
|
|
242
|
-
|
|
243
|
-
### 3. Performance Profiling
|
|
244
|
-
|
|
245
|
-
Monitor performance bottlenecks:
|
|
246
|
-
|
|
247
|
-
```typescript
|
|
248
|
-
const performanceMetrics = new Map();
|
|
249
|
-
|
|
250
|
-
agent.on(AgentEvents.NODE_START, async ({ nodeId }) => {
|
|
251
|
-
performanceMetrics.set(nodeId, Date.now());
|
|
252
|
-
});
|
|
253
|
-
|
|
254
|
-
agent.on(AgentEvents.NODE_END, async ({ nodeId }) => {
|
|
255
|
-
const startTime = performanceMetrics.get(nodeId);
|
|
256
|
-
if (startTime) {
|
|
257
|
-
const duration = Date.now() - startTime;
|
|
258
|
-
logger.debug('Node execution time', {
|
|
259
|
-
nodeId,
|
|
260
|
-
durationMs: duration,
|
|
261
|
-
});
|
|
262
|
-
performanceMetrics.delete(nodeId);
|
|
263
|
-
}
|
|
264
|
-
});
|
|
265
|
-
```
|
|
266
|
-
|
|
267
|
-
## Production Debugging
|
|
268
|
-
|
|
269
|
-
### 1. Session-Based Debugging
|
|
270
|
-
|
|
271
|
-
Enable debugging for specific sessions:
|
|
272
|
-
|
|
273
|
-
```typescript
|
|
274
|
-
const debugSessions = new Set(process.env.DEBUG_SESSIONS?.split(',') || []);
|
|
275
|
-
|
|
276
|
-
agent.on(AgentEvents.INIT, async ({ state }) => {
|
|
277
|
-
if (debugSessions.has(state.sessionId)) {
|
|
278
|
-
// Enable verbose logging for this session
|
|
279
|
-
logger.setLevel('debug', state.sessionId);
|
|
280
|
-
}
|
|
40
|
+
import { Agent, LLMDebugCallbackHandler } from '@minded-ai/mindedjs';
|
|
41
|
+
|
|
42
|
+
// Create the debug handler
|
|
43
|
+
const debugHandler = new LLMDebugCallbackHandler();
|
|
44
|
+
|
|
45
|
+
// Configure your agent with the debug handler
|
|
46
|
+
const agent = new Agent({
|
|
47
|
+
config: {
|
|
48
|
+
...config,
|
|
49
|
+
llm: {
|
|
50
|
+
...config.llm,
|
|
51
|
+
properties: {
|
|
52
|
+
...config.llm.properties,
|
|
53
|
+
callbacks: [debugHandler],
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
tools,
|
|
58
|
+
memorySchema,
|
|
281
59
|
});
|
|
282
60
|
```
|
|
283
61
|
|
|
284
|
-
###
|
|
62
|
+
### Advanced Usage - Custom Debug Handler
|
|
285
63
|
|
|
286
|
-
|
|
64
|
+
You can extend the `LLMDebugCallbackHandler` to add your own debugging logic:
|
|
287
65
|
|
|
288
66
|
```typescript
|
|
289
|
-
|
|
67
|
+
import { LLMDebugCallbackHandler } from '@minded-ai/mindedjs';
|
|
290
68
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
69
|
+
class CustomDebugHandler extends LLMDebugCallbackHandler {
|
|
70
|
+
async handleLLMEnd(output: any, ...args: any[]): Promise<void> {
|
|
71
|
+
// Log token usage if available
|
|
72
|
+
const tokenUsage = output.llmOutput?.tokenUsage;
|
|
73
|
+
console.log(`Token usage: ${tokenUsage.totalTokens}`);
|
|
295
74
|
}
|
|
296
|
-
}
|
|
297
|
-
```
|
|
298
|
-
|
|
299
|
-
### 3. Error Context Collection
|
|
300
|
-
|
|
301
|
-
Collect comprehensive context on errors:
|
|
302
|
-
|
|
303
|
-
```typescript
|
|
304
|
-
agent.on(AgentEvents.ERROR, async ({ error, state }) => {
|
|
305
|
-
const errorContext = {
|
|
306
|
-
error: {
|
|
307
|
-
message: error.message,
|
|
308
|
-
stack: error.stack,
|
|
309
|
-
name: error.name,
|
|
310
|
-
},
|
|
311
|
-
session: {
|
|
312
|
-
id: state.sessionId,
|
|
313
|
-
messageCount: state.messages.length,
|
|
314
|
-
duration: Date.now() - state.startTime,
|
|
315
|
-
},
|
|
316
|
-
lastNodes: state.history.slice(-5),
|
|
317
|
-
memory: sanitizeMemory(state.memory), // Remove sensitive data
|
|
318
|
-
timestamp: new Date().toISOString(),
|
|
319
|
-
};
|
|
320
|
-
|
|
321
|
-
// Send to error tracking service
|
|
322
|
-
await errorTracker.report(errorContext);
|
|
323
|
-
});
|
|
75
|
+
}
|
|
324
76
|
```
|
|
325
77
|
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
1. **Use Structured Logging**: Always include relevant context in your logs
|
|
329
|
-
2. **Avoid Console.log**: Use the MindedJS logger for consistency
|
|
330
|
-
3. **Sanitize Sensitive Data**: Never log PII or sensitive information
|
|
331
|
-
4. **Use Debug Levels**: Leverage different log levels appropriately
|
|
332
|
-
5. **Create Debug Utilities**: Build reusable debugging functions
|
|
333
|
-
6. **Monitor Performance**: Track execution times and bottlenecks
|
|
334
|
-
7. **Test Edge Cases**: Use debugging to verify edge case handling
|
|
335
|
-
8. **Document Debug Patterns**: Share debugging strategies with your team
|
|
336
|
-
|
|
337
|
-
## Next Steps
|
|
338
|
-
|
|
339
|
-
- Review [Logging](./logging.md) for detailed logging configuration
|
|
340
|
-
- Explore [Events](./events.md) for all available debugging events
|
|
341
|
-
- Check [Memory](./memory.md) for memory debugging techniques
|
|
342
|
-
- See [Parallel LLM](./parallel-llm.md) for performance debugging
|
|
78
|
+
The `LLMDebugCallbackHandler` extends LangChain's `BaseCallbackHandler` and can override different mathods in langchain flow. See the [LangChain documentation](https://js.langchain.com/docs/modules/callbacks/).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@minded-ai/mindedjs",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.130",
|
|
4
4
|
"description": "MindedJS is a TypeScript library for building agents.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -66,4 +66,4 @@
|
|
|
66
66
|
"uuid": "^11.1.0",
|
|
67
67
|
"ws": "^8.15.1"
|
|
68
68
|
}
|
|
69
|
-
}
|
|
69
|
+
}
|
package/src/agent.ts
CHANGED
|
@@ -22,17 +22,7 @@ import { AgentEventRequestPayloads, AgentEventResponsePayloads, AgentEvents } fr
|
|
|
22
22
|
import { z } from 'zod';
|
|
23
23
|
import * as mindedConnection from './platform/mindedConnection';
|
|
24
24
|
import { InvokeMessage, mindedConnectionSocketMessageType, UpdateStateRequest } from './platform/mindedConnectionTypes';
|
|
25
|
-
import
|
|
26
|
-
import * as path from 'path';
|
|
27
|
-
import * as yaml from 'js-yaml';
|
|
28
|
-
import {
|
|
29
|
-
AgentInvokeParams,
|
|
30
|
-
AppTriggerHistoryStep,
|
|
31
|
-
TriggerHistoryStep,
|
|
32
|
-
MindedSDKConfig,
|
|
33
|
-
SessionType,
|
|
34
|
-
HistoryStep,
|
|
35
|
-
} from './types/Agent.types';
|
|
25
|
+
import { AgentInvokeParams, MindedSDKConfig, SessionType } from './types/Agent.types';
|
|
36
26
|
import { createLlmInstance } from './llm/createLlmInstance';
|
|
37
27
|
import { createCheckpointSaver } from './checkpointer/checkpointSaverFactory';
|
|
38
28
|
import { getConfig } from './platform/config';
|
|
@@ -41,15 +31,16 @@ import { createInterruptSessionManager } from './interrupts/interruptSessionMana
|
|
|
41
31
|
import { BaseMessage, HumanMessage } from '@langchain/core/messages';
|
|
42
32
|
import triggerTypeToDefaultMessage from './triggers/triggerTypeToDefaultMessage';
|
|
43
33
|
import appActionRunnerToolCreator from './internalTools/appActionRunnerTool';
|
|
44
|
-
import libraryActionRunnerToolCreator from './internalTools/libraryActionRunnerTool';
|
|
45
34
|
import { VoiceSession } from './voice/voiceSession';
|
|
46
35
|
import { BaseVoiceMessage, OnVoiceAudioOut } from './platform/mindedConnectionTypes';
|
|
47
36
|
import { PIIGateway, PIIGatewayInstance } from './platform/piiGateway';
|
|
48
37
|
import { logger } from './utils/logger';
|
|
49
38
|
import { loadPlaybooks, Playbook } from './playbooks/playbooks';
|
|
50
|
-
import {
|
|
39
|
+
import { createTriggerHistoryStep } from './utils/history';
|
|
51
40
|
import { timerHandlers } from './internalTools/timer';
|
|
52
41
|
import { parseAttachments, combineContentWithAttachments } from './platform/utils/parseAttachments';
|
|
42
|
+
import { ToolExecutor, ToolExecutionRequest, ToolExecutionResponse } from './platform/toolExecutor';
|
|
43
|
+
import { initLibraryActionsRunnerTools, loadFlows } from './utils/agentUtils';
|
|
53
44
|
|
|
54
45
|
type CreateAgentParams<Memory> = {
|
|
55
46
|
memorySchema: z.ZodSchema;
|
|
@@ -102,6 +93,9 @@ export class Agent {
|
|
|
102
93
|
private _piiGateway: PIIGatewayInstance | null = null;
|
|
103
94
|
public playbooks: Playbook[] = [];
|
|
104
95
|
|
|
96
|
+
// Tool executor for standalone tool execution
|
|
97
|
+
private toolExecutor: ToolExecutor;
|
|
98
|
+
|
|
105
99
|
// Getter for PII Gateway that ensures it's available
|
|
106
100
|
public get piiGateway(): PIIGatewayInstance {
|
|
107
101
|
if (!this._piiGateway) {
|
|
@@ -158,6 +152,7 @@ export class Agent {
|
|
|
158
152
|
this.memorySchema = memorySchema;
|
|
159
153
|
this.initPromise = this.init(params);
|
|
160
154
|
this.config = params.config;
|
|
155
|
+
this.toolExecutor = new ToolExecutor(this);
|
|
161
156
|
}
|
|
162
157
|
|
|
163
158
|
private async init(params: CreateAgentParams<z.infer<typeof this.memorySchema>>): Promise<void> {
|
|
@@ -195,16 +190,42 @@ export class Agent {
|
|
|
195
190
|
const { sessionId, state } = message as UpdateStateRequest;
|
|
196
191
|
this.updateState({ sessionId, state });
|
|
197
192
|
});
|
|
193
|
+
|
|
194
|
+
// Handle tool execution requests from browser-use
|
|
195
|
+
mindedConnection.on(mindedConnectionSocketMessageType.EXECUTE_TOOL, async (message) => {
|
|
196
|
+
const request = message as ToolExecutionRequest;
|
|
197
|
+
const requestId = message.requestId;
|
|
198
|
+
logger.debug({ msg: '[Agent] Received tool execution request', toolName: request.toolName, sessionId: request.sessionId });
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
const response = await this.executeTool(request);
|
|
202
|
+
// Send response back via socket
|
|
203
|
+
return {
|
|
204
|
+
...response,
|
|
205
|
+
requestId,
|
|
206
|
+
};
|
|
207
|
+
} catch (error) {
|
|
208
|
+
logger.error({ msg: '[Agent] Error executing tool', error });
|
|
209
|
+
return {
|
|
210
|
+
error: error instanceof Error ? error.message : String(error),
|
|
211
|
+
requestId,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
});
|
|
198
215
|
}
|
|
199
216
|
|
|
200
|
-
const [, flows, playbooks] = await Promise.all([this.loadSecrets(),
|
|
217
|
+
const [, flows, playbooks] = await Promise.all([this.loadSecrets(), loadFlows(config.flows), loadPlaybooks(config.playbooks)]);
|
|
201
218
|
|
|
202
219
|
this.playbooks = playbooks;
|
|
203
220
|
this.flows = flows;
|
|
204
221
|
this.validate();
|
|
205
222
|
const appActionsRunnerTools = this.initAppActionsRunnerTools();
|
|
206
|
-
const libraryActionsRunnerTools =
|
|
223
|
+
const libraryActionsRunnerTools = initLibraryActionsRunnerTools(flows);
|
|
207
224
|
this.tools = [...tools, ...appActionsRunnerTools, ...libraryActionsRunnerTools];
|
|
225
|
+
|
|
226
|
+
// Register tools with the tool executor
|
|
227
|
+
this.toolExecutor.registerTools(this.tools);
|
|
228
|
+
|
|
208
229
|
this.checkpointer = memorySaver || createCheckpointSaver();
|
|
209
230
|
this.interruptSessionManager = interruptSessionManager || createInterruptSessionManager();
|
|
210
231
|
|
|
@@ -225,57 +246,6 @@ export class Agent {
|
|
|
225
246
|
}
|
|
226
247
|
}
|
|
227
248
|
|
|
228
|
-
private async loadFlows(flowsDirectories: string[]) {
|
|
229
|
-
const { env, isDeployed } = getConfig();
|
|
230
|
-
if (['sandbox-staging', 'sandbox'].includes(env) && isDeployed) {
|
|
231
|
-
const response = await mindedConnection.awaitEmit<object, { flows: Record<string, Flow> }>(
|
|
232
|
-
mindedConnectionSocketMessageType.GET_FLOWS,
|
|
233
|
-
{},
|
|
234
|
-
);
|
|
235
|
-
if (!response?.flows) {
|
|
236
|
-
throw new Error('Could not load flows from the platform connection');
|
|
237
|
-
}
|
|
238
|
-
return Object.values(response.flows);
|
|
239
|
-
}
|
|
240
|
-
return this.loadFlowsFromDirectory(flowsDirectories);
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
private loadFlowsFromDirectory(flowsDirectories: string[]): Flow[] {
|
|
244
|
-
const flows: Flow[] = [];
|
|
245
|
-
for (const flowsDirectory of flowsDirectories) {
|
|
246
|
-
if (!fs.existsSync(flowsDirectory)) {
|
|
247
|
-
throw new Error(`Flows directory does not exist: ${flowsDirectory}`);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
const files = fs.readdirSync(flowsDirectory);
|
|
251
|
-
|
|
252
|
-
for (const file of files) {
|
|
253
|
-
if (file.endsWith('.yaml') || file.endsWith('.yml')) {
|
|
254
|
-
const filePath = path.join(flowsDirectory, file);
|
|
255
|
-
try {
|
|
256
|
-
const fileContent = fs.readFileSync(filePath, 'utf8');
|
|
257
|
-
const parsedFlow = yaml.load(fileContent) as Flow;
|
|
258
|
-
|
|
259
|
-
// Validate that the parsed flow has the required structure
|
|
260
|
-
if (!parsedFlow.name || !parsedFlow.nodes || !parsedFlow.edges) {
|
|
261
|
-
throw new Error(`Invalid flow structure in ${file}. Flow must have name, nodes, and edges.`);
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
flows.push(parsedFlow);
|
|
265
|
-
} catch (error) {
|
|
266
|
-
throw new Error(`Failed to parse flow file ${file}: ${error}`);
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
if (flows.length === 0) {
|
|
272
|
-
throw new Error(`No YAML flow files found in directory: ${flowsDirectory}`);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
return flows;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
249
|
private validate() {
|
|
280
250
|
if (this.flows.length === 0) {
|
|
281
251
|
throw new Error('No flows provided');
|
|
@@ -406,7 +376,7 @@ export class Agent {
|
|
|
406
376
|
|
|
407
377
|
const initialState = {
|
|
408
378
|
messages: [],
|
|
409
|
-
memory: { ...initialMemory, ...state.memory || {} },
|
|
379
|
+
memory: { ...initialMemory, ...(state.memory || {}) },
|
|
410
380
|
triggerMetadata: null,
|
|
411
381
|
history: [],
|
|
412
382
|
sessionId: state.sessionId || uuidv4(), // Preserve existing sessionId or generate new one
|
|
@@ -414,6 +384,7 @@ export class Agent {
|
|
|
414
384
|
overrideStartFromNodeId: null,
|
|
415
385
|
goto: null,
|
|
416
386
|
scenario: state.scenario || {},
|
|
387
|
+
cdpUrl: null,
|
|
417
388
|
};
|
|
418
389
|
|
|
419
390
|
// Emit INIT event with the initial state
|
|
@@ -424,33 +395,6 @@ export class Agent {
|
|
|
424
395
|
return initialState;
|
|
425
396
|
}
|
|
426
397
|
|
|
427
|
-
private createTriggerHistoryStep(
|
|
428
|
-
currentHistory: HistoryStep[],
|
|
429
|
-
nodeId: string,
|
|
430
|
-
messageIds: string[],
|
|
431
|
-
triggerName: string,
|
|
432
|
-
triggerBody: any,
|
|
433
|
-
appName?: string,
|
|
434
|
-
): HistoryStep {
|
|
435
|
-
const baseStep = {
|
|
436
|
-
nodeId: nodeId,
|
|
437
|
-
nodeDisplayName: triggerName,
|
|
438
|
-
raw: triggerBody,
|
|
439
|
-
messageIds,
|
|
440
|
-
} as HistoryStep;
|
|
441
|
-
|
|
442
|
-
return appName
|
|
443
|
-
? createHistoryStep<AppTriggerHistoryStep>(currentHistory, {
|
|
444
|
-
...baseStep,
|
|
445
|
-
type: NodeType.TRIGGER,
|
|
446
|
-
appName,
|
|
447
|
-
})
|
|
448
|
-
: createHistoryStep<TriggerHistoryStep>(currentHistory, {
|
|
449
|
-
...baseStep,
|
|
450
|
-
type: NodeType.TRIGGER,
|
|
451
|
-
});
|
|
452
|
-
}
|
|
453
|
-
|
|
454
398
|
/**
|
|
455
399
|
* Invoke a trigger to start agent execution with the specified parameters.
|
|
456
400
|
*
|
|
@@ -555,7 +499,7 @@ export class Agent {
|
|
|
555
499
|
throw new Error('No node to be invoked');
|
|
556
500
|
}
|
|
557
501
|
nodeToBeInvoked = nodeToBeInvoked.replace(new RegExp(suffixes.join('|'), 'g'), '');
|
|
558
|
-
const historyStep =
|
|
502
|
+
const historyStep = createTriggerHistoryStep(
|
|
559
503
|
state.values.history,
|
|
560
504
|
nodeToBeInvoked,
|
|
561
505
|
messages.map((m) => m.id!),
|
|
@@ -749,14 +693,6 @@ export class Agent {
|
|
|
749
693
|
.map((node) => appActionRunnerToolCreator(node.metadata.schema, node.displayName!));
|
|
750
694
|
}
|
|
751
695
|
|
|
752
|
-
private initLibraryActionsRunnerTools() {
|
|
753
|
-
return this.flows
|
|
754
|
-
.flatMap((flow) =>
|
|
755
|
-
flow.nodes.filter((node): node is AppToolNode => node.type === NodeType.APP_TOOL && (node as AppToolNode).appName === 'Minded'),
|
|
756
|
-
)
|
|
757
|
-
.map((node) => libraryActionRunnerToolCreator(node.actionKey, node.displayName!));
|
|
758
|
-
}
|
|
759
|
-
|
|
760
696
|
// Private method to get secrets from the backend service and load them into environment variables
|
|
761
697
|
private async loadSecrets(): Promise<Record<string, string>> {
|
|
762
698
|
// Skip secret loading in local development
|
|
@@ -930,4 +866,18 @@ export class Agent {
|
|
|
930
866
|
langraphConfig,
|
|
931
867
|
);
|
|
932
868
|
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* Execute a tool by name with given parameters
|
|
872
|
+
* This is used for standalone tool execution (e.g., from browser-use)
|
|
873
|
+
*/
|
|
874
|
+
async executeTool(request: ToolExecutionRequest): Promise<ToolExecutionResponse> {
|
|
875
|
+
await this.waitForInitialization();
|
|
876
|
+
try {
|
|
877
|
+
return await this.toolExecutor.executeTool(request);
|
|
878
|
+
} catch (error) {
|
|
879
|
+
logger.error({ msg: '[Agent] Error executing tool', error });
|
|
880
|
+
return { error: 'Failed to execute tool' };
|
|
881
|
+
}
|
|
882
|
+
}
|
|
933
883
|
}
|