Metadata-Version: 2.4
Name: agentium
Version: 2.0.0
Summary: Context and trust integrity for multi-agent and long-running AI agents.
Author-email: Sanjay N <2005sanjaynrs@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/RNS-Forge/Agentium-Python-Library-
Project-URL: Documentation, https://github.com/RNS-Forge/Agentium-Python-Library-#readme
Project-URL: Repository, https://github.com/RNS-Forge/Agentium-Python-Library-.git
Project-URL: Issues, https://github.com/RNS-Forge/Agentium-Python-Library-/issues
Project-URL: Changelog, https://github.com/RNS-Forge/Agentium-Python-Library-/blob/main/CHANGELOG.md
Keywords: ai,agents,lineage,multi-agent,provenance,fingerprint,context-integrity
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.20.0; extra == "otel"
Provides-Extra: otelsdk
Requires-Dist: opentelemetry-sdk>=1.20.0; extra == "otelsdk"
Provides-Extra: tenacity
Requires-Dist: tenacity>=8.2.0; extra == "tenacity"
Provides-Extra: pybreaker
Requires-Dist: pybreaker>=1.0.0; extra == "pybreaker"
Provides-Extra: cachetools
Requires-Dist: cachetools>=5.0.0; extra == "cachetools"
Provides-Extra: pydantic
Requires-Dist: pydantic>=2.0.0; extra == "pydantic"
Provides-Extra: jsonschema
Requires-Dist: jsonschema>=4.0.0; extra == "jsonschema"
Provides-Extra: jsonrepair
Requires-Dist: json-repair>=0.10.0; extra == "jsonrepair"
Provides-Extra: jmespath
Requires-Dist: jmespath>=1.0.0; extra == "jmespath"
Provides-Extra: rapidfuzz
Requires-Dist: rapidfuzz>=3.0.0; extra == "rapidfuzz"
Provides-Extra: deepdiff
Requires-Dist: deepdiff>=6.0.0; extra == "deepdiff"
Provides-Extra: tiktoken
Requires-Dist: tiktoken>=0.5.0; extra == "tiktoken"
Provides-Extra: litellm
Requires-Dist: litellm>=1.0.0; extra == "litellm"
Provides-Extra: httpx
Requires-Dist: httpx>=0.24.0; extra == "httpx"
Provides-Extra: langgraph
Requires-Dist: langgraph>=0.0.20; extra == "langgraph"
Provides-Extra: crewai
Requires-Dist: crewai>=0.1.0; extra == "crewai"
Provides-Extra: openai-agents
Requires-Dist: openai>=1.0.0; extra == "openai-agents"
Provides-Extra: mcp
Requires-Dist: mcp>=1.0.0; extra == "mcp"
Provides-Extra: pluggy
Requires-Dist: pluggy>=1.0.0; extra == "pluggy"
Provides-Extra: pytest
Requires-Dist: pytest>=7.0.0; extra == "pytest"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: hypothesis>=6.0.0; extra == "dev"
Provides-Extra: langchain
Requires-Dist: langchain>=0.1.0; extra == "langchain"
Provides-Extra: ai
Requires-Dist: google-generativeai>=0.3.0; extra == "ai"

# Agentium

<p align="center">
  <img src="https://raw.githubusercontent.com/RNS-Forge/Agentium-Python-Library-/main/assets/agentium_companion.gif" width="220" alt="Agentium Orbital Companion Bot" />
</p>
<p align="center">
  <em>The Zero-Dependency Context and Trust Integrity Toolkit for Autonomous AI Agents</em>
</p>

