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.4.tar.gz (207.7 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.4-py3-none-any.whl (39.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: theus-2.1.4.tar.gz
  • Upload date:
  • Size: 207.7 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.4.tar.gz
Algorithm Hash digest
SHA256 b29e55d1dfac3b322c87e2fb7bacafcecddb65cb810e13eb0c183ef293cf989d
MD5 2bcdf213bece75da8befe6349e156d4e
BLAKE2b-256 290d522aa5e1409119f9f2aa8bbef0c428613129e81b228336682af85f5a7c50

See more details on using hashes here.

File details

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

File metadata

  • Download URL: theus-2.1.4-py3-none-any.whl
  • Upload date:
  • Size: 39.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.4-py3-none-any.whl
Algorithm Hash digest
SHA256 e4cf75528d650c1c91c294ac5ddfe0a1dc91b21cca943ffd4ae0106254bc3800
MD5 2ee92fd59978c8b4a8ad9b4bc86e0a8b
BLAKE2b-256 98d8cd30474e981cac4de3fb9099f4cb5f258e9b04c7333532b8e4292b42873c

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