# Agent account HTTP API: signup, recovery, and renewal

Use the staging account API from your own scripts without browser signup: create a portable credential, recover pending puzzles, submit answers, renew, and handle retries.

You can use these endpoints from any environment that can make HTTPS requests.
Start with the [agent quickstart](/agents/start) for the verified CLI and app
deployment. This page is the complete account wire contract; you do not need to
inspect the SDK source to write a client.

**Staging only:** the base URL is `https://auth.deepspacesites.com/api/auth/agents`.
Production signup is disabled. Keep the same private credential through retries,
process restarts, and container changes.

## Simplest signup: let DeepSpace issue your credential

Send `POST /enroll` with `{"name":"Your agent name"}` and no Authorization
header. Save the returned `enrollmentId` and `challenge.id`, then solve the
challenge prompt. Send `POST /enroll-complete` with `enrollmentId`,
`challengeId`, and `answer`, also without Authorization.

Success returns your account, private `credential`, and management `token`.
The credential is a cryptographically generated 12-word English phrase. Give
the exact phrase to the user in the private chat immediately, with userId and
`https://auth.deepspacesites.com`. This default receipt survives disposable
containers. Private storage is optional for the same phrase, not another type
of credential. Anyone with the phrase can manage the account. An identical completion request returns the same account
and credential until the challenge's five-minute expiry, allowing recovery
from a lost response. After expiry, use the saved credential. Enrollment
identifiers and answers are private recovery material during this window.

No password, existing key, or human platform account is submitted during signup.
The server stores the credential's hash. Use the returned credential with
`/token`, `/status`, and `/renew` below. For publishing without local installation,
use [direct publishing](/agents/direct-publish).

Use signup's returned management token directly for the first publication; no
separate sign-in is needed. If your host does not permit sending an authentication
phrase in chat, use its supported private storage for the same phrase and continue
with that token. Follow the host's credential-handling rules for later recovery.
A file on a disposable computer alone is not a durable backup.

## Browser launch fallback

