Spaces:
Running
Running
File size: 11,095 Bytes
5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 5249791 81aa0b5 fc74cc0 873734c 81aa0b5 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 fc74cc0 5249791 873734c 5249791 873734c 5249791 81aa0b5 5249791 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | # SoniCoder v2.1 β Project Memory
> This file is the project's persistent memory. The agent reads it on every session.
> Edit it freely β it overrides defaults.
## What is SoniCoder?
SoniCoder v2.1 is a **local-first AI coding agent** that can:
### Core Capabilities
- Generate complete fullstack applications in any language/framework
- Read, write, and edit files in a sandboxed workspace
- Run shell commands (git, npm, pip, tests) with enhanced safety
- Apply specialized skills (frontend-design, feature-dev, code-review, debugging, fullstack-scaffold, commit-workflow)
- Respond to slash commands (/commit, /review, /feature, /design, /explain, /test, /refactor, /skill, /help)
- Deploy to HuggingFace Spaces with one click
- Manage and export conversation sessions
- Use code templates for rapid development
### v2.1 Enhancements
- **Session Management**: Persistent conversations with JSON/Markdown/HTML export
- **Code Templates**: Pre-built templates for Flask, React, Gradio, Express
- **Performance**: Response caching, model optimization, progress tracking
- **Security**: Enhanced command blocking, input validation, audit logging
- **Metrics**: Inference statistics, token counting, performance monitoring
- **New Models**: DeepSeek-Coder-1.3B support for advanced reasoning
## Architecture
```
app.py β Entry point: launches Gradio Server
code/
βββ config/constants.py β App config, system prompt, templates (ENHANCED)
βββ model/
β βββ loader.py β Model loading with progress & memory optimization
β βββ inference.py β Streaming inference with caching & metrics
βββ agent/__init__.py β Agent loop (model β tools, supports custom agents)
βββ tools/
β βββ fs.py β read_file, write_file, edit_file, glob, grep, list_dir
β βββ bash.py β Sandboxed shell execution (ENHANCED - audit trail)
β βββ todos.py β Todo list management
β βββ github.py β GitHub repo import (shallow clone + strip heavy dirs)
βββ skills/
β βββ __init__.py β Skill discovery + loading
β βββ builtins/ β Built-in skills (markdown)
βββ agents/ β Custom Agent system (AI-generated personas)
β βββ __init__.py β Agent CRUD + system-prompt builder
β βββ builtins/ β Built-in agents (code-reviewer, test-writer)
βββ commands/
β βββ __init__.py β Slash command parser + expander
β βββ builtins/ β Built-in commands (markdown)
βββ hooks/
β βββ __init__.py β Hook rule engine
β βββ builtins/ β Built-in hook rules (markdown)
βββ execution/
β βββ code_extractor.py β Code extraction from model output
β βββ python_runner.py β Sandboxed Python execution
β βββ gradio_runner.py β Gradio app subprocess runner
βββ huggingface/
β βββ dockerfile_gen.py β Auto Dockerfile/package.json for JS
β βββ push.py β HF Hub push + ZIP packaging
βββ websearch/google_scraper.py β DuckDuckGo + Google scraping (no API)
βββ server/
βββ routes.py β All HTTP + API endpoints
βββ chat_helpers.py β Chat history + prompt building (ENHANCED)
βββ session_manager.py β Session persistence & export (NEW)
βββ __init__.py β Server utilities & helpers
index.html β Frontend (single-file SPA)
workspace/ β Sandboxed agent workspace (auto-created)
downloads/ β Exported files directory (auto-created)
```
## Conventions
- **Python**: 3.11+, type hints everywhere, `from __future__ import annotations`
- **Style**: Black formatting, 4-space indent, 100 char line limit
- **Docstrings**: Google style for modules, functions, classes
- **Error handling**: catch specific exceptions, never bare `except:`
- **Logging**: use `logging.getLogger(__name__)`, never `print()`
- **Tests**: pytest, in `tests/` directory, `test_*.py` naming
- **Frontend**: single-file HTML with inline CSS/JS, no build step
## Server Rules
- All servers bind to `0.0.0.0` (never `localhost`)
- Default port: `7860` (HF Spaces convention)
- Sub-servers use `7861`, `7862`, etc.
- Graceful shutdown on SIGTERM/SIGINT
## Model Configuration
| Model | Type | Size | Best For |
|-------|------|------|----------|
| Qwen2.5-Coder-1.5B | Text | 3.0 GB | Tool-calling, code generation |
| MiniCPM5-1B | Text | 2.17 GB | Fast inference |
| MiniCPM-V-4.6 | VLM | 2.8 GB | Image understanding |
| DeepSeek-Coder-1.3B | Text | 2.6 GB | Advanced reasoning |
- Default: `Qwen/Qwen2.5-Coder-1.5B-Instruct`
- Loaded in background thread on startup
- Streaming inference via `TextIteratorStreamer`
- One model loaded at a time (memory conservation)
## Tool Call Format
The model calls tools by emitting fenced code blocks with `tool` as the language:
```tool
read_file
path: src/app.py
```
Multi-line values use YAML block scalars:
```tool
write_file
path: src/new.py
content: |
import os
def main():
pass
```
## Slash Commands
| Command | Description |
|---------|-------------|
| `/commit` | Create a git commit with a generated message |
| `/review` | Review current changes for bugs and quality |
| `/feature <desc>` | Guided feature development workflow |
| `/design <brief>` | Generate a distinctive frontend design |
| `/explain <target>` | Explain how code works |
| `/test <target>` | Generate tests |
| `/refactor <target>` | Refactor code for clarity |
| `/skill <name>` | Load and apply a skill |
| `/agent create <desc>` | AI generates a custom agent from natural-language description |
| `/agent use <name>` | Activate a saved agent |
| `/agent list` | List all saved agents |
| `/github <url> [subdir] [--branch <name>] [--into <path>]` | Import a GitHub repo into the workspace |
| `/help` | Show available commands and skills |
## Code Templates
Templates provide quick-start code for common patterns:
| Template ID | Name | Language | Framework |
|-------------|------|----------|-----------|
| `python-flask-api` | Flask REST API | Python | Flask |
| `react-todo-app` | React Todo App | JavaScript | React |
| `gradio-image-app` | Gradio Image Processor | Python | Gradio |
| `express-js-server` | Express.js Server | JavaScript | Express.js |
Access via API: `GET /api/templates` or `GET /api/templates/{id}`
## Session Management
Sessions are automatically created and persisted:
- **Storage**: `CONFIG_DIR/sessions/*.json`
- **Auto-save**: On each message
- **Export formats**: JSON, Markdown, HTML
- **Cleanup**: Sessions older than 30 days are auto-removed
### Session API Endpoints
| Endpoint | Description |
|----------|-------------|
| `POST /api/sessions/create` | Create new session |
| `GET /api/sessions/{id}` | Get session details |
| `PUT /api/sessions/{id}` | Update session metadata |
| `DELETE /api/sessions/{id}` | Delete session |
| `GET /api/sessions` | List sessions (with search) |
| `POST /api/sessions/{id}/export` | Export session |
## Performance Features
### Response Caching
- Similar prompts are cached for faster responses
- Configurable TTL (default: 5 minutes)
- Automatic cache invalidation
- Cache stats available via `/api/cache/stats`
### Model Optimization
- Automatic precision selection (bfloat16 > float16 > float32)
- Better Transformer structure when available
- Torch compile support (PyTorch 2.0+)
- Memory-efficient loading with offload support
### Metrics Tracking
Each inference call tracks:
- Time to first token (TTFT)
- Tokens per second
- Total generation time
- Cache hit/miss status
- Error information
## Security Enhancements
### Command Safety (Enhanced)
Additional blocked patterns:
- Regex-based pattern matching
- Fork bomb detection (`:(){:|:&};:`)
- Pipe-to-shell prevention (`curl ... | bash`)
- Root filesystem protection
- Character validation (null bytes, etc.)
### Input Validation
- Maximum prompt length: 10,000 characters
- Maximum file size: 10 MB
- Rate limiting: 30 requests/minute
- Environment variable scrubbing (secrets removal)
### Audit Trail
All bash commands are logged with:
- Timestamp
- Full command (truncated to 500 chars)
- Success/failure status
- Return code
- Timeout flag
- Execution duration
Access via: `GET /api/audit/log` or `code.tools.bash.get_command_history()`
## Hooks
Hooks are markdown rules that fire on events (`bash`, `file`, `prompt`, `stop`).
They can `warn` (show a message) or `block` (prevent the action).
Built-in hooks:
- `block-dangerous-rm` β blocks `rm -rf /`, `~`, `$HOME`, `..`
- `warn-debug-code` β warns on `console.log`, `debugger`, `print`, `alert`
- `warn-secrets-in-code` β warns on hardcoded API_KEY/SECRET/TOKEN/PASSWORD
- `warn-eval-exec` β warns on `eval()` and `exec()`
Users can add custom hooks in `workspace/.sonicoder/hooks/*.local.md`.
## Workspace
The agent's sandboxed filesystem lives at `./workspace/` (configurable via
`SONICODER_WORKSPACE` env var). All file tools refuse paths that escape this root.
## Deploy
Generated projects can be pushed to HuggingFace Spaces via the Deploy tab.
Supported SDKs:
- `static` β HTML/CSS/JS
- `gradio` β Python Gradio apps
- `streamlit` β Python Streamlit apps
- `docker` β JS/TS frameworks (auto-generates Dockerfile + package.json)
## Testing
Run the test suite:
```bash
# Install test dependencies
pip install pytest pytest-cov
# Run tests
pytest tests/ -v --cov=code --cov-report=html
# Run specific test file
pytest tests/test_bash_safety.py -v
```
## Troubleshooting
### Common Issues
**Model fails to load (OOM)**
- Try a smaller model (MiniCPM5-1B)
- Close other applications using GPU memory
- Check available RAM (need ~4GB for text models)
**Slow response times**
- Enable caching (default: on)
- Use smaller max_tokens for testing
- Consider CPU-only mode if GPU transfer is slow
**Commands being blocked**
- Review blocked patterns in `code/tools/bash.py`
- Check hook rules in `code/hooks/`
- Use `/help` for allowed operations
## Version History
### v2.1.0 (Current)
- Added DeepSeek-Coder-1.3B model support
- Implemented session management with persistence
- Added code template system
- Enhanced security with regex-based command blocking
- Added response caching and performance metrics
- Improved error handling and recovery
- Added export functionality (JSON/Markdown/HTML)
### v2.0.0
- Initial release with Gradio 6.x architecture
- Multi-model support (Qwen2.5-Coder, MiniCPM5, MiniCPM-V)
- Agent loop with tool calling
- Skills and commands system
- GitHub integration
- HuggingFace deployment
|