# @gpt-platform/admin

> **🚧 GPT Integrators — Internal Use Only.** This SDK is published for use by GPT Integrators during platform testing and buildout. It is **not** offered for general public access at this time and is **not ready for public release**. Do not redistribute, share credentials, or build production integrations against this package outside of authorized GPT Integrator engagements.

The official TypeScript Admin SDK for the GPT Platform — ISV administration across tenants, workspaces, applications, billing, webhooks, and 60+ domain namespaces covering CRM, scheduling, clinical, forms, invoices, campaigns, direct email, voice, agent executions, Reactor pipelines, contracts, meetings, cases, human-review queues, multi-channel messaging, managed OAuth connectors, compliance (HIPAA/GDPR/PCI), brand identities + themes, and more.

[![npm version](https://img.shields.io/npm/v/@gpt-platform/admin.svg)](https://www.npmjs.com/package/@gpt-platform/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)

⚠️ **Server-side only.** This SDK requires admin privileges. Never expose admin tokens in browser code.

---

<!-- AI_CONTEXT_START
This SDK provides TypeScript bindings for GPT Platform ADMIN operations.
Use this for: tenant/workspace administration, webhooks, storage, accounts,
billing, and the full admin surface across CRM, scheduling, clinical, forms,
invoices, campaigns, voice, pipelines, executions, etc.
NOT for: end-user-facing operations (use @gpt-platform/client instead).
SECURITY: Server-side only. Never expose admin tokens in client code.

Quick patterns:
- Initialize: new GptAdmin({ baseUrl, token, applicationId })
- Tenants: admin.tenants.list() / .create({ ... })
- Workspaces: admin.workspaces.list() / .create({ ... })
- Webhooks: admin.webhooks.configs.list() / .create(name, url, events, appId)
- Storage: admin.storage.stats() / .buckets.list()
- Accounts: admin.accounts.credit(id, amount, description)
- API Keys: admin.apiKeys.list() / .create({...}) / .revoke(id) / .rotate(id)
- Executions: admin.executions.start(agentId, opts) / .stream(execId) / .tree(rootId) / .children(parentId)

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

## For AI Coding Assistants

> **TL;DR:**
>
> ```typescript
> import { GptAdmin } from "@gpt-platform/admin";
> const admin = new GptAdmin({
>   baseUrl: "https://api.gpt-core.com",
>   token: process.env.ADMIN_JWT_TOKEN,
>   applicationId: process.env.APPLICATION_ID,
> });
> ```
>
> See [llms.txt](llms.txt) for the complete AI-readable SDK reference.

---

## Features

- **60+ domain namespaces** — Full admin surface across tenants, workspaces, applications, CRM, scheduling, clinical, forms, invoices, campaigns, direct email, voice, agent executions, Reactor pipelines, compliance (HIPAA/GDPR/PCI), audit, brand identities + themes, multi-channel messaging, and more
- **Fully typed** — Auto-generated types from OpenAPI specs
- **Runtime validation** — Zod schemas for request validation
- **Stripe-style API versioning** — `Accept: application/vnd.api+json; version=YYYY-MM-DD`
- **SSE streaming** — Real-time agent execution events with multi-agent delegation tree queries
- **Comprehensive error handling** — Detailed context on every error
- **JSON:API envelope unwrapping** — Automatic

## Installation

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

## Quick Start

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

const admin = new GptAdmin({
  baseUrl: "https://api.gpt-core.com",
  token: process.env.ADMIN_JWT_TOKEN!, // Admin JWT or sk_srv_… server key
  applicationId: process.env.APPLICATION_ID!,
});

// List tenants
const tenants = await admin.tenants.list();

// Storage stats
const stats = await admin.storage.stats();

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

## Configuration

```typescript
const admin = new GptAdmin({
  baseUrl: "https://api.gpt-core.com", // Required: API base URL
  token: "admin-jwt-token", // Required: Admin JWT or sk_srv_…
  applicationId: "your-app-id", // Required: Application ID
  apiVersion: "2026-05-13", // Optional: Pin API version
});
```

### Environment Variables

```bash
# .env
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-platform/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. Every request includes the SDK's built-in API version in the `Accept` header automatically. Pin a specific version for production:

```typescript
const admin = new GptAdmin({
  baseUrl: "https://api.gpt-core.com",
  token: process.env.ADMIN_JWT_TOKEN!,
  applicationId: process.env.APPLICATION_ID!,
  apiVersion: "2026-05-13",
});
```

Discover available versions with `GET /api-versions`.

## API Reference (Highlights)

### Tenancy

```typescript
// Tenants
const tenants = await admin.tenants.list();
const tenant = await admin.tenants.create({ name: "Acme Inc.", slug: "acme" });
await admin.tenants.update(tenant.id!, { name: "Acme Co." });

// Workspaces (across tenants)
const workspaces = await admin.workspaces.list();
const ws = await admin.workspaces.create({
  name: "Engineering",
  slug: "engineering",
  tenant_id: tenant.id!,
});

// Applications (ISV products)
const apps = await admin.applications.list();

// Invitations
await admin.invitations.create({ email: "user@example.com", role: "admin" });
```

### Webhooks

```typescript
// Configs
const configs = await admin.webhooks.configs.list();
const webhook = await admin.webhooks.configs.create(
  "Order Notifications",
  "https://your-server.com/webhook",
  ["document.analyzed", "thread.message.created"],
  process.env.APPLICATION_ID!,
);
await admin.webhooks.configs.test(webhook.id!);
await admin.webhooks.configs.update(webhook.id!, { enabled: false });

// Deliveries
const deliveries = await admin.webhooks.deliveries.list();
await admin.webhooks.deliveries.retry("delivery-id");
```

### System Messages

```typescript
// Platform-wide ToS, privacy policy, welcome, and announcements
const messages = await admin.systemMessages.list();
const announcement = await admin.systemMessages.create({
  type: "announcement",
  title: "Scheduled maintenance",
  content: "We will be down Sunday 02:00–03:00 UTC.",
});
await admin.systemMessages.publish(announcement.id!);
await admin.systemMessages.unpublish(announcement.id!);
```

### Storage Administration

```typescript
const stats = await admin.storage.stats();
const wsStats = await admin.storage.stats("workspace-id");

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

### Accounts + Billing

```typescript
const accounts = await admin.accounts.list();
await admin.accounts.credit("account-id", 1000, "Bonus credits");
await admin.accounts.debit("account-id", 500, "Usage charge");

// Plans, capabilities, billing
const plans = await admin.billing.plans.list();
const capabilities = await admin.capabilities.list();
```

### Documents

```typescript
// admin.documents covers report generation helpers (generatePdf, emailReport).
// Bulk document operations live on the extraction sub-namespace:
await admin.extraction.documents.bulkDelete(["doc-1", "doc-2"]);
await admin.extraction.documents.bulkReprocess(["doc-1", "doc-2"]);
```

### API Keys

```typescript
const keys = await admin.apiKeys.list();
await admin.apiKeys.create({
  name: "Production server key",
  scopes: ["read:agents", "write:agents"],
});
await admin.apiKeys.rotate("key-id");
await admin.apiKeys.revoke("key-id");
```

### Executions (Agent Streaming)

```typescript
// Start an agent execution
const execution = await admin.executions.start(agentId, {
  input: { task: "Process this data" },
});

// Stream events in real time
const stream = admin.executions.stream(execution.id);
for await (const event of stream) {
  switch (event.type) {
    case "token_delta":
      process.stdout.write(event.data.content);
      break;
    case "tool_call":
      console.log(`Tool: ${event.data.name}`);
      break;
    case "done":
      console.log(`Status: ${event.data.status}`);
      break;
  }
}

// Multi-agent delegation tree
const tree = await admin.executions.tree(rootExecutionId);
const children = await admin.executions.children(parentExecutionId);
```

## Domain Namespaces

The admin SDK exposes 60+ namespaces. The full set, with one-line domain summaries, is in [llms.txt](llms.txt). Selected highlights:

| Namespace                      | Domain                                                                                                                                                                                                                                                       |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `admin.tenants`                | Tenant CRUD                                                                                                                                                                                                                                                  |
| `admin.workspaces`             | Workspace management within tenants                                                                                                                                                                                                                          |
| `admin.applications`           | ISV application configuration                                                                                                                                                                                                                                |
| `admin.invitations`            | Tenant + workspace invitations                                                                                                                                                                                                                               |
| `admin.users`                  | User administration                                                                                                                                                                                                                                          |
| `admin.userProfiles`           | User profile management                                                                                                                                                                                                                                      |
| `admin.roles`                  | Role definitions                                                                                                                                                                                                                                             |
| `admin.permissions`            | Permission registry                                                                                                                                                                                                                                          |
| `admin.scopes`                 | API key scope catalog                                                                                                                                                                                                                                        |
| `admin.accessGrants`           | Access grant administration                                                                                                                                                                                                                                  |
| `admin.ownershipTransfers`     | Tenant ownership transfer flows                                                                                                                                                                                                                              |
| `admin.accounts`               | Account credit/debit, balance management                                                                                                                                                                                                                     |
| `admin.billing`                | Plans, capabilities, usage events, wallet mutations                                                                                                                                                                                                          |
| `admin.capabilities`           | Capability registry per plan                                                                                                                                                                                                                                 |
| `admin.apiKeys`                | API key allocation, rotation, revocation                                                                                                                                                                                                                     |
| `admin.audit`                  | Audit log queries                                                                                                                                                                                                                                            |
| `admin.webhooks`               | Webhook configs + deliveries                                                                                                                                                                                                                                 |
| `admin.systemMessages`         | Platform-wide ToS, privacy policy, welcome, announcements                                                                                                                                                                                                    |
| `admin.storage`                | Bucket + object administration                                                                                                                                                                                                                               |
| `admin.crm`                    | Contacts, companies, deals, pipelines (admin)                                                                                                                                                                                                                |
| `admin.crmClusters`            | CRM relationship discovery                                                                                                                                                                                                                                   |
| `admin.scheduling`             | Events, availability, calendars (admin)                                                                                                                                                                                                                      |
| `admin.clinical`               | Patients, sessions, notes (admin)                                                                                                                                                                                                                            |
| `admin.forms`                  | Form definitions, publications, submissions (admin)                                                                                                                                                                                                          |
| `admin.invoices`               | Invoice rules, payments, recurring generation (admin)                                                                                                                                                                                                        |
| `admin.campaigns`              | Campaign + recipient management (admin)                                                                                                                                                                                                                      |
| `admin.email`                  | Direct email, sender profiles, tracking (admin)                                                                                                                                                                                                              |
| `admin.support`                | Tickets, queues, SLA (admin)                                                                                                                                                                                                                                 |
| `admin.cases`                  | Case management (admin)                                                                                                                                                                                                                                      |
| `admin.contracts`              | AI contract lifecycle, clauses, renewal alerts (admin)                                                                                                                                                                                                       |
| `admin.meetings`               | AI meeting transcription, summary, action items (admin)                                                                                                                                                                                                      |
| `admin.reviews`                | Review queues (admin)                                                                                                                                                                                                                                        |
| `admin.recipes`                | Recipes, shopping lists, nutrition (admin)                                                                                                                                                                                                                   |
| `admin.documents`              | Document administration + bulk ops                                                                                                                                                                                                                           |
| `admin.extraction`             | Extraction pipeline administration                                                                                                                                                                                                                           |
| `admin.executions`             | Agent execution management + multi-agent delegation trees                                                                                                                                                                                                    |
| `admin.pipelines`              | Pipeline definitions                                                                                                                                                                                                                                         |
| `admin.pipelineExecutions`     | Pipeline run management                                                                                                                                                                                                                                      |
| `admin.pipelineNodes`          | Pipeline node definitions                                                                                                                                                                                                                                    |
| `admin.pipelineNodeExecutions` | Pipeline node execution telemetry                                                                                                                                                                                                                            |
| `admin.agents`                 | Agent CRUD, versioning, training (admin)                                                                                                                                                                                                                     |
| `admin.ai`                     | LLM operations (admin)                                                                                                                                                                                                                                       |
| `admin.models`                 | Model catalog                                                                                                                                                                                                                                                |
| `admin.threads`                | Thread administration                                                                                                                                                                                                                                        |
| `admin.compliance`             | Full compliance admin surface — breach incidents, BAAs, GDPR DSRs, retention policies, audit chain, access logs, amendments, disclosures, ePHI assets, risk assessments, policy reviews, CDE scope, requirements, document templates, and compliance posture |
| `admin.connectors`             | Managed OAuth + adapters                                                                                                                                                                                                                                     |
| `admin.crawler`                | Web crawling administration                                                                                                                                                                                                                                  |
| `admin.imports`                | Bulk import administration                                                                                                                                                                                                                                   |
| `admin.voice`                  | Voice sessions, STT/TTS administration                                                                                                                                                                                                                       |
| `admin.preferences`            | User preferences administration                                                                                                                                                                                                                              |
| `admin.themes`                 | Design tokens + theme versions                                                                                                                                                                                                                               |
| `admin.brandIdentities`        | Tenant/application brand identity                                                                                                                                                                                                                            |
| `admin.platformTones`          | Platform tone configuration                                                                                                                                                                                                                                  |
| `admin.claimedDomains`         | Domain ownership                                                                                                                                                                                                                                             |
| `admin.portal`                 | ISV end-user portal                                                                                                                                                                                                                                          |
| `admin.social`                 | Social account administration                                                                                                                                                                                                                                |
| `admin.channels`               | Scoped channel-token exchange (admin)                                                                                                                                                                                                                        |
| `admin.content`                | Generic content operations                                                                                                                                                                                                                                   |
| `admin.registry`               | Service/feature registry                                                                                                                                                                                                                                     |
| `admin.projects`               | Project administration                                                                                                                                                                                                                                       |

## Bulk Operations

All bulk operations support 1–100 items per request with Zod-validated payloads.

```typescript
const docIds = ["doc-1", "doc-2", "doc-3"];
await admin.extraction.documents.bulkDelete(docIds);
await admin.extraction.documents.bulkReprocess(docIds);
```

## Security

⚠️ **Admin SDK is server-side only.**

- Never use admin tokens in browser code
- Store credentials in environment variables or secret managers
- 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) {
  // The SDK throws typed errors with detailed context.
  // Inspect error.message, error.requestId, error.status.
  console.error("Admin API error:", error);
}
```

## TypeScript Support

Full TypeScript definitions, plus per-namespace subpath imports for faster type resolution:

```typescript
import { GptAdmin } from "@gpt-platform/admin";
import type { CrmAPI } from "@gpt-platform/admin/crm";
import type { SchedulingAPI } from "@gpt-platform/admin/scheduling";
```

## Testing

```bash
bun run test           # Unit tests (MSW-mocked)
bun run test:coverage  # With coverage
```

## License

MIT © GPT Integrators
