# RingHi developer API v1

Base URL: the origin hosting this document. Public documents require no authentication. Developer requests use `Authorization: Bearer $RINGHI_DEVELOPER_KEY` and `Content-Type: application/json`.

## Qualification and keys

A human signs in at `/developer`, submits real identity details and a verified phone, and waits for manual approval. Keys are created by that approved user in **上传密钥**. A key expires after 1–90 days, is shown once, is stored only as a digest, can be restricted to a single owned app, and can be revoked immediately. At most 20 active keys per developer. Suspension revokes all keys; restoration requires new keys.

Scopes:

| Scope | Allowed operations |
| --- | --- |
| `apps:read` | List own apps and version Manifests |
| `apps:write` | Create an app or upload a new immutable draft version |
| `apps:test` | Save/read isolated test system configuration, send synthetic test events |
| `apps:submit` | Submit a draft or rejected version for review |

Keys cannot create more keys, edit identity, review/publish/withdraw apps, access production system values, install test versions, read customer data, access devices or make calls. A single-app key cannot create new apps or access another app. Keys are only recognized on developer endpoints.

## List applications

`GET /api/v1/developer/apps` → `{ "apps": [...] }`

Each row represents a version: `id`, `name`, `description`, `version`, `manifest`, `version_status` (`draft`, `review`, `published`, `rejected`), `submission_note`, `review_note`, `preview_installation_id`. A single-app key receives only that app. Empty list means no visible apps, not permission to act on any ID.

## Upload (recommended for agents)

`POST /api/v1/developer/uploads` — `apps:write`, JSON body ≤ 4 MiB (bundles are base64):

```json
{
  "requestId": "unique-upload-id-0001",
  "name": "My call notes",
  "description": "Summarize authorized call transcripts",
  "icon": "data:image/png;base64,...",
  "manifest": {}
}
```

Replace `manifest` with a valid object from the schema/example. `requestId` is 8–120 ASCII letters, digits, `.`, `_` or `-`. `name` 1–80 chars; `description` 1–1000 chars. Icon is PNG/JPEG/WebP data URL, actual image ≤256 KiB. SVG and remote image URLs are not accepted.

For `runtime: "hosted"`, add `script` (base64 of the classic-script JS file, ≤ 512 KiB decoded). For `ui.type: "bundled"`, add `pages` (base64 zip of static files, ≤ 2 MiB, ≤ 200 files, each ≤ 1 MiB, entry file required, no `..` or absolute paths). Oversize returns `413`. The CLI reads `manifestPath`, `scriptPath` and `pagesPath` from `app.json`; `pagesPath` may be a folder (zipped by the CLI, hidden files skipped) or a `.zip`.

For a new version, send only `requestId`, `appId`, `manifest` (plus `script`/`pages` when the runtime needs them). Name/description/icon cannot be silently changed through a version upload; for an unpublished draft app (never published and with no version currently in review), use `PATCH /api/v1/developer/apps/:id` (`apps:write`) to update `{ name?, description?, icon? }`. Once published, app metadata is managed by platform administrators.

Response `201`: `{ "id": "developer.<id>", "version": 1, "replayed": false }`. Repeating the same normalized payload and request ID returns the same app/version with `replayed:true`; a different payload with that ID returns `409`. Idempotency is per developer, shared across their keys. All author mutations are serialized. Limit: 60 new uploads/hour per developer, 120 key requests/minute (invalid traffic also globally limited).

Compatibility routes: `POST /api/v1/developer/apps` accepts new-app fields without requestId; `POST /api/v1/developer/apps/:id/versions` accepts a raw Manifest. Both support `Idempotency-Key`. Prefer `/uploads` for explicit retry semantics. Versions are immutable: there is no PUT Manifest endpoint.

## Isolated test system configuration

`GET /api/v1/developer/apps/:id/versions/:version/test-configuration` — `apps:test`.
Returns `{ "config": {}, "configuredSecrets": ["apiKey"] }`, never secret values.

`PUT` same URL:

```json
{"version":1,"config":{"region":"cn"},"secrets":{"apiKey":"provide-via-local-secret-environment"}}
```

Keys must match `systemFields`. Missing secrets preserve previous values; explicit empty strings clear values (unless required). Save the complete non-secret config. Required fields and select options are validated. Test values are encrypted separately from production. No promotion on publication.

## Synthetic test

`POST /api/v1/developer/apps/:id/versions/:version/test` — `apps:test`:

```json
{}
```

