# Approvals API Source: https://docs.neuralcleave.com/api-reference/approvals Review and approve or deny pending shell command executions before they run. When `ShellTool` is configured with `require_approval=True`, every shell command is queued and waits for explicit approval before executing. The approvals API lets you review, approve, or deny these queued commands. ## GET /approvals/pending List all commands waiting for approval. ```bash theme={null} curl http://localhost:7432/api/v1/approvals/pending ``` ```json theme={null} { "pending": [ { "id": "550e8400-e29b-41d4-a716-446655440000", "tool_name": "shell", "command": "rm -rf /tmp/old-logs", "arguments": { "command": "rm -rf /tmp/old-logs", "timeout": 30, "workdir": "/home/user" }, "session_id": "default", "created_at": 1723123200.0 } ] } ``` ## POST /approvals//approve Approve a pending command. The command executes immediately after approval. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/approvals/550e8400-e29b-41d4-a716-446655440000/approve ``` ```json theme={null} { "approved": true, "id": "550e8400-e29b-41d4-a716-446655440000", "always_allowed": false } ``` Pass `{"always": true}` in the body to also persist a durable allowlist entry for the command's program name, so future matching commands skip the prompt entirely: ```bash theme={null} curl -X POST http://localhost:7432/api/v1/approvals/550e8400.../approve \ -H "Content-Type: application/json" -d '{"always": true}' ``` Returns `404` if the approval ID is not found (expired or already resolved). ## POST /approvals//deny Deny a pending command. The agent receives an error: `"Command denied by user approval gate."`. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/approvals/550e8400-e29b-41d4-a716-446655440000/deny ``` ```json theme={null} { "denied": true } ``` ## Approval timeout Approval requests expire after 120 seconds. If no decision is made, the command is automatically denied. ## Persistent allowlist Commands matching a stored entry skip the prompt entirely (subject to the `ask` mode below). ```bash theme={null} curl http://localhost:7432/api/v1/approvals/allowlist curl -X POST http://localhost:7432/api/v1/approvals/allowlist \ -H "Content-Type: application/json" -d '{"pattern": "git", "arg_pattern": "^git log"}' curl -X DELETE http://localhost:7432/api/v1/approvals/allowlist/3 ``` `pattern` is a glob matched against the program name (e.g. `git`, `curl*`); `arg_pattern` (optional) is a regex matched against the full command line. ## Security & ask modes ```bash theme={null} curl http://localhost:7432/api/v1/approvals/policy curl -X POST http://localhost:7432/api/v1/approvals/policy \ -H "Content-Type: application/json" -d '{"security": "allowlist", "ask": "on-miss"}' ``` | `security` | Behavior | | ----------- | ----------------------------------------------------------------------- | | `deny` | Every gated command is denied outright — no prompt. | | `allowlist` | Matching commands auto-approve; others fall through to `ask`. (default) | | `full` | Every gated command auto-approves — gate effectively disabled. | | `ask` | Behavior | | --------- | ------------------------------------------------------ | | `off` | Never prompt; an unmatched command is denied silently. | | `on-miss` | Prompt only when no allowlist entry matches. (default) | | `always` | Always prompt, even when an entry matches. | `GET /api/v1/approvals/policy` also returns `require_shell_approval` — whether the gate itself is actually enabled on the running `shell`/`browser` tools right now (defaults from `[security] require_shell_approval` in `config.toml`, see [Configuration](/configuration)). The `security`/`ask` modes above have no effect at all when this is `false` — every command just runs. It's `null` if the tool registry isn't available yet (still starting up). `POST /api/v1/approvals/policy` also accepts `require_shell_approval` to toggle the gate live on both tools, no restart needed: ```bash theme={null} curl -X POST http://localhost:7432/api/v1/approvals/policy \ -H "Content-Type: application/json" -d '{"require_shell_approval": true}' ``` ## Channel-forwarded approval A pending approval is also sent as a plain-text message via the channel that triggered it (Telegram, Slack, Discord, etc. — any of the 34 adapters). Reply directly in that channel: ``` approve a1b2c3d4 deny a1b2c3d4 ``` matching the short id shown in the notification — no separate UI visit required. ## CLI equivalents ```bash theme={null} neuralcleave approvals pending neuralcleave approvals approve [--always] neuralcleave approvals deny neuralcleave approvals allowlist list|add|remove ``` ## Enabling the approval gate ```python theme={null} from neuralcleave.tools.shell import ShellTool tool = ShellTool(require_approval=True, session_id="default") ``` ## Dashboard The `/terminal` page in the dashboard shows pending approvals and lets you approve or deny them with a click — without needing to call the API directly. # Channels API Source: https://docs.neuralcleave.com/api-reference/channels List, inspect, and manage connected channel adapters. ## GET /channels List all configured channels and their connection status. ```bash theme={null} curl http://localhost:7432/api/v1/channels ``` ```json theme={null} { "channels": [ { "name": "telegram", "status": "connected", "unread": 3, "messages_total": 1204, "last_message_at": "2026-08-08T14:22:00Z" }, { "name": "discord", "status": "connected", "unread": 0, "messages_total": 87, "last_message_at": "2026-08-08T12:10:00Z" }, { "name": "slack", "status": "disconnected", "unread": 0, "messages_total": 0, "last_message_at": null } ] } ``` ## GET /channels/ Get details for a specific channel. ```bash theme={null} curl http://localhost:7432/api/v1/channels/telegram ``` ```json theme={null} { "name": "telegram", "status": "connected", "config": { "enabled": true, "reply_mode": "direct", "rate_limit_per_minute": 30 }, "stats": { "messages_in_total": 1204, "messages_out_total": 1198, "errors_total": 2 } } ``` ## POST /channels//enable Enable a channel adapter (requires the channel to be configured in `config.toml`). ```bash theme={null} curl -X POST http://localhost:7432/api/v1/channels/telegram/enable # { "enabled": true } ``` ## POST /channels//disable Gracefully disconnect and disable a channel. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/channels/telegram/disable # { "disabled": true } ``` ## POST /channels//reconnect Reconnect a channel that has dropped. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/channels/telegram/reconnect # { "reconnecting": true } ``` ## GET /channels//messages Retrieve recent messages from a channel's history. ```bash theme={null} curl "http://localhost:7432/api/v1/channels/telegram/messages?limit=20" ``` ```json theme={null} { "messages": [ { "id": "msg-123", "direction": "in", "text": "What time is it?", "user": "user-456", "timestamp": "2026-08-08T14:20:00Z" }, { "id": "msg-124", "direction": "out", "text": "It's 2:20 PM UTC.", "timestamp": "2026-08-08T14:20:01Z" } ], "total": 1204 } ``` ## PATCH /channels//mark-read Mark a channel's unread messages as read. ```bash theme={null} curl -X PATCH http://localhost:7432/api/v1/channels/telegram/mark-read # { "marked_read": 3 } ``` # Chat API Source: https://docs.neuralcleave.com/api-reference/chat Send messages to NeuralCleave and receive LLM replies. ## POST /chat Send a message and receive a synchronous reply. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/chat \ -H "Content-Type: application/json" \ -d '{ "message": "What is the capital of France?", "session_id": "default" }' ``` **Request body** | Field | Type | Required | Description | | --------------- | ------- | -------- | ----------------------------------------------- | | `message` | string | Yes | The user message | | `session_id` | string | No | Session identifier (default: `"default"`) | | `system_prompt` | string | No | Override the system prompt for this request | | `stream` | boolean | No | Stream the reply via WebSocket (default: false) | **Response** ```json theme={null} { "reply": "Paris.", "session_id": "default", "tokens_in": 12, "tokens_out": 3, "provider": "openai", "model": "gpt-4o-mini" } ``` ## GET /sessions List active sessions. ```bash theme={null} curl http://localhost:7432/api/v1/sessions ``` ```json theme={null} { "sessions": [ { "id": "default", "message_count": 42, "last_active": "2026-08-08T14:22:00Z" } ] } ``` ## DELETE /sessions/ Clear a session's conversation history. ```bash theme={null} curl -X DELETE http://localhost:7432/api/v1/sessions/default # { "cleared": true } ``` ## WebSocket streaming Connect to `ws://localhost:7432/ws` and send: ```json theme={null} { "type": "chat", "message": "Hello", "session_id": "default" } ``` Receive frames: ```json theme={null} { "type": "message_chunk", "text": "Hello" } { "type": "message_chunk", "text": " there" } { "type": "message_done", "text": "Hello there!" } ``` ## POST /chat/canvas Send a message and request a structured output (canvas render). ```bash theme={null} curl -X POST http://localhost:7432/api/v1/chat/canvas \ -H "Content-Type: application/json" \ -d '{ "message": "Show me a bar chart of monthly sales", "session_id": "default" }' ``` The response includes `canvas_data` when the LLM produces chart-compatible output: ```json theme={null} { "reply": "Here is your bar chart.", "canvas_data": { "type": "bar", "labels": ["Jan", "Feb", "Mar"], "values": [100, 150, 120] } } ``` # MCP API Source: https://docs.neuralcleave.com/api-reference/mcp Spawn and manage the Model Context Protocol stdio server — exposes NeuralCleave tools to Claude Desktop, Cursor, and other MCP clients. The NeuralCleave MCP server implements [Model Context Protocol](https://modelcontextprotocol.io) over stdio (JSON-RPC 2.0). Once spawned, external MCP clients (Claude Desktop, Cursor, VS Code extensions) can call NeuralCleave's registered tools directly. ## POST /mcp/spawn Start the MCP stdio server subprocess. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/mcp/spawn ``` ```json theme={null} { "pid": 12345, "running": true, "already_running": false } ``` Calling this endpoint when the server is already running returns `"already_running": true` without starting a second process. ## GET /mcp/status Check whether the MCP server is running. ```bash theme={null} curl http://localhost:7432/api/v1/mcp/status ``` ```json theme={null} { "running": true, "pid": 12345 } ``` ## DELETE /mcp/server Stop the MCP stdio server. ```bash theme={null} curl -X DELETE http://localhost:7432/api/v1/mcp/server ``` ```json theme={null} { "killed": true } ``` ## MCP protocol The stdio server implements MCP protocol version `2024-11-05`: | Method | Description | | ------------ | -------------------------------------------------------------- | | `initialize` | Handshake; returns capabilities and server info | | `tools/list` | List all registered NeuralCleave tools as MCP tool descriptors | | `tools/call` | Call a tool by name with arguments | | `ping` | Liveness check | Notifications (requests without an `id`) are silently ignored per the MCP spec. ## Claude Desktop integration Add to `~/.config/claude/config.json`: ```json theme={null} { "mcpServers": { "neuralcleave": { "command": "python", "args": ["-m", "neuralcleave.mcp.server"] } } } ``` Restart Claude Desktop. NeuralCleave tools appear in the tool panel. ## Cursor integration Add to `.cursor/mcp.json` in your project root: ```json theme={null} { "mcpServers": { "neuralcleave": { "command": "python", "args": ["-m", "neuralcleave.mcp.server"] } } } ``` # API Overview Source: https://docs.neuralcleave.com/api-reference/overview NeuralCleave REST API — base URL, authentication, and response format. The NeuralCleave gateway exposes a REST API at `http://localhost:7432/api/v1`. All endpoints accept and return JSON. ## Base URL ``` http://localhost:7432/api/v1 ``` Change the host and port in `[gateway]` config if you've customized them. ## Authentication The API has no built-in authentication layer. When self-hosted on a local machine, the gateway is only accessible from localhost by default. If you expose the gateway publicly (behind nginx or a VPN), add authentication at the proxy level. ## Response format ### Success ```json theme={null} { "field": "value" } ``` ### Error ```json theme={null} { "detail": "Human-readable error message" } ``` HTTP status codes follow standard conventions: `200` for success, `201` for created, `404` for not found, `422` for validation errors. ## WebSocket The gateway also exposes a WebSocket at: ``` ws://localhost:7432/ws ``` The dashboard uses this for streaming chat replies (`message_chunk` / `message_done` frames) and voice transcripts. ## Liveness and readiness ```bash theme={null} curl http://localhost:7432/health # always 200 once the process is up curl http://localhost:7432/ready # 200 once startup fully completes, 503 while initializing ``` `/health` and `/ready` are deliberately distinct — an orchestrator that gates traffic admission on readiness (not mere liveness) should probe `/ready`. ## Gateway status ```bash theme={null} curl http://localhost:7432/api/v1/status ``` ```json theme={null} { "status": "ok", "version": "2.1.5", "uptime_seconds": 412.3, "active_sessions": 2, "runtime_available": true, "init_phase": "ready", "voice": { "stt_available": true, "tts_available": true, "wake_word_active": false }, "host": { "cpu_percent": 3.2, "memory_rss_bytes": 84213760, "disk_usage_percent": 41.7, "disk_free_bytes": 128849018880 }, "memory": { "semantic_available": true } } ``` `memory.semantic_available` reflects whether the local embedding model (`sentence-transformers`) has actually loaded — `true`/`false` once known, `null` if no embed call has happened yet since startup. Never triggers a model load itself (that can take a while on first use); it only reports cached state. See [Memory](/memory). `host` fields are `null` (not `0`) when `psutil` isn't installed or a read fails — that distinguishes "unavailable" from "genuinely zero." ## API sections Send messages and stream replies. PTT, continuous listen, wake word status. List, enable, and disable channels. Update LLM provider, model, thinking level, and voice settings. Provider credential status and live reachability (`GET /api/v1/models`). Per-model token usage and estimated cost (`GET /api/v1/usage`). Spawn and manage the MCP stdio server. Review pending exec commands and manage the persistent allowlist. Privacy settings and the (now persistent) audit log. ## Provider status ```bash theme={null} curl http://localhost:7432/api/v1/models curl "http://localhost:7432/api/v1/models?live=true" ``` ```json theme={null} { "providers": [ { "provider": "anthropic", "configured": true, "live_checked": false, "reachable": null, "detail": "" }, { "provider": "bedrock", "configured": null, "live_checked": false, "reachable": null, "detail": "live check not supported for this provider" } ] } ``` `configured` is `null` only for Bedrock, whose credentials are resolved by the AWS SDK's own chain rather than tracked by NeuralCleave directly. Reads the live runtime's `ModelRouter` when a gateway is running (reflecting any settings applied via `/settings/model`), otherwise builds one from the on-disk config. ## Usage & cost ```bash theme={null} curl http://localhost:7432/api/v1/usage ``` ```json theme={null} { "models": { "claude-opus-4-8": { "input_tokens": 4210, "output_tokens": 1340, "cost_usd": 0.1642 } }, "total_cost_usd": 0.1642 } ``` A live, in-process view (resets on restart) — scrape `/api/v1/metrics` for long-term history. # Privacy API Source: https://docs.neuralcleave.com/api-reference/privacy Read and clear the outbound HTTP audit log. Every outbound HTTP call NeuralCleave's providers make (method, URL, destination host, timestamp) is recorded to a privacy audit log — metadata only, never request/response bodies. The audit log now **persists across gateway restarts**, stored at `~/.neuralcleave/privacy_audit.db` (override via the `NEURALCLEAVE_AUDIT_DB_PATH` env var), with entries older than 90 days pruned automatically — durable enough for compliance review, bounded so it isn't an indefinite log. ## GET /privacy/report Get the audit report — every outbound HTTP call recorded, optionally filtered to one session. ```bash theme={null} curl http://localhost:7432/api/v1/privacy/report curl "http://localhost:7432/api/v1/privacy/report?session_id=default" ``` ```json theme={null} { "session_id": "default", "total": 2, "unique_destinations": ["api.anthropic.com"], "entries": [ { "session_id": "default", "method": "POST", "url": "https://api.anthropic.com/v1/messages", "destination": "api.anthropic.com", "timestamp": 1723123200.0 } ] } ``` Omit `session_id` to get every recorded session. ## DELETE /privacy/report Clear recorded audit entries — omit `session_id` to clear everything. ```bash theme={null} curl -X DELETE http://localhost:7432/api/v1/privacy/report curl -X DELETE "http://localhost:7432/api/v1/privacy/report?session_id=default" ``` ```json theme={null} { "cleared": 2, "session_id": null } ``` ## Privacy mode (zero external calls) With `privacy_mode = true`, every request routes to local Ollama — the report will show zero entries for any session started after enabling it: ```json theme={null} { "session_id": "default", "total": 0, "unique_destinations": [], "entries": [] } ``` See [Privacy Mode](/privacy-mode) for how to enable it. # Settings API Source: https://docs.neuralcleave.com/api-reference/settings Update LLM provider credentials, active model, thinking level, privacy mode, pipeline, and voice settings at runtime without a gateway restart. ## POST /settings/llm Update LLM provider API keys/endpoints. Also persists to `~/.neuralcleave/config.toml` under `[models]`, so keys survive a restart. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/settings/llm \ -H "Content-Type: application/json" \ -d '{ "openai_api_key": "sk-...", "anthropic_api_key": "sk-ant-...", "web_search_enabled": true }' ``` ```json theme={null} { "applied": true, "updated_fields": ["openai_api_key", "anthropic_api_key", "web_search_enabled"] } ``` Accepts a key/endpoint field per provider — see [LLM Providers](/llm-providers) for the full list (`gemini_api_key`, `deepseek_api_key`, `mistral_api_key`, `xai_api_key`, `cohere_api_key`, `moonshot_api_key`, `zhipuai_api_key`, `dashscope_api_key`, `qianfan_api_key`, `ark_api_key`, `ollama_base_url`, `openrouter_api_key`, `azure_api_key`, `azure_endpoint`, `bedrock_region`, `groq_api_key`, `together_api_key`, `fireworks_api_key`). ## POST /settings/model Force the active provider, set the reasoning-effort level, or toggle privacy mode — all runtime-only, **not** persisted to `config.toml` (unlike `/settings/llm` above). ```bash theme={null} curl -X POST http://localhost:7432/api/v1/settings/model \ -H "Content-Type: application/json" \ -d '{ "provider": "anthropic", "thinking": "high", "privacy_mode": false }' ``` ```json theme={null} { "applied": true, "settings": { "provider": "anthropic", "thinking": "high", "privacy_mode": false } } ``` | Field | Values | Effect | | -------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `provider` | a provider name (some accept aliases, e.g. `xai`/`grok`, `zhipu`/`glm`), or `null` | Force every request through this provider; `null` restores automatic task-based routing. | | `thinking` | `off`/`low`/`medium`/`high`/`xhigh`/`max`, or `null` | Normalized reasoning effort — see [LLM Providers → Reasoning effort](/llm-providers#reasoning-effort-thinking). | | `privacy_mode` | boolean | Forces every request to local Ollama when `true`. | At least one field must be present; unrecognized `provider`/`thinking` values return `422`. ## POST /settings/pipeline ```bash theme={null} curl -X POST http://localhost:7432/api/v1/settings/pipeline \ -H "Content-Type: application/json" \ -d '{ "max_tool_steps": 8 }' ``` ```json theme={null} { "applied": true, "updated_fields": ["max_tool_steps"], "settings": { "max_tool_steps": 8 } } ``` `max_tool_steps` (1–20) caps how many agentic tool-call iterations run per pipeline turn. ## POST /settings/voice Update voice settings. See [Voice API](/api-reference/voice) for the full field list and `GET /voice/config` for reading current values back. ## Slash-command equivalents Most settings are also reachable without the REST API, directly in any channel: ``` /model anthropic # same as {"provider": "anthropic"} /model auto # same as {"provider": null} /think high # same as {"thinking": "high"} /privacy on # same as {"privacy_mode": true} ``` # Voice API Source: https://docs.neuralcleave.com/api-reference/voice REST endpoints for PTT, continuous listening, wake word status, and voice device management. ## GET /voice/status Get the current state of all voice subsystems. ```bash theme={null} curl http://localhost:7432/api/v1/voice/status ``` ```json theme={null} { "runtime_available": true, "continuous_available": false, "continuous_listening": false, "ptt_available": true, "ptt_is_recording": false, "wake_detector_active": true, "is_handoff_active": false, "stt_available": true, "tts_available": true } ``` ## POST /voice/ptt/start Start a PTT recording session. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/voice/ptt/start ``` ```json theme={null} { "started": true } ``` ## POST /voice/ptt/stop Stop PTT recording and return the transcript. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/voice/ptt/stop ``` ```json theme={null} { "transcript": "What is the weather today?", "response": "It is currently 22°C and sunny in London.", "stopped": true } ``` ## POST /voice/continuous/start Start continuous voice listening mode. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/voice/continuous/start ``` ```json theme={null} { "started": true } ``` ## POST /voice/continuous/stop Stop continuous listening. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/voice/continuous/stop ``` ```json theme={null} { "stopped": true } ``` ## GET /voice/devices List available audio input/output devices. ```bash theme={null} curl http://localhost:7432/api/v1/voice/devices ``` ```json theme={null} { "input": [ { "name": "Built-in Microphone", "index": 0 }, { "name": "USB Headset", "index": 1 } ], "output": [ { "name": "Built-in Speakers", "index": 0 }, { "name": "USB Headset", "index": 1 } ], "active": { "input_device": "USB Headset", "output_device": "Built-in Speakers" } } ``` ## POST /settings/voice Persist STT settings to `config.toml`. Only `stt`, `stt_model`, and `stt_device` are accepted — a gateway restart is required before they take effect (there's no live TTS/device settings write path yet). ```bash theme={null} curl -X POST http://localhost:7432/api/v1/settings/voice \ -H "Content-Type: application/json" \ -d '{ "stt": "whisper", "stt_model": "small", "stt_device": "cpu" }' ``` ```json theme={null} { "ok": true, "restart_required": true, "updated_fields": ["stt", "stt_model", "stt_device"] } ``` # Architecture Source: https://docs.neuralcleave.com/architecture How the NeuralCleave gateway, pipeline, and channel adapters fit together. ## Overview NeuralCleave is a Python process (the **gateway**) with an optional Next.js dashboard. The gateway owns the full pipeline from incoming message to outgoing reply. ``` Channels (32) Gateway Providers (13) ────────────── ──────────────────────────── ───────────────── Telegram ──┐ ┌─ Channel Manager OpenAI Discord ──┤ message │ ├─ Session Manager Anthropic Slack ──┤─────────►│ ├─ Memory (embed + search) Gemini WhatsApp ──┤ │ ├─ Skill Router Ollama (local) ... ──┘ │ ├─ LLM Provider ... │ └─ Tool Chain Runner WebSocket ◄────────────┤ REST API ◄────────────┘ Dashboard ◄── WebSocket ◄──────────────────────────── Frontend ``` ## Components ### Gateway (Python / FastAPI) The gateway exposes a REST API at `http://localhost:7432/api/v1` and a WebSocket at `ws://localhost:7432/ws`. It orchestrates: * **Channel adapters** — one background task per enabled channel * **Session manager** — per-session state, history, and memory retrieval * **LLM provider** — interchangeable adapter (OpenAI, Anthropic, Ollama, …) * **Tool chain runner** — executes up to N skill/tool calls per pipeline run * **Voice pipeline** — STT → LLM → TTS, all in-process ### Memory Vector-embedded conversation store. Uses sentence-transformers for embedding and cosine similarity (or FAISS) for retrieval. Stored in a local SQLite file. ### Skills Python files loaded from `~/.neuralcleave/skills/`. Hot-reloaded without restart. Can be written by the agent itself. ### MCP server An optional Model Context Protocol stdio server (`neuralcleave.mcp.server`) exposes all registered tools over JSON-RPC 2.0, allowing external clients (Claude Desktop, Cursor, etc.) to call NeuralCleave tools. ### Exec approval A gate that intercepts `ShellTool` calls and requires explicit user approval via `POST /api/v1/approvals/{id}/approve` before execution. Prevents unattended destructive shell commands. ## Data flow — single message ``` 1. Channel adapter receives message 2. Session Manager loads history + retrieves relevant memory chunks 3. Context assembled: [system prompt] [memory] [history] [user message] 4. LLM Provider called → response streamed 5. Tool chain runner: if TOOL_CALL detected → call skill → feed result back → re-generate (up to max_tool_steps, default 5) 6. Final reply sent back through channel 7. Turn appended to memory store ``` ## Configuration files ``` ~/.neuralcleave/ config.toml # main config memory.db # SQLite memory store skills/ # installed skills logs/ # gateway logs audit/ # privacy audit log ``` ## Process model NeuralCleave runs as a single Python process. Each channel adapter is an `asyncio` background task. The LLM provider call is `await`-based, so the gateway handles concurrent conversations without threads. ## Tauri desktop app The dashboard can be packaged as a Tauri desktop app (Windows/macOS/Linux). The Tauri shell spawns the Python gateway as a sidecar process and serves the Next.js frontend from a local file server. # Changelog Source: https://docs.neuralcleave.com/changelog Release history and what changed in each version of NeuralCleave. ## Unreleased Everything below has merged to `main` since v2.1.5 but hasn't shipped under a bumped version number yet — per project policy, `__version__` only bumps at a full OpenClaw-parity launch, not for incremental gap-closing work. Tracked toward the "NeuralCleave v2.1.6" milestone. **Fixed `neuralcleave usage` reading the wrong process's counters, and a stale/incomplete pricing table** — the command read a `REGISTRY` singleton local to the CLI's own process, which never performs a generation, so it could only ever print "No LLM generations recorded" regardless of how much the actual running gateway had processed. Now proxies through `GET /api/v1/usage` first (the same pattern `approvals`/`hub install` use), falling back to the local registry only when no gateway is reachable. Separately, the pricing table used to price only 14 of 29 provider/model pairs the router can actually select — including missing `gemini-2.5-flash`/`gemini-2.5-pro` and `deepseek-coder`, the first-choice models for 6 of the router's 10 task types — added the missing entries (plus new Groq/Together/Fireworks pricing) and a test that fails if a routed model is ever left unpriced again. A model with genuinely no pricing entry now reports as unpriced (excluded from totals) rather than a misleading `$0.0000`, which was indistinguishable from a real free model (Ollama). **Fixed the embedded terminal's Stop button — it has never actually worked** — `_run_command()`'s subprocess was tracked in a local variable the "interrupt" handler and disconnect cleanup could never see, so both were permanent no-ops; on top of that, even a correctly-wired interrupt only killed the shell wrapper the command runs through, leaving whatever it actually spawned (e.g. a `python script.py`) running as an orphan. Both fixed: `_run_command()` now runs concurrently with the WebSocket's message loop so an interrupt can reach it (including one that arrives before the subprocess even exists yet), and termination now kills the whole process tree, not just its immediate shell. **Orchestrator routing now actually generates a response** — `AgentOrchestrator.route()` was a documented stub returning a hardcoded placeholder string in every deployment; it now calls `ModelRouter.generate()` with the selected node's `model_override` and returns the real generated text (with `model`/`provider`/`usage` in the result metadata) whenever the orchestrator has a router — which the live gateway now provides. New `ModelRouter.generate(model_override=...)` param backs this: forces one specific model for a single call without mutating router-wide state. Not the full `CognitivePipeline` (still no memory retrieval, reflection, or tool calls for a routed task) — that stays open as a larger future integration. `neuralcleave orchestrate route` now prints the generated content, not just the selected node name. **Canvas `html` block network egress locked down** — an agent-authored `html` block already ran in a sandboxed iframe (`sandbox="allow-scripts"`, isolating it from the parent page/cookies), but that alone doesn't restrict network access. Every `html` block's `srcdoc` now gets a `Content-Security-Policy` meta tag with `connect-src 'none'`, blocking all `fetch`/`XHR`/`WebSocket` egress by default. **Removed the orphaned `commands/` package** — a complete, parallel slash-command implementation (`/reset`, `/memory`, `/model`, `/status`, `/compact`, `/voice`, `/canvas`) that nothing in the live gateway ever called into; every real message goes through `agent/runtime.py`'s own separate inline dispatch instead, which also had five commands (`/think`, `/tag`, `/tags`, `/privacy`, `/forget`) this module never had. Removes no working functionality — the one command unique to it, `/canvas` as a typed chat message, was never reachable in production either. **Closed a WebSocket auth gap on the embedded terminal, main chat socket, and voice socket** — `gateway/terminal.py`'s own docstring claimed CORS protected its WebSocket, but Starlette's `CORSMiddleware` never applies to WebSocket scope at all (documented Starlette behavior, not a NeuralCleave bug), and the optional `gateway.api_key` middleware explicitly exempts every `/ws/*` path. Net effect: any local web page could open the embedded terminal's WebSocket and run arbitrary shell commands with zero authentication, with the full unsanitized process environment (every provider API key included) handed to the subprocess. Fixed with a new shared `gateway/origin_check.py` allow-list, consulted by `CORSMiddleware` and by each of `/ws/terminal`, `/ws`, and `/ws/voice`'s own pre-`accept()` origin check (rejecting a mismatched `Origin` with close code 1008; a missing `Origin` — the case for non-browser clients — is still allowed). `terminal.py`'s subprocess spawn now goes through the same `sanitize_env()` helper `ShellTool`/`BrowserAutomationTool` already use, instead of a raw, unscrubbed `os.environ`. **Hardened the Hub installer's fetch path** — `_fetch_code()` accepted cleartext `http://` despite its own documented https-only contract; the fetched code gets loaded and registered as a live, LLM-callable tool, so this let a network-position attacker substitute what actually runs. Now rejects anything but `https://`/`data:`. `neuralcleave hub install --checksum ` (and `POST /api/v1/hub/packages` with `expected_checksum`) now verifies the fetched code against a publisher-declared digest before installing — previously the recorded checksum only ever documented what was fetched, it couldn't verify anything. Also removed `scan_url()`: dead code with zero callers that would have raised if ever invoked from an async context. **Closed the WebSocket auth gap round 6 missed, and the regression it introduced** — round 6 added an origin check to `/ws`, `/ws/voice`, and `/ws/terminal` but missed a fourth socket, `/ws/canvas`, which accepted every connection unconditionally and streamed live agent-authored canvas content to any origin. Also fixed: the origin allow-list's regex only matched `localhost`, not `127.0.0.1` — the same host to every browser — so a page served on the gateway's own port via its loopback IP (e.g. `/canvas` at `http://127.0.0.1:7432/canvas`) had its WebSocket wrongly rejected. **Made the web/desktop chat UI actually benefit from the session-identity fix below** — the previous fix made `Session.session_id` stable, but `gateway/websocket.py` was passing its own per-*connection* ID (a fresh random UUID every reconnect) as the sender identity, so the fix never reached the primary chat client — only external channel adapters (Telegram, Discord, etc.) benefited. The frontend now generates and persists a client ID in `localStorage` and sends it on every `/ws`/`/ws/voice` connection; the gateway uses it as the durable memory identity instead of the connection's own ID. **Fixed config hot-reload watching the wrong file, and added an audit trail for the embedded terminal** — `ConfigWatcher` used to re-guess which config file to watch from two hard-coded candidates, ignoring the path actually passed via `-c custom.toml`; a save to the unrelated default path could then silently apply its `[security]` settings to a running gateway. `NeuralCleaveConfig` now records the path it was actually loaded from, and the watcher uses that directly. `watchfiles` and `cryptography` — both directly imported by real code but previously only present transitively — are now explicit dependencies. Separately: the embedded desktop terminal now records every command it runs to a lightweight, purpose-built log (`~/.neuralcleave/terminal_history.log`) — deliberately *not* gated behind an approval prompt like agent-issued shell commands are, since it's a direct interactive session for the operator's own machine, not an agent acting on their behalf. **Fixed the PWA mobile companion's broken chat, and stopped `/push/notify` claiming fake success** — the PWA app shell sent `{content: text}` but the server only reads `text`/`payload`, so every message sent from `/app` failed with "Empty message"; the receive side had the same mismatch (`delta`/`text` vs. `content`). `/push/notify` returned `{"sent": N}` implying N devices were notified, when no push-subscription client exists anywhere and no WebPush delivery is wired at all — it now honestly reports `sent: 0` with a separate `matched_subscribers` count. Push notifications themselves remain unbuilt (no subscription client, no VAPID key provisioning, no `pywebpush` dependency) — deliberately deferred rather than fixed in this pass. **Fixed long-term memory silently resetting on restart or idle timeout** — `Session.session_id`, the key every long-term-memory write/search/`/forget` path scopes by, was a fresh random UUID minted every time a `Session` object was constructed. A gateway restart or a single 30-minute idle gap (the default `SessionManager` timeout) silently orphaned a real user's entire memory history from every later lookup — "long-term" memory only actually lasted as long as one continuous in-process session. Now derived deterministically from `(channel, sender_id)`, so it survives both. Separately, `/forget ` now previews matches (count + snippets) before deleting anything; `/forget confirm` performs the actual deletion, matching the existing `approve `/`deny ` chat-command pattern. **Fixed wrong voice config keys across README, mintlify docs, and the API reference** — `stt_backend`/`tts_backend`/`tts_provider`/`wake_word_model`/`wake_word_sensitivity`/`wake_word_enabled` don't exist in `VoiceConfig`; the real fields are `stt`, `tts_engine`, `wake_word`, `wake_word_threshold`. Following the most prominent "Quick enable" example in the docs as written configured nothing at all, silently. Also fixed a doubly-wrong `PATCH /settings/voice` API reference example (real: `POST`, accepting only `stt`/`stt_model`/`stt_device`) and documented two previously-undocumented limitations found in the same pass: `tts_engine` only gates TTS on/off — it doesn't pin synthesis to one engine or skip the ElevenLabs→Kokoro→pyttsx3 fallback chain — and `privacy_mode` has no effect on the voice pipeline (it's a text-generation-only, in-chat-`/privacy`-only toggle, not a `[voice]` config key). **Browser tool environment sanitization** * `BrowserAutomationTool` launches a real Chromium child process via Playwright — it previously inherited every provider API key/secret in the gateway's own environment with no scrubbing at all, unlike `ShellTool`'s subprocess exec. Extracted the shared `sanitize_env()` helper (`neuralcleave/tools/env_sanitize.py`) so both tools get the same protection **Semantic memory, Hub installs, auto-compaction, the scheduler, and streaming `/think`** * `sentence-transformers` was never in the packaged dependency list `pip install neuralcleave` actually reads (only in a separate, non-canonical `requirements.txt`) — semantic memory has been silently dead by default in every real install; now a core dependency. `GET /api/v1/status` gains `memory.semantic_available` so a degraded install is visible instead of silent * Hub-marketplace installs (`neuralcleave hub install`, `POST /api/v1/hub/packages`) reported success while never actually registering the installed skill's tools with the live agent — the injected `PluginRegistry` reference was stored and never read. Installs now genuinely validate, write, load, and (when a registry is available) hot-reload * Auto-compaction (`ConversationCompactor.maybe_compact()`) and the heartbeat scheduler were both dead code — zero real call sites outside their own docstrings/tests despite claiming otherwise. The pipeline now auto-compacts a session's history after each turn once it crosses 50% of the context window, and a daily memory-archival job is registered with the scheduler on startup * `/think` is now wired all the way through the streaming path (`generate_stream()`/`_call_stream()`) — it previously had zero effect for NeuralCleave's own Web UI chat and voice assistant while working correctly for all 32 external channel adapters * `neuralcleave hub install/remove` and `neuralcleave orchestrate list/add/remove/route/status` now proxy through a running gateway's REST API first (same pattern as the `approvals` CLI fix), falling back to a local, disconnected instance only if no gateway is reachable * Corrected the `orchestrate` CLI's docs: node-selection logic is real, but routing itself is a stub that returns a placeholder — no node registered there is reachable from an actual conversation yet (full pipeline wiring deferred to a future round) **Exec-approval gate, readiness probe, and reasoning-control fixes** * Fixed the exec-approval gate being completely unreachable in production: `require_shell_approval`/`security_mode`/`ask_mode` had nowhere to be configured, so `ShellTool`/`BrowserAutomationTool` were always constructed with the gate off regardless of the CLI/REST surface built for it — new `[security]` config section closes this * The channel-forwarded approval notification described below now actually fires — `notify_channel()` existed but was never called from the live request path; `ApprovalQueue` gained an `on_request` hook and `AgentRuntime` wires itself into it * `GET /api/v1/approvals/policy` now also reports `require_shell_approval` sourced from the live tool registry, since the security/ask modes are meaningless when the gate itself is off; `POST` can now toggle it live too, no restart needed * New `approval_notifications_total` metric (by `outcome=sent|failed`) so the channel-forwarded notification above is actually observable * Fixed `GET /ready` reporting `ready: true` even when `AgentRuntime.from_config()` had raised and the runtime never got constructed at all — it now checks the actual runtime object and (when channels are configured) at least one connected adapter, not just a phase string * Extended `/think` to Ollama's native `think` field (collapsed to a boolean, since not every model supports the 3-tier string form); DeepSeek stays unmapped on purpose — its API has no per-request reasoning-effort field, only a model choice (`deepseek-chat` vs. `deepseek-reasoner`) * Fixed config hot-reload's `[security]` handling: the reload callback previously only logged that it applied "model settings + API keys" without touching anything at all; it now genuinely applies `[security]` live (model/API-key hot-reload remains unimplemented — the doc claim for that was removed rather than faked) **Provider status, host metrics, and reasoning control** * `neuralcleave models list/status [--live]` + `GET /api/v1/models` — credential-configured status for all 19 providers; `--live` adds a real HTTP reachability probe for the 9 providers with a documented, stable check * `GET /api/v1/status` now includes live CPU/RSS/disk gauges (`process_cpu_percent`, `process_memory_rss_bytes`, `host_disk_usage_percent`, `host_disk_free_bytes`) * New root-level `GET /ready` (200 once startup fully completes, 503 during init) — distinct from the always-200 `/health` * Normalized `/think off|low|medium|high|xhigh|max` reasoning-effort control, mapped to Anthropic's extended thinking and xAI/OpenRouter's `reasoning_effort` — also settable via `POST /api/v1/settings/model {"thinking": ...}` * `ModelRouter.from_config()` extracted as the single config→provider-key mapping (was previously duplicated inline and had silently dropped provider keys once before) **Cost tracking** * Static per-model USD pricing table turns already-recorded token counts into an estimated cost — `neuralcleave usage` CLI and `GET /api/v1/usage` * New `cost_usd_total` metric **Exec-approval allowlist** * Persistent glob/regex allowlist (`neuralcleave approvals allowlist list/add/remove`, `GET/POST /api/v1/approvals/allowlist`) with `security: deny|allowlist|full` and `ask: off|on-miss|always` modes (`GET/POST /api/v1/approvals/policy`) * `POST /api/v1/approvals/{id}/approve` accepts `{"always": true}` to persist a durable allowlist entry * Pending approvals now forward as a plain-text message in the channel that triggered them — reply `approve ` / `deny ` directly in chat * New `approval_decisions_total` metric **Skill review (propose → apply/reject/quarantine)** * Agent-authored skills (via the `write_skill` tool) no longer load immediately — they're queued as a pending proposal a human must approve or reject (`neuralcleave skills review pending/show/approve/reject`, `GET/POST /api/v1/skills/review/*`) * `neuralcleave skills quarantine ` unloads a skill without deleting it from disk * `write_skill`/`list_skills`/`delete_skill` tools are now actually wired into the agent's default tool registry — this closes a real gap where they existed but were never reachable by the live agent * Fixed a related, deeper bug: the gateway's `PluginRegistry` was constructed with no reference to the running agent's `ToolRegistry` at all, so hub-installed and self-written-skill tools never became callable regardless of "successful" registration **Plugin management** * `neuralcleave plugins install/uninstall` (pip wrapper, with an explicit `--force` trust gate for non-local/non-PyPI sources) and `plugins enable/disable` (persistent, independent of entry-point discovery) — `plugins list` now shows disabled status **Secrets, backup, and durability** * `op://vault/item/field` secret references (1Password CLI), alongside the existing `ENV:VAR` pattern, for every provider key and all 34 channel adapters * Privacy audit log now **persists across restarts** (SQLite, 90-day retention) — it used to reset every time the gateway restarted * `neuralcleave backup create/list/verify/restore` — the state directory (config, memory, audit log, skills) had no first-party backup path before this **New providers & search backends** * Groq, Together AI, and Fireworks AI (OpenAI-compatible, joining the existing 16) — 19 providers total * Brave Search and Tavily as alternate `web_search` backends alongside SearXNG/DuckDuckGo *** ## v2.1.5 — 2026-08-08 **Voice UI (P6)** * PTT button always visible in chat toolbar — shows disabled state with Settings tooltip when unconfigured * `VoiceStatusIndicator` shows idle "Voice" badge when STT is configured but nothing is actively recording * Dedicated `/voice` dashboard page: subsystem status grid, wake word card, last transcript card, continuous-listening toggle * "Voice" link added to sidebar navigation **MCP stdio server (P3)** * `neuralcleave.mcp` package: `protocol.py`, `tool_adapter.py`, `server.py`, `spawn.py` * JSON-RPC 2.0 over stdio; implements `initialize`, `tools/list`, `tools/call`, `ping` * Gateway routes: `POST /mcp/spawn`, `GET /mcp/status`, `DELETE /mcp/server` * Claude Desktop and Cursor integration supported **Exec approval manager** * `ApprovalQueue` with 120-second timeout gate * `ShellTool` gains `require_approval` mode * Gateway routes: `GET /approvals/pending`, `POST /approvals/{id}/approve`, `POST /approvals/{id}/deny` **Privacy audit (P7)** * `PrivacyAuditLog` records every outbound HTTP call * `neuralcleave privacy report` CLI command * `GET /privacy/report` and `GET /privacy/settings` endpoints **Multi-step tool chains (P10)** * `_run_tool_chain` in the pipeline runs up to `max_tool_steps` (default 5) tool calls per pipeline turn * `tool_chain_depth` metric in `/metrics` *** ## v2.1.4 — 2026-08-07 **OpenClaw parity gaps P0–P5 (PR #114)** * Semantic memory with sentence-transformers embeddings and cosine retrieval * Orchestrator for multi-agent routing * Canvas WebSocket for real-time chart updates * 8 new LLM providers: Mistral, xAI Grok, Cohere, Groq, Together AI, Perplexity, Fireworks, OpenRouter * Settings UI fields for all 13 providers * Config hot-reload via watchfiles (API keys and model settings without restart) *** ## v2.1.3 — 2026-07-30 **Voice pipeline phases 1–2 (PR #88)** * Binary audio lane over WebSocket * faster-whisper STT integration * ElevenLabs, Kokoro, and pyttsx3 TTS * OpenWakeWord wake word detection * PTT REST API (`/voice/ptt/start`, `/voice/ptt/stop`) * Voice settings API (`PATCH /settings/voice`) *** ## v2.1.2 — 2026-07-15 **Audio device selector** * Settings → Voice: input/output device dropdowns populated from `GET /voice/devices` * Active device persistence across gateway restarts **Gateway restart command** * `POST /settings/gateway/restart` endpoint * STT default changed to `whisper` (was `none`) *** ## v2.1.1 — 2026-06-15 **CortexFlow → NeuralCleave rename** * All Python packages renamed `cortexflow` → `neuralcleave` * CLI renamed `cortexflow` → `neuralcleave` * neuralcleave.com domain acquired *** ## v2.0.0 — 2026-06-07 **Personal AI assistant pivot** * Pivoted from enterprise B2B to personal AI assistant (OpenClaw competitor) * Enterprise features mirrored to `CortexFlow-Enterprise` repo * 32 channel adapters, 5 initial LLM providers * Phase 8 integration: REST metrics, reflection engine, WebSocket channels # Channels Source: https://docs.neuralcleave.com/channels Connect NeuralCleave to any of 32 messaging platforms with a single config block. NeuralCleave ships with adapters for 32 messaging and communication platforms. Each channel is a background task that forwards incoming messages to the gateway pipeline and sends replies back. ## Channel list Telegram, Discord, Slack, WhatsApp (via Twilio), Signal (via signal-cli), Viber, Line, WeChat, KakaoTalk, Zalo IMAP/SMTP Email, Twilio SMS, AWS SNS, Mailgun Microsoft Teams, Google Chat, Zoom Chat, Jira, Notion, Linear Twitter/X DMs, Instagram DMs, Facebook Messenger, Reddit DMs, LinkedIn, Mastodon WebSocket (built-in), HTTP webhook, WebRTC (experimental), Twilio Voice GitHub Issues, GitLab Issues ## Quick setup ### Telegram 1. Create a bot with [@BotFather](https://t.me/BotFather) and copy the token. ```toml theme={null} [channels.telegram] token = "ENV:TELEGRAM_BOT_TOKEN" enabled = true ``` ```bash theme={null} export TELEGRAM_BOT_TOKEN="123456:ABC-DEF..." neuralcleave start ``` Send a message to your bot — NeuralCleave replies instantly. ### Discord 1. Create an application at [discord.com/developers](https://discord.com/developers). 2. Add a Bot, copy the token, enable Message Content Intent. ```toml theme={null} [channels.discord] token = "ENV:DISCORD_BOT_TOKEN" guild_id = "YOUR_GUILD_ID" # optional: restrict to one server enabled = true ``` ### Slack Requires a Slack app with `chat:write` and `app_mentions:read` scopes, plus Socket Mode enabled. ```toml theme={null} [channels.slack] bot_token = "ENV:SLACK_BOT_TOKEN" app_token = "ENV:SLACK_APP_TOKEN" enabled = true ``` ### Email (IMAP/SMTP) ```toml theme={null} [channels.email] imap_host = "imap.gmail.com" imap_port = 993 smtp_host = "smtp.gmail.com" smtp_port = 587 username = "ENV:EMAIL_ADDRESS" password = "ENV:EMAIL_PASSWORD" check_interval_seconds = 30 enabled = true ``` ### WebSocket (built-in) The gateway exposes a WebSocket at `ws://localhost:7432/ws` by default — used by the dashboard. No additional config needed. ### HTTP Webhook Expose an endpoint that external services can POST to: ```toml theme={null} [channels.webhook] path = "/webhook/my-service" secret = "ENV:WEBHOOK_SECRET" enabled = true ``` External service POSTs: ```json theme={null} { "message": "Hello from my app", "user": "user-id" } ``` ## Shared channel options All channels support these optional fields: ```toml theme={null} [channels.telegram] # ... reply_mode = "direct" # direct | thread max_message_length = 4096 # split long replies rate_limit_per_minute = 30 # 0 = unlimited system_prompt_override = "" # per-channel system prompt enabled = true ``` ## Checking channel status ```bash theme={null} curl http://localhost:7432/api/v1/channels ``` ```json theme={null} { "channels": [ { "name": "telegram", "status": "connected", "unread": 0 }, { "name": "discord", "status": "connected", "unread": 2 } ] } ``` # CLI Reference Source: https://docs.neuralcleave.com/cli All neuralcleave command-line commands. ## Global flags ``` neuralcleave [-c/--config PATH] COMMAND ``` | Flag | Default | Description | | ---------------- | ----------------------------- | ------------------- | | `-c`, `--config` | `~/.neuralcleave/config.toml` | Path to config file | ## Gateway lifecycle ### `start` Start the gateway and all enabled channel adapters. ```bash theme={null} neuralcleave start neuralcleave start --background # detached process neuralcleave start --bind 0.0.0.0 --port 8000 neuralcleave start --voice-mode # start with voice always listening ``` ### `stop` Stop a gateway previously started with `--background`. ```bash theme={null} neuralcleave stop ``` ### `open` Open the web UI in the default browser (starts the gateway first if not already running). ```bash theme={null} neuralcleave open ``` ### `tray` Start the gateway in the background and open the web UI — the typical one-command way to launch NeuralCleave. ```bash theme={null} neuralcleave tray ``` ### `chat` Interactive chat session directly in the terminal, no channel adapter required. ```bash theme={null} neuralcleave chat ``` ### `status` Show agent config, enabled channels, and memory stats at a glance. ```bash theme={null} neuralcleave status ``` ## Config ### `config show` Print the resolved config (merged defaults + config.toml + env overrides). ### `config init` Write a starter `config.toml` to `~/.neuralcleave/`. ### `config edit` Open `config.toml` in `$EDITOR`. ## Backup & restore State (config, memory database, privacy audit log, skills) lives entirely under `~/.neuralcleave/` — these commands tar/verify/restore that one directory. ```bash theme={null} neuralcleave backup create # -> ~/.neuralcleave-backups/neuralcleave-backup-.tar.gz neuralcleave backup list neuralcleave backup verify neuralcleave backup restore --target /fresh/restore/path neuralcleave backup restore --target /existing/path --force # only if the target isn't empty ``` Restore refuses a non-empty target directory unless `--force` is passed, and archive extraction rejects path traversal / unsafe members. ## Usage & cost tracking ### `usage` Show accumulated LLM token usage and estimated cost per model. Proxies through a running gateway's `GET /api/v1/usage` (the same pattern `approvals`/`hub install` use) so it reflects the gateway's actual counters, not this CLI invocation's own — falling back to this process's own, necessarily-empty local registry only if no gateway is reachable. ```bash theme={null} neuralcleave usage ``` ``` NeuralCleave Usage (since gateway start) ┌────────────────────┬──────────────┬───────────────┬─────────────────┐ │ Model │ Input Tokens │ Output Tokens │ Est. Cost (USD) │ ├────────────────────┼──────────────┼───────────────┼─────────────────┤ │ claude-opus-4-8 │ 4,210 │ 1,340 │ $0.1642 │ │ Total │ 4,210 │ 1,340 │ $0.1642 │ └────────────────────┴──────────────┴───────────────┴─────────────────┘ ``` This is a live view of counters recorded since the gateway started, not a persisted historical ledger — it resets when the gateway restarts. Scrape `/api/v1/metrics` into a real time-series store for long-term history. ## Providers ### `models list` List every supported provider and whether credentials are configured (no network calls). ```bash theme={null} neuralcleave models list ``` ### `models status` Same as `list`, plus (with `--live`) an actual HTTP reachability probe — only for providers with a documented, stable check (OpenAI-compatible `GET /v1/models` for OpenAI/Mistral/xAI/Moonshot/OpenRouter/Groq/Together/Fireworks/DeepSeek, Ollama's `GET /api/tags`). Every other provider reports "not supported" rather than a guess. ```bash theme={null} neuralcleave models status neuralcleave models status --live ``` `--live` makes real network calls — it's not run automatically. ## Exec approvals Set `[security] require_shell_approval = true` in `config.toml` (or toggle it live via `POST /api/v1/approvals/policy`) to gate the `shell`/`browser` tools behind a persistent allowlist + security policy — see [Configuration](/configuration). ```bash theme={null} neuralcleave approvals pending # commands awaiting a decision neuralcleave approvals approve neuralcleave approvals approve --always # also allowlist this command's program neuralcleave approvals deny neuralcleave approvals allowlist list neuralcleave approvals allowlist add git --arg-pattern "^git log" neuralcleave approvals allowlist remove ``` `pending`/`approve`/`deny` first try the REST API of a gateway running at the configured `[gateway]` bind/port — the same live queue the channel-forwarded chat reply and web UI use. If no gateway is reachable there (nothing running, or a different bind/port), they fall back to this CLI process's own in-memory queue instead, printing a note when that happens — that fallback can never see a separately running gateway's pending requests, since `ApprovalQueue` has no persistence or IPC of its own. `allowlist add/list/remove` don't need any of this — the allowlist is SQLite-backed and genuinely shared across processes either way. Security/ask modes (`deny|allowlist|full` and `off|on-miss|always`) and `require_shell_approval` are all set via `GET`/`POST /api/v1/approvals/policy` — see [API Reference → Approvals](/api-reference/approvals). Pending approvals are also forwarded as a plain-text message in the channel that triggered them — reply `approve ` or `deny ` directly in chat. ## Skills Skills are Python modules the agent can write for itself at `~/.neuralcleave/skills//skill.py`. ```bash theme={null} neuralcleave skills write --file code.py # trusted path — writes and loads immediately neuralcleave skills list neuralcleave skills show neuralcleave skills delete neuralcleave skills validate # check syntax + blocked imports without writing neuralcleave skills quarantine # unload without deleting the file ``` ### Agent-authored skills go through review When the **agent itself** writes a skill (via the `write_skill` tool), it no longer loads immediately — it's queued as a pending proposal for a human to decide: ```bash theme={null} neuralcleave skills review pending neuralcleave skills review show neuralcleave skills review approve # writes to disk, loads, and wires its tools in neuralcleave skills review reject # never written to disk ``` `neuralcleave skills write` (above) is the separate, trusted, immediate-load path — used for e.g. code you wrote yourself or installed from the skills gallery, not for reviewing agent output. ## Hub `neuralcleave hub` installs skill packages from a URL, scans them with `PackageScanner`, and registers them the same way `skills write` does. ```bash theme={null} neuralcleave hub install --name my-skill neuralcleave hub install --force # install even if the scanner flags it neuralcleave hub remove neuralcleave hub search neuralcleave hub scan # scan only, don't install neuralcleave hub enable/disable ``` `install`/`remove` try a running gateway's REST API first — that's the only way an install becomes callable by a *live* agent, since this CLI process has no connection to a separately running gateway's tool registry. If no gateway is reachable at the configured `[gateway]` bind/port, they fall back to writing/loading into this process's own local hub state instead (a note is printed either way telling you which happened). `--force` only overrides the Hub's own scanner — it does not bypass the underlying skill writer's independent blocked-import check (`subprocess`, `ctypes`, etc.), which has no override anywhere in NeuralCleave. There is no remote/curated package catalog today — `hub search` only searches packages you've already installed. Hub currently means "fetch a URL, scan it, install it," not a marketplace with discovery. ## Plugins Plugins are `pip`-installed packages that declare a `NeuralCleave.plugins` entry point. ```bash theme={null} neuralcleave plugins list neuralcleave plugins install some-plugin # PyPI name or local path — no --force needed neuralcleave plugins install git+https://github.com/x/y.git --force # non-PyPI sources need --force neuralcleave plugins uninstall some-plugin neuralcleave plugins enable neuralcleave plugins disable # stays discovered, but its tools stop loading neuralcleave plugins reload # hot-reload all, no gateway restart neuralcleave plugins reload # hot-reload one ``` ## Channels ```bash theme={null} neuralcleave channels list neuralcleave channels add neuralcleave channels remove ``` ## Memory ```bash theme={null} neuralcleave memory prune --threshold 0.2 neuralcleave memory clear --session neuralcleave memory edit --content "..." --importance 0.9 neuralcleave memory archive --days 30 neuralcleave memory search "" ``` ## Voice ```bash theme={null} neuralcleave voice listen # always-on, no wake word neuralcleave voice wake # wake-word detection loop neuralcleave voice clone file1.wav file2.wav # voice cloning, if the TTS backend supports it ``` ## Migration ```bash theme={null} neuralcleave migrate openclaw --source ~/.openclaw --dry-run neuralcleave migrate openclaw --source ~/.openclaw ``` Imports an OpenClaw installation's channel/provider config into a NeuralCleave `config.toml`. ## Cloud deployment ```bash theme={null} neuralcleave cloud check # verify Docker + Compose neuralcleave cloud generate # write Dockerfile, docker-compose.yml, railway.toml, render.yaml neuralcleave cloud status ``` ## Autostart ```bash theme={null} neuralcleave autostart enable neuralcleave autostart disable neuralcleave autostart status ``` ## Tools ```bash theme={null} neuralcleave tools list # every registered tool + description ``` ## Orchestrator ```bash theme={null} neuralcleave orchestrate list neuralcleave orchestrate add --name node-a --model anthropic/claude-opus-4-8 --task-types code_generation neuralcleave orchestrate remove node-a neuralcleave orchestrate route --content "some task" --task-type code_generation neuralcleave orchestrate status ``` `list`/`add`/`remove`/`route`/`status` try a running gateway's REST API first (reusing its live, shared orchestrator instance) and fall back to a local, throwaway one only if no gateway is reachable — a note is printed either way. Against a running gateway, `route` generates a real response via the selected node's `model_override` (`ModelRouter.generate()` directly — no memory retrieval, reflection, or tool calls, so it's a lighter-weight one-shot generation rather than a full conversational turn). Against the local fallback orchestrator (no gateway reachable), routing only selects a node and prints a placeholder, since a bare CLI invocation has no provider credentials to build a real router from. Node-selection logic (priority, keyword, channel, task-type matching) is real everywhere. Full `CognitivePipeline` integration (memory, reflection, tool calls) for a routed task is still future work — routing a task is not the same as a normal chat turn through any channel adapter. ## Version & updates ```bash theme={null} neuralcleave version neuralcleave update --check # check PyPI without installing neuralcleave update # install if a newer version exists ``` # Configuration Source: https://docs.neuralcleave.com/configuration Complete config.toml reference — agent, models, memory, voice, gateway, and secret resolution. NeuralCleave is configured with a single TOML file at `~/.neuralcleave/config.toml`. ## Secret resolution Instead of hard-coding an API key: ```toml theme={null} anthropic_api_key = "sk-ant-abc123..." # ❌ stored in plain text ``` Use one of two resolvable prefixes: ```toml theme={null} anthropic_api_key = "ENV:ANTHROPIC_API_KEY" # ✅ read from an environment variable anthropic_api_key = "op://Private/Anthropic/api_key" # ✅ resolved via the 1Password CLI (`op`) ``` A missing `ENV:` variable resolves to an empty string, not an error. An unresolvable `op://` reference raises a clear error naming the missing `op` CLI or the failed lookup. ## Full reference ### `[agent]` ```toml theme={null} [agent] name = "My Assistant" model = "auto" ``` ### `[models]` ```toml theme={null} [models] primary = "claude-opus-4-8" # default model fallback = "gemini-2.5-flash" # used if primary fails fast = "gemini-2.5-flash" # used for simple/cheap tasks local = "ollama/llama3.2:1b" # used in privacy mode # API keys — one field per provider, ENV:/op:// both supported anthropic_api_key = "ENV:ANTHROPIC_API_KEY" gemini_api_key = "ENV:GEMINI_API_KEY" openai_api_key = "ENV:OPENAI_API_KEY" deepseek_api_key = "ENV:DEEPSEEK_API_KEY" mistral_api_key = "ENV:MISTRAL_API_KEY" xai_api_key = "ENV:XAI_API_KEY" cohere_api_key = "ENV:COHERE_API_KEY" moonshot_api_key = "ENV:MOONSHOT_API_KEY" zhipuai_api_key = "ENV:ZHIPUAI_API_KEY" dashscope_api_key = "ENV:DASHSCOPE_API_KEY" qianfan_api_key = "ENV:QIANFAN_API_KEY" ark_api_key = "ENV:ARK_API_KEY" openrouter_api_key = "ENV:OPENROUTER_API_KEY" azure_api_key = "ENV:AZURE_OPENAI_API_KEY" azure_endpoint = "ENV:AZURE_OPENAI_ENDPOINT" bedrock_region = "us-east-1" # AWS credentials come from the standard AWS SDK chain groq_api_key = "ENV:GROQ_API_KEY" together_api_key = "ENV:TOGETHER_API_KEY" fireworks_api_key = "ENV:FIREWORKS_API_KEY" # Local provider (no key needed) ollama_base_url = "http://localhost:11434" web_search_enabled = false ``` See [LLM Providers](/llm-providers) for the full provider list and [Settings API](/api-reference/settings) for changing these at runtime. ### `[memory]` ```toml theme={null} [memory] short_term_ttl = 3600 # seconds a short-term turn stays in context long_term_days = 90 # long-term memory retention window redis_url = "redis://localhost:6379" # short-term store qdrant_url = "http://localhost:6333" # vector store for semantic retrieval sqlite_path = "~/.neuralcleave/memory.db" # long-term SQLite store ``` ### `[voice]` ```toml theme={null} [voice] stt = "none" # none | whisper (see stt_model for size) tts = "none" # none | pyttsx3 | kokoro | elevenlabs stt_model = "base" # tiny | base | small | medium | large-v3 stt_device = "cpu" # cpu | cuda tts_engine = "none" tts_voice = "Rachel" elevenlabs_api_key = "ENV:ELEVENLABS_API_KEY" elevenlabs_voice_id = "" language = "" # forced STT language, empty = auto-detect # Wake word wake_word = "" wake_word_model_path = "" wake_word_threshold = 0.5 # VAD (voice activity detection) vad_backend = "energy" vad_aggressiveness = 2 vad_silence_threshold = 300.0 vad_silence_duration_s = 0.8 continuous_voice_enabled = false wake_handoff_duration_s = 10.0 ptt_max_duration_s = 30.0 voice_session_idle_s = 300.0 ``` ### `[gateway]` ```toml theme={null} [gateway] bind = "127.0.0.1" port = 7432 api_key = "" # optional — when set, required as X-API-Key for /api/* and /ws/* requests ``` ### `[security]` Controls the exec-approval gate consulted by the `shell` and `browser` tools. Off by default — a command runs immediately with no prompt unless you opt in. ```toml theme={null} [security] require_shell_approval = false # true = gate shell/browser tool calls behind approval security_mode = "allowlist" # deny | allowlist | full ask_mode = "on-miss" # off | on-miss | always ``` * `require_shell_approval` — when `true`, every `shell` and `browser` tool call is queued and blocks until approved. When a pending request is queued, NeuralCleave also sends a notification into the channel that triggered it (Slack, Telegram, Discord, …) — reply `approve ` or `deny ` right there, or use `neuralcleave approvals approve/deny`. * `security_mode` — `"deny"` denies every gated command outright; `"allowlist"` auto-approves commands matching a stored allowlist entry (see `neuralcleave approvals allowlist add/list/remove`) and falls through to `ask_mode` for the rest; `"full"` disables the gate entirely (auto-approves everything, equivalent to `require_shell_approval = false`). * `ask_mode` — only consulted when `security_mode = "allowlist"`: `"off"` never prompts (an unmatched command is denied silently), `"on-miss"` prompts only when no allowlist entry matches (the default), `"always"` prompts even on an allowlist match. ### `[ui]` ```toml theme={null} [ui] web_port = 3000 ``` ### `[channels.]` Configure each channel adapter under its own key, e.g.: ```toml theme={null} [channels.telegram] enabled = true bot_token = "ENV:TELEGRAM_BOT_TOKEN" [channels.discord] enabled = true bot_token = "ENV:DISCORD_BOT_TOKEN" ``` Every channel adapter's secret fields resolve through the same `ENV:`/`op://` mechanism as `[models]`. ## Hot-reload The gateway watches `config.toml` for changes, but only `[security]` (`require_shell_approval`, `security_mode`, `ask_mode`) is actually applied live — the same mutation `POST /api/v1/approvals/policy` does. Model/API-key settings and channel connections are **not** hot-reloaded despite being watched — restart the gateway (or use `neuralcleave channels remove`/`add` for channel config) after changing those. # Deployment Source: https://docs.neuralcleave.com/deployment Run NeuralCleave as a systemd service, Docker container, or Tauri desktop app. ## Local (development) ```bash theme={null} neuralcleave start cd frontend && npm run dev ``` ## systemd (Linux server) Create `/etc/systemd/system/neuralcleave.service`: ```ini theme={null} [Unit] Description=NeuralCleave AI Gateway After=network.target [Service] Type=simple User=neuralcleave ExecStart=/usr/local/bin/neuralcleave start Restart=on-failure RestartSec=5s Environment=OPENAI_API_KEY=sk-... Environment=TELEGRAM_BOT_TOKEN=123456:ABC... [Install] WantedBy=multi-user.target ``` ```bash theme={null} sudo systemctl daemon-reload sudo systemctl enable neuralcleave sudo systemctl start neuralcleave ``` ## Docker ```dockerfile theme={null} FROM python:3.12-slim WORKDIR /app COPY . . RUN pip install -e ".[channels]" EXPOSE 7432 CMD ["neuralcleave", "start"] ``` ```bash theme={null} docker build -t neuralcleave . docker run -d \ -p 7432:7432 \ -v ~/.neuralcleave:/root/.neuralcleave \ -e OPENAI_API_KEY=$OPENAI_API_KEY \ -e TELEGRAM_BOT_TOKEN=$TELEGRAM_BOT_TOKEN \ neuralcleave ``` ### Docker Compose ```yaml theme={null} version: "3.9" services: gateway: build: . ports: - "7432:7432" volumes: - neuralcleave-data:/root/.neuralcleave environment: OPENAI_API_KEY: ${OPENAI_API_KEY} TELEGRAM_BOT_TOKEN: ${TELEGRAM_BOT_TOKEN} restart: unless-stopped volumes: neuralcleave-data: ``` ## Tauri desktop app Build a self-contained desktop app (bundles both the gateway and the dashboard): ```bash theme={null} cd frontend npm run tauri build ``` The output is a platform-native installer (`.exe` on Windows, `.dmg` on macOS, `.AppImage` / `.deb` on Linux). The installer ships: * The Next.js frontend (static export) * The Python gateway as a Tauri sidecar binary * A system tray icon with start/stop controls ## Reverse proxy (nginx) If you expose the dashboard publicly: ```nginx theme={null} server { listen 443 ssl; server_name ai.example.com; location /api/ { proxy_pass http://127.0.0.1:7432; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { proxy_pass http://127.0.0.1:3000; } } ``` Do not expose the gateway API publicly without adding authentication. The gateway has no built-in auth layer. ## Environment variables reference | Variable | Required | Description | | -------------------- | ----------------------- | ------------------ | | `OPENAI_API_KEY` | If using OpenAI | OpenAI API key | | `ANTHROPIC_API_KEY` | If using Anthropic | Anthropic API key | | `TELEGRAM_BOT_TOKEN` | If using Telegram | Telegram bot token | | `DISCORD_BOT_TOKEN` | If using Discord | Discord bot token | | `ELEVENLABS_API_KEY` | If using ElevenLabs TTS | ElevenLabs key | # Installation Source: https://docs.neuralcleave.com/installation Install NeuralCleave on Linux, macOS, or Windows. ## System requirements | Component | Minimum | Recommended | | --------- | --------------------------- | ---------------------------- | | Python | 3.11 | 3.12 | | RAM | 2 GB | 8 GB (16 GB for local voice) | | Disk | 500 MB | 4 GB (models add more) | | OS | Linux / macOS / Windows 10+ | Ubuntu 22.04 LTS | | Node.js | 20 | 22 (for dashboard only) | ## Install methods ### pip (recommended) ```bash theme={null} pip install neuralcleave ``` For all optional dependencies (voice, embeddings, all channels): ```bash theme={null} pip install "neuralcleave[all]" ``` ### From source ```bash theme={null} git clone https://github.com/TheAmitChandra/NeuralCleave.git cd NeuralCleave pip install -e ".[all]" ``` ### Optional extras | Extra | Installs | | ------------ | ------------------------------------------------ | | `voice` | faster-whisper, pyaudio, openwakeword, kokoro | | `embeddings` | sentence-transformers, faiss-cpu | | `channels` | python-telegram-bot, discord.py, slack-sdk, etc. | | `all` | Everything above | ## Dashboard (optional) The web dashboard is a Next.js app in `frontend/`: ```bash theme={null} cd frontend npm install npm run dev # development npm run build # production build ``` Or run the pre-built Tauri desktop app from the [Releases page](https://github.com/TheAmitChandra/NeuralCleave/releases). ## Verify installation ```bash theme={null} neuralcleave --version # NeuralCleave 2.1.5 neuralcleave doctor # Checking dependencies... # ✓ Python 3.12.3 # ✓ Gateway dependencies # ✓ Voice dependencies (faster-whisper, openwakeword) # ✓ All checks passed ``` ## Upgrading ```bash theme={null} pip install --upgrade neuralcleave ``` After upgrading, run database migrations if prompted: ```bash theme={null} neuralcleave migrate ``` # Introduction Source: https://docs.neuralcleave.com/introduction NeuralCleave is your personal AI assistant — built on the AI stack, not bolted onto it. ## What is NeuralCleave? NeuralCleave is an open-source personal AI assistant runtime that connects a large language model to **32 messaging platforms**, **13 AI providers**, **local voice**, **self-modifying skills**, and a **privacy mode** that keeps every byte on your machine. Unlike tools that wrap an API behind a chatbot UI, NeuralCleave runs the model stack in-process — HuggingFace, faster-whisper, Kokoro TTS, OpenWakeWord, and sentence-transformers all execute locally alongside the Python gateway. ## Key Features Telegram, Discord, Slack, WhatsApp, Email, SMS, and 26 more. One gateway, all platforms. OpenAI, Anthropic, Gemini, DeepSeek, Ollama, Mistral, xAI Grok, Cohere, and more — switchable at runtime. Wake word (OpenWakeWord) → VAD → STT (faster-whisper) → LLM → TTS (ElevenLabs / Kokoro / pyttsx3). 100% local when using Ollama + Kokoro. Skills are Python files the agent can read, write, and reload at runtime. The assistant extends itself. Vector-embedded conversation memory with cosine similarity retrieval. In-process, no external vector DB required. One flag routes everything — LLM, STT, TTS, embeddings — through local models. Zero external API calls. ## How it compares | Feature | NeuralCleave | OpenClaw | | --------------------- | ------------------------ | ---------------------- | | Messaging channels | 32 | 8 | | AI providers | 13 | 5 | | Local voice | Wake word + STT + TTS | ElevenLabs plugin only | | Privacy mode | Full local stack | Partial | | Self-modifying skills | Yes | No | | MCP server | Yes (stdio JSON-RPC 2.0) | No | | Exec approval | Yes | No | ## Where to start Get a live agent in under five minutes. Full `config.toml` reference. Enable wake word, STT, and TTS. REST API for all gateway operations. # LLM Providers Source: https://docs.neuralcleave.com/llm-providers NeuralCleave supports 19 AI providers switchable at runtime without a restart. NeuralCleave ships with 19 provider adapters, configured under `[models]` in `config.toml`. The active provider is chosen automatically per request (`primary` → `fallback` → `fast` → `local`, based on task complexity), or forced to one provider at runtime via `POST /api/v1/settings/model`. ## Supported providers | Provider | Config key | Env var fallback | | ------------------ | ------------------------------------------------ | ------------------------------------------------ | | Anthropic | `anthropic_api_key` | `ANTHROPIC_API_KEY` | | Google Gemini | `gemini_api_key` | `GEMINI_API_KEY` | | OpenAI | `openai_api_key` | `OPENAI_API_KEY` | | DeepSeek | `deepseek_api_key` | `DEEPSEEK_API_KEY` | | Ollama (local) | `ollama_base_url` | — | | Mistral AI | `mistral_api_key` | `MISTRAL_API_KEY` | | xAI Grok | `xai_api_key` | `XAI_API_KEY` | | Cohere | `cohere_api_key` | `COHERE_API_KEY` | | Moonshot / Kimi | `moonshot_api_key` | `MOONSHOT_API_KEY` | | Zhipu / GLM | `zhipuai_api_key` | `ZHIPUAI_API_KEY` | | Qwen (Alibaba) | `dashscope_api_key` | `DASHSCOPE_API_KEY` | | ERNIE (Baidu) | `qianfan_api_key` | `QIANFAN_API_KEY` | | Doubao (ByteDance) | `ark_api_key` | `ARK_API_KEY` | | OpenRouter | `openrouter_api_key` | `OPENROUTER_API_KEY` | | Azure OpenAI | `azure_api_key` + `azure_endpoint` | `AZURE_OPENAI_API_KEY` / `AZURE_OPENAI_ENDPOINT` | | Amazon Bedrock | `bedrock_region` (credentials via AWS SDK chain) | `AWS_REGION` | | Groq | `groq_api_key` | `GROQ_API_KEY` | | Together AI | `together_api_key` | `TOGETHER_API_KEY` | | Fireworks AI | `fireworks_api_key` | `FIREWORKS_API_KEY` | Every key also accepts `ENV:VAR_NAME` (reads an environment variable) or `op://vault/item/field` (resolves via the 1Password CLI) instead of a plaintext value. ## Configuration ```toml theme={null} [models] primary = "claude-opus-4-8" fallback = "gemini-2.5-flash" fast = "gemini-2.5-flash" local = "ollama/llama3.2:1b" anthropic_api_key = "op://Private/Anthropic/api_key" gemini_api_key = "ENV:GEMINI_API_KEY" groq_api_key = "ENV:GROQ_API_KEY" ``` `primary`/`fallback`/`fast`/`local` are model IDs, not provider names — the provider is inferred from the ID's prefix (`claude-*` → Anthropic, `gemini-*` → Google, `grok-*` → xAI, `ollama/*` → Ollama, `openrouter/*` → OpenRouter, etc.). ### Ollama (fully local) ```toml theme={null} [models] local = "ollama/llama3.2:1b" ollama_base_url = "http://localhost:11434" ``` No API key required. Pull the model first: `ollama pull llama3.2:1b`. ## Checking provider status ```bash theme={null} neuralcleave models list # configured or not — no network calls neuralcleave models status --live # also probes reachability for supported providers ``` Live probing only works for providers with a documented, stable check (OpenAI-compatible `GET /v1/models` for OpenAI/Mistral/xAI/Moonshot/OpenRouter/Groq/Together/Fireworks/DeepSeek, Ollama's `GET /api/tags`) — every other provider reports "not supported" rather than a guessed result. See [API Reference → Overview](/api-reference/overview) for the matching `GET /api/v1/models` route. ## Switching providers at runtime ```bash theme={null} curl -X POST http://localhost:7432/api/v1/settings/model \ -H "Content-Type: application/json" \ -d '{"provider": "anthropic"}' ``` Pass `"provider": null` to restore automatic task-based routing. The switch takes effect immediately for the next request — no restart needed. ## Reasoning effort ("thinking") A normalized `off|low|medium|high|xhigh|max` ladder maps to each provider's native reasoning control — Anthropic's extended thinking (with a scaled token budget), xAI/OpenRouter's `reasoning_effort` field, and Ollama's `think` field (collapsed to a boolean: `off` → `false`, anything else → `true`, since not every Ollama model accepts the 3-tier string form). Every other provider ignores it — notably DeepSeek, which has no per-request reasoning-effort field at all; its only reasoning lever is which model you configure (`deepseek-chat` vs. `deepseek-reasoner`). ```bash theme={null} # In any channel, the Web UI chat, or the voice assistant: /think high /think # show current level # Or via REST: curl -X POST http://localhost:7432/api/v1/settings/model \ -H "Content-Type: application/json" \ -d '{"thinking": "high"}' ``` Applies uniformly whether the reply is generated by `ModelRouter.generate()` (the 32 channel adapters) or `generate_stream()` (the Web UI and voice assistant) — both read the same `/think` level. ## Cost tracking Token counts and estimated USD cost (from a static per-model pricing table) are tracked automatically per generation: ```bash theme={null} neuralcleave usage ``` Unpriced providers (OpenRouter, Azure, Bedrock, or any unrecognized model) are omitted from the cost total rather than reported as `$0.00` — see [Observability](/observability). ## Privacy mode With `privacy_mode = true`, NeuralCleave forces every request to Ollama regardless of the configured provider. Combined with local voice (faster-whisper + Kokoro) and local embeddings (all-MiniLM-L6-v2), zero bytes leave your machine. See [Privacy Mode](/privacy-mode). # Memory System Source: https://docs.neuralcleave.com/memory NeuralCleave's 3-tier memory (Redis, Qdrant, SQLite) retrieves relevant context for every query. NeuralCleave combines three memory tiers into one retrieval pass before generating a reply: a fast short-term session cache, a semantic vector search over past conversations, and a durable long-term SQLite store. Redis and Qdrant are both optional at runtime — the pipeline falls back to in-process storage for either one when it isn't reachable, so a bare install with no external services still works. ## How it works 1. **Write**: Each turn is stored short-term (Redis, TTL-based) and embedded for semantic search; important turns are also persisted to the SQLite long-term store. 2. **Retrieve**: At query time, `MemoryRetrievalPipeline.retrieve()` (`neuralcleave/memory/retrieval.py`) pulls from all three tiers in one pass — short-term (priority), Qdrant ANN semantic search (falls back to in-memory cosine similarity if Qdrant is unreachable), and a SQLite long-term query — then deduplicates by content hash, ranks by score, and caps the result at a `top_k` the caller passes in code (the cognitive pipeline uses 8). 3. **Inject**: The assembled results are serialized into prompt blocks and prepended to the LLM call. ``` User message ↓ Short-term (Redis) ─┐ Semantic (Qdrant) ├─→ dedup → rank → cap at top_k → RetrievalContext Long-term (SQLite) ─┘ ↓ [context] + [user message] → LLM ``` Semantic embedding uses `sentence-transformers` (`all-MiniLM-L6-v2`, downloaded automatically on first use). If it isn't importable, `neuralcleave/memory/embedder.py` logs a warning and semantic search is silently skipped for that turn — short-term and long-term retrieval still work normally. ## Configuration ```toml theme={null} [memory] short_term_ttl = 3600 # seconds a Redis entry stays hot long_term_days = 90 # SQLite retention window redis_url = "redis://localhost:6379" qdrant_url = "http://localhost:6333" sqlite_path = "~/.neuralcleave/memory.db" ``` There is no `backend`/`embedding_model`/`chunk_size`/`top_k` config — the embedding model and chunking strategy aren't configurable today; `top_k` is a call-site parameter, not a config field. ## API The REST routes below only reach the SQLite long-term tier — `/memory/search` is a plain `content LIKE '%...%'` query (`neuralcleave/memory/long_term.py`'s `search()`), not the semantic/Qdrant search. Semantic retrieval only happens internally, inside `MemoryRetrievalPipeline.retrieve()` as part of the chat pipeline — there's no REST route that exposes it directly today. ### Search long-term memory (SQLite substring match) ```bash theme={null} curl "http://localhost:7432/api/v1/memory/search?q=what+did+we+discuss+yesterday&limit=10" ``` ```json theme={null} { "query": "what did we discuss yesterday", "results": [ {"id": 1, "content": "We discussed the project timeline...", "importance_score": 0.87} ], "count": 1 } ``` Pass `session_id` to scope the search to one session (omit for all sessions). ### List recent entries ```bash theme={null} curl "http://localhost:7432/api/v1/memory/entries?limit=20" ``` ### Edit an entry ```bash theme={null} curl -X PATCH "http://localhost:7432/api/v1/memory/entries/1" \ -H "Content-Type: application/json" -d '{"content": "corrected text", "importance": 0.5}' ``` ### Delete an entry ```bash theme={null} curl -X DELETE "http://localhost:7432/api/v1/memory/entries/1" ``` ### Prune ```bash theme={null} curl -X POST "http://localhost:7432/api/v1/memory/prune" \ -H "Content-Type: application/json" -d '{"days": 90, "threshold": 0.1}' ``` There is no REST route to clear an entire session or wipe all memory — use the CLI (`neuralcleave memory clear`) for that. ## Auto-compaction Once a session's estimated token usage crosses 50% of the context window, the pipeline automatically summarizes the conversation (via `ConversationCompactor`), replaces the in-memory history with that summary, and persists it to long-term SQLite — the same mechanism the manual `/compact` chat command uses, just triggered automatically instead of on request. Compaction runs fire-and-forget after a turn's reply is already sent, so it never adds latency to the current response; a failure is logged and swallowed rather than surfaced. A separate `memory_archival` job runs daily (03:00) via the heartbeat scheduler, condensing sessions inactive for 30+ days the same way `neuralcleave memory archive` does manually. ## CLI ```bash theme={null} neuralcleave memory search "project timeline" --session default neuralcleave memory prune --threshold 0.2 # low-importance entries + Qdrant near-duplicates neuralcleave memory clear --session default # or omit --session to clear everything neuralcleave memory edit --content "..." --importance 0.6 neuralcleave memory archive --days 30 # condense inactive sessions into a searchable summary ``` ## Privacy note With `privacy_mode = true`, all LLM calls are forced to local Ollama — see [Privacy Mode](/privacy-mode). The embedding model already runs locally regardless of that setting (no embeddings are ever sent to an external API); only the long-term SQLite store and Qdrant's own storage location are affected by where you point `sqlite_path`/`qdrant_url`. # Observability Source: https://docs.neuralcleave.com/observability Metrics, structured logs, and the Observability dashboard for monitoring NeuralCleave in production. NeuralCleave exposes Prometheus-compatible metrics, structured JSON logs, and a real-time Observability dashboard page. ## Metrics endpoints ```bash theme={null} curl http://localhost:7432/api/v1/metrics # Prometheus text exposition curl http://localhost:7432/api/v1/metrics/snapshot # JSON, for the web UI ``` `/metrics/snapshot` returns one entry per registered metric: ```json theme={null} { "tokens_total": { "type": "counter", "description": "LLM tokens consumed, by model and direction (input/output)", "values": { "direction=input,model=claude-opus-4-8": 4210 } }, "cost_usd_total": { "type": "counter", "description": "Estimated USD cost of LLM generations, by provider and model", "values": { "model=claude-opus-4-8,provider=anthropic": 0.1642 } }, "process_cpu_percent": { "type": "gauge", "values": { "": 3.2 } }, "process_memory_rss_bytes": { "type": "gauge", "values": { "": 84213760 } }, "approval_decisions_total": { "type": "counter", "description": "Exec-approval gate outcomes, by decision (auto_approved/prompted/denied_outright)", "values": { "decision=auto_approved": 12 } } } ``` Key metrics: `messages_total`/`messages_sent_total`/`messages_errors_total` (by channel), `generation_requests_total`/`generation_errors_total`/`generation_latency_ms` (by model), `tokens_total` and `cost_usd_total` (by model/provider — see [Cost Tracking](#cost-tracking) below), `memory_entries_total`, `approval_decisions_total`, `approval_notifications_total` (channel-forwarded approval sends, by `outcome=sent|failed`), voice metrics (`voice_transcriptions_total`, `voice_synthesis_total`, PTT/VAD/wake-word counters), and host resource gauges (below). ## Host resource metrics `GET /api/v1/status` includes a live CPU/memory/disk snapshot (also mirrored into the gauges above): ```json theme={null} { "host": { "cpu_percent": 3.2, "memory_rss_bytes": 84213760, "disk_usage_percent": 41.7, "disk_free_bytes": 128849018880 } } ``` Fields are `null` — not `0` — when `psutil` isn't installed or a read fails, so you can tell "unavailable" from "genuinely zero." `cpu_percent` reflects usage since the *previous* read in this process (always `0.0` on the very first call — a `psutil` characteristic, not a bug). ## Readiness vs liveness ```bash theme={null} curl http://localhost:7432/health # always 200 once the process is up curl http://localhost:7432/ready # 200 once startup fully completes, 503 while initializing ``` `/ready`'s response includes a `checks` breakdown (`phase`, `runtime`, and `channel_connected` when at least one channel is configured) — all must be true for `ready: true`. It does not make a live network call to any LLM provider (that would make a frequently-polled endpoint slow and flaky); a total provider/router construction failure already surfaces via the `runtime` check. ## Cost tracking Token counts are already captured per generation; `cost_usd_total` turns them into an estimated dollar figure from a static per-model pricing table. ```bash theme={null} neuralcleave usage curl http://localhost:7432/api/v1/usage ``` Unpriced providers (OpenRouter, Azure, Bedrock, or any unrecognized model) are omitted rather than reported as `$0.00`; Ollama is always `$0.00` (self-hosted, no per-token charge). This is a live, in-process view — it resets on restart. Scrape the metrics endpoints into a real time-series store for long-term history. ## Logs The gateway logs via Python's standard `logging` module to stdout/stderr (module-scoped loggers, e.g. `neuralcleave.agent.runtime`, `neuralcleave.models.router`) — redirect/capture as your process supervisor prefers. There's no built-in file rotation or a dedicated JSON log format yet. ## Observability dashboard The `/observability` page in the dashboard shows live charts for: * Request rate (requests/min) * Token usage (in/out, rolling 60 min) * Memory chunk count * Tool call count and max chain depth * Voice session count * Connected channels ## Prometheus integration ```yaml theme={null} scrape_configs: - job_name: neuralcleave static_configs: - targets: ['localhost:7432'] metrics_path: /api/v1/metrics ``` ## Alerting Combine with Grafana for dashboards and alerting. Key signals to alert on: * `messages_total` rate drops to 0 (gateway or channel down) * `generation_errors_total` rate spike (provider outage or bad credentials — cross-check with `neuralcleave models status --live`) * `process_memory_rss_bytes` / `host_disk_usage_percent` trending toward exhaustion * `cost_usd_total` rate spike (runaway loop or unexpectedly expensive model) # Privacy Mode Source: https://docs.neuralcleave.com/privacy-mode One flag routes all LLM traffic through local Ollama, with a persistent, auditable log of everything else that leaves your machine. Privacy mode forces every LLM request to local Ollama regardless of the configured provider — a single switch, not a per-component opt-in. ## Enable Via a slash command in any channel: ``` /privacy on /privacy # show current state /privacy off ``` Or via the REST API: ```bash theme={null} curl -X POST http://localhost:7432/api/v1/settings/model \ -H "Content-Type: application/json" \ -d '{"privacy_mode": true}' ``` This is a runtime toggle on the live `ModelRouter` — it isn't written back to `config.toml`, so it resets to `false` on the next gateway restart. Set it again after restarting if you want it always on. ## What changes | Component | Default | Privacy mode | | ----------------- | ------------------------------------------------- | --------------------------------------------- | | LLM | Configured provider (`primary`/`fallback`/`fast`) | Forced to Ollama (local) | | STT | faster-whisper (already local) | Unchanged | | Embeddings | sentence-transformers (already local) | Unchanged | | Privacy audit log | Always recording | Unchanged — now shows zero external LLM calls | STT (faster-whisper) and embeddings (sentence-transformers) already run fully locally regardless of privacy mode. ## Local model requirements 1. **Ollama** running locally: `ollama serve` 2. A local model pulled: `ollama pull llama3.2:1b` (or your configured `models.local` ID) ## Verifying zero external calls The privacy audit log records the destination host of every outbound HTTP call and **persists across restarts** (SQLite at `~/.neuralcleave/privacy_audit.db`, 90-day retention). After enabling privacy mode, a fresh session's report should show no external destinations: ```bash theme={null} curl "http://localhost:7432/api/v1/privacy/report?session_id=" ``` ```json theme={null} { "session_id": "", "total": 0, "unique_destinations": [], "entries": [] } ``` See [Privacy API](/api-reference/privacy) for the full report/clear reference. ## Competitive context OpenClaw's equivalent privacy controls are opt-in per-module. NeuralCleave's `/privacy on` (or `privacy_mode: true`) is a single switch that enforces the LLM-traffic constraint and gives an auditable, persistent proof via the report endpoint. # Quickstart Source: https://docs.neuralcleave.com/quickstart Get NeuralCleave running and answering messages in under five minutes. ## Prerequisites * Python 3.11 or later * Node.js 20+ (for the dashboard UI) * An API key for at least one LLM provider, **or** [Ollama](https://ollama.ai) installed locally ## 1. Clone and install ```bash theme={null} git clone https://github.com/TheAmitChandra/NeuralCleave.git cd NeuralCleave pip install -e . pip install -e ".[voice]" # optional — STT/TTS/wake-word dependencies ``` For the dashboard: ```bash theme={null} cd frontend npm install ``` ## 2. Create your config ```bash theme={null} neuralcleave config init ``` Writes a starter `~/.neuralcleave/config.toml`. Edit it to set your provider and key under `[models]`: ```toml theme={null} [models] primary = "gpt-4o-mini" openai_api_key = "ENV:OPENAI_API_KEY" ``` Set your key in the environment: ```bash theme={null} export OPENAI_API_KEY=sk-... ``` See [Configuration](/configuration) for the full reference, and [LLM Providers](/llm-providers) for every supported model ID prefix. ## 3. Start the gateway ```bash theme={null} neuralcleave start ``` Or, to also open the dashboard in one step: ```bash theme={null} neuralcleave tray ``` ## 4. Open the dashboard ```bash theme={null} neuralcleave open ``` Or manually run the frontend dev server: ```bash theme={null} cd frontend npm run dev ``` Navigate to [http://localhost:3000](http://localhost:3000). The chat page is live. ## 5. Send your first message From the terminal, without any channel or dashboard: ```bash theme={null} neuralcleave chat ``` Or check gateway status first: ```bash theme={null} neuralcleave status ``` ## Next steps Route messages from Telegram, Discord, or Slack. Add wake word detection and local STT/TTS. Teach the agent a new capability. Use Ollama for a fully local setup. # Skills Source: https://docs.neuralcleave.com/skills Skills are Python modules NeuralCleave can write, review, and hot-load at runtime — the assistant extends itself, with a human in the loop. Skills are the extension mechanism that makes NeuralCleave self-modifying. Each skill is a Python module at `~/.neuralcleave/skills//skill.py`. ## Anatomy of a skill A skill module contains either **plain functions**, auto-wrapped as tools, or an explicit **`Plugin` subclass** for full control over metadata and lifecycle hooks. ```python theme={null} # ~/.neuralcleave/skills/celsius_to_fahrenheit/skill.py def celsius_to_fahrenheit(celsius: float) -> str: """Convert a Celsius temperature to Fahrenheit.""" fahrenheit = celsius * 9 / 5 + 32 return f"{celsius}°C is {fahrenheit}°F" ``` Every top-level, non-underscore-prefixed callable becomes a tool the agent can invoke. The function's docstring becomes the tool description. Blocked imports (`subprocess`, `ctypes`, `winreg`, `msvcrt`, `pty`, `tty`, `termios`, `fcntl`) are rejected at write/proposal time. ## Two ways a skill gets written ### 1. You write it — immediate, trusted ```bash theme={null} neuralcleave skills write celsius_to_fahrenheit --file code.py neuralcleave skills validate code.py # check syntax + blocked imports first, without writing ``` Writes to disk and hot-loads immediately. This is the trusted path — for code you wrote yourself, or installed from the [Skills Gallery](/skills-gallery). ### 2. The agent writes it — proposed for review When the **agent itself** calls the `write_skill` tool during a conversation, the code is validated and queued as a pending proposal — **not** written to disk or loaded. A human decides: ```bash theme={null} neuralcleave skills review pending neuralcleave skills review show neuralcleave skills review approve # now writes to disk, loads, and wires its tools in neuralcleave skills review reject # never written to disk ``` or via REST: ```bash theme={null} curl http://localhost:7432/api/v1/skills/review/pending curl -X POST http://localhost:7432/api/v1/skills/review//approve curl -X POST http://localhost:7432/api/v1/skills/review//reject ``` This review gate exists because agent-authored code running immediately, with no review step, is a real trust boundary — not a hypothetical one. ## Managing installed skills ```bash theme={null} neuralcleave skills list neuralcleave skills show neuralcleave skills delete # removes the file permanently neuralcleave skills quarantine # unloads without deleting — file stays for inspection ``` A quarantined skill can be restored by re-running `skills write` with the same name — that clears the quarantine flag. ```bash theme={null} curl -X POST http://localhost:7432/api/v1/skills//quarantine ``` ## Multi-step tool chains Skills participate the same way any tool does in multi-step tool chains — the pipeline calls a tool, feeds the result back to the LLM, which can call another tool, up to `max_tool_steps` (default 5) per turn. ## Example conversation ``` User: Create a skill that converts Celsius to Fahrenheit. NeuralCleave: I've proposed the skill 'celsius_to_fahrenheit' for review (id=a1b2c3d4). A human must approve it before it can run. ``` Approving it (`neuralcleave skills review approve a1b2c3d4`) writes the file, loads it, and makes `celsius_to_fahrenheit` callable in the very next turn. ## Skills gallery `~/.neuralcleave/skills/` can also be seeded from the bundled example skills — see [Skills Gallery](/skills-gallery) for the full list (calendar, GitHub, Jira, Linear, Notion, weather, and more). # Skills Gallery Source: https://docs.neuralcleave.com/skills-gallery Community-built skills for NeuralCleave — copy, install, and extend your assistant. Skills are Python files NeuralCleave hot-reloads at runtime. Drop any file below into `~/.neuralcleave/skills/` and your assistant immediately gains the new capability — no restart needed. Want to contribute a skill? Open a PR adding your `.py` file to [`skills/examples/`](https://github.com/TheAmitChandra/NeuralCleave/tree/main/skills/examples) and it will appear here. ## Install any skill ```bash theme={null} # one-liner install from the repo curl -sSL https://raw.githubusercontent.com/TheAmitChandra/NeuralCleave/main/skills/examples/weather.py \ -o ~/.neuralcleave/skills/weather.py ``` Or copy the code block from any skill below and save it as `~/.neuralcleave/skills/.py`. *** ## Developer Tools **Requires:** `GITHUB_TOKEN` env var ```python theme={null} # ~/.neuralcleave/skills/github_issues.py SKILL_METADATA = { "name": "github_issues", "description": "List open issues or create a new issue on any GitHub repo.", "version": "1.0.0", "trigger": "github issues", "dependencies": ["httpx"], } import os import httpx async def run(args: dict) -> str: token = os.environ.get("GITHUB_TOKEN", "") repo = args.get("repo", "") action = args.get("action", "list") headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"} if action == "create": title = args.get("title", "New issue") body = args.get("body", "") r = httpx.post(f"https://api.github.com/repos/{repo}/issues", json={"title": title, "body": body}, headers=headers) issue = r.json() return f"Created #{issue['number']}: {issue['title']} — {issue['html_url']}" r = httpx.get(f"https://api.github.com/repos/{repo}/issues?state=open&per_page=10", headers=headers) issues = r.json() if not issues: return f"No open issues in {repo}" lines = [f"#{i['number']} {i['title']}" for i in issues[:10]] return "\n".join(lines) ``` **Requires:** `GITHUB_TOKEN` env var ```python theme={null} # ~/.neuralcleave/skills/github_pr_summary.py SKILL_METADATA = { "name": "github_pr_summary", "description": "List open pull requests for a GitHub repo with author and status.", "version": "1.0.0", "trigger": "pull requests", "dependencies": ["httpx"], } import os import httpx async def run(args: dict) -> str: token = os.environ.get("GITHUB_TOKEN", "") repo = args.get("repo", "") headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"} r = httpx.get(f"https://api.github.com/repos/{repo}/pulls?state=open&per_page=10", headers=headers) prs = r.json() if not prs: return f"No open PRs in {repo}" lines = [f"#{p['number']} [{p['user']['login']}] {p['title']}" for p in prs] return "\n".join(lines) ``` **Requires:** `LINEAR_API_KEY` env var ```python theme={null} # ~/.neuralcleave/skills/linear_tasks.py SKILL_METADATA = { "name": "linear_tasks", "description": "List your assigned Linear issues or create a new task.", "version": "1.0.0", "trigger": "linear", "dependencies": ["httpx"], } import os import httpx _GQL = "https://api.linear.app/graphql" async def run(args: dict) -> str: key = os.environ.get("LINEAR_API_KEY", "") action = args.get("action", "list") headers = {"Authorization": key, "Content-Type": "application/json"} if action == "create": title = args.get("title", "New task") team_id = args.get("team_id", "") query = """ mutation($title: String!, $teamId: String!) { issueCreate(input: {title: $title, teamId: $teamId}) { issue { identifier title url } } } """ r = httpx.post(_GQL, json={"query": query, "variables": {"title": title, "teamId": team_id}}, headers=headers) issue = r.json()["data"]["issueCreate"]["issue"] return f"Created {issue['identifier']}: {issue['title']} — {issue['url']}" query = """ query { viewer { assignedIssues(first: 10, filter: {state: {type: {nin: ["completed","cancelled"]}}}) { nodes { identifier title state { name } } }}} """ r = httpx.post(_GQL, json={"query": query}, headers=headers) issues = r.json()["data"]["viewer"]["assignedIssues"]["nodes"] if not issues: return "No open assigned issues in Linear" return "\n".join(f"{i['identifier']} [{i['state']['name']}] {i['title']}" for i in issues) ``` **Requires:** `JIRA_URL`, `JIRA_USER`, `JIRA_TOKEN` env vars ```python theme={null} # ~/.neuralcleave/skills/jira_tickets.py SKILL_METADATA = { "name": "jira_tickets", "description": "List your Jira tickets assigned to you or search by JQL.", "version": "1.0.0", "trigger": "jira", "dependencies": ["httpx"], } import os import httpx async def run(args: dict) -> str: url = os.environ.get("JIRA_URL", "").rstrip("/") user = os.environ.get("JIRA_USER", "") token = os.environ.get("JIRA_TOKEN", "") jql = args.get("jql", f"assignee = currentUser() AND resolution = Unresolved ORDER BY updated DESC") r = httpx.get( f"{url}/rest/api/3/search", params={"jql": jql, "maxResults": 10, "fields": "summary,status,priority"}, auth=(user, token), ) data = r.json() issues = data.get("issues", []) if not issues: return "No Jira tickets found" lines = [f"{i['key']} [{i['fields']['status']['name']}] {i['fields']['summary']}" for i in issues] return "\n".join(lines) ``` **Requires:** `FIGMA_TOKEN` env var ```python theme={null} # ~/.neuralcleave/skills/figma_comments.py SKILL_METADATA = { "name": "figma_comments", "description": "List unresolved comments on a Figma file.", "version": "1.0.0", "trigger": "figma comments", "dependencies": ["httpx"], } import os import httpx async def run(args: dict) -> str: token = os.environ.get("FIGMA_TOKEN", "") file_key = args.get("file_key", "") r = httpx.get(f"https://api.figma.com/v1/files/{file_key}/comments", headers={"X-Figma-Token": token}) comments = [c for c in r.json().get("comments", []) if not c.get("resolved_at")] if not comments: return "No unresolved comments" lines = [f"[{c['user']['handle']}] {c['message'][:120]}" for c in comments[:10]] return "\n".join(lines) ``` **No API key required** ```python theme={null} # ~/.neuralcleave/skills/git_summary.py SKILL_METADATA = { "name": "git_summary", "description": "Summarise the last N commits in a local git repository.", "version": "1.0.0", "trigger": "git summary", } import subprocess async def run(args: dict) -> str: path = args.get("path", ".") n = int(args.get("n", 10)) result = subprocess.run( ["git", "-C", path, "log", f"-{n}", "--oneline", "--no-decorate"], capture_output=True, text=True, ) if result.returncode != 0: return f"git error: {result.stderr.strip()}" return result.stdout.strip() or "No commits found" ``` *** ## Productivity **No API key required** ```python theme={null} # ~/.neuralcleave/skills/pomodoro.py SKILL_METADATA = { "name": "pomodoro", "description": "Start a Pomodoro timer (25 min work / 5 min break cycle).", "version": "1.0.0", "trigger": "pomodoro", } import asyncio import time _sessions: dict = {} async def run(args: dict) -> str: action = args.get("action", "start") session_id = args.get("session_id", "default") if action == "start": _sessions[session_id] = {"started": time.time(), "work_min": int(args.get("work_min", 25))} return f"Pomodoro started. Focus for {_sessions[session_id]['work_min']} minutes. Good luck!" if action == "status": if session_id not in _sessions: return "No active Pomodoro. Use action=start to begin." elapsed = (time.time() - _sessions[session_id]["started"]) / 60 work_min = _sessions[session_id]["work_min"] if elapsed >= work_min: return f"Pomodoro complete! Take a 5-minute break. ({elapsed:.1f} min elapsed)" remaining = work_min - elapsed return f"Pomodoro in progress: {remaining:.1f} minutes remaining." if action == "stop": _sessions.pop(session_id, None) return "Pomodoro stopped." return "Unknown action. Use start, status, or stop." ``` **No API key required** ```python theme={null} # ~/.neuralcleave/skills/daily_digest.py SKILL_METADATA = { "name": "daily_digest", "description": "Fetch top headlines from RSS feeds for a morning digest.", "version": "1.0.0", "trigger": "digest", "dependencies": ["httpx", "feedparser"], } import httpx import feedparser _FEEDS = { "HN": "https://news.ycombinator.com/rss", "TheVerge": "https://www.theverge.com/rss/index.xml", "ArsTechnica": "http://feeds.arstechnica.com/arstechnica/index", } async def run(args: dict) -> str: feeds = args.get("feeds", list(_FEEDS.keys())) n = int(args.get("n", 5)) lines = [] for name in feeds: url = _FEEDS.get(name, name) try: r = httpx.get(url, timeout=8, follow_redirects=True) parsed = feedparser.parse(r.text) for entry in parsed.entries[:n]: lines.append(f"[{name}] {entry.title}") except Exception as e: lines.append(f"[{name}] Error: {e}") return "\n".join(lines) if lines else "No items fetched" ``` **No API key required** ```python theme={null} # ~/.neuralcleave/skills/obsidian_notes.py SKILL_METADATA = { "name": "obsidian_notes", "description": "Search your local Obsidian vault for notes matching a query.", "version": "1.0.0", "trigger": "obsidian", } import os from pathlib import Path async def run(args: dict) -> str: vault = Path(args.get("vault", os.path.expanduser("~/Documents/Obsidian"))) query = args.get("query", "").lower() if not vault.exists(): return f"Vault not found at {vault}" matches = [] for md in vault.rglob("*.md"): try: text = md.read_text(encoding="utf-8") if query in text.lower() or query in md.stem.lower(): excerpt = next((l.strip() for l in text.splitlines() if query in l.lower()), "") matches.append(f"{md.stem}: {excerpt[:100]}") if len(matches) >= 10: break except Exception: continue return "\n".join(matches) if matches else f"No notes matching '{query}'" ``` **Requires:** `NOTION_TOKEN`, `NOTION_DATABASE_ID` env vars ```python theme={null} # ~/.neuralcleave/skills/notion_tasks.py SKILL_METADATA = { "name": "notion_tasks", "description": "List incomplete tasks from a Notion database.", "version": "1.0.0", "trigger": "notion", "dependencies": ["httpx"], } import os import httpx async def run(args: dict) -> str: token = os.environ.get("NOTION_TOKEN", "") db_id = os.environ.get("NOTION_DATABASE_ID", "") headers = { "Authorization": f"Bearer {token}", "Notion-Version": "2022-06-28", "Content-Type": "application/json", } body = {"filter": {"property": "Status", "status": {"does_not_equal": "Done"}}, "page_size": 10} r = httpx.post(f"https://api.notion.com/v1/databases/{db_id}/query", json=body, headers=headers) results = r.json().get("results", []) if not results: return "No incomplete tasks in Notion" lines = [] for page in results: props = page.get("properties", {}) title_prop = next((v for v in props.values() if v.get("type") == "title"), None) title = title_prop["title"][0]["plain_text"] if title_prop and title_prop["title"] else "Untitled" lines.append(title) return "\n".join(lines) ``` *** ## Information & Research **No API key required** ```python theme={null} # ~/.neuralcleave/skills/hackernews_top.py SKILL_METADATA = { "name": "hackernews_top", "description": "Fetch the top N stories from Hacker News.", "version": "1.0.0", "trigger": "hacker news", "dependencies": ["httpx"], } import httpx async def run(args: dict) -> str: n = int(args.get("n", 10)) ids = httpx.get("https://hacker-news.firebaseio.com/v0/topstories.json").json()[:n] lines = [] for story_id in ids: story = httpx.get(f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json").json() lines.append(f"[{story.get('score', 0)}pts] {story.get('title', '')} — {story.get('url', 'news.ycombinator.com')}") return "\n".join(lines) ``` **No API key required (uses Yahoo Finance)** ```python theme={null} # ~/.neuralcleave/skills/stock_quote.py SKILL_METADATA = { "name": "stock_quote", "description": "Get the current stock price and daily change for a ticker symbol.", "version": "1.0.0", "trigger": "stock price", "dependencies": ["httpx"], } import httpx async def run(args: dict) -> str: ticker = args.get("ticker", "AAPL").upper() url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?interval=1d&range=1d" headers = {"User-Agent": "Mozilla/5.0"} r = httpx.get(url, headers=headers, follow_redirects=True) result = r.json().get("chart", {}).get("result", []) if not result: return f"Could not fetch data for {ticker}" meta = result[0]["meta"] price = meta.get("regularMarketPrice", 0) prev = meta.get("previousClose", price) change = price - prev pct = (change / prev * 100) if prev else 0 sign = "+" if change >= 0 else "" return f"{ticker}: ${price:.2f} ({sign}{change:.2f}, {sign}{pct:.2f}%)" ``` **No API key required (uses LibreTranslate public instance)** ```python theme={null} # ~/.neuralcleave/skills/translate.py SKILL_METADATA = { "name": "translate", "description": "Translate text to any language using LibreTranslate (free, no key).", "version": "1.0.0", "trigger": "translate", "dependencies": ["httpx"], } import httpx async def run(args: dict) -> str: text = args.get("text", "") target = args.get("target", "es") source = args.get("source", "auto") r = httpx.post("https://libretranslate.com/translate", json={"q": text, "source": source, "target": target, "format": "text"}, headers={"Content-Type": "application/json"}) return r.json().get("translatedText", "Translation failed") ``` **Requires:** `NEWSAPI_KEY` env var (free tier at newsapi.org) ```python theme={null} # ~/.neuralcleave/skills/news_briefing.py SKILL_METADATA = { "name": "news_briefing", "description": "Fetch top news headlines for a topic or country.", "version": "1.0.0", "trigger": "news", "dependencies": ["httpx"], } import os import httpx async def run(args: dict) -> str: key = os.environ.get("NEWSAPI_KEY", "") topic = args.get("topic", "technology") n = int(args.get("n", 5)) r = httpx.get("https://newsapi.org/v2/top-headlines", params={"q": topic, "pageSize": n, "apiKey": key}) articles = r.json().get("articles", []) if not articles: return f"No headlines found for '{topic}'" return "\n".join(f"- {a['title']} ({a['source']['name']})" for a in articles) ``` *** ## System & Infrastructure **No API key required** ```python theme={null} # ~/.neuralcleave/skills/system_monitor.py SKILL_METADATA = { "name": "system_monitor", "description": "Report CPU usage, memory usage, and disk space.", "version": "1.0.0", "trigger": "system status", "dependencies": ["psutil"], } import psutil async def run(args: dict) -> str: cpu = psutil.cpu_percent(interval=1) mem = psutil.virtual_memory() disk = psutil.disk_usage("/") return ( f"CPU: {cpu}%\n" f"Memory: {mem.percent}% used ({mem.used // 1024**2} MB / {mem.total // 1024**2} MB)\n" f"Disk: {disk.percent}% used ({disk.used // 1024**3} GB / {disk.total // 1024**3} GB)" ) ``` **No API key required (uses Docker socket)** ```python theme={null} # ~/.neuralcleave/skills/docker_status.py SKILL_METADATA = { "name": "docker_status", "description": "List running Docker containers with their status and ports.", "version": "1.0.0", "trigger": "docker", "dependencies": ["docker"], } import docker async def run(args: dict) -> str: client = docker.from_env() containers = client.containers.list() if not containers: return "No running containers" lines = [] for c in containers: ports = ", ".join( f"{h[0]['HostPort']}->{p}" for p, h in c.ports.items() if h ) or "no ports" lines.append(f"{c.name} ({c.status}) [{ports}]") return "\n".join(lines) ``` **No API key required** ```python theme={null} # ~/.neuralcleave/skills/ollama_models.py SKILL_METADATA = { "name": "ollama_models", "description": "List installed Ollama models or pull a new one.", "version": "1.0.0", "trigger": "ollama", "dependencies": ["httpx"], } import httpx _BASE = "http://localhost:11434" async def run(args: dict) -> str: action = args.get("action", "list") if action == "list": r = httpx.get(f"{_BASE}/api/tags") models = r.json().get("models", []) if not models: return "No Ollama models installed" return "\n".join(m["name"] for m in models) if action == "pull": name = args.get("model", "llama3") r = httpx.post(f"{_BASE}/api/pull", json={"name": name}, timeout=300) return f"Pulled {name}" if r.status_code == 200 else f"Pull failed: {r.text}" return "Unknown action. Use list or pull." ``` *** ## AI & Machine Learning **Requires:** `HF_TOKEN` env var (free HuggingFace account) ```python theme={null} # ~/.neuralcleave/skills/huggingface_classify.py SKILL_METADATA = { "name": "huggingface_classify", "description": "Zero-shot text classification using a local HuggingFace pipeline.", "version": "1.0.0", "trigger": "classify", "dependencies": ["transformers", "torch"], } from transformers import pipeline as hf_pipeline _clf = None async def run(args: dict) -> str: global _clf if _clf is None: _clf = hf_pipeline("zero-shot-classification", model="facebook/bart-large-mnli") text = args.get("text", "") labels = args.get("labels", ["positive", "negative", "neutral"]) if isinstance(labels, str): labels = [l.strip() for l in labels.split(",")] result = _clf(text, candidate_labels=labels) top = result["labels"][0] score = result["scores"][0] return f"Classification: {top} ({score:.1%} confidence)" ``` **Requires:** `SPOTIFY_ACCESS_TOKEN` env var ```python theme={null} # ~/.neuralcleave/skills/spotify_now_playing.py SKILL_METADATA = { "name": "spotify_now_playing", "description": "Show the currently playing Spotify track.", "version": "1.0.0", "trigger": "spotify", "dependencies": ["httpx"], } import os import httpx async def run(args: dict) -> str: token = os.environ.get("SPOTIFY_ACCESS_TOKEN", "") r = httpx.get("https://api.spotify.com/v1/me/player/currently-playing", headers={"Authorization": f"Bearer {token}"}) if r.status_code == 204: return "Nothing is playing right now" if r.status_code != 200: return f"Spotify error: {r.status_code}" data = r.json() if not data or not data.get("item"): return "Nothing is playing right now" item = data["item"] artists = ", ".join(a["name"] for a in item["artists"]) return f"Now playing: {item['name']} by {artists} ({item['album']['name']})" ``` **No API key required** ```python theme={null} # ~/.neuralcleave/skills/calendar_ical.py SKILL_METADATA = { "name": "calendar_ical", "description": "List upcoming events from an iCal URL (Google Calendar, Fastmail, etc.).", "version": "1.0.0", "trigger": "calendar", "dependencies": ["httpx", "icalendar"], } import httpx from icalendar import Calendar from datetime import datetime, timezone, timedelta async def run(args: dict) -> str: url = args.get("url", "") days = int(args.get("days", 7)) if not url: return "Provide an iCal URL via the `url` argument" r = httpx.get(url, follow_redirects=True) cal = Calendar.from_ical(r.content) now = datetime.now(tz=timezone.utc) cutoff = now + timedelta(days=days) events = [] for component in cal.walk(): if component.name != "VEVENT": continue dtstart = component.get("DTSTART").dt if hasattr(dtstart, "date"): dtstart = datetime.combine(dtstart, datetime.min.time(), tzinfo=timezone.utc) if now <= dtstart <= cutoff: summary = str(component.get("SUMMARY", "Untitled")) events.append((dtstart, summary)) events.sort(key=lambda x: x[0]) if not events: return f"No events in the next {days} days" return "\n".join(f"{dt.strftime('%a %b %d %H:%M')} - {s}" for dt, s in events[:15]) ``` **No API key required** ```python theme={null} # ~/.neuralcleave/skills/web_search.py SKILL_METADATA = { "name": "web_search", "description": "Search the web using DuckDuckGo Instant Answer API (no key required).", "version": "1.0.0", "trigger": "search", "dependencies": ["httpx"], } import httpx async def run(args: dict) -> str: query = args.get("query", "") r = httpx.get("https://api.duckduckgo.com/", params={"q": query, "format": "json", "no_redirect": 1, "no_html": 1}) data = r.json() abstract = data.get("AbstractText", "") related = [r["Text"] for r in data.get("RelatedTopics", [])[:5] if "Text" in r] if abstract: return abstract if related: return "\n".join(related) return f"No instant answer for '{query}'. Try a more specific query." ``` *** ## Contributing a skill 1. Fork the [NeuralCleave repo](https://github.com/TheAmitChandra/NeuralCleave) 2. Add your skill to `skills/examples/your_skill.py` following the anatomy in the [Skills docs](/skills) 3. Open a PR — the skill appears here after merge Skills must include `SKILL_METADATA` with `name` and `description`, and an async `run(args: dict) -> str` function. # Voice Overview Source: https://docs.neuralcleave.com/voice/overview NeuralCleave's local voice pipeline — wake word, VAD, STT, and TTS, all in-process. NeuralCleave ships a complete, local voice pipeline. Unlike tools that bolt on a cloud STT plugin, the voice stack runs in the same Python process as the gateway. ## Pipeline ``` Microphone ↓ OpenWakeWord (wake word detection) ↓ on wake Voice Activity Detection (VAD — energy or WebRTC) ↓ speech detected faster-whisper (STT) ↓ transcript NeuralCleave LLM pipeline (same as text chat) ↓ reply text TTS (ElevenLabs → Kokoro → pyttsx3) ↓ Speaker output ``` With Ollama + Kokoro + faster-whisper: **zero external API calls**. ## Quick enable ```toml theme={null} [voice] stt = "whisper" stt_model = "base" tts_engine = "kokoro" wake_word = "alexa" continuous_voice_enabled = true # required alongside wake_word — see Wake Word ``` Then restart the gateway. The Voice dashboard page at `/voice` shows live status. ## Voice modes | Mode | How to trigger | Use case | | ------------------ | ------------------------------ | ------------------------------ | | Wake word | Say the wake word | Hands-free, always-on | | Push-to-talk (PTT) | Hold the PTT button in the UI | Low-latency, no false triggers | | Continuous listen | Toggle in the Voice page | Voice-first workflows | | Microphone button | Click mic icon in chat toolbar | One-shot voice input | ## Subsystem availability The Voice page in the dashboard shows the live status of each subsystem: * **STT** — faster-whisper loaded and ready * **TTS** — TTS backend configured * **Wake Word** — detector active (amber pulse when listening) * **PTT** — push-to-talk configured ## Next steps Configure OpenWakeWord — always-on detection. PTT mode for low-latency, manual-trigger input. Configure STT and TTS backends. # Voice Providers Source: https://docs.neuralcleave.com/voice/providers Configure STT and TTS backends — from local faster-whisper to ElevenLabs cloud. NeuralCleave supports multiple STT (speech-to-text) and TTS (text-to-speech) backends. The defaults work fully offline. ## STT backends ### faster-whisper (default, local) [faster-whisper](https://github.com/SYSTRAN/faster-whisper) is a CTranslate2-optimized Whisper implementation. It runs on CPU or CUDA, requires no API key, and is completely local. ```toml theme={null} [voice] stt = "whisper" stt_model = "base" # tiny | base | small | medium | large-v3 stt_device = "cpu" # cpu | cuda ``` Model sizes: | Model | Size | Speed | Accuracy | | ---------- | ------ | ------- | -------- | | `tiny` | 75 MB | Fastest | Lowest | | `base` | 145 MB | Fast | Good | | `small` | 465 MB | Medium | Better | | `medium` | 1.5 GB | Slow | High | | `large-v3` | 3 GB | Slowest | Highest | Start with `base`. Models are downloaded automatically on first use. ### Disable STT ```toml theme={null} [voice] stt = "none" ``` ## TTS backends NeuralCleave always tries ElevenLabs → Kokoro → pyttsx3, in that order, using whichever provider succeeds first (ElevenLabs is skipped automatically when no API key is configured). `tts_engine` only gates whether TTS is enabled at all (any value other than `"none"` turns it on) — it does not currently pin synthesis to one specific engine or change the try-order, despite the name. Setting it to `"kokoro"` or `"pyttsx3"` does not skip ElevenLabs if a key happens to be configured. ### Kokoro (local, high quality) [Kokoro](https://github.com/hexgrad/kokoro) is an open-source neural TTS model. It runs on CPU and produces near-ElevenLabs quality without any API key. ```toml theme={null} [voice] tts_engine = "kokoro" ``` There is no config key for selecting a Kokoro voice yet — `TTSEngine` always uses its `"af_sarah"` default, and `[voice]` has no field that reaches it. ### ElevenLabs (cloud, best quality) ```toml theme={null} [voice] tts_engine = "elevenlabs" elevenlabs_api_key = "ENV:ELEVENLABS_API_KEY" elevenlabs_voice_id = "21m00Tcm4TlvDq8ikWAM" # Rachel (default) ``` Find voice IDs at [elevenlabs.io/voice-library](https://elevenlabs.io/voice-library). ### pyttsx3 (local, system TTS) Fallback that uses the OS text-to-speech engine. No install required. ```toml theme={null} [voice] tts_engine = "pyttsx3" ``` ### Disable TTS ```toml theme={null} [voice] tts_engine = "none" ``` ## Audio devices Configure input/output devices to route audio correctly on systems with multiple devices: ```toml theme={null} [voice] input_device = "" # empty = system default output_device = "" # empty = system default ``` The Settings → Voice page in the dashboard shows a live dropdown of available devices populated from `GET /api/v1/voice/devices`. ## Privacy note Privacy mode (the in-chat `/privacy on|off` command) only affects text generation — it forces `ModelRouter` onto local-only models and has no effect on the voice pipeline at all. It does **not** force TTS to Kokoro or stop ElevenLabs from being used, and there is no `privacy_mode` entry in `[voice]` or anywhere else in `config.py` — it isn't a config setting. To keep voice fully local today, don't configure `elevenlabs_api_key` and leave `tts_engine` set to `"kokoro"` or `"pyttsx3"`. # Push-to-Talk Source: https://docs.neuralcleave.com/voice/push-to-talk Manual-trigger voice input — hold the PTT button to record, release to transcribe and reply. Push-to-Talk (PTT) lets you trigger voice input manually by holding a button in the dashboard. This avoids the always-on microphone access required by wake word mode. ## How it works 1. Hold the **PTT button** (phone icon) in the chat toolbar or the `/voice` page. 2. Speak your message. 3. Release the button. 4. NeuralCleave transcribes via STT and generates a reply. 5. The reply is delivered as text (and played via TTS if configured). ## Configuration PTT requires STT to be configured: ```toml theme={null} [voice] stt = "whisper" stt_model = "base" ``` No additional PTT config is needed — the feature activates automatically when `stt` is set. ## PTT button states | State | Appearance | | -------------------------------- | --------------------------------------------------------------------------- | | Unavailable (STT not configured) | Dimmed, disabled — tooltip: "PTT not configured — enable voice in Settings" | | Ready | Normal icon | | Recording | Pulsing green background | The PTT button is always visible in the chat toolbar so users can see the feature exists even before configuring voice. ## API You can trigger PTT programmatically: ```bash theme={null} # Start recording curl -X POST http://localhost:7432/api/v1/voice/ptt/start # { "started": true } # Stop recording and get transcript curl -X POST http://localhost:7432/api/v1/voice/ptt/stop # { "transcript": "What is the weather today?", "response": "It is..." } ``` ## Compared to wake word | | Wake word | PTT | | ---------------- | ---------------------- | ------------------------ | | Hands-free | Yes | No | | Always listening | Yes | No (mic only while held) | | Privacy | Mic always on | Mic only when pressed | | Latency | Higher (handoff + VAD) | Lower (instant) | | False triggers | Possible | None | # Wake Word Source: https://docs.neuralcleave.com/voice/wake-word Always-on wake word detection using OpenWakeWord — cross-platform, runs 100% locally. NeuralCleave uses [OpenWakeWord](https://github.com/dscripka/openWakeWord) for wake word detection. OpenWakeWord runs on CPU, works on Windows, macOS, and Linux, and requires no cloud account. ## Configuration ```toml theme={null} [voice] wake_word = "alexa" # alexa | hey_jarvis | custom wake_word_threshold = 0.5 # 0.0–1.0; higher = fewer false positives continuous_voice_enabled = true # required — see "Handoff" below ``` `continuous_voice_enabled` isn't optional here even though it's a separate key: the wake-word detector only *fires*, it doesn't itself transcribe anything — the handoff to STT described below only happens when continuous listening is also enabled. Leaving it at its default (`false`) with only `wake_word` set produces a detector that logs a detection and does nothing else, with no error to indicate why. ## Built-in wake words | Model name | Phrase | | ------------- | ------------- | | `alexa` | "Alexa" | | `hey_jarvis` | "Hey Jarvis" | | `hey_mycroft` | "Hey Mycroft" | ## Custom wake word You can train a custom wake word model using OpenWakeWord's training tools: 1. Record 50–200 samples of your phrase. 2. Train with `openwakeword train`. 3. Place the `.tflite` model file in `~/.neuralcleave/wakewords/`. 4. Set `wake_word_model_path = "~/.neuralcleave/wakewords/my_phrase.tflite"` (takes precedence over `wake_word`). Keep `wake_word` set to any non-empty value too — it gates whether the detector is created at all. ## Status indicators In the chat toolbar, the `VoiceStatusIndicator` shows an amber **Wake** badge when the detector is active. The `/voice` dashboard page shows a larger animated indicator. ## Tuning sensitivity `wake_word_threshold` controls the detection threshold (0.0–1.0): * **Lower** (e.g. 0.3): more responsive, more false positives * **Higher** (e.g. 0.7): fewer false positives, may miss softer speech Start at `0.5` and adjust based on your environment noise level. ## Handoff Requires `continuous_voice_enabled = true` (see Configuration above) — without it, this handoff never happens. When the wake word is detected: 1. The detector hands off to the VAD (Voice Activity Detection) layer. 2. VAD waits for a full utterance (silence after speech). 3. The audio chunk is passed to the STT backend. 4. The transcript enters the NeuralCleave pipeline. 5. The TTS reply plays back through the output device. The `handoffActive` flag is visible in the `/voice` dashboard during a handoff.