Metadata-Version: 2.4
Name: aql-agent-sandbox
Version: 0.1.0
Summary: Deterministic AI Agent Sandbox & Governance Kernel for autonomous LLM systems
Author-email: ONE XI Technologies <research@onexi.tech>
License: Apache-2.0
Keywords: ai-safety,agent-governance,sandbox,audit-ledger,circuit-breaker,deterministic-runtime,llm-agents,tool-use
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.8
Description-Content-Type: text/markdown

# AQL Agent Sandbox & Governance Kernel (`aql-agent-sandbox`)

**Deterministic pre-execution supervisor, AST transaction compiler, and cryptographic audit journal for autonomous AI agents.**

[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Python: 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/)
[![Integrity: SHA-256 Hash Chain](https://img.shields.io/badge/Integrity-SHA--256%20Chain-emerald.svg)](https://onexi.tech)
[![Compliance: EU AI Act Art. 12](https://img.shields.io/badge/Compliance-EU%20AI%20Act%20Art.%2012-purple.svg)](https://onexi.tech)

---

## Why AQL Agent Sandbox?

As autonomous LLM agents take direct actions in production (database mutations, API calls, financial settlements, email dispatch), existing probabilistic prompt instructions are fundamentally non-deterministic. Prompt injections or unexpected model hallucinations can lead to unauthorized operations.

`aql-agent-sandbox` provides a **deterministic runtime boundary**:

1. **Pre-Execution Interception**: Inspects tool calls *before* execution occurs.
2. **Deterministic `.aql` Transaction Compilation**: Transforms high-level tool calls into formal AST-validated coordinate root specifications (`ح-س-ب`, `ح-ف-ظ`, `ذ-ر-ر`, `ع-د-ل`).
3. **Hardware-Grade Circuit Breakers**: Halts execution instantly if budget limits are exceeded or consecutive execution failures occur (`CIRCUIT_BREAKER_HALT`).
4. **Append-Only SHA-256 Audit Ledger**: Every action (approved or blocked) is permanently recorded into a cryptographically hash-chained SQLite journal with automatic tamper detection (`CHAIN_BREAK`).

---

## Installation

```bash
pip install aql-agent-sandbox
```

Or from local workspace:

```bash
pip install -e packages/aql-agent-sandbox
```

---

## Quickstart

### 1. Basic Tool Interception & Invariant Verification

```python
from aql_agent_sandbox import (
    AgentExecutionSupervisor,
    SandboxPolicy,
    AgentSandboxSecurityError,
)

# Define safety policy
policy = SandboxPolicy(
    allowed_tools={"query_database", "transfer_funds", "send_email"},
    param_limits={
        "transfer_funds": {"amount": {"max": 1000.0, "min": 1.0}}
    }
)

supervisor = AgentExecutionSupervisor(policy=policy, journal_path="agent_audit.db")

# ✅ 1. Safe Action: Transfer $250
result = supervisor.intercept(
    tool_name="transfer_funds",
    arguments={"to": "acct_982", "amount": 250.0},
    agent_id="finance_bot_1"
)
print("Decision:", result.decision)  # PASSED_EXECUTION_GRANTED
print("Compiled AQL:\n", result.compiled_aql.aql_code)

# ❌ 2. Unsafe Action: Exceeds $1,000 threshold -> Raises Security Error
try:
    supervisor.intercept(
        tool_name="transfer_funds",
        arguments={"to": "acct_982", "amount": 75000.0},
        agent_id="finance_bot_1"
    )
except AgentSandboxSecurityError as err:
    print("Blocked by Sandbox:", err)
    # AGENT_SANDBOX_BLOCKED [BLOCKED_PARAM_OUT_OF_BOUNDS]: Parameter 'amount' exceeds 1000.0
```

---

### 2. Guard Native Python Functions with Decorators

```python
@supervisor.guard(tool_name="transfer_funds", agent_id="payout_agent")
def execute_wire_transfer(to: str, amount: float):
    # This code NEVER runs if the sandbox blocks the call
    print(f"Wire transferred ${amount} to {to}")
    return {"status": "SETTLED"}

# Allowed execution
execute_wire_transfer(to="partner_inc", amount=450.0)
```

---

### 3. OpenAI / Anthropic / Gemini Tool Calling Adapter

Feed refusal messages back to your LLM agent so it gracefully chooses safe alternatives:

```python
from aql_agent_sandbox import LLMToolCallingAdapter

adapter = LLMToolCallingAdapter(supervisor)

# Raw tool calls emitted by LLM
llm_tool_calls = [
    {
        "id": "call_01",
        "type": "function",
        "function": {"name": "transfer_funds", "arguments": '{"amount": 500}'}
    },
    {
        "id": "call_02",
        "type": "function",
        "function": {"name": "drop_database", "arguments": '{"db": "production"}'}
    }
]

approved, rejections = adapter.filter_openai_tool_calls(llm_tool_calls)

print(f"Approved: {len(approved)} | Rejected: {len(rejections)}")
# 'approved' has call_01
# 'rejections' contains structured refusal feedback for call_02 to inject into agent context
```

---

### 4. Cryptographic Ledger Audit (Tamper Verification)

Audit the entire history of agent decisions to mathematically verify no log entries were altered or deleted:

```python
valid, anomalies = supervisor.verify_audit_ledger()
if valid:
    print("✓ Cryptographic Audit Passed: 100% SHA-256 chain integrity verified.")
else:
    print("✗ Tamper Alert:", anomalies)
```

Or via the CLI:

```bash
aql-sandbox audit agent_audit.db
```

---

## 4 Coordinate Root Namespaces

`aql-agent-sandbox` maps all actions to one of the 4 absolute coordinate roots:

| Root | Semantic Domain | Authorized Verbs | Common Tools |
|:---:|---|---|---|
| **`ح-س-ب`** | Exact Computation & Querying | `COMPUTE`, `EVALUATE`, `MEASURE` | Math, SQL queries, read operations |
| **`ح-ف-ظ`** | State Preservation & Audit | `COMMIT`, `RECORD`, `AUDIT` | File writes, logging, database updates |
| **`ع-د-ل`** | Justice, Equilibrium & Balance | `RECONCILE`, `BALANCE`, `EMIT` | Fund transfers, payouts, permissions |
| **`ذ-ر-ر`** | Atomization & Processing | `TOKENIZE`, `QUANTIZE`, `QUANTUM_COMPILE` | Quantum gates, embeddings, tokenization |

---

## Compliance & Standards

* **EU AI Act (Article 12):** Satisfies technical requirements for automatic event logging, traceability, and post-market monitoring of autonomous AI systems.
* **SOC2 / ISO 27001:** Append-only SHA-256 hash chains guarantee non-repudiation for automated agent operations.

---

## License

Apache-2.0. Developed by ONE XI Technologies ([onexi.tech](https://onexi.tech)).
