# Platform API Reference

## Base URL

```
https://claw-api.agos.fun
```

## Authentication

| Method        | Header                                | Usage                          |
| ------------- | ------------------------------------- | ------------------------------ |
| JWT Bearer    | `Authorization: Bearer <accessToken>` | User operations                |
| Agent API Key | `Authorization: Bearer <apiKey>`      | LLM calls from deployed agents |

## Response Format

```json
// Success
{ "ok": true, "data": { ... } }

// Error
{ "ok": false, "error": "Error message" }
```

| HTTP Code | Description                       |
| --------- | --------------------------------- |
| 200       | Success                           |
| 201       | Created                           |
| 400       | Bad request                       |
| 401       | Unauthorized                      |
| 402       | Payment required (x402 challenge) |
| 403       | Forbidden                         |
| 404       | Not found                         |
| 409       | Conflict                          |

***

## 1. Authentication (SIWE)

Sign-In-With-Ethereum flow: get challenge → sign with wallet → receive JWT.

### POST /auth/challenge

* **Auth:** None

```json
// Request
{ "address": "0xYourWallet", "chainId": 56 }

// Response
{
  "ok": true,
  "data": {
    "message": "claw-api.agos.fun wants you to sign in with your Ethereum account...",
    "nonce": "a1b2c3d4e5f6"
  }
}
```

### POST /auth/verify

* **Auth:** None

```json
// Request
{ "message": "...siweMessage...", "signature": "0x..." }

// Response
{
  "ok": true,
  "data": {
    "accessToken": "eyJ...",
    "refreshToken": "eyJ...",
    "expiresIn": 86400
  }
}
```

> On first login, user account + wallet + AIOU account are auto-created.

### POST /auth/refresh

* **Auth:** None

```json
// Request
{ "refreshToken": "eyJ..." }

// Response
{ "ok": true, "data": { "accessToken": "eyJ...", "expiresIn": 86400 } }
```

***

## 2. Agent Configuration

### GET /agents/config

Get pricing, promo info, and inventory availability.

* **Auth:** None

```json
{
  "ok": true,
  "data": {
    "minBalanceAiou": "10",
    "setupFeeAiou": "29.9",
    "minInitialFundAiou": "39.9",
    "inviteDiscountAiou": "5",
    "inviteRewardAiou": "5",
    "inviteCodesPerUser": 5,
    "setupFeePromoEnd": "2026-03-24T23:59:59Z",
    "setupFeeEffective": "0",
    "minInitialFundEffective": "10",
    "minFundAiou": "10",
    "inventory": {
      "small": { "available": 10 },
      "large": { "available": 3 }
    }
  }
}
```

> `setupFeeEffective` / `minInitialFundEffective` reflect active promotions.

### GET /agents/models

List available LLM models.

* **Auth:** None

```json
{
  "ok": true,
  "data": [
    {
      "modelId": "deepseek-chat",
      "displayName": "DeepSeek V3",
      "provider": "newapi",
      "promptPrice": "0.000001",
      "completionPrice": "0.000002",
      "sortOrder": 1
    }
  ]
}
```

### GET /templates

List available agent templates.

* **Auth:** None

```json
{
  "ok": true,
  "data": [
    {
      "id": "openclaw-v1",
      "name": "OpenClaw",
      "description": "AI agent with web UI and tool integration",
      "containerPort": 8080,
      "envVars": [
        { "key": "OPENAI_API_KEY", "label": "OpenAI API Key", "required": true, "placeholder": "sk-..." }
      ]
    }
  ]
}
```

***

## 3. Agents

### POST /agents

Create a new agent.

* **Auth:** JWT

**Three creation modes** (mutually exclusive):

| Mode           | Field            | Description                |
| -------------- | ---------------- | -------------------------- |
| Template       | `templateId`     | Use a pre-built template   |
| Custom Docker  | `image`          | Your own Docker image      |
| Docker Compose | `composeContent` | Multi-service compose file |