[![Python Support](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![Zero Core Dependencies](https://img.shields.io/badge/core__dependencies-zero-success.svg)](#zero-runtime-dependency-guarantee)
[![PyPI Version](https://img.shields.io/badge/pypi-v2.0.0-informational.svg)](https://pypi.org/project/agentium/)
[![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Agentium is an open-source engineering toolkit designed to guarantee context survival, claim grounding, and safe execution across multi-agent pipelines and long-running autonomous workflows.

---

## Table of Contents

- [The Core Challenge in Autonomous Agents](#the-core-challenge-in-autonomous-agents)
- [Zero Runtime Dependency Guarantee](#zero-runtime-dependency-guarantee)
- [Quick Start Guide for Beginners](#quick-start-guide-for-beginners)
  - [Step 1: Installation](#step-1-installation)
  - [Step 2: Project Health and Initialization](#step-2-project-health-and-initialization)
  - [Step 3: Five-Minute Working Example](#step-3-five-minute-working-example)
- [Comprehensive Feature Walkthrough](#comprehensive-feature-walkthrough)
  - [Feature 1: Context Pins and Compaction Guard](#feature-1-context-pins-and-compaction-guard)
  - [Feature 2: Action Gate - Shadow and Enforce Modes](#feature-2-action-gate---shadow-and-enforce-modes)
  - [Feature 3: Evidence-Based Claims and Peer Agreement Defense](#feature-3-evidence-based-claims-and-peer-agreement-defense)
  - [Feature 4: Multi-Agent Lineage Graph and Root-Cause Blame](#feature-4-multi-agent-lineage-graph-and-root-cause-blame)
  - [Feature 5: Handoff Contracts and Token Envelopes](#feature-5-handoff-contracts-and-token-envelopes)
  - [Feature 6: Speculative Read-Only Prefetch Engine](#feature-6-speculative-read-only-prefetch-engine)
  - [Feature 7: Cryptographic Run Fingerprints](#feature-7-cryptographic-run-fingerprints)
  - [Feature 8: Continuous Integration Drift Gate](#feature-8-continuous-integration-drift-gate)
  - [Feature 9: Developer Diagnostics - Init and Doctor](#feature-9-developer-diagnostics---init-and-doctor)
  - [Feature 10: Automatic Secret and PII Redaction](#feature-10-automatic-secret-and-pii-redaction)
- [Universal Integration Hub](#universal-integration-hub)
- [Production Recipes Catalog](#production-recipes-catalog)
- [Framework Adapters](#framework-adapters)
- [Command Line Interface Reference](#command-line-interface-reference)
- [Backward Compatibility with Agentium v1](#backward-compatibility-with-agentium-v1)
- [License and Governance](#license-and-governance)

---

## The Core Challenge in Autonomous Agents

When building production systems with large language models, applications routinely fail in four predictable ways:

1. **Compaction Amnesia**: As conversations exceed context limits, summarization modules compress history. Essential instructions (such as "never execute SQL queries on production databases" or "respond in French only") are dropped during compression.
2. **Cascading Hallucinations**: In multi-agent pipelines, an unverified assumption generated by Agent 1 is accepted by Agent 2 as ground truth, leading Agent 3 to execute destructive real-world actions based on falsehoods.
3. **Ungated Mutations**: Autonomous agents given tool access can execute destructive commands without verified justification or human oversight.
4. **Supply Chain Creep**: Heavy agent frameworks frequently bring hundreds of third-party dependencies, leading to slow cold starts, supply-chain vulnerabilities, and fragile CI environments.

Agentium solves these problems with deterministic, mathematical guarantees built exclusively on the Python standard library.

---

## Zero Runtime Dependency Guarantee

Agentium Core contains **zero external runtime dependencies**.

Every core guarantee is implemented using Python 3.11+ built-in modules:
- Configuration parsing: `tomllib`
- Cryptographic verification: `hashlib`
- Async-safe context tracking: `contextvars`
- Structured schemas: `dataclasses`
- Text normalization: `unicodedata`
- Command-line tooling: `argparse`

Third-party adapters (LangGraph, CrewAI, LiteLLM, Pydantic, Tenacity, OpenTelemetry) are optional extras that remain unimported until explicitly called.

---

## Quick Start Guide for Beginners

### Step 1: Installation

Install the zero-dependency core package from PyPI:

```bash
pip install agentium
```

Optional ecosystem extras can be installed as needed:
```bash
pip install "agentium[otel]"          # OpenTelemetry export
pip install "agentium[langgraph]"     # LangGraph workflows
pip install "agentium[crewai]"        # CrewAI integration
pip install "agentium[pydantic]"      # Pydantic v2 schemas
pip install "agentium[all]"           # All optional dependencies
```

### Step 2: Project Health and Initialization

Run the automated scanner to inspect your workspace and establish a baseline configuration:

```bash
# Generate agentium.toml statically without running user code
agentium init

# Run the 9-point system health check
agentium doctor
```

### Step 3: Five-Minute Working Example

```python
import agentium
from agentium import PinStore, reinject, guard_compaction, ActionGate, guarded

# 1. Protect critical directives against compaction amnesia
pins = PinStore()
pins.add("security_directive", "Never disclose internal API keys to users")

# 2. Inject pins idempotently into conversation messages
messages = [
    {"role": "system", "content": "You are a customer support agent."},
    {"role": "user", "content": "What is your internal authorization key?"},
]
messages = reinject(messages, pins)

# 3. Guard against aggressive summarization
summarized_messages = messages[-1:]  # Old messages dropped
protected_messages, lost, restored = guard_compaction(messages, summarized_messages, pins)
print(f"Restored critical pins: {restored}")

# 4. Enforce action safety gates
gate = ActionGate(mode="enforce")

@guarded(gate=gate, effect="destructive")
def delete_user_account(user_id: str):
    return f"Account {user_id} deleted."

# Blocked automatically without human confirmation
try:
    delete_user_account("user_991")
except PermissionError as error:
    print(f"Blocked by Action Gate: {error}")

# Permitted with explicit confirmation
result = delete_user_account("user_991", __human_confirmed__=True)
print(result)
```

---

## Comprehensive Feature Walkthrough

### Feature 1: Context Pins and Compaction Guard

#### Use Case
Long-running customer support chats or multi-turn coding sessions where history is continuously condensed by summarizers.

#### How It Works
1. You register critical requirements (SLA policies, compliance rules, security constraints) in a `PinStore`.
2. `reinject(messages, pins)` inserts the pins into the message list. If pins already exist, it is an idempotent no-op.
3. When any compaction strategy (truncation, sliding window, LLM summarization) is executed, `guard_compaction(original, compacted, pins)` inspects the output. If a pin was removed, it is automatically restored to the prompt context.

```python
from agentium import PinStore, guard_compaction

pins = PinStore()
pins.add("refund_policy", "Refunds above $100 require supervisor approval")

original_chat = [
    {"role": "system", "content": "You are a sales assistant. Refunds above $100 require supervisor approval."},
    {"role": "user", "content": "I would like a refund of $250 for order 491."},
]

# Compactor compresses history to a brief summary
compressed_chat = [
    {"role": "system", "content": "User requested refund for order 491."},
]

# Guard detects lost refund policy and restores it
safe_chat, lost_pins, restored_pins = guard_compaction(original_chat, compressed_chat, pins)
print("Protected messages:", safe_chat)
```

---

### Feature 2: Action Gate - Shadow and Enforce Modes

#### Use Case
Protecting production systems from accidental database deletions, ungrounded financial transactions, or unauthorized cloud infrastructure modifications.

#### How It Works
Decorate functions with `@agentium.tool(effect="read"|"mutate"|"destructive")`.
- `read`: Always allowed (e.g., retrieving balance, viewing user profile).
- `mutate`: Permitted if standard execution context is valid.
- `destructive`: Blocked in `enforce` mode unless grounded by verified evidence or explicit human approval. In `shadow` mode, actions execute while logging security telemetry.

```python
from agentium import ActionGate, guarded

gate = ActionGate(mode="enforce")

@guarded(gate=gate, effect="destructive")
def refund_transaction(transaction_id: str, amount: float):
    return f"Refunded {amount} for {transaction_id}"

# This call raises PermissionError
try:
    refund_transaction("tx_881", 450.00)
except PermissionError:
    print("Action blocked: unauthorized destructive mutation")

# This call succeeds
confirmed = refund_transaction("tx_881", 450.00, __human_confirmed__=True)
```

---

### Feature 3: Evidence-Based Claims and Peer Agreement Defense

#### Use Case
Multi-agent research pipelines where one agent speculates about a financial number or medical diagnosis, and other agents repeat it as verified fact.

#### How It Works
`ClaimStore` tracks statements made by agents. A claim begins as `unverified`.
- **Peer Agreement Defense**: If another agent says "I agree with Agent 1", Agentium records the peer agreement for audit logs, but **refuses to change status to verified**.
- **Evidence Verification**: The claim only transitions to `verified` when an `EvidenceRef` linking to an external tool call or document excerpt is supplied.

```python
from agentium import ClaimStore, EvidenceRef

claims = ClaimStore(run_id="research_run_01")

# Agent 1 proposes an unverified statement
c1 = claims.add("Company revenue grew 34% in Q3", source_agent="extractor_agent")
assert claims.get(c1.id).status == "unverified"

# Agent 2 agrees with Agent 1
claims.record_peer_agreement(c1.id, peer_agent="analyst_agent")
assert claims.get(c1.id).status == "unverified"  # Still unverified!

# Grounding evidence verifies the claim
evidence = EvidenceRef(
    source_type="sec_filing",
    source_id="10-Q_Q3_2026",
    excerpt="Revenue increased 34% year-over-year to $4.2B",
)
claims.verify(c1.id, verifier_name="financial_auditor", evidence=evidence)
assert claims.get(c1.id).status == "verified"
```

---

### Feature 4: Multi-Agent Lineage Graph and Root-Cause Blame

#### Use Case
Auditing complex multi-agent workflows (e.g., planner -> coder -> reviewer -> deployer) to discover which agent introduced an erroneous assumption.

#### How It Works
`LineageGraph` builds an execution DAG tracking agent delegations, tool invocations, and claim dependencies. When an error is found, `graph.blame(claim_id)` walks backwards through the DAG to isolate the origin agent, tools used, and intermediate hops.

```python
from agentium import LineageGraph

graph = LineageGraph(run_id="deploy_run_12")
graph.record_agent("planner")
graph.record_agent("code_generator")
graph.record_agent("security_scanner")

graph.record_step("planner", "code_generator", message_tokens=150)
graph.record_claim_origin("claim_sql_safe", agent="code_generator")
graph.record_step("code_generator", "security_scanner", message_tokens=280)

# Automated blame report
report = graph.blame("claim_sql_safe")
print(f"Origin agent: {report.origin_agent}")
print(f"Dependency path: {report.path}")

# Export to Mermaid flowchart
print(graph.to_mermaid())
```

---

### Feature 5: Handoff Contracts and Token Envelopes

#### Use Case
Ensuring structured context passing between agents without dropped fields, token explosions, or circular handoff loops.

#### How It Works
`HandoffContract` defines the contract between a sender and receiver. `lint_handoff` checks for missing required keys, circular delegation loops (A -> B -> A), and token budget violations.

```python
from agentium import HandoffContract, HandoffPacket

contract = HandoffContract(
    source_agent="triage",
    target_agent="database_admin",
    max_tokens=250,
    required_keys=["incident_id", "severity"],
)

packet = HandoffPacket(
    source_agent="triage",
    target_agent="database_admin",
    payload={"incident_id": "INC-404", "severity": "HIGH"},
)

validation = contract.validate(packet)
assert validation.is_valid is True
```

---

### Feature 6: Speculative Read-Only Prefetch Engine

#### Use Case
Reducing turn latency in multi-turn tool calling pipelines by speculatively running read-only lookups in the background.

#### How It Works
A Markov transition model monitors sequential tool calls. When a predictable pattern occurs (such as `get_order_details` always being followed by `get_shipping_status`), Agentium speculatively executes the second tool if and only if it has `effect="read"`. Destructive or mutating tools are strictly prohibited from speculative execution.

```python
from agentium.speed import PrefetchEngine

engine = PrefetchEngine()
engine.record_transition("fetch_user", "fetch_permissions")

# When fetch_user is invoked, engine predicts next tool
predicted = engine.predict_next("fetch_user")
print(f"Predicted tool for prefetch: {predicted}")
```

---

### Feature 7: Cryptographic Run Fingerprints

#### Use Case
Detecting unintended changes in system prompts, model identifiers, or tool schemas between code commits and production deployments.

#### How It Works
`compute_fingerprint` normalizes strings using Unicode NFC and produces a deterministic SHA-256 hash encompassing prompts, parameters, and tool schemas.

```python
from agentium.fingerprint import compute_fingerprint

fp = compute_fingerprint(
    model="gpt-4o",
    prompt_template="You are an enterprise code reviewer.",
    tools=[{"name": "lint_code", "parameters": {"type": "object"}}],
)
print("Run Fingerprint:", fp.hash)
```

---

### Feature 8: Continuous Integration Drift Gate

#### Use Case
Preventing pull requests from silently altering agent prompts or schema definitions.

#### How It Works
Run `agentium lock` to capture approved baselines. In your CI workflow, run `agentium check`. If any prompt, tool argument, or model configuration drifted without an updated lockfile, the CI step exits with code 1.

```bash
# Capture approved fingerprint
agentium lock --from my_module.agent:build_pipeline

# Check in CI
agentium check --strict
```

---

### Feature 9: Developer Diagnostics - Init and Doctor

#### Use Case
Non-destructive environment setup, configuration verification, and troubleshooting.

#### How It Works
- `agentium init`: Scans workspace files to detect frameworks (LangGraph, CrewAI, OpenAI) and outputs a valid `agentium.toml` without modifying project code.
- `agentium doctor`: Runs a 9-point diagnostic verifying Python versions, config validity, event stores, lock status, pin retention rates, and lineage graph integrity.

```bash
agentium init
agentium doctor --strict
```

---

### Feature 10: Automatic Secret and PII Redaction

#### Use Case
Preventing API keys, authorization tokens, and personal credentials from leaking into OpenTelemetry spans, logs, or JSONL trace files.

#### How It Works
The redaction engine evaluates outgoing event payloads against high-entropy regex patterns matching OpenAI keys (`sk-...`), GitHub tokens (`ghp_...`), Slack tokens (`xoxb-...`), and generic Bearer headers, replacing them with `[REDACTED_API_KEY]`.

```python
from agentium.core.redact import redact_payload

raw_data = {"headers": {"Authorization": "Bearer sk-proj-1234567890abcdef1234567890"}}
safe_data = redact_payload(raw_data)
print(safe_data["headers"]["Authorization"])
# Output: Bearer [REDACTED_API_KEY]
```

---

## Universal Integration Hub

Agentium's integration hub allows wrapping any existing function, API client, or framework tool to instantly provide effect tagging, secret scrubbing, and action gate protection:

```python
from agentium.hub import wrap

def fetch_weather(city: str):
    return {"city": city, "temp": 72}

# Wrap function with read-only effect tag and automatic redaction
safe_fetch = wrap(fetch_weather, effect="read", redact_output=True)
result = safe_fetch("San Francisco")
```

---

## Production Recipes Catalog

Agentium includes 20 pre-built Tier-1 recipes (40 sync/async twins) covering the most common agent engineering patterns:

| ID | Recipe Name | Integrated Tools | Primary Guarantee |
|:---|:---|:---|:---|
| **R01** | `api_call_safe` | `httpx`, `tenacity` | Safe HTTP calls with exponential backoff and secret scrubbing |
| **R03** | `cached_tool` | `cachetools` | Read-only TTL caching keyed on canonical argument hashes |
| **R05** | `validated_tool_args` | `pydantic` | Automatic schema validation for LLM-generated arguments |
| **R06** | `structured_llm` | `jsonrepair`, `pydantic` | Parsing and repair of malformed LLM JSON responses |
| **R08** | `smart_compact` | `tiktoken` | Context compaction that preserves all active pins |
| **R10** | `llm_failover` | `litellm` | Multi-model failover routing upon provider outage |
| **R15** | `mcp_safe_tools` | `mcp` | Model Context Protocol tools gated by ActionGate |
| **R22** | `fuzzy_verify` | `rapidfuzz` | Grounding claims against documents using fuzzy similarity |
| **R23** | `graph_retry` | `langgraph` | Resilient LangGraph nodes with automated rollback |
| **R25** | `graph_tracing` | `langgraph`, `otel` | Automated OpenTelemetry span generation for graph runs |
| **R27** | `protected_handoff` | `pydantic`, `jsonschema` | Token-capped, validated inter-agent handoff envelopes |
| **R28** | `mcp_bridge` | `mcp` | Bidirectional bridge connecting MCP tools to Agentium |
| **R39** | `fuzzy_dedupe_cache` | `rapidfuzz` | Semantic deduplication of incoming tool arguments |
| **R42** | `http_cache_tool` | `cachetools`, `httpx` | RFC-compliant HTTP caching for API tools |
| **R43** | `budget_llm` | `litellm` | Hard token budget and cost tracking per session |
| **R44** | `typed_agent_tools` | `openai-agents` | Type-safe tool signatures with automatic schema export |
| **R45** | `safe_call` | `pybreaker` | Circuit breaker protection preventing cascade outages |
| **R51** | `drift_report` | `deepdiff` | Structural diff reports across agent runs |
| **R58** | `verified_extract` | `jmespath` | Grounded extraction generating verified claims |

---

## Framework Adapters

Agentium adapters connect seamlessly to popular agent runtimes:

- **LangGraph**: `agentium.adapters.LangGraphAdapter` wraps state nodes and checkpointers.
- **CrewAI**: `agentium.adapters.CrewAIAdapter` guards agent delegations and task outputs.
- **OpenAI Agents**: `agentium.adapters.OpenAIAgentsAdapter` provides function schema generation and effect gating.

---

## Command Line Interface Reference

```bash
# Workspace setup and validation
agentium init [--dry-run] [--force]
agentium doctor [--strict] [--json]

# Schema fingerprinting and CI gates
agentium lock --from <module:function>
agentium check [--strict] [--format text|json|md]

# Provenance and lineage analysis
agentium lineage claims <run_id>
agentium lineage blame <run_id> <claim_id>
agentium lineage diff <run_a> <run_b>

# Handoff packet validation
agentium handoff lint <path_to_json>

# Context pins and soak testing
agentium pins render [--run_id id]
agentium soak [--cycles N] [--loss-target float]
```

---

## Backward Compatibility with Agentium v1

All legacy Agentium v1 text-processing classes (`Condenser`, `Optimizer`, `Rearranger`, `Extractor`, `Communicator`, `Translator`, `InsightGenerator`, `WorkflowHelper`, `TemplateManager`, `MemoryHelper`, `CustomSummarizer`, and `LoggerUtils`) remain operational:

```python
# Legacy v1 usage continues to work seamlessly:
from agentium import Condenser, Optimizer, Agentium

agent = Agentium()
result = agent.process_content("Sample text to condense", workflow="basic")
```

---

## License and Governance

Agentium is open-source software licensed under the [MIT License](LICENSE).

Copyright (c) 2024-2026 Sanjay N.
