npm package: @provenonce/sdk
Description: Provenonce Beat SDK — Agent heartbeat client for sovereign time authentication
Latest version: 0.18.0

# @provenonce/sdk

Cryptographic identity and accountability SDK for AI agents. Chain-agnostic (Solana + Ethereum).

## Install

```bash
npm install @provenonce/sdk
```

## Registration

Before using the SDK, register your agent to get an API key:

```typescript
import { register } from '@provenonce/sdk';

// No-wallet registration (default — identity only)
const creds = await register('my-agent-v1', {
  registryUrl: 'https://provenonce.io',
  registrationSecret: process.env.REGISTRATION_SECRET, // required in production
});

console.log(creds.hash);    // unique agent identity
console.log(creds.api_key); // use this for BeatAgent
console.log(creds.secret);  // save — shown only once

// Operator wallet registration (Solana — bring your own wallet)
const withWallet = await register('my-org', {
  registryUrl: 'https://provenonce.io',
  walletModel: 'operator',
  walletAddress: '<your-solana-address>',
  walletSignFn: (msg) => signWithYourWallet(msg),
});

// Child registration (requires parent credentials)
const child = await register('worker-1', {
  registryUrl: 'https://provenonce.io',
  parentHash: creds.hash,
  parentApiKey: creds.api_key,
});
```

## Quick Start

```typescript
import { BeatAgent } from '@provenonce/sdk';
import { Connection, Keypair, SystemProgram, Transaction, PublicKey } from '@solana/web3.js';

const agent = new BeatAgent({
  apiKey: 'pvn_...',
  registryUrl: 'https://provenonce.io',
  verbose: true,
});

await agent.init();           // Initialize beat chain (birth in Logical Time)

// Purchase a SIGIL (cryptographic identity — required before heartbeating)
// Step 1: Send SOL to the ops wallet, get the tx signature
const sigilTx = await sendPayment(0.05); // see "Payment Flow" below
const sigil = await agent.purchaseSigil({
  identity_class: 'autonomous',
  principal: 'my-agent',
  tier: 'ind',
  payment_tx: sigilTx,
});

// Start heartbeating (paid liveness proofs)
// The callback must return a finalized Solana tx signature each interval
agent.startHeartbeat(async () => {
  return await sendPayment(0.0005); // heartbeat fee (tier 1)
});

// Submit VDF beats (free — extends your lifetime beat count)
const beats = await agent.submitBeats(100);
console.log(beats.total_beats);

// Get your Passport (latest lineage proof)
const passport = await agent.getPassport();
console.log(passport?.identity_class);     // 'autonomous'

agent.stopHeartbeat();
```

### Payment Flow

Provenonce verifies that the payment sender matches the agent's registered wallet.
Use any Solana library to send SOL to the ops wallet address:

```typescript
// Get the ops wallet address and fee schedule
const fees = await fetch('https://provenonce.io/api/v1/fees/summary').then(r => r.json());
const opsWallet = new PublicKey(fees.payment_address);

// Send payment (example using @solana/web3.js)
async function sendPayment(solAmount: number): Promise<string> {
  const connection = new Connection('https://api.devnet.solana.com', 'finalized');
  const lamports = Math.round(solAmount * 1e9);
  const tx = new Transaction().add(
    SystemProgram.transfer({ fromPubkey: yourWallet.publicKey, toPubkey: opsWallet, lamports }),
  );
  const sig = await connection.sendTransaction(tx, [yourWallet]);
  // Wait for finalization before passing to Provenonce
  await connection.confirmTransaction(sig, 'finalized');
  return sig;
}
```

### Beats vs Heartbeats

Two distinct systems — don't confuse them:

- **Beats** (`submitBeats()`) — Free VDF computation. Extends your persistent beat chain, credits "Lifetime Beats". Used for spawn eligibility.
- **Heartbeats** (`heartbeat()`) — Paid liveness proof. Requires SIGIL + SOL payment. Proves your agent is alive. Updates `heartbeat_count_epoch`.

## API

### `BeatAgent`

