# uneven-ai — Extended API Reference Full TypeScript API documentation for AI agents and developers integrating with Uneven AI v1.0.8. ## Table of Contents 1. [Uneven Class](#uneven-class) 2. [Type Definitions](#type-definitions) 3. [Configuration](#configuration) 4. [Events](#events) 5. [CLI Commands](#cli-commands) 6. [Brain Providers](#brain-providers) 7. [Knowledge Sources](#knowledge-sources) 8. [Malware Scanner](#malware-scanner) 9. [Data Analyst](#data-analyst) 10. [Data Security](#data-security) 11. [Pentester Modes](#pentester-modes) 12. [CI/CD Pipeline](#cicd-pipeline) 13. [Session State Protocol](#session-state-protocol) 14. [Write Lock Protocol](#write-lock-protocol) 15. [LLM Agent Integration](#llm-agent-integration) --- ## Uneven Class ### Constructor ```typescript constructor(config: UnevenConfig) ``` ### Methods #### init(): Promise Initializes the engine, prepares the knowledge base, and starts internal services. ```typescript const ai = new Uneven(config) await ai.init() ``` #### index(): Promise Indexes all knowledge sources (files, databases, URLs) into the local knowledge base. ```typescript await ai.index() ``` #### ask(question: string): Promise Queries the knowledge base and returns a response grounded in indexed context. ```typescript const answer = await ai.ask('What is the authentication flow?') ``` #### watch(): Promise Starts the terminal watcher and autonomous fix agent. Blocks until stopped. #### stop(): Promise Stops all watchers and shuts down gracefully. #### pentest(): Promise Runs security analysis (static or active depending on config). #### on(event: EventType, handler: UnevenEventHandler): this Registers an event listener. ```typescript ai.on('error-detected', (event) => console.log('Error:', event.data)) ai.on('fix-applied', (event) => console.log('Fixed:', event.data)) ai.on('pentest-finding', (event) => console.log('Security:', event.data)) ai.on('indexed', (event) => console.log('Indexed:', event.data)) ``` #### isInitialized(): boolean #### isRunning(): boolean #### getConfig(): UnevenConfig #### getLogger(): Logger --- ## Type Definitions ### BrainConfig ```typescript interface BrainConfig { provider: 'local' | 'openai' | 'claude' | 'gemini' | 'ollama' model: string apiKey?: string temperature?: number // 0-1, default: 0.3 maxTokens?: number // default: 2048 } ``` ### KnowledgeConfig ```typescript interface KnowledgeConfig { dirs?: string[] files?: string[] db?: { url?: string; tables?: string[] } urls?: string[] externalProject?: string } ``` ### WatchConfig ```typescript interface WatchConfig { terminal?: string autoFix?: boolean // default: true (Pro) confirmBeforeFix?: boolean // default: false alertOnly?: boolean // default: false dirs?: string[] } ``` ### PentesterConfig ```typescript interface PentesterConfig { enabled?: boolean mode?: 'static' | 'active' target?: string // Required for active mode realtime?: boolean static?: { owasp?: boolean secrets?: boolean dependencies?: boolean injections?: boolean headers?: boolean } bruteforce?: BruteforceConfig firewall?: FirewallConfig active?: ActiveConfig network?: NetworkConfig severity?: 'low' | 'medium' | 'high' | 'critical' } ``` ### ParsedError ```typescript interface ParsedError { type: 'compiler' | 'runtime' | 'lint' | 'test' severity: 'error' | 'warning' | 'info' file: string line: number column: number message: string code: string // e.g., 'TS2339', 'GO_UNDEF', 'E0308' context: string[] // Lines around the error fullOutput: string } ``` ### FixSuggestion ```typescript interface FixSuggestion { file: string line: number before: string after: string confidence: number // 0-1 explanation: string groundedInKB?: boolean // true when fix came from knowledge base context kbSources?: string[] // source files that informed the fix } ``` ### SecurityFinding ```typescript interface SecurityFinding { severity: 'low' | 'medium' | 'high' | 'critical' category: string // e.g., 'obfuscation', 'remote-shell', 'supply-chain' confidence: number // 0-1 file?: string line?: number snippet: string description: string recommendation: string } ``` ### ScanResult ```typescript interface ScanResult { findings: SecurityFinding[] riskLevel: 'none' | 'low' | 'medium' | 'high' | 'critical' filesScanned: number durationMs: number } ``` ### TableSchema ```typescript interface TableSchema { name: string rowCount?: number columns: Array<{ name: string type: string nullable: boolean }> } ``` ### QueryResult ```typescript interface QueryResult { columns: string[] rows: Record[] rowCount: number durationMs: number } ``` ### PentestScope ```typescript interface PentestScope { authorizedBy: string targets: Array<{ value: string; notes?: string }> allowedModes: string[] createdAt: string // ISO 8601 expiresAt: string // ISO 8601 integrityHash: string // SHA-256 of targets } ``` --- ## Configuration ### Minimal ```typescript const config: UnevenConfig = { brain: { provider: 'local', model: 'llama3.2' }, } ``` ### Full Development ```typescript const config: UnevenConfig = { brain: { provider: 'local', model: 'llama3.2', temperature: 0.3, maxTokens: 2048 }, knowledge: { dirs: ['./src', './tests', './docs'], files: ['./README.md'], db: { url: process.env.DATABASE_URL, tables: ['users', 'products'] }, urls: ['https://docs.myapp.com'], }, watch: { terminal: 'npm run dev', autoFix: true, dirs: ['./src'] }, pentester: { enabled: true, mode: 'static', static: { owasp: true, secrets: true, dependencies: true, injections: true, headers: true }, severity: 'medium', }, log: { path: './.uneven/log.md', append: true, includeTimestamp: true, includeDiff: true }, } ``` ### Production ```typescript const config: UnevenConfig = { brain: { provider: 'claude', model: 'claude-opus', apiKey: process.env.ANTHROPIC_API_KEY }, knowledge: { dirs: ['./src'] }, watch: { terminal: 'node dist/server.js', autoFix: false, alertOnly: true }, pentester: { enabled: true, mode: 'static', severity: 'low' }, } ``` --- ## Events ```typescript type EventType = 'error-detected' | 'fix-applied' | 'pentest-finding' | 'indexed' | 'warning' | 'info' ``` --- ## CLI Commands ``` uneven-ai — open conversational shell (free) uneven-ai init — initialize project, download LLM, auto-detect GPU uneven-ai start — start the full agent (watch + pentester) uneven-ai watch [--cmd "..."] — start terminal watcher only uneven-ai index [--incremental] — index knowledge sources uneven-ai ask "query" — query knowledge base (unlimited, all plans) uneven-ai explain — explain a file in plain language (free) uneven-ai docs — generate Markdown documentation for a file (free) uneven-ai askf "task" — AI writes or edits files for the described task (Pro) uneven-ai review [--commit ] [--from ] [--staged] — AI code review (Pro) uneven-ai scan [--report] [--json] — malware and supply chain scan uneven-ai analyze --db [--package-exe] — AI data analyst REPL (Pro) uneven-ai pentest [--mode static|active] [--declare-scope] [--report md|html|both] — security analysis uneven-ai ci [--skip-security] [--skip-tests] [--strict-security] [--github] — CI pipeline (Pro) uneven-ai remote-shell — start HTTP/HTTPS server for bots and external tools uneven-ai license activate — activate Pro license uneven-ai license status — show tier and expiry uneven-ai license deactivate — release machine seat uneven-ai log — display activity log uneven-ai reset [--snapshot ] — clear knowledge base; optional rollback ``` --- ## Brain Providers | Provider | Config key | Requires | |---|---|---| | local | `provider: 'local'` | nothing — fully offline, GPU auto-detected | | openai | `provider: 'openai'` | API key | | claude | `provider: 'claude'` | API key | | gemini | `provider: 'gemini'` | API key | | ollama | `provider: 'ollama'` | Ollama installed locally | Free users can configure any provider using their own API key — no Pro upgrade required. --- ## Knowledge Sources ### Local Files Supported: `.ts .tsx .js .jsx .py .go .java .cpp .c .rb .php .md .txt .json .yaml .toml .pdf .docx .xlsx .csv` ### Databases ``` postgresql://user:pass@localhost:5432/mydb mysql://user:pass@localhost:3306/mydb sqlite:./database.sqlite mongodb+srv://user:pass@cluster.mongodb.net/db ``` ### URLs Any HTTP/HTTPS page — Uneven fetches, parses and indexes the text content. --- ## Malware Scanner ### Detection Categories | Category | Severity | Examples | |---|---|---| | `remote-shell` | critical | `/dev/tcp`, `nc -e`, `bash -i >&` | | `supply-chain` | critical | `curl \| bash` in postinstall | | `obfuscation` | high | `eval(atob())`, large `String.fromCharCode` arrays | | `data-exfiltration` | high | credential harvest + external upload | | `credential-theft` | high | SSH key reads, `/etc/passwd`, `~/.aws/credentials` | | `persistence` | high | crontab writes, systemd units, shell profile modification | | `crypto-mining` | high | mining pool references, known miner binaries | | `typosquatting` | medium | package name within edit distance ≤2 of popular packages | ### Risk Levels `none` → `low` → `medium` → `high` → `critical` Exit code 1 on critical or high findings (CI-compatible). ### CLI ```bash uneven-ai scan # colored output grouped by category uneven-ai scan --report # HTML + Markdown report uneven-ai scan --json # raw JSON for CI ``` --- ## Data Analyst Interactive REPL: natural language → generated SQL → human approval → execute → Excel/dashboard export. ### Supported Databases | Database | URL Format | |---|---| | PostgreSQL | `postgresql://user:pass@host/db` | | MySQL | `mysql://user:pass@host/db` | | SQLite | `sqlite:./path/to/db.sqlite` | | MongoDB | `mongodb://host/db` | ### Excel Export Features: dark blue headers, alternating rows, auto-filter, freeze header, auto-fit column widths. ### HTML Dashboard Auto-detects chart type from data shape (line, bar, doughnut, scatter, table). Self-contained HTML with interactive sort/filter and stat cards. ### Report Packager `--package-exe` bundles the HTML dashboard as an offline executable (Windows, macOS, Linux). Viewer opens in browser and auto-exits after 30 minutes. --- ## Data Security 3-layer defense — sensitive data never reaches the LLM or output: **Layer 1 — Schema Filter**: removes blocked tables and columns before the LLM generates SQL. **Layer 2 — SQL Audit**: blocks INSERT, UPDATE, DELETE, DROP, TRUNCATE, ALTER, CREATE, GRANT, EXEC, and references to sensitive tables. **Layer 3 — Result Masking**: redacts values matching sensitive patterns (bcrypt hashes, JWTs, AWS keys, private keys, CPF numbers). Default policy blocks 42 column name patterns and 11 table name patterns. --- ## Pentester Modes ### Static (mode: 'static') Source code analysis — no network calls: - OWASP Top 10 (A01–A10) - Hardcoded secrets (API keys, tokens, passwords, private keys) - Vulnerable dependencies - Injection patterns (SQL, command, path traversal, LDAP, XPath) - Insecure headers (missing CSP, HSTS, X-Frame-Options, X-Content-Type-Options) ### Active (mode: 'active') Real attack simulation — requires declared authorization scope. Tests: brute force, rate limit bypass, port scanning, SQL injection, XSS, IDOR, CORS misconfiguration, SSL/TLS analysis, hidden route enumeration, session hijacking. Scope declaration creates a tamper-evident scope file (integrity-checked on load). Any addition, removal, or modification of targets invalidates the scope. Target validation blocks public internet IPs and CIDR ranges /16 or larger without explicit scope. DoS tools are blocked unconditionally. **WARNING**: Active mode only on systems you own or have written authorization to test. --- ## CI/CD Pipeline ### Pipeline Steps 1. **TypeScript typecheck** — `tsc --noEmit` 2. **Malware scan** — fails on high+ (or medium+ with `--strict-security`) 3. **Test suite** — `npm test` ### Output ```json { "passed": true, "steps": [ { "name": "typecheck", "passed": true, "durationMs": 1200 }, { "name": "security-scan", "passed": true, "riskLevel": "none", "findings": 0, "durationMs": 800 }, { "name": "tests", "passed": true, "durationMs": 3400 } ], "totalDurationMs": 5400, "timestamp": "2026-04-11T10:00:00.000Z" } ``` ### GitHub Actions Integration ```yaml - name: Uneven AI CI run: npx uneven-ai ci --github --strict-security ``` --- ## Remote Shell Exposes a local HTTP/HTTPS server so external tools (Discord bots, Slack bots, custom scripts) can send natural-language messages to Uneven and receive JSON responses via the same classify + execute pipeline as the interactive shell. ### Config ```typescript remoteShell: { port: 4242, secret: 'your-secret-token', // optional https?: { // optional — omit for plain HTTP cert: './certs/cert.pem', key: './certs/key.pem', } } ``` ### Endpoints ``` POST /message Authorization: Bearer // if secret configured x-session-id: // optional — keeps conversation history per caller Content-Type: application/json { "text": "index my project" } GET /health → { "status": "ok", "version": "1.0.8" } ``` ### Response schema ```json { "action": "index", "message": "Indexing complete.", "output": "... captured stdout from the command ...", "status": "ok" } ``` `status` values: - `"ok"` — command completed successfully - `"error"` — command exited with non-zero code - `"async"` — command is long-running (watch, askf) and was dispatched in the background ### Session history `x-session-id` maintains a separate conversation history per caller (up to 6 turns, 30-minute idle TTL). Different Discord channels, users, or bots each get independent context by using different session IDs. ### Python bot example (discord.py) ```python import discord, aiohttp @client.event async def on_message(msg): if msg.author.bot: return async with aiohttp.ClientSession() as session: r = await session.post('http://localhost:4242/message', json={'text': msg.content}, headers={ 'Authorization': 'Bearer your-token', 'x-session-id': str(msg.channel.id), }) data = await r.json() reply = data['message'] if data['output']: reply += f"\n```\n{data['output'][:1800]}\n```" await msg.channel.send(reply) ``` ### Usage ``` uneven-ai remote-shell — standalone server (blocks until Ctrl+C) uneven-ai start — server auto-starts in background when remoteShell is configured ``` --- ## Session State Protocol Uneven AI writes `.uneven/session.json` on every `uneven-ai start`. ```typescript interface UnevenSession { sessionId: string startedAt: string unevenVersion: string projectRoot: string mode: 'development' | 'production' autoFix: boolean knowledge: { lastIndexedAt: string | null staleness: 'fresh' | 'stale' | 'unknown' } writeLock: { active: boolean lockedBy: string | null lockId: string | null timeoutMs: number } pendingDiffs: Array<{ file: string status: 'pending' | 'approved' | 'rejected' }> } ``` LLM agents must read this file before writing any file in an Uneven AI project. --- ## Write Lock Protocol Prevents race conditions between external agent writes and Uneven AI auto-fix. Check `writeLock.active` in session.json before writing. If inactive: set `writeLock.active = true` with a unique `lockId`, write your files, then set `writeLock.active = false` in a finally block. Lock auto-releases after `timeoutMs` (default 30s). Emergency release: `uneven-ai reset`. --- ## LLM Agent Integration ### Division of Labor | Task | Owner | |---|---| | New features, new files, requested logic | LLM agent | | Runtime and compile-time error detection | Uneven AI | | Surgical corrections to existing files | Uneven AI | | Security vulnerability patching | Uneven AI | | Diff approval / rejection | User | ### What Agents Must NOT Do - Re-scan files for errors after writing them - Apply patches to files they did not just create - Propose multi-file refactors to fix a single error - Generate speculative `try/catch` or defensive code --- ## Error Handling ```typescript try { const ai = new Uneven(config) await ai.init() } catch (error) { if (error instanceof Error) { console.error('Initialization failed:', error.message) } } ``` --- ## Links - **npm**: https://www.npmjs.com/package/uneven-ai - **Documentation**: https://uneven-ai.com/docs - **Support**: contato@rileysolucoes.com.br --- Version: 1.0.8 License: BSL 1.1