@minded-ai/mindedjs 1.0.108 → 1.0.109
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 +12 -12
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +44 -30
- package/dist/agent.js.map +1 -1
- package/dist/browserTask/executeBrowserTask.d.ts.map +1 -1
- package/dist/checkpointer/checkpointSaverFactory.js +7 -17
- package/dist/checkpointer/checkpointSaverFactory.js.map +1 -1
- package/dist/cli/index.js +7 -17
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/lambdaHandlerTemplate.d.ts.map +1 -1
- package/dist/edges/createDirectEdge.d.ts.map +1 -1
- package/dist/edges/createLogicalRouter.d.ts +3 -1
- package/dist/edges/createLogicalRouter.d.ts.map +1 -1
- package/dist/edges/createLogicalRouter.js +48 -19
- package/dist/edges/createLogicalRouter.js.map +1 -1
- package/dist/edges/createPromptRouter.d.ts.map +1 -1
- package/dist/edges/edgeFactory.d.ts.map +1 -1
- package/dist/edges/edgeFactory.js +7 -2
- package/dist/edges/edgeFactory.js.map +1 -1
- package/dist/events/AgentEvents.d.ts +19 -1
- package/dist/events/AgentEvents.d.ts.map +1 -1
- package/dist/events/AgentEvents.js +2 -0
- package/dist/events/AgentEvents.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -18
- package/dist/index.js.map +1 -1
- package/dist/interfaces/zendesk.js +7 -17
- package/dist/interfaces/zendesk.js.map +1 -1
- package/dist/internalTools/appActionRunnerTool.d.ts.map +1 -1
- package/dist/internalTools/appActionRunnerTool.js +7 -17
- package/dist/internalTools/appActionRunnerTool.js.map +1 -1
- package/dist/internalTools/documentExtraction/documentExtraction.js +7 -17
- package/dist/internalTools/documentExtraction/documentExtraction.js.map +1 -1
- package/dist/internalTools/libraryActionRunnerTool.d.ts.map +1 -1
- package/dist/internalTools/retell.js +7 -17
- package/dist/internalTools/retell.js.map +1 -1
- package/dist/internalTools/sendPlaceholderMessage.js +7 -17
- package/dist/internalTools/sendPlaceholderMessage.js.map +1 -1
- package/dist/internalTools/timer.d.ts +3 -3
- package/dist/internalTools/timer.d.ts.map +1 -1
- package/dist/internalTools/timer.js +10 -20
- package/dist/internalTools/timer.js.map +1 -1
- package/dist/llm/createLlmInstance.d.ts.map +1 -1
- package/dist/nodes/addAppToolNode.d.ts.map +1 -1
- package/dist/nodes/addBrowserTaskNode.d.ts.map +1 -1
- package/dist/nodes/addBrowserTaskNode.js +7 -17
- package/dist/nodes/addBrowserTaskNode.js.map +1 -1
- package/dist/nodes/addBrowserTaskRunNode.d.ts.map +1 -1
- package/dist/nodes/addHumanInTheLoopNode.d.ts.map +1 -1
- package/dist/nodes/addJumpToNode.d.ts.map +1 -1
- package/dist/nodes/addJunctionNode.d.ts.map +1 -1
- package/dist/nodes/addPromptNode.d.ts.map +1 -1
- package/dist/nodes/addToolNode.d.ts.map +1 -1
- package/dist/nodes/addToolRunNode.d.ts.map +1 -1
- package/dist/nodes/addTriggerNode.d.ts.map +1 -1
- package/dist/nodes/nodeFactory.d.ts.map +1 -1
- package/dist/platform/mindedCheckpointSaver.js +7 -17
- package/dist/platform/mindedCheckpointSaver.js.map +1 -1
- package/dist/platform/mindedConnection.d.ts.map +1 -1
- package/dist/platform/piiGateway/gateway.js +7 -17
- package/dist/platform/piiGateway/gateway.js.map +1 -1
- package/dist/platform/utils/parseAttachments.d.ts.map +1 -1
- package/dist/playbooks/playbooks.js +7 -17
- package/dist/playbooks/playbooks.js.map +1 -1
- package/dist/toolsLibrary/index.js +7 -17
- package/dist/toolsLibrary/index.js.map +1 -1
- package/dist/toolsLibrary/parseDocument.d.ts +3 -3
- package/dist/types/LangGraph.types.d.ts.map +1 -1
- package/dist/utils/extractStateMemoryResponse.d.ts.map +1 -1
- package/dist/utils/history.d.ts.map +1 -1
- package/dist/utils/wait.d.ts.map +1 -1
- package/dist/voice/voiceSession.js +7 -17
- package/dist/voice/voiceSession.js.map +1 -1
- package/docs/SUMMARY.md +8 -4
- package/docs/low-code-editor/edges.md +4 -0
- package/docs/sdk/debugging.md +342 -0
- package/docs/{platform → sdk}/events.md +168 -1
- package/package.json +2 -2
- package/src/agent.ts +48 -21
- package/src/edges/createLogicalRouter.ts +50 -2
- package/src/edges/edgeFactory.ts +7 -2
- package/src/events/AgentEvents.ts +19 -1
- package/src/index.ts +4 -0
- package/src/internalTools/timer.ts +20 -17
- /package/docs/{platform → sdk}/logging.md +0 -0
- /package/docs/{platform → sdk}/memory.md +0 -0
- /package/docs/{platform → sdk}/parallel-llm.md +0 -0
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
# Debugging
|
|
2
|
+
|
|
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
|
+
|
|
5
|
+
## Debugging Logical Conditions
|
|
6
|
+
|
|
7
|
+
MindedJS provides comprehensive debugging capabilities for logical conditions during development:
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
// Enable debug logging
|
|
11
|
+
// Set LOG_LEVEL=debug in your .env file
|
|
12
|
+
|
|
13
|
+
// Listen to condition evaluation events
|
|
14
|
+
import { AgentEvents } from 'mindedjs';
|
|
15
|
+
|
|
16
|
+
agent.on(AgentEvents.ON_LOGICAL_CONDITION, async ({ edge, state, condition }) => {
|
|
17
|
+
console.log('[Debug] Evaluating condition:', condition);
|
|
18
|
+
console.log('[Debug] Current memory:', state.memory);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
agent.on(AgentEvents.ON_LOGICAL_CONDITION_RESULT, async ({ condition, result, executionTimeMs }) => {
|
|
22
|
+
console.log('[Debug] Result:', result);
|
|
23
|
+
console.log('[Debug] Execution time:', executionTimeMs, 'ms');
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Common Debugging Patterns
|
|
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
|
+
```
|
|
152
|
+
|
|
153
|
+
### 5. Trace Execution Flow
|
|
154
|
+
|
|
155
|
+
Track the complete execution path:
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
let executionTrace: any[] = [];
|
|
159
|
+
|
|
160
|
+
agent.on(AgentEvents.NODE_START, async ({ nodeId, nodeType }) => {
|
|
161
|
+
executionTrace.push({
|
|
162
|
+
type: 'node_start',
|
|
163
|
+
nodeId,
|
|
164
|
+
nodeType,
|
|
165
|
+
timestamp: Date.now(),
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
agent.on(AgentEvents.NODE_END, async ({ nodeId, nodeType }) => {
|
|
170
|
+
executionTrace.push({
|
|
171
|
+
type: 'node_end',
|
|
172
|
+
nodeId,
|
|
173
|
+
nodeType,
|
|
174
|
+
timestamp: Date.now(),
|
|
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
|
+
}
|
|
281
|
+
});
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
### 2. Sampling
|
|
285
|
+
|
|
286
|
+
Debug a percentage of sessions in production:
|
|
287
|
+
|
|
288
|
+
```typescript
|
|
289
|
+
const DEBUG_SAMPLE_RATE = 0.01; // 1% of sessions
|
|
290
|
+
|
|
291
|
+
agent.on(AgentEvents.INIT, async ({ state }) => {
|
|
292
|
+
if (Math.random() < DEBUG_SAMPLE_RATE) {
|
|
293
|
+
logger.info('Debug sampling enabled', { sessionId: state.sessionId });
|
|
294
|
+
// Enable additional logging
|
|
295
|
+
}
|
|
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
|
+
});
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
## Best Practices
|
|
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
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Events are messages that flow through your agent during execution, providing visibility into what's happening and enabling reactive behavior.
|
|
4
4
|
|
|
5
|
-
MindedJS currently supports
|
|
5
|
+
MindedJS currently supports 6 main event types. Each event type has its own specific input structure, output requirements, and use cases.
|
|
6
6
|
|
|
7
7
|
## History Structure
|
|
8
8
|
|
|
@@ -372,3 +372,170 @@ agent.on(events.ERROR, async ({ error, state }) => {
|
|
|
372
372
|
- **Error Recovery**: Implement custom recovery logic or fallback behaviors
|
|
373
373
|
- **Session Management**: Clean up or reset sessions that encountered errors
|
|
374
374
|
- **Analytics**: Track error patterns and frequencies for system improvement
|
|
375
|
+
|
|
376
|
+
## ON_LOGICAL_CONDITION
|
|
377
|
+
|
|
378
|
+
The `ON_LOGICAL_CONDITION` event is emitted when the agent is about to evaluate a logical condition on an edge. This event provides visibility into the condition evaluation process and allows you to track which conditions are being checked during flow execution.
|
|
379
|
+
|
|
380
|
+
### Input Structure
|
|
381
|
+
|
|
382
|
+
```typescript
|
|
383
|
+
{
|
|
384
|
+
edge: LogicalConditionEdge; // The edge containing the condition
|
|
385
|
+
state: { // Full agent state at evaluation time
|
|
386
|
+
messages: BaseMessage[]; // Conversation messages
|
|
387
|
+
memory: Memory; // Current memory state (your defined memory schema)
|
|
388
|
+
history: HistoryStep[]; // Flow execution history with detailed step information
|
|
389
|
+
sessionId: string; // Session identifier
|
|
390
|
+
};
|
|
391
|
+
condition: string; // The condition expression being evaluated
|
|
392
|
+
}
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
### Handler Return Value
|
|
396
|
+
|
|
397
|
+
- **Return type**: `void`
|
|
398
|
+
- **Purpose**: Handlers are used for debugging, logging, and monitoring condition evaluations
|
|
399
|
+
- **Note**: Return values are ignored
|
|
400
|
+
|
|
401
|
+
### Usage Example
|
|
402
|
+
|
|
403
|
+
```typescript
|
|
404
|
+
import { Agent, events } from 'mindedjs';
|
|
405
|
+
|
|
406
|
+
const agent = new Agent({
|
|
407
|
+
memorySchema,
|
|
408
|
+
config,
|
|
409
|
+
tools,
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
// Listen to condition evaluation events
|
|
413
|
+
agent.on(events.ON_LOGICAL_CONDITION, async ({ edge, state, condition }) => {
|
|
414
|
+
console.log('Evaluating condition:', condition);
|
|
415
|
+
console.log('On edge from:', edge.source, 'to:', edge.target);
|
|
416
|
+
console.log('Current memory:', state.memory);
|
|
417
|
+
console.log('Session ID:', state.sessionId);
|
|
418
|
+
|
|
419
|
+
// Log for debugging
|
|
420
|
+
await logger.debug({
|
|
421
|
+
event: 'condition_evaluation_start',
|
|
422
|
+
condition,
|
|
423
|
+
edge: {
|
|
424
|
+
source: edge.source,
|
|
425
|
+
target: edge.target,
|
|
426
|
+
},
|
|
427
|
+
memory: state.memory,
|
|
428
|
+
sessionId: state.sessionId,
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
// Track condition usage analytics
|
|
432
|
+
await analytics.track('condition_evaluated', {
|
|
433
|
+
condition,
|
|
434
|
+
edgeSource: edge.source,
|
|
435
|
+
edgeTarget: edge.target,
|
|
436
|
+
sessionId: state.sessionId,
|
|
437
|
+
});
|
|
438
|
+
});
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
### Common Use Cases
|
|
442
|
+
|
|
443
|
+
- **Debugging Flow Logic**: Trace which conditions are evaluated and in what order
|
|
444
|
+
- **Performance Monitoring**: Track when condition evaluations start
|
|
445
|
+
- **Analytics**: Understand which flow paths are most commonly evaluated
|
|
446
|
+
- **Testing**: Verify that expected conditions are being checked
|
|
447
|
+
- **Audit Logging**: Record decision points for compliance or debugging
|
|
448
|
+
|
|
449
|
+
## ON_LOGICAL_CONDITION_RESULT
|
|
450
|
+
|
|
451
|
+
The `ON_LOGICAL_CONDITION_RESULT` event is emitted after a logical condition has been evaluated, providing the result and execution metrics. This event is crucial for understanding flow decisions and monitoring performance.
|
|
452
|
+
|
|
453
|
+
### Input Structure
|
|
454
|
+
|
|
455
|
+
```typescript
|
|
456
|
+
{
|
|
457
|
+
edge: LogicalConditionEdge; // The edge containing the condition
|
|
458
|
+
state: { // Full agent state after evaluation
|
|
459
|
+
messages: BaseMessage[]; // Conversation messages
|
|
460
|
+
memory: Memory; // Current memory state (your defined memory schema)
|
|
461
|
+
history: HistoryStep[]; // Flow execution history with detailed step information
|
|
462
|
+
sessionId: string; // Session identifier
|
|
463
|
+
};
|
|
464
|
+
condition: string; // The condition expression that was evaluated
|
|
465
|
+
result: boolean; // The evaluation result (true/false)
|
|
466
|
+
executionTimeMs: number; // Time taken to evaluate the condition in milliseconds
|
|
467
|
+
error?: Error; // Optional error if evaluation failed
|
|
468
|
+
}
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
### Handler Return Value
|
|
472
|
+
|
|
473
|
+
- **Return type**: `void`
|
|
474
|
+
- **Purpose**: Handlers are used for logging results, performance monitoring, and debugging
|
|
475
|
+
- **Note**: Return values are ignored
|
|
476
|
+
|
|
477
|
+
### Usage Example
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
import { Agent, events } from 'mindedjs';
|
|
481
|
+
|
|
482
|
+
const agent = new Agent({
|
|
483
|
+
memorySchema,
|
|
484
|
+
config,
|
|
485
|
+
tools,
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
// Listen to condition results
|
|
489
|
+
agent.on(events.ON_LOGICAL_CONDITION_RESULT, async ({ edge, state, condition, result, executionTimeMs, error }) => {
|
|
490
|
+
console.log('Condition result:', result);
|
|
491
|
+
console.log('Execution time:', executionTimeMs, 'ms');
|
|
492
|
+
|
|
493
|
+
if (error) {
|
|
494
|
+
console.error('Condition evaluation failed:', error.message);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// Log detailed results
|
|
498
|
+
await logger.debug({
|
|
499
|
+
event: 'condition_evaluation_complete',
|
|
500
|
+
condition,
|
|
501
|
+
result,
|
|
502
|
+
executionTimeMs,
|
|
503
|
+
edge: {
|
|
504
|
+
source: edge.source,
|
|
505
|
+
target: edge.target,
|
|
506
|
+
},
|
|
507
|
+
memory: state.memory,
|
|
508
|
+
sessionId: state.sessionId,
|
|
509
|
+
error: error?.message,
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
// Performance monitoring
|
|
513
|
+
if (executionTimeMs > 10) {
|
|
514
|
+
await logger.warn({
|
|
515
|
+
message: 'Slow condition detected',
|
|
516
|
+
condition,
|
|
517
|
+
executionTimeMs,
|
|
518
|
+
sessionId: state.sessionId,
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// Track failed conditions
|
|
523
|
+
if (!result) {
|
|
524
|
+
await analytics.track('condition_failed', {
|
|
525
|
+
condition,
|
|
526
|
+
edgeSource: edge.source,
|
|
527
|
+
edgeTarget: edge.target,
|
|
528
|
+
sessionId: state.sessionId,
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
### Common Use Cases
|
|
535
|
+
|
|
536
|
+
- **Performance Monitoring**: Track execution times to identify slow conditions
|
|
537
|
+
- **Debugging Failed Conditions**: Understand why certain flow paths aren't taken
|
|
538
|
+
- **Flow Analytics**: Analyze which conditions pass/fail most frequently
|
|
539
|
+
- **Error Tracking**: Monitor and alert on condition evaluation errors
|
|
540
|
+
- **Optimization**: Identify conditions that could be simplified or cached
|
|
541
|
+
- **Testing**: Verify condition results match expected behavior
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@minded-ai/mindedjs",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.109",
|
|
4
4
|
"description": "MindedJS is a TypeScript library for building agents.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"example-browser": "cd examples/browserUsingAgent && nodemon --watch '**/*.ts' --exec 'ts-node' browserUsingAgent.ts",
|
|
25
25
|
"lint": "eslint .",
|
|
26
26
|
"lintFix": "eslint --fix .",
|
|
27
|
-
"generateApiDocs": "typedoc
|
|
27
|
+
"generateApiDocs": "typedoc"
|
|
28
28
|
},
|
|
29
29
|
"author": "",
|
|
30
30
|
"license": "ISC",
|
package/src/agent.ts
CHANGED
|
@@ -120,12 +120,12 @@ export class Agent {
|
|
|
120
120
|
/**
|
|
121
121
|
* Create a new Agent instance.
|
|
122
122
|
*
|
|
123
|
-
* @param params - Configuration parameters for the agent
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
123
|
+
* @param params - Configuration parameters for the agent containing:
|
|
124
|
+
* - memorySchema: Zod schema defining the structure of the agent's memory
|
|
125
|
+
* - config: SDK configuration including flows directory and LLM settings
|
|
126
|
+
* - tools: Array of custom tools to be available to the agent
|
|
127
|
+
* - platformToken: Optional token for platform authentication
|
|
128
|
+
* - memorySaver: Optional custom checkpoint saver for conversation memory
|
|
129
129
|
*
|
|
130
130
|
* @example
|
|
131
131
|
* ```typescript
|
|
@@ -334,8 +334,35 @@ export class Agent {
|
|
|
334
334
|
}
|
|
335
335
|
|
|
336
336
|
// Add edges to __end__ for nodes with no outgoing edges
|
|
337
|
+
// Default behavior depends on node type:
|
|
338
|
+
// - PROMPT_NODE: defaults to canStayOnNode=true (stays at node)
|
|
339
|
+
// - TOOL, APP_TOOL, JUMP_TO_NODE, BROWSER_TASK: defaults to canStayOnNode=false (ends flow)
|
|
340
|
+
// - Other types: defaults to canStayOnNode=false (ends flow)
|
|
337
341
|
const sourceNodes = new Set(edges.map((edge) => edge.source));
|
|
338
|
-
const lastNodes = Object.keys(nodesObject).filter((nodeName) =>
|
|
342
|
+
const lastNodes = Object.keys(nodesObject).filter((nodeName) => {
|
|
343
|
+
if (sourceNodes.has(nodeName)) return false; // Not a leaf node
|
|
344
|
+
|
|
345
|
+
const node = nodesObject[nodeName];
|
|
346
|
+
|
|
347
|
+
// If canStayOnNode is explicitly set, respect that
|
|
348
|
+
if (node.canStayOnNode !== undefined) {
|
|
349
|
+
return !node.canStayOnNode;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Default behavior based on node type
|
|
353
|
+
switch (node.type) {
|
|
354
|
+
case NodeType.PROMPT_NODE:
|
|
355
|
+
return false; // Default: stay at node (no edge to __end__)
|
|
356
|
+
case NodeType.TOOL:
|
|
357
|
+
case NodeType.APP_TOOL:
|
|
358
|
+
case NodeType.JUMP_TO_NODE:
|
|
359
|
+
case NodeType.BROWSER_TASK:
|
|
360
|
+
return true; // Default: end flow (add edge to __end__)
|
|
361
|
+
default:
|
|
362
|
+
return true; // Default for other types: end flow
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
|
|
339
366
|
lastNodes.forEach((nodeName) => {
|
|
340
367
|
edges.push({
|
|
341
368
|
source: nodeName,
|
|
@@ -393,14 +420,14 @@ export class Agent {
|
|
|
393
420
|
|
|
394
421
|
return appName
|
|
395
422
|
? createHistoryStep<AppTriggerHistoryStep>(currentHistory, {
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
423
|
+
...baseStep,
|
|
424
|
+
type: NodeType.TRIGGER,
|
|
425
|
+
appName,
|
|
426
|
+
})
|
|
400
427
|
: createHistoryStep<TriggerHistoryStep>(currentHistory, {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
428
|
+
...baseStep,
|
|
429
|
+
type: NodeType.TRIGGER,
|
|
430
|
+
});
|
|
404
431
|
}
|
|
405
432
|
|
|
406
433
|
/**
|
|
@@ -409,11 +436,11 @@ export class Agent {
|
|
|
409
436
|
* This method processes triggers from external systems or applications, allowing the agent
|
|
410
437
|
* to respond to events and execute the appropriate flows based on the trigger type.
|
|
411
438
|
*
|
|
412
|
-
* @param params - The trigger invocation parameters
|
|
413
|
-
*
|
|
414
|
-
*
|
|
415
|
-
*
|
|
416
|
-
*
|
|
439
|
+
* @param params - The trigger invocation parameters containing:
|
|
440
|
+
* - triggerBody: The payload/data associated with the trigger
|
|
441
|
+
* - triggerName: The name/type of the trigger being invoked
|
|
442
|
+
* - sessionId: Optional session identifier for conversation continuity
|
|
443
|
+
* - appName: Optional name of the application triggering the agent in case of an app trigger
|
|
417
444
|
*
|
|
418
445
|
* @returns Promise that resolves with the agent's execution result
|
|
419
446
|
*
|
|
@@ -737,8 +764,8 @@ export class Agent {
|
|
|
737
764
|
(this.eventHandlers[event] as Array<typeof handler>).push(handler);
|
|
738
765
|
}
|
|
739
766
|
|
|
740
|
-
//
|
|
741
|
-
|
|
767
|
+
// Method to emit events to the registered listeners
|
|
768
|
+
public async emit<E extends keyof AgentEventRequestPayloads<z.infer<typeof this.memorySchema>>>(
|
|
742
769
|
event: E,
|
|
743
770
|
payload: AgentEventRequestPayloads<z.infer<typeof this.memorySchema>>[E],
|
|
744
771
|
): Promise<AgentEventResponsePayloads<z.infer<typeof this.memorySchema>>[E][]> {
|