| Method | Description |
|--------|-------------|
| `init()` | Initialize the agent's Beat chain (birth in Logical Time) |
| `purchaseSigil(opts)` | Purchase a SIGIL identity (required for heartbeating) |
| `updateMetadata(fields)` | Update mutable SIGIL metadata fields |
| `heartbeat(paymentTx, globalAnchor?)` | Submit a paid heartbeat and receive a signed passport |
| `startHeartbeat(paymentTxFn)` | Start autonomous heartbeat loop |
| `stopHeartbeat()` | Stop heartbeat |
| `getPassport()` | Get latest passport (cached, no network call) |
| `getLatestPassport()` | Get latest passport (alias for getPassport) |
| `reissuePassport(paymentTx?)` | Reissue passport without extending lineage |
| `requestSpawn(name?)` | Spawn a child agent (requires accumulated beats) |
| `getStatus()` | Get full beat status from registry |
| `getLocalState()` | Get local state (no network call) |
| `submitBeats(count?)` | Submit VDF beats to extend lifetime beat count (free) |
| `static verifyPassportLocally(proof, pubKey)` | Verify a passport offline |

### `BeatAgentConfig`

| Option | Default | Description |
|--------|---------|-------------|
| `apiKey` | *required* | API key from registration (`pvn_...`) |
| `registryUrl` | *required* | Provenonce registry URL |
| `heartbeatIntervalSec` | `300` | Seconds between automatic heartbeats |
| `onHeartbeat` | — | Callback when heartbeat completes |
| `onError` | — | Callback on error |
| `onStatusChange` | — | Callback when status changes |
| `verbose` | `false` | Enable console logging |

### `register(name, options)`

| Option | Description |
|--------|-------------|
| `registryUrl` | Registry URL (required) |
| `registrationSecret` | Registration gate (mainnet) |
| `walletModel` | `'operator'` (opt-in BYO wallet) |
| `walletChain` | `'solana'` or `'ethereum'` |
| `walletAddress` | Ethereum BYO address |
| `walletSignFn` | Signing function for BYO wallets |
| `parentHash` | Parent hash (child registration) |
| `parentApiKey` | Parent's API key (child registration) |

Returns `RegistrationResult` with `hash`, `api_key`, `secret`, `wallet?`.

**Note:** Agent names should only contain `[a-zA-Z0-9_\-. ]`. Other characters are stripped by the server before signature verification.

### Phase 2 Types

```typescript
import type { Passport, IdentityClass, SigilResult, HeartbeatResult } from '@provenonce/sdk';

// Passport is the primary type. LineageProof is a deprecated alias (sunset 2026-09-01).
// Contains: agent_hash, agent_public_key, identity_class, lineage_chain_hash,
//           provenonce_signature, issued_at, valid_until, etc.

// IdentityClass = 'narrow_task' | 'autonomous' | 'orchestrator'
```

### `purchaseSigil(opts)` required fields

```typescript
await agent.purchaseSigil({
  identity_class: 'narrow_task' | 'autonomous' | 'orchestrator',
  principal: 'my-agent',
  tier: 'sov' | 'org' | 'ind' | 'eph' | 'sbx',
  payment_tx: 'solana-tx-signature...',
  name: 'optional-display-name'
});
```

### Error Handling

```typescript
import { ProvenonceError, AuthError, RateLimitError, FrozenError, ErrorCode } from '@provenonce/sdk';

try {
  await agent.heartbeat();
} catch (err) {
  if (err instanceof RateLimitError) {
    console.log(`Retry after ${err.retryAfterMs}ms`);
  } else if (err instanceof FrozenError) {
    console.log('Agent is frozen — heartbeat refused');
  } else if (err instanceof AuthError) {
    console.log('Invalid API key');
  }
}
```

## Framework Integration Examples

Ready-to-run examples for popular agent frameworks are in [`examples/`](./examples/):

| Framework | File | What it shows |
|-----------|------|---------------|
| **CrewAI** | [`crewai_example.py`](./examples/crewai_example.py) | Register a research crew with parent-child lineage |
| **AutoGen** | [`autogen_example.py`](./examples/autogen_example.py) | Coder + reviewer agents with post-run provenance audit |
| **LangGraph** | [`langgraph_example.py`](./examples/langgraph_example.py) | Pipeline nodes with on-chain audit trail |
| **Any (Node.js)** | [`add-provenonce.ts`](./examples/add-provenonce.ts) | 20-line generic integration |

Python examples use the REST API directly — no Python SDK needed. See [`examples/README.md`](./examples/README.md) for details.

## Links

- [Live prototype](https://provenonce.io)
- [npm package](https://www.npmjs.com/package/@provenonce/sdk)
- [API docs](https://provenonce.dev)
- [Whitepaper](https://provenonce.dev/whitepaper)