Architecture Overview
Five-layer system architecture, module dependencies, and data flow from user message to AI response.
Aleph is organized into five horizontal layers that form a clean processing pipeline: Interface, Gateway, Orchestrator, Harness, and Storage. Every user message traverses these layers top-to-bottom; every response travels back up. This page maps the full system, shows how modules depend on one another, and traces a request through the entire lifecycle.
For deeper dives into individual subsystems, see Gateway Architecture, Harness, Session Service, Tool Architecture, and Memory System.
Design Philosophy
Single-Core Multi-Terminal, Shell-Core Separation; Gateway Interoperability, Access Control.
Aleph's architecture is built on four principles that govern every design decision:
-
Single-Core Multi-Terminal — One
aleph-serverprocess powers every interface. Whether you chat via the desktop app, CLI, Telegram, or Discord, the same core handles all reasoning, tool execution, and state management. -
Shell-Core Separation — The desktop app is a thin native shell (Tauri v2). It owns the window, tray, notifications, and OS integrations — but zero business logic and zero business UI. All product UI lives in the Leptos Panel served by the core. All reasoning, tools, and state live in
aleph-server. The shell can connect to a local core or a remote one over Tailnet/VPN. -
Gateway Interoperability — Every terminal speaks the same authenticated WebSocket protocol (
JSON-RPC 2.0overws://). A CLI tool, a Telegram bot, and the desktop shell all call identical methods on the same Gateway. -
Access Control — Every connection is authenticated. The desktop shell reads a shared token from the core's security database. Remote connections use the same token mechanism. Guest sessions carry restricted scopes. See Identity and Security for details.
From "many channels" to "many bodies." Single-Core Multi-Terminal gives one brain many I/O channels. Cluster Federation extends the same principle to many execution bodies: a single center core orchestrates work across several machines (nodes) — while the cluster still has exactly one mind.
System Layers
┌─────────────────────────────────────────────────────────────────────────────┐
│ INTERFACE LAYER (I/O) │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Desktop │ │ CLI │ │ Telegram │ │ Discord │ │ TUI │ │
│ │ Shell │ │ │ │Interface │ │Interface │ │ │ │
│ │(Tauri v2)│ │ │ │ │ │ │ │ │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │ │
│ └─────────────┴─────────────┴─────────────┴─────────────┘ │
│ │ │
│ WebSocket (JSON-RPC 2.0) + Auth Token │
│ ws://127.0.0.1:18790/ws │
└───────────────────────────────────┬─────────────────────────────────────────┘
│
┌───────────────────────────────────┴─────────────────────────────────────────┐
│ GATEWAY LAYER │
│ (Control Plane + Routing) │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Router │ │ Session │ │ Event │ │ Security │ │
│ │ (JSON-RPC) │ │ Manager │ │ Bus │ │ (Auth) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Interface │ │ Config │ │ Webhooks │ │ Cron │ │
│ │ Registry │ │ Hot Reload │ │ │ │ Scheduler │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
└───────────────────────────────────┬─────────────────────────────────────────┘
│
┌───────────────────────────────────┴─────────────────────────────────────────┐
│ ORCHESTRATOR LAYER │
│ (AgentDef + FlowSpec Resolution + Dispatch) │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ Orchestrator │ │
│ │ Resolves AgentDef + FlowSpec, builds HarnessDeps, dispatches │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└───────────────────────────────────┬─────────────────────────────────────────┘
│
┌───────────────────────────────────┴─────────────────────────────────────────┐
│ HARNESS LAYER │
│ (Think→Act Loop + Stop-Hooks) │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ AgentHarness │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Context │→ │ Think │→ │ Act │→ │Stop-Hook│→ │ Compact │ │ │
│ │ │ (Budget)│ │(Thinker)│ │ (Tools) │ │ Check │ │ (Budget)│ │ │
│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ ToolService │ │ Guards │ │ Overflow │ │
│ │ (Tool Exec) │ │ (Safety) │ │ Detector │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└───────────────────────────────────┬─────────────────────────────────────────┘
│
┌───────────────────────────────────┴─────────────────────────────────────────┐
│ STORAGE LAYER │
├─────────────────────────────────────────────────────────────────────────────┤
│ ┌────────────────────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Memory (SQLite+sqlite-vec)│ │ Resilience │ │ Config Store │ │
│ │ ┌──────┐ ┌───────┐ │ │ (SQLite) │ │ ┌─────┐┌────┐ │ │
│ │ │Facts │ │ Graph │ │ │ ┌──────────┐ │ │ │TOML ││Keys│ │ │
│ │ │+Vec │ │ Nodes │ │ │ │ State │ │ │ │File ││ │ │ │
│ │ │+FTS │ │ Edges │ │ │ │ Database │ │ │ └─────┘└────┘ │ │
│ │ └──────┘ └───────┘ │ │ └──────────┘ │ └─────────────────┘ │
│ └────────────────────────────┘ └────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘Layer 1: Interface
The topmost layer contains all client applications. Every client — whether the desktop shell, terminal CLI, or a Telegram/Discord bot — connects to the same Gateway via a single authenticated WebSocket endpoint at ws://127.0.0.1:18790/ws. Communication uses JSON-RPC 2.0, meaning every client speaks the same protocol regardless of platform.
Desktop Shell (Tauri v2). The native desktop app is the "last-mile native shell." It provides:
- Native window + webview hosting the Leptos Panel (
http://127.0.0.1:18790) - System tray with "Quit" and "Quit & Stop Aleph" options
- OS notifications via WebSocket event bridge
- Global summon hotkey (
CmdOrCtrl+Shift+A) aleph://URL scheme for deep links- Background auto-update checker
- Launch-at-login
- Daemon lifecycle supervision (relaunches core if it crashes)
Crucially, the shell contains no business logic and no business UI. All product UI (chat, memory, settings) lives in the Panel (WASM, served by the core). All reasoning, tools, and state live in aleph-server. This separation means:
- The shell can be updated independently of the core
- The core can run headless on a server while the shell connects remotely
- The same core serves the desktop shell, CLI, and messaging bots simultaneously
Remote Core Support. The desktop shell can connect to a remote aleph-server over Tailnet or VPN. The Panel's directory picker browses the server's filesystem via JSON-RPC (fs.*), ensuring correct semantics for remote deployments. Authentication uses a shared token injected by the shell at startup (read from ~/.aleph/data/security.db via the core's bootstrap-token subcommand).
Layer 2: Gateway
The Gateway is the control plane. It accepts WebSocket connections, parses JSON-RPC messages, routes them to the correct handler, and manages sessions, events, and authentication. It also hosts the Interface Registry (which tracks active chat integrations), a configuration hot-reload watcher, and the cron scheduler for background tasks. See Gateway Architecture for details.
Layer 3: Orchestrator
The Orchestrator resolves the AgentDef and FlowSpec for each incoming request, assembles the HarnessDeps (injecting SessionService, ToolService, Sandbox, and AiProvider), and dispatches to HarnessRunner::run. This layer separates routing concerns from execution logic, allowing the Gateway to remain a thin control plane. See Harness for the Orchestrator-Harness interaction.
Layer 4: Harness
The Harness layer runs the core intelligence loop. When a message arrives, AgentHarness executes a Think→Act cycle with context budget enforcement, stop-hook evaluation, and optional compaction: it gathers context with budget constraints, calls an LLM to decide what to do, executes tools if needed, evaluates stop-hooks and guards, and optionally compresses the history. ToolService handles tool execution, while guards enforce safety limits like iteration caps and token budgets. See Harness for the full cycle.
Layer 5: Storage
The bottom layer provides persistent storage and state management. Memory uses SQLite with sqlite-vec extension for vector search, plus markdown notes and wikilink graphs. Resilience stores task recovery and state in SQLite. Config persists settings via TOML files and key management. See Memory System for details.
Module Dependencies
The following diagram shows how Rust modules depend on each other at compile time. The gateway crate is the entry point; it fans out into interfaces, routing, and the orchestrator. The orchestrator dispatches to the harness, which drives memory and execution subsystems. The workflow module compiles declarative templates into the existing coord_tasks DAG executed by the TeamDispatcher (see Workflow).
┌─────────────┐
│ gateway │ ← Entry point (chat ingress, protocol adapters)
└──────┬──────┘
│ FlowRequest
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│interfaces │ │ routing │ │orchestrator│
└───────────┘ └───────────┘ └─────┬─────┘
│ HarnessRunner::run
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ harness │ │ memory │ │ exec │
└─────┬─────┘ └───────────┘ └───────────┘
│
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ thinker │ │tool_service│ │ engine │
└─────┬─────┘ └───────────┘ └─────┬─────┘
│ │
▼ ▼
┌───────────┐ ┌───────────┐
│ providers │ │ tools │
└───────────┘ └─────┬─────┘
│
┌─────────────────┼─────────────────┐
│ │ │
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│ builtin │ │ mcp │ │ extension │
│ tools │ │ client │ │ (plugins) │
└───────────┘ └───────────┘ └───────────┘Core Modules
As of 26.7.22+ the
aleph-serverprocess holds 70src/<module>directories plus 6 top-level.rsfiles (canvas_io.rs/sync_primitives.rs/pricing.rs/event_handler.rs/lib.rs/error.rs). The table below is grouped by purpose and stays in sync with thesrc/tree.
| Module | Path | Purpose |
|---|---|---|
| gateway | src/gateway/ | WebSocket server, JSON-RPC routing, channel adapters, TLS, OpenAI-compatible API |
| orchestrator | src/orchestrator/ | FlowSpec / FlowRequest resolution, HarnessRunner trait, AgentHarnessRunner |
| harness | src/harness/ | Think→Act loop, stop-hooks, context budget, compaction, HarnessDeps struct |
| agents | src/agents/ | Agent runtime, subagent spawning, think_level resolution, model binding |
| thinker | src/thinker/ | LLM interaction, prompt assembly (PromptBuilder / PromptPipeline), layer registry |
| tool_metadata | src/tool_metadata/ | Tool metadata + risk + unified index + slash aliases (replaces the retired src/dispatcher/) |
| providers | src/providers/ | AI provider implementations + failover chain + MoA aggregator |
| tools | src/tools/ | AlephTool trait, tool server, scoped tool service, turn budget |
| builtin_tools | src/builtin_tools/ | Built-in tools (hub/ absorbs store/, skill_reader/, browser_tools/ per-action) |
| memory | src/memory/ | Facts DB, hybrid retrieval (SQLite + sqlite-vec + markdown notes + wikilink graph) |
| extension | src/extension/ | Plugin system (WASM, Node.js) |
| exec | src/exec/ | Shell execution, approval system, OS-native sandboxing |
| sandbox | src/sandbox/ | Sandbox trait + WorkspaceSandbox — per-session workspace, capability ledger, ApprovalGate escalation |
| mcp | src/mcp/ | MCP client implementation + on-demand discovery tools |
| routing | src/routing/ | Session key resolution + binding rules |
| config | src/config/ | Configuration management + reloader + typed policy |
| runtimes | src/runtimes/ | Capability ledger — probe, bootstrap, persist external tool status |
| session | src/session/ | Append-only session event log (session_events is the single source) + in-process actor |
| loop_graph | src/loop_graph/ | Governance topology store + service + templates (layered on top of the core) |
| looping | src/looping/ | Loop subsystem (in-process LoopRegistry + state machine) |
| goal | src/goal/ | Goal subsystem (persistent GoalStore + objective gate + TreeBudget) |
| strategy | src/strategy/ | Strategy subsystem (composite-keyed StrategyStore + planner + renderer) |
| hub | src/hub/ | Aleph Hub single source (replaces the retired src/store/) — primer / catalog_client / official_* / install / reconcile / trust / verify / secrets |
| artifacts | src/artifacts/ | Artifact store (ArtifactStore + MAX_ARTIFACT_BYTES = 50 MB + 4 ArtifactOrigins) |
| export | src/export/ | session HTML / Markdown export + CSS + collect + page + document |
| clipboard | src/clipboard/ | Clipboard context (10s) + multimodal image extraction |
| projects | src/projects/ | Project store (projects.json + lock) |
| vision | src/vision/ | Vision subsystem (claude / OpenAI-compat / multimodal) |
| a2a | src/a2a/ | A2A protocol adapter |
| acp | src/acp/ | ACP protocol implementation |
| approval | src/approval/ | Approval system + action-aware grant |
| browser | src/browser/ | Browser automation (secret guard / PII single source) |
| cluster | src/cluster/ | Single-center node federation — reverse RPC, node registry, node_invoke / node_file |
| command | src/command/ | Lightweight command-completion aggregator (top-level mod.rs / parser.rs) |
| components | src/components/ | Shared domain types (only types; the legacy EventHandler chain was removed during the Harness migration) |
| context | src/context/ | Context management (ContextBudget / ContextCompactor / PreflightPipeline) |
| core | src/core/ | Core types and primitives |
| diagnostics | src/diagnostics/ | Diagnostics utilities |
| discovery | src/discovery/ | Service discovery |
| domain | src/domain/ | Shared domain types |
| event | src/event/ | Event system |
| fetch | src/fetch/ | HTTP fetch (for tools) |
| generation | src/generation/ | Media generation (image / video / voice) |
| group_chat | src/group_chat/ | Group chat management |
| guardrails | src/guardrails/ | Guardrail registry (input / output / tool-call) |
| identity | src/identity/ | Agent identity and signing |
| init_unified | src/init_unified/ | One-shot install coordinator (5 phases: dirs / config / DB / runtimes / skills) |
| logging | src/logging/ | Logging infrastructure |
| markdown | src/markdown/ | Markdown processing |
| media | src/media/ | Media processing |
| metrics | src/metrics/ | Metrics collection |
| pii | src/pii/ | PII detection and handling |
| pricing | src/pricing.rs (top-level) | Core-side pricing + cost estimation |
| resilience | src/resilience/ | State management (SQLite) |
| search | src/search/ | Search providers |
| secrets | src/secrets/ | Secret management |
| security | src/security/ | Security utilities (SSRF, unicode guard) |
| skill | src/skill/ | Skill system (v2 SkillSystem + eligible-skill injection) |
| tasks | src/tasks/ | Task management (cron / heartbeat / dreaming / reaper) |
| teams | src/teams/ | Team coordination |
| workflow | src/workflow/ | Declarative workflow templates, compilation, and execution |
| tool_output | src/tool_output/ | Tool output handling |
| utils | src/utils/ | Utilities |
| verification | src/verification/ | Verifier chain (StopHookVerifier / ToolLoopVerifier / model robustness profile) |
| wizard | src/wizard/ | Wizard flows (RPC-driven wizard.next sessions; no CLI aleph wizard subcommand) |
Data Flow: Request Lifecycle
When a user sends a message, the following sequence occurs:
Client Request (JSON-RPC over WebSocket)
│
▼
┌─────────────────────────────────────────────────────┐
│ Gateway: InboundRouter │
│ • Parse JSON-RPC message │
│ • Route to appropriate handler │
│ • Authentication check (if enabled) │
│ • Construct FlowRequest { agent_id, input, ... } │
└─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ Orchestrator │
│ • Resolve AgentDef + FlowSpec │
│ • Build HarnessDeps (SessionService, ToolService, │
│ Sandbox, AiProvider) │
│ • Dispatch to HarnessRunner::run │
└─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ AgentHarness: Think → Act loop │
│ 1. Context: Apply budget, preflight prep │
│ 2. Think: Call Thinker (LLM) for decision │
│ 3. Act: Execute tools via ToolService │
│ 4. Stop-hook: Evaluate completion / guards │
│ 5. Compact: If overflow, compact history │
└─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ FlowOutcome → Gateway renders response │
│ • Stream events via TraceSink / EventBus │
│ • Final response as JSON-RPC result │
│ • Session history persisted to SQLite │
└─────────────────────────────────────────────────────┘Tool Execution Sub-Flow
When the Thinker decides to call a tool, execution branches through the Dispatcher and Engine:
Thinker Decision (tool_use)
│
▼
┌─────────────────────────────────────────────────────┐
│ Dispatcher │
│ • Analyze tool request │
│ • Check permissions (ToolFilter) │
│ • Risk evaluation │
│ • Confirmation flow (if needed) │
└─────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────┐
│ Engine │
│ • Lookup tool (Builtin / MCP / Extension) │
│ • Deserialize arguments │
│ • Execute with timeout │
│ • Capture output │
└─────────────────────────────────────────────────────┘
│
├─── Builtin Tool (AlephTool trait)
│ • Direct Rust execution
│
├─── MCP Tool (Model Context Protocol)
│ • JSON-RPC to external process
│
└─── Extension Tool (WASM / Node.js)
• Plugin runtime executionExec-class tools (code_exec, bash_exec) route through an additional Sandbox layer (src/sandbox/) between the tool and process execution. The sandbox owns per-session workspace provisioning (~/.aleph/workspaces/{session_id}/), capability enforcement, and OS-level seatbelt isolation via OsSandboxDriver.
Design Patterns
Aleph employs several Rust-idiomatic design patterns across the codebase.
Context Pattern
Groups related function parameters into dedicated structs, reducing parameter sprawl and enabling the builder pattern:
// Before: 7 parameters passed directly
legacy_agent_loop.run(request, context, tools, identity, callback, abort_signal, initial_history).await
// After: structured deps + FlowRequest
let deps = HarnessDeps { session, tool_service, sandbox, provider, trace_sink };
let flow = FlowRequest::new(agent_id, input, identity)
.with_abort_signal(abort_rx);
HarnessRunner::run(flow, deps).awaitBenefits:
- Extensibility: Add parameters without breaking changes
- Readability: Clear parameter grouping
- Type Safety: Compile-time validation
- Ergonomics: Builder pattern for optional parameters
Newtype Pattern
Wraps primitive types in distinct structs for compile-time safety. You cannot accidentally pass a SessionId where an ExperimentId is expected:
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExperimentId(String);
impl ExperimentId {
pub fn new(id: impl Into<String>) -> Self { Self(id.into()) }
pub fn as_str(&self) -> &str { &self.0 }
}
impl Deref for ExperimentId {
type Target = str;
fn deref(&self) -> &Self::Target { &self.0 }
}Newtype Catalog:
- IDs:
ExperimentId,VariantId,ContextId,TaskId,SubscriptionId - Collections:
Ruleset(permission rules) - Values:
Answer(question responses)
FromStr Trait Pattern
Provides consistent parsing interface across the codebase:
impl FromStr for TaskStatus {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"pending" => Ok(Self::Pending),
"running" => Ok(Self::Running),
_ => Err(format!("Invalid TaskStatus: {}", s)),
}
}
}
// Usage
let status: TaskStatus = "pending".parse()?;Implemented for: FactType, HookKind, DeviceType, TaskStatus, RuntimeKind, and 10+ other types.
Feature Flags
All production features are always compiled; no feature flags are needed. Only test features remain:
[features]
default = []
loom = ["dep:loom"] # Concurrency testing
test-helpers = [] # Integration test helpersChannels are enabled or disabled at runtime via config.toml configuration.
Workspace Structure
The Aleph repository is organized as a Cargo workspace:
aleph/
├── Cargo.toml # Workspace root + alephcore package
├── src/ # alephcore library + aleph-server binary
│ ├── lib.rs # Library crate entrypoint
│ ├── bin/
│ │ └── aleph-server/ # Server binary
│ ├── gateway/ # WebSocket server, JSON-RPC routing
│ ├── orchestrator/ # AgentDef + FlowSpec resolution
│ ├── harness/ # Think→Act loop
│ ├── thinker/ # LLM interaction, prompt building
│ ├── memory/ # SQLite+sqlite-vec storage
│ ├── builtin_tools/ # Built-in tool implementations
│ ├── extension/ # Plugin system (WASM, Node.js)
│ ├── mcp/ # MCP client
│ ├── providers/ # AI provider adapters
│ ├── sandbox/ # WorkspaceSandbox, OsSandboxDriver
│ ├── session/ # SessionService, append-only event log
│ ├── workflow/ # Declarative workflow templates, compilation, .workflow.js interop
│ └── ... # 50+ additional modules
├── desktop/
│ ├── shell/ # Tauri v2 native desktop app (thin shell)
│ │ ├── src/ # Window, tray, daemon lifecycle, notifications
│ │ ├── splash/ # Launch splash screen
│ │ └── binaries/ # Bundled aleph-server + bridge binaries
│ ├── shared/ # DesktopCapability trait + IPC protocol
│ ├── macos/ # macOS native bridge (Swift)
│ ├── linux/ # Linux native bridge
│ └── windows/ # Windows native bridge
├── shared/
│ ├── protocol/ # Shared types (aleph-protocol crate)
│ ├── logging/ # Logging infrastructure
│ ├── ui_logic/ # Shared UI logic
│ └── client/ # Shared client utilities
├── interfaces/
│ ├── cli/ # Terminal client
│ ├── tui/ # TUI client
│ └── webchat/ # Web-based chat interface (WASM)
├── docs/ # Architecture docs and design specs
└── plugins/ # Plugin examples and SDKThe workspace root Cargo.toml defines shared dependency versions so all members stay in sync.
Protocol Adapter System
Aleph supports multiple AI providers through a layered protocol adapter architecture:
| Layer | Type | Examples |
|---|---|---|
| Built-in | Compiled Rust | OpenAiProtocol, AnthropicProtocol, GeminiProtocol, OllamaProvider |
| Configurable | YAML hot-reload | Custom protocols in ~/.aleph/protocols/, extend built-in or fully custom |
| Extension | Plugin | WASM/Node.js protocols (future) |
The ProtocolRegistry resolves a protocol name by checking dynamic (YAML) protocols first, then built-in protocols. YAML protocol definitions are hot-reloaded within 600ms of file changes using notify-debouncer-full.
Identity and Security
An immutable IdentityContext flows through the entire execution chain from session creation to tool execution. This enables fine-grained, role-based access control:
- Owner sessions have full access to all tools
- Guest sessions carry a
GuestScopethat restricts which tools are available and when the session expires - Anonymous sessions are denied by default
The PolicyEngine performs stateless permission checks at the Executor level, ensuring that every tool call is authorized before execution.
Identity Context Flow
┌─────────────────────────────────────────────────────────────────┐
│ Identity Context Flow │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. Session Creation │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ SessionManager │ │
│ │ ┌────────────────────────────────────────────────────┐ │ │
│ │ │ Owner Session: │ │ │
│ │ │ metadata = SessionIdentityMeta { │ │ │
│ │ │ role: Owner, │ │ │
│ │ │ identity_id: "owner", │ │ │
│ │ │ scope: None │ │ │
│ │ │ } │ │ │
│ │ │ │ │ │
│ │ │ Guest Session: │ │ │
│ │ │ metadata = SessionIdentityMeta { │ │ │
│ │ │ role: Guest, │ │ │
│ │ │ identity_id: "guest-123", │ │ │
│ │ │ scope: Some(GuestScope { │ │ │
│ │ │ allowed_tools: ["translate"], │ │ │
│ │ │ expires_at: Some(1735689600) │ │ │
│ │ │ }) │ │ │
│ │ │ } │ │ │
│ │ └────────────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ 2. Request Processing │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Orchestrator │ │
│ │ ┌────────────────────────────────────────────────────┐ │ │
│ │ │ let identity = session_manager │ │ │
│ │ │ .get_identity_context(&session_key, "gateway") │ │ │
│ │ │ .await?; │ │ │
│ │ │ │ │ │
│ │ │ // IdentityContext { │ │ │
│ │ │ // request_id: "req-456", │ │ │
│ │ │ // session_key: "session-123", │ │ │
│ │ │ // role: Guest, │ │ │
│ │ │ // identity_id: "guest-123", │ │ │
│ │ │ // scope: Some(GuestScope { ... }), │ │ │
│ │ │ // created_at: 1735689000, │ │ │
│ │ │ // source_channel: "gateway" │ │ │
│ │ │ // } │ │ │
│ │ └────────────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ 3. Harness Execution │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ HarnessRunner::run( │ │
│ │ FlowRequest { │ │
│ │ agent_id, │ │
│ │ input, │ │
│ │ identity, // ← IdentityContext passed here │ │
│ │ abort_signal, │ │
│ │ }, │ │
│ │ HarnessDeps { session, tool_service, sandbox, ... } │ │
│ │ ) │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ 4. Tool Execution │
│ ┌──────────────────────────────────────────────────────────┐ │
│ │ Engine::execute(&action, &identity) │ │
│ │ ┌────────────────────────────────────────────────────┐ │ │
│ │ │ // Normalize tool name │ │ │
│ │ │ let normalized = normalize_tool_name(tool_name); │ │ │
│ │ │ │ │ │
│ │ │ // Check permission │ │ │
│ │ │ let result = PolicyEngine::check_tool_permission( │ │ │
│ │ │ &identity, │ │ │
│ │ │ &normalized │ │ │
│ │ │ ); │ │ │
│ │ │ │ │ │
│ │ │ match result { │ │ │
│ │ │ Allowed => execute_tool(...), │ │ │
│ │ │ Denied { reason } => ToolError { error: reason }│ │ │
│ │ │ } │ │ │
│ │ └────────────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘Security Properties
- Immutability:
IdentityContextcannot be modified after creation - Frozen Permissions: Guest scope is frozen at session creation time
- Stateless Checks:
PolicyEnginehas no mutable state - Certificate of Authority: Identity is constructed once and passed down
- Fail-Safe: Missing or invalid metadata defaults to Owner (backward compatible)
Next Steps
- Gateway Architecture — WebSocket protocol, JSON-RPC methods, and multi-channel routing
- Harness — The Think→Act cycle, Orchestrator, and AgentHarness
- Session Service — Session lifecycle, context compression, and persistence
- Tool Architecture — The
AlephTooltrait, tool server, and MCP integration - Memory System — SQLite+sqlite-vec storage, hybrid retrieval, and cognitive memory
Reference Documentation
For the authoritative system architecture, see the canonical Architecture Reference in the source repository.
26.7.x Addendum
The Third Twin: Session Mode
chat / work / code is the third user-adjustable axis alongside exec_tier and think_level. It statically partitions the tool presentation surface only (progressive-disclosure core set + deferred-tool tier), never permissions. Switchable from the Panel composer pill, from Settings → Policies (global default), or via the session_set_mode tool. Each mode also drives a distinct right-panel behavior (chat = badge, work = plan surface, code = tool detail) and adds one cache-stable prompt line.
Loop-Graph Governance Layer (loop_graph)
loop_graph adds a governance topology on top of the Harness:
- Team nodes — fuse the multi-agent system into the graph
- Audit ring — closed-set audit action log
- Objective ACLs — authorized by graph node identity
- Victory-claim watchers — triggered on team/loop completion
- Built-in
loop-auditoragent — audit/supervision default to independent-context evidence
It gives the four single-loop failure modes (Goodhart, reference blindness, ring conflict, measurement decay) a topological answer.
Self-Signed TLS + TOFU
26.7.17/18+:
- The gateway terminates TLS in-process (self-signed or user-supplied)
- Self-signed cert SAN auto-discovers the host's non-loopback interface IPs
- Drift sidecar + atomic regen marker
- Client-side TOFU (fingerprint + SAN approval + pinned trust store)
- macOS WKWebView + iOS Keychain adapters
Real Cost and Token Accounting
26.7.15+: session.usage now carries a real spend ledger (previously partly fabricated); prompt-cache discipline restored; thinking depth wired end-to-end.
Daemon-Computed Session Cost
session.usage computes cost via core pricing and the duplicate price table in the shell was deleted.
Full RPC Count
26.7.x the gateway exposes ~265 RPC methods — see Gateway Methods Reference. Categories added after 26.7.22+ include artifacts.* (3 RPC), voice.* (6 RPC + 1 delta topic), hub.* (5 RPC), strategy.*, goals.*, loop.*, and others.
Full Module Inventory
The aleph-server process holds ~70 src/<module> directories plus 6 top-level .rs files (canvas_io.rs / sync_primitives.rs / pricing.rs / event_handler.rs / lib.rs / error.rs). See the src/ directory tree.
See Also
- Architecture 1-2-3-4 Model — stable skeleton
- Architectural Redlines R1–R10 — hard constraints
- Gateway Protocol — protocol
Loop / Goal / Strategy
Three independent subsystems: loop (sustained repetition), goal (autonomous objective pursuit), strategy (team or naked-loop plan). Shared TreeBudget single-rail invariant, cross-session kill switch, four composite-key namespaces, plus the 9-action loop / 7-action goal / 3-action strategy tool surfaces.
1-2-3-4 Architecture Model
The engineering skeleton: 1 Core, 2 Faces, 3 Limbs, 4 Nerves