Package Exports
- agentguard-js
Readme
AgentGuard JS SDK
Monitor and protect yourself with AI agent budget controls, approval workflows, and anomaly detection.
AgentGuard sits between your AI agent and its actions. Every action is validated before it runs, checking budgets, rate limits, and approval thresholds in real-time.
Install
npm install agentguard-jsQuick Start
import { AgentGuard } from 'agentguard-js';
const guard = new AgentGuard({
apiKey: 'ag_your_api_key', // Get this from app.agent-guard.io
});
// Wrap any async function for automatic protection
const chat = guard.wrap(
async (prompt: string) => await openai.chat({ prompt }),
{
action: 'openai_chat',
provider: 'openai',
model: 'gpt-4',
estimatedCost: 0.05,
getCost: (result) => result.usage.total_cost,
}
);
// This automatically:
// ✓ Checks if agent is active
// ✓ Checks budget limits
// ✓ Checks approval thresholds
// ✓ Runs your function (only if allowed)
// ✓ Logs the result
const result = await chat('Hello!');Core Methods
guard.wrap(fn, options) — Recommended
The easiest way to protect any function. Handles checking, execution, and logging automatically.
const sendEmail = guard.wrap(
async (to: string, body: string) => await emailService.send(to, body),
{
action: 'send_email',
estimatedCost: 0.01,
}
);
try {
await sendEmail('user@example.com', 'Hello!');
} catch (err) {
if (err instanceof BudgetExceededError) {
console.log('Budget exceeded — stopping agent');
}
if (err instanceof ApprovalRequiredError) {
console.log('Approval needed — waiting...');
}
}guard.check(input) — Pre-action validation
Check if an action is allowed before running it.
const check = await guard.check({
action: 'openai_chat',
estimatedCost: 0.05,
});
if (check.allowed) {
// Safe to proceed
const result = await openai.chat({ prompt: 'Hello' });
} else {
console.log('Blocked:', check.reason, check.message);
}guard.log(input) — Log an action
Log an action after it completes.
await guard.log({
action: 'api_call',
provider: 'openai',
model: 'gpt-4',
cost: 0.05,
status: 'SUCCESS',
request: { prompt: 'Hello' },
response: { completion: 'Hi there!' },
inputTokens: 10,
outputTokens: 25,
});guard.track(action) — Track duration
Start a timer and log when done.
const done = guard.track('openai_chat', { provider: 'openai' });
const result = await openai.chat({ prompt: 'Hello' });
await done({ cost: 0.05, response: result });
// Duration is calculated automaticallyBudget Management
// Get current budget status
const budget = await guard.getBudget();
console.log(`Spent: $${budget.budgetSpent} / $${budget.budgetLimit}`);
// Check if a specific cost is within budget
const check = await guard.checkBudget(0.50);
if (!check.allowed) {
console.log('Would exceed budget');
}
// Throw if over budget
await guard.ensureBudget(0.50); // throws BudgetExceededError if overApproval Workflows
// Request approval for a high-cost action
const approval = await guard.requestApproval({
action: 'send_bulk_email',
description: 'Send marketing email to 10,000 users',
estimatedCost: 45.00,
expiresInMinutes: 60,
});
// Wait for human decision (polls every 5 seconds)
try {
const decided = await guard.waitForApproval(approval.id, {
pollIntervalMs: 5000,
timeoutMs: 3600000, // 1 hour
});
console.log('Approved! Proceeding...');
} catch (err) {
console.log('Rejected or expired');
}Error Handling
AgentGuard throws specific errors you can catch:
import {
AgentGuardError, // Base error
AgentPausedError, // Agent is paused
AgentBlockedError, // Agent is blocked (kill switch)
BudgetExceededError, // Budget limit hit
ApprovalRequiredError // Needs human approval
} from 'agentguard-js';
try {
await chat('Hello!');
} catch (err) {
if (err instanceof AgentPausedError) {
// Agent was paused in the dashboard — stop gracefully
process.exit(0);
}
if (err instanceof BudgetExceededError) {
// Budget limit reached — wait for reset or increase
console.log('Budget exceeded, waiting for reset...');
}
if (err instanceof ApprovalRequiredError) {
// Action needs human approval
console.log('Waiting for approval:', err.approvalId);
}
}Configuration
const guard = new AgentGuard({
apiKey: 'ag_your_api_key', // Required
baseUrl: 'https://api.agent-guard.io', // Optional (default: AgentGuard API)
timeout: 10000, // Optional: request timeout in ms (default: 10000)
debug: false, // Optional: enable debug logging (default: false)
});Dashboard
Manage your agents, view logs, approve actions, and monitor budgets at app.agent-guard.io
Links
License
MIT