Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.agentbot.raveculture.xyz/llms.txt

Use this file to discover all available pages before exploring further.

Usage tracking API

The usage tracking system records per-event token consumption and tool execution metrics. You can query aggregated data by agent, model, or time period.
The usage tracker records events to a PostgreSQL database whenever an AI completion or tool call is made. The endpoints below are read-only query APIs for retrieving aggregated usage data.
The live, user-facing endpoints on this page are GET /api/dashboard/data, GET /api/dashboard/analytics, GET /api/dashboard/bootstrap, GET /api/dashboard/cost, and GET /api/dashboard/stats. The lower query endpoints are roadmap/spec documentation only and are not linked from the main navigation.

Dashboard data

GET /api/dashboard/data
Requires session authentication. Returns all dashboard data in a single request using parallel database queries. This endpoint replaces multiple sequential calls with one optimized request, reducing dashboard load time from 2–4 seconds to 200–400 ms. Runs on the Vercel Edge Runtime with CDN-level caching (s-maxage=5, stale-while-revalidate=30).

Response

{
  "userId": "user_abc123",
  "credits": 5,
  "plan": "solo",
  "openclawUrl": "https://agentbot-agent-abc123-production.up.railway.app",
  "openclawInstanceId": "abc123",
  "gatewayToken": "a1b2c3d4e5f6...",
  "agent": {
    "id": "agent_xyz",
    "status": "active",
    "name": "Atlas",
    "tier": "pro"
  },
  "health": {
    "status": "healthy",
    "checks": [
      { "name": "Database", "status": "ok" },
      { "name": "Gateway", "status": "ok" }
    ]
  },
  "meta": {
    "responseTime": 180,
    "cached": false,
    "timestamp": "2026-04-04T05:00:00.000Z"
  }
}

Response fields

FieldTypeDescription
userIdstringAuthenticated user’s ID
creditsnumberReferral credits balance. Defaults to 0.
planstringCurrent subscription plan (for example solo, collective, label, network). Defaults to free.
openclawUrlstring | nullURL of the user’s deployed OpenClaw instance, or null if not registered.
openclawInstanceIdstring | nullOpenClaw instance ID, falling back to the agent ID if not set.
gatewayTokenstring | nullGateway authentication token resolved from the token manager or agent registration.
agentobject | nullPrimary agent data, or null if no agent exists.
agent.idstringAgent identifier
agent.statusstringAgent status (for example active, running, stopped)
agent.namestringAgent display name
agent.tierstringAgent tier
healthobjectSystem health summary
health.statusstringOverall status: healthy or degraded
health.checksarrayIndividual service health checks
health.checks[].namestringService name (for example Database, Gateway)
health.checks[].statusstringok or down
meta.responseTimenumberServer-side response time in milliseconds
meta.cachedbooleanWhether the response was served from cache
meta.timestampstringISO 8601 timestamp of the response

Caching

Responses include CDN caching headers:
HeaderValue
Cache-Controlpublic, s-maxage=5, stale-while-revalidate=30
Vercel-CDN-Cache-Controlpublic, s-maxage=5, stale-while-revalidate=30
CDN-Cache-Controlpublic, s-maxage=5
Browser caching is prevented — only CDN-level caching is applied. Stale responses are served for up to 30 seconds while the CDN revalidates in the background.

Errors

CodeDescription
401Unauthorized — no valid session
500Failed to fetch dashboard data (includes details and responseTime in the response body)

Dashboard analytics

GET /api/dashboard/analytics
Requires session authentication. Returns deployment, skill, and task trends over time, channel activity, and top skill usage. Use this endpoint to render analytics charts and channel status indicators on the dashboard.

Query parameters

ParameterTypeDefaultDescription
rangeinteger180Number of days of history to include. Accepted values: 30, 90, 180, 365. Other values default to 180.

Response

