// wallet api reference

Give your AI agent a wallet.
Let it pay its own bills.

AgentKit is a self-serve REST API. Create a wallet, set spending limits, add providers. Your agent calls the API directly — no human in the loop.

REST JSON API Key Auth No monthly fees
base url https://agentkit-2.polsia.app

// api playground

Type your API key, pick an endpoint, hit send. Real requests. Real responses.

try:
Response will appear here

// tutorial

Your first AgentKit transaction, step by step.

01

Create a wallet

Register an agent with a spending limit and initial balance.

POST /api/wallets

// Request
{
  "agent_id": "my-agent-001",
  "spending_limit_cents": 50000,
  "initial_balance_cents": 10000,
  "allowed_providers": ["openai", "stripe"]
}

// Response — 201 Created
{
  "wallet": { "id": 12, "agent_id": "my-agent-001" },
  "api_key": "ak_live_...xxxxxxxx"
}
02

Fund the wallet

Add funds via the credit endpoint, then confirm the new balance.

// Add $50 to wallet
POST /api/wallets/12/credit
X-API-Key: ak_live_...xxxxxxxx

{ "amount_cents": 5000 }

// Confirm balance
GET /api/wallets
X-API-Key: ak_live_...xxxxxxxx

// Response — 200 OK
{ "balance_cents": 15000 }
03

Make a charge

Call /pay with a provider and amount. The policy engine approves or blocks it.

POST /api/pay
X-API-Key: ak_live_...xxxxxxxx

{
  "provider": "openai",
  "amount_cents": 420,
  "idempotency_key": "req-001"
}

// Response — 201 Created
{
  "status": "approved",
  "transaction_id": 4891,
  "balance_cents": 14580
}
04

View the transaction log

Filter by provider or status to see approved and blocked charges.

GET /api/transactions?provider=openai&status=approved
X-API-Key: ak_live_...xxxxxxxx

// Response — 200 OK
{
  "transactions": [
    { "id": 4891, "provider": "openai", "amount_cents": 420, "status": "approved" }
  ]
}

// onboarding tutorial

Run a full wallet lifecycle in 5 minutes. Copy, paste, done.

01

Create a wallet

No auth needed. Give your agent an ID, a spending cap, and an initial balance.

curl
Python
curl -X POST https://agentkit-2.polsia.app/api/wallets \n
  -H "Content-Type: application/json" \n
  -d '{
    "agent_id": "my-agent-001",
    "spending_limit_cents": 50000,
    "initial_balance_cents": 10000,
    "allowed_providers": ["openai", "stripe"]
  }'
import requests

res = requests.post(
    'https://agentkit-2.polsia.app/api/wallets',
    json={
        'agent_id': 'my-agent-001',
        'spending_limit_cents': 50000,
        'initial_balance_cents': 10000,
        'allowed_providers': ['openai', 'stripe']
    }
)
wallet = res.json()
# wallet = {'wallet': {'id': 12, ...}, 'api_key': 'ak_live_...'}
api_key = wallet['api_key']
wallet_id = wallet['wallet']['id']
→ Response
{ "wallet": { "id": 12, ... }, "api_key": "ak_live_xxxxxxxx" }
02

Fund the wallet

Add money with the credit endpoint. Use your new API key.

curl
Python
curl -X POST https://agentkit-2.polsia.app/api/wallets/12/credit \n
  -H "Content-Type: application/json" \n
  -H "X-API-Key: ak_live_xxxxxxxx" \n
  -d '{"amount_cents": 5000}'  # add $50
import requests

res = requests.post(
    'https://agentkit-2.polsia.app/api/wallets/12/credit',
    headers={'X-API-Key': 'ak_live_xxxxxxxx'},
    json={'amount_cents': 5000}  # add $50
)
balance = res.json()['balance_cents']  # 15000
→ Response
{ "balance_cents": 15000 }
03

Make a charge

Call /pay with a provider and amount. The policy engine approves or blocks.

curl
Python
curl -X POST https://agentkit-2.polsia.app/api/pay \n
  -H "Content-Type: application/json" \n
  -H "X-API-Key: ak_live_xxxxxxxx" \n
  -d '{
    "provider": "openai",
    "amount_cents": 420,
    "idempotency_key": "req-001"
  }'
import requests

res = requests.post(
    'https://agentkit-2.polsia.app/api/pay',
    headers={'X-API-Key': 'ak_live_xxxxxxxx'},
    json={
        'provider': 'openai',
        'amount_cents': 420,
        'idempotency_key': 'req-001'
    }
)
result = res.json()
# result = {'status': 'approved', 'balance_cents': 14580}
→ Response
{ "status": "approved", "balance_cents": 14580 }
04

View the transaction log

Filter by provider or status to audit approved and blocked charges.

curl
Python
curl "https://agentkit-2.polsia.app/api/transactions?provider=openai&status=approved" \n
  -H "X-API-Key: ak_live_xxxxxxxx"
import requests

res = requests.get(
    'https://agentkit-2.polsia.app/api/transactions',
    headers={'X-API-Key': 'ak_live_xxxxxxxx'},
    params={'provider': 'openai', 'status': 'approved'}
)
transactions = res.json()['transactions']
→ Response
{ "transactions": [{ "id": 4891, "provider": "openai", "amount_cents": 420, "status": "approved" }] }

// run it now

Single-file Python walkthrough

One script that creates a wallet, funds it, and makes a charge. Copy the file or run it directly — no dependencies beyond the standard library.

download

// expected output

================================================================
  AgentKit Walkthrough
  Base URL: https://agentkit-2.polsia.app
================================================================

[Step 1] Create wallet
  agent_id:              my-agent-001
  spending_limit_cents:  50000  ($500.00)
  initial_balance_cents: 10000 ($100.00)
  allowed_providers:     ['openai', 'stripe']

  ✓ Wallet created (id=13)
  ✓ Initial balance: $100.00

  ⚠️  Save your API key — it's only shown once:
     ak_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

[Step 2] Check balance
  ✓ Balance: $100.00 / $500.00 limit

[Step 3] Fund wallet (+$250.00)
  ✓ New balance: $350.00

