Quick Start Authentication SDK Reference API Endpoints Rate Limits Webhooks TRIPPYCOIN API Community API Agent Marketplace Users API Goals API Streaks API Vitals API Error Codes Examples

Quick Start

Get running in under two minutes. Install the SDK, drop in your API key, and run your first autonomous agent task.

1. Install

bash
npm install apxai-hub

2. Initialize & run your first agent

typescript
import { APxAI } from 'apxai-hub'

const agent = new APxAI({ apiKey: process.env.APXAI_API_KEY })

const result = await agent.run('refactor auth module to use JWT refresh tokens')
console.log(result.output)  // "Refactored src/auth/index.ts — 3 files changed."
API Keys are provisioned after subscribing to any paid plan. Keys are prefixed apxai_sk_ for server-side use. Never expose them in client-side code or public repositories. Rotate from your dashboard at any time.

Authentication

APxAI supports two authentication methods. All protected endpoints require the Authorization header to be present.

Method 1 — API Key (recommended for production)

Permanent key tied to your subscription. Pass it as a Bearer token on every request.

shell
curl -X POST https://api.apxai.co/api/ap/run \
  -H "Authorization: Bearer apxai_sk_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"task":"refactor auth module","model":"claude-sonnet-4-6"}'

Method 2 — Bearer JWT (dashboard sessions)

Short-lived JWT (24 h TTL) issued by POST /api/auth/login. Use for interactive dashboard flows — not for server-to-server calls.

shell
# 1. Exchange credentials for a short-lived JWT
curl -X POST https://api.apxai.co/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"you@company.com","password":"your_password"}'

# 2. Use the returned token (expires in 24 h)
curl https://api.apxai.co/api/usage/stats \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
Security note: API keys are permanent and have full access to your account. Store them in environment variables or a secrets manager — never in source code or .env files committed to version control.

SDK Reference

The apxai-hub TypeScript SDK wraps all REST endpoints with typed interfaces and built-in retry logic.

Constructor

typescript
interface APxAIConfig {
  apiKey:    string            // required — your apxai_sk_ key
  baseUrl?:   string            // default: 'https://api.apxai.co'
  model?:     string            // default: 'claude-sonnet-4-6'
  memory?:    boolean           // enable persistent memory context
  timeout?:   number            // ms, default 30000
  retries?:   number            // default 2
}

Method reference

Method Signature Returns Description
run() run(task: string, opts?: RunOpts) Promise<RunResult> Execute an autonomous coding task. Returns the agent output, token usage, and run ID.
diagnose() diagnose(issue: string, path?: string) Promise<DiagnoseResult> Run xAI diagnostics on a codebase path or describe an issue in plain English. Returns diagnosis and fix suggestions.
autopilot() autopilot(goal: string, opts?: AutopilotOpts) Promise<PilotResult> Set a high-level goal and let the agent plan, code, test, and deploy autonomously across multiple steps.
usage() usage() Promise<UsageStats> Retrieve current run counts, token consumption, and remaining quota for your account tier.
health() health() Promise<HealthStatus> Ping the API and return service health for all subsystems. No authentication required.

TypeScript interfaces

typescript
interface RunResult {
  ok:          boolean
  runId:       string
  output:      string
  tokensUsed:  number
  model:       string
  durationMs:  number
}

interface DiagnoseResult {
  ok:           boolean
  diagnosis:   string
  suggestions: string[]
  severity:    'low' | 'medium' | 'high' | 'critical'
  filesScanned: number
}

interface PilotResult {
  ok:              boolean
  pilotId:         string
  goal:            string
  stepsCompleted:  number
  steps:           string[]
  durationMs:      number
}

SDK v2.1 — BrainClient & streaming

SDK v2.1 ships BrainClient — a dedicated client for the Brain subsystem with async generator SSE streaming and a built-in webhooks sub-namespace. The main APxAI class is unchanged — import BrainClient alongside it.

BrainClient — streaming + webhook management
typescript
import { BrainClient } from 'apxai-hub'

const brain = new BrainClient({ apiKey: 'apx_...' })

