docs: 补齐 MonkeyAI 国际版部署、模块与 API 参考

This commit is contained in:
Jesse Yin committed 2026-12-03 15:10:35 +08:00
1 parent 7f11200546
commit d73ea25c04
12 files changed
+1266 -5

No files matched your search

+6 -5
View File
@@ -99,7 +99,7 @@ When prompted, enter the absolute path to an empty installation directory and th
- **Run on your own infrastructure.** Manage MonkeyAI’s configuration, monitor its status, and plan upgrades and maintenance around the way your team works.
- **Adapt it to your business.** Customize the open-source workspace, choose models and tools that suit your team, and connect your existing business systems.
For source deployments, see the [Docker Compose configuration](./monkeyai/docker-compose.yml).
For installation options, first sign-in, and maintenance, see the [self-hosting and operations guide](./monkeyai/README.en.md). For source deployments, see the [Docker Compose configuration](./monkeyai/docker-compose.yml).
## Try the demo
@@ -187,10 +187,11 @@ Join our [Discord community](https://discord.gg/2pPmuyr4pP) to ask questions, sh
## Development and repository layout
- [Docker Compose configuration for the server](./monkeyai/docker-compose.yml)
- [Backend source code](./monkeyai/backend/), [Admin API specification](./monkeyai/backend/api/admin.yaml), and [Agent API specification](./monkeyai/backend/api/agent.yaml)
- [Web admin console source code](./monkeyai/web/)
- [Website source code](./monkeyai/landing/)
- [Self-hosting and operations guide](./monkeyai/README.en.md) · [Docker Compose configuration](./monkeyai/docker-compose.yml)
- [Backend development guide](./monkeyai/backend/README.en.md) · [Source](./monkeyai/backend/)
- [Admin API reference](./monkeyai/backend/api/admin.en.md) · [Agent API reference](./monkeyai/backend/api/agent.en.md)
- [Web admin console development guide](./monkeyai/web/README.en.md) · [Source](./monkeyai/web/)
- [Website development guide](./monkeyai/landing/README.en.md) · [Source](./monkeyai/landing/)
## License
+185
View File
@@ -0,0 +1,185 @@
# Self-host MonkeyAI
Use this guide to install MonkeyAI on your own infrastructure, sign in to the admin console, and maintain the instance. The [Chinese deployment guide](README.md) and [Compose file](docker-compose.yml) provide more detail on the source deployment.
[Choose an installation path](#choose-an-installation-path) · [Prepare the host](#prepare-the-host) · [Install](#install) · [Sign in for the first time](#sign-in-for-the-first-time) · [Configure your instance](#configure-your-instance) · [Back up and restore](#back-up-and-restore) · [Upgrade](#upgrade) · [Troubleshoot](#troubleshoot)
## Choose an installation path
| Path | Use it when | What it does |
| --- | --- | --- |
| Published installer | You want a packaged deployment on a Linux server. | Installs the release's prebuilt images, sets up credentials and data directories, and manages upgrades. An offline package is available for networks without registry access. |
| Docker Compose from source | You want to build or test components at a particular revision, or already have compatible application images. | Uses the checkout's Compose configuration. You manage credentials, storage, networking, and upgrades. The public source build alone does not bootstrap an administrator. |
Keep the two paths separate. The published package has its own Compose files, image variables, and defaults; do not copy the repository's Compose file over an installed instance.
## Prepare the host
- **Host and tools.** The published installer supports Linux on AMD64 (x86-64) and ARM64, with root access for installation. Its documented test baselines are Ubuntu 22.04/24.04 and Rocky Linux 9. Plan for Docker Engine and Docker Compose v2.20 or later. Installing Docker through the installer requires a running systemd, iptables/NAT, and cgroups. The installer does not support Podman, Alpine/OpenRC, or 32-bit hosts. CentOS 7 has a legacy path but is no longer maintained; openEuler is not yet verified by the release documentation. A source build requires Docker with Compose and BuildKit, plus a full Git checkout; Go and Node run inside the build images.
- **Capacity.** The [project overview](../README.md#self-host-monkeyai) lists 1 CPU core and 1 GB of RAM for a lightweight instance. Treat that as a starting point, not a build or production capacity guarantee. Allow space for images, temporary files, PostgreSQL, RustFS objects, and backups. Size CPU and RAM for your workload and concurrent connections. Cloud computers require a separate [engine host](engine/INSTALL.md); the base Compose stack does not provision one.
- **Network.** Pick the address users will actually open and check for port conflicts. Use a private network for initial setup and trusted HTTPS for production. If using built-in certificate issuance, prepare a public domain and inbound TCP 80 and 443. The online installer and source builds need outbound access to their download and registry endpoints; source builds also need access to package registries. The offline installer bundles Docker/Compose and the service images. It does not make the running service air-gapped: configured integrations can still need network access, and the packaged Pro backend documents outbound aggregate instance reporting.
Use one deployment per Docker host with these defaults: the packaged installation uses fixed container names, and the source configuration also has fixed names for the ingress and task proxy.
## Install
### Use the published installer
On the Linux host, open [Self-host MonkeyAI](../README.md#self-host-monkeyai) and run the published installation command in an interactive terminal as root. The bootstrap selects a release from the [server release manifest](https://release.monkeycode-ai.com/public/monkeyai/server/latest.json), verifies the package checksum, and starts the installer. To select a specific published version, pass its tag as `MONKEYAI_VERSION` to the bootstrap. For an offline installation, choose the matching Linux architecture and offline archive from the manifest, verify its SHA-256, transfer and extract it on the target host, then run `sudo sh ./install.sh` from the extracted directory. The archive's README lists preflight and non-interactive options.
1. Choose **Install** (`安装`). The release installer may display a Chinese terminal menu even when the web UI is in English.
2. Choose an empty installation directory (default: `/data/monkeyai`) and enter the service address. New packaged installations use HTTPS on port 443 by default, with HTTP on port 80 redirecting to it. An explicit port in the HTTPS address changes the HTTPS listener's host port. Plan for both port mappings.
3. Save the administrator email and generated password shown at the end. The default email is `admin@baizhi.cloud`. The installer generates the PostgreSQL and RustFS credentials and does not retain the bootstrap admin password in `.env` after a successful new installation.
The default packaged TLS certificate uses a shared key and may not match your hostname or be trusted by browsers. Before sending credentials over an untrusted network or inviting users, configure a trusted certificate using [automatic TLS or an external gateway](#publish-over-https). Do not bypass browser certificate warnings in production.
### Build and start from source
Run the commands in this section from `monkeyai/` inside a full clone of [the MonkeyAI repository](https://github.com/chaitin/MonkeyAI). Check out the revision you intend to deploy before building. Use a new PostgreSQL database or an empty data directory for a fresh installation.
> **First-login limitation:** At this revision, the public server entry point uses a [no-op member writer](backend/member/empty.go). Building the public checkout does not create the first administrator, even if you set the bootstrap variables. A healthy stack is not proof that you can sign in. Use the published installer for a new instance with admin access, or supply a compatible backend image that implements member management.
1. On first setup only, create `.env` from the [configuration example](.env.example):
```bash
(umask 077; cp -n .env.example .env)
chmod 600 .env
```
Replace the sample values for `POSTGRES_PASSWORD`, `RUSTFS_ACCESS_KEY`, and `RUSTFS_SECRET_KEY`. If using a backend image that supports administrator bootstrap, set `MONKEYAI_INITIAL_ADMIN_EMAIL` and a unique `MONKEYAI_INITIAL_ADMIN_PASSWORD` of at least 12 characters for a fresh database. Use a database password made from URL-safe characters with the default connection string: Compose inserts it into the URI as-is. If you supply your own `MONKEYAI_DATABASE_URL`, apply proper URI encoding to its credentials.
2. Prepare the bind mounts. RustFS and the application runtime use UID/GID `10001:10001`. On Linux, run:
```bash
sudo mkdir -p data/rustfs data/rustfs-logs data/runtime
sudo chown 10001:10001 data/rustfs data/rustfs-logs data/runtime
sudo chmod 700 data/runtime
```
If you are reusing restored data, make sure the existing contents have the correct ownership and permissions too. Preserve `data/runtime/identity.json` from the original instance.
3. Validate the configuration and start the stack:
```bash
docker compose config --quiet
docker compose up -d --build
docker compose ps -a
```
For a local instance, open <http://localhost:8080>. For a remote host, use a private connection and set `MONKEYAI_PUBLIC_URL` to the real browser-facing address. Do not expose the default HTTP setup to the public internet.
PostgreSQL must be healthy before `migrate` runs. The `backend` and `proxy` services wait for migrations to succeed and for RustFS to be healthy. The backend checks the private resource bucket and creates it if needed, with a one-minute initialization limit. The `admin` service serves static web files; the `nginx` service is the public ingress. The page or ingress may respond before the backend is ready. A migration container that exits with code `0` is expected.
**Use prebuilt images with the source Compose file.** If you distribute your own images instead of building on the host, set `ADMIN_IMAGE`, `BACKEND_IMAGE`, `MIGRATE_IMAGE`, `PROXY_IMAGE`, and `NGINX_IMAGE` to the full image references for the same release set. Make them available locally or from a registry the host can access, then run `docker compose up -d --no-build`. The migration image contains the SQL and must match the backend release. The repository defaults ending in `:local` are build tags, not published image URLs.
## Sign in for the first time
These steps assume either a packaged installation or a Compose deployment with an administrator-capable backend image.
1. Open the instance's public address and follow the sign-in link, or go directly to `/admin`. An unauthenticated visit to `/admin` redirects to `/login`.
2. Choose **Password sign-in**. Use the credentials from the installer result, or the initial email and password you set for the source build. Once signed in, confirm you can open the admin console. The packaged Pro backend lets the first administrator sign in before a license is imported, but requires a valid license to add or re-enable other members. Check the license screen in system settings.
3. For a source deployment, after confirming access, remove `MONKEYAI_INITIAL_ADMIN_EMAIL` and `MONKEYAI_INITIAL_ADMIN_PASSWORD` from `.env` and recreate the backend with `docker compose up -d --no-build --no-deps backend`. The bootstrap settings only create an administrator when the user table is empty. They do not reset an existing account.
## Configure your instance
Edit `.env` in the deployment directory. Use `docker compose config --quiet` before applying changes. Use `docker compose up -d` to recreate the affected services; `restart` does not apply new environment values or port mappings. For packaged deployments, use their installed Compose files and avoid replacing their pinned image references with source-build defaults.
| Setting | Default in source Compose | When to change it |
| --- | --- | --- |
| `MONKEYAI_PUBLIC_URL` | `http://localhost:8080` | Set it to the exact external root address, including scheme and any nonstandard port. The web app and API share this origin, which is also used for OAuth, redirects, and resource URLs. |
| `MONKEYAI_ADMIN_PORT` / `MONKEYAI_HTTPS_PORT` | `8080` / `8443` on the host | Change if ports conflict. The container ports stay `8080` / `8443`. The HTTPS port is mapped even when built-in TLS is off. `admin` and `backend` do not publish their own ports. |
| `POSTGRES_USER` / `POSTGRES_DB` | `monkeyai` / `monkeyai` | Use `MONKEYAI_DATABASE_URL` if pointing migrate, backend, and proxy to a different database. Changing `POSTGRES_PASSWORD` alone does not rotate the password in an initialized database. |
| `MONKEYAI_S3_ENDPOINT` / `MONKEYAI_S3_BUCKET` | `http://rustfs:9000` / `monkeyai-resources` | Set a different endpoint or bucket when replacing the bundled object storage. The default region is `us-east-1` and path-style access is on. The S3 API is internal by default; the source stack publishes the RustFS console only at `127.0.0.1:9001`. The reviewed installer package does not publish the console. |
| `MONKEYAI_S3_ACCESS_KEY` / `MONKEYAI_S3_SECRET_KEY` | Fall back to the RustFS credentials | To use separate app credentials, grant `s3:ListBucket` and `s3:GetBucketLocation` on the bucket, plus `s3:GetObject`, `s3:PutObject`, and `s3:DeleteObject` on its objects. Add `s3:CreateBucket` if the backend must create the bucket. |
| `MONKEYAI_RUNTIME_RELAY` | `true` | Set to `false` if you do not need relay access. Leaving it on does not authorize access by itself: device owners must enable remote access locally and approve permissions. File URLs use the public origin unless `MONKEYAI_RUNTIME_FILES_ORIGIN` is set. |
| `MONKEYAI_LOG_LEVEL` / `MONKEYAI_LOG_MAX_SIZE` / `MONKEYAI_LOG_MAX_FILES` | `warn` / `20m` / `5` | Adjust backend verbosity and per-service Docker log rotation for your retention and disk budget. |
### Publish over HTTPS
If an existing gateway terminates TLS, configure it for the external hostname, preserve the host, and support WebSocket upgrades and streaming. Keep the internal ingress private. Set `MONKEYAI_PUBLIC_URL` to the public HTTPS address. In `MONKEYAI_TRUSTED_PROXY_CIDRS`, list only the IP addresses or CIDRs of proxies that connect directly to `nginx`. Have those proxies append the actual peer address to `X-Forwarded-For` or replace the header; do not pass arbitrary client-supplied values unchanged. Leave the setting empty when clients connect directly.
For built-in ACME, point the domain's DNS at the host. Public TCP 80 must reach container port 8080 for HTTP-01; TCP 443 must reach 8443 for HTTPS. If you publish an AAAA record, make sure IPv6 can reach the ingress as well. The container must be able to reach the CA over HTTPS. Set these values in `.env`:
```dotenv
MONKEYAI_AUTO_TLS_ENABLED=true
MONKEYAI_AUTO_TLS_EMAIL=admin@example.com
MONKEYAI_PUBLIC_URL=https://ai.example.com
MONKEYAI_ADMIN_PORT=80
MONKEYAI_HTTPS_PORT=443
```
Use an HTTPS domain root, not an IP address, localhost, a wildcard, or a URL with a path prefix, query, or fragment. Enabling ACME accepts the selected CA's terms. The default CA is Let's Encrypt; `MONKEYAI_AUTO_TLS_CA` overrides its directory URL. To apply the configuration to a running instance with the current images already available, run:
```bash
docker compose up -d --pull never --no-build --no-deps backend proxy nginx
docker compose logs --tail=100 nginx
```
This can interrupt active connections. The first certificate is issued in the background; the local `/healthz` response does not prove that public TLS works. Confirm the HTTPS URL from a separate network without disabling certificate verification. To turn off ACME, set `MONKEYAI_AUTO_TLS_ENABLED=false` and update the public URL if the external address changes. If packaged local TLS remains enabled, Nginx falls back to the bundled certificate. The `acme` volume is retained when this setting changes.
### Set outbound access and client download links
Set `HTTP_PROXY` and `HTTPS_PROXY` for backend OAuth and S3 traffic if needed. Keep internal destinations out of the proxy. Source Compose uses `MONKEYAI_NO_PROXY` to populate `NO_PROXY`; preserve `db,rustfs,backend,anydoc,localhost,127.0.0.1,::1` when overriding it. The inspected release package uses `NO_PROXY` plus its own internal exclusions instead. Docker image pulls use the Docker daemon's network settings, not the application's proxy settings.
Model and image upstream requests, MCP tool calls, and MCP OAuth discovery connect directly. MCP OAuth token exchange and refresh can use an HTTP proxy configured via `HTTPS_PROXY` for HTTPS token endpoints, subject to the existing target checks. SMTP and ingress ACME do not use the backend proxy. Review the [backend outbound proxy notes](README.md#后端出站代理) if your environment restricts egress.
To change the download links shown by the server's web app, edit [`web/public/downloads.json`](web/public/downloads.json) and rebuild the `admin` image, or mount a copy read-only at `/usr/share/nginx/html/downloads.json` on `admin`. Use HTTPS URLs or absolute paths on the same site. Set separate Linux and macOS links for ARM64 and x64. An empty value disables the link for that platform.
## Back up and restore
Make a backup before each upgrade and on a regular schedule. Either stop writes during a maintenance window or use a coordinated backup method that keeps PostgreSQL and object storage consistent. Do not copy the live PostgreSQL data directory as an ordinary file backup.
- **Database and objects:** Keep a PostgreSQL backup and the corresponding RustFS bucket contents together. On the local stack, the bind mounts are `data/postgres` and `data/rustfs`. Back up external services separately if you replaced either one. Preserve objects referenced by any retained database snapshot; do not purge old objects based only on current database references.
- **Instance and configuration:** Keep `.env`, the Compose files and overrides, the image versions, `data/runtime` (including the signing identity), `data/license`, and `data/tls/server` when present. For a packaged installation, also preserve `compose.defaults.yml`, `.monkeyai.json`, and any extra persistent data directories used by enabled features, such as `data/environment-images`. Record the Compose project name.
- **ACME:** Back up the named `acme` volume separately. It is usually named `<project>_acme` and is mounted at `/var/lib/nginx/acme` in `nginx`, outside `data/`. Protect and encrypt backups containing credentials and private keys.
For a logical database backup with the bundled PostgreSQL service, run this from the deployment directory during the coordinated backup window:
```bash
backup_dir=$(mktemp -d ./monkeyai-backup.XXXXXX) &&
docker compose exec -T db sh -c 'pg_dump -Fc -U "$POSTGRES_USER" "$POSTGRES_DB"' > "$backup_dir/monkeyai-db.dump.partial" &&
mv "$backup_dir/monkeyai-db.dump.partial" "$backup_dir/monkeyai-db.dump"
```
The dump is ready only if the command succeeded and produced `monkeyai-db.dump` in the new backup directory. Test the dump and its matching objects by restoring them in isolation. For recovery, start from the matching service versions and configuration; restore both the objects and database **before** starting the application stack. Preserve file ownership and the original identity for a recovery of the same instance. Verify sign-in and an existing resource download, including its checksum where available. Keep restored test instances isolated so they do not reuse a production identity on the same network or report as the live instance.
`docker compose down` stops and removes the containers but leaves bind-mounted data and named volumes in place. Do not use `docker compose down -v` for routine maintenance: it removes named volumes, including ACME state. In the current source Compose file, `data/runtime` is a bind mount, not a named volume; protect it independently.
## Upgrade
1. Review the target release and the [database migration notes](backend/migrations/README.md). Plan a maintenance window, allow time for migration, drain active work, and take a coordinated backup. An old database from before the consolidated migration history needs a separate migration plan; do not use `migrate force` to make it appear compatible.
2. **Packaged installation:** Verify and extract the target release package. From its extracted directory, run `sudo sh ./install.sh`, select **Upgrade** (`升级`), and point it at the existing installation directory. For a non-interactive upgrade, use the same directory with the following command (substitute your actual path):
```bash
sudo sh ./install.sh --non-interactive --action upgrade --install-dir /data/monkeyai
```
Do not use the installer to upgrade a manually managed Compose instance. The installer's configuration backup alone cannot roll back a database migration.
3. **Source Compose:** Keep the same project name and data paths. Build or stage matching images first. For a source build, run `docker compose build` at the target revision before the maintenance window. Stop the old services with `docker compose down` (no `-v`), then run `docker compose up -d --no-build` in the same deployment directory. Update ingress, admin, backend, proxy, and migrate as a set; do not run old and new application processes against an incompatible schema.
4. Check `docker compose ps -a` and migration logs. Verify backend readiness, the external URL and certificate, admin sign-in, and an existing resource download before reopening access. If migration fails, keep the old application off until you confirm schema compatibility. Use a tested restore or the release-specific recovery steps, not an image-only rollback after an incompatible migration.
## Troubleshoot
Run these commands from the source Compose directory or the packaged installation directory. Use `sudo` only if your Docker setup requires it.
```bash
docker compose ps -a
docker compose logs --tail=100 db migrate rustfs backend proxy nginx admin
docker compose exec -T backend wget -Y off -qO- http://127.0.0.1:8080/readyz
```
| Symptom | What to check |
| --- | --- |
| Page loads but sign-in or API calls fail | Check the backend's readiness probe and the `backend` and `nginx` logs. The ingress `/healthz` checks Nginx only. The backend `/readyz` checks database and bucket access; use the internal probe above, not the browser-facing path. |
| Migration does not finish | Check `migrate` logs and database connectivity. Confirm the migration image matches the backend and inspect the migration state before retrying. Do not force a version or clear the database to get past an error. |
| Backend keeps restarting | Check the bootstrap credentials if administrator bootstrap is supported, the bucket credentials and permissions, and ownership of the RustFS and runtime directories. Missing or unreadable persisted signing state is not fixed by discarding the old identity. |
| Redirects, login loops, or browser TLS errors | Check `MONKEYAI_PUBLIC_URL` against the URL you opened. For ACME, check the `nginx` logs, A/AAAA records, inbound port 80, CAA policy, outbound CA access, and ACME volume permissions. |
| Upstream works from the browser but not from the server | Check access from the sending container and whether that request type uses a proxy. Confirm private exclusions. When sharing logs, redact credentials and sensitive query parameters: Nginx logs can contain the original request URL. |
If you forget the administrator password and the backend container is running, use the reset command. It operates on an existing administrator, prints a new password, and revokes that account's old sessions and OAuth credentials. Keep the terminal output private.
```bash
docker compose exec --user 10001:10001 backend /app/monkeyai-server reset
```
For a packaged instance, use the verified release package's `status` or `doctor` action for installer diagnostics; it saves diagnostic files under `.monkeyai/diagnostics/`. If an upgrade entered database migration, review its logs and migration state before using the package's retry action.
+2
View File
@@ -1,5 +1,7 @@
# MonkeyAI
[English](./README.en.md)
## Docker Compose 启动
复制环境变量示例并至少修改数据库密码和初始管理员密码:
+80
View File
@@ -0,0 +1,80 @@
# MonkeyAI backend
[中文原文](./README.md)
The Go backend serves the MonkeyAI admin console and AI Work Agents. Both use the same business services and data model, but have separate HTTP contracts and request types. The standalone server composes both surfaces; the supplied Compose stack runs the same executable in separate control and proxy roles.
## Where to start
| Path | Responsibility |
| --- | --- |
| [cmd/server/](./cmd/server/) and [server/](./server/) | Standalone CLI and embeddable server entry points. |
| [internal/app/](./internal/app/) and [internal/httpapi/](./internal/httpapi/) | Application wiring and lifecycle; shared routing, middleware, and response conventions. |
| [api/](./api/) | OpenAPI contracts: [Admin](./api/admin.yaml) at `/api/admin/v1`, [Agent](./api/agent.yaml) at `/api/v1`, and [Host](./api/host.yaml). Model protocol compatibility uses `/v1`. See the [Admin API reference](./api/admin.en.md) and [Agent API reference](./api/agent.en.md) for English examples and operation indexes. |
| [internal/](./internal/) | Feature packages for identity, resources, models, knowledge bases, billing, sessions, devices, and the runtime relay. Keep handlers, SQL, generated repositories, and tests with their feature. |
| [migrations/](./migrations/) and [schema/](./schema/) | PostgreSQL migrations and the derived schema used by sqlc. |
| [docs/](./docs/) and [CONTEXT.md](./CONTEXT.md) | Design decisions, operational notes, and domain terminology. |
## Tools and dependencies
- Go 1.27 (see [go.mod](./go.mod)); GNU Make for the module targets. The service uses `net/http`, `chi/v5`, structured logging via `log/slog`, and serves JSON APIs and upstream model SSE streams.
- PostgreSQL with pgvector for database-backed development. Queries use `pgx/v5` and sqlc v1.30.0. Install the golang-migrate v4 CLI with the PostgreSQL driver for the standalone workflow, or use the Compose migration service.
- RustFS or a compatible S3 endpoint for resource storage. Docker and Compose are needed for the container workflow, not for ordinary Go compilation.
## Run locally
Run the following from `monkeyai/backend`. Start a **local development** PostgreSQL instance with pgvector and a reachable S3-compatible service first. Replace the example values with credentials for those services; do not use production credentials or commit them.
```bash
export MONKEYAI_DATABASE_URL='postgres://monkeyai:dev-password@127.0.0.1:5432/monkeyai?sslmode=disable'
export MONKEYAI_S3_ENDPOINT='http://127.0.0.1:9000'
export MONKEYAI_S3_ACCESS_KEY='your-local-access-key'
export MONKEYAI_S3_SECRET_KEY='your-local-secret-key'
export MONKEYAI_HTTP_ADDR='127.0.0.1:8080'
migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up
make run
```
Startup checks the object bucket and creates it if needed, with a one-minute deadline. The credentials need bucket/object access and, if the bucket does not exist, `s3:CreateBucket`. The defaults are bucket `monkeyai-resources` and region `us-east-1`; use a separate bucket for integration tests.
The public executable wires [stub member writers](./member/empty.go). A fresh database plus environment variables is not enough to create an administrator or sign in. For workflows that require real sign-in, use a development deployment that supplies the member writers via [server.Run](./server/server.go). With a working writer, bootstrap settings are `MONKEYAI_INITIAL_ADMIN_EMAIL`, `MONKEYAI_INITIAL_ADMIN_PASSWORD` (at least 12 characters), and optional `MONKEYAI_INITIAL_ADMIN_NAME`. Bootstrap is for an empty user table; remove the password from the environment after provisioning.
```bash
curl --fail http://127.0.0.1:8080/healthz
curl --fail http://127.0.0.1:8080/readyz
```
`/healthz` reports liveness; `/readyz` also checks PostgreSQL and the resource bucket. Profiling runs separately at `127.0.0.1:6060/debug/pprof/` by default. Run `go run ./cmd/server -h` for flags. See [configuration](./internal/config/), [logging](./docs/logging.md), and the [Compose and operations guide](../README.en.md) for additional settings, mounted data directories, and the full stack. The Compose file does not publish PostgreSQL or RustFS's S3 port to the host; do not assume it supplies the loopback endpoints above.
When running the [admin frontend](../web/README.en.md) separately, set `MONKEYAI_PUBLIC_URL` to the browser-visible Vite origin, normally `http://localhost:5173`, and point **both** Vite proxy environment variables to your local backend. The backend listener is still controlled by `MONKEYAI_HTTP_ADDR`. The public URL is also used for OAuth metadata, callbacks, and post-login redirects; use HTTPS for production.
If you lose the password for an existing **development** administrator, run `go run ./cmd/server reset` (or `./bin/monkeyai-server reset`) against that instance's database. This prints a new password, revokes old sessions and authentication grants, and does not create a user. It needs only `MONKEYAI_DATABASE_URL` or `--database-url`. Do not run it as a smoke test.
## Build, test, and generate code
The module [Makefile](./Makefile) defines these commands. The [Dockerfile](./Dockerfile) is the public backend image build used by [Compose](../docker-compose.yml); the parent Makefile also has private release targets with additional inputs.
```bash
make build # bin/monkeyai-server
./bin/monkeyai-server -h # print startup options without starting services
go test ./internal/model/... # example feature-level check
go test ./migrations # includes migration name and up/down pairing checks
make test # go test ./...
make check # sqlc drift check, tests, and go vet
```
Use a disposable PostgreSQL database for `MONKEYAI_TEST_DATABASE_URL` and an isolated bucket for `MONKEYAI_S3_*` before running `go test ./... -count=1` with integration coverage. Database tests may create and remove temporary schemas; storage tests can leave immutable objects in the test bucket. Without these settings some tests skip. A migration upgrade test also needs the `migrate` executable. For endpoint and relay work, run `go test ./internal/relay/... ./internal/endpoint/... ./internal/session/...`; add `-race` for concurrency changes. The relay's Nginx integration additionally needs Docker and `MONKEYAI_TEST_NGINX_IMAGE`. The application-level relay test needs both the test database and object storage: `go test ./internal/app -run '^TestRuntimeRelayApplication$'`.
When queries or migrations change, use `make generate` and commit the SQL, `schema/schema.sql`, and generated Go files together. Use `make sqlc-check` to check drift without rewriting output. The Makefile pins sqlc through `go run`; `SQLC=sqlc` is an override for an installed copy of the same version. Migrations are the source of truth; the extractor skips data changes and temporary tables. Use `sqlc.narg` for nullable parameters and explicit PostgreSQL array types. Do not edit generated files or assemble application SQL strings by hand.
Create migrations with `migrate create -ext sql -dir migrations -seq <feature>_<action>`, then check for sequence collisions before merging. Never rewrite a published migration or force an old, incompatible migration history onto the current schema. See the [migration guide](./migrations/README.md) before upgrading or testing a rollback.
## Contributor notes
- Follow [AGENTS.md](./AGENTS.md). Keep changes in the owning feature; coordinate changes to dependencies, wiring, shared HTTP code, and OpenAPI contracts. Register routes explicitly through `app`, not `init`. Define small interfaces in the consuming package, keep HTTP DTOs separate from domain objects, and avoid generic catch-all packages. Use receiver-returning `WithXxx` methods for optional configuration; reserve underscores in hand-written file names for tests and platform suffixes.
- **Design resources:** [designcatalog](./internal/designcatalog/) owns immutable snapshots, validation, and media access; [resourceimport](./internal/resourceimport/) handles import plans, receipts, and retries. At `/api/v1/design-resources`, JSON and ZIP use Agent authentication; media uses a separate short-lived token. See the [import guide](../design/design-resource-import.md) and [authentication setup](../design/agent-auth-settings.md).
- **Devices and remote execution:** The legacy WebSocket bridge keeps live connections and queues in memory; don't run two bridge owners during a rolling restart or retry requests whose outcome is unknown. Use the configured public origin for WS/WSS. The relay is on by default (`MONKEYAI_RUNTIME_RELAY=false` disables it). Keep `MONKEYAI_RUNTIME_STATE_DIR` writable and persistent; losing it changes the server identity. In Compose the runtime bind mount must be writable by UID 10001. In split deployments keep ingress, control, and proxy versions aligned. See the [endpoint map](./internal/endpoint/guidelines.md), [relay map](./internal/relay/guidelines.md), and [runtime protocol](../design/remote-runtime-protocol.md). Optional execution previews require a distinct wildcard origin and matching TLS certificate at **Nginx ingress**; ordinary file downloads are not execution previews.
- **Resource consistency:** Agent resource endpoints version their responses separately. Apply permission and credential checks on every request; use a read-only Repeatable Read snapshot where a list and its related data need to agree. Preserve hash and ETag semantics, and don't turn a failed resource lookup into an empty response. Keep optimistic concurrency on credit adjustments and move normalized API identifiers through the owning service.
- **MCP tool snapshots:** Resolution uses stored snapshots, not a live fetch on misses. The [refresh worker](./internal/mcp/refresh.go) controls `MONKEYAI_MCP_TOOLS_REFRESH_*` defaults; its ten-minute interval is a target, not an expiration. Run migrations and warm active connections before cutting over so older clients do not mistake a cold tool list for an unavailable connector.
- **Model usage accounting:** Preserve the original JSON encoding and idempotency hashes. Stream parsers may borrow the current SSE event's bytes; do not mutate or reuse that view across event reads. Estimate input use only when the upstream does not supply it.
+2
View File
@@ -1,5 +1,7 @@
# MonkeyAI Backend
[English](./README.en.md)
MonkeyAI 的统一 Go 后端,同时承接管理后台和 AI Work Agent 的请求。首期使用一个服务进程,两类调用方复用同一套业务逻辑和数据模型。
## 设计资源
+2
View File
@@ -1,5 +1,7 @@
# API
[English Admin API reference](./admin.en.md) · [English Agent API reference](./agent.en.md)
OpenAPI 源文件按调用方分为 `admin.yaml` 和 `agent.yaml`。管理后台接口统一维护在 `admin.yaml`,工作 Agent 接口统一维护在 `agent.yaml`,不再按业务模块拆分或生成合并文档。
每个接口必须声明请求体、成功与错误响应、响应 JSON Schema,并为字段补充类型、约束和说明;不能只记录状态码和响应描述。契约字段以实际 HTTP DTO 为准,密钥等不返回的敏感字段需要明确说明。
+455
View File
@@ -0,0 +1,455 @@
# MonkeyAI Admin API developer reference
Use this guide to find an operation and see how to call it. For the full contract, open the [Admin OpenAPI specification](./admin.yaml) on this branch and find the exact path and method under `paths`. Resolve shared schemas, parameters, responses, and security schemes under `components`. The [Chinese API notes](./README.md) cover additional behavior and related protocols. This reference indexes all 218 operations declared in the Admin specification, including the few related routes outside `/api/admin/v1`.
[Authentication](#authentication-and-access) · [Requests and errors](#requests-responses-and-errors) · [Examples](#common-workflows) · [Operation index](#operation-index) · [Contract notes](#contract-and-implementation-notes)
## Authentication and access
Use your MonkeyAI instance's origin as the base URL. Use HTTPS when sending credentials, and keep cookies, automation secrets, and upstream provider keys out of URLs, source code, and logs.
| Credential | Send it as | Where it applies |
| --- | --- | --- |
| Admin browser session | `Cookie: monkeyai_session=<session>` | Normal console access. The browser sends the HttpOnly cookie after sign-in. The route still checks the account's role. |
| Admin automation token | `X-MK-API-TOKEN: <admin-token-secret>` | Admin automation on routes that accept it. Send the raw secret, without a `Bearer` prefix. Authorization follows the token creator's current account status and role; creating a token does not grant new privileges. |
| Browser session for self-service | The same `monkeyai_session` cookie | The four profile operations under `/api/auth/v1/profile` work for any valid browser session, not just an administrator. Profile writes also need `X-CSRF-Token` from the profile GET; if you send an `Origin`, it must match the instance's public origin. After a password change, use the new cookie and CSRF token from the response. |
| Knowledge-base image access | Browser cookie **or** `Authorization: Bearer <agent-access-token>` | Only for the indexed content-image read at `/api/kb/{id}/assets/{name}`. Access to the knowledge base is checked on each read. If an Authorization header is supplied, the implementation takes the Agent-auth path. |
Most console operations require a **global administrator** (stored role `admin`). A signed-in **group supervisor** (web role `group_admin`) can use the shared and scoped GET operations marked **Shared** and **Scoped** in the [operation index](#operation-index). Scoped reads are limited to current managed employees in the supervisor's groups and descendant groups; some fields are omitted. For example, supervisors do not receive request parameters, target IDs, or error details in audit results. The shared user and group lists are not the same as a scoped member-detail read. For a scoped user candidate search, pass `scope=managed`; only global admins can request `include_deleted=true`. The fallback environment list is scoped; an installed environment module can provide its own route and authorization rules.
If `X-MK-API-TOKEN` is present on an Admin-auth route, a bad token gets `401` even if the request also carries a valid cookie. An expired or disabled token, or one whose creator is no longer active, is invalid. Token management at `/api/admin/v1/admin-tokens` is **global-admin browser-session only** and rejects cross-site requests. Create a token with a `name` (1–80 characters) and `expires_on` (an eligible Shanghai calendar date in `YYYY-MM-DD` format). The `201` response contains `token` metadata and the one-time `secret`. Rotation returns a replacement secret and invalidates the old one; enabling a token does not renew it. The list never returns secrets. Agent OAuth access tokens and the model/MCP invocation keys are not Admin automation tokens.
The public sign-in, branding, capabilities, and versioned avatar routes do not take an Admin credential. The connector OAuth callback validates its authorization transaction and OAuth state. The internal AnyDoc image callback instead requires a server-issued signed `token` query parameter and checks the initiating user's current write permission; it is not a general-purpose upload endpoint.
## Requests, responses, and errors
- Replace each `{placeholder}` with the required path value; many IDs are UUIDs. Send `Content-Type: application/json` for JSON bodies. Use the content type listed by the operation for multipart uploads, raw image bytes, or downloads.
- Success responses are specific to each operation: a resource object, a list, a status object, binary data, a redirect, or no body for `204 No Content`. There is no common success wrapper. Check the operation's status, headers, and schema before decoding.
- For revision-protected writes, send the current `ETag` as `If-Match`, including its quotes. Read the specific operation's contract instead of assuming every mutation requires it. On `412`, re-read the resource and reconcile your changes before retrying.
- Most JSON errors use `{"error":{"code":"…","message":"…"}}`; some include `error.references` for recovery. Branch on the HTTP status and `error.code`, not the localized message. Use `Accept-Language: en-US` for English; the server supports English and Simplified Chinese, with `zh-CN` as the fallback when no supported language is selected. On localized errors, check `Content-Language` and retain the trace ID appended to the message when present. Callbacks, downloads, and router-level errors need not use this JSON shape.
| HTTP status | What to check |
| --- | --- |
| `400` | Validate the request shape, required fields, and filter values. |
| `401` | Sign in again, or check the explicit automation token; an invalid token does not fall back to the cookie. |
| `403` | Check role, scope, credential type, and operation-specific restrictions. |
| `404` | Check the ID and visibility. Some scoped reads deliberately hide out-of-scope resources. |
| `409` | Inspect the operation's error code, such as `user_exists` when creating a member. |
| `412` / `428` | Where required, the revision did not match or `If-Match` was missing. |
| `429` | A rate limit applies, for example on email-code requests; follow `Retry-After` when present. |
| `502` / `504` | Where declared, the upstream service failed or timed out. Do not blindly replay a write. |
### Pagination
| Pattern | Examples and stopping rule |
| --- | --- |
| `page`, `page_size`, `total` | Audits start at page 1, default to 20 per page, and allow up to 500. Use `total` as the count of matching records. |
| `page`, `page_size`, `has_next` | Task and conversation history start at page 1, default to 20, and allow up to 500 per page. They do not return `total`. Billing entries also use `has_next`; follow the endpoint's own filter and page-size rules. |
| `cursor`, `limit`, `next_cursor` | Rules and knowledge bases default to 200 per request, with `limit` between 1 and 500. Omit `cursor` on the first request, then pass back the returned `next_cursor` unchanged with the same filters. Stop when it is empty. Other cursor-based endpoints may use different limits. |
| Endpoint-specific | Environment and environment-operation lists have a page size of at most 100; do not assume a count or `has_next` field. The users route returns `users` without search parameters, or `items` and `has_next` for a candidate search (`limit` defaults to 20, range 1–50). Candidate search does not use numbered pages. |
## Common workflows
The requests below are examples, not live credentials or responses. Use your own instance origin and replace placeholder values. Response headers are shown only when relevant.
### Sign in with a password
Requires an active global admin account and enabled password sign-in. Supply both `email` and `password`. For email-code sign-in instead, request a code with `purpose: "login"` via `POST /api/auth/v1/email/code`, then submit `email` and `code` to `POST /api/auth/v1/admin/email/login`; that admin endpoint does not create accounts.
~~~http
POST /api/auth/v1/admin/login
Content-Type: application/json
Accept-Language: en-US
{"email":"admin@example.com","password":"<admin-password>"}
~~~
~~~http
HTTP/1.1 200 OK
Set-Cookie: monkeyai_session=<session>; Path=/; HttpOnly; Secure; SameSite=Lax
Content-Type: application/json
{"id":"11111111-1111-4111-8111-111111111111","name":"Example Admin","email":"admin@example.com","role":"admin","status":"active","joined_at":"2026-01-15T10:00:00Z"}
~~~
On a failed credential check, the implementation returns `401 invalid_credentials`; if password sign-in is disabled, it returns `403 method_disabled`. The successful example assumes HTTPS. A group supervisor uses an existing browser session from the regular sign-in flow, not either admin-only sign-in endpoint.
### Create a regular member
Send `name`, `email`, and `role`. With `role: "user"`, the server generates a 16-character initial password and ignores any supplied password. With `role: "admin"`, the contract requires a password of at least 12 characters. To add the member directly to existing groups, supply their UUIDs in the optional `group_ids`; do not use the virtual root group ID.
~~~http
POST /api/admin/v1/users
X-MK-API-TOKEN: <admin-token-secret>
Content-Type: application/json
Accept-Language: en-US
{"name":"Example Member","email":"member@example.com","role":"user"}
~~~
~~~http
HTTP/1.1 201 Created
Cache-Control: no-store
Content-Type: application/json
{"id":"22222222-2222-4222-8222-222222222222","name":"Example Member","email":"member@example.com","role":"user","status":"active","joined_at":"2026-01-15T10:00:00Z","initial_password":"<initial-password>"}
~~~
Handle `initial_password` as a secret. The API returns it only on creation; do not log it or keep it in client storage. An email already in use returns, for example:
~~~http
HTTP/1.1 409 Conflict
Content-Type: application/json
{"error":{"code":"user_exists","message":"An account with this email address already exists. [trace_id: 0123456789abcdef0123456789abcdef]"}}
~~~
### Read a page of task history
No query parameters are required. This request filters by user UUID and illustrates a page with no matches or no further results. Use `has_next` to decide whether to increment `page`; do not look for `total`. For a time filter, `from` is inclusive and `until` is exclusive; include a time zone.
~~~http
GET /api/admin/v1/statistics/history?user_id=22222222-2222-4222-8222-222222222222&page=1&page_size=20
X-MK-API-TOKEN: <admin-token-secret>
Accept-Language: en-US
~~~
~~~http
HTTP/1.1 200 OK
Cache-Control: private, no-store
Content-Type: application/json
{"items":[],"page":1,"page_size":20,"has_next":false}
~~~
### Update a system rule without overwriting another edit
Read the rule with `GET /api/admin/v1/rules/{id}` and copy the returned `ETag` verbatim. The update requires the rule UUID, `If-Match`, and both `name` and `content`. This example updates a rule whose grants are already empty. Consult `RuleInput` and `RuleResource` in [OpenAPI](./admin.yaml) before changing grants or tags.
~~~http
PUT /api/admin/v1/rules/33333333-3333-4333-8333-333333333333
X-MK-API-TOKEN: <admin-token-secret>
If-Match: "1"
Content-Type: application/json
Accept-Language: en-US
{"name":"Review changes","content":"Explain the impact of every change."}
~~~
~~~http
HTTP/1.1 200 OK
ETag: "2"
Content-Type: application/json
{"id":"33333333-3333-4333-8333-333333333333","name":"Review changes","content":"Explain the impact of every change.","revision":2,"ownership_type":"system","grants":[]}
~~~
~~~http
HTTP/1.1 412 Precondition Failed
Content-Type: application/json
{"error":{"code":"revision_conflict","message":"The resource has changed. Refresh and try again. [trace_id: 0123456789abcdef0123456789abcdef]"}}
~~~
## Operation index
Paths are shown exactly as in [OpenAPI](./admin.yaml). For an operation's required inputs, supported content types, success schemas, and declared error responses, search for its exact path there and select the method. **Shared** and **Scoped** mark GETs available to group supervisors as described in [Authentication and access](#authentication-and-access). Unmarked console operations normally require a global administrator.
### Sign-in, profile, and public instance information
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/auth/v1/methods` | Read the public password and email-code sign-in settings. |
| `GET` | `/api/auth/v1/capabilities` | Read the features available on this instance. |
| `GET` | `/api/auth/v1/branding` | Read public product and workspace branding. |
| `GET` | `/api/auth/v1/branding/logo` | Read the public brand logo. |
| `POST` | `/api/auth/v1/email/code` | Request an email code for sign-in or password reset. |
| `POST` | `/api/auth/v1/email/reset-password` | Reset a password using an email code issued for password reset. |
| `POST` | `/api/auth/v1/admin/login` | Sign a global administrator in with a password and set the session cookie. |
| `POST` | `/api/auth/v1/admin/email/login` | Sign a global administrator in with an email code and set the session cookie. |
| `GET` | `/api/auth/v1/profile` | Read your own profile and obtain its CSRF token. |
| `PUT` | `/api/auth/v1/profile/avatar` | Upload your own custom avatar as image bytes. |
| `DELETE` | `/api/auth/v1/profile/avatar` | Remove your custom avatar and restore the fallback avatar. |
| `POST` | `/api/auth/v1/profile/password` | Change your password and rotate the current session and CSRF token. |
| `GET` | `/api/auth/v1/avatars/{userID}/{avatarID}` | Read a user's current custom avatar by user ID and avatar version. |
### Admin automation tokens and API discovery
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/admin-tokens` | List this instance's admin automation token metadata without secrets or hashes. |
| `POST` | `/api/admin/v1/admin-tokens` | Issue an automation token under the signed-in administrator and return its secret once. |
| `PATCH` | `/api/admin/v1/admin-tokens/{id}/expiry` | Renew a token from the later of its old expiry or the current time, without changing its secret or enabled state. |
| `POST` | `/api/admin/v1/admin-tokens/{id}/rotate` | Atomically replace a token's secret without changing its owner, name, status, or expiry. |
| `PATCH` | `/api/admin/v1/admin-tokens/{id}/status` | Disable or re-enable a token without changing its expiry. |
| `DELETE` | `/api/admin/v1/admin-tokens/{id}` | Delete an automation token while retaining its audit events. |
| `GET` | `/api/admin/v1/openapi/admin.yaml` | **Shared.** Download the serving instance's Admin OpenAPI YAML. |
### Members and groups
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/users` | **Shared.** List members or search for matching user candidates. |
| `POST` | `/api/admin/v1/users` | Create a member and optionally add them to groups in the same request. |
| `GET` | `/api/admin/v1/users/{userID}` | **Scoped.** Read a member profile by user ID. |
| `DELETE` | `/api/admin/v1/users/{userID}` | Delete the specified member account. |
| `POST` | `/api/admin/v1/users/{userID}/reset-password` | Reset a member's password as a global administrator. |
| `GET` | `/api/admin/v1/groups` | **Shared.** List member groups. |
| `POST` | `/api/admin/v1/groups` | Create a group under the specified parent, or at the top level. |
| `POST` | `/api/admin/v1/groups/move` | Move a batch of groups or members. |
| `PATCH` | `/api/admin/v1/groups/{groupID}` | Rename a group or change its parent. |
| `DELETE` | `/api/admin/v1/groups/{groupID}` | Delete the specified group. |
| `PUT` | `/api/admin/v1/groups/{groupID}/members` | Replace the group's direct membership list. |
| `PUT` | `/api/admin/v1/groups/{groupID}/supervisors` | Replace the group's supervisor list. |
### Instance settings, approvals, and audit
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/settings` | Read the administrator settings exposed by the service. |
| `PATCH` | `/api/admin/v1/settings/authentication` | Replace the email-domain allowlist for automatic registration. |
| `GET` | `/api/admin/v1/settings/branding` | Read the administrative branding settings. |
| `PUT` | `/api/admin/v1/settings/branding` | Update the product and workspace names and optionally replace or reset the logo. |
| `PUT` | `/api/admin/v1/settings/branding/logo` | Upload or replace the brand logo. |
| `DELETE` | `/api/admin/v1/settings/branding/logo` | Remove the custom logo and restore the default. |
| `GET` | `/api/admin/v1/settings/mcp` | Read the MCP network access settings. |
| `PUT` | `/api/admin/v1/settings/mcp` | Save the blocked IP ranges for MCP. |
| `GET` | `/api/admin/v1/settings/model_network` | Read the model network access settings. |
| `PUT` | `/api/admin/v1/settings/model_network` | Save the blocked IP ranges for models. |
| `GET` | `/api/admin/v1/settings/proxies` | Read the system network proxy configuration. |
| `PUT` | `/api/admin/v1/settings/proxies` | Save the system network proxy configuration. |
| `POST` | `/api/admin/v1/settings/email/test` | Send a test email using the saved SMTP settings. |
| `GET` | `/api/admin/v1/settings/client_access_policy` | Read the client sign-in and token-renewal policy. |
| `PATCH` | `/api/admin/v1/settings/client_access_policy` | Atomically change the sign-in and token-renewal switch for one client type. |
| `GET` | `/api/admin/v1/settings/member_resource_policy` | Read client-side write and sharing policies for the six resource types. |
| `PATCH` | `/api/admin/v1/settings/member_resource_policy` | Atomically change one resource policy without replacing the others. |
| `GET` | `/api/admin/v1/approvals` | List pending and resolved approval requests. |
| `GET` | `/api/admin/v1/approvals/{id}` | Read redacted approval details and a preview of the proposed change. |
| `POST` | `/api/admin/v1/approvals/{id}/decision` | Approve or reject a pending request. |
| `GET` | `/api/admin/v1/audits` | **Scoped.** Search the audit log with actor, time, and other filters. |
### Billing, quotas, and invocation keys
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/billing/settings` | Read billing policy and remote connection status without exposing certificates or private keys. |
| `PATCH` | `/api/admin/v1/billing/settings/{section}` | Update one billing-settings section, such as pricing, cycle, mode, cloud-desktop billing, or remote connection configuration. |
| `GET` | `/api/admin/v1/billing/quotas` | Read member and group quotas and the source of inherited quotas. |
| `PUT` | `/api/admin/v1/billing/quotas` | Update group quotas in bulk for the next billing cycle. |
| `POST` | `/api/admin/v1/billing/quotas/reset` | Reset the current-cycle quotas for the selected groups or members immediately. |
| `GET` | `/api/admin/v1/billing/accounts/{userID}` | Read a member's current-cycle credit account. |
| `POST` | `/api/admin/v1/billing/accounts/{userID}/adjustments` | Apply an idempotent adjustment to a member's current-cycle credits. |
| `PUT` | `/api/admin/v1/billing/accounts/{userID}/wallet` | Verify and bind a member's Baizhi Cloud wallet identity, provided there are no pending remote transactions. |
| `GET` | `/api/admin/v1/billing/entries` | **Scoped.** Page through immutable credit ledger entries. |
| `GET` | `/api/admin/v1/billing/summary` | Summarize charges and refunds for the selected filters. |
| `GET` | `/api/admin/v1/billing/reconciliation` | Find unfinished transactions, ledger discrepancies, and legacy configuration migration issues. |
| `GET` | `/api/admin/v1/billing/transactions/{id}` | Read a billing transaction's usage, price snapshot, ledger entries, and wallet records. |
| `POST` | `/api/admin/v1/billing/transactions/{id}/retry` | Retry settlement of a pending transaction whose usage is known. |
| `POST` | `/api/admin/v1/billing/transactions/{id}/resolve` | Resolve a transaction with an unknown outcome using verified evidence. |
| `POST` | `/api/admin/v1/billing/transactions/{id}/refund` | Reverse a locally settled charge in full, at most once per transaction. |
| `GET` | `/api/admin/v1/api-keys` | List model and MCP invocation-key metadata. |
| `DELETE` | `/api/admin/v1/api-keys/{keyID}` | Revoke an invocation key as an administrator. |
### Usage analytics and session history
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/statistics/models/overview` | **Scoped.** Read model runtime metrics, the 24-hour message distribution by model, and 90-day trends. |
| `GET` | `/api/admin/v1/statistics/realtime` | Read real-time runtime statistics. |
| `GET` | `/api/admin/v1/statistics/session-reporting/sessions/overview` | **Scoped.** Read the session analytics overview, including totals, trends, model usage, and message outcomes. |
| `GET` | `/api/admin/v1/statistics/session-reporting/members/overview` | **Scoped.** Read member totals, 7-day and 24-hour activity, and 90-day trends. |
| `GET` | `/api/admin/v1/statistics/session-reporting/members/{id}` | **Scoped.** Read usage and resource-creation statistics for a member. |
| `GET` | `/api/admin/v1/statistics/conversations` | **Scoped.** Page through conversation-turn history. |
| `GET` | `/api/admin/v1/statistics/history` | **Scoped.** Page through task history. |
| `GET` | `/api/admin/v1/sessions/{id}` | Read session statistics metadata or the tombstone for a purged session. |
| `DELETE` | `/api/admin/v1/sessions/{id}` | Purge statistics for a root session and its children while retaining the tombstone and financial ledger. |
| `GET` | `/api/admin/v1/statistics/session-reporting/sessions/{id}` | Read detailed session reporting, including turns and gateway calls. |
| `GET` | `/api/admin/v1/statistics/session-reporting/resources` | **Scoped.** Read per-member resource enablement, use, invocation, and failure metrics. |
| `GET` | `/api/admin/v1/statistics/session-reporting/clients` | Read client metrics grouped by platform, version, and outcome. |
| `GET` | `/api/admin/v1/statistics/session-reporting/clients/overview` | Read distributions of sessions by client type, platform, and version. |
### Feedback and registered devices
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/feedback` | **Scoped.** Page through user feedback. |
| `GET` | `/api/admin/v1/feedback/{id}` | **Scoped.** Read a feedback submission and its details. |
| `PATCH` | `/api/admin/v1/feedback/{id}` | Update the status of a feedback submission. |
| `GET` | `/api/admin/v1/feedback/{id}/attachments/{attachmentID}` | **Scoped.** Download an image attached to a feedback submission. |
| `GET` | `/api/admin/v1/endpoints` | **Scoped.** List registered client devices. |
| `GET` | `/api/admin/v1/endpoints/overview` | **Scoped.** Read totals and distributions for registered client devices. |
### Models
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/models` | List models and their administrative metadata. |
| `POST` | `/api/admin/v1/models` | Create a system model configuration. |
| `POST` | `/api/admin/v1/models/discover` | Discover available text models using upstream connection settings. |
| `POST` | `/api/admin/v1/models/{modelID}/probe` | Test a saved system text or embedding model using its stored configuration. |
| `GET` | `/api/admin/v1/models/image-capabilities` | Read supported image-model qualities, aspect ratios, and operations. |
| `GET` | `/api/admin/v1/models/authorization-subjects` | List users and groups that can be granted model access. |
| `PUT` | `/api/admin/v1/models/{modelID}` | Update a system model configuration. |
| `DELETE` | `/api/admin/v1/models/{modelID}` | Delete the specified system model. |
| `PATCH` | `/api/admin/v1/models/{modelID}/enabled` | Enable or disable the specified system model. |
### Rules, skills, experts, tags, and grants
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/rules` | List rules, with filters for ownership and search text. |
| `POST` | `/api/admin/v1/rules` | Create a system rule. |
| `GET` | `/api/admin/v1/rules/{id}` | Read a rule and its configuration. |
| `PUT` | `/api/admin/v1/rules/{id}` | Update a system rule at the specified revision. |
| `DELETE` | `/api/admin/v1/rules/{id}` | Delete a rule at the specified revision, subject to reference checks. |
| `PATCH` | `/api/admin/v1/rules/{id}/enabled` | Enable or disable a system rule, including an imported rule. |
| `GET` | `/api/admin/v1/skills` | List skills, with filters for ownership and search text. |
| `POST` | `/api/admin/v1/skills` | Create a skill from a multipart ZIP package, with optional metadata. |
| `GET` | `/api/admin/v1/skills/{id}` | Read a skill and its metadata. |
| `PUT` | `/api/admin/v1/skills/{id}` | Update a skill's metadata or content. |
| `DELETE` | `/api/admin/v1/skills/{id}` | Delete the specified skill. |
| `PATCH` | `/api/admin/v1/skills/{id}/enabled` | Enable or disable a skill. |
| `PUT` | `/api/admin/v1/skills/{id}/package` | Replace a skill's uploaded package. |
| `GET` | `/api/admin/v1/skills/{id}/package` | Download a skill package after checking current access. |
| `GET` | `/api/admin/v1/skills/{id}/manifest` | Read a skill's manifest text. |
| `GET` | `/api/admin/v1/experts` | List experts, with filters for ownership and search text. |
| `POST` | `/api/admin/v1/experts` | Create a system expert. |
| `GET` | `/api/admin/v1/experts/{id}` | Read an expert's configuration and dependencies. |
| `PUT` | `/api/admin/v1/experts/{id}` | Update a system expert's configuration. |
| `DELETE` | `/api/admin/v1/experts/{id}` | Delete the specified expert. |
| `GET` | `/api/admin/v1/experts/{id}/avatar` | Read an expert's avatar image. |
| `PATCH` | `/api/admin/v1/experts/{id}/enabled` | Enable or disable a system expert. |
| `POST` | `/api/admin/v1/experts/{id}/copy` | Copy a system expert as a disabled expert with no grants. |
| `POST` | `/api/admin/v1/experts/{id}/preview` | Preview an expert's resolved resources for a specified user. |
| `GET` | `/api/admin/v1/resources/authorization-subjects` | List actual users and groups that can receive resource grants. |
| `GET` | `/api/admin/v1/resources/{type}/{id}/grants` | Read the current grants for a resource. |
| `PUT` | `/api/admin/v1/resources/{type}/{id}/grants` | Replace a resource's grants at the current revision. |
| `GET` | `/api/admin/v1/tags` | List resource tags. |
| `POST` | `/api/admin/v1/tags` | Create a resource tag. |
| `PUT` | `/api/admin/v1/tags/{id}` | Rename a resource tag. |
| `DELETE` | `/api/admin/v1/tags/{id}` | Delete a resource tag. |
### MCP connectors and credentials
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/connectors` | List connectors and their administrative metadata. |
| `POST` | `/api/admin/v1/connectors` | Create a connector configuration. |
| `GET` | `/api/admin/v1/connectors/{id}` | Read a connector configuration and its status. |
| `PUT` | `/api/admin/v1/connectors/{id}` | Update a connector configuration. |
| `DELETE` | `/api/admin/v1/connectors/{id}` | Delete the specified connector. |
| `PATCH` | `/api/admin/v1/connectors/{id}/enabled` | Enable or disable a connector. |
| `PATCH` | `/api/admin/v1/connectors/{id}/tools/{toolID}` | Configure a tool's enabled state or credits per call within the applicable credential context. |
| `POST` | `/api/admin/v1/connectors/{id}/test` | Test a connector with a live MCP handshake and tool discovery. |
| `GET` | `/api/admin/v1/connectors/{id}/tools` | Discover the connector's tools live in the applicable authentication context. |
| `POST` | `/api/admin/v1/connectors/{id}/oauth/authorizations` | Start an OAuth authorization to add a named credential for a centrally authenticated connector. |
| `GET` | `/api/admin/v1/connector-authorizations/{id}` | Read the status of a connector authorization transaction you initiated. |
| `GET` | `/api/admin/v1/connectors/{id}/credentials` | List centralized credential metadata without secrets. |
| `GET` | `/api/admin/v1/connectors/{id}/credentials/{credential_id}` | Read the specified credential's metadata and ETag without exposing its secret. |
| `POST` | `/api/admin/v1/connectors/{id}/credentials/{credential_id}/oauth/authorizations` | Start OAuth reauthorization for an existing credential, retaining its ID on success. |
| `POST` | `/api/admin/v1/connectors/{id}/credentials/{credential_id}/test` | Test the specified credential with a live MCP handshake and tool discovery. |
| `GET` | `/api/admin/v1/connectors/{id}/credentials/{credential_id}/tools` | Discover tools live using the specified credential context. |
| `PUT` | `/api/admin/v1/connectors/{id}/icon` | Upload a connector icon. |
| `GET` | `/api/admin/v1/connectors/{id}/icon` | Read a connector icon. |
| `GET` | `/api/admin/v1/connectors/{id}/tool-contexts` | List credential contexts available for reading a system connector's tools. |
| `GET` | `/oauth/connectors/{id}/callback` | Handle the upstream OAuth callback for a specific connector. |
### Resource package imports
| Method | Path | Purpose |
| --- | --- | --- |
| `POST` | `/api/admin/v1/resource-import-uploads` | Create a resumable resource package upload session. |
| `GET` | `/api/admin/v1/resource-import-uploads` | List the current administrator's unfinished upload sessions. |
| `GET` | `/api/admin/v1/resource-import-uploads/{id}` | Read upload progress and the list of stored chunks. |
| `DELETE` | `/api/admin/v1/resource-import-uploads/{id}` | Abandon an unfinished upload session. |
| `PUT` | `/api/admin/v1/resource-import-uploads/{id}/chunks/{index}` | Upload a numbered chunk of the resource package. |
| `POST` | `/api/admin/v1/resource-import-uploads/{id}/complete` | Validate the assembled ZIP and finalize the upload. |
| `POST` | `/api/admin/v1/resource-imports/preview` | Inspect a resource package and preview its changes. |
| `POST` | `/api/admin/v1/resource-imports` | Confirm import of the selected sections of a previewed package. |
| `GET` | `/api/admin/v1/resource-imports` | Page through resource package import batches. |
| `GET` | `/api/admin/v1/resource-imports/{id}` | Read the details of a resource package import batch. |
### Knowledge bases, documents, and imports
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/kb-concurrency` | Read knowledge-base concurrency settings. |
| `PUT` | `/api/admin/v1/kb-concurrency` | Save knowledge-base concurrency settings. |
| `GET` | `/api/admin/v1/kb-models` | Read the dedicated knowledge-base model assignments. |
| `PUT` | `/api/admin/v1/kb-models/{kind}` | Save the model assignment for the specified knowledge-base model kind. |
| `GET` | `/api/admin/v1/kb` | List knowledge bases with cursor pagination. |
| `POST` | `/api/admin/v1/kb` | Create a knowledge base. |
| `POST` | `/api/admin/v1/kb/{id}/images/upload` | Upload an image for knowledge-base document content. |
| `GET` | `/api/admin/v1/kb/{id}/avatar` | Read a knowledge base's icon after checking access. |
| `GET` | `/api/admin/v1/kb/{id}` | Read knowledge-base details. |
| `PUT` | `/api/admin/v1/kb/{id}` | Update a knowledge base, optionally replacing its icon. |
| `DELETE` | `/api/admin/v1/kb/{id}` | Delete the specified knowledge base. |
| `PATCH` | `/api/admin/v1/kb/{id}/enabled` | Enable or disable a knowledge base. |
| `POST` | `/api/admin/v1/kb/search` | Search knowledge-base document chunks. |
| `POST` | `/api/admin/v1/kb/{id}/embedding-model/switch` | Switch or unbind a knowledge base's embedding model. |
| `POST` | `/api/admin/v1/kb/{id}/index/rebuild` | Rebuild a knowledge base's index. |
| `POST` | `/api/admin/v1/kb/{id}/imports/upload` | Upload a file and start or complete document import, depending on file type. |
| `GET` | `/api/admin/v1/kb/{id}/imports/models` | List models available to the caller for describing images in imports. |
| `POST` | `/api/admin/v1/kb/{id}/imports/query` | Poll AnyDoc conversion and save the document when its result is ready. |
| `POST` | `/api/admin/v1/kb/{id}/imports/result` | Check whether a document associated with an import context already exists. |
| `GET` | `/api/admin/v1/kb/{id}/documents/{documentId}/file/detail` | Download or preview the original file for an imported document. |
| `GET` | `/api/admin/v1/kb/{id}/documents` | List documents in a knowledge base. |
| `POST` | `/api/admin/v1/kb/{id}/documents` | Add a document and submit it for learning. |
| `POST` | `/api/admin/v1/kb/{id}/documents/delete` | Delete one or more document or folder IDs. |
| `POST` | `/api/admin/v1/kb/{id}/documents/move` | Move one or more nodes in a knowledge base's document tree. |
| `GET` | `/api/admin/v1/kb/{id}/documents/{documentId}` | Read an individual document. |
| `PUT` | `/api/admin/v1/kb/{id}/documents/{documentId}` | Update a document and submit it for relearning. |
| `POST` | `/api/admin/v1/kb/{id}/documents/restudy` | Submit multiple documents for relearning. |
| `GET` | `/api/admin/v1/kb/{id}/documents/{documentId}/chunks` | List the chunks of an individual document. |
| `GET` | `/api/kb/{id}/assets/{name}` | Read an image referenced by knowledge-base content after checking access. |
| `POST` | `/internal/kb/imports/images/upload` | Receive an AnyDoc image upload through the server-issued signed callback. |
### Cloud environments and images
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/environments` | **Scoped.** List cloud environments with filters and paging, subject to the installed module's route rules. |
| `GET` | `/api/admin/v1/environments/{id}` | Read the details of a cloud environment. |
| `DELETE` | `/api/admin/v1/environments/{id}` | Delete a running instance while retaining its persistent directory. |
| `GET` | `/api/admin/v1/environments/{id}/runtime` | Read the environment's runtime version and upgrade capability. |
| `POST` | `/api/admin/v1/environments/{id}/runtime/upgrade` | Upgrade the environment's runtime without rebuilding its container. |
| `GET` | `/api/admin/v1/environments/{id}/operations` | List operations for the specified environment. |
| `POST` | `/api/admin/v1/environments/{id}/stop` | Request that a cloud environment stop. |
| `GET` | `/api/admin/v1/system-images` | List system images that have not been removed from the catalog. |
| `POST` | `/api/admin/v1/system-images/pull` | Pull a system image from an online registry. |
| `POST` | `/api/admin/v1/system-images/upload` | Upload a Docker image archive. |
| `GET` | `/api/admin/v1/system-images/{id}` | Read a system image and its processing progress. |
| `PATCH` | `/api/admin/v1/system-images/{id}` | Change a system image's display name. |
| `DELETE` | `/api/admin/v1/system-images/{id}` | Remove a system image from the catalog without affecting existing instances. |
| `GET` | `/api/admin/v1/environment-images` | List cloud environment images synced to the server. |
| `POST` | `/api/admin/v1/environment-images/sync` | Sync a digest-pinned image into the server registry. |
| `GET` | `/api/admin/v1/environment-specifications` | Read the global cloud-desktop specification catalog. |
| `PUT` | `/api/admin/v1/environment-specifications` | Atomically replace the global cloud-desktop specification catalog. |
### Environment capacity and engine hosts
| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/admin/v1/environment-hosts` | List host capacity for scheduling cloud environments. |
| `GET` | `/api/admin/v1/environment-hosts/{id}/setup` | Read the authorization scope for an environment host. |
| `PUT` | `/api/admin/v1/environment-hosts/{id}/setup` | Atomically update the authorization scope for an environment host. |
| `PATCH` | `/api/admin/v1/environment-hosts/{id}/scheduling` | Set whether an environment host accepts new allocations. |
| `PUT` | `/api/admin/v1/environment-hosts/{id}` | Set the host scheduling switch through the legacy endpoint. |
| `POST` | `/api/admin/v1/engine-host-enrollments` | Generate an enrollment command for installing an engine host. |
| `GET` | `/api/admin/v1/engine-upgrade` | Read the shared engine installation or upgrade command. |
| `GET` | `/api/admin/v1/engine-hosts` | Page through engine hosts and their latest preflight reports. |
| `POST` | `/api/admin/v1/engine-hosts/{id}/upgrade` | Dispatch an engine upgrade job to the specified host. |
| `POST` | `/api/admin/v1/engine-hosts/{id}/enrollment` | Regenerate the installation command for a host awaiting enrollment. |
| `DELETE` | `/api/admin/v1/engine-hosts/{id}` | Revoke the specified engine host's enrollment. |
| `DELETE` | `/api/admin/v1/engine-hosts/{id}/record` | Remove a host from the management list and revoke its access without uninstalling it. |
## Contract and implementation notes
These differences were found by reading the pinned sources, not by calling a deployment. They do not change the operation index, which follows [Admin OpenAPI](./admin.yaml).
- The [Chinese overview's session-analysis note](./README.md#会话分析概览) says the overview is admin-only. The [OpenAPI operation](./admin.yaml#L1722) and the [registration](../internal/stats/service.go#L60) instead put it on the scoped read path. The guide follows the contract and implementation here.
- The [Chinese audit note](./README.md#操作审计) says only admins can read audits. The [audit operation](./admin.yaml#L1566) describes supervisor scope and redaction, and the [audit registration](../internal/audit/service.go#L87) uses a scoped read wired through the shared console router. The guide follows the scoped behavior.
- The [OpenAPI download description](./admin.yaml#L101) mentions browser sessions, with no operation-level override of the global security alternatives. The [route registration](../internal/app/app.go#L309) uses the shared Admin middleware, which [also processes an explicit automation token](../internal/identity/middleware.go#L58). Browser-session access is the documented usage; confirm whether automation access should be stated explicitly in the contract.
- The [rule detail and update operations](./admin.yaml#L3785) refer callers to the last ETag for writes, but do not declare the success response header. The [resource handlers](../internal/resource/store.go#L887) set the ETag on read and save. The update example shows that implemented header.
- The [create-user operation](./admin.yaml#L2868) documents `409 user_exists`. The [handler](../internal/identity/admin.go#L237) can also return `409 seats_exceeded` or `503 seats_unavailable`/`member_writer_unavailable` when the applicable deployment enforces seat limits or the member writer is unavailable. Confirm whether to extend the OpenAPI responses; this guide does not treat those as universal deployment behavior.
- The [identity router](../internal/identity/admin.go#L40) also registers `GET /api/admin/v1/me` and `PATCH /api/admin/v1/users/{userID}`, neither of which is declared in this OpenAPI file. Confirm whether to document them in the contract; they are not part of the 218-operation index.
+397
View File
@@ -0,0 +1,397 @@
# MonkeyAI Agent API reference
## Authentication and callers
This reference is for MonkeyAI client and integration developers. Use the public origin of your MonkeyAI deployment as the base URL. The [Agent OpenAPI contract](./agent.yaml) (version 1.0.0) on this branch contains the complete request and response schemas, constraints, and per-operation status codes. Administrator APIs and standalone host enrollment have separate contracts: [Admin](./admin.yaml) and [Host](./host.yaml).
| Caller | Credential and boundary |
| --- | --- |
| Signed-in desktop, mobile, or web client | Send `Authorization: Bearer <access_token>` for the Agent REST APIs. The token identifies the user; it does not grant access to another user's resources. Visibility, ownership, sharing, and review policy still apply. |
| OAuth installation client | Discover deployment capabilities at `/.well-known/oauth-authorization-server`. Use the registered client ID and redirect URI, browser consent, and PKCE S256 for authorization-code login. Exchange the code with the original redirect URI and verifier at `/oauth/token` using form encoding. Refresh with the rotated refresh token; replay of an already rotated token revokes the grant family. |
| Browser consent UI | Completion and device decisions use the `monkeyai_session` cookie and the consent request's CSRF checks, not an Agent Bearer token. Public lookup endpoints may show the current browser login state without requiring login. |
| Independently authorized runtime | Use the device authorization flow for `monkeyai-runtime`. A machine-bound runtime grant is not a desktop control grant: it can use authorized account resources, but not interactive-only routes such as billing or feedback. Runtime invocation-key management requires a bound machine and key. |
| Remote control client | Request a short-lived target-specific ticket using OAuth and the required device/business scopes. Device proxy routes use that ticket, not the OAuth access token. The general WebSocket bridge to a target uses `monkeyai.v1` plus `monkeyai.token.<ticket>`; the terminal uses `monkeyai.terminal.v1` with the ticket subprotocol or Bearer ticket. |
| MCP or image gateway client | Create a separate invocation key with the signed-in OAuth token. Send the key as Bearer for MCP (`mcp:invoke`). For image calls (`model:invoke`), `X-Api-Key` takes precedence over Bearer. Neither gateway accepts the OAuth access token as an invocation key. |
| Scoped file or media client | Isolated runtime preview/file URLs carry a signed grant tied to the configured origin and target. Local design media uses a short-lived media JWT (Bearer or `token` query parameter); a supplied Authorization header takes precedence without query fallback. Request `target=monkeyai-media` from the design token endpoint; its JWT cannot be replaced with an Agent or design hub token. A knowledge-base MCP upload can use a temporary, target-bound upload token. Do not log these URLs or credentials. |
Request the scopes appropriate to the operation. For example, environment reads use `environment:read`, environment changes use `environment:manage`, device connections use `device:connect`, and desktop pairing control uses `device:manage`. Old tokens do not acquire new scopes on refresh. The OAuth device flow and the desktop-to-mobile pairing flow are separate. In pairing, the desktop creates and approves the request; the phone joins with the QR secret, binds a PKCE challenge, and exchanges the resulting device code using the pairing-code grant. Follow the returned polling interval; `slow_down` tells the phone to add five seconds. The mobile token does not carry device management or publishing permission.
- [Read resources and paginate](#read-resources-and-paginate)
- [Search or update a knowledge base](#search-or-update-a-knowledge-base)
- [Select and use a connector credential](#select-and-use-a-connector-credential)
- [Handle errors](#handle-errors)
- [Operation index](#operation-index) · [Contract and implementation differences](#contract-and-implementation-differences)
### Exchange an authorization code
After desktop browser consent, exchange the returned code. Use the same registered redirect URI and the original PKCE verifier from the authorization request. The origin and credentials below are placeholders.
```sh
BASE_URL='https://<your-monkeyai-host>'
curl --include "$BASE_URL/oauth/token" \
-H 'Accept-Language: en-US' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'client_id=monkeyai-desktop' \
--data-urlencode 'redirect_uri=monkeyai-desktop://oauth/callback' \
--data-urlencode 'code=<authorization-code>' \
--data-urlencode 'code_verifier=<original-pkce-verifier>'
```
A `200` JSON response includes `access_token`, `refresh_token`, `token_type`, and `expires_in`; it is marked `Cache-Control: no-store`. Send the access token to the Agent API and keep the refresh token out of resource requests and logs. OAuth `400 invalid_grant` calls for checking the code, callback, or verifier, not replaying the same exchange.
### Request and response conventions
Use `Content-Type: application/json` for JSON bodies. Use URL-encoded forms for OAuth token and device flows, and multipart bodies for uploads that declare them. Ordinary REST success bodies are endpoint-specific JSON, not a universal `data` wrapper. Design catalog JSON is an exception: catalog successes use `{code: 0, message: "", data: ...}`; the design token response is a bare object. Follow redirects only where documented; inspect the status and media type before decoding ZIPs, images, HTML, forwarded responses, or protocol frames. A `204` or `304` response has no body.
Treat `202` according to the operation. For a reviewable personal resource, it is an approval receipt, not effective content or permission: retain `resource_id` and `approval_id`, check the approval, and re-read the resource. A share may also still be waiting for the first publication. For document ingestion or a cloud operation, `202` instead means work was accepted for processing; for an MCP notification it is an empty acknowledgment.
## Read resources and paginate
Read settings, models, rules, skills, experts, connectors, and knowledge bases separately; `GET /api/v1/config` is no longer supported. The example uses shell variables throughout this guide. Replace the placeholder deployment origin and retrieve a real token through the OAuth flow; never hard-code or commit one.
```sh
ACCESS_TOKEN='<oauth-access-token>'
curl --include --get "$BASE_URL/api/v1/models" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H 'Accept-Language: en-US' \
--data-urlencode 'owner=shared' \
--data-urlencode 'page=1' \
--data-urlencode 'page_size=20'
```
A `200` contains `models`, `model_gateway`, `version`, `total_count`, `page`, and `page_size`. Use a model's `model` selector (not its display name) for gateway calls. Model API keys and upstream configuration are not exposed to recipients. The conditional catalog reads send `ETag` and `Cache-Control: private, no-cache`. Save the returned ETag with its quoted value, then send it as `If-None-Match` on the **same** request. A `304` reuses that cached page; a `200` replaces it, including removed or revoked entries. Cache per deployment, authenticated user, endpoint, and query. The `version` is specific to the returned representation, not a shared revision across catalogs. Do not use a catalog ETag as the edit revision: get the resource detail and send its revision ETag as `If-Match` where required.
| Listing family | Input and result |
| --- | --- |
| Models, rules, skills, experts, connectors, knowledge bases | `page` starts at 1 (default 1, max 1,000,000); `page_size` defaults to 20 and is at most 100. An invalid value returns `400`. Filters apply before pagination; `total_count` is the filtered count. Use `owner=all/team/mine/shared` where advertised, `q` for search, and `tag_id` or repeated/comma-separated `tag_ids` where supported (any matching tag). The array key is resource-specific, for example `rules` or `knowledge_bases`, not always `items`. |
| Knowledge-base documents | `items`, `total_count`, `page`, and `page_size`. Use `q`, `status`, and `source_type` before paging. List rows omit document body content; fetch the document detail to read it. |
| Author inventory, approvals, and approval-backed drafts | `items` and `total`. `resources/mine` requires `resource_type`; approvals accept `status`, `resource_type`, and `action`. Do not use this inventory as a runtime catalog. |
| Endpoints and credit entries | `items`, `total`, `page`, and `page_size`; the remote endpoint directory adds `version`. The session index instead nests page information under `pagination`. |
| Cloud environments and operations | `items`, `page`, and `page_size`, without a total. System images and environment specifications are catalogs, not pages. Do not require a count field across all lists. |
An author's catalog can include a first unpublished draft, or mark an existing row with a pending edit while still serving its published content. Gate runtime use on effective content and current permissions. The expert manifest and resource resolution expose `available` and `issues`; a read can succeed even if the selection is not runnable. Required rules are included during resolution; optional rules can be selected in `rule_ids`. Select the model independently of the expert.
## Search or update a knowledge base
1. List accessible libraries with `GET /api/v1/kb`. Read the chosen library with `GET /api/v1/kb/{id}`. Use `permissions.can_write_content` to decide whether to offer writing. Read/write access includes content deletion, not library settings, re-sharing, permission management, or deletion of the library. An owner can manage personal library grants via the permissions endpoints.
2. Search learned content with `POST /api/v1/kb/search`. `query` is required, `kb_ids` can narrow the search to at most 50 accessible libraries, and `top_k` defaults to 8 (range 1–20). Omit `kb_ids` to search across accessible libraries; pass IDs explicitly if the deployment has more than 50. A library with no learned content contributes no hits. `filters` is reserved, not an implemented generic filter.
```sh
curl --include "$BASE_URL/api/v1/kb/search" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H 'Accept-Language: en-US' \
-H 'Content-Type: application/json' \
--data '{"query":"expense approval policy","kb_ids":["11111111-1111-4111-8111-111111111111"],"top_k":5}'
```
Replace the illustrative UUID with a library the caller can read. A `200` reports `items`, `retrieval_mode`, `channels_used`, `fusion`, `degraded`, and `warnings` along with the query. Hits identify the library, document, and chunk; use the returned citation information where available. Search uses lexical retrieval without a usable embedding model, and hybrid retrieval when configured. A failed vector channel can fall back to lexical; read the reported channels and warnings, not an assumed mode. Bad input returns `400`; an inaccessible explicitly selected ID can return `404` in this implementation.
3. To write a text document, send JSON such as `{ "title": "Expense policy", "content": "..." }` to `POST /api/v1/kb/{id}/documents`. A text document is returned as `202` with `status=pending` while learning runs. Use the document list/detail to check its state. For binary sources use the import workflow, not the text body. Library create/update also support multipart `metadata` (a JSON string) and one `avatar` image when setting an icon.
4. For collaborative edits use the document's `expected_revision` or REST `If-Match` as specified. For batch move/delete, pass `ids` and a per-ID `expected_revisions` map as required. Inspect `succeeded` and `failed` even on a successful HTTP response; the batch item `reason` is not the top-level error envelope. `403` means a read-only member cannot write; missing and stale required revisions can produce `428` and `412`. Read the current state before retrying a conflict.
5. For an original, use `GET /api/v1/kb/{id}/documents/{documentId}/file/detail`; the default is an attachment, and `preview=true` permits inline PDF only. URLs served by `/api/kb/{id}/assets/{name}` use an OAuth access token or browser session, never an MCP key. The dedicated MCP upload returns a separate target-bound token and upload URL via `kb_upload_file`; send original bytes outside model context and use the returned task context to poll a pending import.
## Select and use a connector credential
1. Start with `GET /api/v1/connectors` using OAuth. Treat it as connector and credential metadata, not a live tool directory. A caller must still have permission to use the connector, and independent credentials belong to that caller. The connector's `authorization_mode` determines the next step:
| Mode | Inspect and test with OAuth | Invoke with the MCP key |
| --- | --- | --- |
| `none` | Call connector-level `/tools` or `/test`. | Use the connector's gateway URL without a credential ID. |
| `centralized` | Call connector-level `/tools`. Only administrators can test centrally. | Use the published gateway URL for the centralized credential. |
| `independent` | List `/credentials`, pick a credential, then use its `/tools` or `/test` path. | Use that credential's gateway URL. Sharing the connector does not share the owner's secrets. |
2. Add a named Header credential with `POST /api/v1/connectors/{id}/credentials` and JSON containing `name` and `http_headers`. A `201` returns metadata and an ETag, not Header values. The server attempts a test after saving; a failed test does not undo the save. Alternatively, start OAuth authorization with `name`, open the returned authorization URL, and poll `GET /api/v1/connector-authorizations/{id}` using the initiator's token. `succeeded` includes `credential_id`; inspect the connection status separately. Use the credential ETag when replacing Headers, revoking, or reauthorizing that credential. The OAuth callback is a browser page, not a client JSON endpoint.
3. For a session, call `POST /api/v1/resources/resolve` with `expert_id` and/or explicit resource IDs. To select an independent credential, include its connector in `connector_ids` (or via the expert) and set `connector_bindings` to a map of connector ID to credential ID. A single authorized credential can be selected automatically; zero or several become issues in a `200` result, potentially setting `available=false`. An invalid explicit binding does not silently choose a different credential. Use explicit tool reads for live discovery; resolution uses the usable stored snapshot. Do not interpret an empty snapshot as proof that the upstream has no tools.
4. Use the gateway address returned for the selected connector/credential, and a separate `mcp:invoke` key. Creating it is a standard REST request:
```sh
curl --include "$BASE_URL/api/v1/api-keys" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H 'Accept-Language: en-US' \
-H 'Content-Type: application/json' \
--data '{"name":"Example connector client","scopes":["mcp:invoke"],"expires_in_days":90}'
```
A `201` includes `api_key` once; store it securely and use `GET /api/v1/api-keys` for metadata only. For invocation, configure a Streamable HTTP MCP client with the returned `mcp_gateway.url` and `Authorization: Bearer <invocation-api-key>`. Initialize, send `notifications/initialized` without an ID, then use `tools/list` and the names it returns. Send the negotiated `MCP-Protocol-Version` on subsequent requests. The gateway returns JSON-RPC over HTTP, gives empty `202` for notifications, and does not provide downstream SSE subscriptions or sessions. Missing credential context on a credentialed connector can return `400 credential_selection_required`. If a tool call's result is unknown, do not automatically replay it; follow the gateway's idempotency and billing rules in the contract.
## Handle errors
Inspect HTTP status and content type first, then branch on the stable error code. For ordinary Agent REST errors, read `error.code` and show `error.message`. Some responses include `error.references` for recovery; they do not add a top-level or nested `reason` to this envelope. As an example, omitting the Bearer token on the model catalog can return:
```http
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Language: en-US
Vary: Accept-Language
{"error":{"code":"invalid_token","message":"A Bearer access token is required. [trace_id: 0123456789abcdef0123456789abcdef]"}}
```
Send `Accept-Language: en-US` for English. Supported language variants are matched to `en-US` or `zh-CN`; absent or unsupported values fall back to `zh-CN`. Read `Content-Language` and honor `Vary: Accept-Language`. The trace ID above is illustrative; keep the actual `X-Request-ID` and any `trace_id` suffix for support, without retaining credentials or private content. The trace and request IDs are distinct. Do not match localized messages or assume upstream text, persisted `last_error`, or user content is translated.
| HTTP result | What to do |
| --- | --- |
| `400` / `422` | Fix the request using the endpoint's validation rules when it defines the status. Do not retry an unchanged invalid payload. |
| `401` / `403` | Check credential type, expiry, and then scopes or resource permissions. A valid token alone is not sufficient. |
| `404` | Check the identifier and current access. Many resource reads deliberately use the same status for missing and inaccessible content. Router-level `404` or `405` can be plain text. |
| `409` / `412` / `428` | Resolve the conflict, reload the current revision, or supply the required precondition as indicated by the code and endpoint. |
| `429` / `5xx` | Honor `Retry-After` when sent. Back off for temporary failures; do not blindly repeat non-idempotent operations. |
Exceptions matter: OAuth token errors use `error` and `error_description`. An OAuth `503 server_error` is not `invalid_grant`; back off rather than clearing the existing login. MCP uses numeric JSON-RPC errors and may put a business code in `error.data.code`; distinguish that from tool-result failures such as `isError`. Frozen design catalog errors have their own envelope, HEAD responses have no body, and relay routes can preserve upstream responses. Follow the route's contract rather than decoding every failure as ordinary Agent JSON.
## Operation index
All 179 HTTP operations declared in [agent.yaml](./agent.yaml), grouped by task. Paths are relative to the deployment origin. **OAuth** means the default Agent OAuth Bearer access token. Named OAuth scopes in the credential column are additional requirements, not separate credentials. Statuses shown are successful or conditional outcomes unless explicitly marked as unsupported. For schemas, limits, and all errors, search the [OpenAPI contract](./agent.yaml) for the exact path and method.
For request bodies, use JSON unless the route specifies another encoding; the index calls out common non-JSON bodies. An empty response or HEAD has no body. Range responses may include a multipart range body where the contract permits multiple ranges.
- [OAuth, pairing, and public login](#oauth-pairing-and-public-login) · [Author inventory, approvals, and sharing](#author-inventory-approvals-and-sharing)
- [Settings and models](#settings-and-models) · [Rules, skills, experts, and resource resolution](#rules-skills-experts-and-resource-resolution)
- [Connector catalog, credentials, and MCP gateway](#connector-catalog-credentials-and-mcp-gateway) · [Knowledge bases, documents, and imports](#knowledge-bases-documents-and-imports)
- [Invocation keys, image tasks, billing, and feedback](#invocation-keys-image-tasks-billing-and-feedback) · [Cloud environments](#cloud-environments)
- [Sessions, devices, remote relay, and files](#sessions-devices-remote-relay-and-files) · [Design resources](#design-resources)
### OAuth, pairing, and public login
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/auth/v1/capabilities` | Read the feature flags currently advertised by this deployment. | Public | 200 JSON |
| `GET /.well-known/oauth-authorization-server` | Discover OAuth endpoints, supported grants, and scopes. | Public | 200 JSON |
| `GET /oauth/authorize` | Start browser authorization for an installed client using PKCE. | Browser flow + PKCE | 302 redirect |
| `POST /oauth/token` | Exchange an authorization, pairing, or device code, or refresh an installation grant. Request: form. | OAuth grant credentials | 200 OAuth token JSON |
| `POST /oauth/pairing` | Create a short-lived QR pairing request from the desktop. | device:manage | 200 JSON |
| `POST /oauth/pairing/{pairingID}/join` | Join the QR pairing on the phone and bind its PKCE challenge. | Pairing secret + PKCE | 200 JSON |
| `GET /oauth/pairing/{pairingID}` | Read pairing state and phone information as the initiating user. | OAuth; initiating interactive user | 200 JSON |
| `POST /oauth/pairing/{pairingID}/approve` | Approve the phone pairing with the user-entered short code. | device:manage | 200 JSON |
| `POST /oauth/revoke` | Revoke the current installation grant family. Request: form. | OAuth revocation credentials | 200 empty |
| `GET /api/auth/v1/client-requests/{requestID}` | Read a frozen installation consent request and browser sign-in state. | Public lookup; optional session | 200 JSON |
| `POST /api/auth/v1/client-requests/{requestID}/complete` | Complete installation consent and generate the one-time callback. | Browser session + CSRF | 200 JSON |
| `POST /oauth/device/authorization` | Request independent runtime authorization for a machine and public key. Request: form. | Runtime device request | 200 JSON |
| `POST /api/auth/v1/device/decision` | Approve or deny a runtime device request in the browser. | Browser session + CSRF | 200 empty |
| `GET /api/auth/v1/client-requests/device` | Look up a frozen runtime request using its user-facing code. | Short-code lookup | 200 empty |
| `GET /api/auth/v1/methods` | Read which sign-in methods are available without signing in. | Public | 200 JSON |
| `GET /api/auth/v1/branding` | Read public deployment branding. | Public | 200 JSON |
| `GET /api/auth/v1/branding/logo` | Download the public branding logo, if configured. | Public | 200 PNG; 304 |
| `POST /api/auth/v1/email/code` | Request an email verification code. | Public | 200 JSON |
| `POST /api/auth/v1/email/reset-password` | Reset a password with an email verification code. | Public | 200 JSON |
| `POST /api/auth/v1/login` | Sign in to the client with a password. | Public | 200 JSON |
| `POST /api/auth/v1/email/login` | Sign in to the client with an email verification code. | Public | 200 JSON |
### Author inventory, approvals, and sharing
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/resources/mine` | List the caller's published resources and drafts for author management. | OAuth | 200 JSON |
| `GET /api/v1/approvals` | List the caller's approval requests with optional state and resource filters. | OAuth | 200 JSON |
| `GET /api/v1/approvals/{id}` | Read the caller's approval request and its outcome. | OAuth | 200 JSON |
| `GET /api/v1/resources/drafts` | List the approval records associated with unpublished drafts. | OAuth | 200 JSON |
| `GET /api/v1/groups` | List groups or search for groups to share with. | OAuth | 200 JSON |
| `GET /api/v1/users` | Search for eligible sharing recipients by name or email. | OAuth | 200 JSON |
| `GET /api/v1/resources/shares` | Read effective grants and pending or rejected share requests for an owned resource. | OAuth | 200 JSON |
| `POST /api/v1/resources/shares` | Share selected owned resources with users or groups, subject to review policy. | OAuth | 200 JSON; 202 JSON; 204 empty |
| `DELETE /api/v1/resources/shares` | Revoke the specified direct grants and pending share targets in a batch. | OAuth | 204 empty |
| `GET /api/v1/settings/member_resource_policy` | Read the effective personal-resource policies for the signed-in account. | OAuth | 200 JSON |
### Settings and models
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/settings` | Read the agent settings without server secrets. | OAuth | 200 JSON; 304 empty |
| `GET /api/v1/models/tags` | List tags on model configurations available to the caller. | OAuth | 200 JSON |
| `GET /api/v1/models` | Read available model selectors and model gateway information. | OAuth | 200 JSON; 304 empty |
| `POST /api/v1/models` | Create a personal model configuration or submit it for review. | OAuth | 201 JSON; 202 JSON |
| `GET /api/v1/models/{modelID}` | Read an owned model for editing without disclosing its stored key. | OAuth | 200 JSON |
| `PUT /api/v1/models/{modelID}` | Update the caller's model configuration. | OAuth | 200 JSON; 202 JSON |
| `DELETE /api/v1/models/{modelID}` | Delete the caller's model and associated shares. | OAuth | 204 empty |
### Rules, skills, experts, and resource resolution
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/rules` | Read the rule catalog, including which rules are required. | OAuth | 200 JSON; 304 empty |
| `POST /api/v1/rules` | Create a personal rule or submit it for review. | OAuth | 201 JSON; 202 JSON |
| `GET /api/v1/rules/{id}` | Read an owned personal rule for editing. | OAuth | 200 JSON |
| `PUT /api/v1/rules/{id}` | Edit an owned personal rule. | OAuth | 200 JSON; 202 JSON |
| `DELETE /api/v1/rules/{id}` | Delete an owned personal rule. | OAuth | 204 empty |
| `GET /api/v1/skills/tags` | List tags on skill configurations available to the caller. | OAuth | 200 JSON |
| `GET /api/v1/skills` | Read the effective skill catalog with caller-visible review state. | OAuth | 200 JSON; 304 empty |
| `POST /api/v1/skills` | Upload a skill ZIP to create a personal skill. Request: multipart. | OAuth | 201 JSON; 202 JSON |
| `GET /api/v1/skills/{id}/package` | Download a skill ZIP using current resource permissions. | OAuth | 200 ZIP |
| `PUT /api/v1/skills/{id}/package` | Replace the package for a personal skill the caller owns. Request: multipart. | OAuth | 200 JSON; 202 JSON |
| `GET /api/v1/skills/{id}` | Read a personal skill the caller owns. | OAuth | 200 JSON |
| `PUT /api/v1/skills/{id}` | Edit a personal skill the caller owns. | OAuth | 200 JSON; 202 JSON |
| `DELETE /api/v1/skills/{id}` | Delete a personal skill the caller owns. | OAuth | 204 empty |
| `GET /api/v1/skills/{id}/manifest` | Read the manifest content of an owned personal skill. | OAuth | 200 JSON |
| `GET /api/v1/experts/tags` | List tags on expert configurations available to the caller. | OAuth | 200 JSON |
| `GET /api/v1/experts/knowledge-support` | Check whether personal experts can bind knowledge bases. | OAuth | 200 JSON |
| `GET /api/v1/experts/avatar-support` | Check whether personal experts can write avatar images. | OAuth | 200 JSON |
| `GET /api/v1/experts` | List available experts and their manifest paths. | OAuth | 200 JSON; 304 empty |
| `POST /api/v1/experts` | Create a personal expert or submit it for review. | OAuth | 201 JSON; 202 JSON |
| `GET /api/v1/experts/{id}/manifest` | Read an available expert's prompt and resolved dependency manifest. | OAuth | 200 JSON; 304 empty |
| `GET /api/v1/experts/{id}/skills/{skillID}/package` | Download a linked skill ZIP using the expert's delegated access rules. | OAuth | 200 ZIP |
| `GET /api/v1/experts/{id}/avatar` | Read the avatar of an expert the caller may access. | OAuth | 200 image |
| `GET /api/v1/experts/{id}` | Read a personal expert the caller owns for editing. | OAuth | 200 JSON |
| `PUT /api/v1/experts/{id}` | Edit a personal expert the caller owns. | OAuth | 200 JSON; 202 JSON |
| `DELETE /api/v1/experts/{id}` | Delete a personal expert the caller owns. | OAuth | 204 empty |
| `POST /api/v1/resources/resolve` | Resolve the selected expert, rules, skills, and connector bindings for use. | OAuth | 200 JSON |
### Connector catalog, credentials, and MCP gateway
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/connectors/tags` | List tags on connector configurations available to the caller. | OAuth | 200 JSON |
| `GET /api/v1/connectors` | Read connector metadata and available credential contexts without live tool discovery. | OAuth | 200 JSON; 304 empty |
| `POST /api/v1/connectors` | Create a personal connector or submit it for review. | OAuth | 201 JSON; 202 JSON |
| `GET /api/v1/connectors/{id}/icon` | Download an icon for a connector the caller may access. | OAuth | 200 PNG |
| `PUT /api/v1/connectors/{id}/icon` | Upload an icon for an owned personal connector. Request: multipart. | OAuth | 200 JSON; 202 JSON |
| `GET /api/v1/connectors/{id}` | Read an owned personal connector for editing. | OAuth | 200 JSON |
| `PUT /api/v1/connectors/{id}` | Edit an owned personal connector. | OAuth | 200 JSON; 202 JSON |
| `DELETE /api/v1/connectors/{id}` | Delete an owned personal connector. | OAuth | 204 empty |
| `POST /api/v1/connectors/{id}/test` | Test a connector that does not require an independent credential. | OAuth | 200 JSON |
| `GET /api/v1/connectors/{id}/tools` | Discover current tools for a connector without independent credentials. | OAuth | 200 JSON |
| `POST /api/v1/connectors/{id}/oauth/authorizations` | Start OAuth authorization to add a named credential. | OAuth | 200 JSON |
| `GET /oauth/connectors/{id}/callback` | Complete or report the outcome of a connector's OAuth browser callback. | OAuth state; no Agent token | 200 HTML |
| `GET /api/v1/connector-authorizations/{id}` | Poll an OAuth authorization transaction started by the current user. | OAuth | 200 JSON |
| `GET /api/v1/connectors/{id}/credentials` | List the caller's independent credentials for a connector. | OAuth | 200 JSON |
| `POST /api/v1/connectors/{id}/credentials` | Save a named Header credential and attempt an initial connection test. | OAuth | 201 JSON |
| `GET /api/v1/connectors/{id}/credentials/{credential_id}` | Read a specific credential's metadata and revision ETag. | OAuth | 200 JSON |
| `PATCH /api/v1/connectors/{id}/credentials/{credential_id}` | Rename a credential or replace its complete Header set. | OAuth | 200 JSON |
| `DELETE /api/v1/connectors/{id}/credentials/{credential_id}` | Revoke a credential and invalidate its tool catalog. | OAuth | 204 empty |
| `POST /api/v1/connectors/{id}/credentials/{credential_id}/oauth/authorizations` | Reauthorize one OAuth credential without changing its ID. | OAuth | 200 JSON |
| `POST /api/v1/connectors/{id}/credentials/{credential_id}/test` | Test the upstream connection and discover tools for one credential. | OAuth | 200 JSON |
| `GET /api/v1/connectors/{id}/credentials/{credential_id}/tools` | Discover current tools for one credential. | OAuth | 200 JSON |
| `POST /mcp/connectors/{id}` | Invoke an MCP operation on a connector with no upstream authentication. | MCP key | 200 JSON-RPC; 202 empty |
| `GET /mcp/connectors/{id}` | Reject SSE subscription attempts on this stateless MCP route. | MCP key | 405; no subscription |
| `DELETE /mcp/connectors/{id}` | Reject downstream session-close requests on this stateless MCP route. | MCP key | 405; no session |
| `POST /mcp/connectors/{id}/credentials/{credential_id}` | Invoke an MCP operation using a specific centralized or independent credential. | MCP key | 200 JSON-RPC; 202 empty |
| `GET /mcp/connectors/{id}/credentials/{credential_id}` | Reject SSE subscription attempts on this stateless credential route. | MCP key | 405; no subscription |
| `DELETE /mcp/connectors/{id}/credentials/{credential_id}` | Reject downstream session-close requests on this stateless credential route. | MCP key | 405; no session |
### Knowledge bases, documents, and imports
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/kb` | List accessible knowledge bases and caller-visible review state. | OAuth | 200 JSON; 304 empty |
| `POST /api/v1/kb` | Create a personal knowledge base or submit it for review. Request: JSON or multipart. | OAuth | 201 JSON; 202 JSON |
| `GET /api/v1/kb/tags` | List tags on knowledge bases available to the caller. | OAuth | 200 JSON |
| `POST /api/v1/kb/search` | Search learned chunks in accessible knowledge bases. | OAuth | 200 JSON |
| `POST /api/v1/kb/{id}/images/upload` | Upload a content image without creating or editing a document. Request: multipart. | OAuth | 201 JSON |
| `GET /api/v1/kb/{id}/avatar` | Read an accessible knowledge base's custom avatar. | OAuth | 200 image |
| `GET /api/v1/kb/{id}` | Read an accessible library and the caller's effective permissions. | OAuth | 200 JSON |
| `PUT /api/v1/kb/{id}` | Update the caller's personal library settings or avatar. Request: JSON or multipart. | OAuth | 200 JSON; 202 JSON |
| `DELETE /api/v1/kb/{id}` | Delete a personal library the caller owns. | OAuth | 204 empty |
| `GET /api/v1/kb/permissions/list` | Read the grants on a personal library the caller owns. | OAuth | 200 JSON |
| `PUT /api/v1/kb/permissions/update` | Update a personal library's grants using its revision ETag. | OAuth | 200 JSON; 202 JSON |
| `POST /api/v1/kb/documents/restudy` | Queue accessible writable documents for relearning and report per-document results. | OAuth | 202 JSON |
| `POST /api/v1/kb/{id}/imports/upload` | Upload an original file or retry a prepared import. Request: multipart or JSON. | OAuth | 200 JSON |
| `GET /api/v1/kb/{id}/imports/models` | List image-captioning models available for imports. | OAuth | 200 JSON |
| `POST /api/v1/kb/{id}/imports/query` | Poll the file conversion result for a prepared import. | OAuth | 200 JSON |
| `POST /api/v1/kb/{id}/imports/result` | Check whether a document produced by an import exists. | OAuth | 200 JSON |
| `GET /api/kb/{id}/assets/{name}` | Read a protected knowledge-base image or original file. | OAuth or browser session | 200 binary |
| `GET /api/v1/kb/{id}/documents/{documentId}/file/detail` | Download the original file for a document or request inline PDF preview. | OAuth | 200 binary |
| `GET /api/v1/kb/{id}/documents` | List readable documents, excluding their body content. | OAuth | 200 JSON |
| `POST /api/v1/kb/{id}/documents` | Create a document or folder in a writable library. | OAuth | 202 JSON |
| `POST /api/v1/kb/{id}/documents/delete` | Delete document or folder nodes and report per-ID results. | OAuth | 200 JSON |
| `POST /api/v1/kb/{id}/documents/move` | Move document or folder nodes and report per-ID results. | OAuth | 200 JSON |
| `GET /api/v1/kb/{id}/documents/{documentId}` | Read the detail of an accessible document. | OAuth | 200 JSON |
| `PUT /api/v1/kb/{id}/documents/{documentId}` | Edit a writable document and requeue it for learning when applicable. | OAuth | 202 JSON |
| `POST /mcp/kb/{id}/files/upload` | Upload original bytes to a knowledge base with a scoped upload token or MCP key. Request: multipart. | Upload token or MCP key | 201 JSON |
| `POST /mcp/kb` | Use the built-in knowledge-base tools over MCP. | MCP key | 200 JSON-RPC; 202 empty |
### Invocation keys, image tasks, billing, and feedback
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/api-keys` | List invocation-key metadata without returning key secrets. | OAuth; runtime key policy | 200 JSON |
| `POST /api/v1/api-keys` | Create an invocation key and return its secret once. | OAuth; runtime key policy | 201 JSON |
| `DELETE /api/v1/api-keys/{keyID}` | Revoke an invocation key. | OAuth; runtime key policy | 204 empty |
| `POST /api/v1/api-keys/{keyID}/rotate` | Rotate a key and return the replacement secret once. | OAuth; runtime key policy | 201 JSON |
| `POST /v1/images/inputs` | Upload a reference image for a later generation or edit. Request: multipart. | Model key | 201 JSON |
| `POST /v1/images/generations` | Queue an asynchronous image generation task. | Model key | 202 JSON |
| `POST /v1/images/edits` | Queue an asynchronous image editing task. | Model key | 202 JSON |
| `GET /v1/images/tasks/{id}` | Poll the caller's image task and read its results when available. | Model key | 200 JSON |
| `GET /v1/images/outputs/{id}` | Download an image result owned by the calling key's user. | Model key | 200 image |
| `GET /api/v1/billing/account` | Read the caller's credit account and balances. | OAuth | 200 JSON |
| `GET /api/v1/billing/entries` | Page through the caller's usage charges and refunds. | OAuth | 200 JSON |
| `POST /api/v1/feedback` | Submit feedback with text, screenshots, or both. Request: multipart. | OAuth | 200 JSON; 201 JSON |
### Cloud environments
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/system-images` | List ready system images that administrators have published. | environment:read | 200 JSON |
| `GET /api/v1/environment-specifications` | Read the full list of selectable cloud computer specifications. | environment:read | 200 JSON |
| `GET /api/v1/environment-hosts` | List execution hosts available to the caller. | environment:read | 200 JSON |
| `GET /api/v1/environments` | List the caller's cloud environments. | environment:read | 200 JSON |
| `POST /api/v1/environments` | Queue creation of an environment using a selected specification and version. | environment:manage | 202 JSON |
| `GET /api/v1/environments/{id}` | Read the caller's environment and its current state. | environment:read | 200 JSON |
| `DELETE /api/v1/environments/{id}` | Queue removal of the runtime instance while retaining persistent storage. | environment:manage | 202 JSON |
| `GET /api/v1/environments/{id}/runtime` | Read the environment's runtime version and available upgrade information. | environment:read | 200 JSON |
| `POST /api/v1/environments/{id}/runtime/upgrade` | Queue an in-place runtime upgrade for a stopped environment. | environment:manage | 202 JSON |
| `GET /api/v1/environments/{id}/operations` | List operations on the caller's environment. | environment:read | 200 JSON |
| `POST /api/v1/environments/{id}/stop` | Queue a stop for the selected environment. | environment:manage | 202 JSON |
| `POST /api/v1/environments/{id}/start` | Queue a start for the selected stopped environment. | environment:manage | 202 JSON |
### Sessions, devices, remote relay, and files
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/sessions` | List the caller's cross-device session summaries without message bodies. | session:read | 200 JSON |
| `GET /api/v1/sessions/{id}` | Read the caller's session summary by ID. | session:read | 200 JSON |
| `PUT /api/v1/sessions/{id}` | Create or update a snapshot of session metadata. | session reporting authorization | 200 JSON |
| `POST /api/v1/sessions/{id}/turns` | Append a batch of completed session-turn reports. | session reporting authorization | 200 JSON |
| `GET /api/v1/endpoints` | Read the caller's endpoint directory; the remote directory requires device:connect. | OAuth | 200 JSON |
| `GET /api/v1/endpoint-bridge` | Prove device identity and establish a control or data tunnel. | device:bind; publish also device:publish | 101 WebSocket / binary yamux |
| `POST /api/v1/endpoints/{machine_id}/connections` | Create or renew a scoped connection ticket for a target device. | device:connect + requested scopes | 200 JSON |
| `GET /api/v1/endpoints/{machine_id}/proxy/terminal` | Attach to a terminal through the target's data tunnel. | Runtime ticket + session:control | 101 terminal WebSocket |
| `GET /api/v1/endpoints/{machine_id}/proxy/{path}` | Forward an allowed target WebSocket, MCP stream, or file read. | Runtime ticket | 101 WebSocket; 200 forwarded stream; 206 range |
| `POST /api/v1/endpoints/{machine_id}/proxy/{path}` | Forward an allowed session, resource, interaction, or MCP request. | Runtime ticket | 200 forwarded response |
| `PUT /api/v1/endpoints/{machine_id}/proxy/{path}` | Stream data into an approved target upload slot. | Runtime ticket | 200 forwarded response |
| `HEAD /api/v1/endpoints/{machine_id}/proxy/{path}` | Probe a target file or upload offset without fetching a body. | Runtime ticket | 200 forwarded headers only |
| `DELETE /api/v1/endpoints/{machine_id}/proxy/{path}` | Forward an MCP session-close request to the target. | Runtime ticket | 200 forwarded response |
| `GET /api/v1/endpoints/connect` | Establish a native client's endpoint bridge. | OAuth Bearer only | 101 WebSocket / JSON frames |
| `DELETE /api/v1/endpoints/{machine_id}` | Remove a remote execution registration. | OAuth | 204 empty |
| `PUT /api/v1/endpoints/{machine_id}` | Register or update metadata for one of the caller's devices. | OAuth | 200 JSON |
| `GET /api/v1/endpoints/{machine_id}` | Read one of the caller's registered endpoints. | OAuth | 200 JSON |
| `PATCH /api/v1/endpoints/{machine_id}` | Change a registered endpoint's display alias. | OAuth | 200 JSON |
| `POST /api/v1/endpoints/{machine_id}/revoke` | Revoke an endpoint and disconnect it. | device:manage for verified devices | 200 JSON |
| `POST /api/v1/endpoints/{machine_id}/restore` | Restore a revoked endpoint record without reconnecting it. | OAuth | 200 JSON |
| `GET /preview/{machine_id}/{grant}/{path}` | Serve an artifact in its isolated preview origin. | Signed preview grant | 200 artifact; 206 range |
| `HEAD /preview/{machine_id}/{grant}/{path}` | Inspect headers for an isolated preview asset without its body. | Signed preview grant | 200 headers only |
| `GET /endpoints/{machine_id}/files/{grant}/{path}` | Download a file authorized by an isolated file URL. | Signed file grant | 200 attachment; 206 range |
| `HEAD /endpoints/{machine_id}/files/{grant}/{path}` | Inspect headers for an authorized file without downloading it. | Signed file grant | 200 headers only |
### Design resources
| Method and path | Purpose | Credential | Response |
| --- | --- | --- | --- |
| `GET /api/v1/design-resources/config` | Read the design-resource source configuration. | OAuth | 200 JSON |
| `POST /api/v1/design-resources/token` | Mint a short-lived design credential for a registered device. | OAuth | 200 JSON |
| `GET /api/v1/design-resources/catalog/snapshot` | Read the current or a specified frozen design snapshot. | OAuth | 200 JSON |
| `GET /api/v1/design-resources/catalog/taxonomy` | Read frozen taxonomy, counts, and template associations. | OAuth | 200 JSON |
| `GET /api/v1/design-resources/catalog/{kind}` | List frozen resources of one design kind. | OAuth | 200 JSON |
| `GET /api/v1/design-resources/catalog/{kind}/{id}` | Read a frozen resource of one design kind. | OAuth | 200 JSON |
| `GET /api/v1/design-resources/catalog/templates/{id}/download` | Download a frozen template source ZIP. | OAuth | 200 ZIP; 206 range; 304 |
| `HEAD /api/v1/design-resources/catalog/templates/{id}/download` | Inspect a frozen template ZIP's length and ETag without downloading it. | OAuth | ZIP headers only (HEAD) |
| `GET /api/v1/design-resources/design-systems/{id}/download` | Download a frozen design system source ZIP. | OAuth | 200 ZIP; 206 range; 304 |
| `HEAD /api/v1/design-resources/design-systems/{id}/download` | Inspect a frozen design system ZIP's length and ETag without downloading it. | OAuth | ZIP headers only (HEAD) |
| `GET /api/v1/design-resources/catalog/previews/{id}/{path}` | Read protected design preview media. | Media JWT | 200 media; 206 range; 304 |
| `HEAD /api/v1/design-resources/catalog/previews/{id}/{path}` | Inspect protected design preview media headers without its body. | Media JWT | Media headers only (HEAD) |
| `GET /api/v1/design-resources/catalog/style-assets/{id}/{path}` | Read protected style asset media. | Media JWT | 200 media; 206 range; 304 |
| `HEAD /api/v1/design-resources/catalog/style-assets/{id}/{path}` | Inspect protected style asset media headers without its body. | Media JWT | Media headers only (HEAD) |
## Contract and implementation differences
These findings are from static inspection of the pinned backend. The [Chinese API notes](./README.md), [OpenAPI](./agent.yaml), and handlers describe different revisions of some behaviors. The client guidance above follows the implementation for the differences below; confirm the intended public contract before relying on an undocumented behavior.
| Area | Difference and client guidance |
| --- | --- |
| Resource lists and pagination | The [Chinese resource-read summary](./README.md#agent-资源读取) lists short response shapes. [OpenAPI pagination components](./agent.yaml#L5466) and [the resource list handler](../internal/agentconfig/resources.go#L542) include filter-aware pagination and caller-visible draft data. Use the count and array key of the individual endpoint; do not assume that a successful catalog read is an unpaged list of runnable resources. |
| Share results | The [Chinese sharing example](./README.md#用户模型与分享) describes a successful share/revoke as `204`. [The share contract](./agent.yaml#L2822) and [the handler](../internal/resource/sharing.go#L82) also allow `200` per-target results or a `202` approval receipt on share creation. Only treat an effective grant as access. |
| Expert and connector tool discovery | The [Chinese MCP notes](./README.md#mcp-代理) say expert manifests discover tools live. In this revision, [the manifest handler](../internal/agentconfig/resources.go#L624) sets snapshot mode and [the connector adapter](../internal/mcp/agent.go#L24) separates live discovery from snapshot reads. [OpenAPI](./agent.yaml#L3460) does not explain that manifest distinction and explicitly describes snapshot reads for resolution. Use the REST tools route for explicit live discovery. |
| Connector selection | The [Chinese credential notes](./README.md#connector-多凭证) say multiple usable credentials return `credential_selection_required`. [The resolver](../internal/agentconfig/resources.go#L833) emits it in `issues[]` on HTTP `200` (blocking for a required connector). Do not handle it only as an HTTP error. The connector-level test/tools and gateway routes can instead produce an HTTP error when a credential is required. |
| Knowledge-base search | [The search operation](./agent.yaml#L4833) lists `400` and `401` failures. [The search implementation](../internal/kb/search.go#L12) can also return `404 not_found` for a selected inaccessible library; the 50-library cap is enforced after expanding an empty selection as well. Send explicit readable IDs to bound the search. |
| Knowledge-base asset authentication | [The asset operation](./agent.yaml#L5158) inherits the OAuth-only security declaration, but its description and [router](../internal/app/app.go#L395) also accept browser-session auth when no Authorization header is supplied. An invalid supplied Bearer does not fall back to a cookie. |
| Image reference formats | [The Chinese image notes](./README.md#生图模型网关) include WebP. [OpenAPI for reference uploads](./agent.yaml#L4626) describes PNG/JPEG only, while [the uploader](../internal/imagegen/inputs.go#L48) accepts PNG, JPEG, and WebP. Use PNG or JPEG for the documented common subset pending contract confirmation. |
+62
View File
@@ -0,0 +1,62 @@
# MonkeyAI public website
[中文原文](./README.md)
The public website presents MonkeyAI, client downloads, and the two demo paths. It also serves the blog, legal documents, and the app-link page for device pairing. Astro emits HTML and SEO metadata at build time; React islands add interaction without making the content depend on client-side routing.
## Where to start
| Path | Responsibility |
| --- | --- |
| [src/pages/](./src/pages/) and [src/layouts/](./src/layouts/) | Homepage, localized route entries, blog and legal pages, sitemap, and the shared layout. |
| [src/components/](./src/components/) and [src/styles/](./src/styles/) | Astro sections, interactive React components, and styling. |
| [src/i18n/](./src/i18n/) and [src/blog/](./src/blog/) | Route definitions, dictionaries, legal translations, and localized articles. |
| [src/lib/](./src/lib/), [src/assets/](./src/assets/), and [public/](./public/) | Shared logic, bundled images/fonts, static downloads metadata, and license notices. |
| [tests/](./tests/) and [scripts/](./scripts/) | Node regression tests and the font import script. |
| [astro.config.mjs](./astro.config.mjs), [Dockerfile](./Dockerfile), and [Caddyfile](./Caddyfile) | Static build, image, and serving configuration. |
## Run locally
Use Node **22.12 or later** and npm **9.6.5 or later** (the requirements declared by the locked Astro package); the Docker builder uses Node 26.13.1. Run these commands in `monkeyai/landing`. This module uses npm and [package-lock.json](./package-lock.json) for reproducible builds. A pnpm lockfile exists in this snapshot, but it isn't used by the npm or image build. Don't generate or update pnpm metadata as part of a site change.
```bash
npm ci
npm run dev
```
Astro normally serves on <http://localhost:4321/>; open `/en/` directly for English. The config isolates Vite caches by Astro command in `node_modules/.vite/astro-*` so a check or build won't replace a running dev server's optimized dependencies.
## Build, test, and preview
```bash
npm test # node --test tests/*.test.mjs
npm run check # Astro and TypeScript diagnostics
npm run build # runs check, then writes the static site to dist/
npm run preview # serves the build locally
```
The tests cover locale selection, locale dictionary parity, legal translations, app-link query preservation, platform detection, and release-download URL validation. When translating site copy, run both the tests and the build. Before deploying, set the canonical origin with `SITE_URL` and any mount prefix with `PUBLIC_BASE_PATH`. Set `PUBLIC_GA_ID` to override the GA4 property; an invalid value disables analytics. See [.env.example](./.env.example) for the current defaults. After a deployment-prefix change, inspect the canonical links, sitemap, paths to static assets, and pairing pages in the built output.
## Localization and content
- Ten homepages are generated. The root HTML is Simplified Chinese; on the unprefixed entry the language preference code honors a saved choice, then matches the browser's list, and falls back to English. A direct URL with a language prefix stays in that language. Follow [languages.ts](./src/i18n/languages.ts) for route IDs rather than hard-coding them.
- Update the source copy and corresponding [dictionaries](./src/i18n/locales/) together. Register copy used by React islands in [islands.json](./src/i18n/islands.json) so the page ships only the locale and keys it needs. The three legal pages have reference translations for the nine other locales alongside the Simplified Chinese source. Language switches on the scan page must preserve the pairing query, including duplicate keys and encoding.
- To publish a blog entry, add `src/blog/<slug>/zh-CN.md` with `title` and `summary` in the front matter, optionally `seoTitle`. The directory name determines `/blog/<slug>/` and its sort order. Store translations as locale-named siblings such as `en-US.md`. The build generates localized article pages and sitemap entries; untranslated articles label the Simplified Chinese fallback. See [an existing article](./src/blog/monkeyai-vs-workbuddy/).
- Keep the canonical URL, `hreflang`, robots directives, Open Graph/Twitter metadata, and structured data in sync with route changes. The build emits `/sitemap.xml` and `/robots.txt`.
## Styling and interaction
- Use Astro with React islands and Tailwind CSS v4. [BaseLayout.astro](./src/layouts/BaseLayout.astro) supplies the shared header and footer. Maintain site colors in [site.css](./src/styles/site.css); use semantic type roles from the [typography guide](./TYPOGRAPHY.md) and [typography.css](./src/styles/typography.css). Don't reintroduce Tailwind Preflight or unrelated component font sizes.
- Hydrate only interactive boundaries with `client:load` or `client:visible`. Keep full text and navigation available in the initial HTML; the FAQ retains native `details/summary` before hydration. Preserve keyboard operation, focus restoration, and reduced-motion behavior. The demo dialog distinguishes installed-client access from the web admin console. Use the shared clipboard feedback component and respect the site base path for the downloads jump. Keep a static, readable fallback for shader cards when JavaScript or WebGL2 is unavailable.
- Keep the promotion's content in [promotion.ts](./src/lib/promotion.ts). If changing the sticky banner or header, ensure anchor offsets follow the measured top bar height. Reuse the community QR asset and keep hover, keyboard, touch, and dismiss behavior accessible. For new UI primitives, run `npx shadcn@latest add dialog` from this module and review the generated styles against [components.json](./components.json) and [shadcn.css](./src/styles/shadcn.css). Keep the distinction between buttons and native links; only include the icons used in the build.
- Fonts and license notices are checked in; everyday builds do not download fonts. MiSans uses three local static weights and JetBrains Mono is the local code font. To reimport MiSans, obtain the official archive and run the following with Python 3.11+; the [script](./scripts/sync-fonts.py) checks the archive hash and writes the expected weights, CSS, and metadata. Review source hashes and the license before upgrading. Notices are in [public/licenses/](./public/licenses/).
```bash
npm run fonts:sync -- --archive /path/to/MiSans.zip
```
## Container and deployment files
The [Dockerfile](./Dockerfile) runs the npm build and copies `dist/` into Caddy. **Its `COPY` sources are relative to a build context containing a `homepage/` directory.** They do not match a direct `docker build .` from `monkeyai/landing`; for normal development use the npm workflow above. The [Compose file](./compose.yml) runs a prebuilt image, controlled by `HOMEPAGE_IMAGE` and `IMAGE_TAG`. Its checked-in defaults still use the Jiying hostname and image. Confirm the image, `SITE_ADDRESS`, and canonical build origin with the deployment owner rather than assuming these defaults describe the live MonkeyAI website.
For a deployment that uses this Caddy bundle, preserve the certificate state, configuration, and log mounts under `data/caddy/`. Release files in `data/releases` are mounted read-only, served by explicit path, and not listed. The internal health check reads the built index through Caddy; the public `/healthz` also provides an endpoint for checking DNS and TLS from outside the container. The [systemd files](./systemd/) are for the existing Linux deployment layout (`/data/homepage` and `jiying-homepage`), not for local development. The timer runs a Compose update and the script checks the resulting container's health.
+2
View File
@@ -1,5 +1,7 @@
# 百智办公官网首页
[English](./README.en.md)
## 首页语言
首页为十种语言分别生成静态 HTML。根路径为简体中文;首次打开根路径时按浏览器语言列表匹配,无匹配使用英语。页头的语言菜单会记住手动选择,优先于浏览器偏好。直接打开带语言前缀的链接不会跳转。服务协议、隐私政策和用户协议提供九种语言的完整参考译本,保留简体中文原文。扫码地址保持不变,按同一语言偏好打开本地化页面,并保留配对参数。
+71
View File
@@ -0,0 +1,71 @@
# MonkeyAI admin frontend
[中文原文](./README.md)
This React application is the MonkeyAI admin console. It manages members and groups, AI resources, billing, analytics, registered devices, and cloud environments. It also serves browser pages for client sign-in and authorization. The general web workspace is still a placeholder; it is not a replacement for the installed member client.
## Where to start
| Path | Responsibility |
| --- | --- |
| [src/pages/admin/](./src/pages/admin/) | Admin screens. |
| [src/pages/](./src/pages/) and [src/lib/routes.ts](./src/lib/routes.ts) | Public and client authorization pages, with route metadata for the app. |
| [src/components/](./src/components/) and [src/hooks/](./src/hooks/) | Shared UI, reusable feature components, and hooks. shadcn/ui components live in [src/components/ui/](./src/components/ui/). |
| [src/lib/](./src/lib/) and [src/i18n/](./src/i18n/) | API helpers, browser compatibility, and localization. |
| [test/](./test/) and [scripts/](./scripts/) | Node tests, browser regressions, and the local cloud-environment fixture. |
| [nginx/](./nginx/) and [Dockerfile](./Dockerfile) | Nginx ingress configuration and the production static image. |
## Run locally
Use a Node release supported by the locked dependencies (Node 22.18 is sufficient for a local build; the Docker builder uses Node 26.13.1) and pnpm **10.12.4** as pinned in [package.json](./package.json). Run from `monkeyai/web`. Keep [pnpm-lock.yaml](./pnpm-lock.yaml) and the patch declared in [pnpm-workspace.yaml](./pnpm-workspace.yaml) together.
```bash
pnpm install --frozen-lockfile
MONKEYAI_DEV_BACKEND_URL=http://localhost:8080 MONKEYAI_DEV_API_URL=http://localhost:8080 pnpm dev --force
```
Open <http://localhost:5173/>. For real sign-in, use a [development backend with member writers](../backend/README.en.md#run-locally) and set its `MONKEYAI_PUBLIC_URL` to the browser-visible Vite origin. Set **both** proxy variables explicitly for local work. In [vite.config.ts](./vite.config.ts), `MONKEYAI_DEV_BACKEND_URL` handles `/oauth`, `/mcp` and `/v1`; `MONKEYAI_DEV_API_URL` handles `/api`, device routes and OAuth discovery metadata. The latter defaults to a remote service, not localhost. Restart Vite with `--force` after changing PostCSS or reinstalling patched dependencies so it doesn't reuse an old prebundle.
To work on cloud-environment screens without a backend, build the UI and start the local fixture:
```bash
pnpm build
pnpm dev:environments
```
Open <http://127.0.0.1:4187/admin/environments/instances>. The [fixture](./scripts/environment-fixture.mjs) binds to loopback, accepts a `PORT` override, and uses disposable in-memory data. `/__fixture` is test-only. A running container in the UI is not proof that its runtime is connected; see the [environment control guide](../design/environment-control.md) for state meanings.
## Build and test
```bash
pnpm build # tsc -b, then Vite; writes dist/
pnpm preview # serves the build locally, not a complete backend
pnpm test # Node test runner over test/*.test.mjs
pnpm lint # ESLint
```
The [Vite build](./vite.config.ts) targets Chrome 86 for JavaScript and CSS. Browser tests use `playwright-core` and a real Chrome/Chromium binary, not a spoofed User-Agent. Build first, then run the suite with each browser you need to support:
```bash
CHROME_BIN=/path/to/chrome86 pnpm test:browser
CHROME_BIN=/path/to/current-chrome pnpm test:browser
```
The default harness serves the built app with simulated API responses. Only use `ADMIN_DEV_URL` with an isolated development server and test data: the base harness then lets unmatched requests reach that server. The [test scripts](./package.json) also expose focused regressions; set `CHROME_BIN` for each of these:
| Script | Coverage |
| --- | --- |
| `test:browser:members`, `test:browser:quotas` | Virtualized member and quota lists, measured rows, selection, focus, and large fixtures. |
| `test:browser:task-analysis` | Session/model metrics, responsive layouts, loading/empty states, and retry. |
| `test:browser:billing-users`, `test:browser:account-links` | Billing user selection and account links that carry the selected user. |
| `test:browser:table-query` | Bookmarks, filters, pagination, and history navigation (use `SCENARIO_FILTER=task:390` for that case only). |
| `test:browser:client-devices`, `test:browser:auth` | Registration inventory and client authorization. |
## Contributor notes
- **Chrome 86:** Keep Tailwind CSS on 3.4 and selectors compatible with [PostCSS](./postcss.config.cjs). Do not introduce cascade layers, OKLCH, or other unsupported CSS into shared styles. [browser-compat.ts](./src/lib/browser-compat.ts) and [platform-compat.ts](./src/lib/platform-compat.ts) preserve native behavior where available. Keep ResizeObserver breakpoints and fallback aspect ratios where required. Recheck the versioned Base UI click-event patch when upgrading; use both old and current Chromium. ZIP remains a fallback for large imports on browsers that cannot stage files to disk. Clipboard access still follows browser permissions and secure-context rules.
- **Components:** From this directory, `npx shadcn@latest add button` is the generator entry point. Review the output before applying it: current templates may use Tailwind 4 syntax. Import the local button as `@/components/ui/button`. [GroupSelect](./src/components/group-select.tsx) is controlled and does not fetch data or grant access. Supply group/user options, localized labels, and a controlled `{ groupIds, userIds }` value; reset it when changing selection modes. Searching uses names, optional emails, and pinyin without changing the saved expansion state. Cascaded grants are computed against the complete tree, not just visible results.
- **Virtual lists:** The group tree and measured member cards keep expansion and selection outside mounted rows. Preserve source keys for users who appear in several groups and keep focused, menu, and drag rows mounted while active. Virtualization reduces mounted elements, not the records fetched. Quota cards retain search and sorting when account details close.
- **Analytics:** Session metrics and the model overview each come from a server snapshot, not generated sample data. Preserve the distinction between zero counts, missing duration/percentile data, loading, and errors. Trend buckets use Beijing time; overflow segments are grouped as “Other.”
- **Filters and CSV:** Persist submitted filters and pagination to the URL; leave unsubmitted input in the form. User-picker results use exact IDs; preserve the handling of older text-query links. CSV exports reuse the active filters without changing the page and cap a request at 5,000 rows, with a UTF-8 BOM.
- **Device registration and client authorization:** A device row represents `(user_id, machine_id)`, not an online session or version history. Preserve the distinction between OS and OS version, list/chart filter parity, and separate chart retries. `/client-login` requires an explicit confirmation even with no additional scopes; keep `approved_scopes` and `X-CSRF-Token` on confirmation and validate the final redirect against the approved destination.
+2
View File
@@ -1,5 +1,7 @@
# React + TypeScript + Vite + shadcn/ui
[English](./README.en.md)
MonkeyAI Web 前端包含管理端和客户端页面,使用 React、TypeScript、Vite 和 Tailwind CSS 3.4。降级前的完整回退基线为提交 `5789bb73`。
## Chrome 86 兼容