[Step 4] Make tool purchase
  provider:     openai
  amount_cents: 420 ($4.20)
  ✓ Approved  (transaction #4892)
  ✓ Remaining balance: $345.80

================================================================
  Walkthrough complete.
================================================================

// troubleshooting

HTTP 401 — invalid API key HTTP 403 — provider not in allowlist HTTP 403 — insufficient balance HTTP 422 — missing required field Connection error — check network

// dashboard tour

A guided tour of the merchant portal areas you'll use most — find each feature, run a quick check, and know what to do first after signup.

AgentKit is API-first, so every "dashboard" view maps to a REST call you can run from your terminal or the playground above. The five areas below are what you'll check most in week one.

01

Review every charge

The transaction log is your single source of truth for wallet activity. Filter by provider or status to see exactly what's been approved, blocked, or rate-limited.

GET /api/transactions?provider=openai&status=approved
X-API-Key: ak_live_...xxxxxxxx

// Response — 200 OK
{
  "transactions": [
    { "id": 4891, "provider": "openai", "amount_cents": 420, "status": "approved" }
  ]
}
02

Inspect webhook deliveries

Every registered webhook is listed below. The fastest verification is the Fire test event button in the test harness above — it dispatches a signed POST without moving real money.

GET /api/v1/webhooks
X-API-Key: ak_live_...xxxxxxxx

// Response — 200 OK
{
  "webhooks": [
    { "id": 42, "url": "https://your-app.com/webhooks/agentkit", "events": ["fund_received", "balance_low"], "status": "active" }
  ]
}
03

Rotate and recover keys

If a key leaks, rotate immediately. The response returns a fresh key and the previous one is revoked the instant the new key is issued.

POST /api/wallets/api-key
X-API-Key: ak_live_...xxxxxxxx

// Response — 201 Created
{
  "api_key": "ak_live_...abcdef123",
  "warning": "Store api_key — shown once only"
}
04

Read your balance and burn rate

AgentKit exposes the numbers — balance_cents and spending_limit_cents on the wallet, plus the full transaction log. Pull both endpoints and sum on the client to chart spend over time.

// Current wallet state
GET /api/wallets
X-API-Key: ak_live_...xxxxxxxx

// Response — 200 OK
{ "balance_cents": 14580, "spending_limit_cents": 50000 }

// Pull last 7 days of approved spend
GET /api/transactions?status=approved
X-API-Key: ak_live_...xxxxxxxx
05

Switch environments safely

The sandbox-balance and sandbox-simulate playground presets (above) call /api/v1/sandbox — those balances are isolated from your live wallet and never deduct real funds.

GET /api/v1/sandbox/balance

// Response — 200 OK
{ "balance_cents": 100000, "isolated": true }

// Sandbox state never touches live wallet balances.

// first five minutes

After signup — work through this list.
  1. Save your API key from the wallet-create response — it's shown once and cannot be retrieved later.
  2. Fund the wallet via POST /api/wallets/:id/credit so your agent has a balance to charge against.
  3. Register a webhook for fund_received and balance_low so you hear when money moves.
  4. Fire a test event from the panel above to confirm your endpoint receives and verifies the signature end-to-end.

// agent-to-agent payment

One AI agent pays another for services using the transfer endpoint.

01

Each agent creates its own wallet

No auth required for wallet creation. Each agent gets its own API key and wallet ID.

curl
Python
# Agent A creates its wallet
curl -X POST https://agentkit-2.polsia.app/api/wallets \n
  -H "Content-Type: application/json" \n
  -d '{"agent_id": "agent-a", "spending_limit_cents": 100000, "initial_balance_cents": 50000}'
# → {"wallet": {"id": 21}, "api_key": "ak_live_aaa..."}

# Agent B creates its wallet
curl -X POST https://agentkit-2.polsia.app/api/wallets \n
  -H "Content-Type: application/json" \n
  -d '{"agent_id": "agent-b", "spending_limit_cents": 100000, "initial_balance_cents": 0}'
# → {"wallet": {"id": 22}, "api_key": "ak_live_bbb..."}
import requests

BASE = 'https://agentkit-2.polsia.app'

# Agent A creates its wallet
res_a = requests.post(f'{BASE}/api/wallets', json={
    'agent_id': 'agent-a',
    'spending_limit_cents': 100000,
    'initial_balance_cents': 50000
})
agent_a = res_a.json()
wallet_a_id = agent_a['wallet']['id']   # 21
key_a = agent_a['api_key']              # "ak_live_aaa..."

# Agent B creates its wallet
res_b = requests.post(f'{BASE}/api/wallets', json={
    'agent_id': 'agent-b',
    'spending_limit_cents': 100000,
    'initial_balance_cents': 0
})
agent_b = res_b.json()
wallet_b_id = agent_b['wallet']['id']   # 22
→ Response (Agent A)
{ "wallet": { "id": 21, "agent_id": "agent-a" }, "api_key": "ak_live_aaa..." }
02

Agent A transfers funds to Agent B

Agent A authenticates with its own API key and calls the transfer endpoint, specifying both wallet IDs and the amount.

curl
Python
curl -X POST https://agentkit-2.polsia.app/api/v1/wallet/transfer \n
  -H "Content-Type: application/json" \n
  -H "X-API-Key: ak_live_aaa..." \n
  -d '{
    "from_wallet_id": 21,
    "to_wallet_id": 22,
    "amount_cents": 1500,
    "idempotency_key": "transfer-req-001"
  }'
import requests

# Agent A pays Agent B $15.00 for a completed task
res = requests.post(
    'https://agentkit-2.polsia.app/api/v1/wallet/transfer',
    headers={'X-API-Key': key_a},
    json={
        'from_wallet_id': wallet_a_id,   # 21 — must match authenticated wallet
        'to_wallet_id':   wallet_b_id,   # 22 — Agent B's wallet
        'amount_cents':   1500,          # $15.00
        'idempotency_key': 'transfer-req-001'
    }
)
result = res.json()
# result['status']            → "completed"
# result['from_balance_cents'] → 48500
# result['to_balance_cents']   → 1500
→ Response — 201 Created
{ "status": "completed", "transfer_id": "txfr_...", "from_balance_cents": 48500, "to_balance_cents": 1500 }

// required fields

Field Type Description
from_wallet_idrequired integer Wallet ID of the payer. Must match the wallet associated with the authenticating API key.
to_wallet_idrequired integer Wallet ID of the recipient. Can be any valid wallet in the system.
amount_centsrequired integer Amount to transfer in cents. Must be a positive integer. Deducted from from_wallet_id and credited to to_wallet_id atomically.
idempotency_key string Optional but recommended. Prevents double-charging if the request is retried. Same key returns the original transfer result.
// expected response — 201 Created
{ "status": "completed", "transfer_id": "txfr_9f4a8b2c...", "from_wallet_id": 21, "to_wallet_id": 22, "amount_cents": 1500, "from_balance_cents": 48500, "to_balance_cents": 1500 }

// try it now

One POST. One charge. Watch the balance drop.

Node.js
Python
const res = await fetch('https://agentkit-2.polsia.app/api/pay', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-API-Key': 'ak_live_...' },
  body: JSON.stringify({ provider: 'openai', amount_cents: 420, idempotency_key: 'req-001' })
});
const { status, balance_cents } = await res.json();
// → { status: 'approved', balance_cents: 9580 }
res = requests.post('https://agentkit-2.polsia.app/api/pay',
  headers={'X-API-Key': 'ak_live_...'},
  json={'provider': 'openai', 'amount_cents': 420, 'idempotency_key': 'req-001'})
status, balance = res.json()['status'], res.json()['balance_cents']
# → { status: 'approved', balance_cents: 9580 }
Replace ak_live_... with your real API key from step 01.
Full Python demo script agent_wallet_demo.py — check balance, fund wallet, make payments, view transactions. Works in under 10 min.
download

// quick start

From zero to first charge in under 2 minutes.

01

Create a wallet

Register an agent with a spending limit and initial balance.

POST /api/wallets

// Request
{
  "agent_id": "my-agent-001",
  "spending_limit_cents": 50000,   // $500/month cap
  "initial_balance_cents": 10000,  // fund with $100
  "allowed_providers": ["openai", "stripe"]
}

// Response 201
{
  "wallet": { "id": 12, "agent_id": "my-agent-001" },
  "api_key": "ak_live_...abcdef123",
  "warning": "Store api_key — shown once only"
}
Store the returned api_key. You cannot retrieve it again.
02

Give key to your agent

Your agent includes the key in every request header.

X-API-Key: ak_live_...abcdef123
03

Agent charges against the wallet

Every /pay call is checked against wallet balance, spending limit, and provider allowlist.

POST /api/pay
X-API-Key: ak_live_...abcdef123

{
  "provider": "openai",
  "amount_cents": 420,        // $4.20
  "idempotency_key": "req-abc123"  // prevent double-charges
}

// Response 201 — approved
{
  "status": "approved",
  "transaction_id": 4891,
  "balance_cents": 9580
}
04

Reconcile via transaction log

Audit every charge — approved or blocked — with provider, amount, and reason.

GET /api/transactions
X-API-Key: ak_live_...abcdef123

// Response 200
{
  "transactions": [
    { "id": 4891, "provider": "openai", "amount_cents": 420, "status": "approved" },
    { "id": 4890, "provider": "anthropic", "amount_cents": 1200, "status": "blocked", "reason": "provider_not_allowed" }
  ]
}
View full endpoint reference → Run the full curl walkthrough → Read the wallet lifecycle guide →

// api reference

All endpoints. All auth requirements. No ambiguity.

Method Endpoint Auth Description
POST /api/wallets None Create a wallet. Returns wallet + api_key. api_key shown once.
GET /api/wallets X-API-Key Get your wallet — balance, spending_limit, policies.
PATCH /api/wallets X-API-Key Update spending_limit_cents.
POST /api/wallets/:id/credit X-API-Key Add funds to wallet. Body: {amount_cents: number}.
POST /api/wallets/policies X-API-Key Set allowed providers. Body: {providers: string[]}.
POST /api/wallets/api-key X-API-Key Regenerate the API key. Previous key is immediately revoked.
POST /api/pay X-API-Key Authorize + deduct a charge. Returns approved or blocked.
GET /api/transactions X-API-Key List transactions. Filter: ?provider=&status=