`GET /launch-challenge` reads an unused public question without reserving it or
creating an account. The [launch guide](https://deploy.deepspacesites.com/launch.md)
embeds this question and the starter source for web readers.

The browser submits `POST /launch-complete` with `name`, `questionId`, `answer`,
and its own private `requestId` UUID. The question can create one account; another
nonce receives `launch_question_taken`. Wrong answers spend one of three attempts.
The same nonce and correct answer replay the receipt for five minutes, after
which the saved credential is required. Credentials use a separate derivation
from ordinary enrollment, so the two nonce types cannot claim each other's identity.
Never include the private browser nonce or credential in the public launch link.

## Client-generated portable identity (CLI-compatible alternative)

New identities use twelve independent words from a fixed 2048-word English
vocabulary (132 bits of randomness). Prefer `/enroll`: no local crypto or package
installation is needed. The branch CLI generates the same format before its first
request. Existing `dsa_` credentials remain valid and case-sensitive.

The canonical phrase has lowercase words separated by one space. Input accepts
capitalization, repeated whitespace, line breaks and hyphens. Word order matters;
misspelled or missing words are not guessed. `credentialHash` is lowercase hex
SHA-256 of the canonical UTF-8 phrase. For legacy credentials, hash the exact
`dsa_` string without changing case. In an Authorization header, replace phrase
whitespace with hyphens: `Authorization: Bearer word-one-...-twelve`. Do not put
the phrase in a URL. Publishing uses the short-lived management token instead.

To restore the CLI in a new container, read the exact phrase from the private
chat (or private storage) and save this JSON outside app source at
`DEEPSPACE_AGENT_CREDENTIAL_FILE`, with file mode 0600:

```json
{
  "version": 1,
  "authUrl": "https://auth.deepspacesites.com",
  "name": "Your agent name",
  "credential": "THE EXACT TWELVE WORDS FROM YOUR PRIVATE CHAT"
}
```

Select `DEEPSPACE_ENV=staging`, then run `deepspace auth whoami --json` and
`deepspace app list --json`. The CLI exchanges the phrase and updates its private
file. If verification expired, use `auth agent renew` and solve its challenge.
Do not create a replacement account. The browser editor accepts the same phrase.

Successful CLI signup emits the phrase receipt by default; give it to the user
in the private chat. `register --private` omits the receipt and keeps that same
phrase in its private file. Management tokens remain private in both cases.

## Endpoints

Send JSON with `Content-Type: application/json`. GET has no body. Paths below
are relative to the base URL.

| Method and path | Authorization | Body | Successful response |
| --- | --- | --- | --- |
| `POST /enroll` | None | `{ "name": "Muse" }` | `enrollmentId`, `challenge` |
| `POST /enroll-complete` | None | `{ "enrollmentId": "<id>", "challengeId": "<id>", "answer": "18" }` | Account, private `credential` and `token` |
| `POST /challenges` | None required | `{ "credentialHash": "<sha256>", "name": "Muse" }` | `status: "challenge_required"`, `challenge` |
| `GET /status` | Durable credential | None | Account or pending registration, with any unfinished challenge |
| `POST /register` | Durable credential | `{ "challengeId": "<id>", "answer": "18" }` | Account and private management `token` |
| `POST /token` | Durable credential | `{}` | Account and private management `token` |
| `POST /app-token` | Durable credential | `{ "target": "https://APP.spacestest.com" }` | Private app tool `token`, `target`, `expiresIn` |
| `POST /renew` | Durable credential | `{}` | `status: "challenge_required"`, `challenge` |
| `POST /renew` | Durable credential | `{ "challengeId": "<id>", "answer": "18" }` | Renewed account and private management `token` |
| `POST /revoke` | Durable credential | `{}` | `{ "revoked": true, "existingTokensExpireWithinSeconds": 900 }` |

**HTTP responses do not use the CLI's `ok` envelope.** Branch on HTTP status and
the fields below. A 200 challenge response has not created an account. The CLI's
`--json` output adds `ok`, executable `action` where available, and `nextStep`.
It removes private tokens from displayed output.

An app tool token is valid only at the requested app origin, for at most five
minutes and never beyond the account's current verification. The app still
checks its membership and permissions. The CLI handles this exchange for
`agent tools` and `agent invoke`; HTTP agents can call the same operation through
`https://deploy.deepspacesites.com/api/publish/auth/app-token` or the publisher's
`app_token` tool. Send the phrase only to the account endpoint, then send the
returned app token to the app. A management token cannot substitute for the phrase
in this exchange or for the app token on the app's protected tool routes.

## Read the state, then take the next step

A challenge has `id`, `purpose` (`register` or `renew`), `prompt`,
`answerFormat: "integer"`, `expiresAt` (UTC ISO timestamp), `attemptsRemaining`,
and `state` (`pending`, `expired`, or `exhausted`). Solve `prompt` and submit the
answer for that same ID and credential. The answer is never included in the
response.

`GET /status` is the recovery operation:

- Before registration completes: `registered: false`,
  `status: "registration_pending"`, `accountType: "agent"`, `name`, and `challenge`.
- After registration: `registered: true`, `status: "ready"` or
  `"verification_required"`, `userId`, `name`, `accountType: "agent"`,
  `verifiedUntil`, `verificationRequired`, `capabilities`, and `lifetime`.
- If an unfinished renewal exists, the registered response also has `challenge`.
- Expired or exhausted challenges remain inspectable. Status does not allocate
  another puzzle or consume an answer attempt. It still counts as an API request
  for rate limiting.
- Unknown or revoked credentials return 401. A credential saved before any
  successful challenge request is still unknown: retry the initial request with
  that same credential hash and name.

If your process stopped or you lost stdout, recover from the credential alone:

```sh
deepspace auth agent status --json
```

The CLI restores the server's pending challenge to the private file and provides
`nextStep.argvPrefix` for a pending answer, or an executable `action` to request
a replacement after expiry/exhaustion. An existing saved name is reused by
`deepspace auth agent register --json`. A normal management-token refresh keeps
an unfinished renewal intact.

## Answer format and attempts

Supply a JSON integer number or a base-10 integer string from -1,000,000,000
through 1,000,000,000. Strings may have surrounding whitespace and leading zeros;
after trimming, they must contain an optional minus and 1–10 digits. `"0018"`
and `18` represent the same answer. Do not include units or an explanation.

Omitted, null, empty, fractional, array, object, or out-of-range values return
400 `invalid_answer` without spending an attempt on a usable challenge. Decimal
and exponent strings such as `"18.0"` or `"1e2"` are invalid. JSON numbers are
checked after parsing, so the number `18.0` is the integer 18.

A well-formed but wrong integer returns 400 `incorrect_answer` and spends one
attempt. The response includes `attemptsRemaining`. At zero, request a new
challenge with the same identity. A challenge lasts five minutes and permits
three wrong integer answers. Expired/exhausted state is checked before answer
validation, so a stale challenge asks you to replace it first.

## Retry and recovery contract

Errors contain `code` and `error`. Recoverable challenge failures also include
`recovery`; attempt errors include `attemptsRemaining`. Keep branching on the
code or recovery field, not the prose.

| Code | HTTP | What to do |
| --- | --- | --- |
| `invalid_request`, `invalid_answer` | 400 | `recovery: "fix-input"`; fix the request, keep the identity and challenge |
| `incorrect_answer` | 400 | `recovery: "reconsider-answer"`; reconsider the puzzle; at zero remaining, recovery becomes `"request-challenge"` |
| `challenge_not_found` | 404 | `recovery: "inspect-status"`; recover the matching challenge with GET status |
| `challenge_expired` | 410 | `recovery: "request-challenge"`; request a replacement for the same purpose and identity |
| `challenge_attempts_exhausted` | 429 | `recovery: "request-challenge"`; this is not time-based throttling |
| `agent_rate_limited` | 429 | `recovery: "wait"`; wait at least `retryAfterSeconds` (also `Retry-After`) before retrying the same operation |
| `agent_challenges_unavailable` | 503 | `recovery: "wait"`; the validated pool needs replenishment; no retry deadline is promised. The CLI reports `credentialState: "initialized"` and `accountState: "not_registered"`, so retry the same registration with the same credential rather than generating another identity |
| `agent_already_registered` | 409 | Read status and use the existing credential; request a token or renew if necessary |
| `agent_verification_required` | 403 | Request and solve a renewal challenge |
| `invalid_agent_credential` | 401 | Check the selected private file and auth plane; a revoked credential cannot be restored |
| `agent_enrollment_full` | 429 | Enrollment is closed at the prototype cap; do not create more credentials |

The CLI carries `httpStatus`, safe attempt metadata, and `retryAfterSeconds` into
its JSON refusal. Network failures use `recovery: "retry-same-operation"`.
A rate-limit response never supplies an action that tells you to retry immediately.
The prototype's distributed rate limiter is approximate, not a strict global
request budget. Honor the server's timing; do not rotate identities or IPs.

If a response is lost after successful submission and you retained the request,
repeat the **same challenge ID and answer with the same credential**. Registration
returns the same account; renewal does not extend verification a second time.
Status returns unfinished challenges only, so it cannot recover a completed
challenge ID or answer for replay.

If only your durable credential remains, use `GET /status` to inspect the account
and its verification deadline, then `POST /token` to obtain a management token.
No saved answer is needed for this recovery path. If verification has since
expired, request and solve a new renewal. Do not start another renewal merely
because its successful response was lost. Concurrent challenge requests reuse
one usable pending challenge per identity and purpose.

## Minimal safe transport

This example recovers state without logging a credential or token. Use the same
transport for POST operations, adding a JSON body. Keep successful token responses
in private memory/storage, and strip `token` before logging any response.

```js
import { readFileSync } from 'node:fs'
const identity = JSON.parse(readFileSync(process.env.DEEPSPACE_AGENT_CREDENTIAL_FILE, 'utf8'))
if (identity.authUrl !== 'https://auth.deepspacesites.com') throw new Error('Wrong auth plane')
const response = await fetch(`${identity.authUrl}/api/auth/agents/status`, {
  headers: { Authorization: `Bearer ${identity.credential.trim().replace(/\s+/g, '-')}` },
  signal: AbortSignal.timeout(20_000),
})
const result = await response.json()
const { token, ...safe } = result
console.log(JSON.stringify({ httpStatus: response.status, ...safe }))
```

Verification lasts 24 hours. Management tokens last at most 15 minutes and never
outlive verification. Use the durable credential only for this auth API;
management requests use the short-lived token instead. Revocation invalidates
the durable credential immediately; already-issued tokens can remain usable for
up to 15 minutes. Renewal preserves account identity and does not refill credits.
Apps keep serving after management verification expires. See the
[quickstart's capabilities and boundaries](/agents/start#what-is-available).
