Aleph
Architecture

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:

  1. Single-Core Multi-Terminal — One aleph-server process 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.

  2. 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.

  3. Gateway Interoperability — Every terminal speaks the same authenticated WebSocket protocol (JSON-RPC 2.0 over ws://). A CLI tool, a Telegram bot, and the desktop shell all call identical methods on the same Gateway.

  4. 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

ModulePathPurpose
gatewaysrc/gateway/WebSocket server, JSON-RPC routing, interfaces
orchestratorsrc/orchestrator/Resolve FlowSpec, build HarnessDeps, dispatch
harnesssrc/harness/Think→Act loop, stop-hooks, context budget, compaction
agentssrc/agents/Agent runtime, subagent spawning, team coordination
thinkersrc/thinker/LLM interaction, prompt building, streaming
dispatchersrc/dispatcher/Task orchestration, tool filtering
enginesrc/engine/Tool execution engine
providerssrc/providers/AI provider implementations
toolssrc/tools/AlephTool trait, tool server
builtin_toolssrc/builtin_tools/Built-in tool implementations
memorysrc/memory/Facts DB, hybrid retrieval (SQLite + sqlite-vec + markdown notes + wikilink graph)
extensionsrc/extension/Plugin system (WASM, Node.js)
execsrc/exec/Shell execution, approval system, OS-native sandboxing
sandboxsrc/sandbox/Sandbox trait + WorkspaceSandbox — per-session workspace, capability ledger
mcpsrc/mcp/MCP client implementation
routingsrc/routing/Session key resolution
configsrc/config/Configuration management
runtimessrc/runtimes/Capability ledger — probe, bootstrap, persist external tool status
sessionsrc/session/Append-only session event log + in-process actor
a2asrc/a2a/A2A protocol adapter
acpsrc/acp/ACP protocol implementation
approvalsrc/approval/Approval system
arenasrc/arena/Arena functionality
browsersrc/browser/Browser automation
capabilitysrc/capability/Capability system
clawhubsrc/clawhub/ClawHub integration
componentssrc/components/Shared components
compressorsrc/compressor/Context compression
coresrc/core/Core types and primitives
daemonsrc/daemon/Background daemon
discoverysrc/discovery/Service discovery
eventsrc/event/Event system
generationsrc/generation/Media generation
group_chatsrc/group_chat/Group chat management
intentsrc/intent/Intent recognition
loggingsrc/logging/Logging infrastructure
markdownsrc/markdown/Markdown processing
mediasrc/media/Media processing
metricssrc/metrics/Metrics collection
permissionsrc/permission/Permission system
piisrc/pii/PII detection and handling
promptsrc/prompt/Prompt management
resiliencesrc/resilience/State management (SQLite)
schedulersrc/scheduler/Job scheduling
searchsrc/search/Search providers
secretssrc/secrets/Secret management
securitysrc/security/Security utilities
skillsrc/skill/Skill system
supervisorsrc/supervisor/Execution supervision
taskssrc/tasks/Task management
teamssrc/teams/Team coordination
workflowsrc/workflow/Declarative workflow templates, compilation, and execution
tool_outputsrc/tool_output/Tool output handling
utilssrc/utils/Utilities
visionsrc/vision/Vision processing
wizardsrc/wizard/Wizard flows

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 execution

Exec-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).await

Benefits:

  • 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 helpers

Channels are enabled or disabled at runtime via aleph.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 SDK

The 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:

LayerTypeExamples
Built-inCompiled RustOpenAiProtocol, AnthropicProtocol, GeminiProtocol, OllamaProvider
ConfigurableYAML hot-reloadCustom protocols in ~/.aleph/protocols/, extend built-in or fully custom
ExtensionPluginWASM/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 GuestScope that 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

  1. Immutability: IdentityContext cannot be modified after creation
  2. Frozen Permissions: Guest scope is frozen at session creation time
  3. Stateless Checks: PolicyEngine has no mutable state
  4. Certificate of Authority: Identity is constructed once and passed down
  5. 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 AlephTool trait, 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.

On this page