agent

Nexel AI Agent

2026/09/29
Nexel AI Agent

Nexel Agent System Architecture

Redesign of clash.py — from a single-file monolith into a modular, local, server-side agent platform.

Architecture Reference Document. Any major architectural change must update this document first.


1. Why the Redesign?

clash.py is a powerful prototype (12,020 lines in a single file), but architecturally it has reached its limits:

Problem Consequence
The agent loop runs inside the browser Refreshing the page kills an 18-step execution
The entire UI (~8,900 lines) is embedded inside a Python string Impossible to lint/debug properly; no separation of concerns
No sessions or database Multiple tabs can race; nothing is persisted server-side
run_python has no sandbox Code executes with full user + environment access, including secrets
Tool calls are parsed using brace-scanning Fragile and error-prone; two manually maintained tool lists can drift
No authentication, rate limiting, or audit trail Any local process can execute code without leaving a trace

What We Keep

We preserve the proven patterns from the original implementation:

  • Path confinement through safe_path

  • Anti-hallucination contract: never claim that something was saved unless the tool explicitly confirms it

  • Before/after snapshots for edits

  • Read-back verification after file modifications

  • Follow-up guidance after every tool result


2. Design Principles

  1. Server-side Agent Loop
    The browser is only a viewer. Executions are checkpointed and can be resumed and audited.

  2. Central Contracts
    core/models.py is the single source of truth for shared data types. No module depends on server.

  3. Session Isolation
    Every session has its own private directory, history, and workspace.

  4. Centralized Policy, Constrained Execution
    The policy engine makes security decisions, the sandbox limits execution, and the audit system records everything.

  5. Progressive Architecture
    Advanced capabilities such as Docker and embeddings are implemented as adapters with fallbacks. The system remains functional without them.

  6. Python 3.9+ Compatibility
    Avoid newer syntax such as X | Y type unions and match statements.


3. Package Structure

nexel-agent/

├── clash.py                       # Preserved reference implementation, untouched

├── nexel_agent/
│   ├── __init__.py                # Version + package documentation
│   ├── server.py                  # FastAPI: HTTP + WebSocket + SSE
│   │
│   ├── core/
│   │   ├── __init__.py            # Stable exports
│   │   ├── models.py              # Shared contracts (single source of truth)
│   │   ├── sessions.py            # Session + SessionStore (SQLite)
│   │   ├── context.py             # Token-aware context management
│   │   ├── router.py              # Multi-model routing
│   │   ├── planner.py             # Task decomposition into a DAG
│   │   └── orchestrator.py        # Server-side agent loop
│   │
│   ├── tools/
│   │   ├── __init__.py            # ToolRegistry
│   │   ├── base.py                # ToolContext → ToolSpec → execution
│   │   ├── filesystem.py          # Isolated filesystem tools
│   │   └── code.py                # Sandboxed code execution
│   │
│   ├── memory/
│   │   ├── __init__.py
│   │   ├── store.py               # Vector memory + SQLite
│   │   └── cache.py               # Semantic cache
│   │
│   ├── safety/
│   │   ├── __init__.py
│   │   ├── policy.py              # Centralized policy engine
│   │   ├── sandbox.py             # Restricted code execution
│   │   ├── approvals.py           # Human-in-the-loop gates
│   │   └── audit.py               # Audit log
│   │
│   └── web/
│       └── static/index.html      # Lightweight dashboard
│
├── tests/                         # pytest test suite
│
├── ARCHITECTURE.md                # This document
│
└── README.md                      # User guide (English)

4. Agent Execution Flow

User (WebSocket/SSE)
   │
   │  POST /api/sessions/{sid}/runs
   │  { "goal": "..." }
   ▼
AgentOrchestrator.run()
   │
   │  1. Planner → TaskPlan (DAG)
   │  2. Checkpoint (resumable)
   ▼
Step Loop (until max_steps or completion)
   │
   │  3. ContextManager.build() → token-aware messages
   │
   │  4. ModelRouter → model selection + streamed generation
   │     (native tool calling)
   │
   │  5. PolicyEngine.evaluate(tool_call)
   │     ├─ needs_approval → suspend and wait for human decision
   │     ├─ deny           → ToolResult(denied), no execution
   │     └─ allow          → continue
   │
   │  6. ToolRegistry.execute(tool_call, ToolContext)
   │     inside the sandbox
   │
   │  7. Audit.log + ToolResult
   │     → return the result to the model (role=tool)
   │
   │  8. Memory.remember()
   │     → store important facts
   ▼
