Search documentation

Search all documentation pages

JavaScript / TypeScript

Official TypeScript SDK for evaluating content, managing sessions, and polling reviews with the Aguardic API.

Installation

npm install @aguardic/sdk

Requires Node.js 18+. Zero dependencies — uses native fetch.

Quick Start

import Aguardic from "@aguardic/sdk";
 
const aguardic = new Aguardic("ag_live_xxxxx");
 
const result = await aguardic.evaluate({
  input: { content: "Transfer $50,000 to account 12345" },
  targetKey: "bank-transfer",
});
 
if (result.enforcementAction === "BLOCK") {
  console.log("Blocked:", result.violations);
}

Configuration

// Simple — API key only
const aguardic = new Aguardic("ag_live_xxxxx");
 
// Advanced — full options
const aguardic = new Aguardic({
  apiKey: "ag_live_xxxxx",
  baseUrl: "https://api.aguardic.com/v1", // default
  timeout: 30000, // default, in milliseconds
});

Evaluate Content

Send content for policy evaluation. The response tells you whether the content is allowed, warned, blocked, or requires approval.

const result = await aguardic.evaluate({
  input: { content: "User message to check" },
  targetKey: "chat-message",
  correlationId: "req-123",
});
 
switch (result.enforcementAction) {
  case "ALLOW":
    // Proceed normally
    break;
  case "WARN":
    console.log("Warnings:", result.violations);
    // Proceed with caution
    break;
  case "BLOCK":
    console.log("Blocked:", result.violations);
    // Stop execution
    break;
  case "APPROVAL_REQUIRED":
    // Poll for human approval
    const review = await aguardic.reviews.get(result.reviewRequestId!);
    break;
}

Parameters

FieldTypeDescription
inputrequired
Record<string, any>The content to evaluate
targetKey
stringRoute to specific policies by target key
targetMetadata
Record<string, any>Additional context for audit and notifications (not passed to rule evaluation)
correlationId
stringYour own ID for tracking
callbackUrl
stringWebhook URL for async results
sessionId
stringLink this evaluation to a session

Response

FieldTypeDescription
outcome
stringALLOW, DENY, or FLAG
enforcementAction
stringALLOW, WARN, BLOCK, or APPROVAL_REQUIRED
evaluationRunId
string or nullID of the evaluation run
reviewRequestId
string or nullID for approval polling (when APPROVAL_REQUIRED)
pollUrl
string or nullURL to poll for review status
sessionId
string or nullSession ID if provided
violations
Violation[]List of triggered policy violations

Session Management

Sessions track multi-step interactions like AI agent conversations. Each evaluation within a session builds up a history of actions, tools used, and data tags.

// Create a session
const session = await aguardic.sessions.create({
  metadata: { agentId: "support-bot", userId: "user-456" },
});
 
// Evaluate within the session
const result = await aguardic.evaluate({
  input: { tool: "send_email", to: "user@example.com" },
  sessionId: session.id,
  targetKey: "send_email",
});
 
// End the session
const summary = await aguardic.sessions.end(session.id, {
  status: "COMPLETED",
});
console.log("Actions:", summary.actionCount);
console.log("Tools used:", summary.toolsUsed);

Create Session Parameters

FieldTypeDescription
entityId
stringAssociate session with a governed entity for tracking and audit
externalSessionId
stringYour own session identifier
expiresAt
stringISO timestamp for auto-expiry
metadata
Record<string, any>Custom metadata

Review Polling

When an evaluation returns APPROVAL_REQUIRED, poll the review endpoint for a human decision.

const result = await aguardic.evaluate({
  input: { action: "delete_account", userId: "u-789" },
  targetKey: "destructive-action",
  correlationId: "my-request-123",
});
 
if (result.enforcementAction === "APPROVAL_REQUIRED") {
  // Poll by review ID
  const review = await aguardic.reviews.get(result.reviewRequestId!);
 
  // Or poll by your correlation ID
  const reviewByCorrelation = await aguardic.reviews.getByCorrelation("my-request-123");
 
  // review.status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'EXPIRED' | 'CANCELLED'
}

Error Handling

The SDK throws typed errors with status codes and structured error messages.

import {
  AguardicError,
  AuthenticationError,
  ValidationError,
  RateLimitError,
} from "@aguardic/sdk";
 
try {
  await aguardic.evaluate({ input: { content: "test" } });
} catch (error) {
  if (error instanceof AuthenticationError) {
    // 401 — invalid or expired API key
  } else if (error instanceof ValidationError) {
    // 400 — invalid request body
  } else if (error instanceof RateLimitError) {
    // 429 — too many requests
  } else if (error instanceof AguardicError) {
    // Any other API error
    console.log(error.statusCode, error.errors);
  }
}
FieldTypeDescription
ValidationError
400Invalid request parameters
AuthenticationError
401Invalid or missing API key
ForbiddenError
403Insufficient permissions
NotFoundError
404Resource not found
RateLimitError
429Rate limit exceeded
ServerError
500+Server-side error

TypeScript Types

All types are exported for use in your application:

import type {
  EvaluateParams,
  EvaluateResponse,
  Violation,
  Session,
  ReviewRequest,
} from "@aguardic/sdk";

Multiple Integrations

Each API key is scoped to a single integration and its bound policies. If you govern multiple systems — a chatbot, an internal tool, an email sender — create a separate integration for each and use a separate client instance:

import Aguardic from "@aguardic/sdk";
 
// Each integration has its own API key and policy bindings
const chatbot = new Aguardic(process.env.CHATBOT_API_KEY);
const codeReview = new Aguardic(process.env.CODE_REVIEW_API_KEY);
const emailSender = new Aguardic(process.env.EMAIL_API_KEY);
 
// Chatbot evaluations check PII + harmful content policies
const chatResult = await chatbot.evaluate({
  input: { role: "assistant", content: userMessage },
});
 
// Code review evaluations check secrets + security policies
const codeResult = await codeReview.evaluate({
  input: { diff: prDiff, files: changedFiles },
});

This keeps policy enforcement isolated — tuning chatbot rules won't affect your code review checks, and each integration has its own audit trail.

Use policy sets to share a common baseline (e.g., "Security Baseline") across multiple integrations without duplicating bindings.

Using Without the SDK

You can also use the REST API directly with any HTTP client:

const res = await fetch("https://api.aguardic.com/v1/evaluate", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    input: { content: "Hello" },
  }),
});
 
const json = await res.json();
const result = json.data; // responses are wrapped in { success, statusCode, data }

Next Steps