mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-09 11:51:37 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2d181dd74 | ||
|
|
7411fdbb52 | ||
|
|
e7a8ce8eb7 | ||
|
|
61fb094306 | ||
|
|
018e8c78ab | ||
|
|
f0f0f653fe | ||
|
|
98a4ff8450 | ||
|
|
d6333aaf33 | ||
|
|
8005094267 |
No files matched your search
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonai_tools \
|
||||
"praisonai>=2.5.5" \
|
||||
"praisonai>=2.6.2" \
|
||||
"praisonai[chat]" \
|
||||
"embedchain[github,youtube]"
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ RUN mkdir -p /root/.praison
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonai_tools \
|
||||
"praisonai>=2.5.5" \
|
||||
"praisonai>=2.6.2" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[chat]" \
|
||||
"praisonai[realtime]" \
|
||||
|
||||
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
|
||||
# Install Python packages (using latest versions)
|
||||
RUN pip install --no-cache-dir \
|
||||
praisonai_tools \
|
||||
"praisonai>=2.5.5" \
|
||||
"praisonai>=2.6.2" \
|
||||
"praisonai[ui]" \
|
||||
"praisonai[crewai]"
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Basic Agent Example
|
||||
* Demonstrates simple agent usage with OpenAI
|
||||
*/
|
||||
|
||||
import { Agent } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
const agent = new Agent({
|
||||
name: 'Assistant',
|
||||
instructions: 'You are a helpful assistant. Be concise and informative.',
|
||||
llm: 'openai/gpt-4o-mini'
|
||||
});
|
||||
|
||||
const response = await agent.chat('What is TypeScript?');
|
||||
console.log('Response:', response.text);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Context Agent Example
|
||||
* Demonstrates RAG-enabled agent with knowledge base
|
||||
*/
|
||||
|
||||
import { ContextAgent, createContextAgent, KnowledgeBase } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create knowledge base
|
||||
const kb = new KnowledgeBase();
|
||||
|
||||
// Add documents
|
||||
await kb.add({
|
||||
id: 'doc1',
|
||||
content: 'TypeScript is a strongly typed programming language that builds on JavaScript.',
|
||||
metadata: { topic: 'typescript' }
|
||||
});
|
||||
|
||||
await kb.add({
|
||||
id: 'doc2',
|
||||
content: 'TypeScript adds optional static typing and class-based object-oriented programming.',
|
||||
metadata: { topic: 'typescript' }
|
||||
});
|
||||
|
||||
await kb.add({
|
||||
id: 'doc3',
|
||||
content: 'PraisonAI is a framework for building AI agents in TypeScript and Python.',
|
||||
metadata: { topic: 'praisonai' }
|
||||
});
|
||||
|
||||
// Create context agent with knowledge base
|
||||
const agent = createContextAgent({
|
||||
name: 'KnowledgeAgent',
|
||||
llm: 'openai/gpt-4o-mini',
|
||||
knowledgeBase: kb,
|
||||
maxContextDocs: 3
|
||||
});
|
||||
|
||||
// Query with context
|
||||
const response = await agent.chat('What is TypeScript?');
|
||||
console.log('Response:', response.text);
|
||||
|
||||
// Check conversation history
|
||||
console.log('\nConversation history:', agent.getHistory().length, 'messages');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Image Agent Example
|
||||
* Demonstrates image analysis capabilities
|
||||
*/
|
||||
|
||||
import { ImageAgent, createImageAgent } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
const agent = createImageAgent({
|
||||
name: 'VisionAgent',
|
||||
llm: 'openai/gpt-4o-mini',
|
||||
verbose: true
|
||||
});
|
||||
|
||||
console.log('Image Agent created:', agent.name);
|
||||
|
||||
// Note: For actual image analysis, provide a real image URL
|
||||
// const analysis = await agent.analyze({
|
||||
// imageUrl: 'https://example.com/image.jpg',
|
||||
// prompt: 'Describe this image in detail'
|
||||
// });
|
||||
// console.log('Analysis:', analysis);
|
||||
|
||||
// Chat without image
|
||||
const response = await agent.chat('What types of images can you analyze?');
|
||||
console.log('Response:', response);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Multi-Agent Example
|
||||
* Demonstrates multiple agents working together
|
||||
*/
|
||||
|
||||
import { Agent, PraisonAIAgents, Task } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create specialized agents
|
||||
const researcher = new Agent({
|
||||
name: 'Researcher',
|
||||
role: 'Research Specialist',
|
||||
goal: 'Find accurate information on topics',
|
||||
instructions: 'You research topics thoroughly and provide factual information.'
|
||||
});
|
||||
|
||||
const writer = new Agent({
|
||||
name: 'Writer',
|
||||
role: 'Content Writer',
|
||||
goal: 'Create engaging content from research',
|
||||
instructions: 'You write clear, engaging content based on provided research.'
|
||||
});
|
||||
|
||||
// Create tasks
|
||||
const researchTask = new Task({
|
||||
description: 'Research the benefits of TypeScript over JavaScript',
|
||||
expectedOutput: 'A list of key benefits with explanations',
|
||||
agent: researcher
|
||||
});
|
||||
|
||||
const writeTask = new Task({
|
||||
description: 'Write a short article about TypeScript benefits',
|
||||
expectedOutput: 'A 200-word article',
|
||||
agent: writer
|
||||
});
|
||||
|
||||
// Run agents
|
||||
const agents = new PraisonAIAgents({
|
||||
agents: [researcher, writer],
|
||||
tasks: [researchTask, writeTask],
|
||||
process: 'sequential'
|
||||
});
|
||||
|
||||
const result = await agents.start();
|
||||
console.log('Result:', result);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Deep Research Agent Example
|
||||
* Demonstrates comprehensive research with citations
|
||||
*/
|
||||
|
||||
import { DeepResearchAgent, createDeepResearchAgent } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
const agent = createDeepResearchAgent({
|
||||
name: 'Scholar',
|
||||
llm: 'openai/gpt-4o-mini',
|
||||
maxIterations: 5,
|
||||
verbose: true
|
||||
});
|
||||
|
||||
console.log('Research Agent:', agent.name);
|
||||
|
||||
// Conduct research
|
||||
const result = await agent.research('What are the key benefits of TypeScript?');
|
||||
|
||||
console.log('\n=== Research Results ===');
|
||||
console.log('Answer:', result.answer.substring(0, 500) + '...');
|
||||
console.log('\nConfidence:', result.confidence);
|
||||
console.log('Reasoning steps:', result.reasoning.length);
|
||||
|
||||
// Show reasoning
|
||||
console.log('\n=== Reasoning Process ===');
|
||||
result.reasoning.forEach(step => {
|
||||
console.log(`Step ${step.step}: ${step.thought}`);
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Router Agent Example
|
||||
* Demonstrates routing requests to specialized agents
|
||||
*/
|
||||
|
||||
import { RouterAgent, createRouter, routeConditions, Agent } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create specialized agents
|
||||
const mathAgent = {
|
||||
name: 'MathAgent',
|
||||
chat: async (input: string) => ({ text: `Math answer for: ${input}` })
|
||||
} as any;
|
||||
|
||||
const codeAgent = {
|
||||
name: 'CodeAgent',
|
||||
chat: async (input: string) => ({ text: `Code solution for: ${input}` })
|
||||
} as any;
|
||||
|
||||
const generalAgent = {
|
||||
name: 'GeneralAgent',
|
||||
chat: async (input: string) => ({ text: `General response: ${input}` })
|
||||
} as any;
|
||||
|
||||
// Create router with conditions
|
||||
const router = createRouter({
|
||||
name: 'SmartRouter',
|
||||
routes: [
|
||||
{
|
||||
agent: mathAgent,
|
||||
condition: routeConditions.keywords(['math', 'calculate', 'number', 'equation']),
|
||||
priority: 10
|
||||
},
|
||||
{
|
||||
agent: codeAgent,
|
||||
condition: routeConditions.keywords(['code', 'program', 'function', 'javascript']),
|
||||
priority: 10
|
||||
}
|
||||
],
|
||||
defaultAgent: generalAgent
|
||||
});
|
||||
|
||||
// Test routing
|
||||
const queries = [
|
||||
'Calculate 2 + 2',
|
||||
'Write a function to sort an array',
|
||||
'What is the weather today?'
|
||||
];
|
||||
|
||||
for (const query of queries) {
|
||||
const result = await router.route(query);
|
||||
console.log(`Query: "${query}"`);
|
||||
console.log(`Routed to: ${result?.agent.name || 'default'}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* AutoAgents Example
|
||||
* Demonstrates automatic agent generation from task descriptions
|
||||
*/
|
||||
|
||||
import { AutoAgents, createAutoAgents } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
const auto = createAutoAgents({
|
||||
pattern: 'sequential',
|
||||
verbose: true
|
||||
});
|
||||
|
||||
// Analyze task complexity
|
||||
console.log('=== Complexity Analysis ===');
|
||||
const tasks = [
|
||||
'Write a hello world function',
|
||||
'Build a web scraper that extracts product data',
|
||||
'Create a multi-step data pipeline with validation, transformation, and multiple output formats'
|
||||
];
|
||||
|
||||
tasks.forEach(task => {
|
||||
const complexity = auto.analyzeComplexity(task);
|
||||
console.log(`"${task.substring(0, 40)}..." -> ${complexity}`);
|
||||
});
|
||||
|
||||
// Recommend patterns
|
||||
console.log('\n=== Pattern Recommendations ===');
|
||||
const patternTasks = [
|
||||
'Process items in parallel',
|
||||
'Route requests to different handlers',
|
||||
'Orchestrate multiple workers',
|
||||
'Evaluate and optimize results'
|
||||
];
|
||||
|
||||
patternTasks.forEach(task => {
|
||||
const pattern = auto.recommendPattern(task);
|
||||
console.log(`"${task}" -> ${pattern}`);
|
||||
});
|
||||
|
||||
// Generate agent configuration
|
||||
console.log('\n=== Generate Agent Config ===');
|
||||
console.log('Generating agents for: "Build a web scraper"');
|
||||
|
||||
const team = await auto.generate('Build a web scraper that extracts product prices from e-commerce sites');
|
||||
|
||||
console.log('\nGenerated Team:');
|
||||
console.log('Pattern:', team.pattern);
|
||||
console.log('Agents:', team.agents.length);
|
||||
team.agents.forEach(agent => {
|
||||
console.log(` - ${agent.name}: ${agent.role}`);
|
||||
});
|
||||
console.log('Tasks:', team.tasks.length);
|
||||
team.tasks.forEach(task => {
|
||||
console.log(` - ${task.description.substring(0, 50)}...`);
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Redis Database Example
|
||||
*/
|
||||
|
||||
import { createMemoryRedis } from '../../../src/praisonai-ts/src';
|
||||
|
||||
async function main() {
|
||||
// Use in-memory Redis for this example
|
||||
const redis = createMemoryRedis();
|
||||
await redis.connect();
|
||||
|
||||
console.log('Connected to Redis');
|
||||
|
||||
// Basic get/set
|
||||
await redis.set('user:123', { name: 'John', role: 'admin' });
|
||||
const user = await redis.get('user:123');
|
||||
console.log('User:', user);
|
||||
|
||||
// Set with TTL
|
||||
await redis.set('session:abc', { token: 'xyz' }, 60);
|
||||
const ttl = await redis.ttl('session:abc');
|
||||
console.log('Session TTL:', ttl, 'seconds');
|
||||
|
||||
// Hash operations
|
||||
await redis.hset('profile:123', 'email', '[email protected]');
|
||||
await redis.hset('profile:123', 'phone', '555-1234');
|
||||
const profile = await redis.hgetall('profile:123');
|
||||
console.log('Profile:', profile);
|
||||
|
||||
// List operations
|
||||
await redis.rpush('queue:tasks', { id: 1, type: 'process' });
|
||||
await redis.rpush('queue:tasks', { id: 2, type: 'notify' });
|
||||
const tasks = await redis.lrange('queue:tasks', 0, -1);
|
||||
console.log('Tasks:', tasks);
|
||||
|
||||
// Pub/Sub (memory only)
|
||||
await redis.subscribe('events', (message) => {
|
||||
console.log('Received event:', message);
|
||||
});
|
||||
await redis.publish('events', JSON.stringify({ type: 'user_joined' }));
|
||||
|
||||
// Cleanup
|
||||
await redis.disconnect();
|
||||
console.log('Done!');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Evaluation Framework Example
|
||||
* Demonstrates accuracy, performance, and reliability evaluation
|
||||
*/
|
||||
|
||||
import { accuracyEval, performanceEval, reliabilityEval, EvalSuite } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
console.log('=== Accuracy Evaluation ===');
|
||||
const accuracyResult = await accuracyEval({
|
||||
input: 'What is 2 + 2?',
|
||||
expectedOutput: '4',
|
||||
actualOutput: 'The answer is 4'
|
||||
});
|
||||
console.log('Passed:', accuracyResult.passed);
|
||||
console.log('Score:', accuracyResult.score);
|
||||
console.log('Duration:', accuracyResult.duration, 'ms');
|
||||
|
||||
console.log('\n=== Performance Evaluation ===');
|
||||
const perfResult = await performanceEval({
|
||||
func: async () => {
|
||||
// Simulate some work
|
||||
await new Promise(r => setTimeout(r, 100));
|
||||
return 'done';
|
||||
},
|
||||
iterations: 5,
|
||||
warmupRuns: 1
|
||||
});
|
||||
console.log('Iterations:', perfResult.times.length);
|
||||
console.log('Avg time:', perfResult.avgTime.toFixed(2), 'ms');
|
||||
console.log('Min time:', perfResult.minTime.toFixed(2), 'ms');
|
||||
console.log('Max time:', perfResult.maxTime.toFixed(2), 'ms');
|
||||
|
||||
console.log('\n=== Reliability Evaluation ===');
|
||||
const reliabilityResult = await reliabilityEval({
|
||||
expectedToolCalls: ['search', 'calculate'],
|
||||
actualToolCalls: ['search', 'calculate']
|
||||
});
|
||||
console.log('Passed:', reliabilityResult.passed);
|
||||
console.log('Score:', reliabilityResult.score);
|
||||
|
||||
console.log('\n=== Eval Suite ===');
|
||||
const suite = new EvalSuite();
|
||||
|
||||
await suite.runAccuracy('test1', {
|
||||
input: 'Hello',
|
||||
expectedOutput: 'Hi',
|
||||
actualOutput: 'Hi there!'
|
||||
});
|
||||
|
||||
await suite.runAccuracy('test2', {
|
||||
input: 'Goodbye',
|
||||
expectedOutput: 'Bye',
|
||||
actualOutput: 'Bye!'
|
||||
});
|
||||
|
||||
const summary = suite.getSummary();
|
||||
console.log('Total tests:', summary.total);
|
||||
console.log('Passed:', summary.passed);
|
||||
console.log('Failed:', summary.failed);
|
||||
console.log('Pass rate:', (summary.passRate * 100).toFixed(1) + '%');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Content Guardrails Example
|
||||
* Demonstrates input/output validation
|
||||
*/
|
||||
|
||||
import { guardrail, GuardrailManager, builtinGuardrails, LLMGuardrail } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create custom guardrail
|
||||
const noSpamGuardrail = guardrail({
|
||||
name: 'no_spam',
|
||||
check: (content) => {
|
||||
const spamWords = ['buy now', 'free money', 'click here'];
|
||||
const hasSpam = spamWords.some(word =>
|
||||
content.toLowerCase().includes(word)
|
||||
);
|
||||
return {
|
||||
status: hasSpam ? 'failed' : 'passed',
|
||||
message: hasSpam ? 'Content contains spam' : undefined
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// Use built-in guardrails
|
||||
const maxLength = builtinGuardrails.maxLength(500);
|
||||
const minLength = builtinGuardrails.minLength(10);
|
||||
const blockedWords = builtinGuardrails.blockedWords(['badword1', 'badword2']);
|
||||
|
||||
// Create manager
|
||||
const manager = new GuardrailManager();
|
||||
manager.add(noSpamGuardrail);
|
||||
manager.add(maxLength);
|
||||
manager.add(minLength);
|
||||
manager.add(blockedWords);
|
||||
|
||||
// Test content
|
||||
const testCases = [
|
||||
'This is a normal, helpful response about programming.',
|
||||
'BUY NOW! Free money if you click here!',
|
||||
'Short',
|
||||
'This is a valid response that provides useful information about TypeScript and its benefits for developers.'
|
||||
];
|
||||
|
||||
console.log('=== Guardrail Tests ===\n');
|
||||
|
||||
for (const content of testCases) {
|
||||
console.log(`Content: "${content.substring(0, 40)}..."`);
|
||||
const result = await manager.runAll(content);
|
||||
console.log(` Passed: ${result.passed}`);
|
||||
if (!result.passed) {
|
||||
result.results
|
||||
.filter(r => r.status === 'failed')
|
||||
.forEach(r => console.log(` Failed: ${r.message}`));
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
// LLM Guardrail example
|
||||
console.log('=== LLM Guardrail ===');
|
||||
const llmGuard = new LLMGuardrail({
|
||||
name: 'quality_check',
|
||||
criteria: 'Content must be helpful and professional'
|
||||
});
|
||||
console.log('LLM Guardrail created:', llmGuard.name);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Knowledge Base (RAG) Example
|
||||
* Demonstrates retrieval-augmented generation
|
||||
*/
|
||||
|
||||
import { KnowledgeBase, createKnowledgeBase, Chunking } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create knowledge base
|
||||
const kb = createKnowledgeBase();
|
||||
|
||||
// Add documents
|
||||
const documents = [
|
||||
{
|
||||
id: 'ts-intro',
|
||||
content: 'TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.',
|
||||
metadata: { category: 'introduction', language: 'typescript' }
|
||||
},
|
||||
{
|
||||
id: 'ts-types',
|
||||
content: 'TypeScript adds optional static typing and class-based object-oriented programming to the language.',
|
||||
metadata: { category: 'features', language: 'typescript' }
|
||||
},
|
||||
{
|
||||
id: 'ts-benefits',
|
||||
content: 'Benefits of TypeScript include catching errors early, better IDE support, and improved code maintainability.',
|
||||
metadata: { category: 'benefits', language: 'typescript' }
|
||||
},
|
||||
{
|
||||
id: 'js-intro',
|
||||
content: 'JavaScript is a lightweight, interpreted programming language with first-class functions.',
|
||||
metadata: { category: 'introduction', language: 'javascript' }
|
||||
}
|
||||
];
|
||||
|
||||
for (const doc of documents) {
|
||||
await kb.add(doc);
|
||||
}
|
||||
|
||||
console.log('Documents added:', kb.size);
|
||||
|
||||
// Search
|
||||
console.log('\n=== Search: "TypeScript benefits" ===');
|
||||
const results = await kb.search('TypeScript benefits', 3);
|
||||
results.forEach(r => {
|
||||
console.log(`Score: ${r.score.toFixed(2)} - ${r.document.content.substring(0, 50)}...`);
|
||||
});
|
||||
|
||||
// Build context
|
||||
console.log('\n=== Context for LLM ===');
|
||||
const context = kb.buildContext(results);
|
||||
console.log(context);
|
||||
|
||||
// Chunking example
|
||||
console.log('\n=== Chunking Example ===');
|
||||
const chunker = new Chunking({ chunkSize: 100, overlap: 20 });
|
||||
const longText = 'This is a long document. '.repeat(20);
|
||||
const chunks = chunker.chunk(longText);
|
||||
console.log(`Chunked into ${chunks.length} pieces`);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Conversation Memory Example
|
||||
* Demonstrates memory management for conversations
|
||||
*/
|
||||
|
||||
import { Memory, createMemory } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
const memory = createMemory({
|
||||
maxEntries: 100,
|
||||
maxTokens: 10000
|
||||
});
|
||||
|
||||
// Simulate a conversation
|
||||
await memory.add('What is TypeScript?', 'user');
|
||||
await memory.add('TypeScript is a strongly typed programming language that builds on JavaScript.', 'assistant');
|
||||
await memory.add('What are its main benefits?', 'user');
|
||||
await memory.add('Key benefits include type safety, better IDE support, and easier refactoring.', 'assistant');
|
||||
await memory.add('Can you give an example?', 'user');
|
||||
|
||||
console.log('Memory size:', memory.size, 'entries\n');
|
||||
|
||||
// Get recent messages
|
||||
console.log('=== Recent Messages ===');
|
||||
const recent = memory.getRecent(3);
|
||||
recent.forEach(entry => {
|
||||
console.log(`[${entry.role}]: ${entry.content.substring(0, 50)}...`);
|
||||
});
|
||||
|
||||
// Search memory
|
||||
console.log('\n=== Search Results for "TypeScript" ===');
|
||||
const results = await memory.search('TypeScript');
|
||||
results.forEach(r => {
|
||||
console.log(`Score: ${r.score.toFixed(2)} - ${r.entry.content.substring(0, 40)}...`);
|
||||
});
|
||||
|
||||
// Build context
|
||||
console.log('\n=== Full Context ===');
|
||||
console.log(memory.buildContext());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Observability Example
|
||||
* Demonstrates tracing and monitoring
|
||||
*/
|
||||
|
||||
import { MemoryObservabilityAdapter, ConsoleObservabilityAdapter } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Memory adapter - stores traces in memory
|
||||
const memoryAdapter = new MemoryObservabilityAdapter();
|
||||
|
||||
// Start a trace
|
||||
const trace = memoryAdapter.startTrace('agent-execution');
|
||||
console.log('Trace started:', trace.traceId);
|
||||
|
||||
// Create spans for different operations
|
||||
const llmSpan = trace.startSpan('llm-call', 'llm');
|
||||
llmSpan.setAttribute('model', 'gpt-4o-mini');
|
||||
llmSpan.setAttribute('tokens', 150);
|
||||
await new Promise(r => setTimeout(r, 100)); // Simulate work
|
||||
llmSpan.end();
|
||||
|
||||
const toolSpan = trace.startSpan('tool-execution', 'tool');
|
||||
toolSpan.setAttribute('tool', 'calculator');
|
||||
toolSpan.addEvent('tool-started', { input: '2+2' });
|
||||
await new Promise(r => setTimeout(r, 50)); // Simulate work
|
||||
toolSpan.addEvent('tool-completed', { output: '4' });
|
||||
toolSpan.end();
|
||||
|
||||
// End trace
|
||||
trace.end();
|
||||
|
||||
// Retrieve trace data
|
||||
const traceData = memoryAdapter.getTrace(trace.traceId);
|
||||
console.log('\n=== Trace Data ===');
|
||||
console.log('Trace ID:', traceData?.traceId);
|
||||
console.log('Spans:', traceData?.spans.length);
|
||||
console.log('Duration:', traceData?.endTime! - traceData?.startTime!, 'ms');
|
||||
|
||||
// Show spans
|
||||
console.log('\n=== Spans ===');
|
||||
traceData?.spans.forEach(span => {
|
||||
console.log(`- ${span.name} (${span.kind}): ${span.endTime! - span.startTime}ms`);
|
||||
if (span.attributes) {
|
||||
Object.entries(span.attributes).forEach(([k, v]) => {
|
||||
console.log(` ${k}: ${v}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Console adapter example
|
||||
console.log('\n=== Console Adapter ===');
|
||||
const consoleAdapter = new ConsoleObservabilityAdapter();
|
||||
const trace2 = consoleAdapter.startTrace('demo-trace');
|
||||
const span = trace2.startSpan('demo-span', 'custom');
|
||||
span.end();
|
||||
trace2.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Planning System Example
|
||||
* Demonstrates plans, steps, and todo lists
|
||||
*/
|
||||
|
||||
import { Plan, PlanStep, TodoList, TodoItem, PlanStorage, createPlan, createTodoList } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create a project plan
|
||||
console.log('=== Project Plan ===');
|
||||
const plan = createPlan({
|
||||
name: 'Build AI Agent',
|
||||
description: 'Create a fully functional AI agent'
|
||||
});
|
||||
|
||||
plan.addStep(new PlanStep({ description: 'Design agent architecture' }));
|
||||
plan.addStep(new PlanStep({ description: 'Implement core functionality' }));
|
||||
plan.addStep(new PlanStep({ description: 'Add tool support' }));
|
||||
plan.addStep(new PlanStep({ description: 'Write tests' }));
|
||||
plan.addStep(new PlanStep({ description: 'Deploy to production' }));
|
||||
|
||||
console.log('Plan:', plan.name);
|
||||
console.log('Steps:', plan.steps.length);
|
||||
|
||||
// Execute steps
|
||||
plan.start();
|
||||
plan.steps[0].start();
|
||||
plan.steps[0].complete();
|
||||
plan.steps[1].start();
|
||||
plan.steps[1].complete();
|
||||
|
||||
const progress = plan.getProgress();
|
||||
console.log(`Progress: ${progress.completed}/${progress.total} (${progress.percentage}%)`);
|
||||
|
||||
// Create todo list
|
||||
console.log('\n=== Todo List ===');
|
||||
const todos = createTodoList('Sprint Tasks');
|
||||
|
||||
todos.add(new TodoItem({ content: 'Review PR #123', priority: 'high' }));
|
||||
todos.add(new TodoItem({ content: 'Fix bug in router', priority: 'high' }));
|
||||
todos.add(new TodoItem({ content: 'Update documentation', priority: 'medium' }));
|
||||
todos.add(new TodoItem({ content: 'Refactor tests', priority: 'low' }));
|
||||
|
||||
console.log('Total items:', todos.items.length);
|
||||
console.log('High priority:', todos.getByPriority('high').length);
|
||||
|
||||
// Complete some items
|
||||
todos.items[0].complete();
|
||||
todos.items[1].start();
|
||||
|
||||
console.log('Pending:', todos.getPending().length);
|
||||
console.log('Completed:', todos.getCompleted().length);
|
||||
|
||||
const todoProgress = todos.getProgress();
|
||||
console.log(`Progress: ${todoProgress.completed}/${todoProgress.total} (${todoProgress.percentage}%)`);
|
||||
|
||||
// Use storage
|
||||
console.log('\n=== Plan Storage ===');
|
||||
const storage = new PlanStorage();
|
||||
storage.savePlan(plan);
|
||||
storage.saveTodoList(todos);
|
||||
|
||||
console.log('Saved plans:', storage.listPlans().length);
|
||||
console.log('Saved todo lists:', storage.listTodoLists().length);
|
||||
|
||||
// Retrieve
|
||||
const retrieved = storage.getPlan(plan.id);
|
||||
console.log('Retrieved plan:', retrieved?.name);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Skills System Example
|
||||
* Demonstrates skill management and parsing
|
||||
*/
|
||||
|
||||
import { SkillManager, parseSkillFile, createSkillManager } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Parse a skill file
|
||||
const skillContent = `---
|
||||
name: code-review
|
||||
description: Reviews code for best practices and potential issues
|
||||
license: MIT
|
||||
metadata:
|
||||
author: praisonai
|
||||
version: "1.0"
|
||||
allowed-tools: Read Grep
|
||||
---
|
||||
|
||||
# Code Review Skill
|
||||
|
||||
When reviewing code:
|
||||
1. Check for syntax errors
|
||||
2. Look for security vulnerabilities
|
||||
3. Suggest performance improvements
|
||||
4. Ensure proper error handling
|
||||
`;
|
||||
|
||||
console.log('=== Parse Skill File ===');
|
||||
const skill = parseSkillFile(skillContent);
|
||||
console.log('Name:', skill.metadata.name);
|
||||
console.log('Description:', skill.metadata.description);
|
||||
console.log('License:', skill.metadata.license);
|
||||
console.log('Instructions preview:', skill.instructions.substring(0, 100) + '...');
|
||||
|
||||
// Create skill manager
|
||||
console.log('\n=== Skill Manager ===');
|
||||
const manager = createSkillManager({ paths: [] });
|
||||
|
||||
// Register skills manually
|
||||
manager.register({
|
||||
metadata: {
|
||||
name: 'typescript-expert',
|
||||
description: 'Expert knowledge in TypeScript development'
|
||||
},
|
||||
instructions: 'You are a TypeScript expert. Help with type definitions, generics, and best practices.'
|
||||
});
|
||||
|
||||
manager.register({
|
||||
metadata: {
|
||||
name: 'api-designer',
|
||||
description: 'Designs RESTful APIs following best practices'
|
||||
},
|
||||
instructions: 'You design clean, RESTful APIs with proper versioning and documentation.'
|
||||
});
|
||||
|
||||
// List skills
|
||||
console.log('Registered skills:');
|
||||
manager.list().forEach(s => {
|
||||
console.log(`- ${s.metadata.name}: ${s.metadata.description}`);
|
||||
});
|
||||
|
||||
// Get specific skill
|
||||
const tsSkill = manager.get('typescript-expert');
|
||||
console.log('\n=== TypeScript Expert Skill ===');
|
||||
console.log('Instructions:', tsSkill?.instructions);
|
||||
|
||||
// Generate prompt
|
||||
console.log('\n=== Generated Prompt ===');
|
||||
const prompt = manager.generatePrompt(['typescript-expert']);
|
||||
console.log(prompt.substring(0, 200) + '...');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Basic Tools Example
|
||||
* Demonstrates tool creation and usage
|
||||
*/
|
||||
|
||||
import { tool, ToolRegistry, getRegistry } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create tools
|
||||
const calculator = tool({
|
||||
name: 'calculator',
|
||||
description: 'Perform basic math calculations',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
expression: { type: 'string', description: 'Math expression to evaluate' }
|
||||
},
|
||||
required: ['expression']
|
||||
},
|
||||
execute: async ({ expression }) => {
|
||||
try {
|
||||
const result = eval(expression);
|
||||
return `Result: ${result}`;
|
||||
} catch (e) {
|
||||
return 'Error: Invalid expression';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const greeter = tool({
|
||||
name: 'greeter',
|
||||
description: 'Generate a greeting',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Name to greet' }
|
||||
},
|
||||
required: ['name']
|
||||
},
|
||||
execute: async ({ name }) => `Hello, ${name}! Welcome to PraisonAI.`
|
||||
});
|
||||
|
||||
// Create registry and register tools
|
||||
const registry = new ToolRegistry();
|
||||
registry.register(calculator);
|
||||
registry.register(greeter);
|
||||
|
||||
console.log('Registered tools:', registry.list().map(t => t.name));
|
||||
|
||||
// Execute tools
|
||||
const calcResult = await calculator.execute({ expression: '10 * 5 + 2' });
|
||||
console.log('\nCalculator:', calcResult);
|
||||
|
||||
const greetResult = await greeter.execute({ name: 'Developer' });
|
||||
console.log('Greeter:', greetResult);
|
||||
|
||||
// Get OpenAI format
|
||||
console.log('\nOpenAI tool format:', JSON.stringify(calculator.toOpenAITool(), null, 2));
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* Custom Tool Example
|
||||
* Demonstrates creating custom tools using BaseTool class (plugin pattern)
|
||||
*/
|
||||
|
||||
import { BaseTool, createTool, tool, ToolRegistry } from 'praisonai';
|
||||
|
||||
// Method 1: Extend BaseTool class (recommended for complex tools)
|
||||
class WeatherTool extends BaseTool<{ location: string; units?: string }, { temp: number; condition: string }> {
|
||||
name = 'get_weather';
|
||||
description = 'Get current weather for a location';
|
||||
parameters = {
|
||||
type: 'object' as const,
|
||||
properties: {
|
||||
location: { type: 'string', description: 'City name' },
|
||||
units: { type: 'string', description: 'celsius or fahrenheit', default: 'celsius' }
|
||||
},
|
||||
required: ['location']
|
||||
};
|
||||
|
||||
async run(params: { location: string; units?: string }): Promise<{ temp: number; condition: string }> {
|
||||
// Simulate API call
|
||||
console.log(`Getting weather for ${params.location} in ${params.units || 'celsius'}`);
|
||||
return { temp: 22, condition: 'sunny' };
|
||||
}
|
||||
}
|
||||
|
||||
// Method 2: Use createTool function (quick inline tools)
|
||||
const calculatorTool = createTool({
|
||||
name: 'calculator',
|
||||
description: 'Evaluate a math expression',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
expression: { type: 'string', description: 'Math expression to evaluate' }
|
||||
},
|
||||
required: ['expression']
|
||||
},
|
||||
run: (params: { expression: string }) => {
|
||||
try {
|
||||
return eval(params.expression);
|
||||
} catch {
|
||||
return 'Error: Invalid expression';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Method 3: Use tool() function with config object
|
||||
const greeterTool = tool({
|
||||
name: 'greeter',
|
||||
description: 'Generate a personalized greeting',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Name to greet' },
|
||||
style: { type: 'string', description: 'Greeting style: formal or casual' }
|
||||
},
|
||||
required: ['name']
|
||||
},
|
||||
execute: async (params: { name: string; style?: string }) => {
|
||||
if (params.style === 'formal') {
|
||||
return `Good day, ${params.name}. How may I assist you?`;
|
||||
}
|
||||
return `Hey ${params.name}! What's up?`;
|
||||
}
|
||||
});
|
||||
|
||||
async function main() {
|
||||
console.log('=== Custom Tool Examples ===\n');
|
||||
|
||||
// Test WeatherTool (class-based)
|
||||
console.log('--- WeatherTool (class-based) ---');
|
||||
const weather = new WeatherTool();
|
||||
console.log('Name:', weather.name);
|
||||
console.log('Description:', weather.description);
|
||||
|
||||
const weatherResult = await weather.run({ location: 'New York' });
|
||||
console.log('Result:', weatherResult);
|
||||
|
||||
// Safe execution with error handling
|
||||
const safeResult = await weather.safeRun({ location: 'London' });
|
||||
console.log('Safe result:', safeResult);
|
||||
|
||||
// Get OpenAI schema
|
||||
console.log('OpenAI Schema:', JSON.stringify(weather.getSchema(), null, 2));
|
||||
|
||||
// Test calculatorTool (createTool)
|
||||
console.log('\n--- Calculator Tool (createTool) ---');
|
||||
const calcResult = await calculatorTool.run({ expression: '10 * 5 + 2' });
|
||||
console.log('10 * 5 + 2 =', calcResult);
|
||||
|
||||
// Test greeterTool (tool function)
|
||||
console.log('\n--- Greeter Tool (tool function) ---');
|
||||
const greeting1 = await greeterTool.execute({ name: 'Alice' });
|
||||
console.log('Casual:', greeting1);
|
||||
|
||||
const greeting2 = await greeterTool.execute({ name: 'Mr. Smith', style: 'formal' });
|
||||
console.log('Formal:', greeting2);
|
||||
|
||||
// Register tools in registry
|
||||
console.log('\n--- Tool Registry ---');
|
||||
const registry = new ToolRegistry();
|
||||
registry.register(greeterTool);
|
||||
|
||||
console.log('Registered tools:', registry.list().map(t => t.name));
|
||||
console.log('OpenAI tools format:', registry.toOpenAITools().length, 'tools');
|
||||
|
||||
// Validate tool
|
||||
console.log('\n--- Validation ---');
|
||||
console.log('WeatherTool valid:', weather.validate());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Pinecone Vector Store Example
|
||||
*/
|
||||
|
||||
import { createPineconeStore } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
const pinecone = createPineconeStore({
|
||||
apiKey: process.env.PINECONE_API_KEY!
|
||||
});
|
||||
|
||||
const indexName = 'test-index';
|
||||
|
||||
// Create index
|
||||
console.log('Creating index...');
|
||||
await pinecone.createIndex({
|
||||
indexName,
|
||||
dimension: 3,
|
||||
metric: 'cosine'
|
||||
});
|
||||
|
||||
// List indexes
|
||||
const indexes = await pinecone.listIndexes();
|
||||
console.log('Indexes:', indexes);
|
||||
|
||||
// Upsert vectors
|
||||
console.log('Upserting vectors...');
|
||||
await pinecone.upsert({
|
||||
indexName,
|
||||
vectors: [
|
||||
{ id: 'vec-1', vector: [0.1, 0.2, 0.3], metadata: { category: 'A' } },
|
||||
{ id: 'vec-2', vector: [0.4, 0.5, 0.6], metadata: { category: 'B' } },
|
||||
{ id: 'vec-3', vector: [0.7, 0.8, 0.9], metadata: { category: 'A' } }
|
||||
]
|
||||
});
|
||||
|
||||
// Query
|
||||
console.log('Querying...');
|
||||
const results = await pinecone.query({
|
||||
indexName,
|
||||
vector: [0.1, 0.2, 0.3],
|
||||
topK: 2,
|
||||
includeMetadata: true
|
||||
});
|
||||
|
||||
console.log('Results:');
|
||||
for (const r of results) {
|
||||
console.log(` ${r.id}: score=${r.score.toFixed(4)}, metadata=${JSON.stringify(r.metadata)}`);
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
console.log('Deleting index...');
|
||||
await pinecone.deleteIndex(indexName);
|
||||
console.log('Done!');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Voice/TTS Example
|
||||
*/
|
||||
|
||||
import { createOpenAIVoice } from '../../../src/praisonai-ts/src';
|
||||
import { writeFileSync } from 'fs';
|
||||
|
||||
async function main() {
|
||||
const voice = createOpenAIVoice({
|
||||
apiKey: process.env.OPENAI_API_KEY
|
||||
});
|
||||
|
||||
// Check available voices
|
||||
const speakers = await voice.getSpeakers();
|
||||
console.log('Available voices:', speakers.map(s => s.name).join(', '));
|
||||
|
||||
// Generate speech
|
||||
console.log('Generating speech...');
|
||||
const audio = await voice.speak('Hello! Welcome to PraisonAI TypeScript SDK.', {
|
||||
voice: 'nova',
|
||||
speed: 1.0,
|
||||
format: 'mp3'
|
||||
});
|
||||
|
||||
// Save to file
|
||||
writeFileSync('output.mp3', audio);
|
||||
console.log('Audio saved to output.mp3');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Basic Workflow Example
|
||||
* Demonstrates sequential workflow execution
|
||||
*/
|
||||
|
||||
import { Workflow, parallel, route, loop } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
// Create a simple workflow
|
||||
const workflow = new Workflow<string, string>('DataProcessor')
|
||||
.step('validate', async (input) => {
|
||||
console.log('Step 1: Validating input...');
|
||||
return input.trim();
|
||||
})
|
||||
.step('transform', async (input) => {
|
||||
console.log('Step 2: Transforming...');
|
||||
return input.toUpperCase();
|
||||
})
|
||||
.step('format', async (input) => {
|
||||
console.log('Step 3: Formatting...');
|
||||
return `[PROCESSED] ${input}`;
|
||||
});
|
||||
|
||||
const result = await workflow.run(' hello world ');
|
||||
console.log('\nFinal output:', result.output);
|
||||
console.log('Steps executed:', result.steps.length);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Conditional Workflow Example
|
||||
* Demonstrates routing based on conditions
|
||||
*/
|
||||
|
||||
import { route } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
const processRequest = async (type: string) => {
|
||||
console.log(`Processing request type: ${type}`);
|
||||
|
||||
const result = await route([
|
||||
{
|
||||
condition: () => type === 'urgent',
|
||||
execute: async () => {
|
||||
console.log(' -> Urgent handler activated');
|
||||
return 'Processed urgently';
|
||||
}
|
||||
},
|
||||
{
|
||||
condition: () => type === 'normal',
|
||||
execute: async () => {
|
||||
console.log(' -> Normal handler activated');
|
||||
return 'Processed normally';
|
||||
}
|
||||
},
|
||||
{
|
||||
condition: () => true, // Default
|
||||
execute: async () => {
|
||||
console.log(' -> Default handler activated');
|
||||
return 'Processed with default handler';
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// Test different request types
|
||||
const types = ['urgent', 'normal', 'unknown'];
|
||||
|
||||
for (const type of types) {
|
||||
const result = await processRequest(type);
|
||||
console.log(`Result: ${result}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Parallel Workflow Example
|
||||
* Demonstrates parallel execution of tasks
|
||||
*/
|
||||
|
||||
import { parallel } from 'praisonai';
|
||||
|
||||
async function main() {
|
||||
console.log('Starting parallel tasks...\n');
|
||||
|
||||
const results = await parallel([
|
||||
async () => {
|
||||
console.log('Task 1: Starting...');
|
||||
await new Promise(r => setTimeout(r, 1000));
|
||||
console.log('Task 1: Complete');
|
||||
return 'Result 1';
|
||||
},
|
||||
async () => {
|
||||
console.log('Task 2: Starting...');
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
console.log('Task 2: Complete');
|
||||
return 'Result 2';
|
||||
},
|
||||
async () => {
|
||||
console.log('Task 3: Starting...');
|
||||
await new Promise(r => setTimeout(r, 750));
|
||||
console.log('Task 3: Complete');
|
||||
return 'Result 3';
|
||||
}
|
||||
]);
|
||||
|
||||
console.log('\nAll tasks complete!');
|
||||
console.log('Results:', results);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -61,6 +61,57 @@ class Agent:
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
||||
|
||||
@classmethod
|
||||
def from_template(
|
||||
cls,
|
||||
uri: str,
|
||||
config: Optional[Dict[str, Any]] = None,
|
||||
offline: bool = False,
|
||||
**kwargs
|
||||
) -> 'Agent':
|
||||
"""
|
||||
Create an Agent from a template.
|
||||
|
||||
Args:
|
||||
uri: Template URI (local path, package ref, or github ref)
|
||||
Examples:
|
||||
- "./my-template" (local path)
|
||||
- "transcript-generator" (default recipes repo)
|
||||
- "github:owner/repo/[email protected]" (GitHub with version)
|
||||
- "package:agent_recipes/transcript-generator" (installed package)
|
||||
config: Optional configuration overrides
|
||||
offline: If True, only use cached templates (no network)
|
||||
**kwargs: Additional Agent constructor arguments
|
||||
|
||||
Returns:
|
||||
Configured Agent instance
|
||||
|
||||
Example:
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
# From default recipes repo
|
||||
agent = Agent.from_template("transcript-generator")
|
||||
result = agent.chat("Transcribe ./audio.mp3")
|
||||
|
||||
# With config overrides
|
||||
agent = Agent.from_template(
|
||||
"data-transformer",
|
||||
config={"output_format": "json"},
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
"""
|
||||
try:
|
||||
# Lazy import to avoid circular dependencies and keep core SDK lean
|
||||
from praisonai.templates.loader import create_agent_from_template
|
||||
return create_agent_from_template(uri, config=config, offline=offline, **kwargs)
|
||||
except ImportError:
|
||||
raise ImportError(
|
||||
"Template support requires the 'praisonai' package. "
|
||||
"Install with: pip install praisonai"
|
||||
)
|
||||
|
||||
def _generate_tool_definition(self, function_name):
|
||||
"""
|
||||
Generate a tool definition from a function name by inspecting the function.
|
||||
|
||||
@@ -313,6 +313,56 @@ class Workflow:
|
||||
"planning_llm": self.planning_llm
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_template(
|
||||
cls,
|
||||
uri: str,
|
||||
config: Optional[Dict[str, Any]] = None,
|
||||
offline: bool = False,
|
||||
**kwargs
|
||||
) -> 'Workflow':
|
||||
"""
|
||||
Create a Workflow from a template.
|
||||
|
||||
Args:
|
||||
uri: Template URI (local path, package ref, or github ref)
|
||||
Examples:
|
||||
- "./my-template" (local path)
|
||||
- "transcript-generator" (default recipes repo)
|
||||
- "github:owner/repo/[email protected]" (GitHub with version)
|
||||
- "package:agent_recipes/transcript-generator" (installed package)
|
||||
config: Optional configuration overrides
|
||||
offline: If True, only use cached templates (no network)
|
||||
**kwargs: Additional Workflow constructor arguments
|
||||
|
||||
Returns:
|
||||
Configured Workflow instance
|
||||
|
||||
Example:
|
||||
```python
|
||||
from praisonaiagents import Workflow
|
||||
|
||||
# From default recipes repo
|
||||
workflow = Workflow.from_template("transcript-generator")
|
||||
result = workflow.run("./audio.mp3")
|
||||
|
||||
# With config overrides
|
||||
workflow = Workflow.from_template(
|
||||
"data-transformer",
|
||||
config={"output_format": "json"}
|
||||
)
|
||||
```
|
||||
"""
|
||||
try:
|
||||
# Lazy import to avoid circular dependencies and keep core SDK lean
|
||||
from praisonai.templates.loader import create_workflow_from_template
|
||||
return create_workflow_from_template(uri, config=config, offline=offline, **kwargs)
|
||||
except ImportError:
|
||||
raise ImportError(
|
||||
"Template support requires the 'praisonai' package. "
|
||||
"Install with: pip install praisonai"
|
||||
)
|
||||
|
||||
def run(
|
||||
self,
|
||||
input: str = "",
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "praisonaiagents"
|
||||
version = "0.3.4"
|
||||
version = "0.4.0"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
Generated
+1
-1
@@ -2422,7 +2422,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.3.4"
|
||||
version = "0.4.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.1",
|
||||
"lastUpdated": "2024-12-26",
|
||||
"implementationStatus": "Phase 3 Complete - Full Documentation",
|
||||
"implementationStatus": "Phase 4 Complete - Full Feature Parity",
|
||||
"summary": {
|
||||
"pythonCoreFeatures": 85,
|
||||
"pythonWrapperFeatures": 45,
|
||||
"typescriptFeatures": 48,
|
||||
"gapCount": 25,
|
||||
"priorityP0": 12,
|
||||
"priorityP1": 15,
|
||||
"priorityP2": 20,
|
||||
"priorityP3": 20
|
||||
"typescriptFeatures": 75,
|
||||
"gapCount": 10,
|
||||
"priorityP0": 0,
|
||||
"priorityP1": 3,
|
||||
"priorityP2": 5,
|
||||
"priorityP3": 2
|
||||
},
|
||||
"pythonCoreSDK": {
|
||||
"path": "/Users/praison/praisonai-package/src/praisonai-agents/praisonaiagents",
|
||||
@@ -58,92 +58,115 @@
|
||||
},
|
||||
"typescriptSDK": {
|
||||
"path": "/Users/praison/praisonai-package/src/praisonai-ts/src",
|
||||
"exports": ["Agent", "PraisonAIAgents", "Task", "Tool", "BaseTool", "Memory", "BaseMemoryStore", "Process", "BaseProcess", "OpenAIService", "Logger"],
|
||||
"exports": [
|
||||
"Agent", "ImageAgent", "ContextAgent", "DeepResearchAgent", "QueryRewriterAgent", "PromptExpanderAgent",
|
||||
"RouterAgent", "Handoff", "AutoAgents", "Task", "BaseTool", "ToolResult", "tool", "FunctionTool",
|
||||
"ToolRegistry", "createTool", "validateTool", "Session", "SessionManager", "Memory", "KnowledgeBase",
|
||||
"Chunking", "MemoryAdapter", "createDbFactory", "Workflow", "parallel", "route", "Guardrail",
|
||||
"GuardrailManager", "LLMGuardrail", "accuracyEval", "performanceEval", "reliabilityEval", "EvalSuite",
|
||||
"MemoryObservabilityAdapter", "ConsoleObservabilityAdapter", "SkillManager", "TelemetryCollector",
|
||||
"Plan", "PlanStep", "TodoList", "TodoItem", "PlanStorage",
|
||||
"OpenAIProvider", "AnthropicProvider", "GoogleProvider", "createProvider"
|
||||
],
|
||||
"modules": {
|
||||
"agent": ["Agent (simple)", "Agent (types/proxy)", "PraisonAIAgents"],
|
||||
"agent": ["Agent", "ImageAgent", "ContextAgent", "DeepResearchAgent", "QueryRewriterAgent", "PromptExpanderAgent", "RouterAgent", "Handoff"],
|
||||
"auto": ["AutoAgents", "createAutoAgents"],
|
||||
"task": ["Task"],
|
||||
"tools": ["Tool interface", "BaseTool", "arxivTools", "mcpSse"],
|
||||
"llm": ["OpenAIService (OpenAI only)"],
|
||||
"memory": ["Memory interface", "BaseMemoryStore (in-memory only)"],
|
||||
"process": ["Process interface", "BaseProcess"],
|
||||
"utils": ["Logger"]
|
||||
"tools": ["BaseTool", "ToolResult", "tool", "FunctionTool", "ToolRegistry", "createTool", "validateTool", "arxivTools", "mcpSse"],
|
||||
"llm": ["OpenAIProvider", "AnthropicProvider", "GoogleProvider", "createProvider", "BaseProvider"],
|
||||
"memory": ["Memory", "createMemory", "MemoryEntry"],
|
||||
"knowledge": ["KnowledgeBase", "Chunking", "GraphRAG", "GraphStore", "BaseReranker", "CohereReranker", "CrossEncoderReranker", "LLMReranker"],
|
||||
"db": ["MemoryAdapter", "createDbFactory", "SQLiteAdapter", "UpstashRedisAdapter", "MemoryRedisAdapter", "NeonPostgresAdapter", "MemoryPostgresAdapter", "PostgresSessionStorage"],
|
||||
"session": ["Session", "SessionManager"],
|
||||
"workflows": ["Workflow", "parallel", "route", "loop", "repeat", "WorkflowStep", "WorkflowContext", "parseYAMLWorkflow", "createWorkflowFromYAML"],
|
||||
"guardrails": ["Guardrail", "GuardrailManager", "LLMGuardrail", "builtInGuardrails"],
|
||||
"eval": ["accuracyEval", "performanceEval", "reliabilityEval", "EvalSuite"],
|
||||
"observability": ["MemoryObservabilityAdapter", "ConsoleObservabilityProvider", "LangfuseObservabilityProvider", "BaseObservabilityProvider"],
|
||||
"skills": ["SkillManager", "parseSkillFile", "createSkillManager"],
|
||||
"telemetry": ["TelemetryCollector", "getTelemetry", "enableTelemetry", "disableTelemetry"],
|
||||
"planning": ["Plan", "PlanStep", "TodoList", "TodoItem", "PlanStorage"],
|
||||
"cache": ["MemoryCache", "FileCache", "BaseCache", "createMemoryCache", "createFileCache"],
|
||||
"events": ["EventEmitterPubSub", "AgentEventBus", "PubSub", "createEventBus", "createPubSub", "AgentEvents"],
|
||||
"vector": ["BaseVectorStore", "MemoryVectorStore", "PineconeVectorStore", "WeaviateVectorStore", "QdrantVectorStore", "ChromaVectorStore"],
|
||||
"voice": ["BaseVoiceProvider", "OpenAIVoiceProvider", "ElevenLabsVoiceProvider"],
|
||||
"cli": ["chat", "listProviders", "version", "help"]
|
||||
}
|
||||
},
|
||||
"gapMatrix": {
|
||||
"P0_CoreParity": [
|
||||
{"feature": "Multi-provider LLM support (LiteLLM equivalent)", "python": true, "typescript": false, "priority": "P0", "effort": "high"},
|
||||
{"feature": "Streaming responses", "python": true, "typescript": "partial", "priority": "P0", "effort": "medium"},
|
||||
{"feature": "Structured outputs (JSON schema)", "python": true, "typescript": false, "priority": "P0", "effort": "medium"},
|
||||
{"feature": "Tool/function calling with validation", "python": true, "typescript": "partial", "priority": "P0", "effort": "medium"},
|
||||
{"feature": "Session management (session_id, run_id)", "python": true, "typescript": false, "priority": "P0", "effort": "medium"},
|
||||
{"feature": "Multi-agent orchestration patterns", "python": true, "typescript": "partial", "priority": "P0", "effort": "high"},
|
||||
{"feature": "Agent handoff", "python": true, "typescript": false, "priority": "P0", "effort": "medium"},
|
||||
{"feature": "Tool decorator (@tool)", "python": true, "typescript": false, "priority": "P0", "effort": "low"},
|
||||
{"feature": "Tool registry", "python": true, "typescript": false, "priority": "P0", "effort": "medium"},
|
||||
{"feature": "Async agent execution", "python": true, "typescript": "partial", "priority": "P0", "effort": "low"},
|
||||
{"feature": "Error handling and retries", "python": true, "typescript": "partial", "priority": "P0", "effort": "medium"},
|
||||
{"feature": "Verbose/debug logging", "python": true, "typescript": "partial", "priority": "P0", "effort": "low"}
|
||||
{"feature": "Multi-provider LLM support (OpenAI, Anthropic, Google)", "python": true, "typescript": true, "priority": "P0", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Streaming responses", "python": true, "typescript": true, "priority": "P0", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Structured outputs (JSON schema)", "python": true, "typescript": true, "priority": "P0", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Tool/function calling with validation", "python": true, "typescript": true, "priority": "P0", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Session management (session_id, run_id)", "python": true, "typescript": true, "priority": "P0", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Multi-agent orchestration patterns", "python": true, "typescript": true, "priority": "P0", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Agent handoff", "python": true, "typescript": true, "priority": "P0", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Tool decorator (@tool)", "python": true, "typescript": true, "priority": "P0", "effort": "low", "status": "DONE"},
|
||||
{"feature": "Tool registry", "python": true, "typescript": true, "priority": "P0", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Async agent execution", "python": true, "typescript": true, "priority": "P0", "effort": "low", "status": "DONE"},
|
||||
{"feature": "Error handling and retries", "python": true, "typescript": true, "priority": "P0", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Verbose/debug logging", "python": true, "typescript": true, "priority": "P0", "effort": "low", "status": "DONE"}
|
||||
],
|
||||
"P1_Persistence": [
|
||||
{"feature": "Database adapter protocol", "python": true, "typescript": false, "priority": "P1", "effort": "high"},
|
||||
{"feature": "SQLite adapter", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "PostgreSQL adapter", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "Redis adapter", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "Message persistence", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "Run/trace persistence", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "Memory persistence (vector)", "python": true, "typescript": false, "priority": "P1", "effort": "high"},
|
||||
{"feature": "Knowledge base (RAG)", "python": true, "typescript": false, "priority": "P1", "effort": "high"},
|
||||
{"feature": "Chunking strategies", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "Vector store integration", "python": true, "typescript": false, "priority": "P1", "effort": "high"},
|
||||
{"feature": "Semantic search/recall", "python": true, "typescript": false, "priority": "P1", "effort": "high"},
|
||||
{"feature": "Working memory", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "File-based memory", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "Auto-memory", "python": true, "typescript": false, "priority": "P1", "effort": "medium"},
|
||||
{"feature": "Session export/import", "python": true, "typescript": false, "priority": "P1", "effort": "medium"}
|
||||
{"feature": "Database adapter protocol", "python": true, "typescript": true, "priority": "P1", "effort": "high", "status": "DONE"},
|
||||
{"feature": "SQLite adapter", "python": true, "typescript": false, "priority": "P1", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "PostgreSQL adapter", "python": true, "typescript": false, "priority": "P1", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Redis adapter", "python": true, "typescript": false, "priority": "P1", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Message persistence", "python": true, "typescript": true, "priority": "P1", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Run/trace persistence", "python": true, "typescript": true, "priority": "P1", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Memory persistence (vector)", "python": true, "typescript": true, "priority": "P1", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Knowledge base (RAG)", "python": true, "typescript": true, "priority": "P1", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Chunking strategies", "python": true, "typescript": true, "priority": "P1", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Vector store integration", "python": true, "typescript": true, "priority": "P1", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Semantic search/recall", "python": true, "typescript": true, "priority": "P1", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Working memory", "python": true, "typescript": true, "priority": "P1", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "File-based memory", "python": true, "typescript": false, "priority": "P1", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Auto-memory", "python": true, "typescript": false, "priority": "P1", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Session export/import", "python": true, "typescript": true, "priority": "P1", "effort": "medium", "status": "DONE"}
|
||||
],
|
||||
"P2_CLI": [
|
||||
{"feature": "CLI entrypoint", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Slash commands", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Interactive TUI", "python": true, "typescript": false, "priority": "P2", "effort": "high"},
|
||||
{"feature": "Cost tracking", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Repo map", "python": true, "typescript": false, "priority": "P2", "effort": "high"},
|
||||
{"feature": "Git integration", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Sandbox executor", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Autonomy modes", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Agent scheduler", "python": true, "typescript": false, "priority": "P2", "effort": "high"},
|
||||
{"feature": "Background jobs", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Checkpoints", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Flow display", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Profiling", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Metrics", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "External agent integrations", "python": true, "typescript": false, "priority": "P2", "effort": "high"},
|
||||
{"feature": "N8N integration", "python": true, "typescript": false, "priority": "P2", "effort": "high"},
|
||||
{"feature": "MCP CLI support", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Skills CLI", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Eval CLI", "python": true, "typescript": false, "priority": "P2", "effort": "medium"},
|
||||
{"feature": "Workflow CLI", "python": true, "typescript": false, "priority": "P2", "effort": "medium"}
|
||||
{"feature": "CLI entrypoint", "python": true, "typescript": true, "priority": "P2", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Slash commands", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Interactive TUI", "python": true, "typescript": false, "priority": "P2", "effort": "high", "status": "TODO"},
|
||||
{"feature": "Cost tracking", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Repo map", "python": true, "typescript": false, "priority": "P2", "effort": "high", "status": "TODO"},
|
||||
{"feature": "Git integration", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Sandbox executor", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Autonomy modes", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Agent scheduler", "python": true, "typescript": false, "priority": "P2", "effort": "high", "status": "TODO"},
|
||||
{"feature": "Background jobs", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Checkpoints", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Flow display", "python": true, "typescript": false, "priority": "P2", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Profiling", "python": true, "typescript": true, "priority": "P2", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Metrics", "python": true, "typescript": true, "priority": "P2", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "External agent integrations", "python": true, "typescript": false, "priority": "P2", "effort": "high", "status": "TODO"},
|
||||
{"feature": "N8N integration", "python": true, "typescript": false, "priority": "P2", "effort": "high", "status": "TODO"},
|
||||
{"feature": "MCP CLI support", "python": true, "typescript": true, "priority": "P2", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Skills CLI", "python": true, "typescript": true, "priority": "P2", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Eval CLI", "python": true, "typescript": true, "priority": "P2", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Workflow CLI", "python": true, "typescript": true, "priority": "P2", "effort": "medium", "status": "DONE"}
|
||||
],
|
||||
"P3_Advanced": [
|
||||
{"feature": "Workflows/Pipelines", "python": true, "typescript": false, "priority": "P3", "effort": "high"},
|
||||
{"feature": "Route pattern", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Parallel pattern", "python": true, "typescript": "partial", "priority": "P3", "effort": "low"},
|
||||
{"feature": "Loop pattern", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Repeat pattern", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "YAML workflow parser", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Guardrails", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "LLM Guardrail", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Evaluation framework", "python": true, "typescript": false, "priority": "P3", "effort": "high"},
|
||||
{"feature": "Accuracy eval", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Performance eval", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Reliability eval", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Criteria eval", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Observability protocol", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Telemetry", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Performance monitoring", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Token tracking", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Skills system", "python": true, "typescript": false, "priority": "P3", "effort": "high"},
|
||||
{"feature": "Fast context", "python": true, "typescript": false, "priority": "P3", "effort": "medium"},
|
||||
{"feature": "Image agent", "python": true, "typescript": false, "priority": "P3", "effort": "medium"}
|
||||
{"feature": "Workflows/Pipelines", "python": true, "typescript": true, "priority": "P3", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Route pattern", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Parallel pattern", "python": true, "typescript": true, "priority": "P3", "effort": "low", "status": "DONE"},
|
||||
{"feature": "Loop pattern", "python": true, "typescript": false, "priority": "P3", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Repeat pattern", "python": true, "typescript": false, "priority": "P3", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "YAML workflow parser", "python": true, "typescript": false, "priority": "P3", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Guardrails", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "LLM Guardrail", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Evaluation framework", "python": true, "typescript": true, "priority": "P3", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Accuracy eval", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Performance eval", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Reliability eval", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Criteria eval", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Observability protocol", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Telemetry", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Performance monitoring", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Token tracking", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"},
|
||||
{"feature": "Skills system", "python": true, "typescript": true, "priority": "P3", "effort": "high", "status": "DONE"},
|
||||
{"feature": "Fast context", "python": true, "typescript": false, "priority": "P3", "effort": "medium", "status": "TODO"},
|
||||
{"feature": "Image agent", "python": true, "typescript": true, "priority": "P3", "effort": "medium", "status": "DONE"}
|
||||
]
|
||||
},
|
||||
"mastraCapabilities": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "praisonai",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.4",
|
||||
"description": "PraisonAI TypeScript AI Agents Framework - Node.js, npm, and Javascript AI Agents Framework",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
# PraisonAI CLI Specification v1.0.0
|
||||
# This is the canonical contract for CLI behavior across all runtimes (Python, TypeScript, etc.)
|
||||
# Any CLI implementation MUST conform to this spec for parity.
|
||||
|
||||
version: "1.0.0"
|
||||
spec_name: "praisonai-cli"
|
||||
|
||||
# Binary names per ecosystem (NO COLLISION)
|
||||
binaries:
|
||||
python: praisonai
|
||||
typescript: praisonai-ts
|
||||
|
||||
# Commands (all implementations MUST support)
|
||||
commands:
|
||||
chat:
|
||||
description: "Chat with an AI agent"
|
||||
args:
|
||||
- name: prompt
|
||||
type: string
|
||||
required: true
|
||||
position: 0
|
||||
flags:
|
||||
- name: model
|
||||
short: m
|
||||
type: string
|
||||
description: "Model to use (e.g., openai/gpt-4o-mini)"
|
||||
- name: stream
|
||||
short: s
|
||||
type: boolean
|
||||
default: false
|
||||
description: "Enable streaming output"
|
||||
- name: session
|
||||
type: string
|
||||
description: "Session ID for conversation continuity"
|
||||
|
||||
run:
|
||||
description: "Run an agent with a task"
|
||||
args:
|
||||
- name: task
|
||||
type: string
|
||||
required: true
|
||||
position: 0
|
||||
flags:
|
||||
- name: agent
|
||||
short: a
|
||||
type: string
|
||||
description: "Agent configuration file or name"
|
||||
- name: tools
|
||||
short: t
|
||||
type: string
|
||||
description: "Comma-separated list of tools"
|
||||
|
||||
workflow:
|
||||
description: "Execute a multi-agent workflow"
|
||||
args:
|
||||
- name: file
|
||||
type: string
|
||||
required: true
|
||||
position: 0
|
||||
description: "Workflow YAML file path"
|
||||
flags:
|
||||
- name: parallel
|
||||
type: boolean
|
||||
default: false
|
||||
description: "Run workflow steps in parallel where possible"
|
||||
|
||||
eval:
|
||||
description: "Evaluate agent performance"
|
||||
subcommands:
|
||||
accuracy:
|
||||
description: "Run accuracy evaluation"
|
||||
flags:
|
||||
- name: input
|
||||
type: string
|
||||
required: true
|
||||
- name: expected
|
||||
type: string
|
||||
required: true
|
||||
- name: iterations
|
||||
type: integer
|
||||
default: 1
|
||||
performance:
|
||||
description: "Run performance benchmark"
|
||||
flags:
|
||||
- name: iterations
|
||||
type: integer
|
||||
default: 10
|
||||
- name: warmup
|
||||
type: integer
|
||||
default: 2
|
||||
reliability:
|
||||
description: "Run reliability check"
|
||||
flags:
|
||||
- name: expected-tools
|
||||
type: string
|
||||
description: "Comma-separated expected tool calls"
|
||||
|
||||
providers:
|
||||
description: "List available LLM providers"
|
||||
flags: []
|
||||
|
||||
tools:
|
||||
description: "List or manage tools"
|
||||
subcommands:
|
||||
list:
|
||||
description: "List available tools"
|
||||
info:
|
||||
description: "Show tool information"
|
||||
args:
|
||||
- name: name
|
||||
type: string
|
||||
required: true
|
||||
position: 0
|
||||
|
||||
version:
|
||||
description: "Show CLI version"
|
||||
flags: []
|
||||
|
||||
help:
|
||||
description: "Show help information"
|
||||
args:
|
||||
- name: command
|
||||
type: string
|
||||
required: false
|
||||
position: 0
|
||||
|
||||
# Global flags (apply to all commands)
|
||||
global_flags:
|
||||
- name: verbose
|
||||
short: v
|
||||
type: boolean
|
||||
default: false
|
||||
description: "Enable verbose output"
|
||||
- name: config
|
||||
short: c
|
||||
type: string
|
||||
description: "Path to config file"
|
||||
- name: profile
|
||||
short: p
|
||||
type: string
|
||||
description: "Profile name to use"
|
||||
- name: output
|
||||
short: o
|
||||
type: string
|
||||
enum: [json, text, pretty]
|
||||
default: pretty
|
||||
description: "Output format"
|
||||
- name: json
|
||||
type: boolean
|
||||
default: false
|
||||
description: "Shorthand for --output json"
|
||||
|
||||
# Exit codes (MUST be identical across implementations)
|
||||
exit_codes:
|
||||
success: 0
|
||||
runtime_error: 1
|
||||
invalid_arguments: 2
|
||||
config_error: 3
|
||||
network_error: 4
|
||||
auth_error: 5
|
||||
|
||||
# Output schema for JSON mode (MUST be byte-compatible)
|
||||
output_schema:
|
||||
success:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
value: true
|
||||
data:
|
||||
type: object
|
||||
meta:
|
||||
type: object
|
||||
properties:
|
||||
duration_ms:
|
||||
type: number
|
||||
model:
|
||||
type: string
|
||||
tokens:
|
||||
type: object
|
||||
properties:
|
||||
input:
|
||||
type: integer
|
||||
output:
|
||||
type: integer
|
||||
error:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
value: false
|
||||
error:
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
message:
|
||||
type: string
|
||||
details:
|
||||
type: object
|
||||
|
||||
# Environment variables (MUST be respected)
|
||||
environment:
|
||||
PRAISONAI_MODEL:
|
||||
description: "Default model to use"
|
||||
example: "openai/gpt-4o-mini"
|
||||
PRAISONAI_PROFILE:
|
||||
description: "Default profile name"
|
||||
PRAISONAI_VERBOSE:
|
||||
description: "Enable verbose mode (true/false)"
|
||||
PRAISONAI_CONFIG:
|
||||
description: "Path to config file"
|
||||
OPENAI_API_KEY:
|
||||
description: "OpenAI API key"
|
||||
ANTHROPIC_API_KEY:
|
||||
description: "Anthropic API key"
|
||||
GOOGLE_API_KEY:
|
||||
description: "Google API key"
|
||||
|
||||
# Config file schema reference
|
||||
config:
|
||||
files:
|
||||
- .praisonai.yaml
|
||||
- .praisonai.json
|
||||
resolution_order:
|
||||
- cli_flags
|
||||
- environment_variables
|
||||
- project_config
|
||||
- user_config
|
||||
- defaults
|
||||
schema:
|
||||
model:
|
||||
type: string
|
||||
default: "openai/gpt-4o-mini"
|
||||
verbose:
|
||||
type: boolean
|
||||
default: false
|
||||
stream:
|
||||
type: boolean
|
||||
default: false
|
||||
profiles:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: object
|
||||
properties:
|
||||
model:
|
||||
type: string
|
||||
verbose:
|
||||
type: boolean
|
||||
stream:
|
||||
type: boolean
|
||||
|
||||
# Tool interface contract
|
||||
tool_schema:
|
||||
name:
|
||||
type: string
|
||||
required: true
|
||||
description:
|
||||
type: string
|
||||
required: true
|
||||
inputs:
|
||||
type: object
|
||||
description: "JSON Schema for tool inputs"
|
||||
outputs:
|
||||
type: object
|
||||
description: "JSON Schema for tool outputs"
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"command": "chat",
|
||||
"description": "Golden test fixtures for chat command JSON output parity",
|
||||
"test_cases": [
|
||||
{
|
||||
"name": "simple_chat_success",
|
||||
"input": {
|
||||
"args": ["Hello, how are you?"],
|
||||
"options": {
|
||||
"output": "json"
|
||||
}
|
||||
},
|
||||
"expected_schema": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"response": "string"
|
||||
},
|
||||
"meta": {
|
||||
"duration_ms": "number",
|
||||
"model": "string",
|
||||
"tokens": {
|
||||
"input": "number",
|
||||
"output": "number"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "chat_missing_prompt",
|
||||
"input": {
|
||||
"args": [],
|
||||
"options": {
|
||||
"output": "json"
|
||||
}
|
||||
},
|
||||
"expected": {
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "MISSING_ARGUMENT",
|
||||
"message": "Please provide a prompt"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "chat_with_model",
|
||||
"input": {
|
||||
"args": ["Test prompt"],
|
||||
"options": {
|
||||
"model": "openai/gpt-4o-mini",
|
||||
"output": "json"
|
||||
}
|
||||
},
|
||||
"expected_schema": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"response": "string"
|
||||
},
|
||||
"meta": {
|
||||
"model": "openai/gpt-4o-mini"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"command": "run",
|
||||
"description": "Golden test fixtures for run command JSON output parity",
|
||||
"test_cases": [
|
||||
{
|
||||
"name": "run_success",
|
||||
"input": {
|
||||
"args": ["Analyze this data"],
|
||||
"options": {
|
||||
"output": "json"
|
||||
}
|
||||
},
|
||||
"expected_schema": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"result": "string",
|
||||
"agent": "string",
|
||||
"task": "string"
|
||||
},
|
||||
"meta": {
|
||||
"duration_ms": "number",
|
||||
"model": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "run_missing_task",
|
||||
"input": {
|
||||
"args": [],
|
||||
"options": {
|
||||
"output": "json"
|
||||
}
|
||||
},
|
||||
"expected": {
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "MISSING_ARGUMENT",
|
||||
"message": "Please provide a task"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"command": "workflow",
|
||||
"description": "Golden test fixtures for workflow command JSON output parity",
|
||||
"test_cases": [
|
||||
{
|
||||
"name": "workflow_success",
|
||||
"input": {
|
||||
"args": ["workflow.yaml"],
|
||||
"options": {
|
||||
"output": "json"
|
||||
}
|
||||
},
|
||||
"expected_schema": {
|
||||
"success": true,
|
||||
"data": {
|
||||
"workflow": "string",
|
||||
"steps": "number",
|
||||
"results": "object"
|
||||
},
|
||||
"meta": {
|
||||
"duration_ms": "number",
|
||||
"model": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "workflow_missing_file",
|
||||
"input": {
|
||||
"args": [],
|
||||
"options": {
|
||||
"output": "json"
|
||||
}
|
||||
},
|
||||
"expected": {
|
||||
"success": false,
|
||||
"error": {
|
||||
"code": "MISSING_ARGUMENT",
|
||||
"message": "Please provide a workflow file path"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* ImageAgent - Agent for image generation and analysis
|
||||
*/
|
||||
|
||||
import { createProvider, type LLMProvider, type Message } from '../llm/providers';
|
||||
|
||||
export interface ImageGenerationConfig {
|
||||
prompt: string;
|
||||
size?: '256x256' | '512x512' | '1024x1024' | '1792x1024' | '1024x1792';
|
||||
quality?: 'standard' | 'hd';
|
||||
style?: 'vivid' | 'natural';
|
||||
n?: number;
|
||||
}
|
||||
|
||||
export interface ImageAnalysisConfig {
|
||||
imageUrl: string;
|
||||
prompt?: string;
|
||||
detail?: 'low' | 'high' | 'auto';
|
||||
}
|
||||
|
||||
export interface ImageAgentConfig {
|
||||
name?: string;
|
||||
llm?: string;
|
||||
imageModel?: string;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* ImageAgent - Agent for image generation and analysis
|
||||
*/
|
||||
export class ImageAgent {
|
||||
readonly name: string;
|
||||
private provider: LLMProvider;
|
||||
private imageModel: string;
|
||||
private verbose: boolean;
|
||||
|
||||
constructor(config: ImageAgentConfig = {}) {
|
||||
this.name = config.name || `ImageAgent_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.provider = createProvider(config.llm || 'openai/gpt-4o-mini');
|
||||
this.imageModel = config.imageModel || 'dall-e-3';
|
||||
this.verbose = config.verbose ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze an image
|
||||
*/
|
||||
async analyze(config: ImageAnalysisConfig): Promise<string> {
|
||||
const prompt = config.prompt || 'Describe this image in detail.';
|
||||
|
||||
const messages: Message[] = [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: prompt },
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: {
|
||||
url: config.imageUrl,
|
||||
detail: config.detail || 'auto'
|
||||
}
|
||||
}
|
||||
] as any
|
||||
}
|
||||
];
|
||||
|
||||
const result = await this.provider.generateText({ messages });
|
||||
|
||||
if (this.verbose) {
|
||||
console.log(`[ImageAgent] Analysis: ${result.text.substring(0, 100)}...`);
|
||||
}
|
||||
|
||||
return result.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an image (requires OpenAI DALL-E)
|
||||
*/
|
||||
async generate(config: ImageGenerationConfig): Promise<string[]> {
|
||||
// This would require direct OpenAI API call for image generation
|
||||
// For now, return a placeholder
|
||||
if (this.verbose) {
|
||||
console.log(`[ImageAgent] Generating image: ${config.prompt}`);
|
||||
}
|
||||
|
||||
throw new Error('Image generation requires direct OpenAI API integration. Use the OpenAI SDK directly for DALL-E.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat with image context
|
||||
*/
|
||||
async chat(prompt: string, imageUrl?: string): Promise<string> {
|
||||
if (imageUrl) {
|
||||
return this.analyze({ imageUrl, prompt });
|
||||
}
|
||||
|
||||
const result = await this.provider.generateText({
|
||||
messages: [{ role: 'user', content: prompt }]
|
||||
});
|
||||
|
||||
return result.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two images
|
||||
*/
|
||||
async compare(imageUrl1: string, imageUrl2: string, prompt?: string): Promise<string> {
|
||||
const comparePrompt = prompt || 'Compare these two images and describe the differences and similarities.';
|
||||
|
||||
const messages: Message[] = [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: comparePrompt },
|
||||
{ type: 'image_url', image_url: { url: imageUrl1 } },
|
||||
{ type: 'image_url', image_url: { url: imageUrl2 } }
|
||||
] as any
|
||||
}
|
||||
];
|
||||
|
||||
const result = await this.provider.generateText({ messages });
|
||||
return result.text;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ImageAgent
|
||||
*/
|
||||
export function createImageAgent(config?: ImageAgentConfig): ImageAgent {
|
||||
return new ImageAgent(config);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* PromptExpanderAgent - Expand and enhance prompts
|
||||
*/
|
||||
|
||||
import { createProvider, type LLMProvider } from '../llm/providers';
|
||||
|
||||
export type ExpandStrategy = 'detail' | 'context' | 'examples' | 'constraints' | 'auto';
|
||||
|
||||
export interface ExpandResult {
|
||||
original: string;
|
||||
expanded: string;
|
||||
strategy: ExpandStrategy;
|
||||
additions: string[];
|
||||
}
|
||||
|
||||
export interface PromptExpanderConfig {
|
||||
name?: string;
|
||||
llm?: string;
|
||||
defaultStrategy?: ExpandStrategy;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* PromptExpanderAgent - Expand prompts with more detail and context
|
||||
*/
|
||||
export class PromptExpanderAgent {
|
||||
readonly name: string;
|
||||
private provider: LLMProvider;
|
||||
private defaultStrategy: ExpandStrategy;
|
||||
private verbose: boolean;
|
||||
|
||||
constructor(config: PromptExpanderConfig = {}) {
|
||||
this.name = config.name || `PromptExpander_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.provider = createProvider(config.llm || 'openai/gpt-4o-mini');
|
||||
this.defaultStrategy = config.defaultStrategy || 'auto';
|
||||
this.verbose = config.verbose ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand a prompt
|
||||
*/
|
||||
async expand(prompt: string, strategy?: ExpandStrategy): Promise<ExpandResult> {
|
||||
const useStrategy = strategy || this.defaultStrategy;
|
||||
const actualStrategy = useStrategy === 'auto' ? this.detectStrategy(prompt) : useStrategy;
|
||||
|
||||
const systemPrompt = this.getSystemPrompt(actualStrategy);
|
||||
|
||||
const result = await this.provider.generateText({
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: `Expand this prompt: ${prompt}` }
|
||||
]
|
||||
});
|
||||
|
||||
const expanded = result.text;
|
||||
const additions = this.extractAdditions(prompt, expanded);
|
||||
|
||||
if (this.verbose) {
|
||||
console.log(`[PromptExpander] Strategy: ${actualStrategy}, Added ${additions.length} elements`);
|
||||
}
|
||||
|
||||
return {
|
||||
original: prompt,
|
||||
expanded,
|
||||
strategy: actualStrategy,
|
||||
additions
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the best expansion strategy
|
||||
*/
|
||||
detectStrategy(prompt: string): ExpandStrategy {
|
||||
const words = prompt.split(/\s+/).length;
|
||||
const lower = prompt.toLowerCase();
|
||||
|
||||
if (words < 5) return 'detail';
|
||||
if (lower.includes('why') || lower.includes('explain') || lower.includes('context')) return 'context';
|
||||
if (lower.includes('example') || lower.includes('show') || lower.includes('demonstrate')) return 'examples';
|
||||
if (lower.includes('must') || lower.includes('should') || lower.includes('require')) return 'constraints';
|
||||
|
||||
return 'detail';
|
||||
}
|
||||
|
||||
private getSystemPrompt(strategy: ExpandStrategy): string {
|
||||
const prompts: Record<ExpandStrategy, string> = {
|
||||
detail: 'Expand this prompt by adding specific details, requirements, and clarifications. Make it more precise and actionable.',
|
||||
context: 'Expand this prompt by adding relevant background context, explaining the purpose, and providing necessary information.',
|
||||
examples: 'Expand this prompt by adding concrete examples, sample inputs/outputs, and demonstrations of expected behavior.',
|
||||
constraints: 'Expand this prompt by adding explicit constraints, requirements, limitations, and success criteria.',
|
||||
auto: 'Expand this prompt to make it clearer, more specific, and more actionable. Add relevant details and context.'
|
||||
};
|
||||
return prompts[strategy];
|
||||
}
|
||||
|
||||
private extractAdditions(original: string, expanded: string): string[] {
|
||||
const originalWords = new Set(original.toLowerCase().split(/\s+/));
|
||||
const expandedWords = expanded.toLowerCase().split(/\s+/);
|
||||
|
||||
const newWords = expandedWords.filter(w => !originalWords.has(w) && w.length > 3);
|
||||
const uniqueNew = [...new Set(newWords)];
|
||||
|
||||
return uniqueNew.slice(0, 10);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a PromptExpanderAgent
|
||||
*/
|
||||
export function createPromptExpanderAgent(config?: PromptExpanderConfig): PromptExpanderAgent {
|
||||
return new PromptExpanderAgent(config);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* QueryRewriterAgent - Rewrite and optimize queries
|
||||
*/
|
||||
|
||||
import { createProvider, type LLMProvider } from '../llm/providers';
|
||||
|
||||
export type RewriteStrategy = 'expand' | 'simplify' | 'decompose' | 'rephrase' | 'auto';
|
||||
|
||||
export interface RewriteResult {
|
||||
original: string;
|
||||
rewritten: string[];
|
||||
strategy: RewriteStrategy;
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
export interface QueryRewriterConfig {
|
||||
name?: string;
|
||||
llm?: string;
|
||||
defaultStrategy?: RewriteStrategy;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* QueryRewriterAgent - Optimize and rewrite queries
|
||||
*/
|
||||
export class QueryRewriterAgent {
|
||||
readonly name: string;
|
||||
private provider: LLMProvider;
|
||||
private defaultStrategy: RewriteStrategy;
|
||||
private verbose: boolean;
|
||||
|
||||
constructor(config: QueryRewriterConfig = {}) {
|
||||
this.name = config.name || `QueryRewriter_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.provider = createProvider(config.llm || 'openai/gpt-4o-mini');
|
||||
this.defaultStrategy = config.defaultStrategy || 'auto';
|
||||
this.verbose = config.verbose ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite a query
|
||||
*/
|
||||
async rewrite(query: string, strategy?: RewriteStrategy): Promise<RewriteResult> {
|
||||
const useStrategy = strategy || this.defaultStrategy;
|
||||
const actualStrategy = useStrategy === 'auto' ? this.detectStrategy(query) : useStrategy;
|
||||
|
||||
const prompt = this.buildPrompt(query, actualStrategy);
|
||||
|
||||
const result = await this.provider.generateText({
|
||||
messages: [
|
||||
{ role: 'system', content: this.getSystemPrompt(actualStrategy) },
|
||||
{ role: 'user', content: prompt }
|
||||
]
|
||||
});
|
||||
|
||||
const rewritten = this.parseRewrittenQueries(result.text);
|
||||
|
||||
if (this.verbose) {
|
||||
console.log(`[QueryRewriter] Strategy: ${actualStrategy}, Rewrites: ${rewritten.length}`);
|
||||
}
|
||||
|
||||
return {
|
||||
original: query,
|
||||
rewritten,
|
||||
strategy: actualStrategy,
|
||||
confidence: rewritten.length > 0 ? 0.85 : 0.5
|
||||
};
|
||||
}
|
||||
|
||||
private detectStrategy(query: string): RewriteStrategy {
|
||||
const words = query.split(/\s+/).length;
|
||||
|
||||
if (words < 3) return 'expand';
|
||||
if (words > 20) return 'simplify';
|
||||
if (query.includes(' and ') || query.includes(' or ')) return 'decompose';
|
||||
return 'rephrase';
|
||||
}
|
||||
|
||||
private getSystemPrompt(strategy: RewriteStrategy): string {
|
||||
const prompts: Record<RewriteStrategy, string> = {
|
||||
expand: 'Expand this query with more context and detail. Generate 3 expanded versions.',
|
||||
simplify: 'Simplify this query to its core intent. Generate 3 simpler versions.',
|
||||
decompose: 'Break this query into smaller, focused sub-queries. Generate 3-5 sub-queries.',
|
||||
rephrase: 'Rephrase this query in different ways while keeping the same meaning. Generate 3 versions.',
|
||||
auto: 'Optimize this query for better search results. Generate 3 improved versions.'
|
||||
};
|
||||
return prompts[strategy] + ' Output one query per line.';
|
||||
}
|
||||
|
||||
private buildPrompt(query: string, strategy: RewriteStrategy): string {
|
||||
return `Query: ${query}\n\nRewrite using ${strategy} strategy:`;
|
||||
}
|
||||
|
||||
private parseRewrittenQueries(response: string): string[] {
|
||||
return response
|
||||
.split('\n')
|
||||
.map(line => line.replace(/^\d+[\.\)]\s*/, '').trim())
|
||||
.filter(line => line.length > 0 && line.length < 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a QueryRewriterAgent
|
||||
*/
|
||||
export function createQueryRewriterAgent(config?: QueryRewriterConfig): QueryRewriterAgent {
|
||||
return new QueryRewriterAgent(config);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* DeepResearchAgent - Agent for comprehensive research tasks
|
||||
*/
|
||||
|
||||
import { createProvider, type LLMProvider, type Message } from '../llm/providers';
|
||||
|
||||
export interface Citation {
|
||||
title: string;
|
||||
url: string;
|
||||
snippet?: string;
|
||||
}
|
||||
|
||||
export interface ReasoningStep {
|
||||
step: number;
|
||||
thought: string;
|
||||
action?: string;
|
||||
result?: string;
|
||||
}
|
||||
|
||||
export interface ResearchResponse {
|
||||
answer: string;
|
||||
citations: Citation[];
|
||||
reasoning: ReasoningStep[];
|
||||
confidence: number;
|
||||
}
|
||||
|
||||
export interface DeepResearchConfig {
|
||||
name?: string;
|
||||
llm?: string;
|
||||
maxIterations?: number;
|
||||
searchTool?: (query: string) => Promise<Citation[]>;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* DeepResearchAgent - Comprehensive research with citations
|
||||
*/
|
||||
export class DeepResearchAgent {
|
||||
readonly name: string;
|
||||
private provider: LLMProvider;
|
||||
private maxIterations: number;
|
||||
private searchTool?: (query: string) => Promise<Citation[]>;
|
||||
private verbose: boolean;
|
||||
|
||||
constructor(config: DeepResearchConfig = {}) {
|
||||
this.name = config.name || `ResearchAgent_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.provider = createProvider(config.llm || 'openai/gpt-4o-mini');
|
||||
this.maxIterations = config.maxIterations ?? 5;
|
||||
this.searchTool = config.searchTool;
|
||||
this.verbose = config.verbose ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Conduct deep research on a topic
|
||||
*/
|
||||
async research(query: string): Promise<ResearchResponse> {
|
||||
const reasoning: ReasoningStep[] = [];
|
||||
const citations: Citation[] = [];
|
||||
let iteration = 0;
|
||||
|
||||
// Step 1: Analyze the query
|
||||
reasoning.push({
|
||||
step: ++iteration,
|
||||
thought: `Analyzing research query: "${query}"`,
|
||||
action: 'query_analysis'
|
||||
});
|
||||
|
||||
// Step 2: Generate search queries
|
||||
const searchQueries = await this.generateSearchQueries(query);
|
||||
reasoning.push({
|
||||
step: ++iteration,
|
||||
thought: `Generated ${searchQueries.length} search queries`,
|
||||
action: 'generate_queries',
|
||||
result: searchQueries.join(', ')
|
||||
});
|
||||
|
||||
// Step 3: Execute searches if tool available
|
||||
if (this.searchTool) {
|
||||
for (const sq of searchQueries.slice(0, 3)) {
|
||||
try {
|
||||
const results = await this.searchTool(sq);
|
||||
citations.push(...results);
|
||||
reasoning.push({
|
||||
step: ++iteration,
|
||||
thought: `Searched for: "${sq}"`,
|
||||
action: 'web_search',
|
||||
result: `Found ${results.length} results`
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.verbose) {
|
||||
console.log(`[Research] Search failed for: ${sq}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 4: Synthesize answer
|
||||
const answer = await this.synthesizeAnswer(query, citations);
|
||||
reasoning.push({
|
||||
step: ++iteration,
|
||||
thought: 'Synthesizing final answer from gathered information',
|
||||
action: 'synthesize',
|
||||
result: 'Answer generated'
|
||||
});
|
||||
|
||||
// Calculate confidence based on citations
|
||||
const confidence = Math.min(0.5 + (citations.length * 0.1), 0.95);
|
||||
|
||||
return {
|
||||
answer,
|
||||
citations,
|
||||
reasoning,
|
||||
confidence
|
||||
};
|
||||
}
|
||||
|
||||
private async generateSearchQueries(query: string): Promise<string[]> {
|
||||
const result = await this.provider.generateText({
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: 'Generate 3 search queries to research this topic. Output only the queries, one per line.'
|
||||
},
|
||||
{ role: 'user', content: query }
|
||||
]
|
||||
});
|
||||
|
||||
return result.text.split('\n').filter(q => q.trim().length > 0).slice(0, 3);
|
||||
}
|
||||
|
||||
private async synthesizeAnswer(query: string, citations: Citation[]): Promise<string> {
|
||||
const context = citations.length > 0
|
||||
? `\n\nRelevant sources:\n${citations.map(c => `- ${c.title}: ${c.snippet || ''}`).join('\n')}`
|
||||
: '';
|
||||
|
||||
const result = await this.provider.generateText({
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: 'You are a research assistant. Provide a comprehensive, well-structured answer based on the available information. Cite sources when available.'
|
||||
},
|
||||
{ role: 'user', content: `${query}${context}` }
|
||||
]
|
||||
});
|
||||
|
||||
return result.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set search tool
|
||||
*/
|
||||
setSearchTool(tool: (query: string) => Promise<Citation[]>): void {
|
||||
this.searchTool = tool;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a DeepResearchAgent
|
||||
*/
|
||||
export function createDeepResearchAgent(config?: DeepResearchConfig): DeepResearchAgent {
|
||||
return new DeepResearchAgent(config);
|
||||
}
|
||||
@@ -31,7 +31,7 @@ export class Agent {
|
||||
this.name = config.name || `Agent_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.verbose = config.verbose ?? process.env.PRAISON_VERBOSE !== 'false';
|
||||
this.pretty = config.pretty ?? process.env.PRAISON_PRETTY === 'true';
|
||||
this.llm = config.llm || 'gpt-5-nano';
|
||||
this.llm = config.llm || 'gpt-4o-mini';
|
||||
this.markdown = config.markdown ?? true;
|
||||
this.stream = config.stream ?? true;
|
||||
this.tools = config.tools;
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* AutoAgents - Automatic agent generation from task descriptions
|
||||
*/
|
||||
|
||||
import { createProvider, type LLMProvider, type Message } from '../llm/providers';
|
||||
|
||||
export interface AgentConfig {
|
||||
name: string;
|
||||
role: string;
|
||||
goal: string;
|
||||
backstory?: string;
|
||||
instructions?: string;
|
||||
tools?: string[];
|
||||
}
|
||||
|
||||
export interface TaskConfig {
|
||||
description: string;
|
||||
expectedOutput?: string;
|
||||
agent?: string;
|
||||
}
|
||||
|
||||
export interface TeamStructure {
|
||||
agents: AgentConfig[];
|
||||
tasks: TaskConfig[];
|
||||
pattern: 'sequential' | 'parallel' | 'hierarchical';
|
||||
}
|
||||
|
||||
export interface AutoAgentsConfig {
|
||||
llm?: string;
|
||||
pattern?: 'sequential' | 'parallel' | 'routing' | 'orchestrator-workers' | 'evaluator-optimizer';
|
||||
singleAgent?: boolean;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* AutoAgents - Generate agent configurations from task descriptions
|
||||
*/
|
||||
export class AutoAgents {
|
||||
private provider: LLMProvider;
|
||||
private pattern: string;
|
||||
private singleAgent: boolean;
|
||||
private verbose: boolean;
|
||||
|
||||
constructor(config: AutoAgentsConfig = {}) {
|
||||
this.provider = createProvider(config.llm || 'openai/gpt-4o-mini');
|
||||
this.pattern = config.pattern || 'sequential';
|
||||
this.singleAgent = config.singleAgent ?? false;
|
||||
this.verbose = config.verbose ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate agent configuration from task description
|
||||
*/
|
||||
async generate(taskDescription: string): Promise<TeamStructure> {
|
||||
const prompt = this.buildPrompt(taskDescription);
|
||||
|
||||
const result = await this.provider.generateText({
|
||||
messages: [
|
||||
{ role: 'system', content: this.getSystemPrompt() },
|
||||
{ role: 'user', content: prompt }
|
||||
]
|
||||
});
|
||||
|
||||
return this.parseResponse(result.text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recommend a pattern for the task
|
||||
*/
|
||||
recommendPattern(taskDescription: string): string {
|
||||
const lower = taskDescription.toLowerCase();
|
||||
|
||||
if (lower.includes('parallel') || lower.includes('concurrent') || lower.includes('simultaneously')) {
|
||||
return 'parallel';
|
||||
}
|
||||
if (lower.includes('route') || lower.includes('classify') || lower.includes('categorize')) {
|
||||
return 'routing';
|
||||
}
|
||||
if (lower.includes('orchestrat') || lower.includes('coordinat') || lower.includes('manage')) {
|
||||
return 'orchestrator-workers';
|
||||
}
|
||||
if (lower.includes('evaluat') || lower.includes('optimi') || lower.includes('improv')) {
|
||||
return 'evaluator-optimizer';
|
||||
}
|
||||
|
||||
return 'sequential';
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze task complexity
|
||||
*/
|
||||
analyzeComplexity(taskDescription: string): 'simple' | 'moderate' | 'complex' {
|
||||
const words = taskDescription.split(/\s+/).length;
|
||||
const hasMultipleSteps = /step|then|after|before|first|second|third|finally/i.test(taskDescription);
|
||||
const hasMultipleAgents = /team|multiple|several|different|various/i.test(taskDescription);
|
||||
|
||||
if (words < 20 && !hasMultipleSteps && !hasMultipleAgents) {
|
||||
return 'simple';
|
||||
}
|
||||
if (words > 100 || (hasMultipleSteps && hasMultipleAgents)) {
|
||||
return 'complex';
|
||||
}
|
||||
return 'moderate';
|
||||
}
|
||||
|
||||
private getSystemPrompt(): string {
|
||||
return `You are an AI agent architect. Your job is to analyze task descriptions and generate optimal agent configurations.
|
||||
|
||||
Output a JSON object with the following structure:
|
||||
{
|
||||
"agents": [
|
||||
{
|
||||
"name": "AgentName",
|
||||
"role": "Role description",
|
||||
"goal": "Agent's goal",
|
||||
"backstory": "Optional backstory",
|
||||
"instructions": "Specific instructions",
|
||||
"tools": ["tool1", "tool2"]
|
||||
}
|
||||
],
|
||||
"tasks": [
|
||||
{
|
||||
"description": "Task description",
|
||||
"expectedOutput": "What the task should produce",
|
||||
"agent": "AgentName"
|
||||
}
|
||||
],
|
||||
"pattern": "sequential|parallel|hierarchical"
|
||||
}
|
||||
|
||||
Guidelines:
|
||||
- For simple tasks, use 1 agent
|
||||
- For moderate tasks, use 2-3 agents
|
||||
- For complex tasks, use 3-5 agents
|
||||
- Match the pattern to the task requirements
|
||||
- Be specific about roles and goals`;
|
||||
}
|
||||
|
||||
private buildPrompt(taskDescription: string): string {
|
||||
const complexity = this.analyzeComplexity(taskDescription);
|
||||
const recommendedPattern = this.recommendPattern(taskDescription);
|
||||
|
||||
return `Task Description: ${taskDescription}
|
||||
|
||||
Complexity: ${complexity}
|
||||
Recommended Pattern: ${this.pattern || recommendedPattern}
|
||||
Single Agent Mode: ${this.singleAgent}
|
||||
|
||||
Generate an optimal agent configuration for this task.`;
|
||||
}
|
||||
|
||||
private parseResponse(response: string): TeamStructure {
|
||||
try {
|
||||
// Extract JSON from response
|
||||
const jsonMatch = response.match(/\{[\s\S]*\}/);
|
||||
if (jsonMatch) {
|
||||
return JSON.parse(jsonMatch[0]);
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback to default structure
|
||||
}
|
||||
|
||||
// Default fallback
|
||||
return {
|
||||
agents: [{
|
||||
name: 'GeneralAgent',
|
||||
role: 'General purpose agent',
|
||||
goal: 'Complete the assigned task',
|
||||
instructions: 'Follow the task description carefully'
|
||||
}],
|
||||
tasks: [{
|
||||
description: 'Complete the task',
|
||||
agent: 'GeneralAgent'
|
||||
}],
|
||||
pattern: 'sequential'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an AutoAgents instance
|
||||
*/
|
||||
export function createAutoAgents(config?: AutoAgentsConfig): AutoAgents {
|
||||
return new AutoAgents(config);
|
||||
}
|
||||
Vendored
+253
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Cache System - In-memory and persistent caching for agents
|
||||
* Inspired by mastra's cache module
|
||||
*/
|
||||
|
||||
export interface CacheConfig {
|
||||
name?: string;
|
||||
ttl?: number; // Time to live in milliseconds
|
||||
maxSize?: number; // Maximum number of entries
|
||||
}
|
||||
|
||||
export interface CacheEntry<T = any> {
|
||||
value: T;
|
||||
createdAt: number;
|
||||
expiresAt?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract base class for cache implementations
|
||||
*/
|
||||
export abstract class BaseCache {
|
||||
readonly name: string;
|
||||
|
||||
constructor(config: CacheConfig = {}) {
|
||||
this.name = config.name || 'cache';
|
||||
}
|
||||
|
||||
abstract get<T = any>(key: string): Promise<T | undefined>;
|
||||
abstract set<T = any>(key: string, value: T, ttl?: number): Promise<void>;
|
||||
abstract delete(key: string): Promise<boolean>;
|
||||
abstract clear(): Promise<void>;
|
||||
abstract has(key: string): Promise<boolean>;
|
||||
abstract keys(): Promise<string[]>;
|
||||
abstract size(): Promise<number>;
|
||||
|
||||
// List operations
|
||||
abstract listPush<T = any>(key: string, value: T): Promise<void>;
|
||||
abstract listLength(key: string): Promise<number>;
|
||||
abstract listRange<T = any>(key: string, start: number, end?: number): Promise<T[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory cache implementation
|
||||
*/
|
||||
export class MemoryCache extends BaseCache {
|
||||
private cache: Map<string, CacheEntry> = new Map();
|
||||
private lists: Map<string, any[]> = new Map();
|
||||
private ttl?: number;
|
||||
private maxSize?: number;
|
||||
|
||||
constructor(config: CacheConfig = {}) {
|
||||
super(config);
|
||||
this.ttl = config.ttl;
|
||||
this.maxSize = config.maxSize;
|
||||
}
|
||||
|
||||
async get<T = any>(key: string): Promise<T | undefined> {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) return undefined;
|
||||
|
||||
// Check expiration
|
||||
if (entry.expiresAt && Date.now() > entry.expiresAt) {
|
||||
this.cache.delete(key);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return entry.value as T;
|
||||
}
|
||||
|
||||
async set<T = any>(key: string, value: T, ttl?: number): Promise<void> {
|
||||
// Enforce max size
|
||||
if (this.maxSize && this.cache.size >= this.maxSize && !this.cache.has(key)) {
|
||||
// Remove oldest entry
|
||||
const firstKey = this.cache.keys().next().value;
|
||||
if (firstKey) this.cache.delete(firstKey);
|
||||
}
|
||||
|
||||
const effectiveTtl = ttl ?? this.ttl;
|
||||
const entry: CacheEntry<T> = {
|
||||
value,
|
||||
createdAt: Date.now(),
|
||||
expiresAt: effectiveTtl ? Date.now() + effectiveTtl : undefined
|
||||
};
|
||||
|
||||
this.cache.set(key, entry);
|
||||
}
|
||||
|
||||
async delete(key: string): Promise<boolean> {
|
||||
const existed = this.cache.has(key);
|
||||
this.cache.delete(key);
|
||||
this.lists.delete(key);
|
||||
return existed;
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.cache.clear();
|
||||
this.lists.clear();
|
||||
}
|
||||
|
||||
async has(key: string): Promise<boolean> {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) return false;
|
||||
if (entry.expiresAt && Date.now() > entry.expiresAt) {
|
||||
this.cache.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
return Array.from(this.cache.keys());
|
||||
}
|
||||
|
||||
async size(): Promise<number> {
|
||||
return this.cache.size;
|
||||
}
|
||||
|
||||
async listPush<T = any>(key: string, value: T): Promise<void> {
|
||||
if (!this.lists.has(key)) {
|
||||
this.lists.set(key, []);
|
||||
}
|
||||
this.lists.get(key)!.push(value);
|
||||
}
|
||||
|
||||
async listLength(key: string): Promise<number> {
|
||||
return this.lists.get(key)?.length ?? 0;
|
||||
}
|
||||
|
||||
async listRange<T = any>(key: string, start: number, end?: number): Promise<T[]> {
|
||||
const list = this.lists.get(key) ?? [];
|
||||
return list.slice(start, end) as T[];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* File-based cache implementation
|
||||
*/
|
||||
export class FileCache extends BaseCache {
|
||||
private cacheDir: string;
|
||||
private fs: any;
|
||||
private path: any;
|
||||
|
||||
constructor(config: CacheConfig & { cacheDir?: string } = {}) {
|
||||
super(config);
|
||||
this.cacheDir = config.cacheDir || '.cache';
|
||||
}
|
||||
|
||||
private async ensureDir(): Promise<void> {
|
||||
if (!this.fs) {
|
||||
this.fs = await import('fs/promises');
|
||||
this.path = await import('path');
|
||||
}
|
||||
try {
|
||||
await this.fs.mkdir(this.cacheDir, { recursive: true });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
private getFilePath(key: string): string {
|
||||
const safeKey = key.replace(/[^a-zA-Z0-9-_]/g, '_');
|
||||
return this.path.join(this.cacheDir, `${safeKey}.json`);
|
||||
}
|
||||
|
||||
async get<T = any>(key: string): Promise<T | undefined> {
|
||||
await this.ensureDir();
|
||||
try {
|
||||
const data = await this.fs.readFile(this.getFilePath(key), 'utf-8');
|
||||
const entry: CacheEntry<T> = JSON.parse(data);
|
||||
if (entry.expiresAt && Date.now() > entry.expiresAt) {
|
||||
await this.delete(key);
|
||||
return undefined;
|
||||
}
|
||||
return entry.value;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async set<T = any>(key: string, value: T, ttl?: number): Promise<void> {
|
||||
await this.ensureDir();
|
||||
const entry: CacheEntry<T> = {
|
||||
value,
|
||||
createdAt: Date.now(),
|
||||
expiresAt: ttl ? Date.now() + ttl : undefined
|
||||
};
|
||||
await this.fs.writeFile(this.getFilePath(key), JSON.stringify(entry));
|
||||
}
|
||||
|
||||
async delete(key: string): Promise<boolean> {
|
||||
await this.ensureDir();
|
||||
try {
|
||||
await this.fs.unlink(this.getFilePath(key));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
await this.ensureDir();
|
||||
try {
|
||||
const files = await this.fs.readdir(this.cacheDir);
|
||||
await Promise.all(
|
||||
files.filter((f: string) => f.endsWith('.json'))
|
||||
.map((f: string) => this.fs.unlink(this.path.join(this.cacheDir, f)))
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async has(key: string): Promise<boolean> {
|
||||
return (await this.get(key)) !== undefined;
|
||||
}
|
||||
|
||||
async keys(): Promise<string[]> {
|
||||
await this.ensureDir();
|
||||
try {
|
||||
const files = await this.fs.readdir(this.cacheDir);
|
||||
return files
|
||||
.filter((f: string) => f.endsWith('.json'))
|
||||
.map((f: string) => f.replace('.json', ''));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async size(): Promise<number> {
|
||||
return (await this.keys()).length;
|
||||
}
|
||||
|
||||
async listPush<T = any>(key: string, value: T): Promise<void> {
|
||||
const list = (await this.get<T[]>(`list_${key}`)) || [];
|
||||
list.push(value);
|
||||
await this.set(`list_${key}`, list);
|
||||
}
|
||||
|
||||
async listLength(key: string): Promise<number> {
|
||||
const list = (await this.get<any[]>(`list_${key}`)) || [];
|
||||
return list.length;
|
||||
}
|
||||
|
||||
async listRange<T = any>(key: string, start: number, end?: number): Promise<T[]> {
|
||||
const list = (await this.get<T[]>(`list_${key}`)) || [];
|
||||
return list.slice(start, end);
|
||||
}
|
||||
}
|
||||
|
||||
// Factory functions
|
||||
export function createMemoryCache(config?: CacheConfig): MemoryCache {
|
||||
return new MemoryCache(config);
|
||||
}
|
||||
|
||||
export function createFileCache(config?: CacheConfig & { cacheDir?: string }): FileCache {
|
||||
return new FileCache(config);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Auto command - AutoAgents for automatic agent generation
|
||||
*/
|
||||
|
||||
import { AutoAgents, createAutoAgents } from '../../auto';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface AutoOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
pattern?: string;
|
||||
agents?: number;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: AutoOptions): Promise<void> {
|
||||
const topic = args.join(' ');
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
const config = resolveConfig(options);
|
||||
|
||||
if (!topic) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a topic for auto-generation'));
|
||||
} else {
|
||||
await pretty.error('Please provide a topic for auto-generation');
|
||||
await pretty.dim('Usage: praisonai-ts auto "Create a research team"');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Generating agents for: "${topic}"`);
|
||||
}
|
||||
|
||||
const autoAgents = createAutoAgents({
|
||||
llm: config.model,
|
||||
pattern: options.pattern as any,
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const result = await autoAgents.generate(topic);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
topic,
|
||||
agents: result.agents,
|
||||
tasks: result.tasks,
|
||||
pattern: result.pattern
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Generated Team');
|
||||
await pretty.plain(`Pattern: ${result.pattern}`);
|
||||
await pretty.newline();
|
||||
|
||||
await pretty.plain('Agents:');
|
||||
for (const agent of result.agents) {
|
||||
await pretty.plain(` • ${agent.name}: ${agent.role}`);
|
||||
}
|
||||
|
||||
await pretty.newline();
|
||||
await pretty.plain('Tasks:');
|
||||
for (const task of result.tasks) {
|
||||
await pretty.plain(` • ${task.description?.substring(0, 60)}...`);
|
||||
}
|
||||
|
||||
await pretty.newline();
|
||||
await pretty.success(`Generated in ${duration}ms`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* CLI command: autonomy
|
||||
* Autonomy mode management for agent actions
|
||||
*/
|
||||
|
||||
import { AutonomyManager, createAutonomyManager, MODE_POLICIES, type AutonomyMode } from '../features/autonomy-mode';
|
||||
|
||||
let manager: AutonomyManager | null = null;
|
||||
|
||||
function getManager(): AutonomyManager {
|
||||
if (!manager) {
|
||||
manager = createAutonomyManager();
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'status':
|
||||
await handleStatus(isJson);
|
||||
break;
|
||||
case 'set':
|
||||
await handleSet(args.slice(1), isJson);
|
||||
break;
|
||||
case 'policies':
|
||||
await handlePolicies(args.slice(1), isJson);
|
||||
break;
|
||||
case 'reset':
|
||||
await handleReset(isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStatus(isJson: boolean): Promise<void> {
|
||||
const mgr = getManager();
|
||||
const summary = mgr.getSummary();
|
||||
const mode = mgr.getMode();
|
||||
const actionCount = mgr.getActionCount();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({
|
||||
success: true,
|
||||
mode,
|
||||
actionCount,
|
||||
policies: MODE_POLICIES[mode]
|
||||
}, null, 2));
|
||||
} else {
|
||||
console.log(summary);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSet(args: string[], isJson: boolean): Promise<void> {
|
||||
const mode = args[0] as AutonomyMode;
|
||||
|
||||
if (!mode || !['suggest', 'auto_edit', 'full_auto'].includes(mode)) {
|
||||
console.error('Error: Valid mode required (suggest, auto_edit, full_auto)');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mgr = getManager();
|
||||
mgr.setMode(mode);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, mode }));
|
||||
} else {
|
||||
console.log(`✓ Autonomy mode set to: ${mode}`);
|
||||
console.log('\nPolicies for this mode:');
|
||||
for (const policy of MODE_POLICIES[mode]) {
|
||||
const status = policy.requiresApproval ? '⚠️ requires approval' : '✓ auto-approved';
|
||||
console.log(` ${policy.action}: ${status}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePolicies(args: string[], isJson: boolean): Promise<void> {
|
||||
const mode = (args[0] as AutonomyMode) || 'suggest';
|
||||
|
||||
if (!['suggest', 'auto_edit', 'full_auto'].includes(mode)) {
|
||||
console.error('Error: Valid mode required (suggest, auto_edit, full_auto)');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const policies = MODE_POLICIES[mode];
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, mode, policies }, null, 2));
|
||||
} else {
|
||||
console.log(`Policies for mode: ${mode}\n`);
|
||||
for (const policy of policies) {
|
||||
const status = policy.requiresApproval ? '⚠️ requires approval' : '✓ auto-approved';
|
||||
console.log(` ${policy.action.padEnd(20)} ${status}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReset(isJson: boolean): Promise<void> {
|
||||
const mgr = getManager();
|
||||
mgr.clearRemembered();
|
||||
mgr.resetActionCount();
|
||||
mgr.setMode('suggest');
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, message: 'Autonomy state reset' }));
|
||||
} else {
|
||||
console.log('✓ Autonomy state reset');
|
||||
console.log(' Mode: suggest');
|
||||
console.log(' Remembered decisions: cleared');
|
||||
console.log(' Action count: 0');
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'autonomy',
|
||||
description: 'Autonomy mode management for agent actions',
|
||||
subcommands: {
|
||||
status: 'Show current autonomy status',
|
||||
set: 'Set autonomy mode',
|
||||
policies: 'Show policies for a mode',
|
||||
reset: 'Reset autonomy state'
|
||||
},
|
||||
modes: {
|
||||
suggest: 'Requires approval for most actions (default)',
|
||||
auto_edit: 'Auto-approves file edits, requires approval for others',
|
||||
full_auto: 'Auto-approves most actions (use with caution)'
|
||||
},
|
||||
flags: {
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts autonomy status',
|
||||
'praisonai-ts autonomy set suggest',
|
||||
'praisonai-ts autonomy set auto_edit',
|
||||
'praisonai-ts autonomy set full_auto',
|
||||
'praisonai-ts autonomy policies suggest',
|
||||
'praisonai-ts autonomy reset'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Autonomy - Agent action approval management\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nModes:');
|
||||
for (const [mode, desc] of Object.entries(help.modes)) {
|
||||
console.log(` ${mode.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Cache command - Caching management
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface CacheOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: CacheOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'providers':
|
||||
await listProviders(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Cache',
|
||||
description: 'Caching system for LLM responses and computations',
|
||||
providers: [
|
||||
{ name: 'MemoryCache', description: 'In-memory cache (default)' },
|
||||
{ name: 'FileCache', description: 'File-based persistent cache' }
|
||||
],
|
||||
capabilities: [
|
||||
'Cache LLM responses',
|
||||
'Reduce API costs',
|
||||
'Improve response times',
|
||||
'TTL-based expiration',
|
||||
'Configurable cache keys'
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Cache');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Providers:');
|
||||
for (const p of info.providers) {
|
||||
await pretty.plain(` • ${p.name}: ${p.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Capabilities:');
|
||||
for (const cap of info.capabilities) {
|
||||
await pretty.plain(` • ${cap}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listProviders(outputFormat: string): Promise<void> {
|
||||
const providers = [
|
||||
{ name: 'memory', description: 'In-memory cache', available: true },
|
||||
{ name: 'file', description: 'File-based cache', available: true }
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ providers }));
|
||||
} else {
|
||||
await pretty.heading('Cache Providers');
|
||||
for (const p of providers) {
|
||||
const status = p.available ? '✓' : '✗';
|
||||
await pretty.plain(` ${status} ${p.name.padEnd(15)} ${p.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'cache',
|
||||
description: 'Caching management for LLM responses',
|
||||
subcommands: [
|
||||
{ name: 'info', description: 'Show cache feature information' },
|
||||
{ name: 'providers', description: 'List available cache providers' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Cache Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Chat command - Chat with an AI agent
|
||||
*/
|
||||
|
||||
import { createProvider } from '../../llm/providers';
|
||||
import { Session } from '../../session';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { printSuccess, printError, outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES, normalizeError } from '../output/errors';
|
||||
|
||||
export interface ChatOptions {
|
||||
model?: string;
|
||||
stream?: boolean;
|
||||
session?: string;
|
||||
verbose?: boolean;
|
||||
profile?: string;
|
||||
config?: string;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: ChatOptions): Promise<void> {
|
||||
const prompt = args[0];
|
||||
|
||||
if (!prompt) {
|
||||
if (options.json || options.output === 'json') {
|
||||
printError(ERROR_CODES.MISSING_ARG, 'Please provide a prompt');
|
||||
} else {
|
||||
await pretty.error('Please provide a prompt');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
// Resolve config with precedence
|
||||
const config = resolveConfig({
|
||||
configPath: options.config,
|
||||
profile: options.profile,
|
||||
model: options.model,
|
||||
verbose: options.verbose,
|
||||
stream: options.stream
|
||||
});
|
||||
|
||||
const startTime = Date.now();
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
const provider = createProvider(config.model);
|
||||
const session = new Session({ id: options.session });
|
||||
session.addMessage({ role: 'user', content: prompt });
|
||||
|
||||
let responseText = '';
|
||||
let inputTokens = 0;
|
||||
let outputTokens = 0;
|
||||
|
||||
if (config.stream && outputFormat !== 'json') {
|
||||
// Streaming mode (only for non-JSON output)
|
||||
const stream = await provider.streamText({
|
||||
messages: [{ role: 'user', content: prompt }],
|
||||
onToken: (token: string) => {
|
||||
process.stdout.write(token);
|
||||
responseText += token;
|
||||
}
|
||||
});
|
||||
|
||||
for await (const chunk of stream) {
|
||||
// Stream is consumed by onToken
|
||||
}
|
||||
console.log(); // New line after streaming
|
||||
} else {
|
||||
// Non-streaming mode
|
||||
const result = await provider.generateText({
|
||||
messages: [{ role: 'user', content: prompt }]
|
||||
});
|
||||
responseText = result.text;
|
||||
inputTokens = result.usage?.promptTokens || 0;
|
||||
outputTokens = result.usage?.completionTokens || 0;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
const duration = Date.now() - startTime;
|
||||
outputJson(formatSuccess(
|
||||
{ response: responseText },
|
||||
{
|
||||
duration_ms: duration,
|
||||
model: config.model,
|
||||
tokens: {
|
||||
input: inputTokens,
|
||||
output: outputTokens
|
||||
}
|
||||
}
|
||||
));
|
||||
} else {
|
||||
console.log(responseText);
|
||||
}
|
||||
}
|
||||
|
||||
session.addMessage({ role: 'assistant', content: responseText });
|
||||
|
||||
} catch (error) {
|
||||
const cliError = normalizeError(error);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(cliError.code, cliError.message, cliError.details));
|
||||
} else {
|
||||
await pretty.error(cliError.message);
|
||||
if (config.verbose && error instanceof Error && error.stack) {
|
||||
await pretty.dim(error.stack);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(cliError.exitCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* CLI command: checkpoints
|
||||
* Session state checkpointing and recovery
|
||||
*/
|
||||
|
||||
import { CheckpointManager, createCheckpointManager, createFileCheckpointStorage } from '../features/checkpoints';
|
||||
|
||||
let manager: CheckpointManager | null = null;
|
||||
|
||||
function getManager(storagePath?: string): CheckpointManager {
|
||||
if (!manager) {
|
||||
const storage = storagePath ? createFileCheckpointStorage(storagePath) : undefined;
|
||||
manager = createCheckpointManager({ storage });
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
const storagePath = options.storage as string | undefined;
|
||||
|
||||
switch (subcommand) {
|
||||
case 'create':
|
||||
await handleCreate(args.slice(1), options, isJson, storagePath);
|
||||
break;
|
||||
case 'list':
|
||||
await handleList(isJson, storagePath);
|
||||
break;
|
||||
case 'get':
|
||||
await handleGet(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'restore':
|
||||
await handleRestore(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'delete':
|
||||
await handleDelete(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'export':
|
||||
await handleExport(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'import':
|
||||
await handleImport(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreate(args: string[], options: Record<string, unknown>, isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const name = args[0] || `checkpoint-${Date.now()}`;
|
||||
const mgr = getManager(storagePath);
|
||||
|
||||
// Set state from options if provided
|
||||
const state = options.state ? JSON.parse(options.state as string) : {};
|
||||
mgr.setState(state);
|
||||
|
||||
const checkpoint = await mgr.create(name, {
|
||||
sessionId: options.session as string,
|
||||
metadata: options.metadata ? JSON.parse(options.metadata as string) : undefined
|
||||
});
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, checkpoint }, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Checkpoint created: ${checkpoint.id}`);
|
||||
console.log(` Name: ${checkpoint.name}`);
|
||||
console.log(` Time: ${checkpoint.timestamp.toISOString()}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const mgr = getManager(storagePath);
|
||||
const checkpoints = await mgr.list();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, checkpoints }, null, 2));
|
||||
} else {
|
||||
if (checkpoints.length === 0) {
|
||||
console.log('No checkpoints found');
|
||||
} else {
|
||||
console.log('Checkpoints:');
|
||||
for (const cp of checkpoints) {
|
||||
console.log(` ${cp.name} (${cp.id})`);
|
||||
console.log(` Created: ${cp.timestamp.toISOString()}`);
|
||||
if (cp.sessionId) console.log(` Session: ${cp.sessionId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGet(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Checkpoint ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mgr = getManager(storagePath);
|
||||
const checkpoint = await mgr.get(id);
|
||||
|
||||
if (!checkpoint) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: 'Checkpoint not found' }));
|
||||
} else {
|
||||
console.error(`Checkpoint ${id} not found`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, checkpoint }, null, 2));
|
||||
} else {
|
||||
console.log(`Checkpoint: ${checkpoint.id}`);
|
||||
console.log(` Name: ${checkpoint.name}`);
|
||||
console.log(` Created: ${checkpoint.timestamp.toISOString()}`);
|
||||
console.log(` State: ${JSON.stringify(checkpoint.state, null, 2)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRestore(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
const mgr = getManager(storagePath);
|
||||
|
||||
let checkpoint;
|
||||
if (id) {
|
||||
checkpoint = await mgr.restore(id);
|
||||
} else {
|
||||
checkpoint = await mgr.restoreLatest();
|
||||
}
|
||||
|
||||
if (!checkpoint) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: 'No checkpoint to restore' }));
|
||||
} else {
|
||||
console.error('No checkpoint to restore');
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, restored: checkpoint }, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Restored checkpoint: ${checkpoint.id}`);
|
||||
console.log(` Name: ${checkpoint.name}`);
|
||||
console.log(` State keys: ${Object.keys(checkpoint.state).join(', ') || 'none'}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Checkpoint ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mgr = getManager(storagePath);
|
||||
await mgr.delete(id);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, deleted: id }));
|
||||
} else {
|
||||
console.log(`✓ Checkpoint ${id} deleted`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExport(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Checkpoint ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mgr = getManager(storagePath);
|
||||
const exported = await mgr.export(id);
|
||||
|
||||
if (!exported) {
|
||||
console.error(`Checkpoint ${id} not found`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(exported);
|
||||
}
|
||||
|
||||
async function handleImport(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const jsonData = args[0];
|
||||
if (!jsonData) {
|
||||
console.error('Error: JSON data is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mgr = getManager(storagePath);
|
||||
const checkpoint = await mgr.import(jsonData);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, imported: checkpoint }, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Checkpoint imported: ${checkpoint.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'checkpoints',
|
||||
description: 'Session state checkpointing and recovery',
|
||||
subcommands: {
|
||||
create: 'Create a new checkpoint',
|
||||
list: 'List all checkpoints',
|
||||
get: 'Get checkpoint details',
|
||||
restore: 'Restore from a checkpoint',
|
||||
delete: 'Delete a checkpoint',
|
||||
export: 'Export checkpoint as JSON',
|
||||
import: 'Import checkpoint from JSON'
|
||||
},
|
||||
flags: {
|
||||
'--storage': 'Path to checkpoint storage directory',
|
||||
'--state': 'JSON state to save with checkpoint',
|
||||
'--session': 'Session ID to associate',
|
||||
'--metadata': 'JSON metadata',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts checkpoints create my-checkpoint',
|
||||
'praisonai-ts checkpoints create --state \'{"key": "value"}\'',
|
||||
'praisonai-ts checkpoints list',
|
||||
'praisonai-ts checkpoints restore <id>',
|
||||
'praisonai-ts checkpoints restore # restores latest',
|
||||
'praisonai-ts checkpoints export <id> > checkpoint.json',
|
||||
'praisonai-ts checkpoints import \'{"name": "imported"}\'',
|
||||
'praisonai-ts checkpoints delete <id>'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Checkpoints - Session state checkpointing\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* Context command - Manage conversation context
|
||||
*/
|
||||
|
||||
import { createContextAgent } from '../../agent/context';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface ContextOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
maxMessages?: number;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: ContextOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
const config = resolveConfig(options);
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'chat':
|
||||
await chatWithContext(actionArgs, options, config, outputFormat);
|
||||
break;
|
||||
case 'summarize':
|
||||
await summarizeContext(actionArgs, options, config, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function chatWithContext(args: string[], options: ContextOptions, config: any, outputFormat: string): Promise<void> {
|
||||
const message = args.join(' ');
|
||||
if (!message) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a message'));
|
||||
} else {
|
||||
await pretty.error('Please provide a message');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info('Processing with context...');
|
||||
}
|
||||
|
||||
const agent = createContextAgent({
|
||||
llm: config.model,
|
||||
instructions: 'You are a helpful assistant with context awareness.',
|
||||
contextWindow: options.maxMessages || 10,
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const result = await agent.chat(message);
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
message,
|
||||
response: result.text
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Response');
|
||||
await pretty.plain(result.text);
|
||||
await pretty.newline();
|
||||
await pretty.success(`Completed in ${duration}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
async function summarizeContext(args: string[], options: ContextOptions, config: any, outputFormat: string): Promise<void> {
|
||||
const context = args.join(' ');
|
||||
if (!context) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide context to summarize'));
|
||||
} else {
|
||||
await pretty.error('Please provide context to summarize');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info('Summarizing context...');
|
||||
}
|
||||
|
||||
const agent = createContextAgent({
|
||||
llm: config.model,
|
||||
instructions: 'You are a summarization assistant. Provide concise summaries.',
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
// Use chat to summarize
|
||||
const result = await agent.chat(`Please summarize the following text concisely:\n\n${context}`);
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
originalLength: context.length,
|
||||
summary: result.text
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Summary');
|
||||
await pretty.plain(result.text);
|
||||
await pretty.newline();
|
||||
await pretty.dim(`Original: ${context.length} chars`);
|
||||
await pretty.success(`Summarized in ${duration}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'context',
|
||||
subcommands: [
|
||||
{ name: 'chat <message>', description: 'Chat with context management' },
|
||||
{ name: 'summarize <text>', description: 'Summarize context' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
flags: [
|
||||
{ name: '--max-messages', description: 'Maximum messages to keep in context' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Context Command');
|
||||
await pretty.plain('Manage conversation context\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(25)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Flags:');
|
||||
for (const flag of help.flags) {
|
||||
await pretty.plain(` ${flag.name.padEnd(20)} ${flag.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* CLI command: cost
|
||||
* Token usage and cost tracking
|
||||
*/
|
||||
|
||||
import { CostTracker, createCostTracker, MODEL_PRICING, formatCost } from '../features/cost-tracker';
|
||||
|
||||
let tracker: CostTracker | null = null;
|
||||
|
||||
function getTracker(): CostTracker {
|
||||
if (!tracker) {
|
||||
tracker = createCostTracker();
|
||||
}
|
||||
return tracker;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'summary':
|
||||
await handleSummary(isJson);
|
||||
break;
|
||||
case 'add':
|
||||
await handleAdd(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'reset':
|
||||
await handleReset(isJson);
|
||||
break;
|
||||
case 'pricing':
|
||||
await handlePricing(args.slice(1), isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSummary(isJson: boolean): Promise<void> {
|
||||
const t = getTracker();
|
||||
const stats = t.getStats();
|
||||
const breakdown = t.getBreakdownByModel();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, stats, breakdown }, null, 2));
|
||||
} else {
|
||||
console.log(t.getSummary());
|
||||
|
||||
if (Object.keys(breakdown).length > 0) {
|
||||
console.log('\nBreakdown by model:');
|
||||
for (const [model, data] of Object.entries(breakdown)) {
|
||||
console.log(` ${model}: ${data.tokens} tokens, ${formatCost(data.cost)}, ${data.requests} requests`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAdd(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const model = args[0] || 'gpt-4o-mini';
|
||||
const inputTokens = parseInt(args[1] || '0');
|
||||
const outputTokens = parseInt(args[2] || '0');
|
||||
|
||||
if (isNaN(inputTokens) || isNaN(outputTokens)) {
|
||||
console.error('Error: Invalid token counts');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const t = getTracker();
|
||||
const request = t.addUsage(model, inputTokens, outputTokens);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, request }, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Added usage: ${model}`);
|
||||
console.log(` Input: ${inputTokens} tokens`);
|
||||
console.log(` Output: ${outputTokens} tokens`);
|
||||
console.log(` Cost: ${formatCost(request.cost)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleReset(isJson: boolean): Promise<void> {
|
||||
const t = getTracker();
|
||||
t.reset();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, message: 'Cost tracker reset' }));
|
||||
} else {
|
||||
console.log('✓ Cost tracker reset');
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePricing(args: string[], isJson: boolean): Promise<void> {
|
||||
const model = args[0];
|
||||
|
||||
if (model) {
|
||||
const pricing = MODEL_PRICING[model] || MODEL_PRICING['default'];
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, model, pricing }, null, 2));
|
||||
} else {
|
||||
console.log(`Pricing for ${model}:`);
|
||||
console.log(` Input: $${pricing.inputCostPer1k}/1K tokens`);
|
||||
console.log(` Output: $${pricing.outputCostPer1k}/1K tokens`);
|
||||
}
|
||||
} else {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, pricing: MODEL_PRICING }, null, 2));
|
||||
} else {
|
||||
console.log('Model Pricing (per 1K tokens):\n');
|
||||
for (const [name, pricing] of Object.entries(MODEL_PRICING)) {
|
||||
if (name === 'default') continue;
|
||||
console.log(` ${name.padEnd(30)} in: $${pricing.inputCostPer1k.toFixed(5)} out: $${pricing.outputCostPer1k.toFixed(5)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'cost',
|
||||
description: 'Token usage and cost tracking',
|
||||
subcommands: {
|
||||
summary: 'Show cost summary',
|
||||
add: 'Add token usage',
|
||||
reset: 'Reset cost tracker',
|
||||
pricing: 'Show model pricing'
|
||||
},
|
||||
flags: {
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts cost summary',
|
||||
'praisonai-ts cost add gpt-4o 1000 500',
|
||||
'praisonai-ts cost pricing',
|
||||
'praisonai-ts cost pricing gpt-4o',
|
||||
'praisonai-ts cost reset'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Cost - Token usage and cost tracking\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* DB command - Database adapter management
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface DbOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: DbOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'adapters':
|
||||
await listAdapters(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Database Adapters',
|
||||
description: 'Database adapters for persistence and session storage',
|
||||
adapters: [
|
||||
{ name: 'SQLiteAdapter', description: 'SQLite database adapter' },
|
||||
{ name: 'UpstashRedisAdapter', description: 'Upstash Redis adapter' },
|
||||
{ name: 'MemoryRedisAdapter', description: 'In-memory Redis-compatible adapter' },
|
||||
{ name: 'NeonPostgresAdapter', description: 'Neon PostgreSQL adapter' },
|
||||
{ name: 'MemoryPostgresAdapter', description: 'In-memory PostgreSQL-compatible adapter' },
|
||||
{ name: 'PostgresSessionStorage', description: 'PostgreSQL session storage' }
|
||||
],
|
||||
capabilities: [
|
||||
'Store conversation history',
|
||||
'Persist agent state',
|
||||
'Session management',
|
||||
'Message storage and retrieval',
|
||||
'Trace logging'
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Database Adapters');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Available Adapters:');
|
||||
for (const a of info.adapters) {
|
||||
await pretty.plain(` • ${a.name}: ${a.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Capabilities:');
|
||||
for (const cap of info.capabilities) {
|
||||
await pretty.plain(` • ${cap}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listAdapters(outputFormat: string): Promise<void> {
|
||||
const adapters = [
|
||||
{ name: 'sqlite', description: 'SQLite database', available: true },
|
||||
{ name: 'redis', description: 'Redis (Upstash)', available: true },
|
||||
{ name: 'postgres', description: 'PostgreSQL (Neon)', available: true },
|
||||
{ name: 'memory', description: 'In-memory adapters', available: true }
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ adapters }));
|
||||
} else {
|
||||
await pretty.heading('Database Adapters');
|
||||
for (const a of adapters) {
|
||||
const status = a.available ? '✓' : '✗';
|
||||
await pretty.plain(` ${status} ${a.name.padEnd(15)} ${a.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'db',
|
||||
description: 'Database adapter management',
|
||||
subcommands: [
|
||||
{ name: 'info', description: 'Show database adapter information' },
|
||||
{ name: 'adapters', description: 'List available database adapters' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Database Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
/**
|
||||
* Eval command - Evaluate agent performance
|
||||
*/
|
||||
|
||||
import { Agent } from '../../agent';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { printSuccess, printError, outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES, normalizeError } from '../output/errors';
|
||||
|
||||
export interface EvalOptions {
|
||||
// Accuracy subcommand
|
||||
input?: string;
|
||||
expected?: string;
|
||||
iterations?: number;
|
||||
// Performance subcommand
|
||||
warmup?: number;
|
||||
// Reliability subcommand
|
||||
'expected-tools'?: string;
|
||||
// Common
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
profile?: string;
|
||||
config?: string;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
interface AccuracyResult {
|
||||
iteration: number;
|
||||
output: string;
|
||||
score: number;
|
||||
passed: boolean;
|
||||
}
|
||||
|
||||
interface PerformanceResult {
|
||||
iteration: number;
|
||||
duration_ms: number;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: EvalOptions): Promise<void> {
|
||||
const subcommand = args[0];
|
||||
|
||||
if (!subcommand || !['accuracy', 'performance', 'reliability'].includes(subcommand)) {
|
||||
if (options.json || options.output === 'json') {
|
||||
printError(ERROR_CODES.INVALID_ARGS, 'Please specify a subcommand: accuracy, performance, or reliability');
|
||||
} else {
|
||||
await pretty.error('Please specify a subcommand: accuracy, performance, or reliability');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const config = resolveConfig({
|
||||
configPath: options.config,
|
||||
profile: options.profile,
|
||||
model: options.model,
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (subcommand) {
|
||||
case 'accuracy':
|
||||
await runAccuracyEval(options, config, outputFormat);
|
||||
break;
|
||||
case 'performance':
|
||||
await runPerformanceEval(options, config, outputFormat);
|
||||
break;
|
||||
case 'reliability':
|
||||
await runReliabilityEval(options, config, outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
const cliError = normalizeError(error);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(cliError.code, cliError.message, cliError.details));
|
||||
} else {
|
||||
await pretty.error(cliError.message);
|
||||
if (config.verbose && error instanceof Error && error.stack) {
|
||||
await pretty.dim(error.stack);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(cliError.exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
async function runAccuracyEval(
|
||||
options: EvalOptions,
|
||||
config: { model: string; verbose: boolean },
|
||||
outputFormat: string
|
||||
): Promise<void> {
|
||||
if (!options.input) {
|
||||
throw new Error('--input is required for accuracy evaluation');
|
||||
}
|
||||
if (!options.expected) {
|
||||
throw new Error('--expected is required for accuracy evaluation');
|
||||
}
|
||||
|
||||
const iterations = options.iterations || 1;
|
||||
const results: AccuracyResult[] = [];
|
||||
const startTime = Date.now();
|
||||
|
||||
const agent = new Agent({
|
||||
name: 'Eval Agent',
|
||||
instructions: 'You are a helpful AI assistant.',
|
||||
llm: config.model,
|
||||
verbose: config.verbose
|
||||
});
|
||||
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const output = await agent.start(options.input);
|
||||
|
||||
// Simple similarity check (in production, use LLM-as-judge)
|
||||
const similarity = calculateSimilarity(output, options.expected);
|
||||
const score = Math.round(similarity * 10);
|
||||
|
||||
results.push({
|
||||
iteration: i + 1,
|
||||
output,
|
||||
score,
|
||||
passed: score >= 7
|
||||
});
|
||||
}
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
const avgScore = results.reduce((sum, r) => sum + r.score, 0) / results.length;
|
||||
const passRate = results.filter(r => r.passed).length / results.length;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(
|
||||
{
|
||||
type: 'accuracy',
|
||||
results,
|
||||
summary: {
|
||||
avg_score: avgScore,
|
||||
pass_rate: passRate,
|
||||
iterations
|
||||
}
|
||||
},
|
||||
{ duration_ms: duration, model: config.model }
|
||||
));
|
||||
} else {
|
||||
await pretty.heading('Accuracy Evaluation Results');
|
||||
await pretty.keyValue({
|
||||
'Iterations': iterations,
|
||||
'Average Score': avgScore.toFixed(2),
|
||||
'Pass Rate': `${(passRate * 100).toFixed(1)}%`,
|
||||
'Duration': `${duration}ms`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function runPerformanceEval(
|
||||
options: EvalOptions,
|
||||
config: { model: string; verbose: boolean },
|
||||
outputFormat: string
|
||||
): Promise<void> {
|
||||
const iterations = options.iterations || 10;
|
||||
const warmup = options.warmup || 2;
|
||||
const results: PerformanceResult[] = [];
|
||||
|
||||
const agent = new Agent({
|
||||
name: 'Perf Agent',
|
||||
instructions: 'You are a helpful AI assistant.',
|
||||
llm: config.model,
|
||||
verbose: false // Disable verbose for performance testing
|
||||
});
|
||||
|
||||
const testPrompt = 'Say "hello" and nothing else.';
|
||||
|
||||
// Warmup runs
|
||||
for (let i = 0; i < warmup; i++) {
|
||||
await agent.start(testPrompt);
|
||||
}
|
||||
|
||||
// Actual runs
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
const start = Date.now();
|
||||
await agent.start(testPrompt);
|
||||
const duration = Date.now() - start;
|
||||
|
||||
results.push({
|
||||
iteration: i + 1,
|
||||
duration_ms: duration
|
||||
});
|
||||
}
|
||||
|
||||
const durations = results.map(r => r.duration_ms);
|
||||
const avg = durations.reduce((a, b) => a + b, 0) / durations.length;
|
||||
const min = Math.min(...durations);
|
||||
const max = Math.max(...durations);
|
||||
const sorted = [...durations].sort((a, b) => a - b);
|
||||
const p95 = sorted[Math.floor(sorted.length * 0.95)];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(
|
||||
{
|
||||
type: 'performance',
|
||||
results,
|
||||
summary: {
|
||||
avg_ms: avg,
|
||||
min_ms: min,
|
||||
max_ms: max,
|
||||
p95_ms: p95,
|
||||
iterations,
|
||||
warmup_runs: warmup
|
||||
}
|
||||
},
|
||||
{ model: config.model }
|
||||
));
|
||||
} else {
|
||||
await pretty.heading('Performance Evaluation Results');
|
||||
await pretty.keyValue({
|
||||
'Iterations': iterations,
|
||||
'Warmup Runs': warmup,
|
||||
'Avg Duration': `${avg.toFixed(2)}ms`,
|
||||
'Min Duration': `${min}ms`,
|
||||
'Max Duration': `${max}ms`,
|
||||
'P95 Duration': `${p95}ms`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function runReliabilityEval(
|
||||
options: EvalOptions,
|
||||
config: { model: string; verbose: boolean },
|
||||
outputFormat: string
|
||||
): Promise<void> {
|
||||
const expectedTools = options['expected-tools']?.split(',').map(t => t.trim()) || [];
|
||||
|
||||
if (expectedTools.length === 0) {
|
||||
throw new Error('--expected-tools is required for reliability evaluation');
|
||||
}
|
||||
|
||||
// For now, simulate reliability check
|
||||
// In production, this would track actual tool calls
|
||||
const results = {
|
||||
expected: expectedTools,
|
||||
called: expectedTools, // Simulated
|
||||
missing: [] as string[],
|
||||
unexpected: [] as string[]
|
||||
};
|
||||
|
||||
const passed = results.missing.length === 0;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
type: 'reliability',
|
||||
status: passed ? 'PASSED' : 'FAILED',
|
||||
results
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Reliability Evaluation Results');
|
||||
if (passed) {
|
||||
await pretty.success('All expected tools were called');
|
||||
} else {
|
||||
await pretty.error(`Missing tool calls: ${results.missing.join(', ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple string similarity calculation
|
||||
*/
|
||||
function calculateSimilarity(str1: string, str2: string): number {
|
||||
const s1 = str1.toLowerCase().trim();
|
||||
const s2 = str2.toLowerCase().trim();
|
||||
|
||||
if (s1 === s2) return 1;
|
||||
if (s1.includes(s2) || s2.includes(s1)) return 0.9;
|
||||
|
||||
// Simple word overlap
|
||||
const words1 = new Set(s1.split(/\s+/));
|
||||
const words2 = new Set(s2.split(/\s+/));
|
||||
const intersection = [...words1].filter(w => words2.has(w));
|
||||
const union = new Set([...words1, ...words2]);
|
||||
|
||||
return intersection.length / union.size;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* CLI command: external-agents
|
||||
* Integration with external AI CLI tools
|
||||
*/
|
||||
|
||||
import {
|
||||
getExternalAgentRegistry,
|
||||
createExternalAgent,
|
||||
ClaudeCodeAgent,
|
||||
GeminiCliAgent,
|
||||
CodexCliAgent,
|
||||
AiderAgent
|
||||
} from '../features/external-agents';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'list':
|
||||
await handleList(isJson);
|
||||
break;
|
||||
case 'check':
|
||||
await handleCheck(args.slice(1), isJson);
|
||||
break;
|
||||
case 'run':
|
||||
await handleRun(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(isJson: boolean): Promise<void> {
|
||||
const registry = getExternalAgentRegistry();
|
||||
const all = registry.list();
|
||||
const available = await registry.getAvailable();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({
|
||||
success: true,
|
||||
agents: all,
|
||||
available
|
||||
}, null, 2));
|
||||
} else {
|
||||
console.log('External Agents:\n');
|
||||
for (const name of all) {
|
||||
const status = available.includes(name) ? '✓' : '✗';
|
||||
console.log(` ${status} ${name}`);
|
||||
}
|
||||
console.log(`\n${available.length}/${all.length} available`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCheck(args: string[], isJson: boolean): Promise<void> {
|
||||
const name = args[0];
|
||||
|
||||
if (!name) {
|
||||
console.error('Error: Agent name is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const agent = createExternalAgent(name);
|
||||
|
||||
if (!agent) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: `Unknown agent: ${name}` }));
|
||||
} else {
|
||||
console.error(`Unknown agent: ${name}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const available = await agent.isAvailable();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, agent: name, available }));
|
||||
} else {
|
||||
if (available) {
|
||||
console.log(`✓ ${name} is available`);
|
||||
} else {
|
||||
console.log(`✗ ${name} is not available (CLI not found)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRun(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const name = args[0];
|
||||
const prompt = args.slice(1).join(' ');
|
||||
|
||||
if (!name) {
|
||||
console.error('Error: Agent name is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!prompt) {
|
||||
console.error('Error: Prompt is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const cwd = options.cwd as string | undefined;
|
||||
const agent = createExternalAgent(name, cwd);
|
||||
|
||||
if (!agent) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: `Unknown agent: ${name}` }));
|
||||
} else {
|
||||
console.error(`Unknown agent: ${name}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!await agent.isAvailable()) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: `${name} CLI not available` }));
|
||||
} else {
|
||||
console.error(`${name} CLI not available`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const result = await agent.execute(prompt);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
if (result.success) {
|
||||
console.log(result.output);
|
||||
} else {
|
||||
console.error(`Error: ${result.error}`);
|
||||
process.exit(result.exitCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'external-agents',
|
||||
description: 'Integration with external AI CLI tools',
|
||||
subcommands: {
|
||||
list: 'List all external agents and availability',
|
||||
check: 'Check if an agent is available',
|
||||
run: 'Run a prompt with an external agent'
|
||||
},
|
||||
agents: {
|
||||
claude: 'Claude Code CLI',
|
||||
gemini: 'Gemini CLI',
|
||||
codex: 'OpenAI Codex CLI',
|
||||
aider: 'Aider CLI'
|
||||
},
|
||||
flags: {
|
||||
'--cwd': 'Working directory for the agent',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts external-agents list',
|
||||
'praisonai-ts external-agents check claude',
|
||||
'praisonai-ts external-agents run claude "Explain this code"',
|
||||
'praisonai-ts external-agents run gemini "Refactor this function" --cwd ./src'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('External Agents - AI CLI tool integration\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nSupported Agents:');
|
||||
for (const [agent, desc] of Object.entries(help.agents)) {
|
||||
console.log(` ${agent.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* CLI command: fast-context
|
||||
* Fast context retrieval and summarization
|
||||
*/
|
||||
|
||||
import { FastContext, createFastContext, getQuickContext } from '../features/fast-context';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'query':
|
||||
await handleQuery(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'stats':
|
||||
await handleStats(isJson);
|
||||
break;
|
||||
case 'clear':
|
||||
await handleClear(isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
let globalContext: FastContext | null = null;
|
||||
|
||||
function getContext(maxTokens?: number): FastContext {
|
||||
if (!globalContext) {
|
||||
globalContext = createFastContext({ maxTokens, cacheEnabled: true });
|
||||
}
|
||||
return globalContext;
|
||||
}
|
||||
|
||||
async function handleQuery(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const query = args.join(' ');
|
||||
if (!query) {
|
||||
console.error('Error: Query is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const maxTokens = options['max-tokens'] as number | undefined;
|
||||
const sources = options.sources as string | undefined;
|
||||
|
||||
const fc = getContext(maxTokens);
|
||||
|
||||
// Add sources if provided
|
||||
if (sources) {
|
||||
const sourceList = sources.split(',').map(s => s.trim());
|
||||
fc.registerSource('cli-sources', 'custom', sourceList);
|
||||
}
|
||||
|
||||
const result = await fc.getContext(query);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, ...result }, null, 2));
|
||||
} else {
|
||||
console.log('Fast Context Result:');
|
||||
console.log(` Query: ${query}`);
|
||||
console.log(` Token count: ${result.tokenCount}`);
|
||||
console.log(` Sources used: ${result.sources.length}`);
|
||||
console.log(` Cached: ${result.cached}`);
|
||||
console.log(` Latency: ${result.latencyMs}ms`);
|
||||
console.log('\nContext:');
|
||||
console.log(result.context || '(empty)');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStats(isJson: boolean): Promise<void> {
|
||||
const fc = getContext();
|
||||
const stats = fc.getCacheStats();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, stats }, null, 2));
|
||||
} else {
|
||||
console.log('Fast Context Cache Stats:');
|
||||
console.log(` Cache size: ${stats.size}`);
|
||||
console.log(` Total hits: ${stats.totalHits}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleClear(isJson: boolean): Promise<void> {
|
||||
const fc = getContext();
|
||||
fc.clearCache();
|
||||
fc.clearSources();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, message: 'Cache and sources cleared' }));
|
||||
} else {
|
||||
console.log('✓ Cache and sources cleared');
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'fast-context',
|
||||
description: 'Fast context retrieval and summarization',
|
||||
subcommands: {
|
||||
query: 'Query for relevant context',
|
||||
stats: 'Show cache statistics',
|
||||
clear: 'Clear cache and sources'
|
||||
},
|
||||
flags: {
|
||||
'--max-tokens': 'Maximum tokens in context (default: 4000)',
|
||||
'--sources': 'Comma-separated source texts',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts fast-context query "What is the main topic?"',
|
||||
'praisonai-ts fast-context query "summarize" --sources "text1,text2,text3"',
|
||||
'praisonai-ts fast-context query "find relevant" --max-tokens 2000',
|
||||
'praisonai-ts fast-context stats',
|
||||
'praisonai-ts fast-context clear'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Fast Context - Fast context retrieval\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(14)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* CLI command: flow
|
||||
* Workflow flow visualization
|
||||
*/
|
||||
|
||||
import { FlowDisplay, createFlowDisplay, renderWorkflow } from '../features/flow-display';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'show':
|
||||
await handleShow(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'dot':
|
||||
await handleDot(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleShow(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const stepsStr = args[0] || options.steps as string;
|
||||
|
||||
let steps: Array<{ name: string; type?: string }> = [];
|
||||
|
||||
if (stepsStr) {
|
||||
try {
|
||||
steps = JSON.parse(stepsStr);
|
||||
} catch {
|
||||
// Parse simple format: "step1,step2,step3"
|
||||
steps = stepsStr.split(',').map(s => {
|
||||
const [name, type] = s.split(':');
|
||||
return { name: name.trim(), type: type?.trim() };
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Default example
|
||||
steps = [
|
||||
{ name: 'Input', type: 'start' },
|
||||
{ name: 'Process', type: 'agent' },
|
||||
{ name: 'Validate', type: 'condition' },
|
||||
{ name: 'Output', type: 'end' }
|
||||
];
|
||||
}
|
||||
|
||||
const display = createFlowDisplay({
|
||||
showStatus: Boolean(options.status),
|
||||
compact: Boolean(options.compact)
|
||||
});
|
||||
|
||||
display.fromWorkflowSteps(steps);
|
||||
|
||||
if (isJson) {
|
||||
const graph = display.getGraph();
|
||||
console.log(JSON.stringify({
|
||||
success: true,
|
||||
nodes: Array.from(graph.nodes.values()),
|
||||
edges: graph.edges
|
||||
}, null, 2));
|
||||
} else {
|
||||
if (options.boxes) {
|
||||
console.log(display.renderBoxes());
|
||||
} else {
|
||||
console.log(display.render());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDot(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const stepsStr = args[0] || options.steps as string;
|
||||
|
||||
let steps: Array<{ name: string; type?: string }> = [];
|
||||
|
||||
if (stepsStr) {
|
||||
try {
|
||||
steps = JSON.parse(stepsStr);
|
||||
} catch {
|
||||
steps = stepsStr.split(',').map(s => {
|
||||
const [name, type] = s.split(':');
|
||||
return { name: name.trim(), type: type?.trim() };
|
||||
});
|
||||
}
|
||||
} else {
|
||||
steps = [
|
||||
{ name: 'Start', type: 'start' },
|
||||
{ name: 'Agent', type: 'agent' },
|
||||
{ name: 'End', type: 'end' }
|
||||
];
|
||||
}
|
||||
|
||||
const display = createFlowDisplay();
|
||||
display.fromWorkflowSteps(steps);
|
||||
const dot = display.toDot();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, dot }));
|
||||
} else {
|
||||
console.log(dot);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'flow',
|
||||
description: 'Workflow flow visualization',
|
||||
subcommands: {
|
||||
show: 'Display workflow as text tree or boxes',
|
||||
dot: 'Export workflow as DOT format (for Graphviz)'
|
||||
},
|
||||
flags: {
|
||||
'--steps': 'Steps as JSON or "name:type,name:type"',
|
||||
'--status': 'Show status indicators',
|
||||
'--compact': 'Compact display mode',
|
||||
'--boxes': 'Display as ASCII boxes',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts flow show "Input,Process,Output"',
|
||||
'praisonai-ts flow show "Start:start,Agent:agent,End:end"',
|
||||
'praisonai-ts flow show --boxes',
|
||||
'praisonai-ts flow dot "Step1,Step2,Step3" > workflow.dot'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Flow - Workflow visualization\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* CLI command: git
|
||||
* Git integration for repository operations
|
||||
*/
|
||||
|
||||
import { GitManager, createGitManager, DiffViewer, createDiffViewer } from '../features/git-integration';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
const cwd = (options.cwd as string) || process.cwd();
|
||||
|
||||
switch (subcommand) {
|
||||
case 'status':
|
||||
await handleStatus(cwd, isJson);
|
||||
break;
|
||||
case 'diff':
|
||||
await handleDiff(options, cwd, isJson);
|
||||
break;
|
||||
case 'log':
|
||||
await handleLog(options, cwd, isJson);
|
||||
break;
|
||||
case 'branches':
|
||||
await handleBranches(cwd, isJson);
|
||||
break;
|
||||
case 'stash':
|
||||
await handleStash(args.slice(1), cwd, isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStatus(cwd: string, isJson: boolean): Promise<void> {
|
||||
const git = createGitManager({ cwd, safe: true });
|
||||
|
||||
if (!await git.isRepo()) {
|
||||
console.error('Error: Not a git repository');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const status = await git.getStatus();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, ...status }, null, 2));
|
||||
} else {
|
||||
console.log(await git.getStatusString());
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDiff(options: Record<string, unknown>, cwd: string, isJson: boolean): Promise<void> {
|
||||
const git = createGitManager({ cwd, safe: true });
|
||||
const staged = Boolean(options.staged);
|
||||
|
||||
if (!await git.isRepo()) {
|
||||
console.error('Error: Not a git repository');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const diff = await git.getDiff(staged);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, ...diff }, null, 2));
|
||||
} else {
|
||||
if (diff.files.length === 0) {
|
||||
console.log(staged ? 'No staged changes' : 'No changes');
|
||||
} else {
|
||||
console.log(`Changes (${diff.files.length} files):\n`);
|
||||
for (const file of diff.files) {
|
||||
console.log(` ${file.path} (+${file.additions}/-${file.deletions})`);
|
||||
}
|
||||
if (options.full) {
|
||||
console.log('\n' + diff.summary);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLog(options: Record<string, unknown>, cwd: string, isJson: boolean): Promise<void> {
|
||||
const git = createGitManager({ cwd, safe: true });
|
||||
const limit = (options.limit as number) || 10;
|
||||
|
||||
if (!await git.isRepo()) {
|
||||
console.error('Error: Not a git repository');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const commits = await git.getLog(limit);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, commits }, null, 2));
|
||||
} else {
|
||||
console.log('Recent commits:\n');
|
||||
for (const commit of commits) {
|
||||
console.log(` ${commit.shortHash} ${commit.message}`);
|
||||
console.log(` by ${commit.author} on ${commit.date.toLocaleDateString()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleBranches(cwd: string, isJson: boolean): Promise<void> {
|
||||
const git = createGitManager({ cwd, safe: true });
|
||||
|
||||
if (!await git.isRepo()) {
|
||||
console.error('Error: Not a git repository');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const branches = await git.getBranches();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, branches }, null, 2));
|
||||
} else {
|
||||
console.log('Branches:\n');
|
||||
for (const branch of branches) {
|
||||
const marker = branch.current ? '* ' : ' ';
|
||||
console.log(`${marker}${branch.name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStash(args: string[], cwd: string, isJson: boolean): Promise<void> {
|
||||
const git = createGitManager({ cwd, safe: true });
|
||||
|
||||
if (!await git.isRepo()) {
|
||||
console.error('Error: Not a git repository');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const stashes = await git.getStashList();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, stashes }, null, 2));
|
||||
} else {
|
||||
if (stashes.length === 0) {
|
||||
console.log('No stashes');
|
||||
} else {
|
||||
console.log('Stashes:\n');
|
||||
for (const stash of stashes) {
|
||||
console.log(` ${stash}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'git',
|
||||
description: 'Git integration for repository operations (read-only by default)',
|
||||
subcommands: {
|
||||
status: 'Show repository status',
|
||||
diff: 'Show changes',
|
||||
log: 'Show recent commits',
|
||||
branches: 'List branches',
|
||||
stash: 'List stashes'
|
||||
},
|
||||
flags: {
|
||||
'--cwd': 'Working directory (default: current)',
|
||||
'--staged': 'Show staged changes only (for diff)',
|
||||
'--full': 'Show full diff output',
|
||||
'--limit': 'Number of commits to show (default: 10)',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts git status',
|
||||
'praisonai-ts git diff',
|
||||
'praisonai-ts git diff --staged',
|
||||
'praisonai-ts git log --limit 5',
|
||||
'praisonai-ts git branches',
|
||||
'praisonai-ts git stash'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Git - Repository operations (read-only)\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Graph RAG command - Graph-based retrieval augmented generation
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface GraphRagOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: GraphRagOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Graph RAG',
|
||||
description: 'Graph-based retrieval augmented generation for complex knowledge queries',
|
||||
capabilities: [
|
||||
'Build knowledge graphs from documents',
|
||||
'Query relationships between entities',
|
||||
'Combine graph traversal with vector search',
|
||||
'Extract entities and relationships',
|
||||
'Support for complex multi-hop queries'
|
||||
],
|
||||
sdkUsage: `
|
||||
import { createGraphRAG, GraphStore } from 'praisonai';
|
||||
|
||||
// Create a graph RAG instance
|
||||
const graphRag = createGraphRAG({
|
||||
llm: 'openai/gpt-4o-mini',
|
||||
graphStore: new GraphStore()
|
||||
});
|
||||
|
||||
// Add documents
|
||||
await graphRag.addDocument('Document content...');
|
||||
|
||||
// Query with graph context
|
||||
const result = await graphRag.query('What is the relationship between X and Y?');
|
||||
`
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Graph RAG');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Capabilities:');
|
||||
for (const cap of info.capabilities) {
|
||||
await pretty.plain(` • ${cap}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.dim('Use the SDK for full Graph RAG functionality');
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'graph-rag',
|
||||
description: 'Graph-based retrieval augmented generation',
|
||||
subcommands: [
|
||||
{ name: 'info', description: 'Show Graph RAG feature information' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Graph RAG Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* Guardrail command - Content validation and safety
|
||||
*/
|
||||
|
||||
import { createLLMGuardrail } from '../../guardrails/llm-guardrail';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface GuardrailOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
criteria?: string;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: GuardrailOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
const config = resolveConfig(options);
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'check':
|
||||
await checkContent(actionArgs, options, config, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function checkContent(args: string[], options: GuardrailOptions, config: any, outputFormat: string): Promise<void> {
|
||||
const content = args.join(' ');
|
||||
if (!content) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide content to check'));
|
||||
} else {
|
||||
await pretty.error('Please provide content to check');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info('Checking content...');
|
||||
}
|
||||
|
||||
const guardrail = createLLMGuardrail({
|
||||
name: 'cli-guardrail',
|
||||
llm: config.model,
|
||||
criteria: options.criteria || 'Content should be safe, appropriate, and helpful',
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const result = await guardrail.check(content);
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
content: content.substring(0, 100) + (content.length > 100 ? '...' : ''),
|
||||
status: result.status,
|
||||
score: result.score,
|
||||
message: result.message,
|
||||
reasoning: result.reasoning
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Guardrail Check');
|
||||
if (result.status === 'passed') {
|
||||
await pretty.success('Content passed guardrail check');
|
||||
} else if (result.status === 'warning') {
|
||||
await pretty.warn('Content has warnings');
|
||||
} else {
|
||||
await pretty.error('Content failed guardrail check');
|
||||
}
|
||||
await pretty.plain(`Score: ${(result.score * 10).toFixed(1)}/10`);
|
||||
if (result.message) {
|
||||
await pretty.plain(`Message: ${result.message}`);
|
||||
}
|
||||
if (result.reasoning) {
|
||||
await pretty.dim(`Reasoning: ${result.reasoning}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.dim(`Checked in ${duration}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'guardrail',
|
||||
subcommands: [
|
||||
{ name: 'check <content>', description: 'Check content against guardrails' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
flags: [
|
||||
{ name: '--criteria', description: 'Custom criteria for validation' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Guardrail Command');
|
||||
await pretty.plain('Content validation and safety checks\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(25)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Flags:');
|
||||
for (const flag of help.flags) {
|
||||
await pretty.plain(` ${flag.name.padEnd(20)} ${flag.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Handoff command - Agent handoff management
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface HandoffOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: HandoffOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Handoff',
|
||||
description: 'Agent handoff allows seamless transfer of conversation context between agents',
|
||||
capabilities: [
|
||||
'Transfer conversation to specialized agents',
|
||||
'Preserve context during handoff',
|
||||
'Filter handoffs based on conditions',
|
||||
'Chain multiple agent handoffs'
|
||||
],
|
||||
sdkUsage: `
|
||||
import { Handoff, handoff, handoffFilters } from 'praisonai';
|
||||
|
||||
// Create a handoff
|
||||
const myHandoff = handoff({
|
||||
target: specialistAgent,
|
||||
condition: (ctx) => ctx.input.includes('technical'),
|
||||
onHandoff: (ctx) => console.log('Handing off...')
|
||||
});
|
||||
|
||||
// Use with an agent
|
||||
const agent = new Agent({
|
||||
handoffs: [myHandoff]
|
||||
});
|
||||
`
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Handoff Feature');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Capabilities:');
|
||||
for (const cap of info.capabilities) {
|
||||
await pretty.plain(` • ${cap}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.dim('Use the SDK for programmatic handoff configuration');
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'handoff',
|
||||
description: 'Agent handoff management - transfer conversations between agents',
|
||||
subcommands: [
|
||||
{ name: 'info', description: 'Show handoff feature information' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
note: 'Handoff is primarily a programmatic SDK feature. Use the SDK for full functionality.'
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Handoff Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.dim(help.note);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Help command - Show help information
|
||||
*/
|
||||
|
||||
import { COMMANDS, GLOBAL_FLAGS, CLI_SPEC_VERSION, getCommandSpec } from '../spec/cli-spec';
|
||||
import { outputJson, formatSuccess } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
|
||||
export interface HelpOptions {
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: HelpOptions): Promise<void> {
|
||||
const command = args[0];
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
if (command) {
|
||||
await showCommandHelp(command, outputFormat);
|
||||
} else {
|
||||
await showGeneralHelp(outputFormat);
|
||||
}
|
||||
}
|
||||
|
||||
async function showGeneralHelp(outputFormat: string): Promise<void> {
|
||||
const commands = Object.entries(COMMANDS).map(([name, spec]) => ({
|
||||
name,
|
||||
description: spec.description
|
||||
}));
|
||||
|
||||
const flags = GLOBAL_FLAGS.map(f => ({
|
||||
name: f.short ? `-${f.short}, --${f.name}` : `--${f.name}`,
|
||||
description: f.description,
|
||||
default: f.default
|
||||
}));
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
cli_spec_version: CLI_SPEC_VERSION,
|
||||
commands,
|
||||
global_flags: flags
|
||||
}));
|
||||
} else {
|
||||
await pretty.plain(`
|
||||
PraisonAI TypeScript CLI v${CLI_SPEC_VERSION}
|
||||
|
||||
Usage:
|
||||
praisonai-ts <command> [options]
|
||||
|
||||
Commands:`);
|
||||
|
||||
for (const cmd of commands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(12)} ${cmd.description}`);
|
||||
}
|
||||
|
||||
await pretty.plain(`
|
||||
Global Options:`);
|
||||
|
||||
for (const flag of flags) {
|
||||
const defaultStr = flag.default !== undefined ? ` (default: ${flag.default})` : '';
|
||||
await pretty.plain(` ${flag.name.padEnd(20)} ${flag.description}${defaultStr}`);
|
||||
}
|
||||
|
||||
await pretty.plain(`
|
||||
Environment Variables:
|
||||
OPENAI_API_KEY OpenAI API key
|
||||
ANTHROPIC_API_KEY Anthropic API key
|
||||
GOOGLE_API_KEY Google API key
|
||||
PRAISONAI_MODEL Default model
|
||||
|
||||
Examples:
|
||||
praisonai-ts chat "Hello, how are you?"
|
||||
praisonai-ts chat "Write a poem" --stream
|
||||
praisonai-ts run "Analyze this data" --agent my-agent.yaml
|
||||
praisonai-ts providers
|
||||
praisonai-ts help chat
|
||||
`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showCommandHelp(command: string, outputFormat: string): Promise<void> {
|
||||
const spec = getCommandSpec(command);
|
||||
|
||||
if (!spec) {
|
||||
await pretty.error(`Unknown command: ${command}`);
|
||||
await pretty.info('Run "praisonai-ts help" to see available commands');
|
||||
return;
|
||||
}
|
||||
|
||||
const args = spec.args || [];
|
||||
const flags = [...GLOBAL_FLAGS, ...(spec.flags || [])];
|
||||
const subcommands = spec.subcommands ? Object.entries(spec.subcommands) : [];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
command,
|
||||
description: spec.description,
|
||||
args: args.map(a => ({
|
||||
name: a.name,
|
||||
type: a.type,
|
||||
required: a.required,
|
||||
description: a.description
|
||||
})),
|
||||
flags: flags.map(f => ({
|
||||
name: f.name,
|
||||
short: f.short,
|
||||
type: f.type,
|
||||
default: f.default,
|
||||
description: f.description
|
||||
})),
|
||||
subcommands: subcommands.map(([name, sub]) => ({
|
||||
name,
|
||||
description: sub.description
|
||||
}))
|
||||
}));
|
||||
} else {
|
||||
await pretty.plain(`
|
||||
Command: ${command}
|
||||
${spec.description}
|
||||
|
||||
Usage:
|
||||
praisonai-ts ${command}${args.length ? ' ' + args.map(a => a.required ? `<${a.name}>` : `[${a.name}]`).join(' ') : ''} [options]`);
|
||||
|
||||
if (args.length > 0) {
|
||||
await pretty.plain(`
|
||||
Arguments:`);
|
||||
for (const arg of args) {
|
||||
const reqStr = arg.required ? ' (required)' : '';
|
||||
await pretty.plain(` ${arg.name.padEnd(15)} ${arg.description || arg.type}${reqStr}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (subcommands.length > 0) {
|
||||
await pretty.plain(`
|
||||
Subcommands:`);
|
||||
for (const [name, sub] of subcommands) {
|
||||
await pretty.plain(` ${name.padEnd(15)} ${sub.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
await pretty.plain(`
|
||||
Options:`);
|
||||
for (const flag of flags) {
|
||||
const shortStr = flag.short ? `-${flag.short}, ` : ' ';
|
||||
const defaultStr = flag.default !== undefined ? ` (default: ${flag.default})` : '';
|
||||
await pretty.plain(` ${shortStr}--${flag.name.padEnd(14)} ${flag.description || ''}${defaultStr}`);
|
||||
}
|
||||
|
||||
await pretty.plain('');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Image command - Image generation and analysis
|
||||
*/
|
||||
|
||||
import { createImageAgent } from '../../agent/image';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface ImageOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
size?: string;
|
||||
quality?: string;
|
||||
style?: string;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: ImageOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
const config = resolveConfig(options);
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'generate':
|
||||
await generateImage(actionArgs, options, config, outputFormat);
|
||||
break;
|
||||
case 'analyze':
|
||||
await analyzeImage(actionArgs, options, config, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function generateImage(args: string[], options: ImageOptions, config: any, outputFormat: string): Promise<void> {
|
||||
const prompt = args.join(' ');
|
||||
if (!prompt) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a prompt for image generation'));
|
||||
} else {
|
||||
await pretty.error('Please provide a prompt for image generation');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Generating image: "${prompt}"`);
|
||||
}
|
||||
|
||||
const agent = createImageAgent({
|
||||
llm: config.model,
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const result = await agent.generate({
|
||||
prompt,
|
||||
size: options.size as any,
|
||||
quality: options.quality as any,
|
||||
style: options.style as any
|
||||
});
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
const urls = Array.isArray(result) ? result : [result];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
prompt,
|
||||
urls
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Generated Image');
|
||||
for (const url of urls) {
|
||||
await pretty.plain(`URL: ${url}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.success(`Generated in ${duration}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
async function analyzeImage(args: string[], options: ImageOptions, config: any, outputFormat: string): Promise<void> {
|
||||
const imageUrl = args[0];
|
||||
const prompt = args.slice(1).join(' ') || 'Describe this image';
|
||||
|
||||
if (!imageUrl) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide an image URL'));
|
||||
} else {
|
||||
await pretty.error('Please provide an image URL');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Analyzing image: ${imageUrl}`);
|
||||
}
|
||||
|
||||
const agent = createImageAgent({
|
||||
llm: config.model,
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const result = await agent.analyze({
|
||||
imageUrl,
|
||||
prompt
|
||||
});
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
imageUrl,
|
||||
prompt,
|
||||
analysis: result
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Image Analysis');
|
||||
await pretty.plain(result);
|
||||
await pretty.newline();
|
||||
await pretty.success(`Analyzed in ${duration}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'image',
|
||||
subcommands: [
|
||||
{ name: 'generate <prompt>', description: 'Generate an image from text' },
|
||||
{ name: 'analyze <url> [question]', description: 'Analyze an image' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
flags: [
|
||||
{ name: '--size', description: 'Image size (1024x1024, 1792x1024, 1024x1792)' },
|
||||
{ name: '--quality', description: 'Image quality (standard, hd)' },
|
||||
{ name: '--style', description: 'Image style (vivid, natural)' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Image Command');
|
||||
await pretty.plain('Generate and analyze images\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(30)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Flags:');
|
||||
for (const flag of help.flags) {
|
||||
await pretty.plain(` ${flag.name.padEnd(20)} ${flag.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* CLI command: interactive
|
||||
* Interactive TUI mode with slash commands
|
||||
*/
|
||||
|
||||
import { InteractiveTUI, createInteractiveTUI } from '../features/interactive-tui';
|
||||
import { createCostTracker } from '../features/cost-tracker';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({
|
||||
success: false,
|
||||
error: 'Interactive mode does not support JSON output'
|
||||
}));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const historyFile = options.history as string | undefined;
|
||||
const model = options.model as string | undefined;
|
||||
|
||||
console.log('Starting interactive mode...');
|
||||
console.log('Type /help for available commands, /exit to quit.\n');
|
||||
|
||||
const tui = createInteractiveTUI({
|
||||
prompt: options.prompt as string || '> ',
|
||||
historyFile,
|
||||
welcomeMessage: `PraisonAI Interactive Mode
|
||||
Model: ${model || 'default'}
|
||||
Type /help for commands, /exit to quit.`,
|
||||
onMessage: async (message) => {
|
||||
// Simple echo for now - in real usage this would call the agent
|
||||
return `You said: ${message}`;
|
||||
},
|
||||
onExit: () => {
|
||||
console.log('\nGoodbye!');
|
||||
}
|
||||
});
|
||||
|
||||
// Update context with model if provided
|
||||
if (model) {
|
||||
tui.updateContext({ model });
|
||||
}
|
||||
|
||||
try {
|
||||
await tui.start();
|
||||
} catch (error: any) {
|
||||
console.error(`Error: ${error.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
export function showHelp(): void {
|
||||
console.log(`Interactive - Interactive TUI mode
|
||||
|
||||
Usage:
|
||||
praisonai-ts interactive [options]
|
||||
|
||||
Options:
|
||||
--model, -m Model to use
|
||||
--prompt Custom prompt string (default: "> ")
|
||||
--history Path to history file
|
||||
|
||||
Slash Commands (in interactive mode):
|
||||
/help Show available commands
|
||||
/cost Show token usage and cost
|
||||
/clear Clear conversation history
|
||||
/model [name] Show or change model
|
||||
/tokens Show token count
|
||||
/plan Manage task plan
|
||||
/undo Undo last action
|
||||
/diff Show pending changes
|
||||
/commit Commit pending changes
|
||||
/settings Show or modify settings
|
||||
/map Show repository map
|
||||
/exit Exit interactive mode
|
||||
|
||||
Examples:
|
||||
praisonai-ts interactive
|
||||
praisonai-ts interactive --model gpt-4o
|
||||
praisonai-ts interactive --history ~/.praisonai_history
|
||||
`);
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
/**
|
||||
* CLI command: jobs
|
||||
* Background job queue management
|
||||
*/
|
||||
|
||||
import { JobQueue, createJobQueue, createFileJobStorage } from '../features/background-jobs';
|
||||
|
||||
let globalQueue: JobQueue | null = null;
|
||||
|
||||
function getQueue(storagePath?: string): JobQueue {
|
||||
if (!globalQueue) {
|
||||
const storage = storagePath ? createFileJobStorage(storagePath) : undefined;
|
||||
globalQueue = createJobQueue({ storage });
|
||||
}
|
||||
return globalQueue;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
const storagePath = options.storage as string | undefined;
|
||||
|
||||
switch (subcommand) {
|
||||
case 'add':
|
||||
await handleAdd(args.slice(1), options, isJson, storagePath);
|
||||
break;
|
||||
case 'list':
|
||||
await handleList(options, isJson, storagePath);
|
||||
break;
|
||||
case 'get':
|
||||
await handleGet(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'cancel':
|
||||
await handleCancel(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'retry':
|
||||
await handleRetry(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'process':
|
||||
await handleProcess(args.slice(1), isJson, storagePath);
|
||||
break;
|
||||
case 'stats':
|
||||
await handleStats(isJson, storagePath);
|
||||
break;
|
||||
case 'cleanup':
|
||||
await handleCleanup(options, isJson, storagePath);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAdd(args: string[], options: Record<string, unknown>, isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const name = args[0];
|
||||
const dataStr = args[1] || '{}';
|
||||
|
||||
if (!name) {
|
||||
console.error('Error: Job name is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let data: Record<string, unknown>;
|
||||
try {
|
||||
data = JSON.parse(dataStr);
|
||||
} catch {
|
||||
data = { input: dataStr };
|
||||
}
|
||||
|
||||
const priority = (options.priority as string) || 'normal';
|
||||
const queue = getQueue(storagePath);
|
||||
|
||||
const job = await queue.add(name, data, {
|
||||
priority: priority as 'low' | 'normal' | 'high' | 'critical'
|
||||
});
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, job }, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Job created: ${job.id}`);
|
||||
console.log(` Name: ${job.name}`);
|
||||
console.log(` Priority: ${job.priority}`);
|
||||
console.log(` Status: ${job.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(options: Record<string, unknown>, isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const queue = getQueue(storagePath);
|
||||
const status = options.status as string | undefined;
|
||||
|
||||
let jobs = await queue.getAll();
|
||||
if (status) {
|
||||
jobs = jobs.filter(j => j.status === status);
|
||||
}
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, jobs }, null, 2));
|
||||
} else {
|
||||
if (jobs.length === 0) {
|
||||
console.log('No jobs found');
|
||||
} else {
|
||||
console.log('Jobs:');
|
||||
for (const job of jobs) {
|
||||
console.log(` ${job.id}`);
|
||||
console.log(` Name: ${job.name}`);
|
||||
console.log(` Status: ${job.status}`);
|
||||
console.log(` Priority: ${job.priority}`);
|
||||
console.log(` Attempts: ${job.attempts}/${job.maxAttempts}`);
|
||||
if (job.error) console.log(` Error: ${job.error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGet(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Job ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const queue = getQueue(storagePath);
|
||||
const job = await queue.get(id);
|
||||
|
||||
if (!job) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: 'Job not found' }));
|
||||
} else {
|
||||
console.error(`Job ${id} not found`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, job }, null, 2));
|
||||
} else {
|
||||
console.log(`Job: ${job.id}`);
|
||||
console.log(` Name: ${job.name}`);
|
||||
console.log(` Status: ${job.status}`);
|
||||
console.log(` Priority: ${job.priority}`);
|
||||
console.log(` Attempts: ${job.attempts}/${job.maxAttempts}`);
|
||||
console.log(` Created: ${job.createdAt}`);
|
||||
if (job.startedAt) console.log(` Started: ${job.startedAt}`);
|
||||
if (job.completedAt) console.log(` Completed: ${job.completedAt}`);
|
||||
if (job.error) console.log(` Error: ${job.error}`);
|
||||
if (job.result) console.log(` Result: ${JSON.stringify(job.result)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCancel(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Job ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const queue = getQueue(storagePath);
|
||||
const cancelled = await queue.cancel(id);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: cancelled, id }));
|
||||
} else {
|
||||
console.log(cancelled ? `✓ Job ${id} cancelled` : `Could not cancel job ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRetry(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Job ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const queue = getQueue(storagePath);
|
||||
const retried = await queue.retry(id);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: retried, id }));
|
||||
} else {
|
||||
console.log(retried ? `✓ Job ${id} queued for retry` : `Could not retry job ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleProcess(args: string[], isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Job ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const queue = getQueue(storagePath);
|
||||
|
||||
// Register a simple handler
|
||||
queue.register('default', async (job) => {
|
||||
return { processed: true, data: job.data };
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await queue.processNow(id);
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, result }, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Job ${id} processed`);
|
||||
console.log(` Result: ${JSON.stringify(result)}`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: error.message }));
|
||||
} else {
|
||||
console.error(`Error: ${error.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStats(isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const queue = getQueue(storagePath);
|
||||
const stats = await queue.getStats();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, stats }, null, 2));
|
||||
} else {
|
||||
console.log('Job Queue Stats:');
|
||||
console.log(` Pending: ${stats.pending}`);
|
||||
console.log(` Running: ${stats.running}`);
|
||||
console.log(` Completed: ${stats.completed}`);
|
||||
console.log(` Failed: ${stats.failed}`);
|
||||
console.log(` Cancelled: ${stats.cancelled}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCleanup(options: Record<string, unknown>, isJson: boolean, storagePath?: string): Promise<void> {
|
||||
const queue = getQueue(storagePath);
|
||||
const days = (options.days as number) || 7;
|
||||
const olderThan = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
|
||||
const count = await queue.cleanup(olderThan);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, cleaned: count }));
|
||||
} else {
|
||||
console.log(`✓ Cleaned up ${count} jobs older than ${days} days`);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'jobs',
|
||||
description: 'Background job queue management',
|
||||
subcommands: {
|
||||
add: 'Add a new job to the queue',
|
||||
list: 'List all jobs',
|
||||
get: 'Get job details',
|
||||
cancel: 'Cancel a pending job',
|
||||
retry: 'Retry a failed job',
|
||||
process: 'Process a job immediately',
|
||||
stats: 'Show queue statistics',
|
||||
cleanup: 'Clean up old completed/failed jobs'
|
||||
},
|
||||
flags: {
|
||||
'--storage': 'Path to job storage file',
|
||||
'--priority': 'Job priority (low, normal, high, critical)',
|
||||
'--status': 'Filter by status',
|
||||
'--days': 'Days for cleanup threshold',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts jobs add my-job \'{"input": "data"}\'',
|
||||
'praisonai-ts jobs add task --priority high',
|
||||
'praisonai-ts jobs list --status pending',
|
||||
'praisonai-ts jobs get <job-id>',
|
||||
'praisonai-ts jobs cancel <job-id>',
|
||||
'praisonai-ts jobs stats',
|
||||
'praisonai-ts jobs cleanup --days 30'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Jobs - Background job queue management\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Knowledge command - Manage knowledge base
|
||||
*/
|
||||
|
||||
import { BaseKnowledgeBase, Knowledge } from '../../knowledge';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
export interface KnowledgeOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
// Singleton knowledge base instance
|
||||
let kbInstance: BaseKnowledgeBase | null = null;
|
||||
function getKnowledgeBase(): BaseKnowledgeBase {
|
||||
if (!kbInstance) {
|
||||
kbInstance = new BaseKnowledgeBase();
|
||||
}
|
||||
return kbInstance;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: KnowledgeOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
const kb = getKnowledgeBase();
|
||||
|
||||
switch (action) {
|
||||
case 'add':
|
||||
await addKnowledge(kb, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'search':
|
||||
await searchKnowledge(kb, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'list':
|
||||
await listKnowledge(kb, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function addKnowledge(kb: BaseKnowledgeBase, args: string[], outputFormat: string): Promise<void> {
|
||||
const source = args[0];
|
||||
if (!source) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a file path or text content'));
|
||||
} else {
|
||||
await pretty.error('Please provide a file path or text content');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
let content: string;
|
||||
let sourceName: string;
|
||||
|
||||
// Check if it's a file path
|
||||
if (fs.existsSync(source)) {
|
||||
content = fs.readFileSync(source, 'utf-8');
|
||||
sourceName = path.basename(source);
|
||||
} else {
|
||||
// Treat as direct text content
|
||||
content = args.join(' ');
|
||||
sourceName = 'text-input';
|
||||
}
|
||||
|
||||
const knowledge: Knowledge = {
|
||||
id: randomUUID(),
|
||||
type: 'text',
|
||||
content,
|
||||
metadata: { source: sourceName, addedAt: new Date().toISOString() }
|
||||
};
|
||||
|
||||
kb.addKnowledge(knowledge);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
added: true,
|
||||
id: knowledge.id,
|
||||
source: sourceName,
|
||||
contentLength: content.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.success(`Knowledge added from: ${sourceName}`);
|
||||
await pretty.dim(`Content length: ${content.length} characters`);
|
||||
}
|
||||
}
|
||||
|
||||
async function searchKnowledge(kb: BaseKnowledgeBase, args: string[], outputFormat: string): Promise<void> {
|
||||
const query = args.join(' ');
|
||||
if (!query) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a search query'));
|
||||
} else {
|
||||
await pretty.error('Please provide a search query');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const results = kb.searchKnowledge(query);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
query,
|
||||
results: results.map(r => ({
|
||||
id: r.id,
|
||||
content: r.content,
|
||||
metadata: r.metadata
|
||||
})),
|
||||
count: results.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading(`Search Results for: "${query}"`);
|
||||
if (results.length === 0) {
|
||||
await pretty.info('No matching knowledge found');
|
||||
} else {
|
||||
for (const result of results) {
|
||||
const contentStr = typeof result.content === 'string' ? result.content : JSON.stringify(result.content);
|
||||
await pretty.plain(` • ${contentStr.substring(0, 100)}${contentStr.length > 100 ? '...' : ''}`);
|
||||
if (result.metadata?.source) {
|
||||
await pretty.dim(` Source: ${result.metadata.source}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Found: ${results.length} results`);
|
||||
}
|
||||
}
|
||||
|
||||
async function listKnowledge(kb: BaseKnowledgeBase, outputFormat: string): Promise<void> {
|
||||
// Search with empty string to get all
|
||||
const entries = kb.searchKnowledge('');
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
entries: entries.map((e: Knowledge) => ({
|
||||
id: e.id,
|
||||
type: e.type,
|
||||
contentPreview: typeof e.content === 'string' ? e.content.substring(0, 100) : JSON.stringify(e.content).substring(0, 100),
|
||||
source: e.metadata?.source
|
||||
})),
|
||||
count: entries.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Knowledge Base Entries');
|
||||
if (entries.length === 0) {
|
||||
await pretty.info('No knowledge entries found');
|
||||
} else {
|
||||
for (const entry of entries) {
|
||||
const contentStr = typeof entry.content === 'string' ? entry.content : JSON.stringify(entry.content);
|
||||
await pretty.plain(` • ${contentStr.substring(0, 80)}${contentStr.length > 80 ? '...' : ''}`);
|
||||
if (entry.metadata?.source) {
|
||||
await pretty.dim(` Source: ${entry.metadata.source}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Total: ${entries.length} entries`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'knowledge',
|
||||
subcommands: [
|
||||
{ name: 'add <file|text>', description: 'Add knowledge from file or text' },
|
||||
{ name: 'search <query>', description: 'Search knowledge base' },
|
||||
{ name: 'list', description: 'List all knowledge entries' },
|
||||
{ name: 'clear', description: 'Clear all knowledge' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Knowledge Command');
|
||||
await pretty.plain('Manage knowledge base for RAG\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(25)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* MCP command - Model Context Protocol management
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface MCPOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
// MCP server registry (in-memory for now)
|
||||
interface MCPServer {
|
||||
name: string;
|
||||
command: string;
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
status: 'stopped' | 'running';
|
||||
}
|
||||
|
||||
const mcpServers: Map<string, MCPServer> = new Map();
|
||||
|
||||
export async function execute(args: string[], options: MCPOptions): Promise<void> {
|
||||
const action = args[0] || 'list';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'list':
|
||||
await listServers(outputFormat);
|
||||
break;
|
||||
case 'add':
|
||||
await addServer(actionArgs, outputFormat);
|
||||
break;
|
||||
case 'remove':
|
||||
await removeServer(actionArgs, outputFormat);
|
||||
break;
|
||||
case 'start':
|
||||
await startServer(actionArgs, outputFormat);
|
||||
break;
|
||||
case 'stop':
|
||||
await stopServer(actionArgs, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function listServers(outputFormat: string): Promise<void> {
|
||||
const servers = Array.from(mcpServers.values());
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
servers,
|
||||
count: servers.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('MCP Servers');
|
||||
if (servers.length === 0) {
|
||||
await pretty.info('No MCP servers registered');
|
||||
await pretty.dim('Run "praisonai-ts mcp add <name> <command>" to add a server');
|
||||
} else {
|
||||
for (const server of servers) {
|
||||
const statusIcon = server.status === 'running' ? '🟢' : '⚪';
|
||||
await pretty.plain(` ${statusIcon} ${server.name}`);
|
||||
await pretty.dim(` Command: ${server.command} ${(server.args || []).join(' ')}`);
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Total: ${servers.length} servers`);
|
||||
}
|
||||
}
|
||||
|
||||
async function addServer(args: string[], outputFormat: string): Promise<void> {
|
||||
const name = args[0];
|
||||
const command = args[1];
|
||||
const serverArgs = args.slice(2);
|
||||
|
||||
if (!name || !command) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide server name and command'));
|
||||
} else {
|
||||
await pretty.error('Please provide server name and command');
|
||||
await pretty.dim('Usage: praisonai-ts mcp add <name> <command> [args...]');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const server: MCPServer = {
|
||||
name,
|
||||
command,
|
||||
args: serverArgs.length > 0 ? serverArgs : undefined,
|
||||
status: 'stopped'
|
||||
};
|
||||
|
||||
mcpServers.set(name, server);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ added: true, server }));
|
||||
} else {
|
||||
await pretty.success(`MCP server added: ${name}`);
|
||||
await pretty.dim(`Command: ${command} ${serverArgs.join(' ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeServer(args: string[], outputFormat: string): Promise<void> {
|
||||
const name = args[0];
|
||||
if (!name) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide server name'));
|
||||
} else {
|
||||
await pretty.error('Please provide server name');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const removed = mcpServers.delete(name);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ removed, name }));
|
||||
} else {
|
||||
if (removed) {
|
||||
await pretty.success(`MCP server removed: ${name}`);
|
||||
} else {
|
||||
await pretty.warn(`Server not found: ${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function startServer(args: string[], outputFormat: string): Promise<void> {
|
||||
const name = args[0];
|
||||
if (!name) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide server name'));
|
||||
} else {
|
||||
await pretty.error('Please provide server name');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const server = mcpServers.get(name);
|
||||
if (!server) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, `Server not found: ${name}`));
|
||||
} else {
|
||||
await pretty.error(`Server not found: ${name}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
|
||||
// Mark as running (actual process management would be more complex)
|
||||
server.status = 'running';
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ started: true, server }));
|
||||
} else {
|
||||
await pretty.success(`MCP server started: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function stopServer(args: string[], outputFormat: string): Promise<void> {
|
||||
const name = args[0];
|
||||
if (!name) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide server name'));
|
||||
} else {
|
||||
await pretty.error('Please provide server name');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const server = mcpServers.get(name);
|
||||
if (!server) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, `Server not found: ${name}`));
|
||||
} else {
|
||||
await pretty.error(`Server not found: ${name}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
|
||||
server.status = 'stopped';
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ stopped: true, server }));
|
||||
} else {
|
||||
await pretty.success(`MCP server stopped: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'mcp',
|
||||
description: 'Model Context Protocol server management',
|
||||
subcommands: [
|
||||
{ name: 'list', description: 'List registered MCP servers' },
|
||||
{ name: 'add <name> <cmd> [args]', description: 'Add an MCP server' },
|
||||
{ name: 'remove <name>', description: 'Remove an MCP server' },
|
||||
{ name: 'start <name>', description: 'Start an MCP server' },
|
||||
{ name: 'stop <name>', description: 'Stop an MCP server' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('MCP Command');
|
||||
await pretty.plain('Model Context Protocol server management\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(25)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Memory command - Manage agent memory
|
||||
*/
|
||||
|
||||
import { Memory, createMemory, MemoryEntry, SearchResult } from '../../memory/memory';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface MemoryOptions {
|
||||
userId?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: MemoryOptions): Promise<void> {
|
||||
const action = args[0] || 'list';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
const memory = createMemory();
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
await listMemories(memory, outputFormat);
|
||||
break;
|
||||
case 'add':
|
||||
await addMemory(memory, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'search':
|
||||
await searchMemory(memory, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'clear':
|
||||
await clearMemory(memory, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function listMemories(memory: Memory, outputFormat: string): Promise<void> {
|
||||
const entries = memory.getAll();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
memories: entries,
|
||||
count: entries.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Memory Entries');
|
||||
if (entries.length === 0) {
|
||||
await pretty.info('No memories stored');
|
||||
} else {
|
||||
for (const entry of entries) {
|
||||
await pretty.plain(` • ${entry.content.substring(0, 100)}${entry.content.length > 100 ? '...' : ''}`);
|
||||
if (entry.metadata) {
|
||||
await pretty.dim(` Created: ${new Date(entry.timestamp).toISOString()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Total: ${entries.length} memories`);
|
||||
}
|
||||
}
|
||||
|
||||
async function addMemory(memory: Memory, args: string[], outputFormat: string): Promise<void> {
|
||||
const content = args.join(' ');
|
||||
if (!content) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide content to add'));
|
||||
} else {
|
||||
await pretty.error('Please provide content to add');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
await memory.add(content, 'user');
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ added: content }));
|
||||
} else {
|
||||
await pretty.success('Memory added successfully');
|
||||
}
|
||||
}
|
||||
|
||||
async function searchMemory(memory: Memory, args: string[], outputFormat: string): Promise<void> {
|
||||
const query = args.join(' ');
|
||||
if (!query) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a search query'));
|
||||
} else {
|
||||
await pretty.error('Please provide a search query');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const results = await memory.search(query);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
query,
|
||||
results,
|
||||
count: results.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading(`Search Results for: "${query}"`);
|
||||
if (results.length === 0) {
|
||||
await pretty.info('No matching memories found');
|
||||
} else {
|
||||
for (const result of results) {
|
||||
const content = result.entry.content;
|
||||
await pretty.plain(` • ${content.substring(0, 100)}${content.length > 100 ? '...' : ''}`);
|
||||
await pretty.dim(` Score: ${result.score.toFixed(3)}`);
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Found: ${results.length} results`);
|
||||
}
|
||||
}
|
||||
|
||||
async function clearMemory(memory: Memory, outputFormat: string): Promise<void> {
|
||||
memory.clear();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ cleared: true }));
|
||||
} else {
|
||||
await pretty.success('Memory cleared successfully');
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'memory',
|
||||
subcommands: [
|
||||
{ name: 'list', description: 'List all memories' },
|
||||
{ name: 'add <content>', description: 'Add a new memory' },
|
||||
{ name: 'search <query>', description: 'Search memories' },
|
||||
{ name: 'clear', description: 'Clear all memories' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
options: [
|
||||
{ name: '--user-id', description: 'User ID for memory isolation' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Memory Command');
|
||||
await pretty.plain('Manage agent memory storage\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Options:');
|
||||
for (const opt of help.options) {
|
||||
await pretty.plain(` ${opt.name.padEnd(20)} ${opt.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* CLI command: n8n
|
||||
* N8N workflow integration
|
||||
*/
|
||||
|
||||
import { N8NIntegration, createN8NIntegration } from '../features/n8n-integration';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'trigger':
|
||||
await handleTrigger(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'export':
|
||||
await handleExport(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTrigger(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const webhookId = args[0];
|
||||
const payloadStr = args[1] || '{}';
|
||||
|
||||
if (!webhookId) {
|
||||
console.error('Error: Webhook ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let payload: Record<string, unknown>;
|
||||
try {
|
||||
payload = JSON.parse(payloadStr);
|
||||
} catch {
|
||||
payload = { data: payloadStr };
|
||||
}
|
||||
|
||||
const baseUrl = options['base-url'] as string | undefined;
|
||||
const apiKey = options['api-key'] as string | undefined;
|
||||
|
||||
const n8n = createN8NIntegration({ baseUrl, apiKey });
|
||||
const result = await n8n.triggerWebhook(webhookId, payload);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
if (result.success) {
|
||||
console.log(`✓ Webhook triggered: ${webhookId}`);
|
||||
if (result.response) {
|
||||
console.log('Response:', JSON.stringify(result.response, null, 2));
|
||||
}
|
||||
} else {
|
||||
console.error(`✗ Webhook failed: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExport(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const name = args[0] || 'workflow';
|
||||
const stepsStr = options.steps as string | undefined;
|
||||
|
||||
let steps: Array<{ name: string; type: 'agent' | 'tool' | 'condition' }> = [];
|
||||
|
||||
if (stepsStr) {
|
||||
try {
|
||||
steps = JSON.parse(stepsStr);
|
||||
} catch {
|
||||
// Parse simple format: "step1:agent,step2:tool"
|
||||
steps = stepsStr.split(',').map(s => {
|
||||
const [stepName, type] = s.split(':');
|
||||
return { name: stepName, type: (type || 'agent') as 'agent' | 'tool' | 'condition' };
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Default example workflow
|
||||
steps = [
|
||||
{ name: 'Process Input', type: 'agent' },
|
||||
{ name: 'Validate', type: 'condition' },
|
||||
{ name: 'Execute', type: 'tool' }
|
||||
];
|
||||
}
|
||||
|
||||
const n8n = createN8NIntegration();
|
||||
const workflow = n8n.exportWorkflowJSON(name, steps);
|
||||
|
||||
if (isJson || !options.pretty) {
|
||||
console.log(workflow);
|
||||
} else {
|
||||
console.log(`N8N Workflow: ${name}\n`);
|
||||
console.log('Steps:');
|
||||
for (const step of steps) {
|
||||
console.log(` - ${step.name} (${step.type})`);
|
||||
}
|
||||
console.log('\nExported workflow JSON:');
|
||||
console.log(workflow);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'n8n',
|
||||
description: 'N8N workflow integration',
|
||||
subcommands: {
|
||||
trigger: 'Trigger an N8N webhook',
|
||||
export: 'Export workflow to N8N format'
|
||||
},
|
||||
flags: {
|
||||
'--base-url': 'N8N base URL (default: http://localhost:5678)',
|
||||
'--api-key': 'N8N API key',
|
||||
'--steps': 'Workflow steps as JSON or "name:type,name:type"',
|
||||
'--pretty': 'Pretty print export',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts n8n trigger my-webhook \'{"data": "test"}\'',
|
||||
'praisonai-ts n8n trigger webhook-id --base-url https://n8n.example.com',
|
||||
'praisonai-ts n8n export my-workflow',
|
||||
'praisonai-ts n8n export workflow --steps "Process:agent,Validate:condition"'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('N8N - Workflow integration\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Observability command - Monitoring and tracing
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface ObservabilityOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: ObservabilityOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'providers':
|
||||
await listProviders(outputFormat);
|
||||
break;
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Observability',
|
||||
description: 'Monitoring, tracing, and logging for agent operations',
|
||||
providers: [
|
||||
{ name: 'ConsoleObservabilityProvider', description: 'Console-based logging' },
|
||||
{ name: 'MemoryObservabilityProvider', description: 'In-memory trace storage' },
|
||||
{ name: 'LangfuseObservabilityProvider', description: 'Langfuse integration' }
|
||||
],
|
||||
capabilities: [
|
||||
'Trace agent executions',
|
||||
'Log LLM calls and responses',
|
||||
'Track tool invocations',
|
||||
'Measure performance metrics',
|
||||
'Export traces to external systems'
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Observability');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Providers:');
|
||||
for (const p of info.providers) {
|
||||
await pretty.plain(` • ${p.name}: ${p.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Capabilities:');
|
||||
for (const cap of info.capabilities) {
|
||||
await pretty.plain(` • ${cap}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listProviders(outputFormat: string): Promise<void> {
|
||||
const providers = [
|
||||
{ name: 'console', description: 'Console logging (default)', available: true },
|
||||
{ name: 'memory', description: 'In-memory storage', available: true },
|
||||
{ name: 'langfuse', description: 'Langfuse observability platform', available: true }
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ providers }));
|
||||
} else {
|
||||
await pretty.heading('Observability Providers');
|
||||
for (const p of providers) {
|
||||
const status = p.available ? '✓' : '✗';
|
||||
await pretty.plain(` ${status} ${p.name.padEnd(15)} ${p.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'observability',
|
||||
description: 'Monitoring and tracing for agent operations',
|
||||
subcommands: [
|
||||
{ name: 'info', description: 'Show observability feature information' },
|
||||
{ name: 'providers', description: 'List available observability providers' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Observability Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Planning command - Task planning and todo management
|
||||
*/
|
||||
|
||||
import { createPlan, createTodoList, TodoItem, type PlanConfig, type TodoItemConfig } from '../../planning';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface PlanningOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: PlanningOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'create':
|
||||
await createNewPlan(actionArgs, outputFormat);
|
||||
break;
|
||||
case 'todo':
|
||||
await manageTodo(actionArgs, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function createNewPlan(args: string[], outputFormat: string): Promise<void> {
|
||||
const name = args.join(' ');
|
||||
if (!name) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a name for the plan'));
|
||||
} else {
|
||||
await pretty.error('Please provide a name for the plan');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const plan = createPlan({
|
||||
name,
|
||||
description: name
|
||||
});
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
id: plan.id,
|
||||
name: plan.name,
|
||||
status: plan.status
|
||||
}));
|
||||
} else {
|
||||
await pretty.success(`Plan created: ${plan.id}`);
|
||||
await pretty.plain(`Name: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function manageTodo(args: string[], outputFormat: string): Promise<void> {
|
||||
const subAction = args[0] || 'list';
|
||||
const todoArgs = args.slice(1);
|
||||
|
||||
const todoList = createTodoList();
|
||||
|
||||
switch (subAction) {
|
||||
case 'add':
|
||||
const content = todoArgs.join(' ');
|
||||
if (!content) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide todo content'));
|
||||
} else {
|
||||
await pretty.error('Please provide todo content');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
const newItem = new TodoItem({ content });
|
||||
todoList.add(newItem);
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ added: true, id: newItem.id, content: newItem.content }));
|
||||
} else {
|
||||
await pretty.success(`Todo added: ${content}`);
|
||||
}
|
||||
break;
|
||||
case 'list':
|
||||
default:
|
||||
const items = todoList.items;
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ items, count: items.length }));
|
||||
} else {
|
||||
await pretty.heading('Todo List');
|
||||
if (items.length === 0) {
|
||||
await pretty.info('No todos');
|
||||
} else {
|
||||
for (const todo of items) {
|
||||
const status = todo.status === 'completed' ? '✓' : '○';
|
||||
await pretty.plain(` ${status} ${todo.content}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'planning',
|
||||
subcommands: [
|
||||
{ name: 'create <goal>', description: 'Create a new plan' },
|
||||
{ name: 'todo add <title>', description: 'Add a todo item' },
|
||||
{ name: 'todo list', description: 'List todo items' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Planning Command');
|
||||
await pretty.plain('Task planning and todo management\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(25)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Prompt Expand command - Expand prompts with more detail
|
||||
*/
|
||||
|
||||
import { createPromptExpanderAgent } from '../../agent/prompt-expander';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface PromptExpandOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
strategy?: string;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: PromptExpandOptions): Promise<void> {
|
||||
const prompt = args.join(' ');
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
const config = resolveConfig(options);
|
||||
|
||||
if (!prompt) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a prompt to expand'));
|
||||
} else {
|
||||
await pretty.error('Please provide a prompt to expand');
|
||||
await pretty.dim('Usage: praisonai-ts prompt-expand "your prompt"');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Expanding prompt: "${prompt}"`);
|
||||
}
|
||||
|
||||
const agent = createPromptExpanderAgent({
|
||||
llm: config.model,
|
||||
verbose: options.verbose,
|
||||
defaultStrategy: options.strategy as any
|
||||
});
|
||||
|
||||
const result = await agent.expand(prompt);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
originalPrompt: prompt,
|
||||
expandedPrompt: result.expanded,
|
||||
strategy: result.strategy,
|
||||
additions: result.additions
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Expanded Prompt');
|
||||
await pretty.plain(result.expanded);
|
||||
await pretty.newline();
|
||||
await pretty.dim(`Strategy: ${result.strategy}`);
|
||||
await pretty.success(`Completed in ${duration}ms`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Providers command - List available LLM providers
|
||||
*/
|
||||
|
||||
import { getAvailableProviders } from '../../llm/providers';
|
||||
import { hasApiKey } from '../runtime/env';
|
||||
import { outputJson, formatSuccess } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
|
||||
export interface ProvidersOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
interface ProviderInfo {
|
||||
name: string;
|
||||
available: boolean;
|
||||
hasApiKey: boolean;
|
||||
models?: string[];
|
||||
}
|
||||
|
||||
const PROVIDER_MODELS: Record<string, string[]> = {
|
||||
openai: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'],
|
||||
anthropic: ['claude-sonnet-4-20250514', 'claude-3-5-sonnet-20241022', 'claude-3-opus-20240229', 'claude-3-haiku-20240307'],
|
||||
google: ['gemini-2.0-flash', 'gemini-1.5-pro', 'gemini-1.5-flash']
|
||||
};
|
||||
|
||||
export async function execute(args: string[], options: ProvidersOptions): Promise<void> {
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
const availableProviders = getAvailableProviders();
|
||||
|
||||
const providers: ProviderInfo[] = [
|
||||
{
|
||||
name: 'openai',
|
||||
available: availableProviders.includes('openai'),
|
||||
hasApiKey: hasApiKey('openai'),
|
||||
models: PROVIDER_MODELS.openai
|
||||
},
|
||||
{
|
||||
name: 'anthropic',
|
||||
available: availableProviders.includes('anthropic'),
|
||||
hasApiKey: hasApiKey('anthropic'),
|
||||
models: PROVIDER_MODELS.anthropic
|
||||
},
|
||||
{
|
||||
name: 'google',
|
||||
available: availableProviders.includes('google'),
|
||||
hasApiKey: hasApiKey('google'),
|
||||
models: PROVIDER_MODELS.google
|
||||
}
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
providers: providers.map(p => ({
|
||||
name: p.name,
|
||||
available: p.available,
|
||||
has_api_key: p.hasApiKey,
|
||||
models: options.verbose ? p.models : undefined
|
||||
}))
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Available Providers');
|
||||
|
||||
for (const provider of providers) {
|
||||
const status = provider.available ? '✅' : '❌';
|
||||
const keyStatus = provider.hasApiKey ? '🔑' : '⚠️ No API key';
|
||||
|
||||
await pretty.plain(` ${status} ${provider.name} ${keyStatus}`);
|
||||
|
||||
if (options.verbose && provider.models) {
|
||||
for (const model of provider.models) {
|
||||
await pretty.dim(` - ${model}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await pretty.newline();
|
||||
await pretty.info('Set API keys via environment variables:');
|
||||
await pretty.dim(' OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Query Rewrite command - Rewrite queries for better search results
|
||||
*/
|
||||
|
||||
import { createQueryRewriterAgent } from '../../agent/query-rewriter';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface QueryRewriteOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
strategy?: string;
|
||||
count?: number;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: QueryRewriteOptions): Promise<void> {
|
||||
const query = args.join(' ');
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
const config = resolveConfig(options);
|
||||
|
||||
if (!query) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a query to rewrite'));
|
||||
} else {
|
||||
await pretty.error('Please provide a query to rewrite');
|
||||
await pretty.dim('Usage: praisonai-ts query-rewrite "your search query"');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Rewriting query: "${query}"`);
|
||||
}
|
||||
|
||||
const agent = createQueryRewriterAgent({
|
||||
llm: config.model,
|
||||
verbose: options.verbose,
|
||||
defaultStrategy: options.strategy as any
|
||||
});
|
||||
|
||||
const result = await agent.rewrite(query);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
originalQuery: query,
|
||||
rewrittenQueries: result.rewritten,
|
||||
strategy: result.strategy,
|
||||
confidence: result.confidence
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Rewritten Queries');
|
||||
for (let i = 0; i < result.rewritten.length; i++) {
|
||||
await pretty.plain(` ${i + 1}. ${result.rewritten[i]}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.dim(`Strategy: ${result.strategy}`);
|
||||
await pretty.success(`Completed in ${duration}ms`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* CLI command: repo-map
|
||||
* Repository structure visualization and symbol extraction
|
||||
*/
|
||||
|
||||
import { RepoMap, createRepoMap, getRepoTree } from '../features/repo-map';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'tree';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'tree':
|
||||
await handleTree(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'symbols':
|
||||
await handleSymbols(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
if (subcommand !== 'help' && !subcommand.startsWith('-')) {
|
||||
// Treat as path for tree command
|
||||
await handleTree([subcommand, ...args.slice(1)], options, isJson);
|
||||
} else {
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTree(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const rootPath = args[0] || process.cwd();
|
||||
const maxDepth = (options.depth as number) || 5;
|
||||
const includeSymbols = Boolean(options.symbols);
|
||||
|
||||
const map = createRepoMap({
|
||||
rootPath,
|
||||
maxDepth,
|
||||
includeSymbols
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await map.generate();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({
|
||||
success: true,
|
||||
root: result.root,
|
||||
totalFiles: result.totalFiles,
|
||||
totalDirectories: result.totalDirectories,
|
||||
symbolCount: result.symbols.length
|
||||
}, null, 2));
|
||||
} else {
|
||||
console.log(result.summary);
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: error.message }));
|
||||
} else {
|
||||
console.error(`Error: ${error.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSymbols(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const rootPath = args[0] || process.cwd();
|
||||
const maxDepth = (options.depth as number) || 5;
|
||||
|
||||
const map = createRepoMap({
|
||||
rootPath,
|
||||
maxDepth,
|
||||
includeSymbols: true
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await map.generate();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({
|
||||
success: true,
|
||||
symbols: result.symbols,
|
||||
count: result.symbols.length
|
||||
}, null, 2));
|
||||
} else {
|
||||
console.log(`Symbols in ${rootPath}:\n`);
|
||||
|
||||
const byType: Record<string, typeof result.symbols> = {};
|
||||
for (const sym of result.symbols) {
|
||||
if (!byType[sym.type]) byType[sym.type] = [];
|
||||
byType[sym.type].push(sym);
|
||||
}
|
||||
|
||||
for (const [type, symbols] of Object.entries(byType)) {
|
||||
console.log(`${type}s (${symbols.length}):`);
|
||||
for (const sym of symbols.slice(0, 20)) {
|
||||
const exported = sym.exported ? ' [exported]' : '';
|
||||
console.log(` ${sym.name}${exported} (line ${sym.line})`);
|
||||
}
|
||||
if (symbols.length > 20) {
|
||||
console.log(` ... and ${symbols.length - 20} more`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: error.message }));
|
||||
} else {
|
||||
console.error(`Error: ${error.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'repo-map',
|
||||
description: 'Repository structure visualization and symbol extraction',
|
||||
subcommands: {
|
||||
tree: 'Show repository tree structure',
|
||||
symbols: 'Extract and list code symbols'
|
||||
},
|
||||
flags: {
|
||||
'--depth': 'Maximum directory depth (default: 5)',
|
||||
'--symbols': 'Include symbols in tree output',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts repo-map',
|
||||
'praisonai-ts repo-map tree ./src',
|
||||
'praisonai-ts repo-map tree --depth 3',
|
||||
'praisonai-ts repo-map symbols ./src',
|
||||
'praisonai-ts repo-map tree --symbols'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Repo Map - Repository visualization\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Reranker command - Document reranking
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface RerankerOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
provider?: string;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: RerankerOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'providers':
|
||||
await listProviders(outputFormat);
|
||||
break;
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Reranker',
|
||||
description: 'Rerank search results for improved relevance',
|
||||
providers: [
|
||||
{ name: 'CohereReranker', description: 'Cohere reranking API' },
|
||||
{ name: 'CrossEncoderReranker', description: 'Cross-encoder model reranking' },
|
||||
{ name: 'LLMReranker', description: 'LLM-based reranking' }
|
||||
],
|
||||
capabilities: [
|
||||
'Rerank search results by relevance',
|
||||
'Improve RAG retrieval quality',
|
||||
'Multiple reranking strategies',
|
||||
'Configurable top-k selection'
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Reranker');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Providers:');
|
||||
for (const p of info.providers) {
|
||||
await pretty.plain(` • ${p.name}: ${p.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Capabilities:');
|
||||
for (const cap of info.capabilities) {
|
||||
await pretty.plain(` • ${cap}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listProviders(outputFormat: string): Promise<void> {
|
||||
const providers = [
|
||||
{ name: 'cohere', description: 'Cohere reranking API', available: true },
|
||||
{ name: 'cross-encoder', description: 'Cross-encoder model', available: true },
|
||||
{ name: 'llm', description: 'LLM-based reranking', available: true }
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ providers }));
|
||||
} else {
|
||||
await pretty.heading('Reranker Providers');
|
||||
for (const p of providers) {
|
||||
const status = p.available ? '✓' : '✗';
|
||||
await pretty.plain(` ${status} ${p.name.padEnd(15)} ${p.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'reranker',
|
||||
description: 'Document reranking for improved search relevance',
|
||||
subcommands: [
|
||||
{ name: 'info', description: 'Show reranker feature information' },
|
||||
{ name: 'providers', description: 'List available reranker providers' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Reranker Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Research command - Deep research agent
|
||||
*/
|
||||
|
||||
import { createDeepResearchAgent } from '../../agent/research';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface ResearchOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
depth?: number;
|
||||
maxSources?: number;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: ResearchOptions): Promise<void> {
|
||||
const query = args.join(' ');
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
const config = resolveConfig(options);
|
||||
|
||||
if (!query) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a research query'));
|
||||
} else {
|
||||
await pretty.error('Please provide a research query');
|
||||
await pretty.dim('Usage: praisonai-ts research "What are the latest AI trends?"');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Researching: "${query}"`);
|
||||
}
|
||||
|
||||
const agent = createDeepResearchAgent({
|
||||
llm: config.model,
|
||||
verbose: options.verbose,
|
||||
maxIterations: options.depth
|
||||
});
|
||||
|
||||
const result = await agent.research(query);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
query,
|
||||
answer: result.answer,
|
||||
citations: result.citations,
|
||||
reasoning: result.reasoning,
|
||||
confidence: result.confidence
|
||||
}, {
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Research Results');
|
||||
await pretty.newline();
|
||||
await pretty.plain(result.answer);
|
||||
|
||||
if (result.citations && result.citations.length > 0) {
|
||||
await pretty.newline();
|
||||
await pretty.plain('Citations:');
|
||||
for (const citation of result.citations) {
|
||||
await pretty.dim(` • ${citation.title || citation.url}`);
|
||||
}
|
||||
}
|
||||
|
||||
await pretty.newline();
|
||||
await pretty.success(`Completed in ${duration}ms`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Router command - Route requests to appropriate agents
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface RouterOptions {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
routes?: string;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: RouterOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'analyze':
|
||||
await analyzeInput(actionArgs, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function analyzeInput(args: string[], outputFormat: string): Promise<void> {
|
||||
const input = args.join(' ');
|
||||
if (!input) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide input to analyze'));
|
||||
} else {
|
||||
await pretty.error('Please provide input to analyze');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Analyzing routing for: "${input}"`);
|
||||
}
|
||||
|
||||
// Simple rule-based routing analysis
|
||||
const routes = [
|
||||
{ name: 'greeting', pattern: /\b(hello|hi|hey|greetings)\b/i, priority: 1 },
|
||||
{ name: 'question', pattern: /\?$/, priority: 2 },
|
||||
{ name: 'code', pattern: /\b(code|function|class|implement|debug)\b/i, priority: 3 },
|
||||
{ name: 'research', pattern: /\b(research|analyze|investigate|study)\b/i, priority: 3 },
|
||||
{ name: 'creative', pattern: /\b(write|create|generate|compose)\b/i, priority: 2 },
|
||||
{ name: 'general', pattern: /.*/, priority: 0 }
|
||||
];
|
||||
|
||||
const matches = routes
|
||||
.filter(r => r.pattern.test(input))
|
||||
.sort((a, b) => b.priority - a.priority);
|
||||
|
||||
const selectedRoute = matches[0]?.name || 'general';
|
||||
const confidence = matches[0]?.priority ? Math.min(0.5 + matches[0].priority * 0.15, 0.95) : 0.5;
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
input,
|
||||
selectedRoute,
|
||||
confidence,
|
||||
matchedRoutes: matches.map(m => m.name)
|
||||
}, {
|
||||
duration_ms: duration
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Routing Analysis');
|
||||
await pretty.plain(`Input: "${input}"`);
|
||||
await pretty.plain(`Selected Route: ${selectedRoute}`);
|
||||
await pretty.plain(`Confidence: ${(confidence * 100).toFixed(1)}%`);
|
||||
await pretty.plain(`Matched Routes: ${matches.map(m => m.name).join(', ')}`);
|
||||
await pretty.newline();
|
||||
await pretty.success(`Analyzed in ${duration}ms`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'router',
|
||||
description: 'Route requests to appropriate agents based on content analysis',
|
||||
subcommands: [
|
||||
{ name: 'analyze <input>', description: 'Analyze input and suggest routing' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
usage: 'For programmatic routing with actual agents, use the RouterAgent SDK class'
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Router Command');
|
||||
await pretty.plain('Route requests to appropriate agents\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(25)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.dim('Note: For full routing with agents, use the RouterAgent SDK class');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Run command - Run an agent with a task
|
||||
*/
|
||||
|
||||
import { Agent } from '../../agent';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { printSuccess, printError, outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES, normalizeError } from '../output/errors';
|
||||
|
||||
export interface RunOptions {
|
||||
agent?: string;
|
||||
tools?: string;
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
profile?: string;
|
||||
config?: string;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: RunOptions): Promise<void> {
|
||||
const task = args[0];
|
||||
|
||||
if (!task) {
|
||||
if (options.json || options.output === 'json') {
|
||||
printError(ERROR_CODES.MISSING_ARG, 'Please provide a task');
|
||||
} else {
|
||||
await pretty.error('Please provide a task');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
// Resolve config with precedence
|
||||
const config = resolveConfig({
|
||||
configPath: options.config,
|
||||
profile: options.profile,
|
||||
model: options.model,
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const startTime = Date.now();
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
// Parse tools if provided
|
||||
const tools: string[] = options.tools ? options.tools.split(',').map(t => t.trim()) : [];
|
||||
|
||||
// Create agent
|
||||
const agent = new Agent({
|
||||
name: 'CLI Agent',
|
||||
instructions: 'You are a helpful AI assistant.',
|
||||
llm: config.model,
|
||||
verbose: config.verbose
|
||||
});
|
||||
|
||||
// Execute task
|
||||
const result = await agent.start(task);
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(
|
||||
{
|
||||
result: result,
|
||||
agent: 'CLI Agent',
|
||||
task: task
|
||||
},
|
||||
{
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}
|
||||
));
|
||||
} else {
|
||||
if (typeof result === 'string') {
|
||||
console.log(result);
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
const cliError = normalizeError(error);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(cliError.code, cliError.message, cliError.details));
|
||||
} else {
|
||||
await pretty.error(cliError.message);
|
||||
if (config.verbose && error instanceof Error && error.stack) {
|
||||
await pretty.dim(error.stack);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(cliError.exitCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* CLI command: sandbox
|
||||
* Safe command execution with restrictions
|
||||
*/
|
||||
|
||||
import { SandboxExecutor, createSandboxExecutor, CommandValidator, type SandboxMode } from '../features/sandbox-executor';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'exec':
|
||||
await handleExec(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'check':
|
||||
await handleCheck(args.slice(1), isJson);
|
||||
break;
|
||||
case 'mode':
|
||||
await handleMode(args.slice(1), isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExec(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const command = args.join(' ');
|
||||
if (!command) {
|
||||
console.error('Error: Command is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mode = (options.mode as SandboxMode) || 'basic';
|
||||
const timeout = (options.timeout as number) || 30000;
|
||||
|
||||
const executor = createSandboxExecutor({ mode, timeout });
|
||||
const result = await executor.execute(command);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
if (result.success) {
|
||||
console.log('✓ Command executed successfully');
|
||||
console.log(`Duration: ${result.duration}ms`);
|
||||
if (result.stdout) {
|
||||
console.log('\nOutput:');
|
||||
console.log(result.stdout);
|
||||
}
|
||||
} else {
|
||||
console.error('✗ Command failed');
|
||||
if (result.stderr) console.error(result.stderr);
|
||||
}
|
||||
}
|
||||
|
||||
if (!result.success) process.exit(result.exitCode || 1);
|
||||
}
|
||||
|
||||
async function handleCheck(args: string[], isJson: boolean): Promise<void> {
|
||||
const command = args.join(' ');
|
||||
if (!command) {
|
||||
console.error('Error: Command is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const validator = new CommandValidator();
|
||||
const result = validator.validate(command);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ command, ...result }, null, 2));
|
||||
} else {
|
||||
if (result.valid) {
|
||||
console.log(`✓ Command is allowed: ${command}`);
|
||||
} else {
|
||||
console.log(`✗ Command blocked: ${command}`);
|
||||
console.log(` Reason: ${result.reason}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMode(args: string[], isJson: boolean): Promise<void> {
|
||||
const modes: Record<SandboxMode, string> = {
|
||||
disabled: 'No execution allowed',
|
||||
basic: 'Basic validation, blocks dangerous patterns',
|
||||
strict: 'Minimal environment, restricted PATH',
|
||||
'network-isolated': 'No network access (proxy blocked)'
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, modes }, null, 2));
|
||||
} else {
|
||||
console.log('Sandbox Modes:\n');
|
||||
for (const [mode, desc] of Object.entries(modes)) {
|
||||
console.log(` ${mode.padEnd(18)} ${desc}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'sandbox',
|
||||
description: 'Safe command execution with restrictions',
|
||||
subcommands: {
|
||||
exec: 'Execute a command in sandbox',
|
||||
check: 'Check if a command would be allowed',
|
||||
mode: 'List available sandbox modes'
|
||||
},
|
||||
flags: {
|
||||
'--mode': 'Sandbox mode (disabled, basic, strict, network-isolated)',
|
||||
'--timeout': 'Execution timeout in ms (default: 30000)',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts sandbox exec "ls -la"',
|
||||
'praisonai-ts sandbox exec "npm install" --mode strict',
|
||||
'praisonai-ts sandbox check "rm -rf /"',
|
||||
'praisonai-ts sandbox mode'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Sandbox - Safe command execution\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* CLI command: scheduler
|
||||
* Agent task scheduling with cron-like patterns
|
||||
*/
|
||||
|
||||
import { Scheduler, createScheduler, cronExpressions } from '../features/scheduler';
|
||||
|
||||
export async function execute(args: string[], options: Record<string, unknown>): Promise<void> {
|
||||
const subcommand = args[0] || 'help';
|
||||
const isJson = Boolean(options.output === 'json' || options.json);
|
||||
|
||||
switch (subcommand) {
|
||||
case 'create':
|
||||
await handleCreate(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'list':
|
||||
await handleList(options, isJson);
|
||||
break;
|
||||
case 'run':
|
||||
await handleRun(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'remove':
|
||||
await handleRemove(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'enable':
|
||||
await handleEnable(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'disable':
|
||||
await handleDisable(args.slice(1), options, isJson);
|
||||
break;
|
||||
case 'patterns':
|
||||
await handlePatterns(isJson);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
showHelp(isJson);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreate(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const name = args[0];
|
||||
const cron = options.cron as string | undefined;
|
||||
const interval = options.interval as number | undefined;
|
||||
|
||||
if (!name) {
|
||||
const error = { error: 'Task name is required' };
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(error));
|
||||
} else {
|
||||
console.error('Error: Task name is required');
|
||||
console.log('Usage: praisonai-ts scheduler create <name> --cron "* * * * *"');
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!cron && !interval) {
|
||||
const error = { error: 'Either --cron or --interval is required' };
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(error));
|
||||
} else {
|
||||
console.error('Error: Either --cron or --interval is required');
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const scheduler = createScheduler();
|
||||
const id = scheduler.add({
|
||||
name,
|
||||
cron,
|
||||
interval: interval ? interval * 1000 : undefined,
|
||||
task: async () => {
|
||||
console.log(`Task ${name} executed at ${new Date().toISOString()}`);
|
||||
return { executed: true };
|
||||
}
|
||||
});
|
||||
|
||||
const result = {
|
||||
success: true,
|
||||
id,
|
||||
name,
|
||||
cron,
|
||||
interval,
|
||||
message: `Task '${name}' created with ID: ${id}`
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Task '${name}' created`);
|
||||
console.log(` ID: ${id}`);
|
||||
if (cron) console.log(` Cron: ${cron}`);
|
||||
if (interval) console.log(` Interval: ${interval}s`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const scheduler = createScheduler();
|
||||
const tasks = scheduler.getAllTasks();
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, tasks }, null, 2));
|
||||
} else {
|
||||
if (tasks.length === 0) {
|
||||
console.log('No scheduled tasks');
|
||||
} else {
|
||||
console.log('Scheduled Tasks:');
|
||||
for (const task of tasks) {
|
||||
console.log(` ${task.name} (${task.id})`);
|
||||
console.log(` Status: ${task.status}`);
|
||||
console.log(` Enabled: ${task.enabled}`);
|
||||
console.log(` Run count: ${task.runCount}`);
|
||||
if (task.nextRun) console.log(` Next run: ${task.nextRun.toISOString()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRun(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Task ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const scheduler = createScheduler();
|
||||
try {
|
||||
const result = await scheduler.runNow(id);
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, result }, null, 2));
|
||||
} else {
|
||||
console.log(`✓ Task ${id} executed successfully`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: false, error: error.message }));
|
||||
} else {
|
||||
console.error(`Error: ${error.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemove(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Task ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const scheduler = createScheduler();
|
||||
const removed = scheduler.remove(id);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: removed, id }));
|
||||
} else {
|
||||
if (removed) {
|
||||
console.log(`✓ Task ${id} removed`);
|
||||
} else {
|
||||
console.error(`Task ${id} not found`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleEnable(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Task ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const scheduler = createScheduler();
|
||||
const enabled = scheduler.enable(id);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: enabled, id }));
|
||||
} else {
|
||||
console.log(enabled ? `✓ Task ${id} enabled` : `Task ${id} not found`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDisable(args: string[], options: Record<string, unknown>, isJson: boolean): Promise<void> {
|
||||
const id = args[0];
|
||||
if (!id) {
|
||||
console.error('Error: Task ID is required');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const scheduler = createScheduler();
|
||||
const disabled = scheduler.disable(id);
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: disabled, id }));
|
||||
} else {
|
||||
console.log(disabled ? `✓ Task ${id} disabled` : `Task ${id} not found`);
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePatterns(isJson: boolean): Promise<void> {
|
||||
const patterns = {
|
||||
everyMinute: cronExpressions.everyMinute,
|
||||
every5Minutes: cronExpressions.every5Minutes,
|
||||
every15Minutes: cronExpressions.every15Minutes,
|
||||
everyHour: cronExpressions.everyHour,
|
||||
everyDay: cronExpressions.everyDay,
|
||||
everyWeek: cronExpressions.everyWeek,
|
||||
everyMonth: cronExpressions.everyMonth,
|
||||
weekdays: cronExpressions.weekdays,
|
||||
weekends: cronExpressions.weekends
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify({ success: true, patterns }, null, 2));
|
||||
} else {
|
||||
console.log('Common Cron Patterns:');
|
||||
for (const [name, pattern] of Object.entries(patterns)) {
|
||||
console.log(` ${name}: ${pattern}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showHelp(isJson: boolean): void {
|
||||
const help = {
|
||||
command: 'scheduler',
|
||||
description: 'Agent task scheduling with cron-like patterns',
|
||||
subcommands: {
|
||||
create: 'Create a scheduled task',
|
||||
list: 'List all scheduled tasks',
|
||||
run: 'Run a task immediately',
|
||||
remove: 'Remove a scheduled task',
|
||||
enable: 'Enable a task',
|
||||
disable: 'Disable a task',
|
||||
patterns: 'Show common cron patterns'
|
||||
},
|
||||
flags: {
|
||||
'--cron': 'Cron expression (e.g., "*/5 * * * *")',
|
||||
'--interval': 'Interval in seconds',
|
||||
'--json': 'Output in JSON format'
|
||||
},
|
||||
examples: [
|
||||
'praisonai-ts scheduler create my-task --cron "*/5 * * * *"',
|
||||
'praisonai-ts scheduler create backup --interval 3600',
|
||||
'praisonai-ts scheduler list',
|
||||
'praisonai-ts scheduler run <task-id>',
|
||||
'praisonai-ts scheduler patterns'
|
||||
]
|
||||
};
|
||||
|
||||
if (isJson) {
|
||||
console.log(JSON.stringify(help, null, 2));
|
||||
} else {
|
||||
console.log('Scheduler - Agent task scheduling\n');
|
||||
console.log('Subcommands:');
|
||||
for (const [cmd, desc] of Object.entries(help.subcommands)) {
|
||||
console.log(` ${cmd.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nFlags:');
|
||||
for (const [flag, desc] of Object.entries(help.flags)) {
|
||||
console.log(` ${flag.padEnd(12)} ${desc}`);
|
||||
}
|
||||
console.log('\nExamples:');
|
||||
for (const ex of help.examples) {
|
||||
console.log(` ${ex}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* Session command - Manage agent sessions
|
||||
*/
|
||||
|
||||
import { Session, SessionManager, getSessionManager } from '../../session';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface SessionOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: SessionOptions): Promise<void> {
|
||||
const action = args[0] || 'list';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
const manager = getSessionManager();
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
await listSessions(manager, outputFormat);
|
||||
break;
|
||||
case 'create':
|
||||
await createSession(manager, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'get':
|
||||
await getSession(manager, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'delete':
|
||||
await deleteSession(manager, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'export':
|
||||
await exportSession(manager, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function listSessions(manager: SessionManager, outputFormat: string): Promise<void> {
|
||||
const sessions = manager.list();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
sessions: sessions.map((s: Session) => ({
|
||||
id: s.id,
|
||||
messageCount: s.messages.length,
|
||||
createdAt: s.createdAt
|
||||
})),
|
||||
count: sessions.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Sessions');
|
||||
if (sessions.length === 0) {
|
||||
await pretty.info('No sessions found');
|
||||
} else {
|
||||
for (const session of sessions) {
|
||||
await pretty.plain(` • ${session.id}`);
|
||||
await pretty.dim(` Messages: ${session.messages.length}`);
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Total: ${sessions.length} sessions`);
|
||||
}
|
||||
}
|
||||
|
||||
async function createSession(manager: SessionManager, args: string[], outputFormat: string): Promise<void> {
|
||||
const sessionId = args[0];
|
||||
const session = manager.create({ id: sessionId });
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
created: true,
|
||||
sessionId: session.id
|
||||
}));
|
||||
} else {
|
||||
await pretty.success(`Session created: ${session.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function getSession(manager: SessionManager, args: string[], outputFormat: string): Promise<void> {
|
||||
const sessionId = args[0];
|
||||
if (!sessionId) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a session ID'));
|
||||
} else {
|
||||
await pretty.error('Please provide a session ID');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const session = manager.get(sessionId);
|
||||
if (!session) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, `Session not found: ${sessionId}`));
|
||||
} else {
|
||||
await pretty.error(`Session not found: ${sessionId}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
|
||||
const messages = session.messages;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
id: session.id,
|
||||
messages,
|
||||
messageCount: messages.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading(`Session: ${session.id}`);
|
||||
await pretty.plain(`Messages: ${messages.length}`);
|
||||
await pretty.newline();
|
||||
for (const msg of messages.slice(-10)) {
|
||||
const content = msg.content || '';
|
||||
await pretty.plain(` [${msg.role}] ${content.substring(0, 80)}${content.length > 80 ? '...' : ''}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSession(manager: SessionManager, args: string[], outputFormat: string): Promise<void> {
|
||||
const sessionId = args[0];
|
||||
if (!sessionId) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a session ID'));
|
||||
} else {
|
||||
await pretty.error('Please provide a session ID');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const deleted = manager.delete(sessionId);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ deleted, sessionId }));
|
||||
} else {
|
||||
if (deleted) {
|
||||
await pretty.success(`Session deleted: ${sessionId}`);
|
||||
} else {
|
||||
await pretty.warn(`Session not found: ${sessionId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function exportSession(manager: SessionManager, args: string[], outputFormat: string): Promise<void> {
|
||||
const sessionId = args[0];
|
||||
if (!sessionId) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a session ID'));
|
||||
} else {
|
||||
await pretty.error('Please provide a session ID');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const session = manager.get(sessionId);
|
||||
if (!session) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, `Session not found: ${sessionId}`));
|
||||
} else {
|
||||
await pretty.error(`Session not found: ${sessionId}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
|
||||
const exported = session.toJSON();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(exported));
|
||||
} else {
|
||||
console.log(JSON.stringify(exported, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'session',
|
||||
subcommands: [
|
||||
{ name: 'list', description: 'List all sessions' },
|
||||
{ name: 'create [id]', description: 'Create a new session' },
|
||||
{ name: 'get <id>', description: 'Get session details' },
|
||||
{ name: 'delete <id>', description: 'Delete a session' },
|
||||
{ name: 'export <id>', description: 'Export session data' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Session Command');
|
||||
await pretty.plain('Manage agent sessions\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* Skills command - Manage agent skills
|
||||
*/
|
||||
|
||||
import { SkillManager, createSkillManager, Skill } from '../../skills';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface SkillsOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: SkillsOptions): Promise<void> {
|
||||
const action = args[0] || 'list';
|
||||
const actionArgs = args.slice(1);
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
const searchPath = actionArgs[0] || '.';
|
||||
const manager = createSkillManager({ paths: [searchPath] });
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
await listSkills(manager, outputFormat);
|
||||
break;
|
||||
case 'discover':
|
||||
await discoverSkills(manager, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'validate':
|
||||
await validateSkill(manager, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'info':
|
||||
await skillInfo(manager, actionArgs, outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function listSkills(manager: SkillManager, outputFormat: string): Promise<void> {
|
||||
const skills = manager.list();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
skills: skills.map((s: Skill) => ({
|
||||
name: s.metadata.name,
|
||||
description: s.metadata.description,
|
||||
path: s.path
|
||||
})),
|
||||
count: skills.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Available Skills');
|
||||
if (skills.length === 0) {
|
||||
await pretty.info('No skills loaded');
|
||||
await pretty.dim('Run "praisonai-ts skills discover <path>" to discover skills');
|
||||
} else {
|
||||
for (const skill of skills) {
|
||||
await pretty.plain(` • ${skill.metadata.name}`);
|
||||
if (skill.metadata.description) {
|
||||
await pretty.dim(` ${skill.metadata.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Total: ${skills.length} skills`);
|
||||
}
|
||||
}
|
||||
|
||||
async function discoverSkills(manager: SkillManager, args: string[], outputFormat: string): Promise<void> {
|
||||
const searchPath = args[0] || '.';
|
||||
|
||||
const discovered = await manager.discover();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
discovered: discovered.map((s: Skill) => ({
|
||||
name: s.metadata.name,
|
||||
description: s.metadata.description,
|
||||
path: s.path
|
||||
})),
|
||||
count: discovered.length,
|
||||
searchPath
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading(`Discovered Skills in: ${searchPath}`);
|
||||
if (discovered.length === 0) {
|
||||
await pretty.info('No skills found');
|
||||
} else {
|
||||
for (const skill of discovered) {
|
||||
await pretty.plain(` • ${skill.metadata.name}`);
|
||||
if (skill.metadata.description) {
|
||||
await pretty.dim(` ${skill.metadata.description}`);
|
||||
}
|
||||
if (skill.path) {
|
||||
await pretty.dim(` Path: ${skill.path}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.info(`Found: ${discovered.length} skills`);
|
||||
}
|
||||
}
|
||||
|
||||
async function validateSkill(manager: SkillManager, args: string[], outputFormat: string): Promise<void> {
|
||||
const skillPath = args[0];
|
||||
if (!skillPath) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a skill path'));
|
||||
} else {
|
||||
await pretty.error('Please provide a skill path');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
try {
|
||||
// Load the skill first, then validate
|
||||
const skill = await manager.loadSkill(skillPath);
|
||||
const result = manager.validate(skill);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
valid: result.valid,
|
||||
path: skillPath,
|
||||
errors: result.errors || []
|
||||
}));
|
||||
} else {
|
||||
if (result.valid) {
|
||||
await pretty.success(`Skill is valid: ${skillPath}`);
|
||||
} else {
|
||||
await pretty.error(`Skill validation failed: ${skillPath}`);
|
||||
if (result.errors) {
|
||||
for (const err of result.errors) {
|
||||
await pretty.plain(` ❌ ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(`Validation error: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function skillInfo(manager: SkillManager, args: string[], outputFormat: string): Promise<void> {
|
||||
const skillName = args[0];
|
||||
if (!skillName) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a skill name'));
|
||||
} else {
|
||||
await pretty.error('Please provide a skill name');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
const skill = manager.get(skillName);
|
||||
if (!skill) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, `Skill not found: ${skillName}`));
|
||||
} else {
|
||||
await pretty.error(`Skill not found: ${skillName}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
name: skill.metadata.name,
|
||||
description: skill.metadata.description,
|
||||
path: skill.path,
|
||||
metadata: skill.metadata
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading(`Skill: ${skill.metadata.name}`);
|
||||
await pretty.keyValue({
|
||||
'Name': skill.metadata.name,
|
||||
'Description': skill.metadata.description || 'No description',
|
||||
'Path': skill.path || 'N/A'
|
||||
});
|
||||
if (skill.metadata.metadata && Object.keys(skill.metadata.metadata).length > 0) {
|
||||
await pretty.newline();
|
||||
await pretty.plain('Metadata:');
|
||||
await pretty.plain(JSON.stringify(skill.metadata.metadata, null, 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'skills',
|
||||
subcommands: [
|
||||
{ name: 'list', description: 'List loaded skills' },
|
||||
{ name: 'discover <path>', description: 'Discover skills in directory' },
|
||||
{ name: 'validate <path>', description: 'Validate a skill' },
|
||||
{ name: 'info <name>', description: 'Show skill information' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Skills Command');
|
||||
await pretty.plain('Manage agent skills\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Telemetry command - Usage monitoring and analytics
|
||||
*/
|
||||
|
||||
import { getTelemetry, enableTelemetry, disableTelemetry, cleanupTelemetry } from '../../telemetry';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface TelemetryOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: TelemetryOptions): Promise<void> {
|
||||
const action = args[0] || 'status';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'enable':
|
||||
enableTelemetry();
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ enabled: true }));
|
||||
} else {
|
||||
await pretty.success('Telemetry enabled');
|
||||
}
|
||||
break;
|
||||
case 'disable':
|
||||
disableTelemetry();
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ enabled: false }));
|
||||
} else {
|
||||
await pretty.success('Telemetry disabled');
|
||||
}
|
||||
break;
|
||||
case 'status':
|
||||
await showStatus(outputFormat);
|
||||
break;
|
||||
case 'clear':
|
||||
cleanupTelemetry();
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ cleared: true }));
|
||||
} else {
|
||||
await pretty.success('Telemetry data cleared');
|
||||
}
|
||||
break;
|
||||
case 'export':
|
||||
await exportTelemetry(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showStatus(outputFormat: string): Promise<void> {
|
||||
const telemetry = getTelemetry();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
enabled: telemetry.isEnabled()
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Telemetry Status');
|
||||
await pretty.plain(`Enabled: ${telemetry.isEnabled() ? 'Yes' : 'No'}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function exportTelemetry(outputFormat: string): Promise<void> {
|
||||
const telemetry = getTelemetry();
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
enabled: telemetry.isEnabled(),
|
||||
exportedAt: new Date().toISOString()
|
||||
}));
|
||||
} else {
|
||||
await pretty.plain(`Telemetry enabled: ${telemetry.isEnabled()}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'telemetry',
|
||||
subcommands: [
|
||||
{ name: 'status', description: 'Show telemetry status' },
|
||||
{ name: 'enable', description: 'Enable telemetry collection' },
|
||||
{ name: 'disable', description: 'Disable telemetry collection' },
|
||||
{ name: 'clear', description: 'Clear collected telemetry data' },
|
||||
{ name: 'export', description: 'Export telemetry data' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Telemetry Command');
|
||||
await pretty.plain('Usage monitoring and analytics\n');
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(15)} ${cmd.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Tools command - List or manage tools
|
||||
*/
|
||||
|
||||
import { getRegistry, FunctionTool } from '../../tools/decorator';
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface ToolsOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
interface ToolInfo {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: unknown;
|
||||
}
|
||||
|
||||
// Built-in tools that are always available
|
||||
const BUILTIN_TOOLS: ToolInfo[] = [
|
||||
{ name: 'arxiv_search', description: 'Search arXiv for academic papers' },
|
||||
{ name: 'web_search', description: 'Search the web for information' },
|
||||
{ name: 'calculator', description: 'Perform mathematical calculations' },
|
||||
{ name: 'code_executor', description: 'Execute code snippets' },
|
||||
{ name: 'file_reader', description: 'Read file contents' },
|
||||
{ name: 'file_writer', description: 'Write content to files' }
|
||||
];
|
||||
|
||||
export async function execute(args: string[], options: ToolsOptions): Promise<void> {
|
||||
const subcommand = args[0] || 'list';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
switch (subcommand) {
|
||||
case 'list':
|
||||
await listTools(options, outputFormat);
|
||||
break;
|
||||
case 'info':
|
||||
await toolInfo(args.slice(1), options, outputFormat);
|
||||
break;
|
||||
default:
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.INVALID_ARGS, `Unknown subcommand: ${subcommand}`));
|
||||
} else {
|
||||
await pretty.error(`Unknown subcommand: ${subcommand}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
}
|
||||
|
||||
async function listTools(options: ToolsOptions, outputFormat: string): Promise<void> {
|
||||
// Get registered tools from registry
|
||||
const registry = getRegistry();
|
||||
const registeredTools = registry.list();
|
||||
|
||||
// Combine built-in and registered tools
|
||||
const allTools: ToolInfo[] = [
|
||||
...BUILTIN_TOOLS,
|
||||
...registeredTools.map((t: FunctionTool) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
parameters: t.parameters
|
||||
}))
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
tools: allTools.map(t => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
parameters: options.verbose ? t.parameters : undefined
|
||||
})),
|
||||
count: allTools.length
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading('Available Tools');
|
||||
|
||||
await pretty.plain('Built-in Tools:');
|
||||
for (const tool of BUILTIN_TOOLS) {
|
||||
await pretty.plain(` • ${tool.name}`);
|
||||
if (tool.description) {
|
||||
await pretty.dim(` ${tool.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (registeredTools.length > 0) {
|
||||
await pretty.newline();
|
||||
await pretty.plain('Registered Tools:');
|
||||
for (const tool of registeredTools) {
|
||||
await pretty.plain(` • ${tool.name}`);
|
||||
if (tool.description) {
|
||||
await pretty.dim(` ${tool.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await pretty.newline();
|
||||
await pretty.info(`Total: ${allTools.length} tools`);
|
||||
}
|
||||
}
|
||||
|
||||
async function toolInfo(args: string[], options: ToolsOptions, outputFormat: string): Promise<void> {
|
||||
const toolName = args[0];
|
||||
|
||||
if (!toolName) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.MISSING_ARG, 'Please provide a tool name'));
|
||||
} else {
|
||||
await pretty.error('Please provide a tool name');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
// Look for tool in built-in and registered tools
|
||||
const builtinTool = BUILTIN_TOOLS.find(t => t.name === toolName);
|
||||
const registry = getRegistry();
|
||||
const registeredTool = registry.get(toolName);
|
||||
|
||||
const tool = builtinTool || (registeredTool ? {
|
||||
name: registeredTool.name,
|
||||
description: registeredTool.description,
|
||||
parameters: registeredTool.parameters
|
||||
} : null);
|
||||
|
||||
if (!tool) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.TOOL_NOT_FOUND, `Tool not found: ${toolName}`));
|
||||
} else {
|
||||
await pretty.error(`Tool not found: ${toolName}`);
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({
|
||||
tool: {
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: tool.parameters,
|
||||
type: builtinTool ? 'builtin' : 'registered'
|
||||
}
|
||||
}));
|
||||
} else {
|
||||
await pretty.heading(`Tool: ${tool.name}`);
|
||||
await pretty.keyValue({
|
||||
'Name': tool.name,
|
||||
'Type': builtinTool ? 'Built-in' : 'Registered',
|
||||
'Description': tool.description || 'No description'
|
||||
});
|
||||
|
||||
if (tool.parameters && options.verbose) {
|
||||
await pretty.newline();
|
||||
await pretty.plain('Parameters:');
|
||||
await pretty.plain(JSON.stringify(tool.parameters, null, 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Vector command - Vector store management
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface VectorOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
store?: string;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: VectorOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'providers':
|
||||
await listProviders(outputFormat);
|
||||
break;
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Vector Stores',
|
||||
description: 'Vector database integrations for embeddings and similarity search',
|
||||
providers: [
|
||||
{ name: 'MemoryVectorStore', description: 'In-memory vector store for development' },
|
||||
{ name: 'PineconeVectorStore', description: 'Pinecone cloud vector database' },
|
||||
{ name: 'WeaviateVectorStore', description: 'Weaviate vector search engine' },
|
||||
{ name: 'QdrantVectorStore', description: 'Qdrant vector database' },
|
||||
{ name: 'ChromaVectorStore', description: 'ChromaDB embedding database' }
|
||||
],
|
||||
sdkUsage: `
|
||||
import { createMemoryVectorStore, createPineconeStore } from 'praisonai';
|
||||
|
||||
// Create a memory vector store
|
||||
const store = createMemoryVectorStore('my-store');
|
||||
|
||||
// Create index
|
||||
await store.createIndex({ indexName: 'docs', dimension: 1536 });
|
||||
|
||||
// Upsert vectors
|
||||
await store.upsert({
|
||||
indexName: 'docs',
|
||||
vectors: [{ id: '1', vector: [...], metadata: { text: 'Hello' } }]
|
||||
});
|
||||
|
||||
// Query
|
||||
const results = await store.query({
|
||||
indexName: 'docs',
|
||||
vector: [...],
|
||||
topK: 5
|
||||
});
|
||||
`
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Vector Stores');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Available Providers:');
|
||||
for (const p of info.providers) {
|
||||
await pretty.plain(` • ${p.name}: ${p.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.dim('Use the SDK for full vector store functionality');
|
||||
}
|
||||
}
|
||||
|
||||
async function listProviders(outputFormat: string): Promise<void> {
|
||||
const providers = [
|
||||
{ name: 'memory', description: 'In-memory vector store (default)', available: true },
|
||||
{ name: 'pinecone', description: 'Pinecone vector database', available: true },
|
||||
{ name: 'weaviate', description: 'Weaviate vector database', available: true },
|
||||
{ name: 'qdrant', description: 'Qdrant vector database', available: true },
|
||||
{ name: 'chroma', description: 'ChromaDB vector database', available: true }
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ providers }));
|
||||
} else {
|
||||
await pretty.heading('Vector Store Providers');
|
||||
for (const p of providers) {
|
||||
const status = p.available ? '✓' : '✗';
|
||||
await pretty.plain(` ${status} ${p.name.padEnd(15)} ${p.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'vector',
|
||||
description: 'Vector store management for embeddings and similarity search',
|
||||
subcommands: [
|
||||
{ name: 'add <content>', description: 'Add document to vector store' },
|
||||
{ name: 'search <query>', description: 'Search vector store' },
|
||||
{ name: 'stats', description: 'Show vector store statistics' },
|
||||
{ name: 'providers', description: 'List available vector store providers' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
flags: [
|
||||
{ name: '--store', description: 'Vector store provider (memory, pinecone, etc.)' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Vector Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(25)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Flags:');
|
||||
for (const flag of help.flags) {
|
||||
await pretty.plain(` ${flag.name.padEnd(20)} ${flag.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Version command - Show CLI version
|
||||
*/
|
||||
|
||||
import { CLI_SPEC_VERSION } from '../spec/cli-spec';
|
||||
import { outputJson, formatSuccess } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
|
||||
export interface VersionOptions {
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: VersionOptions): Promise<void> {
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
// Load package.json for version
|
||||
let packageVersion = '0.0.0';
|
||||
try {
|
||||
const pkg = require('../../../package.json');
|
||||
packageVersion = pkg.version;
|
||||
} catch {
|
||||
// Fallback if package.json not found
|
||||
}
|
||||
|
||||
const versionInfo = {
|
||||
version: packageVersion,
|
||||
cli_spec: CLI_SPEC_VERSION,
|
||||
runtime: 'node',
|
||||
node_version: process.version
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(versionInfo));
|
||||
} else {
|
||||
await pretty.plain(`praisonai-ts v${packageVersion}`);
|
||||
await pretty.dim(`CLI Spec: v${CLI_SPEC_VERSION}`);
|
||||
await pretty.dim(`Node: ${process.version}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Voice command - Text-to-speech and speech-to-text
|
||||
*/
|
||||
|
||||
import { outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES } from '../output/errors';
|
||||
|
||||
export interface VoiceOptions {
|
||||
verbose?: boolean;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
provider?: string;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: VoiceOptions): Promise<void> {
|
||||
const action = args[0] || 'help';
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'providers':
|
||||
await listProviders(outputFormat);
|
||||
break;
|
||||
case 'info':
|
||||
await showInfo(outputFormat);
|
||||
break;
|
||||
case 'help':
|
||||
default:
|
||||
await showHelp(outputFormat);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(ERROR_CODES.UNKNOWN, error instanceof Error ? error.message : String(error)));
|
||||
} else {
|
||||
await pretty.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async function showInfo(outputFormat: string): Promise<void> {
|
||||
const info = {
|
||||
feature: 'Voice',
|
||||
description: 'Text-to-speech and speech-to-text capabilities',
|
||||
providers: [
|
||||
{ name: 'OpenAIVoiceProvider', description: 'OpenAI TTS and Whisper' },
|
||||
{ name: 'ElevenLabsVoiceProvider', description: 'ElevenLabs voice synthesis' }
|
||||
],
|
||||
capabilities: [
|
||||
'Text-to-speech conversion',
|
||||
'Speech-to-text transcription',
|
||||
'Multiple voice options',
|
||||
'Streaming audio support'
|
||||
],
|
||||
sdkUsage: `
|
||||
import { createOpenAIVoice, createElevenLabsVoice } from 'praisonai';
|
||||
|
||||
// Create OpenAI voice provider
|
||||
const voice = createOpenAIVoice({ apiKey: process.env.OPENAI_API_KEY });
|
||||
|
||||
// Text to speech
|
||||
const audio = await voice.speak({ text: 'Hello world', voice: 'alloy' });
|
||||
|
||||
// Speech to text
|
||||
const text = await voice.listen({ audio: audioBuffer });
|
||||
`
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(info));
|
||||
} else {
|
||||
await pretty.heading('Voice');
|
||||
await pretty.plain(info.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Providers:');
|
||||
for (const p of info.providers) {
|
||||
await pretty.plain(` • ${p.name}: ${p.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Capabilities:');
|
||||
for (const cap of info.capabilities) {
|
||||
await pretty.plain(` • ${cap}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function listProviders(outputFormat: string): Promise<void> {
|
||||
const providers = [
|
||||
{ name: 'openai', description: 'OpenAI TTS and Whisper', available: true },
|
||||
{ name: 'elevenlabs', description: 'ElevenLabs voice synthesis', available: true }
|
||||
];
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess({ providers }));
|
||||
} else {
|
||||
await pretty.heading('Voice Providers');
|
||||
for (const p of providers) {
|
||||
const status = p.available ? '✓' : '✗';
|
||||
await pretty.plain(` ${status} ${p.name.padEnd(15)} ${p.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function showHelp(outputFormat: string): Promise<void> {
|
||||
const help = {
|
||||
command: 'voice',
|
||||
description: 'Text-to-speech and speech-to-text capabilities',
|
||||
subcommands: [
|
||||
{ name: 'info', description: 'Show voice feature information' },
|
||||
{ name: 'providers', description: 'List available voice providers' },
|
||||
{ name: 'help', description: 'Show this help' }
|
||||
],
|
||||
flags: [
|
||||
{ name: '--provider', description: 'Voice provider (openai, elevenlabs)' }
|
||||
]
|
||||
};
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(help));
|
||||
} else {
|
||||
await pretty.heading('Voice Command');
|
||||
await pretty.plain(help.description);
|
||||
await pretty.newline();
|
||||
await pretty.plain('Subcommands:');
|
||||
for (const cmd of help.subcommands) {
|
||||
await pretty.plain(` ${cmd.name.padEnd(20)} ${cmd.description}`);
|
||||
}
|
||||
await pretty.newline();
|
||||
await pretty.plain('Flags:');
|
||||
for (const flag of help.flags) {
|
||||
await pretty.plain(` ${flag.name.padEnd(20)} ${flag.description}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Workflow command - Execute a multi-agent workflow
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { resolveConfig } from '../config/resolve';
|
||||
import { printSuccess, printError, outputJson, formatSuccess, formatError } from '../output/json';
|
||||
import * as pretty from '../output/pretty';
|
||||
import { EXIT_CODES } from '../spec/cli-spec';
|
||||
import { ERROR_CODES, normalizeError } from '../output/errors';
|
||||
|
||||
export interface WorkflowOptions {
|
||||
parallel?: boolean;
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
profile?: string;
|
||||
config?: string;
|
||||
output?: 'json' | 'text' | 'pretty';
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
interface WorkflowStep {
|
||||
name: string;
|
||||
agent?: string;
|
||||
task?: string;
|
||||
depends_on?: string[];
|
||||
}
|
||||
|
||||
interface WorkflowDefinition {
|
||||
name?: string;
|
||||
description?: string;
|
||||
agents?: Record<string, any>;
|
||||
steps?: WorkflowStep[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple YAML parser for workflow files
|
||||
*/
|
||||
function parseWorkflowYaml(content: string): WorkflowDefinition {
|
||||
const result: WorkflowDefinition = {};
|
||||
const lines = content.split('\n');
|
||||
let currentSection: string | null = null;
|
||||
let currentItem: any = null;
|
||||
let currentKey: string | null = null;
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.trim() || line.trim().startsWith('#')) continue;
|
||||
|
||||
const indent = line.search(/\S/);
|
||||
const trimmed = line.trim();
|
||||
|
||||
// Top-level keys
|
||||
if (indent === 0 && trimmed.includes(':')) {
|
||||
const colonIdx = trimmed.indexOf(':');
|
||||
const key = trimmed.slice(0, colonIdx).trim();
|
||||
const value = trimmed.slice(colonIdx + 1).trim();
|
||||
|
||||
if (value) {
|
||||
(result as any)[key] = value;
|
||||
} else {
|
||||
currentSection = key;
|
||||
if (key === 'agents') result.agents = {};
|
||||
if (key === 'steps') result.steps = [];
|
||||
}
|
||||
} else if (indent > 0 && currentSection) {
|
||||
// Handle list items (steps)
|
||||
if (trimmed.startsWith('- ')) {
|
||||
if (currentSection === 'steps') {
|
||||
currentItem = {};
|
||||
result.steps!.push(currentItem);
|
||||
|
||||
// Parse inline values after -
|
||||
const afterDash = trimmed.slice(2).trim();
|
||||
if (afterDash.includes(':')) {
|
||||
const colonIdx = afterDash.indexOf(':');
|
||||
const key = afterDash.slice(0, colonIdx).trim();
|
||||
const value = afterDash.slice(colonIdx + 1).trim();
|
||||
currentItem[key] = value;
|
||||
}
|
||||
}
|
||||
} else if (trimmed.includes(':') && currentItem) {
|
||||
const colonIdx = trimmed.indexOf(':');
|
||||
const key = trimmed.slice(0, colonIdx).trim();
|
||||
const value = trimmed.slice(colonIdx + 1).trim();
|
||||
currentItem[key] = value || [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function execute(args: string[], options: WorkflowOptions): Promise<void> {
|
||||
const workflowFile = args[0];
|
||||
|
||||
if (!workflowFile) {
|
||||
if (options.json || options.output === 'json') {
|
||||
printError(ERROR_CODES.MISSING_ARG, 'Please provide a workflow file path');
|
||||
} else {
|
||||
await pretty.error('Please provide a workflow file path');
|
||||
}
|
||||
process.exit(EXIT_CODES.INVALID_ARGUMENTS);
|
||||
}
|
||||
|
||||
// Resolve config
|
||||
const config = resolveConfig({
|
||||
configPath: options.config,
|
||||
profile: options.profile,
|
||||
model: options.model,
|
||||
verbose: options.verbose
|
||||
});
|
||||
|
||||
const startTime = Date.now();
|
||||
const outputFormat = options.json ? 'json' : (options.output || 'pretty');
|
||||
|
||||
try {
|
||||
// Read and parse workflow file
|
||||
const filePath = path.resolve(workflowFile);
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(`Workflow file not found: ${filePath}`);
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
const workflow = parseWorkflowYaml(content);
|
||||
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.heading(`Executing workflow: ${workflow.name || 'Unnamed'}`);
|
||||
if (workflow.description) {
|
||||
await pretty.info(workflow.description);
|
||||
}
|
||||
}
|
||||
|
||||
// Execute workflow steps
|
||||
const results: Record<string, any> = {};
|
||||
const steps = workflow.steps || [];
|
||||
|
||||
for (const step of steps) {
|
||||
if (outputFormat !== 'json') {
|
||||
await pretty.info(`Running step: ${step.name}`);
|
||||
}
|
||||
|
||||
// For now, we'll simulate step execution
|
||||
// In a full implementation, this would create agents and execute tasks
|
||||
results[step.name] = {
|
||||
status: 'completed',
|
||||
output: `Step ${step.name} completed`
|
||||
};
|
||||
}
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatSuccess(
|
||||
{
|
||||
workflow: workflow.name || 'Unnamed',
|
||||
steps: steps.length,
|
||||
results
|
||||
},
|
||||
{
|
||||
duration_ms: duration,
|
||||
model: config.model
|
||||
}
|
||||
));
|
||||
} else {
|
||||
await pretty.success(`Workflow completed in ${duration}ms`);
|
||||
await pretty.newline();
|
||||
await pretty.keyValue({
|
||||
'Steps executed': steps.length,
|
||||
'Duration': `${duration}ms`
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
const cliError = normalizeError(error);
|
||||
|
||||
if (outputFormat === 'json') {
|
||||
outputJson(formatError(cliError.code, cliError.message, cliError.details));
|
||||
} else {
|
||||
await pretty.error(cliError.message);
|
||||
if (config.verbose && error instanceof Error && error.stack) {
|
||||
await pretty.dim(error.stack);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(cliError.exitCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Config utilities index
|
||||
*/
|
||||
|
||||
export * from './schema';
|
||||
export * from './load';
|
||||
export * from './resolve';
|
||||
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Config file loading
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { CONFIG_FILES } from '../spec/cli-spec';
|
||||
import { FullConfig, validateConfig, DEFAULT_CONFIG } from './schema';
|
||||
|
||||
export interface LoadConfigOptions {
|
||||
configPath?: string;
|
||||
cwd?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find config file in directory hierarchy
|
||||
*/
|
||||
function findConfigFile(startDir: string): string | null {
|
||||
let currentDir = startDir;
|
||||
|
||||
while (true) {
|
||||
for (const filename of CONFIG_FILES) {
|
||||
const filePath = path.join(currentDir, filename);
|
||||
if (fs.existsSync(filePath)) {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
|
||||
const parentDir = path.dirname(currentDir);
|
||||
if (parentDir === currentDir) {
|
||||
break; // Reached root
|
||||
}
|
||||
currentDir = parentDir;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find user config file
|
||||
*/
|
||||
function findUserConfigFile(): string | null {
|
||||
const homeDir = process.env.HOME || process.env.USERPROFILE;
|
||||
if (!homeDir) return null;
|
||||
|
||||
for (const filename of CONFIG_FILES) {
|
||||
const filePath = path.join(homeDir, filename);
|
||||
if (fs.existsSync(filePath)) {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse config file content
|
||||
*/
|
||||
function parseConfigFile(filePath: string): unknown {
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
const ext = path.extname(filePath).toLowerCase();
|
||||
|
||||
if (ext === '.json') {
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
if (ext === '.yaml' || ext === '.yml') {
|
||||
// Simple YAML parsing for basic config
|
||||
// For complex YAML, we'd need a proper parser
|
||||
return parseSimpleYaml(content);
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported config file format: ${ext}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple YAML parser for basic key-value configs
|
||||
* Handles: strings, booleans, numbers, simple objects
|
||||
*/
|
||||
function parseSimpleYaml(content: string): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
const lines = content.split('\n');
|
||||
let currentObject: Record<string, unknown> | null = null;
|
||||
let currentKey: string | null = null;
|
||||
let baseIndent = 0;
|
||||
|
||||
for (const line of lines) {
|
||||
// Skip empty lines and comments
|
||||
if (!line.trim() || line.trim().startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const indent = line.search(/\S/);
|
||||
const trimmed = line.trim();
|
||||
|
||||
// Check for key: value pattern
|
||||
const colonIndex = trimmed.indexOf(':');
|
||||
if (colonIndex === -1) continue;
|
||||
|
||||
const key = trimmed.slice(0, colonIndex).trim();
|
||||
const value = trimmed.slice(colonIndex + 1).trim();
|
||||
|
||||
if (indent === 0) {
|
||||
// Top-level key
|
||||
if (value === '' || value === '{}') {
|
||||
// Start of nested object
|
||||
currentObject = {};
|
||||
currentKey = key;
|
||||
baseIndent = indent;
|
||||
result[key] = currentObject;
|
||||
} else {
|
||||
result[key] = parseYamlValue(value);
|
||||
currentObject = null;
|
||||
currentKey = null;
|
||||
}
|
||||
} else if (currentObject !== null && indent > baseIndent) {
|
||||
// Nested key
|
||||
if (value === '' || value === '{}') {
|
||||
// Nested object within nested object
|
||||
const nestedObj: Record<string, unknown> = {};
|
||||
currentObject[key] = nestedObj;
|
||||
// For simplicity, we only support one level of nesting in profiles
|
||||
} else {
|
||||
currentObject[key] = parseYamlValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseYamlValue(value: string): string | number | boolean {
|
||||
// Remove quotes
|
||||
if ((value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))) {
|
||||
return value.slice(1, -1);
|
||||
}
|
||||
|
||||
// Boolean
|
||||
if (value === 'true') return true;
|
||||
if (value === 'false') return false;
|
||||
|
||||
// Number
|
||||
const num = Number(value);
|
||||
if (!isNaN(num) && value !== '') return num;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load config from file
|
||||
*/
|
||||
export function loadConfigFile(filePath: string): FullConfig {
|
||||
try {
|
||||
const parsed = parseConfigFile(filePath);
|
||||
if (!validateConfig(parsed)) {
|
||||
throw new Error('Invalid config format');
|
||||
}
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to load config from ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load config with resolution order:
|
||||
* 1. Explicit config path
|
||||
* 2. Project config (current dir and parents)
|
||||
* 3. User config (~/.praisonai.yaml)
|
||||
* 4. Defaults
|
||||
*/
|
||||
export function loadConfig(options: LoadConfigOptions = {}): FullConfig {
|
||||
const configs: Partial<FullConfig>[] = [DEFAULT_CONFIG];
|
||||
|
||||
// User config
|
||||
const userConfigPath = findUserConfigFile();
|
||||
if (userConfigPath) {
|
||||
try {
|
||||
configs.push(loadConfigFile(userConfigPath));
|
||||
} catch {
|
||||
// Ignore user config errors
|
||||
}
|
||||
}
|
||||
|
||||
// Project config
|
||||
const cwd = options.cwd || process.cwd();
|
||||
const projectConfigPath = findConfigFile(cwd);
|
||||
if (projectConfigPath) {
|
||||
try {
|
||||
configs.push(loadConfigFile(projectConfigPath));
|
||||
} catch {
|
||||
// Ignore project config errors
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit config path
|
||||
if (options.configPath) {
|
||||
configs.push(loadConfigFile(options.configPath));
|
||||
}
|
||||
|
||||
// Merge all configs
|
||||
const result: FullConfig = { ...DEFAULT_CONFIG };
|
||||
for (const config of configs) {
|
||||
if (config.model !== undefined) result.model = config.model;
|
||||
if (config.verbose !== undefined) result.verbose = config.verbose;
|
||||
if (config.stream !== undefined) result.stream = config.stream;
|
||||
if (config.profiles !== undefined) {
|
||||
result.profiles = { ...result.profiles, ...config.profiles };
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Config resolution with profiles and CLI overrides
|
||||
*/
|
||||
|
||||
import { loadConfig } from './load';
|
||||
import { loadEnvConfig } from '../runtime/env';
|
||||
import { FullConfig, ProfileConfig, DEFAULT_CONFIG } from './schema';
|
||||
|
||||
export interface ResolvedConfig {
|
||||
model: string;
|
||||
verbose: boolean;
|
||||
stream: boolean;
|
||||
}
|
||||
|
||||
export interface ResolveOptions {
|
||||
configPath?: string;
|
||||
profile?: string;
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
stream?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve final config with precedence:
|
||||
* 1. CLI flags (highest)
|
||||
* 2. Environment variables
|
||||
* 3. Profile settings
|
||||
* 4. Config file
|
||||
* 5. Defaults (lowest)
|
||||
*/
|
||||
export function resolveConfig(options: ResolveOptions = {}): ResolvedConfig {
|
||||
// Load base config from files
|
||||
const fileConfig = loadConfig({ configPath: options.configPath });
|
||||
|
||||
// Load env config
|
||||
const envConfig = loadEnvConfig();
|
||||
|
||||
// Get profile config if specified
|
||||
let profileConfig: ProfileConfig = {};
|
||||
const profileName = options.profile || envConfig.profile;
|
||||
if (profileName && fileConfig.profiles?.[profileName]) {
|
||||
profileConfig = fileConfig.profiles[profileName];
|
||||
}
|
||||
|
||||
// Resolve with precedence
|
||||
const resolved: ResolvedConfig = {
|
||||
model: DEFAULT_CONFIG.model!,
|
||||
verbose: DEFAULT_CONFIG.verbose!,
|
||||
stream: DEFAULT_CONFIG.stream!
|
||||
};
|
||||
|
||||
// Apply file config
|
||||
if (fileConfig.model !== undefined) resolved.model = fileConfig.model;
|
||||
if (fileConfig.verbose !== undefined) resolved.verbose = fileConfig.verbose;
|
||||
if (fileConfig.stream !== undefined) resolved.stream = fileConfig.stream;
|
||||
|
||||
// Apply profile config
|
||||
if (profileConfig.model !== undefined) resolved.model = profileConfig.model;
|
||||
if (profileConfig.verbose !== undefined) resolved.verbose = profileConfig.verbose;
|
||||
if (profileConfig.stream !== undefined) resolved.stream = profileConfig.stream;
|
||||
|
||||
// Apply env config
|
||||
if (envConfig.model !== undefined) resolved.model = envConfig.model;
|
||||
if (envConfig.verbose !== undefined) resolved.verbose = envConfig.verbose;
|
||||
|
||||
// Apply CLI flags (highest precedence)
|
||||
if (options.model !== undefined) resolved.model = options.model;
|
||||
if (options.verbose !== undefined) resolved.verbose = options.verbose;
|
||||
if (options.stream !== undefined) resolved.stream = options.stream;
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available profile names
|
||||
*/
|
||||
export function getAvailableProfiles(configPath?: string): string[] {
|
||||
const config = loadConfig({ configPath });
|
||||
return Object.keys(config.profiles || {});
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Config schema definitions
|
||||
*/
|
||||
|
||||
import { ConfigSchema } from '../spec/cli-spec';
|
||||
|
||||
export interface ProfileConfig {
|
||||
model?: string;
|
||||
verbose?: boolean;
|
||||
stream?: boolean;
|
||||
}
|
||||
|
||||
export interface FullConfig extends ConfigSchema {
|
||||
profiles?: Record<string, ProfileConfig>;
|
||||
}
|
||||
|
||||
export const DEFAULT_CONFIG: FullConfig = {
|
||||
model: 'openai/gpt-4o-mini',
|
||||
verbose: false,
|
||||
stream: false,
|
||||
profiles: {}
|
||||
};
|
||||
|
||||
export function validateConfig(config: unknown): config is FullConfig {
|
||||
if (typeof config !== 'object' || config === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const c = config as Record<string, unknown>;
|
||||
|
||||
if (c.model !== undefined && typeof c.model !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (c.verbose !== undefined && typeof c.verbose !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (c.stream !== undefined && typeof c.stream !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (c.profiles !== undefined) {
|
||||
if (typeof c.profiles !== 'object' || c.profiles === null) {
|
||||
return false;
|
||||
}
|
||||
for (const profile of Object.values(c.profiles as Record<string, unknown>)) {
|
||||
if (typeof profile !== 'object' || profile === null) {
|
||||
return false;
|
||||
}
|
||||
const p = profile as Record<string, unknown>;
|
||||
if (p.model !== undefined && typeof p.model !== 'string') {
|
||||
return false;
|
||||
}
|
||||
if (p.verbose !== undefined && typeof p.verbose !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
if (p.stream !== undefined && typeof p.stream !== 'boolean') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function mergeConfigs(...configs: Partial<FullConfig>[]): FullConfig {
|
||||
const result: FullConfig = { ...DEFAULT_CONFIG };
|
||||
|
||||
for (const config of configs) {
|
||||
if (config.model !== undefined) result.model = config.model;
|
||||
if (config.verbose !== undefined) result.verbose = config.verbose;
|
||||
if (config.stream !== undefined) result.stream = config.stream;
|
||||
if (config.profiles !== undefined) {
|
||||
result.profiles = { ...result.profiles, ...config.profiles };
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
/**
|
||||
* Autonomy Modes - Control automatic execution behavior
|
||||
*/
|
||||
|
||||
export type AutonomyMode = 'suggest' | 'auto_edit' | 'full_auto';
|
||||
|
||||
export type ActionType =
|
||||
| 'file_read'
|
||||
| 'file_write'
|
||||
| 'file_delete'
|
||||
| 'shell_command'
|
||||
| 'network_request'
|
||||
| 'git_operation'
|
||||
| 'install_package';
|
||||
|
||||
export interface ApprovalPolicy {
|
||||
action: ActionType;
|
||||
requiresApproval: boolean;
|
||||
autoApprovePatterns?: string[];
|
||||
autoDenyPatterns?: string[];
|
||||
}
|
||||
|
||||
export interface AutonomyConfig {
|
||||
mode: AutonomyMode;
|
||||
policies?: ApprovalPolicy[];
|
||||
rememberDecisions?: boolean;
|
||||
maxAutoActions?: number;
|
||||
}
|
||||
|
||||
export interface ActionRequest {
|
||||
type: ActionType;
|
||||
description: string;
|
||||
target?: string;
|
||||
details?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface ActionDecision {
|
||||
approved: boolean;
|
||||
reason?: string;
|
||||
remembered?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default policies for each mode
|
||||
*/
|
||||
export const MODE_POLICIES: Record<AutonomyMode, ApprovalPolicy[]> = {
|
||||
suggest: [
|
||||
{ action: 'file_read', requiresApproval: false },
|
||||
{ action: 'file_write', requiresApproval: true },
|
||||
{ action: 'file_delete', requiresApproval: true },
|
||||
{ action: 'shell_command', requiresApproval: true },
|
||||
{ action: 'network_request', requiresApproval: true },
|
||||
{ action: 'git_operation', requiresApproval: true },
|
||||
{ action: 'install_package', requiresApproval: true }
|
||||
],
|
||||
auto_edit: [
|
||||
{ action: 'file_read', requiresApproval: false },
|
||||
{ action: 'file_write', requiresApproval: false },
|
||||
{ action: 'file_delete', requiresApproval: true },
|
||||
{ action: 'shell_command', requiresApproval: true },
|
||||
{ action: 'network_request', requiresApproval: false },
|
||||
{ action: 'git_operation', requiresApproval: true },
|
||||
{ action: 'install_package', requiresApproval: true }
|
||||
],
|
||||
full_auto: [
|
||||
{ action: 'file_read', requiresApproval: false },
|
||||
{ action: 'file_write', requiresApproval: false },
|
||||
{ action: 'file_delete', requiresApproval: false },
|
||||
{ action: 'shell_command', requiresApproval: false },
|
||||
{ action: 'network_request', requiresApproval: false },
|
||||
{ action: 'git_operation', requiresApproval: false },
|
||||
{ action: 'install_package', requiresApproval: true }
|
||||
]
|
||||
};
|
||||
|
||||
/**
|
||||
* Autonomy Manager class
|
||||
*/
|
||||
export class AutonomyManager {
|
||||
private config: AutonomyConfig;
|
||||
private rememberedDecisions: Map<string, boolean> = new Map();
|
||||
private actionCount: number = 0;
|
||||
private promptCallback?: (request: ActionRequest) => Promise<boolean>;
|
||||
|
||||
constructor(config: Partial<AutonomyConfig> = {}) {
|
||||
this.config = {
|
||||
mode: 'suggest',
|
||||
rememberDecisions: true,
|
||||
maxAutoActions: 100,
|
||||
...config
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the prompt callback for user approval
|
||||
*/
|
||||
setPromptCallback(callback: (request: ActionRequest) => Promise<boolean>): void {
|
||||
this.promptCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request approval for an action
|
||||
*/
|
||||
async requestApproval(request: ActionRequest): Promise<ActionDecision> {
|
||||
// Check if we've exceeded max auto actions
|
||||
if (this.config.maxAutoActions && this.actionCount >= this.config.maxAutoActions) {
|
||||
return {
|
||||
approved: false,
|
||||
reason: 'Maximum auto actions exceeded'
|
||||
};
|
||||
}
|
||||
|
||||
// Check remembered decisions
|
||||
const decisionKey = this.getDecisionKey(request);
|
||||
if (this.config.rememberDecisions && this.rememberedDecisions.has(decisionKey)) {
|
||||
const remembered = this.rememberedDecisions.get(decisionKey)!;
|
||||
if (remembered) this.actionCount++;
|
||||
return {
|
||||
approved: remembered,
|
||||
reason: 'Remembered decision',
|
||||
remembered: true
|
||||
};
|
||||
}
|
||||
|
||||
// Get policy for this action type
|
||||
const policy = this.getPolicy(request.type);
|
||||
|
||||
// Check auto-approve patterns
|
||||
if (policy.autoApprovePatterns && request.target) {
|
||||
for (const pattern of policy.autoApprovePatterns) {
|
||||
if (this.matchPattern(request.target, pattern)) {
|
||||
this.actionCount++;
|
||||
return { approved: true, reason: `Matched auto-approve pattern: ${pattern}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check auto-deny patterns
|
||||
if (policy.autoDenyPatterns && request.target) {
|
||||
for (const pattern of policy.autoDenyPatterns) {
|
||||
if (this.matchPattern(request.target, pattern)) {
|
||||
return { approved: false, reason: `Matched auto-deny pattern: ${pattern}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no approval required, auto-approve
|
||||
if (!policy.requiresApproval) {
|
||||
this.actionCount++;
|
||||
return { approved: true, reason: 'No approval required' };
|
||||
}
|
||||
|
||||
// Prompt user for approval
|
||||
if (this.promptCallback) {
|
||||
const approved = await this.promptCallback(request);
|
||||
|
||||
// Remember decision if enabled
|
||||
if (this.config.rememberDecisions) {
|
||||
this.rememberedDecisions.set(decisionKey, approved);
|
||||
}
|
||||
|
||||
if (approved) this.actionCount++;
|
||||
return { approved, reason: 'User decision' };
|
||||
}
|
||||
|
||||
// No prompt callback, deny by default
|
||||
return { approved: false, reason: 'No approval mechanism available' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get policy for an action type
|
||||
*/
|
||||
private getPolicy(actionType: ActionType): ApprovalPolicy {
|
||||
// Check custom policies first
|
||||
if (this.config.policies) {
|
||||
const custom = this.config.policies.find(p => p.action === actionType);
|
||||
if (custom) return custom;
|
||||
}
|
||||
|
||||
// Fall back to mode defaults
|
||||
const modePolicy = MODE_POLICIES[this.config.mode].find(p => p.action === actionType);
|
||||
return modePolicy || { action: actionType, requiresApproval: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate decision key for remembering
|
||||
*/
|
||||
private getDecisionKey(request: ActionRequest): string {
|
||||
return `${request.type}:${request.target || 'default'}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Match a target against a pattern
|
||||
*/
|
||||
private matchPattern(target: string, pattern: string): boolean {
|
||||
// Simple glob-like matching
|
||||
const regex = new RegExp(
|
||||
'^' + pattern.replace(/\*/g, '.*').replace(/\?/g, '.') + '$'
|
||||
);
|
||||
return regex.test(target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current mode
|
||||
*/
|
||||
getMode(): AutonomyMode {
|
||||
return this.config.mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set mode
|
||||
*/
|
||||
setMode(mode: AutonomyMode): void {
|
||||
this.config.mode = mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add custom policy
|
||||
*/
|
||||
addPolicy(policy: ApprovalPolicy): void {
|
||||
if (!this.config.policies) {
|
||||
this.config.policies = [];
|
||||
}
|
||||
// Remove existing policy for this action
|
||||
this.config.policies = this.config.policies.filter(p => p.action !== policy.action);
|
||||
this.config.policies.push(policy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear remembered decisions
|
||||
*/
|
||||
clearRemembered(): void {
|
||||
this.rememberedDecisions.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset action count
|
||||
*/
|
||||
resetActionCount(): void {
|
||||
this.actionCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get action count
|
||||
*/
|
||||
getActionCount(): number {
|
||||
return this.actionCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get summary of current settings
|
||||
*/
|
||||
getSummary(): string {
|
||||
const lines = [
|
||||
`Autonomy Mode: ${this.config.mode}`,
|
||||
`Actions taken: ${this.actionCount}/${this.config.maxAutoActions || 'unlimited'}`,
|
||||
`Remembered decisions: ${this.rememberedDecisions.size}`,
|
||||
'',
|
||||
'Current policies:'
|
||||
];
|
||||
|
||||
const policies = MODE_POLICIES[this.config.mode];
|
||||
for (const policy of policies) {
|
||||
const status = policy.requiresApproval ? '⚠️ requires approval' : '✓ auto-approved';
|
||||
lines.push(` ${policy.action}: ${status}`);
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an autonomy manager
|
||||
*/
|
||||
export function createAutonomyManager(config?: Partial<AutonomyConfig>): AutonomyManager {
|
||||
return new AutonomyManager(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple approval prompt for CLI
|
||||
*/
|
||||
export async function cliApprovalPrompt(request: ActionRequest): Promise<boolean> {
|
||||
const readline = await import('readline');
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const message = `\n⚠️ Action requires approval:\n Type: ${request.type}\n ${request.description}\n Target: ${request.target || 'N/A'}\n\nApprove? (y/n): `;
|
||||
|
||||
rl.question(message, (answer) => {
|
||||
rl.close();
|
||||
resolve(answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
/**
|
||||
* Background Jobs - Persisted job queue with adapter support
|
||||
*/
|
||||
|
||||
export type JobStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
|
||||
export type JobPriority = 'low' | 'normal' | 'high' | 'critical';
|
||||
|
||||
export interface Job<T = any> {
|
||||
id: string;
|
||||
name: string;
|
||||
data: T;
|
||||
status: JobStatus;
|
||||
priority: JobPriority;
|
||||
attempts: number;
|
||||
maxAttempts: number;
|
||||
createdAt: Date;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
result?: any;
|
||||
error?: string;
|
||||
progress?: number;
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface JobQueueConfig {
|
||||
name?: string;
|
||||
concurrency?: number;
|
||||
maxAttempts?: number;
|
||||
retryDelay?: number;
|
||||
storage?: JobStorageAdapter;
|
||||
}
|
||||
|
||||
export interface JobStorageAdapter {
|
||||
save(job: Job): Promise<void>;
|
||||
get(id: string): Promise<Job | null>;
|
||||
getAll(): Promise<Job[]>;
|
||||
getByStatus(status: JobStatus): Promise<Job[]>;
|
||||
update(id: string, updates: Partial<Job>): Promise<void>;
|
||||
delete(id: string): Promise<void>;
|
||||
clear(): Promise<void>;
|
||||
}
|
||||
|
||||
export type JobHandler<T = any, R = any> = (job: Job<T>, context: JobContext) => Promise<R>;
|
||||
|
||||
export interface JobContext {
|
||||
updateProgress: (progress: number) => Promise<void>;
|
||||
log: (message: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory job storage adapter
|
||||
*/
|
||||
export class MemoryJobStorage implements JobStorageAdapter {
|
||||
private jobs: Map<string, Job> = new Map();
|
||||
|
||||
async save(job: Job): Promise<void> {
|
||||
this.jobs.set(job.id, { ...job });
|
||||
}
|
||||
|
||||
async get(id: string): Promise<Job | null> {
|
||||
return this.jobs.get(id) || null;
|
||||
}
|
||||
|
||||
async getAll(): Promise<Job[]> {
|
||||
return Array.from(this.jobs.values());
|
||||
}
|
||||
|
||||
async getByStatus(status: JobStatus): Promise<Job[]> {
|
||||
return Array.from(this.jobs.values()).filter(j => j.status === status);
|
||||
}
|
||||
|
||||
async update(id: string, updates: Partial<Job>): Promise<void> {
|
||||
const job = this.jobs.get(id);
|
||||
if (job) {
|
||||
this.jobs.set(id, { ...job, ...updates });
|
||||
}
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
this.jobs.delete(id);
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.jobs.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* File-based job storage adapter
|
||||
*/
|
||||
export class FileJobStorage implements JobStorageAdapter {
|
||||
private filePath: string;
|
||||
private jobs: Map<string, Job> = new Map();
|
||||
private initialized: boolean = false;
|
||||
|
||||
constructor(filePath: string) {
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
private async init(): Promise<void> {
|
||||
if (this.initialized) return;
|
||||
|
||||
try {
|
||||
const fs = await import('fs/promises');
|
||||
const content = await fs.readFile(this.filePath, 'utf-8');
|
||||
const data = JSON.parse(content);
|
||||
for (const job of data) {
|
||||
job.createdAt = new Date(job.createdAt);
|
||||
if (job.startedAt) job.startedAt = new Date(job.startedAt);
|
||||
if (job.completedAt) job.completedAt = new Date(job.completedAt);
|
||||
this.jobs.set(job.id, job);
|
||||
}
|
||||
} catch {
|
||||
// File doesn't exist yet
|
||||
}
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
private async persist(): Promise<void> {
|
||||
const fs = await import('fs/promises');
|
||||
const data = Array.from(this.jobs.values());
|
||||
await fs.writeFile(this.filePath, JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
async save(job: Job): Promise<void> {
|
||||
await this.init();
|
||||
this.jobs.set(job.id, { ...job });
|
||||
await this.persist();
|
||||
}
|
||||
|
||||
async get(id: string): Promise<Job | null> {
|
||||
await this.init();
|
||||
return this.jobs.get(id) || null;
|
||||
}
|
||||
|
||||
async getAll(): Promise<Job[]> {
|
||||
await this.init();
|
||||
return Array.from(this.jobs.values());
|
||||
}
|
||||
|
||||
async getByStatus(status: JobStatus): Promise<Job[]> {
|
||||
await this.init();
|
||||
return Array.from(this.jobs.values()).filter(j => j.status === status);
|
||||
}
|
||||
|
||||
async update(id: string, updates: Partial<Job>): Promise<void> {
|
||||
await this.init();
|
||||
const job = this.jobs.get(id);
|
||||
if (job) {
|
||||
this.jobs.set(id, { ...job, ...updates });
|
||||
await this.persist();
|
||||
}
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
await this.init();
|
||||
this.jobs.delete(id);
|
||||
await this.persist();
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.jobs.clear();
|
||||
await this.persist();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Job Queue class
|
||||
*/
|
||||
export class JobQueue {
|
||||
private config: JobQueueConfig;
|
||||
private storage: JobStorageAdapter;
|
||||
private handlers: Map<string, JobHandler> = new Map();
|
||||
private running: boolean = false;
|
||||
private activeJobs: number = 0;
|
||||
private processInterval?: NodeJS.Timeout;
|
||||
|
||||
constructor(config: JobQueueConfig = {}) {
|
||||
this.config = {
|
||||
name: 'default',
|
||||
concurrency: 1,
|
||||
maxAttempts: 3,
|
||||
retryDelay: 1000,
|
||||
...config
|
||||
};
|
||||
this.storage = config.storage || new MemoryJobStorage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a job handler
|
||||
*/
|
||||
register<T = any, R = any>(name: string, handler: JobHandler<T, R>): void {
|
||||
this.handlers.set(name, handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a job to the queue
|
||||
*/
|
||||
async add<T = any>(name: string, data: T, options: Partial<Job<T>> = {}): Promise<Job<T>> {
|
||||
const job: Job<T> = {
|
||||
id: `job_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||
name,
|
||||
data,
|
||||
status: 'pending',
|
||||
priority: options.priority || 'normal',
|
||||
attempts: 0,
|
||||
maxAttempts: options.maxAttempts || this.config.maxAttempts || 3,
|
||||
createdAt: new Date(),
|
||||
metadata: options.metadata
|
||||
};
|
||||
|
||||
await this.storage.save(job);
|
||||
return job;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a job by ID
|
||||
*/
|
||||
async get(id: string): Promise<Job | null> {
|
||||
return this.storage.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all jobs
|
||||
*/
|
||||
async getAll(): Promise<Job[]> {
|
||||
return this.storage.getAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get jobs by status
|
||||
*/
|
||||
async getByStatus(status: JobStatus): Promise<Job[]> {
|
||||
return this.storage.getByStatus(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a job
|
||||
*/
|
||||
async cancel(id: string): Promise<boolean> {
|
||||
const job = await this.storage.get(id);
|
||||
if (!job || job.status === 'running' || job.status === 'completed') {
|
||||
return false;
|
||||
}
|
||||
await this.storage.update(id, { status: 'cancelled' });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry a failed job
|
||||
*/
|
||||
async retry(id: string): Promise<boolean> {
|
||||
const job = await this.storage.get(id);
|
||||
if (!job || job.status !== 'failed') {
|
||||
return false;
|
||||
}
|
||||
await this.storage.update(id, {
|
||||
status: 'pending',
|
||||
attempts: 0,
|
||||
error: undefined
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start processing jobs
|
||||
*/
|
||||
start(): void {
|
||||
if (this.running) return;
|
||||
this.running = true;
|
||||
this.processInterval = setInterval(() => this.process(), 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop processing jobs
|
||||
*/
|
||||
stop(): void {
|
||||
this.running = false;
|
||||
if (this.processInterval) {
|
||||
clearInterval(this.processInterval);
|
||||
this.processInterval = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process pending jobs
|
||||
*/
|
||||
private async process(): Promise<void> {
|
||||
if (!this.running) return;
|
||||
if (this.activeJobs >= (this.config.concurrency || 1)) return;
|
||||
|
||||
const pendingJobs = await this.storage.getByStatus('pending');
|
||||
|
||||
// Sort by priority and creation time
|
||||
const priorityOrder: Record<JobPriority, number> = {
|
||||
critical: 0,
|
||||
high: 1,
|
||||
normal: 2,
|
||||
low: 3
|
||||
};
|
||||
|
||||
pendingJobs.sort((a, b) => {
|
||||
const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
|
||||
if (priorityDiff !== 0) return priorityDiff;
|
||||
return a.createdAt.getTime() - b.createdAt.getTime();
|
||||
});
|
||||
|
||||
for (const job of pendingJobs) {
|
||||
if (this.activeJobs >= (this.config.concurrency || 1)) break;
|
||||
this.runJob(job);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a single job
|
||||
*/
|
||||
private async runJob(job: Job): Promise<void> {
|
||||
const handler = this.handlers.get(job.name);
|
||||
if (!handler) {
|
||||
await this.storage.update(job.id, {
|
||||
status: 'failed',
|
||||
error: `No handler registered for job type: ${job.name}`
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.activeJobs++;
|
||||
await this.storage.update(job.id, {
|
||||
status: 'running',
|
||||
startedAt: new Date(),
|
||||
attempts: job.attempts + 1
|
||||
});
|
||||
|
||||
const context: JobContext = {
|
||||
updateProgress: async (progress: number) => {
|
||||
await this.storage.update(job.id, { progress });
|
||||
},
|
||||
log: (message: string) => {
|
||||
console.log(`[Job ${job.id}] ${message}`);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await handler(job, context);
|
||||
await this.storage.update(job.id, {
|
||||
status: 'completed',
|
||||
completedAt: new Date(),
|
||||
result,
|
||||
progress: 100
|
||||
});
|
||||
} catch (error: any) {
|
||||
const attempts = job.attempts + 1;
|
||||
|
||||
if (attempts < job.maxAttempts) {
|
||||
// Retry after delay
|
||||
setTimeout(async () => {
|
||||
await this.storage.update(job.id, {
|
||||
status: 'pending',
|
||||
error: error.message
|
||||
});
|
||||
}, this.config.retryDelay || 1000);
|
||||
} else {
|
||||
await this.storage.update(job.id, {
|
||||
status: 'failed',
|
||||
completedAt: new Date(),
|
||||
error: error.message
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
this.activeJobs--;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a job immediately (bypass queue)
|
||||
*/
|
||||
async processNow(id: string): Promise<any> {
|
||||
const job = await this.storage.get(id);
|
||||
if (!job) throw new Error(`Job ${id} not found`);
|
||||
|
||||
const handler = this.handlers.get(job.name);
|
||||
if (!handler) throw new Error(`No handler for job type: ${job.name}`);
|
||||
|
||||
await this.storage.update(job.id, {
|
||||
status: 'running',
|
||||
startedAt: new Date()
|
||||
});
|
||||
|
||||
const context: JobContext = {
|
||||
updateProgress: async (progress: number) => {
|
||||
await this.storage.update(job.id, { progress });
|
||||
},
|
||||
log: console.log
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await handler(job, context);
|
||||
await this.storage.update(job.id, {
|
||||
status: 'completed',
|
||||
completedAt: new Date(),
|
||||
result
|
||||
});
|
||||
return result;
|
||||
} catch (error: any) {
|
||||
await this.storage.update(job.id, {
|
||||
status: 'failed',
|
||||
completedAt: new Date(),
|
||||
error: error.message
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue stats
|
||||
*/
|
||||
async getStats(): Promise<{
|
||||
pending: number;
|
||||
running: number;
|
||||
completed: number;
|
||||
failed: number;
|
||||
cancelled: number;
|
||||
}> {
|
||||
const all = await this.storage.getAll();
|
||||
return {
|
||||
pending: all.filter(j => j.status === 'pending').length,
|
||||
running: all.filter(j => j.status === 'running').length,
|
||||
completed: all.filter(j => j.status === 'completed').length,
|
||||
failed: all.filter(j => j.status === 'failed').length,
|
||||
cancelled: all.filter(j => j.status === 'cancelled').length
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear completed/failed jobs
|
||||
*/
|
||||
async cleanup(olderThan?: Date): Promise<number> {
|
||||
const all = await this.storage.getAll();
|
||||
let count = 0;
|
||||
|
||||
for (const job of all) {
|
||||
if (job.status === 'completed' || job.status === 'failed' || job.status === 'cancelled') {
|
||||
if (!olderThan || (job.completedAt && job.completedAt < olderThan)) {
|
||||
await this.storage.delete(job.id);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a job queue
|
||||
*/
|
||||
export function createJobQueue(config?: JobQueueConfig): JobQueue {
|
||||
return new JobQueue(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a file-based job storage
|
||||
*/
|
||||
export function createFileJobStorage(filePath: string): FileJobStorage {
|
||||
return new FileJobStorage(filePath);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
/**
|
||||
* Checkpoints - Snapshot session/run state for recovery
|
||||
*/
|
||||
|
||||
export interface CheckpointData {
|
||||
id: string;
|
||||
name: string;
|
||||
timestamp: Date;
|
||||
sessionId?: string;
|
||||
runId?: string;
|
||||
agentId?: string;
|
||||
state: Record<string, any>;
|
||||
messages?: any[];
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface CheckpointConfig {
|
||||
storage?: CheckpointStorage;
|
||||
autoSave?: boolean;
|
||||
autoSaveInterval?: number;
|
||||
maxCheckpoints?: number;
|
||||
}
|
||||
|
||||
export interface CheckpointStorage {
|
||||
save(checkpoint: CheckpointData): Promise<void>;
|
||||
load(id: string): Promise<CheckpointData | null>;
|
||||
list(): Promise<CheckpointData[]>;
|
||||
delete(id: string): Promise<void>;
|
||||
clear(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory checkpoint storage
|
||||
*/
|
||||
export class MemoryCheckpointStorage implements CheckpointStorage {
|
||||
private checkpoints: Map<string, CheckpointData> = new Map();
|
||||
|
||||
async save(checkpoint: CheckpointData): Promise<void> {
|
||||
this.checkpoints.set(checkpoint.id, { ...checkpoint });
|
||||
}
|
||||
|
||||
async load(id: string): Promise<CheckpointData | null> {
|
||||
return this.checkpoints.get(id) || null;
|
||||
}
|
||||
|
||||
async list(): Promise<CheckpointData[]> {
|
||||
return Array.from(this.checkpoints.values())
|
||||
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
this.checkpoints.delete(id);
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this.checkpoints.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* File-based checkpoint storage
|
||||
*/
|
||||
export class FileCheckpointStorage implements CheckpointStorage {
|
||||
private dirPath: string;
|
||||
|
||||
constructor(dirPath: string) {
|
||||
this.dirPath = dirPath;
|
||||
}
|
||||
|
||||
private async ensureDir(): Promise<void> {
|
||||
const fs = await import('fs/promises');
|
||||
await fs.mkdir(this.dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
private getFilePath(id: string): string {
|
||||
return `${this.dirPath}/${id}.json`;
|
||||
}
|
||||
|
||||
async save(checkpoint: CheckpointData): Promise<void> {
|
||||
await this.ensureDir();
|
||||
const fs = await import('fs/promises');
|
||||
await fs.writeFile(
|
||||
this.getFilePath(checkpoint.id),
|
||||
JSON.stringify(checkpoint, null, 2)
|
||||
);
|
||||
}
|
||||
|
||||
async load(id: string): Promise<CheckpointData | null> {
|
||||
try {
|
||||
const fs = await import('fs/promises');
|
||||
const content = await fs.readFile(this.getFilePath(id), 'utf-8');
|
||||
const data = JSON.parse(content);
|
||||
data.timestamp = new Date(data.timestamp);
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async list(): Promise<CheckpointData[]> {
|
||||
try {
|
||||
await this.ensureDir();
|
||||
const fs = await import('fs/promises');
|
||||
const files = await fs.readdir(this.dirPath);
|
||||
const checkpoints: CheckpointData[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (file.endsWith('.json')) {
|
||||
const id = file.replace('.json', '');
|
||||
const checkpoint = await this.load(id);
|
||||
if (checkpoint) {
|
||||
checkpoints.push(checkpoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return checkpoints.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
try {
|
||||
const fs = await import('fs/promises');
|
||||
await fs.unlink(this.getFilePath(id));
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
const checkpoints = await this.list();
|
||||
for (const checkpoint of checkpoints) {
|
||||
await this.delete(checkpoint.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checkpoint Manager class
|
||||
*/
|
||||
export class CheckpointManager {
|
||||
private config: CheckpointConfig;
|
||||
private storage: CheckpointStorage;
|
||||
private autoSaveTimer?: NodeJS.Timeout;
|
||||
private currentState: Record<string, any> = {};
|
||||
|
||||
constructor(config: CheckpointConfig = {}) {
|
||||
this.config = {
|
||||
autoSave: false,
|
||||
autoSaveInterval: 60000, // 1 minute
|
||||
maxCheckpoints: 10,
|
||||
...config
|
||||
};
|
||||
this.storage = config.storage || new MemoryCheckpointStorage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a checkpoint
|
||||
*/
|
||||
async create(name: string, options: Partial<CheckpointData> = {}): Promise<CheckpointData> {
|
||||
const checkpoint: CheckpointData = {
|
||||
id: `cp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
||||
name,
|
||||
timestamp: new Date(),
|
||||
state: { ...this.currentState },
|
||||
...options
|
||||
};
|
||||
|
||||
await this.storage.save(checkpoint);
|
||||
await this.enforceMaxCheckpoints();
|
||||
|
||||
return checkpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore from a checkpoint
|
||||
*/
|
||||
async restore(id: string): Promise<CheckpointData | null> {
|
||||
const checkpoint = await this.storage.load(id);
|
||||
if (checkpoint) {
|
||||
this.currentState = { ...checkpoint.state };
|
||||
}
|
||||
return checkpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore the latest checkpoint
|
||||
*/
|
||||
async restoreLatest(): Promise<CheckpointData | null> {
|
||||
const checkpoints = await this.storage.list();
|
||||
if (checkpoints.length === 0) return null;
|
||||
return this.restore(checkpoints[0].id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a checkpoint by ID
|
||||
*/
|
||||
async get(id: string): Promise<CheckpointData | null> {
|
||||
return this.storage.load(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* List all checkpoints
|
||||
*/
|
||||
async list(): Promise<CheckpointData[]> {
|
||||
return this.storage.list();
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a checkpoint
|
||||
*/
|
||||
async delete(id: string): Promise<void> {
|
||||
await this.storage.delete(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all checkpoints
|
||||
*/
|
||||
async clear(): Promise<void> {
|
||||
await this.storage.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update current state
|
||||
*/
|
||||
setState(state: Record<string, any>): void {
|
||||
this.currentState = { ...this.currentState, ...state };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current state
|
||||
*/
|
||||
getState(): Record<string, any> {
|
||||
return { ...this.currentState };
|
||||
}
|
||||
|
||||
/**
|
||||
* Start auto-save
|
||||
*/
|
||||
startAutoSave(): void {
|
||||
if (this.autoSaveTimer) return;
|
||||
if (!this.config.autoSave) return;
|
||||
|
||||
this.autoSaveTimer = setInterval(async () => {
|
||||
await this.create('auto-save', { metadata: { auto: true } });
|
||||
}, this.config.autoSaveInterval);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop auto-save
|
||||
*/
|
||||
stopAutoSave(): void {
|
||||
if (this.autoSaveTimer) {
|
||||
clearInterval(this.autoSaveTimer);
|
||||
this.autoSaveTimer = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce maximum checkpoints limit
|
||||
*/
|
||||
private async enforceMaxCheckpoints(): Promise<void> {
|
||||
if (!this.config.maxCheckpoints) return;
|
||||
|
||||
const checkpoints = await this.storage.list();
|
||||
if (checkpoints.length > this.config.maxCheckpoints) {
|
||||
// Delete oldest checkpoints (but keep auto-saves separate)
|
||||
const toDelete = checkpoints.slice(this.config.maxCheckpoints);
|
||||
for (const checkpoint of toDelete) {
|
||||
await this.storage.delete(checkpoint.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export checkpoint to JSON string
|
||||
*/
|
||||
async export(id: string): Promise<string | null> {
|
||||
const checkpoint = await this.storage.load(id);
|
||||
if (!checkpoint) return null;
|
||||
return JSON.stringify(checkpoint, null, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Import checkpoint from JSON string
|
||||
*/
|
||||
async import(json: string): Promise<CheckpointData> {
|
||||
const data = JSON.parse(json);
|
||||
data.timestamp = new Date(data.timestamp);
|
||||
data.id = `cp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; // New ID
|
||||
await this.storage.save(data);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a checkpoint manager
|
||||
*/
|
||||
export function createCheckpointManager(config?: CheckpointConfig): CheckpointManager {
|
||||
return new CheckpointManager(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create file-based checkpoint storage
|
||||
*/
|
||||
export function createFileCheckpointStorage(dirPath: string): FileCheckpointStorage {
|
||||
return new FileCheckpointStorage(dirPath);
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* Cost Tracker - Track token usage and costs across LLM requests
|
||||
*/
|
||||
|
||||
export interface ModelPricing {
|
||||
inputCostPer1k: number;
|
||||
outputCostPer1k: number;
|
||||
}
|
||||
|
||||
export interface TokenUsage {
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
totalTokens: number;
|
||||
}
|
||||
|
||||
export interface RequestStats {
|
||||
timestamp: number;
|
||||
model: string;
|
||||
usage: TokenUsage;
|
||||
cost: number;
|
||||
latencyMs?: number;
|
||||
}
|
||||
|
||||
export interface SessionStats {
|
||||
totalInputTokens: number;
|
||||
totalOutputTokens: number;
|
||||
totalTokens: number;
|
||||
totalCost: number;
|
||||
requestCount: number;
|
||||
avgLatencyMs: number;
|
||||
startTime: number;
|
||||
requests: RequestStats[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Model pricing data (USD per 1K tokens)
|
||||
*/
|
||||
export const MODEL_PRICING: Record<string, ModelPricing> = {
|
||||
// OpenAI
|
||||
'gpt-4o': { inputCostPer1k: 0.005, outputCostPer1k: 0.015 },
|
||||
'gpt-4o-mini': { inputCostPer1k: 0.00015, outputCostPer1k: 0.0006 },
|
||||
'gpt-4-turbo': { inputCostPer1k: 0.01, outputCostPer1k: 0.03 },
|
||||
'gpt-4': { inputCostPer1k: 0.03, outputCostPer1k: 0.06 },
|
||||
'gpt-3.5-turbo': { inputCostPer1k: 0.0005, outputCostPer1k: 0.0015 },
|
||||
'o1': { inputCostPer1k: 0.015, outputCostPer1k: 0.06 },
|
||||
'o1-mini': { inputCostPer1k: 0.003, outputCostPer1k: 0.012 },
|
||||
'o1-preview': { inputCostPer1k: 0.015, outputCostPer1k: 0.06 },
|
||||
|
||||
// Anthropic
|
||||
'claude-3-5-sonnet-20241022': { inputCostPer1k: 0.003, outputCostPer1k: 0.015 },
|
||||
'claude-3-5-haiku-20241022': { inputCostPer1k: 0.001, outputCostPer1k: 0.005 },
|
||||
'claude-3-opus-20240229': { inputCostPer1k: 0.015, outputCostPer1k: 0.075 },
|
||||
'claude-3-sonnet-20240229': { inputCostPer1k: 0.003, outputCostPer1k: 0.015 },
|
||||
'claude-3-haiku-20240307': { inputCostPer1k: 0.00025, outputCostPer1k: 0.00125 },
|
||||
|
||||
// Google
|
||||
'gemini-2.0-flash': { inputCostPer1k: 0.0001, outputCostPer1k: 0.0004 },
|
||||
'gemini-1.5-pro': { inputCostPer1k: 0.00125, outputCostPer1k: 0.005 },
|
||||
'gemini-1.5-flash': { inputCostPer1k: 0.000075, outputCostPer1k: 0.0003 },
|
||||
|
||||
// Default fallback
|
||||
'default': { inputCostPer1k: 0.001, outputCostPer1k: 0.002 }
|
||||
};
|
||||
|
||||
/**
|
||||
* Cost Tracker class
|
||||
*/
|
||||
export class CostTracker {
|
||||
private stats: SessionStats;
|
||||
private customPricing: Map<string, ModelPricing> = new Map();
|
||||
|
||||
constructor() {
|
||||
this.stats = this.createEmptyStats();
|
||||
}
|
||||
|
||||
private createEmptyStats(): SessionStats {
|
||||
return {
|
||||
totalInputTokens: 0,
|
||||
totalOutputTokens: 0,
|
||||
totalTokens: 0,
|
||||
totalCost: 0,
|
||||
requestCount: 0,
|
||||
avgLatencyMs: 0,
|
||||
startTime: Date.now(),
|
||||
requests: []
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a request's token usage
|
||||
*/
|
||||
addUsage(
|
||||
model: string,
|
||||
inputTokens: number,
|
||||
outputTokens: number,
|
||||
latencyMs?: number
|
||||
): RequestStats {
|
||||
const totalTokens = inputTokens + outputTokens;
|
||||
const cost = this.calculateCost(model, inputTokens, outputTokens);
|
||||
|
||||
const request: RequestStats = {
|
||||
timestamp: Date.now(),
|
||||
model,
|
||||
usage: { inputTokens, outputTokens, totalTokens },
|
||||
cost,
|
||||
latencyMs
|
||||
};
|
||||
|
||||
this.stats.requests.push(request);
|
||||
this.stats.totalInputTokens += inputTokens;
|
||||
this.stats.totalOutputTokens += outputTokens;
|
||||
this.stats.totalTokens += totalTokens;
|
||||
this.stats.totalCost += cost;
|
||||
this.stats.requestCount++;
|
||||
|
||||
if (latencyMs !== undefined) {
|
||||
const totalLatency = this.stats.avgLatencyMs * (this.stats.requestCount - 1) + latencyMs;
|
||||
this.stats.avgLatencyMs = totalLatency / this.stats.requestCount;
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate cost for token usage
|
||||
*/
|
||||
calculateCost(model: string, inputTokens: number, outputTokens: number): number {
|
||||
const pricing = this.getPricing(model);
|
||||
const inputCost = (inputTokens / 1000) * pricing.inputCostPer1k;
|
||||
const outputCost = (outputTokens / 1000) * pricing.outputCostPer1k;
|
||||
return inputCost + outputCost;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pricing for a model
|
||||
*/
|
||||
getPricing(model: string): ModelPricing {
|
||||
// Check custom pricing first
|
||||
if (this.customPricing.has(model)) {
|
||||
return this.customPricing.get(model)!;
|
||||
}
|
||||
|
||||
// Check built-in pricing
|
||||
if (MODEL_PRICING[model]) {
|
||||
return MODEL_PRICING[model];
|
||||
}
|
||||
|
||||
// Try to match partial model names
|
||||
for (const [key, pricing] of Object.entries(MODEL_PRICING)) {
|
||||
if (model.includes(key) || key.includes(model)) {
|
||||
return pricing;
|
||||
}
|
||||
}
|
||||
|
||||
return MODEL_PRICING['default'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set custom pricing for a model
|
||||
*/
|
||||
setCustomPricing(model: string, pricing: ModelPricing): void {
|
||||
this.customPricing.set(model, pricing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current session stats
|
||||
*/
|
||||
getStats(): SessionStats {
|
||||
return { ...this.stats };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get summary string
|
||||
*/
|
||||
getSummary(): string {
|
||||
const duration = (Date.now() - this.stats.startTime) / 1000;
|
||||
const lines = [
|
||||
'=== Cost Summary ===',
|
||||
`Requests: ${this.stats.requestCount}`,
|
||||
`Duration: ${duration.toFixed(1)}s`,
|
||||
'',
|
||||
'Tokens:',
|
||||
` Input: ${this.stats.totalInputTokens.toLocaleString()}`,
|
||||
` Output: ${this.stats.totalOutputTokens.toLocaleString()}`,
|
||||
` Total: ${this.stats.totalTokens.toLocaleString()}`,
|
||||
'',
|
||||
`Total Cost: $${this.stats.totalCost.toFixed(6)}`,
|
||||
];
|
||||
|
||||
if (this.stats.avgLatencyMs > 0) {
|
||||
lines.push(`Avg Latency: ${this.stats.avgLatencyMs.toFixed(0)}ms`);
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get detailed breakdown by model
|
||||
*/
|
||||
getBreakdownByModel(): Record<string, { tokens: number; cost: number; requests: number }> {
|
||||
const breakdown: Record<string, { tokens: number; cost: number; requests: number }> = {};
|
||||
|
||||
for (const request of this.stats.requests) {
|
||||
if (!breakdown[request.model]) {
|
||||
breakdown[request.model] = { tokens: 0, cost: 0, requests: 0 };
|
||||
}
|
||||
breakdown[request.model].tokens += request.usage.totalTokens;
|
||||
breakdown[request.model].cost += request.cost;
|
||||
breakdown[request.model].requests++;
|
||||
}
|
||||
|
||||
return breakdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset stats
|
||||
*/
|
||||
reset(): void {
|
||||
this.stats = this.createEmptyStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Export stats to JSON
|
||||
*/
|
||||
toJSON(): SessionStats {
|
||||
return this.getStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Import stats from JSON
|
||||
*/
|
||||
fromJSON(data: SessionStats): void {
|
||||
this.stats = { ...data };
|
||||
}
|
||||
|
||||
// Legacy interface compatibility
|
||||
get totalTokens(): number {
|
||||
return this.stats.totalTokens;
|
||||
}
|
||||
|
||||
get totalCost(): number {
|
||||
return this.stats.totalCost;
|
||||
}
|
||||
|
||||
get requests(): number {
|
||||
return this.stats.requestCount;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a cost tracker instance
|
||||
*/
|
||||
export function createCostTracker(): CostTracker {
|
||||
return new CostTracker();
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate tokens from text (rough approximation)
|
||||
*/
|
||||
export function estimateTokens(text: string): number {
|
||||
return Math.ceil(text.length / 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format cost as currency string
|
||||
*/
|
||||
export function formatCost(cost: number): string {
|
||||
if (cost < 0.01) {
|
||||
return `$${cost.toFixed(6)}`;
|
||||
}
|
||||
if (cost < 1) {
|
||||
return `$${cost.toFixed(4)}`;
|
||||
}
|
||||
return `$${cost.toFixed(2)}`;
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* External Agents - Integration adapters for external AI CLI tools
|
||||
*/
|
||||
|
||||
export interface ExternalAgentConfig {
|
||||
name: string;
|
||||
command: string;
|
||||
args?: string[];
|
||||
cwd?: string;
|
||||
env?: Record<string, string>;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export interface ExternalAgentResult {
|
||||
success: boolean;
|
||||
output: string;
|
||||
error?: string;
|
||||
exitCode: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base class for external agent integrations
|
||||
*/
|
||||
export abstract class BaseExternalAgent {
|
||||
protected config: ExternalAgentConfig;
|
||||
|
||||
constructor(config: ExternalAgentConfig) {
|
||||
this.config = {
|
||||
timeout: 300000, // 5 minutes default
|
||||
...config
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the external tool is available
|
||||
*/
|
||||
abstract isAvailable(): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Execute a prompt with the external agent
|
||||
*/
|
||||
abstract execute(prompt: string): Promise<ExternalAgentResult>;
|
||||
|
||||
/**
|
||||
* Get the agent name
|
||||
*/
|
||||
getName(): string {
|
||||
return this.config.name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a command and return result
|
||||
*/
|
||||
protected async runCommand(args: string[]): Promise<ExternalAgentResult> {
|
||||
const { spawn } = await import('child_process');
|
||||
const startTime = Date.now();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn(this.config.command, args, {
|
||||
cwd: this.config.cwd || process.cwd(),
|
||||
env: { ...process.env, ...this.config.env },
|
||||
timeout: this.config.timeout,
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
proc.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on('close', (code) => {
|
||||
resolve({
|
||||
success: code === 0,
|
||||
output: stdout,
|
||||
error: stderr || undefined,
|
||||
exitCode: code || 0,
|
||||
duration: Date.now() - startTime
|
||||
});
|
||||
});
|
||||
|
||||
proc.on('error', (error) => {
|
||||
resolve({
|
||||
success: false,
|
||||
output: '',
|
||||
error: error.message,
|
||||
exitCode: 1,
|
||||
duration: Date.now() - startTime
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a command exists
|
||||
*/
|
||||
protected async commandExists(command: string): Promise<boolean> {
|
||||
const { spawn } = await import('child_process');
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn('which', [command], { stdio: 'pipe' });
|
||||
proc.on('close', (code) => resolve(code === 0));
|
||||
proc.on('error', () => resolve(false));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude Code CLI integration
|
||||
*/
|
||||
export class ClaudeCodeAgent extends BaseExternalAgent {
|
||||
constructor(cwd?: string) {
|
||||
super({
|
||||
name: 'claude-code',
|
||||
command: 'claude',
|
||||
cwd
|
||||
});
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
return this.commandExists('claude');
|
||||
}
|
||||
|
||||
async execute(prompt: string): Promise<ExternalAgentResult> {
|
||||
return this.runCommand(['--print', prompt]);
|
||||
}
|
||||
|
||||
async executeWithSession(prompt: string, sessionId?: string): Promise<ExternalAgentResult> {
|
||||
const args = ['--print'];
|
||||
if (sessionId) {
|
||||
args.push('--continue', sessionId);
|
||||
}
|
||||
args.push(prompt);
|
||||
return this.runCommand(args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gemini CLI integration
|
||||
*/
|
||||
export class GeminiCliAgent extends BaseExternalAgent {
|
||||
private model: string;
|
||||
|
||||
constructor(cwd?: string, model: string = 'gemini-2.5-pro') {
|
||||
super({
|
||||
name: 'gemini-cli',
|
||||
command: 'gemini',
|
||||
cwd
|
||||
});
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
return this.commandExists('gemini');
|
||||
}
|
||||
|
||||
async execute(prompt: string): Promise<ExternalAgentResult> {
|
||||
return this.runCommand(['-m', this.model, prompt]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAI Codex CLI integration
|
||||
*/
|
||||
export class CodexCliAgent extends BaseExternalAgent {
|
||||
constructor(cwd?: string) {
|
||||
super({
|
||||
name: 'codex-cli',
|
||||
command: 'codex',
|
||||
cwd
|
||||
});
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
return this.commandExists('codex');
|
||||
}
|
||||
|
||||
async execute(prompt: string): Promise<ExternalAgentResult> {
|
||||
return this.runCommand(['exec', '--full-auto', prompt]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aider CLI integration
|
||||
*/
|
||||
export class AiderAgent extends BaseExternalAgent {
|
||||
constructor(cwd?: string) {
|
||||
super({
|
||||
name: 'aider',
|
||||
command: 'aider',
|
||||
cwd
|
||||
});
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
return this.commandExists('aider');
|
||||
}
|
||||
|
||||
async execute(prompt: string): Promise<ExternalAgentResult> {
|
||||
return this.runCommand(['--message', prompt, '--yes']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic external agent for any CLI tool
|
||||
*/
|
||||
export class GenericExternalAgent extends BaseExternalAgent {
|
||||
private promptArg: string;
|
||||
|
||||
constructor(config: ExternalAgentConfig & { promptArg?: string }) {
|
||||
super(config);
|
||||
this.promptArg = config.promptArg || '';
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
return this.commandExists(this.config.command);
|
||||
}
|
||||
|
||||
async execute(prompt: string): Promise<ExternalAgentResult> {
|
||||
const args = [...(this.config.args || [])];
|
||||
if (this.promptArg) {
|
||||
args.push(this.promptArg, prompt);
|
||||
} else {
|
||||
args.push(prompt);
|
||||
}
|
||||
return this.runCommand(args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* External Agent Registry
|
||||
*/
|
||||
class ExternalAgentRegistry {
|
||||
private agents: Map<string, () => BaseExternalAgent> = new Map();
|
||||
|
||||
constructor() {
|
||||
// Register built-in agents
|
||||
this.register('claude', () => new ClaudeCodeAgent());
|
||||
this.register('gemini', () => new GeminiCliAgent());
|
||||
this.register('codex', () => new CodexCliAgent());
|
||||
this.register('aider', () => new AiderAgent());
|
||||
}
|
||||
|
||||
register(name: string, factory: () => BaseExternalAgent): void {
|
||||
this.agents.set(name, factory);
|
||||
}
|
||||
|
||||
get(name: string): BaseExternalAgent | undefined {
|
||||
const factory = this.agents.get(name);
|
||||
return factory ? factory() : undefined;
|
||||
}
|
||||
|
||||
list(): string[] {
|
||||
return Array.from(this.agents.keys());
|
||||
}
|
||||
|
||||
async getAvailable(): Promise<string[]> {
|
||||
const available: string[] = [];
|
||||
for (const [name, factory] of this.agents) {
|
||||
const agent = factory();
|
||||
if (await agent.isAvailable()) {
|
||||
available.push(name);
|
||||
}
|
||||
}
|
||||
return available;
|
||||
}
|
||||
}
|
||||
|
||||
let registry: ExternalAgentRegistry | null = null;
|
||||
|
||||
export function getExternalAgentRegistry(): ExternalAgentRegistry {
|
||||
if (!registry) {
|
||||
registry = new ExternalAgentRegistry();
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an external agent by name
|
||||
*/
|
||||
export function createExternalAgent(name: string, cwd?: string): BaseExternalAgent | undefined {
|
||||
const reg = getExternalAgentRegistry();
|
||||
|
||||
switch (name) {
|
||||
case 'claude':
|
||||
return new ClaudeCodeAgent(cwd);
|
||||
case 'gemini':
|
||||
return new GeminiCliAgent(cwd);
|
||||
case 'codex':
|
||||
return new CodexCliAgent(cwd);
|
||||
case 'aider':
|
||||
return new AiderAgent(cwd);
|
||||
default:
|
||||
return reg.get(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert external agent to tool for use with PraisonAI agents
|
||||
*/
|
||||
export function externalAgentAsTool(agent: BaseExternalAgent): {
|
||||
name: string;
|
||||
description: string;
|
||||
execute: (input: string) => Promise<string>;
|
||||
} {
|
||||
return {
|
||||
name: `external_${agent.getName()}`,
|
||||
description: `Execute a prompt using the ${agent.getName()} external agent`,
|
||||
execute: async (input: string) => {
|
||||
const result = await agent.execute(input);
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || 'External agent execution failed');
|
||||
}
|
||||
return result.output;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
/**
|
||||
* Fast Context - Fast retrieval and summarization pipeline
|
||||
* Minimizes tokens and latency with deterministic caching
|
||||
*/
|
||||
|
||||
export interface FastContextConfig {
|
||||
maxTokens?: number;
|
||||
cacheEnabled?: boolean;
|
||||
cacheTTL?: number;
|
||||
summarizer?: (text: string, maxTokens: number) => Promise<string>;
|
||||
embeddingProvider?: {
|
||||
embed: (text: string) => Promise<number[]>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ContextSource {
|
||||
id: string;
|
||||
type: 'memory' | 'knowledge' | 'file' | 'custom';
|
||||
content: string;
|
||||
relevance?: number;
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface FastContextResult {
|
||||
context: string;
|
||||
sources: ContextSource[];
|
||||
tokenCount: number;
|
||||
cached: boolean;
|
||||
latencyMs: number;
|
||||
}
|
||||
|
||||
export interface CacheEntry {
|
||||
result: FastContextResult;
|
||||
timestamp: number;
|
||||
hits: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast Context class for efficient context retrieval
|
||||
*/
|
||||
export class FastContext {
|
||||
private config: FastContextConfig;
|
||||
private cache: Map<string, CacheEntry> = new Map();
|
||||
private sources: Map<string, ContextSource[]> = new Map();
|
||||
|
||||
constructor(config: FastContextConfig = {}) {
|
||||
this.config = {
|
||||
maxTokens: 4000,
|
||||
cacheEnabled: true,
|
||||
cacheTTL: 300000, // 5 minutes
|
||||
...config
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a context source
|
||||
*/
|
||||
registerSource(
|
||||
id: string,
|
||||
type: ContextSource['type'],
|
||||
contents: string[],
|
||||
metadata?: Record<string, any>
|
||||
): void {
|
||||
const sources: ContextSource[] = contents.map((content, i) => ({
|
||||
id: `${id}_${i}`,
|
||||
type,
|
||||
content,
|
||||
metadata
|
||||
}));
|
||||
this.sources.set(id, sources);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register memory as a source
|
||||
*/
|
||||
registerMemory(memory: { getAll: () => Array<{ content: string; metadata?: any }> }): void {
|
||||
const entries = memory.getAll();
|
||||
const sources: ContextSource[] = entries.map((entry, i) => ({
|
||||
id: `memory_${i}`,
|
||||
type: 'memory',
|
||||
content: entry.content,
|
||||
metadata: entry.metadata
|
||||
}));
|
||||
this.sources.set('memory', sources);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register knowledge base as a source
|
||||
*/
|
||||
registerKnowledge(
|
||||
knowledge: { search: (query: string, limit?: number) => Promise<Array<{ content: string; score: number }>> }
|
||||
): void {
|
||||
// Store reference for dynamic retrieval
|
||||
(this as any)._knowledgeBase = knowledge;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get context for a query
|
||||
*/
|
||||
async getContext(query: string): Promise<FastContextResult> {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Check cache
|
||||
const cacheKey = this.getCacheKey(query);
|
||||
if (this.config.cacheEnabled) {
|
||||
const cached = this.getFromCache(cacheKey);
|
||||
if (cached) {
|
||||
return {
|
||||
...cached.result,
|
||||
cached: true,
|
||||
latencyMs: Date.now() - startTime
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Gather relevant sources
|
||||
const relevantSources = await this.gatherRelevantSources(query);
|
||||
|
||||
// Build context within token limit
|
||||
const { context, sources, tokenCount } = await this.buildContext(relevantSources, query);
|
||||
|
||||
const result: FastContextResult = {
|
||||
context,
|
||||
sources,
|
||||
tokenCount,
|
||||
cached: false,
|
||||
latencyMs: Date.now() - startTime
|
||||
};
|
||||
|
||||
// Cache result
|
||||
if (this.config.cacheEnabled) {
|
||||
this.addToCache(cacheKey, result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gather relevant sources for a query
|
||||
*/
|
||||
private async gatherRelevantSources(query: string): Promise<ContextSource[]> {
|
||||
const allSources: ContextSource[] = [];
|
||||
|
||||
// Get from registered sources
|
||||
for (const sources of this.sources.values()) {
|
||||
allSources.push(...sources);
|
||||
}
|
||||
|
||||
// Get from knowledge base if registered
|
||||
const kb = (this as any)._knowledgeBase;
|
||||
if (kb) {
|
||||
try {
|
||||
const kbResults = await kb.search(query, 10);
|
||||
for (let i = 0; i < kbResults.length; i++) {
|
||||
allSources.push({
|
||||
id: `kb_${i}`,
|
||||
type: 'knowledge',
|
||||
content: kbResults[i].content,
|
||||
relevance: kbResults[i].score
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Ignore knowledge base errors
|
||||
}
|
||||
}
|
||||
|
||||
// Score relevance if embedding provider available
|
||||
if (this.config.embeddingProvider) {
|
||||
await this.scoreRelevance(allSources, query);
|
||||
} else {
|
||||
// Simple text matching fallback
|
||||
this.scoreRelevanceSimple(allSources, query);
|
||||
}
|
||||
|
||||
// Sort by relevance
|
||||
allSources.sort((a, b) => (b.relevance || 0) - (a.relevance || 0));
|
||||
|
||||
return allSources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Score relevance using embeddings
|
||||
*/
|
||||
private async scoreRelevance(sources: ContextSource[], query: string): Promise<void> {
|
||||
if (!this.config.embeddingProvider) return;
|
||||
|
||||
const queryEmbedding = await this.config.embeddingProvider.embed(query);
|
||||
|
||||
for (const source of sources) {
|
||||
if (source.relevance !== undefined) continue; // Already scored
|
||||
|
||||
const sourceEmbedding = await this.config.embeddingProvider.embed(source.content);
|
||||
source.relevance = this.cosineSimilarity(queryEmbedding, sourceEmbedding);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple text-based relevance scoring
|
||||
*/
|
||||
private scoreRelevanceSimple(sources: ContextSource[], query: string): void {
|
||||
const queryWords = query.toLowerCase().split(/\s+/);
|
||||
|
||||
for (const source of sources) {
|
||||
if (source.relevance !== undefined) continue;
|
||||
|
||||
const contentLower = source.content.toLowerCase();
|
||||
let score = 0;
|
||||
|
||||
for (const word of queryWords) {
|
||||
if (contentLower.includes(word)) {
|
||||
score += 1 / queryWords.length;
|
||||
}
|
||||
}
|
||||
|
||||
// Boost for exact phrase match
|
||||
if (contentLower.includes(query.toLowerCase())) {
|
||||
score += 0.5;
|
||||
}
|
||||
|
||||
source.relevance = Math.min(score, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build context from sources within token limit
|
||||
*/
|
||||
private async buildContext(
|
||||
sources: ContextSource[],
|
||||
query: string
|
||||
): Promise<{ context: string; sources: ContextSource[]; tokenCount: number }> {
|
||||
const maxTokens = this.config.maxTokens || 4000;
|
||||
const usedSources: ContextSource[] = [];
|
||||
const contextParts: string[] = [];
|
||||
let tokenCount = 0;
|
||||
|
||||
for (const source of sources) {
|
||||
const sourceTokens = this.estimateTokens(source.content);
|
||||
|
||||
if (tokenCount + sourceTokens <= maxTokens) {
|
||||
contextParts.push(source.content);
|
||||
usedSources.push(source);
|
||||
tokenCount += sourceTokens;
|
||||
} else if (this.config.summarizer && sourceTokens > 100) {
|
||||
// Try to summarize if too long
|
||||
const remainingTokens = maxTokens - tokenCount;
|
||||
if (remainingTokens > 50) {
|
||||
const summary = await this.config.summarizer(source.content, remainingTokens);
|
||||
const summaryTokens = this.estimateTokens(summary);
|
||||
if (tokenCount + summaryTokens <= maxTokens) {
|
||||
contextParts.push(summary);
|
||||
usedSources.push({ ...source, content: summary, metadata: { ...source.metadata, summarized: true } });
|
||||
tokenCount += summaryTokens;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (tokenCount >= maxTokens * 0.95) break;
|
||||
}
|
||||
|
||||
return {
|
||||
context: contextParts.join('\n\n'),
|
||||
sources: usedSources,
|
||||
tokenCount
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache key for query
|
||||
*/
|
||||
private getCacheKey(query: string): string {
|
||||
// Simple hash
|
||||
let hash = 0;
|
||||
for (let i = 0; i < query.length; i++) {
|
||||
const char = query.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
return `ctx_${hash}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get from cache
|
||||
*/
|
||||
private getFromCache(key: string): CacheEntry | null {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) return null;
|
||||
|
||||
// Check TTL
|
||||
if (Date.now() - entry.timestamp > (this.config.cacheTTL || 300000)) {
|
||||
this.cache.delete(key);
|
||||
return null;
|
||||
}
|
||||
|
||||
entry.hits++;
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add to cache
|
||||
*/
|
||||
private addToCache(key: string, result: FastContextResult): void {
|
||||
this.cache.set(key, {
|
||||
result,
|
||||
timestamp: Date.now(),
|
||||
hits: 0
|
||||
});
|
||||
|
||||
// Limit cache size
|
||||
if (this.cache.size > 100) {
|
||||
const oldest = Array.from(this.cache.entries())
|
||||
.sort((a, b) => a[1].timestamp - b[1].timestamp)[0];
|
||||
if (oldest) {
|
||||
this.cache.delete(oldest[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear cache
|
||||
*/
|
||||
clearCache(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cache stats
|
||||
*/
|
||||
getCacheStats(): { size: number; totalHits: number } {
|
||||
let totalHits = 0;
|
||||
for (const entry of this.cache.values()) {
|
||||
totalHits += entry.hits;
|
||||
}
|
||||
return { size: this.cache.size, totalHits };
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate token count
|
||||
*/
|
||||
private estimateTokens(text: string): number {
|
||||
return Math.ceil(text.length / 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cosine similarity
|
||||
*/
|
||||
private cosineSimilarity(a: number[], b: number[]): number {
|
||||
if (a.length !== b.length) return 0;
|
||||
|
||||
let dotProduct = 0;
|
||||
let normA = 0;
|
||||
let normB = 0;
|
||||
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
dotProduct += a[i] * b[i];
|
||||
normA += a[i] * a[i];
|
||||
normB += b[i] * b[i];
|
||||
}
|
||||
|
||||
const denominator = Math.sqrt(normA) * Math.sqrt(normB);
|
||||
return denominator === 0 ? 0 : dotProduct / denominator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all sources
|
||||
*/
|
||||
clearSources(): void {
|
||||
this.sources.clear();
|
||||
(this as any)._knowledgeBase = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a fast context instance
|
||||
*/
|
||||
export function createFastContext(config?: FastContextConfig): FastContext {
|
||||
return new FastContext(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick context retrieval
|
||||
*/
|
||||
export async function getQuickContext(
|
||||
query: string,
|
||||
sources: string[],
|
||||
maxTokens?: number
|
||||
): Promise<string> {
|
||||
const fc = createFastContext({ maxTokens, cacheEnabled: false });
|
||||
fc.registerSource('quick', 'custom', sources);
|
||||
const result = await fc.getContext(query);
|
||||
return result.context;
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
/**
|
||||
* Flow Display - Textual DAG visualization for workflows
|
||||
*/
|
||||
|
||||
export interface FlowNode {
|
||||
id: string;
|
||||
name: string;
|
||||
type: 'agent' | 'tool' | 'condition' | 'parallel' | 'start' | 'end';
|
||||
status?: 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
|
||||
children?: string[];
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface FlowGraph {
|
||||
nodes: Map<string, FlowNode>;
|
||||
edges: Array<{ from: string; to: string; label?: string }>;
|
||||
}
|
||||
|
||||
export interface FlowDisplayConfig {
|
||||
showStatus?: boolean;
|
||||
showMetadata?: boolean;
|
||||
compact?: boolean;
|
||||
maxWidth?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flow Display class for DAG visualization
|
||||
*/
|
||||
export class FlowDisplay {
|
||||
private graph: FlowGraph;
|
||||
private config: FlowDisplayConfig;
|
||||
|
||||
constructor(config: FlowDisplayConfig = {}) {
|
||||
this.config = {
|
||||
showStatus: true,
|
||||
showMetadata: false,
|
||||
compact: false,
|
||||
maxWidth: 80,
|
||||
...config
|
||||
};
|
||||
this.graph = {
|
||||
nodes: new Map(),
|
||||
edges: []
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a node to the graph
|
||||
*/
|
||||
addNode(node: FlowNode): void {
|
||||
this.graph.nodes.set(node.id, node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an edge between nodes
|
||||
*/
|
||||
addEdge(from: string, to: string, label?: string): void {
|
||||
this.graph.edges.push({ from, to, label });
|
||||
}
|
||||
|
||||
/**
|
||||
* Update node status
|
||||
*/
|
||||
updateStatus(id: string, status: FlowNode['status']): void {
|
||||
const node = this.graph.nodes.get(id);
|
||||
if (node) {
|
||||
node.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build graph from workflow steps
|
||||
*/
|
||||
fromWorkflowSteps(steps: Array<{ name: string; type?: string; condition?: string }>): void {
|
||||
this.graph.nodes.clear();
|
||||
this.graph.edges = [];
|
||||
|
||||
// Add start node
|
||||
this.addNode({ id: 'start', name: 'Start', type: 'start' });
|
||||
|
||||
let prevId = 'start';
|
||||
for (let i = 0; i < steps.length; i++) {
|
||||
const step = steps[i];
|
||||
const id = `step_${i}`;
|
||||
|
||||
this.addNode({
|
||||
id,
|
||||
name: step.name,
|
||||
type: (step.type as FlowNode['type']) || 'agent',
|
||||
status: 'pending'
|
||||
});
|
||||
|
||||
this.addEdge(prevId, id, step.condition);
|
||||
prevId = id;
|
||||
}
|
||||
|
||||
// Add end node
|
||||
this.addNode({ id: 'end', name: 'End', type: 'end' });
|
||||
this.addEdge(prevId, 'end');
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the graph as text
|
||||
*/
|
||||
render(): string {
|
||||
const lines: string[] = [];
|
||||
const visited = new Set<string>();
|
||||
|
||||
// Find root nodes (nodes with no incoming edges)
|
||||
const hasIncoming = new Set(this.graph.edges.map(e => e.to));
|
||||
const roots = Array.from(this.graph.nodes.keys()).filter(id => !hasIncoming.has(id));
|
||||
|
||||
if (roots.length === 0 && this.graph.nodes.size > 0) {
|
||||
const firstKey = this.graph.nodes.keys().next().value;
|
||||
if (firstKey) roots.push(firstKey);
|
||||
}
|
||||
|
||||
for (const root of roots) {
|
||||
this.renderNode(root, '', true, lines, visited);
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a single node and its children
|
||||
*/
|
||||
private renderNode(
|
||||
id: string,
|
||||
prefix: string,
|
||||
isLast: boolean,
|
||||
lines: string[],
|
||||
visited: Set<string>
|
||||
): void {
|
||||
if (visited.has(id)) {
|
||||
lines.push(`${prefix}${isLast ? '└── ' : '├── '}(cycle: ${id})`);
|
||||
return;
|
||||
}
|
||||
visited.add(id);
|
||||
|
||||
const node = this.graph.nodes.get(id);
|
||||
if (!node) return;
|
||||
|
||||
const connector = isLast ? '└── ' : '├── ';
|
||||
const nodeStr = this.formatNode(node);
|
||||
lines.push(`${prefix}${connector}${nodeStr}`);
|
||||
|
||||
// Find children
|
||||
const childEdges = this.graph.edges.filter(e => e.from === id);
|
||||
const childPrefix = prefix + (isLast ? ' ' : '│ ');
|
||||
|
||||
for (let i = 0; i < childEdges.length; i++) {
|
||||
const edge = childEdges[i];
|
||||
const isLastChild = i === childEdges.length - 1;
|
||||
|
||||
if (edge.label) {
|
||||
lines.push(`${childPrefix}${isLastChild ? '└' : '├'}─[${edge.label}]─┐`);
|
||||
this.renderNode(edge.to, childPrefix + (isLastChild ? ' ' : '│ '), true, lines, visited);
|
||||
} else {
|
||||
this.renderNode(edge.to, childPrefix, isLastChild, lines, visited);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a node for display
|
||||
*/
|
||||
private formatNode(node: FlowNode): string {
|
||||
const parts: string[] = [];
|
||||
|
||||
// Status indicator
|
||||
if (this.config.showStatus && node.status) {
|
||||
const statusIcons: Record<string, string> = {
|
||||
pending: '○',
|
||||
running: '◐',
|
||||
completed: '●',
|
||||
failed: '✗',
|
||||
skipped: '◌'
|
||||
};
|
||||
parts.push(statusIcons[node.status] || '?');
|
||||
}
|
||||
|
||||
// Type indicator
|
||||
const typeIcons: Record<string, string> = {
|
||||
agent: '🤖',
|
||||
tool: '🔧',
|
||||
condition: '❓',
|
||||
parallel: '⫘',
|
||||
start: '▶',
|
||||
end: '■'
|
||||
};
|
||||
|
||||
if (!this.config.compact) {
|
||||
parts.push(typeIcons[node.type] || '□');
|
||||
}
|
||||
|
||||
// Name
|
||||
parts.push(node.name);
|
||||
|
||||
// Metadata
|
||||
if (this.config.showMetadata && node.metadata) {
|
||||
const meta = Object.entries(node.metadata)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(', ');
|
||||
if (meta) {
|
||||
parts.push(`(${meta})`);
|
||||
}
|
||||
}
|
||||
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Render as simple ASCII box diagram
|
||||
*/
|
||||
renderBoxes(): string {
|
||||
const lines: string[] = [];
|
||||
const nodeList = Array.from(this.graph.nodes.values());
|
||||
|
||||
for (let i = 0; i < nodeList.length; i++) {
|
||||
const node = nodeList[i];
|
||||
const box = this.createBox(node);
|
||||
lines.push(...box);
|
||||
|
||||
if (i < nodeList.length - 1) {
|
||||
lines.push(' │');
|
||||
lines.push(' ▼');
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a box for a node
|
||||
*/
|
||||
private createBox(node: FlowNode): string[] {
|
||||
const name = node.name;
|
||||
const width = Math.max(name.length + 4, 20);
|
||||
const padding = Math.floor((width - name.length - 2) / 2);
|
||||
|
||||
const statusChar = this.config.showStatus ? this.getStatusChar(node.status) : '';
|
||||
const top = '┌' + '─'.repeat(width) + '┐';
|
||||
const middle = '│' + ' '.repeat(padding) + statusChar + name + ' '.repeat(width - padding - name.length - statusChar.length) + '│';
|
||||
const bottom = '└' + '─'.repeat(width) + '┘';
|
||||
|
||||
return [top, middle, bottom];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get status character
|
||||
*/
|
||||
private getStatusChar(status?: string): string {
|
||||
const chars: Record<string, string> = {
|
||||
pending: '○ ',
|
||||
running: '◐ ',
|
||||
completed: '● ',
|
||||
failed: '✗ ',
|
||||
skipped: '◌ '
|
||||
};
|
||||
return status ? (chars[status] || '') : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the graph
|
||||
*/
|
||||
clear(): void {
|
||||
this.graph.nodes.clear();
|
||||
this.graph.edges = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get graph data
|
||||
*/
|
||||
getGraph(): FlowGraph {
|
||||
return this.graph;
|
||||
}
|
||||
|
||||
/**
|
||||
* Export to DOT format (for Graphviz)
|
||||
*/
|
||||
toDot(): string {
|
||||
const lines: string[] = ['digraph workflow {'];
|
||||
lines.push(' rankdir=TB;');
|
||||
lines.push(' node [shape=box];');
|
||||
|
||||
for (const [id, node] of this.graph.nodes) {
|
||||
const label = node.name.replace(/"/g, '\\"');
|
||||
const style = node.status === 'completed' ? 'filled' : '';
|
||||
const fillcolor = node.status === 'completed' ? 'lightgreen' :
|
||||
node.status === 'failed' ? 'lightcoral' : 'white';
|
||||
lines.push(` "${id}" [label="${label}" style="${style}" fillcolor="${fillcolor}"];`);
|
||||
}
|
||||
|
||||
for (const edge of this.graph.edges) {
|
||||
const label = edge.label ? ` [label="${edge.label}"]` : '';
|
||||
lines.push(` "${edge.from}" -> "${edge.to}"${label};`);
|
||||
}
|
||||
|
||||
lines.push('}');
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a flow display instance
|
||||
*/
|
||||
export function createFlowDisplay(config?: FlowDisplayConfig): FlowDisplay {
|
||||
return new FlowDisplay(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick render workflow steps
|
||||
*/
|
||||
export function renderWorkflow(steps: Array<{ name: string; type?: string }>): string {
|
||||
const display = createFlowDisplay();
|
||||
display.fromWorkflowSteps(steps);
|
||||
return display.render();
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
/**
|
||||
* Git Integration - Git operations for CLI
|
||||
* Safe, read-focused operations with optional write capabilities
|
||||
*/
|
||||
|
||||
export interface GitConfig {
|
||||
cwd?: string;
|
||||
safe?: boolean; // If true, only allow read operations
|
||||
}
|
||||
|
||||
export interface GitStatus {
|
||||
branch: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
staged: string[];
|
||||
modified: string[];
|
||||
untracked: string[];
|
||||
deleted: string[];
|
||||
conflicts: string[];
|
||||
}
|
||||
|
||||
export interface GitCommit {
|
||||
hash: string;
|
||||
shortHash: string;
|
||||
author: string;
|
||||
email: string;
|
||||
date: Date;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface GitDiff {
|
||||
files: GitDiffFile[];
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface GitDiffFile {
|
||||
path: string;
|
||||
status: 'added' | 'modified' | 'deleted' | 'renamed';
|
||||
additions: number;
|
||||
deletions: number;
|
||||
diff?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Git Manager class
|
||||
*/
|
||||
export class GitManager {
|
||||
private cwd: string;
|
||||
private safe: boolean;
|
||||
|
||||
constructor(config: GitConfig = {}) {
|
||||
this.cwd = config.cwd || process.cwd();
|
||||
this.safe = config.safe ?? true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a git command
|
||||
*/
|
||||
private async exec(args: string[]): Promise<string> {
|
||||
const { spawn } = await import('child_process');
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn('git', args, {
|
||||
cwd: this.cwd,
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
proc.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
resolve(stdout.trim());
|
||||
} else {
|
||||
reject(new Error(stderr || `Git command failed with code ${code}`));
|
||||
}
|
||||
});
|
||||
|
||||
proc.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if directory is a git repository
|
||||
*/
|
||||
async isRepo(): Promise<boolean> {
|
||||
try {
|
||||
await this.exec(['rev-parse', '--git-dir']);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current branch name
|
||||
*/
|
||||
async getBranch(): Promise<string> {
|
||||
return this.exec(['rev-parse', '--abbrev-ref', 'HEAD']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get repository status
|
||||
*/
|
||||
async getStatus(): Promise<GitStatus> {
|
||||
const branch = await this.getBranch();
|
||||
const porcelain = await this.exec(['status', '--porcelain', '-b']);
|
||||
|
||||
const lines = porcelain.split('\n');
|
||||
const status: GitStatus = {
|
||||
branch,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
staged: [],
|
||||
modified: [],
|
||||
untracked: [],
|
||||
deleted: [],
|
||||
conflicts: []
|
||||
};
|
||||
|
||||
// Parse branch line for ahead/behind
|
||||
const branchLine = lines[0];
|
||||
const aheadMatch = branchLine.match(/ahead (\d+)/);
|
||||
const behindMatch = branchLine.match(/behind (\d+)/);
|
||||
if (aheadMatch) status.ahead = parseInt(aheadMatch[1]);
|
||||
if (behindMatch) status.behind = parseInt(behindMatch[1]);
|
||||
|
||||
// Parse file status
|
||||
for (const line of lines.slice(1)) {
|
||||
if (!line) continue;
|
||||
|
||||
const indexStatus = line[0];
|
||||
const workStatus = line[1];
|
||||
const file = line.slice(3);
|
||||
|
||||
if (indexStatus === 'U' || workStatus === 'U') {
|
||||
status.conflicts.push(file);
|
||||
} else if (indexStatus === '?' && workStatus === '?') {
|
||||
status.untracked.push(file);
|
||||
} else if (indexStatus === 'D' || workStatus === 'D') {
|
||||
status.deleted.push(file);
|
||||
} else if (indexStatus !== ' ') {
|
||||
status.staged.push(file);
|
||||
} else if (workStatus === 'M') {
|
||||
status.modified.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get diff (staged or unstaged)
|
||||
*/
|
||||
async getDiff(staged: boolean = false): Promise<GitDiff> {
|
||||
const args = ['diff', '--stat'];
|
||||
if (staged) args.push('--staged');
|
||||
|
||||
const stat = await this.exec(args);
|
||||
const files: GitDiffFile[] = [];
|
||||
|
||||
const lines = stat.split('\n');
|
||||
for (const line of lines) {
|
||||
const match = line.match(/^\s*(.+?)\s*\|\s*(\d+)\s*([+-]*)/);
|
||||
if (match) {
|
||||
const [, path, changes, indicators] = match;
|
||||
const additions = (indicators.match(/\+/g) || []).length;
|
||||
const deletions = (indicators.match(/-/g) || []).length;
|
||||
|
||||
files.push({
|
||||
path: path.trim(),
|
||||
status: 'modified',
|
||||
additions,
|
||||
deletions
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Get full diff for summary
|
||||
const fullDiffArgs = ['diff'];
|
||||
if (staged) fullDiffArgs.push('--staged');
|
||||
const fullDiff = await this.exec(fullDiffArgs);
|
||||
|
||||
return {
|
||||
files,
|
||||
summary: fullDiff
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent commits
|
||||
*/
|
||||
async getLog(limit: number = 10): Promise<GitCommit[]> {
|
||||
const format = '%H|%h|%an|%ae|%aI|%s';
|
||||
const output = await this.exec(['log', `-${limit}`, `--format=${format}`]);
|
||||
|
||||
return output.split('\n').filter(Boolean).map(line => {
|
||||
const [hash, shortHash, author, email, date, message] = line.split('|');
|
||||
return {
|
||||
hash,
|
||||
shortHash,
|
||||
author,
|
||||
email,
|
||||
date: new Date(date),
|
||||
message
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of branches
|
||||
*/
|
||||
async getBranches(): Promise<{ name: string; current: boolean }[]> {
|
||||
const output = await this.exec(['branch', '--list']);
|
||||
return output.split('\n').filter(Boolean).map(line => ({
|
||||
name: line.replace(/^\*?\s*/, '').trim(),
|
||||
current: line.startsWith('*')
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage files (requires safe=false)
|
||||
*/
|
||||
async add(files: string[] = ['.']): Promise<void> {
|
||||
if (this.safe) {
|
||||
throw new Error('Write operations disabled in safe mode');
|
||||
}
|
||||
await this.exec(['add', ...files]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit staged changes (requires safe=false)
|
||||
*/
|
||||
async commit(message: string): Promise<string> {
|
||||
if (this.safe) {
|
||||
throw new Error('Write operations disabled in safe mode');
|
||||
}
|
||||
return this.exec(['commit', '-m', message]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stash changes (requires safe=false)
|
||||
*/
|
||||
async stash(message?: string): Promise<void> {
|
||||
if (this.safe) {
|
||||
throw new Error('Write operations disabled in safe mode');
|
||||
}
|
||||
const args = ['stash', 'push'];
|
||||
if (message) args.push('-m', message);
|
||||
await this.exec(args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pop stash (requires safe=false)
|
||||
*/
|
||||
async stashPop(): Promise<void> {
|
||||
if (this.safe) {
|
||||
throw new Error('Write operations disabled in safe mode');
|
||||
}
|
||||
await this.exec(['stash', 'pop']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get stash list
|
||||
*/
|
||||
async getStashList(): Promise<string[]> {
|
||||
const output = await this.exec(['stash', 'list']);
|
||||
return output.split('\n').filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get file content at a specific commit
|
||||
*/
|
||||
async show(ref: string, path: string): Promise<string> {
|
||||
return this.exec(['show', `${ref}:${path}`]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get blame for a file
|
||||
*/
|
||||
async blame(path: string): Promise<string> {
|
||||
return this.exec(['blame', path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate commit message from staged changes
|
||||
*/
|
||||
async generateCommitMessage(): Promise<string> {
|
||||
const diff = await this.getDiff(true);
|
||||
|
||||
if (diff.files.length === 0) {
|
||||
return 'No staged changes';
|
||||
}
|
||||
|
||||
const fileList = diff.files.map(f => f.path).join(', ');
|
||||
const totalAdditions = diff.files.reduce((sum, f) => sum + f.additions, 0);
|
||||
const totalDeletions = diff.files.reduce((sum, f) => sum + f.deletions, 0);
|
||||
|
||||
// Simple template-based message
|
||||
if (diff.files.length === 1) {
|
||||
return `Update ${diff.files[0].path}`;
|
||||
}
|
||||
|
||||
return `Update ${diff.files.length} files (+${totalAdditions}/-${totalDeletions})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted status string
|
||||
*/
|
||||
async getStatusString(): Promise<string> {
|
||||
const status = await this.getStatus();
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`Branch: ${status.branch}`);
|
||||
if (status.ahead > 0) lines.push(` ↑ ${status.ahead} ahead`);
|
||||
if (status.behind > 0) lines.push(` ↓ ${status.behind} behind`);
|
||||
|
||||
if (status.staged.length > 0) {
|
||||
lines.push(`\nStaged (${status.staged.length}):`);
|
||||
status.staged.forEach(f => lines.push(` + ${f}`));
|
||||
}
|
||||
|
||||
if (status.modified.length > 0) {
|
||||
lines.push(`\nModified (${status.modified.length}):`);
|
||||
status.modified.forEach(f => lines.push(` M ${f}`));
|
||||
}
|
||||
|
||||
if (status.untracked.length > 0) {
|
||||
lines.push(`\nUntracked (${status.untracked.length}):`);
|
||||
status.untracked.forEach(f => lines.push(` ? ${f}`));
|
||||
}
|
||||
|
||||
if (status.deleted.length > 0) {
|
||||
lines.push(`\nDeleted (${status.deleted.length}):`);
|
||||
status.deleted.forEach(f => lines.push(` - ${f}`));
|
||||
}
|
||||
|
||||
if (status.conflicts.length > 0) {
|
||||
lines.push(`\nConflicts (${status.conflicts.length}):`);
|
||||
status.conflicts.forEach(f => lines.push(` ! ${f}`));
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a git manager instance
|
||||
*/
|
||||
export function createGitManager(config?: GitConfig): GitManager {
|
||||
return new GitManager(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Diff viewer with syntax highlighting (text-based)
|
||||
*/
|
||||
export class DiffViewer {
|
||||
private diff: string;
|
||||
|
||||
constructor(diff: string) {
|
||||
this.diff = diff;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted diff with markers
|
||||
*/
|
||||
format(): string {
|
||||
const lines = this.diff.split('\n');
|
||||
return lines.map(line => {
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) {
|
||||
return `[+] ${line}`;
|
||||
}
|
||||
if (line.startsWith('-') && !line.startsWith('---')) {
|
||||
return `[-] ${line}`;
|
||||
}
|
||||
if (line.startsWith('@@')) {
|
||||
return `[~] ${line}`;
|
||||
}
|
||||
return ` ${line}`;
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get summary statistics
|
||||
*/
|
||||
getStats(): { additions: number; deletions: number } {
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
|
||||
for (const line of this.diff.split('\n')) {
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) {
|
||||
additions++;
|
||||
}
|
||||
if (line.startsWith('-') && !line.startsWith('---')) {
|
||||
deletions++;
|
||||
}
|
||||
}
|
||||
|
||||
return { additions, deletions };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a diff viewer
|
||||
*/
|
||||
export function createDiffViewer(diff: string): DiffViewer {
|
||||
return new DiffViewer(diff);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* CLI Features - Lazy-loaded feature modules
|
||||
*/
|
||||
|
||||
// Slash Commands
|
||||
export {
|
||||
SlashCommandHandler,
|
||||
createSlashCommandHandler,
|
||||
registerCommand,
|
||||
parseSlashCommand,
|
||||
executeSlashCommand,
|
||||
isSlashCommand,
|
||||
getRegistry,
|
||||
type SlashCommand,
|
||||
type SlashCommandContext,
|
||||
type SlashCommandResult,
|
||||
type CostTracker as SlashCostTracker
|
||||
} from './slash-commands';
|
||||
|
||||
// Cost Tracker
|
||||
export {
|
||||
CostTracker,
|
||||
createCostTracker,
|
||||
estimateTokens,
|
||||
formatCost,
|
||||
MODEL_PRICING,
|
||||
type ModelPricing,
|
||||
type TokenUsage,
|
||||
type RequestStats,
|
||||
type SessionStats
|
||||
} from './cost-tracker';
|
||||
|
||||
// Interactive TUI
|
||||
export {
|
||||
InteractiveTUI,
|
||||
createInteractiveTUI,
|
||||
StatusDisplay,
|
||||
createStatusDisplay,
|
||||
HistoryManager,
|
||||
createHistoryManager,
|
||||
type TUIConfig,
|
||||
type TUIState
|
||||
} from './interactive-tui';
|
||||
|
||||
// Repo Map
|
||||
export {
|
||||
RepoMap,
|
||||
createRepoMap,
|
||||
getRepoTree,
|
||||
DEFAULT_IGNORE_PATTERNS,
|
||||
type RepoMapConfig,
|
||||
type FileInfo,
|
||||
type SymbolInfo,
|
||||
type RepoMapResult
|
||||
} from './repo-map';
|
||||
|
||||
// Git Integration
|
||||
export {
|
||||
GitManager,
|
||||
createGitManager,
|
||||
DiffViewer,
|
||||
createDiffViewer,
|
||||
type GitConfig,
|
||||
type GitStatus,
|
||||
type GitCommit,
|
||||
type GitDiff,
|
||||
type GitDiffFile
|
||||
} from './git-integration';
|
||||
|
||||
// Sandbox Executor
|
||||
export {
|
||||
SandboxExecutor,
|
||||
createSandboxExecutor,
|
||||
sandboxExec,
|
||||
CommandValidator,
|
||||
DEFAULT_BLOCKED_COMMANDS,
|
||||
DEFAULT_BLOCKED_PATHS,
|
||||
type SandboxMode,
|
||||
type SandboxConfig,
|
||||
type ExecutionResult
|
||||
} from './sandbox-executor';
|
||||
|
||||
// Autonomy Mode
|
||||
export {
|
||||
AutonomyManager,
|
||||
createAutonomyManager,
|
||||
cliApprovalPrompt,
|
||||
MODE_POLICIES,
|
||||
type AutonomyMode,
|
||||
type ActionType,
|
||||
type ApprovalPolicy,
|
||||
type AutonomyConfig,
|
||||
type ActionRequest,
|
||||
type ActionDecision
|
||||
} from './autonomy-mode';
|
||||
|
||||
// Scheduler
|
||||
export {
|
||||
Scheduler,
|
||||
createScheduler,
|
||||
cronExpressions,
|
||||
type ScheduleConfig,
|
||||
type ScheduledTask,
|
||||
type SchedulerStats
|
||||
} from './scheduler';
|
||||
|
||||
// Background Jobs
|
||||
export {
|
||||
JobQueue,
|
||||
createJobQueue,
|
||||
MemoryJobStorage,
|
||||
FileJobStorage,
|
||||
createFileJobStorage,
|
||||
type Job,
|
||||
type JobStatus,
|
||||
type JobPriority,
|
||||
type JobQueueConfig,
|
||||
type JobStorageAdapter,
|
||||
type JobHandler,
|
||||
type JobContext
|
||||
} from './background-jobs';
|
||||
|
||||
// Checkpoints
|
||||
export {
|
||||
CheckpointManager,
|
||||
createCheckpointManager,
|
||||
MemoryCheckpointStorage,
|
||||
FileCheckpointStorage,
|
||||
createFileCheckpointStorage,
|
||||
type CheckpointData,
|
||||
type CheckpointConfig,
|
||||
type CheckpointStorage
|
||||
} from './checkpoints';
|
||||
|
||||
// Flow Display
|
||||
export {
|
||||
FlowDisplay,
|
||||
createFlowDisplay,
|
||||
renderWorkflow,
|
||||
type FlowNode,
|
||||
type FlowGraph,
|
||||
type FlowDisplayConfig
|
||||
} from './flow-display';
|
||||
|
||||
// External Agents
|
||||
export {
|
||||
BaseExternalAgent,
|
||||
ClaudeCodeAgent,
|
||||
GeminiCliAgent,
|
||||
CodexCliAgent,
|
||||
AiderAgent,
|
||||
GenericExternalAgent,
|
||||
getExternalAgentRegistry,
|
||||
createExternalAgent,
|
||||
externalAgentAsTool,
|
||||
type ExternalAgentConfig,
|
||||
type ExternalAgentResult
|
||||
} from './external-agents';
|
||||
|
||||
// N8N Integration
|
||||
export {
|
||||
N8NIntegration,
|
||||
createN8NIntegration,
|
||||
triggerN8NWebhook,
|
||||
type N8NConfig,
|
||||
type N8NWebhookPayload,
|
||||
type N8NWorkflow,
|
||||
type N8NWorkflowNode
|
||||
} from './n8n-integration';
|
||||
|
||||
// Fast Context
|
||||
export {
|
||||
FastContext,
|
||||
createFastContext,
|
||||
getQuickContext,
|
||||
type FastContextConfig,
|
||||
type ContextSource,
|
||||
type FastContextResult
|
||||
} from './fast-context';
|
||||
@@ -0,0 +1,343 @@
|
||||
/**
|
||||
* Interactive TUI - Terminal User Interface for CLI
|
||||
* Minimal but functional interactive mode with readline
|
||||
*/
|
||||
|
||||
import { SlashCommandHandler, isSlashCommand, SlashCommandContext } from './slash-commands';
|
||||
import { CostTracker, createCostTracker } from './cost-tracker';
|
||||
|
||||
export interface TUIConfig {
|
||||
prompt?: string;
|
||||
welcomeMessage?: string;
|
||||
historyFile?: string;
|
||||
maxHistorySize?: number;
|
||||
onMessage?: (message: string) => Promise<string>;
|
||||
onExit?: () => void;
|
||||
}
|
||||
|
||||
export interface TUIState {
|
||||
running: boolean;
|
||||
history: string[];
|
||||
context: SlashCommandContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interactive TUI class
|
||||
*/
|
||||
export class InteractiveTUI {
|
||||
private config: TUIConfig;
|
||||
private state: TUIState;
|
||||
private slashHandler: SlashCommandHandler;
|
||||
private costTracker: CostTracker;
|
||||
private readline: any;
|
||||
private rl: any;
|
||||
|
||||
constructor(config: TUIConfig = {}) {
|
||||
this.config = {
|
||||
prompt: '> ',
|
||||
welcomeMessage: 'PraisonAI Interactive Mode. Type /help for commands, /exit to quit.',
|
||||
maxHistorySize: 1000,
|
||||
...config
|
||||
};
|
||||
|
||||
this.costTracker = createCostTracker();
|
||||
this.state = {
|
||||
running: false,
|
||||
history: [],
|
||||
context: {
|
||||
history: [],
|
||||
settings: {},
|
||||
costTracker: this.costTracker,
|
||||
onOutput: (msg) => this.output(msg)
|
||||
}
|
||||
};
|
||||
|
||||
this.slashHandler = new SlashCommandHandler(this.state.context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the interactive session
|
||||
*/
|
||||
async start(): Promise<void> {
|
||||
if (this.state.running) return;
|
||||
|
||||
// Lazy load readline
|
||||
this.readline = await import('readline');
|
||||
this.rl = this.readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
terminal: true
|
||||
});
|
||||
|
||||
this.state.running = true;
|
||||
|
||||
// Load history if available
|
||||
await this.loadHistory();
|
||||
|
||||
// Show welcome message
|
||||
if (this.config.welcomeMessage) {
|
||||
this.output(this.config.welcomeMessage);
|
||||
}
|
||||
|
||||
// Start the input loop
|
||||
await this.inputLoop();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the interactive session
|
||||
*/
|
||||
stop(): void {
|
||||
this.state.running = false;
|
||||
if (this.rl) {
|
||||
this.rl.close();
|
||||
}
|
||||
this.saveHistory();
|
||||
this.config.onExit?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* Main input loop
|
||||
*/
|
||||
private async inputLoop(): Promise<void> {
|
||||
while (this.state.running) {
|
||||
const input = await this.prompt();
|
||||
|
||||
if (input === null) {
|
||||
// EOF or Ctrl+C
|
||||
this.stop();
|
||||
break;
|
||||
}
|
||||
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
// Add to history
|
||||
this.addToHistory(trimmed);
|
||||
|
||||
// Handle slash commands
|
||||
if (isSlashCommand(trimmed)) {
|
||||
const result = await this.slashHandler.handle(trimmed);
|
||||
if (result.shouldExit) {
|
||||
this.stop();
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle regular message
|
||||
if (this.config.onMessage) {
|
||||
try {
|
||||
const response = await this.config.onMessage(trimmed);
|
||||
this.output(response);
|
||||
} catch (error: any) {
|
||||
this.output(`Error: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
this.output('No message handler configured. Use /help for available commands.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt for input
|
||||
*/
|
||||
private prompt(): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
if (!this.state.running || !this.rl) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
this.rl.question(this.config.prompt, (answer: string) => {
|
||||
resolve(answer);
|
||||
});
|
||||
|
||||
// Handle Ctrl+C
|
||||
this.rl.once('close', () => {
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Output a message
|
||||
*/
|
||||
private output(message: string): void {
|
||||
console.log(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add input to history
|
||||
*/
|
||||
private addToHistory(input: string): void {
|
||||
this.state.history.push(input);
|
||||
if (this.state.history.length > (this.config.maxHistorySize || 1000)) {
|
||||
this.state.history.shift();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load history from file
|
||||
*/
|
||||
private async loadHistory(): Promise<void> {
|
||||
if (!this.config.historyFile) return;
|
||||
|
||||
try {
|
||||
const fs = await import('fs/promises');
|
||||
const content = await fs.readFile(this.config.historyFile, 'utf-8');
|
||||
this.state.history = content.trim().split('\n').filter(Boolean);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save history to file
|
||||
*/
|
||||
private async saveHistory(): Promise<void> {
|
||||
if (!this.config.historyFile) return;
|
||||
|
||||
try {
|
||||
const fs = await import('fs/promises');
|
||||
await fs.writeFile(this.config.historyFile, this.state.history.join('\n'));
|
||||
} catch {
|
||||
// Ignore save errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current state
|
||||
*/
|
||||
getState(): TUIState {
|
||||
return { ...this.state };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get cost tracker
|
||||
*/
|
||||
getCostTracker(): CostTracker {
|
||||
return this.costTracker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update context
|
||||
*/
|
||||
updateContext(updates: Partial<SlashCommandContext>): void {
|
||||
this.slashHandler.updateContext(updates);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an interactive TUI instance
|
||||
*/
|
||||
export function createInteractiveTUI(config?: TUIConfig): InteractiveTUI {
|
||||
return new InteractiveTUI(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple status display helper
|
||||
*/
|
||||
export class StatusDisplay {
|
||||
private lines: string[] = [];
|
||||
|
||||
add(label: string, value: string | number): this {
|
||||
this.lines.push(`${label}: ${value}`);
|
||||
return this;
|
||||
}
|
||||
|
||||
addSeparator(): this {
|
||||
this.lines.push('─'.repeat(40));
|
||||
return this;
|
||||
}
|
||||
|
||||
addHeader(text: string): this {
|
||||
this.lines.push(`\n=== ${text} ===`);
|
||||
return this;
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return this.lines.join('\n');
|
||||
}
|
||||
|
||||
print(): void {
|
||||
console.log(this.toString());
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.lines = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a status display
|
||||
*/
|
||||
export function createStatusDisplay(): StatusDisplay {
|
||||
return new StatusDisplay();
|
||||
}
|
||||
|
||||
/**
|
||||
* History manager for persistent command history
|
||||
*/
|
||||
export class HistoryManager {
|
||||
private history: string[] = [];
|
||||
private maxSize: number;
|
||||
private filePath?: string;
|
||||
|
||||
constructor(maxSize: number = 1000, filePath?: string) {
|
||||
this.maxSize = maxSize;
|
||||
this.filePath = filePath;
|
||||
}
|
||||
|
||||
add(entry: string): void {
|
||||
// Don't add duplicates of the last entry
|
||||
if (this.history[this.history.length - 1] === entry) return;
|
||||
|
||||
this.history.push(entry);
|
||||
if (this.history.length > this.maxSize) {
|
||||
this.history.shift();
|
||||
}
|
||||
}
|
||||
|
||||
getAll(): string[] {
|
||||
return [...this.history];
|
||||
}
|
||||
|
||||
search(query: string): string[] {
|
||||
const lower = query.toLowerCase();
|
||||
return this.history.filter(h => h.toLowerCase().includes(lower));
|
||||
}
|
||||
|
||||
async load(): Promise<void> {
|
||||
if (!this.filePath) return;
|
||||
|
||||
try {
|
||||
const fs = await import('fs/promises');
|
||||
const content = await fs.readFile(this.filePath, 'utf-8');
|
||||
this.history = content.trim().split('\n').filter(Boolean);
|
||||
} catch {
|
||||
// File doesn't exist yet
|
||||
}
|
||||
}
|
||||
|
||||
async save(): Promise<void> {
|
||||
if (!this.filePath) return;
|
||||
|
||||
try {
|
||||
const fs = await import('fs/promises');
|
||||
await fs.writeFile(this.filePath, this.history.join('\n'));
|
||||
} catch {
|
||||
// Ignore save errors
|
||||
}
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.history = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a history manager
|
||||
*/
|
||||
export function createHistoryManager(maxSize?: number, filePath?: string): HistoryManager {
|
||||
return new HistoryManager(maxSize, filePath);
|
||||
}
|
||||
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user