mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-09 03:39:37 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2d181dd74 | ||
|
|
7411fdbb52 | ||
|
|
e7a8ce8eb7 | ||
|
|
61fb094306 | ||
|
|
018e8c78ab | ||
|
|
f0f0f653fe | ||
|
|
98a4ff8450 | ||
|
|
d6333aaf33 | ||
|
|
8005094267 | ||
|
|
08b21dabe3 | ||
|
|
8c70d840df | ||
|
|
d8e944c1d3 |
No files matched your search
@@ -35,46 +35,108 @@ PraisonAI is a production-ready Multi-AI Agents framework with self-reflection,
|
||||
|
||||
---
|
||||
|
||||
> **Quick Paths:**
|
||||
> - 🚀 **New here?** → [Quick Start](#-quick-start)
|
||||
> - 📦 **Installing?** → [Installation](#-installation)
|
||||
> - 💻 **Python SDK?** → [Python Examples](#-using-python-code)
|
||||
> - 🎯 **CLI user?** → [CLI Reference](#-cli--no-code-interface)
|
||||
> - 🔧 **Need config?** → [Configuration](#-configuration--integration)
|
||||
> - 🤝 **Contributing?** → [Development](#-development)
|
||||
|
||||
---
|
||||
|
||||
## 📑 Table of Contents
|
||||
|
||||
### Getting Started
|
||||
- [⚡ Performance](#-performance)
|
||||
- [🚀 Quick Start](#-quick-start)
|
||||
- [📦 Installation](#-installation)
|
||||
- [Python SDK](#python-sdk)
|
||||
- [JavaScript SDK](#javascript-sdk)
|
||||
- [💻 Usage](#-usage)
|
||||
- [Python Code Examples](#python-code-examples)
|
||||
- [CLI / No-Code Interface](#cli--no-code-interface)
|
||||
- [JavaScript Code Examples](#javascript-code-examples)
|
||||
- [Environment Variables](#environment-variables)
|
||||
|
||||
### Core Concepts
|
||||
- [✨ Key Features](#-key-features)
|
||||
- [🌐 Supported Providers](#-supported-providers)
|
||||
|
||||
### Python SDK
|
||||
- [📘 Python Examples](#-using-python-code)
|
||||
- [1. Single Agent](#1-single-agent)
|
||||
- [2. Multi Agents](#2-multi-agents)
|
||||
- [3. Planning Mode](#3-agent-with-planning-mode)
|
||||
- [4. Deep Research](#4-deep-research-agent)
|
||||
- [5. Query Rewriter](#5-query-rewriter-agent)
|
||||
- [6. Agent Memory](#6-agent-memory-zero-dependencies)
|
||||
- [7. Rules & Instructions](#7-rules--instructions)
|
||||
- [8. Auto-Generated Memories](#8-auto-generated-memories)
|
||||
- [9. Agentic Workflows](#9-agentic-workflows)
|
||||
- [10. Hooks](#10-hooks)
|
||||
- [11. Shadow Git Checkpoints](#11-shadow-git-checkpoints)
|
||||
- [12. Background Tasks](#12-background-tasks)
|
||||
- [13. Policy Engine](#13-policy-engine)
|
||||
- [14. Thinking Budgets](#14-thinking-budgets)
|
||||
- [15. Output Styles](#15-output-styles)
|
||||
- [16. Context Compaction](#16-context-compaction)
|
||||
- [17. Field Names Reference](#17-field-names-reference-a-i-g-s)
|
||||
- [18. Extended agents.yaml](#18-extended-agentsyaml-with-workflow-patterns)
|
||||
- [19. MCP Protocol](#19-mcp-model-context-protocol)
|
||||
- [20. A2A Protocol](#20-a2a-agent2agent-protocol)
|
||||
- [🛠️ Custom Tools](#️-custom-tools)
|
||||
|
||||
### JavaScript SDK
|
||||
- [💻 JavaScript Examples](#-using-javascript-code)
|
||||
|
||||
### CLI Reference
|
||||
- [🎯 CLI Overview](#-cli--no-code-interface)
|
||||
- [Auto Mode](#auto-mode)
|
||||
- [Interactive Mode](#interactive-mode-cli)
|
||||
- [Deep Research CLI](#deep-research-cli)
|
||||
- [Planning Mode CLI](#planning-mode-cli)
|
||||
- [Memory CLI](#memory-cli)
|
||||
- [Workflow CLI](#workflow-cli)
|
||||
- [Knowledge CLI](#knowledge-cli)
|
||||
- [Session CLI](#session-cli)
|
||||
- [Tools CLI](#tools-cli)
|
||||
- [MCP Config CLI](#mcp-config-cli)
|
||||
- [External Agents CLI](#external-agents-cli)
|
||||
- [CLI Features Summary](#cli-features)
|
||||
|
||||
### Configuration
|
||||
- [🔧 Configuration & Integration](#-configuration--integration)
|
||||
- [Ollama Integration](#ollama-integration)
|
||||
- [Groq Integration](#groq-integration)
|
||||
- [100+ Models Support](#100-models-support)
|
||||
- [📋 Workflows](#-workflows)
|
||||
- [Workflow Patterns](#workflow-patterns)
|
||||
- [YAML Configuration](#yaml-configuration)
|
||||
- [Agents Playbook](#agents-playbook)
|
||||
- [🧠 Memory & Context](#-memory--context)
|
||||
- [📋 Agents Playbook](#-agents-playbook)
|
||||
|
||||
### Advanced Features
|
||||
- [🔬 Advanced Features](#-advanced-features)
|
||||
- [Research & Intelligence](#research--intelligence)
|
||||
- [Memory & Caching](#memory--caching)
|
||||
- [Planning & Workflows](#planning--workflows)
|
||||
- [Specialised Agents](#specialised-agents)
|
||||
- [MCP Protocol](#mcp-protocol)
|
||||
- [A2A & A2UI Protocols](#a2a--a2ui-protocols)
|
||||
- [Safety & Control](#safety--control)
|
||||
- [Developer Tools](#developer-tools)
|
||||
|
||||
### Architecture
|
||||
- [📊 Process Types & Patterns](#-process-types--patterns)
|
||||
- [Sequential Process](#sequential-process)
|
||||
- [Hierarchical Process](#hierarchical-process)
|
||||
- [Workflow Process](#workflow-process)
|
||||
- [Agentic Patterns](#agentic-patterns)
|
||||
|
||||
### Data & Persistence
|
||||
- [💾 Persistence (Databases)](#-persistence-databases)
|
||||
- [📚 Knowledge & Retrieval (RAG)](#-knowledge--retrieval-rag)
|
||||
- [🔧 Tools Table](#-tools-table)
|
||||
|
||||
### Learning & Community
|
||||
- [🎓 Video Tutorials](#-video-tutorials)
|
||||
- [⭐ Star History](#-star-history)
|
||||
- [👥 Contributing](#-contributing)
|
||||
- [🔧 Development](#-development)
|
||||
- [❓ FAQ & Troubleshooting](#-faq--troubleshooting)
|
||||
|
||||
---
|
||||
|
||||
@@ -143,6 +205,30 @@ pip install praisonai
|
||||
npm install praisonai
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Required | Description |
|
||||
|----------|----------|-------------|
|
||||
| `OPENAI_API_KEY` | Yes* | OpenAI API key |
|
||||
| `ANTHROPIC_API_KEY` | No | Anthropic Claude API key |
|
||||
| `GOOGLE_API_KEY` | No | Google Gemini API key |
|
||||
| `GROQ_API_KEY` | No | Groq API key |
|
||||
| `OPENAI_BASE_URL` | No | Custom API endpoint (for Ollama, Groq, etc.) |
|
||||
|
||||
> *At least one LLM provider API key is required.
|
||||
|
||||
```bash
|
||||
# Set your API key
|
||||
export OPENAI_API_KEY=your_key_here
|
||||
|
||||
# For Ollama (local models)
|
||||
export OPENAI_BASE_URL=http://localhost:11434/v1
|
||||
|
||||
# For Groq
|
||||
export OPENAI_API_KEY=your_groq_key
|
||||
export OPENAI_BASE_URL=https://api.groq.com/openai/v1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💻 Usage
|
||||
@@ -169,147 +255,263 @@ npm install praisonai
|
||||
|
||||
## ✨ Key Features
|
||||
|
||||
<details open>
|
||||
<summary><strong>🤖 Core Agents</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| **🤖 Core Agents** | | |
|
||||
| ↳ Single Agent | [Example](examples/python/agents/single-agent.py) | [📖](https://docs.praison.ai/agents/single) |
|
||||
| ↳ Multi Agents | [Example](examples/python/general/mini_agents_example.py) | [📖](https://docs.praison.ai/concepts/agents) |
|
||||
| ↳ Auto Agents | [Example](examples/python/general/auto_agents_example.py) | [📖](https://docs.praison.ai/features/autoagents) |
|
||||
| ↳ Self Reflection AI Agents | [Example](examples/python/concepts/self-reflection-details.py) | [📖](https://docs.praison.ai/features/selfreflection) |
|
||||
| ↳ Reasoning AI Agents | [Example](examples/python/concepts/reasoning-extraction.py) | [📖](https://docs.praison.ai/features/reasoning) |
|
||||
| ↳ Multi Modal AI Agents | [Example](examples/python/general/multimodal.py) | [📖](https://docs.praison.ai/features/multimodal) |
|
||||
| **🔄 Workflows** | | |
|
||||
| ↳ Simple Workflow | [Example](examples/python/workflows/simple_workflow.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| ↳ Workflow with Agents | [Example](examples/python/workflows/workflow_with_agents.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| ↳ Agentic Routing (`route()`) | [Example](examples/python/workflows/workflow_routing.py) | [📖](https://docs.praison.ai/features/routing) |
|
||||
| ↳ Parallel Execution (`parallel()`) | [Example](examples/python/workflows/workflow_parallel.py) | [📖](https://docs.praison.ai/features/parallelisation) |
|
||||
| ↳ Loop over List/CSV (`loop()`) | [Example](examples/python/workflows/workflow_loop_csv.py) | [📖](https://docs.praison.ai/features/repetitive) |
|
||||
| ↳ Evaluator-Optimizer (`repeat()`) | [Example](examples/python/workflows/workflow_repeat.py) | [📖](https://docs.praison.ai/features/evaluator-optimiser) |
|
||||
| ↳ Conditional Steps | [Example](examples/python/workflows/workflow_conditional.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| ↳ Workflow Branching | [Example](examples/python/workflows/workflow_branching.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| ↳ Workflow Early Stop | [Example](examples/python/workflows/workflow_early_stop.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| ↳ Workflow Checkpoints | [Example](examples/python/workflows/workflow_checkpoints.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| **💻 Code & Development** | | |
|
||||
| ↳ Code Interpreter Agents | [Example](examples/python/agents/code-agent.py) | [📖](https://docs.praison.ai/features/codeagent) |
|
||||
| ↳ AI Code Editing Tools | [Example](examples/python/code/code_editing_example.py) | [📖](https://docs.praison.ai/code/editing) |
|
||||
| ↳ External Agents (All) | [Example](examples/python/code/external_agents_example.py) | [📖](https://docs.praison.ai/code/external-agents) |
|
||||
| ↳ Claude Code CLI | [Example](examples/python/code/claude_code_example.py) | [📖](https://docs.praison.ai/code/claude-code) |
|
||||
| ↳ Gemini CLI | [Example](examples/python/code/gemini_cli_example.py) | [📖](https://docs.praison.ai/code/gemini-cli) |
|
||||
| ↳ Codex CLI | [Example](examples/python/code/codex_cli_example.py) | [📖](https://docs.praison.ai/code/codex-cli) |
|
||||
| ↳ Cursor CLI | [Example](examples/python/code/cursor_cli_example.py) | [📖](https://docs.praison.ai/code/cursor-cli) |
|
||||
| **🧠 Memory & Knowledge** | | |
|
||||
| ↳ Memory (Short & Long Term) | [Example](examples/python/general/memory_example.py) | [📖](https://docs.praison.ai/concepts/memory) |
|
||||
| ↳ File-Based Memory | [Example](examples/python/general/memory_example.py) | [📖](https://docs.praison.ai/concepts/memory) |
|
||||
| ↳ Claude Memory Tool | [Example](#claude-memory-tool-cli) | [📖](https://docs.praison.ai/features/claude-memory-tool) |
|
||||
| ↳ Add Custom Knowledge | [Example](examples/python/concepts/knowledge-agents.py) | [📖](https://docs.praison.ai/features/knowledge) |
|
||||
| ↳ RAG Agents | [Example](examples/python/concepts/rag-agents.py) | [📖](https://docs.praison.ai/features/rag) |
|
||||
| ↳ Chat with PDF Agents | [Example](examples/python/concepts/chat-with-pdf.py) | [📖](https://docs.praison.ai/features/chat-with-pdf) |
|
||||
| ↳ Data Readers (PDF, DOCX, etc.) | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-readers-api) |
|
||||
| ↳ Vector Store Selection | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-vector-store-api) |
|
||||
| ↳ Retrieval Strategies | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-retrieval-api) |
|
||||
| ↳ Rerankers | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-reranker-api) |
|
||||
| ↳ Index Types (Vector/Keyword/Hybrid) | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-index-api) |
|
||||
| ↳ Query Engines (Sub-Question, etc.) | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-query-engine-api) |
|
||||
| **🔬 Research & Intelligence** | | |
|
||||
| ↳ Deep Research Agents | [Example](examples/python/agents/research-agent.py) | [📖](https://docs.praison.ai/agents/deep-research) |
|
||||
| ↳ Query Rewriter Agent | [Example](#5-query-rewriter-agent) | [📖](https://docs.praison.ai/agents/query-rewriter) |
|
||||
| ↳ Native Web Search | [Example](examples/python/agents/websearch-agent.py) | [📖](https://docs.praison.ai/agents/websearch) |
|
||||
| ↳ Built-in Search Tools | [Example](examples/python/agents/websearch-agent.py) | [📖](https://docs.praison.ai/tools/tavily) |
|
||||
| ↳ Unified Web Search | [Example](src/praisonai-agents/examples/web_search_example.py) | [📖](https://docs.praison.ai/tools/web-search) |
|
||||
| ↳ Web Fetch (Anthropic) | [Example](#web-search-web-fetch--prompt-caching) | [📖](https://docs.praison.ai/features/model-capabilities) |
|
||||
| **📋 Planning & Execution** | | |
|
||||
| ↳ Planning Mode | [Example](examples/python/agents/planning-agent.py) | [📖](https://docs.praison.ai/features/planning-mode) |
|
||||
| ↳ Planning Tools | [Example](#3-agent-with-planning-mode) | [📖](https://docs.praison.ai/features/planning-mode) |
|
||||
| ↳ Planning Reasoning | [Example](#3-agent-with-planning-mode) | [📖](https://docs.praison.ai/features/planning-mode) |
|
||||
| ↳ Prompt Chaining | [Example](examples/python/general/prompt_chaining.py) | [📖](https://docs.praison.ai/features/promptchaining) |
|
||||
| ↳ Evaluator Optimiser | [Example](examples/python/general/evaluator-optimiser.py) | [📖](https://docs.praison.ai/features/evaluator-optimiser) |
|
||||
| ↳ Orchestrator Workers | [Example](examples/python/general/orchestrator-workers.py) | [📖](https://docs.praison.ai/features/orchestrator-worker) |
|
||||
| **👥 Specialized Agents** | | |
|
||||
| ↳ Data Analyst Agent | [Example](examples/python/agents/data-analyst-agent.py) | [📖](https://docs.praison.ai/agents/data-analyst) |
|
||||
| ↳ Finance Agent | [Example](examples/python/agents/finance-agent.py) | [📖](https://docs.praison.ai/agents/finance) |
|
||||
| ↳ Shopping Agent | [Example](examples/python/agents/shopping-agent.py) | [📖](https://docs.praison.ai/agents/shopping) |
|
||||
| ↳ Recommendation Agent | [Example](examples/python/agents/recommendation-agent.py) | [📖](https://docs.praison.ai/agents/recommendation) |
|
||||
| ↳ Wikipedia Agent | [Example](examples/python/agents/wikipedia-agent.py) | [📖](https://docs.praison.ai/agents/wikipedia) |
|
||||
| ↳ Programming Agent | [Example](examples/python/agents/programming-agent.py) | [📖](https://docs.praison.ai/agents/programming) |
|
||||
| ↳ Math Agents | [Example](examples/python/agents/math-agent.py) | [📖](https://docs.praison.ai/features/mathagent) |
|
||||
| ↳ Markdown Agent | [Example](examples/python/agents/markdown-agent.py) | [📖](https://docs.praison.ai/agents/markdown) |
|
||||
| ↳ Prompt Expander Agent | [Example](#prompt-expansion) | [📖](https://docs.praison.ai/agents/prompt-expander) |
|
||||
| **🎨 Media & Multimodal** | | |
|
||||
| ↳ Image Generation Agent | [Example](examples/python/image/image-agent.py) | [📖](https://docs.praison.ai/features/image-generation) |
|
||||
| ↳ Image to Text Agent | [Example](examples/python/agents/image-to-text-agent.py) | [📖](https://docs.praison.ai/agents/image-to-text) |
|
||||
| ↳ Video Agent | [Example](examples/python/agents/video-agent.py) | [📖](https://docs.praison.ai/agents/video) |
|
||||
| ↳ Camera Integration | [Example](examples/python/camera/) | [📖](https://docs.praison.ai/features/camera-integration) |
|
||||
| **🔌 Protocols & Integration** | | |
|
||||
| ↳ MCP Transports | [Example](examples/python/mcp/mcp-transports-overview.py) | [📖](https://docs.praison.ai/mcp/transports) |
|
||||
| ↳ WebSocket MCP | [Example](examples/python/mcp/websocket-mcp.py) | [📖](https://docs.praison.ai/mcp/sse-transport) |
|
||||
| ↳ MCP Security | [Example](examples/python/mcp/mcp-security.py) | [📖](https://docs.praison.ai/mcp/transports) |
|
||||
| ↳ MCP Resumability | [Example](examples/python/mcp/mcp-resumability.py) | [📖](https://docs.praison.ai/mcp/sse-transport) |
|
||||
| ↳ MCP Config Management | [Example](#mcp-config-cli) | [📖](https://docs.praison.ai/docs/cli/mcp) |
|
||||
| ↳ LangChain Integrated Agents | [Example](examples/python/general/langchain_example.py) | [📖](https://docs.praison.ai/features/langchain) |
|
||||
| **🛡️ Safety & Control** | | |
|
||||
| ↳ Guardrails | [Example](examples/python/guardrails/comprehensive-guardrails-example.py) | [📖](https://docs.praison.ai/features/guardrails) |
|
||||
| ↳ Human Approval | [Example](examples/python/general/human_approval_example.py) | [📖](https://docs.praison.ai/features/approval) |
|
||||
| ↳ Rules & Instructions | [Example](#6-rules--instructions) | [📖](https://docs.praison.ai/features/rules) |
|
||||
| **⚙️ Advanced Features** | | |
|
||||
| ↳ Async & Parallel Processing | [Example](examples/python/general/async_example.py) | [📖](https://docs.praison.ai/features/async) |
|
||||
| ↳ Parallelisation | [Example](examples/python/general/parallelisation.py) | [📖](https://docs.praison.ai/features/parallelisation) |
|
||||
| ↳ Repetitive Agents | [Example](examples/python/concepts/repetitive-agents.py) | [📖](https://docs.praison.ai/features/repetitive) |
|
||||
| ↳ Agent Handoffs | [Example](examples/python/handoff/handoff_basic.py) | [📖](https://docs.praison.ai/features/handoffs) |
|
||||
| ↳ Stateful Agents | [Example](examples/python/stateful/workflow-state-example.py) | [📖](https://docs.praison.ai/features/stateful-agents) |
|
||||
| ↳ Autonomous Workflow | [Example](examples/python/general/autonomous-agent.py) | [📖](https://docs.praison.ai/features/autonomous-workflow) |
|
||||
| ↳ Structured Output Agents | [Example](examples/python/general/structured_agents_example.py) | [📖](https://docs.praison.ai/features/structured) |
|
||||
| ↳ Model Router | [Example](examples/python/agents/router-agent-cost-optimization.py) | [📖](https://docs.praison.ai/features/model-router) |
|
||||
| ↳ Prompt Caching | [Example](#web-search-web-fetch--prompt-caching) | [📖](https://docs.praison.ai/features/model-capabilities) |
|
||||
| ↳ Fast Context | [Example](examples/context/00_agent_fast_context_basic.py) | [📖](https://docs.praison.ai/features/fast-context) |
|
||||
| **🛠️ Tools & Configuration** | | |
|
||||
| ↳ 100+ Custom Tools | [Example](examples/python/general/tools_example.py) | [📖](https://docs.praison.ai/tools/tools) |
|
||||
| ↳ YAML Configuration | [Example](examples/cookbooks/yaml/secondary_market_research_agents.yaml) | [📖](https://docs.praison.ai/developers/agents-playbook) |
|
||||
| ↳ 100+ LLM Support | [Example](examples/python/providers/openai/openai_gpt4_example.py) | [📖](https://docs.praison.ai/models) |
|
||||
| ↳ Callback Agents | [Example](examples/python/general/advanced-callback-systems.py) | [📖](https://docs.praison.ai/features/callbacks) |
|
||||
| ↳ Hooks | [Example](#9-hooks) | [📖](https://docs.praison.ai/features/hooks) |
|
||||
| ↳ Middleware System | [Example](examples/middleware/basic_middleware.py) | [📖](https://docs.praison.ai/features/middleware) |
|
||||
| ↳ Configurable Model | [Example](examples/middleware/configurable_model.py) | [📖](https://docs.praison.ai/features/configurable-model) |
|
||||
| ↳ Rate Limiter | [Example](examples/middleware/rate_limiter.py) | [📖](https://docs.praison.ai/features/rate-limiter) |
|
||||
| ↳ Injected Tool State | [Example](examples/middleware/injected_state.py) | [📖](https://docs.praison.ai/features/injected-state) |
|
||||
| ↳ Shadow Git Checkpoints | [Example](#10-shadow-git-checkpoints) | [📖](https://docs.praison.ai/features/checkpoints) |
|
||||
| ↳ Background Tasks | [Example](examples/background/basic_background.py) | [📖](https://docs.praison.ai/features/background-tasks) |
|
||||
| ↳ Policy Engine | [Example](examples/policy/basic_policy.py) | [📖](https://docs.praison.ai/features/policy-engine) |
|
||||
| ↳ Thinking Budgets | [Example](examples/thinking/basic_thinking.py) | [📖](https://docs.praison.ai/features/thinking-budgets) |
|
||||
| ↳ Output Styles | [Example](examples/output/basic_output.py) | [📖](https://docs.praison.ai/features/output-styles) |
|
||||
| ↳ Context Compaction | [Example](examples/compaction/basic_compaction.py) | [📖](https://docs.praison.ai/features/context-compaction) |
|
||||
| **📊 Monitoring & Management** | | |
|
||||
| ↳ Sessions Management | [Example](examples/python/sessions/comprehensive-session-management.py) | [📖](https://docs.praison.ai/features/sessions) |
|
||||
| ↳ Auto-Save Sessions | [Example](#session-management-python) | [📖](https://docs.praison.ai/docs/cli/session) |
|
||||
| ↳ History in Context | [Example](#session-management-python) | [📖](https://docs.praison.ai/docs/cli/session) |
|
||||
| ↳ Telemetry | [Example](examples/python/telemetry/production-telemetry-example.py) | [📖](https://docs.praison.ai/features/telemetry) |
|
||||
| ↳ Project Docs (.praison/docs/) | [Example](#docs-cli) | [📖](https://docs.praison.ai/docs/cli/docs) |
|
||||
| ↳ AI Commit Messages | [Example](#ai-commit-cli) | [📖](https://docs.praison.ai/docs/cli/commit) |
|
||||
| ↳ @Mentions in Prompts | [Example](#mentions-in-prompts) | [📖](https://docs.praison.ai/docs/cli/mentions) |
|
||||
| **🖥️ CLI Features** | | |
|
||||
| ↳ Slash Commands | [Example](examples/python/cli/slash_commands_example.py) | [📖](https://docs.praison.ai/docs/cli/slash-commands) |
|
||||
| ↳ Autonomy Modes | [Example](examples/python/cli/autonomy_modes_example.py) | [📖](https://docs.praison.ai/docs/cli/autonomy-modes) |
|
||||
| ↳ Cost Tracking | [Example](examples/python/cli/cost_tracking_example.py) | [📖](https://docs.praison.ai/docs/cli/cost-tracking) |
|
||||
| ↳ Repository Map | [Example](examples/python/cli/repo_map_example.py) | [📖](https://docs.praison.ai/docs/cli/repo-map) |
|
||||
| ↳ Interactive TUI | [Example](examples/python/cli/interactive_tui_example.py) | [📖](https://docs.praison.ai/docs/cli/interactive-tui) |
|
||||
| ↳ Git Integration | [Example](examples/python/cli/git_integration_example.py) | [📖](https://docs.praison.ai/docs/cli/git-integration) |
|
||||
| ↳ Sandbox Execution | [Example](examples/python/cli/sandbox_execution_example.py) | [📖](https://docs.praison.ai/docs/cli/sandbox-execution) |
|
||||
| ↳ CLI Compare | [Example](examples/compare/cli_compare_basic.py) | [📖](https://docs.praison.ai/docs/cli/compare) |
|
||||
| ↳ Profile/Benchmark | [Example](#profile-benchmark) | [📖](https://docs.praison.ai/docs/cli/profile) |
|
||||
| ↳ Auto Mode | [Example](#auto-mode) | [📖](https://docs.praison.ai/docs/cli/auto) |
|
||||
| ↳ Init | [Example](#init) | [📖](https://docs.praison.ai/docs/cli/init) |
|
||||
| ↳ File Input | [Example](#file-input) | [📖](https://docs.praison.ai/docs/cli/file-input) |
|
||||
| ↳ Final Agent | [Example](#final-agent) | [📖](https://docs.praison.ai/docs/cli/final-agent) |
|
||||
| ↳ Max Tokens | [Example](#max-tokens) | [📖](https://docs.praison.ai/docs/cli/max-tokens) |
|
||||
| **🧪 Evaluation** | | |
|
||||
| ↳ Accuracy Evaluation | [Example](examples/eval/accuracy_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
| ↳ Performance Evaluation | [Example](examples/eval/performance_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
| ↳ Reliability Evaluation | [Example](examples/eval/reliability_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
| ↳ Criteria Evaluation | [Example](examples/eval/criteria_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
| **🎯 Agent Skills** | | |
|
||||
| ↳ Skills Management | [Example](examples/skills/basic_skill_usage.py) | [📖](https://docs.praison.ai/features/skills) |
|
||||
| ↳ Custom Skills | [Example](examples/skills/custom_skill_example.py) | [📖](https://docs.praison.ai/features/skills) |
|
||||
| **⏰ 24/7 Scheduling** | | |
|
||||
| ↳ Agent Scheduler | [Example](examples/python/scheduled_agents/news_checker_live.py) | [📖](https://docs.praison.ai/docs/cli/scheduler) |
|
||||
| Single Agent | [Example](examples/python/agents/single-agent.py) | [📖](https://docs.praison.ai/agents/single) |
|
||||
| Multi Agents | [Example](examples/python/general/mini_agents_example.py) | [📖](https://docs.praison.ai/concepts/agents) |
|
||||
| Auto Agents | [Example](examples/python/general/auto_agents_example.py) | [📖](https://docs.praison.ai/features/autoagents) |
|
||||
| Self Reflection AI Agents | [Example](examples/python/concepts/self-reflection-details.py) | [📖](https://docs.praison.ai/features/selfreflection) |
|
||||
| Reasoning AI Agents | [Example](examples/python/concepts/reasoning-extraction.py) | [📖](https://docs.praison.ai/features/reasoning) |
|
||||
| Multi Modal AI Agents | [Example](examples/python/general/multimodal.py) | [📖](https://docs.praison.ai/features/multimodal) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🔄 Workflows</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Simple Workflow | [Example](examples/python/workflows/simple_workflow.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| Workflow with Agents | [Example](examples/python/workflows/workflow_with_agents.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| Agentic Routing (`route()`) | [Example](examples/python/workflows/workflow_routing.py) | [📖](https://docs.praison.ai/features/routing) |
|
||||
| Parallel Execution (`parallel()`) | [Example](examples/python/workflows/workflow_parallel.py) | [📖](https://docs.praison.ai/features/parallelisation) |
|
||||
| Loop over List/CSV (`loop()`) | [Example](examples/python/workflows/workflow_loop_csv.py) | [📖](https://docs.praison.ai/features/repetitive) |
|
||||
| Evaluator-Optimizer (`repeat()`) | [Example](examples/python/workflows/workflow_repeat.py) | [📖](https://docs.praison.ai/features/evaluator-optimiser) |
|
||||
| Conditional Steps | [Example](examples/python/workflows/workflow_conditional.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| Workflow Branching | [Example](examples/python/workflows/workflow_branching.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| Workflow Early Stop | [Example](examples/python/workflows/workflow_early_stop.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
| Workflow Checkpoints | [Example](examples/python/workflows/workflow_checkpoints.py) | [📖](https://docs.praison.ai/features/workflows) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>💻 Code & Development</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Code Interpreter Agents | [Example](examples/python/agents/code-agent.py) | [📖](https://docs.praison.ai/features/codeagent) |
|
||||
| AI Code Editing Tools | [Example](examples/python/code/code_editing_example.py) | [📖](https://docs.praison.ai/code/editing) |
|
||||
| External Agents (All) | [Example](examples/python/code/external_agents_example.py) | [📖](https://docs.praison.ai/code/external-agents) |
|
||||
| Claude Code CLI | [Example](examples/python/code/claude_code_example.py) | [📖](https://docs.praison.ai/code/claude-code) |
|
||||
| Gemini CLI | [Example](examples/python/code/gemini_cli_example.py) | [📖](https://docs.praison.ai/code/gemini-cli) |
|
||||
| Codex CLI | [Example](examples/python/code/codex_cli_example.py) | [📖](https://docs.praison.ai/code/codex-cli) |
|
||||
| Cursor CLI | [Example](examples/python/code/cursor_cli_example.py) | [📖](https://docs.praison.ai/code/cursor-cli) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🧠 Memory & Knowledge</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Memory (Short & Long Term) | [Example](examples/python/general/memory_example.py) | [📖](https://docs.praison.ai/concepts/memory) |
|
||||
| File-Based Memory | [Example](examples/python/general/memory_example.py) | [📖](https://docs.praison.ai/concepts/memory) |
|
||||
| Claude Memory Tool | [Example](#claude-memory-tool-cli) | [📖](https://docs.praison.ai/features/claude-memory-tool) |
|
||||
| Add Custom Knowledge | [Example](examples/python/concepts/knowledge-agents.py) | [📖](https://docs.praison.ai/features/knowledge) |
|
||||
| RAG Agents | [Example](examples/python/concepts/rag-agents.py) | [📖](https://docs.praison.ai/features/rag) |
|
||||
| Chat with PDF Agents | [Example](examples/python/concepts/chat-with-pdf.py) | [📖](https://docs.praison.ai/features/chat-with-pdf) |
|
||||
| Data Readers (PDF, DOCX, etc.) | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-readers-api) |
|
||||
| Vector Store Selection | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-vector-store-api) |
|
||||
| Retrieval Strategies | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-retrieval-api) |
|
||||
| Rerankers | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-reranker-api) |
|
||||
| Index Types (Vector/Keyword/Hybrid) | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-index-api) |
|
||||
| Query Engines (Sub-Question, etc.) | [CLI](#knowledge-cli) | [📖](https://docs.praison.ai/api/praisonai/knowledge-query-engine-api) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🔬 Research & Intelligence</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Deep Research Agents | [Example](examples/python/agents/research-agent.py) | [📖](https://docs.praison.ai/agents/deep-research) |
|
||||
| Query Rewriter Agent | [Example](#5-query-rewriter-agent) | [📖](https://docs.praison.ai/agents/query-rewriter) |
|
||||
| Native Web Search | [Example](examples/python/agents/websearch-agent.py) | [📖](https://docs.praison.ai/agents/websearch) |
|
||||
| Built-in Search Tools | [Example](examples/python/agents/websearch-agent.py) | [📖](https://docs.praison.ai/tools/tavily) |
|
||||
| Unified Web Search | [Example](src/praisonai-agents/examples/web_search_example.py) | [📖](https://docs.praison.ai/tools/web-search) |
|
||||
| Web Fetch (Anthropic) | [Example](#web-search-web-fetch--prompt-caching) | [📖](https://docs.praison.ai/features/model-capabilities) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>📋 Planning & Execution</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Planning Mode | [Example](examples/python/agents/planning-agent.py) | [📖](https://docs.praison.ai/features/planning-mode) |
|
||||
| Planning Tools | [Example](#3-agent-with-planning-mode) | [📖](https://docs.praison.ai/features/planning-mode) |
|
||||
| Planning Reasoning | [Example](#3-agent-with-planning-mode) | [📖](https://docs.praison.ai/features/planning-mode) |
|
||||
| Prompt Chaining | [Example](examples/python/general/prompt_chaining.py) | [📖](https://docs.praison.ai/features/promptchaining) |
|
||||
| Evaluator Optimiser | [Example](examples/python/general/evaluator-optimiser.py) | [📖](https://docs.praison.ai/features/evaluator-optimiser) |
|
||||
| Orchestrator Workers | [Example](examples/python/general/orchestrator-workers.py) | [📖](https://docs.praison.ai/features/orchestrator-worker) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>👥 Specialized Agents</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Data Analyst Agent | [Example](examples/python/agents/data-analyst-agent.py) | [📖](https://docs.praison.ai/agents/data-analyst) |
|
||||
| Finance Agent | [Example](examples/python/agents/finance-agent.py) | [📖](https://docs.praison.ai/agents/finance) |
|
||||
| Shopping Agent | [Example](examples/python/agents/shopping-agent.py) | [📖](https://docs.praison.ai/agents/shopping) |
|
||||
| Recommendation Agent | [Example](examples/python/agents/recommendation-agent.py) | [📖](https://docs.praison.ai/agents/recommendation) |
|
||||
| Wikipedia Agent | [Example](examples/python/agents/wikipedia-agent.py) | [📖](https://docs.praison.ai/agents/wikipedia) |
|
||||
| Programming Agent | [Example](examples/python/agents/programming-agent.py) | [📖](https://docs.praison.ai/agents/programming) |
|
||||
| Math Agents | [Example](examples/python/agents/math-agent.py) | [📖](https://docs.praison.ai/features/mathagent) |
|
||||
| Markdown Agent | [Example](examples/python/agents/markdown-agent.py) | [📖](https://docs.praison.ai/agents/markdown) |
|
||||
| Prompt Expander Agent | [Example](#prompt-expansion) | [📖](https://docs.praison.ai/agents/prompt-expander) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🎨 Media & Multimodal</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Image Generation Agent | [Example](examples/python/image/image-agent.py) | [📖](https://docs.praison.ai/features/image-generation) |
|
||||
| Image to Text Agent | [Example](examples/python/agents/image-to-text-agent.py) | [📖](https://docs.praison.ai/agents/image-to-text) |
|
||||
| Video Agent | [Example](examples/python/agents/video-agent.py) | [📖](https://docs.praison.ai/agents/video) |
|
||||
| Camera Integration | [Example](examples/python/camera/) | [📖](https://docs.praison.ai/features/camera-integration) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🔌 Protocols & Integration</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| MCP Transports | [Example](examples/python/mcp/mcp-transports-overview.py) | [📖](https://docs.praison.ai/mcp/transports) |
|
||||
| WebSocket MCP | [Example](examples/python/mcp/websocket-mcp.py) | [📖](https://docs.praison.ai/mcp/sse-transport) |
|
||||
| MCP Security | [Example](examples/python/mcp/mcp-security.py) | [📖](https://docs.praison.ai/mcp/transports) |
|
||||
| MCP Resumability | [Example](examples/python/mcp/mcp-resumability.py) | [📖](https://docs.praison.ai/mcp/sse-transport) |
|
||||
| MCP Config Management | [Example](#mcp-config-cli) | [📖](https://docs.praison.ai/docs/cli/mcp) |
|
||||
| LangChain Integrated Agents | [Example](examples/python/general/langchain_example.py) | [📖](https://docs.praison.ai/features/langchain) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🛡️ Safety & Control</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Guardrails | [Example](examples/python/guardrails/comprehensive-guardrails-example.py) | [📖](https://docs.praison.ai/features/guardrails) |
|
||||
| Human Approval | [Example](examples/python/general/human_approval_example.py) | [📖](https://docs.praison.ai/features/approval) |
|
||||
| Rules & Instructions | [Example](#7-rules--instructions) | [📖](https://docs.praison.ai/features/rules) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>⚙️ Advanced Features</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Async & Parallel Processing | [Example](examples/python/general/async_example.py) | [📖](https://docs.praison.ai/features/async) |
|
||||
| Parallelisation | [Example](examples/python/general/parallelisation.py) | [📖](https://docs.praison.ai/features/parallelisation) |
|
||||
| Repetitive Agents | [Example](examples/python/concepts/repetitive-agents.py) | [📖](https://docs.praison.ai/features/repetitive) |
|
||||
| Agent Handoffs | [Example](examples/python/handoff/handoff_basic.py) | [📖](https://docs.praison.ai/features/handoffs) |
|
||||
| Stateful Agents | [Example](examples/python/stateful/workflow-state-example.py) | [📖](https://docs.praison.ai/features/stateful-agents) |
|
||||
| Autonomous Workflow | [Example](examples/python/general/autonomous-agent.py) | [📖](https://docs.praison.ai/features/autonomous-workflow) |
|
||||
| Structured Output Agents | [Example](examples/python/general/structured_agents_example.py) | [📖](https://docs.praison.ai/features/structured) |
|
||||
| Model Router | [Example](examples/python/agents/router-agent-cost-optimization.py) | [📖](https://docs.praison.ai/features/model-router) |
|
||||
| Prompt Caching | [Example](#web-search-web-fetch--prompt-caching) | [📖](https://docs.praison.ai/features/model-capabilities) |
|
||||
| Fast Context | [Example](examples/context/00_agent_fast_context_basic.py) | [📖](https://docs.praison.ai/features/fast-context) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🛠️ Tools & Configuration</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| 100+ Custom Tools | [Example](examples/python/general/tools_example.py) | [📖](https://docs.praison.ai/tools/tools) |
|
||||
| YAML Configuration | [Example](examples/cookbooks/yaml/secondary_market_research_agents.yaml) | [📖](https://docs.praison.ai/developers/agents-playbook) |
|
||||
| 100+ LLM Support | [Example](examples/python/providers/openai/openai_gpt4_example.py) | [📖](https://docs.praison.ai/models) |
|
||||
| Callback Agents | [Example](examples/python/general/advanced-callback-systems.py) | [📖](https://docs.praison.ai/features/callbacks) |
|
||||
| Hooks | [Example](#10-hooks) | [📖](https://docs.praison.ai/features/hooks) |
|
||||
| Middleware System | [Example](examples/middleware/basic_middleware.py) | [📖](https://docs.praison.ai/features/middleware) |
|
||||
| Configurable Model | [Example](examples/middleware/configurable_model.py) | [📖](https://docs.praison.ai/features/configurable-model) |
|
||||
| Rate Limiter | [Example](examples/middleware/rate_limiter.py) | [📖](https://docs.praison.ai/features/rate-limiter) |
|
||||
| Injected Tool State | [Example](examples/middleware/injected_state.py) | [📖](https://docs.praison.ai/features/injected-state) |
|
||||
| Shadow Git Checkpoints | [Example](#11-shadow-git-checkpoints) | [📖](https://docs.praison.ai/features/checkpoints) |
|
||||
| Background Tasks | [Example](examples/background/basic_background.py) | [📖](https://docs.praison.ai/features/background-tasks) |
|
||||
| Policy Engine | [Example](examples/policy/basic_policy.py) | [📖](https://docs.praison.ai/features/policy-engine) |
|
||||
| Thinking Budgets | [Example](examples/thinking/basic_thinking.py) | [📖](https://docs.praison.ai/features/thinking-budgets) |
|
||||
| Output Styles | [Example](examples/output/basic_output.py) | [📖](https://docs.praison.ai/features/output-styles) |
|
||||
| Context Compaction | [Example](examples/compaction/basic_compaction.py) | [📖](https://docs.praison.ai/features/context-compaction) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>📊 Monitoring & Management</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Sessions Management | [Example](examples/python/sessions/comprehensive-session-management.py) | [📖](https://docs.praison.ai/features/sessions) |
|
||||
| Auto-Save Sessions | [Example](#session-management-python) | [📖](https://docs.praison.ai/docs/cli/session) |
|
||||
| History in Context | [Example](#session-management-python) | [📖](https://docs.praison.ai/docs/cli/session) |
|
||||
| Telemetry | [Example](examples/python/telemetry/production-telemetry-example.py) | [📖](https://docs.praison.ai/features/telemetry) |
|
||||
| Project Docs (.praison/docs/) | [Example](#docs-cli) | [📖](https://docs.praison.ai/docs/cli/docs) |
|
||||
| AI Commit Messages | [Example](#ai-commit-cli) | [📖](https://docs.praison.ai/docs/cli/commit) |
|
||||
| @Mentions in Prompts | [Example](#mentions-in-prompts) | [📖](https://docs.praison.ai/docs/cli/mentions) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🖥️ CLI Features</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Slash Commands | [Example](examples/python/cli/slash_commands_example.py) | [📖](https://docs.praison.ai/docs/cli/slash-commands) |
|
||||
| Autonomy Modes | [Example](examples/python/cli/autonomy_modes_example.py) | [📖](https://docs.praison.ai/docs/cli/autonomy-modes) |
|
||||
| Cost Tracking | [Example](examples/python/cli/cost_tracking_example.py) | [📖](https://docs.praison.ai/docs/cli/cost-tracking) |
|
||||
| Repository Map | [Example](examples/python/cli/repo_map_example.py) | [📖](https://docs.praison.ai/docs/cli/repo-map) |
|
||||
| Interactive TUI | [Example](examples/python/cli/interactive_tui_example.py) | [📖](https://docs.praison.ai/docs/cli/interactive-tui) |
|
||||
| Git Integration | [Example](examples/python/cli/git_integration_example.py) | [📖](https://docs.praison.ai/docs/cli/git-integration) |
|
||||
| Sandbox Execution | [Example](examples/python/cli/sandbox_execution_example.py) | [📖](https://docs.praison.ai/docs/cli/sandbox-execution) |
|
||||
| CLI Compare | [Example](examples/compare/cli_compare_basic.py) | [📖](https://docs.praison.ai/docs/cli/compare) |
|
||||
| Profile/Benchmark | [Example](#profile-benchmark) | [📖](https://docs.praison.ai/docs/cli/profile) |
|
||||
| Auto Mode | [Example](#auto-mode) | [📖](https://docs.praison.ai/docs/cli/auto) |
|
||||
| Init | [Example](#init) | [📖](https://docs.praison.ai/docs/cli/init) |
|
||||
| File Input | [Example](#file-input) | [📖](https://docs.praison.ai/docs/cli/file-input) |
|
||||
| Final Agent | [Example](#final-agent) | [📖](https://docs.praison.ai/docs/cli/final-agent) |
|
||||
| Max Tokens | [Example](#max-tokens) | [📖](https://docs.praison.ai/docs/cli/max-tokens) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🧪 Evaluation</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Accuracy Evaluation | [Example](examples/eval/accuracy_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
| Performance Evaluation | [Example](examples/eval/performance_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
| Reliability Evaluation | [Example](examples/eval/reliability_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
| Criteria Evaluation | [Example](examples/eval/criteria_example.py) | [📖](https://docs.praison.ai/docs/cli/eval) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>🎯 Agent Skills</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Skills Management | [Example](examples/skills/basic_skill_usage.py) | [📖](https://docs.praison.ai/features/skills) |
|
||||
| Custom Skills | [Example](examples/skills/custom_skill_example.py) | [📖](https://docs.praison.ai/features/skills) |
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>⏰ 24/7 Scheduling</strong></summary>
|
||||
|
||||
| Feature | Code | Docs |
|
||||
|---------|:----:|:----:|
|
||||
| Agent Scheduler | [Example](examples/python/scheduled_agents/news_checker_live.py) | [📖](https://docs.praison.ai/docs/cli/scheduler) |
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
@@ -543,7 +745,7 @@ memory.handle_command("/memory save my_session")
|
||||
| `memory="sqlite"` | Built-in | SQLite with indexing |
|
||||
| `memory="chromadb"` | chromadb | Vector/semantic search |
|
||||
|
||||
### 6. Rules & Instructions
|
||||
### 7. Rules & Instructions
|
||||
|
||||
PraisonAI auto-discovers instruction files from your project root and git root:
|
||||
|
||||
@@ -592,7 +794,7 @@ activation: always # always, glob, manual, ai_decision
|
||||
- Follow PEP 8
|
||||
```
|
||||
|
||||
### 7. Auto-Generated Memories
|
||||
### 8. Auto-Generated Memories
|
||||
|
||||
```python
|
||||
from praisonaiagents.memory import FileMemory, AutoMemory
|
||||
@@ -607,7 +809,7 @@ memories = auto.process_interaction(
|
||||
# Extracts: name="John", preference="Python for backend"
|
||||
```
|
||||
|
||||
### 8. Agentic Workflows
|
||||
### 9. Agentic Workflows
|
||||
|
||||
Create powerful multi-agent workflows with the `Workflow` class:
|
||||
|
||||
@@ -877,7 +1079,7 @@ callbacks:
|
||||
on_workflow_complete: log_complete
|
||||
```
|
||||
|
||||
### 9. Hooks
|
||||
### 10. Hooks
|
||||
|
||||
Intercept and modify agent behavior at various lifecycle points:
|
||||
|
||||
@@ -916,7 +1118,7 @@ praisonai hooks validate hooks.json # Validate configuration
|
||||
```
|
||||
|
||||
|
||||
### 10. Shadow Git Checkpoints
|
||||
### 11. Shadow Git Checkpoints
|
||||
|
||||
File-level undo/restore using shadow git:
|
||||
|
||||
@@ -953,7 +1155,7 @@ praisonai checkpoint restore abc123 # Restore to checkpoint
|
||||
|
||||
---
|
||||
|
||||
### 11. Background Tasks
|
||||
### 12. Background Tasks
|
||||
|
||||
Run agent tasks asynchronously without blocking:
|
||||
|
||||
@@ -991,7 +1193,7 @@ praisonai background clear # Clear completed tasks
|
||||
|
||||
---
|
||||
|
||||
### 12. Policy Engine
|
||||
### 13. Policy Engine
|
||||
|
||||
Control what agents can and cannot do with policy-based execution:
|
||||
|
||||
@@ -1032,7 +1234,7 @@ praisonai policy init # Create template
|
||||
|
||||
---
|
||||
|
||||
### 13. Thinking Budgets
|
||||
### 14. Thinking Budgets
|
||||
|
||||
Configure token budgets for extended thinking:
|
||||
|
||||
@@ -1065,7 +1267,7 @@ praisonai thinking stats # Show usage statistics
|
||||
|
||||
---
|
||||
|
||||
### 14. Output Styles
|
||||
### 15. Output Styles
|
||||
|
||||
Configure how agents format their responses:
|
||||
|
||||
@@ -1095,7 +1297,7 @@ praisonai output set concise # Set output style
|
||||
|
||||
---
|
||||
|
||||
### 15. Context Compaction
|
||||
### 16. Context Compaction
|
||||
|
||||
Automatically manage context window size:
|
||||
|
||||
@@ -1130,7 +1332,7 @@ praisonai compaction stats # Show statistics
|
||||
|
||||
---
|
||||
|
||||
### 16. Field Names Reference (A-I-G-S)
|
||||
### 17. Field Names Reference (A-I-G-S)
|
||||
|
||||
PraisonAI accepts both old (agents.yaml) and new (workflow.yaml) field names. Use the **canonical names** for new projects:
|
||||
|
||||
@@ -1164,7 +1366,7 @@ steps: # Define steps (not 'tasks')
|
||||
|
||||
> **Note:** The parser accepts both old and new names. Run `praisonai workflow validate <file.yaml>` to see suggestions for canonical names.
|
||||
|
||||
### 12. Extended agents.yaml with Workflow Patterns
|
||||
### 18. Extended agents.yaml with Workflow Patterns
|
||||
|
||||
**Feature Parity:** Both `agents.yaml` and `workflow.yaml` now support the same features:
|
||||
- All workflow patterns (route, parallel, loop, repeat)
|
||||
@@ -1240,7 +1442,7 @@ Run with the same simple command:
|
||||
praisonai agents.yaml
|
||||
```
|
||||
|
||||
### 12. MCP (Model Context Protocol)
|
||||
### 19. MCP (Model Context Protocol)
|
||||
|
||||
PraisonAI supports MCP Protocol Revision 2025-11-25 with multiple transports.
|
||||
|
||||
@@ -1316,7 +1518,7 @@ server.run() # stdio for Claude Desktop
|
||||
| Security | Origin validation, DNS rebinding prevention |
|
||||
| WebSocket | Auto-reconnect with exponential backoff |
|
||||
|
||||
### 13. A2A (Agent2Agent Protocol)
|
||||
### 20. A2A (Agent2Agent Protocol)
|
||||
|
||||
PraisonAI supports the [A2A Protocol](https://a2a-protocol.org) for agent-to-agent communication, enabling your agents to be discovered and collaborate with other AI agents.
|
||||
|
||||
@@ -1364,6 +1566,22 @@ app.include_router(a2a.get_router())
|
||||
|
||||
PraisonAI provides a powerful CLI for no-code automation and quick prototyping.
|
||||
|
||||
### CLI Quick Reference
|
||||
|
||||
| Category | Commands |
|
||||
|----------|----------|
|
||||
| **Execution** | `praisonai`, `--auto`, `--interactive`, `--chat` |
|
||||
| **Research** | `research`, `--query-rewrite`, `--deep-research` |
|
||||
| **Planning** | `--planning`, `--planning-tools`, `--planning-reasoning` |
|
||||
| **Workflows** | `workflow run`, `workflow list`, `workflow auto` |
|
||||
| **Memory** | `memory show`, `memory add`, `memory search`, `memory clear` |
|
||||
| **Knowledge** | `knowledge add`, `knowledge query`, `knowledge list` |
|
||||
| **Sessions** | `session list`, `session resume`, `session delete` |
|
||||
| **Tools** | `tools list`, `tools info`, `tools search` |
|
||||
| **MCP** | `mcp list`, `mcp create`, `mcp enable` |
|
||||
| **Development** | `commit`, `docs`, `checkpoint`, `hooks` |
|
||||
| **Scheduling** | `schedule start`, `schedule list`, `schedule stop` |
|
||||
|
||||
### Auto Mode
|
||||
```bash
|
||||
pip install praisonai
|
||||
@@ -3023,6 +3241,119 @@ cd src/praisonai && uv publish
|
||||
|
||||
---
|
||||
|
||||
## ❓ FAQ & Troubleshooting
|
||||
|
||||
<details>
|
||||
<summary><strong>ModuleNotFoundError: No module named 'praisonaiagents'</strong></summary>
|
||||
|
||||
Install the package:
|
||||
```bash
|
||||
pip install praisonaiagents
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>API key not found / Authentication error</strong></summary>
|
||||
|
||||
Ensure your API key is set:
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_key_here
|
||||
```
|
||||
|
||||
For other providers, see [Environment Variables](#environment-variables).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>How do I use a local model (Ollama)?</strong></summary>
|
||||
|
||||
```bash
|
||||
# Start Ollama server first
|
||||
ollama serve
|
||||
|
||||
# Set environment variable
|
||||
export OPENAI_BASE_URL=http://localhost:11434/v1
|
||||
```
|
||||
|
||||
See [Ollama Integration](#ollama-integration) for more details.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>How do I persist conversations to a database?</strong></summary>
|
||||
|
||||
Use the `db` parameter:
|
||||
```python
|
||||
from praisonaiagents import Agent, db
|
||||
|
||||
agent = Agent(
|
||||
name="Assistant",
|
||||
db=db(database_url="postgresql://localhost/mydb"),
|
||||
session_id="my-session"
|
||||
)
|
||||
```
|
||||
|
||||
See [Persistence (Databases)](#-persistence-databases) for supported databases.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>How do I enable agent memory?</strong></summary>
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent
|
||||
|
||||
agent = Agent(
|
||||
name="Assistant",
|
||||
memory=True, # Enables file-based memory (no extra deps!)
|
||||
user_id="user123"
|
||||
)
|
||||
```
|
||||
|
||||
See [Agent Memory](#6-agent-memory-zero-dependencies) for more options.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>How do I run multiple agents together?</strong></summary>
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, PraisonAIAgents
|
||||
|
||||
agent1 = Agent(instructions="Research topics")
|
||||
agent2 = Agent(instructions="Summarize findings")
|
||||
agents = PraisonAIAgents(agents=[agent1, agent2])
|
||||
agents.start()
|
||||
```
|
||||
|
||||
See [Multi Agents](#2-multi-agents) for more examples.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>How do I use MCP tools?</strong></summary>
|
||||
|
||||
```python
|
||||
from praisonaiagents import Agent, MCP
|
||||
|
||||
agent = Agent(
|
||||
tools=MCP("npx @modelcontextprotocol/server-memory")
|
||||
)
|
||||
```
|
||||
|
||||
See [MCP Protocol](#19-mcp-model-context-protocol) for all transport options.
|
||||
|
||||
</details>
|
||||
|
||||
### Getting Help
|
||||
|
||||
- 📚 [Full Documentation](https://docs.praison.ai)
|
||||
- 🐛 [Report Issues](https://github.com/MervinPraison/PraisonAI/issues)
|
||||
- 💬 [Discussions](https://github.com/MervinPraison/PraisonAI/discussions)
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<p><strong>Made with ❤️ by the PraisonAI Team</strong></p>
|
||||
<p>
|
||||
|
||||
@@ -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.3" \
|
||||
"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.3" \
|
||||
"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.3" \
|
||||
"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.
|
||||
|
||||
@@ -89,11 +89,9 @@ class AccuracyEvaluator(BaseEvaluator):
|
||||
EvaluationScore with score and reasoning
|
||||
"""
|
||||
try:
|
||||
from openai import OpenAI
|
||||
import litellm
|
||||
except ImportError:
|
||||
raise ImportError("OpenAI package required for accuracy evaluation. Install with: pip install openai")
|
||||
|
||||
client = OpenAI()
|
||||
raise ImportError("litellm package required for accuracy evaluation. Install with: pip install litellm")
|
||||
|
||||
prompt = f"""You are an expert evaluator. Compare the actual output against the expected output and provide a score from 1-10.
|
||||
|
||||
@@ -115,7 +113,8 @@ Respond in this exact format:
|
||||
SCORE: [number 1-10]
|
||||
REASONING: [brief explanation]"""
|
||||
|
||||
response = client.chat.completions.create(
|
||||
# Use litellm for unified multi-provider support
|
||||
response = litellm.completion(
|
||||
model=self.model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
temperature=0.1,
|
||||
|
||||
@@ -99,11 +99,9 @@ class CriteriaEvaluator(BaseEvaluator):
|
||||
CriteriaScore with score, passed status, and reasoning
|
||||
"""
|
||||
try:
|
||||
from openai import OpenAI
|
||||
import litellm
|
||||
except ImportError:
|
||||
raise ImportError("OpenAI package required for criteria evaluation. Install with: pip install openai")
|
||||
|
||||
client = OpenAI()
|
||||
raise ImportError("litellm package required for criteria evaluation. Install with: pip install litellm")
|
||||
|
||||
if self.scoring_type == "binary":
|
||||
prompt = f"""You are an expert evaluator. Evaluate the following output against the given criteria.
|
||||
@@ -138,7 +136,8 @@ Respond in this exact format:
|
||||
SCORE: [number 1-10]
|
||||
REASONING: [brief explanation]"""
|
||||
|
||||
response = client.chat.completions.create(
|
||||
# Use litellm for unified multi-provider support
|
||||
response = litellm.completion(
|
||||
model=self.model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
temperature=0.1,
|
||||
|
||||
@@ -91,19 +91,20 @@ class MongoDBMemory:
|
||||
raise Exception(f"Failed to initialize MongoDB: {e}")
|
||||
|
||||
def _init_embedding_model(self):
|
||||
"""Initialize embedding model from config."""
|
||||
"""Initialize embedding model from config using litellm for unified provider support."""
|
||||
try:
|
||||
# Set up embedding model based on config
|
||||
embedder_config = self.config.get("embedder", {})
|
||||
if embedder_config.get("provider") == "openai":
|
||||
import openai
|
||||
self.embedding_model = openai.OpenAI()
|
||||
self.embedding_model_name = embedder_config.get("config", {}).get("model", "text-embedding-3-small")
|
||||
else:
|
||||
# Default to OpenAI
|
||||
import openai
|
||||
self.embedding_model = openai.OpenAI()
|
||||
self.embedding_model_name = "text-embedding-3-small"
|
||||
provider = embedder_config.get("provider", "openai")
|
||||
model_name = embedder_config.get("config", {}).get("model", "text-embedding-3-small")
|
||||
|
||||
# Store model name for later use
|
||||
self.embedding_model_name = model_name
|
||||
|
||||
# Use litellm for embeddings - it handles all providers uniformly
|
||||
# We'll use litellm.embedding() in _get_embeddings() instead of storing a client
|
||||
self.embedding_provider = provider
|
||||
self.embedding_model = None # Will use litellm.embedding() directly
|
||||
except Exception as e:
|
||||
raise Exception(f"Failed to initialize embedding model: {e}")
|
||||
|
||||
@@ -172,13 +173,16 @@ class MongoDBMemory:
|
||||
logging.warning(f"Could not create vector search index: {e}")
|
||||
|
||||
def _get_embedding(self, text):
|
||||
"""Get embedding for text."""
|
||||
"""Get embedding for text using litellm for unified provider support."""
|
||||
try:
|
||||
response = self.embedding_model.embeddings.create(
|
||||
input=text,
|
||||
model=self.embedding_model_name
|
||||
import litellm
|
||||
|
||||
# Use litellm.embedding() for unified multi-provider support
|
||||
response = litellm.embedding(
|
||||
model=self.embedding_model_name,
|
||||
input=text
|
||||
)
|
||||
return response.data[0].embedding
|
||||
return response.data[0]["embedding"]
|
||||
except Exception as e:
|
||||
logging.error(f"Error getting embedding: {e}")
|
||||
return None
|
||||
|
||||
@@ -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.3"
|
||||
version = "0.4.0"
|
||||
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -91,14 +91,11 @@ class TestAccuracyEvaluator:
|
||||
|
||||
def test_judge_output(self):
|
||||
"""Test LLM judging of output."""
|
||||
with patch('openai.OpenAI') as mock_openai_class:
|
||||
mock_client = MagicMock()
|
||||
mock_openai_class.return_value = mock_client
|
||||
|
||||
with patch('litellm.completion') as mock_completion:
|
||||
mock_response = MagicMock()
|
||||
mock_response.choices = [MagicMock()]
|
||||
mock_response.choices[0].message.content = "SCORE: 8\nREASONING: Good match"
|
||||
mock_client.chat.completions.create.return_value = mock_response
|
||||
mock_completion.return_value = mock_response
|
||||
|
||||
def test_func(x):
|
||||
return "4"
|
||||
@@ -115,14 +112,11 @@ class TestAccuracyEvaluator:
|
||||
|
||||
def test_run_returns_accuracy_result(self):
|
||||
"""Test that run returns AccuracyResult."""
|
||||
with patch('openai.OpenAI') as mock_openai_class:
|
||||
mock_client = MagicMock()
|
||||
mock_openai_class.return_value = mock_client
|
||||
|
||||
with patch('litellm.completion') as mock_completion:
|
||||
mock_response = MagicMock()
|
||||
mock_response.choices = [MagicMock()]
|
||||
mock_response.choices[0].message.content = "SCORE: 9\nREASONING: Excellent"
|
||||
mock_client.chat.completions.create.return_value = mock_response
|
||||
mock_completion.return_value = mock_response
|
||||
|
||||
def test_func(x):
|
||||
return "4"
|
||||
@@ -140,14 +134,11 @@ class TestAccuracyEvaluator:
|
||||
|
||||
def test_evaluate_output(self):
|
||||
"""Test evaluate_output method for pre-generated outputs."""
|
||||
with patch('openai.OpenAI') as mock_openai_class:
|
||||
mock_client = MagicMock()
|
||||
mock_openai_class.return_value = mock_client
|
||||
|
||||
with patch('litellm.completion') as mock_completion:
|
||||
mock_response = MagicMock()
|
||||
mock_response.choices = [MagicMock()]
|
||||
mock_response.choices[0].message.content = "SCORE: 10\nREASONING: Perfect"
|
||||
mock_client.chat.completions.create.return_value = mock_response
|
||||
mock_completion.return_value = mock_response
|
||||
|
||||
def test_func(x):
|
||||
return "unused"
|
||||
@@ -325,14 +316,11 @@ class TestCriteriaEvaluator:
|
||||
|
||||
def test_judge_output_numeric(self):
|
||||
"""Test numeric scoring."""
|
||||
with patch('openai.OpenAI') as mock_openai_class:
|
||||
mock_client = MagicMock()
|
||||
mock_openai_class.return_value = mock_client
|
||||
|
||||
with patch('litellm.completion') as mock_completion:
|
||||
mock_response = MagicMock()
|
||||
mock_response.choices = [MagicMock()]
|
||||
mock_response.choices[0].message.content = "SCORE: 8\nREASONING: Good"
|
||||
mock_client.chat.completions.create.return_value = mock_response
|
||||
mock_completion.return_value = mock_response
|
||||
|
||||
def test_func(x):
|
||||
return "test"
|
||||
@@ -350,14 +338,11 @@ class TestCriteriaEvaluator:
|
||||
|
||||
def test_judge_output_binary(self):
|
||||
"""Test binary scoring."""
|
||||
with patch('openai.OpenAI') as mock_openai_class:
|
||||
mock_client = MagicMock()
|
||||
mock_openai_class.return_value = mock_client
|
||||
|
||||
with patch('litellm.completion') as mock_completion:
|
||||
mock_response = MagicMock()
|
||||
mock_response.choices = [MagicMock()]
|
||||
mock_response.choices[0].message.content = "RESULT: PASS\nREASONING: Meets criteria"
|
||||
mock_client.chat.completions.create.return_value = mock_response
|
||||
mock_completion.return_value = mock_response
|
||||
|
||||
def test_func(x):
|
||||
return "test"
|
||||
@@ -374,14 +359,11 @@ class TestCriteriaEvaluator:
|
||||
|
||||
def test_on_fail_callback(self):
|
||||
"""Test on_fail callback is called."""
|
||||
with patch('openai.OpenAI') as mock_openai_class:
|
||||
mock_client = MagicMock()
|
||||
mock_openai_class.return_value = mock_client
|
||||
|
||||
with patch('litellm.completion') as mock_completion:
|
||||
mock_response = MagicMock()
|
||||
mock_response.choices = [MagicMock()]
|
||||
mock_response.choices[0].message.content = "SCORE: 3\nREASONING: Poor"
|
||||
mock_client.chat.completions.create.return_value = mock_response
|
||||
mock_completion.return_value = mock_response
|
||||
|
||||
on_fail_called = []
|
||||
def on_fail(score):
|
||||
@@ -403,14 +385,11 @@ class TestCriteriaEvaluator:
|
||||
|
||||
def test_evaluate_output_criteria(self):
|
||||
"""Test evaluate_output method."""
|
||||
with patch('openai.OpenAI') as mock_openai_class:
|
||||
mock_client = MagicMock()
|
||||
mock_openai_class.return_value = mock_client
|
||||
|
||||
with patch('litellm.completion') as mock_completion:
|
||||
mock_response = MagicMock()
|
||||
mock_response.choices = [MagicMock()]
|
||||
mock_response.choices[0].message.content = "SCORE: 9\nREASONING: Great"
|
||||
mock_client.chat.completions.create.return_value = mock_response
|
||||
mock_completion.return_value = mock_response
|
||||
|
||||
def test_func(x):
|
||||
return "unused"
|
||||
|
||||
Generated
+1
-1
@@ -2422,7 +2422,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "praisonaiagents"
|
||||
version = "0.3.3"
|
||||
version = "0.4.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
{
|
||||
"version": "1.2.1",
|
||||
"lastUpdated": "2024-12-26",
|
||||
"implementationStatus": "Phase 4 Complete - Full Feature Parity",
|
||||
"summary": {
|
||||
"pythonCoreFeatures": 85,
|
||||
"pythonWrapperFeatures": 45,
|
||||
"typescriptFeatures": 75,
|
||||
"gapCount": 10,
|
||||
"priorityP0": 0,
|
||||
"priorityP1": 3,
|
||||
"priorityP2": 5,
|
||||
"priorityP3": 2
|
||||
},
|
||||
"pythonCoreSDK": {
|
||||
"path": "/Users/praison/praisonai-package/src/praisonai-agents/praisonaiagents",
|
||||
"exports": [
|
||||
"Agent", "ImageAgent", "ContextAgent", "DeepResearchAgent", "QueryRewriterAgent", "PromptExpanderAgent",
|
||||
"PraisonAIAgents", "Agents", "Task", "Tools", "BaseTool", "ToolResult", "tool", "FunctionTool",
|
||||
"ToolRegistry", "get_registry", "register_tool", "get_tool", "AutoAgents", "Session", "Memory",
|
||||
"Knowledge", "Chunking", "db", "obs", "MCP", "Workflow", "Pipeline", "WorkflowStep", "WorkflowContext",
|
||||
"StepResult", "Route", "Parallel", "Loop", "Repeat", "GuardrailResult", "LLMGuardrail",
|
||||
"Handoff", "handoff", "FlowDisplay", "FastContext", "SkillManager", "SkillProperties",
|
||||
"get_telemetry", "enable_telemetry", "MinimalTelemetry", "TelemetryCollector", "AGUI", "A2A"
|
||||
],
|
||||
"modules": {
|
||||
"agent": ["Agent", "ImageAgent", "ContextAgent", "DeepResearchAgent", "QueryRewriterAgent", "PromptExpanderAgent", "RouterAgent", "Handoff"],
|
||||
"agents": ["PraisonAIAgents", "AutoAgents"],
|
||||
"task": ["Task"],
|
||||
"tools": ["Tools", "BaseTool", "ToolResult", "tool", "FunctionTool", "ToolRegistry", "40+ built-in tools"],
|
||||
"llm": ["LLM", "OpenAIClient", "ModelRouter", "RateLimiter", "ModelCapabilities"],
|
||||
"memory": ["Memory", "AutoMemory", "FileMemory", "RulesManager", "DocsManager", "Hooks"],
|
||||
"knowledge": ["Knowledge", "Chunking", "VectorStore", "QueryEngine", "Readers", "Rerankers"],
|
||||
"db": ["DbAdapter", "AsyncDbAdapter", "DbMessage", "DbToolCall", "DbRun", "DbSpan", "DbTrace"],
|
||||
"obs": ["ObservabilityAdapter", "Span", "Trace", "16 provider integrations"],
|
||||
"mcp": ["MCP", "MCPServer", "MCPSession", "MCPTransport", "MCPWebSocket", "MCPSSE", "MCPHTTPStream"],
|
||||
"workflows": ["Workflow", "Pipeline", "WorkflowStep", "WorkflowContext", "StepResult", "Route", "Parallel", "Loop", "Repeat", "YAMLWorkflowParser"],
|
||||
"guardrails": ["GuardrailResult", "LLMGuardrail"],
|
||||
"eval": ["AccuracyEval", "PerformanceEval", "ReliabilityEval", "CriteriaEval"],
|
||||
"skills": ["SkillManager", "SkillProperties", "SkillLoader", "SkillDiscovery", "SkillValidator"],
|
||||
"telemetry": ["MinimalTelemetry", "TelemetryCollector", "PerformanceMonitor", "TokenCollector"],
|
||||
"context": ["FastContext", "FastContextResult"],
|
||||
"session": ["Session"],
|
||||
"ui": ["AGUI", "A2A"]
|
||||
}
|
||||
},
|
||||
"pythonWrapper": {
|
||||
"path": "/Users/praison/praisonai-package/src/praisonai/praisonai",
|
||||
"exports": ["PraisonAI"],
|
||||
"cliFeatures": [
|
||||
"slash_commands", "autonomy_mode", "cost_tracker", "repo_map", "interactive_tui",
|
||||
"git_integration", "sandbox_executor", "agent_scheduler", "agents", "at_mentions",
|
||||
"auto_memory", "background", "checkpoints", "compare", "eval", "external_agents",
|
||||
"fast_context", "flow_display", "guardrail", "handoff", "hooks", "image", "jobs",
|
||||
"knowledge", "mcp", "message_queue", "metrics", "n8n", "observability", "persistence",
|
||||
"profile", "profiling", "router", "session", "skills", "telemetry", "todo", "tools", "workflow"
|
||||
]
|
||||
},
|
||||
"typescriptSDK": {
|
||||
"path": "/Users/praison/praisonai-package/src/praisonai-ts/src",
|
||||
"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", "ImageAgent", "ContextAgent", "DeepResearchAgent", "QueryRewriterAgent", "PromptExpanderAgent", "RouterAgent", "Handoff"],
|
||||
"auto": ["AutoAgents", "createAutoAgents"],
|
||||
"task": ["Task"],
|
||||
"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 (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": 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": 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": 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": {
|
||||
"implemented": [
|
||||
"Agent core", "Tool calling", "Streaming (partial)", "Multi-agent (partial)"
|
||||
],
|
||||
"missing": [
|
||||
"Memory with semantic recall", "Working memory", "Thread management", "Resource scoping",
|
||||
"Storage abstraction", "Vector store integration", "Embeddings", "Evaluation scorers",
|
||||
"Workflow engine", "Step execution", "Branching logic", "Event-driven workflows",
|
||||
"MCP integration", "Voice/TTS", "Observability hooks", "Request context",
|
||||
"Tool validation", "Tool suspend/resume", "Provider options per tool"
|
||||
]
|
||||
},
|
||||
"implementationPlan": {
|
||||
"phase1_P0": {
|
||||
"description": "Core agent parity - streaming, structured outputs, sessions, tool system",
|
||||
"tasks": [
|
||||
"Implement AI SDK provider abstraction (OpenAI, Anthropic, Google)",
|
||||
"Add streaming response support with proper typing",
|
||||
"Implement structured output with JSON schema/Zod",
|
||||
"Add session management (session_id, run_id, trace_id)",
|
||||
"Implement tool decorator and registry",
|
||||
"Add agent handoff support",
|
||||
"Improve error handling and retries"
|
||||
]
|
||||
},
|
||||
"phase2_P1": {
|
||||
"description": "Persistence layer - db adapters, memory, knowledge",
|
||||
"tasks": [
|
||||
"Implement DbAdapter protocol",
|
||||
"Add SQLite adapter",
|
||||
"Add message/run/trace persistence",
|
||||
"Implement Memory with persistence",
|
||||
"Add Knowledge base (RAG) support",
|
||||
"Implement vector store integration"
|
||||
]
|
||||
},
|
||||
"phase3_P2": {
|
||||
"description": "CLI parity",
|
||||
"tasks": [
|
||||
"Create CLI entrypoint",
|
||||
"Implement slash commands",
|
||||
"Add cost tracking",
|
||||
"Implement interactive mode"
|
||||
]
|
||||
},
|
||||
"phase4_P3": {
|
||||
"description": "Advanced features",
|
||||
"tasks": [
|
||||
"Implement Workflow engine",
|
||||
"Add workflow patterns (Route, Parallel, Loop, Repeat)",
|
||||
"Implement Guardrails",
|
||||
"Add Evaluation framework",
|
||||
"Implement Observability hooks",
|
||||
"Add Skills system"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const config: Config.InitialOptions = {
|
||||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
roots: ['<rootDir>/tests'],
|
||||
testMatch: ['**/*.main.test.ts', '**/*.spec.ts'],
|
||||
testMatch: ['**/*.test.ts', '**/*.spec.ts'],
|
||||
moduleFileExtensions: ['ts', 'js', 'json'],
|
||||
coverageDirectory: 'coverage',
|
||||
collectCoverageFrom: [
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
{
|
||||
"name": "praisonai",
|
||||
"version": "1.0.19",
|
||||
"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",
|
||||
"bin": {
|
||||
"praisonai-ts": "./dist/cli/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "jest",
|
||||
@@ -62,7 +65,6 @@
|
||||
"fast-xml-parser": "^4.5.1",
|
||||
"node-fetch": "^2.6.9",
|
||||
"openai": "^4.81.0",
|
||||
"praisonai": "^1.0.19",
|
||||
"@modelcontextprotocol/sdk": "^1.12.1"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
|
||||
@@ -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,159 @@
|
||||
/**
|
||||
* Context Agent - Agent with enhanced context management
|
||||
*/
|
||||
|
||||
import { createProvider, type LLMProvider, type Message } from '../llm/providers';
|
||||
import { Session } from '../session';
|
||||
import { KnowledgeBase, type SearchResult } from '../knowledge/rag';
|
||||
|
||||
export interface ContextAgentConfig {
|
||||
name?: string;
|
||||
instructions: string;
|
||||
llm?: string;
|
||||
knowledgeBase?: KnowledgeBase;
|
||||
contextWindow?: number;
|
||||
maxContextTokens?: number;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
export interface ContextMessage {
|
||||
role: 'system' | 'user' | 'assistant';
|
||||
content: string;
|
||||
timestamp: number;
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Context Agent - Agent with RAG and context management
|
||||
*/
|
||||
export class ContextAgent {
|
||||
readonly name: string;
|
||||
readonly instructions: string;
|
||||
|
||||
private provider: LLMProvider;
|
||||
private knowledgeBase?: KnowledgeBase;
|
||||
private contextWindow: number;
|
||||
private maxContextTokens: number;
|
||||
private messages: ContextMessage[] = [];
|
||||
private verbose: boolean;
|
||||
|
||||
constructor(config: ContextAgentConfig) {
|
||||
this.name = config.name || `ContextAgent_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.instructions = config.instructions;
|
||||
this.provider = createProvider(config.llm || 'gpt-4o-mini');
|
||||
this.knowledgeBase = config.knowledgeBase;
|
||||
this.contextWindow = config.contextWindow ?? 10;
|
||||
this.maxContextTokens = config.maxContextTokens ?? 4000;
|
||||
this.verbose = config.verbose ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat with context awareness
|
||||
*/
|
||||
async chat(prompt: string): Promise<{ text: string; context?: SearchResult[] }> {
|
||||
// Add user message
|
||||
this.messages.push({
|
||||
role: 'user',
|
||||
content: prompt,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
// Build context from knowledge base
|
||||
let ragContext: SearchResult[] = [];
|
||||
let contextString = '';
|
||||
|
||||
if (this.knowledgeBase) {
|
||||
ragContext = await this.knowledgeBase.search(prompt);
|
||||
if (ragContext.length > 0) {
|
||||
contextString = this.knowledgeBase.buildContext(ragContext);
|
||||
if (this.verbose) {
|
||||
console.log(`[ContextAgent] Found ${ragContext.length} relevant documents`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build messages array with context
|
||||
const systemPrompt = contextString
|
||||
? `${this.instructions}\n\nRelevant context:\n${contextString}`
|
||||
: this.instructions;
|
||||
|
||||
const messages: Message[] = [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
...this.getRecentMessages()
|
||||
];
|
||||
|
||||
// Generate response
|
||||
const result = await this.provider.generateText({ messages });
|
||||
|
||||
// Add assistant message
|
||||
this.messages.push({
|
||||
role: 'assistant',
|
||||
content: result.text,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
|
||||
return {
|
||||
text: result.text,
|
||||
context: ragContext.length > 0 ? ragContext : undefined
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recent messages within context window
|
||||
*/
|
||||
private getRecentMessages(): Message[] {
|
||||
const recent = this.messages.slice(-this.contextWindow);
|
||||
return recent.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add document to knowledge base
|
||||
*/
|
||||
async addDocument(id: string, content: string, metadata?: Record<string, any>): Promise<void> {
|
||||
if (!this.knowledgeBase) {
|
||||
throw new Error('No knowledge base configured');
|
||||
}
|
||||
await this.knowledgeBase.add({ id, content, metadata });
|
||||
}
|
||||
|
||||
/**
|
||||
* Search knowledge base
|
||||
*/
|
||||
async searchKnowledge(query: string, limit?: number): Promise<SearchResult[]> {
|
||||
if (!this.knowledgeBase) {
|
||||
return [];
|
||||
}
|
||||
return this.knowledgeBase.search(query, limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear conversation history
|
||||
*/
|
||||
clearHistory(): void {
|
||||
this.messages = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get conversation history
|
||||
*/
|
||||
getHistory(): ContextMessage[] {
|
||||
return [...this.messages];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set knowledge base
|
||||
*/
|
||||
setKnowledgeBase(kb: KnowledgeBase): void {
|
||||
this.knowledgeBase = kb;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a context agent
|
||||
*/
|
||||
export function createContextAgent(config: ContextAgentConfig): ContextAgent {
|
||||
return new ContextAgent(config);
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/**
|
||||
* Enhanced Agent - Agent with session management, provider abstraction, and tool support
|
||||
*/
|
||||
|
||||
import { createProvider, type LLMProvider, type Message, type ToolCall, type GenerateTextResult } from '../llm/providers';
|
||||
import { Session, Run, Trace, getSessionManager } from '../session';
|
||||
import { FunctionTool, ToolRegistry, tool } from '../tools/decorator';
|
||||
import { Logger } from '../utils/logger';
|
||||
|
||||
export interface EnhancedAgentConfig {
|
||||
name?: string;
|
||||
instructions: string;
|
||||
llm?: string;
|
||||
tools?: Array<FunctionTool | Function | { name: string; description?: string; parameters?: any; execute: Function }>;
|
||||
session?: Session;
|
||||
sessionId?: string;
|
||||
verbose?: boolean;
|
||||
stream?: boolean;
|
||||
maxToolCalls?: number;
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
outputSchema?: any;
|
||||
}
|
||||
|
||||
export interface ChatOptions {
|
||||
stream?: boolean;
|
||||
temperature?: number;
|
||||
maxTokens?: number;
|
||||
outputSchema?: any;
|
||||
onToken?: (token: string) => void;
|
||||
}
|
||||
|
||||
export interface ChatResult {
|
||||
text: string;
|
||||
structured?: any;
|
||||
toolCalls?: ToolCall[];
|
||||
usage: {
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
totalTokens: number;
|
||||
};
|
||||
runId: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enhanced Agent with full feature support
|
||||
*/
|
||||
export class EnhancedAgent {
|
||||
readonly name: string;
|
||||
readonly instructions: string;
|
||||
readonly sessionId: string;
|
||||
|
||||
private provider: LLMProvider;
|
||||
private session: Session;
|
||||
private toolRegistry: ToolRegistry;
|
||||
private verbose: boolean;
|
||||
private stream: boolean;
|
||||
private maxToolCalls: number;
|
||||
private temperature: number;
|
||||
private maxTokens?: number;
|
||||
private outputSchema?: any;
|
||||
|
||||
constructor(config: EnhancedAgentConfig) {
|
||||
this.name = config.name || `Agent_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.instructions = config.instructions;
|
||||
this.verbose = config.verbose ?? true;
|
||||
this.stream = config.stream ?? true;
|
||||
this.maxToolCalls = config.maxToolCalls ?? 10;
|
||||
this.temperature = config.temperature ?? 0.7;
|
||||
this.maxTokens = config.maxTokens;
|
||||
this.outputSchema = config.outputSchema;
|
||||
|
||||
// Initialize provider
|
||||
this.provider = createProvider(config.llm || 'gpt-4o-mini');
|
||||
|
||||
// Initialize session
|
||||
if (config.session) {
|
||||
this.session = config.session;
|
||||
} else if (config.sessionId) {
|
||||
this.session = getSessionManager().getOrCreate(config.sessionId);
|
||||
} else {
|
||||
this.session = getSessionManager().create();
|
||||
}
|
||||
this.sessionId = this.session.id;
|
||||
|
||||
// Initialize tool registry
|
||||
this.toolRegistry = new ToolRegistry();
|
||||
if (config.tools) {
|
||||
this.registerTools(config.tools);
|
||||
}
|
||||
|
||||
Logger.setVerbose(this.verbose);
|
||||
}
|
||||
|
||||
private registerTools(tools: EnhancedAgentConfig['tools']): void {
|
||||
if (!tools) return;
|
||||
|
||||
for (const t of tools) {
|
||||
if (t instanceof FunctionTool) {
|
||||
this.toolRegistry.register(t);
|
||||
} else if (typeof t === 'function') {
|
||||
// Convert function to tool
|
||||
const funcName = t.name || `function_${Math.random().toString(36).substr(2, 9)}`;
|
||||
this.toolRegistry.register(tool({
|
||||
name: funcName,
|
||||
description: `Function ${funcName}`,
|
||||
execute: t as any,
|
||||
}));
|
||||
} else if (typeof t === 'object' && 'execute' in t) {
|
||||
// Tool config object
|
||||
this.toolRegistry.register(tool({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
parameters: t.parameters,
|
||||
execute: t.execute as any,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a tool to the agent
|
||||
*/
|
||||
addTool(t: FunctionTool | { name: string; description?: string; parameters?: any; execute: Function }): this {
|
||||
if (t instanceof FunctionTool) {
|
||||
this.toolRegistry.register(t);
|
||||
} else {
|
||||
this.toolRegistry.register(tool({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
parameters: t.parameters,
|
||||
execute: t.execute as any,
|
||||
}));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered tools
|
||||
*/
|
||||
getTools(): FunctionTool[] {
|
||||
return this.toolRegistry.list();
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat with the agent
|
||||
*/
|
||||
async chat(prompt: string, options: ChatOptions = {}): Promise<ChatResult> {
|
||||
const run = this.session.createRun().start();
|
||||
const trace = run.createTrace({ name: 'chat' }).start();
|
||||
|
||||
try {
|
||||
// Add user message to session
|
||||
this.session.addMessage({ role: 'user', content: prompt });
|
||||
|
||||
// Build messages array
|
||||
const messages: Message[] = [
|
||||
{ role: 'system', content: this.instructions },
|
||||
...this.session.getMessagesForLLM() as Message[],
|
||||
];
|
||||
|
||||
// Get tool definitions
|
||||
const tools = this.toolRegistry.list().length > 0
|
||||
? this.toolRegistry.getDefinitions()
|
||||
: undefined;
|
||||
|
||||
let result: GenerateTextResult;
|
||||
let fullText = '';
|
||||
let allToolCalls: ToolCall[] = [];
|
||||
let iterations = 0;
|
||||
|
||||
// Tool calling loop
|
||||
while (iterations < this.maxToolCalls) {
|
||||
iterations++;
|
||||
|
||||
if (options.stream && !tools && options.onToken) {
|
||||
// Streaming without tools
|
||||
const stream = await this.provider.streamText({
|
||||
messages,
|
||||
temperature: options.temperature ?? this.temperature,
|
||||
maxTokens: options.maxTokens ?? this.maxTokens,
|
||||
onToken: options.onToken,
|
||||
});
|
||||
|
||||
let usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };
|
||||
for await (const chunk of stream) {
|
||||
if (chunk.text) fullText += chunk.text;
|
||||
if (chunk.usage) usage = { ...usage, ...chunk.usage };
|
||||
}
|
||||
|
||||
result = {
|
||||
text: fullText,
|
||||
usage,
|
||||
finishReason: 'stop',
|
||||
};
|
||||
break;
|
||||
} else if (options.outputSchema) {
|
||||
// Structured output
|
||||
const objResult = await this.provider.generateObject({
|
||||
messages,
|
||||
schema: options.outputSchema ?? this.outputSchema,
|
||||
temperature: options.temperature ?? this.temperature,
|
||||
maxTokens: options.maxTokens ?? this.maxTokens,
|
||||
});
|
||||
|
||||
result = {
|
||||
text: JSON.stringify(objResult.object),
|
||||
usage: objResult.usage,
|
||||
finishReason: 'stop',
|
||||
};
|
||||
fullText = result.text;
|
||||
break;
|
||||
} else {
|
||||
// Regular generation with potential tool calls
|
||||
result = await this.provider.generateText({
|
||||
messages,
|
||||
temperature: options.temperature ?? this.temperature,
|
||||
maxTokens: options.maxTokens ?? this.maxTokens,
|
||||
tools,
|
||||
});
|
||||
|
||||
if (result.toolCalls && result.toolCalls.length > 0) {
|
||||
allToolCalls.push(...result.toolCalls);
|
||||
|
||||
// Add assistant message with tool calls
|
||||
messages.push({
|
||||
role: 'assistant',
|
||||
content: result.text || null,
|
||||
tool_calls: result.toolCalls,
|
||||
});
|
||||
|
||||
// Execute tool calls
|
||||
for (const tc of result.toolCalls) {
|
||||
const toolTrace = trace.createChild({ name: `tool:${tc.function.name}` }).start();
|
||||
|
||||
try {
|
||||
const toolFn = this.toolRegistry.get(tc.function.name);
|
||||
if (!toolFn) {
|
||||
throw new Error(`Tool '${tc.function.name}' not found`);
|
||||
}
|
||||
|
||||
const args = JSON.parse(tc.function.arguments);
|
||||
const toolResult = await toolFn.execute(args, {
|
||||
agentName: this.name,
|
||||
sessionId: this.sessionId,
|
||||
runId: run.id,
|
||||
});
|
||||
|
||||
const resultStr = typeof toolResult === 'string'
|
||||
? toolResult
|
||||
: JSON.stringify(toolResult);
|
||||
|
||||
messages.push({
|
||||
role: 'tool',
|
||||
content: resultStr,
|
||||
tool_call_id: tc.id,
|
||||
});
|
||||
|
||||
toolTrace.complete({ result: resultStr });
|
||||
} catch (error: any) {
|
||||
messages.push({
|
||||
role: 'tool',
|
||||
content: `Error: ${error.message}`,
|
||||
tool_call_id: tc.id,
|
||||
});
|
||||
toolTrace.fail(error);
|
||||
}
|
||||
}
|
||||
|
||||
// Continue loop to get final response
|
||||
continue;
|
||||
}
|
||||
|
||||
// No tool calls, we have our final response
|
||||
fullText = result.text;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Add assistant message to session
|
||||
this.session.addMessage({
|
||||
role: 'assistant',
|
||||
content: fullText,
|
||||
tool_calls: allToolCalls.length > 0 ? allToolCalls : undefined,
|
||||
});
|
||||
|
||||
trace.complete({ responseLength: fullText.length });
|
||||
run.complete();
|
||||
|
||||
// Parse structured output if schema was provided
|
||||
let structured: any;
|
||||
if (options.outputSchema) {
|
||||
try {
|
||||
structured = JSON.parse(fullText);
|
||||
} catch {
|
||||
// Not valid JSON
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text: fullText,
|
||||
structured,
|
||||
toolCalls: allToolCalls.length > 0 ? allToolCalls : undefined,
|
||||
usage: result!.usage,
|
||||
runId: run.id,
|
||||
sessionId: this.sessionId,
|
||||
};
|
||||
} catch (error: any) {
|
||||
trace.fail(error);
|
||||
run.fail(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start method for compatibility
|
||||
*/
|
||||
async start(prompt: string, options?: ChatOptions): Promise<string> {
|
||||
const result = await this.chat(prompt, options);
|
||||
return result.text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the session
|
||||
*/
|
||||
getSession(): Session {
|
||||
return this.session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear conversation history
|
||||
*/
|
||||
clearHistory(): void {
|
||||
this.session.clearMessages();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Agent Handoff - Transfer conversations between agents
|
||||
*/
|
||||
|
||||
import type { EnhancedAgent } from './enhanced';
|
||||
|
||||
export interface HandoffConfig {
|
||||
agent: EnhancedAgent;
|
||||
name?: string;
|
||||
description?: string;
|
||||
condition?: (context: HandoffContext) => boolean;
|
||||
transformContext?: (messages: any[]) => any[];
|
||||
}
|
||||
|
||||
export interface HandoffContext {
|
||||
messages: any[];
|
||||
lastMessage: string;
|
||||
topic?: string;
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface HandoffResult {
|
||||
handedOffTo: string;
|
||||
response: string;
|
||||
context: HandoffContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handoff class - Represents a handoff target
|
||||
*/
|
||||
export class Handoff {
|
||||
readonly targetAgent: EnhancedAgent;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly condition?: (context: HandoffContext) => boolean;
|
||||
readonly transformContext?: (messages: any[]) => any[];
|
||||
|
||||
constructor(config: HandoffConfig) {
|
||||
this.targetAgent = config.agent;
|
||||
this.name = config.name || `handoff_to_${config.agent.name}`;
|
||||
this.description = config.description || `Transfer conversation to ${config.agent.name}`;
|
||||
this.condition = config.condition;
|
||||
this.transformContext = config.transformContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if handoff should be triggered
|
||||
*/
|
||||
shouldTrigger(context: HandoffContext): boolean {
|
||||
if (this.condition) {
|
||||
return this.condition(context);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the handoff
|
||||
*/
|
||||
async execute(context: HandoffContext): Promise<HandoffResult> {
|
||||
let messages = context.messages;
|
||||
|
||||
if (this.transformContext) {
|
||||
messages = this.transformContext(messages);
|
||||
}
|
||||
|
||||
// Transfer context to target agent
|
||||
const response = await this.targetAgent.chat(context.lastMessage);
|
||||
|
||||
return {
|
||||
handedOffTo: this.targetAgent.name,
|
||||
response: response.text,
|
||||
context: {
|
||||
...context,
|
||||
messages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tool definition for LLM
|
||||
*/
|
||||
getToolDefinition(): { name: string; description: string; parameters: any } {
|
||||
return {
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
reason: {
|
||||
type: 'string',
|
||||
description: 'Reason for the handoff',
|
||||
},
|
||||
},
|
||||
required: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a handoff configuration
|
||||
*/
|
||||
export function handoff(config: HandoffConfig): Handoff {
|
||||
return new Handoff(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handoff filters - Common condition functions
|
||||
*/
|
||||
export const handoffFilters = {
|
||||
/**
|
||||
* Trigger handoff based on topic keywords
|
||||
*/
|
||||
topic: (keywords: string | string[]) => {
|
||||
const keywordList = Array.isArray(keywords) ? keywords : [keywords];
|
||||
return (context: HandoffContext): boolean => {
|
||||
const lastMessage = context.lastMessage.toLowerCase();
|
||||
return keywordList.some(kw => lastMessage.includes(kw.toLowerCase()));
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Trigger handoff based on metadata
|
||||
*/
|
||||
metadata: (key: string, value: any) => {
|
||||
return (context: HandoffContext): boolean => {
|
||||
return context.metadata?.[key] === value;
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Always trigger
|
||||
*/
|
||||
always: () => {
|
||||
return (): boolean => true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Never trigger (manual only)
|
||||
*/
|
||||
never: () => {
|
||||
return (): boolean => false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Combine multiple conditions with AND
|
||||
*/
|
||||
and: (...conditions: Array<(context: HandoffContext) => boolean>) => {
|
||||
return (context: HandoffContext): boolean => {
|
||||
return conditions.every(cond => cond(context));
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Combine multiple conditions with OR
|
||||
*/
|
||||
or: (...conditions: Array<(context: HandoffContext) => boolean>) => {
|
||||
return (context: HandoffContext): boolean => {
|
||||
return conditions.some(cond => cond(context));
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Router Agent - Route requests to specialized agents
|
||||
*/
|
||||
|
||||
import type { EnhancedAgent } from './enhanced';
|
||||
|
||||
export interface RouteConfig {
|
||||
agent: EnhancedAgent;
|
||||
condition: (input: string, context?: RouteContext) => boolean | Promise<boolean>;
|
||||
priority?: number;
|
||||
}
|
||||
|
||||
export interface RouteContext {
|
||||
history?: string[];
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface RouterConfig {
|
||||
name?: string;
|
||||
routes: RouteConfig[];
|
||||
defaultAgent?: EnhancedAgent;
|
||||
verbose?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Router Agent - Routes requests to the most appropriate agent
|
||||
*/
|
||||
export class RouterAgent {
|
||||
readonly name: string;
|
||||
private routes: RouteConfig[];
|
||||
private defaultAgent?: EnhancedAgent;
|
||||
private verbose: boolean;
|
||||
|
||||
constructor(config: RouterConfig) {
|
||||
this.name = config.name || 'Router';
|
||||
this.routes = config.routes.sort((a, b) => (b.priority || 0) - (a.priority || 0));
|
||||
this.defaultAgent = config.defaultAgent;
|
||||
this.verbose = config.verbose ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route a request to the appropriate agent
|
||||
*/
|
||||
async route(input: string, context?: RouteContext): Promise<{ agent: EnhancedAgent; response: string } | null> {
|
||||
for (const route of this.routes) {
|
||||
const matches = await route.condition(input, context);
|
||||
if (matches) {
|
||||
if (this.verbose) {
|
||||
console.log(`[Router] Routing to: ${route.agent.name}`);
|
||||
}
|
||||
const response = await route.agent.chat(input);
|
||||
return { agent: route.agent, response: response.text };
|
||||
}
|
||||
}
|
||||
|
||||
if (this.defaultAgent) {
|
||||
if (this.verbose) {
|
||||
console.log(`[Router] Using default agent: ${this.defaultAgent.name}`);
|
||||
}
|
||||
const response = await this.defaultAgent.chat(input);
|
||||
return { agent: this.defaultAgent, response: response.text };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a route
|
||||
*/
|
||||
addRoute(config: RouteConfig): this {
|
||||
this.routes.push(config);
|
||||
this.routes.sort((a, b) => (b.priority || 0) - (a.priority || 0));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all routes
|
||||
*/
|
||||
getRoutes(): RouteConfig[] {
|
||||
return [...this.routes];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Route condition helpers
|
||||
*/
|
||||
export const routeConditions = {
|
||||
/**
|
||||
* Match by keywords
|
||||
*/
|
||||
keywords: (keywords: string | string[]) => {
|
||||
const keywordList = Array.isArray(keywords) ? keywords : [keywords];
|
||||
return (input: string): boolean => {
|
||||
const lower = input.toLowerCase();
|
||||
return keywordList.some(kw => lower.includes(kw.toLowerCase()));
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Match by regex
|
||||
*/
|
||||
pattern: (regex: RegExp) => {
|
||||
return (input: string): boolean => regex.test(input);
|
||||
},
|
||||
|
||||
/**
|
||||
* Match by metadata
|
||||
*/
|
||||
metadata: (key: string, value: any) => {
|
||||
return (_input: string, context?: RouteContext): boolean => {
|
||||
return context?.metadata?.[key] === value;
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Always match (for default routes)
|
||||
*/
|
||||
always: () => {
|
||||
return (): boolean => true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Combine conditions with AND
|
||||
*/
|
||||
and: (...conditions: Array<(input: string, context?: RouteContext) => boolean>) => {
|
||||
return (input: string, context?: RouteContext): boolean => {
|
||||
return conditions.every(c => c(input, context));
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Combine conditions with OR
|
||||
*/
|
||||
or: (...conditions: Array<(input: string, context?: RouteContext) => boolean>) => {
|
||||
return (input: string, context?: RouteContext): boolean => {
|
||||
return conditions.some(c => c(input, context));
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a router agent
|
||||
*/
|
||||
export function createRouter(config: RouterConfig): RouterAgent {
|
||||
return new RouterAgent(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;
|
||||
}
|
||||
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user