{
  "overview": {
    "deployedAgents": 3,
    "liveAgents": 2,
    "installedSkills": 5,
    "scheduledTasks": 8,
    "connectedChannels": 2,
    "channelMessages": 142
  },
  "trend": [
    { "label": "Jan", "deployments": 1, "skills": 2, "tasks": 3 },
    { "label": "Feb", "deployments": 0, "skills": 1, "tasks": 2 }
  ],
  "topSkills": [
    { "name": "web_search", "installs": 3 }
  ],
  "channels": [
    { "name": "Webchat", "messages": 120, "lastActive": "2026-04-03T12:00:00Z", "status": "connected" },
    { "name": "Telegram", "messages": 22, "lastActive": "2026-04-02T08:30:00Z", "status": "connected" },
    { "name": "Discord", "messages": 0, "lastActive": null, "status": "not-configured" }
  ],
  "source": {
    "gateway": "live",
    "sessions": "live"
  }
}

Response fields

FieldTypeDescription
overview.deployedAgentsnumberTotal agents deployed by the user
overview.liveAgentsnumberAgents in active or running status
overview.installedSkillsnumberTotal enabled skills across all agents
overview.scheduledTasksnumberTotal scheduled tasks
overview.connectedChannelsnumberNumber of channels with a connected status
overview.channelMessagesnumberTotal messages across all channels
trendarrayMonthly buckets of deployment, skill, and task counts over the requested range
trend[].labelstringMonth label (for example Jan, Feb)
trend[].deploymentsnumberAgents deployed in this month
trend[].skillsnumberSkills installed in this month
trend[].tasksnumberTasks created in this month
topSkillsarrayTop 6 most-installed skills, sorted by install count descending
topSkills[].namestringSkill name
topSkills[].installsnumberNumber of installs
channelsarrayPer-channel activity and connection status
channels[].namestringChannel display name (for example Webchat, Telegram, Discord)
channels[].messagesnumberTotal messages on this channel
channels[].lastActivestring | nullISO 8601 timestamp of last activity, or null
channels[].statusstringConnection status: connected, not-configured, or unreachable
source.gatewaystringGateway data source status: live or unreachable
source.sessionsstringSessions data source status: live or unavailable

Errors

CodeDescription
401Unauthorized — no valid session
500Failed to fetch analytics

Dashboard bootstrap

GET /api/dashboard/bootstrap
Requires session authentication. Returns lightweight user and runtime shell data in a single request. Use this endpoint to populate the dashboard shell immediately without waiting for slower runtime probes. This endpoint consolidates data that previously required multiple separate fetches (user profile, OpenClaw state, and gateway token) into one call. The gatewayToken returned is the authenticated user’s own token, enabling automatic pairing with their agent instance. The dashboard renders skeleton cards for runtime-dependent data while the full runtime probe completes in the background.

Response

{
  "credits": 5,
  "referralCode": "abc123",
  "referralCount": 2,
  "plan": "solo",
  "openclawUrl": "https://agentbot-agent-abc123-production.up.railway.app",
  "openclawInstanceId": "abc123",
  "gatewayToken": "a1b2c3d4e5f6..."
}
FieldTypeDescription
creditsnumberReferral credits balance. Defaults to 0 when no credits exist.
referralCodestring | nullThe user’s referral code, or null if not set.
referralCountnumberNumber of successful referrals. Defaults to 0.
planstring | nullCurrent subscription plan (for example, solo, collective, label, network), or null if no plan is active.
openclawUrlstring | nullURL of the user’s deployed OpenClaw instance, or null if no instance is registered.
openclawInstanceIdstring | nullIdentifier of the user’s OpenClaw instance, or null if no instance is registered.
gatewayTokenstring | nullThe authenticated user’s gateway token for auto-pairing with their agent instance, or null if no token is registered.

Errors

CodeDescription
401Unauthorized — no valid session

Test usage logging (deprecated)

This endpoint was removed in the March 2026 security audit and is no longer available. Requests to this path return 404. Use the cost dashboard endpoint to verify that usage tracking is working.
POST /api/test-usage
A debug endpoint that fires a single test event through the usage logging pipeline.

Cost dashboard

