
Security News
Frontier AI Is Now Critical Infrastructure
The Fable shutdown shows how quickly model access can become a business continuity risk for AI-dependent engineering teams.
@governs-ai/sdk
Advanced tools
TypeScript SDK for GovernsAI - AI governance platform with unified memory service
A comprehensive TypeScript SDK for the GovernsAI platform, providing secure control over AI interactions, budget management, and policy enforcement.
npm install @governs-ai/sdk
import { GovernsAIClient, createClientFromEnv } from "@governs-ai/sdk";
// Create client from environment variables (all required)
// Requires: GOVERNS_API_KEY, GOVERNS_BASE_URL, GOVERNS_ORG_ID
const client = createClientFromEnv();
// Or create client with explicit configuration (both URLs required)
const client = new GovernsAIClient({
apiKey: "your-api-key",
baseUrl: "https://your-platform-url", // platform APIs
precheckBaseUrl: "https://your-precheck-url", // precheck-only APIs
orgId: "org-456", // Organization context (static)
});
// Test connection
const isConnected = await client.testConnection();
console.log("Connected:", isConnected);
// Precheck a request
const precheckResponse = await client.precheck(
{
tool: "model.chat",
scope: "net.external",
raw_text: "Hello, how are you?",
payload: { messages: [{ role: "user", content: "Hello" }] },
tags: ["demo", "chat"],
},
);
if (precheckResponse.decision === "deny") {
console.log("Request blocked:", precheckResponse.reasons);
} else if (precheckResponse.decision === "confirm") {
console.log("Confirmation required");
// Handle confirmation flow...
} else {
console.log("Request allowed");
// Proceed with AI call...
}
# Required
GOVERNS_API_KEY=your-api-key
GOVERNS_BASE_URL=https://your-platform-url
GOVERNS_PRECHECK_BASE_URL=https://your-precheck-url
GOVERNS_ORG_ID=org-456
# Optional
GOVERNS_TIMEOUT=30000
GOVERNS_RETRIES=3
GOVERNS_RETRY_DELAY=1000
const client = new GovernsAIClient({
apiKey: "your-api-key",
baseUrl: "https://your-platform-url",
orgId: "org-456",
timeout: 30000,
retries: 3,
retryDelay: 1000,
});
Validate requests before AI operations:
// Check a chat message
const precheckResponse = await client.precheck({
tool: 'model.chat',
scope: 'net.external',
raw_text: 'Hello, how are you?',
payload: { messages: [{ role: 'user', content: 'Hello' }] },
tags: ['demo', 'chat'],
}, 'user-123');
// Check a tool call (via PrecheckClient)
const toolPrecheck = await client.precheckClient.checkToolCall(
'weather_current',
{ latitude: 52.52, longitude: 13.41, location_name: 'Berlin' },
'net.external',
undefined
);
// Handle different decisions
switch (precheckResponse.decision) {
case 'allow':
// Proceed with AI call
break;
case 'deny':
// Block the request
console.log('Request blocked:', precheckResponse.reasons);
break;
case 'confirm':
// Require user confirmation
const confirmation = await client.confirm(
'correlation-id',
'chat',
'Chat request',
{ messages: [...] },
precheckResponse.reasons
);
break;
case 'redact':
// Use redacted content
const redactedContent = precheckResponse.content;
break;
}
Handle user approval for sensitive operations:
// Create confirmation request
const confirmation = await client.confirm(
"correlation-id",
"tool_call",
"Execute payment tool",
{ tool: "payment_process", args: { amount: 99.99 } },
["High risk operation"]
);
// Poll for approval
await client.pollConfirmation(
confirmation.confirmation.correlationId,
(status) => {
console.log("Confirmation status:", status);
}
);
// Wait for approval
const approvedConfirmation = await client.confirmationClient.waitForApproval(
confirmation.confirmation.correlationId,
{
interval: 2000,
timeout: 300000,
onStatusChange: (status) => console.log("Status:", status),
}
);
Track and manage AI usage costs:
// Get budget context (identity derived from auth)
const budgetContext = await client.getBudgetContext();
console.log("Remaining budget:", budgetContext.remaining_budget);
// Check if budget allows a cost
const budgetStatus = await client.budgetClient.checkBudget(50.0);
if (!budgetStatus.allowed) {
console.log("Insufficient budget:", budgetStatus.reason);
}
// Record usage after AI call (v1 payload)
await client.recordUsage({
toolId: "chat",
model: "gpt-4",
tokensIn: 100,
tokensOut: 50,
cost: 0.15,
metadata: { correlationId: "corr-123" },
});
// Get spend analytics
const spendData = await client.analyticsClient.getSpendAnalytics("30d");
console.log("Total spend:", spendData.spend.totalSpend);
console.log("Monthly spend:", spendData.spend.monthlySpend);
console.log("Over budget:", spendData.spend.isOverBudget);
Register and manage tools:
// Register tools
const tools = [
{
type: "function",
function: {
name: "weather_current",
description: "Get current weather for a location",
parameters: {
type: "object",
properties: {
latitude: { type: "number", description: "Latitude coordinate" },
longitude: { type: "number", description: "Longitude coordinate" },
},
required: ["latitude", "longitude"],
},
},
},
];
await client.toolsClient.registerTools(tools);
// Execute tool with governance checks
const toolResult = await client.toolsClient.executeTool("weather_current", {
latitude: 52.52,
longitude: 13.41,
});
// Get tool metadata
const metadata = await client.toolsClient.getToolMetadata("weather_current");
console.log("Risk level:", metadata.metadata.risk_level);
Get comprehensive analytics and reporting:
// Get decision analytics
const decisions = await client.analyticsClient.getDecisions({
timeRange: "30d",
includeStats: true,
});
console.log("Total decisions:", decisions.stats.total);
console.log("By decision:", decisions.stats.byDecision);
// Get spend analytics
const spendData = await client.analyticsClient.getSpendAnalytics("30d");
console.log("Spend breakdown:", {
total: spendData.spend.totalSpend,
monthly: spendData.spend.monthlySpend,
byTool: spendData.spend.toolSpend,
byModel: spendData.spend.modelSpend,
});
// Get usage records
const usageRecords = await client.analyticsClient.getUsageRecords({
startDate: "2024-01-01",
endDate: "2024-01-31",
limit: 100,
});
// Get comprehensive dashboard data
const dashboardData = await client.analyticsClient.getDashboardData(
"org-slug",
"30d"
);
// Search context
const results = await client.searchContext({
query: 'project spec',
scope: 'user',
limit: 20,
});
// Get recent conversation context
const contexts = await client.getRecentContext({
userId: 'user-123',
limit: 20,
scope: 'user',
});
// Store context
const saved = await client.context.storeContext({
content: 'Discussion summary...',
contentType: 'user_message',
agentId: 'agent-1',
visibility: 'private',
});
For external applications that want to use their own user IDs:
// Store memory for your external user
// User will be auto-created if they don't exist
await client.context.storeMemory({
externalUserId: 'shopify-user-456',
externalSource: 'shopify', // Your application name
content: 'User prefers blue widgets and express shipping',
agentId: 'product-recommendations',
metadata: {
source: 'checkout-page',
timestamp: new Date().toISOString()
}
});
// Search memories for your external user
const results = await client.context.searchMemory({
externalUserId: 'shopify-user-456',
externalSource: 'shopify',
query: 'shipping preferences',
limit: 10
});
console.log('Found memories:', results.memories);
// Optional: Resolve external user to internal ID
const resolved = await client.context.resolveUser({
externalUserId: 'shopify-user-456',
externalSource: 'shopify',
email: 'user@example.com', // Optional for auto-creation
name: 'John Doe' // Optional for auto-creation
});
console.log('Internal ID:', resolved.internalUserId);
console.log('Was created:', resolved.created);
Key Features:
// Upload a document (sync by default)
const upload = await client.documents.uploadDocument({
externalUserId: 'customer-123',
externalSource: 'support-portal',
file: myFileBuffer,
filename: 'invoice.pdf',
metadata: { caseId: 'case-456' },
});
console.log('Document status:', upload.status, upload.documentId);
// Optionally upload async (requires Redis + DOCUMENT_PROCESSING_MODE=async)
await client.documents.uploadDocument({
externalUserId: 'customer-123',
externalSource: 'support-portal',
file: myFileBuffer,
filename: 'receipt.pdf',
processingMode: 'async',
});
// Check status + chunks
const document = await client.documents.getDocument(upload.documentId, {
includeChunks: true,
});
// List documents
const list = await client.documents.listDocuments({
externalUserId: 'customer-123',
externalSource: 'support-portal',
limit: 25,
});
// Search across document chunks
const results = await client.documents.searchDocuments({
externalUserId: 'customer-123',
externalSource: 'support-portal',
query: 'refund policy',
limit: 5,
});
// Delete a document
await client.documents.deleteDocument(upload.documentId);
const { policies } = await client.getPolicies();
The SDK provides comprehensive error handling with retry logic:
import { GovernsAIError, PrecheckError, BudgetError } from "@governs-ai/sdk";
try {
const response = await client.precheck(request, 'user-123');
} catch (error) {
if (error instanceof PrecheckError) {
console.error("Precheck failed:", error.message);
} else if (error instanceof BudgetError) {
console.error("Budget error:", error.message);
} else if (error instanceof GovernsAIError) {
console.error("SDK error": error.message);
}
}
// Configure retry behavior
client.updateConfig({
retries: 5,
retryDelay: 2000,
});
// Use with custom retry logic
await client.withRetry(async () => {
return await client.precheck(request);
}, "custom operation");
// Batch precheck multiple requests
const requests = [
{ tool: "model.chat", scope: "net.external", raw_text: "Hello" },
{ tool: "weather_current", scope: "net.external", raw_text: "Weather" },
];
const results = await client.precheckClient.checkBatch(requests);
// Batch tool execution
const toolCalls = [
{ tool: "weather_current", args: { latitude: 52.52, longitude: 13.41 } },
{ tool: "payment_process", args: { amount: 99.99 } },
];
const toolResults = await client.toolsClient.executeBatchTools(toolCalls);
// Check service health
const healthStatus = await client.getHealthStatus();
console.log("Platform status:", healthStatus.status);
console.log("Services:", healthStatus.services);
// Test individual services
const precheckStatus = await client.precheckClient.getServiceStatus();
const budgetStatus = await client.budgetClient.getServiceStatus();
See the examples/ directory for complete usage examples:
basic-usage.ts - Basic SDK functionalitychat-integration.ts - Chat application integrationtool-calling.ts - Tool calling with governancedashboard-analytics.ts - Analytics and reportingMain client class that orchestrates all SDK functionality.
precheck(request: PrecheckRequest, userId: string): Promise<PrecheckResponse>getBudgetContext(userId: string): Promise<BudgetContext>recordUsage(usage: UsageRecord): Promise<void>confirm(...): Promise<ConfirmationResponse>getConfirmationStatus(correlationId: string): Promise<ConfirmationStatus>pollConfirmation(...): Promise<void>testConnection(): Promise<boolean>getHealthStatus(): Promise<HealthStatus>The SDK provides comprehensive TypeScript definitions for all types, interfaces, and methods. All API responses and request parameters are fully typed.
import {
PrecheckRequest,
PrecheckResponse,
BudgetContext,
UsageRecord,
Decision,
Tool,
Message,
} from "@governs-ai/sdk";
MIT License - This SDK is fully open source with no restrictions.
You can:
See LICENSE file for details.
This SDK is part of the GovernsAI open-core ecosystem:
Learn more: GovernsAI Licensing
For support and questions:
FAQs
TypeScript SDK for GovernsAI - AI governance platform with unified memory service
We found that @governs-ai/sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
The Fable shutdown shows how quickly model access can become a business continuity risk for AI-dependent engineering teams.

Security News
AI agents are pulling packages into environments no scanner is watching, creating exposure before security teams can see it.

Security News
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.