```json
// Request — Template mode
{
  "name": "my-agent",
  "templateId": "openclaw-v1",
  "resourceClass": "small",
  "envVars": { "KEY": "value" }
}

// Request — Custom Docker mode
{
  "name": "my-custom-agent",
  "image": "ghcr.io/org/my-image:latest",
  "resourceClass": "small",
  "containerPort": 8080,
  "healthCheckPath": "/health",
  "modelId": "deepseek-chat",
  "envVars": { "KEY": "value" }
}

// Request — Docker Compose mode
{
  "name": "my-compose-agent",
  "composeContent": "version: '3'\nservices:\n  app:\n    image: ...",
  "resourceClass": "small",
  "containerPort": 8080
}
```

| Field             | Type   | Required     | Description                                 |
| ----------------- | ------ | ------------ | ------------------------------------------- |
| `name`            | string | ✅            | Agent display name                          |
| `templateId`      | string | One of three | Pre-built template ID                       |
| `image`           | string | One of three | Docker image URL                            |
| `composeContent`  | string | One of three | Docker Compose YAML                         |
| `resourceClass`   | string | No           | `"small"` or `"large"` (default: `"small"`) |
| `modelId`         | string | No           | LLM model ID (default: `"deepseek-chat"`)   |
| `containerPort`   | number | No           | Container port (default from template)      |
| `healthCheckPath` | string | No           | Health check path (e.g., `"/health"`)       |
| `envVars`         | object | No           | Environment variables                       |

```json
// Response 201
{
  "ok": true,
  "data": {
    "agent": {
      "id": "uuid",
      "name": "my-agent",
      "status": "pending_fund",
      "walletAddress": "0x...",
      "resourceClass": "small",
      "endpoint": null,
      "gatewayToken": null,
      "createdAt": "2025-01-01T00:00:00.000Z"
    },
    "apiKey": "ak_abc123...",
    "minBalanceRequired": 10,
    "minInitialFund": 39.9,
    "setupFee": 29.9
  }
}
```

> ⚠️ `apiKey` is only returned at creation time. Store it securely — it's the agent's LLM API credential.

### GET /agents

List your agents (excludes deleted).

* **Auth:** JWT

```json
{
  "ok": true,
  "data": [
    {
      "id": "uuid",
      "name": "my-agent",
      "status": "active",
      "templateId": "openclaw-v1",
      "image": "ghcr.io/org/image:latest",
      "resourceClass": "small",
      "walletAddress": "0x...",
      "endpoint": "https://uuid.agent.agos.fun",
      "gatewayToken": "gw_token...",
      "createdAt": "2025-01-01T00:00:00.000Z",
      "deployment": {
        "id": "dep-uuid",
        "status": "running",
        "publicIp": "1.2.3.4",
        "plan": "small",
        "hourlyRateAiou": "0.5",
        "totalCostAiou": "12.0",
        "createdAt": "2025-01-01T00:05:00.000Z"
      }
    }
  ]
}
```

### GET /agents/:id

Get agent details including balance.

* **Auth:** JWT

```json
{
  "ok": true,
  "data": {
    "id": "uuid",
    "name": "my-agent",
    "status": "active",
    "endpoint": "https://uuid.agent.agos.fun",
    "gatewayToken": "gw_token...",
    "updatedAt": "2025-01-01T01:00:00.000Z",
    "aiouBalance": {
      "available": "100.50",
      "frozen": "2.00",
      "spent": "48.00",
      "spentVps": "12.00",
      "spentLlm": "36.00"
    },
    "deployment": {
      "id": "dep-uuid",
      "status": "running",
      "publicIp": "1.2.3.4",
      "defaultPassword": "random-password",
      "updatedAt": "2025-01-01T01:00:00.000Z"
    }
  }
}
```

### PATCH /agents/:id/status

Change agent status.

* **Auth:** JWT

```json
// Request
{ "status": "stopped" }
```

| Transition  | Effect                                                          |
| ----------- | --------------------------------------------------------------- |
| → `active`  | Re-deploys if no active deployment and balance >= minimum       |
| → `stopped` | Pauses agent. VPS/DNS stay intact, can restart immediately      |
| → `deleted` | Full cleanup — VPS terminated, DNS removed, inventory reclaimed |

```json
// Response
{ "ok": true, "data": { "agentId": "uuid", "status": "deploying" } }
```

### POST /agents/:id/redeploy

Rebuild and redeploy a running agent.

* **Auth:** JWT

```json
// Response
{ "ok": true, "data": { "agentId": "uuid", "status": "deploying", "message": "Redeploy initiated" } }
```