// policy engine

Every /pay call runs through all checks before a cent is spent.

1

Provider Check

Is the provider in the wallet's allowlist? Block if not.

→
2

Daily Limit

Has the provider hit its daily cap today? Block if exceeded.

→
3

Spend Cap

Is the charge under the wallet's monthly spending limit? Block if over.

→
4

Balance Check

Does the wallet have enough balance? Block if insufficient.

→
✓

Approved

Balance deducted. Transaction logged. Response returned in <50ms.

// supported providers

Any string is accepted. Policy enforcement kicks in only for configured providers.

// AI

openai anthropic google-ai cohere mistral huggingface replicate

// payments

stripe braintree paddle lemon-squeezy plaid

// comms

twilio sendgrid resend postmark mailgun

// infra

aws gcp azure vercel render digitalocean

Missing one? Any string works — just configure the provider name in your policies.

// webhooks

Get notified the moment something happens in your wallet — funds arrive, charges clear, or balance runs low. Register a URL and we POST JSON to it with an HMAC-SHA256 signature you can verify.

// fund_received

Funds added

Fires when POST /api/wallets/:id/credit succeeds. Includes the credited amount and new balance.

// charge_sent

Charge approved

Fires when POST /api/pay approves a charge. Includes provider, amount, transaction ID, and new balance.

// balance_low

Balance threshold

Fires once when balance crosses below 20% of spending limit (or 2000 cents if no limit). Does not re-fire until balance rises above threshold again.

// wallet_spent

Wallet spend

Fires when POST /api/v1/wallets/:agentId/transactions succeeds (non-replay). Payload mirrors the ledger row: tx_id, agent_id, amount, currency, merchant, idempotency_key, spent_at.

// event catalog & payload reference

Every dispatch is a single POST with Content-Type: application/json and a JSON envelope shaped as { event, wallet_id, data, delivered_at }. The data object varies per event — each card below shows the exact shape AgentKit ships. Headers on every request:

  • X-AgentKit-Signature — HMAC-SHA256 hex digest over the raw body bytes, keyed by your signing_secret.
  • X-AgentKit-Webhook-Id — numeric id of the registered webhook that fired (use it to dedupe across retries).

Click an event to expand its payload schema, field-by-field reference, and a Node.js HMAC verification snippet using the exact envelope shape above.

event fund_received POST /api/wallets/:id/credit succeeded

Envelope

{
  "event": "fund_received",
  "wallet_id": 42,
  "data": {
    "wallet_id": 42,
    "amount_cents": 5000,
    "new_balance_cents": 15000
  },
  "delivered_at": "2026-07-18T12:34:56.789Z"
}

Fields

  • data.wallet_id — integer. Wallet that received the credit. Same value as the envelope wallet_id. Not nullable.
  • data.amount_cents — integer. Amount credited (positive). Not nullable.
  • data.new_balance_cents — integer. Wallet balance after the credit. Not nullable.

Verify (Node.js)

const crypto = require('crypto');

// pin to raw body bytes — never JSON.stringify(parsed)
const expected = crypto
  .createHmac('sha256', process.env.AGENTKIT_WEBHOOK_SECRET)
  .update(req.rawBody)
  .digest('hex');
const a = Buffer.from(expected, 'hex');
const b = Buffer.from(req.headers['x-agentkit-signature'], 'hex');
if (a.length !== b.length ||
    !crypto.timingSafeEqual(a, b)) {
  return res.status(401).send('Bad signature');
}
const { event, wallet_id, data } = JSON.parse(req.rawBody);
if (event === 'fund_received') {
  // data: { wallet_id, amount_cents, new_balance_cents }
}
event charge_sent POST /api/pay approved a charge

Envelope

{
  "event": "charge_sent",
  "wallet_id": 42,
  "data": {
    "wallet_id": 42,
    "provider": "openai",
    "amount_cents": 320,
    "transaction_id": 901,
    "new_balance_cents": 9680
  },
  "delivered_at": "2026-07-18T12:34:56.789Z"
}

Fields

  • data.wallet_id — integer. Wallet that was charged. Not nullable.
  • data.provider — string. Provider the charge was billed against (e.g. "openai", "vercel"). Not nullable.
  • data.amount_cents — integer. Charged amount in cents. Not nullable.
  • data.transaction_id — integer. Id of the matching row in transactions. Not nullable.
  • data.new_balance_cents — integer. Wallet balance after the deduction. Not nullable.

Verify (Node.js)

const crypto = require('crypto');

const expected = crypto
  .createHmac('sha256', process.env.AGENTKIT_WEBHOOK_SECRET)
  .update(req.rawBody)
  .digest('hex');
const a = Buffer.from(expected, 'hex');
const b = Buffer.from(req.headers['x-agentkit-signature'], 'hex');
if (a.length !== b.length ||
    !crypto.timingSafeEqual(a, b)) {
  return res.status(401).send('Bad signature');
}
const { event, data } = JSON.parse(req.rawBody);
if (event === 'charge_sent') {
  // data: { wallet_id, provider, amount_cents, transaction_id, new_balance_cents }
}
event wallet_spent POST /api/v1/wallets/:agentId/transactions succeeded

Envelope

{
  "event": "wallet_spent",
  "wallet_id": 42,
  "data": {
    "tx_id": 1234,
    "agent_id": "agent-001",
    "amount": 250,
    "currency": "USD",
    "merchant": "order-9X2",
    "idempotency_key": "k-abc",
    "spent_at": "2026-07-30T12:34:56.789Z"
  },
  "delivered_at": "2026-07-30T12:34:56.789Z"
}

Fields

  • data.tx_id — integer. Ledger row id matching transactions.id. Not nullable.
  • data.agent_id — string. Agent identifier the spend was posted against. Not nullable.
  • data.amount — integer. Debited amount in cents. Not nullable.
  • data.currency — string. ISO 4217 currency code (currently always "USD"). Not nullable.
  • data.merchant — string | null. Caller-supplied merchant_ref (e.g. order id). Nullable when the caller omitted merchant_ref.
  • data.idempotency_key — string | null. Caller-supplied idempotency key, mirrored from the ledger row. Nullable when the caller did not supply one.
  • data.spent_at — string. ISO-8601 timestamp the ledger row was written. Equals transactions.created_at and matches the envelope delivered_at when dispatch is immediate. Not nullable.

Verify (Node.js)

const crypto = require('crypto');

const expected = crypto
  .createHmac('sha256', process.env.AGENTKIT_WEBHOOK_SECRET)
  .update(req.rawBody)
  .digest('hex');
const a = Buffer.from(expected, 'hex');
const b = Buffer.from(req.headers['x-agentkit-signature'], 'hex');
if (a.length !== b.length ||
    !crypto.timingSafeEqual(a, b)) {
  return res.status(401).send('Bad signature');
}
const { event, data } = JSON.parse(req.rawBody);
if (event === 'wallet_spent') {
  // data: { tx_id, agent_id, amount, currency, merchant, idempotency_key, spent_at }
}
event balance_low balance crossed below 20% threshold

Envelope

{
  "event": "balance_low",
  "wallet_id": 42,
  "data": {
    "wallet_id": 42,
    "balance_cents": 800,
    "threshold_cents": 1000
  },
  "delivered_at": "2026-07-18T12:34:56.789Z"
}

Fields

  • data.wallet_id — integer. Wallet whose balance dropped. Not nullable.
  • data.balance_cents — integer. Balance after the charge that triggered the alert. Not nullable.
  • data.threshold_cents — integer. Threshold that was crossed — 20% of spending_limit_cents, or 2000 when no spending limit is set. Not nullable.

Does not re-fire until the wallet balance rises above threshold_cents again. The dispatcher tracks this hysteresis per wallet.

Verify (Node.js)

const crypto = require('crypto');

const expected = crypto
  .createHmac('sha256', process.env.AGENTKIT_WEBHOOK_SECRET)
  .update(req.rawBody)
  .digest('hex');
