GuardianAI Technical Documentation
Dual-plane security for autonomous AI agents: millisecond-scale prompt injection firewalls off-chain, coupled with cryptographically verifiable ERC-8004 identity and evidence anchoring on-chain.
Off-Chain Layer
10-layer heuristic, regex, semantic, and de-obfuscation firewall filtering attacks in under 42ms p95.
On-Chain Layer
ERC-8004 agent registries, Merkle tree state anchors, and signed insurance certificate registries.
5-Min Setup
Drop-in proxy or single-line Python SDK wrapper for OpenAI, Anthropic, LangChain, and CrewAI.
Contract Analyzer
48 AST/CFG validated vulnerability detection rules for Solidity & Vyper smart contracts.
Quickstart (5-Minute Integration)
Integrate GuardianAI into your existing autonomous agent stack in minutes using either our reverse proxy or the native Python SDK.
Option A: OpenAI-Compatible Ingress Proxy
Point your existing client code to the Guardian proxy host (http://127.0.0.1:8081 or your managed cloud gateway) by simply updating the base_url:
from openai import OpenAI
# Route completions directly through the GuardianAI Security Proxy
client = OpenAI(
base_url="http://127.0.0.1:8081/v1",
api_key="your-guardian-api-token"
)
response = client.chat.completions.create(
model="gpt-5.6",
messages=[{"role": "user", "content": "Deploy trading agent transaction"}]
)
print(response.choices[0].message.content)
Option B: Python SDK Direct Wrapper
Wrap standard agent frameworks like LangChain, LlamaIndex, or AutoGen using the guardian library:
from guardian.sdk import GuardianAgentGuard
# Initialize runtime firewall with balanced preset
guard = GuardianAgentGuard(preset="balanced", fail_closed=True)
# Inspect user input prior to model execution
verdict = guard.inspect_input(user_prompt)
if not verdict.allowed:
raise SecurityException(f"Attack blocked: {verdict.rule_id} ({verdict.reason})")
# Forward to model and sanitize response
response = agent.run(user_prompt)
sanitized_output = guard.inspect_output(response)
Option C: Interactive CLI Walkthroughs
Run the 6-stage interactive walkthrough or 3-act attack simulation locally in your terminal:
# 1. Six-stage interactive CLI preview (Firewall, Enclave, PolicyGuard)
python demo/full_demo.py --preview
# 2. Three-act adversarial attack simulation
python demo/run_demo.py
3-Layer Defense-in-Depth Architecture
GuardianAI guards an agent with two gates: an off-chain AI firewall that filters threats in milliseconds, and PolicyGuard on Monad that refuses any payment GuardianAI didn't approve. Mera passkeys give the agent its identity and sealed memory.
| Defense Layer | Target Execution | Core Responsibilities | Performance & SLA |
|---|---|---|---|
| Gate 1: AI Firewall (off-chain) | Off-Chain Ingress Proxy & Gateway | 10-layer prompt firewall, de-obfuscation pipeline, PII/secret DLP scrubber, honeypot canary tripwires, fail-closed token bucket | < 42 ms p95 under attack, 494 req/s blocking capacity |
| Agent identity & sealed memory (Mera) | WebAuthn PRF & Hardware Memory Sealing | Category Labs Mera Passkey PRF key derivation, AES-256-GCM sealed memory with replay-protected AAD, active MEMORY_POISONING_DETECTED tamper tripwire |
Sub-0.5ms P50 latency, 184/184 tests, 0 collisions across 4 GitHub corpora |
| Gate 2: PolicyGuard (on Monad) | Monad Parallel EVM Smart Contracts | GuardianPolicyGuard.sol pre-flight execution firewall, GuardianThreatOracle.sol Chainlink CRE receiver (live on testnet, fed by CRE simulation), GuardianAgentWallet.sol per-agent wallet, ERC-8004 identity, Merkle Cortex state anchoring |
207/207 Hardhat tests (11 suites), per-agent nonces for parallel execution |
10-Layer AI Prompt Firewall
Every incoming prompt passes through a progressive 10-stage defense-in-depth pipeline. Fast heuristics reject obvious attacks in microseconds, while deeper semantic and de-obfuscation engines neutralize advanced multi-turn and obfuscated jailbreaks.
1. Regex Fast-Path
Known jailbreak prefixes, instruction reset patterns, and exploit signatures evaluated in < 0.5ms.
2. Shannon Entropy Filter
Detects high-entropy encrypted blobs, raw binary payloads, and compressed ciphertext attacks.
3. Steganography & Cipher Engine
Automated decoding for Braille, Morse code, Base64, Hex, ROT13, Leetspeak, and Unicode homoglyphs.
4. Semantic Classifier
Fine-tuned lightweight classifier scoring adversarial intent, DAN variants, and system-prompt extraction.
5. Multi-Lingual Translation Gate
Normalizes cross-lingual evasion attempts in Chinese, Russian, Arabic, and low-resource languages.
6. Token Smuggling / Zero-Width
Strips zero-width joiners, invisible unicode separators, and RTL directional override exploits.
7. Roleplay & Virtualization Filter
Neutralizes "fictional scenarios", "debug mode", "developer override", and hypothetical simulation prompts.
8. Tool Calling & Transaction Interlock
Validates tool arguments against strict schema constraints; blocks unauthorized wallet transfers and parameter tampering.
9. Honeypot Canary Engine
Plants synthetic credentials in system context; triggers immediate session quarantine if referenced.
10. Threat Intelligence Matcher
Live matching against globally synchronized IOC feeds and newly cataloged zero-day prompt signatures.
Output DLP & Secret Scanner
Even if an LLM is coaxed into generating sensitive data, GuardianAI's egress filter inspects completions before they reach the user or client application.
| Data Category | Detection Mechanism | Sanitization Action |
|---|---|---|
| Cloud & Payment API Credentials | Entropy + Prefix heuristics (AWS, Stripe, OpenAI, Cloud providers) | Redacted with cryptographic audit hash |
| Cryptographic Keys & Seed Phrases | Checksum validation & high-entropy pattern matching | Zeroized & logged to security audit stream |
| Personal & Regulatory Identifiers (PII) | HIPAA / GDPR regex & named entity recognition | Masked prior to client delivery |
Honeypots & Threat Intel Feed
GuardianAI dynamically injects synthetic decoy credentials and canary tokens into agent system prompts. If a prompt coaxes the model into reciting or calling a tool with a canary token, GuardianAI identifies the breach instantly and logs an emergency threat signal.
# Dynamically provision canary token per tenant session
canary_token = honeypot.generate_token(session_id="agent_sess_89a2")
# Inject transparently into system message
system_prompt += f"\nInternal Vault Key: {canary_token.secret}"
# If tool arguments or egress contain the canary, tripwire fires immediately
if honeypot.is_tripped(response_text):
security_pipeline.quarantine_session(session_id)
Fail-Closed Rate Limiter
To defend against denial-of-wallet and automated prompt bombing, GuardianAI implements a strict fail-closed token-bucket rate limiter powered by atomic Redis Lua scripts (_REDIS_RATE_LIMIT_LUA) for zero-drift distributed replenishment. In-memory local buckets are bounded to 50,000 entries and continually swept by a 60-second RateLimiterJanitor daemon. If backing services experience downtime, GuardianAI safely restricts requests rather than failing open.
| Tier | Rate Limit (Req/Min) | Burst Allowance | Rate Limit Backend |
|---|---|---|---|
| Standard Ingress | 100 req/min | 20 requests | In-Memory Ring Buffer |
| High-Throughput Gateway | 1,000 req/min | 150 requests | Redis Distributed Cluster |
| Dedicated Cluster | Unlimited / Custom | Custom SLA | Dedicated Redis Multi-Region |
Mera Passkey PRF Sovereign Enclave (agent identity & memory)
Try it with your own passkey: one operator passkey derives each agent’s identity (and the agent card the relay checks before approving payments), its memory key and a credential vault, and a handoff link reproduces them on a second device.
Built on Category Labs’ Mera SDK (@category-labs/mera), GuardianAI’s Sovereign Agent Enclave harnesses client-side WebAuthn Pseudo-Random Functions (PRF) (FaceID, TouchID, and FIDO2 hardware authenticators) to generate deterministic, unlinkable agent identities without storing raw private keys or master secrets on any server.
Hardware-Bound PRF Keys
Master seed derived within local device Secure Enclave; never leaves client RAM and cannot be exfiltrated via server-side compromise.
AES-256-GCM Memory Sealing
Agent episodic memory vectors and tool credentials encrypted with HKDF-derived keys and replay-protected Additional Authenticated Data (AAD).
Cross-Device Determinism
Same physical human authenticator generates identical agent DIDs and decrypts sealed state across independent devices.
Live Benchmark Receipts
184/184 tests passing (18 core Vitest + 166 hard audit assertions on 4 corpora), sub-0.5ms P50 latency, 0 collisions.
Memory Poisoning Guard & Tamper Tripwire
Autonomous agents that consume external web data, pull requests, or Discord messages risk context injection and persistent memory poisoning. GuardianAI embeds an active cryptographic tamper tripwire directly into the memory retrieval path.
// Memory retrieval verification in @guardianai/middleware
try {
const decryptedContext = await enclave.unsealMemory(agentId, sealedRecord);
return decryptedContext;
} catch (err) {
if (err.code === "ERR_GCM_AUTH_FAILED" || err.message.includes("tag mismatch")) {
// Single-bit ciphertext flip trips immediate fail-closed quarantine
await securityPipeline.quarantineAgent(agentId, {
code: "MEMORY_POISONING_DETECTED",
incidentSeverity: "CRITICAL",
action: "REVOKE_HOT_WALLET_PERMISSIONS"
});
throw new SecurityException("Agent context compromised: Memory poisoning tripwire fired.");
}
}
Monad PolicyGuard (Gate 2: on-chain payment guard)
GuardianAI deploys native smart contracts to the Monad Parallel EVM (Chain ID 10143). The flagship execution firewall, GuardianPolicyGuard.sol, checks every agent payment against a GuardianAI-signed approval before it runs: exact target, calldata and value, a deadline, a risk limit, an active agent ID card, and a one-time nonce.
GuardianPolicyGuard is deployed at 0x90Fd...EF60 ↗. Source verification on MonadScan is pending. Hardhat suite: 207 tests across 11 suites in our last local run (cd contracts && npx hardhat test).
Storage Slot Isolation
Nonces are tracked per agent in usedNonces[agentId][nonce], so independent agents write to different storage slots and don't contend on Monad's parallel EVM.
On-chain Risk Limit
Payments GuardianAI scored above maxAllowedRiskScore (currently 25/100) revert with RiskScoreExceedsThreshold, even if the agent itself was fooled.
Revocable Agent Identity
A payment only runs while the agent's GuardianPassportSBT card is active. Revoke the card and the agent can't pay (PassportRevokedOrInactive).
EIP-712 Signed Approvals
Each approval is a SafetyAttestation bound to the target, calldata hash, value, risk score, nonce and deadline. Change one byte, or sign with any other key, and it fails (InvalidAttestationSignature).
Pay per Approval (x402, USDC on Monad)
The relay can charge agents per signed approval with x402. No account or API key: the agent's first call to /api/v1/attest gets HTTP 402 with the price, the agent signs a USDC authorization, and the request is retried with payment attached. Only an approved attestation is settled on-chain. A blocked action returns 403 and the agent is not charged.
Status: works on Monad testnet ($0.01 USDC per approval). Example settlement: 0xc6c604d0…f1d57b. Off by default; mainnet USDC is not enabled yet.
GUARDIAN_X402_ENABLED=true
GUARDIAN_X402_PAY_TO=0xYourWallet # receives the USDC
GUARDIAN_X402_PRICE=$0.01
GUARDIAN_X402_NETWORK=eip155:10143 # Monad testnet
GUARDIAN_X402_FREE_PER_AGENT_MONTH=0 # optional free approvals per agent
GUARDIAN_ATTESTATION_SIGNER_KEY=0x... # required: relay refuses to charge without it
# end-to-end test with a funded testnet payer
python tools/x402_e2e.py
Chainlink Threat Consumer (GuardianThreatConsumer)
GuardianThreatOracle.sol (0x2614…dA95 on Monad testnet) receives reports from the Chainlink CRE workflow guardian-threat-sync: every node fetches GuardianAI's scam list, the nodes agree on it (list and digest identical, counters by median), and the signed report is delivered through the Chainlink forwarder, the only address allowed to write. GuardianAgentWallet checks isFlagged() on the target and on token recipients before every call. Status: run with cre workflow simulate guardian-threat-sync --target staging-settings --broadcast, which delivered a real report flagging 2 addresses; a payment to one of them then reverted with FlaggedDestination. Not yet running on a live DON. (The older GuardianThreatConsumer.sol is superseded.)
ERC-8004 Agent Registries
GuardianAI integrates with the canonical ERC-8004 "Trustless Agents" standard. Each autonomous agent receives a cryptographically verifiable on-chain identity linked to its verified developer and authorized capabilities.
Identity Registry
Maps Agent ID to deployer address, cryptographic public keys, and verifiable credential hashes.
Identity Gate & Enforcement
Pre-flight transaction and inter-agent validation against on-chain ERC-8004 ownerOf() with hot-wallet collision guards.
Reputation Registry
Anchors cryptographically signed compliance attestations and historic SLA uptime scores.
Validation Registry
Permits smart contract analyzers and auditor daemons to write tamper-proof security validation stamps.
Merkle Cortex State Anchoring
GuardianAI aggregates telemetry events into episodic memory batches, constructs a cryptographic Merkle tree, and periodically anchors the 32-byte root hash to the blockchain. Trees strictly follow RFC 6962 domain separation (using a 0x01 internal node prefix) and promote odd trailing leaves directly to parent tiers, completely preventing Bitcoin-style (CVE-2012-2459) duplicate-leaf collision and second-preimage attacks.
import { verifyMerkleProof } from "@guardianai/cortex";
// Verifies whether a security incident was recorded in block root #140293
const isValid = verifyMerkleProof({
leaf: "0x3f7a1...",
proof: ["0x8b2c...", "0x1e9a..."],
root: "0x94f0c8...",
});
console.log("Cryptographic Proof Valid:", isValid); // true
Insurance Certificates (GuardianInsuranceLedger)
The GuardianInsuranceLedger.sol smart contract anchors signed liability and insurance certificates for autonomous AI agents. The contract enforces a hard cap of 100,000 certificates per registry instance and is protected by a 24-hour OpenZeppelin Timelock.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IGuardianInsuranceLedger {
error CertificateLimitReached(uint256 maxCertificates);
function issueCertificate(
bytes32 agentId,
bytes32 policyHash,
uint256 coverageAmount,
uint256 expiration
) external returns (bytes32 certificateId);
}
Smart Contract Static Analyzer (48 Rules)
GuardianAI includes a purpose-built static analysis engine that validates EVM smart contracts against 48 AST/CFG-verified vulnerability classes before an autonomous agent interacts with them.
| Rule ID | Category | Engine | Description |
|---|---|---|---|
SWC-107 |
Reentrancy | Slither AST | State change after external call without reentrancy guard. |
SWC-112 |
Delegatecall Injection | Slither CFG | Uncontrolled delegatecall to user-supplied contract address. |
SWC-115 |
Authorization Flaw | AST Semantic | Missing tx.origin / msg.sender checks on privileged mint or drain functions. |
GRD-041 |
Approval Phishing | Bytecode Heuristic | Permit2 and universal approval traps designed to drain ERC-20 allowances. |
@guardianai/middleware TypeScript SDK
Drop-in middleware for TypeScript and JavaScript autonomous agent frameworks including ElizaOS and Viem wallet clients. Enforces pre-flight calldata decoding, memory poisoning defense, and policy compliance.
import { createGuardianSecurityPlugin, wrapViemWalletClient } from "@guardianai/middleware";
import { createWalletClient, http } from "viem";
import { monadTestnet } from "viem/chains";
// 1. ElizaOS Agent Plugin integration
export const agentConfig = {
plugins: [
createGuardianSecurityPlugin({
enclavePreset: "mera-passkey-prf",
failClosed: true,
policyGuardAddress: "0x90Fdc8E1e5C951701eCd84677038B38560CdEF60"
})
]
};
// 2. Viem Web3 Wallet Client wrapper
const rawClient = createWalletClient({
chain: monadTestnet,
transport: http("https://testnet-rpc.monad.xyz")
});
export const secureWallet = wrapViemWalletClient(rawClient, {
agentId: "0xagent_482c",
relayerUrl: "http://localhost:8546" // your GuardianAI relay (python -m guardian.web3sec.rpc_relay)
});
Python SDK & Decorators
The guardianai Python package provides asynchronous and synchronous decorators and clients for wrapping standard Python code.
from guardian import protect_agent
@protect_agent(firewall="strict", dlp=True, redact_keys=True)
async def autonomous_trading_agent(user_query: str):
# Safe execution context
return await llm.ainvoke(user_query)
OpenAI-Compatible Proxy Gateway
The gateway runs on port 8081 by default, accepting standard completions requests and injecting security inspection headers.
server:
host: "0.0.0.0"
port: 8081
upstream_url: "http://127.0.0.1:8080"
firewall:
preset: "balanced"
fail_closed: true
entropy_threshold: 4.8
max_body_bytes: 1048576 # 1MB request body limit
Telemetry & Event Pipeline
All security events, prompt classifications, and blocked attacks are logged into append-only JSONL files and streamed to the admin dashboard.
{
"event_id": "evt_98f410c8e2",
"timestamp": "2026-08-29T17:15:00Z",
"action": "BLOCK",
"rule_id": "INJ-011",
"layer": "Semantic classifier",
"latency_ms": 1.42,
"tenant_id": "default",
"client_ip": "198.51.100.24"
}
API Reference: Ingress Proxy
POST /v1/chat/completions
Sends a standard chat completion request through Guardian's 10-layer firewall.
| Header / Param | Type | Description |
|---|---|---|
Authorization |
Header (Bearer) | Your GuardianAI project API key or tenant JWT. |
model |
String (Body) | Target model (e.g. gpt-5.6, claude-opus-5, glm-5.3, deepseek-r1, o3-mini). |
messages |
Array (Body) | Array of message objects with role and content. |
Response Status Codes:
200 OK: Prompt passed all security layers; upstream model response returned.403 Forbidden: Attack detected and blocked. Response contains detailed rule match metadata.413 Payload Too Large: Request entity exceeded the 10MB gateway body ceiling (MAX_CONTENT_LENGTH).429 Too Many Requests: Rate limit exceeded (fail-closed protection triggered).
Backend Telemetry API
Access telemetry analytics and WebSocket threat streams via port 8001:
GET /api/v1/analytics- Summary statistics of blocked attacks and latency percentiles.GET /api/v1/events- Queryable security event history with pagination.GET /api/v1/export/json- Complete compliance audit log export.WebSocket /ws/threats- Live event stream with first-message JWT authentication.
Compliance & EU AI Act Article 15
GuardianAI automatically compiles compliance evidence artifacts required by regulatory frameworks, including Article 15 of the EU AI Act (Cybersecurity, Accuracy, and Robustness).
GET /api/v1/export/json.