Skip to main content

Theus Agentic Framework - Industrial Grade Process-Oriented Programming (POP)

Project description

Theus: Process-Oriented Operating System for Python

PyPI version License: MIT Paper License: CC-BY 4.0 Python 3.12+

"Data is the Asset. Code is the Liability. Theus protects the Asset."

Theus is a next-generation architectural framework that treats your application not as a collection of objects, but as a deterministic workflow of processes. It introduces the Process-Oriented Programming (POP) paradigm to solve the chaos of state management in complex systems like AI Agents, Core Banking, and Industrial Automation.


🌪️ The Problem

In modern software (OOP, EDA, Microservices), the biggest source of bugs is State Management:

  • Implicit Mutations: Who changed user.balance? Was it the PaymentService or the RefundHandler?
  • Race Conditions: Transient events corrupting persistent data.
  • Zombie State: Old references pointing to stale data.
  • Audit Gaps: We log what happened, but we can't mathematically prove why it was allowed.

🛡️ The Theus Solution

Theus acts as a micro-kernel for your logic, enforcing strict architectural invariants at runtime:

1. The 3-Axis Context Model

State is no longer a "bag of variables". It is a 3D space defined by:

  • Layer: Global (Config), Domain (Session), Local (Process).
  • Semantic: Input (Read-only), Output (Write-only).
  • Zone:
    • DATA: Persistent Assets (Replayable).
    • SIGNAL: Transient Events (Reset on Read).
    • META: Observability (Logs/Traces).
                                     [Y] SEMANTIC
                             (Input, Output, SideEffect, Error)
                                      ^
                                      |
                                      |
                                      |                +------+------+
                                      |               /|             /|
                                      +--------------+ |  CONTEXT   + |----------> [Z] ZONE
                                     /               | |  OBJECT    | |      (Data, Signal, Meta)
                                    /                | +------------+ |
                                   /                 |/             |/
                                  /                  +------+------+
                                 v
                            [X] LAYER
                     (Global, Domain, Local)

2. Zero-Trust Memory

  • Default Deny: Processes cannot access ANY data unless explicitly declared in a @process Contract.
  • Immutability: Inputs are physically frozen (FrozenList, FrozenDict).
  • Isolation: Signals cannot be used as Inputs for Business Logic (Architectural Boundary enforcement).

3. Industrial-Grade Audit

  • Active Defense: Rules (min, max, regex) are enforced at Input/Output Gates.
  • Severity Levels:
    • S (Safety): Emergency Stop.
    • A (Abort): Hard Stop Workflow.
    • B (Block): Rollback Transaction.
    • C (Campaign): Warning.
  • Resilience: Configurable tolerance thresholds (e.g., "Allow 2 glitches, block on 3rd").

📦 Installation

Theus requires Python 3.12+ to leverage advanced typing and dataclasses.

pip install theus

⚡ Quick Start: Building a Bank

This example demonstrates Contracts, Zoning, and Transaction safety.

1. Define the Context (The Asset)

from dataclasses import dataclass, field
from theus.context import BaseSystemContext

@dataclass
class BankDomain:
    # DATA ZONE: Persistent Assets
    accounts: dict = field(default_factory=dict) # {user_id: balance}
    total_reserves: int = 1_000_000
    
    # SIGNAL ZONE: Control Flow
    sig_fraud_detected: bool = False

@dataclass
class BankSystem(BaseSystemContext):
    domain: BankDomain = field(default_factory=BankDomain)

2. Define the Process (The Logic)

from theus.contracts import process

@process(
    # STRICT CONTRACT
    inputs=['domain.accounts'],
    outputs=['domain.accounts', 'domain.total_reserves', 'domain.sig_fraud_detected'],
    errors=['ValueError']
)
def transfer(ctx, from_user: str, to_user: str, amount: int):
    # 1. Input Validation
    if amount <= 0:
        raise ValueError("Amount must be positive")
    
    # 2. Business Logic (Operating on Shadow Copies)
    # ctx.domain.accounts is a TrackedDict
    sender_bal = ctx.domain.accounts.get(from_user, 0)
    
    if sender_bal < amount:
        # Trigger Signal
        ctx.domain.sig_fraud_detected = True
        return "Failed: Insufficient Funds"

    # 3. Mutation (Optimistic Write)
    ctx.domain.accounts[from_user] -= amount
    ctx.domain.accounts[to_user] = ctx.domain.accounts.get(to_user, 0) + amount
    
    # 4. Invariant Update
    # (Note: reserves don't change in transfer, but we have write access just in case)
    
    return "Success"

