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.2.tar.gz (207.9 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.2-py3-none-any.whl (37.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: theus-2.1.2.tar.gz
  • Upload date:
  • Size: 207.9 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.2.tar.gz
Algorithm Hash digest
SHA256 d6af52a085dfca1adf75a2221d84ee653a2839afe2479f26e2440cce2a2e015c
MD5 0e56eca82acac1f46e431b098a19be46
BLAKE2b-256 d675868343de65b63f239a606bb714729ef429ccd8ed871a262c67fbda9dd4cf

See more details on using hashes here.

File details

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

File metadata

  • Download URL: theus-2.1.2-py3-none-any.whl
  • Upload date:
  • Size: 37.8 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.2-py3-none-any.whl
Algorithm Hash digest
SHA256 3f9bac2f389a51516ca4cee7545cce6a91e43649d5e5556a0cd2565d7e738085
MD5 d6437a37dd4b731716dae585a342af50
BLAKE2b-256 c192e29101bd59211103727c0bab25afd2be8141de82d5d155a117cd89b2b393

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