ALSORNDocs

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

terminal
npm install @alsorn/sdk

Quick Start

Create a client, register an agent, and query its trust score.

quickstart.ts
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

ParameterTypeRequiredDescription
apiKeystringrequiredYour Alsorn API key. Falls back to the ALSORN_API_KEY environment variable if not provided.
baseUrlstringoptionalBase URL for the API. Defaults to "https://api.alsorn.com". Override for sandbox or self-hosted deployments.
timeoutnumberoptionalRequest timeout in milliseconds. Defaults to 30000.
maxRetriesnumberoptionalMaximum number of automatic retries for failed requests. Defaults to 3.
config.ts
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.

agents/register.ts
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.

agents/list.ts
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.

agents/get.ts
const agent = await client.agents.get('agent_7f3k9x2m');console.log(agent.name, agent.status, agent.createdAt);

verify()

Verify an agent's cryptographic fingerprint.

agents/verify.ts
const result = await client.agents.verify('agent_7f3k9x2m');console.log(result.verified);     // trueconsole.log(result.fingerprint);  // sha256:9f86d08...

update()

Update an agent's configuration.

agents/update.ts
const agent = await client.agents.update('agent_7f3k9x2m', {  name: 'renamed-agent',  spendingLimit: 20000,});console.log(agent.name); // renamed-agent

suspend()

Suspend an active agent.

agents/suspend.ts
const agent = await client.agents.suspend('agent_7f3k9x2m');console.log(agent.status); // suspended

getAuditChain()

Retrieve the full audit chain for an agent.

agents/auditChain.ts
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.

trust/query.ts
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.

trust/evaluate.ts
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.

trust/batchQuery.ts
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.

trust/getHistory.ts
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.

trust/report.ts
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_g9h0i1j2k3

Transactions

Transaction methods are available on client.transactions.

execute()

Execute a new transaction between agents.

transactions/execute.ts
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... completed

list()

List transactions with optional filters.

transactions/list.ts
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.

transactions/get.ts
const tx = await client.transactions.get('tx_r4s5t6u7v8');console.log(tx.fromAgent, tx.toAgent, tx.amount, tx.status);

reverse()

Reverse a completed transaction.

transactions/reverse.ts
const reversal = await client.transactions.reverse('tx_r4s5t6u7v8', {  reason: 'Duplicate payment',});console.log(reversal.id, reversal.status); // tx_b4c5d6... reversed

export()

Export transactions as CSV or JSON.

transactions/export.ts
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.

webhooks/register.ts
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.

webhooks/list.ts
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.

webhooks/get.ts
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.

webhooks/update.ts
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.

webhooks/delete.ts
await client.webhooks.delete('wh_x1y2z3');

test()

Send a test event to a webhook endpoint.

webhooks/test.ts
const result = await client.webhooks.test('wh_x1y2z3');console.log(result.statusCode); // 200console.log(result.success);    // true

Error Handling

The SDK throws typed error classes for different failure conditions. Use instanceof checks to handle each case.

errorHandling.ts
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

The SDK automatically retries requests that fail with 429 (rate limited) or 5xx (server error) status codes, using exponential back-off. Customize this with the 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.

types.ts
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);