npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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.

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-sdk

Optional 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/core

Quick 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:

  1. Commitment binding -- SHA-256 hash proves action integrity without revealing content
  2. ECIES encryption -- Action, category, and financial amount encrypted to org's public key
  3. 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) or 503 (unavailable)
  • LangChain callback throws to abort tool execution
  • AutoGen proxy stores blocked messages for audit

License

MIT