Architecture Overview · MIT License
Isolated Rust authority for multi-organization AI agents
Most multi-user AI agent tools run orchestration, database writes, prompt assembly, and workspace access inside one web process—leaving one prompt injection or concurrent request to race a Git merge, leak keys, or bypass spend limits.
Allen separates durable state and execution from web transport. A Rust authority daemon (allen-agent-server + allen-firm) owns SQLite persistence, tenant isolation, integer spend limits, and FD-pinned file tools across OpenAI, Anthropic, Google, and OpenRouter-compatible models. A loopback-only Next.js gateway handles browser sessions and untrusted ingestion without holding database write locks or sending provider keys to client code.
9 crates · 5 layers
Reusable MIT-licensed Rust crates (allen-core through allen-runtime), plus 4 product shells (13 workspace crates, Rust 1.94+).
SQLite + Postgres
Single-host SQLite powers the Allen workbench; external cloud services can run the standalone runtime crates on PostgresAgentStore.
127.0.0.1 · 0600 socket
Loopback-only web gateway talking to Rust over an owner-only Unix socket and a 256-bit Bearer-authenticated loopback port.
Zero unsafe in workspace
All 13 crates forbid unsafe code and deny warnings; OS syscalls and SQLite stay inside audited dependencies (rustix, sqlx).
01 · System Topology
Four boundaries separate clients, web transport, Rust authority, and local disk
Allen runs on one host machine (a developer workstation or a shared team host) against local Git repositories or plain folders. Teammates connect through a browser or the pure-Rust allen terminal client—locally on 127.0.0.1, or remotely behind an outbound Cloudflare Tunnel.
crates/server/client/generated/) enforces SHA-256 schema parity between Boundary 02 and Boundary 03.Solid arrows: primary request path · Dashed: optional tunnel / standalone TUIBrowser users authenticate with an HttpOnly session cookie (allen_firm_session) or WebAuthn passkeys. The pure-Rust allen terminal client authenticates via POST /v1/auth/cli/login and stores an opaque Bearer token in the OS Keychain or a 0600 file.
For solo work, all traffic stays on 127.0.0.1. For small teams sharing a host, an optional outbound Cloudflare Tunnel (--public-origin) forwards HTTPS traffic to the loopback gateway. In standalone mode (allen local), the TUI skips the gateway and runs the same Rust session engine in-process.
Browser code never receives provider API keys, bot tokens, or raw filesystem handles.
Binds exclusively to 127.0.0.1, validates exact Host and Origin headers against loopback or --public-origin, enforces no-referrer / DENY / nosniff / no-store headers, and strips any caller-supplied x-allen-firm-* headers before verifying cookies or Bearer tokens.
Parsing untrusted URLs, PDFs, spreadsheets, and Telegram/Slack webhooks runs in this Node/TypeScript layer so slow or failing external parsers stay off the serialized SQLite actor loop. Spend math and tenant SQL queries are never re-implemented here.
Trust boundary note: the gateway shares the host trust domain with the Rust daemon and forwards verified (user_id, org_id) RPCs over server.sock, so strict gateway header checks, SSRF blocking, and bounded parsing are part of the host threat model.
allen-agent-server accepts requests only over a private 0600 Unix domain socket (server.sock) or a loopback HTTP/1.1 + SSE port protected by a constant-time-verified 256-bit Bearer token on every route except /healthz.
FirmStore runs as a single serialized Tokio actor over firm.sqlite inside BEGIN IMMEDIATE transactions, preventing concurrent HTTP requests from racing single-use invite acceptance, last-admin safety, worker spend caps, or Git merge leases. Wire contracts generate from crates/server/src/protocol.rs with a SHA-256 schema digest checked by npm run check:protocol.
Typed FirmError variants map exhaustively to HTTP statuses at the gateway—no string parsing across process boundaries.
Durable state splits cleanly between firm.sqlite (organizations, projects, chats, reviews, instructions, FTS5 search, append-only migrations 0001–0014 checked by SHA-256 on startup) and sessions.sqlite (event-sourced agent turns and idempotency receipts).
Provider keys live in Doppler (doppler run -- ...) or per-organization 0600 files (firm-credentials.json), never in SQLite or client state. Local Git repositories and plain folders attach only inside configured allowed_repo_roots; reviewed changes merge to local branches without breaking existing GitHub PR or CI workflows.
Live VACUUM INTO database backups stage inside a 0700 directory with 0600 output permissions and SHA-256 verification.
02 · Modular Rust Crate Stack
Five isolated Rust layers separate domain rules from storage, providers, and UI
Nine MIT-licensed crates (crates/allen-*/) implement the Open Agent Infrastructure Standard underneath the Allen workbench. Select any layer—or move with the arrow keys—to inspect its permitted dependencies, Cargo feature gates, and hard exclusions verified in CI by npm run check:boundaries.
Layer 3 · Depends on Layer 0
File Containment & Feature-Gated Tools
Isolates workspace file tools and Git operations behind OS file-descriptor containment and compile-time Cargo feature gates.
Crates & Cargo Features
allen-sandbox — readonly (default), write, process, git, schemars
Enforced Boundary Exclusions
Under --no-default-features --features readonly: zero sqlx, zero allen-model, zero allen-store, and zero write, process, or Git code compiled into the binary.
- FD-pinned RootGuard: Pins an open root directory descriptor via rustix, verifies device/inode identity, traverses segments with O_NOFOLLOW to block symlink escapes, rejects .git/** writes, caps read bytes (default 16 MiB), and swaps writes atomically via same-directory temp files.
- Hardened GitAuthority: Prepends SAFE_GIT_FLAGS (disabling fsmonitor, hooksPath, ext:: protocol, and external diffs) to every Git subprocess and aborts cleanly on merge conflict.
- Swappable WorkspaceBackend: Tools (read, grep, find, ls, write, edit, bash) re-verify their PolicyGate permit before acting and run against LocalRootGuardBackend, InMemoryWorkspaceBackend, or a caller-supplied container/remote backend.
Deployment profile A · Local workbench (SQLite)
The Allen workbench pairs allen-firm (firm.sqlite) and SqliteAgentStore (sessions.sqlite) on one host for a solo engineer or a small firm sharing repositories behind Cloudflare Tunnel. Projects attach zero repositories, non-Git local folders, a monorepo, or multiple repositories without hardcoded directory layouts.
Deployment profile B · Embeddable crates (PostgreSQL & containers)
External Rust services can embed allen-core through allen-runtime directly without the Next.js workbench: pair PostgresAgentStore for multi-replica scheduling, allen-model::LoopbackGateway to keep API keys outside containers, and allen-sandbox --no-default-features --features readonly to omit write and process tools at compile time.
03 · Agent Loop & Durability
Event-sourced commits keep turns, approvals, compaction, and peer messaging consistent
The browser workbench, remote allen TUI, and standalone allen local execute through the same Rust SessionActor and SessionRuntime turn loop. Ephemeral tokens stream out-of-band while durable state commits atomically at turn boundaries.
- Step 01
Command Admit
Check idempotent CommandId receipt, verify active OwnerFence and SessionRevision, and reject stale or closed-session mutations.
- Step 02
Cache-Stable Prompt
Build PromptPrefix::stable strictly from registered active tools (zero ghost tools); append dynamic SQLite instructions, AGENTS.md, and SKILL.md without busting cache.
- Step 03
Out-of-Band Stream
Forward token and tool deltas over EventSink without stalling on SQLite; retry mid-stream TCP drops cleanly before writing durable entries.
- Step 04
Policy & Approval Gate
Re-verify PolicyGate permits on every tool call; pause Running -> Waiting -> Running for guarded bash commands, sensitive file writes, or ask dialogs.
- Step 05
Atomic StepCommit
Commit entries, active leaf, validated effect transitions, MicroUsd spend, and command receipt in one transaction; run pair-safe compaction when near context limits.
Crash recovery, approval hooks & pair-safe compaction
Every external side effect moves through an explicit state machine (Prepared -> Claimed -> Observed | FailedBeforeDispatch | Unknown). If the server crashes mid-tool, startup recovery marks orphaned Claimed effects as Unknown instead of blindly replaying them. Mid-stream TCP drops retry before writing an AssistantTurn or SpendLedgerEntry, preventing duplicate turns or spend drift.
With guards.enabled active, destructive bash commands (rm -rf, git push --force, sudo, curl|sh) and writes to sensitive files (.env*, credential files, .ssh/*) pause in Waiting until a human decides. When context approaches the model window, non-destructive compaction writes a summary checkpoint without deleting history and adjusts the cut point so a tool call is never separated from its tool result.
Org-scoped peer messaging with hard loop breakers
Native tools list_agents and message_agent (crates/server/src/session_tools.rs, migration 0014) let agents coordinate across an organization while keeping private projects sealed. Agents in organization chats and shared projects can discover and message each other across shared projects; agents in a private project can see and message only peers inside that same private project.
list_agents is read-only and $0—it never wakes idle actors. message_agent persists messages durably in SQLite, lazily loads cold actors, carries explicit sender attribution without stealing an active human typing lock (DriverLock), and enforces hard loop caps (thread depth, per-turn fan-out, and unassisted sends reset on human input).
04 · Multi-Org Controls & Security Invariants
Roles, spend caps, workspaces, and merges fail closed inside Rust and SQLite
Allen separates human organization membership from agent execution ceilings, computes monetary budgets in integer microdollars inside Rust, and serializes repository merges with durable SQLite leases.
Membership vs. execution roles
MembershipRole (Admin, Member) governs human tenant privileges in SQLite: inviting teammates, attaching workspaces, enforcing last-admin safety, and overriding spend caps.
ExecutionRole in allen-core enforces three-way agent delegation ceilings: Authorities (Sponsor, Manager) delegate; Builders (Worker, Support) mutate scoped workspaces; Independent gates (Reviewer, Verifier, Auditor) verify digest-pinned snapshots read-only with self-review blocked. PolicyCeiling::narrow only adds restrictions.
Checked integer MicroUsd spend
allen-core::spend is the single source of truth for spend accounting ($1.00 = 1,000,000 MicroUsd, checked integer math, never duplicated in TypeScript). Unknown models fall back to conservative rates ($15 input / $75 output per 1M tokens) and sub-floor telemetry is overridden so misreported costs cannot bypass limits.
Before launching a worker, FirmStore checks organization, project-window, and campaign caps inside BEGIN IMMEDIATE. Cap breaches or burn-rate spikes return HTTP 402 and queue an Inbox review that only an Admin can override.
Orthogonal workspaces & merge leases
Each attached workspace configures independent flags—source_kind (git_repo or local_folder), write_policy (review_required, auto_commit_paths, or read_only), is_public (which permanently disables auto-commit), and capability flags (worktrees, skills, checks, filing target, cached project brief)—plus optional .allen/repo.json manifests.
Human approval in Inbox acquires a durable SQLite merge lease, blocks concurrent status changes while leased, enforces TwoPartyRule (blocking self-approval in multi-member organizations while allowing solo founders to merge), verifies pinned head_sha, and merges with SAFE_GIT_FLAGS.
Security & isolation invariant ledger
| Invariant | Enforcement layer | Automated verification |
|---|---|---|
| Multi-org & private-project visibility isolation | crates/firm/ joins organization_memberships and verifies (visibility = shared OR owner_user_id = acting_user) on every query, including single-record lookups and member removal cascades. | crates/server/tests/firm_store.rs |
| Loopback-only HTTP & anti-spoofing headers | web/src/desktop/http.ts binds 127.0.0.1 only, checks exact Host/Origin against loopback or --public-origin, strips caller x-allen-firm-* headers, and sets no-referrer / DENY / nosniff / no-store. | web/test/desktop-http.test.ts |
| Zero raw secrets in SQLite, browser, or check env | Provider and bridge secrets stay in Doppler or 0600 files; auth and invite tokens persist only as 64-char SHA-256 hex digests; workspace checks run under sanitizedBuildEnv(). | .github/workflows/security.yml |
| FD-pinned file tools & hardened Git subprocesses | allen-sandbox::fs_guard::RootGuard pins root directory descriptors with O_NOFOLLOW traversal, blocks .git/** writes, writes atomically, and prepends SAFE_GIT_FLAGS on every Git call. | crates/allen-sandbox/ |
| Zero-secret container egress & data-residency check | allen-model::LoopbackGateway isolates upstream keys behind a 256-bit constant-time token, sends regional data-residency hints, verifies the answering provider up to 1 MiB of SSE, and revokes job keys. | crates/allen-runtime/tests/adversarial.rs |
| Atomic MicroUsd spend caps & burn-rate circuit breaker | allen-core::spend integer arithmetic wired inside BEGIN IMMEDIATE worker admission (crates/firm/src/rooms.rs); returns HTTP 402 before spawning on cap breach with admin-only Inbox override. | web/test/spend-guardrails-api.test.ts |
| Two-party merge approval & durable SQLite merge leases | TwoPartyRule blocks self-approval in organizations with >= 2 members; AcquireMergeLease / CommitMergeLease / ReleaseMergeLease serialize merges against pinned head_sha and block status races. | crates/server/tests/firm_store.rs |
| Append-only SHA-256 migrations & Rust-to-TS wire parity | FirmStore::migrate verifies SHA-256 checksums across migrations 0001–0014 and refuses drifted databases; ProtocolSchema digest blocks Rust/TypeScript client drift. | crates/server/scripts/generate-client.mjs |
| Identical InMemory, SQLite & Postgres store conformance | Shared conformance::run_all and run_concurrency suites verify fencing, RevisionConflict rollback, tenant mismatch rejection, crash recovery, and multi-replica Postgres locking. | crates/allen-store/src/conformance.rs |
| XSS-safe Markdown & safe link rendering | Browser Markdown renders directly from the marked.Lexer AST without dangerouslySetInnerHTML and filters unsafe link schemes via safeMarkdownLink. | web/test/ui.test.tsx |
05 · Verification & Quickstart
Run the local workbench, expose a team host, or embed the Rust crates
Every security, isolation, spend, and wire-contract invariant in Allen is backed by automated Rust, Bun, and Headless Chromium verification suites. Pick a starting path below and copy the commands directly.
Build the Rust authority binary and Next.js workbench once, verify environment readiness with doctor, and start on 127.0.0.1:7419. Prefix the last command with doppler run -- when loading provider keys from Doppler.
cargo build --release --manifest-path crates/server/Cargo.toml --bin allen-agent-server
npm --prefix web run build
npm run doctor
node --experimental-transform-types web/scripts/allen.mjs serve \
--root "$HOME/.allen-firm" \
--workspace "$HOME/FirmWorkspace" \
--port 7419Open http://127.0.0.1:7419. First-run setup creates one organization and one admin account locally with no tunnel or external accounts required.