const a = Buffer.from(expected, 'hex');
const b = Buffer.from(req.headers['x-agentkit-signature'], 'hex');
if (a.length !== b.length ||
    !crypto.timingSafeEqual(a, b)) {
  return res.status(401).send('Bad signature');
}
const { event, data } = JSON.parse(req.rawBody);
if (event === 'balance_low') {
  // data: { wallet_id, balance_cents, threshold_cents }
}
event test synthetic dispatch from /api/v1/webhooks/test

Envelope

{
  "event": "test",
  "wallet_id": 42,
  "data": {
    "wallet_id": 42,
    "test": true
  },
  "delivered_at": "2026-07-18T12:34:56.789Z"
}

Fields

  • data.wallet_id — integer. Wallet the test was fired against. Not nullable.
  • data.test — boolean. Always true. Lets your handler short-circuit bookkeeping side-effects for synthetic deliveries. Not nullable.

The test endpoint accepts an optional event field in the request body — when present it overrides the default "test" and dispatches with that event name instead, which is how the test harness form (further down this page) lets you fire fake copies of fund_received, charge_sent, or balance_low without moving real money.

Verify (Node.js)

const crypto = require('crypto');

const expected = crypto
  .createHmac('sha256', process.env.AGENTKIT_WEBHOOK_SECRET)
  .update(req.rawBody)
  .digest('hex');
const a = Buffer.from(expected, 'hex');
const b = Buffer.from(req.headers['x-agentkit-signature'], 'hex');
if (a.length !== b.length ||
    !crypto.timingSafeEqual(a, b)) {
  return res.status(401).send('Bad signature');
}
const { event, data } = JSON.parse(req.rawBody);
if (event === 'test' && data.test) {
  // synthetic — skip side effects
}

// subscription.renewed  ·  // subscription.expired

Forward-target events — not dispatched by AgentKit

AgentKit does not fire subscription.renewed or subscription.expired itself, and they will be rejected by POST /api/v1/webhooks if you list them in events (only fund_received, charge_sent, balance_low, test are allowed there). These names are the events your billing system posts to your handler, which keeps your customer's plan_status in sync. See the // subscription event handler block below for the full receive-side sample.

// register a webhook

Node.js
Python
cURL
res = await fetch('https://agentkit-2.polsia.app/api/v1/webhooks', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'ak_live_...'
  },
  body: JSON.stringify({
    url: 'https://your-app.com/webhooks/agentkit',
    events: ['fund_received', 'charge_sent', 'balance_low']
  })
});
const { webhook, signing_secret } = await res.json();
// signing_secret shown once — save it now
resp = requests.post(
    'https://agentkit-2.polsia.app/api/v1/webhooks',
    headers={'X-API-Key': 'ak_live_...'},
    json={
        'url': 'https://your-app.com/webhooks/agentkit',
        'events': ['fund_received', 'charge_sent', 'balance_low']
    }
)
result = resp.json()
signing_secret = result['signing_secret']
# signing_secret shown once — save it now
curl -X POST https://agentkit-2.polsia.app/api/v1/webhooks \n
  -H "Content-Type: application/json" \n
  -H "X-API-Key: ak_live_..." \n
  -d '{
    "url": "https://your-app.com/webhooks/agentkit",
    "events": ["fund_received", "charge_sent", "balance_low"]
  }'

// verify signature

Every POST includes X-AgentKit-Signature — an HMAC-SHA256 hex digest of the raw body, signed with your signing_secret. Verify it to ensure the request came from AgentKit.

const crypto = require('crypto');

// Express example — add this middleware
app.post('/webhooks/agentkit', (req, res) => {
  const rawBody = req.rawBody; // must be the unmodified buffer
  const sig = req.headers['x-agentkit-signature'];
  const expected = crypto
    .createHmac('sha256', process.env.AGENTKIT_WEBHOOK_SECRET)
    .update(rawBody)
    .digest('hex');
  if (sig !== expected) {
    return res.status(401).send('Bad signature');
  }
  const { event, wallet_id, data } = JSON.parse(rawBody);
  // Handle event...
  res.status(200).send('OK');
});

// subscription event handler

Same shape as the AgentKit webhooks above — verify the HMAC signature, parse the JSON, branch on event, update your own customer record, and respond 200. The handler below lives in your service (it is not an AgentKit endpoint): when your billing system posts a subscription.renewed or subscription.expired event, this code is what keeps your customer's plan_status in sync.

Node.js
Python
const crypto = require('crypto');

// In-memory customer store for the demo. Replace with your DB.
const CUSTOMERS = new Map(); // customer_id -> {plan_status, current_period_end}

app.post('/webhooks/subscription', (req, res) => {
  const rawBody = req.rawBody;
  const sig = req.headers['x-agentkit-signature'] || '';
  const expected = crypto
    .createHmac('sha256', process.env.AGENTKIT_WEBHOOK_SECRET)
    .update(rawBody)
    .digest('hex');

  const sigBuf = Buffer.from(sig, 'utf8');
  const expBuf = Buffer.from(expected, 'utf8');
  if (sigBuf.length !== expBuf.length ||
      !crypto.timingSafeEqual(sigBuf, expBuf)) {
    return res.status(401).send('Bad signature');
  }

  const { event, data } = JSON.parse(rawBody);
  const customer = CUSTOMERS.get(data.customer_id);
  if (!customer) return res.status(200).send('OK');

  switch (event) {
    case 'subscription.renewed':
      customer.plan_status = 'active';
      customer.current_period_end = data.current_period_end;
      break;
    case 'subscription.expired':
      customer.plan_status = 'expired';
      console.log('subscription revoked', customer);
      break;
  }
  res.status(200).send('OK');
});
import os, hmac, hashlib
from flask import Flask, request

app = Flask(__name__)
CUSTOMERS = {}  # customer_id -> {plan_status, current_period_end, ...}

