npm package: @gamma23/sdk
Description: Official TypeScript SDK for the Gamma23 agent payments API
Author: Gamma23
Latest version: 0.1.0

# @gamma23/sdk

Official TypeScript SDK for the **Gamma23** agent payments API. Give your AI agents the ability to spend money safely — with budgets, policy guardrails, and full auditability.

## Installation

```bash
npm install @gamma23/sdk
```

```bash
pnpm add @gamma23/sdk
```

```bash
yarn add @gamma23/sdk
```

> **Requirements:** Node.js 18+ (uses native `fetch`)

## Quick Start

```typescript
import { Gamma23 } from '@gamma23/sdk';

const gamma23 = new Gamma23({
  apiKey: process.env.GAMMA23_API_KEY!, // gm23_...
});

// 1. Create a spend intent
const intent = await gamma23.spendIntents.create({
  goal: 'Purchase cloud compute credits',
  budget: 50.00,
  currency: 'USD',
  merchant: 'AWS',
  category: 'cloud_compute',
});

console.log(`Intent ${intent.id}: ${intent.status}`);
// Intent si_abc123: APPROVED

// 2. Execute the approved intent
if (intent.spendToken) {
  const result = await gamma23.spendIntents.execute(intent.id, {
    spendToken: intent.spendToken,
    mode: 'LIVE',
  });

  console.log(`Transaction ${result.transactionId}: $${result.amount}`);
}
```

## Configuration

```typescript
const gamma23 = new Gamma23({
  apiKey: 'gm23_...',          // Required — your API key
  baseUrl: 'https://...',      // Optional — defaults to GAMMA23_API_URL env var or https://gamma23.app
  timeout: 30_000,             // Optional — request timeout in ms (default: 30s)
  maxRetries: 3,               // Optional — retry count for 429/5xx (default: 3)
});
```

## API Reference

### Spend Intents

Spend intents are the core primitive — they represent an agent's *intent* to spend money, subject to policy evaluation.

#### `spendIntents.create(params)`

Create a new spend intent for policy evaluation.

```typescript
const intent = await gamma23.spendIntents.create({
  goal: 'Book a flight to SF',
  budget: 500,
  currency: 'USD',          // optional, defaults to USD
  merchant: 'United',       // optional
  category: 'travel',       // optional
  domain: 'united.com',     // optional
  metadata: { trip: 'Q1' }, // optional, arbitrary metadata
  idempotencyKey: 'uniq-1', // optional, prevents duplicate creation
});
```

**Returns:** `SpendIntent`

| Field | Type | Description |
|-------|------|-------------|
| `id` | `string` | Unique intent identifier |
| `status` | `SpendIntentStatus` | `PENDING`, `APPROVED`, `DENIED`, `EXECUTED`, `CANCELLED`, `EXPIRED` |
| `goal` | `string` | What the agent wants to buy |
| `budget` | `number` | Maximum spend amount |
| `currency` | `string` | ISO 4217 currency code |
| `selectedRail` | `string \| null` | Payment rail selected by policy |
| `policyDecision` | `string \| null` | Policy engine decision details |
| `spendToken` | `string` | Token required to execute (present when approved) |
| `executeUrl` | `string` | URL to execute the intent |
| `tokenExpiresInSeconds` | `number` | Time until token expires |
| `spendRequestId` | `string` | Associated spend request ID |

#### `spendIntents.get(id)`

Retrieve a spend intent by ID.

```typescript
const intent = await gamma23.spendIntents.get('si_abc123');
```

#### `spendIntents.cancel(id)`

Cancel a pending or approved spend intent.

```typescript
const cancelled = await gamma23.spendIntents.cancel('si_abc123');
```

#### `spendIntents.execute(id, params)`

Execute an approved spend intent.

```typescript
const result = await gamma23.spendIntents.execute('si_abc123', {
  spendToken: intent.spendToken!,
  mode: 'LIVE', // MANUAL | MOCK | SIMULATED | LIVE
});
```