GET /api/dashboard/cost
Requires session authentication. Returns aggregated cost, token, and call data for the cost dashboard. Breaks down spending by agent, model, and day. Plan subscription costs are sourced from the database. AI token usage is fetched from the backend metrics service when available.

Query parameters

ParameterTypeDefaultDescription
periodstring7dTime window for the aggregation. Accepted values: 7d (last 7 days), 30d (last 30 days), mtd (month to date).

Response

{
  "period": "7d",
  "summary": {
    "totalCost": 13.68,
    "totalTokens": 4560000,
    "totalCalls": 1946,
    "avgCostPerCall": 0.007
  },
  "agents": [
    {
      "name": "Atlas",
      "tokens": 2840000,
      "cost": 8.52,
      "calls": 1247,
      "avgCostPerCall": 0.0068,
      "model": "claude-3-7-sonnet"
    }
  ],
  "daily": [
    {
      "date": "Mar 17",
      "cost": 1.42,
      "tokens": 380000
    }
  ],
  "modelBreakdown": [
    {
      "model": "claude-3-7-sonnet",
      "percent": 68,
      "cost": 9.30
    }
  ],
  "isMockData": false,
  "plan": "solo",
  "planMonthlyCost": 29,
  "agentCount": 4,
  "activeAgents": 3
}

Response fields

FieldTypeDescription
periodstringThe requested period echoed back (7d, 30d, or mtd)
summary.totalCostnumberTotal cost in USD for the period
summary.totalTokensnumberTotal tokens (input + output) consumed
summary.totalCallsnumberTotal API calls made
summary.avgCostPerCallnumberBlended average cost per call in USD
agentsarrayPer-agent cost breakdown, sorted by cost descending
agents[].namestringAgent name or identifier
agents[].tokensnumberTotal tokens consumed by the agent
agents[].costnumberTotal cost in USD attributed to the agent
agents[].callsnumberNumber of API calls made by the agent
agents[].avgCostPerCallnumberAverage cost per call for the agent
agents[].modelstringPrimary model used by the agent
dailyarrayDaily cost and token totals
daily[].datestringFormatted date label (e.g. "Mar 17")
daily[].costnumberCost in USD for that day
daily[].tokensnumberTotal tokens consumed that day
modelBreakdownarrayCost breakdown by model, sorted by cost descending
modelBreakdown[].modelstringModel identifier
modelBreakdown[].percentnumberPercentage of total cost attributed to this model
modelBreakdown[].costnumberCost in USD for this model
isMockDatabooleanAlways false. Retained for backward compatibility.
planstringUser’s current subscription plan (for example solo, collective, label, network).
planMonthlyCostnumberMonthly cost in USD for the user’s current plan.
agentCountnumberTotal number of agents owned by the user.
activeAgentsnumberNumber of agents in active or running status.

Errors

CodeDescription
401Unauthorized — no valid session
500Failed to fetch cost data

Dashboard stats

GET /api/dashboard/stats
Requires session authentication. Returns aggregated agent, skill, and task counts for the authenticated user. Used by the dashboard overview to display real-time stats cards.

Response

{
  "agents": {
    "active": 1,
    "total": 3,
    "limit": 3,
    "newToday": 0
  },
  "skills": {
    "installed": 5
  },
  "tasks": {
    "total": 12
  }
}

Response fields

FieldTypeDescription
agents.activenumberNumber of agents with active status
agents.totalnumberTotal number of agents owned by the user
agents.limitnumberMaximum agents allowed by the user’s plan
agents.newTodaynumberNumber of agents created since midnight (UTC)
skills.installednumberTotal installed skills across all the user’s agents
tasks.totalnumberTotal scheduled tasks across all the user’s agents

Plan-based agent limits

The agents.limit value is determined by the user’s subscription plan:
PlanAgent limit
free1
solo1
starter1
pro3
collective3
scale10
label10
enterprise100
network100

Error handling