@app.post('/webhooks/subscription')
def subscription_event():
    raw = request.get_data()
    sig = request.headers.get('X-AgentKit-Signature', '')
    expected = hmac.new(
        os.environ.get('AGENTKIT_WEBHOOK_SECRET', 'testsecret').encode(),
        raw, hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(sig, expected):
        return ('Bad signature', 401)

    payload = request.get_json()
    customer = CUSTOMERS.get(payload['data']['customer_id'])
    if customer is None:
        return ('OK', 200)

    if payload['event'] == 'subscription.renewed':
        customer['plan_status'] = 'active'
        customer['current_period_end'] = payload['data']['current_period_end']
    elif payload['event'] == 'subscription.expired':
        customer['plan_status'] = 'expired'
        print('subscription revoked', customer)
    return ('OK', 200)

if __name__ == '__main__':
    app.run(port=int(os.environ.get('PORT', 3000)))

// test with ngrok

Start the handler in one shell, then expose it with ngrok http 3000 and copy the https://... forwarding URL — register it as the destination for your subscription events, then run the script below to send a signed payload at that URL. The script signs the body with HMAC-SHA256 and posts it; pass the same --secret you exported when you started the handler.

Node.js
Python
const crypto = require('crypto');
const http = require('http');

const secret = process.env.AGENTKIT_WEBHOOK_SECRET || 'testsecret';
const url = process.argv[2];  // e.g. https://abc123.ngrok.app/webhooks/subscription
const isExpired = process.argv.includes('--expired');

const payload = isExpired
  ? { event: 'subscription.expired', data: { customer_id: 'cus_demo_1' } }
  : { event: 'subscription.renewed', data: { customer_id: 'cus_demo_1', current_period_end: 1735776000 } };
const body = JSON.stringify(payload);
const sig = crypto.createHmac('sha256', secret).update(body).digest('hex');

const u = new URL(url);
const req = http.request({
  hostname: u.hostname, port: u.port || 443, path: u.pathname,
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-AgentKit-Signature': sig }
}, res => {
  let buf = '';
  res.on('data', c => buf += c);
  res.on('end', () => console.log('status=' + res.statusCode + ' body=' + buf));
});
req.on('error', console.error);
req.write(body);
req.end();
import argparse, hashlib, hmac, http.client, json, urllib.parse

PRESETS = {
    'renewed': {
        'event': 'subscription.renewed',
        'data': { 'customer_id': 'cus_demo_1', 'current_period_end': 1735776000 },
    },
    'expired': {
        'event': 'subscription.expired',
        'data': { 'customer_id': 'cus_demo_1' },
    },
}

p = argparse.ArgumentParser()
p.add_argument('--url', required=True)
p.add_argument('--secret', default='testsecret')
p.add_argument('--event', choices=['renewed', 'expired'], default='renewed')
args = p.parse_args()

body = json.dumps(PRESETS[args.event]).encode()
sig = hmac.new(args.secret.encode(), body, hashlib.sha256).hexdigest()

u = urllib.parse.urlparse(args.url)
Conn = http.client.HTTPSConnection if u.scheme == 'https' else http.client.HTTPConnection
conn = Conn(u.hostname, u.port or (443 if u.scheme == 'https' else 80))
conn.request(
    'POST', u.path or '/', body,
    { 'Content-Type': 'application/json', 'X-AgentKit-Signature': sig },
)
resp = conn.getresponse()
resp_body = resp.read().decode()
print(f'status={resp.status} body={resp_body!r}')

marker = 'active' if args.event == 'renewed' else 'expired'
if resp.status == 200:
    print(f'✓ handler accepted · customer plan_status={marker}')
elif resp.status == 401:
    print('✗ 401 — bad signature')

// test harness

Fire a synthetic event to your registered webhooks without moving real money. The dropdown sets the event name on the dispatched payload — pick fund_received, charge_sent, wallet_spent, or balance_low to dry-run that handler branch, or leave it on test for a plain sanity check.

Enter your API key to see registered webhooks

// recent deliveries

No deliveries yet

// list and delete

Node.js
Python
cURL
// List webhooks
const list = await fetch('https://agentkit-2.polsia.app/api/v1/webhooks',
  { headers: { 'X-API-Key': apiKey } });
const { webhooks } = await list.json();
// → [{ id, url, events, is_active }]

// Delete a webhook
await fetch('https://agentkit-2.polsia.app/api/v1/webhooks/42',
  { method: 'DELETE', headers: { 'X-API-Key': apiKey } });
# List webhooks
resp = requests.get('https://agentkit-2.polsia.app/api/v1/webhooks',
    headers={'X-API-Key': api_key})
webhooks = resp.json()['webhooks']

# Delete a webhook
requests.delete('https://agentkit-2.polsia.app/api/v1/webhooks/42',
    headers={'X-API-Key': api_key})
# List webhooks
curl https://agentkit-2.polsia.app/api/v1/webhooks \n
  -H "X-API-Key: ak_live_..."

# Delete a webhook
curl -X DELETE https://agentkit-2.polsia.app/api/v1/webhooks/42 \n
  -H "X-API-Key: ak_live_..."

// pricing

Self-serve. No sales call. No monthly minimum.

pay-as-you-go
1.5%
per transaction
  • ✓ Wallet creation
  • ✓ Policy engine
  • ✓ Transaction logs
  • ✓ 40+ providers
  • ✓ Idempotency keys
  • ✓ Real-time balance
example $500/month spend → $7.50/month AgentKit
volume
Custom
contact for pricing
  • ✓ Everything in pay-as-you-go
  • ✓ Volume discounts
  • ✓ Dedicated support
  • ✓ SLA guarantees
  • ✓ Custom integrations
  • ✓ Invoice billing
Talk to us →

// integration examples

Node.js
Python
cURL
// npm install agentkit (coming soon)
// For now, use fetch:

const BASE = 'https://agentkit-2.polsia.app';

async function createWallet(agentId, limit) {
  const res = await fetch(`${BASE}/api/wallets`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      agent_id: agentId,
      spending_limit_cents: limit,
      initial_balance_cents: 10000,
      allowed_providers: ['openai', 'stripe']
    })
  });
  return res.json();
}

async function charge(apiKey, provider, amountCents) {
  const res = await fetch(`${BASE}/api/pay`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': apiKey
    },
    body: JSON.stringify({
      provider,
      amount_cents: amountCents,
      idempotency_key: crypto.randomUUID()
    })
  });
  return res.json();
}
import requests

BASE = 'https://agentkit-2.polsia.app'

def create_wallet(agent_id, limit_cents):
    res = requests.post(
        f'${BASE}/api/wallets',
        json={
            'agent_id': agent_id,
            'spending_limit_cents': limit_cents,
            'initial_balance_cents': 10000,
            'allowed_providers': ['openai', 'stripe']
        }
    )
    return res.json()

def charge(api_key, provider, amount_cents):
    res = requests.post(
        f'${BASE}/api/pay',
        headers={'X-API-Key': api_key},
        json={
            'provider': provider,
            'amount_cents': amount_cents,
            'idempotency_key': __import__('uuid').uuid4().hex
        }
    )
    return res.json()
# Create wallet
curl -X POST https://agentkit-2.polsia.app/api/wallets \n
  -H "Content-Type: application/json" \n
  -d '{
    "agent_id": "my-agent-001",
    "spending_limit_cents": 50000,
    "initial_balance_cents": 10000,
    "allowed_providers": ["openai", "stripe"]
  }'

# Pay (with API key)
curl -X POST https://agentkit-2.polsia.app/api/pay \n
  -H "Content-Type: application/json" \n
  -H "X-API-Key: ak_live_..." \n
  -d '{
    "provider": "openai",
    "amount_cents": 420,
    "idempotency_key": "req-abc123"
  }'

# Get transactions
curl https://agentkit-2.polsia.app/api/transactions \n
  -H "X-API-Key: ak_live_..." \n
  -G -d "provider=openai" -d "status=approved"

// framework integrations

Drop AgentKit into your existing agent framework. One function, one tool registration — your agent pays its own bills.

LangChain
AutoGen
# pip install langchain langchain-openai requests
import os, uuid, requests
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_tools_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

BASE_URL = 'https://agentkit-2.polsia.app'
API_KEY  = os.environ['AGENTKIT_API_KEY']

@tool
def pay_provider(provider: str, amount_cents: int) -> str:
    """Authorize and deduct a payment from the agent's AgentKit wallet."""
    r = requests.post(f'{BASE_URL}/api/pay',
        headers={'X-API-Key': API_KEY},
        json={'provider': provider, 'amount_cents': amount_cents,
              'idempotency_key': uuid.uuid4().hex}, timeout=15)
    d = r.json()
    return f"status={d['status']} balance_cents={d.get('balance_cents','?')}"

llm   = ChatOpenAI(model="gpt-4o-mini", temperature=0)
tools = [pay_provider]
prompt = ChatPromptTemplate.from_messages([
    ("system", "Use pay_provider when asked to pay for something."),
    ("human", "{input}"), MessagesPlaceholder("agent_scratchpad"),
])
executor = AgentExecutor(agent=create_openai_tools_agent(llm, tools, prompt), tools=tools)
result   = executor.invoke({"input": "Pay openai $4.20 for an API call."})
print(result['output'])
# → status=approved balance_cents=34580 ($345.80 remaining)
download
# pip install pyautogen requests
import os, uuid, requests, autogen

BASE_URL = 'https://agentkit-2.polsia.app'
API_KEY  = os.environ['AGENTKIT_API_KEY']
LLM_CFG  = {'config_list': [{'model': 'gpt-4o-mini', 'api_key': os.environ['OPENAI_API_KEY']}]}

def pay_provider(provider: str, amount_cents: int) -> str:
    """Authorize and deduct a payment from the agent's AgentKit wallet."""
    r = requests.post(f'{BASE_URL}/api/pay',
        headers={'X-API-Key': API_KEY},
        json={'provider': provider, 'amount_cents': amount_cents,
              'idempotency_key': uuid.uuid4().hex}, timeout=15)
    d = r.json()
    return f"status={d['status']} balance_cents={d.get('balance_cents','?')}"

assistant = autogen.ConversableAgent("assistant", llm_config=LLM_CFG,
    system_message="Call pay_provider when asked to pay.")
user = autogen.ConversableAgent("user", human_input_mode="NEVER",
    is_termination_msg=lambda m: "TERMINATE" in m.get("content", ""))