Completion
   │
   ├─ RunStatus = completed
   ├─ RUN_FINISHED event
   └─ Execution summary stored in memory

5. Modules

5.1 core/models.py

Defines the shared Pydantic contracts:

  • AgentMessage

  • ToolCall

  • ToolResult

  • ToolSpec

  • StepEvent

  • PolicyDecision

  • ApprovalRequest

  • TaskPlan

  • MemoryRecord

  • AuditRecord

This module contains data contracts only and no execution logic.


5.2 core/sessions.py

Session

Represents an isolated Nexel execution environment containing:

  • id

  • private session directory

  • workspace_root

  • conversation history

  • metadata

SessionStore

SQLite-backed session persistence providing:

  • Atomic operations

  • Session creation and retrieval

  • State persistence

  • Cleanup of expired/old sessions


5.3 core/context.py

Provides token-aware context management.

Responsibilities

  • Approximate token counting, with optional tiktoken

  • Prefer semantic/digest-style compaction over raw character limits

  • Preserve:

    • system messages

    • the most recent conversation window

  • Incrementally summarize the middle portion of long histories

  • Keep context within the configured token budget


5.4 core/router.py

Provides multi-model routing.

Responsibilities

  • Maintain a model registry such as:

{
    "classify": "light-model",
    "plan": "light-model",
    "generate": "large-model"
}
  • Select models based on task role

  • Stream model output

  • Retry failed requests

  • Fall back to alternative models

  • Provide an adapter-based Ollama integration

Ollama Adapter

The default local provider is Ollama over HTTP.

The interface must remain provider-agnostic so other LLM backends can be added later without changing orchestration logic.


5.5 core/planner.py

Converts a user goal into a structured TaskPlan.

Responsibilities

  • Use a lightweight model to decompose the goal

  • Build a DAG of tasks

  • Define task dependencies using depends_on

  • Return a structured plan

Fallback

When no planning model is available, Nexel falls back to a single-step plan.

Example:

User Goal
   │
   ▼
Task A
   │
   ├──── depends_on: []
   │
   ▼
Task B
   │
   ├──── depends_on: [A]
   │
   ▼
Task C
       depends_on: [B]

5.6 core/orchestrator.py

The orchestrator is the core of Nexel Agent.

Responsibilities

  • Run the server-side agent loop

  • Enforce max_steps

  • Enforce token budgets

  • Detect repeated tool/model behavior

  • Detect consecutive failures

  • Create checkpoints after every step

  • Publish StepEvent updates

  • Suspend execution for approval gates

  • Resume previously suspended executions

  • Run verification loops

  • Coordinate memory and audit logging

Execution Lifecycle

RUN_CREATED
    ↓
PLANNING
    ↓
CHECKPOINTED
    ↓
RUNNING
    ↓
TOOL_CALL
    ↓
POLICY_CHECK
    ├── DENIED
    ├── APPROVAL_REQUIRED
    └── ALLOWED
           ↓
       TOOL_EXECUTION
           ↓
       TOOL_RESULT
           ↓
       MODEL_CONTINUES
           ↓
     VERIFICATION / REFLECTION
           ↓
      next step / completion

6. Tools

6.1 ToolRegistry

The registry is the single runtime interface for Nexel tools.

Responsibilities

  • Tool registration

  • Tool lookup

  • Alias resolution

  • Tool schema generation

  • Prompt/tool list generation

  • Tool execution

  • ToolContext injection


6.2 Core Tools

The initial built-in toolset includes:

list_files
read_file
write_file
edit_file
delete_file
run_python
search_files
validate_python

All filesystem tools must enforce workspace confinement.


6.3 ToolContext

Each tool receives a controlled execution context containing relevant session information, workspace configuration, policy context, and execution metadata.

Tools must not independently bypass centralized safety decisions.


6.4 Filesystem Isolation

Every filesystem operation must pass through:

safe_path

which resolves the requested path and verifies that it remains inside the session workspace.

Conceptually:

requested path
      ↓
resolve()
      ↓
workspace_root
      ↓
relative_to()
      ↓
allowed / rejected

Path traversal outside the workspace must always be rejected.


7. Memory

7.1 memory/store.py

Provides long-term memory and retrieval.

Features

  • SQLite-backed persistence

  • Vector-style retrieval

  • Cosine similarity

  • Optional embeddings

  • Fallback retrieval when embeddings are unavailable

  • Important execution facts

  • Run summaries

  • Snapshot metadata

Embedding Strategy

