> For AI agents: the complete documentation index is available at https://docs.heys.ai/workstation/en/llms.txt, the full documentation bundle is available at https://docs.heys.ai/workstation/en/llms-full.txt.

# Command Line and API

Besides the graphical interface, HeyS can be operated with the `heys` command line, or called by other systems over HTTP. This page is for administrators and developers doing system integration.

## First: where the command line and the API are \{#first-where-the-command-line-and-the-api-are}

| What you use                                   | Command line?                                                                         | External API?                                                                             |
| ---------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| **Desktop app**                                | No. The desktop app is a graphical application and doesn't include the `heys` command | The embedded service only accepts HeyS's own interface and is not open to outside callers |
| **Server deployment** (Docker, server package) | Yes, `heys` ships with it, for use on the server                                      | Yes; the web app uses this same API                                                       |
| **HeyS command-line package**                  | A standalone `heys` executable (macOS arm64, Linux x64 / arm64)                       | You can start a service yourself with `heys server`                                       |

:::note Note
If a task on the desktop asks the agent to run a `heys …` command, it only gets a message saying that HeyS is a desktop app without a heys command line; it won't start a second HeyS. On the desktop, do things directly in the interface; when you need scripting or batch work, use a server deployment or the command-line package.
:::

The command line shares **the same data directory and the same spaces** with the server it lives in: a task started from the command line on the server is visible when you sign in to the web app, and vice versa.

## The heys command line \{#the-heys-command-line}

### Getting the command line

- **Docker deployment**: it is inside the container; run `docker compose exec heys heys <command>`;
- **Server package**: the unpacked directory contains `heys`, for example `/opt/heys-server/heys`;
- **Command-line package**: a zip that unpacks to a single-file executable (with its own runtime, no need to install Node.js) plus resource directories such as `skills/` and `case-templates/` next to it; **these directories must stay with the executable**.

```bash
mkdir -p ~/heys && unzip heys-cli-*-linux-x64.zip -d ~/heys
mv ~/heys/heys-linux-x64 ~/heys/heys
export PATH="$HOME/heys:$PATH"
heys --version
```

If you are told it has no execute permission, run `chmod +x heys`. If macOS blocks it the first time it runs, click "Open Anyway" in System Settings → Privacy & Security.

### General conventions

- `heys --version` shows the core version, which matches **Core version** in **Settings → About**; add `--help` after any command to see all options.
- Most query commands support `--json` for machine-readable JSON output.
- Session, task, project and scheduled task IDs are all 26-character strings; project arguments accept either the ID or the project name.
- Which space a command acts on: `--profile <name>` > the environment variable `HEYS_PROFILE` > the current space set with `heys profile use` > `default`.
- Bad arguments or a missing object → exit code 1. `heys task run` **returns 0 when it finishes, whether the task succeeded or not**; to check the result, look at the last event or at `heys task get <id> --json`.

### Where environment variables come from

At startup, commands load `.env` files automatically without overriding variables that already exist. Priority from high to low:

```
shell environment variables  >  <current directory>/.env  >  <data directory>/.env
```

Each line of `.env` is `KEY=VALUE`, with support for an `export ` prefix, `#` comments and quotes. Values such as model provider keys and the extension market address, written into `desktop.yml` through the Settings pages or with `heys provider add` and `heys hub config`, are also read from there when they aren't found in the shell.

Common global variables:

| Setting                     | Effect                                                                                                                                                          |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `HEYS_HOME=<directory>`     | Sets the data directory; default `~/.heys` ([Data, Cloud Sync and Troubleshooting](https://docs.heys.ai/workstation/en/data-cloud-sync-and-troubleshooting.md)) |
| `HEYS_PROFILE=<name>`       | The space used by this command                                                                                                                                  |
| `HEYS_LANG=zh-CN` / `en-US` | The AI language and the language of command-line output; default `zh-CN`                                                                                        |

### Starting a task

```bash
heys task run "Combine the weekly reports under docs/ into one Word document" --project weekly
```

| Option                                    | Description                                                                                               |
| ----------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `--session <id>`                          | Which session to run in; without it the current session is used, or a new one is created if there is none |
| `--workspace <path>`                      | Working directory for this run                                                                            |
| `--project <name or ID>` / `--no-project` | Put a newly created session in this project / in no project                                               |
| `--expert <name>`                         | Run as an expert                                                                                          |
| `--policy auto\|ask-on-write\|readonly`   | Run directly / stop for your approval before write operations / read only                                 |
| `--ref-session <id>`                      | Reference another session's conversation as background; can be repeated                                   |
| `--no-memory`                             | The new session doesn't use global memory                                                                 |
| `--task-id <id>`                          | Continue a specific task that hasn't finished yet                                                         |
| `--json`                                  | Output the event stream as JSON lines, one event per line                                                 |
| `--debug`                                 | Show debugging details                                                                                    |
| `--no-bg`                                 | Run in the foreground (by default it is handed to a background process)                                   |

While it runs, the explanation, tool calls and results of each step are printed live, and the answer is printed word by word at the end. **Ctrl+C only stops showing the output; the task keeps running in the background.** Reattach later with `heys task attach <taskId>`.

- Without a current session, every `heys task run` is a new session, and the model can't see what was said last time. For a multi-turn conversation, run `heys session create` first, or pass `--session` every time.
- If the session still has an unfinished task, running `heys task run "your follow-up"` again attaches the message to that task and continues it; to end it for good, use `heys task close <taskId>`.
- Start the goal with `/skill-name` to choose a skill: `heys task run "/docx Convert the README to Word"`.
- When the agent stops to ask a question, the command line lists the options with numbers; just answer: `heys task run --session <sid> "1"`.
- The terminal can't draw charts, so charts in answers are replaced with tables automatically.

### Common commands

| Command                                                                                     | Use                                                                                                                                                              |
| ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `heys init [--force]`                                                                       | Initialize the data directory; `--force` restores the default space to factory settings and reinstalls the built-in skills                                       |
| `heys task list / get / state / events / attach / cancel / close`                           | View and control tasks (`cancel` pauses, `close` ends)                                                                                                           |
| `heys session create / list / get / use / workspace / archive / unarchive / delete / tasks` | Sessions                                                                                                                                                         |
| `heys project create / list / get / use / dir / rename / delete / memory`                   | Projects, a project's multiple directories, and project memory                                                                                                   |
| `heys search "<keywords>"`                                                                  | Search across sessions                                                                                                                                           |
| `heys skill list / get / enable / disable / add / remove / update / test`                   | Skills                                                                                                                                                           |
| `heys expert list / get / create / edit / remove`                                           | Experts                                                                                                                                                          |
| `heys connector list / get / enable / disable`, `heys connector plugins …`                  | Knowledge sources and connector plugins                                                                                                                          |
| `heys cron add / list / get / runs / edit / enable / disable / remove / run`                | Scheduled tasks                                                                                                                                                  |
| `heys hub status / search / info / install / list / update`                                 | Extension market                                                                                                                                                 |
| `heys market private show / set / test`                                                     | Enterprise market                                                                                                                                                |
| `heys provider list / add / set / models / test / remove`                                   | Model providers                                                                                                                                                  |
| `heys profile list / get / use / create / copy / edit / rename / delete`                    | Spaces                                                                                                                                                           |
| `heys memory topics / show / remember / edit / remove / export / settings`                  | Global memory                                                                                                                                                    |
| `heys soul show / edit / reset`                                                             | Personality                                                                                                                                                      |
| `heys account add / list / role / passwd / remove`                                          | Sign-in accounts ([CoWork, Collaboration Node, Web App and Deployment](https://docs.heys.ai/workstation/en/cowork-collaboration-node-web-app-and-deployment.md)) |
| `heys home show / migrate / use / reset`                                                    | Data directory ([Data, Cloud Sync and Troubleshooting](https://docs.heys.ai/workstation/en/data-cloud-sync-and-troubleshooting.md))                              |
| `heys server`                                                                               | Start an HTTP service ([Starting a service from the command line: heys server](#starting-a-service-from-the-command-line-heys-server))                           |
| `heys tool list / inspect / test`                                                           | Call a tool directly, without the model                                                                                                                          |

See [Shortcuts and Commands](https://docs.heys.ai/workstation/en/shortcuts-and-commands.md) for all options, or add `--help` after any command. Some examples:

```bash
# Create a project bound to an existing directory, then run tasks in it
heys project create --name weekly --path /data/weekly
heys task run "Summarize this week's reports" --project weekly

# Run once every weekday at 9 am (the schedule can be written in natural language)
heys cron add "Summarize yesterday's customer emails into a daily report" --schedule "every weekday at 9 am" --name email-digest

# In a script: create a session, get its ID, run a task in it, then read the result
SID=$(heys session create --name ci-run --workspace . --no-memory --json | jq -r '.sessionId')
heys task run "Run the tests and report problems" --session $SID --workspace . --json > run.jsonl
heys task get $TASK_ID --json | jq -r '.reason'
```

:::tip Tip
For automation such as pipelines, create sessions with `--no-memory` so that instructions from the pipeline aren't remembered as things "about you".
:::

What the command line doesn't have: question card buttons, charts in answers, Tab completion, the file panel, Computer Use, the Sprite, skins and font size.

## Starting a service from the command line: heys server \{#starting-a-service-from-the-command-line-heys-server}

For team deployments, use the Docker image or server package from [CoWork, Collaboration Node, Web App and Deployment](https://docs.heys.ai/workstation/en/cowork-collaboration-node-web-app-and-deployment.md) (which include the web app and Apps). If you only want to serve an API to your own systems, you can also start a service directly from the command line:

```bash
heys server --port 8888                                              # local use only
heys server --host 0.0.0.0 --port 8888 --token "$(openssl rand -hex 24)" --profile prod
heys server --host 0.0.0.0 --port 8888 --auth accounts --no-web
curl http://127.0.0.1:8888/health                                    # {"ok":true}
```

The arguments are the same as for `heys-server` in [CoWork, Collaboration Node, Web App and Deployment](https://docs.heys.ai/workstation/en/cowork-collaboration-node-web-app-and-deployment.md). A service started with `heys server` **has no web app and no Apps**, and no APIs for the built-in Office editor, Computer Use or Import sessions.

| Auth method | Start                         | How requests authenticate                                          | Which space                                                         |
| ----------- | ----------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------- |
| `none`      | `heys server`                 | Nothing needed                                                     | The current space                                                   |
| `token`     | `heys server --token <T>`     | `Authorization: Bearer <T>`                                        | Pinned if `--profile` is given, otherwise follows the current space |
| `accounts`  | `heys server --auth accounts` | Sign in first to get a token, then `Authorization: Bearer <token>` | The space the account maps to                                       |

- Static tokens must be at least 32 characters; with a shorter one the service won't start (`HEYS_ALLOW_WEAK_KEYS=1` allows it temporarily);
- A static token with the `token` method is **not** an administrator, so administrator APIs such as space settings, skill installation and environment variables are refused; when you need them, use an administrator account with the `accounts` method;
- Behind a reverse proxy, set `HEYS_TRUSTED_PROXIES`;
- Run only one service on the same data directory at any one time; the first Ctrl+C shuts down gracefully, the second exits immediately.

## HTTP API (REST) \{#http-api-rest}

The web app uses this API, and your business systems can call it directly too. The service address is the one your administrator gave you (for example `https://heys.example.com`), or a colleague's collaboration node at `http://<IP>:3777`.

```bash
curl https://heys.example.com/health        # {"ok":true}, no authentication needed
curl https://heys.example.com/api/about     # version, API version, platform, etc.
```

### Signing in and authentication

```bash
curl -X POST https://heys.example.com/api/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"alice","password":"..."}'
# → {"token":"...","profileName":"default","expiresAt":"..."}
```

After that, send `Authorization: Bearer <token>` with every request. A few rules:

- With accounts, the token decides which space you can access; a request that names another space is changed back; sessions in other spaces always come back as "not found".
- For addresses the browser loads directly and that can't carry request headers, such as images, download links and event streams, first exchange the token for a **temporary ticket** with `POST /api/auth/ticket`, and put it on the URL as `?_ticket=<ticket>`. Tickets are valid for 5 minutes and are read-only. The old way of putting the token directly in the URL (`?_token=`) is still accepted but no longer recommended.
- `POST /api/auth/logout` immediately invalidates this account's tokens and tickets on all devices; changing the password or the mapped space, or deleting the account, also voids old tokens.
- Protection against credential stuffing: after several failed sign-ins in a row for the same account, each sign-in waits a while first (up to 30 seconds); the account is not locked. Too many failures from the same source in a short time get a 429.

Administrator-level APIs (space settings, model providers, environment variables, extension installation, account management, and so on): the `none` method counts as administrator, the `token` method does not, and the `accounts` method follows the account's role.

### Running a task

```bash
# 1) Start it (runs in the background, returns 202 immediately)
curl -X POST https://heys.example.com/api/tasks/run \
  -H 'Content-Type: application/json' -H "Authorization: Bearer $T" \
  -d '{"goal":"Analyze the sales data for this month","projectId":"...","expertName":"data-analyst"}'
# → {"taskId":"01K...","sessionId":"01K..."}

# 2) Subscribe to the event stream (SSE: replays history first, then pushes live events)
curl -N "https://heys.example.com/api/tasks/01K.../stream" -H "Authorization: Bearer $T"
```

`goal` is required; the rest are optional: `sessionId` (a new session is created if omitted), `workspace` / `projectId`, `pinnedSkills` (choose skills), `expertName`, `sessionRefs` (reference other sessions), `uploadIds` (attachments uploaded beforehand), `model` (which model to use this time), `memory: "off"` (the new session doesn't use global memory).

| Method     | Path                                             | Description                                               |
| ---------- | ------------------------------------------------ | --------------------------------------------------------- |
| `POST`     | `/api/tasks/run`                                 | Start a task                                              |
| `GET`      | `/api/tasks/:id`, `/events`, `/todo`, `/outputs` | Details, events, to-dos, outputs                          |
| `GET`      | `/api/tasks/:id/stream`                          | Live event stream                                         |
| `POST`     | `/api/tasks/:id/continue`                        | Follow up and continue                                    |
| `POST`     | `/api/tasks/:id/answer`                          | Answer a question card                                    |
| `POST`     | `/api/tasks/:id/cancel`, `/close`                | Pause, end                                                |
| `GET/POST` | `/api/sessions`, `/api/projects`                 | Sessions, projects                                        |
| `POST`     | `/api/sessions/:id/rewind`                       | Rewind to a message                                       |
| `GET/POST` | `/api/cases`, `/api/case-templates`              | Cases and Case templates                                  |
| `GET/POST` | `/api/cron/jobs`                                 | Scheduled tasks                                           |
| `GET`      | `/api/inbox`                                     | Notifications (sent by scheduled tasks and Cases)         |
| `GET/POST` | `/api/fs/*`                                      | Browsing, previewing and editing files                    |
| `GET/PUT`  | `/api/memories/*`                                | Global memory (regular accounts can manage their own too) |

Integration notes:

- **A task can have several segments** (follow-ups, continuations), so terminal events can occur more than once. The event stream ends at an explicit `event: end`; don't disconnect on your own as soon as you receive `task.completed`.
- When the session already has an unfinished task, `/api/tasks/run` returns 409 `SESSION_HAS_OPEN_TASK` (with `taskId`); call `/continue` instead, or `/close` it first.
- When the task has already ended, `/continue` returns 409 `TASK_CLOSED`; start a new task with the same `sessionId`.
- In code, check only the `code` and the HTTP status; don't match error messages, since the text changes with the `Accept-Language` request header.
- A chart in an answer is a ` ```chart ` code block (a JSON spec); the API passes it through as-is, and clients that can't draw charts can replace it with a table.

### Do the versions match?

The server and the client are released separately. In `GET /api/about`: `version` is the product version, `coreVersion` the core version, `apiVersion` the API version the server provides, and `minApiVersion` the oldest client version it still supports.

The client records the version N it was built against: `N < minApiVersion` → the client is too old and needs upgrading; `apiVersion < N` → the server is older and new features are unavailable; otherwise they are compatible.

For the full list of API and event fields, ask your administrator or technical support.

## OpenAI-compatible API \{#openai-compatible-api}

For systems that just want to "send a sentence and get an answer", you can treat HeyS as **a model that does work**, and connect with an off-the-shelf OpenAI SDK or LangChain, changing only `base_url` and `api_key`.

| Method | Path                   | Description                                             |
| ------ | ---------------------- | ------------------------------------------------------- |
| `POST` | `/v1/chat/completions` | Main endpoint, streaming and non-streaming              |
| `GET`  | `/v1/models`           | Lists the available "models"; each `id` is a space name |

```python
from openai import OpenAI
client = OpenAI(base_url="https://heys.example.com/v1", api_key="<token>")

resp = client.chat.completions.create(
    model="default",                         # = a HeyS space
    messages=[{"role": "user", "content": "Tidy up this directory for me"}],
    stream=True,
    extra_body={"session_id": "s1", "workspace": "/data/projects/demo"},
)
```

### How things map

| OpenAI                  | HeyS                                                                                                                |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `model`                 | Space (if it isn't an existing space name, the default space is used; with accounts, the space the account maps to) |
| The last `user` message | Task goal                                                                                                           |
| `system` message        | Temporary personality; not written back to the personality file and not kept in history                             |
| `delta.content`         | Final answer                                                                                                        |
| `reasoning_content`     | Each step's explanation and tool process                                                                            |

**You don't need to resend history**: HeyS keeps the session history itself, and only the last user message in `messages` is taken as the goal. `extra_body` can also carry `task_id`, `profile`, `project_id`, `pinned_skills` and `max_iterations`.

### Multi-turn conversations: session_id and task_id

To continue from the previous turn, send the same `session_id`. Ways to pass it, by priority:

```
headers X-Heys-Session / X-Heys-Task  >  session_id / task_id in extra_body  >  a <metadata> block in the system message
```

If you don't send one, the server generates it and returns it in the **response headers** `x-heys-session` / `x-heys-task`; send it with the next turn. If the session still has an unfinished task, this message continues that task as a follow-up.

### Two request headers

| Request header                              | Effect                                                                                                                                       |
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `x-heys-reasoning-format: openai` (default) | Explanations and tool process all go into `reasoning_content`                                                                                |
| `x-heys-reasoning-format: heys`             | Tool names go into `reasoning_card_title` and tool results into `reasoning_card_content` (HeyS private fields; standard clients ignore them) |
| `x-heys-chart-format: spec`                 | Keeps the original chart code blocks in answers. Without it, `/v1` replaces charts with Markdown tables by default                           |

With accounts, a `model` pointing at someone else's space returns 403, and `/v1/models` lists only your own.

:::note Note
For multi-turn orchestration, follow-ups, file handling and tracking Cases, use the REST API in [HTTP API (REST)](#http-api-rest); `/v1` is for plugging HeyS into existing systems that only understand the OpenAI format.
:::
