> For the complete documentation index, see [llms.txt](https://docs.zdrive.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.zdrive.io/agents.md). Agents can also search and read this documentation through its [MCP server](https://docs.zdrive.io/~gitbook/mcp).

# Agent Access

ZDrive is usable by AI agents with no account and no API key. An agent proves control of a wallet with one signature, then calls TEE models over an end-to-end encrypted channel.

| Step                | What happens                                                                                    |
| ------------------- | ----------------------------------------------------------------------------------------------- |
| 1. Discover         | `GET https://app.zdrive.io/.well-known/zdrive-agent.json` (also on `zdrive.io`)                 |
| 2. Sign             | Sign the auth message with your wallet                                                          |
| 3. Pick a model     | `GET /v1/models`                                                                                |
| 4. Find an instance | `GET /v1/e2e/instances?model=<id>` (signed, or `X-Zdrive-Payment: x402` with no wallet headers) |
| 5. Invoke           | `POST /v1/e2e/invoke` with an encrypted body (signed)                                           |
| 6. Upgrade          | After 20 free calls, buy credits or pay per call with x402                                      |

## The manifest

The manifest lists operations, the auth headers and message template, the headers an invoke needs, credit tiers, the buy-credits URL, and, when enabled, the x402 terms and the free trial (`trial.limit`, `trial.model`). The `trial` block is present only while the trial is on; `x402` only when x402 is configured. Read it at runtime instead of hard-coding values.

## Authentication

Send three headers on signed requests:

| Header             | Value                                                    |
| ------------------ | -------------------------------------------------------- |
| `X-Wallet-Address` | Your address                                             |
| `X-Wallet-Sig`     | `personal_sign` signature (EIP-191) of the message below |
| `X-Wallet-Session` | A token you choose; UUID v4 recommended                  |

The message, verbatim (the address is lowercase):

```
ZDriveX Auth
Address: 0xyouraddresslowercase
Session: your-session-token
This signature verifies wallet ownership and does not authorize any transactions.
```

`ZDriveX Auth` is the literal signing string the Worker verifies; it is not a product name in this context. The signature authorizes no transactions. EOAs and ERC-1271 smart wallets (for example Coinbase Smart Wallet) are supported.

## Quickstart

```ts
import { privateKeyToAccount } from 'viem/accounts';

const BASE = 'https://app.zdrive.io';
const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY as `0x${string}`);

// 1. Manifest
const manifest = await (await fetch(`${BASE}/.well-known/zdrive-agent.json`)).json();
const model: string | undefined = manifest.trial?.model; // trial model; with credits or x402, any model from /v1/models
if (!model) throw new Error('The free trial is off; choose a model from /v1/models');

// 2. Sign
const session = crypto.randomUUID();
const message =
  `ZDriveX Auth\nAddress: ${account.address.toLowerCase()}\nSession: ${session}\n` +
  'This signature verifies wallet ownership and does not authorize any transactions.';
const auth = {
  'X-Wallet-Address': account.address,
  'X-Wallet-Sig': await account.signMessage({ message }),
  'X-Wallet-Session': session,
};

// 3. Model -> chute id
const { models = [] } = await (await fetch(`${BASE}/v1/models`)).json();
const entry = models.find((m: { id: string }) => m.id === model);
if (!entry) throw new Error(`Model ${model} is not in /v1/models right now; retry later or pick another`);
const chuteId: string = entry.chuteId;

// 4. Discover an instance
const disc = await fetch(`${BASE}/v1/e2e/instances?model=${encodeURIComponent(model)}`, { headers: auth });
if (disc.status === 402) throw new Error(JSON.stringify(await disc.json())); // see "Upgrading"
const { instances } = await disc.json();
const inst = instances[0]; // { instance_id, e2e_pubkey, nonces }

// 5. Encrypt (see "Encrypting the request"), then invoke
const payload = { model, messages: [{ role: 'user', content: 'Hello' }], stream: true, max_tokens: 512 };
const { blob, responseKey } = await buildE2eeRequest(inst.e2e_pubkey, payload); // your implementation
const res = await fetch(`${BASE}/v1/e2e/invoke`, {
  method: 'POST',
  headers: {
    ...auth,
    'Content-Type': 'application/octet-stream',
    'X-Zdrive-Model': model,
    'X-Chute-Id': chuteId,
    'X-Instance-Id': inst.instance_id,
    'X-E2E-Nonce': inst.nonces[0],
    'X-E2E-Stream': 'true',
    'X-Zdrive-Idempotency-Key': crypto.randomUUID(),
    'X-Zdrive-Request-Hash': await sha256Hex(JSON.stringify(payload)),
  },
  body: blob,
});
console.log(res.status, res.headers.get('X-Zdrive-Trial-Remaining'));
// 200: encrypted SSE; decrypt with responseKey. 402: upgrade block.
```

`buildE2eeRequest`, the stream decryptor and `sha256Hex` are yours to implement; an outline of the first follows. The request hash may be any stable hash of the call (the reference check uses SHA-256 hex of the plaintext payload); reusing an idempotency key with a different hash returns 409.

### Encrypting the request

The blob is `KEM ciphertext (1088 bytes) || nonce (12 bytes) || sealed`. The libraries below are illustrative; any correct ML-KEM-768, HKDF-SHA256 and ChaCha20-Poly1305 implementation works.

```ts
import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';
import { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305';
import { HKDF } from '@stablelib/hkdf';
import { SHA256 } from '@stablelib/sha256';
import { gzipSync } from 'node:zlib';

const b64 = (b: Uint8Array) => Buffer.from(b).toString('base64');

async function buildE2eeRequest(e2ePubkeyBase64: string, payload: Record<string, unknown>) {
  const responseKeys = ml_kem768.keygen(); // you decrypt the response with responseKeys.secretKey
  const { cipherText, sharedSecret } = ml_kem768.encapsulate(Buffer.from(e2ePubkeyBase64, 'base64'));
  // 32-byte key: HKDF-SHA256(ikm = shared secret, salt = first 16 bytes of the KEM ciphertext, info = "e2e-req-v1")
  const key = new HKDF(SHA256, sharedSecret, cipherText.slice(0, 16), new TextEncoder().encode('e2e-req-v1')).expand(32);
  const body = gzipSync(JSON.stringify({ ...payload, e2e_response_pk: b64(responseKeys.publicKey) }));
  const nonce = crypto.getRandomValues(new Uint8Array(12));
  const sealed = new ChaCha20Poly1305(key).seal(nonce, body); // ciphertext + 16-byte tag
  return { blob: new Uint8Array([...cipherText, ...nonce, ...sealed]), responseKey: responseKeys.secretKey };
}
```

The response (streamed or not) is encrypted to the `e2e_response_pk` you sent, using the same KEM scheme in the opposite direction with HKDF info strings `e2e-resp-v1` (whole response) and `e2e-stream-v1` (stream chunks). Keep `responseKey` until the response is decrypted, then discard it.

## Free trial

* 20 calls per wallet, lifetime, on one model: `trial.model` in the manifest.
* Applies to wallets with no credits. A wallet with credits is on the paid path.
* Anti-abuse gate: an **EOA** needs at least 3 Base transactions (nonce 3 or more). A **smart wallet** (a deployed contract) needs at least 1 USDC. Undeployed smart wallets do not qualify.
* Failed provider calls are refunded; a call that times out counts.
* Limits per wallet per hour: 60 discovery requests and 30 trial invoke attempts.
* Responses carry `X-Zdrive-Trial-Remaining` and `X-Zdrive-Trial-Limit`; `X-Zdrive-Upgrade` appears on the last successful call.
* Other models return 402 `model_not_in_trial` without using a call.

## Upgrading

When the trial cannot serve you, the Worker returns **402** with `reason`, `trial` and `upgrade` (credits steps and tiers, and x402 terms). Reasons: `trial_exhausted`, `wallet_too_new`, `model_not_in_trial`, `trial_unavailable`. Full body in the [API Reference](https://docs.zdrive.io/api/reference.md#trial-402-body).

### Credits

On Base: `USDC.approve(contract, amount)`, then `purchaseCredits(tierId)`.

| Tier  | `tierId` | USDC  | Credits |
| ----- | -------- | ----- | ------- |
| Basic | 0        | 2.03  | 100     |
| Pro   | 1        | 8.12  | 500     |
| Power | 2        | 15.23 | 1,000   |

The contract address is in the 402 body (`upgrade.credits.contract`) and at `GET /vault/config`. Humans can use `https://app.zdrive.io/?buy=credits`. With credits, calls cost 1 credit, any model from `/v1/models` works, and the limit is 100 calls per hour.

### x402: $0.05 per call

No wallet signature headers, no credits. Pay in USDC on Base per call. Discovery is wallet-free too:

1. Discover: `GET /v1/e2e/instances?model=<id>` with header `X-Zdrive-Payment: x402` and no `X-Wallet-*` headers. Any model from `/v1/models` works (x402 also accepts other live TEE models that meet the x402 [margin rule](https://docs.zdrive.io/models.md#margin-rules), but `/v1/models` lists only the chat set). Limit: 60 discoveries per hour per client IP (IPv6: per /64) (429 with `Retry-After` beyond it).
2. Quote: POST the encrypted request to `/v1/e2e/invoke` with `X-Zdrive-Payment: x402` (plus the routing headers). You get `402` with a `PAYMENT-REQUIRED` header, `X-Zdrive-X402-Quote-Id`, and the same requirements as the JSON body. Quotes last 5 minutes and bind to the exact request.
3. Pay: sign an EIP-3009 `TransferWithAuthorization` for `50000` atomic USDC (6 decimals) to `payTo`, with the nonce set to `0x` + the quote id. Standard x402 clients pick a random nonce and will be rejected, so build the authorization yourself (below).
4. Resend the identical request with `PAYMENT-SIGNATURE` (base64 of the JSON payment payload) and `X-Zdrive-X402-Quote-Id`.
5. The 200 response includes `PAYMENT-RESPONSE`, the settlement receipt.

```ts
import { getAddress } from 'viem';

// `quote` is the JSON body of the 402 response; `account` is a viem account.
const accepted = quote.accepts[0]; // scheme "exact", network "eip155:8453", amount "50000"
const { quoteId, authorizationNonce, expiresAt, name, version } = accepted.extra;
if (authorizationNonce !== `0x${quoteId}`) throw new Error('Unexpected quote');

const now = Math.floor(Date.now() / 1000);
const validBefore = Math.min(now + accepted.maxTimeoutSeconds, Math.floor(expiresAt / 1000));
const authorization = {
  from: account.address,
  to: getAddress(accepted.payTo),
  value: accepted.amount,
  validAfter: '0',
  validBefore: String(validBefore),
  nonce: authorizationNonce, // 0x + quote id, NOT random
};
const signature = await account.signTypedData({
  domain: { name, version, chainId: 8453, verifyingContract: getAddress(accepted.asset) },
  types: {
    TransferWithAuthorization: [
      { name: 'from', type: 'address' }, { name: 'to', type: 'address' },
      { name: 'value', type: 'uint256' }, { name: 'validAfter', type: 'uint256' },
      { name: 'validBefore', type: 'uint256' }, { name: 'nonce', type: 'bytes32' },
    ],
  },
  primaryType: 'TransferWithAuthorization',
  message: {
    from: authorization.from, to: authorization.to, value: BigInt(authorization.value),
    validAfter: 0n, validBefore: BigInt(authorization.validBefore), nonce: authorization.nonce,
  },
});

const paymentPayload = { x402Version: 2, payload: { authorization, signature }, resource: quote.resource, accepted };
const paymentSignature = Buffer.from(JSON.stringify(paymentPayload)).toString('base64');
// Resend the SAME body and routing headers, adding:
//   PAYMENT-SIGNATURE: paymentSignature
//   X-Zdrive-X402-Quote-Id: quoteId
```

The resource is `https://app.zdrive.io/v1/e2e/invoke`.

## Other notes

* Free web tiers block datacenter IPs. The agent routes (trial, credits, x402) are not subject to that block.
* `POST /v1/chat/completions` is also available for wallet or session callers, but unencrypted chat is not the agent path. See [Models](https://docs.zdrive.io/models.md) and [Attestation](https://docs.zdrive.io/attestation.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.zdrive.io/agents.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
