chromia-guard-sdk
v1.1.1
Published
On-chain AI safety infrastructure for autonomous agents. Encrypts actions client-side, submits to Chromia blockchain, and gets AI safety verdicts before execution.
Maintainers
Readme
ChromiaGuard Agent SDK
On-chain AI safety infrastructure for autonomous agents. Every action is encrypted client-side, committed to the Chromia blockchain, and verified by AI before execution.
No plaintext ever touches the chain. Only SHA-256 commitments + ECIES-encrypted blobs are stored.
Installation
npm install chromia-guard-sdkOptional peer dependencies (install only if using the corresponding module):
# For easy.ts (zero-config key generation)
npm install @noble/curves
# For langchain.ts integration
npm install @langchain/coreQuick Start
Option 1: Zero-Config (Fastest)
import { protect } from "chromia-guard-sdk/easy";
const guard = await protect();
const ok = await guard.check("Transfer $500 USDC to 0xABC...");
if (ok) doTheThing();Keys are auto-generated and cached. Works in browser (localStorage) and Node.js (file).
Option 2: Full Control
import { ChromiaGuard } from "chromia-guard-sdk";
const guard = new ChromiaGuard({
nodeUrl: "https://node6.testnet.chromia.com:7740",
blockchainRid: "51C8405A...",
agentPrivKey: "your-secp256k1-private-key-hex",
orgEncryptionKey: "org-public-key-hex",
});
const result = await guard.judge("Transfer $500 USDC to 0xABC...");
if (result.allowed) {
executeTransfer();
} else {
console.log(`Blocked: ${result.reason} (${result.verdict})`);
}SDK Modules
| Module | Import | Use Case |
|--------|--------|----------|
| Core | chromia-guard-sdk | Full-featured SDK with sessions, compliance, risk reports |
| Easy | chromia-guard-sdk/easy | Zero-config onboarding -- 3 lines and you're protected |
| Direct | chromia-guard-sdk/direct | Direct on-chain access with commitment verification |
| LangChain | chromia-guard-sdk/langchain | LangChain tool + callback handler integration |
| AutoGen | chromia-guard-sdk/autogen | Microsoft AutoGen proxy agent + function wrapper |
| Middleware | chromia-guard-sdk/middleware | Express.js middleware with rate limiting + logging |
Core SDK
ChromiaGuard Class
The main SDK class. Handles client-side encryption, on-chain submission, and verdict polling.
import { ChromiaGuard } from "chromia-guard-sdk";
const guard = new ChromiaGuard({
nodeUrl: "https://node6.testnet.chromia.com:7740", // optional, defaults to env
blockchainRid: "51C8405A...", // required (or set CHROMIA_BLOCKCHAIN_RID)
agentPrivKey: "hex-private-key", // required -- signs transactions
orgEncryptionKey: "hex-public-key", // required -- ECIES encryption target
pollTimeoutMs: 60000, // optional, default 60s
pollIntervalMs: 2000, // optional, default 2s
});Environment Variables
The SDK supports these environment variables as fallbacks:
| Variable | Purpose |
|----------|---------|
| CHROMIA_NODE_URL | Chromia node URL |
| NEXT_PUBLIC_NODE_URL | Chromia node URL (Next.js) |
| NEXT_PUBLIC_CHROMIA_NODE_URL | Chromia node URL (Next.js alt) |
| CHROMIA_BLOCKCHAIN_RID | Blockchain RID |
| NEXT_PUBLIC_CHAIN_BRID | Blockchain RID (Next.js) |
| NEXT_PUBLIC_BLOCKCHAIN_RID | Blockchain RID (Next.js alt) |
Methods
| Method | Returns | Description |
|--------|---------|-------------|
| judge(action) | JudgeResult | Safety-check an action. Encrypts, submits, polls for AI verdict |
| createSession(durationMs?) | string | Create auth session token (default 1h) |
| registerAgent(pubkey) | boolean | Register agent under your org (admin only) |
| getComplianceScore(orgId, token) | ComplianceScoreResponse | Latest AIUC-1 compliance score |
| getAgentRisk(pubkey, token) | RawAgentRiskResponse | Privacy-safe agent risk report |
| getJudgment(id, token) | JudgmentDetails | Retrieve a specific judgment |
| generateAIUCReport(orgId, token, days?) | AIUCReport | Full AIUC-1 compliance report |
JudgeResult
interface JudgeResult {
allowed: boolean; // true = green/yellow, false = red
verdict: "green" | "yellow" | "red";
reason: string; // AI-generated explanation
judgmentId: string; // Unique ID (j-<32hex>)
onChain: boolean; // Always true for direct submissions
cached: boolean; // true if response_time_ms === 0
responseTimeMs: number; // AI inference time
}Easy SDK
Zero-config mode for fast agent onboarding. Keys are auto-generated and persisted.
import { protect } from "chromia-guard-sdk/easy";
const guard = await protect({
// All optional:
blockchainRid: "...", // defaults to testnet
nodeUrls: ["..."], // defaults to testnet node
orgEncryptionKey: "...", // defaults to agent's own pubkey
apiUrl: "...", // API fallback URL
});
// Simple boolean check
const ok = await guard.check("Send 1 ETH to 0x123...");
// Full result with details
const result = await guard.judge("Transfer $500 USDC");
// Get agent's public key
console.log(guard.pubKey);
// Get judgment history
const history = await guard.history(20);Fallback behavior: Tries direct chain submission first. If the agent key isn't whitelisted, automatically falls back to the hosted API endpoint.
Direct SDK
For agents that need full on-chain control and commitment verification.
import { ChromiaGuardDirect } from "chromia-guard-sdk/direct";
const guard = new ChromiaGuardDirect({
blockchainRid: "51C8405A...",
nodeUrl: "https://node6.testnet.chromia.com:7740",
signerPrivKey: "private-key-hex",
signerPubKey: "public-key-hex",
orgEncryptionKey: "org-public-key-hex",
});
// Create session for authenticated queries
const session = await guard.createSession();
// Judge an action
const result = await guard.judge("Transfer $500 USDC to 0xABC...");
// Verify commitment (proves you submitted that exact action)
const valid = await guard.verifyCommitment(session, result.judgmentId, "Transfer $500 USDC to 0xABC...");
// Get all your judgments
const judgments = await guard.getMyJudgments(session, 20, 0);
// Get privacy stats
const stats = await guard.getPrivacyStats();LangChain Integration
As a Tool
import { DynamicTool } from "@langchain/core/tools";
import { createChromiaGuardTool } from "chromia-guard-sdk/langchain";
const guard = new ChromiaGuard({ ... });
const safeTool = new DynamicTool(createChromiaGuardTool(guard));
// Add to your agent's tools array
const agent = new AgentExecutor({ tools: [safeTool, ...otherTools] });As a Callback (Auto-Intercept All Tools)
import { ChromiaGuardCallback } from "chromia-guard-sdk/langchain";
const callback = new ChromiaGuardCallback(guard);
const executor = AgentExecutor.fromAgentAndTools({
agent, tools,
callbacks: [callback],
});
// After execution, check stats
console.log(callback.getStats()); // { checked: 5, blocked: 1, passed: 4 }Wrap Any Function
import { withSafetyCheck } from "chromia-guard-sdk/langchain";
const safeTransfer = withSafetyCheck(
guard,
transferFunds,
(args) => `Transfer ${args.amount} ${args.token} to ${args.recipient}`
);
await safeTransfer({ amount: 500, token: "USDC", recipient: "0xABCD..." });AutoGen Integration
Safety Proxy Agent
import { ChromiaGuardProxyAgent } from "chromia-guard-sdk/autogen";
const proxy = new ChromiaGuardProxyAgent("safety-proxy", guard, {
systemPromptFilter: false, // skip system messages (default)
maxActionLength: 1000, // truncate long messages
failOpen: false, // fail-closed on errors (default, recommended)
});
// Validate a single message
const result = await proxy.validate({ content: "Send 5 ETH to 0xABC", role: "user" });
if (result.safe && result.message) {
executionAgent.receive(result.message);
}
// Filter a batch of messages
const safeMessages = await proxy.filterMessages(allMessages);
// Audit blocked messages
console.log(proxy.getBlockedMessages());
console.log(proxy.getStats()); // { checked: 10, blocked: 2, passed: 8, errors: 0 }Function Safeguard
import { safeguard } from "chromia-guard-sdk/autogen";
// Static description
const safeTransfer = safeguard(guard, transferFunds, "Transfer funds via API");
// Dynamic description
const safeSend = safeguard(guard, sendEmail, (args) => `Send email to ${args.to}`);Express.js Middleware
Basic Usage
import express from "express";
import { chromiaGuardMiddleware } from "chromia-guard-sdk/middleware";
const app = express();
app.use(express.json());
// Gate a single route
app.post("/execute",
chromiaGuardMiddleware(guard, (req) => req.body.command as string),
handler
);
// Gate all routes
app.use(chromiaGuardMiddleware(guard, (req) => {
return [req.method, req.path, JSON.stringify(req.body)].join(" ");
}));With Rate Limiting
import { chromiaGuardRateLimit } from "chromia-guard-sdk/middleware";
app.post("/execute",
chromiaGuardRateLimit(60), // 60 checks per IP per minute
chromiaGuardMiddleware(guard, (req) => req.body.command as string),
handler
);With Structured Logging
import { chromiaGuardLogging } from "chromia-guard-sdk/middleware";
app.use(chromiaGuardLogging(guard, actionExtractor, (entry) => {
// entry: { timestamp, ip, method, path, action, verdict, allowed, judgmentId, responseTimeMs }
myLogger.info("safety-check", entry);
}));Privacy Architecture
Agent Chromia Blockchain AI Judge
| | |
+-- SHA-256(action+orgKey+id) ----->| commitment (32 bytes) |
+-- ECIES(orgKey, action) --------->| encrypted blob |
+-- ECIES(orgKey, category) ------->| encrypted blob |
+-- ECIES(orgKey, amount) --------->| encrypted blob |
+-- sanitizePrompt(action) -------->| PII-stripped text ------->|
| | |
| |<-- verdict + reason -----|
|<-- poll result -------------------| |Three privacy layers:
- Commitment binding -- SHA-256 hash proves action integrity without revealing content
- ECIES encryption -- Action, category, and financial amount encrypted to org's public key
- PII sanitization -- Emails, phones, SSNs, cards, ETH addresses stripped before AI sees the prompt
Error Handling
All SDK methods follow a fail-closed policy:
- Empty/invalid input -> throws immediately
- Chain submission failure -> retries 3x with exponential backoff, then throws
- Polling timeout -> returns
{ allowed: false, verdict: "yellow" } - Network errors during polling -> silently retries (transient)
- Obfuscation detected -> throws (
sanitizeAndCheckEntropy)
The middleware and callback integrations extend this:
- Middleware returns
403(blocked) or503(unavailable) - LangChain callback throws to abort tool execution
- AutoGen proxy stores blocked messages for audit
License
MIT