Embeddings are treated as an optional adapter rather than a mandatory dependency.

Without an embedding provider, Nexel continues to operate using a lightweight fallback strategy.


7.2 memory/cache.py

Provides semantic caching for repeated requests.

The initial implementation may use a normalized-query hash:

raw query
   ↓
normalize
   ↓
stable hash
   ↓
cache lookup
   ↓
hit / miss

The cache must be scoped appropriately so that one session cannot incorrectly reuse another session's private state.


8. Safety Architecture

8.1 safety/policy.py

The centralized policy engine evaluates operations before execution.

Example policy categories

filesystem.read
filesystem.write
filesystem.delete
code.execute
network.access
process.spawn
environment.read

Each request receives a verdict:

ALLOW
DENY
NEEDS_APPROVAL

Policy Responsibilities

  • Centralize security rules

  • Block restricted filesystem locations

  • Detect dangerous resources

  • Evaluate tool calls

  • Apply approval requirements

  • Produce auditable decisions

Tools themselves must not make independent allow/deny decisions.


8.2 safety/sandbox.py

All code execution must happen through the sandbox.

Requirements

  • Scratch working directory

  • Isolated environment variables

  • Resource limits

  • Execution timeout

  • Output size limits

  • Controlled process execution

  • Restricted filesystem access

Docker Adapter

Docker support is optional.

Architecture:

Code Execution Request
        │
        ▼
Sandbox Interface
        │
        ├── Local Restricted Runtime
        │
        └── Docker Runtime (optional)

The system must continue to function when Docker is unavailable.


8.3 safety/approvals.py

Human-in-the-loop approval gates.

Certain sensitive actions may be suspended until the user explicitly approves them.

Approval Request

An approval contains:

  • request ID

  • session ID

  • run ID

  • tool/action

  • reason

  • expiration time

  • current state

Possible states:

PENDING
APPROVED
DENIED
EXPIRED

8.4 safety/audit.py

Every significant operation is recorded.

The audit trail includes:

  • Allowed operations

  • Denied operations

  • Approval requests

  • Tool executions

  • Tool failures

  • Model decisions

  • Session events

  • Security decisions

A denied request must be logged just like an allowed request.


9. Server

server.py

The Nexel server is built on FastAPI.

Responsibilities

  • HTTP API

  • WebSocket streaming

  • SSE streaming

  • Session management

  • Run management

  • Approval endpoints

  • Authentication

  • Rate limiting

  • Background job execution

  • Observability

  • Health checks


9.1 REST API

Example routes:

POST   /api/sessions
GET    /api/sessions/{sid}
DELETE /api/sessions/{sid}

POST   /api/sessions/{sid}/runs
GET    /api/sessions/{sid}/runs/{rid}
POST   /api/sessions/{sid}/runs/{rid}/resume
POST   /api/sessions/{sid}/runs/{rid}/cancel

GET    /api/sessions/{sid}/events
GET    /api/approvals
POST   /api/approvals/{aid}/approve
POST   /api/approvals/{aid}/deny

9.2 Streaming

Two streaming mechanisms are supported:

Server-Sent Events

Useful for simple event streaming:

RUN_CREATED
STEP_STARTED
MODEL_OUTPUT
TOOL_CALL
TOOL_RESULT
APPROVAL_REQUIRED
STEP_FINISHED
RUN_FINISHED
RUN_FAILED

WebSocket

Used for interactive real-time dashboards and bidirectional communication.


9.3 Authentication

The server requires API key authentication.

Example:

Authorization: Bearer 

or an equivalent configured authentication scheme.

Keys must never be exposed through model prompts or tool outputs.


9.4 Rate Limiting

Rate limits are applied per API key.

Example dimensions:

requests / minute
runs / minute
concurrent runs
tool executions

The exact limits should remain configurable.


10. Agent Event Model

Nexel exposes execution progress through structured events rather than browser-local state.

Example:

{
  "type": "TOOL_RESULT",
  "run_id": "run_123",
  "step": 4,
  "tool": "read_file",
  "status": "success",
  "timestamp": "2026-09-30T12:00:00Z"
}

This allows clients to reconnect and reconstruct the current run state.


11. Checkpointing and Resume

Every meaningful step creates a persistent checkpoint.

A checkpoint may include:

run state
current step
task plan
conversation state
tool results
pending approval
token usage
errors
metadata

After a process restart, Nexel can resume from the last valid checkpoint rather than losing the entire run.


12. Verification Loop

After modifying files or generating code, Nexel should verify the result.

