// HTTP contract — envelopes, codes, quotas, retries

Errors & rate limits

Every API failure is traceable, every quota is visible, and every retry has a safe rule. Use this page when an API response is not a 2xx.

JSON envelope request IDs fixed windows full jitter
base url https://agentkit-2.polsia.app

// error envelope

For every API response with HTTP status >= 400, the contract adds three fields: code for machine handling, message for people and logs, and request_id for support tracing. Existing error, reason, and endpoint-specific fields remain available during the compatibility period.

required code

Stable snake-case value. Prefer this over parsing message.

required message

Human-readable guidance. Server failures never expose raw exception text here.

required request_id

Matches the X-Request-ID response header exactly.

# GET /api/v1/providers?limit=101
HTTP/1.1 400 Bad Request
X-Request-ID: req_7e4f5b8e-1f40-4a20-9c2b-35d5bd2c9f17
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
X-RateLimit-Reset: 1787788860
Content-Type: application/json

{
  "error": "invalid_limit",
  "reason": "limit must be an integer between 1 and 100",
  "code": "invalid_limit",
  "message": "limit must be an integer between 1 and 100",
  "request_id": "req_7e4f5b8e-1f40-4a20-9c2b-35d5bd2c9f17"
}
→

Compatibility: use code for new integrations. The legacy error and reason fields are retained, and policy responses keep fields such as transaction, current_balance_cents, missing, and expected_amount_cents.

// error codes by endpoint group

Codes below are the stable values to branch on. A slash-separated note identifies related route cases that share the same normalized envelope code; endpoint-specific legacy names remain in the response when they already exist.

Wallets

HTTP Code Remediation
400 invalid_request Fix the missing or malformed wallet field; do not retry the same payload unchanged.
400 invalid_cursor Use the opaque cursor returned by the same list endpoint.
400 invalid_limit Send an integer in the endpoint range, normally 1 through 100.
400 invalid_query Remove caller-controlled identity filters and use the API key scope.
401 unauthorizedmissing_api_key / invalid_api_key cases Send a current X-API-Key or Authorization Bearer credential.
403 forbidden Use the key that owns the wallet or resource in the URL.
404 not_foundwallet_not_found / Agent wallet not found cases Verify the wallet or agent ID and create the wallet before referencing it.
409 invalid_requestwallet_already_exists case Reuse the existing wallet for the agent or choose a new agent_id.
500 internal_error Retry with backoff and include request_id if the failure persists.

Webhooks

HTTP Code Remediation
400 invalid_request Provide a valid HTTPS URL and a non-empty supported events array.
400 invalid_json Send a valid JSON payload; do not retry malformed bytes unchanged.
401 unauthorizedmissing_api_key / invalid_api_key cases Send a current API key for webhook management calls.
401 invalid_signature / timestamp_too_old Verify the Stripe signing secret and send a fresh signed delivery.
404 not_foundwebhook_not_found case Check the webhook ID and confirm it belongs to the authenticated wallet.
429 rate_limited Pause until Retry-After expires, then reduce request cadence.
500 internal_error Retry reads or idempotent management work with backoff.
503 webhook_not_configured / service_unavailable Configure the delivery dependency or retry when the service recovers.

Providers

HTTP Code Remediation
400 invalid_cursor Pass a provider cursor returned by the previous page, not a wallet or history cursor.
400 invalid_limit Use an integer from 1 through 100.
400 invalid_category Choose one of the category IDs returned by the provider catalog.
400 invalid_query Send q as a string or omit it.
429 rate_limited Honor Retry-After and resume after the Unix reset time.
500 internal_error Retry with backoff and provide request_id to support.

Payments

HTTP Code Remediation
400 invalid_requestamount_cents, provider, memo, idempotency_key, and routing validation Correct the request shape and do not replay invalid input.
400 missing_session_id / missing_fund_intent_id Send both claim fields from the Stripe success flow.
400 amount_mismatch / invalid_amount Use the configured denomination and a positive integer amount.
400 cannot_transfer_to_self / over_allocation Use distinct wallets and make the routing rule sum exactly.
402 payment_not_verified Wait briefly for Stripe verification, then retry the same funding claim.
403 forbidden / wrong_wallet Use a key bound to the wallet or agent in the request.
403 insufficient_balance Fund the source wallet or reduce the charge; payment blocks include balance details.
403 provider_not_allowed / per_day_max_exceeded / per_merchant_max_exceeded / per_call_max_exceeded / daily_limit_exceeded / spending_limit_exceeded Update the wallet policy, provider allowlist, or balance before retrying.
404 agent_not_found / intent_not_found / wallet_not_found Create or verify the referenced wallet, agent, or funding intent.
409 intent_already_processed / reservation_invalid_state Treat the existing result as final and do not create a second payment.
410 intent_expired Create a fresh funding intent and send the buyer through the new payment link.
422 unsupported_currency / insufficient_available Use USD and reserve no more than the currently available balance.
429 rate_limited Honor Retry-After and reuse the same idempotency_key for the payment retry.
500 payment_failed / transaction_failed / transfer_failed / split_failed / reservation_failed / commit_failed / release_failed / claim_failed Retry safely with backoff and the same idempotency_key; no atomic work should be partially applied.
503 payment_unavailable / payment_verification_unavailable / service_unavailable Wait for the dependency to recover, then retry with backoff.