***

## 4. Agent Funding (x402)

### POST /agents/:id/fund

Request a funding challenge (returns 402 with payment instructions).

* **Auth:** JWT

```json
// Request
{ "amount": "50" }
```

> First funding must be >= `minInitialFundEffective`. Subsequent top-ups must be >= `minFundAiou`.

```json
// Response 402
{
  "x402Version": 1,
  "accepts": [
    {
      "scheme": "exact",
      "network": "bsc",
      "namespace": "evm",
      "networkId": "56",
      "resource": "/agents/{agentId}/fund",
      "payTo": "0x...platformWallet",
      "asset": "0x...aiouTokenContract",
      "maxAmountRequired": "50000000000000000000",
      "extra": {
        "chainId": 56,
        "authorizationType": "eip3009",
        "nonce": "0x...",
        "challengeTs": 1700000000
      }
    }
  ]
}
```

### POST /agents/:id/fund/settle

Submit signed x402 payload to settle payment.

* **Auth:** JWT

```json
// Request
{
  "x402": {
    "authorization": {
      "from": "0x...userWallet",
      "to": "0x...platformWallet",
      "value": "50000000000000000000",
      "chainId": 56
    },
    "signature": "0x...eip712Signature"
  },
  "challengeTs": 1700000000,
  "inviteCode": "ABC123"
}
```

| Field         | Type   | Required | Description                            |
| ------------- | ------ | -------- | -------------------------------------- |
| `x402`        | object | ✅        | Signed EIP-3009 authorization          |
| `challengeTs` | number | ✅        | Timestamp from the 402 challenge       |
| `inviteCode`  | string | No       | Apply invite discount on first funding |

```json
// Response
{
  "ok": true,
  "data": {
    "txHash": "0x...",
    "amount": "50.00",
    "from": "0x...",
    "to": "0x...",
    "status": "confirmed",
    "deployTriggered": true,
    "inviteApplied": true
  }
}
```

> On first funding: setup fee deducted → deployment auto-triggered.

***

## 5. Deposits (On-Chain)

### POST /payments/deposits

Initiate a token deposit via x402 flow.

* **Auth:** JWT

```json
// Request
{
  "amount": "100.00",
  "idempotencyKey": "unique-key-123",
  "token": "USDT"
}
```

| Field            | Type   | Required | Description                 |
| ---------------- | ------ | -------- | --------------------------- |
| `amount`         | string | ✅        | Deposit amount              |
| `idempotencyKey` | string | ✅        | Prevents duplicate orders   |
| `token`          | string | No       | `"USDT"` (default) or `"U"` |

```json
// Response 402
{
  "x402Version": 1,
  "accepts": [
    {
      "scheme": "exact",
      "network": "bsc",
      "namespace": "evm",
      "networkId": "56",
      "payTo": "0x...treasuryContract",
      "asset": "0x...tokenContract",
      "maxAmountRequired": "100000000000000000000",
      "extra": {
        "chainId": 56,
        "authorizationType": "erc20",
        "orderId": "order-uuid",
        "token": "USDT"
      }
    }
  ]
}
```

### POST /payments/deposits/on-chain

Confirm a deposit after executing `AIOUToken.deposit()` on-chain.

* **Auth:** JWT

```json
// Request
{ "txHash": "0x...", "token": "USDT" }
```

| Field    | Type   | Required | Description                                |
| -------- | ------ | -------- | ------------------------------------------ |
| `txHash` | string | ✅        | Transaction hash (starts with `0x`)        |
| `token`  | string | No       | Token hint, verified against on-chain data |

```json
// Response
{
  "ok": true,
  "data": {
    "txHash": "0x...",
    "token": "USDT",
    "amount": "100.00",
    "status": "confirmed"
  }
}
```

> Validates: tx sent to treasury contract, `Deposited` event in logs, depositor matches user wallet. AIOU credited automatically at configured rate.

### GET /payments/deposits

List your deposit orders.

* **Auth:** JWT
* **Query:** `page`, `limit`, `status` (`pending` | `confirmed` | `failed`)

