# timoro — Extended API Reference Full TypeScript API documentation for AI agents and developers. ## Table of Contents 1. [Timoro Class](#timoro-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. [Pentester Modes](#pentester-modes) --- ## Timoro Class ### Constructor ```typescript constructor(config: TimoroConfig) ``` Creates a new Timoro instance with the given configuration. ### Methods #### init(): Promise Initializes the Timoro engine, loads the native binding, and starts the event loop. ```typescript const timoro = new Timoro(config) await timoro.init() ``` #### index(): Promise Indexes all knowledge sources (files, databases, URLs). ```typescript await timoro.index() ``` #### ask(question: string): Promise Queries the knowledge base and returns an LLM response. ```typescript const answer = await timoro.ask('What is the authentication flow?') ``` #### watch(): Promise Starts the terminal watcher and autonomous agent. Blocks until stopped. ```typescript await timoro.watch() // runs until ai.stop() is called ``` #### stop(): Promise Stops all watchers and shuts down gracefully. ```typescript await timoro.stop() ``` #### pentest(): Promise Runs security analysis (static or active depending on config). ```typescript await timoro.pentest() ``` #### on(event: EventType, handler: TimoroEventHandler): this Registers an event listener. ```typescript timoro.on('error-detected', (event) => { console.log('Error:', event.data) }) ``` #### isInitialized(): boolean Returns true if initialize() has been called successfully. ```typescript if (!timoro.isInitialized()) await timoro.init() ``` #### isRunning(): boolean Returns true if watch() is currently running. ```typescript if (!timoro.isRunning()) await timoro.watch() ``` #### getConfig(): TimoroConfig Returns the current configuration object. ```typescript const config = timoro.getConfig() ``` #### getLogger(): Logger Returns the logger instance. ```typescript const logger = timoro.getLogger() await logger.info('Custom message') ``` --- ## Type Definitions ### BrainConfig ```typescript interface BrainConfig { provider: 'local' | 'openai' | 'claude' | 'gemini' | 'ollama' model: string // e.g., 'llama3.2', 'gpt-4', 'claude-opus' apiKey?: string // Required for non-local providers temperature?: number // 0-1, default: 0.3 maxTokens?: number // default: 2048 } ``` **Examples:** ```typescript // Local LLM (default, no API key needed) { provider: 'local', model: 'llama3.2' } // OpenAI { provider: 'openai', model: 'gpt-4', apiKey: process.env.OPENAI_API_KEY } // Anthropic Claude { provider: 'claude', model: 'claude-opus', apiKey: process.env.ANTHROPIC_API_KEY } // Google Gemini { provider: 'gemini', model: 'gemini-pro', apiKey: process.env.GOOGLE_API_KEY } // Ollama (running locally) { provider: 'ollama', model: 'llama2' } ``` ### DbConfig ```typescript interface DbConfig { url?: string // Database URL tables?: string[] // Which tables to index (optional) } ``` ### KnowledgeConfig ```typescript interface KnowledgeConfig { dirs?: string[] // Directories to scan recursively files?: string[] // Specific files to index db?: DbConfig // Database connection + tables urls?: string[] // External documentation URLs externalProject?: string // Path to another project } ``` **Examples:** ```typescript knowledge: { dirs: ['./src', './docs', './tests'], files: ['./README.md', './CHANGELOG.md', './API.md'], db: { url: 'postgresql://user:pass@localhost/mydb', tables: ['users', 'products', 'faq'] }, urls: [ 'https://docs.example.com', 'https://api.example.com/docs' ], externalProject: '../backup-service' } ``` ### WatchConfig ```typescript interface WatchConfig { terminal?: string // Command to execute and watch autoFix?: boolean // Auto-apply fixes (default: true) confirmBeforeFix?: boolean // Ask before fixing (default: false) alertOnly?: boolean // Monitor-only mode (default: false) dirs?: string[] // Directories to watch for changes } ``` **Examples:** ```typescript // Development: auto-fix enabled watch: { terminal: 'npm run dev', autoFix: true, dirs: ['./src'] } // Production: alerts only, no auto-fix watch: { terminal: 'node dist/server.js', autoFix: false, alertOnly: true } ``` ### FirewallConfig ```typescript interface FirewallConfig { enabled?: boolean // default: false portScan?: boolean // Scan for open ports cors?: boolean // Check CORS headers csp?: boolean // Check Content-Security-Policy ssl?: boolean // Check SSL/TLS configuration hsts?: boolean // Check HSTS header xFrameOptions?: boolean // Check X-Frame-Options } ``` ### BruteforceConfig ```typescript interface BruteforceConfig { enabled?: boolean // default: false endpoints?: string[] // e.g., ['/auth/login', '/admin'] wordlist?: string // 'built-in' or path to custom file detectRateLimit?: boolean // Check for rate limiting jwtWeak?: boolean // Test for weak JWT secrets sessionExpiry?: boolean // Test session validation rateLimit?: number // Requests per second } ``` ### ActiveConfig ```typescript interface ActiveConfig { sqlInjection?: boolean // Test SQL injection payloads xssReflected?: boolean // Test XSS vulnerabilities idor?: boolean // Test insecure direct object references directoryTraversal?: boolean // Test path traversal hiddenRoutes?: boolean // Enumerate hidden endpoints } ``` ### NetworkConfig ```typescript interface NetworkConfig { timeout?: number // Request timeout in ms (default: 5000) followRedirects?: boolean // Follow HTTP redirects rateLimit?: number // Global requests per second } ``` ### PentesterConfig ```typescript interface PentesterConfig { enabled?: boolean // default: false mode?: 'static' | 'active' // default: 'static' target?: string // Required for active mode: http://localhost:3000 realtime?: boolean // Analyze during watch (default: false) bruteforce?: BruteforceConfig firewall?: FirewallConfig active?: ActiveConfig network?: NetworkConfig static?: { owasp?: boolean // Check OWASP Top 10 secrets?: boolean // Find hardcoded secrets dependencies?: boolean // Audit npm packages injections?: boolean // Find injection patterns headers?: boolean // Check security headers } severity?: 'low' | 'medium' | 'high' | 'critical' } ``` ### LogConfig ```typescript interface LogConfig { path?: string // default: './.timoro/log.md' append?: boolean // default: true includeTimestamp?: boolean // default: true includeDiff?: boolean // default: true (before/after diffs) } ``` ### TimoroConfig ```typescript interface TimoroConfig { brain: BrainConfig knowledge?: KnowledgeConfig watch?: WatchConfig pentester?: PentesterConfig log?: LogConfig } ``` ### Error Types ```typescript interface ErrorEvent { file: string // e.g., 'src/services/auth.ts' line: number // Line number (1-indexed) column: number // Column number (1-indexed) message: string // Error message stackTrace: string // Full stack trace } ``` ### Fix Types ```typescript interface FixSuggestion { file: string // File to fix line: number // Line number before: string // Original code after: string // Fixed code confidence: number // 0-1, confidence level explanation: string // Why this fix is needed } ``` ### Security Finding ```typescript interface SecurityFinding { severity: 'low' | 'medium' | 'high' | 'critical' type: string // e.g., 'Secret Exposed', 'SQL Injection' file?: string // Source file (if applicable) line?: number // Line number (if applicable) description: string // What was found recommendation: string // How to fix it } ``` ### Index Stats ```typescript interface IndexStats { totalDocuments: number // Total documents indexed totalChunks: number // Total text chunks diskSize: number // Vector store size in bytes } ``` ### Retrieval Result ```typescript interface RetrievalResult { documents: string[] // Retrieved documents scores: number[] // Relevance scores (0-1) } ``` --- ## Configuration Examples ### Minimal Setup ```typescript const config: TimoroConfig = { brain: { provider: 'local', model: 'llama3.2' }, } const timoro = new Timoro(config) await timoro.init() ``` ### Full Development Setup ```typescript const config: TimoroConfig = { brain: { provider: 'local', model: 'llama3.2', temperature: 0.3, maxTokens: 2048, }, knowledge: { dirs: ['./src', './tests', './docs'], files: ['./README.md', './CONTRIBUTING.md'], db: { url: process.env.DATABASE_URL, tables: ['users', 'products', 'faq'], }, urls: ['https://docs.myapp.com'], externalProject: '../shared-services', }, watch: { terminal: 'npm run dev', autoFix: true, confirmBeforeFix: false, dirs: ['./src'], }, pentester: { enabled: true, mode: 'static', static: { owasp: true, secrets: true, dependencies: true, injections: true, headers: true, }, severity: 'medium', }, log: { path: './.timoro/log.md', append: true, includeTimestamp: true, includeDiff: true, }, } ``` ### Production Setup ```typescript const config: TimoroConfig = { brain: { provider: 'claude', model: 'claude-opus', apiKey: process.env.CLAUDE_API_KEY }, knowledge: { dirs: ['./src'], db: { url: process.env.DATABASE_URL, tables: ['logs', 'errors'] }, }, watch: { terminal: 'node dist/server.js', autoFix: false, // CRITICAL: no auto-fix in production alertOnly: true, }, pentester: { enabled: true, mode: 'active', target: process.env.API_URL, // e.g., http://api.company.com severity: 'low', // Capture all issues static: { owasp: true, secrets: true, dependencies: true, }, }, log: { path: '/var/log/timoro.md', append: true, includeDiff: false, // No diffs in production }, } ``` --- ## Events ```typescript type EventType = | 'error-detected' | 'fix-applied' | 'pentest-finding' | 'indexed' | 'warning' | 'info' ``` ### Event Object ```typescript interface TimoroEvent { type: EventType timestamp: Date data: unknown // Event-specific data } ``` ### Examples ```typescript timoro.on('error-detected', (event) => { const errorData = event.data as ErrorEvent console.log(`Error in ${errorData.file}:${errorData.line}`) }) timoro.on('fix-applied', (event) => { const fix = event.data as FixSuggestion console.log(`Fixed ${fix.file}: ${fix.explanation}`) }) timoro.on('pentest-finding', (event) => { const finding = event.data as SecurityFinding console.log(`[${finding.severity}] ${finding.type}: ${finding.description}`) }) timoro.on('indexed', (event) => { const stats = event.data as IndexStats console.log(`Indexed ${stats.totalDocuments} documents`) }) ``` --- ## CLI Commands ### timoro init Initializes a Timoro project in the current directory. ```bash timoro init ``` Creates: - `timoro.config.ts` — configuration file - `.timoro/` — directory for logs and cache - Updated `.gitignore` ### timoro start Starts the full Timoro agent (watch + pentester). ```bash timoro start ``` ### timoro watch Starts only the terminal watcher. ```bash timoro watch --cmd "npm run dev" ``` ### timoro index Indexes all knowledge sources. ```bash timoro index ``` Output shows: - Number of files indexed - Number of documents - Vector store size ### timoro ask Queries the knowledge base via LLM. ```bash timoro ask "What is the payment processing flow?" ``` ### timoro pentest Runs security analysis. ```bash timoro pentest --mode static # Code analysis only timoro pentest --mode active # Real attack testing ``` ### timoro log Displays the current log file. ```bash timoro log ``` Shows formatted `.timoro/log.md` with all detected issues and applied fixes. ### timoro reset Clears the vector store and cache. ```bash timoro reset ``` Removes: - `.timoro/vectors.usearch` — vector database - `.timoro/cache/` — embeddings cache - Resets `.timoro/log.md` --- ## Brain Providers Detailed ### Local (Default) ```typescript brain: { provider: 'local', model: 'llama3.2' // or mistral, etc. } ``` **Pros:** - No API calls - No rate limits - No costs - Privacy-preserving - Works offline **Cons:** - Requires compute power (4GB+ RAM) - Model downloads on first use ### OpenAI ```typescript brain: { provider: 'openai', model: 'gpt-4-turbo', apiKey: process.env.OPENAI_API_KEY } ``` **Models available:** gpt-4, gpt-4-turbo, gpt-4o, gpt-4o-mini **Requires:** `npm install openai` ### Anthropic Claude ```typescript brain: { provider: 'claude', model: 'claude-3-opus', apiKey: process.env.ANTHROPIC_API_KEY } ``` **Models available:** claude-3-opus, claude-3-sonnet, claude-3-haiku **Requires:** `npm install @anthropic-ai/sdk` ### Google Gemini ```typescript brain: { provider: 'gemini', model: 'gemini-pro', apiKey: process.env.GOOGLE_API_KEY } ``` **Models available:** gemini-pro, gemini-pro-vision **Requires:** `npm install @google/generative-ai` ### Ollama ```typescript brain: { provider: 'ollama', model: 'llama2' // or any model in ollama library } ``` **Requirements:** - Ollama installed and running (`ollama serve`) - Accessible at `http://localhost:11434` **Popular models:** llama2, neural-chat, mistral, dolphin-mixtral --- ## Knowledge Sources Supported ### Local Files Supported extensions: - **Code:** .rs, .ts, .tsx, .js, .jsx, .py, .go, .java, .cpp, .c, .rb, .php - **Docs:** .md, .txt - **Config:** .json, .yaml, .yml, .toml ### Databases ```typescript knowledge: { db: { url: 'postgresql://user:pass@localhost:5432/mydb', // PostgreSQL // or mysql://user:pass@localhost:3306/mydb // MySQL // or sqlite:./database.sqlite // SQLite // or mongodb+srv://user:pass@cluster.mongodb.net/db // MongoDB tables: ['users', 'products', 'orders'] } } ``` ### URLs ```typescript knowledge: { urls: [ 'https://docs.example.com', 'https://api.example.com/reference', 'https://blog.example.com' ] } ``` --- ## Pentester Modes Detailed ### Static Analysis Analyzes your codebase without making any network requests. **Scans for:** 1. **OWASP Top 10** (A01-A10) - Broken authentication - Sensitive data exposure - XML external entities - Broken access control - Security misconfiguration - Injection flaws - Cross-site scripting - Insecure deserialization - Using components with known vulnerabilities - Insufficient logging & monitoring 2. **Hardcoded Secrets** - AWS keys, API keys, tokens - Database passwords - Private keys - Session tokens 3. **Vulnerable Dependencies** - CVE database check - npm audit integration - OSV database lookup 4. **Injection Patterns** - SQL injection (string concatenation) - Command injection - Path traversal - LDAP injection 5. **Insecure Headers** - Missing Content-Security-Policy - Missing X-Frame-Options - Missing X-Content-Type-Options - Missing Strict-Transport-Security ### Active Testing Real attack simulation against your application. **Only use on systems you own or have explicit authorization.** **Tests:** 1. **Brute Force** - Login endpoint enumeration - Common password testing - Rate limit detection - JWT weak secret testing 2. **Network Analysis** - Port scanning - Service fingerprinting - CORS configuration check - SSL/TLS certificate analysis 3. **Injection Attacks** - SQL injection payloads - Command injection - Path traversal attempts - XPath injection 4. **Authentication Bypass** - Session hijacking - Token manipulation - Privilege escalation 5. **Information Disclosure** - Hidden route enumeration - Sensitive header parsing - Error message analysis - Directory listing --- ## Logger API ```typescript class Logger { // Async logging methods async info(message: string): Promise async warning(message: string): Promise async error(message: string): Promise async errorDetected(file: string, line: number, column: number, message: string): Promise async fixApplied(file: string, before: string, after: string, explanation: string): Promise async securityFinding(severity: string, type: string, file: string | undefined, line: number | undefined, description: string, recommendation: string): Promise } ``` ### Example ```typescript const logger = timoro.getLogger() await logger.info('Starting deployment') await logger.errorDetected('src/app.ts', 42, 15, 'TypeError: undefined property') await logger.fixApplied('src/app.ts', 'user.id', 'user?.id ?? null', 'Added optional chaining') await logger.securityFinding('high', 'SQL Injection', 'src/db.ts', 28, 'String concatenation in query', 'Use parameterized queries') ``` --- ## Performance Considerations - **Vector store size:** ~100MB per 1 million embeddings - **LLM memory:** Local model requires 4-8GB RAM - **Indexing speed:** ~100 files/second - **Query latency:** 50-500ms (local), 100-1000ms (API) --- ## Error Handling ```typescript try { const timoro = new Timoro(config) await timoro.init() } catch (error) { if (error instanceof Error) { console.error('Initialization failed:', error.message) } } ``` --- ## Support - 🐛 Issues: https://github.com/kreivesler/timoro-llm/issues - 💬 Discussions: https://github.com/kreivesler/timoro-llm/discussions - 📧 Email: contato@rileysolucoes.com.br --- Generated: 2025-01-15 Version: 0.1.0 License: BSL 1.1