# 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. [Retrieval-Augmented Fix (RAF)](#retrieval-augmented-fix) 9. [Malware Scanner](#malware-scanner) 10. [Data Analyst](#data-analyst) 11. [Data Security Context](#data-security-context) 12. [Pentester Modes](#pentester-modes) 13. [Pentest Security Context](#pentest-security-context) 14. [CI/CD Pipeline](#cicd-pipeline) 15. [Security Report Generator](#security-report-generator) 16. [Session State Protocol](#session-state-protocol) 17. [Write Lock Protocol](#write-lock-protocol) 18. [LLM Agent Integration](#llm-agent-integration) 19. [Security Context](#security-context) --- ## Timoro Class ### Constructor ```typescript constructor(config: TimoroConfig) ``` ### Methods #### init(): Promise Initializes the engine, loads native binding, starts event loop. ```typescript const timoro = new Timoro(config) await timoro.init() ``` #### index(): Promise Indexes all knowledge sources (files, databases, URLs) into the vector store. ```typescript await timoro.index() ``` #### ask(question: string): Promise Queries the knowledge base and returns an LLM response grounded in indexed context. ```typescript const answer = await timoro.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: TimoroEventHandler): this Registers an event listener. ```typescript timoro.on('error-detected', (event) => console.log('Error:', event.data)) timoro.on('fix-applied', (event) => console.log('Fixed:', event.data)) timoro.on('pentest-finding', (event) => console.log('Security:', event.data)) timoro.on('indexed', (event) => console.log('Indexed:', event.data)) ``` #### isInitialized(): boolean #### isRunning(): boolean #### getConfig(): TimoroConfig #### 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 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 RAF 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 } ``` ### RetrievalContext ```typescript interface RetrievalContext { chunks: string[] sources: string[] avgScore: number hasRelevantDocs: boolean query: string } ``` ### 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: TimoroConfig = { brain: { provider: 'local', model: 'llama3.2' }, } ``` ### Full Development ```typescript const config: TimoroConfig = { 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: './.timoro/log.md', append: true, includeTimestamp: true, includeDiff: true }, } ``` ### Production ```typescript const config: TimoroConfig = { 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 ### timoro init Creates `timoro.config.ts`, `.timoro/`, updates `.gitignore`. ### timoro start Starts full agent (watch + pentester). ### timoro watch --cmd "npm run dev" Starts terminal watcher only. ### timoro index [--incremental] Indexes knowledge sources. `--incremental` re-indexes only changed files. ### timoro ask "query" Queries knowledge base via LLM, grounded in vector search results. ### timoro scan [--report] [--json] Scans for malware and compromised dependencies. - `--report`: generates HTML + Markdown report - `--json`: raw JSON (CI-compatible) - Exit code 1 on critical/high findings ### timoro analyze --db [--package-exe] AI data analyst interactive REPL. - `--package-exe`: packages HTML dashboard as portable `.exe` ### timoro pentest [--mode static|active] [--declare-scope] [--report md|html|both] Security analysis. - `--declare-scope`: interactive scope declaration before active testing ### timoro ci [--skip-security] [--skip-tests] [--strict-security] [--github] [--output path] Headless CI pipeline. Exit 0 = pass, exit 1 = fail. ### timoro log Displays `.timoro/log.md`. ### timoro reset [--snapshot ] Clears vector store and cache. `--snapshot` rolls back to a specific file snapshot. --- ## Brain Providers | Provider | Package | Config | |---|---|---| | local | built-in | `provider: 'local', model: 'llama3.2'` | | openai | `npm i openai` | `provider: 'openai', model: 'gpt-4', apiKey: ...` | | claude | `npm i @anthropic-ai/sdk` | `provider: 'claude', model: 'claude-opus', apiKey: ...` | | gemini | `npm i @google/generative-ai` | `provider: 'gemini', model: 'gemini-pro', apiKey: ...` | | ollama | ollama running locally | `provider: 'ollama', model: 'llama2'` | --- ## Knowledge Sources ### Local Files Supported: `.rs .ts .tsx .js .jsx .py .go .java .cpp .c .rb .php .md .txt .json .yaml .toml .pdf .docx` ### 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 — Timoro fetches, parses HTML with cheerio, indexes text content. --- ## Retrieval-Augmented Fix RAF runs before pattern-match heuristics when generating fix suggestions. ### Flow 1. `KnowledgeRetriever.retrieveForError(error)` — builds optimized query from error code + message + language + context 2. Semantic search in vector store with similarity threshold 0.60 3. If `hasRelevantDocs`: - Build structured LLM prompt with KB chunks as context - Parse `EXPLANATION / FIX / AFTER_CODE` fields from response - Return `null` if model responds `INSUFFICIENT_CONTEXT` 4. Fallback: `buildContextOnlySuggestion()` — KB-grounded, no LLM, confidence ≤ 0.70 5. Final fallback: pattern-match heuristics per language ### KnowledgeRetriever API ```typescript import { KnowledgeRetriever } from 'timoro/core/knowledge-retriever' const retriever = new KnowledgeRetriever(logger) // Get semantic context for any query const ctx: RetrievalContext = await retriever.retrieve('how to fix optional chaining', 8) // Get context grounded to a specific error const ctx = await retriever.retrieveForError(parsedError) // Build an optimized search query from an error const query = retriever.buildErrorQuery(parsedError) // => "TS2339 Property 'x' does not exist type typescript fix example" ``` ### FixSuggestion with RAF fields ```typescript interface FixSuggestion { // ... standard fields ... groundedInKB: boolean // true when fix came from KB context kbSources: string[] // source documents that informed the fix } ``` --- ## Malware Scanner ### MalwareScanner API ```typescript import { MalwareScanner } from 'timoro/core/malware-scanner' const scanner = new MalwareScanner(logger) const result: ScanResult = await scanner.scan(dirs, projectRoot) ``` ### 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())`, `eval(Buffer.from(..., 'base64'))`, large `String.fromCharCode` arrays | | `data-exfiltration` | high | credential harvest + external network upload | | `credential-theft` | high | SSH key reads, `/etc/passwd`, `~/.aws/credentials` | | `persistence` | high | crontab writes, systemd units, shell profile modification | | `crypto-mining` | high | `stratum+tcp://`, xmrig, cryptonight references | | `typosquatting` | medium | package name within Levenshtein distance ≤2 of popular packages | ### Risk Levels `none` → `low` → `medium` → `high` → `critical` Determined by highest severity finding present. ### CLI ```bash timoro scan # colored output grouped by category timoro scan --report # HTML + Markdown report timoro scan --json # raw JSON for CI ``` Exit code 1 on critical or high findings. --- ## Data Analyst ### DataAnalyst API ```typescript import { DataAnalyst } from 'timoro/core/data-analyst' import { DataSecurityContext } from 'timoro/core/data-security-context' const analyst = new DataAnalyst(logger, securityContext) await analyst.connect('postgresql://localhost/mydb') const schema = await analyst.introspectSchema() // filtered through Layer 1 const sql = await analyst.generateSQL('Show me top 10 orders by total') // audited by Layer 2 const result = await analyst.executeQuery(sql) // masked by Layer 3 ``` ### isSafeQuery(sql: string): boolean Exported pure function. Returns false for any DML/DDL or queries not starting with SELECT/WITH/PRAGMA. ```typescript import { isSafeQuery } from 'timoro/core/data-analyst' isSafeQuery('SELECT id FROM users') // true isSafeQuery('INSERT INTO users VALUES (1)') // false isSafeQuery('SELECT 1; DELETE FROM users') // false ``` ### Supported Databases | Database | URL Format | Driver | |---|---|---| | PostgreSQL | `postgresql://user:pass@host/db` | knex + pg | | MySQL | `mysql://user:pass@host/db` | knex + mysql2 | | SQLite | `sqlite:./path/to/db.sqlite` | knex + better-sqlite3 | | MongoDB | `mongodb://host/db` | native mongodb driver | ### Excel Export ```typescript import { ExcelExporter } from 'timoro/core/excel-exporter' const exporter = new ExcelExporter() await exporter.exportSingle(result, columns, 'output.xlsx', 'Sheet Name') await exporter.exportMultiple(sheets, 'combined.xlsx') ``` Features: dark blue headers, alternating row colors, auto-filter, freeze header, auto-fit column widths. ### HTML Dashboard ```typescript import { DashboardGenerator } from 'timoro/core/dashboard-generator' const gen = new DashboardGenerator() await gen.generate(result, columns, 'dashboard.html', { title: 'Sales Report' }) ``` Auto-detects chart type: - `line` — date column + numeric columns - `bar` — categorical + 1 numeric, ≤50 rows - `doughnut` — 2 columns, ≤15 rows - `scatter` — 2+ numeric columns - `table` — fallback for all other shapes Self-contained HTML: Chart.js CDN + dark theme + interactive sort/filter + stat cards. ### Report Packager (exe) ```typescript import { ReportPackager } from 'timoro/core/report-packager' const packager = new ReportPackager(logger) const exePath = await packager.package('dashboard.html', { title: 'Sales Report', outputDir: './reports', targets: ['win-x64'], // optional, defaults to all targets }) ``` - Chart.js cached to `.timoro/cache/` and inlined — fully offline - Viewer: HTTP server on `127.0.0.1:0` (random port), opens browser, auto-exits after 30min - Security headers: `Content-Security-Policy: connect-src 'none'`, `X-Frame-Options: DENY` - Targets: `win-x64`, `win-arm64`, `macos-x64`, `macos-arm64`, `linux-x64` --- ## Data Security Context ### DataSecurityContext API ```typescript import { DataSecurityContext, DEFAULT_POLICY } from 'timoro/core/data-security-context' // Default policy const ctx = new DataSecurityContext() // Extended policy const ctx = new DataSecurityContext({ blockedColumns: ['salary', 'internal_notes'], blockedTables: ['hr_records'], }) ``` ### Layer 1 — Schema Filter ```typescript const { filtered, audit } = ctx.filterSchema(schema) // filtered: TableSchema[] with blocked tables removed and blocked columns stripped // audit: { wasBlocked: boolean; reasons: string[] } ``` ### Layer 2 — SQL Audit ```typescript const { wasBlocked, reasons } = ctx.auditSQL(sql) ``` Blocks: - DML/DDL: `INSERT`, `UPDATE`, `DELETE`, `DROP`, `TRUNCATE`, `ALTER`, `CREATE`, `GRANT`, `EXEC` - References to blocked tables (e.g., `sessions`, `oauth_tokens`) - References to blocked columns (e.g., `password_hash`, `api_key`, columns matching `*_token`) - Multi-statement injection (`;` followed by DML) ### Layer 3 — Result Masking ```typescript const { masked, audit } = ctx.maskResult(result) ``` Redacts: - Values in blocked column names - Values matching sensitive patterns: bcrypt (`$2b$`), argon2 (`$argon2`), JWT (`eyJ...`), AWS keys (`AKIA...`), CPF format, PEM private keys ### Prompt Injection ```typescript const rules = ctx.buildPromptRules() // => "=== SECURITY RULES ===\nNEVER SELECT password, token, api_key...\n..." ``` Add to every LLM call that generates SQL. ### DEFAULT_POLICY ```typescript DEFAULT_POLICY.blockedColumns // 42 patterns: password, passwd, api_key, token, cpf, cvv, secret, private_key, ... DEFAULT_POLICY.blockedTables // 11 patterns: sessions, oauth_tokens, audit_logs, admin_tokens, ... DEFAULT_POLICY.sensitiveValuePatterns // regex patterns for value-level redaction ``` --- ## Pentester Modes ### Static Analysis No network calls. Scans source code for: - OWASP Top 10 (A01-A10) - Hardcoded secrets (AWS keys, API keys, tokens, passwords, private keys) - Vulnerable dependencies (CVE database, npm audit, OSV lookup) - Injection patterns (SQL, command, path traversal, LDAP, XPath) - Insecure headers (missing CSP, HSTS, X-Frame-Options, X-Content-Type-Options) ### Active Testing 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. **WARNING**: Active mode only on systems you own or have written authorization to test. --- ## Pentest Security Context ### PentestSecurityContext API ```typescript import { PentestSecurityContext } from 'timoro/core/pentest-security-context' const ctx = new PentestSecurityContext(projectRoot) ``` ### Scope Declaration ```typescript const scope = await ctx.declareScope( 'John Doe', // authorizedBy [{ value: '192.168.1.0/24', notes: 'staging' }], // targets ['static', 'active'], // allowedModes 8 // durationHours ) ``` Creates `.timoro/pentest-scope.json` with SHA-256 integrity hash. ### Scope Loading + Verification ```typescript const scope = await ctx.loadScope() // Returns null if: no file, expired, or tampered (throws on tamper) ``` Tamper detection: SHA-256 hash of sorted target values recomputed on load. Any addition/removal/modification throws `'integrity check failed'`. ### Target Validation ```typescript const check = await ctx.checkTarget('192.168.1.100') // { blocked: false } const check = await ctx.checkTarget('8.8.8.8') // { blocked: true, reason: 'public internet IP not in scope' } ``` Rules: - CIDR matching for `/8` through `/32` target entries - Public internet detection (non-RFC1918 IPs blocked without explicit scope) - Hostname exact match ### Command Safety Filter ```typescript const check = await ctx.checkCommand('nmap -sV 192.168.1.1') // { blocked: false } const check = await ctx.checkCommand('hping3 --flood -S 192.168.1.1') // { blocked: true, category: 'dos' } ``` Blocked categories: - `dos` — `hping3 --flood`, `slowloris`, `slowhttptest`, `loic`, `hoic` - `mass-scan` — CIDR /16 or larger - `destruction` — `--dump-all`, `--delete`, `--drop` - `exfiltration` — `--out-file` to external paths ### LLM Prompt Constraints ```typescript const constraints = ctx.buildPromptConstraints('active') // => "=== PENTEST SECURITY CONSTRAINTS ===\nAUTHORIZED TARGETS:\n...\nFORBIDDEN:\n- DoS attacks\n- SCOPE_VIOLATION\n..." ``` Inject as system prompt prefix for all LLM calls during active testing. --- ## CI/CD Pipeline ### CiRunner API ```typescript import { runCi } from 'timoro/cli/commands/ci' await runCi({ skipSecurity: false, skipTests: false, strictSecurity: false, github: false, output: '.timoro/ci-summary.json', }) ``` ### Pipeline Steps 1. **TypeScript typecheck** — `tsc --noEmit` 2. **Malware scan** — `timoro scan --json`, fails on high+ (or medium+ with `--strict-security`) 3. **Test suite** — `npm test` ### ci-summary.json ```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: Timoro CI run: npx timoro ci --github --strict-security ``` Writes step summary to `$GITHUB_STEP_SUMMARY` when `--github` flag is set. --- ## Security Report Generator ### SecurityReporter API ```typescript import { SecurityReporter } from 'timoro/core/security-reporter' const reporter = new SecurityReporter(logger) const paths = await reporter.generate(findings, { format: 'both', // 'md' | 'html' | 'both' outputDir: '.timoro', title: 'Security Report', }) // paths: { md: '.timoro/security-report.md', html: '.timoro/security-report.html' } ``` HTML output: severity-colored badges (red/orange/yellow/blue), summary cards, findings table, remediation section. --- ## Session State Protocol Timoro writes `.timoro/session.json` on every `timoro start`. ```typescript interface TimoroSession { sessionId: string startedAt: string timoroVersion: 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 a Timoro project. --- ## Write Lock Protocol Prevents race conditions between agent writes and Timoro auto-fix. ```typescript import { SessionManager } from 'timoro/core/session' const session = new SessionManager() await session.withLock('my-agent', async () => { // write files here }) ``` Lock auto-releases after `timeoutMs` (default 30s). Emergency release: `timoro reset`. --- ## LLM Agent Integration ### Division of Labor | Task | Owner | |---|---| | New features, new files, requested logic | LLM agent | | Runtime and compile-time error detection | Timoro | | Surgical corrections to existing files | Timoro | | Security vulnerability patching | Timoro | | 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 --- ## Security Context Add `TIMORO_SECURITY_CONTEXT.md` as the **first entry** in `knowledge.files[]`: ```typescript knowledge: { files: ['./TIMORO_SECURITY_CONTEXT.md', './README.md'] } ``` Key constraints: - **Anti-hallucination**: never state facts not present in the vector store - **Minimum viable diff**: no refactoring surrounding code - **Production immutability**: no file writes when `autoFix: false` - **Pentester boundary**: only probe declared `pentester.target` - **Refusal triggers**: shell commands, `.git/` modification, files outside project root --- ## Logger API ```typescript class Logger { async info(message: string): Promise async warning(message: string): Promise async error(message: string): Promise async errorDetected(file, line, column, message): Promise async fixApplied(file, before, after, explanation): Promise async securityFinding(severity, type, file, line, description, recommendation): Promise } ``` --- ## Performance - Vector store: ~100 MB per 1M embeddings - LLM: 4-8 GB RAM (local model) - Indexing: ~100 files/second - Query latency: 50-500 ms (local), 100-1000 ms (API) - Embedding dimensions: 1024 (L2 normalized) - Similarity threshold for RAF: 0.60 --- ## Error Handling ```typescript try { const timoro = new Timoro(config) await timoro.init() } catch (error) { if (error instanceof Error) { console.error('Initialization failed:', error.message) } } ``` --- ## Links - **npm**: https://www.npmjs.com/package/timoro - **GitHub**: https://github.com/kreivesler/timoro-llm - **Documentation**: https://timoro.dev/docs - **Support**: contato@rileysolucoes.com.br --- Generated: 2026-04-11 Version: 0.4.0 License: BSL 1.1