Typical flow:

EDIT
 ↓
SAVE
 ↓
READ BACK
 ↓
VALIDATE
 ↓
TEST / LINT
 ↓
PASS → continue
FAIL → repair

This preserves the original project's read-back verification pattern while making it server-side and auditable.


13. Self-Reflection

Nexel can optionally run a reflection step after meaningful operations.

The reflection process evaluates:

Did the operation satisfy the goal?
Did the tool produce the expected result?
Is verification required?
Should another tool be called?
Should the plan be revised?

Reflection must remain bounded by:

  • max_steps

  • token budget

  • retry limits

  • repeat detection

This prevents infinite agent loops.


14. Repeat Detection

The orchestrator detects repeated behavior such as:

same tool
same arguments
same failure
same response pattern

When the agent repeatedly performs an ineffective operation, the run can:

stop
retry with a fallback strategy
request approval
return a controlled failure

15. Token Budget Management

Each run has a configurable token budget.

The budget is shared across:

planning
context construction
model generation
reflection
tool-result processing

When the budget becomes constrained, ContextManager compacts the conversation before the orchestrator terminates the run.


16. Observability

Nexel exposes structured logs and metrics for:

  • Run duration

  • Tool execution duration

  • Model latency

  • Token usage

  • Errors

  • Retries

  • Policy decisions

  • Approval latency

  • Active sessions

  • Concurrent runs

  • Cache hit rate

The goal is to make agent behavior measurable rather than opaque.


17. Git-like Snapshots and Rollback

Before destructive or important edits, Nexel creates a snapshot.

Conceptually:

Workspace
   │
   ├── Snapshot A
   │
   ├── Edit
   │
   ├── Verification
   │
   └── Snapshot B

This enables:

  • Before/after comparison

  • Safe rollback

  • Change history

  • Recovery from failed agent edits

The snapshot mechanism may use a lightweight internal representation without requiring Git itself.


18. Import / Export Bundles

Nexel can export a session or project into a portable bundle containing:

session metadata
workspace files
conversation history
task plan
run history
snapshots
memory entries
configuration

Bundles can later be imported into another Nexel instance or restored locally.

Sensitive secrets must never be exported unless explicitly authorized.


19. Plugin SDK

The tool layer is designed as a plugin interface.

A plugin should be able to define:

name
description
input schema
output schema
permissions
execution handler
aliases

Example conceptual interface:

class NexelTool:
    name = "example"
    description = "Example Nexel tool"

    def schema(self):
        ...

    def execute(self, context, arguments):
        ...

Plugins must still operate through:

ToolRegistry
   ↓
PolicyEngine
   ↓
Sandbox
   ↓
Audit

They cannot bypass the security architecture.


20. MCP Support

MCP (Model Context Protocol) is implemented as an optional adapter.

Architecture:

Nexel ToolRegistry
       │
       ├── Native Nexel Tools
       │
       └── MCP Adapter
              │
              └── External MCP Servers

MCP tools must be translated into Nexel's internal tool contract and remain subject to the same policy and audit pipeline.


21. 30 Modern Capabilities — Implementation Map

# Capability Responsible Module Status
1 Server-side orchestration loop core/orchestrator.py ✅
2 Native structured tool calling core/orchestrator.py ✅
3 Multi-model routing core/router.py ✅
4 Task decomposition into DAG core/planner.py ✅
5 Self-reflection loop core/orchestrator.py ✅
6 Intelligent context compaction core/context.py ✅
7 Long-term memory + RAG memory/store.py ✅
8 Parallel tool execution core/orchestrator.py ✅
9 Semantic code search tools/ ✅
10 Verification loop (test/lint) core/orchestrator.py ✅
11 Isolated sessions + SQLite core/sessions.py ✅
12 Checkpoint and resume core/orchestrator.py ✅
13 API key + authentication server.py ✅
14 Per-key rate limiting server.py ✅
15 Async task queue server.py ✅
16 Semantic cache memory/cache.py ✅
17 Real-time WebSocket server.py ✅
18 Watch mode core/ (optional) 🔶
19 Scheduled tasks core/ (optional) 🔶
20 Plugin SDK tools/ ✅
21 Sandboxed code execution safety/sandbox.py ✅
22 Centralized policy engine safety/policy.py ✅
23 Human-in-the-loop safety/approvals.py ✅
24 Complete audit log safety/audit.py ✅
25 Git-like snapshot + rollback memory/store.py ✅
26 Retry + model fallback core/router.py ✅
27 Token budget manager core/orchestrator.py ✅
28 Observability (logs/metrics) server.py ✅
29 Import/export bundle tools/ ✅
30 MCP support tools/ (adapter) 🔶