Settlements

HTTP Code Remediation
400 invalid_request / cannot_settle_to_self Correct the wallet IDs, positive integer amount, currency format, or description before retrying.
403 forbidden / insufficient_balance Use the key that owns from_wallet_id and settle no more than the source wallet’s available balance.
404 from_wallet_not_found / to_wallet_not_found Verify both wallet IDs before retrying the settlement.
409 wallet_inactive / idempotency_conflict Use active wallets and reuse the same Idempotency-Key only with the original request parameters.
422 currency_mismatch Send a currency matching both persisted wallet currencies.
500 settlement_failed After a timeout or settlement_failed response, resend the same Idempotency-Key header and request parameters; atomic settlement work rolls back on failure.

// rate limits & retries

Rate limits use a lazy-cleaned fixed window. Read the headers on every developer API response; the values are authoritative for the request that just completed.

X-RateLimit-LimitThe request bucket's maximum calls in the current one-minute window.
X-RateLimit-RemainingCalls left in the current window. It reaches 0 on the request that exhausts the quota.
X-RateLimit-ResetUnix seconds when the current window ends.
Retry-AfterInteger seconds until reset, sent only with a limiter-generated HTTP 429.
BucketQuotaScope
GET/PATCH /api/wallets · GET /api/transactions60 / minuteAPI-key identity
POST /api/wallets/:id/credit · POST /api/pay · POST /api/v1/wallet/transfer30 / minuteAPI-key identity
GET /api/v1/providers · webhook reads60 / minuteAPI-key or client IP
Other API GETs60 / minuteAPI-key or client IP
Other API writes30 / minuteAPI-key or client IP
POST /api/stripe/funding-webhookNot countedStripe delivery endpoint
429

A 429 body has error: "rate_limited", code: "rate_limited", message, and request_id. It also has X-RateLimit-Remaining: 0, a future X-RateLimit-Reset, and a positive integer Retry-After. Normal 4xx responses have no Retry-After.

Throttle proactively when remaining / limit < 0.10. If a retry is still needed, use full jitter: random(0, base * 2^n). Cap the loop at five attempts. For payment, transfer, reservation, and split retries, resend the same idempotency_key so a network timeout cannot create a second charge.

Node.js
Python
// Read quota headers and retry 429 / 5xx safely
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function payWithRetry(url, apiKey, payload) {
  const base = 500;
  for (let attempt = 0; attempt < 5; attempt++) {
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-API-Key': apiKey },
      body: JSON.stringify(payload) // same idempotency_key every time
    });
    const limit = Number(response.headers.get('X-RateLimit-Limit'));
    const remaining = Number(response.headers.get('X-RateLimit-Remaining'));
    const reset = Number(response.headers.get('X-RateLimit-Reset'));
    if (limit > 0 && remaining / limit < 0.10) console.warn('quota nearly exhausted', reset);
    if (response.status !== 429 && response.status < 500) return response;
    const retryAfter = Number.parseInt(response.headers.get('Retry-After') || '', 10);
    const resetDelay = Number.isFinite(reset) ? Math.max(0, reset * 1000 - Date.now()) : 0;
    const jitter = Math.random() * base * (2 ** attempt);
    await sleep(retryAfter > 0 ? retryAfter * 1000 : Math.max(resetDelay, jitter));
  }
  throw new Error('pay: retry budget exhausted');
}
import random, time, requests

BASE_MS = 500

def pay_with_retry(url, api_key, payload):
    for attempt in range(5):
        response = requests.post(url, headers={'X-API-Key': api_key}, json=payload, timeout=15)
        limit = float(response.headers.get('X-RateLimit-Limit', 0))
        remaining = float(response.headers.get('X-RateLimit-Remaining', 0))
        reset = int(response.headers.get('X-RateLimit-Reset', 0))
        if limit and remaining / limit < 0.10:
            print('quota nearly exhausted; reset:', reset)
        if response.status_code != 429 and response.status_code < 500:
            return response
        retry_after = response.headers.get('Retry-After')
        reset_delay = max(0, reset - int(time.time())) if reset else 0
        jitter = random.uniform(0, BASE_MS * (2 ** attempt)) / 1000
        time.sleep(int(retry_after) if retry_after else max(reset_delay, jitter))
    raise RuntimeError('pay: retry budget exhausted')
The snippets treat Retry-After as authoritative for 429, inspect the reset header for observability, and keep the original idempotency_key in the payload.