# ZergBox CLI and token API

The first-party CLI manages workspace storage through HTTP. It does not require
a source checkout, server installation, database connection or desktop app.

The CLI manages files in the selected server and workspace.
See [CLI installation](../cli/README.md) for the standalone package.

## Use the included CLI

Install ZergBox from https://zergbox.com/downloads and sign in with Zerg when
it opens. The app includes its file browser, background sync, Node.js runtime
and the `zergbox` CLI. This one connection registers your computer and makes
your workspace cloud boxes available to the app and CLI.

From `zapps/zergbox`:

On macOS, open the DMG, drag **ZergBox Desktop** to **Applications**, eject the
disk image and open the installed app. Complete Zerg sign-in and browser
approval; setup finishes in the app. Public universal Mac releases support
Apple silicon and Intel on macOS 11+, are Developer ID signed and Apple
notarized. Check per-platform availability on the downloads page for Windows.

The app installs a launcher in `~/.local/bin` and configures the login-shell
path. Open a new terminal if your shell was already open during installation:

```sh
zergbox --version
zergbox whoami --json
zergbox orgs --json
zergbox box ls --json
```

The default CLI configuration reuses the app's private SSO connection and follows
app credential rotation. It saves remote navigation without copying the app's
credential. Do not read, export or duplicate app tokens to configure the CLI.
`zergbox logout` stops CLI reuse without disconnecting the desktop app;
`zergbox login --desktop` explicitly restores it for the default CLI state.
An explicitly selected headless state file remains independent.

ZergBox app updates deliver the file browser, sync service and bundled CLI
together. Verified updates install on the last window close or normal app quit;
a busy sync service finishes its protected work before runtime activation.
See https://zergbox.com/agents.md#macos-app-installation for the app setup guide.

## Install and update a standalone headless CLI

A server or agent host without the app can install the first-party HTTP CLI
independently. Requires Node.js 22+ and npm with registry access. This example
pins the published standalone release:

```sh
npm install --global @zergai/zergbox@0.3.0
zergbox --version

```bash
npm link ./cli
zergbox help
```

Use `npm install --global --prefix "$HOME/.local" @zergai/zergbox@0.3.0` if the
system prefix is not writable, then add `$HOME/.local/bin` to `PATH`.

For this standalone npm installation, `zergbox update --check` reports an npm
update; `zergbox update` installs it on supported macOS/Linux global npm
installations. On Windows, upgrade with npm. The installed channel is preserved,
or select `--channel dev|next|latest`. Startup checks notify on interactive
stderr and never install automatically. Set `ZERGAI_NO_UPDATE_CHECK=1` to
suppress them. Linked, npx and other package-manager installs should update
through their original manager. The app-bundled CLI updates with ZergBox,
rather than through the standalone npm updater.

For development from a checkout, use `npm run cli -- help` or
`node cli/zergbox.js help`. The standalone npm wrapper supplies `update`.

## API token provisioning

The app-bundled CLI needs no separately issued token. For independent headless
work, have a workspace owner
or admin sign in at https://zergbox.com and issue a named, expiring service API
token for the intended workspace. General agent-token issuance currently uses
the session-only API; Settings provides desktop setup rather than a general
agent-token creation form.

An authenticated **same-origin browser request**, using that person's existing
session, sends `POST /api/auth/tokens` with this JSON body:

```json
{
  "name": "storage-agent",
  "organizationId": "WORKSPACE_UUID",
  "tokenType": "service",
  "expiresInHours": 24
}
```

Use a workspace UUID returned by `GET /api/orgs`, not its display name or slug.
The response contains the raw credential in `token` and metadata in `api_token`,
including its ID and prefix. Store the credential privately when issued; do not
put the response in chat, logs or a repository. Do not extract the session cookie
to bootstrap an agent.

Token-management endpoints all require session authentication:

```bash
export ZERGBOX_BASE_URL=http://localhost:3000
export ZERGBOX_STATE_FILE=/tmp/zergbox-state.json
```

Replace example names and IDs with your own values.
Token login reads the token from standard input.

## Core Commands

```bash
zergbox login --email you@example.com
zergbox login --base-url http://localhost:3000 --token-stdin
zergbox whoami
zergbox token create "agent-token" --service --expires-hours 24
zergbox token ls

| Method and path | Behavior |
| --- | --- |
| `GET /api/auth/tokens` | List the signed-in user's token metadata, without raw credentials |
| `POST /api/auth/tokens` | Issue a token; an owner/admin must authorize a workspace binding |
| `DELETE /api/auth/tokens/TOKEN_ID` | Revoke the signed-in user's token |