```json
{
  "ok": true,
  "data": {
    "items": [
      {
        "id": "order-uuid",
        "chainId": 56,
        "tokenSymbol": "USDT",
        "tokenContract": "0x...",
        "expectedAmount": "100.00",
        "actualAmount": "100.00",
        "txHash": "0x...",
        "fromAddress": "0x...",
        "toAddress": "0x...",
        "aiouRateSnapshot": "1.00",
        "status": "confirmed",
        "createdAt": "2025-01-01T00:00:00.000Z"
      }
    ],
    "page": 1,
    "limit": 20
  }
}
```

### GET /payments/deposits/:id

Get deposit order details.

* **Auth:** JWT

***

## 6. Wallet & Balance

### GET /wallets/aiou/balance

Get your platform AIOU balance.

* **Auth:** JWT

```json
{
  "ok": true,
  "data": {
    "availableBalance": "500.00",
    "frozenBalance": "0.00",
    "spentTotal": "150.00",
    "spentVpsTotal": "50.00",
    "spentLlmTotal": "100.00"
  }
}
```

### GET /agents/:agentId/wallet/balance

Get an agent's AIOU balance. Same response format.

* **Auth:** JWT

### POST /wallets/agents/:agentId/topup

Transfer AIOU from your account to an agent.

* **Auth:** JWT

```json
// Request
{ "amount": "50.00", "idempotencyKey": "unique-key" }

// Response
{ "ok": true, "data": { "transferId": "uuid", "amount": "50.00", "status": "completed" } }
```

### POST /wallets/agents/:agentId/reset

Top up agent to a target balance (transfers only the difference).

* **Auth:** JWT

```json
// Request
{ "targetBalance": "100.00", "idempotencyKey": "unique-key" }

// Response
{ "ok": true, "data": { "transferId": "uuid", "topupAmount": "30.00", "status": "completed" } }
```

### GET /agents/:agentId/wallet/transfers

List wallet transfer history for an agent.

* **Auth:** JWT
* **Query:** `page` (default: 1), `limit` (default: 20, max: 100)

***

## 7. Billing & Usage

### GET /billing/snapshots

Daily billing snapshots.

* **Auth:** JWT
* **Query:** `agentId`, `from` (ISO date), `to` (ISO date), `page`, `limit`

```json
{
  "ok": true,
  "data": {
    "items": [
      {
        "billDate": "2025-01-15",
        "agentId": "uuid",
        "totalVpsCostAiou": "12.00",
        "totalLlmCostAiou": "3.50",
        "totalAiouSpent": "15.50",
        "createdAt": "2025-01-16T00:00:00.000Z"
      }
    ],
    "page": 1,
    "limit": 30
  }
}
```

### GET /billing/usage

Detailed LLM usage records.

* **Auth:** JWT
* **Query:** `agentId`, `from`, `to`, `page`, `limit`

```json
{
  "ok": true,
  "data": {
    "items": [
      {
        "requestId": "uuid",
        "agentId": "uuid",
        "provider": "newapi",
        "model": "deepseek-chat",
        "promptTokens": "1200",
        "completionTokens": "800",
        "totalTokens": "2000",
        "actualCostAiou": "0.004",
        "latencyMs": 1500,
        "createdAt": "2025-01-15T12:00:00.000Z"
      }
    ],
    "page": 1,
    "limit": 50
  }
}
```

### GET /ledger/entries

Full transaction history.

* **Auth:** JWT
* **Query:** `eventType`, `from`, `to`, `page`, `limit`

**Event types:** `OnChainFunding` · `Deposit` · `DepositConfirmed` · `AiouMinted` · `SetupFee` · `VpsBilling` · `AiouFrozen` · `AiouCaptured` · `AiouReleased` · `AiouTransferOut` · `AiouTransferIn` · `InviteDiscount` · `InviteReward`

```json
{
  "ok": true,
  "data": {
    "items": [
      {
        "entryId": "string",
        "eventType": "OnChainFunding",
        "direction": "Credit",
        "amount": "50.00",
        "balanceAfterAvailable": "550.00",
        "balanceAfterFrozen": "0.00",
        "currency": "AIOU",
        "referenceType": "agent",
        "referenceId": "agent-uuid",
        "createdAt": "2025-01-01T00:00:00.000Z"
      }
    ],
    "page": 1,
    "limit": 50
  }
}
```

***

## 8. Invites

### GET /invites/codes