autogen.register_function(pay_provider, caller=assistant, executor=user,
    name="pay_provider", description="Charge the AgentKit wallet.")

user.initiate_chat(assistant, message="Pay openai 420 cents for an API call.",
    max_turns=3)
# → status=approved balance_cents=34160 ($341.60 remaining)
download

LangChain: pip install langchain langchain-openai requests  |  AutoGen: pip install pyautogen requests

// examples

Runnable starter projects. Clone, fork, or download — pick the closest one and edit it to fit your business logic.

// basic-checkout

Basic Checkout Flow

Minimal Express server: a single POST /charge endpoint that authorizes and deducts a payment from an AgentKit wallet.

Express AgentKit X-API-Key
clone on github open in codesandbox download zip
// subscription-billing

Subscription Billing

Express webhook listener for charge.cleared events. Schedules the next billing cycle and re-settles between two wallets via the atomic transfer endpoint.

Express AgentKit X-API-Key
clone on github open in codesandbox download zip
// agent-to-agent

Agent-to-Agent Payment

Two Express agents settle a charge end-to-end using /api/pay plus the atomic /api/v1/wallet/transfer endpoint with idempotency keys.

Express AgentKit X-API-Key
clone on github open in codesandbox download zip

Spin up locally with npm install && npm start in each starter — they share one .env.example listing AGENTKIT_API_KEY and AGENTKIT_BASE_URL.

// authentication

How keys are issued, how to send them on every request, what a given key can do, and how to test your setup before making a real charge. Read this once — the rules below are exactly what the server enforces.

// quick checklist — under a minute

Tick every box before your first real call. If you cannot tick all six, the most likely culprit is item 5 (key shape) or item 6 (rotation pattern).

// 01

☐ Created a wallet via POST /api/wallets and captured the api_key value from the response (it starts with ak_).

// 02

☐ Stored the key in a secret manager / env var — never in source, never in a browser, never in a client-side bundle.

// 03

☐ Reached the sandbox without any header: GET /api/v1/sandbox/balance returns 200 with a body containing "sandbox": true.

// 04

☐ Proved both auth paths: GET /api/wallets with your X-API-Key returns 200 — the same call with a missing or wrong header returns 401.

// 05

☐ Confirmed the value matches ^ak_[a-f0-9]{64}$ before shipping — anything else (typo, truncated copy, env-var name leakage) will be rejected with code: unauthorized.

// 06

☐ Planned deploy-time rotation via POST /api/wallets/api-key — store the new value alongside the deploy that starts reading it, then deprecate the old one.

// key types

Every minted key has the same shape: the literal prefix ak_ followed by 64 lowercase hex characters (32 random bytes). There is no live/test prefix split — the distinction is purely operational: a real key talks to the live API, while the mock sandbox is reachable without any header at all.

// live keys

Sent as X-API-Key: ak_… against the live base URL https://agentkit-2.polsia.app. Required for every authenticated endpoint:

  • GET /api/wallets · PATCH /api/wallets
  • POST /api/wallets/policies
  • POST /api/wallets/<id>/credit
  • POST /api/wallets/api-key (rotate)
  • POST /api/pay
  • POST /api/v1/wallet/transfer
  • GET /api/transactions

Every authenticated route is gated by middleware/auth.js, which checks the header, looks up key_hash in api_keys, and attaches req.walletId + req.agentId to the request.

// test path (sandbox)