On failure, the endpoint returns a fallback response with zeroed-out values instead of an error status code:
{
  "agents": { "active": 0, "total": 0, "limit": 1, "newToday": 0 },
  "skills": { "installed": 0 },
  "tasks": { "total": 0 }
}

Errors

CodeDescription
401Unauthorized — no valid session
404User not found

The remaining endpoints below are not live on Agentbot. They are kept here as internal roadmap/spec documentation only.
All query endpoints below require bearer token authentication and are served by the backend API.

Usage summary

GET /api/usage/summary
Returns daily aggregated token usage and cost data across all agents and models.

Query parameters

ParameterTypeDefaultDescription
daysinteger30Number of days of history to return

Response

[
  {
    "date": "2026-03-22",
    "agent_id": "agent_abc",
    "model": "openrouter/anthropic/claude-sonnet-4",
    "provider": "openrouter",
    "input_tokens": 15200,
    "output_tokens": 3400,
    "total_tokens": 18600,
    "cost_usd": 0.042,
    "turn_count": 12
  }
]

Response fields

FieldTypeDescription
datestringDate in YYYY-MM-DD format
agent_idstring | nullAgent that generated the usage, or null for unattributed events
modelstringModel identifier
providerstringAI provider name
input_tokensnumberTotal input tokens for the day
output_tokensnumberTotal output tokens for the day
total_tokensnumberSum of all token types (input, output, cache read, cache write)
cost_usdnumberEstimated cost in USD
turn_countnumberNumber of individual completion calls

Usage by agent

GET /api/usage/by-agent/:agentId
Returns token usage grouped by model for a specific agent.

Path parameters

ParameterTypeDescription
agentIdstringID of the agent to query

Query parameters

ParameterTypeDefaultDescription
daysinteger30Number of days of history to include

Response

[
  {
    "model": "openrouter/anthropic/claude-sonnet-4",
    "provider": "openrouter",
    "input_tokens": 45000,
    "output_tokens": 12000,
    "total_tokens": 57000,
    "cost_usd": 0.13,
    "events": 48
  }
]

Response fields

FieldTypeDescription
modelstringModel identifier
providerstringAI provider name
input_tokensnumberTotal input tokens
output_tokensnumberTotal output tokens
total_tokensnumberTotal tokens across all types
cost_usdnumberEstimated cost in USD
eventsnumberNumber of usage events

Usage by model

GET /api/usage/by-model
Returns token usage aggregated by model across all agents.

Query parameters

ParameterTypeDefaultDescription
daysinteger30Number of days of history to include

Response

[
  {
    "model": "openrouter/anthropic/claude-sonnet-4",
    "provider": "openrouter",
    "input_tokens": 120000,
    "output_tokens": 35000,
    "total_tokens": 155000,
    "cost_usd": 0.35,
    "turns": 200
  }
]

Response fields

FieldTypeDescription
modelstringModel identifier
providerstringAI provider name
input_tokensnumberTotal input tokens
output_tokensnumberTotal output tokens
total_tokensnumberTotal tokens across all types
cost_usdnumberEstimated cost in USD
turnsnumberTotal completion turns

Daily totals

GET /api/usage/daily
Returns total token usage and cost per day.

Query parameters

ParameterTypeDefaultDescription
daysinteger7Number of days of history to return

Response

[
  {
    "date": "2026-03-22",
    "total_tokens": 85000,
    "cost_usd": 0.19,
    "turns": 72
  },
  {
    "date": "2026-03-21",
    "total_tokens": 62000,
    "cost_usd": 0.14,
    "turns": 55
  }
]

Response fields

FieldTypeDescription
datestringDate in YYYY-MM-DD format
total_tokensnumberTotal tokens used that day
cost_usdnumberEstimated cost in USD
turnsnumberTotal completion turns

Tool stats

GET /api/usage/tools
Returns aggregated tool execution statistics, optionally filtered by agent.

Query parameters

ParameterTypeDefaultDescription
agentIdstringFilter results to a specific agent. Omit for all agents.
daysinteger7Number of days of history to include

Response

