# Resident binding

> The resident.ensure contract that binds a client namespace/key to one resident, with its arguments, result, states and refusals.

`resident.ensure` binds a client-chosen `namespace`/`key` pair to one resident and returns that same resident on every subsequent call with the same pair. The MCP tool is `pixling_resident_ensure`; the CLI command is `pixling resident ensure`. Both invoke the same operation and return the same document.

For an end-to-end walkthrough of choosing, binding, writing, and receiving, see [Give your agent a resident](/docs/connect/own-a-resident/). For retry behavior, see [Effects and retries](/docs/connect/effects/).

## Arguments

| Argument | Required | Value |
| --- | --- | --- |
| `namespace` | Yes | 1–64 bytes of ASCII letters, digits, `.`, `_`, or `-`; case-sensitive. |
| `key` | Yes | 1–128 bytes of the same character set; case-sensitive. |
| `assetID` | For a new key | Field Guide resident (`No.N`, exact name, or `pack/asset` ID); at most 512 bytes. |
| `name` | No | Session label: 1–60 characters, at most 240 UTF-8 bytes, nonblank, no control characters. |
| `note` | No | Creation-only remarks for the session, at most 200 characters. |
| `initial` | No | Creation-only placement and settings (see [`initial`](#initial)). |
| `groupID` | No | Creation-only group UUID from `group.list` (see [`groupID`](#groupid)). |

`assetID` accepts a Field Guide `No.N`, an exact name, or a `pack/asset` ID from `zukan.list` (`entries[].id`). `No.N` and names resolve using the same rules as `resident.summon`'s `who`:

- A name shared by two or more Field Guide residents fails with `targetAmbiguous`, with a hint suggesting `No.N`.
- An unknown asset fails with `rejected` / `unknownResident`.
- A placed copy (`No.N#k`) or `everyone` fails with `invalidArguments` on `assetID`.
- Unknown arguments, wrong types, and invalid characters or lengths fail with `invalidArguments`.

`name` labels only this session's resident and never renames the shared asset. For `note` and `initial.note`, see [Notes](/docs/reference/notes/).

### `initial`

```json title="initial payload"
{"placement": {"size": 80}, "settings": {"gravity": "down"}}
```

- `placement`: `x`, `y`, `size`, `rotation`, `mirrored`. Same fields as `resident.place`, without `to`.
- `settings`: Closed patch accepted by `resident.set` without `to`. Omitted keys keep their values, `null` restores the default where allowed, and every value must appear under `options` in `resident.describe`.
- `note`: Creation-only remarks for the resident itself, at most 200 characters.

Unknown fields or wrong types refuse the whole call. `initial` runs only when the key is new:

- **Atomic transaction**: Settings resolve first, the resident is placed with its final representation, and gravity settles it. Creation, placement, and settings commit together; if any step fails, no binding is left behind.
- **Error details**: Settings or placement errors return the same closed `rejected` detail as `resident.set` or `resident.place`, such as `dotsUnavailable`, `poseUnknown`, or `offscreen`.
- **`settings.dots`**: Accepted with the same refusals, though the result omits `dotsWrite`. Dots whose picture the desk must render appear once ready, so inspect them with `resident.describe`.
- **Defaults without `initial`**: A new resident appears at the center of the display with motion off, at the default summon size (apparent idle body of about 160pt), on the floating layer so it can display questions. Explicit `initial.settings` can override both layer and motion.

### `groupID`

With `groupID`, the new resident joins that group in the same save and spawns beside an existing member on the desktop (macOS Space) where that member was last seen, even if another desktop is active now.

- **Target desktop**: Pixling prefers a member on the currently active desktop; otherwise it picks the first group member seen on any desktop.
- **Exclusions**: Hidden members and members shown on every desktop do not count.
- **Fallback**: If no member has been seen on a desktop, or if `initial.placement` specifies a position, the resident spawns as without `groupID`.
- **Unknown group**: Fails with `rejected` / `groupNotFound` and creates nothing.

## Result

```json title="resident.ensure result"
{
  "binding": {"namespace": "…", "key": "…", "selector": "client:…/…", "entityID": "…", "assetID": "pack/asset", "name": "…", "note": "…"},
  "state": "onDesk",
  "resident": {}
}
```

- **`binding.selector`**: Always `client:<namespace>/<key>`. Use it to address your resident.
- **Ownership lock**: Writes to a bound resident by `entityID` or any other selector fail with `boundToAnotherClient`. Anyone may still move it with `resident.place` or `resident.desktopVisibility`.
- **Optional fields**: `name` and `note` appear in `binding` only when set.
- **Cross-references**: `residents.list` and `resident.describe` rows also include `clientBinding`.

`state` describes the bound resident's current presence:

| `state` | `resident` field | Meaning |
| --- | --- | --- |
| `onDesk` | Full `residents.list` row | The resident is in the scene. |
| `stowed` | `null` | The resident was put away. |
| `unavailable` | `null` | The binding exists, but the resident cannot be listed. |

- **`onDesk` does not guarantee visibility**: Check `visibility` and `conversation` before asking a question.
- **`stowed` stays stowed**: Calling `ensure` again does not restore a stowed resident unless the binding was evicted (see [Lifetime](#lifetime)).
- **`unavailable`**: Occurs when the resident's asset is missing or otherwise cannot be listed.

## Resending and conflicts

- Passing `namespace` and `key` alone returns the current binding. Key lookup runs before checking the Field Guide or display.
- Passing `assetID` or `name` on an existing key must match the stored binding; otherwise the call fails with `rejected` / `clientKeyConflict`.
- An `assetID` that no longer resolves uniquely (such as a name now shared by two assets) is not treated as a conflict.
- For an existing key, `initial`, `note`, and `groupID` are ignored, preserving the user's own placement and settings.
- A new key without `assetID` fails with `rejected` / `creationRequiresAsset`.

## Refusals

Beyond the argument and conflict refusals above, `ensure` returns these scene refusals as `rejected` details (shared with `place`, `set`, `duplicate`, `stow`, `summon`, and `sketch`):

| Detail | Meaning |
| --- | --- |
| `appNotReady` | Pixling is starting, stopping, or reloading the desk. |
| `saveFailed` | The desk could not be saved; nothing changed. |
| `sceneInvalid` | The change failed validation; nothing changed. |
| `packLoadFailed` | The resident's pack could not be read. |
| `noDisplay` | No display is available for placement. |
| `offscreen` | The requested placement is outside every display. |
| `unknownResident` | The `assetID` for a new key is not in the Field Guide. |
| `clientBindingLimit` | The 4096-binding limit is reached and every bound resident is currently on the desk. |

Any failure matching no typed refusal returns `internalFailure`, with only the error type's name in `detail`.

## Lifetime

- **Saved across restarts**: Bindings persist locally with the desk across restarts, even after the resident is stowed.
- **4096-binding limit**: Bindings do not expire. When a new key needs room at the limit, Pixling evicts the oldest binding whose resident is off the desk; that evicted key then counts as new again.
- **Stowing preserves the tombstone**: Stowing keeps the binding in `stowed` state until evicted as above.
- **Missing assets**: An existing binding whose asset is missing reports `unavailable`.
- **Starting fresh**: Use a new `key` to start a new session explicitly. Creating a new resident under a new key does not recover a lost key's resident.
- **Serialized mutations**: Concurrent CLI and MCP calls to one app execute one at a time.

> [!CAUTION]
> **`namespace` is a correlation scope, not authentication**
> `namespace` and `key` prevent accidental cross-writes between clients, not malicious access. Never store secrets in a key or a name.

## CLI

```sh title="Terminal"
pixling zukan --json
pixling resident ensure --namespace codex --key session-123 --asset-id No.7 --name Piko --initial '{"placement":{"size":80},"settings":{"gravity":"down"}}' --json
pixling resident ensure --namespace codex --key session-123 --json
```

| Flag | Argument |
| --- | --- |
| `--namespace` | `namespace` |
| `--key` | `key` |
| `--asset-id` | `assetID` (`No.N`, exact name, or ID) |
| `--name` | `name` |
| `--note` | `note` |
| `--initial JSON` | `initial` (a JSON object) |
| `--initial-note` | `initial.note` (pass this or `initial.note`, not both) |
| `--group-id` | `groupID` |

Pass `client:<namespace>/<key>` to `--to` in subsequent commands. When the user chooses to end the session, run `pixling resident stow --to client:<namespace>/<key>`; the key remains `stowed` as described in [Lifetime](#lifetime).

## Related

- [Inbox](/docs/reference/inbox/): Watch, wait for, and read user messages sent to your bound resident.
- [Residents](/docs/reference/residents/): Place, configure, describe, summon, duplicate, and stow residents.