The endpoints under /api/v1/sandbox/* require no header at all — they run against an in-memory mock wallet and never touch the wallets or transactions tables. Build agent logic against the sandbox first, then switch the base URL and add the header when going live.

  • GET /api/v1/sandbox/balance
  • POST /api/v1/sandbox/simulate

Every sandbox response includes "sandbox": true — treat that flag as a hard guard in test code so a live call cannot accidentally slip through.

// Key shape — every key minted by db/apiKey.js uses this format
ak_ + 64 lowercase hex chars
     ^
     KEY_PREFIX = 'ak_'          // db/apiKey.js:5
     KEY_BYTES = 32               // db/apiKey.js:6 → crypto.randomBytes(32).toString('hex')
  cc974c2...e8a1fd          // example (32 bytes = 64 hex chars)

// Regex check before you ship — anything that fails this is rejected:
^ ak_ [a-f0-9]{64} $

// request headers

Authenticated requests send one header: X-API-Key. The Authorization: Bearer … form is also accepted as a fallback — neither is HMAC-signed. Request bodies are not signed today. Webhook deliveries to your receiver are signed with X-AgentKit-Signature (see // webhooks) — that is a separate channel from request auth and uses a different secret.

Node.js
Python
cURL
// Authenticated GET /api/wallets — header form
const r = await fetch('https://agentkit-2.polsia.app/api/wallets', {
  headers: { 'X-API-Key': process.env.AGENTKIT_API_KEY }
});
const { wallet } = await r.json();

// Same call with the Bearer-style fallback
const r2 = await fetch('https://agentkit-2.polsia.app/api/wallets', {
  headers: { 'Authorization': 'Bearer ' + process.env.AGENTKIT_API_KEY }
});
import os, requests

API_KEY = os.environ['AGENTKIT_API_KEY']
BASE    = 'https://agentkit-2.polsia.app'

# Header form
r = requests.get(f'{BASE}/api/wallets',
                 headers={'X-API-Key': API_KEY},
                 timeout=10)
wallet = r.json()['wallet']

# Bearer fallback
r2 = requests.get(f''{BASE}'/api/wallets',
                  headers={'Authorization': f'{Bearer {API_KEY}}'},
                  timeout=10)
# Header form
curl -sS -H "X-API-Key: ak_$(printf '%064x' 1 | head -c 64)" \
     https://agentkit-2.polsia.app/api/wallets

# Bearer fallback
curl -sS -H "Authorization: Bearer ak_$(printf '%064x' 1 | head -c 64)" \
     https://agentkit-2.polsia.app/api/wallets

# Prove the rejection path is wired
curl -i https://agentkit-2.polsia.app/api/wallets
→ HTTP/1.1 401 {"error":"Missing X-API-Key header","code":"unauthorized","message":"Authentication is required or the API key is invalid.","request_id":"req_..."}

curl -i -H "X-API-Key: ak_doesnotexist" \
     https://agentkit-2.polsia.app/api/wallets
→ HTTP/1.1 401 {"error":"Invalid API key","code":"unauthorized","message":"Authentication is required or the API key is invalid.","request_id":"req_..."}
Pick one header style per codebase — do not mix X-API-Key on some calls and Authorization: Bearer on others. The Authorization path is a fallback for HTTP libraries that strip non-standard headers by default.

// scopes & permissions

One key, one wallet — that is the entire model. The DB enforces it: api_keys.wallet_id is a foreign key into wallets.id, and every authenticated route resolves the wallet by joining back through the key. Routes then re-check ownership by comparing the URL's wallet id against the wallet that backs the presented key.

Bucket Endpoint Auth Notes
Authenticated (your wallet only) GET /api/wallets · PATCH /api/wallets · POST /api/wallets/policies · POST /api/wallets/<id>/credit · POST /api/wallets/api-key · GET /api/transactions X-API-Key Always resolves to the wallet backing the key; :id in the URL must match or the call returns 403.
Authenticated (global) POST /api/pay · POST /api/v1/wallet/transfer X-API-Key Pay charges against your wallet; transfer debits your wallet (you cannot initiate a transfer from a wallet you don't own).
Anonymous (registration) POST /api/wallets none Mints a wallet + the first api_key. The wallet is bound to the agent_id you supply and cannot be re-created (409).
Anonymous (sandbox) GET /api/v1/sandbox/balance · POST /api/v1/sandbox/simulate none In-memory mock wallet, no DB writes, every response tagged "sandbox": true. Safe to call from anywhere.

There is no admin scope — a key minted for one wallet cannot read another wallet's transactions, cannot credit someone else's balance, and cannot rotate someone else's key. Cross-wallet attempts are rejected with 403 "Cannot credit another wallet" or 403 forbidden on transfer (see // troubleshooting).

// rotate a key

POST /api/wallets/api-key mints a fresh key for the wallet backing your current key. The new value is returned in the response body — store it before you ack the deploy. Optional label in the body (defaults to "primary") so you can tag which deploy a key was issued for.

Honest about behavior: rotation adds a new row to api_keys — it does not invalidate the old one. During the overlap window, dual-send (send both the old and the new value at deploy time) so traffic in flight still validates; then remove the old value from your env. Plans that promise "the old key stops validating at the swap" describe a future behavior, not what the server does today.

Node.js
Python
// Authenticated with the CURRENT key — mints a new key for your own wallet
const r = await fetch('https://agentkit-2.polsia.app/api/wallets/api-key', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': process.env.AGENTKIT_API_KEY   // current key
  },
  body: JSON.stringify({ label: 'deploy-2026-07' }),
});
const { api_key, warning } = await r.json();
console.log(warning);   // "Store api_key — it is shown once and cannot be retrieved"
// → write api_key to your secret manager NOW; the server will not show it again
import os, requests

API_KEY = os.environ['AGENTKIT_API_KEY']
BASE    = 'https://agentkit-2.polsia.app'

r = requests.post(
    f'{BASE}/api/wallets/api-key',
    headers={'X-API-Key': API_KEY},          # current key
    json={'label': 'deploy-2026-07'},
    timeout=15,
)
body = r.json()
print(body['warning'])           # one-shot warning
# → persist body['api_key'] to your secret store NOW;
#    the server will not show it again.
Treat every rotation as a write-once event: relay the response directly to your secret manager, then ack the deploy. Rotating mid-deploy with the old value still live is the common cause of stale-only 401 Invalid API key errors.

// test locally with the sandbox

The endpoints under /api/v1/sandbox/* are reachable without an API key — they exercise the same response shapes /api/wallets, /api/pay, and the transfer/preview paths use in production, but they never touch your real wallet. Run these before you sign off on auth wiring:

# 1. Sandbox balance — no header
curl -sS https://agentkit-2.polsia.app/api/v1/sandbox/balance
# → 200 { "wallet": { ... }, "sandbox": true }
# 2. Sandbox charge simulation — same body shape as POST /api/pay
curl -sS -X POST https://agentkit-2.polsia.app/api/v1/sandbox/simulate \
  -H 'Content-Type: application/json' \
  -d '{"provider":"openai","amount_cents":420}'
# → 201 { "status": "approved", "transaction": { ... },
#          "balance_cents": 11925, "sandbox": true }
// 3. Same /simulate call from Node.js — proves the auth-less round-trip
const r = await fetch('https://agentkit-2.polsia.app/api/v1/sandbox/simulate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ provider: 'openai', amount_cents: 420 }),
});
const result = await r.json();
if (!result.sandbox) throw new Error('expected sandbox flag');

When you're ready: replace the base URL with https://agentkit-2.polsia.app (the same one, in this case) and add X-API-Key: ak_… — the only thing that changes between sandbox and live is the presence of the key and the wallet the key resolves to.

// error handling

The API now returns a standard code, message, and request_id envelope for every 4xx and 5xx response. The complete endpoint matrix, headers, and retry guidance live on the dedicated reference page.

→

Read the error envelope, error-code matrix, or rate-limit and retry guide. Policy responses still include their audit fields such as transaction and reason.

// api collections

Downloadable Postman v2.1 and Bruno collections covering every public endpoint with example request and response payloads. After import, paste your X-API-Key into the agentkitApiKey environment variable — every request in the Auth & Wallets, Charges, Transfers, and Subscriptions & Webhooks folders will then execute against the sandbox; the Sandbox folder runs with no key required.

Postman Collection (v2.1) agentkit.postman_collection.json — 15 endpoints across 5 folders (Auth & Wallets, Charges, Transfers, Subscriptions & Webhooks, Sandbox), sandbox credentials pre-wired via the companion environment file.
Bruno Collection samples/bruno/ — same 15 endpoints, same example payloads. Bruno imports folders, not single JSON files: clone the repo, download the bruno.json manifest + environments/Sandbox.bru, or open the folder directly in Bruno's "Import Collection" dialog.

// troubleshooting

The errors you will actually hit, with the off-ramp right next to the cause. Skim it once — your agent will hit most of these — and self-serve in under a minute.

401 Missing X-API-Key header absent or key was rotated

Server returned code: "unauthorized" with legacy error: "Missing X-API-Key header". Either the request never carried the header, or the value your code is reading is stale. Use the standard error envelope fields for logging.

  • Re-pull the key from your secret store at startup; do not cache the value across deploys in memory.
  • If you just rotated (via POST /api/wallets/api-key), ship the new value in the same deploy that starts reading it — the old key stops validating at the swap, with no overlap.
  • Confirm your HTTP client is not silently dropping headers (proxies, middleware that strips unknown headers, default allowlists).
401 Invalid API key header present but unknown

Server returned code: "unauthorized" with legacy error: "Invalid API key". The header is present, but the value did not match a stored key.

  • Confirm the value starts with ak_live_ — anything else (typo truncation, env-var name leak, header-name swap) is rejected.
  • Check for trailing whitespace, newlines, or stray quoting in the env var; string-concat bugs are the usual culprit.
  • Confirm the wallet still exists: POST /api/wallets with the same agent_id will return 409 "Wallet already exists" if it does, which proves the wallet is alive and the key is the real problem.
400 Invalid request body bad field — error cites the exact name

The standard error envelope uses code: "invalid_request", a human-readable message, and request_id; the legacy error text still names the offending field, for example "agent_id is required", "amount_cents must be a positive number", "amount_cents exceeds maximum (100000000)", or "from_wallet_id must be an integer".

  • Spot-fix the named field and resubmit — these messages are precise, do not retry the same payload verbatim.
  • For "amount_cents exceeds maximum (100000000)": split into multiple transfers, each under $1,000.00; /api/v1/wallet/transfer caps per-call at this ceiling.
  • For "from_wallet_id must be an integer": the field arrived as a string (common in JSON encoders that stringify all numbers) — coerce before sending.
403 Policy block /api/pay returned { "status": "blocked", "reason": "..." }

Your charge was declined by the policy engine. The standard envelope includes code, message, and request_id; the body also carries "status": "blocked" and a "reason". Fix by the reason, then replay the same idempotency_key:

  • provider_not_allowed — call POST /api/wallets/policies with the new provider in the providers array.
  • insufficient_balance — top up with POST /api/wallets/:id/credit; replay the original /api/pay with the same idempotency_key.
  • daily_limit_exceeded — wait until UTC midnight rolls the counter, or POST /api/wallets/policies with a higher daily_limit_cents for that provider.
  • spending_limit_exceeded — raise the per-charge ceiling with PATCH /api/wallets setting spending_limit_cents.
409 Wallet already exists reusing an agent_id

POST /api/wallets returned code: "invalid_request" with legacy "Wallet already exists for this agent_id". Wallets are 1:1 with agent_id — there is no upsert path.

  • Confirm the original wallet is reachable with GET /api/wallets and your stored X-API-Key (a fresh 404 means the wallet was deleted; recreate is your only path).
  • If the agent is a new one, mint a fresh agent_id (stable across that agent's lifetime — do not randomize per run) and call POST /api/wallets again.
429 Too Many Requests quota overflow

You hit the per-wallet or per-IP rate limit. The response carries Retry-After on 429s and the standard X-RateLimit-* headers on every response.

  • Honor Retry-After verbatim when present; never tight-loop on a 429.
  • Otherwise, jittered exponential backoff: delay = random(0, base * 2^n), cap retries at five attempts. See the ready-made retry pattern.
  • Serialize write calls per wallet — concurrent agents on one wallet will trip the limit faster than per-agent quotas imply.
  • Watch X-RateLimit-Remaining on every response and back off proactively once it drops below 10%.
403 Cross-wallet forbidden API key does not own the target wallet

Calling POST /api/wallets/:id/credit or POST /api/v1/wallet/transfer where the URL wallet id does not match the wallet backing your X-API-Key returns code: "forbidden" with the legacy error text and a field-level reason.

  • Confirm the X-API-Key you are sending is ak_live_… for the wallet whose id is in the URL — not a sibling wallet's key.
  • Swap the URL wallet id, not the key — this almost always means your code resolved the wrong wallet from your own store. Treat it as a logic bug, not transit.
wh Webhook signature mismatch X-AgentKit-Signature rejected

Your receiver returned non-2xx (or your server log shows ok: false on a delivered event). Every delivery carries an X-AgentKit-Signature HMAC-SHA256 over the raw JSON body.

  • Compute HMAC-SHA256 over the raw request body bytes — not over a re-stringified parse of the JSON. Any whitespace difference breaks the signature.
  • Compare with crypto.timingSafeEqual, not === — string equality leaks timing information.
  • Confirm the secret matches what was returned at registration: POST /api/v1/webhooks. Secrets are shown exactly once.
  • End-to-end prove your receiver with POST /api/v1/webhooks/test — fires a synthetic test event to every active URL with the same signed payload structure.
// Verify an X-AgentKit-Signature header in Node.js (use the RAW body)
const crypto = require('crypto');

function verifyAgentKitSig(rawBody, header, secret) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)   // bytes, not JSON.stringify(parsed)
    .digest('hex');
  const a = Buffer.from(expected, 'hex');
  const b = Buffer.from(header, 'hex');
  if (a.length !== b.length) return false;
  return crypto.timingSafeEqual(a, b);
}

The verify block assumes you captured the raw bytes before JSON parsing. In Express, that means app.use('/webhooks', express.raw({ type: 'application/json' })) on the receiver route — not express.json().

// going to production

The checklist below is the bar for shipping. Confirm each item before you cut traffic over — every checkbox ties back to a real AgentKit symbol, not generic advice.

// precondition: proxy through your own server

All requests must come from your server, not a browser or end-user client

The public base URL is https://agentkit-2.polsia.app. Calling it directly from a browser, mobile app, or other end-user surface leaks the X-API-Key header to anyone who can read the network traffic. Put a thin server-side proxy between your product and AgentKit; have your agents call your proxy, and have the proxy call AgentKit. This is the precondition for every item below.

// api-key-rotation

☐ API key rotation Rotate without downtime

Use POST /api/wallets/api-key to mint a fresh ak_live_… key on demand (also reachable via POST /api/wallets at wallet creation). Store the new value alongside the deploy that introduces it, dual-send during the overlap window, then deprecate the old key.

Keys are returned exactly once — the response includes "Store api_key — it is shown once and cannot be retrieved". Persist them to your secret manager at deploy time, not on first use.

// webhook-signature-verification

☐ Webhook signature verification Verify the raw body, then act

Every delivery carries an X-AgentKit-Signature HMAC-SHA256 header. Compute it over the raw request body (bytes, not parsed JSON — re-serializing changes the bytes) and compare with crypto.timingSafeEqual. Reject any POST without a valid signature; do not even log the payload before verification.

Before going live, prove your receiver end-to-end with POST /api/v1/webhooks/test, which fires a synthetic test event to all your active URLs.

// idempotent-payments

☐ Idempotent payment handling One logical charge, one debit

Generate a stable idempotency_key per logical charge (UUIDv4 is fine — the key just needs to be the same on every retry of the same charge) and pass it on POST /api/pay and POST /api/v1/wallet/transfer. A retry that re-sends the same key returns the original response — never double-debits.

If you cannot reconstruct the key on retry, your agents are not idempotent yet — fix the call site before you ship.

// rate-limit-handling

☐ Rate limit handling Back off on 429 with jitter

Expect 429 Too Many Requests under bursty agent traffic. If a Retry-After header is present, honor it verbatim. If not — or on repeated 429s — implement exponential backoff with full jitter (delay = random(0, base * 2^n)) and cap retries; never tight-loop on a 429.

Serialize write calls per wallet where you can — agents sharing one wallet contending on /api/pay will trip limits faster than per-agent quotas would suggest.

// monitoring-and-logging

☐ Monitoring & logging Mirror the audit log, alert on blocks

Poll GET /api/transactions on a schedule (filter by ?status=blocked when investigating) and persist the rows as your own audit log mirror. Alert on status=blocked with reason=daily_limit_exceeded or reason=insufficient_balance — those mean your policies or funding assumptions went wrong.

Subscribe to the balance_low webhook (fires once when balance drops below 20% of the spending limit) and page on it. Never log the raw X-API-Key header value — log key fingerprints at most.

Every box above ticked is the bar for production-ready on AgentKit. Read it, confirm your implementation covers each item, and ship.

// changelog

Public AgentKit API changes — additions, deprecations, breaking changes — in reverse chronological order. Tagged with the affected endpoint(s) and the version that shipped them. New entries are appended at the top.

// 2026-07-29 · v0.9.0 · added

Stripe Connect wallet top-up — fund endpoint returns Stripe payment URL; claim endpoint atomically credits wallet + appends `stripe_topup` ledger row

POST /api/v1/wallets/:agentId/fund POST /api/v1/wallets/:agentId/fund/claim

Two-step top-up via the platform's built-in Stripe Connect account: agent asks the server for a checkout session, redirects buyer to Stripe, then claims the verified payment to atomically credit the wallet — same current_balance_cents + amount ledger write as POST /api/wallets/:id/credit. Reuses the existing fund_received webhook. Currency must match the wallet (USD only today; other currencies return 422 unsupported_currency). See // fund and // fund/claim. Migration: funding_intents (additive).

// 2026-07-28 · v0.8.0 · added

Multi-agent payment split endpoint

POST /api/v1/payments/split

Atomically split one charge across N agent wallets with a single routing rule (percentage or fixed-amount per agent). Persists a parent payment plus child ledger rows on the existing transactions table; partial splits roll back. See the full reference page for parameters, response shape, and error codes. Migration: payment_split_tables (additive, no column changes).

// 2026-07-12 · v0.7.0 · added

Dedicated errors and rate-limits reference published

all authenticated routes

Dedicated HTTP error envelope, endpoint code matrix, X-RateLimit-* header behavior, and Node.js + Python retry snippets with exponential backoff and idempotency-key handling. See /developers/errors.

// 2026-07-05 · v0.6.0 · added

Authentication guide published on /developers

every authenticated route

Full authentication guide: key shape (^ak_[a-f0-9]{64}$), live/sandbox buckets, X-API-Key / Authorization: Bearer header choices, scopes table, POST /api/wallets/api-key rotation, Node.js + Python + cURL examples. See // authentication.

// 2026-06-28 · v0.5.0 · added

Webhook handler: register/list/delete + synthetic test endpoint

POST /api/v1/webhooks GET /api/v1/webhooks DELETE /api/v1/webhooks/:id POST /api/v1/webhooks/test

Register, list, and delete webhook endpoints, plus a synthetic POST /api/v1/webhooks/test for round-trip verification. Signatures are HMAC-SHA256 over the raw request body; deliveries are deduped by the X-AgentKit-Webhook-Id header. See // webhooks.

// 2026-06-17 · v0.4.0 · added

Atomic wallet-to-wallet transfer with idempotency keys

POST /api/v1/wallet/transfer

Atomic wallet-to-wallet transfer with idempotency keys and deadlock-safe row locking. See the agent-to-agent payment walkthrough for a worked example. Migration: none (purely additive).

// 2026-06-01 · v0.2.0 · added

Initial balance on wallet creation, top-up endpoint, transaction filters

POST /api/wallets POST /api/wallets/:id/credit GET /api/transactions

Added initial_balance_cents as an optional field on POST /api/wallets; introduced POST /api/wallets/:id/credit to add funds to an existing wallet; and added provider and status query filters on GET /api/transactions. Migration: none (additive).

// 2026-05-30 · v0.1.0 · added

Initial AgentKit wallet API release

POST /api/wallets GET /api/wallets PATCH /api/wallets POST /api/wallets/policies POST /api/pay GET /api/transactions

First public AgentKit release: wallet create/get/update, policy-controlled charge with spending limits and allowed providers, full transaction log. Auth via X-API-Key header. Migration: N/A (first release).

Breaking-change entries above link to a // migration — YYYY-MM-DD anchor block. None of the seeded entries are breaking; the slot is reserved for future use.