Compare commits

...
28 Commits
Author SHA1 Message Date
Mervin Praison f5d4db4262 Release v3.1.2 2026-01-02 08:17:39 +00:00
Mervin Praison 87d691c616 Release v3.1.1 2026-01-02 07:54:02 +00:00
Mervin Praison 8ea15dee0f Release v3.1.0 2026-01-02 07:35:57 +00:00
Mervin Praison 4f56842e08 Release v3.0.9 2026-01-02 07:22:27 +00:00
Mervin Praison a24836aaee Release v3.0.8 2026-01-02 06:59:48 +00:00
Mervin Praison be9ce27615 Release v3.0.7 2026-01-02 06:43:56 +00:00
Mervin Praison 0159a1e082 Release v3.0.6 2026-01-02 06:18:14 +00:00
Mervin Praison 71a5076c07 Release v3.0.5 2026-01-02 06:06:01 +00:00
Mervin Praison 9815a9f8a8 Release v3.0.4 2026-01-02 05:45:18 +00:00
Mervin Praison 2ae44a05b0 Release v3.0.3 2026-01-02 05:17:33 +00:00
Mervin Praison 3386d25022 Release v3.0.2 2026-01-02 04:33:19 +00:00
Mervin Praison 6dca2ace8a feat(tui): queue editing + update_input method
## Queue Editing
- Added update_input method to QueueScheduler for editing queued runs
- Added update_input method to QueueManager
- Added handler for QueuePanelWidget.EditRequested in TUIApp
- Only queued (not running) items can be edited

## Queue-First Architecture Support
- Queue items can be edited before processing
- EditRequested message already existed in QueuePanelWidget

31 tests passing
2026-01-02 04:24:10 +00:00
Mervin Praison 63548739e8 feat(tui): session history persistence with SessionStore
## Session History Implementation
- Created SessionStore class for in-memory chat history persistence
- Added chat_history field to QueuedRun model
- Modified queue worker to inject chat_history into Agent
- Updated TUIApp to store user/assistant messages in SessionStore
- Pass chat_history to queue when submitting messages

## How It Works
1. User sends message -> stored in SessionStore
2. Queue submission includes chat_history from SessionStore
3. Worker injects chat_history into Agent.chat_history
4. Agent has full conversation context
5. Response stored back in SessionStore

## Verified
- Agent remembers previous messages in session
- History format correct for LLM (role + content)
- 31 tests passing
2026-01-02 04:22:26 +00:00
Mervin Praison 3e046537f4 fix(tui): sessions screen loading + update_sessions_screen method
- Call _update_sessions_screen() after pushing sessions screen
- Add _update_sessions_screen() method to load sessions from persistence
- Fallback to showing current session if persistence fails

31 tests passing
2026-01-02 04:02:55 +00:00
Mervin Praison 4a34677567 fix(tui): compose() NoneType error + add missing slash commands
## Fixes
1. ChatWidget.compose() now yields empty generator instead of None
2. Added 7 missing slash commands: /tokens, /plan, /map, /undo, /diff, /commit, /tools

## Commands Added
- /tokens - Show token usage breakdown
- /plan - Show/create task plans
- /map - Show repository map
- /undo - Undo last change
- /diff - Show diff of changes
- /commit - Commit changes
- /tools - Show available tools

31 tests passing
2026-01-02 04:01:25 +00:00
Mervin Praison 19e91cb669 fix(tui): proper scrollbar + non-blocking input
## Scrollbar Fix (VerticalScroll)
- ChatWidget now inherits from VerticalScroll (not ScrollableContainer)
- Messages mount directly to container (removed inner Vertical)
- scroll_end() called after adding messages and during streaming
- CSS has overflow-y: auto for proper scrollbar display

## Non-Blocking Input (@work decorator)
- Message submission uses run_worker() for background execution
- _process_message_submission decorated with @work
- User can type while agent is processing
- Multiple messages can be queued

## Root Causes Fixed
1. Inner Vertical container had overflow:hidden - removed it
2. Message handler was async blocking - now uses worker pattern

Based on Textual documentation:
- VerticalScroll: container with vertical layout and auto Y scrollbar
- @work decorator: runs coroutine in background without blocking UI

31 tests passing
2026-01-02 03:56:56 +00:00
Mervin Praison 5a6125021a fix(tui): add scrollbar to chat + fix session history
## Scrollbar Fix
- ChatWidget now inherits from ScrollableContainer
- Scrollbar visible in chat area (like queue panel)

## Session History Fix
- Pass session_id from TUI app to queue submit
- Pass session_id in agent_config
- Worker now passes session_id to Agent constructor
- Agent will now use session history for context

Flow: TUI.session_id → queue.submit() → worker → Agent(session_id=...)

31 tests passing
2026-01-02 03:44:55 +00:00
Mervin Praison da26887f24 feat(tui): NEWEST-AT-TOP rendering + fix @ typing blockage
## UX STRATEGY CHANGE (Stabilization)

### Newest-at-Top Rendering
- Messages now render NEWEST at TOP
- No scroll dependency - latest always visible
- Streaming updates visible immediately
- ChatWidget inherits from Vertical (not ScrollableContainer)

### @ Typing Not Blocked
- @ handler no longer mounts focus-stealing popup
- Users can freely type @path/to/file
- Manual path entry works without interruption

### Verified Working
- ✅ New messages appear at TOP
- ✅ Latest response always visible
- ✅ Streaming updates visible
- ✅ Can type while agent runs
- ✅ Queue increments immediately
- ✅ Backslash popup works
- ✅ @ does NOT block typing
- ✅ 31 tests passing
2026-01-02 03:38:13 +00:00
Mervin Praison 1b2f7139f9 docs(tui): update help screen with auto-trigger features
- Document @ auto-show file browser
- Document / auto-show command discovery
- Update backslash description to 'auto-show'
2026-01-02 03:25:17 +00:00
Mervin Praison aafbc86180 feat(tui): auto-trigger popups for backslash, @, and / commands
## Auto-Trigger Features (Claude Code-style UX)

### Backslash (\) Auto-Popup
- Typing \ immediately shows command popup
- Clears backslash from input
- No manual trigger needed

### @ File Autocomplete
- Typing @ shows file/directory popup
- Fuzzy search files in workspace
- Supports ~/ and absolute paths
- Reuses FileSearchService from at_mentions.py

### / Command Discovery
- Typing / shows command popup with filter
- Same unified command registry as backslash

## Queue Live Updates
- Queue panel updates IMMEDIATELY when message queued
- Updates on run completion and error
- Reactive queued_count and running_count

## Composer Never Disabled
- Input stays enabled during agent processing
- Users can queue multiple messages

## New Files
- widgets/file_popup.py: FilePopupWidget for @ autocomplete

## Tests
- 31 tests passing (10 new tests)
- TestAutoTriggerEvents: 4 tests
- TestFilePopup: 4 tests
- TestQueueLiveUpdates: 2 tests
2026-01-02 03:24:39 +00:00
Mervin Praison 3d4ca1b7c0 docs(tui): update help screen with safe keyboard defaults and backslash commands
## Help Screen Updates
- Document backslash (\) command popup
- Show safe keyboard defaults (no Ctrl/Fn by default)
- Add command mode (: prefix) section
- Add slash commands (/ prefix) section
- Document optional Ctrl/Fn key env vars

## Keyboard Shortcuts Documented
- \ - Show command popup
- Enter - Send message
- Shift+Enter - New line
- q - Quit (when not typing)
- ? - Help
- : - Command mode
- / - Search mode
- Escape - Cancel/Close
2026-01-02 03:07:50 +00:00
Mervin Praison 1180aa38bd feat(tui): add backslash command popup for Claude Code-style UX
## New Features

### Command Popup Widget (command_popup.py)
- CommandPopupWidget: Overlay showing all available commands
- Triggered by backslash (\) key - matches Claude Code UX
- Searchable/filterable command list
- Keyboard navigation (arrows, Enter, Escape)
- 16 default commands with aliases

### MainScreen Integration
- Backslash binding shows command popup
- Escape dismisses popup or cancels input
- Command selection executes command
- Popup layer CSS for proper overlay positioning

## Commands Available
- help, clear, model, cost, tokens, queue
- cancel, settings, sessions, tools, exit
- plan, undo, diff, commit, map

## Tests
- 21 tests passing
- TestCommandPopup: 4 new tests
- TestMainScreenBackslash: 3 new tests

## Files Changed
- NEW: widgets/command_popup.py
- screens/main.py: Add popup integration
- tests/unit/tui/test_tui_widgets.py: Add tests
2026-01-02 03:06:44 +00:00
Mervin Praison 65f65e5c7b feat(tui): command mode routing and safe keyboard defaults
## Changes

### Command System (: and / prefix)
- Both : and / now work as command prefixes
- Local command handling in MainScreen._handle_local_command()
- Commands: :quit, :clear, :help, :tools, :queue, :settings, :cancel
- Aliases work: :q, :cl, :h, :t, :qu

### Keyboard Defaults
- TUIApp bindings now hidden in footer (show=False)
- Ctrl+Q/C kept for emergency exit but not displayed
- MainScreen shows safe defaults: q, :, ?, Esc

### Help Text Updated
- Shows safe keyboard shortcuts
- Documents command mode usage
- Removed references to Ctrl/Fn keys

## Files Changed
- app.py: Hide Ctrl bindings in footer, update help text
- screens/main.py: Add _handle_local_command() for : commands
- widgets/composer.py: Support both / and : as command prefixes

## Tests
- 14 tests passing
- Command parsing verified
- TUI app startup verified
2026-01-02 02:48:50 +00:00
Mervin Praison f81a12d5e8 feat(tui): comprehensive UX fixes - safe keyboard defaults, auto-scroll, tools panel
BREAKING CHANGE: Keyboard shortcuts changed to safe defaults

## Changes

### 1. Auto-scroll Fix
- Use call_after_refresh() to ensure scroll happens after DOM updates
- Fixed in ChatWidget.add_message() and update_streaming()

### 2. Tools Panel Fix
- Added ScrollableContainer for tools list (no more truncation)
- Shows count of available tools
- All 13 tools now visible with scrolling

### 3. Safe Keyboard Defaults (NO Ctrl/Fn keys by default)
- Single-char shortcuts: q (quit), : (command mode), ? (help)
- Command mode: :quit, :clear, :help, :tools, :queue, :settings
- Ctrl keys (^Q, ^C, ^L) - DISABLED by default (opt-in)
- Function keys (F1-F5) - DISABLED by default (opt-in)

### 4. Configuration System
- New TUIConfig class in config.py
- Environment variables:
  - PRAISONAI_TUI_CTRL_KEYS=1 (enable Ctrl keys)
  - PRAISONAI_TUI_FN_KEYS=1 (enable Fn keys)
  - PRAISONAI_TUI_LEADER=; (custom leader key)

### 5. Non-blocking Input
- Queue accepts messages while agents are running
- Already implemented in previous commit

## Files Changed
- widgets/chat.py - Auto-scroll fix
- widgets/tool_panel.py - ScrollableContainer, show all tools
- widgets/composer.py - set_text() method for command mode
- screens/main.py - Safe default bindings, command mode actions
- config.py - NEW: TUIConfig, command parsing, help text

## Tests
- 14 tests passing
- New tests for TUIConfig and safe bindings
2026-01-02 02:39:16 +00:00
Mervin Praison cf6f5fbefe feat(tui): fix help screen, Enter key, and add TDD tests
Fixes:
- Add HelpScreen for F1 key (was missing, caused KeyError)
- Fix Enter key to send message using custom SubmitTextArea class
- Fix Shift+Enter to insert newline properly
- Register HelpScreen in TUIApp.SCREENS

Tests:
- Add TDD test suite for TUI widgets (12 tests)
- Test Enter key submission
- Test Shift+Enter newline
- Test F1 help screen
- Test Ctrl key bindings

All 13 default tools (ACP, LSP, Basic) load correctly.
Queue system tested and working with real API keys.
2026-01-02 02:23:02 +00:00
Mervin Praison 908d7710db feat(tui): improve TUI usability and add tools panel display
- Enter key now sends message (was Ctrl+Enter)
- Shift+Enter inserts newline without backslash
- Allow typing while response is generating (queue multiple messages)
- Display available tools in Tools panel
- Add edit/delete functionality to queue panel
- Auto-scroll already working in chat widget

