// wallet api reference
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.
https://agentkit-2.polsia.app
Type your API key, pick an endpoint, hit send. Real requests. Real responses.
Your first AgentKit transaction, step by step.
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"
}
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 }
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
}
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" }
]
}
Run a full wallet lifecycle in 5 minutes. Copy, paste, done.
No auth needed. Give your agent an ID, a spending cap, and an initial balance.
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']
Add money with the credit endpoint. Use your new API key.
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
Call /pay with a provider and amount. The policy engine approves or blocks.
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}
Filter by provider or status to audit approved and blocked charges.
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']
// run it now
Single-file Python walkthroughOne script that creates a wallet, funds it, and makes a charge. Copy the file or run it directly — no dependencies beyond the standard library.
// 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
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.
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" }
]
}
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" }
]
}
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"
}
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
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.POST /api/wallets/:id/credit so your agent has a balance to charge against.fund_received and balance_low so you hear when money moves.One AI agent pays another for services using the transfer endpoint.
No auth required for wallet creation. Each agent gets its own API key and wallet ID.
# 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
Agent A authenticates with its own API key and calls the transfer endpoint, specifying both wallet IDs and the amount.
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
// 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. |
One POST. One charge. Watch the balance drop.
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 }
ak_live_... with your real API key from step 01.
From zero to first charge in under 2 minutes.
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"
}
api_key. You cannot retrieve it again.
Your agent includes the key in every request header.
X-API-Key: ak_live_...abcdef123
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
}
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" }
]
}
All endpoints. All auth requirements. No ambiguity.
spending_limit_cents.
{amount_cents: number}.
{providers: string[]}.
approved or blocked.
?provider=&status=
Every /pay call runs through all checks before a cent is spent.
Is the provider in the wallet's allowlist? Block if not.
Has the provider hit its daily cap today? Block if exceeded.
Is the charge under the wallet's monthly spending limit? Block if over.
Does the wallet have enough balance? Block if insufficient.
Balance deducted. Transaction logged. Response returned in <50ms.
Any string is accepted. Policy enforcement kicks in only for configured providers.
// AI
// payments
// comms
// infra
Missing one? Any string works — just configure the provider name in your policies.
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 addedFires when POST /api/wallets/:id/credit succeeds. Includes the credited amount and new balance.
// charge_sent
Charge approvedFires when POST /api/pay approves a charge. Includes provider, amount, transaction ID, and new balance.
// balance_low
Balance thresholdFires 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 spendFires 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.
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.
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 }
}
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 }
}
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 }
}
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 }
}
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 AgentKitAgentKit 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.
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"]
}'
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');
});
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.
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)))
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.
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')
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.
// recent deliveries
// 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_..."
Self-serve. No sales call. No monthly minimum.
$500/month spend → $7.50/month AgentKit
// 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"
Drop AgentKit into your existing agent framework. One function, one tool registration — your agent pays its own bills.
# 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)
# 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)
LangChain: pip install langchain langchain-openai requests |
AutoGen: pip install pyautogen requests
Runnable starter projects. Clone, fork, or download — pick the closest one and edit it to fit your business logic.
// basic-checkout
Minimal Express server: a single POST /charge endpoint that authorizes and deducts a payment from an AgentKit wallet.
// 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.
// agent-to-agent
Two Express agents settle a charge end-to-end using /api/pay plus the atomic /api/v1/wallet/transfer endpoint with idempotency keys.
Spin up locally with npm install && npm start in each starter — they share one .env.example listing AGENTKIT_API_KEY and AGENTKIT_BASE_URL.
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.
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.
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/walletsPOST /api/wallets/policiesPOST /api/wallets/<id>/creditPOST /api/wallets/api-key (rotate)POST /api/payPOST /api/v1/wallet/transferGET /api/transactionsEvery 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/balancePOST /api/v1/sandbox/simulateEvery 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} $
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.
// 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_..."}
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.
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).
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.
// 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.
401 Invalid API key errors.
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.
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.
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.
bruno.json manifest + environments/Sandbox.bru, or open the folder directly in Bruno's "Import Collection" dialog.
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.
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.
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.Server returned code: "unauthorized" with legacy error: "Invalid API key". The header is present, but the value did not match a stored key.
ak_live_ — anything else (typo truncation, env-var name leak, header-name swap) is rejected.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.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".
"amount_cents exceeds maximum (100000000)": split into multiple transfers, each under $1,000.00; /api/v1/wallet/transfer caps per-call at this ceiling."from_wallet_id must be an integer": the field arrived as a string (common in JSON encoders that stringify all numbers) — coerce before sending.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.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.
GET /api/wallets and your stored X-API-Key (a fresh 404 means the wallet was deleted; recreate is your only path).agent_id (stable across that agent's lifetime — do not randomize per run) and call POST /api/wallets again.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.
Retry-After verbatim when present; never tight-loop on a 429.delay = random(0, base * 2^n), cap retries at five attempts. See the ready-made retry pattern.X-RateLimit-Remaining on every response and back off proactively once it drops below 10%.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.
X-API-Key you are sending is ak_live_… for the wallet whose id is in the URL — not a sibling wallet's key.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.
crypto.timingSafeEqual, not === — string equality leaks timing information.POST /api/v1/webhooks. Secrets are shown exactly once.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().
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 clientThe 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 downtimeUse 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 actEvery 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 debitGenerate 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 jitterExpect 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 blocksPoll 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.
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
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.