✅ = Active in the base implementation
🔶 = Skeleton/adapter with progressive activation


22. Security Model

Trust Boundary

All filesystem paths must go through:

safe_path

using path resolution and containment validation such as:

resolve()
+
relative_to()

A path outside the session workspace must never be accessible.


Code Execution

Code must never be executed directly.

All execution must pass through:

PolicyEngine
      ↓
Sandbox
      ↓
Controlled Runtime

The sandbox provides:

  • scratch directory

  • restricted environment variables

  • execution timeout

  • output limits

  • resource limits

  • optional Docker isolation


Centralized Decisions

The PolicyEngine is the authoritative component for determining whether an operation is:

ALLOW
DENY
NEEDS_APPROVAL

Individual tools must not override or bypass policy.


Auditability

Every security-sensitive action must be auditable.

This includes:

allowed requests
denied requests
approval requests
tool executions
sandbox failures
model actions
filesystem changes

Human Approval

Potentially destructive or sensitive operations are suspended until explicit user approval is received.

No implicit approval should be assumed.


23. Failure Handling

Nexel should fail gracefully at every layer.

Model Failure

Primary Model
     ↓ failure
Fallback Model
     ↓ failure
Controlled Run Failure

Tool Failure

Tool Error
   ↓
ToolResult(error)
   ↓
Model receives structured failure
   ↓
Retry / alternative strategy / finish

Server Restart

Process Restart
      ↓
Load Session
      ↓
Load Checkpoint
      ↓
Resume Run

24. Compatibility Policy

Nexel targets:

Python 3.9+

The codebase must avoid syntax that is unavailable in Python 3.9.

Examples:

# Avoid
str | None

# Prefer
Optional[str]

and:

No match/case syntax
No Python-version-specific APIs without fallback

Dependencies should also remain compatible with the supported Python range.


25. Runtime Requirements

Install the base dependencies:

pip install -r requirements.txt

Core dependencies:

fastapi
uvicorn
pydantic
httpx

Optional dependencies may include:

tiktoken
numpy
embedding providers
docker SDK
pytest

These should remain optional whenever possible.


26. Running Nexel

Start the local server:

uvicorn nexel_agent.server:app --host 127.0.0.1 --port 5000

The default local address is:

http://127.0.0.1:5000

27. Ollama Integration

Ollama is optional.

Default configuration:

OLLAMA_URL=http://127.0.0.1:11434

The router should detect whether Ollama is available.

With Ollama

Nexel
  ↓
ModelRouter
  ↓
Ollama
  ↓
Local Model

Without Ollama

The server still starts successfully.

The infrastructure remains testable:

sessions
checkpoints
policies
sandbox
tool registry
audit
events
approvals
memory

but no actual LLM generation is available unless another model provider is configured.


28. Local-First Architecture

Nexel is designed as a local-first agent platform.

Primary goals:

  • Local execution

  • Local workspace isolation

  • Local session storage

  • Optional local models

  • No mandatory cloud dependency

  • Replaceable model providers

  • Replaceable sandbox providers

This architecture allows Nexel to operate as a self-contained developer/agent environment.


29. Architectural Invariants

The following rules are considered non-negotiable:

Invariant 1 — Browser Is Not the Agent

The browser must never own the authoritative execution loop.

Invariant 2 — No Unconfined File Access

Every filesystem path must pass through safe_path.

Invariant 3 — No Direct Code Execution

Every code execution request must pass through policy and sandbox layers.

Invariant 4 — No False Success Claims

Nexel must never report an operation as successful unless the corresponding tool explicitly confirms success.

Invariant 5 — All Actions Are Auditable

Security-sensitive operations must produce audit records, including denied actions.

Invariant 6 — Sessions Are Isolated

A session must not implicitly access another session's private workspace or memory.

Invariant 7 — Core Contracts Are Centralized

Shared data models belong in:

core/models.py

Invariant 8 — Advanced Features Must Have Fallbacks

Optional infrastructure such as embeddings, Docker, and alternate model providers must not make the base system unusable.


30. Migration Strategy

The redesign should be incremental rather than a complete rewrite in one step.

Phase 1 — Extract Contracts

Create:

core/models.py

and define the shared data types.

Phase 2 — Extract Sessions

Introduce:

core/sessions.py

and move persistent state into SQLite.

Phase 3 — Extract Tools

