Architecture
A detailed look at how MachinaOs works under the hood. For contributors, system designers, and the curious. For a navigable tour with hyperlinks, see the DeepWiki page.System Overview
MachinaOs is three loosely-coupled tiers talking over a single persistent WebSocket connection:100+ Workflow Nodes
AI, agents, social, Android, documents, Google Workspace, code, browser, proxies, utilities
11 Chat-Model Providers
OpenAI, Anthropic, Gemini, OpenRouter, DeepSeek, Kimi, Mistral, Groq, Cerebras, plus local Ollama and LM Studio
16 Specialized Agents
Android, Coding, Web, Task, Social, Travel, Tool, Productivity, Payments, Consumer, Autonomous, Orchestrator, AI Employee, RLM, Claude Code, Codex
WebSocket-First
A single persistent connection carries all frontend-backend RPC and push updates
Built-in Skills
Dozens of skills across many categories, DB-backed with SKILL.md defaults
Three Execution Modes
Temporal distributed, Redis parallel, sequential fallback
Execution Engine
Conductor’s Decide Pattern
Workflow orchestration is a single function with fork/join parallelism:ExecutionContext. No shared global state between concurrent runs. Decide loops serialize per execution via Redis SETNX distributed locks.
Three Execution Modes
Layer Computation via Kahn’s Algorithm
Before execution, the DAG is sorted into layers. Layer 0 is the set of nodes with no dependencies; each subsequent layer depends only on earlier layers. Parallel execution runs each layer withasyncio.gather():
androidTool) are detected and excluded from execution layers — they run only when the parent toolkit invokes them via tool calling.
Result Caching, Recovery, and DLQ
- Prefect-style caching: every node result is stored in Redis/SQLite keyed by
hash_inputs(inputs). Re-running an identical node returns the cached result with statusTaskStatus.CACHED. - Heartbeat recovery:
RecoverySweeperscansexecutions:activeevery 60s; nodes with stale heartbeats (> 5 min) are marked stuck and recovered on next startup. - Dead Letter Queue: failed nodes (after retry exhaustion) are quarantined with full input snapshot. Inspect, replay, or purge via the
get_dlq_*/replay_dlq_entry/purge_dlqWebSocket handlers.
Edge Conditions
Edges carry optional conditions for runtime branching with 20+ operators (eq, neq, gt, lt, contains, exists, matches, in, …). Unmatched branches are marked TaskStatus.SKIPPED.
Event-Driven Deployment
Deployments are event-driven: each trigger event spawns an independent concurrent execution run. There is no iteration loop._pre_executed with {not_triggered: True} so they never block as event waiters.
Push vs Polling Triggers
asyncio.Future, or Redis Streams for multi-worker deployments).
AI Agent System
11 Chat-Model Providers
Each provider below has its own chat-model node and appears in every agent’s provider dropdown. (xAI is reachable on the native chat path through the shared OpenAI-compatible client, but it is not a standalone chat-model node.)| Provider | Native SDK Path | LangChain Path | Notes |
|---|---|---|---|
| OpenAI | Yes | Yes | GPT-5.5/5.4/5.2, GPT-4.1 family, o3/o4-mini reasoning, GPT-4o/4o-mini |
| Anthropic | Yes | Yes | Claude Fable 5, Opus 4.8/4.7, Sonnet 4.6, Haiku 4.5 (extended thinking via budget_tokens) |
| Gemini | Yes | Yes (fallback) | Gemini 3.5-flash, 3.1-pro/flash-lite, 3-flash, 2.5-pro/flash/flash-lite; native path bypasses a LangChain Windows hang |
| OpenRouter | Yes | Yes | 200+ models through one API |
| DeepSeek | Yes (shared OpenAIProvider) | Yes | deepseek-v4-flash, deepseek-v4-pro (chat/reasoner legacy) |
| Kimi | Yes (shared OpenAIProvider) | Yes | Moonshot kimi-k2.6, kimi-k2.5, kimi-k2.7-code |
| Mistral | Yes (shared OpenAIProvider) | Yes | Large / Medium / Small / Codestral (latest) |
| Groq | No (LangChain only) | Yes | Llama 3.3-70b, Llama 3.1-8b, GPT-OSS-120b/20b, Qwen3-32b |
| Cerebras | No (LangChain only) | Yes | GPT-OSS-120b, Qwen-3-235b, GLM-4.7 |
| Ollama | Yes (shared OpenAIProvider) | Yes | Local server; whatever models the user has pulled |
| LM Studio | Yes (shared OpenAIProvider) | Yes | Local server; whatever models the user has loaded |
Dual-Path Architecture
LLMResponse dataclass across all providers. Agent tool-calling still uses the LangChain chat-model wrappers (bind_tools) driven by the plain-async _run_agent_loop; the native SDK path powers direct chat completions and model discovery. Groq and Cerebras remain LangChain-only for chat as well.
16 Specialized Agents
All specialized agents share the same handle architecture (input-main, input-memory, input-skill, input-tools, input-task) and dispatch through the same BaseNode.execute() plugin path. They mostly differ in icon, title, theme color, and default prompt.
- Most agents run the shared plain-async agent loop (
_run_agent_loop) for tool calling and delegation. rlm_agentroutes toRLMService(REPL-based recursive LM withllm_query/rlm_query/FINAL).claude_code_agentandcodex_agentrun through the multi-provider CLI agent framework (Claude Code / Codex CLIs) instead of the standard LLM loop.
Agent Teams Topology
orchestrator_agent and ai_employee have an extra input-teammates handle. Connected agents become delegate_to_<agent_type> tools automatically:
asyncio.create_task(), the parent continues, and the child broadcasts its own status independently. Either way, child completion can be consumed by taskTrigger nodes elsewhere in the workflow.
Agent Loop Flow
tool_calls. A recursion limit guards against infinite tool loops, and a token-based compaction threshold summarizes the transcript before it overflows the model’s context. Tools are built as Pydantic-schema StructuredTool instances with the node’s parameter schema.
Memory, Skills, Tokens, and Cost
Markdown-Based Memory
ThesimpleMemory node stores conversation history as editable Markdown in the parameter panel. The AI Agent handler reads, parses to LangChain messages, executes, appends the new exchange, trims to a window, and archives removed messages to an InMemoryVectorStore (optional) using HuggingFace BAAI/bge-small-en-v1.5 embeddings.
Skill System
Dozens of built-in skills organized into folders underserver/skills/. Each top-level folder appears as an option in the Master Skill node’s folder dropdown:
SKILL.md file containing YAML frontmatter (name, description, allowed-tools, metadata) and Markdown instructions. First load seeds the database; after that the database is source of truth so users can edit skill instructions in the UI. “Reset to Default” reloads the original SKILL.md.
The masterSkill node aggregates multiple skills with enable/disable toggles. A split-panel editor shows the skill list on the left and the selected skill’s Markdown on the right. When connected to an agent, the backend expands the skillsConfig parameter into individual skill entries injected into the agent’s system message.
Token Tracking and Compaction
Every AI execution stores aTokenUsageMetric row with input/output/cache/reasoning token counts and calculated costs (USD) based on server/config/pricing.json. Cumulative state per session lives in SessionTokenState.
Compaction threshold priority (highest to lowest):
- Per-session
custom_threshold(user-set) - Per-user
UserSettings.compaction_ratiox the model’s context window - Environment
COMPACTION_RATIO(default 0.8) x the model’s context window (e.g., ~838K for Claude Sonnet 4.6 with 1M context) - JSON fallback
llm_defaults.jsonratio x context window
CompactionService.compact_context() generates a 5-section summary (Task Overview, Current State, Important Discoveries, Next Steps, Context to Preserve) following the Claude Code pattern and replaces the memory content. Anthropic and OpenAI also have native compaction APIs (context_management edits, compact_threshold) that are configured transparently.
Communication Layer
A single persistent WebSocket at/ws/status handles most frontend-backend communication. Handlers live in the MESSAGE_HANDLERS map in server/routers/websocket.py plus plugin-registered handlers that self-wire through services.ws_handler_registry (each self-contained plugin folder can own its own WebSocket commands). Together they cover: node parameters, tool schemas, node execution, triggers, dead letter queue, deployment, AI operations, API keys, OAuth flows (Claude, Twitter, Google), Android, WhatsApp, Telegram, workflow storage, chat messages, console logs, skills, memory, user settings, pricing, agent teams, and model registry.
Request/Response Pattern
Broadcast Message Types
Auto-Reconnect and Keepalive
Frontend sends{"type": "ping"} every 30 seconds. Reconnection uses PartySocket with jittered exponential backoff and message replay, so a dropped socket recovers automatically and queued requests replay on the new connection. Connection is gated on isAuthenticated so logged-out users never connect.
Cache, Persistence, and Security
Cache Fallback Hierarchy
MachinaOs follows the n8n cache pattern with automatic environment-based fallback:CacheService in server/core/cache.py checks each backend in order. TTL expiration is supported across all three. A background cleanup_expired_cache() task removes expired SQLite rows.
Encrypted Credentials
API keys and OAuth tokens live in a separate SQLite database (credentials.db) isolated from the main workflow database (workflow.db). Encryption uses Fernet (AES-128-CBC + HMAC-SHA256) with keys derived from a server-scoped config key via PBKDF2HMAC (600K iterations, OWASP 2024 recommendation).
credentials.db:
- API key system (
EncryptedAPIKeytable): provider keys the user enters manually - OAuth token system (
EncryptedOAuthTokentable): tokens from OAuth flows (Google, Twitter, Claude.ai)
AuthService only. Direct database access is forbidden. Decrypted values are cached in AuthService memory dicts and never written to disk or Redis.
For cloud deployments, CREDENTIAL_BACKEND can be switched to keyring (OS-native) or aws (Secrets Manager) via the CredentialBackend abstraction.
Authentication
JWT in HttpOnly cookies following the n8n pattern. Two modes:AUTH_MODE=single- first user becomes owner, registration disabled afterAUTH_MODE=multi- open registration for cloud deploymentsVITE_AUTH_ENABLED=false- bypass login entirely for local development
Related
Node Catalog
Browse all workflow nodes by category
AI Models
11 chat-model providers with native SDK and LangChain paths
AI Agents
16 specialized agents with teams and delegation
GitHub
Source code and in-repo
docs-internal/ deep dives