Service tokens require `organizationId`. `expiresInHours` is optional in the
API; explicitly set it for agent credentials. Personal tokens also exist and
can be unbound, so avoid them when one workspace is sufficient. Tokens have a
workspace binding and type, not selectable read/write scopes. Membership and
role still apply on requests. Service tokens can change content and publish
shares; workspace administration is restricted. Bearer credentials cannot list,
issue or revoke API tokens, even when their owner is an administrator.

Web and desktop sign-in use Zerg SSO. Headless provisioning also starts from
an authorized SSO session; no local ZergBox password is needed.

## Authenticate a headless CLI

Have the user deliver the token through a secret manager or private plain-text
file. Read it through stdin instead of a literal command argument:

```sh
export ZERGBOX_STATE_FILE=/private/path/zergbox-state.json
zergbox login --base-url https://zergbox.com --token-stdin < /private/path/token
zergbox whoami --json
zergbox orgs --json
zergbox use WORKSPACE_SLUG

zergbox search notes
zergbox storage
zergbox trash ls
zergbox trash restore file FILE_ID
zergbox trash empty

zergbox share create /client-dropbox/specs/todo.txt
zergbox share create /client-dropbox --allow-upload
zergbox share inspect "http://localhost:3000/share/SHARE_TOKEN"
zergbox share put "http://localhost:3000/share/SHARE_TOKEN" ./drop.txt inbound/
zergbox share ls
zergbox share rm SHARE_ID
```

`login` validates the token, saves the server and selects the first accessible
workspace/root folder. Select the intended workspace explicitly afterward.
Keep `--base-url https://zergbox.com` explicit in reproducible headless commands;
older standalone releases used a development default. The bundled CLI defaults
to production.

State selection is `--state-file PATH`, then `ZERGBOX_STATE_FILE`, then
`~/.config/zergbox-cli/state.json`. Storage commands accept `--state-file`; an
environment variable is convenient for a series of headless commands. Explicit
state selection disables automatic desktop inheritance. A headless state file
includes credentials and the remote directory and is written with mode 0600.
Keep separate state files for different servers/accounts. `ZERGBOX_BASE_URL`
sets the default for a new login; an existing saved login retains its server
unless an explicit `--base-url` replaces it.

For a headless login, `logout` removes local credentials. It does not revoke the
bearer token; revoke it from an authenticated session when it must stop working.
For the default app connection, logout disables CLI inheritance while leaving
the app signed in; `login --desktop` restores that explicit choice.

## Workspaces, boxes and paths

A workspace is the tenant boundary. `use` accepts a workspace slug or UUID.
A box is a top-level folder in its root. Names are remote path components;
files and folders also have stable UUIDs for API operations.

```sh
zergbox orgs --json
zergbox use WORKSPACE_SLUG
zergbox storage --json
zergbox box ls --json
zergbox box create project-files
zergbox box use project-files
zergbox pwd --json
zergbox cd /project-files
zergbox ls /project-files --long --json
zergbox tree /project-files
```

Remote paths starting with `/` are workspace absolute. Other remote paths are
relative to the directory saved by `cd`. `box use` also selects a remote folder.

Workspace lifecycle commands are `workspace create NAME --slug SLUG` and
`workspace rm SLUG_OR_ID --force`. Removing a workspace requires the relevant
authorization; personal workspaces cannot be removed through that command.
`box rm NAME_OR_ID --force` removes the selected top-level folder.

## Files and recovery

```sh
zergbox mkdir -p /project-files/specs/api
zergbox touch /project-files/specs/todo.txt --content "ship cli"
zergbox put ./notes.md /project-files/specs/notes.md
zergbox get /project-files/specs/notes.md ./downloads/
zergbox cat /project-files/specs/todo.txt
zergbox mv /project-files/specs/notes.md /project-files/specs/renamed.md
zergbox search notes --json
```

`touch` handles text content and also accepts `--stdin`. `put` uploads arbitrary
files. `get REMOTE -` writes downloaded bytes to stdout. `cat` refuses binary
content on an interactive terminal unless `--force` is supplied.

```sh
zergbox versions /project-files/specs/todo.txt --json
zergbox get-version /project-files/specs/todo.txt 1 ./downloads/
zergbox restore-version /project-files/specs/todo.txt 1 --json
zergbox rm /project-files/specs/todo.txt
zergbox rm /project-files/specs --recursive
zergbox trash ls --json
zergbox trash restore file FILE_ID
zergbox trash restore folder FOLDER_ID
```