3. Run with Safety (The Engine)

from theus.engine import TheusEngine

# Setup Data
sys_ctx = BankSystem()
sys_ctx.domain.accounts = {"Alice": 1000, "Bob": 0}

# Initialize Engine
engine = TheusEngine(sys_ctx, strict_mode=True)

# 🚀 PRO TIP: Auto-Discovery
# Instead of registering manually: engine.register_process("transfer", transfer)
# You can scan an entire directory (Theus will find all @process functions):
# engine.scan_and_register("src/processes")

engine.register_process("transfer", transfer)

# Execute
result = engine.run_process("transfer", from_user="Alice", to_user="Bob", amount=500)

print(f"Result: {result}")
print(f"Alice: {sys_ctx.domain.accounts['Alice']}") # 500

🛠️ CLI Tools

Theus provides a powerful CLI suite to accelerate development and maintain architectural integrity.

  • theus init <project_name>: Scaffolds a new project with the standard V2 structure (src/, specs/, workflows/).
  • theus audit gen-spec: Scans your @process functions and automatically populates specs/audit_recipe.yaml with rule skeletons.
  • theus audit inspect <process_name>: Inspects the effective audit rules, side effects, and error contracts for a specific process.
  • theus schema gen: Infers and generates specs/context_schema.yaml from your Python Dataclass definitions.

🧠 Advanced Architecture

The Transaction Engine

Theus uses a Hybrid Transaction Model:

  • Scalars: Updated in-place with an Undo Log (for speed).
  • Collections: Updated via Shadow Copy (for safety). If a process crashes or is blocked by Audit, Theus rolls back the entire state instantly.

The Audit Recipe (audit.yaml)

Decouple your business rules from your code.

process_recipes:
  transfer:
    inputs:
      - field: "amount"
        max: 10000        # Max transfer limit
        level: "B"        # Block transaction
    outputs:
      - field: "domain.total_reserves"
        min: 0            # Reserves must never be negative
        level: "S"        # Safety Interlock (Stop System)

The Orchestrator (FSM)

Manage complex flows using workflow.yaml:

states:
  IDLE:
    events:
      CMD_TX: "PROCESSING"
  PROCESSING:
    entry: "transfer"
    events:
      EVT_SUCCESS: "NOTIFY"
      EVT_FAIL: "IDLE"

📚 Documentation


⚖️ License

Maintained by: Hoàng Đỗ Huy

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

theus-2.1.1.tar.gz (207.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

theus-2.1.1-py3-none-any.whl (37.7 kB view details)

Uploaded Python 3

File details

Details for the file theus-2.1.1.tar.gz.

File metadata

  • Download URL: theus-2.1.1.tar.gz
  • Upload date:
  • Size: 207.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for theus-2.1.1.tar.gz
Algorithm Hash digest
SHA256 4bf82379ea74ab60eee614de4386f5f2d6083611bf1a5c6169eba050f3ebdcaf
MD5 8227806ca9295444e55d19a69169450b
BLAKE2b-256 b748780ad072b05044e4176f137c374baa9309fba7141322cc1e1c3bf376c36e

See more details on using hashes here.

File details

Details for the file theus-2.1.1-py3-none-any.whl.

File metadata

  • Download URL: theus-2.1.1-py3-none-any.whl
  • Upload date:
  • Size: 37.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for theus-2.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 eab03b3478156359dfee43dd6c5de3a366bde13db5986f7a04b281f0abcef9d6
MD5 da7ea2e4463465615002dc19ee2fe9f7
BLAKE2b-256 df51c376c885db2a6dcd8739492aa155056759b978cbf50e4a6bc2b5a9f8cd5a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page