# CLI

> How the bundled pixling CLI connects, where it lives, what it prints, its exit codes, doctor, and command notes.

`pixling` is a thin client that sends typed operations to the running Pixling app over a local Unix socket. It never edits settings files directly and keeps no separate state.

```sh title="Terminal"
pixling residents
pixling call residents.list '{"detail":"brief"}'
pixling schema resident.set
```

See [CLI commands](/docs/reference/cli-commands/) for the full subcommand list, [Connect an agent](/docs/connect/) to enable the connection, and [Read refusals](/docs/connect/errors/) for error handling.

## Key behaviors

- **No listener when off**: While **CLI connection** is off, Pixling creates neither a socket listener nor a background helper.
- **Structured envelope**: The app returns a JSON document that the CLI maps to stdout, stderr, and an exit code.
- **Program-first and human commands**: `call`, `rpc`, and `schema` always output one-line JSON and take the exact JSON schemas used by MCP. Everyday subcommands print human-readable text by default and accept `--json` or `PIXLING_FORMAT=json`.
- **Fixed identity**: Every invocation runs as `cli:local-cli`, with no pairing, login, or Keychain credentials.
- **Script-friendly**: The root command and every subcommand support `--help`. Free-text and signed-number options accept leading hyphens (such as `- item` or `-120`) as values rather than flags. The root supports `--version`, `--timeout-ms`, standard usage errors, and never prompts interactively.

## Programmatic interface

Use `call`, `rpc`, and `schema` from scripts, tools, and agents when you want machine-readable JSON without flag translation.

### `pixling call`

Sends one request/response operation by its capability ID and prints one JSON document on stdout:

```sh title="Terminal"
pixling call residents.list '{"detail":"brief"}'
pixling call resident.set @patch.json
printf '{"to":"No.7#1","hidden":true}\n' | pixling call resident.set -
```

- Pass arguments as inline JSON, `@path/to/file.json`, `-` for standard input, or piped standard input (up to 64 KiB). Omitting input on a terminal sends `{}`.
- Arguments follow the exact JSON schema returned by `pixling schema <operation>` and MCP `tools/list`.
- Streaming operations (`inbox.receive`, `resident.follow`, `resident.events`) are refused with exit code `64` and a hint naming their dedicated subcommand.

### `pixling rpc`

Runs a persistent NDJSON worker over standard input and standard output so callers avoid spawning a new process per request:

```sh title="Terminal"
printf '{"id":1,"op":"capabilities.get"}\n{"id":2,"op":"residents.list","args":{"detail":"brief"}}\n' | pixling rpc
```

- Each input line is a JSON object: `{"id"?: string|number, "op": "<operation>", "args"?: {...}, "timeoutMs"?: 100...300000}`.
- Each response is one JSON line on stdout matching the common envelope, echoing `id` when provided.
- `--concurrency <1...16>` sets in-flight request parallelism (default `1`, FIFO response order). Higher concurrency may return responses out of order; correlate with `id`.
- Malformed input lines emit a structured JSON error line and keep the worker running until stdin EOF (exit `0`).

### `pixling schema`

Prints machine-readable JSON schemas for all public operations (or one named operation) without connecting to Pixling:

```sh title="Terminal"
pixling schema
pixling schema resident.set
```

The result includes `operations`: every public capability (`id`, `access`, `streaming: false`, `inputSchema`) plus CLI-only streaming commands (`inbox.receive`, `resident.follow`, and `resident.events` with `streaming: true`, `command`, `summary`, and `inputSchema`).

## Install the binary

Every build bundles the binary inside `Pixling.app`:

- Real binary: `Pixling.app/Contents/Helpers/PixlingCLI.app/Contents/MacOS/pixling`
- Bundled symlink: `Pixling.app/Contents/MacOS/pixling`

Put either path on your `PATH`. Because the App Store build runs inside the App Sandbox, it cannot write outside its container, so you create the symlink yourself:

```sh title="Terminal"
mkdir -p ~/.local/bin && ln -sf '/Applications/Pixling.app/Contents/Helpers/PixlingCLI.app/Contents/MacOS/pixling' ~/.local/bin/pixling
```

With **CLI connection** turned on in **Settings** › **Connect**, **Copy** puts the exact binary path and one-line setup command on your clipboard.