TUI Architecture:
- TUIApp -> QueueManager -> WorkerPool -> Agent (from praisonaiagents)
- Tools stored in runtime registry to avoid JSON serialization issues
2026-01-02 02:08:22 +00:00
Mervin Praison 7d5b41e31f fix: use 'llm' parameter instead of 'model' for Agent initialization in queue worker
- Agent class uses 'llm' parameter, not 'model'
- This fixes 'unexpected keyword argument model' error in TUI mode
2026-01-01 19:57:31 +00:00
Mervin Praison e46a0bc9f3 Release v3.0.1 2025-12-31 19:29:02 +00:00
90 changed files with 13171 additions and 1221 deletions

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=3.0.0" \
"praisonai>=3.1.2" \
"praisonai[chat]" \
"embedchain[github,youtube]"
+1 -1
View File
@@ -20,7 +20,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=3.0.0" \
"praisonai>=3.1.2" \
"praisonai[ui]" \
"praisonai[chat]" \
"praisonai[realtime]" \
+1 -1
View File
@@ -16,7 +16,7 @@ RUN mkdir -p /root/.praison
# Install Python packages (using latest versions)
RUN pip install --no-cache-dir \
praisonai_tools \
"praisonai>=3.0.0" \
"praisonai>=3.1.2" \
"praisonai[ui]" \
"praisonai[crewai]"
+203
View File
@@ -0,0 +1,203 @@
# Profiling CLI
PraisonAI provides unified profiling capabilities for performance analysis and debugging, with **full visibility from ENTER to first response**.
## Quick Start
```bash
# Basic profiling
praisonai "What is 2+2?" --profile
# Deep profiling with call graph, decision trace, and module breakdown
praisonai "What is 2+2?" --profile --profile-deep
# JSON output format
praisonai "What is 2+2?" --profile --profile-format json
```
## Time to First Response (TTFR)
**TTFR** is the key user-perceived latency metric. It measures the time from when you press ENTER until the first visible output appears.
### What contributes to TTFR?
1. **CLI Entry** - Time to reach the CLI entry point
2. **CLI Parse** - Argparse/Typer routing time
3. **Routing** - Command routing to handler
4. **Imports** - Loading required modules
5. **Agent Init** - Initializing the agent
6. **Network Request** - Sending request to LLM API
7. **First Token** - Receiving first token (streaming)
8. **First Output** - Rendering first visible output
### How to reduce TTFR
1. **Warm runs** - Imports are cached after first run
2. **Streaming mode** - See output as tokens arrive
3. **Lighter models** - Faster response times
4. **Local models** - Eliminate network latency
## CLI Flags
| Flag | Description | Default |
|------|-------------|---------|
| `--profile` | Enable profiling with timing breakdown | Disabled |
| `--profile-deep` | Enable deep profiling with call graph (higher overhead) | Disabled |
| `--profile-format` | Output format: `text` or `json` | `text` |
## Profile Command
For more detailed profiling options, use the `profile` subcommand:
```bash
# Profile a query
praisonai profile query "What is 2+2?"
# With deep call tracing
praisonai profile query "Hello" --deep
# Limit functions shown
praisonai profile query "Test" --limit 20
# Save artifacts to directory
praisonai profile query "Test" --save ./profile_results
# JSON output
praisonai profile query "Test" --format json
```
### Profile Query Options
| Option | Description | Default |
|--------|-------------|---------|
| `--model, -m` | Model to use | Default model |
| `--stream/--no-stream` | Use streaming mode | No stream |
| `--deep` | Enable deep call tracing | Disabled |
| `--limit, -n` | Top N functions to show | 30 |
| `--sort, -s` | Sort by: `cumulative` or `tottime` | `cumulative` |
| `--show-callers` | Show caller functions | Disabled |
| `--show-callees` | Show callee functions | Disabled |
| `--save` | Save artifacts to path | None |
| `--format, -f` | Output format: `text` or `json` | `text` |
## Other Profile Commands
```bash
# Profile module import times
praisonai profile imports
# Profile CLI startup time
praisonai profile startup
# Run comprehensive profiling suite
praisonai profile suite
# Create performance snapshots for comparison
praisonai profile snapshot --baseline
praisonai profile snapshot current --compare
# Configure performance optimizations
praisonai profile optimize --show
```
## Output Format
### Text Report
```
======================================================================
PraisonAI Profile Report
======================================================================
Run ID: abc12345
Timestamp: 2024-01-02T12:00:00.000000Z
Method: cli_direct
Version: 3.0.1
## Execution Timeline
---------------------------------------------
Imports : 500.00 ms
Agent Init : 0.50 ms
Execution : 2000.00 ms
───────────────────────────────────────────
⏱ Time to First Response : 2500.50 ms
TOTAL : 2500.50 ms
## Timing Breakdown
----------------------------------------
Imports: 500.00 ms
Agent Init: 0.50 ms
Execution: 2000.00 ms
─────────────────────────────────────
TOTAL: 2500.50 ms
## Decision Trace (deep profile only)
----------------------------------------
Agent Config: default
Model: gpt-4
Streaming: disabled
Profile Layer: 2
## Top Functions by Cumulative Time
----------------------------------------------------------------------
Function Calls Cumul (ms)
----------------------------------------------------------------------
request 1 1800.00
send 1 1750.00
...
```
### JSON Report
```json
{
"schema_version": "1.0",
"run_id": "abc12345",
"timestamp": "2024-01-02T12:00:00.000000Z",
"invocation": {
"method": "cli_direct",
"flags": {"layer": 1, "stream": false, "model": null},
"praisonai_version": "3.0.1",
"python_version": "3.12.0"
},
"timing": {
"total_ms": 2500.5,
"imports_ms": 500.0,
"agent_init_ms": 0.5,
"execution_ms": 2000.0
},
"functions": [...],
"response_preview": "four"
}
```
## Profiling Layers
| Layer | Overhead | Features |
|-------|----------|----------|
| 0 | < 1ms | Wall-clock phases only |
| 1 | ~5% | + cProfile function stats |
| 2 | ~15% | + Call graph (callers/callees) |
- `--profile` uses Layer 1
- `--profile --profile-deep` uses Layer 2
## Performance Tips
1. **Use Layer 0 for production monitoring** - minimal overhead
2. **Use Layer 1 for development profiling** - good balance
3. **Use Layer 2 only for deep debugging** - higher overhead
## Observational Equivalence
The following commands produce equivalent profile reports:
```bash
# CLI direct
praisonai "prompt" --profile
# Profile command
praisonai profile query "prompt"
```
Both use the same unified profiling architecture and produce identical schema output.
+257
View File
@@ -0,0 +1,257 @@
# Profiling Module
PraisonAI provides a unified profiling module for programmatic performance analysis.
## Quick Start
```python
from praisonai.cli.execution import (
ExecutionRequest,
Profiler,
ProfilerConfig,
)
# Create execution request
request = ExecutionRequest(prompt="What is 2+2?")
# Configure profiler
config = ProfilerConfig(layer=1)
# Run with profiling
profiler = Profiler(config)
result, report = profiler.profile_sync(request)
# Access results
print(f"Output: {result.output}")
print(f"Total time: {report.timing.total_ms}ms")
```
## ExecutionRequest
Immutable request descriptor for execution.
```python
from praisonai.cli.execution import ExecutionRequest
# Basic request
request = ExecutionRequest(prompt="Hello")
# With model
request = ExecutionRequest(
prompt="Hello",
model="gpt-4",
agent_name="MyAgent",
)
# With streaming
request = ExecutionRequest(
prompt="Hello",
stream=True,
)
```
### Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `prompt` | str | Required | The prompt to execute |
| `agent_name` | str | "Assistant" | Name of the agent |
| `agent_instructions` | str | None | Custom instructions |
| `model` | str | None | Model to use |
| `stream` | bool | False | Enable streaming |
| `tools` | tuple | () | Tools to provide |
## ProfilerConfig
Configuration for profiling behavior.
```python
from praisonai.cli.execution import ProfilerConfig
# Layer 0: Wall-clock only (< 1ms overhead)
config = ProfilerConfig(layer=0)
# Layer 1: + cProfile stats (~5% overhead)
config = ProfilerConfig(layer=1)
# Layer 2: + Call graph (~15% overhead)
config = ProfilerConfig(
layer=2,
show_callers=True,
show_callees=True,
)
# From CLI flags
config = ProfilerConfig.from_flags(
profile=True,
deep=True,
network=False,
)
```
### Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `layer` | int | 1 | Profiling layer (0, 1, or 2) |
| `limit` | int | 30 | Max functions to show |
| `sort_by` | str | "cumulative" | Sort by: cumulative, time, calls |
| `show_callers` | bool | False | Show caller functions |
| `show_callees` | bool | False | Show callee functions |
| `track_network` | bool | False | Track network requests |
| `output_format` | str | "text" | Output format: text, json |
| `save_path` | str | None | Path to save artifacts |
## Profiler
The main profiler class that wraps execution.
```python
from praisonai.cli.execution import Profiler, ProfilerConfig, ExecutionRequest
config = ProfilerConfig(layer=1)
profiler = Profiler(config)
request = ExecutionRequest(prompt="Hello")
result, report = profiler.profile_sync(request, invocation_method="api")
```
### Methods
#### `profile_sync(request, invocation_method="profile_command")`
Profile synchronous execution.
**Parameters:**
- `request`: ExecutionRequest - The execution request
- `invocation_method`: str - How this was invoked (for report)
**Returns:** Tuple of (ExecutionResult, ProfileReport)
## ProfileReport
The canonical profile report with timing and statistics.
```python
# Access timing breakdown
print(f"Total: {report.timing.total_ms}ms")
print(f"Imports: {report.timing.imports_ms}ms")
print(f"Agent Init: {report.timing.agent_init_ms}ms")
print(f"Execution: {report.timing.execution_ms}ms")
# Access function stats (layer 1+)
if report.functions:
for func in report.functions[:5]:
print(f"{func.name}: {func.cumulative_time_ms}ms")
# Access call graph (layer 2)
if report.call_graph:
print(f"Edges: {len(report.call_graph.edges)}")
# Export formats
json_str = report.to_json()
text_str = report.to_text()
dict_data = report.to_dict()
```
### Schema Version
The report uses schema version `1.0`. Schema is frozen after release - new fields are always optional with defaults.
### Mandatory Fields
- `schema_version`: str
- `run_id`: str
- `timestamp`: str (ISO 8601)
- `invocation`: InvocationInfo
- `timing`: TimingBreakdown
- `response_preview`: str
### Optional Fields
- `functions`: List[FunctionStat] (layer 1+)
- `call_graph`: CallGraph (layer 2)
- `network`: List[RequestTiming] (if track_network)
## ExecutionResult
Result of execution with output and metadata.
```python
# Access output
print(result.output)
print(result.success)
print(result.run_id)
# Check for errors
if result.error:
print(f"Error: {result.error}")
# Duration
print(f"Duration: {result.duration_ms}ms")
```
## Data Bounds
Profile data is strictly bounded to prevent memory issues:
| Data Type | Maximum |
|-----------|---------|
| Function stats | 1000 |
| Call graph edges | 5000 |
| Network requests | 100 |
## Example: Full Profiling Workflow
```python
from praisonai.cli.execution import (
ExecutionRequest,
Profiler,
ProfilerConfig,
)
# Configure deep profiling
config = ProfilerConfig(
layer=2,
limit=50,
show_callers=True,
show_callees=True,
)
# Create request
request = ExecutionRequest(
prompt="Explain quantum computing in simple terms",
model="gpt-4",
)
# Profile execution
profiler = Profiler(config)
result, report = profiler.profile_sync(request)
# Print text report
print(report.to_text())
# Save JSON report
with open("profile.json", "w") as f:
f.write(report.to_json())
# Analyze timing
print(f"\nTiming Analysis:")
print(f" Import overhead: {report.timing.imports_ms / report.timing.total_ms * 100:.1f}%")
print(f" Execution time: {report.timing.execution_ms / report.timing.total_ms * 100:.1f}%")
# Top 5 hotspots
if report.functions:
print(f"\nTop 5 Hotspots:")
for func in report.functions[:5]:
print(f" {func.name}: {func.cumulative_time_ms:.2f}ms ({func.calls} calls)")
```
## Invariants
The profiling module guarantees:
1. **Output Equivalence**: Profiled execution produces identical output to non-profiled execution
2. **Schema Stability**: Schema version 1.0 is frozen; new fields are always optional
3. **Bounded Data**: All profile data respects maximum bounds
4. **Zero Overhead When Disabled**: No profiling code runs unless explicitly enabled
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
"""
PraisonAI Benchmark Example
This example demonstrates how to use the benchmark system programmatically
to compare performance across different execution paths.
Usage:
python benchmark_example.py
Requirements:
- OPENAI_API_KEY environment variable set
- praisonai package installed
"""
import os
import sys
# Ensure the package is importable
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../src/praisonai'))
from praisonai.cli.features.benchmark import BenchmarkHandler, BenchmarkReport
def run_quick_comparison():
"""Run a quick comparison of key execution paths."""
print("=" * 60)
print("Quick Benchmark Comparison")
print("=" * 60)
handler = BenchmarkHandler()
# Run benchmark with 2 iterations on key paths
report = handler.run_full_benchmark(
prompt="What is 2+2?",
iterations=2,
paths=["openai_sdk", "praisonai_agent"],
verbose=True
)
# Print comparison table
print("\n" + handler.create_comparison_table(report))
return report
def run_full_benchmark():
"""Run full benchmark suite across all paths."""
print("=" * 60)
print("Full Benchmark Suite")
print("=" * 60)
handler = BenchmarkHandler()
# Run full benchmark
report = handler.run_full_benchmark(
prompt="Hi",
iterations=3,
verbose=True
)
# Print full report
handler.print_report(report)
return report
def run_agent_benchmark():
"""Benchmark PraisonAI Agent specifically."""
print("=" * 60)
print("Agent Benchmark")
print("=" * 60)
handler = BenchmarkHandler()
# Benchmark agent vs SDK
report = handler.run_full_benchmark(
prompt="Explain Python in one sentence",
iterations=3,
paths=["openai_sdk", "praisonai_agent"],
verbose=True
)
# Show timeline diagrams
for name, result in report.results.items():
print(f"\n### {name}")
print(handler.create_timeline_diagram(result))
# Show variance analysis
print(handler.create_variance_table(report))
return report
def save_benchmark_results(report: BenchmarkReport, output_path: str):
"""Save benchmark results to JSON file."""
import json
with open(output_path, 'w') as f:
json.dump(report.to_dict(), f, indent=2)
print(f"\nResults saved to: {output_path}")
def main():
"""Main entry point."""
import argparse
parser = argparse.ArgumentParser(description="PraisonAI Benchmark Example")
parser.add_argument(
"--mode",
choices=["quick", "full", "agent"],
default="quick",
help="Benchmark mode: quick (2 paths), full (all paths), agent (agent focus)"
)
parser.add_argument(
"--output",
type=str,
default=None,
help="Output JSON file path"
)
args = parser.parse_args()
# Check for API key
if not os.environ.get("OPENAI_API_KEY"):
print("Error: OPENAI_API_KEY environment variable not set")
sys.exit(1)
# Run selected benchmark
if args.mode == "quick":
report = run_quick_comparison()
elif args.mode == "full":
report = run_full_benchmark()
elif args.mode == "agent":
report = run_agent_benchmark()
# Save results if requested
if args.output:
save_benchmark_results(report, args.output)
print("\n✅ Benchmark complete!")
if __name__ == "__main__":
main()
+29 -24
View File
@@ -1,7 +1,7 @@
"""
Basic Profiling Example for PraisonAI
This example demonstrates how to use the profiler programmatically
This example demonstrates how to use the unified profiler programmatically
to measure agent performance.
Run with:
@@ -15,51 +15,56 @@ if not os.environ.get("OPENAI_API_KEY"):
print("Please set OPENAI_API_KEY environment variable")
exit(1)
from praisonai.cli.features.profiler import (
from praisonai.cli.execution import (
ExecutionRequest,
Profiler,
ProfilerConfig,
QueryProfiler,
format_profile_report,
)
def main():
"""Run a profiled query and display results."""
# Configure profiler
# Configure profiler (Layer 1 = basic profiling with function stats)
config = ProfilerConfig(
deep=False, # Set True for detailed call tracing (slower)
layer=1, # 0=minimal, 1=basic, 2=deep
limit=15, # Show top 15 functions
show_files=True, # Group by file
first_token=False, # Track time to first token (for streaming)
show_callers=False, # Set True for caller info (layer 2)
show_callees=False, # Set True for callee info (layer 2)
)
# Create profiler
profiler = QueryProfiler(config)
# Create execution request
request = ExecutionRequest(
prompt="What is 2+2?",
agent_name="ProfiledAgent",
)
# Run profiled query
print("🔬 Running profiled query...")
result = profiler.profile_query(
prompt="What is 2+2?",
model=None, # Use default model
stream=False,
)
profiler = Profiler(config)
result, report = profiler.profile_sync(request)
# Print formatted report
print("\n" + format_profile_report(result, config))
print("\n" + report.to_text())
# Access timing data programmatically
print("\n📊 Timing Summary:")
print(f" Imports: {result.timing.imports_ms:>10.2f} ms")
print(f" Agent Construct:{result.timing.agent_construction_ms:>10.2f} ms")
print(f" Total Run: {result.timing.total_run_ms:>10.2f} ms")
print(f" Imports: {report.timing.imports_ms:>10.2f} ms")
print(f" Agent Init: {report.timing.agent_init_ms:>10.2f} ms")
print(f" Execution: {report.timing.execution_ms:>10.2f} ms")
print(f" Total: {report.timing.total_ms:>10.2f} ms")
# Show top 5 functions
print("\n🔥 Top 5 Functions by Cumulative Time:")
for i, func in enumerate(result.top_functions[:5], 1):
print(f" {i}. {func.name}: {func.cumtime_ms:.2f}ms")
if report.functions:
print("\n🔥 Top 5 Functions by Cumulative Time:")
for i, func in enumerate(report.functions[:5], 1):
print(f" {i}. {func.name}: {func.cumulative_time_ms:.2f}ms")
# Show response preview
print(f"\n💬 Response: {result.response[:100]}...")
# Show response
print(f"\n💬 Response: {result.output}")
# Export to JSON
print("\n📄 JSON Export available via: report.to_json()")
if __name__ == "__main__":
@@ -0,0 +1,165 @@
"""
Session Persistence Example
Demonstrates automatic session persistence with zero configuration.
When you provide a session_id to an Agent, conversation history is
automatically saved to disk and restored on subsequent runs.
Usage:
python session_persistence_example.py
Requirements:
- praisonaiagents package installed
- OPENAI_API_KEY environment variable set
"""
from praisonaiagents import Agent
def example_basic_persistence():
"""Basic session persistence example."""
print("=" * 60)
print("EXAMPLE 1: Basic Session Persistence")
print("=" * 60)
session_id = "demo-session-basic"
# Create agent with session_id
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant. Be very brief.",
session_id=session_id,
verbose=False,
)
# First message
print("\n[User]: My favorite color is blue and my lucky number is 7.")
response1 = agent.chat("My favorite color is blue and my lucky number is 7.")
print(f"[Assistant]: {response1}")
# Second message - agent remembers
print("\n[User]: What is my favorite color?")
response2 = agent.chat("What is my favorite color?")
print(f"[Assistant]: {response2}")
print(f"\n✅ Session saved to: ~/.praison/sessions/{session_id}.json")
print(f" Chat history length: {len(agent.chat_history)} messages")
def example_session_restoration():
"""Demonstrates session restoration across Agent instances."""
print("\n" + "=" * 60)
print("EXAMPLE 2: Session Restoration")
print("=" * 60)
session_id = "demo-session-restore"
# First agent instance
print("\n--- First Agent Instance ---")
agent1 = Agent(
name="MemoryBot",
instructions="You are a helpful assistant. Be very brief.",
session_id=session_id,
verbose=False,
)
print("[User]: Remember that my pet's name is Max.")
response1 = agent1.chat("Remember that my pet's name is Max.")
print(f"[Assistant]: {response1}")
# Simulate new process by creating new agent instance
print("\n--- New Agent Instance (simulating restart) ---")
agent2 = Agent(
name="MemoryBot",
instructions="You are a helpful assistant. Be very brief.",
session_id=session_id,
verbose=False,
)
print("[User]: What is my pet's name?")
response2 = agent2.chat("What is my pet's name?")
print(f"[Assistant]: {response2}")
if "max" in response2.lower():
print("\n✅ Session restored successfully! Agent remembered 'Max'.")
else:
print("\n⚠️ Agent may not have remembered correctly.")
def example_in_memory_only():
"""Demonstrates in-memory memory without persistence."""
print("\n" + "=" * 60)
print("EXAMPLE 3: In-Memory Only (No session_id)")
print("=" * 60)
# Agent without session_id - in-memory only
agent = Agent(
name="TempBot",
instructions="You are a helpful assistant. Be very brief.",
verbose=False,
)
print("\n[User]: My name is Alice.")
response1 = agent.chat("My name is Alice.")
print(f"[Assistant]: {response1}")
print("\n[User]: What is my name?")
response2 = agent.chat("What is my name?")
print(f"[Assistant]: {response2}")
print(f"\n✅ In-memory chat history: {len(agent.chat_history)} messages")
print(" (This will be lost when the Agent instance is garbage collected)")
def example_direct_store_access():
"""Demonstrates direct access to the session store."""
print("\n" + "=" * 60)
print("EXAMPLE 4: Direct Session Store Access")
print("=" * 60)
from praisonaiagents.session import get_default_session_store
store = get_default_session_store()
session_id = "demo-direct-access"
# Add messages directly
store.add_user_message(session_id, "Hello from direct access!")
store.add_assistant_message(session_id, "Hi! I received your message.")
# Get history
history = store.get_chat_history(session_id)
print(f"\n✅ Added {len(history)} messages directly to session store")
for msg in history:
print(f" [{msg['role']}]: {msg['content']}")
# List all sessions
sessions = store.list_sessions()
print(f"\n📋 Total sessions in store: {len(sessions)}")
# Clean up demo session
store.delete_session(session_id)
print(f" Deleted demo session: {session_id}")
def main():
"""Run all examples."""
print("\n" + "=" * 60)
print("SESSION PERSISTENCE EXAMPLES")
print("=" * 60)
# Run examples
example_basic_persistence()
example_session_restoration()
example_in_memory_only()
example_direct_store_access()
print("\n" + "=" * 60)
print("ALL EXAMPLES COMPLETE")
print("=" * 60)
print("\nSession files are stored in: ~/.praison/sessions/")
print("You can inspect them with: cat ~/.praison/sessions/<session_id>.json")
if __name__ == "__main__":
main()
@@ -687,6 +687,11 @@ Your Goal: {self.goal}
self._db = db
self._session_id = session_id
self._db_initialized = False
# Session store for JSON-based persistence (lazy - no imports until used)
# Used when session_id is provided but no DB adapter
self._session_store = None
self._session_store_initialized = False
@property
def console(self):
@@ -2094,6 +2099,49 @@ Your Goal: {self.goal}"""
self._db_initialized = True
self._current_run_id = None # Track current run
def _init_session_store(self):
"""
Initialize session store for JSON-based persistence (lazy, first chat only).
This is used when session_id is provided but no DB adapter.
Enables automatic session persistence with zero configuration.
"""
if self._session_store_initialized:
return
# Only initialize if session_id is provided and no DB adapter
if self._session_id is None or self._db is not None:
self._session_store_initialized = True
return
try:
from ..session import get_default_session_store
self._session_store = get_default_session_store()
# Restore chat history from previous session
history = self._session_store.get_chat_history(self._session_id)
if history:
# Only restore if chat_history is empty (avoid duplicates)
if not self.chat_history:
for msg in history:
self.chat_history.append({
"role": msg["role"],
"content": msg["content"]
})
logging.info(f"Restored session {self._session_id} with {len(history)} messages from JSON store")
# Set agent info
self._session_store.set_agent_info(
self._session_id,
agent_name=self.name,
user_id=self.user_id,
)
except Exception as e:
logging.warning(f"Failed to initialize session store: {e}")
self._session_store = None
self._session_store_initialized = True
def _start_run(self, input_content: str):
"""Start a new run (turn) for persistence tracking."""
@@ -2135,17 +2183,27 @@ Your Goal: {self.goal}"""
self._current_run_id = None
def _persist_message(self, role: str, content: str):
"""Persist a message to the DB if adapter is provided."""
if self._db is None:
"""Persist a message to the DB or session store."""
# Try DB adapter first
if self._db is not None:
try:
if role == "user":
self._db.on_user_message(self._session_id, content)
elif role == "assistant":
self._db.on_agent_message(self._session_id, content)
except Exception as e:
logging.warning(f"Failed to persist message to DB: {e}")
return
try:
if role == "user":
self._db.on_user_message(self._session_id, content)
elif role == "assistant":
self._db.on_agent_message(self._session_id, content)
except Exception as e:
logging.warning(f"Failed to persist message: {e}")
# Fall back to session store (JSON-based)
if self._session_store is not None and self._session_id is not None:
try:
if role == "user":
self._session_store.add_user_message(self._session_id, content)
elif role == "assistant":
self._session_store.add_assistant_message(self._session_id, content)
except Exception as e:
logging.warning(f"Failed to persist message to session store: {e}")
@property
def session_id(self) -> Optional[str]:
@@ -2160,6 +2218,10 @@ Your Goal: {self.goal}"""
# Initialize DB session on first chat (lazy)
self._init_db_session()
# Initialize session store for JSON-based persistence (lazy)
# This enables automatic session persistence when session_id is provided
self._init_session_store()
# Start a new run for this chat turn
prompt_str = prompt if isinstance(prompt, str) else str(prompt)
self._start_run(prompt_str)
+22 -13
View File
@@ -58,6 +58,12 @@ class LLM:
# Class-level flag for one-time logging configuration
_logging_configured = False
# Class-level cache for LiteLLM module (avoids repeated import overhead)
_litellm_module = None
# Class-level flag for LiteLLM global settings (set once)
_litellm_configured = False
# Default window sizes for different models (75% of actual to be safe)
MODEL_WINDOWS = {
# OpenAI
@@ -272,14 +278,16 @@ Respond with ONLY a valid JSON tool call in this format:
if not LLM._logging_configured:
LLM._configure_logging()
# Import litellm after logging is configured
try:
import litellm
except ImportError:
raise ImportError(
"LiteLLM is required but not installed. "
"Please install with: pip install 'praisonaiagents[llm]'"
)
# Use cached LiteLLM module or import once (avoids repeated import overhead)
if LLM._litellm_module is None:
try:
import litellm
LLM._litellm_module = litellm
except ImportError:
raise ImportError(
"LiteLLM is required but not installed. "
"Please install with: pip install 'praisonaiagents[llm]'"
)
self.model = model
self.timeout = timeout
@@ -341,11 +349,12 @@ Respond with ONLY a valid JSON tool call in this format:
self._formatted_tools_cache = {}
self._max_cache_size = 100
# Enable error dropping for cleaner output
import litellm
litellm.drop_params = True
# Enable parameter modification for providers like Anthropic
litellm.modify_params = True
# Configure LiteLLM global settings only once (avoids repeated setup cost)
if not LLM._litellm_configured:
litellm = LLM._litellm_module
litellm.drop_params = True
litellm.modify_params = True
LLM._litellm_configured = True
self._setup_event_tracking(events)
# Log all initialization parameters when in debug mode or verbose >= 10
@@ -0,0 +1,185 @@
# Session Persistence for PraisonAI Agents
This module provides automatic session persistence with zero configuration.
## Quick Start
```python
from praisonaiagents import Agent
# With session persistence (auto-enabled)
agent = Agent(
name="Assistant",
session_id="my-session-123"
)
agent.start("Hello, my name is Alice")
# Later, in a new process - history is restored automatically
agent = Agent(
name="Assistant",
session_id="my-session-123"
)
agent.start("What is my name?") # Agent remembers: "Alice"
```
## How It Works
When you provide a `session_id` to an Agent:
1. **Automatic Persistence**: Conversation history is automatically saved to disk
2. **Automatic Restoration**: When a new Agent is created with the same `session_id`, history is restored
3. **Zero Configuration**: No database setup required - uses JSON files by default
### Default Storage Location
Sessions are stored in: `~/.praison/sessions/{session_id}.json`
### Session File Format
```json
{
"session_id": "my-session-123",
"messages": [
{"role": "user", "content": "Hello", "timestamp": 1704153600.0},
{"role": "assistant", "content": "Hi there!", "timestamp": 1704153601.5}
],
"created_at": "2026-01-02T04:00:00+00:00",
"updated_at": "2026-01-02T04:01:00+00:00",
"agent_name": "Assistant"
}
```
## Behavior Matrix
| Scenario | Behavior |
|----------|----------|
| `session_id` provided, no DB | JSON persistence (auto) |
| `session_id` provided, with DB | DB adapter used |
| No `session_id`, same Agent instance | In-memory only |
| No `session_id`, new Agent instance | No history |
## Advanced Usage
### Direct Session Store Access
```python
from praisonaiagents.session import get_default_session_store
store = get_default_session_store()
# Add messages
store.add_user_message("session-123", "Hello")
store.add_assistant_message("session-123", "Hi there!")
# Get history
history = store.get_chat_history("session-123")
# [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}]
# List all sessions
sessions = store.list_sessions()
# Delete a session
store.delete_session("session-123")
```
### Custom Session Directory
```python
from praisonaiagents.session import DefaultSessionStore
store = DefaultSessionStore(
session_dir="/custom/path/sessions",
max_messages=200, # Default: 100
lock_timeout=10.0, # Default: 5.0 seconds
)
```
### Using with DB Adapter
When a DB adapter is provided, it takes precedence over JSON persistence:
```python
from praisonaiagents import Agent
from praisonai.db import PostgresAdapter
agent = Agent(
name="Assistant",
session_id="my-session",
db=PostgresAdapter(connection_string="...")
)
```
## Multi-Process Safety
The session store uses file locking to ensure safe concurrent access:
- **Unix**: Uses `fcntl.flock()` for file locking
- **Windows**: Uses `msvcrt.locking()` for file locking
- **Atomic Writes**: Uses temp file + rename to prevent corruption
Multiple processes can safely read/write to the same session.
## Context Caching
For cost optimization, use `prompt_caching=True` with Anthropic models:
```python
agent = Agent(
name="Assistant",
session_id="my-session",
prompt_caching=True, # Enables Anthropic prompt caching
)
```
This caches the system prompt, reducing token costs for repeated conversations.
## API Reference
### DefaultSessionStore
```python
class DefaultSessionStore:
def __init__(
self,
session_dir: Optional[str] = None, # Default: ~/.praison/sessions/
max_messages: int = 100,
lock_timeout: float = 5.0,
): ...
def add_message(self, session_id: str, role: str, content: str) -> bool: ...
def add_user_message(self, session_id: str, content: str) -> bool: ...
def add_assistant_message(self, session_id: str, content: str) -> bool: ...
def get_chat_history(self, session_id: str, max_messages: int = None) -> List[Dict]: ...
def get_session(self, session_id: str) -> SessionData: ...
def clear_session(self, session_id: str) -> bool: ...
def delete_session(self, session_id: str) -> bool: ...
def list_sessions(self, limit: int = 50) -> List[Dict]: ...
def session_exists(self, session_id: str) -> bool: ...
```
### SessionData
```python
@dataclass
class SessionData:
session_id: str
messages: List[SessionMessage]
created_at: str
updated_at: str
agent_name: Optional[str]
user_id: Optional[str]
metadata: Dict[str, Any]
def get_chat_history(self, max_messages: int = None) -> List[Dict[str, str]]: ...
```
### SessionMessage
```python
@dataclass
class SessionMessage:
role: str # "user", "assistant", "system"
content: str
timestamp: float
metadata: Dict[str, Any]
```
@@ -0,0 +1,70 @@
"""
Session persistence module for PraisonAI Agents.
Provides automatic session persistence with zero configuration.
When a session_id is provided to an Agent, conversation history
is automatically persisted to disk and restored on subsequent runs.
Usage:
from praisonaiagents import Agent
# With session persistence (auto-enabled)
agent = Agent(
name="Assistant",
session_id="my-session-123"
)
agent.start("Hello")
# Later, new process - history is restored
agent = Agent(
name="Assistant",
session_id="my-session-123"
)
agent.start("What did I say before?") # Remembers!
Default storage: ~/.praison/sessions/{session_id}.json
"""
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .store import DefaultSessionStore, SessionMessage, SessionData
# Lazy loading for zero import overhead
_module_cache = {}
def __getattr__(name: str):
"""Lazy load session components."""
if name in _module_cache:
return _module_cache[name]
if name == "DefaultSessionStore":
from .store import DefaultSessionStore
_module_cache[name] = DefaultSessionStore
return DefaultSessionStore
if name == "SessionMessage":
from .store import SessionMessage
_module_cache[name] = SessionMessage
return SessionMessage
if name == "SessionData":
from .store import SessionData
_module_cache[name] = SessionData
return SessionData
if name == "get_default_session_store":
from .store import get_default_session_store
_module_cache[name] = get_default_session_store
return get_default_session_store
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
__all__ = [
"DefaultSessionStore",
"SessionMessage",
"SessionData",
"get_default_session_store",
]
@@ -0,0 +1,521 @@
"""
Default Session Store for PraisonAI Agents.
JSON-based session persistence with file locking and atomic writes.
Zero dependencies beyond stdlib.
"""
import fcntl
import json
import logging
import os
import sys
import tempfile
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
# Default session directory
DEFAULT_SESSION_DIR = os.path.expanduser("~/.praison/sessions")
# Default limits
DEFAULT_MAX_MESSAGES = 100
DEFAULT_LOCK_TIMEOUT = 5.0 # seconds
@dataclass
class SessionMessage:
"""A single message in a session."""
role: str # "user", "assistant", "system"
content: str
timestamp: float = field(default_factory=time.time)
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"role": self.role,
"content": self.content,
"timestamp": self.timestamp,
"metadata": self.metadata,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "SessionMessage":
"""Create from dictionary."""
return cls(
role=data.get("role", "user"),
content=data.get("content", ""),
timestamp=data.get("timestamp", time.time()),
metadata=data.get("metadata", {}),
)
@dataclass
class SessionData:
"""Complete session data structure."""
session_id: str
messages: List[SessionMessage] = field(default_factory=list)
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
updated_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
agent_name: Optional[str] = None
user_id: Optional[str] = None
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for JSON serialization."""
return {
"session_id": self.session_id,
"messages": [m.to_dict() for m in self.messages],
"created_at": self.created_at,
"updated_at": self.updated_at,
"agent_name": self.agent_name,
"user_id": self.user_id,
"metadata": self.metadata,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "SessionData":
"""Create from dictionary."""
messages = [
SessionMessage.from_dict(m)
for m in data.get("messages", [])
]
return cls(
session_id=data.get("session_id", ""),
messages=messages,
created_at=data.get("created_at", datetime.now(timezone.utc).isoformat()),
updated_at=data.get("updated_at", datetime.now(timezone.utc).isoformat()),
agent_name=data.get("agent_name"),
user_id=data.get("user_id"),
metadata=data.get("metadata", {}),
)
def get_chat_history(self, max_messages: Optional[int] = None) -> List[Dict[str, str]]:
"""
Get chat history in LLM-compatible format.
Returns list of {"role": "user/assistant", "content": "..."} dicts.
"""
messages = self.messages
if max_messages and len(messages) > max_messages:
messages = messages[-max_messages:]
return [{"role": m.role, "content": m.content} for m in messages]
class FileLock:
"""
Cross-platform file locking.
Uses fcntl on Unix and msvcrt on Windows.
"""
def __init__(self, filepath: str, timeout: float = DEFAULT_LOCK_TIMEOUT):
self.filepath = filepath
self.timeout = timeout
self._lock_file = None
self._lock_path = filepath + ".lock"
def __enter__(self):
self.acquire()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()
return False
def acquire(self) -> bool:
"""Acquire the file lock."""
# Ensure directory exists
os.makedirs(os.path.dirname(self._lock_path) or ".", exist_ok=True)
start_time = time.time()
while True:
try:
self._lock_file = open(self._lock_path, "w")
if sys.platform == "win32":
# Windows locking
import msvcrt
msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_NBLCK, 1)
else:
# Unix locking
fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except (IOError, OSError, BlockingIOError):
if self._lock_file:
self._lock_file.close()
self._lock_file = None
if time.time() - start_time > self.timeout:
logger.warning(f"Failed to acquire lock for {self.filepath} after {self.timeout}s")
return False
time.sleep(0.05) # Wait 50ms before retry
def release(self) -> None:
"""Release the file lock."""
if self._lock_file:
try:
if sys.platform == "win32":
import msvcrt
msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_UN)
except (IOError, OSError):
pass
finally:
self._lock_file.close()
self._lock_file = None
# Clean up lock file
try:
os.remove(self._lock_path)
except (IOError, OSError):
pass
class DefaultSessionStore:
"""
JSON-based session persistence with file locking.
Features:
- Zero configuration required
- Automatic file locking for multi-process safety
- Atomic writes to prevent corruption
- Configurable message limits
- Thread-safe operations
Usage:
store = DefaultSessionStore()
# Add messages
store.add_message("session-123", "user", "Hello")
store.add_message("session-123", "assistant", "Hi there!")
# Get history
history = store.get_chat_history("session-123")
# [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}]
# Restore in new process
store2 = DefaultSessionStore()
history = store2.get_chat_history("session-123") # Same history!
"""
def __init__(
self,
session_dir: Optional[str] = None,
max_messages: int = DEFAULT_MAX_MESSAGES,
lock_timeout: float = DEFAULT_LOCK_TIMEOUT,
):
"""
Initialize session store.
Args:
session_dir: Directory for session files. Defaults to ~/.praison/sessions/
max_messages: Maximum messages to keep per session.
lock_timeout: Timeout for file lock acquisition.
"""
self.session_dir = session_dir or DEFAULT_SESSION_DIR
self.max_messages = max_messages
self.lock_timeout = lock_timeout
self._lock = threading.RLock()
self._cache: Dict[str, SessionData] = {}
# Ensure session directory exists
os.makedirs(self.session_dir, exist_ok=True)
def _get_session_path(self, session_id: str) -> str:
"""Get the file path for a session."""
# Sanitize session_id for filesystem
safe_id = "".join(c if c.isalnum() or c in "-_" else "_" for c in session_id)
return os.path.join(self.session_dir, f"{safe_id}.json")
def _load_session(self, session_id: str) -> SessionData:
"""Load session from disk with file locking."""
filepath = self._get_session_path(session_id)
# Check cache first
with self._lock:
if session_id in self._cache:
return self._cache[session_id]
# Load from disk
if not os.path.exists(filepath):
session = SessionData(session_id=session_id)
with self._lock:
self._cache[session_id] = session
return session
with FileLock(filepath, self.lock_timeout):
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
session = SessionData.from_dict(data)
except (json.JSONDecodeError, IOError) as e:
logger.warning(f"Failed to load session {session_id}: {e}")
session = SessionData(session_id=session_id)
with self._lock:
self._cache[session_id] = session
return session
def _save_session(self, session: SessionData) -> bool:
"""Save session to disk with atomic write."""
filepath = self._get_session_path(session.session_id)
session.updated_at = datetime.now(timezone.utc).isoformat()
# Trim messages if over limit
if len(session.messages) > self.max_messages:
session.messages = session.messages[-self.max_messages:]
with FileLock(filepath, self.lock_timeout):
try:
# Atomic write: write to temp file, then rename
dir_path = os.path.dirname(filepath)
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=dir_path,
delete=False,
suffix=".tmp"
) as f:
json.dump(session.to_dict(), f, indent=2, ensure_ascii=False)
temp_path = f.name
# Atomic rename
os.replace(temp_path, filepath)
return True
except (IOError, OSError) as e:
logger.error(f"Failed to save session {session.session_id}: {e}")
# Clean up temp file if it exists
try:
if 'temp_path' in locals():
os.remove(temp_path)
except (IOError, OSError):
pass
return False
def add_message(
self,
session_id: str,
role: str,
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""
Add a message to a session.
Args:
session_id: The session ID.
role: Message role ("user", "assistant", "system").
content: Message content.
metadata: Optional metadata.
Returns:
True if saved successfully.
"""
filepath = self._get_session_path(session_id)
message = SessionMessage(
role=role,
content=content,
timestamp=time.time(),
metadata=metadata or {},
)
# Use file lock for atomic read-modify-write
with FileLock(filepath, self.lock_timeout):
# Always reload from disk inside lock to avoid race conditions
if os.path.exists(filepath):
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
session = SessionData.from_dict(data)
except (json.JSONDecodeError, IOError):
session = SessionData(session_id=session_id)
else:
session = SessionData(session_id=session_id)
# Add message
session.messages.append(message)
session.updated_at = datetime.now(timezone.utc).isoformat()
# Trim messages if over limit
if len(session.messages) > self.max_messages:
session.messages = session.messages[-self.max_messages:]
# Write atomically
try:
dir_path = os.path.dirname(filepath) or "."
os.makedirs(dir_path, exist_ok=True)
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=dir_path,
delete=False,
suffix=".tmp"
) as f:
json.dump(session.to_dict(), f, indent=2, ensure_ascii=False)
temp_path = f.name
os.replace(temp_path, filepath)
# Update cache
with self._lock:
self._cache[session_id] = session
return True
except (IOError, OSError) as e:
logger.error(f"Failed to save session {session_id}: {e}")
try:
if 'temp_path' in locals():
os.remove(temp_path)
except (IOError, OSError):
pass
return False
def add_user_message(
self,
session_id: str,
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""Add a user message to a session."""
return self.add_message(session_id, "user", content, metadata)
def add_assistant_message(
self,
session_id: str,
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""Add an assistant message to a session."""
return self.add_message(session_id, "assistant", content, metadata)
def get_chat_history(
self,
session_id: str,
max_messages: Optional[int] = None,
) -> List[Dict[str, str]]:
"""
Get chat history for a session in LLM-compatible format.
Args:
session_id: The session ID.
max_messages: Maximum messages to return (defaults to store limit).
Returns:
List of {"role": "user/assistant", "content": "..."} dicts.
"""
session = self._load_session(session_id)
limit = max_messages or self.max_messages
return session.get_chat_history(limit)
def get_session(self, session_id: str) -> SessionData:
"""Get full session data."""
return self._load_session(session_id)
def set_agent_info(
self,
session_id: str,
agent_name: Optional[str] = None,
user_id: Optional[str] = None,
) -> bool:
"""Set agent info for a session."""
session = self._load_session(session_id)
with self._lock:
if agent_name:
session.agent_name = agent_name
if user_id:
session.user_id = user_id
self._cache[session_id] = session
return self._save_session(session)
def clear_session(self, session_id: str) -> bool:
"""Clear all messages from a session."""
session = self._load_session(session_id)
with self._lock:
session.messages.clear()
self._cache[session_id] = session
return self._save_session(session)
def delete_session(self, session_id: str) -> bool:
"""Delete a session completely."""
filepath = self._get_session_path(session_id)
with self._lock:
if session_id in self._cache:
del self._cache[session_id]
try:
if os.path.exists(filepath):
os.remove(filepath)
return True
except (IOError, OSError) as e:
logger.error(f"Failed to delete session {session_id}: {e}")
return False
def list_sessions(self, limit: int = 50) -> List[Dict[str, Any]]:
"""List all sessions with metadata."""
sessions = []
try:
for filename in os.listdir(self.session_dir):
if filename.endswith(".json"):
filepath = os.path.join(self.session_dir, filename)
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
sessions.append({
"session_id": data.get("session_id", filename[:-5]),
"agent_name": data.get("agent_name"),
"created_at": data.get("created_at"),
"updated_at": data.get("updated_at"),
"message_count": len(data.get("messages", [])),
})
except (json.JSONDecodeError, IOError):
continue
except (IOError, OSError):
pass
# Sort by updated_at descending
sessions.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
return sessions[:limit]
def session_exists(self, session_id: str) -> bool:
"""Check if a session exists."""
filepath = self._get_session_path(session_id)
return os.path.exists(filepath)
def invalidate_cache(self, session_id: Optional[str] = None) -> None:
"""Invalidate cache for a session or all sessions."""
with self._lock:
if session_id:
self._cache.pop(session_id, None)
else:
self._cache.clear()
# Global session store instance (lazy initialized)
_default_store: Optional[DefaultSessionStore] = None
_store_lock = threading.Lock()
def get_default_session_store() -> DefaultSessionStore:
"""Get the global default session store instance."""
global _default_store
if _default_store is None:
with _store_lock:
if _default_store is None:
_default_store = DefaultSessionStore()
return _default_store
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "praisonaiagents"
version = "0.6.0"
version = "0.6.2"
description = "Praison AI agents for completing complex tasks with Self Reflection Agents"
readme = "README.md"
requires-python = ">=3.10"
@@ -0,0 +1 @@
# Session module tests
@@ -0,0 +1,404 @@
"""
TDD Tests for Session Store.
Tests for DefaultSessionStore with JSON-based persistence.
"""
import json
import os
import tempfile
import threading
import time
import pytest
from concurrent.futures import ThreadPoolExecutor
from praisonaiagents.session.store import (
DefaultSessionStore,
SessionMessage,
SessionData,
FileLock,
DEFAULT_MAX_MESSAGES,
)
class TestSessionMessage:
"""Tests for SessionMessage dataclass."""
def test_create_message(self):
"""Test creating a session message."""
msg = SessionMessage(role="user", content="Hello")
assert msg.role == "user"
assert msg.content == "Hello"
assert msg.timestamp > 0
assert msg.metadata == {}
def test_message_to_dict(self):
"""Test converting message to dict."""
msg = SessionMessage(role="assistant", content="Hi there!")
d = msg.to_dict()
assert d["role"] == "assistant"
assert d["content"] == "Hi there!"
assert "timestamp" in d
assert "metadata" in d
def test_message_from_dict(self):
"""Test creating message from dict."""
d = {"role": "user", "content": "Test", "timestamp": 123.0, "metadata": {"key": "value"}}
msg = SessionMessage.from_dict(d)
assert msg.role == "user"
assert msg.content == "Test"
assert msg.timestamp == 123.0
assert msg.metadata == {"key": "value"}
class TestSessionData:
"""Tests for SessionData dataclass."""
def test_create_session(self):
"""Test creating session data."""
session = SessionData(session_id="test-123")
assert session.session_id == "test-123"
assert session.messages == []
assert session.created_at is not None
assert session.updated_at is not None
def test_session_to_dict(self):
"""Test converting session to dict."""
session = SessionData(session_id="test-123", agent_name="Assistant")
session.messages.append(SessionMessage(role="user", content="Hello"))
d = session.to_dict()
assert d["session_id"] == "test-123"
assert d["agent_name"] == "Assistant"
assert len(d["messages"]) == 1
def test_session_from_dict(self):
"""Test creating session from dict."""
d = {
"session_id": "test-456",
"messages": [{"role": "user", "content": "Hi"}],
"agent_name": "Bot",
}
session = SessionData.from_dict(d)
assert session.session_id == "test-456"
assert session.agent_name == "Bot"
assert len(session.messages) == 1
def test_get_chat_history(self):
"""Test getting chat history in LLM format."""
session = SessionData(session_id="test")
session.messages.append(SessionMessage(role="user", content="Hello"))
session.messages.append(SessionMessage(role="assistant", content="Hi!"))
history = session.get_chat_history()
assert len(history) == 2
assert history[0] == {"role": "user", "content": "Hello"}
assert history[1] == {"role": "assistant", "content": "Hi!"}
def test_get_chat_history_with_limit(self):
"""Test getting limited chat history."""
session = SessionData(session_id="test")
for i in range(10):
session.messages.append(SessionMessage(role="user", content=f"Message {i}"))
history = session.get_chat_history(max_messages=3)
assert len(history) == 3
assert history[0]["content"] == "Message 7"
assert history[2]["content"] == "Message 9"
class TestFileLock:
"""Tests for FileLock."""
def test_acquire_release(self):
"""Test basic lock acquire and release."""
with tempfile.TemporaryDirectory() as tmpdir:
filepath = os.path.join(tmpdir, "test.json")
lock = FileLock(filepath, timeout=1.0)
assert lock.acquire()
lock.release()
def test_context_manager(self):
"""Test lock as context manager."""
with tempfile.TemporaryDirectory() as tmpdir:
filepath = os.path.join(tmpdir, "test.json")
with FileLock(filepath, timeout=1.0):
# Lock is held
pass
# Lock is released
def test_concurrent_locks(self):
"""Test that concurrent locks are serialized."""
with tempfile.TemporaryDirectory() as tmpdir:
filepath = os.path.join(tmpdir, "test.json")
results = []
def worker(worker_id):
with FileLock(filepath, timeout=5.0):
results.append(f"start-{worker_id}")
time.sleep(0.1)
results.append(f"end-{worker_id}")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
# Check that starts and ends are paired (no interleaving)
for i in range(3):
start_idx = results.index(f"start-{i}")
end_idx = results.index(f"end-{i}")
# No other start should be between this start and end
for j in range(3):
if i != j:
other_start = results.index(f"start-{j}")
if start_idx < other_start < end_idx:
pytest.fail(f"Lock interleaving detected: {results}")
class TestDefaultSessionStore:
"""Tests for DefaultSessionStore."""
@pytest.fixture
def temp_store(self):
"""Create a temporary session store."""
with tempfile.TemporaryDirectory() as tmpdir:
store = DefaultSessionStore(session_dir=tmpdir)
yield store
def test_add_message(self, temp_store):
"""Test adding a message."""
result = temp_store.add_message("session-1", "user", "Hello")
assert result is True
history = temp_store.get_chat_history("session-1")
assert len(history) == 1
assert history[0]["role"] == "user"
assert history[0]["content"] == "Hello"
def test_add_user_message(self, temp_store):
"""Test adding a user message."""
temp_store.add_user_message("session-1", "Hello")
history = temp_store.get_chat_history("session-1")
assert history[0]["role"] == "user"
def test_add_assistant_message(self, temp_store):
"""Test adding an assistant message."""
temp_store.add_assistant_message("session-1", "Hi there!")
history = temp_store.get_chat_history("session-1")
assert history[0]["role"] == "assistant"
def test_persistence_across_instances(self, temp_store):
"""Test that sessions persist across store instances."""
session_dir = temp_store.session_dir
# Add messages with first store
temp_store.add_user_message("session-1", "Hello")
temp_store.add_assistant_message("session-1", "Hi!")
# Create new store instance
store2 = DefaultSessionStore(session_dir=session_dir)
# Verify messages are restored
history = store2.get_chat_history("session-1")
assert len(history) == 2
assert history[0]["content"] == "Hello"
assert history[1]["content"] == "Hi!"
def test_session_file_created(self, temp_store):
"""Test that session file is created on disk."""
temp_store.add_user_message("test-session", "Hello")
filepath = os.path.join(temp_store.session_dir, "test-session.json")
assert os.path.exists(filepath)
with open(filepath, "r") as f:
data = json.load(f)
assert data["session_id"] == "test-session"
assert len(data["messages"]) == 1
def test_max_messages_limit(self):
"""Test that messages are trimmed to max limit."""
with tempfile.TemporaryDirectory() as tmpdir:
store = DefaultSessionStore(session_dir=tmpdir, max_messages=5)
for i in range(10):
store.add_user_message("session-1", f"Message {i}")
history = store.get_chat_history("session-1")
assert len(history) == 5
assert history[0]["content"] == "Message 5"
assert history[4]["content"] == "Message 9"
def test_clear_session(self, temp_store):
"""Test clearing a session."""
temp_store.add_user_message("session-1", "Hello")
temp_store.add_assistant_message("session-1", "Hi!")
temp_store.clear_session("session-1")
history = temp_store.get_chat_history("session-1")
assert len(history) == 0
def test_delete_session(self, temp_store):
"""Test deleting a session."""
temp_store.add_user_message("session-1", "Hello")
filepath = os.path.join(temp_store.session_dir, "session-1.json")
assert os.path.exists(filepath)
temp_store.delete_session("session-1")
assert not os.path.exists(filepath)
def test_list_sessions(self, temp_store):
"""Test listing sessions."""
temp_store.add_user_message("session-1", "Hello")
temp_store.add_user_message("session-2", "Hi")
temp_store.add_user_message("session-3", "Hey")
sessions = temp_store.list_sessions()
assert len(sessions) == 3
session_ids = [s["session_id"] for s in sessions]
assert "session-1" in session_ids
assert "session-2" in session_ids
assert "session-3" in session_ids
def test_session_exists(self, temp_store):
"""Test checking if session exists."""
assert not temp_store.session_exists("session-1")
temp_store.add_user_message("session-1", "Hello")
assert temp_store.session_exists("session-1")
def test_set_agent_info(self, temp_store):
"""Test setting agent info."""
temp_store.add_user_message("session-1", "Hello")
temp_store.set_agent_info("session-1", agent_name="TestBot", user_id="user-123")
session = temp_store.get_session("session-1")
assert session.agent_name == "TestBot"
assert session.user_id == "user-123"
def test_concurrent_writes(self, temp_store):
"""Test concurrent writes to same session."""
def writer(msg_id):
temp_store.add_user_message("session-1", f"Message {msg_id}")
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(writer, i) for i in range(10)]
for f in futures:
f.result()
history = temp_store.get_chat_history("session-1")
assert len(history) == 10
def test_sanitize_session_id(self, temp_store):
"""Test that session IDs are sanitized for filesystem."""
temp_store.add_user_message("session/with/slashes", "Hello")
temp_store.add_user_message("session:with:colons", "Hi")
# Should not raise errors
history1 = temp_store.get_chat_history("session/with/slashes")
history2 = temp_store.get_chat_history("session:with:colons")
assert len(history1) == 1
assert len(history2) == 1
def test_empty_session_returns_empty_history(self, temp_store):
"""Test that non-existent session returns empty history."""
history = temp_store.get_chat_history("nonexistent")
assert history == []
def test_invalidate_cache(self, temp_store):
"""Test cache invalidation."""
temp_store.add_user_message("session-1", "Hello")
# Modify file directly
filepath = os.path.join(temp_store.session_dir, "session-1.json")
with open(filepath, "r") as f:
data = json.load(f)
data["messages"].append({"role": "user", "content": "Direct edit", "timestamp": time.time(), "metadata": {}})
with open(filepath, "w") as f:
json.dump(data, f)
# Without invalidation, cache returns old data
history = temp_store.get_chat_history("session-1")
assert len(history) == 1 # Cached
# After invalidation, new data is loaded
temp_store.invalidate_cache("session-1")
history = temp_store.get_chat_history("session-1")
assert len(history) == 2
class TestAgentSessionIntegration:
"""Tests for Agent integration with session store."""
def test_agent_session_persistence(self):
"""Test that Agent persists session with session_id."""
from praisonaiagents import Agent
with tempfile.TemporaryDirectory() as tmpdir:
# Patch the default session directory
import praisonaiagents.session.store as store_module
original_dir = store_module.DEFAULT_SESSION_DIR
store_module.DEFAULT_SESSION_DIR = tmpdir
# Reset global store
store_module._default_store = None
try:
# Create agent with session_id
agent = Agent(
name="TestAgent",
instructions="You are a test agent.",
session_id="test-session-123",
verbose=False,
)
# Verify session store is initialized after first chat
# (We can't actually call chat without API key, so we test init)
agent._init_session_store()
assert agent._session_store is not None
assert agent._session_store_initialized is True
finally:
store_module.DEFAULT_SESSION_DIR = original_dir
store_module._default_store = None
def test_agent_no_session_id_no_persistence(self):
"""Test that Agent without session_id doesn't use session store."""
from praisonaiagents import Agent
agent = Agent(
name="TestAgent",
instructions="You are a test agent.",
verbose=False,
)
agent._init_session_store()
assert agent._session_store is None
assert agent._session_store_initialized is True
def test_agent_with_db_no_session_store(self):
"""Test that Agent with DB adapter doesn't use session store."""
from praisonaiagents import Agent
# Mock DB adapter
class MockDbAdapter:
def on_agent_start(self, **kwargs):
return []
agent = Agent(
name="TestAgent",
instructions="You are a test agent.",
session_id="test-session",
db=MockDbAdapter(),
verbose=False,
)
agent._init_session_store()
# Session store should not be used when DB is provided
assert agent._session_store is None
+1 -1
View File
@@ -2422,7 +2422,7 @@ wheels = [
[[package]]
name = "praisonaiagents"
version = "0.6.0"
version = "0.6.2"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
+2 -2
View File
@@ -3,8 +3,8 @@ class Praisonai < Formula
desc "AI tools for various AI applications"
homepage "https://github.com/MervinPraison/PraisonAI"
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v3.0.0.tar.gz"
sha256 `curl -sL https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v3.0.0.tar.gz | shasum -a 256`.split.first
url "https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v3.1.2.tar.gz"
sha256 `curl -sL https://github.com/MervinPraison/PraisonAI/archive/refs/tags/v3.1.2.tar.gz | shasum -a 256`.split.first
license "MIT"
depends_on "[email protected]"
+442
View File
@@ -0,0 +1,442 @@
"""
Safe Edit Pipeline for ACP.
Implements a propose → diff → approve → apply workflow for file edits.
Ensures no silent file writes - all changes require explicit approval.
"""
import difflib
import logging
import uuid
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
class EditStatus(str, Enum):
"""Status of an edit proposal."""
PENDING = "pending"
APPROVED = "approved"
REJECTED = "rejected"
APPLIED = "applied"
FAILED = "failed"
@dataclass
class EditProposal:
"""
A proposed file edit with diff preview.
Represents a change that has been proposed but not yet applied.
"""
proposal_id: str
file_path: Path
original_content: str
proposed_content: str
description: str
diff_lines: List[str] = field(default_factory=list)
status: EditStatus = EditStatus.PENDING
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
approved_at: Optional[str] = None
applied_at: Optional[str] = None
error: Optional[str] = None
def __post_init__(self):
"""Generate diff on creation."""
if not self.diff_lines:
self.diff_lines = self._generate_diff()
def _generate_diff(self) -> List[str]:
"""Generate unified diff between original and proposed content."""
original_lines = self.original_content.splitlines(keepends=True)
proposed_lines = self.proposed_content.splitlines(keepends=True)
diff = difflib.unified_diff(
original_lines,
proposed_lines,
fromfile=f"a/{self.file_path.name}",
tofile=f"b/{self.file_path.name}",
lineterm=""
)
return list(diff)
@property
def diff_text(self) -> str:
"""Get diff as a single string."""
return "\n".join(self.diff_lines)
@property
def is_new_file(self) -> bool:
"""Check if this is a new file creation."""
return not self.original_content
@property
def is_deletion(self) -> bool:
"""Check if this is a file deletion."""
return not self.proposed_content and bool(self.original_content)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"proposal_id": self.proposal_id,
"file_path": str(self.file_path),
"description": self.description,
"status": self.status.value,
"is_new_file": self.is_new_file,
"is_deletion": self.is_deletion,
"diff": self.diff_text,
"created_at": self.created_at,
"approved_at": self.approved_at,
"applied_at": self.applied_at,
"error": self.error,
}
class SafeEditPipeline:
"""
Safe file editing with diff preview and approval workflow.
Workflow:
1. propose_edit() - Create an edit proposal with diff
2. show_diff() - Display the diff to user
3. approve() / reject() - User decision
4. apply_edit() - Apply approved edit
ACP remains read-only by default. Writes only happen after explicit approval.
"""
def __init__(
self,
workspace: Optional[Path] = None,
auto_approve: bool = False,
approval_callback: Optional[callable] = None,
):
"""
Initialize safe edit pipeline.
Args:
workspace: Root workspace directory for path validation
auto_approve: If True, auto-approve all edits (dangerous, for testing only)
approval_callback: Optional callback for approval (async or sync)
"""
self.workspace = Path(workspace) if workspace else Path.cwd()
self.auto_approve = auto_approve
self.approval_callback = approval_callback
self._proposals: Dict[str, EditProposal] = {}
def _validate_path(self, file_path: Path) -> Path:
"""
Validate and resolve file path.
Ensures path is within workspace and resolves to absolute path.
"""
if not file_path.is_absolute():
file_path = self.workspace / file_path
resolved = file_path.resolve()
# Security check: ensure path is within workspace
try:
resolved.relative_to(self.workspace.resolve())
except ValueError:
raise ValueError(f"Path {file_path} is outside workspace {self.workspace}")
return resolved
def propose_edit(
self,
file_path: Path,
new_content: str,
description: str,
) -> EditProposal:
"""
Create an edit proposal with diff preview.
Args:
file_path: Path to file to edit
new_content: Proposed new content
description: Human-readable description of the change
Returns:
EditProposal with diff
"""
resolved_path = self._validate_path(Path(file_path))
# Read original content if file exists
original_content = ""
if resolved_path.exists():
try:
original_content = resolved_path.read_text()
except Exception as e:
logger.warning(f"Could not read {resolved_path}: {e}")
# Create proposal
proposal = EditProposal(
proposal_id=str(uuid.uuid4())[:8],
file_path=resolved_path,
original_content=original_content,
proposed_content=new_content,
description=description,
)
self._proposals[proposal.proposal_id] = proposal
logger.info(f"Created edit proposal {proposal.proposal_id} for {file_path}")
return proposal
def propose_create(
self,
file_path: Path,
content: str,
description: str,
) -> EditProposal:
"""
Create a proposal for a new file.
Args:
file_path: Path for new file
content: File content
description: Description of the new file
Returns:
EditProposal for file creation
"""
return self.propose_edit(file_path, content, description)
def propose_delete(
self,
file_path: Path,
description: str,
) -> EditProposal:
"""
Create a proposal to delete a file.
Args:
file_path: Path to file to delete
description: Reason for deletion
Returns:
EditProposal for file deletion
"""
return self.propose_edit(file_path, "", description)
def get_proposal(self, proposal_id: str) -> Optional[EditProposal]:
"""Get a proposal by ID."""
return self._proposals.get(proposal_id)
def list_proposals(self, status: Optional[EditStatus] = None) -> List[EditProposal]:
"""
List all proposals, optionally filtered by status.
Args:
status: Optional status filter
Returns:
List of proposals
"""
proposals = list(self._proposals.values())
if status:
proposals = [p for p in proposals if p.status == status]
return proposals
def approve(self, proposal_id: str) -> bool:
"""
Approve an edit proposal.
Args:
proposal_id: ID of proposal to approve
Returns:
True if approved, False if not found or already processed
"""
proposal = self._proposals.get(proposal_id)
if not proposal:
logger.warning(f"Proposal {proposal_id} not found")
return False
if proposal.status != EditStatus.PENDING:
logger.warning(f"Proposal {proposal_id} is not pending (status: {proposal.status})")
return False
proposal.status = EditStatus.APPROVED
proposal.approved_at = datetime.now().isoformat()
logger.info(f"Approved proposal {proposal_id}")
return True
def reject(self, proposal_id: str, reason: Optional[str] = None) -> bool:
"""
Reject an edit proposal.
Args:
proposal_id: ID of proposal to reject
reason: Optional rejection reason
Returns:
True if rejected, False if not found or already processed
"""
proposal = self._proposals.get(proposal_id)
if not proposal:
logger.warning(f"Proposal {proposal_id} not found")
return False
if proposal.status != EditStatus.PENDING:
logger.warning(f"Proposal {proposal_id} is not pending (status: {proposal.status})")
return False
proposal.status = EditStatus.REJECTED
proposal.error = reason
logger.info(f"Rejected proposal {proposal_id}: {reason}")
return True
def apply_edit(self, proposal_id: str) -> bool:
"""
Apply an approved edit.
Args:
proposal_id: ID of approved proposal to apply
Returns:
True if applied successfully, False otherwise
"""
proposal = self._proposals.get(proposal_id)
if not proposal:
logger.error(f"Proposal {proposal_id} not found")
return False
if proposal.status != EditStatus.APPROVED:
logger.error(f"Proposal {proposal_id} is not approved (status: {proposal.status})")
return False
try:
if proposal.is_deletion:
# Delete file
if proposal.file_path.exists():
proposal.file_path.unlink()
logger.info(f"Deleted {proposal.file_path}")
else:
# Create parent directories if needed
proposal.file_path.parent.mkdir(parents=True, exist_ok=True)
# Write new content
proposal.file_path.write_text(proposal.proposed_content)
logger.info(f"Applied edit to {proposal.file_path}")
proposal.status = EditStatus.APPLIED
proposal.applied_at = datetime.now().isoformat()
return True
except Exception as e:
logger.error(f"Failed to apply proposal {proposal_id}: {e}")
proposal.status = EditStatus.FAILED
proposal.error = str(e)
return False
def propose_and_apply(
self,
file_path: Path,
new_content: str,
description: str,
) -> EditProposal:
"""
Convenience method: propose, auto-approve if enabled, and apply.
Only applies if auto_approve is True or approval_callback returns True.
Args:
file_path: Path to file
new_content: New content
description: Description
Returns:
EditProposal (may be pending, approved, or applied)
"""
proposal = self.propose_edit(file_path, new_content, description)
if self.auto_approve:
self.approve(proposal.proposal_id)
self.apply_edit(proposal.proposal_id)
elif self.approval_callback:
try:
if self.approval_callback(proposal):
self.approve(proposal.proposal_id)
self.apply_edit(proposal.proposal_id)
else:
self.reject(proposal.proposal_id, "Rejected by callback")
except Exception as e:
logger.error(f"Approval callback failed: {e}")
proposal.error = str(e)
return proposal
def format_diff_for_display(self, proposal: EditProposal) -> str:
"""
Format diff for terminal display with colors.
Args:
proposal: Edit proposal
Returns:
Formatted diff string with ANSI colors
"""
lines = []
lines.append(f"📝 Edit Proposal: {proposal.proposal_id}")
lines.append(f" File: {proposal.file_path}")
lines.append(f" Description: {proposal.description}")
lines.append(f" Status: {proposal.status.value}")
lines.append("")
if proposal.is_new_file:
lines.append(" [NEW FILE]")
elif proposal.is_deletion:
lines.append(" [DELETE FILE]")
lines.append(" --- Diff ---")
for line in proposal.diff_lines:
if line.startswith("+") and not line.startswith("+++"):
lines.append(f" \033[32m{line}\033[0m") # Green for additions
elif line.startswith("-") and not line.startswith("---"):
lines.append(f" \033[31m{line}\033[0m") # Red for deletions
elif line.startswith("@@"):
lines.append(f" \033[36m{line}\033[0m") # Cyan for line numbers
else:
lines.append(f" {line}")
return "\n".join(lines)
def clear_proposals(self, status: Optional[EditStatus] = None) -> int:
"""
Clear proposals, optionally filtered by status.
Args:
status: Optional status filter (None = clear all)
Returns:
Number of proposals cleared
"""
if status is None:
count = len(self._proposals)
self._proposals.clear()
else:
to_remove = [pid for pid, p in self._proposals.items() if p.status == status]
for pid in to_remove:
del self._proposals[pid]
count = len(to_remove)
logger.info(f"Cleared {count} proposals")
return count
# Global pipeline instance for ACP
_safe_edit_pipeline: Optional[SafeEditPipeline] = None
def get_safe_edit_pipeline(workspace: Optional[Path] = None) -> SafeEditPipeline:
"""Get or create the global safe edit pipeline."""
global _safe_edit_pipeline
if _safe_edit_pipeline is None:
_safe_edit_pipeline = SafeEditPipeline(workspace=workspace)
return _safe_edit_pipeline
+60 -2
View File
@@ -160,7 +160,7 @@ def get_output_controller() -> OutputController:
# Import and register command groups
def register_commands():
"""Register all command groups."""
# Import command modules
# Import command modules - Core commands
from .commands.config import app as config_app
from .commands.traces import app as traces_app
from .commands.environment import app as env_app
@@ -177,12 +177,41 @@ def register_commands():
from .commands.schedule import app as schedule_app
from .commands.run import app as run_app
from .commands.profile import app as profile_app
from .commands.benchmark import app as benchmark_app
# Import new command modules - Previously legacy-only commands
from .commands.chat import app as chat_app
from .commands.code import app as code_app
from .commands.call import app as call_app
from .commands.realtime import app as realtime_app
from .commands.train import app as train_app
from .commands.ui import app as ui_app
from .commands.context import app as context_app
from .commands.research import app as research_app
from .commands.memory import app as memory_app
from .commands.workflow import app as workflow_app
from .commands.tools import app as tools_app
from .commands.knowledge import app as knowledge_app
from .commands.deploy import app as deploy_app
from .commands.agents import app as agents_app
from .commands.skills import app as skills_app
from .commands.eval import app as eval_app
from .commands.templates import app as templates_app
from .commands.recipe import app as recipe_app
from .commands.todo import app as todo_app
from .commands.docs import app as docs_app
from .commands.commit import app as commit_app
from .commands.hooks import app as hooks_app
from .commands.rules import app as rules_app
from .commands.registry import app as registry_app
from .commands.package import app as package_app
from .commands.endpoints import app as endpoints_app
# Import TUI and queue commands
from .features.tui.debug import create_debug_app as create_tui_debug_app
from .features.tui.cli import create_queue_app
# Register sub-apps
# Register sub-apps - Core commands
app.add_typer(config_app, name="config", help="Configuration management")
app.add_typer(traces_app, name="traces", help="Trace collection management")
app.add_typer(env_app, name="env", help="Environment and diagnostics")
@@ -199,6 +228,35 @@ def register_commands():
app.add_typer(schedule_app, name="schedule", help="Scheduler management")
app.add_typer(run_app, name="run", help="Run agents")
app.add_typer(profile_app, name="profile", help="Performance profiling and diagnostics")
app.add_typer(benchmark_app, name="benchmark", help="Comprehensive performance benchmarking")
# Register sub-apps - Previously legacy-only commands (now visible in --help)
app.add_typer(chat_app, name="chat", help="Interactive chat mode")
app.add_typer(code_app, name="code", help="Code assistant mode")
app.add_typer(call_app, name="call", help="Voice/call interaction mode")
app.add_typer(realtime_app, name="realtime", help="Realtime interaction mode")
app.add_typer(train_app, name="train", help="Model training and fine-tuning")
app.add_typer(ui_app, name="ui", help="Web UI management")
app.add_typer(context_app, name="context", help="Context management")
app.add_typer(research_app, name="research", help="Research and analysis")
app.add_typer(memory_app, name="memory", help="Memory management")
app.add_typer(workflow_app, name="workflow", help="Workflow management")
app.add_typer(tools_app, name="tools", help="Tool management")
app.add_typer(knowledge_app, name="knowledge", help="Knowledge base management")
app.add_typer(deploy_app, name="deploy", help="Deployment management")
app.add_typer(agents_app, name="agents", help="Agent management")
app.add_typer(skills_app, name="skills", help="Skill management")
app.add_typer(eval_app, name="eval", help="Evaluation and testing")
app.add_typer(templates_app, name="templates", help="Template management")
app.add_typer(recipe_app, name="recipe", help="Recipe management")
app.add_typer(todo_app, name="todo", help="Todo/task management")
app.add_typer(docs_app, name="docs", help="Documentation management")
app.add_typer(commit_app, name="commit", help="AI-assisted git commits")
app.add_typer(hooks_app, name="hooks", help="Hook management")
app.add_typer(rules_app, name="rules", help="Rules management")
app.add_typer(registry_app, name="registry", help="Registry management")
app.add_typer(package_app, name="package", help="Package management")
app.add_typer(endpoints_app, name="endpoints", help="API endpoint management")
# Register TUI and queue commands
tui_app = create_tui_debug_app()
@@ -0,0 +1,80 @@
"""
Agents command group for PraisonAI CLI.
Provides agent management commands.
"""
import typer
app = typer.Typer(help="Agent management")
@app.command("list")
def agents_list(
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed info"),
):
"""List available agents."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['agents', 'list']
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("create")
def agents_create(
name: str = typer.Argument(..., help="Agent name"),
template: str = typer.Option(None, "--template", "-t", help="Template to use"),
):
"""Create a new agent."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['agents', 'create', name]
if template:
argv.extend(['--template', template])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("info")
def agents_info(
name: str = typer.Argument(..., help="Agent name"),
):
"""Show agent information."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['agents', 'info', name]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,286 @@
"""
Benchmark command group for PraisonAI CLI.
Provides comprehensive performance benchmarking across all execution paths.
"""
from typing import Optional
import typer
app = typer.Typer(help="Comprehensive performance benchmarking")
@app.command("profile")
def benchmark_profile(
prompt: str = typer.Argument("Hi", help="Prompt to benchmark"),
iterations: int = typer.Option(3, "--iterations", "-n", help="Number of iterations per path"),
output_format: str = typer.Option("text", "--format", "-f", help="Output format: text or json"),
output_file: Optional[str] = typer.Option(None, "--output", "-o", help="Save results to file"),
deep: bool = typer.Option(False, "--deep", help="Enable deep cProfile profiling (per-function timing, call graphs)"),
limit: int = typer.Option(30, "--limit", "-l", help="Top N functions to show in deep profile"),
):
"""
Run full benchmark suite across all execution paths.
Benchmarks:
- OpenAI SDK (baseline)
- PraisonAI Agent
- PraisonAI CLI
- PraisonAI CLI with profiling
- PraisonAI Workflow (single agent)
- PraisonAI Workflow (multi-agent)
- PraisonAI via LiteLLM
- LiteLLM standalone
With --deep flag, includes:
- Per-function timing (cProfile stats)
- Self time vs cumulative time
- Call counts per function
- Caller/callee relationships
- Module breakdown by category
- Call graph data
Examples:
praisonai benchmark profile "What is 2+2?"
praisonai benchmark profile "Hi" --iterations 5
praisonai benchmark profile "Hi" --deep --limit 50
praisonai benchmark profile "Hi" --deep --format json --output results.json
"""
try:
from ..features.benchmark import BenchmarkHandler
except ImportError as e:
typer.echo(f"Error: Benchmark module not available: {e}", err=True)
raise typer.Exit(1)
if deep:
typer.echo("⚠️ Deep profiling enabled - this adds overhead to measurements", err=True)
handler = BenchmarkHandler()
report = handler.run_full_benchmark(
prompt=prompt,
iterations=iterations,
verbose=True,
deep=deep,
limit=limit
)
if output_format == "json":
import json
output = json.dumps(report.to_dict(), indent=2)
if output_file:
with open(output_file, "w") as f:
f.write(output)
typer.echo(f"Results saved to {output_file}")
else:
typer.echo(output)
else:
handler.print_report(report, deep=deep, limit=limit)
if output_file:
import json
with open(output_file, "w") as f:
f.write(json.dumps(report.to_dict(), indent=2))
typer.echo(f"\nJSON results saved to {output_file}")
@app.command("compare")
def benchmark_compare(
prompt: str = typer.Argument("Hi", help="Prompt to benchmark"),
iterations: int = typer.Option(2, "--iterations", "-n", help="Number of iterations"),
):
"""
Quick comparison of key execution paths.
Compares OpenAI SDK, PraisonAI Agent, PraisonAI CLI, and LiteLLM.
Examples:
praisonai benchmark compare "Hi"
praisonai benchmark compare "What is 2+2?" --iterations 3
"""
try:
from ..features.benchmark import BenchmarkHandler
except ImportError as e:
typer.echo(f"Error: Benchmark module not available: {e}", err=True)
raise typer.Exit(1)
handler = BenchmarkHandler()
report = handler.run_full_benchmark(
prompt=prompt,
iterations=iterations,
paths=["openai_sdk", "praisonai_agent", "praisonai_cli", "litellm_standalone"],
verbose=True
)
typer.echo("\n" + handler.create_comparison_table(report))
@app.command("sdk")
def benchmark_sdk(
prompt: str = typer.Argument("Hi", help="Prompt to benchmark"),
iterations: int = typer.Option(3, "--iterations", "-n", help="Number of iterations"),
output_format: str = typer.Option("text", "--format", "-f", help="Output format: text or json"),
):
"""
Benchmark OpenAI SDK only (baseline).
Examples:
praisonai benchmark sdk "Hi"
praisonai benchmark sdk "What is 2+2?" --iterations 5
"""
try:
from ..features.benchmark import BenchmarkHandler
except ImportError as e:
typer.echo(f"Error: Benchmark module not available: {e}", err=True)
raise typer.Exit(1)
handler = BenchmarkHandler()
report = handler.run_full_benchmark(prompt=prompt, iterations=iterations, paths=["openai_sdk"], verbose=True)
if output_format == "json":
import json
typer.echo(json.dumps(report.to_dict(), indent=2))
else:
handler.print_report(report)
@app.command("agent")
def benchmark_agent(
prompt: str = typer.Argument("Hi", help="Prompt to benchmark"),
iterations: int = typer.Option(3, "--iterations", "-n", help="Number of iterations"),
output_format: str = typer.Option("text", "--format", "-f", help="Output format: text or json"),
):
"""
Benchmark PraisonAI Agent vs SDK baseline.
Examples:
praisonai benchmark agent "Hi"
praisonai benchmark agent "What is 2+2?" --iterations 5
"""
try:
from ..features.benchmark import BenchmarkHandler
except ImportError as e:
typer.echo(f"Error: Benchmark module not available: {e}", err=True)
raise typer.Exit(1)
handler = BenchmarkHandler()
report = handler.run_full_benchmark(
prompt=prompt,
iterations=iterations,
paths=["openai_sdk", "praisonai_agent"],
verbose=True
)
if output_format == "json":
import json
typer.echo(json.dumps(report.to_dict(), indent=2))
else:
handler.print_report(report)
@app.command("cli")
def benchmark_cli(
prompt: str = typer.Argument("Hi", help="Prompt to benchmark"),
iterations: int = typer.Option(3, "--iterations", "-n", help="Number of iterations"),
output_format: str = typer.Option("text", "--format", "-f", help="Output format: text or json"),
):
"""
Benchmark PraisonAI CLI vs SDK baseline.
Examples:
praisonai benchmark cli "Hi"
praisonai benchmark cli "What is 2+2?" --iterations 5
"""
try:
from ..features.benchmark import BenchmarkHandler
except ImportError as e:
typer.echo(f"Error: Benchmark module not available: {e}", err=True)
raise typer.Exit(1)
handler = BenchmarkHandler()
report = handler.run_full_benchmark(
prompt=prompt,
iterations=iterations,
paths=["openai_sdk", "praisonai_cli", "praisonai_cli_profile"],
verbose=True
)
if output_format == "json":
import json
typer.echo(json.dumps(report.to_dict(), indent=2))
else:
handler.print_report(report)
@app.command("workflow")
def benchmark_workflow(
prompt: str = typer.Argument("Hi", help="Prompt to benchmark"),
iterations: int = typer.Option(3, "--iterations", "-n", help="Number of iterations"),
output_format: str = typer.Option("text", "--format", "-f", help="Output format: text or json"),
):
"""
Benchmark PraisonAI Workflow (single and multi-agent) vs SDK baseline.
Examples:
praisonai benchmark workflow "Hi"
praisonai benchmark workflow "What is 2+2?" --iterations 5
"""
try:
from ..features.benchmark import BenchmarkHandler
except ImportError as e:
typer.echo(f"Error: Benchmark module not available: {e}", err=True)
raise typer.Exit(1)
handler = BenchmarkHandler()
report = handler.run_full_benchmark(
prompt=prompt,
iterations=iterations,
paths=["openai_sdk", "praisonai_workflow_single", "praisonai_workflow_multi"],
verbose=True
)
if output_format == "json":
import json
typer.echo(json.dumps(report.to_dict(), indent=2))
else:
handler.print_report(report)
@app.command("litellm")
def benchmark_litellm(
prompt: str = typer.Argument("Hi", help="Prompt to benchmark"),
iterations: int = typer.Option(3, "--iterations", "-n", help="Number of iterations"),
output_format: str = typer.Option("text", "--format", "-f", help="Output format: text or json"),
):
"""
Benchmark LiteLLM paths vs SDK baseline.
Examples:
praisonai benchmark litellm "Hi"
praisonai benchmark litellm "What is 2+2?" --iterations 5
"""
try:
from ..features.benchmark import BenchmarkHandler
except ImportError as e:
typer.echo(f"Error: Benchmark module not available: {e}", err=True)
raise typer.Exit(1)
handler = BenchmarkHandler()
report = handler.run_full_benchmark(
prompt=prompt,
iterations=iterations,
paths=["openai_sdk", "praisonai_litellm", "litellm_standalone"],
verbose=True
)
if output_format == "json":
import json
typer.echo(json.dumps(report.to_dict(), indent=2))
else:
handler.print_report(report)
@app.callback(invoke_without_command=True)
def benchmark_callback(ctx: typer.Context):
"""Show benchmark help if no subcommand."""
if ctx.invoked_subcommand is None:
typer.echo(ctx.get_help())
@@ -0,0 +1,45 @@
"""
Call command group for PraisonAI CLI.
Provides voice/call interaction commands.
"""
from typing import Optional
import typer
app = typer.Typer(help="Voice/call interaction mode")
@app.callback(invoke_without_command=True)
def call_main(
ctx: typer.Context,
model: Optional[str] = typer.Option(None, "--model", "-m", help="LLM model to use"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
):
"""
Start voice/call interaction mode.
Examples:
praisonai call
praisonai call --model gpt-4o
"""
from praisonai.cli.main import PraisonAI
import sys
argv = ['call']
if model:
argv.extend(['--model', model])
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,60 @@
"""
Chat command group for PraisonAI CLI.
Provides interactive chat commands.
"""
from typing import Optional
import typer
app = typer.Typer(help="Interactive chat mode")
@app.callback(invoke_without_command=True)
def chat_main(
ctx: typer.Context,
prompt: Optional[str] = typer.Argument(None, help="Initial prompt for chat"),
model: Optional[str] = typer.Option(None, "--model", "-m", help="LLM model to use"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
memory: bool = typer.Option(False, "--memory", help="Enable memory"),
tools: Optional[str] = typer.Option(None, "--tools", "-t", help="Tools file path"),
user_id: Optional[str] = typer.Option(None, "--user-id", help="User ID for memory isolation"),
session_id: Optional[str] = typer.Option(None, "--session", "-s", help="Session ID to resume"),
):
"""
Start interactive chat mode.
Examples:
praisonai chat
praisonai chat "Hello, how are you?"
praisonai chat --model gpt-4o --memory
"""
from praisonai.cli.main import PraisonAI
import sys
# Build args for legacy handler
argv = ['chat']
if prompt:
argv.append(prompt)
if model:
argv.extend(['--model', model])
if verbose:
argv.append('--verbose')
if memory:
argv.append('--memory')
if tools:
argv.extend(['--tools', tools])
if user_id:
argv.extend(['--user-id', user_id])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,53 @@
"""
Code command group for PraisonAI CLI.
Provides code assistant commands.
"""
from typing import Optional
import typer
app = typer.Typer(help="Code assistant mode")
@app.callback(invoke_without_command=True)
def code_main(
ctx: typer.Context,
prompt: Optional[str] = typer.Argument(None, help="Code task or question"),
model: Optional[str] = typer.Option(None, "--model", "-m", help="LLM model to use"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
tools: Optional[str] = typer.Option(None, "--tools", "-t", help="Tools file path"),
workspace: Optional[str] = typer.Option(None, "--workspace", "-w", help="Workspace directory"),
):
"""
Start code assistant mode.
Examples:
praisonai code
praisonai code "Refactor this function"
praisonai code --model gpt-4o --workspace ./src
"""
from praisonai.cli.main import PraisonAI
import sys
argv = ['code']
if prompt:
argv.append(prompt)
if model:
argv.extend(['--model', model])
if verbose:
argv.append('--verbose')
if tools:
argv.extend(['--tools', tools])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,47 @@
"""
Commit command group for PraisonAI CLI.
Provides git commit commands with AI assistance.
"""
import typer
app = typer.Typer(help="AI-assisted git commits")
@app.callback(invoke_without_command=True)
def commit_main(
ctx: typer.Context,
message: str = typer.Option(None, "--message", "-m", help="Commit message (auto-generated if not provided)"),
all_files: bool = typer.Option(False, "--all", "-a", help="Stage all changes"),
push: bool = typer.Option(False, "--push", "-p", help="Push after commit"),
):
"""
Create AI-assisted git commits.
Examples:
praisonai commit
praisonai commit -m "Fix bug"
praisonai commit --all --push
"""
from praisonai.cli.main import PraisonAI
import sys
argv = ['commit']
if message:
argv.extend(['--message', message])
if all_files:
argv.append('--all')
if push:
argv.append('--push')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,77 @@
"""
Context command group for PraisonAI CLI.
Provides context management commands.
"""
from typing import Optional
import typer
app = typer.Typer(help="Context management")
@app.command("show")
def context_show(
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
):
"""Show current context."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['context', 'show']
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("clear")
def context_clear():
"""Clear current context."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['context', 'clear']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("add")
def context_add(
content: str = typer.Argument(..., help="Content to add to context"),
):
"""Add content to context."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['context', 'add', content]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,109 @@
"""
Deploy command group for PraisonAI CLI.
Provides deployment commands.
"""
import typer
app = typer.Typer(help="Deployment management")
@app.command("docker")
def deploy_docker(
file: str = typer.Argument("agents.yaml", help="Agent file to deploy"),
tag: str = typer.Option(None, "--tag", "-t", help="Docker image tag"),
):
"""Deploy as Docker container."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['deploy', 'docker', file]
if tag:
argv.extend(['--tag', tag])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("aws")
def deploy_aws(
file: str = typer.Argument("agents.yaml", help="Agent file to deploy"),
region: str = typer.Option(None, "--region", "-r", help="AWS region"),
):
"""Deploy to AWS."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['deploy', 'aws', file]
if region:
argv.extend(['--region', region])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("gcp")
def deploy_gcp(
file: str = typer.Argument("agents.yaml", help="Agent file to deploy"),
project: str = typer.Option(None, "--project", "-p", help="GCP project"),
):
"""Deploy to Google Cloud."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['deploy', 'gcp', file]
if project:
argv.extend(['--project', project])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("azure")
def deploy_azure(
file: str = typer.Argument("agents.yaml", help="Agent file to deploy"),
resource_group: str = typer.Option(None, "--resource-group", "-g", help="Azure resource group"),
):
"""Deploy to Azure."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['deploy', 'azure', file]
if resource_group:
argv.extend(['--resource-group', resource_group])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,54 @@
"""
Docs command group for PraisonAI CLI.
Provides documentation commands.
"""
import typer
app = typer.Typer(help="Documentation management")
@app.command("generate")
def docs_generate(
source: str = typer.Argument(".", help="Source directory"),
output: str = typer.Option("docs", "--output", "-o", help="Output directory"),
):
"""Generate documentation."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['docs', 'generate', source, '--output', output]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("serve")
def docs_serve(
port: int = typer.Option(8000, "--port", "-p", help="Port to serve on"),
):
"""Serve documentation locally."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['docs', 'serve', '--port', str(port)]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,51 @@
"""
Endpoints command group for PraisonAI CLI.
Provides API endpoint management commands.
"""
import typer
app = typer.Typer(help="API endpoint management")
@app.command("list")
def endpoints_list():
"""List available endpoints."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['endpoints', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("test")
def endpoints_test(
endpoint: str = typer.Argument(..., help="Endpoint to test"),
):
"""Test an endpoint."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['endpoints', 'test', endpoint]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,57 @@
"""
Eval command group for PraisonAI CLI.
Provides evaluation commands.
"""
import typer
app = typer.Typer(help="Evaluation and testing")
@app.command("accuracy")
def eval_accuracy(
agent: str = typer.Argument(..., help="Agent file or name"),
input_text: str = typer.Option(..., "--input", "-i", help="Input text"),
expected: str = typer.Option(..., "--expected", "-e", help="Expected output"),
iterations: int = typer.Option(3, "--iterations", "-n", help="Number of iterations"),
):
"""Run accuracy evaluation."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['eval', 'accuracy', agent, '--input', input_text, '--expected', expected]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("performance")
def eval_performance(
agent: str = typer.Argument(..., help="Agent file or name"),
iterations: int = typer.Option(50, "--iterations", "-n", help="Number of iterations"),
):
"""Run performance evaluation."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['eval', 'performance', agent, '--iterations', str(iterations)]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,74 @@
"""
Hooks command group for PraisonAI CLI.
Provides hook management commands.
"""
import typer
app = typer.Typer(help="Hook management")
@app.command("list")
def hooks_list():
"""List available hooks."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['hooks', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("add")
def hooks_add(
name: str = typer.Argument(..., help="Hook name"),
event: str = typer.Option(..., "--event", "-e", help="Event to hook into"),
):
"""Add a hook."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['hooks', 'add', name, '--event', event]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("remove")
def hooks_remove(
name: str = typer.Argument(..., help="Hook name to remove"),
):
"""Remove a hook."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['hooks', 'remove', name]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,76 @@
"""
Knowledge command group for PraisonAI CLI.
Provides knowledge base management commands.
"""
import typer
app = typer.Typer(help="Knowledge base management")
@app.command("add")
def knowledge_add(
source: str = typer.Argument(..., help="Source file or URL"),
name: str = typer.Option(None, "--name", "-n", help="Knowledge base name"),
):
"""Add knowledge from a source."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['knowledge', 'add', source]
if name:
argv.extend(['--name', name])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("list")
def knowledge_list():
"""List knowledge bases."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['knowledge', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("search")
def knowledge_search(
query: str = typer.Argument(..., help="Search query"),
):
"""Search knowledge base."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['knowledge', 'search', query]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,109 @@
"""
Memory command group for PraisonAI CLI.
Provides memory management commands.
"""
import typer
app = typer.Typer(help="Memory management")
@app.command("show")
def memory_show(
user_id: str = typer.Option(None, "--user-id", help="User ID for memory isolation"),
limit: int = typer.Option(10, "--limit", "-l", help="Number of memories to show"),
):
"""Show stored memories."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['memory', 'show']
if user_id:
argv.extend(['--user-id', user_id])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("add")
def memory_add(
content: str = typer.Argument(..., help="Memory content to add"),
user_id: str = typer.Option(None, "--user-id", help="User ID for memory isolation"),
):
"""Add a memory."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['memory', 'add', content]
if user_id:
argv.extend(['--user-id', user_id])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("search")
def memory_search(
query: str = typer.Argument(..., help="Search query"),
user_id: str = typer.Option(None, "--user-id", help="User ID for memory isolation"),
):
"""Search memories."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['memory', 'search', query]
if user_id:
argv.extend(['--user-id', user_id])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("clear")
def memory_clear(
user_id: str = typer.Option(None, "--user-id", help="User ID for memory isolation"),
force: bool = typer.Option(False, "--force", "-f", help="Force clear without confirmation"),
):
"""Clear all memories."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['memory', 'clear']
if user_id:
argv.extend(['--user-id', user_id])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,76 @@
"""
Package command group for PraisonAI CLI.
Provides package management commands (pip-like).
"""
import typer
app = typer.Typer(help="Package management")
@app.command("install")
def package_install(
package: str = typer.Argument(..., help="Package to install"),
upgrade: bool = typer.Option(False, "--upgrade", "-U", help="Upgrade if already installed"),
):
"""Install a package."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['package', 'install', package]
if upgrade:
argv.append('--upgrade')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("uninstall")
def package_uninstall(
package: str = typer.Argument(..., help="Package to uninstall"),
):
"""Uninstall a package."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['package', 'uninstall', package]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("list")
def package_list():
"""List installed packages."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['package', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
+39 -30
View File
@@ -20,62 +20,61 @@ def profile_query(
deep: bool = typer.Option(False, "--deep", help="Enable deep call tracing (higher overhead)"),
limit: int = typer.Option(30, "--limit", "-n", help="Top N functions to show"),
sort: str = typer.Option("cumulative", "--sort", "-s", help="Sort by: cumulative or tottime"),
show_files: bool = typer.Option(False, "--show-files", help="Group timing by file/module"),
show_callers: bool = typer.Option(False, "--show-callers", help="Show caller functions"),
show_callees: bool = typer.Option(False, "--show-callees", help="Show callee functions"),
importtime: bool = typer.Option(False, "--importtime", help="Show module import times"),
first_token: bool = typer.Option(False, "--first-token", help="Track time to first token (streaming)"),
save: Optional[str] = typer.Option(None, "--save", help="Save artifacts to path (creates .prof, .txt)"),
save: Optional[str] = typer.Option(None, "--save", help="Save artifacts to path (creates .prof, .txt, .json)"),
output_format: str = typer.Option("text", "--format", "-f", help="Output format: text or json"),
):
"""
Profile a query execution with detailed timing breakdown.
Shows per-function and per-file timing, call graphs, and latency metrics.
Uses the unified profiling architecture for consistent results across
CLI direct invocation (--profile) and this command.
Shows per-function timing, call graphs, and latency metrics.
Examples:
praisonai profile query "What is 2+2?"
praisonai profile query "Hello" --show-files --limit 20
praisonai profile query "Test" --stream --first-token
praisonai profile query "Hello" --limit 20
praisonai profile query "Test" --deep --show-callers --show-callees
praisonai profile query "Test" --save ./profile_results
"""
# Lazy import to avoid startup overhead
# Use unified profiler for consistent results
try:
from ..features.profiler import (
ProfilerConfig,
QueryProfiler,
format_profile_report,
)
from ..execution import ExecutionRequest, Profiler, ProfilerConfig as UnifiedProfilerConfig
except ImportError as e:
typer.echo(f"Error: Profiler module not available: {e}", err=True)
typer.echo(f"Error: Unified profiler not available: {e}", err=True)
raise typer.Exit(1)
# Warn about deep tracing overhead
if deep:
typer.echo("⚠️ Deep call tracing enabled - this adds significant overhead", err=True)
# Create config
config = ProfilerConfig(
deep=deep,
# Create unified execution request
request = ExecutionRequest(
prompt=prompt,
agent_name="ProfiledAgent",
model=model,
stream=stream,
)
# Create unified profiler config
config = UnifiedProfilerConfig(
layer=2 if deep else 1,
limit=limit,
sort_by=sort,
show_files=show_files,
show_callers=show_callers,
show_callees=show_callees,
importtime=importtime,
first_token=first_token,
save_path=save,
output_format=output_format,
stream=stream,
save_path=save,
)
# Run profiler
typer.echo("🔬 Starting profiled execution...", err=True)
try:
profiler = QueryProfiler(config)
result = profiler.profile_query(prompt, model=model, stream=stream)
profiler = Profiler(config)
result, report = profiler.profile_sync(request, invocation_method="profile_command")
except ImportError as e:
typer.echo(f"Error: {e}", err=True)
typer.echo("Install praisonaiagents: pip install praisonaiagents", err=True)
@@ -86,18 +85,28 @@ def profile_query(
# Output results
if output_format == "json":
import json
typer.echo(json.dumps(result.to_dict(), indent=2, default=str))
typer.echo(report.to_json())
else:
report = format_profile_report(result, config)
typer.echo(report)
typer.echo(report.to_text())
# Save artifacts if requested
if save:
try:
prof_path, txt_path = profiler.save_artifacts(result, save)
import os
os.makedirs(save, exist_ok=True)
# Save JSON report
json_path = os.path.join(save, "profile_report.json")
with open(json_path, 'w') as f:
f.write(report.to_json())
# Save text report
txt_path = os.path.join(save, "profile_report.txt")
with open(txt_path, 'w') as f:
f.write(report.to_text())
typer.echo("\n✅ Artifacts saved:", err=True)
typer.echo(f" {prof_path}", err=True)
typer.echo(f" {json_path}", err=True)
typer.echo(f" {txt_path}", err=True)
except Exception as e:
typer.echo(f"Warning: Failed to save artifacts: {e}", err=True)
@@ -0,0 +1,45 @@
"""
Realtime command group for PraisonAI CLI.
Provides realtime interaction commands.
"""
from typing import Optional
import typer
app = typer.Typer(help="Realtime interaction mode")
@app.callback(invoke_without_command=True)
def realtime_main(
ctx: typer.Context,
model: Optional[str] = typer.Option(None, "--model", "-m", help="LLM model to use"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
):
"""
Start realtime interaction mode.
Examples:
praisonai realtime
praisonai realtime --model gpt-4o
"""
from praisonai.cli.main import PraisonAI
import sys
argv = ['realtime']
if model:
argv.extend(['--model', model])
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,76 @@
"""
Recipe command group for PraisonAI CLI.
Provides recipe management commands.
"""
import typer
app = typer.Typer(help="Recipe management")
@app.command("list")
def recipe_list():
"""List available recipes."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['recipe', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("run")
def recipe_run(
name: str = typer.Argument(..., help="Recipe name"),
model: str = typer.Option(None, "--model", "-m", help="LLM model to use"),
):
"""Run a recipe."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['recipe', 'run', name]
if model:
argv.extend(['--model', model])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("install")
def recipe_install(
source: str = typer.Argument(..., help="Recipe source (path or URL)"),
):
"""Install a recipe."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['recipe', 'install', source]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,51 @@
"""
Registry command group for PraisonAI CLI.
Provides registry management commands.
"""
import typer
app = typer.Typer(help="Registry management")
@app.command("list")
def registry_list():
"""List registry entries."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['registry', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("serve")
def registry_serve(
port: int = typer.Option(8080, "--port", "-p", help="Port to serve on"),
):
"""Start registry server."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['registry', 'serve', '--port', str(port)]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,49 @@
"""
Research command group for PraisonAI CLI.
Provides research and analysis commands.
"""
import typer
app = typer.Typer(help="Research and analysis")
@app.callback(invoke_without_command=True)
def research_main(
ctx: typer.Context,
query: str = typer.Argument(None, help="Research query"),
model: str = typer.Option(None, "--model", "-m", help="LLM model to use"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
output: str = typer.Option(None, "--output", "-o", help="Output file path"),
):
"""
Run research and analysis tasks.
Examples:
praisonai research "What are the latest AI trends?"
praisonai research --model gpt-4o "Analyze market data"
"""
from praisonai.cli.main import PraisonAI
import sys
argv = ['research']
if query:
argv.append(query)
if model:
argv.extend(['--model', model])
if verbose:
argv.append('--verbose')
if output:
argv.extend(['--output', output])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,71 @@
"""
Rules command group for PraisonAI CLI.
Provides rules management commands.
"""
import typer
app = typer.Typer(help="Rules management")
@app.command("list")
def rules_list():
"""List active rules."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['rules', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("add")
def rules_add(
rule: str = typer.Argument(..., help="Rule to add"),
):
"""Add a rule."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['rules', 'add', rule]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("clear")
def rules_clear():
"""Clear all rules."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['rules', 'clear']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,99 @@
"""
Skills command group for PraisonAI CLI.
Provides skill management commands.
"""
import typer
app = typer.Typer(help="Skill management")
@app.command("list")
def skills_list(
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed info"),
):
"""List available skills."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['skills', 'list']
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("validate")
def skills_validate(
path: str = typer.Argument(..., help="Skill directory path"),
):
"""Validate a skill."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['skills', 'validate', path]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("create")
def skills_create(
name: str = typer.Argument(..., help="Skill name"),
):
"""Create a new skill."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['skills', 'create', name]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("install")
def skills_install(
source: str = typer.Argument(..., help="Skill source (path or URL)"),
):
"""Install a skill."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['skills', 'install', source]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,54 @@
"""
Templates command group for PraisonAI CLI.
Provides template management commands.
"""
import typer
app = typer.Typer(help="Template management")
@app.command("list")
def templates_list():
"""List available templates."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['templates', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("create")
def templates_create(
name: str = typer.Argument(..., help="Template name"),
source: str = typer.Option(None, "--source", "-s", help="Source file to create template from"),
):
"""Create a new template."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['templates', 'create', name]
if source:
argv.extend(['--source', source])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,74 @@
"""
Todo command group for PraisonAI CLI.
Provides todo/task management commands.
"""
import typer
app = typer.Typer(help="Todo/task management")
@app.command("list")
def todo_list():
"""List todos."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['todo', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("add")
def todo_add(
task: str = typer.Argument(..., help="Task description"),
priority: str = typer.Option("medium", "--priority", "-p", help="Priority (low, medium, high)"),
):
"""Add a todo."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['todo', 'add', task]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("done")
def todo_done(
task_id: str = typer.Argument(..., help="Task ID to mark as done"),
):
"""Mark a todo as done."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['todo', 'done', task_id]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,77 @@
"""
Tools command group for PraisonAI CLI.
Provides tool management commands.
"""
import typer
app = typer.Typer(help="Tool management")
@app.command("list")
def tools_list(
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed info"),
):
"""List available tools."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['tools', 'list']
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("info")
def tools_info(
name: str = typer.Argument(..., help="Tool name"),
):
"""Show tool information."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['tools', 'info', name]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("test")
def tools_test(
name: str = typer.Argument(..., help="Tool name to test"),
):
"""Test a tool."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['tools', 'test', name]
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,48 @@
"""
Train command group for PraisonAI CLI.
Provides model training commands.
"""
from typing import Optional
import typer
app = typer.Typer(help="Model training and fine-tuning")
@app.callback(invoke_without_command=True)
def train_main(
ctx: typer.Context,
dataset: Optional[str] = typer.Argument(None, help="Training dataset path"),
model: Optional[str] = typer.Option(None, "--model", "-m", help="Base model to fine-tune"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
):
"""
Train or fine-tune models.
Examples:
praisonai train dataset.json
praisonai train --model gpt-4o dataset.json
"""
from praisonai.cli.main import PraisonAI
import sys
argv = ['train']
if dataset:
argv.append(dataset)
if model:
argv.extend(['--model', model])
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,47 @@
"""
UI command group for PraisonAI CLI.
Provides web UI commands.
"""
from typing import Optional
import typer
app = typer.Typer(help="Web UI management")
@app.callback(invoke_without_command=True)
def ui_main(
ctx: typer.Context,
port: int = typer.Option(8080, "--port", "-p", help="Port to run UI on"),
host: str = typer.Option("127.0.0.1", "--host", "-h", help="Host to bind to"),
public: bool = typer.Option(False, "--public", help="Make UI publicly accessible"),
):
"""
Start the web UI.
Examples:
praisonai ui
praisonai ui --port 3000
praisonai ui --public
"""
from praisonai.cli.main import PraisonAI
import sys
argv = ['ui']
argv.extend(['--port', str(port)])
argv.extend(['--host', host])
if public:
argv.append('--public')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,82 @@
"""
Workflow command group for PraisonAI CLI.
Provides workflow management commands.
"""
import typer
app = typer.Typer(help="Workflow management")
@app.command("run")
def workflow_run(
file: str = typer.Argument(..., help="Workflow file path"),
model: str = typer.Option(None, "--model", "-m", help="LLM model to use"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
):
"""Run a workflow."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['workflow', 'run', file]
if model:
argv.extend(['--model', model])
if verbose:
argv.append('--verbose')
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("list")
def workflow_list():
"""List available workflows."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['workflow', 'list']
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@app.command("create")
def workflow_create(
name: str = typer.Argument(..., help="Workflow name"),
template: str = typer.Option(None, "--template", "-t", help="Template to use"),
):
"""Create a new workflow."""
from praisonai.cli.main import PraisonAI
import sys
argv = ['workflow', 'create', name]
if template:
argv.extend(['--template', template])
original_argv = sys.argv
sys.argv = ['praisonai'] + argv
try:
praison = PraisonAI()
praison.main()
except SystemExit:
pass
finally:
sys.argv = original_argv
@@ -0,0 +1,99 @@
"""
PraisonAI Unified Execution Module.
Provides a single, unified execution primitive for all CLI modes:
- CLI direct prompt
- Profile command
- TUI workers
Design Principles:
1. Profiling observes, never alters execution
2. Zero overhead when profiling disabled
3. Sync and async are first-class citizens
4. Fail-safe, not fail-fast
5. Bounded resource usage
6. Schema stability with versioning
"""
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .request import ExecutionRequest
from .result import ExecutionResult
from .core import execute_sync, execute_async
from .profiler import Profiler, ProfilerConfig, ProfileReport
# Lazy loading to maintain zero-overhead when not used
_lazy_cache = {}
def __getattr__(name: str):
"""Lazy load execution components."""
global _lazy_cache
if name in _lazy_cache:
return _lazy_cache[name]
if name == "ExecutionRequest":
from .request import ExecutionRequest
_lazy_cache[name] = ExecutionRequest
return ExecutionRequest
elif name == "ExecutionResult":
from .result import ExecutionResult
_lazy_cache[name] = ExecutionResult
return ExecutionResult
elif name == "execute_sync":
from .core import execute_sync
_lazy_cache[name] = execute_sync
return execute_sync
elif name == "execute_async":
from .core import execute_async
_lazy_cache[name] = execute_async
return execute_async
elif name == "Profiler":
from .profiler import Profiler
_lazy_cache[name] = Profiler
return Profiler
elif name == "ProfilerConfig":
from .profiler import ProfilerConfig
_lazy_cache[name] = ProfilerConfig
return ProfilerConfig
elif name == "ProfileReport":
from .profiler import ProfileReport
_lazy_cache[name] = ProfileReport
return ProfileReport
elif name == "TimingBreakdown":
from .profiler import TimingBreakdown
_lazy_cache[name] = TimingBreakdown
return TimingBreakdown
elif name == "InvocationInfo":
from .profiler import InvocationInfo
_lazy_cache[name] = InvocationInfo
return InvocationInfo
elif name == "DecisionTrace":
from .profiler import DecisionTrace
_lazy_cache[name] = DecisionTrace
return DecisionTrace
elif name == "ModuleBreakdown":
from .profiler import ModuleBreakdown
_lazy_cache[name] = ModuleBreakdown
return ModuleBreakdown
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
__all__ = [
# Core execution
"ExecutionRequest",
"ExecutionResult",
"execute_sync",
"execute_async",
# Profiling
"Profiler",
"ProfilerConfig",
"ProfileReport",
"TimingBreakdown",
"InvocationInfo",
"DecisionTrace",
"ModuleBreakdown",
]
@@ -0,0 +1,210 @@
"""
Core Execution Module.
Provides the unified execution primitives:
- _execute_core(): Single implementation shared by all paths
- execute_sync(): Synchronous wrapper for CLI
- execute_async(): Asynchronous wrapper for TUI workers
"""
import asyncio
import time
import uuid
from typing import Optional, AsyncGenerator
from .request import ExecutionRequest
from .result import ExecutionResult
def _generate_run_id() -> str:
"""Generate a unique run ID."""
return str(uuid.uuid4())[:8]
def _execute_core(
request: ExecutionRequest,
timing: Optional[dict] = None,
) -> ExecutionResult:
"""
THE SINGLE EXECUTION IMPLEMENTATION.
All execution modes call this function.
Profiler wraps this function, never injects into it.
Args:
request: The execution request
timing: Optional dict to record timing phases (for profiling)
Returns:
ExecutionResult with output and metadata
"""
run_id = _generate_run_id()
start_time = time.perf_counter()
if timing is not None:
timing["core_start"] = start_time
try:
# Phase 1: Import (measured inline)
import_start = time.perf_counter()
from praisonaiagents import Agent
import_end = time.perf_counter()
if timing is not None:
timing["imports_ms"] = (import_end - import_start) * 1000
# Phase 2: Agent Construction
agent_start = time.perf_counter()
agent_config = {
"name": request.agent_name,
"verbose": False,
}
if request.agent_instructions:
agent_config["instructions"] = request.agent_instructions
if request.model:
agent_config["llm"] = request.model
if request.tools:
agent_config["tools"] = list(request.tools)
agent = Agent(**agent_config)
agent_end = time.perf_counter()
if timing is not None:
timing["agent_init_ms"] = (agent_end - agent_start) * 1000
# Phase 3: Execution
exec_start = time.perf_counter()
if request.stream:
# For streaming, collect all chunks
chunks = []
if hasattr(agent, '_start_stream'):
for chunk in agent._start_stream(request.prompt):
chunks.append(chunk)
else:
# Fallback to non-streaming
result = agent.start(request.prompt)
chunks = [result] if result else []
output = "".join(chunks)
else:
output = agent.start(request.prompt)
exec_end = time.perf_counter()
if timing is not None:
timing["execution_ms"] = (exec_end - exec_start) * 1000
end_time = time.perf_counter()
if timing is not None:
timing["total_ms"] = (end_time - start_time) * 1000
return ExecutionResult(
output=output or "",
run_id=run_id,
success=True,
start_time=start_time,
end_time=end_time,
metadata={
"model": request.model,
"stream": request.stream,
},
)
except Exception as e:
end_time = time.perf_counter()
if timing is not None:
timing["total_ms"] = (end_time - start_time) * 1000
timing["error"] = str(e)
return ExecutionResult.from_error(
error=str(e),
run_id=run_id,
)
def execute_sync(request: ExecutionRequest) -> ExecutionResult:
"""
Synchronous execution wrapper.
Used by:
- CLI direct prompt
- Profile command
Args:
request: The execution request
Returns:
ExecutionResult with output and metadata
"""
return _execute_core(request)
async def execute_async(request: ExecutionRequest) -> ExecutionResult:
"""
Asynchronous execution wrapper.
Used by:
- TUI workers
- Queue system
Args:
request: The execution request
Returns:
ExecutionResult with output and metadata
"""
# Run the synchronous core in a thread pool to avoid blocking
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, _execute_core, request, None)
async def execute_async_stream(
request: ExecutionRequest,
) -> AsyncGenerator[str, None]:
"""
Asynchronous streaming execution.
Yields chunks as they arrive.
Args:
request: The execution request (stream=True recommended)
Yields:
String chunks of the response
"""
try:
from praisonaiagents import Agent
agent_config = {
"name": request.agent_name,
"verbose": False,
}
if request.agent_instructions:
agent_config["instructions"] = request.agent_instructions
if request.model:
agent_config["llm"] = request.model
if request.tools:
agent_config["tools"] = list(request.tools)
agent = Agent(**agent_config)
if hasattr(agent, '_start_stream'):
for chunk in agent._start_stream(request.prompt):
yield chunk
await asyncio.sleep(0) # Yield control
else:
result = agent.start(request.prompt)
if result:
yield result
except Exception as e:
yield f"Error: {e}"
@@ -0,0 +1,898 @@
"""
Profiler Module.
Provides external profiling that wraps execution.
Execution code has ZERO awareness of profiling.
Design Principles:
1. Profiler wraps execution, does not inject into it
2. Layered profiling with explicit overhead
3. Bounded resource usage
4. Versioned, stable output schema
"""
import cProfile
import pstats
import time
import platform
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from .request import ExecutionRequest
from .result import ExecutionResult
from .core import _execute_core
# Schema version - MUST be incremented for breaking changes
SCHEMA_VERSION = "1.0"
# Bounds for profile data
MAX_FUNCTION_STATS = 1000
MAX_CALL_GRAPH_EDGES = 5000
MAX_NETWORK_REQUESTS = 100
MAX_IMPORT_MODULES = 200
@dataclass
class ProfilerConfig:
"""
Profiler configuration with explicit layer control.
Layers:
- 0: Wall-clock phases only (<1ms overhead)
- 1: + cProfile function stats (~5% overhead)
- 2: + Call graph callers/callees (~15% overhead)
Network timing is orthogonal (opt-in via track_network).
"""
# Layer control (0, 1, or 2)
layer: int = 1
# Layer 1+ options
limit: int = 30 # Max functions to show
sort_by: str = "cumulative" # cumulative, time, calls
# Layer 2 options
show_callers: bool = False
show_callees: bool = False
# Network timing (orthogonal to layers)
track_network: bool = False
# Output options
output_format: str = "text" # text, json
save_path: Optional[str] = None
@classmethod
def from_flags(
cls,
profile: bool = False,
deep: bool = False,
network: bool = False,
) -> 'ProfilerConfig':
"""Create config from CLI flags."""
if deep:
return cls(
layer=2,
show_callers=True,
show_callees=True,
track_network=network,
)
elif profile:
return cls(layer=1, track_network=network)
else:
return cls(layer=0, track_network=network)
@dataclass
class TimingBreakdown:
"""
Phase timing breakdown with full timeline visibility.
All fields in milliseconds.
Timeline order: cli_entry -> cli_parse -> routing -> imports -> agent_init ->
network_start -> first_token -> first_output -> execution_end
"""
# MANDATORY fields (always present)
total_ms: float = 0.0
imports_ms: float = 0.0
agent_init_ms: float = 0.0
execution_ms: float = 0.0
# TIMELINE PHASES (new - for full visibility)
cli_entry_ms: float = 0.0 # Time from ENTER to CLI entry point
cli_parse_ms: float = 0.0 # Argparse/Typer routing time
routing_ms: float = 0.0 # Command routing time
network_start_ms: float = 0.0 # When network request started (relative to start)
first_token_ms: float = 0.0 # Time to first token (streaming)
first_output_ms: float = 0.0 # Time to First Response (TTFR) - first visible output
# OPTIONAL fields (may be 0)
tool_time_ms: float = 0.0 # If tools were called
@property
def time_to_first_response_ms(self) -> float:
"""Time to First Response (TTFR) - the key user-perceived latency metric."""
if self.first_output_ms > 0:
return self.first_output_ms
# Fallback: use execution end if first_output not captured
return self.total_ms
def to_dict(self) -> Dict[str, float]:
"""Convert to dictionary."""
return {
"total_ms": self.total_ms,
"imports_ms": self.imports_ms,
"agent_init_ms": self.agent_init_ms,
"execution_ms": self.execution_ms,
"cli_entry_ms": self.cli_entry_ms,
"cli_parse_ms": self.cli_parse_ms,
"routing_ms": self.routing_ms,
"network_start_ms": self.network_start_ms,
"first_token_ms": self.first_token_ms,
"first_output_ms": self.first_output_ms,
"time_to_first_response_ms": self.time_to_first_response_ms,
"tool_time_ms": self.tool_time_ms,
}
def to_timeline(self) -> List[Tuple[str, float, float]]:
"""
Get ordered timeline of phases.
Returns list of (phase_name, start_ms, duration_ms) tuples.
"""
timeline = []
cursor = 0.0
# CLI Entry (if captured)
if self.cli_entry_ms > 0:
timeline.append(("CLI Entry", 0.0, self.cli_entry_ms))
cursor = self.cli_entry_ms
# CLI Parse
if self.cli_parse_ms > 0:
timeline.append(("CLI Parse", cursor, self.cli_parse_ms))
cursor += self.cli_parse_ms
# Routing
if self.routing_ms > 0:
timeline.append(("Routing", cursor, self.routing_ms))
cursor += self.routing_ms
# Imports
if self.imports_ms > 0:
timeline.append(("Imports", cursor, self.imports_ms))
cursor += self.imports_ms
# Agent Init
if self.agent_init_ms > 0:
timeline.append(("Agent Init", cursor, self.agent_init_ms))
cursor += self.agent_init_ms
# Network to First Token (if streaming)
if self.network_start_ms > 0 and self.first_token_ms > 0:
network_duration = self.first_token_ms - self.network_start_ms
if network_duration > 0:
timeline.append(("Network → First Token", self.network_start_ms, network_duration))
# Execution
if self.execution_ms > 0:
timeline.append(("Execution", cursor, self.execution_ms))
return timeline
@dataclass
class FunctionStat:
"""Statistics for a single function."""
name: str
file: str
line: int
calls: int
total_time_ms: float
cumulative_time_ms: float
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"name": self.name,
"file": self.file,
"line": self.line,
"calls": self.calls,
"total_time_ms": self.total_time_ms,
"cumulative_time_ms": self.cumulative_time_ms,
}
@dataclass
class CallGraph:
"""Call graph data (callers and callees)."""
callers: Dict[str, List[str]] = field(default_factory=dict)
callees: Dict[str, List[str]] = field(default_factory=dict)
@property
def edges(self) -> List[Tuple[str, str]]:
"""Get all edges as (caller, callee) tuples."""
edges = []
for callee, callers in self.callers.items():
for caller in callers:
edges.append((caller, callee))
return edges
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"callers": self.callers,
"callees": self.callees,
"edge_count": len(self.edges),
}
@dataclass
class RequestTiming:
"""Single HTTP request timing."""
url: str
method: str
start_time: float
first_byte_time: float
end_time: float
status_code: int
@property
def ttfb_ms(self) -> float:
"""Time to first byte in milliseconds."""
return (self.first_byte_time - self.start_time) * 1000
@property
def total_ms(self) -> float:
"""Total request time in milliseconds."""
return (self.end_time - self.start_time) * 1000
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"url": self.url,
"method": self.method,
"ttfb_ms": self.ttfb_ms,
"total_ms": self.total_ms,
"status_code": self.status_code,
}
@dataclass
class InvocationInfo:
"""How the profile was invoked."""
method: str # "cli_direct", "profile_command", "tui"
flags: Dict[str, Any] = field(default_factory=dict)
praisonai_version: str = ""
python_version: str = ""
def __post_init__(self):
"""Set version info if not provided."""
if not self.python_version:
self.python_version = platform.python_version()
if not self.praisonai_version:
try:
from praisonai.version import __version__
self.praisonai_version = __version__
except ImportError:
self.praisonai_version = "unknown"
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"method": self.method,
"flags": self.flags,
"praisonai_version": self.praisonai_version,
"python_version": self.python_version,
}
@dataclass
class DecisionTrace:
"""
Decision trace for deep profile visibility.
Explains what decisions were made during execution.
"""
agent_config: str = "" # Agent configuration chosen
model_selected: str = "" # Model used
streaming_mode: bool = False # Streaming vs non-streaming
profile_layer: int = 0 # Profile layer (0/1/2)
tools_enabled: List[str] = field(default_factory=list)
tools_disabled: List[str] = field(default_factory=list)
fallbacks_used: List[str] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"agent_config": self.agent_config,
"model_selected": self.model_selected,
"streaming_mode": self.streaming_mode,
"profile_layer": self.profile_layer,
"tools_enabled": self.tools_enabled,
"tools_disabled": self.tools_disabled,
"fallbacks_used": self.fallbacks_used,
}
def to_text(self) -> str:
"""Format as human-readable text."""
lines = []
lines.append(f" Agent Config: {self.agent_config or 'default'}")
lines.append(f" Model: {self.model_selected or 'default'}")
lines.append(f" Streaming: {'enabled' if self.streaming_mode else 'disabled'}")
lines.append(f" Profile Layer: {self.profile_layer}")
if self.tools_enabled:
lines.append(f" Tools Enabled: {', '.join(self.tools_enabled)}")
if self.tools_disabled:
lines.append(f" Tools Disabled: {', '.join(self.tools_disabled)}")
if self.fallbacks_used:
lines.append(f" Fallbacks: {', '.join(self.fallbacks_used)}")
return "\n".join(lines)
@dataclass
class ModuleBreakdown:
"""
Module/file breakdown for deep profile visibility.
Groups functions by module category.
"""
cli_modules: List[str] = field(default_factory=list)
execution_modules: List[str] = field(default_factory=list)
agent_modules: List[str] = field(default_factory=list)
tool_modules: List[str] = field(default_factory=list)
network_modules: List[str] = field(default_factory=list)
third_party_modules: List[str] = field(default_factory=list)
def to_dict(self) -> Dict[str, List[str]]:
"""Convert to dictionary."""
return {
"cli": self.cli_modules,
"execution": self.execution_modules,
"agent": self.agent_modules,
"tools": self.tool_modules,
"network": self.network_modules,
"third_party": self.third_party_modules,
}
@dataclass
class ProfileReport:
"""
Canonical profile report.
VERSION 1.0 - Schema is frozen after release.
New fields MUST be optional with defaults.
"""
# Schema version (MANDATORY, NEVER CHANGES MEANING)
schema_version: str = SCHEMA_VERSION
# Identity (MANDATORY)
run_id: str = ""
timestamp: str = "" # ISO 8601
# Invocation (MANDATORY)
invocation: InvocationInfo = field(default_factory=lambda: InvocationInfo(method="unknown"))
# Timing (MANDATORY)
timing: TimingBreakdown = field(default_factory=TimingBreakdown)
# Function stats (OPTIONAL, present if layer >= 1)
functions: Optional[List[FunctionStat]] = None
# Call graph (OPTIONAL, present if layer >= 2)
call_graph: Optional[CallGraph] = None
# Network (OPTIONAL, present if track_network)
network: Optional[List[RequestTiming]] = None
# Response (MANDATORY but truncated)
response_preview: str = "" # Max 500 chars
# Decision trace (OPTIONAL, present if layer >= 2)
decision_trace: Optional[DecisionTrace] = None
# Module breakdown (OPTIONAL, present if layer >= 2)
module_breakdown: Optional[ModuleBreakdown] = None
def __post_init__(self):
"""Set timestamp if not provided."""
if not self.timestamp:
self.timestamp = datetime.utcnow().isoformat() + "Z"
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for JSON serialization."""
result = {
"schema_version": self.schema_version,
"run_id": self.run_id,
"timestamp": self.timestamp,
"invocation": self.invocation.to_dict(),
"timing": self.timing.to_dict(),
"timeline": self.timing.to_timeline(),
"timeline_diagram": self.to_timeline_diagram(),
"response_preview": self.response_preview,
}
if self.functions is not None:
result["functions"] = [f.to_dict() for f in self.functions]
if self.call_graph is not None:
result["call_graph"] = self.call_graph.to_dict()
if self.network is not None:
result["network"] = [r.to_dict() for r in self.network]
if self.decision_trace is not None:
result["decision_trace"] = self.decision_trace.to_dict()
if self.module_breakdown is not None:
result["module_breakdown"] = self.module_breakdown.to_dict()
return result
def to_json(self) -> str:
"""Convert to JSON string."""
import json
return json.dumps(self.to_dict(), indent=2, default=str)
def to_timeline_diagram(self) -> str:
"""
Generate ASCII timeline diagram showing execution phases.
Format:
ENTER ─────────────────────────────────────────────────────────► RESPONSE
│ imports │ init │ network │
│ XXXms │ XXms │ XXXms │
└─────────┴──────┴───────────────────────┘
TOTAL: XXXXms
"""
lines = []
total = self.timing.total_ms
if total <= 0:
return "No timing data available"
# Calculate phase widths (proportional to time, min 8 chars)
phases = []
if self.timing.imports_ms > 0:
phases.append(("imports", self.timing.imports_ms))
if self.timing.agent_init_ms > 0:
phases.append(("init", self.timing.agent_init_ms))
if self.timing.execution_ms > 0:
phases.append(("network", self.timing.execution_ms))
if not phases:
phases = [("total", total)]
# Scale to fit in ~60 chars
scale = 50.0 / total if total > 0 else 1
# Build the diagram
lines.append("")
lines.append("## Timeline Diagram")
lines.append("")
# Top line with arrow
top_line = "ENTER "
for name, ms in phases:
width = max(8, int(ms * scale))
top_line += "─" * width
top_line += "► RESPONSE"
lines.append(top_line)
# Phase names line
name_line = " "
for name, ms in phases:
width = max(8, int(ms * scale))
name_line += "│" + name.center(width - 1)
name_line += "│"
lines.append(name_line)
# Phase times line
time_line = " "
for name, ms in phases:
width = max(8, int(ms * scale))
time_str = f"{ms:.0f}ms"
time_line += "│" + time_str.center(width - 1)
time_line += "│"
lines.append(time_line)
# Bottom line
bottom_line = " "
for i, (name, ms) in enumerate(phases):
width = max(8, int(ms * scale))
if i == 0:
bottom_line += "└" + "─" * (width - 1)
else:
bottom_line += "┴" + "─" * (width - 1)
bottom_line += "┘"
lines.append(bottom_line)
# Total line
total_line = " " * (len(bottom_line) - 15) + f"TOTAL: {total:.0f}ms"
lines.append(total_line)
lines.append("")
return "\n".join(lines)
def to_text(self) -> str:
"""Format as human-readable text."""
lines = []
lines.append("=" * 70)
lines.append("PraisonAI Profile Report")
lines.append("=" * 70)
lines.append("")
# Identity
lines.append(f"Run ID: {self.run_id}")
lines.append(f"Timestamp: {self.timestamp}")
lines.append(f"Method: {self.invocation.method}")
lines.append(f"Version: {self.invocation.praisonai_version}")
lines.append("")
# TIMELINE DIAGRAM (visual representation)
lines.append(self.to_timeline_diagram())
# TIMELINE SECTION (shows ENTER → First Response)
lines.append("## Execution Timeline")
lines.append("-" * 45)
timeline = self.timing.to_timeline()
if timeline:
for phase_name, start_ms, duration_ms in timeline:
lines.append(f" {phase_name:<25} : {duration_ms:>8.2f} ms")
else:
# Fallback to basic phases
if self.timing.imports_ms > 0:
lines.append(f" {'Imports':<25} : {self.timing.imports_ms:>8.2f} ms")
if self.timing.agent_init_ms > 0:
lines.append(f" {'Agent Init':<25} : {self.timing.agent_init_ms:>8.2f} ms")
if self.timing.execution_ms > 0:
lines.append(f" {'Execution':<25} : {self.timing.execution_ms:>8.2f} ms")
lines.append(" " + "─" * 43)
# TIME TO FIRST RESPONSE (TTFR) - the key metric
ttfr = self.timing.time_to_first_response_ms
lines.append(f" {'⏱ Time to First Response':<25} : {ttfr:>8.2f} ms")
lines.append(f" {'TOTAL':<25} : {self.timing.total_ms:>8.2f} ms")
lines.append("")
# Timing breakdown (legacy format for compatibility)
lines.append("## Timing Breakdown")
lines.append("-" * 40)
if self.timing.cli_entry_ms > 0:
lines.append(f" CLI Entry: {self.timing.cli_entry_ms:>10.2f} ms")
if self.timing.cli_parse_ms > 0:
lines.append(f" CLI Parse: {self.timing.cli_parse_ms:>10.2f} ms")
if self.timing.routing_ms > 0:
lines.append(f" Routing: {self.timing.routing_ms:>10.2f} ms")
lines.append(f" Imports: {self.timing.imports_ms:>10.2f} ms")
lines.append(f" Agent Init: {self.timing.agent_init_ms:>10.2f} ms")
lines.append(f" Execution: {self.timing.execution_ms:>10.2f} ms")
if self.timing.network_start_ms > 0:
lines.append(f" Network Start: {self.timing.network_start_ms:>10.2f} ms")
if self.timing.first_token_ms > 0:
lines.append(f" First Token: {self.timing.first_token_ms:>10.2f} ms")
if self.timing.first_output_ms > 0:
lines.append(f" First Output: {self.timing.first_output_ms:>10.2f} ms")
lines.append(" ─────────────────────────────────────")
lines.append(f" TOTAL: {self.timing.total_ms:>10.2f} ms")
lines.append("")
# Decision trace (deep profile only)
if self.decision_trace:
lines.append("## Decision Trace")
lines.append("-" * 40)
lines.append(self.decision_trace.to_text())
lines.append("")
# Function stats
if self.functions:
lines.append("## Top Functions by Cumulative Time")
lines.append("-" * 70)
lines.append(f"{'Function':<40} {'Calls':>8} {'Cumul (ms)':>12}")
lines.append("-" * 70)
for func in self.functions[:20]:
name = func.name[:38] if len(func.name) > 38 else func.name
lines.append(f"{name:<40} {func.calls:>8} {func.cumulative_time_ms:>12.2f}")
lines.append("")
# Module breakdown (deep profile only)
if self.module_breakdown:
lines.append("## Module Breakdown")
lines.append("-" * 40)
mb = self.module_breakdown
if mb.cli_modules:
lines.append(f" CLI: {len(mb.cli_modules)} modules")
if mb.execution_modules:
lines.append(f" Execution: {len(mb.execution_modules)} modules")
if mb.agent_modules:
lines.append(f" Agent: {len(mb.agent_modules)} modules")
if mb.tool_modules:
lines.append(f" Tools: {len(mb.tool_modules)} modules")
if mb.network_modules:
lines.append(f" Network: {len(mb.network_modules)} modules")
if mb.third_party_modules:
lines.append(f" Third-party:{len(mb.third_party_modules)} modules")
lines.append("")
# Call graph summary
if self.call_graph:
lines.append(f"## Call Graph: {len(self.call_graph.edges)} edges")
lines.append("")
# Network timing
if self.network:
lines.append("## Network Requests")
lines.append("-" * 70)
for req in self.network[:10]:
lines.append(f" {req.method} {req.url[:50]} - {req.total_ms:.2f}ms (TTFB: {req.ttfb_ms:.2f}ms)")
lines.append("")
# Response preview
if self.response_preview:
lines.append("## Response Preview")
lines.append("-" * 40)
preview = self.response_preview[:200]
if len(self.response_preview) > 200:
preview += "..."
lines.append(preview)
lines.append("")
lines.append("=" * 70)
return "\n".join(lines)
class Profiler:
"""
External profiler that wraps execution.
Execution code has ZERO awareness of profiling.
Profiler uses cProfile.runctx() or similar.
"""
def __init__(self, config: ProfilerConfig):
self.config = config
self._cprofile: Optional[cProfile.Profile] = None
self._timing: Dict[str, float] = {}
self._network_requests: List[RequestTiming] = []
def profile_sync(
self,
request: ExecutionRequest,
invocation_method: str = "profile_command",
) -> Tuple[ExecutionResult, ProfileReport]:
"""
Profile synchronous execution.
Args:
request: The execution request
invocation_method: How this was invoked (for report)
Returns:
Tuple of (ExecutionResult, ProfileReport)
"""
timing_dict: Dict[str, float] = {}
# Layer 0: Wall-clock timing (always)
start = time.perf_counter()
# Layer 1+: cProfile
if self.config.layer >= 1:
self._cprofile = cProfile.Profile()
self._cprofile.enable()
try:
result = _execute_core(request, timing_dict)
finally:
if self._cprofile:
self._cprofile.disable()
total_ms = (time.perf_counter() - start) * 1000
# Build report
report = self._build_report(
request=request,
result=result,
timing_dict=timing_dict,
total_ms=total_ms,
invocation_method=invocation_method,
)
return result, report
def _build_report(
self,
request: ExecutionRequest,
result: ExecutionResult,
timing_dict: Dict[str, float],
total_ms: float,
invocation_method: str,
) -> ProfileReport:
"""Build the profile report from collected data."""
# Calculate first_output_ms (TTFR) - time from start to when output is available
# This is imports + agent_init + execution (when output becomes available)
imports_ms = timing_dict.get("imports_ms", 0.0)
agent_init_ms = timing_dict.get("agent_init_ms", 0.0)
execution_ms = timing_dict.get("execution_ms", 0.0)
first_output_ms = imports_ms + agent_init_ms + execution_ms
# Timing breakdown with full timeline
timing = TimingBreakdown(
total_ms=total_ms,
imports_ms=imports_ms,
agent_init_ms=agent_init_ms,
execution_ms=execution_ms,
cli_entry_ms=timing_dict.get("cli_entry_ms", 0.0),
cli_parse_ms=timing_dict.get("cli_parse_ms", 0.0),
routing_ms=timing_dict.get("routing_ms", 0.0),
network_start_ms=timing_dict.get("network_start_ms", 0.0),
first_token_ms=timing_dict.get("first_token_ms", 0.0),
first_output_ms=first_output_ms,
)
# Invocation info
invocation = InvocationInfo(
method=invocation_method,
flags={
"layer": self.config.layer,
"stream": request.stream,
"model": request.model,
},
)
# Function stats (layer 1+)
functions = None
if self.config.layer >= 1 and self._cprofile:
functions = self._extract_function_stats()
# Call graph (layer 2)
call_graph = None
if self.config.layer >= 2 and self._cprofile:
call_graph = self._extract_call_graph()
# Decision trace (layer 2 - deep profile)
decision_trace = None
if self.config.layer >= 2:
decision_trace = DecisionTrace(
agent_config=request.agent_name or "default",
model_selected=request.model or "default",
streaming_mode=request.stream,
profile_layer=self.config.layer,
tools_enabled=list(request.tools) if request.tools else [],
tools_disabled=[],
fallbacks_used=[],
)
# Module breakdown (layer 2 - deep profile)
module_breakdown = None
if self.config.layer >= 2 and functions:
module_breakdown = self._extract_module_breakdown(functions)
# Response preview (truncated)
response_preview = result.output[:500] if result.output else ""
return ProfileReport(
run_id=result.run_id,
invocation=invocation,
timing=timing,
functions=functions,
call_graph=call_graph,
network=self._network_requests if self._network_requests else None,
response_preview=response_preview,
decision_trace=decision_trace,
module_breakdown=module_breakdown,
)
def _extract_module_breakdown(self, functions: List[FunctionStat]) -> ModuleBreakdown:
"""Extract module breakdown from function stats."""
cli_modules = set()
execution_modules = set()
agent_modules = set()
tool_modules = set()
network_modules = set()
third_party_modules = set()
for func in functions:
file_path = func.file.lower()
if "praisonai/cli" in file_path:
cli_modules.add(func.file)
elif "praisonai" in file_path and "execution" in file_path:
execution_modules.add(func.file)
elif "praisonaiagents" in file_path and "agent" in file_path:
agent_modules.add(func.file)
elif "praisonaiagents" in file_path and "tool" in file_path:
tool_modules.add(func.file)
elif any(x in file_path for x in ["httpx", "httpcore", "urllib", "requests", "aiohttp"]):
network_modules.add(func.file)
elif "site-packages" in file_path or not file_path.startswith("/"):
third_party_modules.add(func.file)
return ModuleBreakdown(
cli_modules=list(cli_modules)[:20],
execution_modules=list(execution_modules)[:20],
agent_modules=list(agent_modules)[:20],
tool_modules=list(tool_modules)[:20],
network_modules=list(network_modules)[:20],
third_party_modules=list(third_party_modules)[:20],
)
def _extract_function_stats(self) -> List[FunctionStat]:
"""Extract function statistics from cProfile."""
if not self._cprofile:
return []
stats = pstats.Stats(self._cprofile)
# Sort by cumulative time
stats.sort_stats(self.config.sort_by)
# Extract stats
function_stats = []
for (filename, line, name), (cc, nc, tt, ct, callers) in stats.stats.items():
if len(function_stats) >= MAX_FUNCTION_STATS:
break
function_stats.append(FunctionStat(
name=name,
file=filename,
line=line,
calls=nc,
total_time_ms=tt * 1000,
cumulative_time_ms=ct * 1000,
))
# Sort and limit
function_stats.sort(key=lambda x: x.cumulative_time_ms, reverse=True)
return function_stats[:self.config.limit]
def _extract_call_graph(self) -> CallGraph:
"""Extract call graph from cProfile."""
if not self._cprofile:
return CallGraph()
stats = pstats.Stats(self._cprofile)
callers: Dict[str, List[str]] = {}
callees: Dict[str, List[str]] = {}
edge_count = 0
for (filename, line, name), (cc, nc, tt, ct, caller_dict) in stats.stats.items():
if edge_count >= MAX_CALL_GRAPH_EDGES:
break
callee_key = f"{name}:{filename}:{line}"
for (caller_file, caller_line, caller_name), _ in caller_dict.items():
if edge_count >= MAX_CALL_GRAPH_EDGES:
break
caller_key = f"{caller_name}:{caller_file}:{caller_line}"
# Add to callers
if callee_key not in callers:
callers[callee_key] = []
if caller_key not in callers[callee_key]:
callers[callee_key].append(caller_key)
# Add to callees
if caller_key not in callees:
callees[caller_key] = []
if callee_key not in callees[caller_key]:
callees[caller_key].append(callee_key)
edge_count += 1
return CallGraph(callers=callers, callees=callees)
@@ -0,0 +1,85 @@
"""
ExecutionRequest - Immutable request for execution.
This is the minimal, immutable request that all execution paths use.
CLI/TUI translate their flags into this structure.
"""
from dataclasses import dataclass
from typing import Callable, Optional, Tuple, Any
@dataclass(frozen=True)
class ExecutionRequest:
"""
Minimal, immutable request for execution.
NOT a kitchen-sink of all CLI flags.
CLI/TUI translate their flags into this.
Attributes:
prompt: The user prompt to execute
agent_name: Name of the agent (default: "Assistant")
agent_instructions: Custom instructions for the agent
model: LLM model to use (None = use default)
tools: Tuple of tool callables (immutable)
stream: Whether to stream the response
Note: This is frozen (immutable) to:
- Prevent accidental mutation during profiling
- Enable safe sharing across threads/coroutines
"""
# Required
prompt: str
# Agent identity (optional, has defaults)
agent_name: str = "Assistant"
agent_instructions: Optional[str] = None
# Model (optional, has defaults)
model: Optional[str] = None # None = use default
# Tools (optional) - using tuple for immutability
tools: Tuple[Callable[..., Any], ...] = ()
# Execution mode
stream: bool = False
def __post_init__(self):
"""Validate request after initialization."""
if not self.prompt:
raise ValueError("prompt cannot be empty")
def with_model(self, model: str) -> 'ExecutionRequest':
"""Create a new request with a different model."""
return ExecutionRequest(
prompt=self.prompt,
agent_name=self.agent_name,
agent_instructions=self.agent_instructions,
model=model,
tools=self.tools,
stream=self.stream,
)
def with_tools(self, tools: Tuple[Callable[..., Any], ...]) -> 'ExecutionRequest':
"""Create a new request with different tools."""
return ExecutionRequest(
prompt=self.prompt,
agent_name=self.agent_name,
agent_instructions=self.agent_instructions,
model=self.model,
tools=tools,
stream=self.stream,
)
def to_dict(self) -> dict:
"""Convert to dictionary for serialization."""
return {
"prompt": self.prompt,
"agent_name": self.agent_name,
"agent_instructions": self.agent_instructions,
"model": self.model,
"tools_count": len(self.tools),
"stream": self.stream,
}
@@ -0,0 +1,74 @@
"""
ExecutionResult - Result from execution.
Contains the output and metadata from an execution.
"""
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class ExecutionResult:
"""
Result from executing a request.
Attributes:
output: The text output from the agent
run_id: Unique identifier for this execution
success: Whether execution completed successfully
error: Error message if execution failed
metadata: Additional metadata about the execution
tool_calls: List of tools that were called
start_time: When execution started (perf_counter)
end_time: When execution ended (perf_counter)
"""
# Primary output
output: str
# Identity
run_id: str = ""
# Status
success: bool = True
error: Optional[str] = None
# Metadata
metadata: Dict[str, Any] = field(default_factory=dict)
# Tool tracking
tool_calls: List[str] = field(default_factory=list)
# Timing (raw perf_counter values)
start_time: float = 0.0
end_time: float = 0.0
@property
def duration_ms(self) -> float:
"""Duration in milliseconds."""
if self.start_time and self.end_time:
return (self.end_time - self.start_time) * 1000
return 0.0
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization."""
return {
"output": self.output,
"run_id": self.run_id,
"success": self.success,
"error": self.error,
"metadata": self.metadata,
"tool_calls": self.tool_calls,
"duration_ms": self.duration_ms,
}
@classmethod
def from_error(cls, error: str, run_id: str = "") -> 'ExecutionResult':
"""Create a result from an error."""
return cls(
output="",
run_id=run_id,
success=False,
error=error,
)
@@ -94,6 +94,8 @@ __all__ = [
'CapabilitiesHandler',
# Performance benchmarking
'PerformanceHandler',
# Comprehensive benchmarking
'BenchmarkHandler',
# Lite agent (BYO-LLM)
'LiteHandler',
# Agent-centric tools (LSP/ACP powered)
@@ -233,6 +235,9 @@ def __getattr__(name):
elif name == 'PerformanceHandler':
from .performance import PerformanceHandler
return PerformanceHandler
elif name == 'BenchmarkHandler':
from .benchmark import BenchmarkHandler
return BenchmarkHandler
elif name == 'LiteHandler':
from .lite import LiteHandler
return LiteHandler
File diff suppressed because it is too large. Load diff
@@ -4,6 +4,7 @@ ACP health checks for PraisonAI Doctor.
import asyncio
import logging
import os
from ..models import CheckCategory, CheckResult, CheckStatus
from ..registry import register_check
@@ -17,7 +18,7 @@ logger = logging.getLogger(__name__)
category=CheckCategory.TOOLS,
description="Check if ACP module is installed"
)
def check_acp_module() -> CheckResult:
def check_acp_module(config=None) -> CheckResult:
"""Check if ACP module is available."""
try:
import importlib.util
@@ -25,21 +26,30 @@ def check_acp_module() -> CheckResult:
if spec is not None:
return CheckResult(
id="acp_module",
title="ACP Module Available",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="ACP module is available",
details={"module": "praisonai.acp"}
metadata={"module": "praisonai.acp"}
)
else:
return CheckResult(
id="acp_module",
title="ACP Module Available",
category=CheckCategory.TOOLS,
status=CheckStatus.WARN,
message="ACP module not found",
details={"hint": "ACP module should be part of praisonai package"}
remediation="ACP module should be part of praisonai package"
)
except Exception as e:
return CheckResult(
id="acp_module",
title="ACP Module Available",
category=CheckCategory.TOOLS,
status=CheckStatus.FAIL,
message=f"Error checking ACP module: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
@@ -49,7 +59,7 @@ def check_acp_module() -> CheckResult:
category=CheckCategory.TOOLS,
description="Check if agent-client-protocol SDK is installed"
)
def check_acp_sdk() -> CheckResult:
def check_acp_sdk(config=None) -> CheckResult:
"""Check if ACP SDK is available."""
try:
import importlib.util
@@ -57,21 +67,30 @@ def check_acp_sdk() -> CheckResult:
if spec is not None:
return CheckResult(
id="acp_sdk",
title="ACP SDK Available",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="ACP SDK (agent-client-protocol) is installed",
details={"package": "agent-client-protocol"}
metadata={"package": "agent-client-protocol"}
)
else:
return CheckResult(
status=CheckStatus.INFO,
id="acp_sdk",
title="ACP SDK Available",
category=CheckCategory.TOOLS,
status=CheckStatus.SKIP,
message="ACP SDK not installed (optional)",
details={"hint": "Install with: pip install agent-client-protocol"}
remediation="Install with: pip install agent-client-protocol"
)
except Exception as e:
return CheckResult(
id="acp_sdk",
title="ACP SDK Available",
category=CheckCategory.TOOLS,
status=CheckStatus.FAIL,
message=f"Error checking ACP SDK: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
@@ -81,27 +100,36 @@ def check_acp_sdk() -> CheckResult:
category=CheckCategory.TOOLS,
description="Check if ACP server can be imported"
)
def check_acp_server() -> CheckResult:
def check_acp_server(config=None) -> CheckResult:
"""Check if ACP server can be imported."""
try:
from praisonai.acp import ACPServer # noqa: F401
return CheckResult(
id="acp_server",
title="ACP Server Import",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="ACP server can be imported",
details={"class": "ACPServer"}
metadata={"class": "ACPServer"}
)
except ImportError as e:
return CheckResult(
id="acp_server",
title="ACP Server Import",
category=CheckCategory.TOOLS,
status=CheckStatus.WARN,
message=f"ACP server import failed: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
except Exception as e:
return CheckResult(
id="acp_server",
title="ACP Server Import",
category=CheckCategory.TOOLS,
status=CheckStatus.FAIL,
message=f"Error importing ACP server: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
@@ -111,20 +139,21 @@ def check_acp_server() -> CheckResult:
category=CheckCategory.CONFIG,
description="Check ACP configuration"
)
def check_acp_config() -> CheckResult:
def check_acp_config(config=None) -> CheckResult:
"""Check ACP configuration."""
import os
config = {
acp_conf = {
"approval_mode": os.environ.get("PRAISONAI_APPROVAL_MODE", "manual"),
"allow_write": os.environ.get("PRAISONAI_ALLOW_WRITE", "false"),
"allow_shell": os.environ.get("PRAISONAI_ALLOW_SHELL", "false"),
}
return CheckResult(
id="acp_config",
title="ACP Configuration",
category=CheckCategory.CONFIG,
status=CheckStatus.PASS,
message=f"ACP configured with approval_mode={config['approval_mode']}",
details=config
message=f"ACP configured with approval_mode={acp_conf['approval_mode']}",
metadata=acp_conf
)
@@ -135,7 +164,7 @@ def check_acp_config() -> CheckResult:
description="Check if ACP runtime can start",
requires_deep=True
)
def check_acp_runtime() -> CheckResult:
def check_acp_runtime(config=None) -> CheckResult:
"""Check if ACP runtime can start."""
try:
from praisonai.cli.features.interactive_runtime import create_runtime
@@ -150,88 +179,39 @@ def check_acp_runtime() -> CheckResult:
await runtime.start()
ready = runtime.acp_ready
error = runtime._acp_state.error
read_only = runtime.read_only
return ready, error, read_only
return ready, error
finally:
await runtime.stop()
ready, error, read_only = asyncio.run(_check())
ready, error = asyncio.run(_check())
if ready:
return CheckResult(
id="acp_runtime",
title="ACP Runtime Check",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="ACP runtime started successfully",
details={"ready": True, "read_only": read_only}
metadata={"ready": True}
)
else:
return CheckResult(
id="acp_runtime",
title="ACP Runtime Check",
category=CheckCategory.TOOLS,
status=CheckStatus.WARN,
message=f"ACP runtime failed to start: {error}",
details={"ready": False, "error": error, "read_only": read_only}
metadata={"ready": False, "error": str(error)}
)
except Exception as e:
return CheckResult(
id="acp_runtime",
title="ACP Runtime Check",
category=CheckCategory.TOOLS,
status=CheckStatus.FAIL,
message=f"ACP runtime check failed: {e}",
details={"error": str(e)}
)
@register_check(
id="interactive_runtime",
title="Interactive Runtime Check",
category=CheckCategory.TOOLS,
description="Check if full interactive runtime can start",
requires_deep=True
)
def check_interactive_runtime() -> CheckResult:
"""Check if full interactive runtime can start."""
try:
from praisonai.cli.features.interactive_runtime import create_runtime
async def _check():
runtime = create_runtime(
workspace=".",
lsp=True,
acp=True
)
try:
await runtime.start()
status = runtime.get_status()
return status
finally:
await runtime.stop()
status = asyncio.run(_check())
lsp_ready = status.get("lsp", {}).get("ready", False)
acp_ready = status.get("acp", {}).get("ready", False)
if lsp_ready and acp_ready:
return CheckResult(
status=CheckStatus.PASS,
message="Interactive runtime fully operational",
details=status
)
elif lsp_ready or acp_ready:
return CheckResult(
status=CheckStatus.WARN,
message="Interactive runtime partially operational",
details=status
)
else:
return CheckResult(
status=CheckStatus.FAIL,
message="Interactive runtime failed to start",
details=status
)
except Exception as e:
return CheckResult(
status=CheckStatus.FAIL,
message=f"Interactive runtime check failed: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
@@ -4,6 +4,7 @@ LSP health checks for PraisonAI Doctor.
import asyncio
import logging
import shutil
from ..models import CheckCategory, CheckResult, CheckStatus
from ..registry import register_check
@@ -17,7 +18,7 @@ logger = logging.getLogger(__name__)
category=CheckCategory.TOOLS,
description="Check if LSP module is installed"
)
def check_lsp_module() -> CheckResult:
def check_lsp_module(config=None) -> CheckResult:
"""Check if LSP module is available."""
try:
import importlib.util
@@ -25,21 +26,30 @@ def check_lsp_module() -> CheckResult:
if spec is not None:
return CheckResult(
id="lsp_module",
title="LSP Module Available",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="LSP module is available",
details={"module": "praisonaiagents.lsp"}
metadata={"module": "praisonaiagents.lsp"}
)
else:
return CheckResult(
id="lsp_module",
title="LSP Module Available",
category=CheckCategory.TOOLS,
status=CheckStatus.WARN,
message="LSP module not found",
details={"hint": "Install praisonaiagents with LSP support"}
remediation="Install praisonaiagents with LSP support"
)
except Exception as e:
return CheckResult(
id="lsp_module",
title="LSP Module Available",
category=CheckCategory.TOOLS,
status=CheckStatus.FAIL,
message=f"Error checking LSP module: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
@@ -49,27 +59,36 @@ def check_lsp_module() -> CheckResult:
category=CheckCategory.TOOLS,
description="Check if LSP client can be imported"
)
def check_lsp_client() -> CheckResult:
def check_lsp_client(config=None) -> CheckResult:
"""Check if LSP client can be imported."""
try:
from praisonaiagents.lsp import LSPClient # noqa: F401
return CheckResult(
id="lsp_client",
title="LSP Client Import",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="LSP client can be imported",
details={"class": "LSPClient"}
metadata={"class": "LSPClient"}
)
except ImportError as e:
return CheckResult(
id="lsp_client",
title="LSP Client Import",
category=CheckCategory.TOOLS,
status=CheckStatus.WARN,
message=f"LSP client import failed: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
except Exception as e:
return CheckResult(
id="lsp_client",
title="LSP Client Import",
category=CheckCategory.TOOLS,
status=CheckStatus.FAIL,
message=f"Error importing LSP client: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
@@ -79,11 +98,8 @@ def check_lsp_client() -> CheckResult:
category=CheckCategory.TOOLS,
description="Check if Python language server is available"
)
def check_lsp_server_python() -> CheckResult:
def check_lsp_server_python(config=None) -> CheckResult:
"""Check if Python language server is available."""
import shutil
# Check for common Python language servers
servers = [
("pyright-langserver", "pyright"),
("pylsp", "python-lsp-server"),
@@ -97,18 +113,21 @@ def check_lsp_server_python() -> CheckResult:
if found:
return CheckResult(
id="lsp_server_python",
title="Python LSP Server",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message=f"Python LSP server available: {found[0]['command']}",
details={"servers": found}
metadata={"servers": found}
)
else:
return CheckResult(
id="lsp_server_python",
title="Python LSP Server",
category=CheckCategory.TOOLS,
status=CheckStatus.WARN,
message="No Python LSP server found",
details={
"hint": "Install with: npm install -g pyright OR pip install python-lsp-server",
"checked": [s[0] for s in servers]
}
remediation="Install with: npm install -g pyright OR pip install python-lsp-server"
)
@@ -118,30 +137,34 @@ def check_lsp_server_python() -> CheckResult:
category=CheckCategory.TOOLS,
description="Check if TypeScript language server is available"
)
def check_lsp_server_typescript() -> CheckResult:
def check_lsp_server_typescript(config=None) -> CheckResult:
"""Check if TypeScript language server is available."""
import shutil
# Check for TypeScript language server
if shutil.which("typescript-language-server"):
return CheckResult(
id="lsp_server_typescript",
title="TypeScript LSP Server",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="TypeScript LSP server available",
details={"command": "typescript-language-server"}
metadata={"command": "typescript-language-server"}
)
elif shutil.which("tsserver"):
return CheckResult(
id="lsp_server_typescript",
title="TypeScript LSP Server",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="TypeScript server available (tsserver)",
details={"command": "tsserver"}
metadata={"command": "tsserver"}
)
else:
return CheckResult(
status=CheckStatus.INFO,
id="lsp_server_typescript",
title="TypeScript LSP Server",
category=CheckCategory.TOOLS,
status=CheckStatus.SKIP,
message="TypeScript LSP server not found (optional)",
details={
"hint": "Install with: npm install -g typescript-language-server typescript"
}
remediation="Install with: npm install -g typescript-language-server typescript"
)
@@ -152,7 +175,7 @@ def check_lsp_server_typescript() -> CheckResult:
description="Check if LSP runtime can start",
requires_deep=True
)
def check_lsp_runtime() -> CheckResult:
def check_lsp_runtime(config=None) -> CheckResult:
"""Check if LSP runtime can start."""
try:
from praisonai.cli.features.interactive_runtime import create_runtime
@@ -175,22 +198,31 @@ def check_lsp_runtime() -> CheckResult:
if ready:
return CheckResult(
id="lsp_runtime",
title="LSP Runtime Check",
category=CheckCategory.TOOLS,
status=CheckStatus.PASS,
message="LSP runtime started successfully",
details={"ready": True}
metadata={"ready": True}
)
else:
return CheckResult(
id="lsp_runtime",
title="LSP Runtime Check",
category=CheckCategory.TOOLS,
status=CheckStatus.WARN,
message=f"LSP runtime failed to start: {error}",
details={"ready": False, "error": error}
metadata={"ready": False, "error": str(error)}
)
except Exception as e:
return CheckResult(
id="lsp_runtime",
title="LSP Runtime Check",
category=CheckCategory.TOOLS,
status=CheckStatus.FAIL,
message=f"LSP runtime check failed: {e}",
details={"error": str(e)}
metadata={"error": str(e)}
)
@@ -29,6 +29,10 @@ class QueueManager:
- Event handling
"""
# Runtime tools registry - stores tools that can't be serialized to JSON
# Key: run_id or "default", Value: list of tool callables
_tools_registry: Dict[str, list] = {}
def __init__(
self,
config: Optional[QueueConfig] = None,
@@ -36,6 +40,7 @@ class QueueManager:
on_complete: Optional[Callable[[str, QueuedRun], Coroutine[Any, Any, None]]] = None,
on_error: Optional[Callable[[str, Exception], Coroutine[Any, Any, None]]] = None,
on_event: Optional[Callable[[QueueEvent], Coroutine[Any, Any, None]]] = None,
default_tools: Optional[list] = None,
):
"""
Initialize queue manager.
@@ -46,6 +51,7 @@ class QueueManager:
on_complete: Callback when run completes.
on_error: Callback when run fails.
on_event: Callback for queue events.
default_tools: Default tools to use for all runs (stored in runtime registry).
"""
self.config = config or QueueConfig()
@@ -70,6 +76,10 @@ class QueueManager:
# Session tracking
self._current_session_id: Optional[str] = None
# Store default tools in registry
if default_tools:
QueueManager._tools_registry["default"] = default_tools
async def start(self, recover: bool = True) -> None:
"""
@@ -157,6 +167,7 @@ class QueueManager:
workspace: Optional[str] = None,
config: Optional[Dict[str, Any]] = None,
run_id: Optional[str] = None,
chat_history: Optional[List[Dict[str, str]]] = None,
) -> str:
"""
Submit a new run to the queue.
@@ -169,6 +180,7 @@ class QueueManager:
workspace: Workspace path.
config: Additional configuration.
run_id: Optional specific run ID.
chat_history: Previous chat messages for context continuity.
Returns:
The run ID.
@@ -181,6 +193,7 @@ class QueueManager:
workspace=workspace or os.getcwd(),
config=config or {},
max_retries=self.config.default_max_retries,
chat_history=chat_history or [],
)
if run_id:
@@ -225,6 +238,10 @@ class QueueManager:
"""Resume a paused run."""
return await self.scheduler.resume(run_id)
async def update_input(self, run_id: str, new_input: str) -> bool:
"""Update the input content of a queued run."""
return await self.scheduler.update_input(run_id, new_input)
def get_run(self, run_id: str) -> Optional[QueuedRun]:
"""Get a run by ID."""
return self.scheduler.get_run(run_id)
@@ -393,3 +410,22 @@ class QueueManager:
def running_count(self) -> int:
"""Number of running runs."""
return self.scheduler.running_count
@classmethod
def get_tools_for_run(cls, run_id: str) -> list:
"""
Get tools for a specific run from the registry.
Falls back to default tools if no run-specific tools are registered.
"""
return cls._tools_registry.get(run_id) or cls._tools_registry.get("default", [])
@classmethod
def register_tools(cls, run_id: str, tools: list) -> None:
"""Register tools for a specific run."""
cls._tools_registry[run_id] = tools
@classmethod
def unregister_tools(cls, run_id: str) -> None:
"""Unregister tools for a specific run."""
cls._tools_registry.pop(run_id, None)
@@ -85,6 +85,9 @@ class QueuedRun:
# Configuration
config: Dict[str, Any] = field(default_factory=dict)
# Chat history for session continuity
chat_history: List[Dict[str, str]] = field(default_factory=list)
# Streaming state
output_chunks: List[str] = field(default_factory=list)
@@ -302,6 +302,40 @@ class QueueScheduler:
"""Clear a cancellation token."""
self._cancel_tokens.discard(run_id)
async def update_input(self, run_id: str, new_input: str) -> bool:
"""
Update the input content of a queued run.
Only works for runs in QUEUED state.
Args:
run_id: The run ID to update.
new_input: The new input content.
Returns:
True if updated, False if not found or not editable.
"""
async with self._lock:
run = self._all_runs.get(run_id)
if run is None:
return False
if run.state != RunState.QUEUED:
logger.warning(f"Cannot edit run {run_id} in state {run.state}")
return False
run.input_content = new_input
logger.debug(f"Updated input for run {run_id}")
self._emit_event(QueueEvent(
event_type="run_updated",
run_id=run_id,
data={"new_input": new_input[:50]}
))
return True
async def retry(self, run_id: str) -> Optional[str]:
"""
Retry a failed run.
@@ -210,20 +210,34 @@ class WorkerPool:
try:
# Import agent lazily to avoid circular imports
from praisonaiagents import Agent
from .manager import QueueManager
# Get agent configuration
agent_config = run.config.get("agent_config", {})
agent_name = run.agent_name or agent_config.get("name", "Assistant")
# Create agent
# Get tools from runtime registry (not from config, as functions can't be serialized)
tools = QueueManager.get_tools_for_run(run.run_id)
# Create agent with session_id for history persistence
# Agent automatically restores history from JSON store when session_id is provided
# Note: Agent uses 'llm' parameter, not 'model'
agent = Agent(
name=agent_name,
instructions=agent_config.get("instructions", "You are a helpful assistant."),
model=agent_config.get("model"),
tools=agent_config.get("tools", []),
llm=agent_config.get("model"),
tools=tools,
verbose=agent_config.get("verbose", False),
session_id=agent_config.get("session_id") or run.session_id, # Use session for history
)
# Legacy: Inject chat history if provided (for backward compatibility)
# This is no longer needed as Agent now has built-in JSON persistence
# but we keep it for cases where chat_history is explicitly passed
if run.chat_history and not agent.chat_history:
agent.chat_history = list(run.chat_history)
logger.debug(f"Injected {len(run.chat_history)} messages from run.chat_history (legacy)")
# Check for cancellation before starting
if self.scheduler.is_cancelled(run.run_id):
logger.debug(f"Run {run.run_id} was cancelled before execution")
+259 -25
View File
@@ -13,12 +13,12 @@ from typing import Any, Dict, List, Optional
try:
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.screen import Screen
from textual import events
from textual import work
TEXTUAL_AVAILABLE = True
except ImportError:
TEXTUAL_AVAILABLE = False
App = object
work = None
logger = logging.getLogger(__name__)
@@ -28,10 +28,13 @@ if TEXTUAL_AVAILABLE:
from .screens.queue import QueueScreen
from .screens.settings import SettingsScreen
from .screens.session import SessionScreen
from .screens.help import HelpScreen
from .widgets.chat import ChatMessage
from .widgets.status import StatusInfo
from .widgets.queue_panel import QueueItem
from ..queue import QueueManager, QueueConfig, QueuedRun, RunPriority
from .session_store import SessionStore
from praisonai.cli.session import get_session_store, UnifiedSession
class TUIApp(App):
"""
@@ -54,9 +57,12 @@ if TEXTUAL_AVAILABLE:
}
"""
# Safe default bindings - Ctrl keys only at app level for emergency exit
# MainScreen handles all other bindings with safe defaults
BINDINGS = [
Binding("ctrl+q", "quit", "Quit", show=True, priority=True),
Binding("ctrl+c", "cancel", "Cancel", show=True),
# Emergency quit - kept at app level for reliability
Binding("ctrl+q", "quit", "Quit", show=False, priority=True),
Binding("ctrl+c", "cancel", "Cancel", show=False),
]
SCREENS = {
@@ -64,6 +70,7 @@ if TEXTUAL_AVAILABLE:
"queue": QueueScreen,
"settings": SettingsScreen,
"sessions": SessionScreen,
"help": HelpScreen,
}
def __init__(
@@ -93,6 +100,10 @@ if TEXTUAL_AVAILABLE:
self.queue_config = queue_config or QueueConfig()
self.queue_manager: Optional[QueueManager] = None
# Session store for chat history persistence (uses UnifiedSession)
self._session_store = get_session_store()
self._unified_session = self._session_store.get_or_create(self.session_id)
# State
self._current_run_id: Optional[str] = None
self._streaming_content: str = ""
@@ -154,16 +165,25 @@ if TEXTUAL_AVAILABLE:
"cost": self._cmd_cost,
"exit": self._cmd_exit,
"quit": self._cmd_exit,
# Additional commands
"tokens": self._cmd_tokens,
"plan": self._cmd_plan,
"map": self._cmd_map,
"undo": self._cmd_undo,
"diff": self._cmd_diff,
"commit": self._cmd_commit,
"tools": self._cmd_tools,
}
async def on_mount(self) -> None:
"""Handle app mount."""
# Initialize queue manager
# Initialize queue manager with default tools (stored in runtime registry)
self.queue_manager = QueueManager(
config=self.queue_config,
on_output=self._handle_output,
on_complete=self._handle_complete,
on_error=self._handle_error,
default_tools=self.agent_config.get("tools", []),
)
await self.queue_manager.start(recover=True)
@@ -172,6 +192,9 @@ if TEXTUAL_AVAILABLE:
# Push main screen
await self.push_screen("main")
# Update tools panel with available tools
self._update_tools_panel()
# Update status
self._update_status()
@@ -186,23 +209,45 @@ if TEXTUAL_AVAILABLE:
# Event handlers
async def on_main_screen_message_submitted(
def on_main_screen_message_submitted(
self, event: MainScreen.MessageSubmitted
) -> None:
"""Handle message submission from main screen."""
content = event.content
"""Handle message submission - dispatch to worker for non-blocking execution."""
# Use run_worker to avoid blocking the UI
self.run_worker(
self._process_message_submission(event.content),
exclusive=False, # Allow multiple messages to queue
exit_on_error=False,
)
@work(exclusive=False, exit_on_error=False)
async def _process_message_submission(self, content: str) -> None:
"""Process message submission in background worker.
# Add user message to chat
Using @work decorator ensures the UI remains responsive.
User can type while agent is processing.
"""
# Add user message to chat display
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_user_message(content)
main_screen.set_processing(True)
# Submit to queue
# Add user message to session store for history persistence
self.session_store.add_user_message(self.session_id, content)
# Get chat history for context continuity
chat_history = self.session_store.get_chat_history(self.session_id, max_messages=50)
# Submit to queue with chat history
# Note: tools are NOT included in config (they can't be JSON serialized)
# Instead, they are stored in QueueManager._tools_registry and retrieved by worker
try:
run_id = await self.queue_manager.submit(
input_content=content,
agent_name=self.agent_config.get("name", "Assistant"),
session_id=self.session_id, # Pass session_id for history
chat_history=chat_history, # Pass previous messages for context
config={
"agent_config": {
"name": self.agent_config.get("name", "Assistant"),
@@ -211,8 +256,8 @@ if TEXTUAL_AVAILABLE:
"You are a helpful AI assistant."
),
"model": self.model,
"tools": self.agent_config.get("tools", []),
"verbose": False,
"session_id": self.session_id, # Pass to agent for history
}
}
)
@@ -220,6 +265,9 @@ if TEXTUAL_AVAILABLE:
self._current_run_id = run_id
self._streaming_content = ""
# IMMEDIATELY update queue panel - increment the moment message is queued
self._update_queue_panel_live()
# Add streaming placeholder
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(
@@ -239,6 +287,7 @@ if TEXTUAL_AVAILABLE:
)
self._update_status()
self._update_queue_panel_live()
async def on_main_screen_command_executed(
self, event: MainScreen.CommandExecuted
@@ -323,6 +372,22 @@ if TEXTUAL_AVAILABLE:
self.queue_manager.set_session(self.session_id)
self._update_status()
async def on_queue_panel_widget_edit_requested(
self, event
) -> None:
"""Handle queue item edit request."""
from .widgets.queue_panel import QueuePanelWidget
if isinstance(event, QueuePanelWidget.EditRequested):
success = await self.queue_manager.update_input(event.run_id, event.new_content)
if success:
self._update_queue_panel_live()
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(
content=f"Updated queue item {event.run_id[:8]}",
agent_name="System",
)
# Queue callbacks
async def _handle_output(self, run_id: str, chunk: str) -> None:
@@ -338,14 +403,17 @@ if TEXTUAL_AVAILABLE:
async def _handle_complete(self, run_id: str, run: QueuedRun) -> None:
"""Handle run completion."""
output_content = run.output_content or self._streaming_content
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.complete_streaming(
run_id,
run.output_content or self._streaming_content
)
await main_screen.complete_streaming(run_id, output_content)
main_screen.set_processing(False)
# Store assistant response in session store for history persistence
if output_content and run.session_id:
self.session_store.add_assistant_message(run.session_id, output_content, run_id)
# Update metrics
if run.metrics:
self._total_tokens += run.metrics.get("tokens", 0)
@@ -356,6 +424,7 @@ if TEXTUAL_AVAILABLE:
self._streaming_content = ""
self._update_status()
self._update_queue_panel_live()
async def _handle_error(self, run_id: str, error: Exception) -> None:
"""Handle run error."""
@@ -369,6 +438,7 @@ if TEXTUAL_AVAILABLE:
self._streaming_content = ""
self._update_status()
self._update_queue_panel_live()
# Command handlers
@@ -388,18 +458,23 @@ if TEXTUAL_AVAILABLE:
- `/cost` - Show cost summary
- `/exit` or `/quit` - Exit TUI
**Keyboard Shortcuts:**
**Keyboard Shortcuts (Safe Defaults):**
- `Ctrl+Enter` - Send message
- `Ctrl+C` - Cancel current operation
- `Ctrl+Q` - Quit
- `Ctrl+L` - Clear screen
- `F1` - Help
- `F2` - Toggle queue panel
- `F3` - Settings
- `F5` - Clear chat
- `Tab` - Cycle focus
- `Enter` - Send message
- `Shift+Enter` - New line
- `q` - Quit (when not typing)
- `:` - Command mode
- `?` - Help
- `Esc` - Cancel/close
**Command Mode:**
Press `:` then type a command:
- `:quit` or `:q` - Quit
- `:clear` or `:cl` - Clear chat
- `:help` or `:h` - Help
- `:tools` or `:t` - Toggle tools
- `:queue` or `:qu` - Toggle queue
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
@@ -476,6 +551,8 @@ if TEXTUAL_AVAILABLE:
async def _cmd_sessions(self, args: str) -> None:
"""Show sessions."""
await self.push_screen("sessions")
# Load and display sessions
await self._update_sessions_screen()
async def _cmd_cost(self, args: str) -> None:
"""Show cost summary."""
@@ -494,6 +571,115 @@ if TEXTUAL_AVAILABLE:
"""Exit TUI."""
self.exit()
async def _cmd_tokens(self, args: str) -> None:
"""Show token usage breakdown."""
msg = f"""
**Token Usage:**
- Total Tokens: {self._total_tokens:,}
- Estimated Cost: ${self._total_cost:.4f}
- Session: {self.session_id}
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(content=msg, agent_name="System")
async def _cmd_plan(self, args: str) -> None:
"""Show or create a plan."""
msg = """
**Plan Command:**
The /plan command is used to create or view task plans.
Currently, plans are managed through the agent's task execution.
Usage:
- `/plan` - View current plan
- `/plan <task>` - Create a plan for a task
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(content=msg, agent_name="System")
async def _cmd_map(self, args: str) -> None:
"""Show repository map."""
msg = """
**Repository Map:**
The /map command shows a map of the repository structure.
Use the file tools to explore the codebase.
Available tools:
- `acp_list_files` - List files in a directory
- `acp_read_file` - Read file contents
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(content=msg, agent_name="System")
async def _cmd_undo(self, args: str) -> None:
"""Undo last change."""
msg = """
**Undo:**
The /undo command reverts the last file change.
Use git commands or the agent to manage file changes.
Tip: Ask the agent to "undo the last change" or use git.
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(content=msg, agent_name="System")
async def _cmd_diff(self, args: str) -> None:
"""Show diff of changes."""
msg = """
**Diff:**
The /diff command shows changes made to files.
Use git diff or ask the agent to show changes.
Tip: Ask the agent "show me the diff" or use `git diff`.
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(content=msg, agent_name="System")
async def _cmd_commit(self, args: str) -> None:
"""Commit changes."""
msg = """
**Commit:**
The /commit command creates a git commit.
Use git commands or ask the agent to commit changes.
Tip: Ask the agent to "commit the changes with message X".
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(content=msg, agent_name="System")
async def _cmd_tools(self, args: str) -> None:
"""Show available tools."""
tools = self.agent_config.get("tools", [])
tool_names = []
for tool in tools:
if hasattr(tool, '__name__'):
tool_names.append(tool.__name__)
elif hasattr(tool, 'name'):
tool_names.append(tool.name)
else:
tool_names.append(str(tool)[:30])
msg = f"""
**Available Tools ({len(tools)}):**
{chr(10).join(f'- {name}' for name in tool_names[:20])}
{"..." if len(tool_names) > 20 else ""}
"""
main_screen = self.screen
if isinstance(main_screen, MainScreen):
await main_screen.add_assistant_message(content=msg, agent_name="System")
# Helper methods
def _update_status(self) -> None:
@@ -510,6 +696,19 @@ if TEXTUAL_AVAILABLE:
is_processing=self._current_run_id is not None,
))
def _update_queue_panel_live(self) -> None:
"""Update queue panel on MainScreen with live counts."""
from .widgets.queue_panel import QueuePanelWidget
main_screen = self.screen
if isinstance(main_screen, MainScreen):
try:
queue_panel = main_screen.query_one("#queue-panel", QueuePanelWidget)
# Update counts immediately
queue_panel.queued_count = self.queue_manager.queued_count if self.queue_manager else 0
queue_panel.running_count = self.queue_manager.running_count if self.queue_manager else 0
except Exception:
pass
def _update_queue_screen(self) -> None:
"""Update queue screen if visible."""
if isinstance(self.screen, QueueScreen):
@@ -527,6 +726,41 @@ if TEXTUAL_AVAILABLE:
for r in runs
])
async def _update_sessions_screen(self) -> None:
"""Update sessions screen with session list."""
if isinstance(self.screen, SessionScreen):
# Get sessions from queue manager or session store
sessions = []
if self.queue_manager:
try:
# Try to get sessions from the persistence layer
from ..queue.persistence import QueuePersistence
persistence = QueuePersistence()
sessions = persistence.list_sessions(limit=50)
except Exception as e:
logger.debug(f"Could not load sessions: {e}")
# Fallback: show current session only
sessions = [{
"session_id": self.session_id,
"created_at": "-",
"updated_at": "-",
"run_count": self.queue_manager.queued_count + self.queue_manager.running_count,
}]
self.screen.update_sessions(sessions)
def _update_tools_panel(self) -> None:
"""Update tools panel with available tools."""
from .widgets.tool_panel import ToolPanelWidget
main_screen = self.screen
if isinstance(main_screen, MainScreen):
try:
tool_panel = main_screen.query_one("#tool-panel", ToolPanelWidget)
tools = self.agent_config.get("tools", [])
tool_panel.set_available_tools(tools)
except Exception:
pass
def action_quit(self) -> None:
"""Quit the application."""
self.exit()
@@ -0,0 +1,150 @@
"""
TUI Configuration for PraisonAI.
Handles keyboard shortcuts and display settings with safe defaults.
"""
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional
@dataclass
class TUIConfig:
"""
Configuration for TUI behavior.
Safe defaults:
- Ctrl keys disabled by default (conflict with IDEs/terminals)
- Function keys disabled by default (conflict with IDEs/OS)
- Single-character shortcuts enabled by default
- Command mode (:) enabled by default
"""
# Keyboard configuration
enable_ctrl_keys: bool = False # Ctrl+Q, Ctrl+L, etc.
enable_fn_keys: bool = False # F1-F12
enable_single_char: bool = True # q, l, etc. (when not in input)
enable_command_mode: bool = True # :quit, :clear, etc.
leader_key: str = ":" # Command mode prefix
# Display configuration
auto_scroll: bool = True
show_tools_panel: bool = True
show_queue_panel: bool = True
@classmethod
def from_env(cls) -> "TUIConfig":
"""Create config from environment variables."""
config = cls()
# Check env vars for enabling Ctrl keys (opt-in)
if os.environ.get("PRAISONAI_TUI_CTRL_KEYS", "").lower() in ("1", "true", "yes"):
config.enable_ctrl_keys = True
# Check env vars for enabling Function keys (opt-in)
if os.environ.get("PRAISONAI_TUI_FN_KEYS", "").lower() in ("1", "true", "yes"):
config.enable_fn_keys = True
# Check for disabling single-char shortcuts
if os.environ.get("PRAISONAI_TUI_NO_SINGLE_CHAR", "").lower() in ("1", "true", "yes"):
config.enable_single_char = False
# Check for custom leader key
leader = os.environ.get("PRAISONAI_TUI_LEADER", "")
if leader and len(leader) == 1:
config.leader_key = leader
return config
@classmethod
def from_cli_args(
cls,
enable_ctrl_keys: bool = False,
enable_fn_keys: bool = False,
leader_key: Optional[str] = None,
) -> "TUIConfig":
"""Create config from CLI arguments, merged with env."""
config = cls.from_env()
# CLI args override env
if enable_ctrl_keys:
config.enable_ctrl_keys = True
if enable_fn_keys:
config.enable_fn_keys = True
if leader_key and len(leader_key) == 1:
config.leader_key = leader_key
return config
# Command mode commands
COMMANDS = {
"quit": {"aliases": ["q", "exit"], "description": "Quit the TUI"},
"clear": {"aliases": ["cl"], "description": "Clear the chat history"},
"help": {"aliases": ["h", "?"], "description": "Show help"},
"tools": {"aliases": ["t"], "description": "Toggle tools panel"},
"queue": {"aliases": ["qu"], "description": "Toggle queue panel"},
"settings": {"aliases": ["set"], "description": "Open settings"},
"cancel": {"aliases": ["c"], "description": "Cancel current operation"},
"sessions": {"aliases": ["sess"], "description": "Manage sessions"},
}
def get_command(input_str: str) -> Optional[str]:
"""
Parse command input and return the canonical command name.
Args:
input_str: The command string (without leader key)
Returns:
Canonical command name or None if not found
"""
input_str = input_str.strip().lower()
# Check direct match
if input_str in COMMANDS:
return input_str
# Check aliases
for cmd, info in COMMANDS.items():
if input_str in info.get("aliases", []):
return cmd
return None
def get_help_text() -> str:
"""Get formatted help text for all commands."""
lines = [
"PraisonAI TUI Commands",
"=" * 40,
"",
"Command Mode (press : to enter):",
]
for cmd, info in COMMANDS.items():
aliases = ", ".join(info.get("aliases", []))
desc = info.get("description", "")
if aliases:
lines.append(f" :{cmd} (or :{aliases}) - {desc}")
else:
lines.append(f" :{cmd} - {desc}")
lines.extend([
"",
"Single-key shortcuts (when not typing):",
" q - Quit",
" l - Clear screen",
" ? - Help",
" / - Search/filter",
"",
"Input shortcuts:",
" Enter - Send message",
" Shift+Enter - New line",
" Escape - Cancel",
" Up/Down - History navigation",
])
return "\n".join(lines)
@@ -0,0 +1,157 @@
"""
Help Screen for PraisonAI TUI.
Displays keyboard shortcuts and usage information.
"""
from typing import Optional
try:
from textual.screen import Screen
from textual.containers import Vertical, Container
from textual.widgets import Static, Footer, Button
from textual.binding import Binding
TEXTUAL_AVAILABLE = True
except ImportError:
TEXTUAL_AVAILABLE = False
Screen = object
if TEXTUAL_AVAILABLE:
from rich.text import Text
from rich.panel import Panel
from rich.table import Table
class HelpScreen(Screen):
"""
Help screen showing keyboard shortcuts and usage.
"""
BINDINGS = [
Binding("escape", "dismiss", "Close", show=True),
Binding("q", "dismiss", "Close", show=True),
]
DEFAULT_CSS = """
HelpScreen {
align: center middle;
}
HelpScreen #help-container {
width: 80;
height: auto;
max-height: 90%;
background: $surface;
border: solid $primary;
padding: 1 2;
}
HelpScreen #help-title {
text-align: center;
text-style: bold;
margin-bottom: 1;
}
HelpScreen #close-button {
margin-top: 1;
width: 100%;
}
"""
def compose(self):
"""Compose the help screen."""
with Container(id="help-container"):
yield Static("PraisonAI TUI Help", id="help-title")
yield Static(self._build_help_content())
yield Button("Close (Esc)", id="close-button", variant="primary")
def _build_help_content(self) -> Text:
"""Build the help content."""
content = Text()
# Safe keyboard shortcuts section
content.append("\n📋 Keyboard Shortcuts (Safe Defaults)\n", style="bold cyan")
content.append("─" * 40 + "\n", style="dim")
shortcuts = [
("\\", "Show command popup"),
("@path", "Reference file (type freely)"),
("/", "Show command discovery"),
("Enter", "Send message"),
("Shift+Enter", "New line in message"),
("q", "Quit (when not typing)"),
("?", "Show this help"),
(":", "Enter command mode"),
("Escape", "Cancel/Close/Dismiss"),
("Tab", "Focus next element"),
("Up/Down", "Navigate history"),
]
for key, desc in shortcuts:
content.append(f" {key:<15}", style="yellow")
content.append(f" {desc}\n")
# Command mode section
content.append("\n⌨️ Command Mode (: prefix)\n", style="bold cyan")
content.append("─" * 40 + "\n", style="dim")
colon_cmds = [
(":quit, :q", "Quit application"),
(":clear, :cl", "Clear chat history"),
(":help, :h", "Show help"),
(":tools, :t", "Toggle tools panel"),
(":queue, :qu", "Toggle queue panel"),
(":settings", "Open settings"),
(":cancel", "Cancel current operation"),
]
for cmd, desc in colon_cmds:
content.append(f" {cmd:<15}", style="green")
content.append(f" {desc}\n")
# Slash commands section
content.append("\n💬 Slash Commands (/ prefix)\n", style="bold cyan")
content.append("─" * 40 + "\n", style="dim")
commands = [
("/help", "Show help"),
("/clear", "Clear chat"),
("/model", "Show/change model"),
("/queue", "Show queue status"),
("/cancel", "Cancel current run"),
("/cost", "Show cost summary"),
("/settings", "Open settings"),
("/sessions", "Manage sessions"),
("/exit", "Exit TUI"),
]
for cmd, desc in commands:
content.append(f" {cmd:<15}", style="green")
content.append(f" {desc}\n")
# Optional keys note
content.append("\n⚙️ Optional Keys (disabled by default)\n", style="bold cyan")
content.append("─" * 40 + "\n", style="dim")
content.append(" Ctrl keys: ", style="dim")
content.append("PRAISONAI_TUI_CTRL_KEYS=1\n", style="yellow")
content.append(" Fn keys: ", style="dim")
content.append("PRAISONAI_TUI_FN_KEYS=1\n", style="yellow")
return content
def on_button_pressed(self, event: Button.Pressed) -> None:
"""Handle button press."""
if event.button.id == "close-button":
self.dismiss()
def action_dismiss(self) -> None:
"""Dismiss the help screen."""
self.dismiss()
else:
class HelpScreen:
"""Placeholder when Textual is not available."""
def __init__(self, *args, **kwargs):
raise ImportError(
"Textual is required for TUI. Install with: pip install praisonai[tui]"
)
@@ -25,6 +25,9 @@ if TEXTUAL_AVAILABLE:
from ..widgets.status import StatusWidget, StatusInfo
from ..widgets.queue_panel import QueuePanelWidget
from ..widgets.tool_panel import ToolPanelWidget
from ..widgets.command_popup import CommandPopupWidget, get_default_commands
from ..widgets.file_popup import FilePopupWidget
from ..config import TUIConfig, get_command
class MainScreen(Screen):
"""
@@ -39,16 +42,18 @@ if TEXTUAL_AVAILABLE:
- Footer with keybindings
"""
# Safe default bindings - no Ctrl or Fn keys by default
# These work in VS Code, Windsurf, tmux, and plain terminals
BINDINGS = [
Binding("ctrl+q", "quit", "Quit", show=True),
Binding("ctrl+c", "cancel", "Cancel", show=True),
Binding("ctrl+l", "clear", "Clear", show=True),
Binding("f1", "help", "Help", show=True),
Binding("f2", "toggle_queue", "Queue", show=True),
Binding("f3", "settings", "Settings", show=True),
Binding("f5", "clear_chat", "Clear Chat", show=True),
# Single-character shortcuts (safe defaults)
Binding("q", "quit", "Quit", show=True, priority=True),
Binding("question_mark", "help", "Help", show=True),
Binding("backslash", "show_commands", "\\cmds", show=True),
Binding("colon", "command_mode", ":cmd", show=False),
Binding("slash", "search", "/search", show=False),
# Navigation
Binding("tab", "focus_next", "Next", show=False),
Binding("escape", "cancel_input", "Cancel", show=False),
Binding("escape", "cancel_or_dismiss", "Cancel", show=True),
]
DEFAULT_CSS = """
@@ -57,6 +62,7 @@ if TEXTUAL_AVAILABLE:
grid-size: 2;
grid-columns: 3fr 1fr;
grid-rows: 1 1fr auto 1;
layers: base popup;
}
MainScreen #status-bar {
@@ -84,6 +90,18 @@ if TEXTUAL_AVAILABLE:
MainScreen .sidebar-panel {
height: 1fr;
}
MainScreen #command-popup {
layer: popup;
dock: bottom;
margin: 0 2 2 2;
}
MainScreen #file-popup {
layer: popup;
dock: bottom;
margin: 0 2 2 2;
}
"""
class MessageSubmitted(Message):
@@ -107,6 +125,7 @@ if TEXTUAL_AVAILABLE:
self,
show_queue: bool = True,
show_tools: bool = True,
config: Optional[TUIConfig] = None,
name: Optional[str] = None,
id: Optional[str] = None,
classes: Optional[str] = None,
@@ -114,6 +133,15 @@ if TEXTUAL_AVAILABLE:
super().__init__(name=name, id=id, classes=classes)
self._show_queue = show_queue
self._show_tools = show_tools
self._config = config or TUIConfig.from_env()
self._command_mode = False
self._command_buffer = ""
self._command_popup_visible = False
self._file_popup_visible = False
self._workspace = None
# Dynamically add Ctrl/Fn bindings if enabled
self._setup_optional_bindings()
def compose(self):
"""Compose the screen."""
@@ -131,6 +159,21 @@ if TEXTUAL_AVAILABLE:
yield Footer()
def _setup_optional_bindings(self) -> None:
"""Setup optional Ctrl/Fn key bindings based on config."""
if self._config.enable_ctrl_keys:
# Add Ctrl key bindings (opt-in)
self._bindings.bind("ctrl+q", "quit", "^Q Quit", show=True)
self._bindings.bind("ctrl+c", "cancel", "^C Cancel", show=True)
self._bindings.bind("ctrl+l", "clear_chat", "^L Clear", show=True)
if self._config.enable_fn_keys:
# Add Function key bindings (opt-in)
self._bindings.bind("f1", "help", "F1 Help", show=True)
self._bindings.bind("f2", "toggle_queue", "F2 Queue", show=True)
self._bindings.bind("f3", "settings", "F3 Settings", show=True)
self._bindings.bind("f5", "clear_chat", "F5 Clear", show=True)
def on_mount(self) -> None:
"""Handle mount."""
# Focus composer
@@ -140,14 +183,52 @@ if TEXTUAL_AVAILABLE:
def on_composer_widget_submitted(self, event: ComposerWidget.Submitted) -> None:
"""Handle message submission."""
if event.is_command:
# Parse command
parts = event.content[1:].split(maxsplit=1)
# Parse command (supports both / and : prefix)
content = event.content
if content.startswith("/") or content.startswith(":"):
content = content[1:] # Remove prefix
parts = content.split(maxsplit=1)
command = parts[0] if parts else ""
args = parts[1] if len(parts) > 1 else ""
# Handle local screen commands first
if self._handle_local_command(command, args):
return
# Forward to app for other commands
self.post_message(self.CommandExecuted(command, args))
else:
self.post_message(self.MessageSubmitted(event.content))
def _handle_local_command(self, command: str, args: str) -> bool:
"""Handle commands that can be processed locally without app involvement."""
cmd = get_command(command)
if cmd == "quit":
self.app.exit()
return True
elif cmd == "clear":
self.action_clear_chat()
return True
elif cmd == "help":
self.action_help()
return True
elif cmd == "tools":
self.action_toggle_tools()
return True
elif cmd == "queue":
self.action_toggle_queue()
return True
elif cmd == "settings":
self.action_settings()
return True
elif cmd == "cancel":
self.action_cancel()
return True
return False # Not handled locally
def action_quit(self) -> None:
"""Quit the application."""
self.app.exit()
@@ -186,6 +267,183 @@ if TEXTUAL_AVAILABLE:
composer = self.query_one("#composer", ComposerWidget)
composer.action_cancel()
def action_command_mode(self) -> None:
"""Enter command mode - focus composer with : prefix."""
composer = self.query_one("#composer", ComposerWidget)
composer.focus_input()
composer.set_text(":")
def action_search(self) -> None:
"""Enter search mode - focus composer with / prefix."""
composer = self.query_one("#composer", ComposerWidget)
composer.focus_input()
composer.set_text("/")
def action_toggle_tools(self) -> None:
"""Toggle tools panel visibility."""
try:
tool_panel = self.query_one("#tool-panel", ToolPanelWidget)
tool_panel.display = not tool_panel.display
except Exception:
pass
def action_show_commands(self) -> None:
"""Show command popup (triggered by backslash)."""
if self._command_popup_visible:
return
self._command_popup_visible = True
# Create and mount command popup
popup = CommandPopupWidget(
commands=get_default_commands(),
id="command-popup",
)
self.mount(popup)
popup.focus_search()
def action_cancel_or_dismiss(self) -> None:
"""Cancel input or dismiss popup."""
if self._command_popup_visible:
self._dismiss_command_popup()
else:
self.action_cancel_input()
def _dismiss_command_popup(self) -> None:
"""Dismiss the command popup."""
if not self._command_popup_visible:
return
try:
popup = self.query_one("#command-popup", CommandPopupWidget)
popup.remove()
except Exception:
pass
self._command_popup_visible = False
# Return focus to composer
composer = self.query_one("#composer", ComposerWidget)
composer.focus_input()
def on_command_popup_widget_command_selected(
self, event: CommandPopupWidget.CommandSelected
) -> None:
"""Handle command selection from popup."""
self._dismiss_command_popup()
# Execute the selected command
if self._handle_local_command(event.command, event.args):
return
# Forward to app for other commands
self.post_message(self.CommandExecuted(event.command, event.args))
def on_command_popup_widget_dismissed(
self, event: CommandPopupWidget.Dismissed
) -> None:
"""Handle popup dismissal."""
self._dismiss_command_popup()
# Auto-trigger event handlers from ComposerWidget
def on_composer_widget_backslash_typed(
self, event: ComposerWidget.BackslashTyped
) -> None:
"""Handle backslash typed - auto-show command popup."""
# Clear the backslash from composer and show popup
composer = self.query_one("#composer", ComposerWidget)
composer.set_text("")
self.action_show_commands()
def on_composer_widget_at_typed(
self, event: ComposerWidget.AtTyped
) -> None:
"""Handle @ typed - DO NOT block typing.
MINIMUM VIABLE UX: User can freely type @path/to/file.
The popup is optional and must NOT steal focus or block input.
For now, we simply allow typing to continue uninterrupted.
"""
# DO NOT show popup that blocks typing
# User can manually type: @README.md, @src/main.py, etc.
pass
def on_composer_widget_slash_typed(
self, event: ComposerWidget.SlashTyped
) -> None:
"""Handle / typed - auto-show command popup with filter."""
if not self._command_popup_visible:
self._command_popup_visible = True
popup = CommandPopupWidget(
commands=get_default_commands(),
id="command-popup",
)
self.mount(popup)
# Set filter to current query
popup.filter_text = event.query
def _show_file_popup(self, query: str, at_pos: int) -> None:
"""Show file autocomplete popup."""
if self._file_popup_visible:
# Update existing popup
try:
popup = self.query_one("#file-popup", FilePopupWidget)
popup.set_query(query, at_pos)
except Exception:
pass
return
self._file_popup_visible = True
# Create and mount file popup
import os
popup = FilePopupWidget(
root_dir=self._workspace or os.getcwd(),
at_pos=at_pos,
id="file-popup",
)
self.mount(popup)
popup.set_query(query, at_pos)
def _dismiss_file_popup(self) -> None:
"""Dismiss the file popup."""
if not self._file_popup_visible:
return
try:
popup = self.query_one("#file-popup", FilePopupWidget)
popup.remove()
except Exception:
pass
self._file_popup_visible = False
# Return focus to composer
composer = self.query_one("#composer", ComposerWidget)
composer.focus_input()
def on_file_popup_widget_file_selected(
self, event: FilePopupWidget.FileSelected
) -> None:
"""Handle file selection from popup."""
self._dismiss_file_popup()
# Insert the file path into composer
composer = self.query_one("#composer", ComposerWidget)
current_text = composer.text
# Replace from @ position to end with selected path
new_text = current_text[:event.at_pos] + "@" + event.path
composer.set_text(new_text)
composer.focus_input()
def on_file_popup_widget_dismissed(
self, event: FilePopupWidget.Dismissed
) -> None:
"""Handle file popup dismissal."""
self._dismiss_file_popup()
# Public methods for updating UI
async def add_user_message(self, content: str) -> None:
@@ -0,0 +1,198 @@
"""
Session Store for PraisonAI TUI.
DEPRECATED: This module is deprecated in favor of the core SDK session store.
Use `praisonaiagents.session.DefaultSessionStore` instead, which provides:
- JSON-based persistence (survives restarts)
- File locking for multi-process safety
- Automatic integration with Agent class
This TUI-specific in-memory store is kept for backward compatibility only.
New code should use the core SDK session store.
Example:
from praisonaiagents.session import get_default_session_store
store = get_default_session_store()
store.add_user_message("session-id", "Hello")
history = store.get_chat_history("session-id")
Maintains chat history in memory for session persistence.
This allows the AI to remember previous messages within a session.
"""
import warnings
import logging
from dataclasses import dataclass, field
from typing import Dict, List, Optional
from datetime import datetime
logger = logging.getLogger(__name__)
@dataclass
class ChatMessage:
"""A single chat message."""
role: str # "user" or "assistant"
content: str
timestamp: datetime = field(default_factory=datetime.now)
run_id: Optional[str] = None
@dataclass
class Session:
"""A chat session with history."""
session_id: str
messages: List[ChatMessage] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
updated_at: datetime = field(default_factory=datetime.now)
def add_message(self, role: str, content: str, run_id: Optional[str] = None) -> None:
"""Add a message to the session."""
self.messages.append(ChatMessage(
role=role,
content=content,
run_id=run_id,
))
self.updated_at = datetime.now()
def get_history_for_llm(self, max_messages: int = 50) -> List[Dict[str, str]]:
"""
Get chat history in LLM-compatible format.
Returns list of {"role": "user/assistant", "content": "..."} dicts.
"""
# Get last N messages
recent = self.messages[-max_messages:] if len(self.messages) > max_messages else self.messages
return [{"role": msg.role, "content": msg.content} for msg in recent]
@property
def run_count(self) -> int:
"""Number of user messages (runs) in this session."""
return sum(1 for msg in self.messages if msg.role == "user")
class SessionStore:
"""
In-memory session store for TUI.
Maintains chat history across agent runs within a session.
"""
def __init__(self, max_sessions: int = 100, max_messages_per_session: int = 1000):
"""
Initialize session store.
Args:
max_sessions: Maximum number of sessions to keep in memory.
max_messages_per_session: Maximum messages per session.
"""
self._sessions: Dict[str, Session] = {}
self._max_sessions = max_sessions
self._max_messages = max_messages_per_session
def get_or_create_session(self, session_id: str) -> Session:
"""Get existing session or create new one."""
if session_id not in self._sessions:
self._sessions[session_id] = Session(session_id=session_id)
self._cleanup_old_sessions()
logger.debug(f"Created new session: {session_id}")
return self._sessions[session_id]
def add_user_message(self, session_id: str, content: str, run_id: Optional[str] = None) -> None:
"""Add a user message to the session."""
session = self.get_or_create_session(session_id)
session.add_message("user", content, run_id)
self._trim_session(session)
logger.debug(f"Added user message to session {session_id}: {content[:50]}...")
def add_assistant_message(self, session_id: str, content: str, run_id: Optional[str] = None) -> None:
"""Add an assistant message to the session."""
session = self.get_or_create_session(session_id)
session.add_message("assistant", content, run_id)
self._trim_session(session)
logger.debug(f"Added assistant message to session {session_id}: {content[:50]}...")
def get_chat_history(self, session_id: str, max_messages: int = 50) -> List[Dict[str, str]]:
"""
Get chat history for a session in LLM-compatible format.
Args:
session_id: The session ID.
max_messages: Maximum number of messages to return.
Returns:
List of {"role": "user/assistant", "content": "..."} dicts.
"""
if session_id not in self._sessions:
return []
return self._sessions[session_id].get_history_for_llm(max_messages)
def get_session(self, session_id: str) -> Optional[Session]:
"""Get a session by ID."""
return self._sessions.get(session_id)
def list_sessions(self, limit: int = 50) -> List[Dict]:
"""List all sessions with metadata."""
sessions = sorted(
self._sessions.values(),
key=lambda s: s.updated_at,
reverse=True
)[:limit]
return [
{
"session_id": s.session_id,
"created_at": s.created_at.strftime("%Y-%m-%d %H:%M"),
"updated_at": s.updated_at.strftime("%Y-%m-%d %H:%M"),
"run_count": s.run_count,
}
for s in sessions
]
def delete_session(self, session_id: str) -> bool:
"""Delete a session."""
if session_id in self._sessions:
del self._sessions[session_id]
logger.debug(f"Deleted session: {session_id}")
return True
return False
def clear_session(self, session_id: str) -> None:
"""Clear all messages from a session."""
if session_id in self._sessions:
self._sessions[session_id].messages.clear()
self._sessions[session_id].updated_at = datetime.now()
logger.debug(f"Cleared session: {session_id}")
def _trim_session(self, session: Session) -> None:
"""Trim session to max messages."""
if len(session.messages) > self._max_messages:
# Keep the most recent messages
session.messages = session.messages[-self._max_messages:]
def _cleanup_old_sessions(self) -> None:
"""Remove oldest sessions if over limit."""
if len(self._sessions) > self._max_sessions:
# Sort by updated_at and remove oldest
sorted_sessions = sorted(
self._sessions.items(),
key=lambda x: x[1].updated_at
)
# Remove oldest sessions
to_remove = len(self._sessions) - self._max_sessions
for session_id, _ in sorted_sessions[:to_remove]:
del self._sessions[session_id]
logger.debug(f"Removed old session: {session_id}")
# Global session store instance for TUI
_session_store: Optional[SessionStore] = None
def get_session_store() -> SessionStore:
"""Get the global session store instance."""
global _session_store
if _session_store is None:
_session_store = SessionStore()
return _session_store
@@ -10,9 +10,8 @@ import time
try:
from textual.widget import Widget
from textual.widgets import Static, RichLog
from textual.containers import ScrollableContainer, Vertical
from textual.reactive import reactive
from textual.widgets import Static
from textual.containers import VerticalScroll
from textual.message import Message
from rich.markdown import Markdown
from rich.panel import Panel
@@ -49,23 +48,21 @@ class ChatMessage:
if TEXTUAL_AVAILABLE:
class ChatWidget(ScrollableContainer):
class ChatWidget(VerticalScroll):
"""
Widget for displaying chat history.
Widget for displaying chat history with scrollbar.
Features:
- Streaming message updates
- Markdown rendering
- Auto-scroll to bottom
- Message history management
Uses VerticalScroll for proper scrollbar support.
Messages are mounted directly to this container.
"""
DEFAULT_CSS = """
ChatWidget {
height: 100%;
height: 1fr;
border: solid $primary;
background: $surface;
padding: 0 1;
overflow-y: auto;
}
ChatWidget .message-user {
@@ -118,29 +115,30 @@ if TEXTUAL_AVAILABLE:
self._streaming_widgets: dict = {}
def compose(self):
"""Compose the widget."""
yield Vertical(id="chat-messages")
"""Compose the widget - no inner container needed."""
# Messages are mounted directly to this VerticalScroll
# Must yield from empty iterable (not return None)
yield from ()
async def add_message(self, message: ChatMessage) -> None:
"""Add a message to the chat."""
"""Add a message to the chat.
NEW BEHAVIOR: Messages render NEWEST at TOP.
This guarantees visibility without relying on scroll.
"""
self._messages.append(message)
# Trim old messages if needed
if len(self._messages) > self._max_messages:
self._messages = self._messages[-self._max_messages:]
# Create message widget
# Render message and scroll to show it
await self._render_message(message)
# Auto-scroll to bottom
self.scroll_end(animate=False)
self.post_message(self.MessageAdded(message))
async def _render_message(self, message: ChatMessage) -> None:
"""Render a single message."""
container = self.query_one("#chat-messages", Vertical)
"""Render a message and scroll to show it."""
# Create role label
role_style = {
"user": "bold cyan",
@@ -153,7 +151,7 @@ if TEXTUAL_AVAILABLE:
# Create content
try:
content = Markdown(message.content)
content = Markdown(message.content) if message.content else Text("")
except Exception:
content = Text(message.content)
@@ -170,7 +168,11 @@ if TEXTUAL_AVAILABLE:
classes=css_class,
)
await container.mount(panel)
# Mount directly to this VerticalScroll container
await self.mount(panel)
# Scroll to end to show new message
self.scroll_end(animate=False)
if message.is_streaming:
self._streaming_widgets[message.run_id] = widget_id
@@ -199,7 +201,7 @@ if TEXTUAL_AVAILABLE:
widget.update(Panel(rendered, title="Assistant", border_style="bold green"))
# Auto-scroll
# Scroll to end to keep streaming content visible
self.scroll_end(animate=False)
except Exception:
@@ -239,8 +241,8 @@ if TEXTUAL_AVAILABLE:
self._messages.clear()
self._streaming_widgets.clear()
container = self.query_one("#chat-messages", Vertical)
await container.remove_children()
# Remove all children from this container
await self.remove_children()
@property
def messages(self) -> List[ChatMessage]:
@@ -0,0 +1,263 @@
"""
Command Popup Widget for PraisonAI TUI.
Shows a searchable list of available commands when user types backslash.
Inspired by Claude Code's command discovery UX.
"""
from typing import List, Optional, Callable
from dataclasses import dataclass
try:
from textual.widget import Widget
from textual.widgets import Static, Input, OptionList
from textual.widgets.option_list import Option
from textual.containers import Vertical, Container
from textual.reactive import reactive
from textual.message import Message
from textual import events
from rich.text import Text
TEXTUAL_AVAILABLE = True
except ImportError:
TEXTUAL_AVAILABLE = False
Widget = object
Message = object
@dataclass
class CommandInfo:
"""Information about a command for display."""
name: str
description: str
aliases: List[str]
category: str = "general"
@property
def display_name(self) -> str:
"""Get display name with aliases."""
if self.aliases:
return f"{self.name} ({', '.join(self.aliases)})"
return self.name
if TEXTUAL_AVAILABLE:
class CommandPopupWidget(Container):
"""
Popup widget for command discovery and selection.
Features:
- Shows all available commands
- Searchable/filterable
- Keyboard navigation
- Category grouping
"""
DEFAULT_CSS = """
CommandPopupWidget {
layer: popup;
width: 60;
height: auto;
max-height: 20;
background: $surface;
border: solid $primary;
padding: 1;
margin: 0 0 0 2;
}
CommandPopupWidget #popup-title {
height: 1;
background: $primary;
color: $text;
text-align: center;
margin-bottom: 1;
}
CommandPopupWidget #popup-search {
height: 3;
margin-bottom: 1;
}
CommandPopupWidget #popup-list {
height: auto;
max-height: 12;
background: $surface-darken-1;
}
CommandPopupWidget .command-item {
padding: 0 1;
}
CommandPopupWidget .command-item:hover {
background: $primary-darken-1;
}
CommandPopupWidget #popup-hint {
height: 1;
color: $text-muted;
text-align: center;
margin-top: 1;
}
"""
class CommandSelected(Message):
"""Event when a command is selected."""
def __init__(self, command: str, args: str = ""):
self.command = command
self.args = args
super().__init__()
class Dismissed(Message):
"""Event when popup is dismissed."""
pass
# Reactive properties
filter_text: reactive[str] = reactive("")
def __init__(
self,
commands: Optional[List[CommandInfo]] = None,
name: Optional[str] = None,
id: Optional[str] = None,
classes: Optional[str] = None,
):
super().__init__(name=name, id=id, classes=classes)
self._commands = commands or []
self._filtered_commands: List[CommandInfo] = []
def compose(self):
"""Compose the widget."""
yield Static("Commands", id="popup-title")
yield Input(placeholder="Type to filter...", id="popup-search")
yield OptionList(id="popup-list")
yield Static("↑↓ Navigate • Enter Select • Esc Cancel", id="popup-hint")
def on_mount(self) -> None:
"""Handle mount."""
self._update_list()
# Focus the search input
search = self.query_one("#popup-search", Input)
search.focus()
def set_commands(self, commands: List[CommandInfo]) -> None:
"""Set the available commands."""
self._commands = commands
self._update_list()
def watch_filter_text(self, value: str) -> None:
"""React to filter text changes."""
self._update_list()
def _update_list(self) -> None:
"""Update the command list based on filter."""
filter_lower = self.filter_text.lower()
if filter_lower:
self._filtered_commands = [
cmd for cmd in self._commands
if (filter_lower in cmd.name.lower() or
filter_lower in cmd.description.lower() or
any(filter_lower in alias.lower() for alias in cmd.aliases))
]
else:
self._filtered_commands = self._commands.copy()
# Update the option list
try:
option_list = self.query_one("#popup-list", OptionList)
option_list.clear_options()
for cmd in self._filtered_commands:
# Create rich text for the option
text = Text()
text.append(f"/{cmd.name}", style="bold cyan")
if cmd.aliases:
text.append(f" ({', '.join(cmd.aliases)})", style="dim")
text.append(f"\n {cmd.description}", style="")
option_list.add_option(Option(text, id=cmd.name))
except Exception:
pass
def on_input_changed(self, event: Input.Changed) -> None:
"""Handle search input changes."""
if event.input.id == "popup-search":
self.filter_text = event.value
def on_input_submitted(self, event: Input.Submitted) -> None:
"""Handle Enter in search input."""
if event.input.id == "popup-search":
# Select first matching command
if self._filtered_commands:
self._select_command(self._filtered_commands[0].name)
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
"""Handle command selection from list."""
if event.option.id:
self._select_command(str(event.option.id))
def on_key(self, event: events.Key) -> None:
"""Handle key events."""
if event.key == "escape":
self.post_message(self.Dismissed())
event.stop()
elif event.key == "down":
# Move focus to list if in search
try:
option_list = self.query_one("#popup-list", OptionList)
option_list.focus()
except Exception:
pass
elif event.key == "up":
# Move focus to search if at top of list
try:
search = self.query_one("#popup-search", Input)
search.focus()
except Exception:
pass
def _select_command(self, command_name: str) -> None:
"""Select a command and emit event."""
self.post_message(self.CommandSelected(command_name))
def focus_search(self) -> None:
"""Focus the search input."""
try:
search = self.query_one("#popup-search", Input)
search.focus()
except Exception:
pass
else:
class CommandPopupWidget:
"""Placeholder when Textual is not available."""
def __init__(self, *args, **kwargs):
raise ImportError(
"Textual is required for TUI. Install with: pip install praisonai[tui]"
)
# Default commands list (matches slash_commands.py registry)
DEFAULT_COMMANDS = [
CommandInfo("help", "Show help for commands", ["h", "?"]),
CommandInfo("clear", "Clear conversation history", ["reset"]),
CommandInfo("model", "Show or change the current model", ["m"]),
CommandInfo("cost", "Show session cost and token usage", ["usage", "stats"]),
CommandInfo("tokens", "Show token usage breakdown", []),
CommandInfo("queue", "Show queue status", ["q"]),
CommandInfo("cancel", "Cancel current operation", ["c"]),
CommandInfo("settings", "Show current settings", ["set"]),
CommandInfo("sessions", "Browse saved sessions", ["sess"]),
CommandInfo("tools", "Toggle tools panel", ["t"]),
CommandInfo("exit", "Exit the TUI", ["quit", "q"]),
CommandInfo("plan", "Create an execution plan", []),
CommandInfo("undo", "Undo the last change", []),
CommandInfo("diff", "Show git diff of changes", []),
CommandInfo("commit", "Commit changes with AI message", []),
CommandInfo("map", "Show repository map", ["repo"]),
]
def get_default_commands() -> List[CommandInfo]:
"""Get the default command list."""
return DEFAULT_COMMANDS.copy()
@@ -6,6 +6,7 @@ Input area for composing messages with slash command support.
from typing import Callable, List, Optional
import asyncio
import os
try:
from textual.widget import Widget
@@ -16,6 +17,31 @@ try:
from textual import events
from rich.text import Text
TEXTUAL_AVAILABLE = True
class SubmitTextArea(TextArea):
"""Custom TextArea that submits on Enter and inserts newline on Shift+Enter."""
class SubmitRequested(Message):
"""Message sent when Enter is pressed."""
pass
async def _on_key(self, event: events.Key) -> None:
"""Handle key events before TextArea processes them."""
if event.key == "enter":
# Don't let TextArea handle Enter - we want to submit
event.prevent_default()
event.stop()
self.post_message(self.SubmitRequested())
return
elif event.key == "shift+enter":
# Insert newline on Shift+Enter
event.prevent_default()
event.stop()
self.insert("\n")
return
# Let TextArea handle other keys
await super()._on_key(event)
except ImportError:
TEXTUAL_AVAILABLE = False
Widget = object
@@ -36,7 +62,7 @@ if TEXTUAL_AVAILABLE:
"""
BINDINGS = [
Binding("ctrl+enter", "submit", "Send", show=True),
Binding("enter", "submit", "Send", show=True),
Binding("escape", "cancel", "Cancel", show=False),
Binding("up", "history_prev", "Previous", show=False),
Binding("down", "history_next", "Next", show=False),
@@ -77,9 +103,26 @@ if TEXTUAL_AVAILABLE:
self.args = args
super().__init__()
class BackslashTyped(Message):
"""Event when backslash is typed - triggers command popup."""
pass
class AtTyped(Message):
"""Event when @ is typed - triggers file autocomplete."""
def __init__(self, query: str, cursor_pos: int):
self.query = query
self.cursor_pos = cursor_pos
super().__init__()
class SlashTyped(Message):
"""Event when / is typed - triggers command discovery."""
def __init__(self, query: str):
self.query = query
super().__init__()
def __init__(
self,
placeholder: str = "Type your message... (Ctrl+Enter to send, /help for commands)",
placeholder: str = "Type your message... (Enter to send, Shift+Enter for newline, /help for commands)",
multiline: bool = True,
name: Optional[str] = None,
id: Optional[str] = None,
@@ -95,7 +138,7 @@ if TEXTUAL_AVAILABLE:
def compose(self):
"""Compose the widget."""
yield TextArea(
yield SubmitTextArea(
"",
id="composer-input",
language=None,
@@ -103,36 +146,53 @@ if TEXTUAL_AVAILABLE:
def on_mount(self) -> None:
"""Handle mount event."""
text_area = self.query_one("#composer-input", TextArea)
text_area = self.query_one("#composer-input", SubmitTextArea)
text_area.focus()
def on_submit_text_area_submit_requested(self, event: SubmitTextArea.SubmitRequested) -> None:
"""Handle submit request from TextArea."""
self.action_submit()
async def on_text_area_changed(self, event: TextArea.Changed) -> None:
"""Handle text changes."""
content = event.text_area.text
# Detect slash commands
# Detect backslash - auto-trigger command popup
if content == "\\":
self.post_message(self.BackslashTyped())
return
# Detect @ for file autocomplete
if "@" in content:
# Find the @ and extract query
at_pos = content.rfind("@")
if at_pos >= 0:
query = content[at_pos + 1:]
# Only trigger if no space after @
if " " not in query or query.endswith(" ") is False:
self.post_message(self.AtTyped(query, at_pos))
# Detect slash commands - auto-trigger command discovery
if content.startswith("/"):
parts = content[1:].split(maxsplit=1)
if parts:
command = parts[0]
args = parts[1] if len(parts) > 1 else ""
self.post_message(self.CommandDetected(command, args))
# Also trigger slash popup for discovery
self.post_message(self.SlashTyped(content[1:]))
def on_key(self, event: events.Key) -> None:
"""Handle key events."""
# Submit on Enter (single line mode) or Ctrl+Enter
if event.key == "enter" and not self._multiline:
event.prevent_default()
self.action_submit()
elif event.key == "ctrl+enter":
event.prevent_default()
self.action_submit()
"""Handle key events at widget level (backup handler)."""
# These are handled by SubmitTextArea now, but keep as backup
pass
def action_submit(self) -> None:
"""Submit the current input."""
if self._is_processing:
return
"""Submit the current input.
Note: We allow submitting even while processing to enable
queueing multiple messages.
"""
text_area = self.query_one("#composer-input", TextArea)
content = text_area.text.strip()
@@ -144,8 +204,8 @@ if TEXTUAL_AVAILABLE:
self._history.append(content)
self._history_index = -1
# Check if it's a command
is_command = content.startswith("/")
# Check if it's a command (/ or : prefix)
is_command = content.startswith("/") or content.startswith(":")
# Clear input
text_area.clear()
@@ -192,10 +252,12 @@ if TEXTUAL_AVAILABLE:
text_area.insert(self._current_input)
def set_processing(self, processing: bool) -> None:
"""Set processing state."""
"""Set processing state.
Note: We no longer disable the text area during processing
to allow users to queue additional messages while waiting.
"""
self._is_processing = processing
text_area = self.query_one("#composer-input", TextArea)
text_area.disabled = processing
@property
def text(self) -> str:
@@ -214,6 +276,12 @@ if TEXTUAL_AVAILABLE:
"""Focus the input area."""
text_area = self.query_one("#composer-input", TextArea)
text_area.focus()
def set_text(self, value: str) -> None:
"""Set the text content and move cursor to end."""
text_area = self.query_one("#composer-input", SubmitTextArea)
text_area.clear()
text_area.insert(value)
else:
class ComposerWidget:
@@ -0,0 +1,207 @@
"""
File Autocomplete Popup Widget for PraisonAI TUI.
Shows file/directory suggestions when user types @.
Reuses FileSearchService from at_mentions.py.
"""
from typing import List, Optional
from dataclasses import dataclass
import os
try:
from textual.widget import Widget
from textual.widgets import Static, Input, OptionList
from textual.widgets.option_list import Option
from textual.containers import Container
from textual.reactive import reactive
from textual.message import Message
from textual import events
from rich.text import Text
TEXTUAL_AVAILABLE = True
except ImportError:
TEXTUAL_AVAILABLE = False
Widget = object
Message = object
@dataclass
class FileInfo:
"""Information about a file for display."""
path: str
file_type: str # "file" or "directory"
score: int = 100
@property
def icon(self) -> str:
"""Get icon for file type."""
return "📁 " if self.file_type == "directory" else "📄 "
@property
def display(self) -> str:
"""Get display string."""
return f"{self.icon}{self.path}"
if TEXTUAL_AVAILABLE:
# Import FileSearchService from at_mentions
try:
from ..at_mentions import FileSearchService, detect_at_mention
FILE_SEARCH_AVAILABLE = True
except ImportError:
FILE_SEARCH_AVAILABLE = False
FileSearchService = None
class FilePopupWidget(Container):
"""
Popup widget for file autocomplete.
Features:
- Shows files/directories matching query
- Fuzzy search
- Keyboard navigation
- Supports ~/ and absolute paths
"""
DEFAULT_CSS = """
FilePopupWidget {
layer: popup;
width: 60;
height: auto;
max-height: 15;
background: $surface;
border: solid $accent;
padding: 1;
margin: 0 0 0 2;
}
FilePopupWidget #file-popup-title {
height: 1;
background: $accent;
color: $text;
text-align: center;
margin-bottom: 1;
}
FilePopupWidget #file-popup-list {
height: auto;
max-height: 10;
background: $surface-darken-1;
}
FilePopupWidget #file-popup-hint {
height: 1;
color: $text-muted;
text-align: center;
margin-top: 1;
}
"""
class FileSelected(Message):
"""Event when a file is selected."""
def __init__(self, path: str, at_pos: int):
self.path = path
self.at_pos = at_pos
super().__init__()
class Dismissed(Message):
"""Event when popup is dismissed."""
pass
# Reactive properties
filter_text: reactive[str] = reactive("")
def __init__(
self,
root_dir: Optional[str] = None,
at_pos: int = 0,
name: Optional[str] = None,
id: Optional[str] = None,
classes: Optional[str] = None,
):
super().__init__(name=name, id=id, classes=classes)
self._root_dir = root_dir or os.getcwd()
self._at_pos = at_pos
self._files: List[FileInfo] = []
self._file_service = None
if FILE_SEARCH_AVAILABLE and FileSearchService:
self._file_service = FileSearchService(self._root_dir)
def compose(self):
"""Compose the widget."""
yield Static("📂 Files", id="file-popup-title")
yield OptionList(id="file-popup-list")
yield Static("↑↓ Navigate • Enter Select • Esc Cancel", id="file-popup-hint")
def on_mount(self) -> None:
"""Handle mount."""
self._update_list()
def set_query(self, query: str, at_pos: int) -> None:
"""Set the search query."""
self.filter_text = query
self._at_pos = at_pos
def watch_filter_text(self, value: str) -> None:
"""React to filter text changes."""
self._update_list()
def _update_list(self) -> None:
"""Update the file list based on filter."""
if not self._file_service:
return
# Search files
results = self._file_service.search(self.filter_text, max_results=15)
self._files = [
FileInfo(
path=r.path,
file_type=r.file_type,
score=r.score
)
for r in results
]
# Update the option list
try:
option_list = self.query_one("#file-popup-list", OptionList)
option_list.clear_options()
for file_info in self._files:
text = Text()
text.append(file_info.icon, style="bold")
text.append(file_info.path, style="cyan" if file_info.file_type == "directory" else "")
option_list.add_option(Option(text, id=file_info.path))
except Exception:
pass
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
"""Handle file selection from list."""
if event.option.id:
self._select_file(str(event.option.id))
def on_key(self, event: events.Key) -> None:
"""Handle key events."""
if event.key == "escape":
self.post_message(self.Dismissed())
event.stop()
elif event.key == "enter":
# Select first item if available
if self._files:
self._select_file(self._files[0].path)
event.stop()
def _select_file(self, path: str) -> None:
"""Select a file and emit event."""
self.post_message(self.FileSelected(path, self._at_pos))
else:
class FilePopupWidget:
"""Placeholder when Textual is not available."""
def __init__(self, *args, **kwargs):
raise ImportError(
"Textual is required for TUI. Install with: pip install praisonai[tui]"
)
@@ -93,6 +93,19 @@ if TEXTUAL_AVAILABLE:
self.run_id = run_id
super().__init__()
class DeleteRequested(Message):
"""Event when delete is requested."""
def __init__(self, run_id: str):
self.run_id = run_id
super().__init__()
class EditRequested(Message):
"""Event when edit is requested."""
def __init__(self, run_id: str, new_content: str):
self.run_id = run_id
self.new_content = new_content
super().__init__()
queued_count: reactive[int] = reactive(0)
running_count: reactive[int] = reactive(0)
@@ -186,6 +199,16 @@ if TEXTUAL_AVAILABLE:
if self._selected_run_id:
self.post_message(self.RetryRequested(self._selected_run_id))
def delete_selected(self) -> None:
"""Delete the selected run."""
if self._selected_run_id:
self.post_message(self.DeleteRequested(self._selected_run_id))
def edit_selected(self, new_content: str) -> None:
"""Edit the selected run's input content."""
if self._selected_run_id:
self.post_message(self.EditRequested(self._selected_run_id, new_content))
@property
def selected_run_id(self) -> Optional[str]:
"""Get the selected run ID."""
@@ -4,14 +4,14 @@ Tool Panel Widget for PraisonAI TUI.
Displays tool execution status and approval dialogs.
"""
from typing import List, Optional
from typing import Any, List, Optional
from dataclasses import dataclass, field
import time
try:
from textual.widget import Widget
from textual.widgets import Static, ListView, ListItem
from textual.containers import Vertical
from textual.containers import Vertical, ScrollableContainer
from textual.reactive import reactive
from textual.message import Message
from rich.text import Text
@@ -61,6 +61,17 @@ if TEXTUAL_AVAILABLE:
padding: 0 1;
}
ToolPanelWidget #available-tools-scroll {
height: 1fr;
min-height: 5;
scrollbar-gutter: stable;
}
ToolPanelWidget #tool-list-scroll {
height: auto;
max-height: 10;
}
ToolPanelWidget .tool-pending {
color: $warning;
}
@@ -82,6 +93,11 @@ if TEXTUAL_AVAILABLE:
border: solid $warning;
padding: 1;
}
ToolPanelWidget .tools-count {
color: $text-muted;
text-style: italic;
}
"""
class ApprovalResponse(Message):
@@ -102,15 +118,58 @@ if TEXTUAL_AVAILABLE:
self._calls: List[ToolCall] = []
self._max_items = max_items
self._pending_approval: Optional[ToolCall] = None
self._available_tools: List[str] = []
def compose(self):
"""Compose the widget."""
yield Static("Tools", id="tool-title", classes="tool-header")
yield Vertical(id="tool-list")
yield ScrollableContainer(Vertical(id="tool-list"), id="tool-list-scroll")
yield Static("", id="tools-count", classes="tools-count")
yield ScrollableContainer(Vertical(id="available-tools"), id="available-tools-scroll")
def on_mount(self) -> None:
"""Handle mount."""
self._update_display()
self._update_available_tools_display()
def set_available_tools(self, tools: List[Any]) -> None:
"""Set the list of available tools to display."""
self._available_tools = []
for tool in tools:
if hasattr(tool, '__name__'):
self._available_tools.append(tool.__name__)
elif hasattr(tool, 'name'):
self._available_tools.append(tool.name)
elif callable(tool):
self._available_tools.append(str(tool))
else:
self._available_tools.append(str(type(tool).__name__))
self._update_available_tools_display()
def _update_available_tools_display(self) -> None:
"""Update the available tools display."""
try:
container = self.query_one("#available-tools", Vertical)
count_widget = self.query_one("#tools-count", Static)
except Exception:
return
container.remove_children()
if not self._available_tools:
container.mount(Static(Text("No tools loaded", style="dim italic")))
count_widget.update("")
return
# Update count display
count_widget.update(f"{len(self._available_tools)} tools available")
# Show ALL tools with scrolling support
for tool_name in sorted(self._available_tools):
text = Text()
text.append("• ", style="cyan")
text.append(tool_name, style="white")
container.mount(Static(text))
def add_call(self, call: ToolCall) -> None:
"""Add a tool call."""
+7 -1
View File
@@ -25,9 +25,15 @@ LEGACY_COMMANDS = {
# Typer commands that have been implemented
TYPER_COMMANDS = {
# Core commands
'config', 'traces', 'env', 'session', 'completion', 'version',
'debug', 'lsp', 'diag', 'doctor', 'acp', 'mcp', 'serve', 'schedule', 'run',
'tui', 'queue', 'profile', # TUI, queue management, and profiling commands
'tui', 'queue', 'profile', 'benchmark',
# Previously legacy-only commands (now in Typer)
'chat', 'code', 'call', 'realtime', 'train', 'ui', 'context', 'research',
'memory', 'workflow', 'tools', 'knowledge', 'deploy', 'agents', 'skills',
'eval', 'templates', 'recipe', 'todo', 'docs', 'commit', 'hooks', 'rules',
'registry', 'package', 'endpoints',
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,13 @@
"""
Unified Session Management for PraisonAI CLI.
Provides persistent session storage shared between TUI and --interactive mode.
"""
from .unified import UnifiedSession, UnifiedSessionStore, get_session_store
__all__ = [
"UnifiedSession",
"UnifiedSessionStore",
"get_session_store",
]
@@ -0,0 +1,306 @@
"""
Unified Session for PraisonAI CLI.
Provides persistent session storage shared between TUI and --interactive mode.
Uses JSON-based persistence with file locking for multi-process safety.
"""
import json
import logging
import os
import uuid
import fcntl
from dataclasses import dataclass, field, asdict
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
# Default session directory
DEFAULT_SESSION_DIR = Path.home() / ".praison" / "sessions"
@dataclass
class UnifiedSession:
"""
Unified session for TUI and --interactive mode.
Stores conversation history, metadata, and token/cost stats.
Persists to disk automatically.
"""
session_id: str
workspace: str = field(default_factory=os.getcwd)
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
messages: List[Dict[str, str]] = field(default_factory=list)
metadata: Dict[str, Any] = field(default_factory=dict)
# Token and cost tracking
total_input_tokens: int = 0
total_output_tokens: int = 0
total_cost: float = 0.0
request_count: int = 0
# Model info
current_model: str = "gpt-4o-mini"
def add_message(self, role: str, content: str) -> None:
"""Add a message to the session."""
self.messages.append({
"role": role,
"content": content,
"timestamp": datetime.now().isoformat(),
})
self.updated_at = datetime.now().isoformat()
def add_user_message(self, content: str) -> None:
"""Add a user message."""
self.add_message("user", content)
def add_assistant_message(self, content: str) -> None:
"""Add an assistant message."""
self.add_message("assistant", content)
def get_chat_history(self, max_messages: int = 50) -> List[Dict[str, str]]:
"""
Get chat history in LLM-compatible format.
Returns list of {"role": "user/assistant", "content": "..."} dicts.
"""
recent = self.messages[-max_messages:] if len(self.messages) > max_messages else self.messages
return [{"role": msg["role"], "content": msg["content"]} for msg in recent]
def update_stats(self, input_tokens: int, output_tokens: int, cost: float = 0.0) -> None:
"""Update token and cost statistics."""
self.total_input_tokens += input_tokens
self.total_output_tokens += output_tokens
self.total_cost += cost
self.request_count += 1
self.updated_at = datetime.now().isoformat()
def clear_messages(self) -> None:
"""Clear all messages from the session."""
self.messages.clear()
self.updated_at = datetime.now().isoformat()
def to_dict(self) -> Dict[str, Any]:
"""Convert session to dictionary."""
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "UnifiedSession":
"""Create session from dictionary."""
return cls(**data)
@property
def message_count(self) -> int:
"""Number of messages in the session."""
return len(self.messages)
@property
def user_message_count(self) -> int:
"""Number of user messages in the session."""
return sum(1 for msg in self.messages if msg.get("role") == "user")
class UnifiedSessionStore:
"""
Persistent session store with file locking.
Stores sessions as JSON files in ~/.praison/sessions/
"""
def __init__(self, session_dir: Optional[Path] = None):
"""
Initialize session store.
Args:
session_dir: Directory to store sessions. Defaults to ~/.praison/sessions/
"""
self.session_dir = session_dir or DEFAULT_SESSION_DIR
self.session_dir.mkdir(parents=True, exist_ok=True)
self._cache: Dict[str, UnifiedSession] = {}
self._last_session_id: Optional[str] = None
def _get_session_path(self, session_id: str) -> Path:
"""Get the file path for a session."""
return self.session_dir / f"{session_id}.json"
def _get_last_session_path(self) -> Path:
"""Get the path to the last session marker file."""
return self.session_dir / ".last_session"
def save(self, session: UnifiedSession) -> None:
"""
Save a session to disk with file locking.
Args:
session: Session to save
"""
path = self._get_session_path(session.session_id)
session.updated_at = datetime.now().isoformat()
try:
with open(path, 'w') as f:
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
try:
json.dump(session.to_dict(), f, indent=2)
finally:
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
# Update cache
self._cache[session.session_id] = session
# Update last session marker
self._update_last_session(session.session_id)
logger.debug(f"Saved session: {session.session_id}")
except Exception as e:
logger.error(f"Failed to save session {session.session_id}: {e}")
raise
def load(self, session_id: str) -> Optional[UnifiedSession]:
"""
Load a session from disk.
Args:
session_id: Session ID to load
Returns:
Session if found, None otherwise
"""
# Check cache first
if session_id in self._cache:
return self._cache[session_id]
path = self._get_session_path(session_id)
if not path.exists():
return None
try:
with open(path, 'r') as f:
fcntl.flock(f.fileno(), fcntl.LOCK_SH)
try:
data = json.load(f)
finally:
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
session = UnifiedSession.from_dict(data)
self._cache[session_id] = session
logger.debug(f"Loaded session: {session_id}")
return session
except Exception as e:
logger.error(f"Failed to load session {session_id}: {e}")
return None
def get_or_create(self, session_id: Optional[str] = None) -> UnifiedSession:
"""
Get existing session or create new one.
Args:
session_id: Optional session ID. If None, creates new session.
Returns:
Session instance
"""
if session_id:
session = self.load(session_id)
if session:
return session
# Create new session
new_id = session_id or str(uuid.uuid4())[:8]
session = UnifiedSession(session_id=new_id)
self.save(session)
return session
def delete(self, session_id: str) -> bool:
"""
Delete a session.
Args:
session_id: Session ID to delete
Returns:
True if deleted, False if not found
"""
path = self._get_session_path(session_id)
if path.exists():
path.unlink()
self._cache.pop(session_id, None)
logger.debug(f"Deleted session: {session_id}")
return True
return False
def list_sessions(self, limit: int = 50) -> List[Dict[str, Any]]:
"""
List all sessions with metadata.
Args:
limit: Maximum number of sessions to return
Returns:
List of session metadata dicts
"""
sessions = []
for path in self.session_dir.glob("*.json"):
try:
with open(path, 'r') as f:
data = json.load(f)
sessions.append({
"session_id": data.get("session_id"),
"created_at": data.get("created_at"),
"updated_at": data.get("updated_at"),
"message_count": len(data.get("messages", [])),
"workspace": data.get("workspace"),
})
except Exception as e:
logger.warning(f"Failed to read session {path}: {e}")
# Sort by updated_at descending
sessions.sort(key=lambda s: s.get("updated_at", ""), reverse=True)
return sessions[:limit]
def _update_last_session(self, session_id: str) -> None:
"""Update the last session marker."""
try:
path = self._get_last_session_path()
with open(path, 'w') as f:
f.write(session_id)
self._last_session_id = session_id
except Exception as e:
logger.warning(f"Failed to update last session marker: {e}")
def get_last_session_id(self) -> Optional[str]:
"""Get the ID of the last used session."""
if self._last_session_id:
return self._last_session_id
path = self._get_last_session_path()
if path.exists():
try:
self._last_session_id = path.read_text().strip()
return self._last_session_id
except Exception as e:
logger.warning(f"Failed to read last session marker: {e}")
return None
def get_last_session(self) -> Optional[UnifiedSession]:
"""Get the last used session."""
session_id = self.get_last_session_id()
if session_id:
return self.load(session_id)
return None
# Global session store instance
_session_store: Optional[UnifiedSessionStore] = None
def get_session_store() -> UnifiedSessionStore:
"""Get the global session store instance."""
global _session_store
if _session_store is None:
_session_store = UnifiedSessionStore()
return _session_store
+1 -1
View File
@@ -57,7 +57,7 @@ class CloudDeployer:
file.write("FROM python:3.11-slim\n")
file.write("WORKDIR /app\n")
file.write("COPY . .\n")
file.write("RUN pip install flask praisonai==3.0.0 gunicorn markdown\n")
file.write("RUN pip install flask praisonai==3.1.2 gunicorn markdown\n")
file.write("EXPOSE 8080\n")
file.write('CMD ["gunicorn", "-b", "0.0.0.0:8080", "api:app"]\n')
@@ -1,24 +1,28 @@
# Only try to import autogen_tools if either CrewAI or AG2 is available
CREWAI_AVAILABLE = False
AUTOGEN_AVAILABLE = False
# Lazy availability checks using find_spec (no actual import)
# This avoids the ~3200ms crewai import at CLI startup
import importlib.util
CREWAI_AVAILABLE = importlib.util.find_spec("crewai") is not None
AUTOGEN_AVAILABLE = importlib.util.find_spec("autogen") is not None
PRAISONAI_TOOLS_AVAILABLE = False
try:
from crewai import Agent, Task, Crew
CREWAI_AVAILABLE = True
except ImportError:
pass
# Lazy import helper - only imports when actually needed
def _get_autogen_tools():
"""Lazy import autogen_tools only when needed."""
global PRAISONAI_TOOLS_AVAILABLE
if CREWAI_AVAILABLE or AUTOGEN_AVAILABLE:
try:
from . import autogen_tools
PRAISONAI_TOOLS_AVAILABLE = True
return autogen_tools
except ImportError:
pass
return None
try:
import autogen
AUTOGEN_AVAILABLE = True
except ImportError:
pass
# Only try to import tools if a framework is available
if CREWAI_AVAILABLE or AUTOGEN_AVAILABLE:
try:
from .autogen_tools import *
PRAISONAI_TOOLS_AVAILABLE = True
except ImportError:
pass
# For backward compatibility, provide __getattr__ for lazy access
def __getattr__(name):
"""Lazy load autogen_tools exports on demand."""
tools_module = _get_autogen_tools()
if tools_module and hasattr(tools_module, name):
return getattr(tools_module, name)
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+11 -1
View File
@@ -1,2 +1,12 @@
# praisonai/inc/__init__.py
from .models import PraisonAIModel
# Lazy loading - PraisonAIModel is only imported when accessed
# This avoids the ~3500ms langchain_openai import at CLI startup
def __getattr__(name):
"""Lazy load PraisonAIModel only when accessed."""
if name == "PraisonAIModel":
from .models import PraisonAIModel
return PraisonAIModel
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
__all__ = ["PraisonAIModel"]
+50 -52
View File
@@ -1,7 +1,11 @@
# praisonai/inc/models.py
# PERFORMANCE OPTIMIZED: Removed all LangChain imports
# Uses direct OpenAI SDK for fast startup (~600ms vs ~3200ms with langchain_openai)
import os
import logging
from urllib.parse import urlparse
import importlib.util
logger = logging.getLogger(__name__)
_loglevel = os.environ.get('LOGLEVEL', 'INFO').strip().upper() or 'INFO'
logging.basicConfig(level=_loglevel, format='%(asctime)s - %(levelname)s - %(message)s')
@@ -9,30 +13,33 @@ logging.basicConfig(level=_loglevel, format='%(asctime)s - %(levelname)s - %(mes
# Constants
LOCAL_SERVER_API_KEY_PLACEHOLDER = "not-needed"
# Conditionally import modules based on availability
try:
from langchain_openai import ChatOpenAI # pip install langchain-openai
OPENAI_AVAILABLE = True
except ImportError:
OPENAI_AVAILABLE = False
# Use find_spec for fast availability checks (no actual import)
# This avoids the ~3200ms langchain_openai import at module load
OPENAI_AVAILABLE = importlib.util.find_spec("openai") is not None
GOOGLE_GENAI_AVAILABLE = importlib.util.find_spec("google.generativeai") is not None
ANTHROPIC_AVAILABLE = importlib.util.find_spec("anthropic") is not None
COHERE_AVAILABLE = importlib.util.find_spec("cohere") is not None
try:
from langchain_google_genai import ChatGoogleGenerativeAI # pip install langchain-google-genai
GOOGLE_GENAI_AVAILABLE = True
except ImportError:
GOOGLE_GENAI_AVAILABLE = False
# Lazy import helpers for provider SDKs
def _get_openai_client():
"""Lazy import OpenAI client."""
from openai import OpenAI
return OpenAI
try:
from langchain_anthropic import ChatAnthropic # pip install langchain-anthropic
ANTHROPIC_AVAILABLE = True
except ImportError:
ANTHROPIC_AVAILABLE = False
def _get_google_genai():
"""Lazy import Google Generative AI."""
import google.generativeai as genai
return genai
try:
from langchain_cohere import ChatCohere # pip install langchain-cohere
COHERE_AVAILABLE = True
except ImportError:
COHERE_AVAILABLE = False
def _get_anthropic_client():
"""Lazy import Anthropic client."""
from anthropic import Anthropic
return Anthropic
def _get_cohere_client():
"""Lazy import Cohere client."""
import cohere
return cohere
class PraisonAIModel:
def __init__(self, model=None, api_key_var=None, base_url=None, api_key=None):
@@ -100,56 +107,47 @@ class PraisonAIModel:
def get_model(self):
"""
Returns an instance of the langchain Chat client with the configured parameters.
Returns an instance of the native SDK client with the configured parameters.
PERFORMANCE: Uses direct SDK clients instead of LangChain wrappers.
This saves ~2600ms on import (OpenAI SDK ~600ms vs langchain_openai ~3200ms).
Returns:
Chat: An instance of the langchain Chat client.
Client: An instance of the native SDK client (OpenAI, Anthropic, etc.)
"""
if self.model.startswith("google/"):
if GOOGLE_GENAI_AVAILABLE:
return ChatGoogleGenerativeAI(
model=self.model_name,
google_api_key=self.api_key
)
genai = _get_google_genai()
genai.configure(api_key=self.api_key)
return genai.GenerativeModel(self.model_name)
else:
raise ImportError(
"Required Langchain Integration 'langchain-google-genai' not found. "
"Please install with 'pip install langchain-google-genai'"
"Required package 'google-generativeai' not found. "
"Please install with 'pip install google-generativeai'"
)
elif self.model.startswith("cohere/"):
if COHERE_AVAILABLE:
return ChatCohere(
model=self.model_name,
cohere_api_key=self.api_key,
)
cohere = _get_cohere_client()
return cohere.Client(api_key=self.api_key)
else:
raise ImportError(
"Required Langchain Integration 'langchain-cohere' not found. "
"Please install with 'pip install langchain-cohere'"
"Required package 'cohere' not found. "
"Please install with 'pip install cohere'"
)
elif self.model.startswith("anthropic/"):
if ANTHROPIC_AVAILABLE:
return ChatAnthropic(
model=self.model_name,
anthropic_api_key=self.api_key,
)
Anthropic = _get_anthropic_client()
return Anthropic(api_key=self.api_key)
else:
raise ImportError(
"Required Langchain Integration 'langchain-anthropic' not found. "
"Please install with 'pip install langchain-anthropic'"
"Required package 'anthropic' not found. "
"Please install with 'pip install anthropic'"
)
elif OPENAI_AVAILABLE:
chat_kwargs = {
"model": self.model_name,
"api_key": self.api_key,
"base_url": self.base_url,
}
# Certain OpenAI models (e.g., gpt-5-* family) only allow temperature=1
if isinstance(self.model_name, str) and self.model_name.startswith("gpt-5"):
chat_kwargs["temperature"] = 1
return ChatOpenAI(**chat_kwargs)
OpenAI = _get_openai_client()
return OpenAI(api_key=self.api_key, base_url=self.base_url)
else:
raise ImportError(
"Required Langchain Integration 'langchain-openai' not found. "
"Please install with 'pip install langchain-openai'"
"Required package 'openai' not found. "
"Please install with 'pip install openai'"
)
+462 -160
View File
@@ -1,34 +1,24 @@
# Standard library imports
"""PraisonAI Chat - Optimized Chainlit Application
This is the optimized chat application with:
- Lazy imports for fast startup
- Agent reuse between messages (persistent agent per session)
- Default ACP/LSP tools with trust mode
- Session management
- Profiling hooks (optional via PRAISON_CHAT_PROFILE=1)
Performance improvements over original chat.py:
- Deferred database initialization
- Lazy loading of PIL, Tavily, crawl4ai, litellm
- Agent reuse (no re-creation per message)
- Interactive tools loaded once per session
"""
# Standard library imports (minimal at top level)
import os
from datetime import datetime
from typing import Dict, Optional
import logging
import json
import asyncio
import io
import base64
import importlib.util
import inspect
# Third-party imports
from dotenv import load_dotenv
from PIL import Image
from tavily import TavilyClient
from crawl4ai import AsyncWebCrawler
# Local application/library imports
import chainlit as cl
from chainlit.input_widget import TextInput
from chainlit.types import ThreadDict
import chainlit.data as cl_data
from litellm import acompletion
from literalai.helper import utc_now
from db import DatabaseManager
# Load environment variables
load_dotenv()
# Logging configuration
# Set up minimal logging first
logger = logging.getLogger(__name__)
log_level = os.getenv("LOGLEVEL", "INFO").upper() or "INFO"
logger.handlers = []
@@ -39,52 +29,204 @@ console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
logger.setLevel(log_level)
# Chainlit must be imported early (required by decorators)
import chainlit as cl
from chainlit.input_widget import TextInput, Switch
from chainlit.types import ThreadDict
import chainlit.data as cl_data
# Profiling support (optional)
PROFILING_ENABLED = os.getenv("PRAISON_CHAT_PROFILE", "").lower() in ("1", "true", "yes")
_profile_data = {}
def _profile_start(name: str):
"""Start profiling a section."""
if PROFILING_ENABLED:
import time
_profile_data[name] = {"start": time.perf_counter()}
def _profile_end(name: str):
"""End profiling a section and log."""
if PROFILING_ENABLED and name in _profile_data:
import time
elapsed = time.perf_counter() - _profile_data[name]["start"]
_profile_data[name]["elapsed"] = elapsed
logger.info(f"[PROFILE] {name}: {elapsed*1000:.2f}ms")
# Lazy import cache
_cached_modules = {}
def _get_json():
if 'json' not in _cached_modules:
import json
_cached_modules['json'] = json
return _cached_modules['json']
def _get_asyncio():
if 'asyncio' not in _cached_modules:
import asyncio
_cached_modules['asyncio'] = asyncio
return _cached_modules['asyncio']
def _get_datetime():
if 'datetime' not in _cached_modules:
from datetime import datetime
_cached_modules['datetime'] = datetime
return _cached_modules['datetime']
def _get_io():
if 'io' not in _cached_modules:
import io
_cached_modules['io'] = io
return _cached_modules['io']
def _get_base64():
if 'base64' not in _cached_modules:
import base64
_cached_modules['base64'] = base64
return _cached_modules['base64']
def _get_importlib():
if 'importlib' not in _cached_modules:
import importlib.util
_cached_modules['importlib'] = importlib
return _cached_modules['importlib']
def _get_inspect():
if 'inspect' not in _cached_modules:
import inspect
_cached_modules['inspect'] = inspect
return _cached_modules['inspect']
def _get_pil_image():
if 'PIL.Image' not in _cached_modules:
_profile_start("import_pil")
from PIL import Image
_cached_modules['PIL.Image'] = Image
_profile_end("import_pil")
return _cached_modules['PIL.Image']
def _get_acompletion():
if 'acompletion' not in _cached_modules:
_profile_start("import_litellm")
from litellm import acompletion
_cached_modules['acompletion'] = acompletion
_profile_end("import_litellm")
return _cached_modules['acompletion']
def _get_tavily_client():
if 'TavilyClient' not in _cached_modules:
try:
_profile_start("import_tavily")
from tavily import TavilyClient
_cached_modules['TavilyClient'] = TavilyClient
_profile_end("import_tavily")
except ImportError:
_cached_modules['TavilyClient'] = None
return _cached_modules['TavilyClient']
def _get_async_web_crawler():
if 'AsyncWebCrawler' not in _cached_modules:
try:
_profile_start("import_crawl4ai")
from crawl4ai import AsyncWebCrawler
_cached_modules['AsyncWebCrawler'] = AsyncWebCrawler
_profile_end("import_crawl4ai")
except ImportError:
_cached_modules['AsyncWebCrawler'] = None
return _cached_modules['AsyncWebCrawler']
def _get_praisonai_agent():
"""Lazy load PraisonAI Agent for reuse."""
if 'Agent' not in _cached_modules:
try:
_profile_start("import_praisonai_agent")
from praisonaiagents import Agent
_cached_modules['Agent'] = Agent
_profile_end("import_praisonai_agent")
except ImportError:
_cached_modules['Agent'] = None
return _cached_modules['Agent']
def _get_interactive_tools():
"""Lazy load interactive tools (ACP, LSP, basic) with trust mode."""
if 'interactive_tools' not in _cached_modules:
try:
_profile_start("load_interactive_tools")
from praisonai.cli.features.interactive_tools import get_interactive_tools, ToolConfig
config = ToolConfig.from_env()
config.workspace = os.getcwd()
config.approval_mode = "auto" # Trust mode - auto-approve all tool executions
tools = get_interactive_tools(config=config)
_cached_modules['interactive_tools'] = tools
_profile_end("load_interactive_tools")
logger.info(f"Loaded {len(tools)} interactive tools (ACP, LSP, basic) with trust mode")
except ImportError as e:
logger.debug(f"Interactive tools not available: {e}")
_cached_modules['interactive_tools'] = []
return _cached_modules['interactive_tools']
# Deferred database initialization
_db_manager = None
def _get_db_manager():
"""Lazy initialize database manager."""
global _db_manager
if _db_manager is None:
_profile_start("init_database")
# Import from the same directory as this module
import sys
ui_dir = os.path.dirname(os.path.abspath(__file__))
if ui_dir not in sys.path:
sys.path.insert(0, ui_dir)
from db import DatabaseManager
_db_manager = DatabaseManager()
_db_manager.initialize()
cl_data._data_layer = _db_manager
_profile_end("init_database")
return _db_manager
# Load environment variables lazily
def _ensure_env_loaded():
if 'env_loaded' not in _cached_modules:
from dotenv import load_dotenv
load_dotenv()
_cached_modules['env_loaded'] = True
# Auth secret setup (required early)
CHAINLIT_AUTH_SECRET = os.getenv("CHAINLIT_AUTH_SECRET")
if not CHAINLIT_AUTH_SECRET:
os.environ["CHAINLIT_AUTH_SECRET"] = "p8BPhQChpg@J>jBz$wGxqLX2V>yTVgP*7Ky9H$aV:axW~ANNX-7_T:o@lnyCBu^U"
CHAINLIT_AUTH_SECRET = os.getenv("CHAINLIT_AUTH_SECRET")
now = utc_now()
create_step_counter = 0
# Initialize database
db_manager = DatabaseManager()
db_manager.initialize()
def save_setting(key: str, value: str):
"""Save a setting to the database"""
asyncio = _get_asyncio()
db_manager = _get_db_manager()
asyncio.run(db_manager.save_setting(key, value))
def load_setting(key: str) -> str:
"""Load a setting from the database"""
asyncio = _get_asyncio()
db_manager = _get_db_manager()
return asyncio.run(db_manager.load_setting(key))
cl_data._data_layer = db_manager
def load_custom_tools():
"""
Load custom tools from tools.py if it exists.
Resolution order:
1. PRAISONAI_TOOLS_PATH environment variable (file or directory)
2. ./tools.py in current working directory
3. No tools (silent, no warning)
"""
"""Load custom tools from tools.py if it exists."""
custom_tools = {}
importlib = _get_importlib()
inspect = _get_inspect()
# Determine tools path
tools_path = os.getenv("PRAISONAI_TOOLS_PATH")
if tools_path:
if not os.path.exists(tools_path):
logger.warning(f"PRAISONAI_TOOLS_PATH set but path does not exist: {tools_path}")
return custom_tools
else:
# Check current working directory for tools.py
cwd_tools = os.path.join(os.getcwd(), "tools.py")
if os.path.exists(cwd_tools):
tools_path = cwd_tools
else:
# No tools configured - this is fine, return silently
logger.debug("No tools.py found in current directory (this is normal)")
return custom_tools
@@ -97,27 +239,23 @@ def load_custom_tools():
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Load all functions from tools.py
for name, obj in inspect.getmembers(module):
if not name.startswith('_') and callable(obj) and not inspect.isclass(obj):
# Store function in globals for access
globals()[name] = obj
# Get function signature to build parameters
sig = inspect.signature(obj)
params_properties = {}
required_params = []
for param_name, param in sig.parameters.items():
if param_name != 'self': # Skip self parameter
# Get type annotation if available
param_type = "string" # Default type
if param.annotation != inspect.Parameter.empty:
if param.annotation == int:
if param_name != 'self':
param_type = "string"
if param.annotation is not inspect.Parameter.empty:
if param.annotation is int:
param_type = "integer"
elif param.annotation == float:
elif param.annotation is float:
param_type = "number"
elif param.annotation == bool:
elif param.annotation is bool:
param_type = "boolean"
params_properties[param_name] = {
@@ -125,11 +263,9 @@ def load_custom_tools():
"description": f"Parameter {param_name}"
}
# Add to required if no default value
if param.default == inspect.Parameter.empty:
if param.default is inspect.Parameter.empty:
required_params.append(param_name)
# Build tool definition
tool_def = {
"type": "function",
"function": {
@@ -149,20 +285,63 @@ def load_custom_tools():
if custom_tools:
logger.info(f"Loaded {len(custom_tools)} custom tools from {tools_path}")
except FileNotFoundError:
# File doesn't exist - this is fine, no warning needed
logger.debug(f"Tools file not found: {tools_path}")
except Exception as e:
logger.warning(f"Error loading custom tools from {tools_path}: {e}")
return custom_tools
# Load custom tools
custom_tools_dict = load_custom_tools()
# Deferred tool loading
_custom_tools_dict = None
_tavily_client = None
_tools_list = None
tavily_api_key = os.getenv("TAVILY_API_KEY")
tavily_client = TavilyClient(api_key=tavily_api_key) if tavily_api_key else None
def _get_custom_tools():
global _custom_tools_dict
if _custom_tools_dict is None:
_custom_tools_dict = load_custom_tools()
return _custom_tools_dict
def _get_tavily():
global _tavily_client
if _tavily_client is None:
tavily_api_key = os.getenv("TAVILY_API_KEY")
if tavily_api_key:
TavilyClient = _get_tavily_client()
if TavilyClient:
_tavily_client = TavilyClient(api_key=tavily_api_key)
return _tavily_client
def _get_tools_list():
"""Get the combined tools list (Tavily + custom tools)."""
global _tools_list
if _tools_list is None:
_tools_list = []
tavily_api_key = os.getenv("TAVILY_API_KEY")
if tavily_api_key:
_tools_list.append({
"type": "function",
"function": {
"name": "tavily_web_search",
"description": "Search the web using Tavily API and crawl the resulting URLs",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
}
})
custom_tools = _get_custom_tools()
_tools_list.extend(list(custom_tools.values()))
return _tools_list
async def tavily_web_search(query):
"""Search the web using Tavily API."""
json = _get_json()
tavily_client = _get_tavily()
if not tavily_client:
return json.dumps({
"query": query,
@@ -172,62 +351,39 @@ async def tavily_web_search(query):
response = tavily_client.search(query)
logger.debug(f"Tavily search response: {response}")
async with AsyncWebCrawler() as crawler:
results = []
for result in response.get('results', []):
url = result.get('url')
if url:
try:
crawl_result = await crawler.arun(url=url)
results.append({
"content": result.get('content'),
"url": url,
"full_content": crawl_result.markdown
})
except Exception as e:
logger.error(f"Error crawling {url}: {str(e)}")
results.append({
"content": result.get('content'),
"url": url,
"full_content": "Error: Unable to crawl this URL"
})
AsyncWebCrawler = _get_async_web_crawler()
if AsyncWebCrawler:
async with AsyncWebCrawler() as crawler:
results = []
for result in response.get('results', []):
url = result.get('url')
if url:
try:
crawl_result = await crawler.arun(url=url)
results.append({
"content": result.get('content'),
"url": url,
"full_content": crawl_result.markdown
})
except Exception as e:
logger.error(f"Error crawling {url}: {str(e)}")
results.append({
"content": result.get('content'),
"url": url,
"full_content": "Error: Unable to crawl this URL"
})
else:
results = [{"content": r.get('content'), "url": r.get('url')} for r in response.get('results', [])]
return json.dumps({
"query": query,
"results": results
})
# Build tools list with Tavily and custom tools
tools = []
# Add Tavily tool if API key is available
if tavily_api_key:
tools.append({
"type": "function",
"function": {
"name": "tavily_web_search",
"description": "Search the web using Tavily API and crawl the resulting URLs",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
}
})
# Add custom tools from tools.py
tools.extend(list(custom_tools_dict.values()))
# Authentication configuration
AUTH_PASSWORD_ENABLED = os.getenv("AUTH_PASSWORD_ENABLED", "true").lower() == "true" # Password authentication enabled by default
AUTH_OAUTH_ENABLED = os.getenv("AUTH_OAUTH_ENABLED", "false").lower() == "true" # OAuth authentication disabled by default
expected_username = os.getenv("CHAINLIT_USERNAME", "admin")
expected_password = os.getenv("CHAINLIT_PASSWORD", "admin")
# Warn if using default credentials
if expected_username == "admin" and expected_password == "admin":
logger.warning("⚠️ Using default admin credentials. Set CHAINLIT_USERNAME and CHAINLIT_PASSWORD environment variables for production.")
@@ -241,38 +397,122 @@ def auth_callback(username: str, password: str):
logger.warning(f"Login failed for user: {username}")
return None
def _get_or_create_agent(model_name: str, tools_enabled: bool = True):
"""Get or create a reusable agent for the session."""
Agent = _get_praisonai_agent()
if Agent is None:
return None
# Get cached agent from session
cached_agent = cl.user_session.get("_cached_agent")
cached_model = cl.user_session.get("_cached_agent_model")
# Reuse if model matches
if cached_agent is not None and cached_model == model_name:
return cached_agent
# Create new agent with interactive tools
_profile_start("create_agent")
tools = []
if tools_enabled:
tools = _get_interactive_tools()
# Add Tavily if available
if os.getenv("TAVILY_API_KEY"):
tools.append(tavily_web_search)
agent = Agent(
name="PraisonAI Assistant",
instructions="""You are a helpful AI assistant with access to powerful tools.
async def send_count():
await cl.Message(
f"Create step counter: {create_step_counter}", disable_feedback=True
).send()
Available capabilities:
- File operations (read, write, create, edit, delete files)
- Code intelligence (find symbols, definitions, references)
- Command execution (run shell commands)
- Web search (if Tavily API key is set)
Use tools when needed to help the user. For file modifications, use the ACP tools which provide safe, reviewable changes.
Always be helpful, accurate, and concise.""",
llm=model_name,
tools=tools if tools else None,
verbose=False,
)
# Cache the agent
cl.user_session.set("_cached_agent", agent)
cl.user_session.set("_cached_agent_model", model_name)
_profile_end("create_agent")
return agent
@cl.on_chat_start
async def start():
model_name = load_setting("model_name") or os.getenv("MODEL_NAME", "gpt-5-nano")
_profile_start("on_chat_start")
_ensure_env_loaded()
model_name = load_setting("model_name") or os.getenv("MODEL_NAME", "gpt-4o-mini")
tools_enabled = (load_setting("tools_enabled") or "true").lower() == "true"
cl.user_session.set("model_name", model_name)
logger.debug(f"Model name: {model_name}")
cl.user_session.set("tools_enabled", tools_enabled)
logger.debug(f"Model name: {model_name}, Tools enabled: {tools_enabled}")
# Pre-create agent for faster first response
_get_or_create_agent(model_name, tools_enabled)
settings = cl.ChatSettings(
[
TextInput(
id="model_name",
label="Enter the Model Name",
placeholder="e.g., gpt-5-nano",
placeholder="e.g., gpt-4o-mini",
initial=model_name
),
Switch(
id="tools_enabled",
label="Enable Tools (ACP, LSP, Web Search)",
initial=tools_enabled
)
]
)
cl.user_session.set("settings", settings)
await settings.send()
# Show loaded tools info
tools = _get_interactive_tools()
tool_names = [t.__name__ for t in tools[:5]]
if len(tools) > 5:
tool_names.append(f"... and {len(tools) - 5} more")
await cl.Message(
content=f"🚀 **PraisonAI Chat Ready**\n\n"
f"**Model:** {model_name}\n"
f"**Tools:** {len(tools)} loaded ({', '.join(tool_names)})\n"
f"**Trust Mode:** Enabled (auto-approve tool executions)\n\n"
f"Type your message to get started!"
).send()
_profile_end("on_chat_start")
@cl.on_settings_update
async def setup_agent(settings):
json = _get_json()
logger.debug(settings)
cl.user_session.set("settings", settings)
model_name = settings["model_name"]
tools_enabled = settings.get("tools_enabled", True)
cl.user_session.set("model_name", model_name)
cl.user_session.set("tools_enabled", tools_enabled)
# Invalidate cached agent if model changed
cached_model = cl.user_session.get("_cached_agent_model")
if cached_model != model_name:
cl.user_session.set("_cached_agent", None)
cl.user_session.set("_cached_agent_model", None)
save_setting("model_name", model_name)
save_setting("tools_enabled", str(tools_enabled).lower())
thread_id = cl.user_session.get("thread_id")
if thread_id:
@@ -285,17 +525,26 @@ async def setup_agent(settings):
except json.JSONDecodeError:
metadata = {}
metadata["model_name"] = model_name
metadata["tools_enabled"] = tools_enabled
await cl_data.update_thread(thread_id, metadata=metadata)
cl.user_session.set("metadata", metadata)
@cl.on_message
async def main(message: cl.Message):
model_name = load_setting("model_name") or os.getenv("MODEL_NAME", "gpt-5-nano")
_profile_start("on_message_total")
json = _get_json()
asyncio = _get_asyncio()
datetime = _get_datetime()
model_name = cl.user_session.get("model_name") or load_setting("model_name") or os.getenv("MODEL_NAME", "gpt-4o-mini")
tools_enabled = cl.user_session.get("tools_enabled", True)
message_history = cl.user_session.get("message_history", [])
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Handle image uploads
image = None
if message.elements and isinstance(message.elements[0], cl.Image):
Image = _get_pil_image()
image_element = message.elements[0]
try:
image = Image.open(image_element.path)
@@ -306,8 +555,7 @@ async def main(message: cl.Message):
await cl.Message(content="Error processing the image. Please try again.").send()
return
user_message = f"""
Answer the question and use tools if needed:
user_message = f"""Answer the question and use tools if needed:
Current Date and Time: {now}
@@ -320,6 +568,58 @@ User Question: {message.content}
message_history.append({"role": "user", "content": user_message})
msg = cl.Message(content="")
# Try PraisonAI Agent first (faster, with tool reuse)
agent = _get_or_create_agent(model_name, tools_enabled) if tools_enabled else None
if agent is not None:
_profile_start("agent_response")
await msg.send()
try:
# Use async chat for streaming
result = await agent.achat(message.content)
# Get response text
if hasattr(result, 'raw'):
response_text = result.raw
else:
response_text = str(result)
# Stream in word chunks for better UX
words = response_text.split(' ')
for i, word in enumerate(words):
token = word + (' ' if i < len(words) - 1 else '')
await msg.stream_token(token)
msg.content = response_text
await msg.update()
message_history.append({"role": "assistant", "content": response_text})
cl.user_session.set("message_history", message_history)
except Exception as e:
logger.error(f"Agent error: {e}")
# Fallback to litellm
await _handle_with_litellm(message, user_message, model_name, message_history, msg, image)
_profile_end("agent_response")
else:
# Fallback to litellm
await _handle_with_litellm(message, user_message, model_name, message_history, msg, image)
_profile_end("on_message_total")
async def _handle_with_litellm(message, user_message, model_name, message_history, msg, image):
"""Fallback handler using litellm for backward compatibility."""
json = _get_json()
asyncio = _get_asyncio()
io = _get_io()
base64 = _get_base64()
acompletion = _get_acompletion()
tools = _get_tools_list()
_profile_start("litellm_response")
completion_params = {
"model": model_name,
"messages": message_history,
@@ -338,7 +638,6 @@ User Question: {message.content}
]
}
# Pass tools if we have any (Tavily or custom)
if tools:
completion_params["tools"] = tools
completion_params["tool_choice"] = "auto"
@@ -356,7 +655,6 @@ User Question: {message.content}
if 'content' in delta and delta['content'] is not None:
token = delta['content']
# Send message on first token to avoid delay
if not msg_sent:
await msg.send()
msg_sent = True
@@ -386,28 +684,25 @@ User Question: {message.content}
if current_tool_call:
tool_calls.append(current_tool_call)
# Ensure message is sent even if no content (e.g., tool calls only)
if not msg_sent:
await msg.send()
logger.debug(f"Full response: {full_response}")
logger.debug(f"Tool calls: {tool_calls}")
message_history.append({"role": "assistant", "content": full_response})
logger.debug(f"Message history: {message_history}")
cl.user_session.set("message_history", message_history)
await msg.update()
if tool_calls and tools: # Check if we have any tools and tool calls
# Handle tool calls
if tool_calls and tools:
custom_tools = _get_custom_tools()
available_functions = {}
# Add Tavily function if available
if tavily_api_key:
if os.getenv("TAVILY_API_KEY"):
available_functions["tavily_web_search"] = tavily_web_search
# Add all custom tool functions from globals
for tool_name in custom_tools_dict:
for tool_name in custom_tools:
if tool_name in globals():
available_functions[tool_name] = globals()[tool_name]
messages = message_history + [{"role": "assistant", "content": None, "function_call": {
"name": tool_calls[0]['function']['name'],
"arguments": tool_calls[0]['function']['arguments']
@@ -422,49 +717,37 @@ User Question: {message.content}
try:
function_args = json.loads(function_args)
# Call function based on whether it's async or sync
if asyncio.iscoroutinefunction(function_to_call):
# For async functions like tavily_web_search
if function_name == "tavily_web_search":
function_response = await function_to_call(
query=function_args.get("query"),
)
function_response = await function_to_call(query=function_args.get("query"))
else:
# For custom async functions, pass all arguments
function_response = await function_to_call(**function_args)
else:
# For sync functions (most custom tools)
function_response = function_to_call(**function_args)
# Convert response to string if needed
if not isinstance(function_response, str):
function_response = json.dumps(function_response)
messages.append(
{
"role": "function",
"name": function_name,
"content": function_response,
}
)
messages.append({
"role": "function",
"name": function_name,
"content": function_response,
})
except json.JSONDecodeError:
logger.error(f"Failed to parse function arguments: {function_args}")
except Exception as e:
logger.error(f"Error calling function {function_name}: {str(e)}")
messages.append(
{
"role": "function",
"name": function_name,
"content": f"Error: {str(e)}",
}
)
messages.append({
"role": "function",
"name": function_name,
"content": f"Error: {str(e)}",
})
second_response = await acompletion(
model=model_name,
stream=True,
messages=messages,
)
logger.debug(f"Second LLM response: {second_response}")
full_response = ""
async for part in second_response:
@@ -480,25 +763,41 @@ User Question: {message.content}
else:
msg.content = full_response
await msg.update()
_profile_end("litellm_response")
@cl.on_chat_resume
async def on_chat_resume(thread: ThreadDict):
json = _get_json()
io = _get_io()
base64 = _get_base64()
Image = _get_pil_image()
logger.info(f"Resuming chat: {thread['id']}")
model_name = load_setting("model_name") or os.getenv("MODEL_NAME", "gpt-5-nano")
model_name = load_setting("model_name") or os.getenv("MODEL_NAME", "gpt-4o-mini")
tools_enabled = (load_setting("tools_enabled") or "true").lower() == "true"
logger.debug(f"Model name: {model_name}")
settings = cl.ChatSettings(
[
TextInput(
id="model_name",
label="Enter the Model Name",
placeholder="e.g., gpt-5-nano",
placeholder="e.g., gpt-4o-mini",
initial=model_name
),
Switch(
id="tools_enabled",
label="Enable Tools (ACP, LSP, Web Search)",
initial=tools_enabled
)
]
)
await settings.send()
thread_id = thread["id"]
cl.user_session.set("thread_id", thread_id)
cl.user_session.set("thread_id", thread["id"])
cl.user_session.set("model_name", model_name)
cl.user_session.set("tools_enabled", tools_enabled)
metadata = thread.get("metadata", {})
if isinstance(metadata, str):
@@ -524,6 +823,9 @@ async def on_chat_resume(thread: ThreadDict):
logger.warning(f"Message without recognized type: {m}")
cl.user_session.set("message_history", message_history)
# Pre-create agent for faster first response
_get_or_create_agent(model_name, tools_enabled)
image_data = metadata.get("image")
if image_data:
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
__version__ = "3.0.0"
__version__ = "3.1.2"
+1 -1
View File
@@ -12,7 +12,7 @@ dependencies = [
"rich>=13.7",
"markdown>=3.5",
"pyparsing>=3.0.0",
"praisonaiagents>=0.6.0",
"praisonaiagents>=0.6.2",
"python-dotenv>=0.19.0",
"instructor>=1.3.3",
"PyYAML>=6.0",
@@ -0,0 +1,376 @@
"""
Unit tests for ACP Safe Edit Pipeline.
"""
import tempfile
import pytest
from pathlib import Path
from praisonai.acp.safe_edit import (
EditProposal,
EditStatus,
SafeEditPipeline,
get_safe_edit_pipeline,
)
class TestEditProposal:
"""Tests for EditProposal class."""
def test_create_proposal(self):
"""Test creating an edit proposal."""
proposal = EditProposal(
proposal_id="test-123",
file_path=Path("/tmp/test.txt"),
original_content="Hello",
proposed_content="Hello, World!",
description="Add greeting",
)
assert proposal.proposal_id == "test-123"
assert proposal.status == EditStatus.PENDING
assert len(proposal.diff_lines) > 0
def test_diff_generation(self):
"""Test diff is generated correctly."""
proposal = EditProposal(
proposal_id="test-123",
file_path=Path("/tmp/test.txt"),
original_content="line1\nline2\nline3",
proposed_content="line1\nmodified\nline3",
description="Modify line 2",
)
diff_text = proposal.diff_text
assert "-line2" in diff_text
assert "+modified" in diff_text
def test_is_new_file(self):
"""Test new file detection."""
proposal = EditProposal(
proposal_id="test-123",
file_path=Path("/tmp/new.txt"),
original_content="",
proposed_content="New content",
description="Create new file",
)
assert proposal.is_new_file is True
assert proposal.is_deletion is False
def test_is_deletion(self):
"""Test deletion detection."""
proposal = EditProposal(
proposal_id="test-123",
file_path=Path("/tmp/delete.txt"),
original_content="Content to delete",
proposed_content="",
description="Delete file",
)
assert proposal.is_deletion is True
assert proposal.is_new_file is False
def test_to_dict(self):
"""Test converting proposal to dictionary."""
proposal = EditProposal(
proposal_id="test-123",
file_path=Path("/tmp/test.txt"),
original_content="Hello",
proposed_content="Hello, World!",
description="Add greeting",
)
data = proposal.to_dict()
assert data["proposal_id"] == "test-123"
assert data["description"] == "Add greeting"
assert data["status"] == "pending"
assert "diff" in data
class TestSafeEditPipeline:
"""Tests for SafeEditPipeline class."""
@pytest.fixture
def temp_workspace(self):
"""Create a temporary workspace."""
with tempfile.TemporaryDirectory() as tmpdir:
yield Path(tmpdir)
@pytest.fixture
def pipeline(self, temp_workspace):
"""Create a pipeline with temp workspace."""
return SafeEditPipeline(workspace=temp_workspace)
def test_create_pipeline(self, temp_workspace):
"""Test creating a pipeline."""
pipeline = SafeEditPipeline(workspace=temp_workspace)
assert pipeline.workspace == temp_workspace
assert pipeline.auto_approve is False
def test_propose_edit(self, pipeline, temp_workspace):
"""Test proposing an edit."""
# Create a file to edit
test_file = temp_workspace / "test.txt"
test_file.write_text("Original content")
proposal = pipeline.propose_edit(
file_path=test_file,
new_content="Modified content",
description="Test edit",
)
assert proposal.status == EditStatus.PENDING
assert proposal.original_content == "Original content"
assert proposal.proposed_content == "Modified content"
def test_propose_create(self, pipeline, temp_workspace):
"""Test proposing a new file."""
new_file = temp_workspace / "new.txt"
proposal = pipeline.propose_create(
file_path=new_file,
content="New file content",
description="Create new file",
)
assert proposal.is_new_file is True
assert proposal.status == EditStatus.PENDING
def test_propose_delete(self, pipeline, temp_workspace):
"""Test proposing a deletion."""
# Create a file to delete
test_file = temp_workspace / "delete.txt"
test_file.write_text("Content to delete")
proposal = pipeline.propose_delete(
file_path=test_file,
description="Delete file",
)
assert proposal.is_deletion is True
assert proposal.status == EditStatus.PENDING
def test_approve_proposal(self, pipeline, temp_workspace):
"""Test approving a proposal."""
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
proposal = pipeline.propose_edit(
file_path=test_file,
new_content="Modified",
description="Test",
)
result = pipeline.approve(proposal.proposal_id)
assert result is True
assert proposal.status == EditStatus.APPROVED
assert proposal.approved_at is not None
def test_reject_proposal(self, pipeline, temp_workspace):
"""Test rejecting a proposal."""
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
proposal = pipeline.propose_edit(
file_path=test_file,
new_content="Modified",
description="Test",
)
result = pipeline.reject(proposal.proposal_id, "Not needed")
assert result is True
assert proposal.status == EditStatus.REJECTED
assert proposal.error == "Not needed"
def test_apply_approved_edit(self, pipeline, temp_workspace):
"""Test applying an approved edit."""
test_file = temp_workspace / "test.txt"
test_file.write_text("Original content")
proposal = pipeline.propose_edit(
file_path=test_file,
new_content="Modified content",
description="Test",
)
pipeline.approve(proposal.proposal_id)
result = pipeline.apply_edit(proposal.proposal_id)
assert result is True
assert proposal.status == EditStatus.APPLIED
assert test_file.read_text() == "Modified content"
def test_apply_unapproved_fails(self, pipeline, temp_workspace):
"""Test that applying unapproved edit fails."""
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
proposal = pipeline.propose_edit(
file_path=test_file,
new_content="Modified",
description="Test",
)
# Don't approve
result = pipeline.apply_edit(proposal.proposal_id)
assert result is False
assert test_file.read_text() == "Original" # Unchanged
def test_apply_creates_new_file(self, pipeline, temp_workspace):
"""Test applying a new file creation."""
new_file = temp_workspace / "subdir" / "new.txt"
proposal = pipeline.propose_create(
file_path=new_file,
content="New content",
description="Create file",
)
pipeline.approve(proposal.proposal_id)
result = pipeline.apply_edit(proposal.proposal_id)
assert result is True
assert new_file.exists()
assert new_file.read_text() == "New content"
def test_apply_deletes_file(self, pipeline, temp_workspace):
"""Test applying a file deletion."""
test_file = temp_workspace / "delete.txt"
test_file.write_text("To delete")
proposal = pipeline.propose_delete(
file_path=test_file,
description="Delete",
)
pipeline.approve(proposal.proposal_id)
result = pipeline.apply_edit(proposal.proposal_id)
assert result is True
assert not test_file.exists()
def test_path_outside_workspace_rejected(self, pipeline, temp_workspace):
"""Test that paths outside workspace are rejected."""
with pytest.raises(ValueError, match="outside workspace"):
pipeline.propose_edit(
file_path=Path("/etc/passwd"),
new_content="hacked",
description="Bad edit",
)
def test_list_proposals(self, pipeline, temp_workspace):
"""Test listing proposals."""
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
pipeline.propose_edit(test_file, "Edit 1", "First")
pipeline.propose_edit(test_file, "Edit 2", "Second")
proposals = pipeline.list_proposals()
assert len(proposals) == 2
def test_list_proposals_by_status(self, pipeline, temp_workspace):
"""Test listing proposals filtered by status."""
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
p1 = pipeline.propose_edit(test_file, "Edit 1", "First")
pipeline.propose_edit(test_file, "Edit 2", "Second")
pipeline.approve(p1.proposal_id)
pending = pipeline.list_proposals(status=EditStatus.PENDING)
approved = pipeline.list_proposals(status=EditStatus.APPROVED)
assert len(pending) == 1
assert len(approved) == 1
def test_auto_approve_mode(self, temp_workspace):
"""Test auto-approve mode."""
pipeline = SafeEditPipeline(workspace=temp_workspace, auto_approve=True)
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
proposal = pipeline.propose_and_apply(
file_path=test_file,
new_content="Auto-modified",
description="Auto edit",
)
assert proposal.status == EditStatus.APPLIED
assert test_file.read_text() == "Auto-modified"
def test_approval_callback(self, temp_workspace):
"""Test approval callback."""
approved_proposals = []
def callback(proposal):
approved_proposals.append(proposal.proposal_id)
return True
pipeline = SafeEditPipeline(
workspace=temp_workspace,
approval_callback=callback,
)
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
proposal = pipeline.propose_and_apply(
file_path=test_file,
new_content="Callback-modified",
description="Callback edit",
)
assert proposal.proposal_id in approved_proposals
assert proposal.status == EditStatus.APPLIED
def test_clear_proposals(self, pipeline, temp_workspace):
"""Test clearing proposals."""
test_file = temp_workspace / "test.txt"
test_file.write_text("Original")
pipeline.propose_edit(test_file, "Edit 1", "First")
pipeline.propose_edit(test_file, "Edit 2", "Second")
count = pipeline.clear_proposals()
assert count == 2
assert len(pipeline.list_proposals()) == 0
def test_format_diff_for_display(self, pipeline, temp_workspace):
"""Test formatting diff for display."""
test_file = temp_workspace / "test.txt"
test_file.write_text("line1\nline2\nline3")
proposal = pipeline.propose_edit(
file_path=test_file,
new_content="line1\nmodified\nline3",
description="Modify line 2",
)
display = pipeline.format_diff_for_display(proposal)
assert "Edit Proposal" in display
assert "Modify line 2" in display
assert "Diff" in display
class TestGlobalPipeline:
"""Tests for global pipeline instance."""
def test_get_safe_edit_pipeline(self):
"""Test getting global pipeline."""
pipeline1 = get_safe_edit_pipeline()
pipeline2 = get_safe_edit_pipeline()
# Should return same instance
assert pipeline1 is pipeline2
@@ -0,0 +1,276 @@
"""
Unit tests for UnifiedSession and UnifiedSessionStore.
"""
import json
import os
import tempfile
import pytest
from pathlib import Path
from datetime import datetime
from praisonai.cli.session.unified import (
UnifiedSession,
UnifiedSessionStore,
get_session_store,
)
class TestUnifiedSession:
"""Tests for UnifiedSession class."""
def test_create_session(self):
"""Test creating a new session."""
session = UnifiedSession(session_id="test-123")
assert session.session_id == "test-123"
assert session.messages == []
assert session.total_input_tokens == 0
assert session.total_output_tokens == 0
assert session.request_count == 0
def test_add_user_message(self):
"""Test adding a user message."""
session = UnifiedSession(session_id="test-123")
session.add_user_message("Hello, world!")
assert len(session.messages) == 1
assert session.messages[0]["role"] == "user"
assert session.messages[0]["content"] == "Hello, world!"
assert "timestamp" in session.messages[0]
def test_add_assistant_message(self):
"""Test adding an assistant message."""
session = UnifiedSession(session_id="test-123")
session.add_assistant_message("Hello! How can I help?")
assert len(session.messages) == 1
assert session.messages[0]["role"] == "assistant"
assert session.messages[0]["content"] == "Hello! How can I help?"
def test_get_chat_history(self):
"""Test getting chat history in LLM format."""
session = UnifiedSession(session_id="test-123")
session.add_user_message("Hello")
session.add_assistant_message("Hi there!")
session.add_user_message("How are you?")
history = session.get_chat_history()
assert len(history) == 3
assert history[0] == {"role": "user", "content": "Hello"}
assert history[1] == {"role": "assistant", "content": "Hi there!"}
assert history[2] == {"role": "user", "content": "How are you?"}
def test_get_chat_history_with_limit(self):
"""Test getting limited chat history."""
session = UnifiedSession(session_id="test-123")
for i in range(10):
session.add_user_message(f"Message {i}")
history = session.get_chat_history(max_messages=3)
assert len(history) == 3
assert history[0]["content"] == "Message 7"
assert history[2]["content"] == "Message 9"
def test_update_stats(self):
"""Test updating token statistics."""
session = UnifiedSession(session_id="test-123")
session.update_stats(100, 50, 0.01)
session.update_stats(200, 100, 0.02)
assert session.total_input_tokens == 300
assert session.total_output_tokens == 150
assert session.total_cost == 0.03
assert session.request_count == 2
def test_clear_messages(self):
"""Test clearing messages."""
session = UnifiedSession(session_id="test-123")
session.add_user_message("Hello")
session.add_assistant_message("Hi")
session.clear_messages()
assert len(session.messages) == 0
def test_message_count(self):
"""Test message count property."""
session = UnifiedSession(session_id="test-123")
assert session.message_count == 0
session.add_user_message("Hello")
session.add_assistant_message("Hi")
assert session.message_count == 2
def test_user_message_count(self):
"""Test user message count property."""
session = UnifiedSession(session_id="test-123")
session.add_user_message("Hello")
session.add_assistant_message("Hi")
session.add_user_message("How are you?")
assert session.user_message_count == 2
def test_to_dict(self):
"""Test converting session to dictionary."""
session = UnifiedSession(session_id="test-123")
session.add_user_message("Hello")
data = session.to_dict()
assert data["session_id"] == "test-123"
assert len(data["messages"]) == 1
assert "created_at" in data
assert "updated_at" in data
def test_from_dict(self):
"""Test creating session from dictionary."""
data = {
"session_id": "test-456",
"workspace": "/tmp/test",
"created_at": "2024-01-01T00:00:00",
"updated_at": "2024-01-01T00:00:00",
"messages": [{"role": "user", "content": "Hello", "timestamp": "2024-01-01T00:00:00"}],
"metadata": {},
"total_input_tokens": 100,
"total_output_tokens": 50,
"total_cost": 0.01,
"request_count": 1,
"current_model": "gpt-4o-mini",
}
session = UnifiedSession.from_dict(data)
assert session.session_id == "test-456"
assert session.total_input_tokens == 100
assert len(session.messages) == 1
class TestUnifiedSessionStore:
"""Tests for UnifiedSessionStore class."""
@pytest.fixture
def temp_session_dir(self):
"""Create a temporary session directory."""
with tempfile.TemporaryDirectory() as tmpdir:
yield Path(tmpdir)
def test_create_store(self, temp_session_dir):
"""Test creating a session store."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
assert store.session_dir == temp_session_dir
assert temp_session_dir.exists()
def test_save_and_load_session(self, temp_session_dir):
"""Test saving and loading a session."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
session = UnifiedSession(session_id="test-123")
session.add_user_message("Hello")
session.add_assistant_message("Hi there!")
store.save(session)
# Clear cache to force reload from disk
store._cache.clear()
loaded = store.load("test-123")
assert loaded is not None
assert loaded.session_id == "test-123"
assert len(loaded.messages) == 2
assert loaded.messages[0]["content"] == "Hello"
def test_get_or_create_new(self, temp_session_dir):
"""Test get_or_create with new session."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
session = store.get_or_create("new-session")
assert session.session_id == "new-session"
assert (temp_session_dir / "new-session.json").exists()
def test_get_or_create_existing(self, temp_session_dir):
"""Test get_or_create with existing session."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
# Create and save a session
original = UnifiedSession(session_id="existing")
original.add_user_message("Original message")
store.save(original)
# Clear cache
store._cache.clear()
# Get or create should return existing
session = store.get_or_create("existing")
assert session.session_id == "existing"
assert len(session.messages) == 1
assert session.messages[0]["content"] == "Original message"
def test_delete_session(self, temp_session_dir):
"""Test deleting a session."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
session = store.get_or_create("to-delete")
assert (temp_session_dir / "to-delete.json").exists()
result = store.delete("to-delete")
assert result is True
assert not (temp_session_dir / "to-delete.json").exists()
def test_list_sessions(self, temp_session_dir):
"""Test listing sessions."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
# Create multiple sessions
for i in range(3):
session = store.get_or_create(f"session-{i}")
session.add_user_message(f"Message {i}")
store.save(session)
sessions = store.list_sessions()
assert len(sessions) == 3
assert all("session_id" in s for s in sessions)
assert all("message_count" in s for s in sessions)
def test_last_session(self, temp_session_dir):
"""Test last session tracking."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
# Create sessions
store.get_or_create("first")
store.get_or_create("second")
last_id = store.get_last_session_id()
assert last_id == "second"
last_session = store.get_last_session()
assert last_session is not None
assert last_session.session_id == "second"
def test_load_nonexistent(self, temp_session_dir):
"""Test loading a nonexistent session."""
store = UnifiedSessionStore(session_dir=temp_session_dir)
session = store.load("nonexistent")
assert session is None
class TestGlobalSessionStore:
"""Tests for global session store."""
def test_get_session_store(self):
"""Test getting global session store."""
store1 = get_session_store()
store2 = get_session_store()
# Should return same instance
assert store1 is store2
@@ -0,0 +1,630 @@
"""
Unit tests for the Unified Profiling Architecture.
Tests the core invariants:
1. Profiled execution produces identical output to non-profiled execution
2. Schema equivalence across invocation methods
3. Overhead bounds
4. Profile data bounds
"""
import pytest
from unittest.mock import patch
class TestExecutionRequest:
"""Tests for ExecutionRequest dataclass."""
def test_create_basic_request(self):
"""Test creating a basic execution request."""
from praisonai.cli.execution import ExecutionRequest
req = ExecutionRequest(prompt="What is 2+2?")
assert req.prompt == "What is 2+2?"
assert req.agent_name == "Assistant"
assert req.model is None
assert req.stream is False
assert req.tools == ()
def test_request_immutability(self):
"""Test that ExecutionRequest is immutable (frozen)."""
from praisonai.cli.execution import ExecutionRequest
req = ExecutionRequest(prompt="test")
with pytest.raises(AttributeError):
req.prompt = "modified"
def test_request_with_model(self):
"""Test creating request with model."""
from praisonai.cli.execution import ExecutionRequest
req = ExecutionRequest(prompt="test", model="gpt-4")
new_req = req.with_model("gpt-3.5-turbo")
assert req.model == "gpt-4"
assert new_req.model == "gpt-3.5-turbo"
assert req.prompt == new_req.prompt
def test_request_validation(self):
"""Test that empty prompt raises error."""
from praisonai.cli.execution import ExecutionRequest
with pytest.raises(ValueError):
ExecutionRequest(prompt="")
def test_request_to_dict(self):
"""Test serialization to dict."""
from praisonai.cli.execution import ExecutionRequest
req = ExecutionRequest(
prompt="test",
agent_name="TestAgent",
model="gpt-4",
)
d = req.to_dict()
assert d["prompt"] == "test"
assert d["agent_name"] == "TestAgent"
assert d["model"] == "gpt-4"
assert d["tools_count"] == 0
class TestExecutionResult:
"""Tests for ExecutionResult dataclass."""
def test_create_basic_result(self):
"""Test creating a basic execution result."""
from praisonai.cli.execution.result import ExecutionResult
result = ExecutionResult(output="four")
assert result.output == "four"
assert result.success is True
assert result.error is None
def test_result_from_error(self):
"""Test creating result from error."""
from praisonai.cli.execution.result import ExecutionResult
result = ExecutionResult.from_error("Something went wrong")
assert result.output == ""
assert result.success is False
assert result.error == "Something went wrong"
def test_result_duration(self):
"""Test duration calculation."""
from praisonai.cli.execution.result import ExecutionResult
result = ExecutionResult(
output="test",
start_time=1000.0,
end_time=1002.5,
)
assert result.duration_ms == 2500.0
class TestProfilerConfig:
"""Tests for ProfilerConfig."""
def test_default_config(self):
"""Test default profiler configuration."""
from praisonai.cli.execution.profiler import ProfilerConfig
config = ProfilerConfig()
assert config.layer == 1
assert config.limit == 30
assert config.track_network is False
def test_from_flags_basic(self):
"""Test creating config from basic --profile flag."""
from praisonai.cli.execution.profiler import ProfilerConfig
config = ProfilerConfig.from_flags(profile=True)
assert config.layer == 1
def test_from_flags_deep(self):
"""Test creating config from --profile --deep flags."""
from praisonai.cli.execution.profiler import ProfilerConfig
config = ProfilerConfig.from_flags(profile=True, deep=True)
assert config.layer == 2
assert config.show_callers is True
assert config.show_callees is True
def test_from_flags_network(self):
"""Test creating config with network tracking."""
from praisonai.cli.execution.profiler import ProfilerConfig
config = ProfilerConfig.from_flags(profile=True, network=True)
assert config.track_network is True
class TestTimingBreakdown:
"""Tests for TimingBreakdown."""
def test_timing_to_dict(self):
"""Test timing serialization."""
from praisonai.cli.execution.profiler import TimingBreakdown
timing = TimingBreakdown(
total_ms=1000.0,
imports_ms=500.0,
agent_init_ms=10.0,
execution_ms=490.0,
)
d = timing.to_dict()
assert d["total_ms"] == 1000.0
assert d["imports_ms"] == 500.0
assert d["agent_init_ms"] == 10.0
assert d["execution_ms"] == 490.0
class TestProfileReport:
"""Tests for ProfileReport."""
def test_report_schema_version(self):
"""Test that schema version is set."""
from praisonai.cli.execution.profiler import ProfileReport, SCHEMA_VERSION
report = ProfileReport(run_id="test123")
assert report.schema_version == SCHEMA_VERSION
assert report.schema_version == "1.0"
def test_report_timestamp(self):
"""Test that timestamp is auto-generated."""
from praisonai.cli.execution.profiler import ProfileReport
report = ProfileReport(run_id="test123")
assert report.timestamp is not None
assert "T" in report.timestamp # ISO 8601 format
def test_report_to_dict(self):
"""Test report serialization."""
from praisonai.cli.execution.profiler import (
ProfileReport, TimingBreakdown, InvocationInfo
)
report = ProfileReport(
run_id="test123",
timing=TimingBreakdown(total_ms=100),
invocation=InvocationInfo(method="test"),
)
d = report.to_dict()
assert d["schema_version"] == "1.0"
assert d["run_id"] == "test123"
assert "timing" in d
assert "invocation" in d
def test_report_to_json(self):
"""Test JSON serialization."""
from praisonai.cli.execution.profiler import ProfileReport
import json
report = ProfileReport(run_id="test123")
json_str = report.to_json()
parsed = json.loads(json_str)
assert parsed["run_id"] == "test123"
def test_report_to_text(self):
"""Test text formatting."""
from praisonai.cli.execution.profiler import ProfileReport
report = ProfileReport(run_id="test123")
text = report.to_text()
assert "test123" in text
assert "Timing Breakdown" in text
class TestProfilerBounds:
"""Tests for profile data bounds."""
def test_max_function_stats(self):
"""Test that function stats are bounded."""
from praisonai.cli.execution.profiler import MAX_FUNCTION_STATS
assert MAX_FUNCTION_STATS == 1000
def test_max_call_graph_edges(self):
"""Test that call graph edges are bounded."""
from praisonai.cli.execution.profiler import MAX_CALL_GRAPH_EDGES
assert MAX_CALL_GRAPH_EDGES == 5000
def test_max_network_requests(self):
"""Test that network requests are bounded."""
from praisonai.cli.execution.profiler import MAX_NETWORK_REQUESTS
assert MAX_NETWORK_REQUESTS == 100
class TestSchemaStability:
"""Tests for schema stability guarantees."""
def test_mandatory_fields_present(self):
"""Test that all mandatory fields are present in report."""
from praisonai.cli.execution.profiler import ProfileReport
report = ProfileReport(run_id="test")
d = report.to_dict()
# Mandatory fields
assert "schema_version" in d
assert "run_id" in d
assert "timestamp" in d
assert "invocation" in d
assert "timing" in d
assert "response_preview" in d
def test_optional_fields_nullable(self):
"""Test that optional fields can be None."""
from praisonai.cli.execution.profiler import ProfileReport
report = ProfileReport(run_id="test")
d = report.to_dict()
# Optional fields should not be present if None
assert "functions" not in d or d["functions"] is None
assert "call_graph" not in d or d["call_graph"] is None
assert "network" not in d or d["network"] is None
class TestInvocationInfo:
"""Tests for InvocationInfo."""
def test_version_auto_populated(self):
"""Test that versions are auto-populated."""
from praisonai.cli.execution.profiler import InvocationInfo
info = InvocationInfo(method="test")
assert info.python_version is not None
assert len(info.python_version) > 0
class TestCallGraph:
"""Tests for CallGraph."""
def test_edges_property(self):
"""Test edges property."""
from praisonai.cli.execution.profiler import CallGraph
graph = CallGraph(
callers={"func_b": ["func_a"]},
callees={"func_a": ["func_b"]},
)
edges = graph.edges
assert len(edges) == 1
assert ("func_a", "func_b") in edges
class TestRequestTiming:
"""Tests for RequestTiming."""
def test_ttfb_calculation(self):
"""Test time to first byte calculation."""
from praisonai.cli.execution.profiler import RequestTiming
timing = RequestTiming(
url="https://api.openai.com",
method="POST",
start_time=1000.0,
first_byte_time=1001.5,
end_time=1002.0,
status_code=200,
)
assert timing.ttfb_ms == 1500.0
assert timing.total_ms == 2000.0
# Integration tests (require mocking)
class TestProfilerIntegration:
"""Integration tests for Profiler class."""
def test_profiler_creates_report(self):
"""Test that profiler creates a valid report."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
# Mock at the profiler level by patching the imported _execute_core
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="four",
run_id="test123",
)
config = ProfilerConfig(layer=0) # Minimal profiling
profiler = Profiler(config)
req = ExecutionRequest(prompt="What is 2+2?")
result, report = profiler.profile_sync(req)
assert result.output == "four"
assert report.schema_version == "1.0"
assert report.timing.total_ms > 0
def test_output_equivalence_profiled_vs_non_profiled(self):
"""INVARIANT 1: Profiled execution produces identical output."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
expected_output = "test_output_value"
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output=expected_output,
run_id="test123",
)
req = ExecutionRequest(prompt="test")
# Layer 0 (minimal)
config0 = ProfilerConfig(layer=0)
result0, _ = Profiler(config0).profile_sync(req)
# Layer 1 (basic)
config1 = ProfilerConfig(layer=1)
result1, _ = Profiler(config1).profile_sync(req)
# Layer 2 (deep)
config2 = ProfilerConfig(layer=2)
result2, _ = Profiler(config2).profile_sync(req)
# All outputs must be identical
assert result0.output == expected_output
assert result1.output == expected_output
assert result2.output == expected_output
def test_schema_equivalence_across_invocation_methods(self):
"""INVARIANT 2: Schema equivalence across invocation methods."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=1)
# CLI direct
_, report1 = Profiler(config).profile_sync(req, invocation_method="cli_direct")
# Profile command
_, report2 = Profiler(config).profile_sync(req, invocation_method="profile_command")
# Schema must be identical
dict1 = report1.to_dict()
dict2 = report2.to_dict()
assert dict1["schema_version"] == dict2["schema_version"]
assert set(dict1["timing"].keys()) == set(dict2["timing"].keys())
assert set(dict1["invocation"].keys()) == set(dict2["invocation"].keys())
def test_data_bounds_function_stats(self):
"""INVARIANT 4: Function stats are bounded."""
from praisonai.cli.execution.profiler import (
Profiler, ProfilerConfig, MAX_FUNCTION_STATS
)
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=1, limit=50)
_, report = Profiler(config).profile_sync(req)
# Functions should be bounded by limit
if report.functions:
assert len(report.functions) <= config.limit
assert len(report.functions) <= MAX_FUNCTION_STATS
def test_layer_0_minimal_overhead(self):
"""INVARIANT 3: Layer 0 has minimal overhead (<1ms)."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
import time
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
# Fast mock execution
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=0)
start = time.perf_counter()
Profiler(config).profile_sync(req)
elapsed = (time.perf_counter() - start) * 1000
# Layer 0 overhead should be minimal (allow some margin for test environment)
# The actual profiling overhead (excluding execution) should be < 1ms
# We can't measure this precisely with mocks, but we verify it runs fast
assert elapsed < 100 # Very generous bound for test environment
def test_ttfr_is_populated(self):
"""Test that Time to First Response (TTFR) is populated and > 0."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=1)
_, report = Profiler(config).profile_sync(req)
# TTFR must be populated
assert report.timing.time_to_first_response_ms > 0
assert report.timing.first_output_ms >= 0
def test_first_output_less_than_total(self):
"""Test that first_output_ms <= total_ms."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=1)
_, report = Profiler(config).profile_sync(req)
# first_output must be <= total
assert report.timing.first_output_ms <= report.timing.total_ms
def test_timeline_phases_ordered(self):
"""Test that timeline phases are correctly ordered."""
from praisonai.cli.execution.profiler import TimingBreakdown
timing = TimingBreakdown(
total_ms=1000.0,
imports_ms=200.0,
agent_init_ms=50.0,
execution_ms=700.0,
)
timeline = timing.to_timeline()
# Timeline should have entries
assert len(timeline) > 0
# Each entry should have (name, start, duration)
for entry in timeline:
assert len(entry) == 3
name, start, duration = entry
assert isinstance(name, str)
assert isinstance(start, float)
assert isinstance(duration, float)
def test_decision_trace_in_deep_profile(self):
"""Test that decision trace is present in deep profile (layer 2)."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test", model="gpt-4")
config = ProfilerConfig(layer=2) # Deep profile
_, report = Profiler(config).profile_sync(req)
# Decision trace must be present in deep profile
assert report.decision_trace is not None
assert report.decision_trace.model_selected == "gpt-4"
assert report.decision_trace.profile_layer == 2
def test_module_breakdown_in_deep_profile(self):
"""Test that module breakdown is present in deep profile (layer 2)."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=2) # Deep profile
_, report = Profiler(config).profile_sync(req)
# Module breakdown must be present in deep profile
assert report.module_breakdown is not None
def test_text_output_includes_timeline(self):
"""Test that text output includes timeline section."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=1)
_, report = Profiler(config).profile_sync(req)
text = report.to_text()
# Text output must include timeline and TTFR
assert "Execution Timeline" in text
assert "Time to First Response" in text
def test_json_output_includes_ttfr(self):
"""Test that JSON output includes time_to_first_response_ms."""
from praisonai.cli.execution.profiler import Profiler, ProfilerConfig
from praisonai.cli.execution.request import ExecutionRequest
from praisonai.cli.execution.result import ExecutionResult
import json
with patch('praisonai.cli.execution.profiler._execute_core') as mock_exec:
mock_exec.return_value = ExecutionResult(
output="test",
run_id="test123",
)
req = ExecutionRequest(prompt="test")
config = ProfilerConfig(layer=1)
_, report = Profiler(config).profile_sync(req)
data = json.loads(report.to_json())
# JSON must include TTFR
assert "time_to_first_response_ms" in data["timing"]
assert data["timing"]["time_to_first_response_ms"] > 0
Whitespace-only changes.
@@ -0,0 +1,330 @@
"""
TDD Test Suite for PraisonAI TUI Widgets.
Tests for:
- ComposerWidget (Enter to send, Shift+Enter for newline)
- HelpScreen (F1 key)
- Keyboard shortcuts (Ctrl+Q, Ctrl+C, Ctrl+L)
- Queue panel (edit/delete)
- Tool panel (display tools)
"""
import pytest
from unittest.mock import MagicMock, patch, AsyncMock
# Check if textual is available
try:
from textual.pilot import Pilot
from textual.app import App
TEXTUAL_AVAILABLE = True
except ImportError:
TEXTUAL_AVAILABLE = False
pytest.skip("Textual not available", allow_module_level=True)
class TestComposerWidget:
"""Tests for ComposerWidget."""
@pytest.mark.asyncio
async def test_submit_text_area_enter_triggers_submit(self):
"""Test that Enter key triggers submit."""
from praisonai.cli.features.tui.widgets.composer import SubmitTextArea
# Create a mock app context
text_area = SubmitTextArea("")
# Verify the class exists and has SubmitRequested message
assert hasattr(SubmitTextArea, 'SubmitRequested')
@pytest.mark.asyncio
async def test_composer_widget_has_correct_bindings(self):
"""Test ComposerWidget has correct key bindings."""
from praisonai.cli.features.tui.widgets.composer import ComposerWidget
# Check bindings include enter for submit
binding_keys = [b.key for b in ComposerWidget.BINDINGS]
assert "enter" in binding_keys
assert "escape" in binding_keys
class TestHelpScreen:
"""Tests for HelpScreen."""
def test_help_screen_exists(self):
"""Test HelpScreen can be imported."""
from praisonai.cli.features.tui.screens.help import HelpScreen
assert HelpScreen is not None
def test_help_screen_has_dismiss_binding(self):
"""Test HelpScreen has escape binding to dismiss."""
from praisonai.cli.features.tui.screens.help import HelpScreen
binding_keys = [b.key for b in HelpScreen.BINDINGS]
assert "escape" in binding_keys
assert "q" in binding_keys
class TestTUIApp:
"""Tests for TUIApp."""
def test_tui_app_has_help_screen_registered(self):
"""Test TUIApp has help screen in SCREENS."""
from praisonai.cli.features.tui.app import TUIApp
assert "help" in TUIApp.SCREENS
assert "main" in TUIApp.SCREENS
assert "settings" in TUIApp.SCREENS
assert "queue" in TUIApp.SCREENS
def test_tui_app_has_ctrl_bindings(self):
"""Test TUIApp has Ctrl key bindings."""
from praisonai.cli.features.tui.app import TUIApp
binding_keys = [b.key for b in TUIApp.BINDINGS]
assert "ctrl+q" in binding_keys
assert "ctrl+c" in binding_keys
class TestMainScreen:
"""Tests for MainScreen."""
def test_main_screen_has_safe_default_bindings(self):
"""Test MainScreen has safe default bindings (no Ctrl/Fn by default)."""
from praisonai.cli.features.tui.screens.main import MainScreen
binding_keys = [b.key for b in MainScreen.BINDINGS]
# Safe defaults - single char shortcuts
assert "q" in binding_keys # quit
assert "colon" in binding_keys # command mode
assert "escape" in binding_keys # cancel
# Ctrl keys should NOT be in default bindings
assert "ctrl+q" not in binding_keys
assert "ctrl+c" not in binding_keys
# Function keys should NOT be in default bindings
assert "f1" not in binding_keys
class TestTUIConfig:
"""Tests for TUIConfig."""
def test_default_config_disables_ctrl_keys(self):
"""Test default config has Ctrl keys disabled."""
from praisonai.cli.features.tui.config import TUIConfig
config = TUIConfig()
assert config.enable_ctrl_keys is False
assert config.enable_fn_keys is False
assert config.enable_single_char is True
assert config.leader_key == ":"
def test_command_parsing(self):
"""Test command mode parsing."""
from praisonai.cli.features.tui.config import get_command
assert get_command("quit") == "quit"
assert get_command("q") == "quit"
assert get_command("exit") == "quit"
assert get_command("clear") == "clear"
assert get_command("cl") == "clear"
assert get_command("invalid") is None
class TestQueuePanel:
"""Tests for QueuePanelWidget."""
def test_queue_panel_has_delete_message(self):
"""Test QueuePanelWidget has DeleteRequested message."""
from praisonai.cli.features.tui.widgets.queue_panel import QueuePanelWidget
assert hasattr(QueuePanelWidget, 'DeleteRequested')
assert hasattr(QueuePanelWidget, 'EditRequested')
def test_queue_panel_has_delete_method(self):
"""Test QueuePanelWidget has delete_selected method."""
from praisonai.cli.features.tui.widgets.queue_panel import QueuePanelWidget
assert hasattr(QueuePanelWidget, 'delete_selected')
assert hasattr(QueuePanelWidget, 'edit_selected')
class TestToolPanel:
"""Tests for ToolPanelWidget."""
def test_tool_panel_has_set_available_tools(self):
"""Test ToolPanelWidget has set_available_tools method."""
from praisonai.cli.features.tui.widgets.tool_panel import ToolPanelWidget
assert hasattr(ToolPanelWidget, 'set_available_tools')
class TestInteractiveTools:
"""Tests for interactive tools loading."""
def test_get_interactive_tools_exists(self):
"""Test get_interactive_tools function exists."""
from praisonai.cli.features.interactive_tools import get_interactive_tools
assert callable(get_interactive_tools)
def test_tool_config_exists(self):
"""Test ToolConfig class exists."""
from praisonai.cli.features.interactive_tools import ToolConfig
assert ToolConfig is not None
class TestCommandPopup:
"""Tests for CommandPopupWidget."""
def test_command_popup_exists(self):
"""Test CommandPopupWidget can be imported."""
from praisonai.cli.features.tui.widgets.command_popup import CommandPopupWidget
assert CommandPopupWidget is not None
def test_command_info_dataclass(self):
"""Test CommandInfo dataclass works correctly."""
from praisonai.cli.features.tui.widgets.command_popup import CommandInfo
cmd = CommandInfo(
name="test",
description="Test command",
aliases=["t", "tst"]
)
assert cmd.name == "test"
assert cmd.description == "Test command"
assert cmd.aliases == ["t", "tst"]
assert cmd.display_name == "test (t, tst)"
def test_get_default_commands(self):
"""Test get_default_commands returns command list."""
from praisonai.cli.features.tui.widgets.command_popup import get_default_commands
commands = get_default_commands()
assert len(commands) > 0
# Check for essential commands
command_names = [c.name for c in commands]
assert "help" in command_names
assert "exit" in command_names
assert "clear" in command_names
assert "model" in command_names
def test_command_popup_has_messages(self):
"""Test CommandPopupWidget has required message classes."""
from praisonai.cli.features.tui.widgets.command_popup import CommandPopupWidget
assert hasattr(CommandPopupWidget, 'CommandSelected')
assert hasattr(CommandPopupWidget, 'Dismissed')
class TestMainScreenBackslash:
"""Tests for MainScreen backslash command support."""
def test_main_screen_has_backslash_binding(self):
"""Test MainScreen has backslash binding for commands."""
from praisonai.cli.features.tui.screens.main import MainScreen
binding_keys = [b.key for b in MainScreen.BINDINGS]
assert "backslash" in binding_keys
def test_main_screen_has_show_commands_action(self):
"""Test MainScreen has action_show_commands method."""
from praisonai.cli.features.tui.screens.main import MainScreen
assert hasattr(MainScreen, 'action_show_commands')
def test_main_screen_has_command_popup_handlers(self):
"""Test MainScreen has command popup event handlers."""
from praisonai.cli.features.tui.screens.main import MainScreen
assert hasattr(MainScreen, 'on_command_popup_widget_command_selected')
assert hasattr(MainScreen, 'on_command_popup_widget_dismissed')
class TestAutoTriggerEvents:
"""Tests for auto-trigger events (backslash, @, /)."""
def test_composer_has_backslash_typed_message(self):
"""Test ComposerWidget has BackslashTyped message."""
from praisonai.cli.features.tui.widgets.composer import ComposerWidget
assert hasattr(ComposerWidget, 'BackslashTyped')
def test_composer_has_at_typed_message(self):
"""Test ComposerWidget has AtTyped message for @ file autocomplete."""
from praisonai.cli.features.tui.widgets.composer import ComposerWidget
assert hasattr(ComposerWidget, 'AtTyped')
def test_composer_has_slash_typed_message(self):
"""Test ComposerWidget has SlashTyped message for / commands."""
from praisonai.cli.features.tui.widgets.composer import ComposerWidget
assert hasattr(ComposerWidget, 'SlashTyped')
def test_main_screen_has_auto_trigger_handlers(self):
"""Test MainScreen has auto-trigger event handlers."""
from praisonai.cli.features.tui.screens.main import MainScreen
assert hasattr(MainScreen, 'on_composer_widget_backslash_typed')
assert hasattr(MainScreen, 'on_composer_widget_at_typed')
assert hasattr(MainScreen, 'on_composer_widget_slash_typed')
class TestFilePopup:
"""Tests for FilePopupWidget."""
def test_file_popup_exists(self):
"""Test FilePopupWidget can be imported."""
from praisonai.cli.features.tui.widgets.file_popup import FilePopupWidget
assert FilePopupWidget is not None
def test_file_popup_has_messages(self):
"""Test FilePopupWidget has required message classes."""
from praisonai.cli.features.tui.widgets.file_popup import FilePopupWidget
assert hasattr(FilePopupWidget, 'FileSelected')
assert hasattr(FilePopupWidget, 'Dismissed')
def test_file_info_dataclass(self):
"""Test FileInfo dataclass works correctly."""
from praisonai.cli.features.tui.widgets.file_popup import FileInfo
file_info = FileInfo(path="test.py", file_type="file")
assert file_info.path == "test.py"
assert file_info.file_type == "file"
assert file_info.icon == "📄 "
dir_info = FileInfo(path="src/", file_type="directory")
assert dir_info.icon == "📁 "
def test_main_screen_has_file_popup_handlers(self):
"""Test MainScreen has file popup event handlers."""
from praisonai.cli.features.tui.screens.main import MainScreen
assert hasattr(MainScreen, 'on_file_popup_widget_file_selected')
assert hasattr(MainScreen, 'on_file_popup_widget_dismissed')
assert hasattr(MainScreen, '_show_file_popup')
assert hasattr(MainScreen, '_dismiss_file_popup')
class TestQueueLiveUpdates:
"""Tests for queue panel live updates."""
def test_app_has_update_queue_panel_live(self):
"""Test TUIApp has _update_queue_panel_live method."""
from praisonai.cli.features.tui.app import TUIApp
assert hasattr(TUIApp, '_update_queue_panel_live')
def test_queue_panel_has_reactive_counts(self):
"""Test QueuePanelWidget has reactive count properties."""
from praisonai.cli.features.tui.widgets.queue_panel import QueuePanelWidget
# Check reactive properties exist
assert hasattr(QueuePanelWidget, 'queued_count')
assert hasattr(QueuePanelWidget, 'running_count')
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+4 -4
View File
@@ -4276,7 +4276,7 @@ requires-dist = [
{ name = "praisonai-tools", marker = "extra == 'autogen'", specifier = ">=0.1.0" },
{ name = "praisonai-tools", marker = "extra == 'autogen-v4'", specifier = ">=0.1.0" },
{ name = "praisonai-tools", marker = "extra == 'crewai'", specifier = ">=0.1.0" },
{ name = "praisonaiagents", specifier = ">=0.6.0" },
{ name = "praisonaiagents", specifier = ">=0.6.2" },
{ name = "pyautogen", marker = "extra == 'autogen'", specifier = "==0.2.29" },
{ name = "pydantic", marker = "extra == 'chat'", specifier = "<=2.10.1" },
{ name = "pydantic", marker = "extra == 'code'", specifier = "<=2.10.1" },
@@ -4324,7 +4324,7 @@ wheels = [
[[package]]
name = "praisonaiagents"
version = "0.6.0"
version = "0.6.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -4333,9 +4333,9 @@ dependencies = [
{ name = "pydantic" },
{ name = "rich" },
]
sdist = { url = "https://files.pythonhosted.org/packages/4b/3c/a25740d7e3da4ebea0d83319d412650a016d91b6eb2f2653df1b28a3882f/praisonaiagents-0.6.0.tar.gz", hash = "sha256:f83528f6f1c0adea17cea25a1ea93f660e46ba43002e354717501e82112d9a96", size = 780850, upload-time = "2025-12-31T18:50:35.35Z" }
sdist = { url = "https://files.pythonhosted.org/packages/ea/d0/42418977331fb9a019331c49ee2eaf66c6dc6967725592a6a8bfb7e529ca/praisonaiagents-0.6.2.tar.gz", hash = "sha256:36d48b4c8b2915671033a05bb3983c4e613acdcc2fd8b3547271a6102f0c0928", size = 785586, upload-time = "2026-01-02T05:42:43.766Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/8e/18/f4f8360024ef26806831dde4ba3dad23950a4d94dde86085dde510ef1833/praisonaiagents-0.6.0-py3-none-any.whl", hash = "sha256:416c4550b6460b0866c1d59b284aacb86f23d849b38e75542f7056e530e84d80", size = 724880, upload-time = "2025-12-31T18:50:33.21Z" },
{ url = "https://files.pythonhosted.org/packages/62/aa/b3a6daeca388a975d4d21fc3e93847be2379726c5e7428d4efc28a31238d/praisonaiagents-0.6.2-py3-none-any.whl", hash = "sha256:440e45851dab829e9019b0ab35d80a2fa5d7c83a5aadb7269412cc119ede7890", size = 730473, upload-time = "2026-01-02T05:42:41.989Z" },
]
[[package]]