[
  {
    "tool_name": "web_search",
    "calls": 150,
    "successes": 142,
    "avg_ms": 1230.5
  },
  {
    "tool_name": "code_edit",
    "calls": 85,
    "successes": 83,
    "avg_ms": 450.2
  }
]

Response fields

FieldTypeDescription
tool_namestringName of the tool
callsnumberTotal number of invocations
successesnumberNumber of successful invocations
avg_msnumberAverage execution duration in milliseconds

Usage event schema

Each usage event is intended to be stored as a row in the usage_logs table (Prisma model name: UsageLog). Events will be recorded automatically whenever an AI completion is made (for example, from the demo chat endpoint or agent chat). Cost is calculated at write time using per-model pricing rates.
The UsageLog Prisma model is not yet in the schema. The usage_logs table was originally created via a dedicated SQL migration (20260323000000_add_usage_logs), but the Prisma model was removed from the build due to build failures. Usage event recording is currently inactive. The schema below documents the intended table structure for when the model is re-added.

Server-side logging

Every usage event emits a structured log line to the server console when it is recorded. This makes it possible to verify that the usage tracking pipeline is working without querying the database. Success log format:
[UsageLogger] Logging: <agentId> | <model> | <inputTokens>+<outputTokens> tokens | $<cost>
For example:
[UsageLogger] Logging: demo-chat | gpt-4o | 450+120 tokens | $0.004050
If the database write fails, an error is logged instead:
[UsageLogger] Failed to log usage: <error message>
Because usage recording is fire-and-forget (it never blocks the API response), these log lines are the primary way to diagnose write failures. Monitor your server logs for [UsageLogger] Failed to log usage entries if usage data appears to be missing from the cost dashboard.

Cost dashboard logging

The cost dashboard endpoint emits its own diagnostic log lines prefixed with [Cost API]. These help you verify that the aggregation query is running and returning data. Query result log:
[Cost API] Found <count> usage logs
For example:
[Cost API] Found 0 usage logs
The cost dashboard now sources plan subscription costs from the database and AI token usage from the backend metrics service. If the backend is unavailable, plan-based cost data is still returned.
If the entire handler fails, a general error is logged and a 500 response is returned:
[Cost API] Error: <error message>
FieldTypeDescription
idintegerAuto-incrementing primary key
user_idvarchar(255)User who triggered the event
agent_idvarchar(255)Agent that triggered the completion
modelvarchar(100)Model identifier (for example anthropic/claude-sonnet-4.5)
input_tokensintegerNumber of input (prompt) tokens. Defaults to 0.
output_tokensintegerNumber of output (completion) tokens. Defaults to 0.
cost_usddecimal(10,6)Computed cost in USD (six decimal places). Defaults to 0.
endpointvarchar(255) | nullAPI route that generated the event (for example /api/demo/chat)
latency_msinteger | nullResponse latency in milliseconds
successbooleanWhether the completion succeeded. Defaults to true.
error_messagetext | nullError description when success is false
created_attimestampTimestamp when the event was recorded. Defaults to NOW().
When accessing the table through the Prisma ORM, use the camelCase field names (userId, agentId, inputTokens, etc.). When writing raw SQL queries, use the snake_case column names shown above (user_id, agent_id, input_tokens, etc.).
The table is indexed on user_id, agent_id, created_at, and the composite pairs (user_id, created_at) and (agent_id, created_at) for efficient time-range queries.
The usage event schema was updated in the March 2026 release. The previous fields session_id, session_key, cache_read_tokens, cache_write_tokens, and total_tokens are no longer recorded. Use input_tokens + output_tokens to calculate total tokens.

Tool event schema

Each tool event records:
FieldTypeDescription
session_idstring | nullSession that triggered the tool call
agent_idstring | nullAgent that invoked the tool
tool_namestringName of the tool
successbooleanWhether the tool call succeeded
duration_msnumber | nullExecution time in milliseconds

Errors

All usage tracking endpoints return the following error codes:
CodeDescription
401Unauthorized — missing or invalid bearer token
500Database query failed