Version restoration creates a new current version from historical bytes.
Ordinary `rm` moves content to trash; a folder requires `--recursive`.
`trash empty` permanently removes authorized trash metadata and queues stored
objects for deletion. Failed byte cleanup can complete later. Run it only for
an authorized permanent deletion.

## Shares and public dropboxes

Share creation exposes content outside workspace membership. Obtain the user's
publication authorization and treat each share URL as a credential.

```sh
zergbox share create /project-files/specs/todo.txt --expires-hours 24 --max-downloads 5 --json
zergbox mkdir -p /project-files/inbound
zergbox share create /project-files/inbound --allow-upload --expires-hours 24 --json
zergbox box share project-files --expires-hours 24 --json
zergbox share inspect SHARE_URL --json
zergbox share inspect SHARE_URL --path inbound --json
zergbox share put SHARE_URL ./delivery.zip
zergbox share ls --json
zergbox share rm SHARE_ID
```

`--allow-upload` requires a folder share. Public `share inspect` and `share put`
do not require an account login. They accept either a share URL or token;
prefer a full URL to identify the intended server. `share put` accepts an
optional remote destination after the local path.

Password input support differs across published CLI versions. Check the
installed help before password-protected automation; keep passwords out of
URLs, command history and literal arguments. HTTP clients send share passwords
in a JSON/form request body, never query parameters. Repeated incorrect passwords
can cause a 429 response; respect `Retry-After` instead of looping.

## Live reads from your other computers

The installed runtime supports owner-scoped peer reads from explicitly enabled
enrolled roots. The default ZergBox folder is hosted read-only automatically;
additional folders need opt-in on the source computer. Both Macs need updated
apps and active runtimes. Cloud copies remain separately accessible offline.

Discover devices with `GET /api/devices?orgId=WORKSPACE_UUID`. Each active
folder's optional `live` metadata is `{ rootId, online, access: "read", epoch }`;
`null` means no enabled live root. Read roots through
`GET /api/devices/DEVICE_UUID/peer-roots?orgId=WORKSPACE_UUID`.

Submit `POST /api/devices/DEVICE_UUID/peer-roots/ROOT_UUID/operations` with:

```json
{
  "orgId": "WORKSPACE_UUID",
  "operation": { "id": "NEW_OPERATION_UUID", "kind": "list", "path": "", "limit": 100, "offset": 0 }
}
```

Poll the returned `operationId` using `GET` on the same operations path plus
`/OPERATION_UUID?orgId=WORKSPACE_UUID`. Status is `queued`, `leased`, `complete`,
`error`, `expired` or `consumed`; completed responses include `result`. Reuse the
same operation ID after a lost response; do not change its payload. After
consuming a result, `DELETE` that status URL to release its temporary bytes.
Results expire after two minutes, so promptly consume or retry an expired read
with a fresh ID. Bounded queues count completed unconsumed results too.

Only `list`, `stat`, `search`, `read` and `read_range` are supported. Binary
`read_range` takes a relative `path`, nonnegative `offset`, `length` from 1 to
524288, and optional `expectedVersion`; its result includes `contentBase64`,
`contentSha256`, `version`, `sizeBytes`, `offset` and `eof`. Verify all metadata
and SHA-256, pin every range to one version and check final stat before using
assembled bytes. Paths cannot escape their enrolled root. This API checks exact
device ownership and current workspace membership; it is unavailable through
public shares, managed-box capabilities or another member's device. It does
not mutate files or grant a whole-computer mount.

## HTTP data access and failures

Ordinary API tokens authenticate as `Authorization: Bearer TOKEN`. Discover the
accessible workspaces with `GET /api/orgs`, then use their UUIDs. Useful read
routes include `GET /api/auth/me`, `GET /api/folders/root?orgId=WORKSPACE_UUID`,
`GET /api/folders/tree?orgId=WORKSPACE_UUID`, `GET /api/files/FILE_ID`,
`GET /api/files/FILE_ID/versions` and `GET /api/files/FILE_ID/download`.
The CLI handles normal file/folder and share request bodies.

Managed-application `zbc_` exact-box capabilities follow a separate restricted
API contract. They cannot perform normal CLI login, workspace discovery, token
administration or public sharing.

Commands support `--json` where listed by `help`; do not assume all output is
JSON. API/network failures write to stderr and return a nonzero exit code.
HTTP requests time out after 30 seconds and mutations are not automatically
retried. After an ambiguous failure, inspect remote state before retrying a
write. Use a disposable workspace for destructive verification and the app's
feedback capture interface for product issues.