// Streaming response via async generator (SSE under the hood)
for await (const chunk of brain.stream('Refactor my auth module')) {
  process.stdout.write(chunk)
}

// Webhook management via brain.webhooks sub-namespace
const wh = await brain.webhooks.create({
  url:     'https://my-server.com/hooks/apxai',
  events:  ['agent.task.completed', 'brain.memory.updated'],
  secret:  'my-secret-123'
})
console.log(wh.id)  // "wh_01j9x8tz..."

APxAIError class

All SDK errors are instances of APxAIError, which extends Error and exposes the HTTP status and structured payload.

typescript
import { APxAI, APxAIError } from 'apxai-hub'

try {
  await agent.run('...')
} catch (err) {
  if (err instanceof APxAIError) {
    console.log(err.status)   // 429
    console.log(err.code)     // "RATE_LIMITED"
    console.log(err.message)  // "Rate limit exceeded"
    console.log(err.retryAfter) // 42 (seconds)
  }
}

API Endpoints

All requests target https://api.apxai.co. Responses are JSON. Public endpoints require no authentication.

Method Route Auth Description
GET /api/health Public Basic health ping. Returns uptime in seconds.
GET /api/status Public Detailed system status across all services (AP, xAI, memory, billing, database).
POST /api/auth/login Public Exchange email + password for a 24 h JWT token.
POST /api/ap/run Bearer Run a coding agent task. Accepts task string and optional model override.
GET /api/ap/history Bearer List the last 50 AP agent runs for your account.
POST /api/xai/run Bearer Run xAI diagnostics on a path or described issue. Returns diagnosis + prioritised fix list.
POST /api/brain/chat Bearer Chat with the AI brain — queries persistent memory and codebase context.
POST /api/brain/stream Bearer Streaming version of /brain/chat — returns SSE (Server-Sent Events) for real-time output.
POST /api/autopilot Bearer Set an autonomous multi-step goal. Agent plans, codes, tests, and deploys without manual intervention.
GET /api/usage/stats Bearer Full usage breakdown: daily runs, weekly runs, token consumption, quota remaining.
GET /api/stripe/prices Public List all pricing tiers with feature sets and monthly limits.
POST /api/stripe/checkout Public Create a Stripe Checkout session. Returns a redirect URL to the hosted payment page.
GET /api/stripe/subscription Bearer Look up current subscription status, tier, and billing period end for an email.
POST /api/waitlist Public Add an email to the early-access waitlist. Returns queue position.

Rate Limits

Limits are enforced per API key. Exceeding them returns 429 Too Many Requests with a Retry-After header.

Tier Requests / Month Requests / Minute Concurrent Runs
Free 50 10 1
Pro 2,000 60 5
Enterprise Unlimited 300 Custom
Rate limit headers: Every response includes X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset (Unix timestamp) so you can implement smart backoff logic without waiting for a 429.

429 response shape

json
{
  "ok":      false,
  "error":    "Rate limit exceeded",
  "retryAfter": 42  // seconds until your window resets
}

Webhooks

Register HTTP endpoints to receive real-time event notifications from APxAI. Every delivery is signed with HMAC-SHA256 so you can verify it originated from the platform.

Supported events

Event Type Description
brain.memory.updated Brain memory store was updated
agent.task.completed Agent task finished successfully
agent.task.failed Agent task failed after retries
autopilot.session.started Autopilot session began
autopilot.session.ended Autopilot session concluded
webhook.test Test delivery sent from dashboard or API

Endpoints

POST /api/webhooks Bearer Create a new webhook registration

Register a URL to receive event deliveries. The response includes a wh_-prefixed ID you use for all subsequent operations on this webhook.

Request body
json
{
  "url":    "https://my-server.com/hooks/apxai",
  "events": ["agent.task.completed", "brain.memory.updated"],
  "secret": "my-secret-123"
}
Response — 201 Created
json
{
  "ok":        true,
  "webhook": {
    "id":        "wh_01j9x8tzk4e2vn7bqr3m",
    "url":       "https://my-server.com/hooks/apxai",
    "events":    ["agent.task.completed", "brain.memory.updated"],
    "enabled":   true,
    "createdAt": "2026-05-27T12:00:00.000Z"
  }
}
POST /api/webhooks/:id/test Bearer Send a test delivery to a registered webhook

