@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.
Files changed (70) hide show
  1. package/dist/agent.d.ts +7 -4
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +45 -72
  4. package/dist/agent.js.map +1 -1
  5. package/dist/browserTask/executeBrowserTask.d.ts +2 -13
  6. package/dist/browserTask/executeBrowserTask.d.ts.map +1 -1
  7. package/dist/browserTask/executeBrowserTask.js +9 -180
  8. package/dist/browserTask/executeBrowserTask.js.map +1 -1
  9. package/dist/debugging/index.d.ts +2 -0
  10. package/dist/debugging/index.d.ts.map +1 -0
  11. package/dist/debugging/index.js +6 -0
  12. package/dist/debugging/index.js.map +1 -0
  13. package/dist/debugging/llmCallbackHandler.d.ts +83 -0
  14. package/dist/debugging/llmCallbackHandler.d.ts.map +1 -0
  15. package/dist/debugging/llmCallbackHandler.js +102 -0
  16. package/dist/debugging/llmCallbackHandler.js.map +1 -0
  17. package/dist/nodes/addBrowserTaskNode.d.ts.map +1 -1
  18. package/dist/nodes/addBrowserTaskNode.js +2 -1
  19. package/dist/nodes/addBrowserTaskNode.js.map +1 -1
  20. package/dist/nodes/addBrowserTaskRunNode.d.ts +1 -1
  21. package/dist/nodes/addBrowserTaskRunNode.d.ts.map +1 -1
  22. package/dist/nodes/addBrowserTaskRunNode.js +10 -2
  23. package/dist/nodes/addBrowserTaskRunNode.js.map +1 -1
  24. package/dist/platform/mindedConnectionTypes.d.ts +28 -1
  25. package/dist/platform/mindedConnectionTypes.d.ts.map +1 -1
  26. package/dist/platform/mindedConnectionTypes.js +2 -0
  27. package/dist/platform/mindedConnectionTypes.js.map +1 -1
  28. package/dist/platform/toolExecutor.d.ts +29 -0
  29. package/dist/platform/toolExecutor.d.ts.map +1 -0
  30. package/dist/platform/toolExecutor.js +95 -0
  31. package/dist/platform/toolExecutor.js.map +1 -0
  32. package/dist/platform/utils/tools.d.ts +6 -0
  33. package/dist/platform/utils/tools.d.ts.map +1 -0
  34. package/dist/platform/utils/tools.js +57 -0
  35. package/dist/platform/utils/tools.js.map +1 -0
  36. package/dist/types/Flows.types.d.ts +1 -0
  37. package/dist/types/Flows.types.d.ts.map +1 -1
  38. package/dist/types/Flows.types.js.map +1 -1
  39. package/dist/types/LangGraph.types.d.ts +2 -0
  40. package/dist/types/LangGraph.types.d.ts.map +1 -1
  41. package/dist/types/LangGraph.types.js +5 -0
  42. package/dist/types/LangGraph.types.js.map +1 -1
  43. package/dist/types/Tools.types.d.ts +3 -2
  44. package/dist/types/Tools.types.d.ts.map +1 -1
  45. package/dist/utils/agentUtils.d.ts +5 -0
  46. package/dist/utils/agentUtils.d.ts.map +1 -0
  47. package/dist/utils/agentUtils.js +86 -0
  48. package/dist/utils/agentUtils.js.map +1 -0
  49. package/dist/utils/history.d.ts +1 -0
  50. package/dist/utils/history.d.ts.map +1 -1
  51. package/dist/utils/history.js +20 -0
  52. package/dist/utils/history.js.map +1 -1
  53. package/docs/SUMMARY.md +1 -0
  54. package/docs/sdk/agent-api.md +524 -0
  55. package/docs/sdk/debugging.md +42 -306
  56. package/package.json +2 -2
  57. package/src/agent.ts +53 -103
  58. package/src/browserTask/executeBrowserTask.ts +11 -215
  59. package/src/debugging/index.ts +1 -0
  60. package/src/debugging/llmCallbackHandler.ts +126 -0
  61. package/src/nodes/addBrowserTaskNode.ts +3 -2
  62. package/src/nodes/addBrowserTaskRunNode.ts +21 -2
  63. package/src/platform/mindedConnectionTypes.ts +33 -1
  64. package/src/platform/toolExecutor.ts +118 -0
  65. package/src/platform/utils/tools.ts +55 -0
  66. package/src/types/Flows.types.ts +1 -0
  67. package/src/types/LangGraph.types.ts +5 -0
  68. package/src/types/Tools.types.ts +2 -1
  69. package/src/utils/agentUtils.ts +68 -0
  70. package/src/utils/history.ts +29 -1