**Returns:** `ExecuteResult`

| Field | Type | Description |
|-------|------|-------------|
| `intentId` | `string` | The intent that was executed |
| `transactionId` | `string` | Unique transaction identifier |
| `status` | `string` | Transaction status |
| `amount` | `number` | Amount charged |
| `currency` | `string` | Currency of the charge |
| `riskFlags` | `string[]` | Any risk flags raised |
| `isSimulated` | `boolean` | Whether this was a simulation |
| `stripeIntentId` | `string` | Stripe PaymentIntent ID (if applicable) |
| `instructions` | `string` | Manual execution instructions (if MANUAL mode) |
| `message` | `string` | Human-readable status message |

---

### Payments

Direct payment requests, bypassing the intent flow.

#### `payments.create(params)`

```typescript
const payment = await gamma23.payments.create({
  amount: 25.00,
  merchant: 'Stripe',
  domain: 'stripe.com',
  category: 'saas',
  reason: 'Monthly subscription',
  evidenceLinks: ['https://example.com/invoice.pdf'],
  idempotencyKey: 'pay-001',
});
```

#### `payments.execute(id, params)`

```typescript
const result = await gamma23.payments.execute(payment.id, {
  spendToken: '...',
  mode: 'LIVE',
});
```

---

### Agents

#### `agents.getBudget(agentId)`

Get the current budget status for an agent.

```typescript
const budget = await gamma23.agents.getBudget('agent_abc');

console.log(`Remaining: $${budget.remainingBudget}`);
console.log(`Utilization: ${budget.budgetUtilizationPct}%`);
console.log(`Can spend: ${budget.canSpend}`);
```

**Returns:** `AgentBudget`

| Field | Type | Description |
|-------|------|-------------|
| `agentId` | `string` | Agent identifier |
| `agentName` | `string` | Human-readable agent name |
| `monthlyBudget` | `number` | Total monthly budget |
| `currentSpend` | `number` | Amount spent this period |
| `remainingBudget` | `number` | Budget remaining |
| `budgetUtilizationPct` | `number` | Percentage of budget used |
| `canSpend` | `boolean` | Whether the agent can still spend |

---

## Error Handling

All API errors throw a `Gamma23Error` with structured fields:

```typescript
import { Gamma23, Gamma23Error, Gamma23TimeoutError } from '@gamma23/sdk';

try {
  await gamma23.spendIntents.create({ goal: '...', budget: 100 });
} catch (err) {
  if (err instanceof Gamma23Error) {
    console.error(`Status: ${err.status}`);        // HTTP status code
    console.error(`Code: ${err.code}`);             // API error code
    console.error(`Message: ${err.message}`);       // Human-readable message
    console.error(`Request ID: ${err.requestId}`);  // For support tickets
  }

  if (err instanceof Gamma23TimeoutError) {
    console.error('Request timed out — try increasing the timeout');
  }
}
```

### Error Types

| Class | When |
|-------|------|
| `Gamma23Error` | Any non-2xx API response |
| `Gamma23TimeoutError` | Request exceeded timeout |
| `Gamma23ConnectionError` | Network / DNS failure |

---

## Retry Behavior

The SDK automatically retries on transient failures (HTTP 429, 5xx) with exponential backoff:

| Attempt | Delay |
|---------|-------|
| 1st retry | ~1s + jitter |
| 2nd retry | ~2s + jitter |
| 3rd retry | ~4s + jitter |

Customize via `maxRetries`:

```typescript
const gamma23 = new Gamma23({
  apiKey: '...',
  maxRetries: 5, // up to 5 retries
});
```

Set `maxRetries: 0` to disable retries entirely.

---

## TypeScript

This SDK is written in TypeScript and ships with full type declarations. All request params and response types are exported:

```typescript
import type {
  CreateSpendIntentParams,
  SpendIntent,
  ExecuteResult,
  AgentBudget,
} from '@gamma23/sdk';
```

## License

MIT