Dispatches a webhook.test event to the registered URL and returns the HTTP response received from your server.

Response — 200 OK
json
{
  "ok":           true,
  "deliveryId":   "dlv_03kp2rz9",
  "statusCode":   200,
  "durationMs":   143
}
DELETE /api/webhooks/:id Bearer Delete a webhook registration

Permanently removes the webhook. Deliveries in flight will still be attempted. Returns 204 No Content on success.

Signed delivery format

Every delivery includes an X-APxAI-Signature header. The value is the HMAC-SHA256 of the raw JSON body, keyed with the secret you provided at registration.

Example delivery headers
text
POST /hooks/apxai HTTP/1.1
Content-Type: application/json
X-APxAI-Event: agent.task.completed
X-APxAI-Delivery: dlv_03kp2rz9
X-APxAI-Signature: sha256=3b4c2d1e9f0a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3

Verify the signature (Node.js)

Always verify signatures before processing a delivery. Use crypto.timingSafeEqual to prevent timing attacks — a standard string comparison is not safe here.
javascript
const crypto = require('crypto')

function verifySignature(payload, signature, secret) {
  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(JSON.stringify(payload))
    .digest('hex')
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  )
}

// Express example
app.post('/hooks/apxai', express.json(), (req, res) => {
  const sig = req.headers['x-apxai-signature']
  if (!verifySignature(req.body, sig, process.env.APXAI_WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature')
  }
  // handle event...
  res.json({ received: true })
})

TRIPPYCOIN API

Read live, on-chain TRIPPYCOIN facts straight from the verified contract on BNB Smart Chain (chainId 56). Every value is fetched from a public RPC node — supply, burned balance, and contract metadata are real and auditable on BscScan. Market fields (price, market cap) are read live from the token's PancakeSwap V2 pool — liquidity is intentionally tiny — while holders stays null until an indexer is wired. We never fabricate a number. All endpoints are public — no authentication required.

Method Route Auth Description
GET /api/trippycoin/price Public Live price & marketCap from the PancakeSwap V2 pool, with honest market status. Liquidity is intentionally tiny.
GET /api/trippycoin/history Public Price history. data is empty — no candle indexer is run, never synthetic. Accepts period query param.
GET /api/trippycoin/burns Public Live burned balance — tokens held at the dead/zero addresses, read from chain.
GET /api/trippycoin/stats Public Full live on-chain snapshot: contract, supply, burned, circulating, and market status.
GET /api/trippycoin/price Public TRIPPY price & market status
Response — 200 OK
json
{
  "symbol":            "TRIPPY",
  "price":             0.0000210,   // USD, live from pool reserves (example)
  "priceBnb":          0.00000003, // WBNB per TRIPPY, live
  "marketCap":         21,        // price × totalSupply, live
  "liquidityUsd":      42,        // ≈ 2× the WBNB side — intentionally tiny
  "bnbUsd":            699,       // WBNB/USDT, live
  "poolAddress":       "0xf6c11f656c285a19ccc416b54eccde423ac302bb",
  "marketStatus":      "live",
  "note":              "Live price read directly from the PancakeSwap V2 pool reserves on BNB Smart Chain.",
  "totalSupply":       1000000,
  "circulatingSupply": 1000000,
  "contractAddress":   "0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed",
  "explorerUrl":       "https://bscscan.com/token/0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed",
  "updatedAt":         "2026-05-31T00:00:00.000Z"
}
GET /api/trippycoin/history?period=7d Public Price history (empty pre-market)

Query param period accepts 1h, 24h, 7d (default), or 30d. data is an empty array — this endpoint runs no price-candle indexer, so no historical series is stored, and no synthetic candles are ever returned. The live price is available from /price and /stats.

Response — 200 OK
json
{
  "period":         "7d",
  "data":           [],            // no candle indexer is run — never synthetic
  "marketStatus":   "live",
  "note":           "No price-candle indexer is run, so no historical series is returned. Live price is in /price and /stats.",
  "contractAddress": "0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed",
  "explorerUrl":     "https://bscscan.com/token/0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed"
}
GET /api/trippycoin/burns Public Recent burn events

Returns the live burned balance — TRIPPY held at the dead and zero addresses, read directly from chain. There is no scheduled or automatic burn mechanism, so this is currently 0 and is never fabricated.

Response — 200 OK
json
{
  "burnedTotal":     0,          // live balance at dead/zero addresses
  "burnRate":        0,          // percent of supply burned
  "burnAddresses": [
    "0x000000000000000000000000000000000000dEaD",
    "0x0000000000000000000000000000000000000000"
  ],
  "note":            "Read live from chain. No scheduled burns are fabricated.",
  "contractAddress": "0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed",
  "explorerUrl":     "https://bscscan.com/token/0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed"
}
GET /api/trippycoin/stats Public Full live on-chain snapshot — market fields read live; liquidity is intentionally tiny
Response — 200 OK
json
{
  "contractAddress":   "0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed",
  "deployer":          "0x2e4893156851fa768f363be8f1e3f98e32b818ce",
  "chain":             { "id": 56, "name": "BNB Smart Chain" },
  "explorerUrl":       "https://bscscan.com/token/0x6a887093a6ce5aabd464ba46b3018a1eb17b67ed",
  "name":              "TRIPPYCOIN",
  "symbol":            "TRIPPY",
  "decimals":          18,
  "totalSupply":       1000000,      // fixed, no minting
  "burnedTotal":       0,
  "circulatingSupply": 1000000,
  "deployerBalance":   0,         // entire fixed supply seeded into the pool
  "price":             0.0000210,   // USD, read live from pool reserves (example)
  "priceBnb":          0.00000003, // WBNB per TRIPPY, live
  "marketCap":         21,        // price × totalSupply, live
  "liquidityUsd":      42,        // ≈ 2× the WBNB side — intentionally tiny
  "bnbUsd":            699,       // WBNB/USDT, live
  "poolAddress":       "0xf6c11f656c285a19ccc416b54eccde423ac302bb",
  "holders":           null,         // requires an indexer; not faked
  "marketStatus":      "live",
  "sourceVerified":    false,
  "liveAt":            "2026-05-29T12:00:00.000Z"
}

Community API

The Community API powers the APxAI leaderboard, creator showcase, and real-time activity feed. All endpoints are public — no authentication required.

Method Endpoint Description
GET /api/community/stats Global community metrics — members, active builders, published agents
GET /api/community/leaderboard Top point earners with optional vertical filter and caller rank
GET /api/community/creators Top agent creators ranked by runs and points earned
GET /api/community/activity Last 20 real-time community activity events
GET /api/community/members Paginated member list with points balance, vertical, and streak
GET /api/community/stats Public Global community metrics
Response — 200 OK
json
{
  "ok":                  true,
  "populated":           false,
  "members":             0,
  "activeBuilders":      0,
  "publishedAgents":     0,
  "weeklyActiveMembers": 0,
  "note":                "Pre-launch: real community metrics appear here as members join."
}
GET /api/community/leaderboard Public Top point earners + caller rank

Query params: limit (1–50, default 25) and vertical — one of FORGE, FLOW, HELIX, or NEXUS. If authenticated, the response includes userRank.

Response — 200 OK
json
{
  "ok":          true,
  "populated":   false,
  "leaderboard": [],      // fills in as members earn rank
  "userRank":    null,    // caller's real rank once they have activity
  "note":        "No leaderboard activity yet."
}
GET /api/community/creators Public Top agent creators by points earned
Response — 200 OK
json
{
  "ok":       true,
  "populated": false,
  "creators": [],     // fills in as creators publish agents
  "note":      "No creators have published agents yet."
}
GET /api/community/activity Public Last 20 community events

Returns the 20 most recent community activity events in reverse chronological order. Events include agent runs, new member joins, points awards, and leaderboard changes.

Response — 200 OK
json
{
  "ok":        true,
  "populated": false,
  "activity":  [],     // fills in as real events occur
  "note":      "No community activity yet."
}
GET /api/community/members Public Paginated member list

Query params: limit (default 20, max 100) and offset (default 0) for pagination.

Response — 200 OK
json
{
  "ok":        true,
  "populated": false,
  "total":     0,
  "members":   [],     // fills in as members join
  "pagination": { "limit": 20, "offset": 0, "hasMore": false, "nextOffset": null }
}

Agent Marketplace

Browse, deploy, and monitor pre-built AI agents from the APxAI marketplace. Subscriptions are cash by default, with an optional non-custodial TRIPPY checkout (subscriber pays the creator wallet-to-wallet). All listing endpoints are public; run and review endpoints require authentication.

Creator earnings: Agent subscriptions are settled in cash by default. Creators may optionally set a TRIPPY price and BNB Chain wallet to accept non-custodial, wallet-to-wallet payment from subscribers — APxAI never takes custody of funds.
Method Endpoint Auth Description
GET /api/agents Public List marketplace agents — filter by category, tier, or featured flag
GET /api/agents/stats Public Marketplace-level statistics — total agents, runs, average rating
GET /api/agents/:id Public Single agent detail including schema, pricing, and usage stats
POST /api/agents/:id/run Bearer Trigger a real agent run — returns 501 until an execution engine is connected
GET /api/agents/runs/:runId Bearer Poll run status — running, completed, or failed
GET /api/agents/:id/reviews Public Agent reviews and aggregate star rating
GET /api/agents Public List marketplace agents

Query params: category, tier (free | pro | enterprise), featured (boolean), limit, offset.

Response — 200 OK
json
{
  "ok":         true,
  "populated":  false,
  "agents":     [],     // fills in as creators publish
  "pagination": { "total": 0, "limit": 20, "offset": 0, "hasMore": false },
  "stats":      { "totalAgents": 0, "totalRuns": 0, "avgRating": null, "activeAgents": 0 },
  "note":       "No agents published yet."
}
GET /api/agents/stats Public Marketplace-level statistics
Response — 200 OK
json
{
  "ok":                  true,
  "totalAgents":         0,
  "totalRuns":           0,
  "avgRating":           null,
  "activeAgents":        0,
  "categories":          7,
  "weeklyActiveAgents":  0
}
GET /api/agents/:id Public Single agent detail
Response — 200 OK
json
// 404 while the marketplace is empty pre-launch.
// Once an agent is published, the object follows this shape:
{
  "ok":    true,
  "agent": {
    "id":            "string",
    "name":          "string",
    "category":      "productivity|dev-tools|finance|health|marketing|research|security",
    "description":   "string",
    "tier":          "free|pro|enterprise",
    "priceTrippy":   null,   // whole TRIPPY tokens, or null for cash-only
    "creatorWallet": null,   // creator's BNB Chain wallet for non-custodial payout
    "rating":        null,   // null until real reviews exist
    "totalRuns":     0,
    "weeklyRuns":    0,
    "status":        "active|beta|deprecated",
    "featured":      false
  }
}
POST /api/agents/:id/run Bearer Trigger an agent run

Triggers a real agent run. APxAI does not simulate execution or fabricate results — until a real agent runtime is connected this endpoint returns 501. Once live, poll GET /api/agents/runs/:runId for results.

Request body
json
{
  "inputs": {
    "prUrl": "https://github.com/myorg/repo/pull/42",
    "depth": "full"
  }
}
Response — 501 Not Implemented
json
{
  "ok":      false,
  "error":   "execution_backend_not_connected",
  "message": "Agent execution is not yet wired to a real engine. We do not simulate or fabricate run results."
}
GET /api/agents/runs/:runId Bearer Poll run status

Poll until status is completed or failed. Recommended poll interval: 2 seconds.

Response — 200 OK
json
// 404 if the run id is unknown. Real runs only — never simulated.
{
  "ok":  true,
  "run": {
    "id":          "string",
    "agentId":     "string",
    "userId":      "string",
    "status":      "running|completed|failed",
    "startedAt":   0,
    "completedAt": null,
    "result":      null
  }
}
GET /api/agents/:id/reviews Public Agent reviews and ratings
Response — 200 OK
json
{
  "ok":           true,
  "agentId":      "string",
  "reviews":      [],     // fills in as subscribers leave reviews
  "totalReviews": 0,
  "note":         "No reviews yet."
}

Users API

Search and interact with IronGram user profiles, social graph, workout history, and achievements.

Method Endpoint Auth Description
GET /api/users/search Public Search users by name or username
GET /api/users/{username} Public Get full user profile
POST /api/users/{username}/follow Bearer Follow or unfollow a user (toggle)
GET /api/users/{username}/workouts Public Get user's workout history
GET /api/users/{username}/achievements Public Get user's earned achievements
GET /api/users/search Public Search users by name or username

Query params: q (required) — search term matched against username and display name. limit (default 20).

Response — 200 OK
json
[
  {
    "username":     "irongram_user",
    "display_name": "Alex Rodriguez",
    "workouts":    183,
    "followers":   284,
    "points_earned":   4420
  }
]
GET /api/users/{username} Public Get full user profile
Response — 200 OK
json
{
  "username":     "irongram_user",
  "display_name": "Alex Rodriguez",
  "bio":         "Powerlifter | NEXUS protocol",
  "stats": {
    "workouts": 183,
    "prs":      12,
    "streak":   47,
    "followers":284
  },
  "points_earned": 4420,
  "badges":    ["FORGE Elite", "PR Machine"]
}
POST /api/users/{username}/follow Bearer Follow or unfollow a user (toggle)

Toggles the follow state for the authenticated user. If already following, the call unfollows; if not following, it follows. Requires a valid Bearer token.

Response — 200 OK
json
{ "following": true, "follower_count": 285 }
GET /api/users/{username}/workouts Public Get user's workout history

Query params: limit (default 10) and offset (default 0) for pagination.

Response — 200 OK
json
[{
  "id":           "wk_001",
  "type":         "FORGE",
  "name":         "Upper Power",
  "duration_min": 68,
  "volume_lbs":   12450,
  "prs":          1,
  "points_earned":    25,
  "date":         "2026-05-27T07:30:00Z"
}]
GET /api/users/{username}/achievements Public Get user's earned achievements
Response — 200 OK
json
[{
  "id":          "ach_001",
  "name":        "First PR",
  "description": "Hit your first personal record",
  "icon":        "🏅",
  "points_reward":   20,
  "earned_at":   "2026-03-15T00:00:00Z"
}]

Goals API

New

Create and track fitness goals tied to the five IronGram verticals. Goals award off-chain engagement points on creation and a bonus payout on completion.

About points: Points (a.k.a. XP) are an off-chain, in-app engagement score used across Goals, Streaks, Vitals, and community leaderboards. They are not the on-chain TRIPPY token and are never distributed on-chain — TRIPPY is a fixed-supply BEP-20 with no reward, airdrop, or burn mechanism.
GET /api/goals Bearer List user goals

Returns all active and completed goals for the authenticated user, ordered by creation date descending.

Response — 200 OK
json
{
  "goals": [
    {
      "id":         "goal_01j9x",
      "title":      "Deadlift 500 lbs",
      "category":  "FORGE",
      "target":    500,
      "current":   445,
      "points_reward": 10,
      "completed": false
    }
    // ... more goals
  ]
}
POST /api/goals Bearer Create a new goal

Creates a goal and immediately awards +10 points to the authenticated user for committing to a target.

Request body
json
{
  "title":    "Deadlift 500 lbs",
  "category": "FORGE",  // "FORGE"|"NEXUS"|"FLOW"|"HELIX"|"HABIT"
  "target":   500,
  "unit":     "lbs"
}
Response — 201 Created
json
{
  "goal": {
    "id":        "goal_01j9x",
    "title":     "Deadlift 500 lbs",
    "category": "FORGE",
    "target":   500,
    "current":  0,
    "unit":     "lbs",
    "completed":false
  },
  "points_reward": 10
}
PUT /api/goals/:id Bearer Update goal progress

Updates the current value for a goal. If current >= target, the goal is automatically marked complete and the completion reward is queued.

Request body
json
{ "current": 500 }
Response — 200 OK
json
{
  "goal": { /* updated goal object */ },
  "completed": true,
  "points_earned": 250  // present only when completed becomes true
}
DELETE /api/goals/:id Bearer Delete a goal

Permanently removes the goal. Points already awarded on creation are not revoked. Returns 404 if the goal does not belong to the authenticated user.

Response — 200 OK
json
{ "deleted": true }
POST /api/goals/:id/complete Bearer Mark goal complete and claim points

Marks a goal complete and triggers the points payout (100–500 points depending on category difficulty). Can only be called once per goal. Returns 409 if the goal is already complete.

Response — 200 OK
json
{
  "points_earned":     350,  // 100–500 based on category
  "total_balance": 4770
}

Streaks API

New

Read and manage daily activity streaks. Milestones at 7, 30, 100, and 365 days trigger automatic points bonuses. Rest Day Banks let users protect streaks across planned rest days.

GET /api/streaks Bearer Get streak data
Response — 200 OK
json
{
  "current_streak":  47,
  "longest_streak":  47,
  "bank_days":       2,
  "milestones": [
    { "days": 7,   "points_reward": 50,   "achieved": true  },
    { "days": 30,  "points_reward": 200,  "achieved": true  },
    { "days": 100, "points_reward": 750,  "achieved": false },
    { "days": 365, "points_reward": 5000, "achieved": false }
  ]
}
POST /api/streaks/log Bearer Log today's activity

Records an activity for today and increments the streak counter. If this log hits a milestone, the response includes milestone_hit with the points bonus amount. Idempotent within the same calendar day (UTC).

Request body
json
{ "activity_type": "workout" }
Response — 200 OK
json
{
  "streak": 30,
  "milestone_hit": {
    "days":      30,
    "points_reward": 200
  }  // omitted if no milestone hit
}
POST /api/streaks/use-bank Bearer Use a rest day bank

Consumes one Rest Day Bank to protect the current streak on a rest day. Returns 400 if no banks remain.

Response — 200 OK
json
{ "banks_remaining": 1 }
Response — 400 No banks
json
{ "error": "No rest day banks available" }

Vitals API

New

Log wearable biometric readings and retrieve a computed recovery score. Logging vitals rewards +3 points per entry to incentivise consistent tracking.

GET /api/vitals Bearer Get user vitals history

Returns the last 30 vitals readings for the authenticated user in reverse chronological order. Accepts optional limit query param (max 90).

Response — 200 OK
json
{
  "vitals": [
    {
      "hrv":           72,        // ms — heart rate variability
      "resting_hr":   52,        // bpm
      "blood_pressure":"118/76",
      "vo2_max":      48.2,
      "logged_at":    "2026-05-28T07:15:00Z"
    }
    // ... more readings
  ]
}
POST /api/vitals Bearer Log vitals reading (+3 points)

All fields are optional — log only the metrics your wearable supports. At least one field must be present. Awards +3 points once per calendar day (UTC).

Request body
json
{
  "hrv":        72,    // ms — optional
  "resting_hr": 52,    // bpm — optional
  "systolic":   118,   // mmHg — optional
  "diastolic":  76,    // mmHg — optional
  "vo2_max":    48.2,  // mL/kg/min — optional
  "spo2":       98     // % — optional
}
Response — 201 Created
json
{
  "vital": {
    "hrv":        72,
    "resting_hr": 52,
    "spo2":       98,
    "logged_at":  "2026-05-28T07:15:00Z"
  },
  "points_earned": 3
}
GET /api/vitals/recovery-score Bearer Get computed recovery score

Returns a 0–100 composite recovery score derived from the last 7 days of vitals and activity data. Component scores show which pillar needs attention.

Response — 200 OK
json
{
  "score": 76,
  "components": {
    "hrv":           85,
    "sleep":         72,
    "resting_hr":   90,
    "activity_load": 65
  }
}

Error Codes

All errors return a consistent JSON shape with "ok": false, an "error" string, and an optional "details" field.

Status Error Description
400 Bad Request Missing or malformed request body field. Check the details array for which field failed validation.
401 Unauthorized Missing or invalid Authorization header. Ensure your API key or JWT is correct and has not expired.
403 Forbidden Valid credentials but insufficient permissions — for example, accessing an Enterprise-only endpoint on a Free plan.
429 Rate Limited Too many requests for your tier. Inspect the Retry-After header and back off for that many seconds.
500 Internal Error Unexpected server error. The request was received but processing failed. Retry with exponential backoff.
503 Service Unavailable A downstream dependency (LLM provider, database) is temporarily unreachable. Check /api/status for details.

Error response shape

json
{
  "ok":      false,
  "error":    "Unauthorized",
  "message":  "Invalid or expired API key. Rotate your key from the dashboard.",
  "details":  null
}
400 validation error example
json
{
  "ok":     false,
  "error":   "Bad Request",
  "message": "Validation failed",
  "details": [
    { "field": "task", "message": "Required string, received undefined" }
  ]
}

Examples

Three real usage patterns to get you shipping with APxAI faster.

1. Basic agent run with AP

Use the SDK to run a coding task with persistent memory enabled. The agent loads previous context from your codebase automatically.

typescript
import { APxAI } from 'apxai-hub'

const agent = new APxAI({
  apiKey: process.env.APXAI_API_KEY!,
  model:  'claude-sonnet-4-6',
  memory: true,  // load persistent codebase context
})

async function main() {
  const result = await agent.run(
    'Add rate limiting middleware to all POST routes using express-rate-limit'
  )

  console.log('Run ID:', result.runId)
  console.log('Output:', result.output)
  console.log('Tokens:', result.tokensUsed)
  // Output: "Added rate limiting to 8 POST routes. Created middleware/rateLimit.ts."
}

main().catch(console.error)

2. Diagnose a Railway deployment failure

Describe an infrastructure failure in plain English and let xAI diagnose the root cause and return prioritised fixes.

typescript
import { APxAI } from 'apxai-hub'

const agent = new APxAI({ apiKey: process.env.APXAI_API_KEY! })

const diag = await agent.diagnose(
  'Railway deploy fails at build step. Error: Cannot find module @prisma/client. ' +
  'Works locally but crashes in CI after adding a new migration.',
  '.'  // scan from project root
)

console.log('Severity:',   diag.severity)
console.log('Diagnosis:',  diag.diagnosis)
// "Prisma client not generated before build. Missing 'prisma generate' in Railway build command."

diag.suggestions.forEach((fix, i) => console.log(`${i + 1}. ${fix}`))
// 1. Add "prisma generate" to Railway build command before "npm run build"
// 2. Add @prisma/client to dependencies (not devDependencies)
// 3. Ensure DATABASE_URL env var is set in Railway project settings

3. Set an autopilot goal and poll for completion

Autopilot takes a high-level goal and executes it autonomously — planning, coding, testing, and opening a PR — without further input.

typescript
import { APxAI } from 'apxai-hub'

const agent = new APxAI({ apiKey: process.env.APXAI_API_KEY! })

// Start autopilot — returns when all steps complete
const pilot = await agent.autopilot(
  'Add Stripe webhook handler for subscription events, write unit tests, and open a draft PR',
  { iterations: 12 }  // allow up to 12 planning steps
)

console.log('Pilot ID:',        pilot.pilotId)
console.log('Steps completed:', pilot.stepsCompleted)
console.log('Duration:',        `${(pilot.durationMs / 1000).toFixed(1)}s`)
console.log('Steps:')
pilot.steps.forEach((step, i) => console.log(`  ${i + 1}. ${step}`))
// Steps:
//   1. Analysed existing Stripe integration in src/billing/
//   2. Created src/webhooks/stripe.ts with event handler
//   3. Wrote 8 unit tests — all passing (jest)
//   4. Opened draft PR #51 on GitHub