@baselineos/autonomy 0.1.0
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/.turbo/turbo-build.log +14 -0
- package/.turbo/turbo-test.log +14 -0
- package/LICENSE +17 -0
- package/README.md +19 -0
- package/dist/index.d.ts +539 -0
- package/dist/index.js +2540 -0
- package/package.json +34 -0
- package/src/__tests__/smoke.test.ts +24 -0
- package/src/index.ts +62 -0
- package/src/integration.ts +600 -0
- package/src/lifecycle.ts +1323 -0
- package/src/mastra-engine.ts +1097 -0
- package/src/system.ts +654 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,1097 @@
|
|
|
1
|
+
import { EventEmitter } from 'events';
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
|
|
4
|
+
// ---------------------------------------------------------------------------
|
|
5
|
+
// Types & Interfaces
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
|
|
8
|
+
export interface SafetyProtocol {
|
|
9
|
+
enabled: boolean;
|
|
10
|
+
level: string;
|
|
11
|
+
rules: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface SafetyCheckResult {
|
|
15
|
+
protocol: string;
|
|
16
|
+
timestamp: Date;
|
|
17
|
+
status: string;
|
|
18
|
+
violations: unknown[];
|
|
19
|
+
details: Record<string, unknown>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface SafetyMonitoringResult {
|
|
23
|
+
timestamp: Date;
|
|
24
|
+
trustScore: number;
|
|
25
|
+
safetyChecks: SafetyCheckResult[];
|
|
26
|
+
violations: unknown[];
|
|
27
|
+
recommendations: unknown[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface MastraAgentPerformanceMetrics {
|
|
31
|
+
tasksCompleted: number;
|
|
32
|
+
tasksFailed: number;
|
|
33
|
+
averageResponseTime: number;
|
|
34
|
+
trustScore: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AgentTask {
|
|
38
|
+
id: string;
|
|
39
|
+
type: string;
|
|
40
|
+
description: string;
|
|
41
|
+
input: Record<string, unknown>;
|
|
42
|
+
priority: number;
|
|
43
|
+
timeout: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface TaskResult {
|
|
47
|
+
taskId: string;
|
|
48
|
+
agentId: string;
|
|
49
|
+
status: string;
|
|
50
|
+
output: unknown;
|
|
51
|
+
reasoning: string;
|
|
52
|
+
confidence: number;
|
|
53
|
+
executionTime: number;
|
|
54
|
+
timestamp: Date;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ReasoningStep {
|
|
58
|
+
step: number;
|
|
59
|
+
action: string;
|
|
60
|
+
reasoning: string;
|
|
61
|
+
confidence: number;
|
|
62
|
+
timestamp: Date;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface ReasoningResult {
|
|
66
|
+
agentId: string;
|
|
67
|
+
task: string;
|
|
68
|
+
steps: ReasoningStep[];
|
|
69
|
+
finalDecision: string;
|
|
70
|
+
confidence: number;
|
|
71
|
+
timestamp: Date;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface CoordinationPlan {
|
|
75
|
+
coordinatorId: string;
|
|
76
|
+
taskId: string;
|
|
77
|
+
participants: string[];
|
|
78
|
+
steps: CoordinationStep[];
|
|
79
|
+
timestamp: Date;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface CoordinationStep {
|
|
83
|
+
step: number;
|
|
84
|
+
agentId: string;
|
|
85
|
+
action: string;
|
|
86
|
+
status: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface CoordinationResult {
|
|
90
|
+
plan: CoordinationPlan;
|
|
91
|
+
results: TaskResult[];
|
|
92
|
+
overallStatus: string;
|
|
93
|
+
timestamp: Date;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface EngineStatus {
|
|
97
|
+
engineId: string;
|
|
98
|
+
version: string;
|
|
99
|
+
status: string;
|
|
100
|
+
capabilities: string[];
|
|
101
|
+
agentCount: number;
|
|
102
|
+
trustScore: number;
|
|
103
|
+
learningRate: number;
|
|
104
|
+
memorySize: number;
|
|
105
|
+
safetyProtocols: string[];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface AgentInfo {
|
|
109
|
+
id: string;
|
|
110
|
+
name: string;
|
|
111
|
+
type: string;
|
|
112
|
+
capabilities: string[];
|
|
113
|
+
status: string;
|
|
114
|
+
trustScore: number;
|
|
115
|
+
performance: MastraAgentPerformanceMetrics;
|
|
116
|
+
taskHistory: TaskResult[];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// MastraAutonomyEngine
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
export class MastraAutonomyEngine extends EventEmitter {
|
|
124
|
+
engineId: string;
|
|
125
|
+
version: string;
|
|
126
|
+
status: string;
|
|
127
|
+
capabilities: Set<string>;
|
|
128
|
+
agents: Map<string, MastraAutonomousAgent>;
|
|
129
|
+
memory: Map<string, unknown>;
|
|
130
|
+
safetyProtocols: Map<string, SafetyProtocol>;
|
|
131
|
+
trustScore: number;
|
|
132
|
+
learningRate: number;
|
|
133
|
+
private llm: unknown;
|
|
134
|
+
private globalMemory: unknown;
|
|
135
|
+
|
|
136
|
+
constructor() {
|
|
137
|
+
super();
|
|
138
|
+
this.engineId = randomUUID();
|
|
139
|
+
this.version = '1.0.0';
|
|
140
|
+
this.status = 'initializing';
|
|
141
|
+
this.capabilities = new Set();
|
|
142
|
+
this.agents = new Map();
|
|
143
|
+
this.memory = new Map();
|
|
144
|
+
this.safetyProtocols = new Map();
|
|
145
|
+
this.trustScore = 1.0;
|
|
146
|
+
this.learningRate = 0.01;
|
|
147
|
+
this.llm = null;
|
|
148
|
+
this.globalMemory = null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// -----------------------------------------------------------------------
|
|
152
|
+
// Initialization
|
|
153
|
+
// -----------------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
async initialize(): Promise<void> {
|
|
156
|
+
console.log('[MastraAutonomyEngine] Initializing Mastra Autonomy Engine...');
|
|
157
|
+
|
|
158
|
+
this.initializeSafetyProtocols();
|
|
159
|
+
this.initializeCapabilities();
|
|
160
|
+
|
|
161
|
+
// Attempt to initialize LangChain components (optional peer deps)
|
|
162
|
+
try {
|
|
163
|
+
await this.initializeLLM();
|
|
164
|
+
} catch {
|
|
165
|
+
console.log('[MastraAutonomyEngine] LLM initialization skipped (optional dependency)');
|
|
166
|
+
this.llm = null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
try {
|
|
170
|
+
await this.initializeMemory();
|
|
171
|
+
} catch {
|
|
172
|
+
console.log('[MastraAutonomyEngine] Memory initialization skipped (optional dependency)');
|
|
173
|
+
this.globalMemory = null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
this.status = 'ready';
|
|
177
|
+
|
|
178
|
+
console.log('[MastraAutonomyEngine] Engine initialized');
|
|
179
|
+
console.log(`[MastraAutonomyEngine] Engine ID: ${this.engineId}`);
|
|
180
|
+
console.log(`[MastraAutonomyEngine] Version: ${this.version}`);
|
|
181
|
+
console.log(`[MastraAutonomyEngine] Capabilities: ${this.capabilities.size}`);
|
|
182
|
+
console.log(`[MastraAutonomyEngine] Safety protocols: ${this.safetyProtocols.size}`);
|
|
183
|
+
console.log(`[MastraAutonomyEngine] Trust score: ${this.trustScore}`);
|
|
184
|
+
|
|
185
|
+
this.emit('initialized', {
|
|
186
|
+
engineId: this.engineId,
|
|
187
|
+
version: this.version,
|
|
188
|
+
capabilities: Array.from(this.capabilities),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
private async initializeLLM(): Promise<void> {
|
|
193
|
+
// LangChain LLM is an optional peer dependency
|
|
194
|
+
// In production, this would be: new ChatOpenAI({ ... })
|
|
195
|
+
this.llm = {
|
|
196
|
+
type: 'mock-llm',
|
|
197
|
+
model: 'gpt-4',
|
|
198
|
+
invoke: async (input: unknown): Promise<{ content: string }> => {
|
|
199
|
+
return { content: `Mock LLM response for: ${JSON.stringify(input)}` };
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
console.log('[MastraAutonomyEngine] LLM initialized (mock mode)');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private async initializeMemory(): Promise<void> {
|
|
206
|
+
// LangChain memory is an optional peer dependency
|
|
207
|
+
// In production, this would be: new BufferMemory({ ... })
|
|
208
|
+
this.globalMemory = {
|
|
209
|
+
type: 'mock-memory',
|
|
210
|
+
entries: new Map<string, unknown>(),
|
|
211
|
+
saveContext: async (_input: Record<string, unknown>, _output: Record<string, unknown>): Promise<void> => {
|
|
212
|
+
// No-op in mock mode
|
|
213
|
+
},
|
|
214
|
+
loadMemoryVariables: async (): Promise<Record<string, unknown>> => {
|
|
215
|
+
return { history: '' };
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
console.log('[MastraAutonomyEngine] Global memory initialized (mock mode)');
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// -----------------------------------------------------------------------
|
|
222
|
+
// Safety Protocols
|
|
223
|
+
// -----------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
private initializeSafetyProtocols(): void {
|
|
226
|
+
const protocols: Array<[string, SafetyProtocol]> = [
|
|
227
|
+
[
|
|
228
|
+
'content-safety',
|
|
229
|
+
{
|
|
230
|
+
enabled: true,
|
|
231
|
+
level: 'strict',
|
|
232
|
+
rules: [
|
|
233
|
+
'no-harmful-content',
|
|
234
|
+
'no-bias-amplification',
|
|
235
|
+
'no-private-data-exposure',
|
|
236
|
+
'content-appropriateness-check',
|
|
237
|
+
],
|
|
238
|
+
},
|
|
239
|
+
],
|
|
240
|
+
[
|
|
241
|
+
'autonomy-limits',
|
|
242
|
+
{
|
|
243
|
+
enabled: true,
|
|
244
|
+
level: 'supervised',
|
|
245
|
+
rules: [
|
|
246
|
+
'human-oversight-required',
|
|
247
|
+
'max-autonomy-level-enforced',
|
|
248
|
+
'decision-logging-required',
|
|
249
|
+
'rollback-capability-required',
|
|
250
|
+
],
|
|
251
|
+
},
|
|
252
|
+
],
|
|
253
|
+
[
|
|
254
|
+
'trust-management',
|
|
255
|
+
{
|
|
256
|
+
enabled: true,
|
|
257
|
+
level: 'dynamic',
|
|
258
|
+
rules: [
|
|
259
|
+
'trust-score-monitoring',
|
|
260
|
+
'trust-decay-enforcement',
|
|
261
|
+
'trust-escalation-protocol',
|
|
262
|
+
'minimum-trust-threshold',
|
|
263
|
+
],
|
|
264
|
+
},
|
|
265
|
+
],
|
|
266
|
+
[
|
|
267
|
+
'resource-safety',
|
|
268
|
+
{
|
|
269
|
+
enabled: true,
|
|
270
|
+
level: 'bounded',
|
|
271
|
+
rules: [
|
|
272
|
+
'resource-usage-limits',
|
|
273
|
+
'cost-threshold-enforcement',
|
|
274
|
+
'rate-limiting',
|
|
275
|
+
'circuit-breaker-enabled',
|
|
276
|
+
],
|
|
277
|
+
},
|
|
278
|
+
],
|
|
279
|
+
];
|
|
280
|
+
|
|
281
|
+
for (const [id, protocol] of protocols) {
|
|
282
|
+
this.safetyProtocols.set(id, protocol);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// -----------------------------------------------------------------------
|
|
287
|
+
// Capabilities
|
|
288
|
+
// -----------------------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
private initializeCapabilities(): void {
|
|
291
|
+
const caps = [
|
|
292
|
+
'autonomous-reasoning',
|
|
293
|
+
'task-execution',
|
|
294
|
+
'multi-agent-coordination',
|
|
295
|
+
'safety-monitoring',
|
|
296
|
+
'trust-management',
|
|
297
|
+
'adaptive-learning',
|
|
298
|
+
'natural-language-understanding',
|
|
299
|
+
'code-generation',
|
|
300
|
+
'decision-making',
|
|
301
|
+
'self-evaluation',
|
|
302
|
+
'context-management',
|
|
303
|
+
'tool-usage',
|
|
304
|
+
];
|
|
305
|
+
|
|
306
|
+
for (const cap of caps) {
|
|
307
|
+
this.capabilities.add(cap);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// -----------------------------------------------------------------------
|
|
312
|
+
// Agent Management
|
|
313
|
+
// -----------------------------------------------------------------------
|
|
314
|
+
|
|
315
|
+
async createAutonomousAgent(
|
|
316
|
+
name: string,
|
|
317
|
+
type: string,
|
|
318
|
+
capabilities: string[]
|
|
319
|
+
): Promise<MastraAutonomousAgent> {
|
|
320
|
+
console.log(`[MastraAutonomyEngine] Creating autonomous agent: ${name} (type: ${type})`);
|
|
321
|
+
|
|
322
|
+
const agent = new MastraAutonomousAgent(name, type, capabilities, this);
|
|
323
|
+
this.agents.set(agent.id, agent);
|
|
324
|
+
|
|
325
|
+
console.log(`[MastraAutonomyEngine] Agent created: ${agent.id}`);
|
|
326
|
+
console.log(`[MastraAutonomyEngine] Name: ${name}`);
|
|
327
|
+
console.log(`[MastraAutonomyEngine] Type: ${type}`);
|
|
328
|
+
console.log(`[MastraAutonomyEngine] Capabilities: ${capabilities.join(', ')}`);
|
|
329
|
+
|
|
330
|
+
this.emit('agent-created', {
|
|
331
|
+
agentId: agent.id,
|
|
332
|
+
name,
|
|
333
|
+
type,
|
|
334
|
+
capabilities,
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
return agent;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// -----------------------------------------------------------------------
|
|
341
|
+
// Autonomous Reasoning
|
|
342
|
+
// -----------------------------------------------------------------------
|
|
343
|
+
|
|
344
|
+
async executeAutonomousReasoning(
|
|
345
|
+
agentId: string,
|
|
346
|
+
task: string,
|
|
347
|
+
context: Record<string, unknown> = {}
|
|
348
|
+
): Promise<ReasoningResult> {
|
|
349
|
+
console.log(`[MastraAutonomyEngine] Executing autonomous reasoning for agent: ${agentId}`);
|
|
350
|
+
|
|
351
|
+
const agent = this.agents.get(agentId);
|
|
352
|
+
if (!agent) {
|
|
353
|
+
throw new Error(`Agent not found: ${agentId}`);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const steps: ReasoningStep[] = [];
|
|
357
|
+
let stepNumber = 0;
|
|
358
|
+
|
|
359
|
+
// Step 1: Analyze task
|
|
360
|
+
stepNumber += 1;
|
|
361
|
+
steps.push({
|
|
362
|
+
step: stepNumber,
|
|
363
|
+
action: 'analyze-task',
|
|
364
|
+
reasoning: `Analyzing task: "${task}" with context keys: ${Object.keys(context).join(', ') || 'none'}`,
|
|
365
|
+
confidence: 0.9,
|
|
366
|
+
timestamp: new Date(),
|
|
367
|
+
});
|
|
368
|
+
await this.delay(50);
|
|
369
|
+
|
|
370
|
+
// Step 2: Retrieve relevant memory
|
|
371
|
+
stepNumber += 1;
|
|
372
|
+
steps.push({
|
|
373
|
+
step: stepNumber,
|
|
374
|
+
action: 'retrieve-memory',
|
|
375
|
+
reasoning: 'Retrieving relevant context and past experiences from memory',
|
|
376
|
+
confidence: 0.85,
|
|
377
|
+
timestamp: new Date(),
|
|
378
|
+
});
|
|
379
|
+
await this.delay(30);
|
|
380
|
+
|
|
381
|
+
// Step 3: Evaluate options
|
|
382
|
+
stepNumber += 1;
|
|
383
|
+
steps.push({
|
|
384
|
+
step: stepNumber,
|
|
385
|
+
action: 'evaluate-options',
|
|
386
|
+
reasoning: 'Evaluating possible approaches and their trade-offs',
|
|
387
|
+
confidence: 0.8,
|
|
388
|
+
timestamp: new Date(),
|
|
389
|
+
});
|
|
390
|
+
await this.delay(40);
|
|
391
|
+
|
|
392
|
+
// Step 4: Safety check
|
|
393
|
+
stepNumber += 1;
|
|
394
|
+
const safetyResult = await this.runSafetyCheck('content-safety', task);
|
|
395
|
+
steps.push({
|
|
396
|
+
step: stepNumber,
|
|
397
|
+
action: 'safety-check',
|
|
398
|
+
reasoning: `Safety check result: ${safetyResult.status}`,
|
|
399
|
+
confidence: safetyResult.status === 'passed' ? 0.95 : 0.5,
|
|
400
|
+
timestamp: new Date(),
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
// Step 5: Make decision
|
|
404
|
+
stepNumber += 1;
|
|
405
|
+
const finalConfidence =
|
|
406
|
+
steps.reduce((sum, s) => sum + s.confidence, 0) / steps.length;
|
|
407
|
+
steps.push({
|
|
408
|
+
step: stepNumber,
|
|
409
|
+
action: 'make-decision',
|
|
410
|
+
reasoning: `Final decision made with aggregate confidence: ${finalConfidence.toFixed(3)}`,
|
|
411
|
+
confidence: finalConfidence,
|
|
412
|
+
timestamp: new Date(),
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
const result: ReasoningResult = {
|
|
416
|
+
agentId,
|
|
417
|
+
task,
|
|
418
|
+
steps,
|
|
419
|
+
finalDecision: `Execute task "${task}" using agent ${agent.name} with confidence ${finalConfidence.toFixed(3)}`,
|
|
420
|
+
confidence: finalConfidence,
|
|
421
|
+
timestamp: new Date(),
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
// Store reasoning in memory
|
|
425
|
+
this.memory.set(`reasoning-${agentId}-${Date.now()}`, result);
|
|
426
|
+
|
|
427
|
+
this.emit('reasoning-complete', result);
|
|
428
|
+
|
|
429
|
+
return result;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// -----------------------------------------------------------------------
|
|
433
|
+
// Task Execution
|
|
434
|
+
// -----------------------------------------------------------------------
|
|
435
|
+
|
|
436
|
+
async executeAutonomousTask(
|
|
437
|
+
agentId: string,
|
|
438
|
+
task: AgentTask
|
|
439
|
+
): Promise<TaskResult> {
|
|
440
|
+
console.log(
|
|
441
|
+
`[MastraAutonomyEngine] Executing autonomous task: ${task.description} (agent: ${agentId})`
|
|
442
|
+
);
|
|
443
|
+
|
|
444
|
+
const agent = this.agents.get(agentId);
|
|
445
|
+
if (!agent) {
|
|
446
|
+
throw new Error(`Agent not found: ${agentId}`);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Pre-execution safety check
|
|
450
|
+
const safetyCheck = await this.runSafetyCheck('autonomy-limits', task.description);
|
|
451
|
+
if (safetyCheck.status === 'failed') {
|
|
452
|
+
const failedResult: TaskResult = {
|
|
453
|
+
taskId: task.id,
|
|
454
|
+
agentId,
|
|
455
|
+
status: 'blocked',
|
|
456
|
+
output: null,
|
|
457
|
+
reasoning: 'Task blocked by safety protocol',
|
|
458
|
+
confidence: 0,
|
|
459
|
+
executionTime: 0,
|
|
460
|
+
timestamp: new Date(),
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
this.emit('task-blocked', { task, safetyCheck });
|
|
464
|
+
return failedResult;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Execute the task
|
|
468
|
+
const result = await agent.executeTask(task);
|
|
469
|
+
|
|
470
|
+
// Post-execution trust update
|
|
471
|
+
if (result.status === 'completed') {
|
|
472
|
+
this.trustScore = Math.min(1.0, this.trustScore + this.learningRate * 0.1);
|
|
473
|
+
} else if (result.status === 'failed') {
|
|
474
|
+
this.trustScore = Math.max(0.0, this.trustScore - this.learningRate * 0.2);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// Store result in memory
|
|
478
|
+
this.memory.set(`task-${task.id}`, result);
|
|
479
|
+
|
|
480
|
+
this.emit('task-complete', result);
|
|
481
|
+
|
|
482
|
+
return result;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// -----------------------------------------------------------------------
|
|
486
|
+
// Multi-Agent Coordination
|
|
487
|
+
// -----------------------------------------------------------------------
|
|
488
|
+
|
|
489
|
+
async coordinateAgents(
|
|
490
|
+
agentIds: string[],
|
|
491
|
+
task: AgentTask
|
|
492
|
+
): Promise<CoordinationResult> {
|
|
493
|
+
console.log(
|
|
494
|
+
`[MastraAutonomyEngine] Coordinating ${agentIds.length} agents for task: ${task.description}`
|
|
495
|
+
);
|
|
496
|
+
|
|
497
|
+
const agents: MastraAutonomousAgent[] = [];
|
|
498
|
+
for (const id of agentIds) {
|
|
499
|
+
const agent = this.agents.get(id);
|
|
500
|
+
if (!agent) {
|
|
501
|
+
throw new Error(`Agent not found: ${id}`);
|
|
502
|
+
}
|
|
503
|
+
agents.push(agent);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Create coordination plan
|
|
507
|
+
const plan = this.createCoordinationPlan(agents, task);
|
|
508
|
+
|
|
509
|
+
console.log(`[MastraAutonomyEngine] Coordination plan created with ${plan.steps.length} steps`);
|
|
510
|
+
|
|
511
|
+
// Execute plan steps
|
|
512
|
+
const results: TaskResult[] = [];
|
|
513
|
+
for (const step of plan.steps) {
|
|
514
|
+
const agent = this.agents.get(step.agentId);
|
|
515
|
+
if (!agent) continue;
|
|
516
|
+
|
|
517
|
+
console.log(
|
|
518
|
+
`[MastraAutonomyEngine] Step ${step.step}: Agent ${agent.name} - ${step.action}`
|
|
519
|
+
);
|
|
520
|
+
|
|
521
|
+
const subtask: AgentTask = {
|
|
522
|
+
id: randomUUID(),
|
|
523
|
+
type: task.type,
|
|
524
|
+
description: `${step.action} (coordinated subtask of: ${task.description})`,
|
|
525
|
+
input: { ...task.input, coordinationStep: step.step },
|
|
526
|
+
priority: task.priority,
|
|
527
|
+
timeout: task.timeout,
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
const result = await agent.executeTask(subtask);
|
|
531
|
+
results.push(result);
|
|
532
|
+
step.status = result.status;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const allCompleted = results.every((r) => r.status === 'completed');
|
|
536
|
+
|
|
537
|
+
const coordinationResult: CoordinationResult = {
|
|
538
|
+
plan,
|
|
539
|
+
results,
|
|
540
|
+
overallStatus: allCompleted ? 'completed' : 'partial',
|
|
541
|
+
timestamp: new Date(),
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
console.log(
|
|
545
|
+
`[MastraAutonomyEngine] Coordination complete: ${coordinationResult.overallStatus}`
|
|
546
|
+
);
|
|
547
|
+
|
|
548
|
+
this.emit('coordination-complete', coordinationResult);
|
|
549
|
+
|
|
550
|
+
return coordinationResult;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
private createCoordinationPlan(
|
|
554
|
+
agents: MastraAutonomousAgent[],
|
|
555
|
+
task: AgentTask
|
|
556
|
+
): CoordinationPlan {
|
|
557
|
+
const steps: CoordinationStep[] = [];
|
|
558
|
+
let stepNumber = 0;
|
|
559
|
+
|
|
560
|
+
for (const agent of agents) {
|
|
561
|
+
stepNumber += 1;
|
|
562
|
+
steps.push({
|
|
563
|
+
step: stepNumber,
|
|
564
|
+
agentId: agent.id,
|
|
565
|
+
action: `Process ${task.type} task component using ${agent.type} capabilities`,
|
|
566
|
+
status: 'pending',
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// Add aggregation step using the first agent
|
|
571
|
+
if (agents.length > 1) {
|
|
572
|
+
stepNumber += 1;
|
|
573
|
+
steps.push({
|
|
574
|
+
step: stepNumber,
|
|
575
|
+
agentId: agents[0].id,
|
|
576
|
+
action: 'Aggregate and synthesize results from all participating agents',
|
|
577
|
+
status: 'pending',
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
return {
|
|
582
|
+
coordinatorId: this.engineId,
|
|
583
|
+
taskId: task.id,
|
|
584
|
+
participants: agents.map((a) => a.id),
|
|
585
|
+
steps,
|
|
586
|
+
timestamp: new Date(),
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// -----------------------------------------------------------------------
|
|
591
|
+
// Trust & Safety Monitoring
|
|
592
|
+
// -----------------------------------------------------------------------
|
|
593
|
+
|
|
594
|
+
async monitorTrustAndSafety(): Promise<SafetyMonitoringResult> {
|
|
595
|
+
console.log('[MastraAutonomyEngine] Running trust and safety monitoring...');
|
|
596
|
+
|
|
597
|
+
const safetyChecks: SafetyCheckResult[] = [];
|
|
598
|
+
|
|
599
|
+
// Run all safety protocol checks
|
|
600
|
+
for (const [protocolId] of this.safetyProtocols) {
|
|
601
|
+
const check = await this.runSafetyCheck(protocolId, 'periodic-monitoring');
|
|
602
|
+
safetyChecks.push(check);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// Validate trust score
|
|
606
|
+
const trustValidation = this.validateTrust();
|
|
607
|
+
|
|
608
|
+
// Check autonomy limits
|
|
609
|
+
const autonomyCheck = this.checkAutonomyLimits();
|
|
610
|
+
|
|
611
|
+
// Collect all violations
|
|
612
|
+
const violations: unknown[] = [];
|
|
613
|
+
for (const check of safetyChecks) {
|
|
614
|
+
if (check.violations.length > 0) {
|
|
615
|
+
violations.push(...check.violations);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// Generate recommendations
|
|
620
|
+
const recommendations = this.generateSafetyRecommendations(
|
|
621
|
+
safetyChecks,
|
|
622
|
+
trustValidation,
|
|
623
|
+
autonomyCheck
|
|
624
|
+
);
|
|
625
|
+
|
|
626
|
+
const result: SafetyMonitoringResult = {
|
|
627
|
+
timestamp: new Date(),
|
|
628
|
+
trustScore: this.trustScore,
|
|
629
|
+
safetyChecks,
|
|
630
|
+
violations,
|
|
631
|
+
recommendations,
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
console.log(`[MastraAutonomyEngine] Safety monitoring complete`);
|
|
635
|
+
console.log(`[MastraAutonomyEngine] Trust score: ${this.trustScore.toFixed(3)}`);
|
|
636
|
+
console.log(`[MastraAutonomyEngine] Safety checks: ${safetyChecks.length}`);
|
|
637
|
+
console.log(`[MastraAutonomyEngine] Violations: ${violations.length}`);
|
|
638
|
+
console.log(`[MastraAutonomyEngine] Recommendations: ${recommendations.length}`);
|
|
639
|
+
|
|
640
|
+
this.emit('safety-monitoring-complete', result);
|
|
641
|
+
|
|
642
|
+
return result;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async runSafetyCheck(
|
|
646
|
+
protocolId: string,
|
|
647
|
+
context: string
|
|
648
|
+
): Promise<SafetyCheckResult> {
|
|
649
|
+
const protocol = this.safetyProtocols.get(protocolId);
|
|
650
|
+
if (!protocol) {
|
|
651
|
+
return {
|
|
652
|
+
protocol: protocolId,
|
|
653
|
+
timestamp: new Date(),
|
|
654
|
+
status: 'unknown',
|
|
655
|
+
violations: [],
|
|
656
|
+
details: { error: `Protocol not found: ${protocolId}` },
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
if (!protocol.enabled) {
|
|
661
|
+
return {
|
|
662
|
+
protocol: protocolId,
|
|
663
|
+
timestamp: new Date(),
|
|
664
|
+
status: 'skipped',
|
|
665
|
+
violations: [],
|
|
666
|
+
details: { reason: 'Protocol disabled' },
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// Simulate safety check
|
|
671
|
+
const violations: unknown[] = [];
|
|
672
|
+
const details: Record<string, unknown> = {
|
|
673
|
+
protocolLevel: protocol.level,
|
|
674
|
+
rulesChecked: protocol.rules.length,
|
|
675
|
+
context,
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
switch (protocolId) {
|
|
679
|
+
case 'content-safety':
|
|
680
|
+
details.contentCheck = this.checkContentSafety(context);
|
|
681
|
+
break;
|
|
682
|
+
case 'autonomy-limits':
|
|
683
|
+
details.autonomyCheck = this.checkAutonomyLimits();
|
|
684
|
+
break;
|
|
685
|
+
case 'trust-management':
|
|
686
|
+
details.trustCheck = this.validateTrust();
|
|
687
|
+
break;
|
|
688
|
+
case 'resource-safety':
|
|
689
|
+
details.resourceCheck = {
|
|
690
|
+
cpuUsage: Math.random() * 100,
|
|
691
|
+
memoryUsage: Math.random() * 100,
|
|
692
|
+
withinLimits: true,
|
|
693
|
+
};
|
|
694
|
+
break;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const passed = violations.length === 0;
|
|
698
|
+
|
|
699
|
+
return {
|
|
700
|
+
protocol: protocolId,
|
|
701
|
+
timestamp: new Date(),
|
|
702
|
+
status: passed ? 'passed' : 'failed',
|
|
703
|
+
violations,
|
|
704
|
+
details,
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
private checkContentSafety(content: string): Record<string, unknown> {
|
|
709
|
+
const harmfulPatterns = ['harmful', 'dangerous', 'malicious', 'exploit'];
|
|
710
|
+
const foundPatterns: string[] = [];
|
|
711
|
+
|
|
712
|
+
for (const pattern of harmfulPatterns) {
|
|
713
|
+
if (content.toLowerCase().includes(pattern)) {
|
|
714
|
+
foundPatterns.push(pattern);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
return {
|
|
719
|
+
safe: foundPatterns.length === 0,
|
|
720
|
+
checkedPatterns: harmfulPatterns.length,
|
|
721
|
+
foundPatterns,
|
|
722
|
+
contentLength: content.length,
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
private validateTrust(): Record<string, unknown> {
|
|
727
|
+
const minimumTrust = 0.3;
|
|
728
|
+
const warningTrust = 0.5;
|
|
729
|
+
|
|
730
|
+
return {
|
|
731
|
+
currentScore: this.trustScore,
|
|
732
|
+
minimumThreshold: minimumTrust,
|
|
733
|
+
warningThreshold: warningTrust,
|
|
734
|
+
status:
|
|
735
|
+
this.trustScore >= warningTrust
|
|
736
|
+
? 'healthy'
|
|
737
|
+
: this.trustScore >= minimumTrust
|
|
738
|
+
? 'warning'
|
|
739
|
+
: 'critical',
|
|
740
|
+
agentTrustScores: Array.from(this.agents.entries()).map(([id, agent]) => ({
|
|
741
|
+
agentId: id,
|
|
742
|
+
trustScore: agent.trustScore,
|
|
743
|
+
})),
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
private checkAutonomyLimits(): Record<string, unknown> {
|
|
748
|
+
const maxAgents = 50;
|
|
749
|
+
const maxMemoryEntries = 10000;
|
|
750
|
+
|
|
751
|
+
return {
|
|
752
|
+
currentAgents: this.agents.size,
|
|
753
|
+
maxAgents,
|
|
754
|
+
agentUtilization: this.agents.size / maxAgents,
|
|
755
|
+
currentMemoryEntries: this.memory.size,
|
|
756
|
+
maxMemoryEntries,
|
|
757
|
+
memoryUtilization: this.memory.size / maxMemoryEntries,
|
|
758
|
+
withinLimits: this.agents.size < maxAgents && this.memory.size < maxMemoryEntries,
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
private generateSafetyRecommendations(
|
|
763
|
+
safetyChecks: SafetyCheckResult[],
|
|
764
|
+
trustValidation: Record<string, unknown>,
|
|
765
|
+
autonomyCheck: Record<string, unknown>
|
|
766
|
+
): unknown[] {
|
|
767
|
+
const recommendations: unknown[] = [];
|
|
768
|
+
|
|
769
|
+
// Check for failed safety protocols
|
|
770
|
+
for (const check of safetyChecks) {
|
|
771
|
+
if (check.status === 'failed') {
|
|
772
|
+
recommendations.push({
|
|
773
|
+
type: 'safety-protocol-failure',
|
|
774
|
+
protocol: check.protocol,
|
|
775
|
+
action: 'Review and resolve safety protocol violations',
|
|
776
|
+
priority: 'high',
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// Check trust status
|
|
782
|
+
if (trustValidation.status === 'critical') {
|
|
783
|
+
recommendations.push({
|
|
784
|
+
type: 'trust-critical',
|
|
785
|
+
action: 'Immediately reduce autonomy level and increase human oversight',
|
|
786
|
+
priority: 'critical',
|
|
787
|
+
});
|
|
788
|
+
} else if (trustValidation.status === 'warning') {
|
|
789
|
+
recommendations.push({
|
|
790
|
+
type: 'trust-warning',
|
|
791
|
+
action: 'Monitor trust score closely and consider reducing autonomy level',
|
|
792
|
+
priority: 'medium',
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// Check autonomy limits
|
|
797
|
+
if (!(autonomyCheck.withinLimits as boolean)) {
|
|
798
|
+
recommendations.push({
|
|
799
|
+
type: 'autonomy-limits',
|
|
800
|
+
action: 'Resource limits approaching - consider scaling or retiring idle agents',
|
|
801
|
+
priority: 'high',
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// Check agent utilization
|
|
806
|
+
const agentUtilization = (autonomyCheck.agentUtilization as number) ?? 0;
|
|
807
|
+
if (agentUtilization > 0.8) {
|
|
808
|
+
recommendations.push({
|
|
809
|
+
type: 'high-agent-utilization',
|
|
810
|
+
action: 'Agent pool nearing capacity - plan for scaling or agent retirement',
|
|
811
|
+
priority: 'medium',
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
return recommendations;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// -----------------------------------------------------------------------
|
|
819
|
+
// Status & Info
|
|
820
|
+
// -----------------------------------------------------------------------
|
|
821
|
+
|
|
822
|
+
getStatus(): EngineStatus {
|
|
823
|
+
return {
|
|
824
|
+
engineId: this.engineId,
|
|
825
|
+
version: this.version,
|
|
826
|
+
status: this.status,
|
|
827
|
+
capabilities: Array.from(this.capabilities),
|
|
828
|
+
agentCount: this.agents.size,
|
|
829
|
+
trustScore: this.trustScore,
|
|
830
|
+
learningRate: this.learningRate,
|
|
831
|
+
memorySize: this.memory.size,
|
|
832
|
+
safetyProtocols: Array.from(this.safetyProtocols.keys()),
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
getCapabilities(): string[] {
|
|
837
|
+
return Array.from(this.capabilities);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
getAgentInfo(agentId: string): AgentInfo | null {
|
|
841
|
+
const agent = this.agents.get(agentId);
|
|
842
|
+
if (!agent) return null;
|
|
843
|
+
|
|
844
|
+
return {
|
|
845
|
+
id: agent.id,
|
|
846
|
+
name: agent.name,
|
|
847
|
+
type: agent.type,
|
|
848
|
+
capabilities: agent.capabilities,
|
|
849
|
+
status: agent.status,
|
|
850
|
+
trustScore: agent.trustScore,
|
|
851
|
+
performance: agent.getPerformanceMetrics(),
|
|
852
|
+
taskHistory: agent.taskHistory,
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
getAllAgents(): AgentInfo[] {
|
|
857
|
+
const agentInfos: AgentInfo[] = [];
|
|
858
|
+
for (const [id] of this.agents) {
|
|
859
|
+
const info = this.getAgentInfo(id);
|
|
860
|
+
if (info) {
|
|
861
|
+
agentInfos.push(info);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return agentInfos;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// -----------------------------------------------------------------------
|
|
868
|
+
// Utility
|
|
869
|
+
// -----------------------------------------------------------------------
|
|
870
|
+
|
|
871
|
+
private delay(ms: number): Promise<void> {
|
|
872
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// ---------------------------------------------------------------------------
|
|
877
|
+
// MastraAutonomousAgent
|
|
878
|
+
// ---------------------------------------------------------------------------
|
|
879
|
+
|
|
880
|
+
export class MastraAutonomousAgent {
|
|
881
|
+
id: string;
|
|
882
|
+
name: string;
|
|
883
|
+
type: string;
|
|
884
|
+
capabilities: string[];
|
|
885
|
+
status: string;
|
|
886
|
+
trustScore: number;
|
|
887
|
+
taskHistory: TaskResult[];
|
|
888
|
+
private engine: MastraAutonomyEngine;
|
|
889
|
+
private createdAt: Date;
|
|
890
|
+
private tasksCompleted: number;
|
|
891
|
+
private tasksFailed: number;
|
|
892
|
+
private totalResponseTime: number;
|
|
893
|
+
private memory: Map<string, unknown>;
|
|
894
|
+
|
|
895
|
+
constructor(
|
|
896
|
+
name: string,
|
|
897
|
+
type: string,
|
|
898
|
+
capabilities: string[],
|
|
899
|
+
engine: MastraAutonomyEngine
|
|
900
|
+
) {
|
|
901
|
+
this.id = randomUUID();
|
|
902
|
+
this.name = name;
|
|
903
|
+
this.type = type;
|
|
904
|
+
this.capabilities = capabilities;
|
|
905
|
+
this.status = 'active';
|
|
906
|
+
this.trustScore = 1.0;
|
|
907
|
+
this.taskHistory = [];
|
|
908
|
+
this.engine = engine;
|
|
909
|
+
this.createdAt = new Date();
|
|
910
|
+
this.tasksCompleted = 0;
|
|
911
|
+
this.tasksFailed = 0;
|
|
912
|
+
this.totalResponseTime = 0;
|
|
913
|
+
this.memory = new Map();
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// -----------------------------------------------------------------------
|
|
917
|
+
// Task Execution
|
|
918
|
+
// -----------------------------------------------------------------------
|
|
919
|
+
|
|
920
|
+
async executeTask(task: AgentTask): Promise<TaskResult> {
|
|
921
|
+
console.log(
|
|
922
|
+
`[MastraAutonomousAgent:${this.name}] Executing task: ${task.description}`
|
|
923
|
+
);
|
|
924
|
+
|
|
925
|
+
const startTime = Date.now();
|
|
926
|
+
|
|
927
|
+
try {
|
|
928
|
+
// Process the task
|
|
929
|
+
const output = await this.processTaskWithLangChain(task);
|
|
930
|
+
|
|
931
|
+
const executionTime = Date.now() - startTime;
|
|
932
|
+
this.totalResponseTime += executionTime;
|
|
933
|
+
this.tasksCompleted += 1;
|
|
934
|
+
|
|
935
|
+
// Update trust score positively
|
|
936
|
+
this.trustScore = Math.min(1.0, this.trustScore + 0.005);
|
|
937
|
+
|
|
938
|
+
const result: TaskResult = {
|
|
939
|
+
taskId: task.id,
|
|
940
|
+
agentId: this.id,
|
|
941
|
+
status: 'completed',
|
|
942
|
+
output,
|
|
943
|
+
reasoning: `Task "${task.description}" processed successfully using ${this.type} capabilities`,
|
|
944
|
+
confidence: 0.8 + Math.random() * 0.2,
|
|
945
|
+
executionTime,
|
|
946
|
+
timestamp: new Date(),
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
this.taskHistory.push(result);
|
|
950
|
+
|
|
951
|
+
// Store in agent memory
|
|
952
|
+
this.memory.set(`task-${task.id}`, result);
|
|
953
|
+
|
|
954
|
+
console.log(
|
|
955
|
+
`[MastraAutonomousAgent:${this.name}] Task completed in ${executionTime}ms`
|
|
956
|
+
);
|
|
957
|
+
|
|
958
|
+
return result;
|
|
959
|
+
} catch (error: unknown) {
|
|
960
|
+
const executionTime = Date.now() - startTime;
|
|
961
|
+
this.totalResponseTime += executionTime;
|
|
962
|
+
this.tasksFailed += 1;
|
|
963
|
+
|
|
964
|
+
// Update trust score negatively
|
|
965
|
+
this.trustScore = Math.max(0.0, this.trustScore - 0.01);
|
|
966
|
+
|
|
967
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
968
|
+
|
|
969
|
+
const result: TaskResult = {
|
|
970
|
+
taskId: task.id,
|
|
971
|
+
agentId: this.id,
|
|
972
|
+
status: 'failed',
|
|
973
|
+
output: null,
|
|
974
|
+
reasoning: `Task failed: ${errMsg}`,
|
|
975
|
+
confidence: 0,
|
|
976
|
+
executionTime,
|
|
977
|
+
timestamp: new Date(),
|
|
978
|
+
};
|
|
979
|
+
|
|
980
|
+
this.taskHistory.push(result);
|
|
981
|
+
|
|
982
|
+
console.error(
|
|
983
|
+
`[MastraAutonomousAgent:${this.name}] Task failed: ${errMsg}`
|
|
984
|
+
);
|
|
985
|
+
|
|
986
|
+
return result;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// -----------------------------------------------------------------------
|
|
991
|
+
// LangChain Integration (mock/optional)
|
|
992
|
+
// -----------------------------------------------------------------------
|
|
993
|
+
|
|
994
|
+
private async processTaskWithLangChain(
|
|
995
|
+
task: AgentTask
|
|
996
|
+
): Promise<Record<string, unknown>> {
|
|
997
|
+
// Simulate LangChain processing pipeline
|
|
998
|
+
// In production this would use actual LangChain chains/agents
|
|
999
|
+
await this.delay(20 + Math.random() * 80);
|
|
1000
|
+
|
|
1001
|
+
const output: Record<string, unknown> = {
|
|
1002
|
+
taskId: task.id,
|
|
1003
|
+
agentId: this.id,
|
|
1004
|
+
agentName: this.name,
|
|
1005
|
+
agentType: this.type,
|
|
1006
|
+
processedAt: new Date().toISOString(),
|
|
1007
|
+
input: task.input,
|
|
1008
|
+
result: `Processed "${task.description}" using ${this.type} agent with capabilities: ${this.capabilities.join(', ')}`,
|
|
1009
|
+
confidence: 0.8 + Math.random() * 0.2,
|
|
1010
|
+
tokens: {
|
|
1011
|
+
input: Math.floor(Math.random() * 500) + 50,
|
|
1012
|
+
output: Math.floor(Math.random() * 300) + 30,
|
|
1013
|
+
},
|
|
1014
|
+
};
|
|
1015
|
+
|
|
1016
|
+
return output;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// -----------------------------------------------------------------------
|
|
1020
|
+
// Coordination Support
|
|
1021
|
+
// -----------------------------------------------------------------------
|
|
1022
|
+
|
|
1023
|
+
createCoordinationPlan(
|
|
1024
|
+
task: AgentTask,
|
|
1025
|
+
collaborators: MastraAutonomousAgent[]
|
|
1026
|
+
): CoordinationPlan {
|
|
1027
|
+
const steps: CoordinationStep[] = [];
|
|
1028
|
+
let stepNumber = 0;
|
|
1029
|
+
|
|
1030
|
+
// Plan steps for each collaborator
|
|
1031
|
+
for (const collaborator of collaborators) {
|
|
1032
|
+
stepNumber += 1;
|
|
1033
|
+
steps.push({
|
|
1034
|
+
step: stepNumber,
|
|
1035
|
+
agentId: collaborator.id,
|
|
1036
|
+
action: `Collaborate on ${task.type} using ${collaborator.type} specialization`,
|
|
1037
|
+
status: 'pending',
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// Add self as final aggregator
|
|
1042
|
+
stepNumber += 1;
|
|
1043
|
+
steps.push({
|
|
1044
|
+
step: stepNumber,
|
|
1045
|
+
agentId: this.id,
|
|
1046
|
+
action: 'Aggregate results and produce final output',
|
|
1047
|
+
status: 'pending',
|
|
1048
|
+
});
|
|
1049
|
+
|
|
1050
|
+
return {
|
|
1051
|
+
coordinatorId: this.id,
|
|
1052
|
+
taskId: task.id,
|
|
1053
|
+
participants: [this.id, ...collaborators.map((c) => c.id)],
|
|
1054
|
+
steps,
|
|
1055
|
+
timestamp: new Date(),
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
// -----------------------------------------------------------------------
|
|
1060
|
+
// Status
|
|
1061
|
+
// -----------------------------------------------------------------------
|
|
1062
|
+
|
|
1063
|
+
getStatus(): Record<string, unknown> {
|
|
1064
|
+
return {
|
|
1065
|
+
id: this.id,
|
|
1066
|
+
name: this.name,
|
|
1067
|
+
type: this.type,
|
|
1068
|
+
capabilities: this.capabilities,
|
|
1069
|
+
status: this.status,
|
|
1070
|
+
trustScore: this.trustScore,
|
|
1071
|
+
createdAt: this.createdAt,
|
|
1072
|
+
performance: this.getPerformanceMetrics(),
|
|
1073
|
+
taskHistorySize: this.taskHistory.length,
|
|
1074
|
+
memorySize: this.memory.size,
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
getPerformanceMetrics(): MastraAgentPerformanceMetrics {
|
|
1079
|
+
const totalTasks = this.tasksCompleted + this.tasksFailed;
|
|
1080
|
+
|
|
1081
|
+
return {
|
|
1082
|
+
tasksCompleted: this.tasksCompleted,
|
|
1083
|
+
tasksFailed: this.tasksFailed,
|
|
1084
|
+
averageResponseTime:
|
|
1085
|
+
totalTasks > 0 ? this.totalResponseTime / totalTasks : 0,
|
|
1086
|
+
trustScore: this.trustScore,
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// -----------------------------------------------------------------------
|
|
1091
|
+
// Utility
|
|
1092
|
+
// -----------------------------------------------------------------------
|
|
1093
|
+
|
|
1094
|
+
private delay(ms: number): Promise<void> {
|
|
1095
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1096
|
+
}
|
|
1097
|
+
}
|