Webhook apps only; hosted scripts are tested through a self-use installation and their run records. The platform signs the synthetic request with the app-level Webhook signing secret generated in **登录与凭据** (`POST /api/v1/developer/apps/:id/webhook-secret`); if none has been generated yet, returns `409 APP_WEBHOOK_SECRET_REQUIRED`. The developer upload key is NOT a Webhook signing secret. The platform sends a synthetic workspace action or call event, marked `test:true`, with isolated test system values. For a workspace action, synthetic string/number/boolean parameters are supplied. A call app may receive a sample transcript only with `transcript.read`. Endpoint timeout is 8 seconds. Limit: 20 tests/hour per developer. Validate and return the protocol result; success is `{ok:true,eventId,...}`. No real call/device data is sent. Developers see a persisted pass/fail event, not a stored credential.

## Submit and withdraw

`POST /api/v1/developer/apps/:id/versions/:version/submit` — `apps:submit`, body `{}` or `{ "submissionNote": "..." }` (`submissionNote` up to 2000 chars explaining sensitive permissions, data flows, and hosted `network.origins`).
Response `{ "ok": true }`. Draft/rejected → review. Retrying a review submission succeeds (and updates `submissionNote` if provided). Published versions cannot be resubmitted. For `runtime: "webhook"`, an app-level Webhook signing secret must already exist, otherwise returns `409 APP_WEBHOOK_SECRET_REQUIRED`. The admin reviews in **应用管理 → 版本审核** (including `submissionNote` and hosted script/bundled page source code), and must approve developer qualification first. Review outcomes are delivered to the in-app message center and developer contact email. Pending status is NOT publication.

`POST /api/v1/developer/apps/:id/versions/:version/withdraw` — `apps:submit`, body `{}`.
Response `{ "ok": true }`. Withdraws a `review` version back to `draft`.
## Human-only operations

These require the normal logged-in session; upload keys are rejected:

- `GET/POST/DELETE /api/v1/developer/profile`: inspect/apply/withdraw enrollment. POST requires `displayName` (2–60), `realName` (2–80), `contactEmail`, `purpose` (4–2000), `agreement:true` and `revision` (0 initially); `bio`, `supportUrl`, `organization` and `verificationNote` may be empty strings. DELETE requires `revision`. Approved developers can PATCH only `{displayName,bio,contactEmail,supportUrl,revision}`; identity changes require a new manual verification process. The current account must have a verified phone. Private identity is encrypted and disclosed only to the applicant and audited admins.
- `GET/POST /api/v1/developer/keys`, `DELETE /api/v1/developer/keys/:id`: list/create/revoke. Create `{name,expiresInDays,scopes,appId?}`. Creation returns `{id,token}` once.
- `GET /api/v1/developer/apps/:id/webhook-secret`, `POST /api/v1/developer/apps/:id/webhook-secret`: inspect or generate/rotate the app-level Webhook signing secret (`rh_whs_…`). Rotation returns the plaintext `webhookSecret` once and keeps the previous secret valid for a 24-hour grace window.
- `GET / PUT /api/v1/developer/apps/:id/oauth`, `POST /api/v1/developer/apps/:id/oauth/secret`, `POST /api/v1/developer/apps/:id/oauth/account-workspaces`: read/update RingHi Login settings (`enabled`, `redirectUris`), generate/rotate the OAuth `clientSecret` (shown once; `clientId` is the app ID), and submit an application for advanced cross-workspace `account.workspaces` scope.
- `POST /api/v1/developer/apps/:id/withdraw`: body `{}`. Withdraws (unpublishes) your own app, stops active runs, revokes app tokens, and disables existing installations; republishing requires review.
- `POST /api/v1/developer/apps/:id/versions/:version/install-test` (self-use): `{version,permissions,workspaceId?,deviceScope?,devices?}`. `permissions` = every required permission plus the optional ones you choose. `workspaceId` is any workspace you own (default: personal). Sensitive permissions need `deviceScope` (`all` or `selected` with `devices`) but not the platform allowlist. Owned app only, approved developer only. Response `{id, enabled}`. Hosted apps, pure-page (`web`) apps, and Webhook apps with an app-level signing secret start enabled unless a required user/system setting has no default. For a hosted app, installing another version over an existing self-use install switches it in place and keeps its data and enabled state; other runtimes return `409` and must be uninstalled first. No automatic updates or conversion to production; stops if you stop owning the workspace.
- `PATCH /api/v1/developer/apps/:id` (`apps:write`, session or upload key): `{ name?, description?, icon? }`. Updates metadata of an unpublished draft app (never published and no version in `review`).
- `GET /api/v1/developer/apps/:id/versions/:version/files` (`apps:read`): `{script, pages}`, base64 of the hosted script and page zip you uploaded for that version (`null` when absent). Use it to start a new version from an existing one.
- `GET /api/v1/developer/apps/:id/permission-status` (`apps:read`): sensitive permissions and network origins the platform has allow-listed for the app.
- `GET /api/v1/developer/apps/:id/hosted-runs` (`apps:read`): hosted executions. Logs and error text only for your own self-use installations; other workspaces show a category.
- `GET /api/v1/developer/logs`: sanitized runtime status, no customer transcripts or credentials.
- `POST /api/v1/developer/messages/read`: `{ids:["message-id"]}` marks specified owned messages read, or `{throughId:"newest-visible-message-id"}` marks owned history up to that message read without clearing later arrivals.
All errors are JSON `{ "error": "human-readable explanation", "code"?: "machine code" }`. `DEVELOPER_APPROVAL_REQUIRED`, `DEVELOPER_KEY_INVALID`, `DEVELOPER_KEY_SCOPE` identify common authorization failures. Never retry a rejected authorization by escalating privileges.

