# Environments

The project decides which machine a conversation's shell and files are on: a project is a folder on one machine, and every conversation in it runs there.

This page covers what follows from that. Machines themselves, each with one connection method, are one registry, designed in [Machines and targets](https://fzkuji.github.io/OpenProgram/docs/reference/design/integrations/computer-use/machines-and-targets.html). A channel (WeChat, Telegram, …) only decides where messages are mirrored. Product page: [Run conversations on another machine](https://fzkuji.github.io/OpenProgram/docs/capabilities/environments.html).

| Shell kind | Backend | Command form | Working folder | Host sandbox |
| --- | --- | --- | --- | --- |
| `local` | `LocalBackend` | Host subprocess. macOS and Linux: `bash -c`, sandboxed or not (`sh` only without bash), so `echo` prints `\n` as written and `printf` expands it; scheduled task commands run the same way. Windows: Git Bash or PowerShell, WSL bash when sandboxed | Host | Applies |
| `ssh` | `SshBackend(target, workdir)` | `ssh … <target> 'cd <dir> && <cmd>'` | Remote absolute path | Off; isolation is the remote account |
| `docker` | `DockerBackend(image, container, mounts, labels)` | `docker exec -i [-w cwd] <container> sh -c <cmd>` | Host path, mounted at the same path | Off; isolation is the container |

The shell feature maps the connection methods commands run through in `SHELLS` (`openprogram/host/backend/__init__.py`): `local`, `ssh` and `docker`, each with its `backend` and, for Docker, `instance_scope="conversation"` and `remove_instances`. The same module registers the methods `ssh` and `docker` (settings schema, `check`) with the device layer. `backend_for(machine, session_id)` builds the backend from the machine's method and names no method.

## The environment role

| Question | Rule |
| --- | --- |
| Which machines qualify | `usable_as_environment`: switched on, reached by a method in `SHELLS`. `list_environments()` lists them, this computer first |
| Which one a conversation uses | `resolve_for_session`: its project's (`resolve_for_project`, from `machine_id` on the project record). The home project and a record naming no machine are `local` |
| Default | None. A new conversation is in a project, and the project names the machine |

Code: `openprogram/host/machines/__init__.py`. `openprogram machines`, the setup wizard's **Machines** step and the WebSocket actions `list_machines`, `save_machine`, `delete_machine`, `set_machine_enabled`, `test_machine` are thin layers. Every change broadcasts a `machines` frame carrying `items` (each with its connection `status`) and `kinds`.

## Conversation binding

| When | Which machine |
| --- | --- |
| Draft | The pending project's. The composer's machine chip shows it and cannot switch it |
| First message | The project the first `chat` frame names binds the session, as before; nothing about the machine is sent or stored on the session |
| After that | The session's project is frozen, so its machine is too |
| Channel conversation | The home project: this computer |
| Machine removed, switched off or running no commands | `resolve_for_session` raises `MachineError` naming Settings > Machines; the backend becomes `UnavailableBackend`: every command returns the same explanation, and a spawned process (`execute_code`, a background command) is refused with it. `current_environment()` reads a bound machine again at each tool call, so a machine switched off or removed during a turn refuses the next command and file call. Tools never fall back to this computer |

Targets of `computer_use` are a separate binding, chosen per call; being the environment never makes a machine the default target.

## Turn binding

`TurnBindings.bind` sets the `_current_environment` ContextVar. `current_environment()` reads it first, then the current session's project's machine, then this computer when there is no session. `get_active_backend()` builds the backend from that and the current session.

When the shell is not this computer's, the `<environment>` block names the machine by id, its name and what its method says of it, and that the chat and OpenProgram stay on this computer; with `computer_use` offered it adds that calls without `device` act on this computer.

- A shell with `remote_files` (SSH): the worktree ContextVar is the project's folder on the host (`remote_project_folder`), so commands start there and the permission fence checks it too. The folder was made absolute on the host (`cd` then `pwd -P`) when the project was opened.
- `remote_workdir`, the machine's remote folder setting, is only where browsing for a project folder starts. Relative tool paths join with `posixpath` and never touch this computer's filesystem.

**SSH command options**

```
ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new
    -o ControlMaster=auto -o ControlPath=<state>/ssh/%C -o ControlPersist=300
    <target> 'cd <dir> && <cmd>'
```

- Connection sharing keeps each tool call to one round trip after the first.
- `%C` hashes host, port and user, keeping the socket under the macOS `sun_path` limit. ControlMaster is skipped on Windows.
- A leading `~` reaches the remote shell unquoted so it expands there.

**Docker container lifecycle**

- The conversation's instance: one long-lived container, `container_name` = `openprogram-<machine>-<conversation>` (characters outside `[a-zA-Z0-9_.-]` become `-`, at most 120), labelled `openprogram.machine`, `openprogram.conversation` and `openprogram.home` (a digest of the state directory, so two installations sharing one Docker tell their containers apart), started with `docker run -d --init … tail -f /dev/null`.
- Working folder, project folder and additional working directories are bind-mounted at identical paths. The first mount is the starting folder.
- A hash of image plus mounts is the `openprogram.mounts` label. Changed: remove and recreate. Matching: start a stopped container again. A per-process cache skips `docker inspect` after the first command; a spawned process does not trust it and checks the container each time.
- When the daemon refuses a command because the container is gone ("No such container") or stopped ("is not running", after a Docker restart or `docker stop`), the cache entry is dropped, the container is started or created again and the command runs once more: nothing reached the old one. Only a refusal that starts `Error response from daemon:` counts.
- A conversation's container is made only while its machine is configured and on. After the command is counted on the machine, and again before that retry, a machine switched off or removed since the backend was made refuses the command ("machine '<id>' was switched off" or "was removed"), and no container is created.
- `remove_instances` finds this installation's containers by those labels, not by the machines configured now, and removes them in a background thread: by conversation when it is deleted, alone or by Clear all, whether or not it was opened since the worker started; by machine when the machine is removed, switched off or saved off.
- For conversations it asks only the shells some configured machine's method uses, switched-off machines included, so nothing runs `docker ps` without a Docker machine. Clear all hands every deleted conversation to one thread, which takes them one after another.
- Without a session ID the backend uses one-shot `docker run --rm`, as `machines test` does; it is not checked against the machine's state.
- For a machine, `remove_instances` first lets running `computer_use` calls finish (up to `registry.FINISH_SECONDS`, 300 s), then waits for the commands counted on it (`wait_idle`, up to `RELEASE_WAIT`, 300 s); `current_environment()` refuses new ones meanwhile.
- Counted are the `run` calls and spawned processes of its SSH and Docker backends, the supervisor of a background or supervised bash command for as long as it lives, and the check or creation of a container for a spawned process.
- A machine configured and on again, checked before the release and after the wait, ends the removal, so its containers stay.
- `openprogram machines remove` and `disable` remove a machine's containers before they return (`wait=True`). The CLI's process counts none of the worker's calls and commands, so they do not wait for them.

## Remote file tools

`read`, `write`, `edit`, `apply_patch`, `glob`, `grep` and `list` call `remote_target()`. A machine whose shell kind has `remote_files` (SSH) gets a `RemoteFS` (`host/machines/remote.py`) and delegates to `programs/tools/files/_remote.py`, with the local tool's output format; results name the machine by id (`devbox:/path`).

Docker and local get `None` and stay local. A conversation whose machine cannot be used gets `RefusedFS`: every operation raises `ConnectionError` with the reason, so the tool reports it and never reads this computer's disk.

| Operation | How |
| --- | --- |
| `stat` | One `test` command: exists, directory, size |
| `read_bytes` | `cat`, at most 32 MiB |
| `write_bytes` | `mkdir -p`, temporary file in the same folder, then `mv` over the target |
| Exit 255 | ssh's own failure: `ConnectionError`, reported as an error, not file content |
| `glob` | `find` on the host plus a regex translated from the glob. GNU `-printf` for mtimes, BSD `stat` as fallback |
| `grep` | `rg` if present, else `grep -rE`, capped by `head` |
| `list` | Shell loop |
| PDF read | Bytes copied to a local temporary file, local reader |
| Read before edit | sha256 per (session, machine, path), kept on the branch under `machine:<id>`. `write` over a file, `edit` and `apply_patch` refuse when never read or changed |
| `write` `source_path` | Refused on SSH: it would cross machines silently |

## Composer

| Chip | Shows and does |
| --- | --- |
| Machine | Always shown: the project's machine, with the icon Settings → Devices uses (`machineIconName`) and, for another machine, its connection dot; colour is the worker connection tone, red when the machine is gone; label is the name. It cannot switch: its menu holds that one machine, checked, and the note "Set by project <name>" |
| Channel | Always shown. Unbound: chat glyph and “No channel”. Bound: `ChannelLogo` and account id; logo alone when squeezed. `channelHealth` is a 6px corner dot: yellow degraded, red unreachable. The menu has one row per app with enabled accounts, each with an accounts submenu (bound one checked), then “Disconnect” while bound and “Manage channels” |

The chip is the only place the composer sets the channel. Menu and chip share `channel-choices.ts` and follow the composer's pane (`useBoundChat`). `statusBadge` and `channelHealth` are separate store slices.

## Implementation status

Implemented: the environment as a role over the machines registry, decided by the project; shells for the methods `local`, `ssh` and `docker`; `openprogram machines`, wizard step, Settings → Devices, WebSocket actions; remote file tools; per-conversation Docker containers removed by label.

Not implemented:

- WSL and cloud environments
- Password or interactive SSH sign-in
- Checkpoint or undo for remote files; revert does not restore them
- Moving a project to another machine
- Waiting for supervised processes that outlived a worker restart before a removed or switched-off machine's instances go; after the restart they are not counted