> [!NOTE]
> **App Sandbox boundary**
> The distributed CLI runs inside the App Sandbox and can reach only its own container and the shared group container. You cannot use `--socket` to target another app's socket.

### Socket locations

The desk helper (`app.pixling.studio.desk`, always sandboxed) serves both CLI and MCP. The CLI checks two socket paths in order and connects to the first one that exists:

| Order | Location | Path |
| --- | --- | --- |
| 1 | Shared group container (`group.app.pixling.studio`) | `~/Library/Group Containers/group.app.pixling.studio/pixling.sock` |
| 2 | Desk container fallback | `~/Library/Containers/app.pixling.studio.desk/Data/.pixling/pixling.sock` |

If neither exists, the CLI fails immediately with `socketMissing`. Before listening, Pixling verifies the socket owner, symlinks, file type, parent directory mode (`0700`), and socket mode (`0600`).

<details>
<summary>When the fallback or `--socket` is used</summary>

- **Desk container fallback**: Used for ad-hoc or other-Team signed builds, or when a long macOS username pushes the group container path to 104 bytes or longer.
- **Development builds (`--bundle-id`)**: Test builds place their socket under `<bundle-id>.desk`. Pass `--socket /absolute/path/to/.pixling/pixling.sock` or set `PIXLING_SOCKET` (development builds only) for non-standard layouts.

</details>

## Output

- **Default (human)**: Everyday subcommands write results to stdout and diagnostics to stderr. Failure hints print on a `hint:` line.
- **`--json` and `PIXLING_FORMAT=json`**: Writes one JSON document per invocation on stdout for both success and failure. Logs never mix into stdout. `call`, `rpc`, and `schema` always output JSON.
- **`--timeout-ms <100...300000>`**: Overrides the per-request socket deadline in milliseconds.

```json title="Common JSON envelope"
{"invocationID":"...","ok":true,"operation":"question.result","protocolVersion":1,"result":{}}
{"error":{"code":"targetNotFound"},"invocationID":"...","ok":false,"operation":"message.send","protocolVersion":1}
```

### Usage errors

With `--json`, argument parser and codec refusals also print a single JSON line on stdout with exit code `64`. Because the request never reached the app, `invocationID` is omitted:

```json title="Usage error with --json"
{"error":{"code":"invalidArguments","field":"limit","hint":"…","problem":"`limit` must be 1...500"},"ok":false,"operation":"zukan.list","protocolVersion":1}
```

Without `--json`, parser messages and usage go to stderr.

### Connection failures

When the CLI cannot reach Pixling, `error.code` is `unavailable` and `error.detail` names the cause:

| `error.detail` | Meaning |
| --- | --- |
| `socketMissing` | Pixling is not running, or **CLI connection** is off (fails without waiting). |
| `connectionFailed` | The socket exists, but refused the connection. |
| `timedOut` | Pixling did not answer in time. |
| `invalidResponse` | Pixling closed the connection or sent an unreadable response. |
| `invalidPath` | No candidate socket path fits within the 104-byte Unix socket limit. |
| `disconnected` | Connection ended while holding `inbox receive` ([Inbox](/docs/reference/inbox/#inbox-receive)). |

For the first three details, human output prints a `hint:` line suggesting `pixling doctor`, and `--json` puts the same text in `error.hint`.

## Exit codes

| Exit code | Meaning | Error codes |
| --- | --- | --- |
| `0` | Success | — |
| `3` | Unreachable, disallowed, busy, or build mismatch | `unavailable`, `unauthorized`, `busy`, `rateLimited`, `unknownOperation` |
| `4` | Target could not be resolved | `targetNotFound`, `targetAmbiguous`, `targetMustBeSingular` |
| `5` | Domain refusal | `rejected` |
| `64` | Usage error (`EX_USAGE`) | `invalidArguments` |
| `70` | Internal or encoding error | `internalFailure` |

`unknownOperation` means the CLI and the running app are different builds; the failure document includes a `hint`.

## Diagnose with doctor

`pixling doctor` runs four read-only checks in one command without changing app state or leaving processes behind. It sends one `capabilities.get` over the socket and one `ping` to MCP.

```sh title="Terminal"
pixling doctor
PIXLING_MCP_TOKEN="..." pixling doctor --json
```

Pass an MCP bearer token only through the `PIXLING_MCP_TOKEN` environment variable, never as a CLI argument.

| Check `id` | What it verifies |
| --- | --- |
| `cli` | Reads the CLI build metadata from `PixlingCLI.app` (works through symlinks). |
| `socket` | Checks candidate paths in search order, verifying existence, file type, 104-byte limit, owner, and modes (`0600` / parent `0700`). |
| `app` | Calls `capabilities.get` and checks whether the CLI and app commits and protocol versions match. |
| `mcp` | Sends a sessionless `POST` `ping` to `127.0.0.1:48271/mcp`. Skipped (`skip`) on the sandboxed distributed CLI. |

Each check outputs a `status` (`ok`, `warn`, `fail`, or `skip`), a closed-set `code`, a one-line `summary`, and a `next` step. Human output prints `status  id  summary`, an indented `→` line for `next`, and a final `all ok` or `N fail, M warn`.

```json title="pixling doctor --json"
{"ok":true,"operation":"doctor","protocolVersion":1,"result":{"checks":[{"code":"identified","details":{},"id":"cli","status":"ok","summary":"…"}],"counts":{"fail":0,"ok":4,"skip":0,"warn":0}}}
```

`ok` is `true` and exit code is `0` when no check fails (`warn` and `skip` pass). Any failure returns exit code `3`.

<details>
<summary>Doctor status codes and diagnostic details</summary>

App refusal words and socket details never become `code`; they appear inside `details` (`appCode`, `detail`).

| `id` | Possible `code` values |
| --- | --- |
| `cli` | `identified` |
| `socket` | `found`, `socketMissing`, `pathTooLong`, `unsafePermissions` |
| `app` | `reachable`, `buildMismatch`, `cliConnectionOff`, `appNotRunning`, `socketMissing`, `connectionRefused`, `timedOut`, `invalidResponse`, `invalidPath`, `unreachable`, `rateLimited`, `appRefused` |
| `mcp` | `answering`, `tokenRequired`, `tokenRejected`, `unexpectedStatus`, `notListening`, `timedOut`, `probeFailed`, `sandboxed` |

- **Build mismatch (`app`)**: Warns `buildMismatch` (`"CLI and app builds differ"`) if commit or protocol version disagrees. When either commit is `unknown`, only the protocol version is compared and `details.sameBuild` is `null`.
- **MCP `401` (`mcp`)**: HTTP `401` reports `tokenRequired` ("answering") without `PIXLING_MCP_TOKEN`, and `fail` (`tokenRejected`) when a token was provided. The sandboxed distributed CLI cannot access the network and reports `skip` (`sandboxed`, `"unknown (sandboxed CLI)"`).
- **Stale sockets and timeouts**: `connectionFailed` on an existing socket is reported as a stale socket or a listener being recreated; `timedOut` indicates the app is busy.

**Off vs. not running**: When no socket exists, doctor checks whether the bundled desk helper inside the same `Pixling.app` (`Pixling.app/Contents/Library/LoginItems/PixlingDesk.app`) is running as your user. Desk helpers from other `Pixling.app` bundles (such as test builds) are ignored.

| Situation | What `pixling doctor` reports | What to do |
| --- | --- | --- |
| Bundled desk helper is running as your user | `cliConnectionOff` (**CLI connection** is off) | Turn on **CLI connection** in **Settings** › **Connect**. |
| Bundled desk helper is not running | `appNotRunning` (Pixling is not running) | Launch Pixling. |

Unbundled CLIs, explicit `--socket` runs, and sandboxed CLIs cannot identify a counterpart desk and report `unknown` with both causes.

</details>

## Compatibility

- **Closed schema**: Every setting or placement change is a typed operation listed by `capabilities.get` and `pixling schema`, validated by the shared control codec. There is no generic `set`, arbitrary file write, or untyped back door.
- **No leaked internals**: Operation results never include secrets, raw exceptions, or local paths. `doctor` is the single exception, reporting the socket paths it inspected.
- **CLI guidelines**: Follows the [Command Line Interface Guidelines](https://clig.dev/).
- **Additive changes**: New operations, optional inputs, result fields, and output enum values can arrive in any release. Ignore unknown output fields and values.
- **Breaking-change grace period**: Removing or renaming anything, requiring a previously optional input, changing a meaning or unit, or narrowing accepted values keeps working until the release after the next one, and for at least **90 days**.

### Deprecation notices

During a grace period, successful `--json` calls that use a deprecated form include `deprecations` beside `result`:

```json title="Response with deprecations"
{"deprecations":[{"instead":"…","removeAfter":{"date":"2027-06-01","release":"1.3.0"},"what":"…"}],"invocationID":"...","ok":true,"operation":"…","protocolVersion":1,"result":{}}
```

- `what` names the old form; `instead` names its replacement.
- The old form may stop working in `removeAfter.release` or later, and never before `removeAfter.date` (ISO 8601 date).
- Absence of `deprecations` means nothing deprecated was used. Failure documents and human output never show `deprecations`.
- A fully deprecated operation also adds `"deprecated": {"instead", "removeAfter": {"release", "date"}}` to its `capabilities.get` row; deprecating an input leaves the operation row unchanged.
- After removal, the refusal `hint` still names the replacement.

## Notes per command

Details that `--help` and usage lines do not cover.

### Selectors

- `SELECTOR` accepts a UUID, a Field Guide number (`No.N`), a placement number (`No.N#ORDINAL`), a resident's current exact name, or `everyone` (`*` also works).
- A number or name targets every copy of that asset on the desk; a placement number targets one copy. A name shared by two assets on the desk fails as ambiguous.
- Questions must resolve to exactly one resident.
- Built-in starters follow the app language (`Moku`, `モク`, `木木`, `모쿠`), so portable scripts should use `No.N`.
- `prompt-id` is an opaque handle returned by `question ask`. Never construct it or pass it as a resident ID.

### `--version` and `capabilities`

`--version` prints `VERSION (build N, commit HASH, protocol P)` (`commit` is `unknown` when unavailable). It reads `Info.plist` from the `PixlingCLI.app` containing the binary's real path, so it stays accurate through symlinks.

The running app's build appears on the `app: …` line of `pixling capabilities`, or in `result.app` with `--json`.

### `sequence start`

Run `pixling sequence start --help` for step syntax. On refusal, the failing item's `reason` prints on the line after `at <path>`. See [Sequences](/docs/reference/sequences/).

### Command reference map

| Command or flag | Details |
| --- | --- |
| `residents` | [Residents: `pixling_residents_list`](/docs/reference/residents/#pixling_residents_list) |
| `--to auto` | [Messages and questions: `auto` target](/docs/reference/messages-and-questions/#the-auto-target) |
| `question ask`, `result`, `cancel` | [Messages and questions: `pixling_question_ask`](/docs/reference/messages-and-questions/#pixling_question_ask) |
| `resident place` | [Residents: `pixling_resident_place`](/docs/reference/residents/#pixling_resident_place) |
| `resident describe`, `set` | [Resident settings](/docs/reference/resident-settings/) (including [gravity](/docs/reference/resident-settings/#gravity)) |
| `resident follow` | Reads window frames from stdin until EOF ([Residents](/docs/reference/residents/#resident-follow-cli-only), [Follow a window](/docs/connect/follow-a-window/)). |
| `resident events` | Streams one JSON line per click on your resident until stowed; nothing is saved ([Residents](/docs/reference/residents/#resident-events-cli-only), [Hear clicks](/docs/connect/hear-clicks/)). |
| `resident glow` | Pass one step with `--select`, or `--steps-json` ([Light (glow)](/docs/reference/light/)). |
| `zukan`, `resident summon`, `duplicate`, `stow` | [Residents: summon, duplicate, and stow](/docs/reference/residents/#summon-duplicate-and-stow) |
| `resident ensure --asset-id` | Accepts `No.N`, exact name, or ID ([Resident binding](/docs/reference/resident-binding/)). |
| Shapes and `resident sketch` | [Residents: shapes and sketch](/docs/reference/residents/#shapes-and-pixling_resident_sketch) |
| `import prepare` | [Import](/docs/reference/import/) |
| `doctor` | Pass the MCP token in `PIXLING_MCP_TOKEN` ([Diagnose with doctor](#diagnose-with-doctor)). |

## Related

- [CLI commands](/docs/reference/cli-commands/): Complete generated list of subcommands and flag synopses.
- [MCP server](/docs/reference/mcp/): Streamable HTTP endpoint, protocol profiles, and trust boundary.
