oneie 1.2.4 ā 1.2.5
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.
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Background Agent Loader System
|
|
5
|
+
* Loads and executes agents from .claude/agents/ directory
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { promises as fs } from 'fs';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import yaml from 'js-yaml';
|
|
11
|
+
import chalk from 'chalk';
|
|
12
|
+
// License validation removed for simplified deployment
|
|
13
|
+
import { AdvancedCache, MemoryMonitor, PerformanceProfiler, LazyLoader } from './performance-optimizer.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* BackgroundAgentLoader class for loading and executing agents
|
|
17
|
+
*/
|
|
18
|
+
export class BackgroundAgentLoader {
|
|
19
|
+
constructor(options = {}) {
|
|
20
|
+
this.agentsPath = options.agentsPath || '.claude/agents';
|
|
21
|
+
|
|
22
|
+
// Advanced caching system
|
|
23
|
+
this.cache = new AdvancedCache({
|
|
24
|
+
maxSize: options.cacheMaxSize || 200,
|
|
25
|
+
ttl: options.cacheTTL || 600000, // 10 minutes
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// Memory monitoring
|
|
29
|
+
this.memoryMonitor = new MemoryMonitor({
|
|
30
|
+
maxHeapSize: options.maxHeapSize || 500 * 1024 * 1024, // 500MB
|
|
31
|
+
warningThreshold: options.memoryWarningThreshold || 0.8
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Performance profiling
|
|
35
|
+
this.profiler = new PerformanceProfiler();
|
|
36
|
+
|
|
37
|
+
// Lazy loading system
|
|
38
|
+
this.lazyLoader = new LazyLoader({
|
|
39
|
+
maxConcurrentLoads: options.maxConcurrentLoads || 5,
|
|
40
|
+
loadTimeout: options.loadTimeout || 5000
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Legacy performance metrics for backward compatibility
|
|
44
|
+
this.performanceMetrics = {
|
|
45
|
+
loadTimes: [],
|
|
46
|
+
memoryUsage: [],
|
|
47
|
+
cacheHits: 0,
|
|
48
|
+
cacheMisses: 0
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
// Initialize license validator for premium agent gating
|
|
52
|
+
// License validation removed for simplified deployment
|
|
53
|
+
|
|
54
|
+
// Coordination will be handled externally to avoid circular dependencies
|
|
55
|
+
this.coordinator = null;
|
|
56
|
+
this.enableCoordination = options.enableCoordination !== false; // Default true
|
|
57
|
+
|
|
58
|
+
// Performance optimization settings
|
|
59
|
+
this.enableProfiling = options.enableProfiling !== false;
|
|
60
|
+
this.enablePreloading = options.enablePreloading !== false;
|
|
61
|
+
this.preloadCommonAgents = options.preloadCommonAgents !== false;
|
|
62
|
+
|
|
63
|
+
// Preload common agents if enabled
|
|
64
|
+
if (this.preloadCommonAgents) {
|
|
65
|
+
this.initializeCommonAgents();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Initialize common agents for preloading
|
|
71
|
+
*/
|
|
72
|
+
async initializeCommonAgents() {
|
|
73
|
+
const commonAgents = [
|
|
74
|
+
'engineering-director',
|
|
75
|
+
'engineering-architect',
|
|
76
|
+
'engineering-developer',
|
|
77
|
+
'content-team-manager',
|
|
78
|
+
'research-foundation-analyst'
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
console.log(chalk.blue('š Preloading common agents...'));
|
|
83
|
+
const results = await this.cache.preload(commonAgents, async (agentName) => {
|
|
84
|
+
try {
|
|
85
|
+
const agentPath = path.join(this.agentsPath, `${agentName}.md`);
|
|
86
|
+
return await this.parseAgentFile(agentPath);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
console.log(chalk.yellow(`ā ļø Failed to preload ${agentName}: ${error.message}`));
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const successful = results.filter(r => r.success && !r.cached).length;
|
|
94
|
+
console.log(chalk.green(`ā
Preloaded ${successful} common agents`));
|
|
95
|
+
} catch (error) {
|
|
96
|
+
console.log(chalk.yellow(`ā ļø Preloading failed: ${error.message}`));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Load an agent from the .claude/agents/ directory
|
|
102
|
+
* @param {string} agentName - Name of the agent (without .md extension)
|
|
103
|
+
* @returns {Promise<BackgroundAgent>} Loaded agent instance
|
|
104
|
+
*/
|
|
105
|
+
async loadAgent(agentName) {
|
|
106
|
+
const startTime = performance.now();
|
|
107
|
+
const profileId = this.enableProfiling ? this.profiler.start(`loadAgent-${agentName}`, {
|
|
108
|
+
operation: 'loadAgent',
|
|
109
|
+
agentName
|
|
110
|
+
}) : null;
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
// No premium gating - all agents are accessible
|
|
114
|
+
const accessValidation = { hasAccess: true, tier: 'free', reason: 'No restrictions' };
|
|
115
|
+
|
|
116
|
+
if (profileId) this.profiler.mark(profileId, 'license-validated');
|
|
117
|
+
|
|
118
|
+
// Check advanced cache first
|
|
119
|
+
const cachedAgent = this.cache.get(agentName);
|
|
120
|
+
if (cachedAgent) {
|
|
121
|
+
this.performanceMetrics.cacheHits++;
|
|
122
|
+
if (profileId) {
|
|
123
|
+
this.profiler.mark(profileId, 'cache-hit');
|
|
124
|
+
this.profiler.end(profileId);
|
|
125
|
+
}
|
|
126
|
+
// Add license info to cached agent
|
|
127
|
+
return new BackgroundAgent({
|
|
128
|
+
...cachedAgent,
|
|
129
|
+
licenseInfo: accessValidation
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
this.performanceMetrics.cacheMisses++;
|
|
134
|
+
if (profileId) this.profiler.mark(profileId, 'cache-miss');
|
|
135
|
+
|
|
136
|
+
// Use lazy loading for optimal performance
|
|
137
|
+
const agentConfig = await this.lazyLoader.load(agentName, async (name) => {
|
|
138
|
+
// Construct agent file path
|
|
139
|
+
const agentPath = path.join(this.agentsPath, `${name}.md`);
|
|
140
|
+
|
|
141
|
+
if (profileId) this.profiler.mark(profileId, 'file-loading');
|
|
142
|
+
|
|
143
|
+
// Parse agent file with optimized parsing
|
|
144
|
+
const config = await this.parseAgentFile(agentPath);
|
|
145
|
+
|
|
146
|
+
if (profileId) this.profiler.mark(profileId, 'file-parsed');
|
|
147
|
+
|
|
148
|
+
return config;
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
// Add license information to agent config
|
|
152
|
+
agentConfig.licenseInfo = accessValidation;
|
|
153
|
+
|
|
154
|
+
// Create agent instance
|
|
155
|
+
const agent = new BackgroundAgent(agentConfig);
|
|
156
|
+
|
|
157
|
+
// Cache for future use with advanced cache
|
|
158
|
+
this.cache.set(agentName, agentConfig);
|
|
159
|
+
|
|
160
|
+
// Record performance metrics (legacy support)
|
|
161
|
+
const loadTime = performance.now() - startTime;
|
|
162
|
+
this.performanceMetrics.loadTimes.push(loadTime);
|
|
163
|
+
|
|
164
|
+
if (profileId) {
|
|
165
|
+
this.profiler.mark(profileId, 'agent-created');
|
|
166
|
+
this.profiler.end(profileId);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return agent;
|
|
170
|
+
|
|
171
|
+
} catch (error) {
|
|
172
|
+
// If it's already an AgentLoadError, re-throw as-is
|
|
173
|
+
if (error instanceof AgentLoadError) {
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
throw new AgentLoadError(`Failed to load agent '${agentName}': ${error.message}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Parse agent file and extract configuration
|
|
182
|
+
* @param {string} agentPath - Path to agent markdown file
|
|
183
|
+
* @returns {Promise<Object>} Agent configuration object
|
|
184
|
+
*/
|
|
185
|
+
async parseAgentFile(agentPath) {
|
|
186
|
+
try {
|
|
187
|
+
// Check if file exists
|
|
188
|
+
const exists = await fs.access(agentPath).then(() => true).catch(() => false);
|
|
189
|
+
if (!exists) {
|
|
190
|
+
throw new Error(`Agent file not found: ${agentPath}`);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Read agent file
|
|
194
|
+
const content = await fs.readFile(agentPath, 'utf8');
|
|
195
|
+
|
|
196
|
+
// Extract YAML frontmatter if present
|
|
197
|
+
let config = {};
|
|
198
|
+
let yamlMatch = content.match(/^---\n([\s\S]*?)\n---/);
|
|
199
|
+
|
|
200
|
+
if (yamlMatch) {
|
|
201
|
+
try {
|
|
202
|
+
config = yaml.load(yamlMatch[1]) || {};
|
|
203
|
+
} catch (yamlError) {
|
|
204
|
+
console.warn(`Warning: Invalid YAML in ${agentPath}: ${yamlError.message}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Extract basic agent info from markdown
|
|
209
|
+
const lines = content.split('\n');
|
|
210
|
+
let title = '';
|
|
211
|
+
let description = '';
|
|
212
|
+
|
|
213
|
+
for (const line of lines) {
|
|
214
|
+
if (line.startsWith('# ') && !title) {
|
|
215
|
+
title = line.substring(2).trim();
|
|
216
|
+
} else if (line.trim() && !line.startsWith('#') && !line.startsWith('---') && !description) {
|
|
217
|
+
description = line.trim();
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Return comprehensive config
|
|
223
|
+
return {
|
|
224
|
+
name: config.name || title || path.basename(agentPath, '.md'),
|
|
225
|
+
title: config.title || title,
|
|
226
|
+
description: config.description || description,
|
|
227
|
+
content: content,
|
|
228
|
+
config: config,
|
|
229
|
+
filePath: agentPath,
|
|
230
|
+
lastModified: (await fs.stat(agentPath)).mtime
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
} catch (error) {
|
|
234
|
+
throw new Error(`Failed to parse agent file ${agentPath}: ${error.message}`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Execute an agent with given context and arguments
|
|
240
|
+
* @param {string} agentName - Name of the agent to execute
|
|
241
|
+
* @param {Object} context - Execution context
|
|
242
|
+
* @param {Array} args - Arguments for the agent
|
|
243
|
+
* @param {Object} options - Execution options
|
|
244
|
+
* @returns {Promise<Object>} Execution result
|
|
245
|
+
*/
|
|
246
|
+
async executeAgent(agentName, context = {}, args = [], options = {}) {
|
|
247
|
+
const startTime = performance.now();
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
// Load the agent
|
|
251
|
+
const agent = await this.loadAgent(agentName);
|
|
252
|
+
|
|
253
|
+
// Check if coordination should be enabled for this execution
|
|
254
|
+
let coordinationResult = null;
|
|
255
|
+
if (this.coordinator && this.enableCoordination && options.enableCoordination !== false) {
|
|
256
|
+
try {
|
|
257
|
+
// Spawn related agents and coordinate if context is complex enough
|
|
258
|
+
const contextString = typeof context === 'string' ? context : JSON.stringify(context);
|
|
259
|
+
if (contextString.length > 50) { // Only coordinate for complex contexts
|
|
260
|
+
coordinationResult = await this.coordinator.spawnRelatedAgents(
|
|
261
|
+
agentName,
|
|
262
|
+
contextString,
|
|
263
|
+
{
|
|
264
|
+
maxSpawn: options.maxSpawn || 2,
|
|
265
|
+
executeImmediately: options.executeSpawnedAgents || false
|
|
266
|
+
}
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
} catch (coordError) {
|
|
270
|
+
console.log(`ā ļø Agent coordination failed: ${coordError.message}`);
|
|
271
|
+
// Continue with normal execution even if coordination fails
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Execute the primary agent with context and arguments
|
|
276
|
+
const result = await agent.execute(context, args);
|
|
277
|
+
|
|
278
|
+
// Record execution time
|
|
279
|
+
const executionTime = performance.now() - startTime;
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
success: true,
|
|
283
|
+
result: result,
|
|
284
|
+
agent: agentName,
|
|
285
|
+
executionTime: executionTime,
|
|
286
|
+
timestamp: new Date().toISOString(),
|
|
287
|
+
coordination: coordinationResult
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
} catch (error) {
|
|
291
|
+
return {
|
|
292
|
+
success: false,
|
|
293
|
+
error: error.message,
|
|
294
|
+
agent: agentName,
|
|
295
|
+
timestamp: new Date().toISOString()
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* List all available agents in the .claude/agents/ directory
|
|
302
|
+
* @returns {Promise<Array<string>>} Array of agent names
|
|
303
|
+
*/
|
|
304
|
+
async listAvailableAgents() {
|
|
305
|
+
try {
|
|
306
|
+
const files = await fs.readdir(this.agentsPath);
|
|
307
|
+
return files
|
|
308
|
+
.filter(file => file.endsWith('.md'))
|
|
309
|
+
.map(file => path.basename(file, '.md'))
|
|
310
|
+
.sort();
|
|
311
|
+
} catch (error) {
|
|
312
|
+
throw new Error(`Failed to list agents: ${error.message}`);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Get license status and agent access summary
|
|
318
|
+
* @returns {Promise<Object>} License status information
|
|
319
|
+
*/
|
|
320
|
+
async getLicenseStatus() {
|
|
321
|
+
return { status: 'free', licenseType: 'open-source' }; // All agents are free
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Check if an agent requires premium access
|
|
326
|
+
* @param {string} agentName - Agent name
|
|
327
|
+
* @returns {boolean} True if premium license required
|
|
328
|
+
*/
|
|
329
|
+
isPremiumAgent(agentName) {
|
|
330
|
+
return false; // All agents are free - no premium restriction
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Generate upgrade prompt for premium agents
|
|
335
|
+
* @param {string} agentName - Agent name
|
|
336
|
+
* @returns {Promise<string>} Formatted upgrade prompt
|
|
337
|
+
*/
|
|
338
|
+
async generateUpgradePrompt(agentName) {
|
|
339
|
+
return ''; // No upgrade prompts needed - all agents are free
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* List available agents with premium status indicators
|
|
344
|
+
* @returns {Promise<Array<Object>>} Array of agent info with premium status
|
|
345
|
+
*/
|
|
346
|
+
async listAgentsWithStatus() {
|
|
347
|
+
const agents = await this.listAvailableAgents();
|
|
348
|
+
const agentList = [];
|
|
349
|
+
|
|
350
|
+
for (const agentName of agents) {
|
|
351
|
+
const isPremium = this.isPremiumAgent(agentName);
|
|
352
|
+
const accessValidation = { hasAccess: true, reason: 'All agents are free' }; // No access restrictions
|
|
353
|
+
|
|
354
|
+
agentList.push({
|
|
355
|
+
name: agentName,
|
|
356
|
+
isPremium: isPremium,
|
|
357
|
+
hasAccess: accessValidation.hasAccess,
|
|
358
|
+
tier: accessValidation.tier,
|
|
359
|
+
reason: accessValidation.reason
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
return agentList;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Create a trial license for testing premium features
|
|
368
|
+
* @param {number} durationDays - Trial duration in days
|
|
369
|
+
* @returns {Promise<Object>} Trial license information
|
|
370
|
+
*/
|
|
371
|
+
async createTrialLicense(durationDays = 7) {
|
|
372
|
+
return { status: 'free', message: 'No trial needed - all agents are free' }; // No trials needed
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Get comprehensive performance metrics
|
|
377
|
+
* @returns {Object} Performance metrics
|
|
378
|
+
*/
|
|
379
|
+
getPerformanceMetrics() {
|
|
380
|
+
const loadTimes = this.performanceMetrics.loadTimes;
|
|
381
|
+
const legacyMetrics = {
|
|
382
|
+
totalLoads: loadTimes.length,
|
|
383
|
+
averageLoadTime: loadTimes.length > 0 ? loadTimes.reduce((a, b) => a + b, 0) / loadTimes.length : 0,
|
|
384
|
+
cacheHitRate: this.performanceMetrics.cacheHits / (this.performanceMetrics.cacheHits + this.performanceMetrics.cacheMisses) || 0,
|
|
385
|
+
memoryUsage: process.memoryUsage(),
|
|
386
|
+
cacheSize: this.cache instanceof Map ? this.cache.size : this.cache.getStats().size
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
// Enhanced metrics from advanced systems
|
|
390
|
+
const cacheStats = this.cache.getStats ? this.cache.getStats() : {};
|
|
391
|
+
const memoryStats = this.memoryMonitor.getStats();
|
|
392
|
+
const lazyStats = this.lazyLoader.getStats();
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
...legacyMetrics,
|
|
396
|
+
advanced: {
|
|
397
|
+
cache: {
|
|
398
|
+
...cacheStats,
|
|
399
|
+
efficiency: cacheStats.hitRate > 0.8 ? 'excellent' :
|
|
400
|
+
cacheStats.hitRate > 0.6 ? 'good' :
|
|
401
|
+
cacheStats.hitRate > 0.4 ? 'fair' : 'poor'
|
|
402
|
+
},
|
|
403
|
+
memory: memoryStats ? {
|
|
404
|
+
current: memoryStats.current,
|
|
405
|
+
average: memoryStats.average,
|
|
406
|
+
peak: memoryStats.peak,
|
|
407
|
+
status: memoryStats.percentages?.heapTotal < 0.8 ? 'healthy' :
|
|
408
|
+
memoryStats.percentages?.heapTotal < 0.9 ? 'warning' : 'critical'
|
|
409
|
+
} : null,
|
|
410
|
+
lazyLoading: lazyStats,
|
|
411
|
+
profiling: {
|
|
412
|
+
enabled: this.enableProfiling,
|
|
413
|
+
profiles: this.profiler.getProfiles().length
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Get detailed profiling report for specific operation
|
|
421
|
+
* @param {string} operationType - Type of operation to analyze
|
|
422
|
+
* @returns {Object} Profiling summary
|
|
423
|
+
*/
|
|
424
|
+
getProfilingReport(operationType = 'loadAgent') {
|
|
425
|
+
if (!this.enableProfiling) {
|
|
426
|
+
return { enabled: false, message: 'Profiling is disabled' };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
return this.profiler.getSummary(operationType);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Optimize cache based on usage patterns
|
|
434
|
+
*/
|
|
435
|
+
optimizeCache() {
|
|
436
|
+
if (this.cache.cleanup) {
|
|
437
|
+
this.cache.cleanup();
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
console.log(chalk.blue('š§ Cache optimization completed'));
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Preload specific agents
|
|
445
|
+
* @param {Array<string>} agentNames - Names of agents to preload
|
|
446
|
+
* @returns {Promise<Array>} Preload results
|
|
447
|
+
*/
|
|
448
|
+
async preloadAgents(agentNames) {
|
|
449
|
+
if (!this.cache.preload) {
|
|
450
|
+
console.log(chalk.yellow('ā ļø Advanced caching not available for preloading'));
|
|
451
|
+
return [];
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const results = await this.cache.preload(agentNames, async (agentName) => {
|
|
455
|
+
const agentPath = path.join(this.agentsPath, `${agentName}.md`);
|
|
456
|
+
return await this.parseAgentFile(agentPath);
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
const successful = results.filter(r => r.success).length;
|
|
460
|
+
console.log(chalk.green(`ā
Preloaded ${successful}/${agentNames.length} agents`));
|
|
461
|
+
|
|
462
|
+
return results;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Check if performance targets are met
|
|
467
|
+
* @returns {Object} Performance target status
|
|
468
|
+
*/
|
|
469
|
+
checkPerformanceTargets() {
|
|
470
|
+
const metrics = this.getPerformanceMetrics();
|
|
471
|
+
const memoryPerAgent = metrics.advanced?.memory?.current?.heapUsed /
|
|
472
|
+
(metrics.cacheSize || 1) / 1024 / 1024; // MB per agent
|
|
473
|
+
|
|
474
|
+
return {
|
|
475
|
+
loadTimeTarget: {
|
|
476
|
+
target: 2000, // 2 seconds
|
|
477
|
+
current: metrics.averageLoadTime,
|
|
478
|
+
met: metrics.averageLoadTime < 2000,
|
|
479
|
+
status: metrics.averageLoadTime < 500 ? 'excellent' :
|
|
480
|
+
metrics.averageLoadTime < 1000 ? 'good' :
|
|
481
|
+
metrics.averageLoadTime < 2000 ? 'acceptable' : 'needs_improvement'
|
|
482
|
+
},
|
|
483
|
+
memoryTarget: {
|
|
484
|
+
target: 100, // 100MB per agent
|
|
485
|
+
current: memoryPerAgent || 0,
|
|
486
|
+
met: (memoryPerAgent || 0) < 100,
|
|
487
|
+
status: memoryPerAgent < 10 ? 'excellent' :
|
|
488
|
+
memoryPerAgent < 25 ? 'good' :
|
|
489
|
+
memoryPerAgent < 50 ? 'acceptable' : 'needs_improvement'
|
|
490
|
+
},
|
|
491
|
+
cacheTarget: {
|
|
492
|
+
target: 0.8, // 80% hit rate
|
|
493
|
+
current: metrics.cacheHitRate,
|
|
494
|
+
met: metrics.cacheHitRate > 0.8,
|
|
495
|
+
status: metrics.cacheHitRate > 0.9 ? 'excellent' :
|
|
496
|
+
metrics.cacheHitRate > 0.8 ? 'good' :
|
|
497
|
+
metrics.cacheHitRate > 0.6 ? 'acceptable' : 'needs_improvement'
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* Set the agent coordinator (to avoid circular dependencies)
|
|
504
|
+
* @param {AgentCoordinator} coordinator - Agent coordinator instance
|
|
505
|
+
*/
|
|
506
|
+
setCoordinator(coordinator) {
|
|
507
|
+
this.coordinator = coordinator;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Get agent coordination statistics
|
|
512
|
+
* @returns {Object} Coordination statistics
|
|
513
|
+
*/
|
|
514
|
+
getCoordinationStats() {
|
|
515
|
+
if (!this.coordinator) {
|
|
516
|
+
return { enabled: false, message: 'Agent coordination is disabled' };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
return {
|
|
520
|
+
enabled: true,
|
|
521
|
+
...this.coordinator.getCoordinationStats()
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Get active coordination sessions
|
|
527
|
+
* @returns {Array} Active coordination sessions
|
|
528
|
+
*/
|
|
529
|
+
getActiveCoordinationSessions() {
|
|
530
|
+
if (!this.coordinator) return [];
|
|
531
|
+
return this.coordinator.getActiveSessions();
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Clear agent cache
|
|
536
|
+
*/
|
|
537
|
+
clearCache() {
|
|
538
|
+
this.cache.clear();
|
|
539
|
+
this.performanceMetrics.cacheHits = 0;
|
|
540
|
+
this.performanceMetrics.cacheMisses = 0;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* BackgroundAgent class representing a loaded agent
|
|
546
|
+
*/
|
|
547
|
+
export class BackgroundAgent {
|
|
548
|
+
constructor(config) {
|
|
549
|
+
this.name = config.name;
|
|
550
|
+
this.title = config.title;
|
|
551
|
+
this.description = config.description;
|
|
552
|
+
this.content = config.content;
|
|
553
|
+
this.config = config.config || {};
|
|
554
|
+
this.filePath = config.filePath;
|
|
555
|
+
this.lastModified = config.lastModified;
|
|
556
|
+
this.state = {};
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Execute the agent with given context and arguments
|
|
561
|
+
* @param {Object} context - Execution context
|
|
562
|
+
* @param {Array} args - Arguments for execution
|
|
563
|
+
* @returns {Promise<Object>} Execution result
|
|
564
|
+
*/
|
|
565
|
+
async execute(context = {}, args = []) {
|
|
566
|
+
// For now, return agent info and basic execution
|
|
567
|
+
// In a full implementation, this would process the agent's instructions
|
|
568
|
+
return {
|
|
569
|
+
agent: this.name,
|
|
570
|
+
title: this.title,
|
|
571
|
+
description: this.description,
|
|
572
|
+
context: context,
|
|
573
|
+
arguments: args,
|
|
574
|
+
state: this.state,
|
|
575
|
+
executed: true,
|
|
576
|
+
timestamp: new Date().toISOString()
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Get agent metadata
|
|
582
|
+
* @returns {Object} Agent metadata
|
|
583
|
+
*/
|
|
584
|
+
getMetadata() {
|
|
585
|
+
return {
|
|
586
|
+
name: this.name,
|
|
587
|
+
title: this.title,
|
|
588
|
+
description: this.description,
|
|
589
|
+
filePath: this.filePath,
|
|
590
|
+
lastModified: this.lastModified,
|
|
591
|
+
configKeys: Object.keys(this.config)
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Custom error class for agent loading errors
|
|
598
|
+
*/
|
|
599
|
+
export class AgentLoadError extends Error {
|
|
600
|
+
constructor(message, code = 'AGENT_LOAD_FAILED', details = null) {
|
|
601
|
+
super(message);
|
|
602
|
+
this.name = 'AgentLoadError';
|
|
603
|
+
this.code = code;
|
|
604
|
+
this.details = details;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// Export default instance
|
|
609
|
+
export default new BackgroundAgentLoader();
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Dynamic Agent Command Generator
|
|
5
|
+
* Creates one:agent-name command files for all agents in .claude/agents/
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { promises as fs } from 'fs';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { BackgroundAgentLoader } from './background-agent-loader.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Agent Command Generator class
|
|
14
|
+
*/
|
|
15
|
+
export class AgentCommandGenerator {
|
|
16
|
+
constructor(options = {}) {
|
|
17
|
+
this.agentsPath = options.agentsPath || '.claude/agents';
|
|
18
|
+
this.commandsPath = options.commandsPath || '.claude/commands';
|
|
19
|
+
this.loader = new BackgroundAgentLoader({ agentsPath: this.agentsPath });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Generate command files for all agents
|
|
24
|
+
*/
|
|
25
|
+
async generateAllCommands() {
|
|
26
|
+
console.log('š¤ Generating command files for all agents...\n');
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
// Get list of all available agents
|
|
30
|
+
const agents = await this.loader.listAvailableAgents();
|
|
31
|
+
console.log(`Found ${agents.length} agents to process`);
|
|
32
|
+
|
|
33
|
+
// Filter out README and other non-agent files
|
|
34
|
+
const validAgents = agents.filter(agent =>
|
|
35
|
+
agent !== 'README' &&
|
|
36
|
+
!agent.startsWith('.') &&
|
|
37
|
+
agent.endsWith !== '.DS_Store'
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
console.log(`Processing ${validAgents.length} valid agents:\n`);
|
|
41
|
+
|
|
42
|
+
let created = 0;
|
|
43
|
+
let updated = 0;
|
|
44
|
+
let skipped = 0;
|
|
45
|
+
|
|
46
|
+
// Generate command file for each agent
|
|
47
|
+
for (const agentName of validAgents) {
|
|
48
|
+
try {
|
|
49
|
+
const result = await this.generateCommandFile(agentName);
|
|
50
|
+
if (result === 'created') {
|
|
51
|
+
created++;
|
|
52
|
+
console.log(`ā
Created: one-${agentName}.md`);
|
|
53
|
+
} else if (result === 'updated') {
|
|
54
|
+
updated++;
|
|
55
|
+
console.log(`š Updated: one-${agentName}.md`);
|
|
56
|
+
} else {
|
|
57
|
+
skipped++;
|
|
58
|
+
console.log(`āļø Skipped: one-${agentName}.md (already exists)`);
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
console.log(`ā Error processing ${agentName}:`, error.message);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
console.log(`\nš Summary:`);
|
|
66
|
+
console.log(` Created: ${created} command files`);
|
|
67
|
+
console.log(` Updated: ${updated} command files`);
|
|
68
|
+
console.log(` Skipped: ${skipped} command files`);
|
|
69
|
+
console.log(` Total agents: ${validAgents.length}`);
|
|
70
|
+
|
|
71
|
+
return { created, updated, skipped, total: validAgents.length };
|
|
72
|
+
|
|
73
|
+
} catch (error) {
|
|
74
|
+
console.error('ā Failed to generate command files:', error.message);
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Generate a single command file for an agent
|
|
81
|
+
*/
|
|
82
|
+
async generateCommandFile(agentName, overwrite = false) {
|
|
83
|
+
const commandFileName = `one-${agentName}.md`;
|
|
84
|
+
const commandFilePath = path.join(this.commandsPath, commandFileName);
|
|
85
|
+
|
|
86
|
+
// Check if command file already exists
|
|
87
|
+
const exists = await fs.access(commandFilePath).then(() => true).catch(() => false);
|
|
88
|
+
if (exists && !overwrite) {
|
|
89
|
+
return 'skipped';
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Load agent to get metadata
|
|
93
|
+
const agent = await this.loader.loadAgent(agentName);
|
|
94
|
+
|
|
95
|
+
// Determine if agent is premium (marketing team)
|
|
96
|
+
const isPremium = agentName.startsWith('marketing-') ||
|
|
97
|
+
agentName.includes('marketing') ||
|
|
98
|
+
agentName.startsWith('crypto-') ||
|
|
99
|
+
agentName.includes('viral');
|
|
100
|
+
|
|
101
|
+
// Generate command file content
|
|
102
|
+
const commandContent = this.generateCommandContent(agentName, agent, isPremium);
|
|
103
|
+
|
|
104
|
+
// Write command file
|
|
105
|
+
await fs.writeFile(commandFilePath, commandContent, 'utf8');
|
|
106
|
+
|
|
107
|
+
return exists ? 'updated' : 'created';
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Generate the content for a command file
|
|
112
|
+
*/
|
|
113
|
+
generateCommandContent(agentName, agent, isPremium = false) {
|
|
114
|
+
const commandName = `one:${agentName}`;
|
|
115
|
+
const title = agent.title || this.formatTitle(agentName);
|
|
116
|
+
const description = agent.description || `${title} specialist agent`;
|
|
117
|
+
|
|
118
|
+
// Extract first sentence of description for brief summary
|
|
119
|
+
const briefDescription = description.split('.')[0].trim();
|
|
120
|
+
|
|
121
|
+
// Determine team category
|
|
122
|
+
const team = this.categorizeAgent(agentName);
|
|
123
|
+
|
|
124
|
+
const premiumWarning = isPremium ? `
|
|
125
|
+
**ā ļø PREMIUM AGENT - Requires ${team.charAt(0).toUpperCase() + team.slice(1)} Team Upgrade ($79)**
|
|
126
|
+
|
|
127
|
+
` : '';
|
|
128
|
+
|
|
129
|
+
return `# ${commandName}
|
|
130
|
+
|
|
131
|
+
Launch the ${title} agent for specialized ${team} support.
|
|
132
|
+
|
|
133
|
+
${premiumWarning}This command loads the ${title} agent from \`.claude/agents/${agentName}.md\` and provides:
|
|
134
|
+
|
|
135
|
+
## ${title} Capabilities
|
|
136
|
+
${briefDescription}
|
|
137
|
+
|
|
138
|
+
## Agent Specialization
|
|
139
|
+
- **Team**: ${team.charAt(0).toUpperCase() + team.slice(1)} Team
|
|
140
|
+
- **Focus**: ${this.getAgentFocus(agentName)}
|
|
141
|
+
- **Integration**: Works with other ${team} agents and cross-functional teams
|
|
142
|
+
|
|
143
|
+
## Usage Examples
|
|
144
|
+
\`\`\`
|
|
145
|
+
${commandName} "Help me with ${this.getExampleTask(agentName)}"
|
|
146
|
+
${commandName} "Review and optimize ${this.getReviewTask(agentName)}"
|
|
147
|
+
${commandName} "Create a strategy for ${this.getStrategyTask(agentName)}"
|
|
148
|
+
\`\`\`
|
|
149
|
+
|
|
150
|
+
## Agent Integration
|
|
151
|
+
- **Loads from**: \`.claude/agents/${agentName}.md\`
|
|
152
|
+
- **Team**: ${team.charAt(0).toUpperCase() + team.slice(1)} ${isPremium ? '(Premium Package - $79)' : '(Free Core Package)'}
|
|
153
|
+
- **Can coordinate with**: Other ${team} agents and cross-functional specialists
|
|
154
|
+
- **Available in parallel**: Runs alongside other agents${isPremium ? '\n- **Requires license validation**: Premium agent access verification' : ''}
|
|
155
|
+
|
|
156
|
+
Arguments: $ARGUMENTS (${this.getArgumentDescription(agentName)})`;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Format agent name into a proper title
|
|
161
|
+
*/
|
|
162
|
+
formatTitle(agentName) {
|
|
163
|
+
return agentName
|
|
164
|
+
.split('-')
|
|
165
|
+
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
|
166
|
+
.join(' ');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Categorize agent by team
|
|
171
|
+
*/
|
|
172
|
+
categorizeAgent(agentName) {
|
|
173
|
+
if (agentName.startsWith('engineering-')) return 'engineering';
|
|
174
|
+
if (agentName.startsWith('marketing-')) return 'marketing';
|
|
175
|
+
if (agentName.startsWith('content-')) return 'content';
|
|
176
|
+
if (agentName.startsWith('research-')) return 'research';
|
|
177
|
+
if (agentName.startsWith('crypto-')) return 'crypto';
|
|
178
|
+
if (agentName.startsWith('company-')) return 'company';
|
|
179
|
+
if (agentName.startsWith('service-')) return 'service';
|
|
180
|
+
if (agentName.includes('sales')) return 'sales';
|
|
181
|
+
return 'specialized';
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Get agent focus area
|
|
186
|
+
*/
|
|
187
|
+
getAgentFocus(agentName) {
|
|
188
|
+
if (agentName.includes('director')) return 'Strategic leadership and coordination';
|
|
189
|
+
if (agentName.includes('architect')) return 'System design and architecture';
|
|
190
|
+
if (agentName.includes('developer')) return 'Implementation and development';
|
|
191
|
+
if (agentName.includes('quality')) return 'Testing and quality assurance';
|
|
192
|
+
if (agentName.includes('content')) return 'Content creation and management';
|
|
193
|
+
if (agentName.includes('marketing')) return 'Marketing strategy and campaigns';
|
|
194
|
+
if (agentName.includes('research')) return 'Analysis and research';
|
|
195
|
+
if (agentName.includes('crypto')) return 'Cryptocurrency and blockchain';
|
|
196
|
+
return 'Specialized domain expertise';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Get example task for agent
|
|
201
|
+
*/
|
|
202
|
+
getExampleTask(agentName) {
|
|
203
|
+
if (agentName.includes('director')) return 'strategic planning and team coordination';
|
|
204
|
+
if (agentName.includes('architect')) return 'system architecture design';
|
|
205
|
+
if (agentName.includes('developer')) return 'feature implementation';
|
|
206
|
+
if (agentName.includes('quality')) return 'test strategy and quality assurance';
|
|
207
|
+
if (agentName.includes('content')) return 'content strategy and creation';
|
|
208
|
+
if (agentName.includes('marketing')) return 'marketing campaign development';
|
|
209
|
+
if (agentName.includes('research')) return 'market research and analysis';
|
|
210
|
+
if (agentName.includes('crypto')) return 'cryptocurrency strategy';
|
|
211
|
+
return 'specialized project requirements';
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Get review task example
|
|
216
|
+
*/
|
|
217
|
+
getReviewTask(agentName) {
|
|
218
|
+
if (agentName.includes('director')) return 'project strategy';
|
|
219
|
+
if (agentName.includes('architect')) return 'system architecture';
|
|
220
|
+
if (agentName.includes('developer')) return 'code implementation';
|
|
221
|
+
if (agentName.includes('quality')) return 'test coverage';
|
|
222
|
+
if (agentName.includes('content')) return 'content strategy';
|
|
223
|
+
if (agentName.includes('marketing')) return 'marketing campaigns';
|
|
224
|
+
if (agentName.includes('research')) return 'research findings';
|
|
225
|
+
if (agentName.includes('crypto')) return 'token strategy';
|
|
226
|
+
return 'project deliverables';
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Get strategy task example
|
|
231
|
+
*/
|
|
232
|
+
getStrategyTask(agentName) {
|
|
233
|
+
if (agentName.includes('director')) return 'team leadership';
|
|
234
|
+
if (agentName.includes('architect')) return 'scalable architecture';
|
|
235
|
+
if (agentName.includes('developer')) return 'development workflow';
|
|
236
|
+
if (agentName.includes('quality')) return 'testing automation';
|
|
237
|
+
if (agentName.includes('content')) return 'content distribution';
|
|
238
|
+
if (agentName.includes('marketing')) return 'customer acquisition';
|
|
239
|
+
if (agentName.includes('research')) return 'competitive analysis';
|
|
240
|
+
if (agentName.includes('crypto')) return 'token economics';
|
|
241
|
+
return 'strategic optimization';
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Get argument description
|
|
246
|
+
*/
|
|
247
|
+
getArgumentDescription(agentName) {
|
|
248
|
+
const team = this.categorizeAgent(agentName);
|
|
249
|
+
return `${team} challenges, project context, specific requirements`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Validate command files exist for all agents
|
|
254
|
+
*/
|
|
255
|
+
async validateCommands() {
|
|
256
|
+
const agents = await this.loader.listAvailableAgents();
|
|
257
|
+
const validAgents = agents.filter(agent => agent !== 'README' && !agent.startsWith('.'));
|
|
258
|
+
|
|
259
|
+
const missing = [];
|
|
260
|
+
const existing = [];
|
|
261
|
+
|
|
262
|
+
for (const agentName of validAgents) {
|
|
263
|
+
const commandFile = path.join(this.commandsPath, `one-${agentName}.md`);
|
|
264
|
+
const exists = await fs.access(commandFile).then(() => true).catch(() => false);
|
|
265
|
+
|
|
266
|
+
if (exists) {
|
|
267
|
+
existing.push(agentName);
|
|
268
|
+
} else {
|
|
269
|
+
missing.push(agentName);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
return {
|
|
274
|
+
total: validAgents.length,
|
|
275
|
+
existing: existing.length,
|
|
276
|
+
missing: missing.length,
|
|
277
|
+
missingAgents: missing
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// CLI usage
|
|
283
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
284
|
+
const generator = new AgentCommandGenerator();
|
|
285
|
+
|
|
286
|
+
try {
|
|
287
|
+
await generator.generateAllCommands();
|
|
288
|
+
|
|
289
|
+
console.log('\nš Validating command coverage...');
|
|
290
|
+
const validation = await generator.validateCommands();
|
|
291
|
+
console.log(`ā
Command files exist for ${validation.existing}/${validation.total} agents`);
|
|
292
|
+
|
|
293
|
+
if (validation.missing > 0) {
|
|
294
|
+
console.log(`ā Missing command files for: ${validation.missingAgents.slice(0, 5).join(', ')}${validation.missingAgents.length > 5 ? '...' : ''}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
} catch (error) {
|
|
298
|
+
console.error('ā Generation failed:', error.message);
|
|
299
|
+
process.exit(1);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
export default AgentCommandGenerator;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oneie",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.5",
|
|
4
4
|
"description": "š¤ ONE Personal Collaborative Intelligence - Creates personalized AI workspace from your me.md profile. Simple: npx oneie ā edit me.md ā generate personalized agents, workflows & missions. From students to enterprises, ONE adapts to your context.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "one/tools/one-cli.js",
|