Agents Framework (@veridex/agents)
A general-purpose TypeScript agent runtime with tools, hooks, memory, checkpoints, transports, policy-aware execution, response integrity seals, and execution accountability.
Installation
npm install @veridex/agents zodQuick Start
import { createAgent, tool, OpenAIProvider } from '@veridex/agents';
import { z } from 'zod';
const agent = createAgent(
{
name: 'my-agent',
description: 'A helpful assistant',
instructions: 'You are a helpful assistant.',
tools: [
tool({
name: 'greet',
description: 'Greet a user',
input: z.object({ name: z.string() }),
safetyClass: 'read',
async execute({ input }) {
return { success: true, llmOutput: `Hello, ${input.name}!` };
},
}),
],
},
{
modelProviders: {
default: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),
},
},
);
const result = await agent.run('Say hello to Alice');
console.log(result.output);Model Providers
Built-in providers for major LLM services:
| Provider | Class | Models |
|---|---|---|
| OpenAI | OpenAIProvider | GPT-4o, GPT-4, GPT-3.5 |
| Anthropic | AnthropicProvider | Claude 4 Opus, Sonnet, Haiku |
GeminiProvider | Gemini 2.5 Pro, Flash | |
| OpenAI-Compatible | OpenAICompatibleProvider | Any OpenAI-compatible endpoint |
import {
OpenAIProvider,
AnthropicProvider,
GeminiProvider,
OpenAICompatibleProvider,
} from '@veridex/agents';
const agent = createAgent(definition, {
modelProviders: {
default: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),
reasoning: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),
fast: new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY }),
local: new OpenAICompatibleProvider({
baseURL: 'http://localhost:11434/v1',
model: 'llama3',
}),
},
});Tools & Safety Classes
Every tool has a safety class that determines policy treatment:
import { tool, ToolSafetyClass } from '@veridex/agents';
const readTool = tool({
name: 'lookup_order',
description: 'Look up an order by ID',
input: z.object({ orderId: z.string() }),
safetyClass: 'read', // auto-allowed by default policy
async execute({ input }) {
return { success: true, llmOutput: `Order ${input.orderId}: shipped` };
},
});| Safety Class | Default Policy | Description |
|---|---|---|
read | Auto-allow | Read-only data access |
write | Auto-allow | State-modifying operations |
financial | Require approval | Money movement |
destructive | Block | Irreversible operations |
privileged | Block | Elevated-access operations |
Response Integrity (ResponseSeal)
Every LLM response is sealed with an HMAC chain-of-custody signature, ensuring tamper-evident provenance from model provider to final output.
import { createResponseSeal, verifyResponseSeal } from '@veridex/agents';
// Seals are created automatically during agent runs.
// To verify a seal manually:
const isValid = verifyResponseSeal(
seal,
rawResponseBytes,
apiKeyBytes,
);How It Works
- The model provider returns a raw response
ResponseSealderives a signing key via HKDF from the API key- HMAC-SHA256 is computed over the raw response bytes
- The seal is attached to
ModelResponse._sealand forwarded through the envelope
ResponseEnvelope
The full response envelope with chain-of-custody:
interface ResponseEnvelope {
runId: string;
turnIndex: number;
model: string;
provider: string;
output: string;
tokensUsed: { prompt: number; completion: number };
chainOfCustodySeal?: {
algorithm: string;
seal: string; // hex-encoded HMAC
rawHash: string; // SHA-256 of raw response
timestamp: number;
};
}Agent Identity
OIDC-A (OpenID Connect for Agents) and A-JWT (Agent JSON Web Tokens) for agentic identity:
interface AgentIdentityClaims {
iss: string; // Issuer
sub: string; // Agent ID
aud: string; // Audience
iat: number; // Issued at
exp: number; // Expires
scope: string[]; // Permissions
agentName: string;
agentVersion: string;
}
interface AgentIntegrityBinding {
agentId: string;
identityClaims: AgentIdentityClaims;
codeHash: string; // SHA-256 of agent code
configHash: string; // SHA-256 of agent configuration
toolManifestHash: string; // SHA-256 of registered tools
timestamp: number;
}Execution Accountability Graph
Track every execution as a directed acyclic graph of nodes and edges:
interface ExecutionNode {
id: string;
type: 'turn' | 'tool_call' | 'model_call' | 'policy_check' | 'approval';
timestamp: number;
data: Record<string, unknown>;
}
interface ExecutionEdge {
from: string;
to: string;
type: 'triggered' | 'required' | 'produced';
}
interface ExecutionGraph {
nodes: ExecutionNode[];
edges: ExecutionEdge[];
rootId: string;
}Data Sovereignty
Track PII exposure and jurisdictional compliance in tool contracts:
const userLookup = tool({
name: 'lookup_user',
description: 'Look up user profile',
input: z.object({ userId: z.string() }),
safetyClass: 'read',
ppiTags: ['name', 'email', 'address'], // PII categories this tool exposes
async execute({ input }) {
return { success: true, llmOutput: `User ${input.userId}: ...` };
},
});Sovereignty violations are automatically detected and reported when PII flows across jurisdictional boundaries.
Core Features & Advanced Examples
1. Multi-Tier Memory Management
The MemoryManager supports four independent tiers (working, episodic, semantic, procedural) to prevent drift and manage the agent's long-term recall without bloat.
import { MemoryManager, InMemoryStore } from '@veridex/agents';
const memory = new MemoryManager({
store: new InMemoryStore(),
decayRate: 0.05, // memory decay score per day
compactionThreshold: 10, // trigger compaction every 10 turns
});
// A. Working Memory: temporary scratchpad for the active run (auto-discarded)
await memory.setWorking('active_intent', 'payout_supplier_invoice');
// B. Episodic Memory: timestamped records of raw events, searchable via semantic index
await memory.writeEpisode({
content: 'User requested a payout status check for INV-2026.',
confidence: 0.95,
tags: ['billing', 'invoice']
});
// C. Semantic Memory: consolidated factual records with confidence scoring & provenance
await memory.commitFact({
subject: 'acme_operations',
fact: '0x742d... is the verified Acme recipient wallet on Base',
confidence: 1.0,
provenance: 'manually_declared_by_owner'
});
// D. Procedural Memory: learned routines or strict operations manuals
await memory.storeProcedure({
trigger: 'excessive_gas_spikes',
actions: ['suspend_non_urgent_swaps', 'notify_engineering_channel']
});2. Custom Rule Composition in the Policy Engine
You can easily register declarative policy checks or write custom verification functions. The engine intercepts every tool proposal before the model can execute it.
import { PolicyEngine, ToolProposal, RuleVerdict } from '@veridex/agents';
const engine = new PolicyEngine();
// Register a custom verification rule
engine.registerRule({
name: 'restrict_weekend_payments',
description: 'Requires human escalation for any financial operations proposed on weekends',
async evaluate(proposal: ToolProposal): Promise<RuleVerdict> {
const isWeekend = [0, 6].includes(new Date().getDay());
if (proposal.safetyClass === 'financial' && isWeekend) {
return {
verdict: 'escalate',
reason: 'Out-of-hours financial transactions require explicit administrator sign-off.'
};
}
return { verdict: 'allow' };
}
});3. MCP Server (Model Context Protocol) Integration
Expose your agent's tools securely to external hosts (like Claude Desktop, Cursor, or peer agents) using standard MCP transports.
import { MCPServerTransport, createAgent } from '@veridex/agents';
const agent = createAgent({
name: 'mcp-treasury-helper',
instructions: 'Expose local balance-checks and transfer tools over MCP.',
tools: [/* your safety-classed tools */]
});
// Initialize the native MCP Server transport
const mcpServer = new MCPServerTransport({
name: 'Veridex Treasury MCP Service',
version: '1.2.0',
agent
});
// Run over stdio (allows deep integration with any local developer environment)
await mcpServer.start();
console.log('Veridex MCP Server listening on standard I/O...');See the Veridex Agents Guide for a comprehensive tutorial covering all features.
Related
- API Reference — Full type signatures
- Veridex Agents Guide — Step-by-step tutorial
- Agent Security — Security gateway
- Agents Adapters — Framework interop
- Agents React — React hooks
- Agents Control Plane — Enterprise governance
For detailed guides, see: