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.3.tar.gz (208.2 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.3-py3-none-any.whl (38.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: theus-2.1.3.tar.gz
  • Upload date:
  • Size: 208.2 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.3.tar.gz
Algorithm Hash digest
SHA256 43734677525eb215856625633417a5ecd582de4ae41a63d5a61f514679eb99d5
MD5 b5636e7f34afd2947b0e2b08cd013418
BLAKE2b-256 5ca3d9dbf14b5efc5a1aa82d4c43b5183103337c77189180cfd764cb6599bb37

See more details on using hashes here.

File details

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

File metadata

  • Download URL: theus-2.1.3-py3-none-any.whl
  • Upload date:
  • Size: 38.1 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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 d86f3c4c014d20eb0ab754403800ddec56a75567712df0e63d0a784177656c49
MD5 f4a9ba37089576803d006dcf5d412546
BLAKE2b-256 4500e9120b942e888bd9b0cdf73ba4bd147ff35e57f40569f0f2b229d7a9b08d

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