TypeScript SDK
The official TypeScript SDK for the Alsorn Protocol. It provides full type safety, automatic retries, and a promise-based API that works in Node.js 18+ and modern edge runtimes.
Installation
npm install @alsorn/sdkQuick Start
Create a client, register an agent, and query its trust score.
import { AlsornClient } from '@alsorn/sdk';
const client = new AlsornClient({ apiKey: 'als_your_api_key' });
// Register an agentconst agent = await client.agents.register({ name: 'order-fulfillment-agent', authorizedActions: ['execute_trade', 'transfer_funds'], spendingLimit: 10000, currency: 'USD', environment: 'sandbox',});
// Query trust scoreconst trust = await client.trust.query(agent.id);console.log(`Score: ${trust.score}, Assessment: ${trust.assessment}`);Client Configuration
The AlsornClient constructor accepts a configuration object with the following properties.
Constructor Options
| Parameter | Type | Required | Description |
|---|---|---|---|
| apiKey | string | required | Your Alsorn API key. Falls back to the ALSORN_API_KEY environment variable if not provided. |
| baseUrl | string | optional | Base URL for the API. Defaults to "https://api.alsorn.com". Override for sandbox or self-hosted deployments. |
| timeout | number | optional | Request timeout in milliseconds. Defaults to 30000. |
| maxRetries | number | optional | Maximum number of automatic retries for failed requests. Defaults to 3. |
const client = new AlsornClient({ apiKey: process.env.ALSORN_API_KEY!, baseUrl: 'https://sandbox.alsorn.com', timeout: 15000, maxRetries: 5,});Agents
All agent management methods are available on client.agents.
register()
Register a new agent on the protocol.
const agent = await client.agents.register({ name: 'data-pipeline-agent', authorizedActions: ['execute_trade'], spendingLimit: 5000, currency: 'USD', environment: 'production',});console.log(agent.id, agent.fingerprint);list()
List all agents in your organization.
const agents = await client.agents.list({ status: 'active', limit: 50 });for (const agent of agents) { console.log(agent.id, agent.name, agent.status);}get()
Retrieve a single agent by ID.
const agent = await client.agents.get('agent_7f3k9x2m');console.log(agent.name, agent.status, agent.createdAt);verify()
Verify an agent's cryptographic fingerprint.
const result = await client.agents.verify('agent_7f3k9x2m');console.log(result.verified); // trueconsole.log(result.fingerprint); // sha256:9f86d08...update()
Update an agent's configuration.
const agent = await client.agents.update('agent_7f3k9x2m', { name: 'renamed-agent', spendingLimit: 20000,});console.log(agent.name); // renamed-agentsuspend()
Suspend an active agent.
const agent = await client.agents.suspend('agent_7f3k9x2m');console.log(agent.status); // suspendedgetAuditChain()
Retrieve the full audit chain for an agent.
const chain = await client.agents.getAuditChain('agent_7f3k9x2m');for (const entry of chain) { console.log(entry.action, entry.timestamp, entry.actor);}Trust
Trust scoring methods are available on client.trust.
query()
Query the current trust profile for an agent.
const trust = await client.trust.query('agent_7f3k9x2m');console.log(trust.score); // 0–1000console.log(trust.assessment); // "Verified", "Moderate", or "High Risk"console.log(trust.factors); // { completionRate: 0.98, disputeRatio: 0.01, ... }evaluate()
Run a trust evaluation before executing a transaction.
const evaluation = await client.trust.evaluate({ agentId: 'agent_7f3k9x2m', action: 'transfer_funds', amount: 5000, currency: 'USD',});console.log(evaluation.allowed); // trueconsole.log(evaluation.reason); // "Trust score meets threshold"batchQuery()
Query trust scores for multiple agents at once.
const results = await client.trust.batchQuery([ 'agent_7f3k9x2m', 'agent_2b8m4p1q', 'agent_9c1n5r3s',]);for (const r of results) { console.log(r.agentId, r.score, r.assessment);}getHistory()
Get the trust score history for an agent.
const history = await client.trust.getHistory('agent_7f3k9x2m', { since: '2025-01-01T00:00:00Z',});for (const snapshot of history) { console.log(snapshot.timestamp, snapshot.score, snapshot.assessment);}report()
File a trust dispute against an agent.
const dispute = await client.trust.report({ agentId: 'agent_7f3k9x2m', reason: 'Agent did not deliver agreed-upon results.', evidenceIds: ['tx_r4s5t6u7v8'],});console.log(dispute.disputeId); // disp_g9h0i1j2k3Transactions
Transaction methods are available on client.transactions.
execute()
Execute a new transaction between agents.
const tx = await client.transactions.execute({ fromAgent: 'agent_7f3k9x2m', toAgent: 'agent_2b8m4p1q', action: 'transfer_funds', amount: 500, currency: 'USD', memo: 'Payment for data processing job',});console.log(tx.id, tx.status); // tx_abc123... completedlist()
List transactions with optional filters.
const txns = await client.transactions.list({ agentId: 'agent_7f3k9x2m', status: 'completed', limit: 25,});for (const tx of txns) { console.log(tx.id, tx.amount, tx.currency, tx.status);}get()
Retrieve a single transaction by ID.
const tx = await client.transactions.get('tx_r4s5t6u7v8');console.log(tx.fromAgent, tx.toAgent, tx.amount, tx.status);reverse()
Reverse a completed transaction.
const reversal = await client.transactions.reverse('tx_r4s5t6u7v8', { reason: 'Duplicate payment',});console.log(reversal.id, reversal.status); // tx_b4c5d6... reversedexport()
Export transactions as CSV or JSON.
import fs from 'fs';
const exportData = await client.transactions.export({ format: 'csv', since: '2025-01-01T00:00:00Z', until: '2025-06-01T00:00:00Z',});fs.writeFileSync('transactions.csv', exportData.content);Webhooks
Webhook management methods are available on client.webhooks.
register()
Register a new webhook endpoint.
const webhook = await client.webhooks.register({ url: 'https://example.com/webhooks/alsorn', events: ['agent.registered', 'transaction.completed'],});console.log(webhook.id); // wh_x1y2z3console.log(webhook.secret); // whsec_a1b2c3... (only returned once)list()
List all registered webhook endpoints.
const webhooks = await client.webhooks.list();for (const wh of webhooks) { console.log(wh.id, wh.url, wh.active);}get()
Retrieve a single webhook by ID.
const webhook = await client.webhooks.get('wh_x1y2z3');console.log(webhook.url, webhook.events, webhook.consecutiveFailures);update()
Update a webhook's URL or subscribed events.
const webhook = await client.webhooks.update('wh_x1y2z3', { events: ['agent.registered', 'transaction.completed', 'trust.score_changed'],});console.log(webhook.events);delete()
Delete a webhook endpoint.
await client.webhooks.delete('wh_x1y2z3');test()
Send a test event to a webhook endpoint.
const result = await client.webhooks.test('wh_x1y2z3');console.log(result.statusCode); // 200console.log(result.success); // trueError Handling
The SDK throws typed error classes for different failure conditions. Use instanceof checks to handle each case.
import { AlsornClient } from '@alsorn/sdk';import { AlsornError, AlsornRateLimitError, AlsornNotFoundError, AlsornAuthError, AlsornValidationError,} from '@alsorn/sdk/errors';
const client = new AlsornClient({ apiKey: 'als_your_api_key' });
try { const agent = await client.agents.get('agent_nonexistent');} catch (err) { if (err instanceof AlsornNotFoundError) { console.error(`Agent not found: ${err.message}`); } else if (err instanceof AlsornRateLimitError) { console.error(`Rate limited. Retry after ${err.retryAfter}s.`); } else if (err instanceof AlsornAuthError) { console.error(`Authentication failed: ${err.message}`); } else if (err instanceof AlsornValidationError) { console.error(`Invalid request: ${err.message}`); for (const fieldError of err.fieldErrors) { console.error(` ${fieldError.field}: ${fieldError.message}`); } } else if (err instanceof AlsornError) { console.error(`API error ${err.statusCode}: ${err.message}`); }}Automatic retries
maxRetries constructor option.TypeScript Types
The SDK exports all request and response types so you can use them in your own code. Import them from the main package or the dedicated types path.
import type { Agent, AgentRegistration, TrustProfile, TrustEvaluation, Transaction, TransactionExecution, Webhook, WebhookRegistration,} from '@alsorn/sdk/types';
// Use types in your own functionsasync function checkAgent( client: AlsornClient, agentId: string): Promise<{ agent: Agent; trust: TrustProfile }> { const [agent, trust] = await Promise.all([ client.agents.get(agentId), client.trust.query(agentId), ]); return { agent, trust };}
// Type-safe webhook registrationconst config: WebhookRegistration = { url: 'https://example.com/webhooks/alsorn', events: ['agent.registered', 'transaction.completed'],};const webhook: Webhook = await client.webhooks.register(config);