Docs/Core SDK/Initialization

Initialization

Initialize the Invariance SDK, generate Ed25519 keypairs, configure transport and observability, and manage the client lifecycle.

import { Invariance } from '@invariance/sdk';

Overview

The Invariance SDK is initialized through the static `Invariance.init()` factory method. This creates a configured client instance that manages transport (batching and flushing receipts to the API), observability (tracing, anomaly detection), and optional monitor polling.

Before initializing, you typically generate an Ed25519 keypair using `Invariance.generateKeypair()`. The private key is used to sign every receipt, creating a cryptographic audit trail. The public key is registered with the server so signatures can be verified independently.

The client uses a batched transport layer that queues receipts and flushes them periodically (default: every 5 seconds or 50 receipts). When you're done, call `inv.shutdown()` to flush remaining receipts and clean up timers.

Architecture

The Invariance class is a thin orchestrator that owns a Transport instance (HTTP batching), an InvarianceTracer (observability), and optional monitor polling. Sessions and agents are created through it but manage their own receipt chains independently.

Important Notes

Never expose your private key
The privateKey is used to sign receipts. Store it in environment variables or a secrets manager. Never commit it to source control or expose it in client-side code.
Always call shutdown()
Failing to call `inv.shutdown()` before your process exits may result in un-flushed receipts being lost. Use try/finally or process exit handlers.

Quick Example

Initialize and shut downtypescript
import { Invariance } from '@invariance/sdk';

// Generate a signing keypair (do this once, store securely)
const { privateKey, publicKey } = Invariance.generateKeypair();

// Initialize the SDK
const inv = Invariance.init({
  apiKey: 'dev_your_api_key',
  privateKey,
});

// ... use inv.session(), inv.wrap(), etc. ...

// Clean shutdown — flushes remaining receipts
await inv.shutdown();

Type Definitions

InvarianceConfig
interface InvarianceConfig {
  apiKey: string;
  apiUrl?: string;
  privateKey?: string;
  policies?: PolicyRule[];
  flushIntervalMs?: number;
  maxBatchSize?: number;
  maxQueueSize?: number;
  onError?: ErrorHandler;
  mode?: 'DEV' | 'PROD';
  sampleRate?: number;
  anomalyThreshold?: number;
  onAnomaly?: (node: TraceEvent) => void;
  devOutput?: 'ui' | 'console' | 'both';
  captureReplaySnapshots?: boolean;
  onMonitorTrigger?: (event: MonitorTriggerEvent) => void;
  monitorPollIntervalMs?: number;
}
Full configuration object for SDK initialization. Only apiKey is required.

API Reference

Invariance.init
Initialize the SDK with configuration. Returns a configured Invariance instance.
static init(config: InvarianceConfig): Invariance
Parameters
configInvarianceConfigSDK configuration object
ReturnsInvariance
Invariance.generateKeypair
Generate a new Ed25519 keypair for signing receipts.
static generateKeypair(): { privateKey: string; publicKey: string }
Returns{ privateKey: string; publicKey: string }
healthCheck
Check if the Invariance backend API is reachable.
async healthCheck(): Promise<boolean>
ReturnsPromise<boolean>
flush
Force-flush all batched receipts to the API immediately.
async flush(): Promise<void>
ReturnsPromise<void>
shutdown
Shut down the SDK: stop timers, stop monitor polling, and send all remaining batched receipts.
async shutdown(): Promise<void>
ReturnsPromise<void>

Walkthrough

Setting up Invariance from scratch
1
Install the SDK
Add @invariance/sdk to your project.
typescript
npm install @invariance/sdk
2
Generate a keypair
Generate an Ed25519 keypair. Do this once and store the private key securely.
typescript
import { Invariance } from '@invariance/sdk';

const { privateKey, publicKey } = Invariance.generateKeypair();
// Save privateKey to .env or secrets manager
3
Initialize the client
Create an Invariance instance with your API key and private key.
typescript
const inv = Invariance.init({
  apiKey: process.env.INVARIANCE_API_KEY!,
  privateKey: process.env.INVARIANCE_PRIVATE_KEY!,
  flushIntervalMs: 5000,
  maxBatchSize: 50,
  mode: 'PROD',
  onError: (err) => console.error('[Invariance]', err),
});
4
Verify connectivity
Confirm the SDK can reach the backend.
typescript
const healthy = await inv.healthCheck();
if (!healthy) throw new Error('Cannot reach Invariance API');
5
Shut down gracefully
Always shut down before your process exits.
typescript
process.on('SIGINT', async () => {
  await inv.shutdown();
  process.exit(0);
});

Configuration

OptionTypeDefaultDescription
apiKeystring(required)API key for authentication (dev_, org_, inv_, or agent key)
apiUrlstring"https://api.invariance.dev"Base URL for the Invariance API
privateKeystringundefinedEd25519 private key (64-char hex) for signing receipts
policiesPolicyRule[][]Local policy rules evaluated before recording
flushIntervalMsnumber5000How often to flush batched receipts (ms)
maxBatchSizenumber50Max receipts to batch before auto-flush
mode'DEV' | 'PROD''PROD'Observability mode — DEV captures everything, PROD samples

Error Handling

Error handling patterntypescript
import { InvarianceError } from '@invariance/sdk';

try {
  const inv = Invariance.init({ apiKey: '' });
} catch (err) {
  if (err instanceof InvarianceError) {
    console.error(err.code);    // 'INIT_FAILED'
    console.error(err.message); // 'apiKey is required'
  }
}

Use Cases

  • Initialize the SDK in your application entry point with API key and signing key
  • Generate keypairs for new agents or during onboarding
  • Configure batching intervals for high-throughput vs. low-latency use cases
  • Set up policy rules at initialization to enforce guardrails across all actions
On this page
OverviewArchitectureImportant NotesQuick ExampleType DefinitionsAPI ReferenceWalkthroughConfigurationError HandlingUse CasesRelated Modules