## Sensitive permissions, external access and hosted runtime

The full contract is in [the platform guide](../../app-platform.md). Summary for agents:

- Tiers come from the platform catalog (`GET /api/v1/call-apps/capabilities`). Sensitive permissions need the platform allowlist (review is blocked with `409 REVIEW_BLOCKED` until it is in place) and the workspace owner's grant with a device scope. Declare optional ones in `optionalPermissions`.
- App server → RingHi: `POST /api/open/v1/apps/token` authenticated either with the app-level Webhook signing secret (`X-RingHi-Timestamp`, `X-RingHi-Signature: v1=HMAC-SHA256(secret, timestamp + "." + body)`) or with OAuth HTTP Basic auth (`Client ID + Client Secret`), with body `{installationId, nonce?}` or `{appId, workspaceId, nonce?}`; then `Authorization: Bearer rh_app_…` on `GET /api/open/v1/apps/capabilities`, `POST /api/open/v1/apps/actions/:capability` (`{deviceCode, idempotencyKey, input}`) and `GET /api/open/v1/apps/events?after=`. Tokens last 15 minutes; the grant is re-checked on every call.
- Launch tickets: `rh_launch` on the page URL, exchanged once within 60 s at `POST /api/open/v1/apps/launch/exchange` (same signing). Identities are workspace-scoped `openId`/`unionId`; nickname/avatar only with the member's own consent when the Manifest sets `userProfile`.
- Hosted scripts run in RingHi's sandbox with the global `ringhi` (see `hosted-sdk.d.ts`): capabilities, allow-listed `fetch`, KV, logs. Limits: 5 s, 32 MB, 10 fetches and 20 capability calls per run.
- Never put the signing secret or an access token in a page, a URL, logs or a repository. Do not treat a page's own claims as identity; only the exchanged ticket is.

## CLI example

Download `upload-app.mjs` from `/developer/upload-app.mjs` on the same origin. Use Node.js 22 or later. Set `RINGHI_DEVELOPER_KEY` through your local secret environment; do not put its value in shell commands recorded by your Agent.

```sh
node upload-app.mjs upload app.json
node upload-app.mjs submit developer.REPLACE_WITH_RETURNED_ID 1 --note "Explain sensitive permissions and data destination"
```

`app.json` is the upload body with optional `iconPath` (local PNG/JPEG/WebP, converted to a data URL), `manifestPath` (a separate `manifest.json`), `scriptPath` and `pagesPath` (folder or `.zip`). `node upload-app.mjs prepare app.json` checks it offline without a key. It derives a stable request ID from the payload so retries are safe. To intentionally upload identical content as a new version, pass a new third argument: `node upload-app.mjs upload app.json new-release-2026-10-24`. Use `RINGHI_BASE_URL` only when targeting another authorized RingHi deployment; it must be an HTTPS origin (localhost HTTP is allowed for development). The CLI rejects redirects to avoid forwarding a credential to an unexpected destination.

### Application model and voice selection policy

Shared AI connections and credentials are platform resources. Use `systemFields` for administrator-fixed connections. For user-selectable platform models, declare `fields` with `type: "model"` (`ttsModelId` selects TTS, `asrModelId` selects ASR, other model fields select LLM). Declare voice choices as `select` fields whose key contains `voice`, such as `translationVoice`.

Administrators can restrict each version's allowed choices, default, and whether users may choose. The user-facing catalog resolves model fields to filtered `select` options. Do not build choices from the global model list, persist provider keys in user configuration, or assume every platform model is available to your application. A fixed selector exposes only its default and explains the restriction. Treat an empty choice as the application default. Refresh after a rejected or stale configuration rather than retrying with arbitrary IDs.

New runs receive the effective, policy-constrained configuration snapshot. Do not fetch newer defaults during an active audio stream. Runtime voice changes remain unsupported; language and original-audio controls follow the supported handler's runtime contract. Developer upload keys cannot change administrator resource policies.
