# Stand public API and CLI

This reference keeps `--json` explicit for agents and automation. For a readable walkthrough, use the [Stand CLI guide](https://stand.chat/guide/cli) or [Public API guide](https://stand.chat/guide/account-api). Human terminal examples there omit `--json` unless structured output is needed.

Use this guide for authorized ongoing management of Stand Chat. For a new installation, the complete user prompt is **“Add stand.chat”**; follow the [agent setup recipe](https://stand.chat/guide/ai-setup.md). Signup, consent and initial profile/organization onboarding remain human browser steps.

The [OpenAPI contract](https://stand.chat/api/v1/openapi.json) and [API reference](https://stand.chat/api/v1/reference.html) describe all 109 public operations. The CLI calls those existing backend operations. Public scopes do not bypass resource ownership, organization roles, plan allowances or active-account checks.

## Install and authorize

Use Node.js 22+ on macOS, Linux or WSL. Native Windows is unsupported. Install the official `@standchat/cli` package from npm’s `latest` tag, record `stand --version`, then read `stand commands --json`. If the official package is unavailable, report that distribution is unavailable; do not substitute another package.

For initial installation:

```sh
npm install --global @standchat/cli
stand auth login --setup --json
stand setup status --json
```

Keep the login process running while the human opens its trusted verification URL, signs up or signs in and consents. After approval, the browser shows **Stand CLI authorized** and can be closed. Wait for the CLI to confirm that credentials were stored, then check `stand setup status --json`. The human completes any initial profile form at the returned onboarding URL using the same account. The CLI cannot create that initial profile or organization. Existing profiles can be edited after onboarding with `profile:write`.

Setup requests eight business scopes: `profile:read`, `org:read`, `sites:read`, `sites:write`, `standins:read`, `standins:write`, `knowledge:read` and `knowledge:write`. Request additional permissions only when the user authorizes the corresponding work. For example, profile management needs:

```sh
stand auth login --scopes 'profile:read profile:write' --json
```

Use one named CLI profile consistently. Credentials stay in the CLI store outside websites and repositories. If a secure vault is unavailable, select `--credential-store file` explicitly to use a private local file. Never request pasted tokens, browser cookies or passwords. Access tokens last five minutes; proof-bound refresh remains within existing session limits. Revocation or expiry requires a new human authorization. Logout revokes refresh access before removing saved credentials; check the result, because revocation failure can leave credentials locally. Use `--local-only` only for intentional local removal without revocation.

## Permissions and capabilities

| Scope | Available operations, subject to existing permissions |
| --- | --- |
| `profile:read`, `profile:write` | Existing profile, greetings, avatar and personal lapel-pin branding. Organization renaming also requires `org:write`. |
| `sites:read`, `sites:write` | Site creation, reads, updates and deletion; routing matches; personal Site preferences; Site prompts and prompt history. |
| `org:read`, `org:write` | Organization prompts, privacy and lapel-pin branding; plan and usage reads. Owner-only operations remain owner-only. |
| `sessions:read`, `sessions:write` | Authorized active/archived conversations, messages, seen/close, takeover, handoff offers and history export. Access follows existing conversation assignment and organization-owner rules. |
| `team:read` | Team list and invite-provider default. No invitations, removals or role changes. |
| `digest:read`, `digest:write` | Personal digest and AI-digest preferences, and sending a digest within applicable permissions. |
| `standins:read`, `standins:write` | Owned Stand-in creation, reading, updating, cloning and deletion; enablement, skills, avatar generation/upload/selection and branding. |
| `knowledge:read`, `knowledge:write` | Knowledge bases, connected Stand-ins, uploads, website crawls, sitemaps, sources, documents, chunks, search, indexing tasks and Stand-in attachments. |
| `integrations:read`, `integrations:write` | Owned integration definitions, OpenAPI preview and Stand-in integration attachments. |
| `analytics:read` | Permitted statistics and Live Shows. |
| `feedback:write` | Feedback submission. |

Not every operation in a family needs both scopes. Read the operation's schema and permission before requesting consent. Uploads, sitemaps, limits and other paid features retain their existing plan checks. A scope does not upgrade the account's plan.

The API does not expose account deletion, subscription/payment management, team-member mutations, initial onboarding, MCP, WordPress or Site-connection credentials. Representative WebSockets remain unavailable to CLI credentials. CLI reads do not refresh human presence; explicit personal Site-preference changes are supported.

## JavaScript experimentation consent

The owner must first enable JavaScript experimentation under **Sites → Chat widget behavior → Experimentation (Advanced)** in the browser. Stand-admin behavior access is a separate browser opt-in. A public API client cannot enable or restore either permission, including within a Site creation or mixed update. Owner requests that try this fail with `EXPERIMENTATION_CONSENT_REQUIRED` before the Site's other requested changes are saved. Other callers remain subject to the existing ownership checks.

Once the owner has enabled experimentation, an authorized `sites:write` client can edit experiments. Read the current Site first and preserve unrelated fields. The owner's browser opt-in is not blanket authorization for an agent to change a live website; perform only the requested experiment. Basic widget installation does not require JavaScript experimentation.

## Discover commands and schemas

```sh
stand commands --json
stand schema updateSite --json
stand schema updateRepProfile --json
stand sites list --json
stand sites get SITE_ID --json
stand profile get --json
```

Named commands cover common workflows. In `stand commands --json`, every `commands[]` entry has a boolean `confirmation`: `false` for API reads and `true` for mutations. The generic `stand api` command reaches every published operation, using the same contract, scope and ownership checks. An unpublished backend route cannot be accessed through this command.

Read the schema before constructing a request. Supply JSON through a file, use `--json` for machine-readable output and `--yes` for an already approved mutation. `--yes` skips the CLI prompt; it does not grant permission to exceed the user's request.

```sh
stand sites update SITE_ID --body-file site.json --yes --json
stand standins update STANDIN_ID --body-file standin.json --yes --json
stand api GET /v1/reps/profile --json
stand api PUT /v1/sites/SITE_ID --body-file site.json --yes --json
```

Site updates change supplied settings, but legacy `embedOptions` replaces behavior rules and resets experimentation consent. Prefer the complete current `behaviorConfig` when preserving behavior. Stand-in saves are not partial PATCH requests: construct the complete writable body from its schema and existing values. A save may return a replacement Stand-in version to preserve chat history; use the returned `standinProfileId` for later calls.

For queries, use repeated `--query-param key=value` options with the parameter names from the schema. Do not embed tokens or sensitive data in URLs. Successful JSON goes to stdout; errors and diagnostics go to stderr. Inspect the exit status as well as the response: API HTTP 404 errors exit with code 3, HTTP 401/403 with code 4, and other API HTTP errors with code 1. This also applies to history export. Transport and response-validation failures keep their own exit codes; malformed JSON returns exit code 5.

## Knowledge management

Knowledge reads require `knowledge:read`; mutations require `knowledge:write` and ownership of the knowledge base. Named base deletion also requires `knowledge:read` to inspect affected Stand-ins before confirmation. Organization members can inspect shared bases, but a scope does not let them change another member's sources. Setup login already includes both scopes. Search is a read operation even though its API method is POST.

Start with `stand knowledge list --json`. Check `ownedByCurrentRep` on the intended base and the returned `capabilities`, `usage`, `limitsReached`, `ingestionAllowed`, `ingestionUnavailableReason` and `graceReadOnly`. New ingestion must be allowed and outside grace read-only state. `capabilities.documentUploadAllowed` permits supported document uploads; `sitemapAllowed` permits sitemap sources; `automaticRefreshAllowed` permits enabling nightly sitemap updates. The backend still checks capacity and worker availability. Follow these returned values rather than assuming a plan from its name; [Pricing](https://stand.chat/pricing) owns current plan allowances. Base supports website crawling and approved Stand-in instructions without document uploads or sitemaps.

Create a base with `stand knowledge create --body-file knowledge.json --yes --json`, where `knowledge.json` contains `{"name":"Approved support material","description":"Visitor-facing support facts"}`. Rename or describe an owned base with `stand knowledge update KNOWLEDGE_BASE_ID --body-file knowledge.json --yes --json`; supply both fields, because this replaces the name and description.

### Upload an approved local document

```sh
stand knowledge upload KNOWLEDGE_BASE_ID \
  --file /absolute/path/approved-document.pdf --yes --json
stand knowledge tasks KNOWLEDGE_BASE_ID --json
stand knowledge documents KNOWLEDGE_BASE_ID --json
stand knowledge documents get DOCUMENT_ID --json
stand knowledge documents chunks DOCUMENT_ID --json
stand knowledge documents search DOCUMENT_ID --query 'approved support policy' --top-k 5 --json
stand knowledge search KNOWLEDGE_BASE_ID --query 'approved support policy' --top-k 5 --json
```

Supported formats are PDF (`.pdf`), Word DOCX (`.docx`), Markdown (`.md`, `.markdown`) and plain text (`.txt`). Files must be nonempty and at most 10 MiB. Legacy `.doc` and image-only scans need conversion or text extraction first. Indexed-content allowance counts extracted text, separately from the upload-size limit.

The document can stay off the public website. Upload only content specifically approved for transfer to Stand and suitable for the chat audience: replies can quote or paraphrase it. File access is not permission to upload private project files or secrets. Ordinary document/chunk/search responses contain source text; handle them as private content. Metadata-only inspection is described below.

`documents get` reads extracted document text; `documents chunks` reads its indexed sections. Document search is limited to one document; `knowledge search` searches the base. Both accept `--top-k` from 1 to 20, defaulting to 5, may return fewer results, and need no mutation confirmation. They use the same ranking method over different scopes. A result's `score` is a relative relevance signal, can exceed 1, and is not a confidence percentage or probability. Do not compare scores across queries or scopes or use a universal cutoff. Preserve the returned order and inspect the matched text; raw-score sorting can undo the search's selection of distinct, useful passages.

Retain the returned task and source IDs. An accepted upload queues ingestion; poll the intended task and inspect its indexed documents before reporting success. Attach the base to the intended Stand-in and verify an answer from its approved content. Uploading alone neither attaches the base nor verifies an answer.

### Revise an uploaded source

```sh
stand knowledge sources KNOWLEDGE_BASE_ID --json
stand knowledge upload KNOWLEDGE_BASE_ID --source UPLOAD_SOURCE_ID \
  --file /absolute/path/approved-revision.pdf --yes --json
```

`--source` replaces an existing uploaded source in that same knowledge base. It cannot target a website or sitemap source, and a source already indexing returns a conflict. Prior successful content remains active until the replacement succeeds; failure or cancellation preserves that content. Inspect the completed replacement before claiming that the source is current. A replacement with existing completed content can proceed at a new-ingestion capacity boundary, but must still fit the resulting allowance and cannot bypass upload entitlement or grace read-only restrictions.

Without `--source`, every upload creates a new source, even with the same filename. Both sources can consume allowance and contribute to answers until the old source is deleted. The dashboard has no in-place document Replace control; its workflow is upload, inspect and delete the outdated source. Keep original files outside Stand if they may be needed again.

### Website and sitemap sources

```sh
stand knowledge crawl KNOWLEDGE_BASE_ID --body-file crawl.json --yes --json
stand knowledge sitemap KNOWLEDGE_BASE_ID --body-file sitemap.json --yes --json
stand knowledge sources recrawl SOURCE_ID --yes --json
stand knowledge sources refresh SITEMAP_SOURCE_ID --enabled true --yes --json
```

A minimal `crawl.json` is `{"domain":"example.com","urlPrefix":"https://example.com/docs/","maxDepth":0}`. Crawls stay within the starting host and path subtree; depth is 0–10. A minimal `sitemap.json` is `{"sitemapUrl":"https://example.com/sitemap.xml","dailyRefreshEnabled":false}`. Only enable daily refresh when `automaticRefreshAllowed` is true and the user requests it. Crawl and sitemap page guardrails are returned by `knowledge list`; they do not increase plan allowances.

`sources recrawl` manually refreshes a website or re-ingests a sitemap, retaining the prior successful content until replacement succeeds. `sources refresh` changes only a sitemap's nightly-refresh setting; it does not queue an immediate full refresh. Set `--enabled false` to stop future automatic refreshes without deleting content. Nightly updates need usable page-level `lastmod` dates and do not remove pages missing from the latest sitemap; a full manual re-ingest reconciles the listed pages. See the [refresh reference](https://stand.chat/features/knowledge-source-refreshes) for failure and date handling.

### Inspect, cancel and delete

```sh
stand knowledge agents KNOWLEDGE_BASE_ID --json
stand knowledge tasks KNOWLEDGE_BASE_ID --json
stand knowledge tasks cancel TASK_ID --yes --json
stand knowledge documents delete DOCUMENT_ID --yes --json
stand knowledge sources delete SOURCE_ID --yes --json
stand knowledge delete KNOWLEDGE_BASE_ID --yes --json
```

These are separate operations, not a cleanup recipe. Inspect the intended IDs and get approval for the specific destructive action before using `--yes`. It suppresses a prompt; it does not authorize deletion or detachment. Cancellation stops unfinished ingestion; a terminal task returns its existing state. Deleting a document removes that document's indexed text; deleting a source removes its derived content and cancels that source's open tasks. Deletion affects future retrieval, not messages already sent.

Before deleting a base, inspect `knowledge agents` and the connected Stand-ins shown in the CLI deletion preview. A base still attached to Stand-ins is refused unless `--force-detach` is explicitly supplied. Use `stand knowledge delete KNOWLEDGE_BASE_ID --force-detach --yes --json` only after approval to remove the base from all connected Stand-ins, including other members' Stand-ins. The preview is a snapshot, not a conditional revision check: connections added after it can also be removed. Coordinate attachment changes before deletion. This deletes the base and its content and cancels its unfinished tasks. If the affected attachments change or the outcome is uncertain, inspect again rather than repeating the mutation blindly.

For other multipart operations, the generic API command uses the contract's field names, for example `--form-file file=/absolute/path/approved-document.pdf`. Multipart file arguments cannot be combined with `--body-file`. The CLI limits combined file and text content to 11 MiB; the server limits the entire encoded multipart request, including headers and boundaries, to 12 MiB. Per-file limits still apply, including 10 MiB for knowledge documents.

## History export

History export streams to a new private file and validates the complete response before publishing the file. It refuses to overwrite an existing destination:

```sh
stand history export --scope myself --output /absolute/path/history.json --json
```

Filters include `--query`, `--scope myself|org`, `--site`, `--type all|rep|agent`, `--contact all|email|phone|any`, `--label`, `--closed-from`, `--closed-to`, `--sort-by closedAt|createdAt|page|messageCount` and `--sort-dir asc|desc`. Organization history requires the appropriate existing role. The default export timeout is 600 seconds and the default byte limit is 100 MiB; `--timeout SECONDS` and `--max-bytes BYTES` can raise these limits to at most 3,600 seconds and 1 GiB. Treat downloaded conversations as private user data, and do not commit them to a website repository.

## Bounded knowledge inspection

Knowledge source, document and task lists support `view=inspection` with `limit` from 1 to 50 and the opaque `after` cursor. This returns bounded metadata, not document text or raw ingestion errors. Use a returned `nextCursor` only with the same knowledge base and filters. For example:

```sh
stand api GET /v1/knowledge-bases/KNOWLEDGE_BASE_ID/documents \
  --query-param view=inspection --query-param limit=20 --json
```

Check `hasMore`, `nextCursor` and `complete`; one page is not the entire base when more results remain. Counts describe the current observation, not a snapshot across multiple requests. Ordinary list representations remain available. Inspect the operation schema for supported task/source filters.

## Safe changes, interruptions and verification

Inspect existing resources and their IDs before creating or editing anything. Names alone are not unique identifiers. Read before replacing knowledge or integration attachment lists, greetings or other collections, and preserve intended existing entries. There is no conditional revision or general idempotency guarantee. Coordinate concurrent edits to shared configuration.

The CLI does not blindly retry mutations. If a request times out or its outcome is uncertain, inspect the resulting resource before deciding whether another write is safe. Retain known resource IDs and task IDs so a resumed agent can reconcile progress. If the outcome remains ambiguous, stop and report it.

Enabling an owner's Stand-in master switch affects that owner's other enabled Stand-ins. Deleting a Site, Stand-in, knowledge source or integration is supported but still requires the user's authorization and inspection of the consequences. Integration tools can call external services; creating or attaching one requires authorization for that behavior and appropriate handling of its credentials.

A configured Site is not a verified installation. Follow the [setup recipe](https://stand.chat/guide/ai-setup.md): install the returned public snippet, deploy through the website's authorized process and verify a real visitor message and answer in a real browser on the intended hostname. Report missing distribution, deployment or verification as incomplete.