List your invite codes.

* **Auth:** JWT

```json
{
  "ok": true,
  "data": [
    {
      "id": "uuid",
      "code": "ABC123",
      "usedByUserId": null,
      "usedAt": null,
      "rewardCredited": false,
      "createdAt": "2025-01-01T00:00:00.000Z"
    }
  ]
}
```

### POST /invites/codes/generate

Generate invite codes (up to per-user limit).

* **Auth:** JWT

```json
// Response
{ "ok": true, "data": { "generated": 5, "codes": ["ABC123", "DEF456", "..."] } }
```

### POST /invites/codes/validate

Check if a code is valid before funding.

* **Auth:** JWT

```json
// Request
{ "code": "ABC123" }

// Response (valid)
{ "ok": true, "data": { "valid": true, "discountAiou": "5" } }

// Response (invalid)
{ "ok": true, "data": { "valid": false, "reason": "Code already used" } }
```

### GET /invites/rewards

View invite reward history.

* **Auth:** JWT

```json
{
  "ok": true,
  "data": {
    "items": [
      {
        "code": "ABC123",
        "usedByUserId": "user-uuid",
        "usedAt": "2025-01-15T00:00:00.000Z",
        "rewardCredited": true,
        "rewardAmount": "5"
      }
    ],
    "totalRewardAiou": "25.00",
    "rewardPerInvite": "5"
  }
}
```

***

## 9. LLM API (OpenAI-Compatible)

Base path: `https://claw-api.agos.fun/v1/`

### GET /v1/models

* **Auth:** None

```json
{
  "object": "list",
  "data": [
    {
      "id": "deepseek-chat",
      "object": "model",
      "owned_by": "deepseek",
      "promptPriceAiou": "0.000001",
      "completionPriceAiou": "0.000002"
    }
  ]
}
```

### POST /v1/chat/completions

Standard OpenAI chat completion. Billed per token in AIOU.

* **Auth:** Agent API Key

```json
// Request
{
  "model": "deepseek-chat",
  "messages": [
    { "role": "system", "content": "You are a helpful assistant." },
    { "role": "user", "content": "Hello!" }
  ],
  "stream": false,
  "max_tokens": 1024,
  "temperature": 0.7
}
```

```json
// Response
{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "model": "deepseek-chat",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "Hello! How can I help?" },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30 }
}
```

Streaming (`"stream": true`) returns SSE events, final event is `data: [DONE]`.

**Billing flow:** Freeze estimated cost → Call LLM → Capture actual → Release remainder.

***

## Quick Start

```bash
# 1. Login (SIWE)
TOKEN=$(curl -s -X POST /auth/verify -d '{"message":"...","signature":"0x..."}' | jq -r .data.accessToken)

# 2. Create agent
AGENT=$(curl -s -X POST /agents -H "Authorization: Bearer $TOKEN" \
  -d '{"name":"my-agent","templateId":"openclaw-v1"}')
AGENT_ID=$(echo $AGENT | jq -r .data.agent.id)
API_KEY=$(echo $AGENT | jq -r .data.apiKey)  # Save this!

# 3. Fund agent (get 402 challenge → sign → settle)
curl -X POST /agents/$AGENT_ID/fund -H "Authorization: Bearer $TOKEN" \
  -d '{"amount":"39.9"}'
# → Sign the EIP-3009 authorization off-chain
curl -X POST /agents/$AGENT_ID/fund/settle -H "Authorization: Bearer $TOKEN" \
  -d '{"x402":{...},"challengeTs":...}'

# 4. Wait for deployment (~5 min), poll until status = "running"
curl /agents/$AGENT_ID -H "Authorization: Bearer $TOKEN"

# 5. Use LLM API
curl -X POST /v1/chat/completions -H "Authorization: Bearer $API_KEY" \
  -d '{"model":"deepseek-chat","messages":[{"role":"user","content":"Hello!"}]}'
```

***

## Agent Lifecycle

```
pending_fund ──Fund──→ deploying ──→ running (active)
                                        ↕
                                      stopped (VPS stays alive)
                                        ↓
                                      deleted (VPS terminated)
```

> Billing continues while `active` or `stopped`. Server is only released on `deleted`.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://agos.gitbook.io/agos/agos-cloud/reference/api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
