> ## Documentation Index
> Fetch the complete documentation index at: https://docs.steward.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# API Overview

> Authentication, base URL, and common patterns for the Steward REST API.

# API Overview

The Steward API is a REST API built with [Hono](https://hono.dev) running on [Bun](https://bun.sh). All responses follow a consistent `ApiResponse<T>` shape.

## Base URL

```
https://api.steward.fi
```

For self-hosted instances, replace with your deployment URL.

## Authentication

Steward supports three authentication methods:

<Tabs>
  <Tab title="Tenant API Key">
    For tenant-level operations (agent CRUD, policy management, secret management):

    ```bash theme={null}
    curl https://api.steward.fi/agents \
      -H "X-Steward-Key: stwd_your_tenant_api_key"
    ```

    The API key is returned once when a tenant is created and cannot be retrieved again.
  </Tab>

  <Tab title="Agent JWT">
    For agent-scoped operations (signing, balance checks). Preferred for agents:

    ```bash theme={null}
    curl https://api.steward.fi/vault/my-agent/sign \
      -H "Authorization: Bearer stwd_jwt_..."
    ```

    Generate agent tokens via `POST /agents/:agentId/token` (requires tenant auth).
  </Tab>

  <Tab title="SIWE (Sign In With Ethereum)">
    For web dashboard authentication:

    ```bash theme={null}
    # 1. Get nonce
    curl https://api.steward.fi/auth/nonce

    # 2. Sign message and verify
    curl -X POST https://api.steward.fi/auth/verify \
      -H "Content-Type: application/json" \
      -d '{ "message": "...", "signature": "0x..." }'
    ```

    Returns a session JWT. Auto-creates a tenant on first sign-in.
  </Tab>
</Tabs>

### Platform Key

For platform-level operations (cross-tenant management), use the platform key:

```bash theme={null}
curl https://api.steward.fi/platform/stats \
  -H "X-Steward-Platform-Key: your-platform-key"
```

## Response Format

All endpoints return a consistent format:

```typescript theme={null}
// Success
{
  "ok": true,
  "data": T  // Response payload
}

// Error
{
  "ok": false,
  "error": "Human-readable error message",
  "data"?: T  // Optional additional context (e.g., policy results)
}
```

## HTTP Status Codes

| Code | Meaning                                    |
| ---- | ------------------------------------------ |
| 200  | Success                                    |
| 201  | Created (new resource)                     |
| 202  | Accepted (transaction queued for approval) |
| 400  | Bad request (invalid input)                |
| 401  | Unauthorized (missing or invalid auth)     |
| 403  | Forbidden (policy denied, wrong scope)     |
| 404  | Not found                                  |
| 409  | Conflict (duplicate resource)              |
| 429  | Too many requests                          |
| 500  | Internal server error                      |
| 502  | Bad gateway (RPC error from blockchain)    |

## Rate Limits

The Bun API entrypoint enforces a process-local global request limit per client
IP, and sensitive wallet routes can enforce Redis-backed per-agent limits via
[policies](/guides/policies). Production multi-instance deployments should
configure Redis for shared auth and wallet-action throttles.

Rate-limited responses return `429` with `Retry-After`, standard
`RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` headers, plus
legacy `X-RateLimit-*` compatibility headers. Successful wallet-action
responses that evaluate a rate-limit policy include the same standard remaining
budget headers without `Retry-After`.

## Request Hardening Inventory

The generated OpenAPI contract marks sensitive mutating operations with
`x-steward-hardening`. These operations are under the same sensitive-prefix
inventory used by the request-expiry and authorization-signature middleware.

For these routes:

* `X-Steward-Request-Timestamp` or `X-Steward-Request-Expires-At` is required
  when request-expiry enforcement is enabled.
* `X-Steward-Signature` is required when authorization signatures are enabled.
  The header accepts HMAC `v1=` signatures and P-256 `p256=` signatures.
* `X-Steward-Signing-Key-Id` can select a managed tenant request-signing key.
* `Idempotency-Key` is required for signed sensitive requests and recommended
  for all sensitive mutations.

OpenAPI also lists these headers as optional parameters because enforcement is
deployment-configurable; the `x-steward-hardening` extension records when they
become mandatory.

### Idempotency and safe retries

For fund-moving or signing workflows, include a caller-stable `referenceId` in
the request body when the endpoint supports it, and send an `Idempotency-Key`
header for sensitive mutations where your deployment accepts or requires one.
Use the same values when retrying after client timeouts so transaction history,
audit events, and lifecycle webhooks can be correlated to one business
operation.

Bitcoin PSBT signing is sign/finalize-only: `POST
/vault/:agentId/sign-bitcoin-psbt` returns Steward's `transactionId`, may return
finalized raw transaction metadata when `finalize: true`, and never broadcasts.
Because the route enforces fee caps and spend/address policies before signing,
clients should query by `referenceId` before creating replacement PSBT requests.
If a finalized raw transaction was already handed to a broadcaster, do not retry
that broadcast blindly; check the Bitcoin `txId` with your broadcaster or
indexer first.

## Route Groups

| Prefix            | Description                                                                     | Auth Required                    |
| ----------------- | ------------------------------------------------------------------------------- | -------------------------------- |
| `/agents`         | Agent CRUD + policy management                                                  | Tenant key or agent JWT          |
| `/accounts`       | Digital asset account resources grouping tenant wallets                         | Tenant key                       |
| `/user/me/wallet` | Authenticated user-wallet provisioning, indexed wallets, and additional signers | Personal user session            |
| `/vault`          | Signing, approvals, history                                                     | Agent JWT or tenant key          |
| `/audit`          | Tenant audit events and action-history filters                                  | Owner/admin session + recent MFA |
| `/secrets`        | Secret + route CRUD                                                             | Tenant key only                  |
| `/condition-sets` | Reusable policy allow/block list CRUD and item management                       | Tenant owner/admin session       |
| `/tenants`        | Tenant management                                                               | Tenant key                       |
| `/auth`           | SIWE, passkeys, email login                                                     | Varies                           |
| `/platform`       | Cross-tenant admin                                                              | Platform key                     |
| `/health`         | Health check                                                                    | None                             |

## Content Type

All request bodies must be JSON:

```
Content-Type: application/json
```

## Error Handling

```typescript theme={null}
import { StewardClient, StewardApiError } from "@stwd/sdk";

try {
  await steward.signTransaction("my-agent", { ... });
} catch (error) {
  if (error instanceof StewardApiError) {
    console.error(`Status: ${error.status}`);
    console.error(`Message: ${error.message}`);
    console.error(`Data:`, error.data); // May contain policy results
  }
}
```