Move filesystem and code execution into:

tools/

with a centralized registry.

Phase 4 — Introduce Safety

Add:

safety/policy.py
safety/sandbox.py
safety/approvals.py
safety/audit.py

Phase 5 — Move Agent Loop Server-Side

Implement:

core/orchestrator.py

and make browser clients observe the execution through WebSocket/SSE.

Phase 6 — Add Planning and Routing

Introduce:

core/planner.py
core/router.py

Phase 7 — Add Memory and Context Management

Introduce:

core/context.py
memory/store.py
memory/cache.py

Phase 8 — Replace the Monolithic UI

Move the embedded HTML out of clash.py and into:

web/static/index.html

while preserving the existing UX patterns where useful.

Phase 9 — Compatibility Layer

Keep:

clash.py

as the untouched reference implementation during migration.

The old implementation should remain runnable until the replacement reaches feature parity.


31. Definition of Done

The Nexel redesign is considered operational when:

✓ Agent execution is fully server-side
✓ Browser refresh does not terminate a run
✓ Sessions persist in SQLite
✓ Runs can be checkpointed and resumed
✓ Tool calls are structured and centrally registered
✓ All filesystem access is workspace-confined
✓ Python execution is sandboxed
✓ Policy decisions are centralized
✓ Sensitive operations can require approval
✓ All important operations are audited
✓ Model routing supports fallback
✓ Context is token-aware
✓ Memory persists across runs
✓ Verification occurs after critical edits
✓ WebSocket/SSE clients can reconnect
✓ API keys and rate limits are enforced
✓ Optional infrastructure has fallbacks
✓ Python 3.9+ compatibility is maintained
✓ `clash.py` remains preserved as the original reference

32. Final Architecture

The target Nexel architecture is:

                       ┌──────────────────────┐
                       │       Browser        │
                       │  Dashboard / Client   │
                       └──────────┬───────────┘
                                  │
                         HTTP / SSE / WebSocket
                                  │
                                  ▼
                       ┌──────────────────────┐
                       │      Nexel Server    │
                       │      FastAPI         │
                       └──────────┬───────────┘
                                  │
                    ┌─────────────┴─────────────┐
                    │                           │
                    ▼                           ▼
          ┌──────────────────┐       ┌──────────────────┐
          │ AgentOrchestrator│       │   SessionStore   │
          └────────┬─────────┘       │     SQLite       │
                   │                 └──────────────────┘
        ┌──────────┼───────────┐
        │          │           │
        ▼          ▼           ▼
   ┌────────┐ ┌─────────┐ ┌──────────┐
   │Planner │ │ Context │ │  Router  │
   └────────┘ └─────────┘ └────┬─────┘
                                │
                                ▼
                         ┌─────────────┐
                         │  LLM Model  │
                         │ Ollama/etc. │
                         └──────┬──────┘
                                │
                                ▼
                         Structured Tool Call
                                │
                                ▼
                     ┌─────────────────────┐
                     │    Policy Engine    │
                     └─────────┬───────────┘
                               │
                ┌──────────────┼──────────────┐
                │              │              │
                ▼              ▼              ▼
             DENY       NEEDS_APPROVAL      ALLOW
                              │              │
                              ▼              ▼
                         ┌─────────┐   ┌─────────────┐
                         │ Approval│   │ ToolRegistry│
                         └─────────┘   └──────┬──────┘
                                             │
                                             ▼
                                      ┌─────────────┐
                                      │   Sandbox   │
                                      └──────┬──────┘
                                             │
                                             ▼
                                      ┌─────────────┐
                                      │ Tool / Code │
                                      └──────┬──────┘
                                             │
                              ┌──────────────┴──────────────┐
                              │                             │
                              ▼                             ▼
                         Audit Log                    Tool Result
                              │                             │
                              └──────────────┬──────────────┘
                                             ▼
                                      AgentOrchestrator
                                             │
                                  ┌──────────┴──────────┐
                                  ▼                     ▼
                              Memory                Checkpoint

33. Project Identity

Product

Nexel

Agent

Nexel Agent

Architecture

Local-first, server-side, modular agent platform

Primary Runtime

Python 3.9+

API Framework

FastAPI

Persistence

SQLite

Local Model Provider

Ollama (optional)

Communication

HTTP + WebSocket + SSE

Security Model

Policy Engine + Sandbox + Human Approval + Audit


Nexel Agent is the target architecture. clash.py remains the original reference implementation during the migration and should not be modified as part of the architectural extraction unless explicitly required.