@@ -0,0 +1,524 @@
1
+ # Agent API
2
+
3
+ The Agent class is the core component of MindedJS that orchestrates conversations, manages state, and coordinates flows. This document covers the key methods available on the Agent instance.
4
+
5
+ ## Overview
6
+
7
+ The Agent class provides methods for:
8
+
9
+ - Managing conversation state
10
+ - Updating session data
11
+ - Retrieving state information
12
+ - Handling events and triggers
13
+ - Managing voice sessions
14
+
15
+ ## Key Methods
16
+
17
+ ### updateState
18
+
19
+ Updates the state of an active session. This method allows you to programmatically modify the conversation state, including messages, memory, and other state properties.
20
+
21
+ #### Signature
22
+
23
+ ```typescript
24
+ async updateState({
25
+ sessionId: string,
26
+ state: Partial<State>
27
+ }): Promise<void>
28
+ ```
29
+
30
+ #### Parameters
31
+
32
+ - `sessionId` (string): The unique identifier of the session to update
33
+ - `state` (Partial<State>): An object containing the state properties to update. Can include:
34
+ - `messages`: Array of messages to add or update
35
+ - `memory`: Partial memory object to merge with existing memory
36
+ - `overrideStartFromNodeId`: Node ID to override the next execution point
37
+ - Any other state properties defined in your agent
38
+
39
+ #### Usage Examples
40
+
41
+ ##### Update Memory
42
+
43
+ ```typescript
44
+ // Update specific memory fields
45
+ await agent.updateState({
46
+ sessionId: 'session-123',
47
+ state: {
48
+ memory: {
49
+ user: {
50
+ name: 'John Doe',
51
+ preferences: {
52
+ language: 'en',
53
+ },
54
+ },
55
+ },
56
+ },
57
+ });
58
+ ```
59
+
60
+ ##### Add Messages
61
+
62
+ ```typescript
63
+ import { HumanMessage, AIMessage } from '@langchain/core/messages';
64
+
65
+ // Add a new message to the conversation
66
+ await agent.updateState({
67
+ sessionId: 'session-123',
68
+ state: {
69
+ messages: [new HumanMessage('User input'), new AIMessage('Agent response')],
70
+ },
71
+ });
72
+ ```
73
+
74
+ ##### Update Multiple State Properties
75
+
76
+ ```typescript
77
+ // Update both memory and messages
78
+ await agent.updateState({
79
+ sessionId: 'session-123',
80
+ state: {
81
+ memory: {
82
+ conversation: {
83
+ topic: 'Order inquiry',
84
+ urgency: 'high',
85
+ },
86
+ },
87
+ messages: [new HumanMessage('I need help with my order')],
88
+ },
89
+ });
90
+ ```
91
+
92
+ #### Common Use Cases
93
+
94
+ 1. **Tool State Updates**: Tools can update state after execution
95
+
96
+ ```typescript
97
+ // Inside a tool's execute method
98
+ async execute({ input, state, agent }) {
99
+ // Perform tool logic
100
+ const result = await processOrder(input.orderId);
101
+
102
+ // Update state with results
103
+ await agent.updateState({
104
+ sessionId: state.sessionId,
105
+ state: {
106
+ memory: {
107
+ order: {
108
+ id: result.orderId,
109
+ status: result.status
110
+ }
111
+ }
112
+ }
113
+ });
114
+
115
+ return { result };
116
+ }
117
+ ```
118
+
119
+ 2. **External Event Handling**: Update state based on external events
120
+
121
+ ```typescript
122
+ // Handle webhook or external trigger
123
+ async handleWebhook(sessionId: string, webhookData: any) {
124
+ await agent.updateState({
125
+ sessionId,
126
+ state: {
127
+ memory: {
128
+ externalData: webhookData,
129
+ lastWebhookTime: new Date().toISOString()
130
+ }
131
+ }
132
+ });
133
+ }
134
+ ```
135
+
136
+ 3. **Voice Session Corrections**: Update messages during voice conversations
137
+ ```typescript
138
+ // Correct a voice transcription
139
+ await agent.updateState({
140
+ sessionId: voiceSessionId,
141
+ state: {
142
+ messages: [correctedMessage],
143
+ overrideStartFromNodeId: currentNodeId,
144
+ },
145
+ });
146
+ ```
147
+
148
+ ### getState
149
+
150
+ Retrieves the current state of a session.
151
+
152
+ #### Signature
153
+
154
+ ```typescript
155
+ async getState(sessionId: string): Promise<State<Memory>>
156
+ ```
157
+
158
+ #### Parameters
159
+
160
+ - `sessionId` (string): The unique identifier of the session
161
+
162
+ #### Returns
163
+
164
+ A `State` object containing:
165
+
166
+ - `sessionId`: The session identifier
167
+ - `memory`: The current memory state
168
+ - `messages`: Array of conversation messages
169
+ - `sessionType`: The type of session (TEXT, VOICE, etc.)
170
+ - Other state properties
171
+
172
+ #### Usage Example
173
+
174
+ ```typescript
175
+ // Get current state
176
+ const state = await agent.getState('session-123');
177
+
178
+ // Access memory
179
+ console.log('User name:', state.memory.user?.name);
180
+
181
+ // Check conversation history
182
+ console.log('Message count:', state.messages.length);
183
+
184
+ // Get session type
185
+ console.log('Session type:', state.sessionType);
186
+ ```
187
+
188
+ ### compiledGraph
189
+
190
+ Access to the underlying LangGraph compiled graph for advanced operations.
191
+
192
+ #### Usage Example
193
+
194
+ ```typescript
195
+ // Get LangGraph state directly
196
+ const graphState = await agent.compiledGraph.getState(agent.getLangraphConfig(sessionId));
197
+
198
+ // Update state with LangGraph API
199
+ await agent.compiledGraph.updateState(agent.getLangraphConfig(sessionId), {
200
+ messages: [newMessage],
201
+ overrideStartFromNodeId: 'specific-node',
202
+ });
203
+ ```
204
+
205
+ ## State Management Best Practices
206
+
207
+ ### 1. Partial Updates
208
+
209
+ Always use partial updates to avoid overwriting existing state:
210
+
211
+ ```typescript
212
+ // ✅ Good - Partial update
213
+ await agent.updateState({
214
+ sessionId,
215
+ state: {
216
+ memory: {
217
+ user: { name: 'Jane' },
218
+ },
219
+ },
220
+ });
221
+
222
+ // ❌ Avoid - Don't replace entire memory
223
+ await agent.updateState({
224
+ sessionId,
225
+ state: {
226
+ memory: completeMemoryObject, // This might lose other fields
227
+ },
228
+ });
229
+ ```
230
+
231
+ ### 2. Atomic Operations
232
+
233
+ Group related updates together:
234
+
235
+ ```typescript
236
+ // ✅ Good - Single atomic update
237
+ await agent.updateState({
238
+ sessionId,
239
+ state: {
240
+ memory: {
241
+ order: { id: '123', status: 'confirmed' },
242
+ lastAction: 'order_confirmed',
243
+ },
244
+ messages: [confirmationMessage],
245
+ },
246
+ });
247
+
248
+ // ❌ Avoid - Multiple separate updates
249
+ await agent.updateState({ sessionId, state: { memory: { order: { id: '123' } } } });
250
+ await agent.updateState({ sessionId, state: { memory: { order: { status: 'confirmed' } } } });
251
+ await agent.updateState({ sessionId, state: { messages: [confirmationMessage] } });
252
+ ```
253
+
254
+ ### 3. State Validation
255
+
256
+ The state updates are validated against your memory schema:
257
+
258
+ ```typescript
259
+ try {
260
+ await agent.updateState({
261
+ sessionId,
262
+ state: {
263
+ memory: {
264
+ user: {
265
+ email: 'invalid-email', // Will fail validation if email has format validation
266
+ },
267
+ },
268
+ },
269
+ });
270
+ } catch (error) {
271
+ console.error('State validation failed:', error);
272
+ }
273
+ ```
274
+
275
+ ### 4. Tool State Updates
276
+
277
+ Tools should return state updates rather than calling `updateState` directly when possible:
278
+
279
+ ```typescript
280
+ // ✅ Preferred - Return state updates
281
+ async execute({ input, state }) {
282
+ const result = await processData(input);
283
+ return {
284
+ result,
285
+ state: {
286
+ memory: {
287
+ processedData: result.data
288
+ }
289
+ }
290
+ };
291
+ }
292
+
293
+ // ⚠️ Use only when necessary - Direct update
294
+ async execute({ input, state, agent }) {
295
+ const result = await processData(input);
296
+ await agent.updateState({
297
+ sessionId: state.sessionId,
298
+ state: {
299
+ memory: { processedData: result.data }
300
+ }
301
+ });
302
+ return { result };
303
+ }
304
+ ```
305
+
306
+ ## Tool Execution API
307
+
308
+ ### ToolExecutor
309
+
310
+ The `ToolExecutor` class enables standalone tool execution, particularly useful for browser automation and external tool invocations.
311
+
312
+ #### Setting Up Tool Execution
313
+
314
+ ```typescript
315
+ import { ToolExecutor } from '@minded-ai/mindedjs';
316
+
317
+ // Create a tool executor
318
+ const toolExecutor = new ToolExecutor(agent);
319
+
320
+ // Register tools that can be executed via requests
321
+ // Only tools with allowExecutionRequests: true will be registered
322
+ toolExecutor.registerTools(tools);
323
+ ```
324
+
325
+ #### Tool Configuration for Execution
326
+
327
+ Tools must explicitly opt-in to be executable via requests:
328
+
329
+ ```typescript
330
+ import { Tool } from '@minded-ai/mindedjs';
331
+
332
+ const myBrowserTool: Tool<typeof schema, Memory> = {
333
+ name: 'browserAction',
334
+ description: 'Performs browser automation',
335
+ input: schema,
336
+ allowExecutionRequests: true, // Required for ToolExecutor
337
+ execute: async ({ input, state, agent }) => {
338
+ // Access CDP URL if available (browser-use context)
339
+ if (state.cdpUrl) {
340
+ // Connect to browser using Playwright or similar
341
+ const browser = await chromium.connectOverCDP(state.cdpUrl);
342
+ const page = browser.contexts()[0].pages()[0];
343
+
344
+ // Perform browser automation
345
+ await page.goto(input.url);
346
+ const title = await page.title();
347
+
348
+ return {
349
+ result: { pageTitle: title },
350
+ state: {
351
+ memory: {
352
+ lastVisitedUrl: input.url,
353
+ },
354
+ },
355
+ };
356
+ }
357
+
358
+ // Fallback for non-browser context
359
+ return { result: 'Browser context not available' };
360
+ },
361
+ };
362
+ ```
363
+
364
+ #### Executing Tools
365
+
366
+ ```typescript
367
+ const response = await toolExecutor.executeTool({
368
+ toolName: 'browserAction',
369
+ toolParams: { url: 'https://example.com' },
370
+ sessionId: 'session-123',
371
+ requestId: 'req-456',
372
+ cdpUrl: 'ws://localhost:9222/devtools/browser/...', // Optional, for browser-use
373
+ });
374
+
375
+ if (response.error) {
376
+ console.error('Tool execution failed:', response.error);
377
+ } else {
378
+ console.log('Tool result:', response.result);
379
+ }
380
+ ```
381
+
382
+ ### CDP URL and Browser Automation
383
+
384
+ When tools are executed in a browser-use context, the Chrome DevTools Protocol (CDP) URL is available in the state:
385
+
386
+ #### Accessing CDP URL in Tools
387
+
388
+ ```typescript
389
+ const browserTool: Tool<typeof schema, Memory> = {
390
+ name: 'advancedBrowserAction',
391
+ description: 'Advanced browser automation with direct CDP access',
392
+ input: schema,
393
+ allowExecutionRequests: true,
394
+ execute: async ({ input, state, agent }) => {
395
+ const { cdpUrl } = state;
396
+
397
+ if (!cdpUrl) {
398
+ return {
399
+ result: 'This tool requires browser context',
400
+ error: 'CDP URL not available',
401
+ };
402
+ }
403
+
404
+ // Use Playwright with CDP
405
+ const browser = await playwright.chromium.connectOverCDP(cdpUrl);
406
+ const context = browser.contexts()[0];
407
+ const page = context.pages()[0];
408
+
409
+ // Perform complex browser automation
410
+ await page.evaluate(() => {
411
+ // Execute JavaScript in the browser
412
+ document.querySelector('#submit')?.click();
413
+ });
414
+
415
+ // Take screenshot
416
+ const screenshot = await page.screenshot();
417
+
418
+ return {
419
+ result: {
420
+ success: true,
421
+ screenshot: screenshot.toString('base64'),
422
+ },
423
+ state: {
424
+ memory: {
425
+ lastAction: 'browser_automation',
426
+ timestamp: new Date().toISOString(),
427
+ },
428
+ },
429
+ };
430
+ },
431
+ };
432
+ ```
433
+
434
+ #### Browser-Use Integration Flow
435
+
436
+ 1. Browser-use requests tool execution via socket
437
+ 2. ToolExecutor receives request with CDP URL
438
+ 3. CDP URL is injected into state (`state.cdpUrl`)
439
+ 4. Tool connects to browser using CDP URL
440
+ 5. Tool performs automation and returns results
441
+ 6. State updates are automatically applied
442
+
443
+ #### Security Considerations
444
+
445
+ - Tools must have `allowExecutionRequests: true` to be executable via ToolExecutor
446
+ - CDP URLs are only available during browser-use execution context
447
+ - Tools should validate CDP URL availability before attempting browser operations
448
+ - Always handle connection failures gracefully
449
+
450
+ ## Integration with Other Features
451
+
452
+ ### With Browser Use Tools
453
+
454
+ When using browser automation tools, state updates happen automatically through the ToolExecutor:
455
+
456
+ ```typescript
457
+ // Browser tools can update state via the ToolExecutor
458
+ const toolExecutor = new ToolExecutor(agent);
459
+ toolExecutor.registerTools(browserTools);
460
+
461
+ // State updates are handled internally when tools return state changes
462
+ // The cdpUrl is automatically injected when available
463
+ ```
464
+
465
+ ### With Voice Sessions
466
+
467
+ Voice sessions use `updateState` for real-time corrections:
468
+
469
+ ```typescript
470
+ // Voice session correction flow
471
+ const voiceSession = new VoiceSession(agent, sessionId);
472
+ // Corrections use updateState internally
473
+ ```
474
+
475
+ ### With Events
476
+
477
+ State can be updated in event handlers:
478
+
479
+ ```typescript
480
+ agent.on(AgentEvents.TRIGGER_EVENT, async ({ triggerName, sessionId }) => {
481
+ if (triggerName === 'external_update') {
482
+ await agent.updateState({
483
+ sessionId,
484
+ state: {
485
+ memory: {
486
+ lastTrigger: triggerName,
487
+ triggerTime: new Date().toISOString(),
488
+ },
489
+ },
490
+ });
491
+ }
492
+ });
493
+ ```
494
+
495
+ ## Error Handling
496
+
497
+ Always handle potential errors when updating state:
498
+
499
+ ```typescript
500
+ try {
501
+ await agent.updateState({
502
+ sessionId,
503
+ state: stateUpdates,
504
+ });
505
+ } catch (error) {
506
+ if (error.message.includes('Session not found')) {
507
+ // Handle missing session
508
+ console.error('Session does not exist:', sessionId);
509
+ } else if (error.message.includes('Validation')) {
510
+ // Handle validation errors
511
+ console.error('Invalid state update:', error);
512
+ } else {
513
+ // Handle other errors
514
+ console.error('Failed to update state:', error);
515
+ }
516
+ }
517
+ ```
518
+
519
+ ## Related Documentation
520
+
521
+ - [Memory](./memory.md) - Learn about memory schemas and management
522
+ - [Events](./events.md) - Handle agent events and triggers
523
+ - [Debugging](./debugging.md) - Debug state updates and transitions
524
+ - [Tools](../low-code-editor/tools.md) - Create tools that update state