Documentation Index
Fetch the complete documentation index at: https://docs.relayer.fi/llms.txt
Use this file to discover all available pages before exploring further.
@relayerfi/agent-sdk is the runtime SDK your agent loads. It signs every API call with HMAC-SHA256, enforces 3-layer budgets, polls the kill switch, batches telemetry, and orchestrates x402 payments + human approvals — all behind a small public surface.
New to the Agent Kit? Start with Getting Started for the full journey from workspace signup to running agent.
Package
| Package | Version | Purpose |
|---|---|---|
@relayerfi/agent-sdk | 1.0.0 | RelayerSDK facade + HMAC, budget, kill switch, x402, approvals, LLM wrappers, Mastra hook |
Entry points
RelayerSDK
The main facade. Construct once per agent process and reuse.Constructor
The agent UUID, issued by
POST /v1/agents/confirm-policies at provisioning time.
Typically: process.env.RELAYER_AGENT_ID.The agent’s HMAC secret, also issued by
POST /v1/agents/confirm-policies — shown once, never retrievable.
Typically: process.env.RELAYER_AGENT_SECRET.Base URL of the Relayer API.
https://api.relayer.fi for production, https://testnet.relayer.fi for sandbox.
Typically: process.env.RELAYER_API_URL.Number of retry attempts on HTTP failure. Retries
429 and 5xx. Non-429 4xx errors never retry (caller bug, not transient).Base backoff in ms. Exponential with jitter, capped at 10s.
Per-request timeout in ms (via
AbortSignal.timeout).How often the kill-switch poller hits
GET /v1/agents/{id}/status. Lower = faster reaction to a kill, higher = less API noise.How often the event batcher flushes to
POST /v1/agents/events/batch. Flushes earlier if the buffer reaches eventBatchSize or if a payment event arrives (immediate).Max events per flush. The batcher splices the whole buffer when flushing.
How often
x402fetch polls GET /v1/signing/approvals/{id} while waiting for human approval.Max time to wait for an approval before throwing
ApprovalTimeoutError. Default 5 minutes.Register
SIGTERM / beforeExit handlers that call shutdown() and flush pending events. Disable if you manage shutdown manually.Optional logger with
info(msg, data?), warn(msg, data?), error(msg, data?). Undefined by default — no logs are printed.Minimal init
- Validates the 3 required fields (throws synchronously if missing)
- Builds an
HttpClientwith HMAC-SHA256 signing - Starts the kill-switch poller (immediate first call, then interval)
- Starts the event batcher’s interval flush
- Registers shutdown handlers (unless
autoShutdown: false)
Methods
checkBudget(): Promise<void>
Checks budget layers 1+2 only (infra + tokens). Use for telemetry-only operations that should still proceed if only payments are exhausted.
GET /v1/agents/{id}/budget, throws BudgetExhaustedError([...failed]) with the array of exhausted layers. Layer 3 (payments) is not checked here.
checkPaymentBudget(): Promise<void>
Checks all 3 layers plus the kill switch. Use before any USDC outflow.
isBlocked if agent.killSwitch === true or the API is unreachable (fail-safe).
isKillSwitchActive: boolean (getter)
true if the kill switch is currently active OR the API was unreachable on the last poll.
emitEvent(event: RelayerEvent): void
Adds an event to the batch buffer. Returns immediately. The batch flushes:
- On the configured interval (default 10s)
- When buffer length reaches
eventBatchSize(default 50) - Immediately if
event.type === "payment"
payment, token_usage, llm_call, api_call, budget_check, kill_switch, error.
Failure handling inside the batcher:
429and5xxfrom event batch endpoint → re-enqueue with 60s backoff4xx(non-429) → drop the batch (permanent failure, caller bug)- Network error / timeout → re-enqueue with 60s backoff
createUserWallet(input): Promise<{ wallet_id, addresses }>
Asks the API to stamp a CREATE_WALLET activity using the agent’s own P-256 key. Requires the agent’s policies to include Allow: Agent — Create Wallets.
POST /v1/agents/wallets. The wallet is owned by the agent itself, not by the agent’s parent workspace.
buildAuthHeaders(method, path, body?): Record<string, string>
Returns the 4 headers the API expects for HMAC-authenticated requests. Useful if you bypass the SDK’s HTTP client (e.g. WebSocket auth):
${method}${path}${timestamp}${sha256(body)}. The signature is HMAC-SHA256 over that string with the agent secret. Empty body → sha256(""). The server validates the timestamp window (±60s).
http: HttpClient (getter)
Direct access to the underlying HTTP client. Use for endpoints the SDK doesn’t expose as first-class methods:
HttpClient exposes get<T>(path), post<T>(path, body), agentId, apiUrl, and buildAuthHeaders(...).
agentId: string and apiUrl: string (getters)
Convenience accessors:
budget (object)
Tiny accessor for the cached budget snapshot. The cache is populated automatically when API responses include budget_status (server-pushed updates).
shutdown(): Promise<void>
Stops the kill-switch poll, stops the approval handler, flushes pending events, stops the event batcher. Idempotent. Called automatically on SIGTERM and beforeExit if autoShutdown is true (default).
x402fetch
Afetch-compatible wrapper that ties together: budget check, HMAC auth, x402 detection, payment, approval, and retry.
What it does, step by step
- Budget check —
sdk.checkPaymentBudget(). ThrowsBudgetExhaustedErrororKillSwitchActiveErrorbefore any network call. - Auth headers — builds HMAC headers for the external URL (path-only, since the host is external).
- First request — sends with the original body and headers.
- 402 handling — if the server returns
402 Payment Required, extracts thepaymentRequirementfrom the body, callsPOST /v1/agents/{id}/x402-pay, gets apaymentHeader, retries the request with that header. Emits apaymentevent on success. - 202 handling — if the server returns
202 Acceptedwith anapprovalId, suspends and pollsGET /v1/signing/approvals/{id}every 5s. On approval, retries the original request. On rejection, throwsApprovalRejectedError. On timeout, throwsApprovalTimeoutError. - Everything else — passes through unchanged.
When to use
- Calling any third-party API that’s x402-gated
- Any operation where you want budget + approval + payment in one call
sdk.http.post(...) directly.
LLM Wrappers
ES Proxy wrappers that intercept LLM provider calls and emitllm_call events with token counts. Zero overhead until the first LLM call — the proxy is lazy.
wrapAnthropic<T>(client: T, sdk: RelayerSDK): T
provider: "anthropic", model, tokens_input, tokens_output extracted from response.usage.
wrapOpenAI<T>(client: T, sdk: RelayerSDK): T
Same pattern. Intercepts client.chat.completions.create() and extracts response.usage.{prompt_tokens, completion_tokens}.
wrapGoogle<T>(client: T, sdk: RelayerSDK): T
Same pattern. Intercepts the Gemini SDK’s generation calls.
Type safety
The wrappers return the same type as the input client. SowrapAnthropic(new Anthropic(...)) returns an Anthropic instance from your IDE’s perspective. No type juggling.
Failure mode
Tracking errors are swallowed silently — if event emission fails, the LLM call still succeeds. Logged via the SDK logger if one is configured.Mastra Integration
For agents built with Mastra. The hook plugs intoagent.generate({ onStepFinish }).
relayerMastraHook(sdk: RelayerSDK)
{ onStepFinish: (step) => void }. Reads step.usage (Mastra’s standardized usage object) and emits llm_call events with provider and model parsed from step.modelId (format: "provider/model", e.g. "anthropic/claude-opus-4-5").
Tracking errors are swallowed — broken telemetry never breaks the agent.
Errors
All SDK errors extendRelayerError. Use instanceof for dispatch.
Dispatch example
Fail-safe vs fail-open
- Payment operations (anything that moves USDC) — fail-safe: if anything is wrong (budget out, kill switch, API unreachable), the operation is blocked.
- Infrastructure operations (telemetry, status polls, non-payment API calls) — fail-open: if the API is unreachable, the agent continues. Telemetry buffers; reconnects retry automatically.
Events
The batcher posts events toPOST /v1/agents/events/batch. Server fills in timestamp and agentId server-side; the SDK maps to a minimal shape before send.
| Type | When emitted | Auto-emitted by | Manual? |
|---|---|---|---|
payment | After a successful x402 payment | x402fetch | Yes |
llm_call | After an LLM call returns | wrapAnthropic / wrapOpenAI / wrapGoogle / relayerMastraHook | Yes |
token_usage | Alias usable for explicit token accounting | Caller | Yes |
api_call | Any non-LLM external HTTP call worth metering | Caller | Yes |
budget_check | Diagnostic for budget queries | Caller | Yes |
kill_switch | Diagnostic for kill switch state changes | Caller | Yes |
error | Caller-chosen error checkpoints | Caller | Yes |
Configuration cheat sheet
| Default | Knob | When to change |
|---|---|---|
retries: 3 | HTTP retry attempts | Lower for hot loops (avoid amplification on outages); higher for batch jobs |
retryBaseMs: 1_000 | Base backoff | Raise to spread retries across longer windows |
timeoutMs: 30_000 | Per-request timeout | Lower for snappy UX; raise for large payloads |
killSwitchPollInterval: 30_000 | Status poll interval | Lower for faster kill reaction (more API noise); raise for quieter agents |
eventFlushInterval: 10_000 | Telemetry flush cadence | Raise if your telemetry is non-critical; lower if you want faster dashboards |
eventBatchSize: 50 | Max events per flush | Raise for very chatty agents to reduce flush count |
approvalPollInterval: 5_000 | Approval queue poll | Raise if approvals are rare; never lower below 5s (API rate limit) |
approvalTimeout: 300_000 | Approval wait timeout | Match the human approver’s response SLA (CFO availability) |
autoShutdown: true | Register SIGTERM handlers | Disable if you manage shutdown manually |
Production checklist
Secret in a secret manager
RELAYER_AGENT_SECRET lives in your platform’s secret store. Not in .env committed to git. Not in environment variables logged by your runtime.Rotate on schedule
Run
POST /v1/agents/{id}/rotate quarterly (or after any suspected leak). The old secret is revoked instantly; push the new one to your secret store.Configure a logger
Pass a
logger to RelayerSDK so kill-switch state changes, retries, and event-batch failures are surfaced. The SDK is silent by default.Wire wallet balance to alerts
Poll
GET /v1/agents/{id}/wallet-balance and alert when it drops below a refill threshold. Top up via POST /v1/agents/{id}/fund/prepare + /fund/confirm.Test the kill switch
From the dashboard, kill the agent once in staging. Verify your runtime gracefully stops payment operations within ~30s and that infra operations continue.
See also
Getting Started
The full path from signup to running agent.
Flow Guide
Agent lifecycle, funding, budget, and approvals — focused on the API endpoints.
API Reference
Every endpoint with interactive playground and cURL / Node.js / Python samples.
Authentication
The three auth modes, including the HMAC payload spec the SDK implements.