npm package: @gpt-core/admin
Description: TypeScript SDK for GPT Core Admin API - Platform administration and ISV management
Author: GPT Integrators
Latest version: 0.11.2

# @gpt-core/admin

The official TypeScript Admin SDK for the GPT Core Platform - platform administration, webhook management, and system monitoring.

[![npm version](https://img.shields.io/npm/v/@gpt-core/admin.svg)](https://www.npmjs.com/package/@gpt-core/admin)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

⚠️ **This SDK requires admin privileges and should only be used in secure server environments.**

---

<!-- AI_CONTEXT_START
This SDK provides TypeScript bindings for GPT Core ADMIN operations.
Use this for: webhooks, storage admin, account credits, bulk operations, API key management.
NOT for: user-facing operations (use @gpt-core/client instead).
SECURITY: Server-side only. Never expose admin tokens in client code.

Quick patterns:
- Initialize: new GptAdmin({ baseUrl, token, applicationId? })
- Webhooks: admin.webhooks.configs.list() / .create(name, url, events, appId)
- Storage: admin.storage.stats() / .buckets.list()
- Accounts: admin.accounts.credit(id, amount, description)
- Documents: admin.documents.bulkDelete(ids[])
- API Keys: admin.apiKeys.allocate(id, amount) / .revoke(id) / .rotate(id)

All methods return typed responses. Uses class-based API with namespaced methods.
AI_CONTEXT_END -->

## For AI Coding Assistants

> **TL;DR for Claude, Cursor, Copilot, and other AI assistants:**
>
> ```typescript
> import { GptAdmin } from "@gpt-core/admin";
> const admin = new GptAdmin({
>   baseUrl: "https://api.example.com",
>   token: "admin-jwt",
> });
> ```
>
> **Common operations:**
> | Task | Code |
> |------|------|
> | Storage stats | `await admin.storage.stats()` |
> | List webhooks | `await admin.webhooks.configs.list()` |
> | Create webhook | `await admin.webhooks.configs.create(name, url, events, appId)` |
> | Credit account | `await admin.accounts.credit(id, amount, 'reason')` |
> | Bulk delete docs | `await admin.documents.bulkDelete(ids)` |
> | Rotate API key | `await admin.apiKeys.rotate(keyId)` |
>
> **See [llms.txt](llms.txt) for complete AI-readable SDK reference.**

---

## Features

✅ **Fully Typed** - Complete TypeScript support with auto-generated types from OpenAPI specs
✅ **Runtime Validation** - Zod schemas for request validation
✅ **Bulk Operations** - Efficient batch processing for documents and webhooks
✅ **Webhook Management** - Configure, monitor, and test webhook configurations
✅ **Storage Administration** - Monitor storage usage across workspaces and buckets
✅ **Account Operations** - Credit/debit account balances with audit trails
✅ **Document Management** - Bulk delete and reprocess documents
✅ **API Key Management** - Allocate, revoke, and rotate API keys
✅ **Error Handling** - Comprehensive error handling with detailed context

## Installation

```bash
npm install @gpt-core/admin
# or
yarn add @gpt-core/admin
# or
pnpm add @gpt-core/admin
```

## Quick Start

```typescript
import { GptAdmin } from "@gpt-core/admin";

// Initialize admin client
const admin = new GptAdmin({
  baseUrl: "https://api.gpt-core.com",
  token: process.env.ADMIN_JWT_TOKEN, // Admin JWT token
  applicationId: process.env.APPLICATION_ID, // Your application ID
});

// Get storage statistics
const stats = await admin.storage.stats();
console.log(`Total storage: ${(stats.total_size / 1024 / 1024).toFixed(2)} MB`);
console.log(`Total files: ${stats.file_count}`);

// List webhook configurations
const webhooks = await admin.webhooks.configs.list();
console.log(
  `Active webhooks: ${webhooks.filter((w) => w.attributes.enabled).length}`,
);
```

## Configuration

```typescript
const admin = new GptAdmin({
  // Required: API base URL
  baseUrl: "https://api.gpt-core.com",

  // Required: Admin JWT token
  token: "admin-jwt-token",

  // Required: Application ID
  applicationId: "your-app-id",
});
```

### Environment Variables (Recommended)

```bash
# .env or .env.local
ADMIN_API_URL=https://api.gpt-core.com
ADMIN_JWT_TOKEN=your-admin-jwt-token
APPLICATION_ID=your-application-id
```

```typescript
// lib/admin-client.ts
import { GptAdmin } from "@gpt-core/admin";

export const admin = new GptAdmin({
  baseUrl: process.env.ADMIN_API_URL!,
  token: process.env.ADMIN_JWT_TOKEN!,
  applicationId: process.env.APPLICATION_ID!,
});
```

## API Versioning

The SDK uses Stripe-style API versioning. A default API version is sent with every request via the `Accept` header.

### Default Behavior

Every request automatically includes the SDK's built-in API version:

```http
Accept: application/vnd.api+json; version=2025-12-03
```

No configuration is needed -- the SDK sends `DEFAULT_API_VERSION` from `base-client.ts` automatically.

### Pinning a Version (Recommended for Production)

Pin a specific API version to protect your integration from breaking changes:

```typescript
const admin = new GptAdmin({
  baseUrl: "https://api.gpt-core.com",
  token: process.env.ADMIN_JWT_TOKEN,
  applicationId: process.env.APPLICATION_ID,
  apiVersion: "2025-12-03", // Pin to this version
});
```

### Reading the Active Version

```typescript
// The version the SDK is configured to send
console.log(admin.apiVersion);
```

### Response Header

Every API response includes the version that was used to process the request:

```
x-api-version: 2025-12-03
```

### Discovering Available Versions

List all supported API versions and their changelogs:

```bash
GET /api-versions
```

This returns the full list of versions with descriptions and deprecation status.

## API Reference

### Webhooks

#### List Webhook Configs

```typescript
const configs = await admin.webhooks.configs.list();
```

#### Create Webhook

```typescript
const webhook = await admin.webhooks.configs.create(
  "My Webhook", // name
  "https://your-server.com/webhook", // url
  ["document.analyzed", "thread.message.created"], // events
  "app-123", // application_id
  "your-webhook-secret", // secret (optional)
  true, // enabled
);
```

#### Update Webhook Config

```typescript
const config = await admin.webhooks.configs.update("webhook-id", {
  enabled: false,
  events: ["document.analyzed"],
});
```

#### Delete Webhook Config

```typescript
await admin.webhooks.configs.delete("webhook-id");
```

#### Test Webhook Config

```typescript
const result = await admin.webhooks.configs.test("webhook-id");
console.log("Test delivery ID:", result.delivery_id);
```

#### Webhook Deliveries

```typescript
// List deliveries
const deliveries = await admin.webhooks.deliveries.list();

// Get delivery details
const delivery = await admin.webhooks.deliveries.get("delivery-id");

// Retry failed delivery
await admin.webhooks.deliveries.retry("delivery-id");
```

### Storage Administration

```typescript
// Get overall storage stats
const stats = await admin.storage.stats();
console.log(stats.total_size, stats.file_count);

// Get stats for specific workspace
const workspaceStats = await admin.storage.stats("workspace-id");

// List all buckets
const buckets = await admin.storage.buckets.list();

// Get bucket details
const bucket = await admin.storage.buckets.get("bucket-id");

// Get bucket stats
const bucketStats = await admin.storage.buckets.stats("bucket-id");

// List bucket objects
const objects = await admin.storage.buckets.objects("bucket-id");
```

### Account Management

```typescript
// List all accounts
const accounts = await admin.accounts.list();

// Get account details
const account = await admin.accounts.get("account-id");

// Credit an account
await admin.accounts.credit("account-id", 1000, "Bonus credits");

// Debit an account
await admin.accounts.debit("account-id", 500, "Usage charge");
```

### Document Administration

```typescript
// List documents
const documents = await admin.documents.list();

// Get document details
const document = await admin.documents.get("doc-id");

// Bulk delete documents
await admin.documents.bulkDelete(["doc-id-1", "doc-id-2"]);

// Bulk reprocess documents
await admin.documents.bulkReprocess(["doc-id-1", "doc-id-2"]);
```

### API Key Management

```typescript
// List API keys
const keys = await admin.apiKeys.list();

// Get API key details
const key = await admin.apiKeys.get("key-id");

// Allocate credits to API key
await admin.apiKeys.allocate("key-id", 5000, "Monthly allocation");

// Revoke API key
await admin.apiKeys.revoke("key-id");

// Rotate API key
await admin.apiKeys.rotate("key-id");
```

## Webhook Events

Available webhook events:

- `document.uploaded`
- `document.analyzed`
- `document.deleted`
- `thread.created`
- `thread.message.created`
- `extraction.completed`
- `workspace.created`
- `user.registered`

## Bulk Operations

All bulk operations support:

- Minimum: 1 item
- Maximum: 100 items per request
- Validation via Zod schemas

```typescript
// Bulk delete up to 100 documents
const documentIds = ["doc-1", "doc-2", "doc-3"];
await admin.documents.bulkDelete(documentIds);

// Bulk reprocess documents
await admin.documents.bulkReprocess(documentIds);
```

## Security

⚠️ **Admin SDK should NEVER be used in client-side code.**

- Use only in secure server environments
- Never expose admin tokens in client code
- Rotate admin tokens regularly
- Audit admin actions
- Limit admin access to essential operations

## Error Handling

```typescript
try {
  await admin.accounts.credit("account-id", 1000);
} catch (error) {
  if (error instanceof ZodError) {
    console.error("Validation error:", error.errors);
  } else {
    console.error("API error:", error);
  }
}
```

## Configuration

```typescript
const admin = new GptAdmin({
  baseUrl: "https://api.gpt-core.com", // API base URL
  token: "admin-jwt-token", // Admin JWT token
  applicationId: "app-id", // Application ID
  apiKey: "api-key", // Optional: API key
});
```

## TypeScript Support

Full TypeScript definitions included:

```typescript
import type {
  WebhookConfig,
  WebhookDelivery,
  Account,
  Document,
  ApiKey,
  Bucket,
} from "@gpt-core/admin";
```

## Testing

```bash
# Run tests
npm test

# Watch mode
npm run test:watch

# Coverage
npm run test:coverage
```

## License

MIT © GPT Integrators