SDK Reference
Complete TypeScript/JavaScript SDK documentation for @tessorium/sdk
OVERVIEW
The Tessorium SDK provides three client classes for different use cases:
TessoriumUnifiedRECOMMENDEDSingle client supporting api, hybrid, and p2p modes
TessoriumP2PDirect P2P operations with full network access
TessoriumBrowserLightweight browser-optimized client
// Recommended: Use factory functions
import { createApiClient, createHybridClient } from '@tessorium/sdk';
// API-only mode
const apiClient = createApiClient(apiKey);
// Hybrid mode (recommended for production)
const hybridClient = createHybridClient(apiKey);
await hybridClient.start();CLIENT_CLASSES
TessoriumUnified
The main client class supporting all three operation modes.
import { TessoriumUnified } from '@tessorium/sdk';
const tessorium = new TessoriumUnified({
mode: 'hybrid', // 'api' | 'hybrid' | 'p2p'
apiKey: 'tsr_xxx', // Required for api/hybrid modes
apiBaseUrl: 'https://api.tessorium.ai',
bootstrapNodes: [], // For p2p mode
minTrustScore: 70, // Default threshold
cacheTTL: 300000, // 5 minutes
autoRate: true, // Auto-rate after interactions
debug: false
});
// Lifecycle
await tessorium.start(); // Required for hybrid/p2p
await tessorium.stop(); // CleanupCONFIGURATION
| Property | Type | Description |
|---|---|---|
mode* | 'api' | 'hybrid' | 'p2p' | Operation mode |
apiKey | string | Tessorium API key (required for api/hybrid) |
apiBaseUrl | string | API base URL (default: https://api.tessorium.ai) |
bootstrapNodes | string[] | P2P bootstrap nodes |
minTrustScore | number | Minimum trust threshold (default: 70) |
cacheTTL | number | Cache TTL in ms (default: 300000) |
autoRate | boolean | Auto-rate after interactions (default: true) |
debug | boolean | Enable debug logging (default: false) |
TessoriumP2P
Direct P2P client for decentralized operations.
import { TessoriumP2P } from '@tessorium/sdk/p2p';
const p2p = new TessoriumP2P({
mode: 'hybrid', // 'gateway' | 'hybrid' | 'p2p'
bootstrapNodes: [],
autoDiscovery: true,
enableRevocationSync: true,
gatewayUrl: 'https://api.tessorium.ai',
apiKey: 'tsr_xxx'
});
await p2p.start();
const trust = await p2p.verifyTrust('did:tessorium:agent:alice:v1');
await p2p.stop();TessoriumBrowser
Lightweight client optimized for browser environments.
import { TessoriumBrowser } from '@tessorium/sdk/browser';
const tessorium = new TessoriumBrowser({
apiKey: 'tsr_xxx',
mode: 'hybrid',
minTrustScore: 70,
cacheTTL: 300000,
timeout: 10000
});
const trust = await tessorium.verifyTrust('did:tessorium:agent:alice:v1');
// Cache management
tessorium.invalidate('did:tessorium:agent:alice:v1');
tessorium.clearCache();
const stats = tessorium.getCacheStats(); // { size, hits, misses }FACTORY_FUNCTIONS
Convenience functions for creating clients:
import {
createTessorium,
createApiClient,
createHybridClient
} from '@tessorium/sdk';
// Generic factory
const client = createTessorium({
mode: 'hybrid',
apiKey: 'tsr_xxx'
});
// API-only client (simplest)
const apiClient = createApiClient('tsr_xxx');
// Hybrid client (recommended)
const hybridClient = createHybridClient('tsr_xxx', {
minTrustScore: 80,
debug: true
});METHODS
verify()
Verify trust for an agent.
async verify(
did: string,
options?: VerificationOptions
): Promise<UnifiedTrustResult>
// Example
const trust = await tessorium.verify('did:tessorium:agent:alice:v1');
const trust = await tessorium.verify('alice'); // Short form also works
// With options
const trust = await tessorium.verify('alice', {
forceFresh: true, // Skip cache
timeoutMs: 5000, // Custom timeout
includeCollusionRisk: true // Include fraud signals
});verifyBatch()
Verify multiple agents in parallel.
async verifyBatch(dids: string[]): Promise<Map<string, UnifiedTrustResult>>
// Example
const results = await tessorium.verifyBatch([
'did:tessorium:agent:alice:v1',
'did:tessorium:agent:bob:v1',
'did:tessorium:agent:charlie:v1'
]);
for (const [did, trust] of results) {
console.log(`${did}: ${trust.score}`);
}verifyIdentity()
Complete identity verification with Ed25519 key.
async verifyIdentity(
privateKey: Uint8Array | crypto.KeyObject
): Promise<IdentityVerificationResult>
// Example
import crypto from 'crypto';
const { privateKey } = crypto.generateKeyPairSync('ed25519');
const result = await tessorium.verifyIdentity(privateKey);
console.log(result);
// {
// verified: true,
// did: 'did:tessorium:agent:my-agent:v1',
// identityScore: 50,
// trust: { score: 50, stage: 'provisional', ... },
// verifiedAt: '2026-02-08T...'
// }rate()
Submit a rating after an interaction.
async rate(
did: string,
rating: RatingInput
): Promise<void>
// Example
await tessorium.rate('did:tessorium:agent:alice:v1', {
outcome: 'success', // 'success' | 'failure' | 'partial'
dimensions: {
reliability: 5, // 1-5
quality: 5, // 1-5
speed: 4, // 1-5
communication: 5, // 1-5
safety: 5 // 1-5
},
wouldWorkAgain: true,
comment: 'Excellent service' // Optional, max 500 chars
});getAgent()
Get agent profile information.
async getAgent(agentId: string): Promise<Agent>
// Example
const agent = await tessorium.getAgent('alice');
console.log(agent);
// {
// id: 'uuid',
// tessoriumId: 'TSR-XXXX',
// name: 'Alice Agent',
// handle: 'alice',
// trustScore: 85,
// trustStage: 'established',
// ratingCount: 42,
// verified: true,
// ...
// }DISCOVERY_TOOL
The Discovery Tool enables Shadow AI auditing and continuous monitoring of AI agents in your environment.
runAudit()
Execute a comprehensive discovery audit across your infrastructure.
import { DiscoveryTool } from '@tessorium/sdk';
const discovery = new DiscoveryTool({
apiKey: process.env.TESSORIUM_API_KEY,
region: 'us-east-1' // Optional, for data residency
});
async runAudit(options: AuditOptions): Promise<AuditResult>
// Full example
const audit = await discovery.runAudit({
// Network ranges to scan
networks: ['10.0.0.0/8', '192.168.0.0/16'],
// Known API endpoints
endpoints: [
'https://api.openai.com',
'https://api.anthropic.com',
'https://generativelanguage.googleapis.com'
],
// Cloud provider integrations
clouds: ['aws', 'gcp', 'azure'],
// Analysis depth: 'quick' | 'standard' | 'comprehensive'
analysisDepth: 'comprehensive',
// Time limit in minutes
timeout: 30
});
// Result structure
console.log(audit);
// {
// id: 'audit-uuid',
// startedAt: '2026-02-08T...',
// completedAt: '2026-02-08T...',
// discoveredAgents: [...],
// unregisteredAgents: [...],
// riskyShadowAI: [...],
// overallRiskScore: 42,
// complianceGaps: [...],
// recommendations: [...]
// }checkForShadowAI()
Quick check for unregistered or unauthorized AI agents.
async checkForShadowAI(options?: ShadowAIOptions): Promise<ShadowAgent[]>
const shadowAgents = await discovery.checkForShadowAI({
// Only check specific sources
sources: ['network', 'logs', 'cloud'],
// Minimum risk level to report
minRiskLevel: 'medium'
});
// Each shadow agent includes:
// {
// identifier: 'openai-gpt4-unauthorized',
// discoverySource: 'network_traffic',
// firstSeen: '2026-02-01T...',
// lastSeen: '2026-02-08T...',
// requestCount: 1547,
// trustStatus: 'unverified',
// riskLevel: 'high',
// riskFactors: ['no_approval', 'sensitive_data_access'],
// recommendedAction: 'register_or_block'
// }createMonitor()
Set up continuous AI agent monitoring.
const monitor = discovery.createMonitor({
scanInterval: '1h', // How often to scan
alertThreshold: 'medium', // 'low' | 'medium' | 'high' | 'critical'
notifyChannels: ['slack', 'email', 'pagerduty']
});
// Event handlers
monitor.on('new-agent-detected', (agent) => { ... });
monitor.on('trust-change', (agent, oldScore, newScore) => { ... });
monitor.on('policy-violation', (violation) => { ... });
await monitor.start();
await monitor.stop();GATEWAY_PROXY
The Gateway Proxy provides zero-code trust enforcement as a reverse proxy or middleware.
createGatewayProxy()
Create a gateway proxy instance for programmatic control.
import { createGatewayProxy } from '@tessorium/sdk';
const gateway = createGatewayProxy({
apiKey: process.env.TESSORIUM_API_KEY,
// Trust requirements
minTrustScore: 70,
requireIdentityVerification: true,
blockUnverified: true,
// Actions requiring elevated trust
highRiskActions: {
minScore: 85,
actions: ['financial_transaction', 'data_export'],
requireHumanApproval: true
},
// Audit configuration
audit: {
logLevel: 'detailed', // 'minimal' | 'standard' | 'detailed'
retentionDays: 90,
includePayloads: false, // GDPR consideration
exportFormat: 'json'
},
// Rate limiting
rateLimit: {
maxRequestsPerMinute: 1000,
perAgent: true
}
});
// Start proxy server
await gateway.listen(8080);Express.js Middleware
Use as Express middleware for existing applications.
import express from 'express';
import { tessoriumMiddleware } from '@tessorium/sdk/express';
const app = express();
// Apply to all routes
app.use(tessoriumMiddleware({
apiKey: process.env.TESSORIUM_API_KEY,
minTrustScore: 70,
// Extract agent DID from request
extractAgentDid: (req) => req.headers['x-agent-did'],
// Custom policy per route
routePolicies: {
'/api/sensitive/*': { minTrustScore: 90 },
'/api/public/*': { minTrustScore: 0 }
}
}));
// Or apply to specific routes
app.post('/api/agent-action',
tessoriumMiddleware({ minTrustScore: 85 }),
async (req, res) => {
// Request only reaches here if trust verified
const trust = req.tessoriumTrust;
console.log(`Verified agent: ${trust.did}, score: ${trust.score}`);
}
);Next.js Middleware
Protect Next.js API routes and server actions.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createTessoriumMiddleware } from '@tessorium/sdk/next';
const tessorium = createTessoriumMiddleware({
apiKey: process.env.TESSORIUM_API_KEY!,
minTrustScore: 70
});
export async function middleware(request: NextRequest) {
// Only apply to agent API routes
if (request.nextUrl.pathname.startsWith('/api/agent/')) {
const result = await tessorium.verify(request);
if (!result.trusted) {
return NextResponse.json(
{ error: 'Trust verification failed', reason: result.reason },
{ status: 403 }
);
}
// Add trust info to headers for downstream use
const response = NextResponse.next();
response.headers.set('x-tessorium-trust-score', String(result.score));
response.headers.set('x-tessorium-trust-stage', result.stage);
return response;
}
return NextResponse.next();
}
export const config = {
matcher: '/api/agent/:path*'
};HUMAN_OVERSIGHT
Implement EU AI Act Article 14 compliant human oversight for high-risk AI operations.
createOversightLayer()
Create a human oversight layer for AI agent actions.
import { createOversightLayer } from '@tessorium/sdk';
const oversight = createOversightLayer({
apiKey: process.env.TESSORIUM_API_KEY,
// Actions requiring human approval
requireApproval: [
'financial_transaction',
'personal_data_processing',
'automated_decision',
'high_risk_classification'
],
// Approval workflow
workflow: {
// Who can approve
approvers: ['admin@company.com', 'compliance-team'],
// Approval timeout
timeoutMinutes: 60,
// Escalation if not approved
escalation: {
after: 30, // minutes
to: ['cto@company.com']
}
},
// Notification channels
notifications: {
slack: process.env.SLACK_WEBHOOK,
email: true
}
});requestReview()
Request human review for an AI action.
async requestReview(action: ActionRequest): Promise<ReviewResult>
// Example: Financial transaction requiring approval
const review = await oversight.requestReview({
action: 'financial_transaction',
agentDid: 'did:tessorium:agent:finance-bot:v1',
description: 'Transfer $50,000 to vendor account',
// Context for reviewer
context: {
vendor: 'Acme Corp',
invoiceId: 'INV-2026-001',
amount: 50000,
currency: 'USD'
},
// Priority affects notification urgency
priority: 'high',
// Optional: require specific approvers
requiredApprovers: ['finance-lead@company.com']
});
// Handle review result
if (review.status === 'approved') {
console.log(`Approved by: ${review.approvedBy}`);
console.log(`Approval notes: ${review.notes}`);
// Proceed with action
} else if (review.status === 'rejected') {
console.log(`Rejected by: ${review.rejectedBy}`);
console.log(`Rejection reason: ${review.reason}`);
// Handle rejection
} else if (review.status === 'timeout') {
// Escalation already triggered
console.log('Review timed out, escalation in progress');
}Audit Trail
Query oversight decisions for compliance reporting.
// Get oversight audit trail
const auditTrail = await oversight.getAuditTrail({
startDate: '2026-01-01',
endDate: '2026-02-08',
actions: ['financial_transaction'],
status: 'all' // 'approved' | 'rejected' | 'timeout' | 'all'
});
// Export for compliance
await auditTrail.exportCSV('./oversight-audit-q1-2026.csv');
// Generate compliance report
const report = await oversight.generateComplianceReport({
framework: 'EU_AI_ACT_ARTICLE_14',
period: 'Q1-2026'
});KILL_SWITCH
Emergency controls for immediately halting AI agent operations. Critical for incident response.
emergencyStop()
Immediately halt all operations for a specific agent or globally.
import { KillSwitch } from '@tessorium/sdk';
const killSwitch = new KillSwitch({
apiKey: process.env.TESSORIUM_API_KEY,
// Require confirmation for global stops
requireConfirmation: true,
// Notification on activation
notifyOnActivation: ['security@company.com', 'cto@company.com']
});
// Stop specific agent
async emergencyStop(target: string | StopOptions): Promise<StopResult>
await killSwitch.emergencyStop({
target: 'did:tessorium:agent:compromised:v1',
reason: 'Detected malicious behavior',
scope: 'agent', // 'agent' | 'publisher' | 'global'
duration: 'indefinite', // or '1h', '24h', etc.
notifyAgent: true // Send stop signal to agent
});
// Global emergency stop (requires confirmation)
await killSwitch.emergencyStop({
scope: 'global',
reason: 'Security incident - halting all AI operations',
confirmation: 'CONFIRM_GLOBAL_STOP'
});circuitBreaker()
Automatic circuit breaker based on error rates or anomaly detection.
// Configure automatic circuit breaker
const breaker = killSwitch.circuitBreaker({
// Trigger conditions
triggers: {
errorRate: {
threshold: 0.5, // 50% error rate
window: '5m', // Over 5 minute window
minRequests: 10 // Minimum requests to evaluate
},
anomalyScore: {
threshold: 0.9, // 90% anomaly confidence
detector: 'behavioral'
},
trustDrop: {
threshold: 20, // Trust score drops by 20+
window: '1h'
}
},
// Action when triggered
action: 'halt', // 'halt' | 'throttle' | 'alert'
// Auto-recovery
recovery: {
mode: 'manual', // 'manual' | 'auto'
autoRecoveryAfter: '30m'
}
});
// Event handlers
breaker.on('triggered', (event) => {
console.log(`Circuit breaker triggered: ${event.reason}`);
console.log(`Affected agents: ${event.affectedAgents.length}`);
});
breaker.on('recovered', (event) => {
console.log(`Circuit recovered: ${event.recoveryMode}`);
});
// Manual recovery
await breaker.recover('did:tessorium:agent:recovered:v1');
// Check status
const status = await breaker.getStatus();
// {
// state: 'open' | 'closed' | 'half-open',
// openedAt: '2026-02-08T...',
// reason: 'error_rate_exceeded',
// affectedAgents: [...]
// }TYPES
UnifiedTrustResult
| Property | Type | Description |
|---|---|---|
did | string | Agent DID |
trusted | boolean | 'caution' | Trust decision |
score | number | null | Composite trust score |
stage | TrustStage | Trust stage |
source | 'api' | 'p2p' | 'cache' | Data source |
latencyMs | number | Verification latency |
reason | string | Rejection reason (if not trusted) |
identityScore | number | Identity verification component |
reputationScore | number | Reputation-based component |
dimensions | DimensionScores | Rating dimensions |
TrustStage
type TrustStage =
| 'unverified' // No identity verification
| 'provisional' // Identity verified, no reputation
| 'new' // Starting to build reputation
| 'building' // Growing reputation
| 'established'; // Strong reputationERROR_HANDLING
import { TessoriumError, TessoriumApiError } from '@tessorium/sdk';
try {
const trust = await tessorium.verify('unknown-agent');
} catch (error) {
if (error instanceof TessoriumApiError) {
console.log(error.code); // 'AGENT_NOT_FOUND'
console.log(error.message); // 'Agent not found'
console.log(error.details); // Additional context
} else if (error instanceof TessoriumError) {
console.log(error.message); // Generic SDK error
}
}
// Error codes:
// - AGENT_NOT_FOUND
// - API_ERROR
// - INVALID_API_KEY
// - AGENT_FLAGGED
// - AGENT_BANNED
// - RATE_LIMIT_EXCEEDED