Metadata-Version: 2.5
Name: qodalis-cli-server-plugin-docker
Version: 1.0.0b40
Summary: Docker containers, images, stacks, volumes and networks plugin for Qodalis CLI servers: commands, API, MCP, exec socket and Console page
Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
Project-URL: Issues, https://github.com/qodalis-solutions/cli-server-python/issues
Author-email: Nicolae Lupei <nicolae.lupei@qodalis.com>
License-Expression: MIT
License-File: LICENSE
Keywords: cli,containers,docker,plugin,qodalis
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Requires-Dist: fastapi>=0.100.0
Requires-Dist: opentelemetry-api<1.46
Requires-Dist: qodalis-cli-server-abstractions>=1.0.0b39
Provides-Extra: users
Requires-Dist: qodalis-cli-server-plugin-users>=1.0.0b40; extra == 'users'
Description-Content-Type: text/markdown

# qodalis-cli-server-plugin-docker

Docker for the [Qodalis CLI Server (Python)](https://github.com/qodalis-solutions/cli-server-python): containers, images,
compose stacks, volumes and networks of one or more Docker hosts, through the Docker Engine API, from the Qodalis Console
(a Docker page), the web terminal (`docker`), MCP and a REST API, with an interactive exec session in the Console. The
design and the contract shared with the Node and .NET servers is
`web-cli/docs/superpowers/specs/2026-12-04-docker-plugin-design.md`.

```bash
pip install qodalis-cli-server-plugin-docker
```

The plugin is opt-in and has no default endpoint: the Docker socket is root-equivalent, so the server's owner says which
engine to use. Without an `endpoint` the plugin is **needs configuration** (it registers nothing).

## Use

```python
from qodalis_cli import create_cli_server
from qodalis_cli_docker import plugin as docker

result = create_cli_server(CliServerOptions(
    configure=lambda builder: builder.add_plugin(docker, {"endpoint": "unix:///var/run/docker.sock", "protect": ["postgres*"]}),
))
```

or without the plugin loader:

```python
from qodalis_cli_docker import CliDockerBuilder, DockerSettings

plugin = (
    CliDockerBuilder()
    .set_settings(lambda: DockerSettings(endpoint="unix:///var/run/docker.sock", protect=["postgres*"]))
    .set_audit(record)  # optional: an async function of the audit entry (a dict)
    .build()
)
result.mount_plugin(plugin)  # routes, commands, permissions, the Console page, the MCP tools and the exec socket
```

The demo server enables the plugin only when `QCLI_DOCKER_ENDPOINT` is set (its value is the endpoint); it is protected
(users plugin), so the plugin serves signed-in callers; `QCLI_DOCKER_ALLOW_UNPROTECTED=true` turns `allowUnprotected` on.

## Settings

Config provider `docker`, section `settings` (Console Config page, `config set docker.settings.<key> <value>`). They are
read on every call, so a change applies without a restart, except hosts and TLS files, which apply to new connections.

| Key | Type | Default | Meaning |
|---|---|---|---|
| `endpoint` | string, required | none | The default host (named `local`): `unix:///var/run/docker.sock`, `tcp://host:2375`, `tcp://host:2376` (TLS when a certificate is set or the port is 2376), `https://host:2376` |
| `tlsCa`, `tlsCert`, `tlsKey` | string | none | Paths of PEM files for the default host |
| `tlsVerify` | boolean | true | Verify the engine's certificate |
| `hosts` | json | `{}` | More hosts: `{ "<name>": { "endpoint": "...", "tlsCa": "...", "tlsCert": "...", "tlsKey": "...", "tlsVerify": true } }`; names match `^[a-z0-9][a-z0-9-]{0,31}$`, `local` is reserved; invalid entries are dropped and logged |
| `readOnly` | boolean | false | Refuse every change (actions, pulls, exec, removals, prunes, creation) |
| `hide` | string[] | `[]` | Containers nobody sees (404, left out of lists, counts, stacks, events) |
| `protect` | string[] | `[]` | Containers that can be read but not changed (409 `container <name> is protected`) |
| `composeRoots` | string[] | `[]` | The only folders compose files are read from, written to and run from (absolute paths); empty: no compose file is read and no compose feature works |
| `composeCommand` | string | `docker compose` | The compose CLI: words split like a shell line, run without a shell (`docker-compose` works too) |
| `composeHosts` | string[] | `["local"]` | The hosts compose may change; write, `up`, compose `down` and delete on another host are 409 `compose is not enabled for host <name>` (the Engine API way of `down` for a stack without a file works on any host) |
| `composeEnv` | string[] | `[]` | Names of the server's environment variables the compose CLI may see (for `${VAR}` in compose files); names starting with `DOCKER_` or `COMPOSE_` are ignored |
| `composeTimeoutSeconds` | number 10-3600 | 900 | Time limit of one compose `up` (`down` has 120 s) |
| `bindMounts` | string[] | `[]` | Host folders a created or edited container may bind-mount (absolute paths); a bind source must be one of them or lie under one, compared as text after normalizing (`.`, `..`, repeated and trailing `/` removed; a source that climbs above `/` is refused). The folders are on the engine's machine, so the server cannot resolve links there: list only folders whose content the admins control. Empty: 400 `bind mounts are not allowed (see the bindMounts setting)`; outside: 400 `bind mount <source> is outside the allowed folders` |
| `allowPrivileged` | boolean | false | Allow the settings that give a container power over the host: `privileged`, `capAdd`, `devices`, `securityOpt`, `networkMode`/`pidMode`/`ipcMode`/`usernsMode`/`cgroupnsMode` `host`. Off: 400 `<field> needs the allowPrivileged setting`. An edit keeps a value the container already has; only what it adds is checked |
| `allowUnprotected` | boolean | false | Serve callers that are not signed in (a server without the users plugin's protection); off: see the first rule below |
| `timeoutSeconds` | number 1-120 | 15 | Timeout of one Engine API call (not of streams, pulls or exec) |

A pattern of `hide` / `protect` is a container name with `*` wildcards (`postgres*`, case-sensitive, matched against the
name without the leading `/`), or `label:<key>` / `label:<key>=<value>`. Every route takes `?host=<name>`, every command
`--host <name>`; an unknown name is 404 / `Error: unknown Docker host: <name>`.

## Permissions

| Permission | Allows |
|---|---|
| `docker:read` | See containers, images, stacks, volumes, networks, logs and stats |
| `docker:manage` | Start, stop and restart containers and stacks, pull images |
| `docker:exec` | Run commands inside containers (REST, terminal, MCP and the exec socket) |
| `docker:admin` | Remove containers and images, prune, create and remove volumes and networks, take stacks down |

On a protected server the route gate maps GET to the first permission and other methods to the second of each path:
`/api/v1/qcli/docker` `docker:read` / `docker:manage`, `/exec` `docker:exec`, `/admin` `docker:admin`. The exec socket needs
`docker:exec` (the plugin checks it itself); the root command `docker` needs `docker:read` and each sub-command adds its own.

## REST API (`/api/v1/qcli/docker`)

Errors are `{ "error": "<text>" }`: 400 invalid input or an ambiguous container reference, 403 `the Docker plugin is
read-only` or `the Docker plugin needs a protected server (sign-in); see its allowUnprotected setting`, 404 unknown host,
container, image, volume, network, stack or operation, 409 `container <name> is protected` or the engine's own conflict,
502 `cannot reach Docker at <host>: <message>`, 504 an exec that did not finish. A container reference is a full id, an id
prefix of at least 3 characters or a name.

| Route | Permission | Answer |
|---|---|---|
| `GET /hosts` | read | `{ hosts, readOnly }` (each host probed with a 3 s timeout) |
| `GET /info`, `/df` | read | engine info; disk usage with reclaimable sizes |
| `GET /events?since=&limit=` | read | `{ host, events }`, newest first |
| `GET /containers?all=&stack=`, `/containers/{id}` | read | containers sorted by name; one with its detail (command, masked environment, mounts, networks) |
| `GET /containers/{id}/logs?tail=&since=&timestamps=` | read | `{ host, lines }`, oldest first |
| `GET /stats?ids=` | read | CPU, memory, network, block I/O and pids (two samples per container) |
| `GET /compose` | read | `{ available, version?, roots, error?, bindMounts, allowPrivileged }`: whether the compose CLI answers (`version --short`, 5 s, cached 60 s), and what the container form may offer (the normalized `bindMounts` and `allowPrivileged`) |
| `GET /images`, `/stacks`, `/stacks/{name}`, `/volumes[/{name}]`, `/networks[/{id}]` | read | lists and details; a stack has `composeFile` (the path found by the rule) and the state `down` when only its folder exists |
| `GET /operations`, `/operations/{id}` | read | the last 50 operations (pulls, stack updates), newest first |
| `POST /containers/{id}/start\|stop\|restart\|kill\|pause\|unpause` | manage | `{ ok, container }` |
| `POST /images/pull` `{ image }` | manage | 202 `{ operation }`; the pull runs in the background |
| `POST /stacks/{name}/start\|stop\|restart` | manage | `{ ok, results }` per container (a protected one is reported, the rest run) |
| `POST /stacks/{name}/pull` | manage | 202 `{ operation }` |
| `POST /exec/{id}` `{ command, user?, workdir?, timeoutSeconds? }` | exec | `{ exitCode, stdout, stderr, truncated }` (1 MB per stream; 504 on timeout) |
| `GET /admin/containers/{id}/spec` | admin | `{ host, spec, stack, editable, reason? }`: the container's configuration as a ContainerSpec (see Creating and editing containers) |
| `POST /admin/containers` `{ spec, start?, pull? }` | admin | 202 `{ operation }` (kind `container-create`) |
| `PUT /admin/containers/{id}` `{ spec, pull? }` | admin | 202 `{ operation }` (kind `container-update`): an in-place update or a recreate |
| `DELETE /admin/containers/{id}?force=&volumes=`, `POST /admin/containers/prune` | admin | `{ ok }`; `{ removed, reclaimedBytes }` (hidden and protected containers are never pruned) |
| `DELETE /admin/images/{id}?force=`, `POST /admin/images/prune` `{ all? }` | admin | `{ ok, untagged, deleted }`; `{ removed, reclaimedBytes }` |
| `POST /admin/volumes`, `DELETE /admin/volumes/{name}?force=`, `POST /admin/volumes/prune` | admin | 201 `{ volume }`; `{ ok }`; `{ removed, reclaimedBytes }` |
| `POST /admin/networks`, `DELETE /admin/networks/{id}`, `POST /admin/networks/prune` | admin | 201 `{ network }`; `{ ok }` (a built-in network is 409); `{ removed }` |
| `POST /admin/stacks/{name}/down` body `{ volumes? }` | admin | a stack with a compose file: `compose down` (`--volumes`), 120 s; without a file the Engine API way: stops and removes the containers, then the stack's networks; refused whole (409) with a protected container |
| `PUT /admin/stacks/{name}/compose` body `{ content }` | admin | writes the stack's compose file after `config --quiet` accepted it; `{ stack, composeFile }` |
| `POST /admin/stacks/{name}/up` body `{ pull?, file? }` | admin | 202 `{ operation }` (kind `stack-up`, with the CLI's `log`) |
| `DELETE /admin/stacks/{name}/compose` | admin | removes the file of a stack that is down |

`stacks start` starts the stack's existing containers; creating and updating stacks is the Compose feature below (the
Engine API has no compose).

A pull publishes `docker:operation` on the event bus (data: the operation, audience `docker:read`) on each state change
and at most once a second while its progress changes.

## Exec socket

`WS /ws/v1/qcli/docker/exec?host=&container=&cmd=&user=&cols=&rows=&ticket=` (also `/ws/qcli/docker/exec`): an
interactive session with a TTY. `cmd` defaults to `/bin/sh -c 'command -v bash >/dev/null 2>&1 && exec bash || exec sh'`.
The messages are those of `/ws/v1/qcli/shell`: the client sends `{ "type": "stdin", "data" }` and
`{ "type": "resize", "cols", "rows" }`; the server `{ "type": "ready", "shell", "os" }` (`shell` is a short label: `sh` for
the default shell, else the first word of `cmd`), `{ "type": "stdout", "data" }`, `{ "type": "exit", "code" }` and
`{ "type": "error", "message" }`. Closing the socket ends the exec. Hidden and protected containers, read-only mode, an
unknown host or container, a container that is not running and an unreachable engine are refused with ONE message
`{ "type": "error", "message" }` (the text of the matching REST error) and a normal close (1000), because a browser cannot
read the status of a refused upgrade. The server's own origin check applies (a foreign origin is closed with 4403 `origin
not allowed`); a protected server closes with 4401 `unauthorized` (no or a used ticket) or 4403 `forbidden` (no
`docker:exec`), like the shell socket. `docker exec -it <container> [command...]` in a web terminal that can run sessions
(`sessions: true` in the request) answers with a `session` block that points at this socket (the container, `cmd`, `user`);
`docker exec <container>` without a command does too.

## Terminal commands

Output v2 (typed tables, status tones, key-value panels, progress); `--host <name>` everywhere, `--json` where data is
printed (the route's answer indented by 2); destructive commands ask first (`--yes`, `-y`).

| Command | Permission | Notes |
|---|---|---|
| `docker` | read | the hosts, a summary of the default host, the sub-commands |
| `docker hosts` | read | name, endpoint, state, version, containers |
| `docker ps [--all] [--stack <name>]` | read | running containers unless `--all`; a row opens `docker inspect` |
| `docker inspect <container>` | read | panels: container, ports, mounts, networks, environment |
| `docker logs <container> [--tail <n>] [--since <10m\|2h\|ISO>] [--timestamps] [--follow]` | read | `--follow` streams until stopped (streaming terminals) |
| `docker stats [container] [--watch]` | read | `--watch` refreshes the table every 2 s |
| `docker start\|stop\|restart\|kill\|pause\|unpause <container...>` | manage | one line per container; exit 1 when any failed |
| `docker rm <container...> [--force] [--volumes] [--yes]` | admin | asks first |
| `docker run [options] <image> [command...]`, `docker create [options] <image> [command...]` | admin | creates (and starts, for `run`) a container; the options are the Docker CLI's, before the image, everything after it is the command (see below). A progress block, then `Created <name> (<shortId>), <state>` |
| `docker update [--restart <policy>[:<n>]] [--memory <size>] [--memory-reservation <size>] [--memory-swap <size>] [--cpus <n>] [--cpu-shares <n>] [--cpuset-cpus <list>] [--pids-limit <n>] <container>` | admin | an in-place change only; removing a limit is refused (edit the container to recreate it) |
| `docker exec [options] <container> [<command...>]` | exec | options `-i`, `-t`, `-it`, `--interactive`, `--tty`, `--user`/`-u`, `--workdir`/`-w`, `--timeout <s>`, `--host` go BEFORE the container (as in the docker CLI); everything after the container is the command, flags included, taken from the raw line and split like a shell line: `docker exec web ls -la /`, `docker exec -u root web sh -c "echo a; exit 3"`. Output: stdout, then stderr (warning); the command's exit code |
| `docker images`, `docker images prune [--all] [--yes]` | read; admin | |
| `docker pull <image>` | manage | progress until done |
| `docker rmi <image...> [--force] [--yes]` | admin | asks first |
| `docker stacks`, `stacks show <name>` | read | the compose file is shown when it can be read; a folder with a compose file and no containers is listed as `down` |
| `docker stacks start\|stop\|restart\|pull <name>` | manage | |
| `docker stacks up <name> [--file <path>] [--pull]` | admin | compose up; a progress block labelled with the last output line, the log as a code block when it fails |
| `docker stacks down <name> [--volumes] [--yes]` | admin | asks first |
| `docker stacks rm <name> [--yes]` | admin | deletes the compose file of a stack that is down; asks first |
| `docker compose ...` | | `compose` is an alias of `stacks` (`docker compose up shop`) |
| `docker volumes`, `volumes inspect <name>` | read | |
| `docker volumes create <name> [--driver <d>]`, `rm <name...> [--force] [--yes]`, `prune [--yes]` | admin | |
| `docker networks`, `networks inspect <name>` | read | |
| `docker networks create <name> [--driver <d>] [--internal] [--subnet <cidr>]`, `rm <name...> [--yes]`, `prune [--yes]` | admin | |
| `docker system info`, `system df`, `system events [--since <1h>] [--follow]` | read | |

## Creating and editing containers

`docker:admin` only, refused in read-only mode, audited (`docker.container.create`, `docker.container.update`; properties
`{ host, image, recreated }`, never the spec: its env can hold secrets). Docker cannot change most of a container's
configuration in place, so an **edit recreates the container under the same name** (its volumes are kept), except for the
few settings the engine updates in place.

**ContainerSpec** (the body's `spec`): `name`, `image` (required; no tag means `:latest`), `command`, `entrypoint` (`[""]`
clears the image's), `workdir`, `user`, `hostname`, `domainname`, `env` (`NAME=value`, 200 at most), `labels` (100 at most;
`com.docker.compose.*` is reserved), `tty`, `openStdin`, `ports` (`{ private, public?, ip?, type? }`), `publishAll`, `mounts`
(`{ type: volume|bind|tmpfs, source?, destination, readOnly?, tmpfsSizeBytes? }`), `networkMode`, `networks`
(`{ name, aliases?, ipv4Address?, ipv6Address? }`: the first one, or the one `networkMode` names, is used at create, the
others are connected before the start), `dns`, `dnsSearch`, `dnsOptions`, `extraHosts`, `restartPolicy`, `maxRetries`,
`memoryBytes` (0 or at least 6 MB), `memoryReservationBytes`, `memorySwapBytes`, `cpus`, `cpuShares`, `cpusetCpus`,
`pidsLimit`, `shmSizeBytes`, `ulimits`, `healthcheck` (`{ test, intervalSeconds?, timeoutSeconds?, startPeriodSeconds?, retries? }`),
`stopSignal`, `stopTimeoutSeconds`, `init`, `readOnlyRootfs`, `autoRemove`, `logDriver`, `logOptions`, `sysctls`, `capAdd`,
`capDrop`, `privileged`, `devices`, `securityOpt`, `pidMode`, `ipcMode`, `usernsMode`, `cgroupnsMode` and `platform` (create
only). An unknown field is 400 `unknown field <name>`; `null` counts as missing. Nothing but what the spec sets is sent to
the engine's create call.

- `GET /admin/containers/{id}/spec` returns what a person would have written: only the fields that differ from the image's
  or the engine's defaults. Secret-like env values are `••••••`; sending `NAME=••••••` back keeps the container's value
  (a name it does not have: 400 `env <NAME> has no value to keep`). Anonymous volumes come back with their volume name as
  `source`, so an edit keeps their data. `editable` is false with a `reason` for a protected container and for one that
  belongs to a compose stack (`container <name> belongs to stack <stack>; change the stack's compose file`).
- Create: pull as asked (`pull`: `missing` (default), `always`, `never`: with the image missing it fails `image <image> is not on host <host>`),
  create, connect the other networks, start when `start` (default true). A failed start leaves the created container (as
  `docker run` does): the operation fails with the engine's message and carries `result.container`.
- The spec of an edit is the whole desired state of the fields a ContainerSpec has: a field left out means the image's or the engine's default (a limit is removed, `command` is the image's), and an explicit `0`, `""`, `false` or `[]` means the same; only settings a spec cannot express are kept from the container. An existing bind mount (same source and destination) is kept without the `bindMounts` check. Health check durations may be fractional seconds (nanoseconds, rounded down).
- Edit: when only `restartPolicy`, `maxRetries`, `memoryBytes`, `memoryReservationBytes`, `memorySwapBytes`, `cpus`,
  `cpuShares`, `cpusetCpus` and `pidsLimit` differ, the engine's update call runs (no restart; message `updated in place`).
  Otherwise the container is recreated: the new one is made as `<name>-next-<6 hex>` from the old one's whole configuration with
  the spec's fields applied (what the spec does not express, set by another tool, is kept), its other networks connected,
  the old one stopped when it was running and renamed `<name>-old-<6 hex>`, the new one renamed and started, the old one
  removed (without its volumes). A failure after the old one was stopped or renamed puts it back (the new one is removed,
  the old one renamed back and started when it was running) and the operation fails with `<engine message>; the old container was restored`.
  The id changes; `result.container` is the new container (the restored one after a restore).
- Checked before the operation starts (the answer is the error, no operation): the spec (400), `bindMounts` and
  `allowPrivileged` (400), a name or labels that a `hide` or `protect` pattern would match (409 `container <name> would be hidden or protected`), an existing container
  with the new name (409 `a container named <name> already exists`), an unknown network (404 `no such network: <name>`), a hidden (404), protected (409) or stack (409) container being edited.
- Rules found in review (create and edit alike):
  - `autoRemove`: an edit that needs a recreate is 409 `container <name> removes itself when stopped (autoRemove); it cannot be recreated` (the engine would remove the old container when it stops); an in-place edit still works.
  - `networkMode`, `pidMode` and `ipcMode` of the form `container:<x>` resolve `<x>` through the visible list: hidden or unknown is 404 `no such container: <x>`, protected 409 `container <name> is protected`; a target that is privileged or uses a host namespace needs `allowPrivileged`. A value the container already has is kept on an edit.
  - A volume used by a hidden container is 404 `no such volume: <source>`; one used by a protected container may only be mounted read-only (409 `volume <source> belongs to protected container <name>`). Mounts a container already has are kept on an edit.
  - A container that already has `allowPrivileged` fields needs the setting to change its `image`, `command`, `entrypoint` or `user` (400 `<field> needs the allowPrivileged setting`).
  - A create refuses `NAME=••••••` (400 `env <NAME> has no value to keep`); an edit keeps the value.
  - The spec read leaves out `hostname` and `domainname` when the network mode is `host` or `container:*`. `stopTimeoutSeconds` is 0 to 2147483647; durations take Go's compound form (`1m30s`, `1h2m`, `2m500ms`).
  - While a create or update runs, its names (the container, `-next-`, `-old-`, the ids) are locked: actions, `rm`, `exec` (and the exec socket), stack actions and prune answer 409 `container <name> is being updated`. Reading the new container back is part of the swap (a failure restores the old one); a paused container is paused again after a recreate or a restore. If the server stops in the middle of a recreate, the `<name>-next-<hex>` and `<name>-old-<hex>` containers stay for an operator to clean up.
- Rules found in the second review:
  - A network named `host` (in `networks`, or the host network's id) is `networkMode` host: it needs `allowPrivileged` (400 `networkMode needs the allowPrivileged setting`).
  - `container:` chains are followed up to 5 steps (a chain that is longer counts as powerful); the powers of every container on the way count as the container's own, also for the edit rule.
  - A container that already has any power `allowPrivileged` gates (its own or through a `container:` target) needs the setting for every edit that recreates it (`<first changed field> needs the allowPrivileged setting`); in-place updates stay free.
  - `PUT /admin/containers/:id` itself is checked against the name lock (409 `container <name> is being updated` for the old, new, `-next-` and `-old-` container, by name or id).
- Rules found in the third review (containers): the existing powers of a container for the edit rule also include `DeviceCgroupRules`, `DeviceRequests`, `UTSMode` host, a `Runtime` other than the default, `CgroupParent`, `GroupAdd` and bind mounts outside `bindMounts`; within one spec no bind may lie inside the source of another read-write bind (400 `bind mount <source> lies inside the read-write bind <other>`).
- Residual: a container created with a read-write bind of a `bindMounts` folder can swap folders that another stack or container binds inside it, because the plugin cannot see what writers do on the host. List in `bindMounts` only folders whose writers you trust.
- One container name has at most one running create or update (409 `container <name> is already being updated`); they count towards the 5 running operations.
- `docker run` / `docker create` options, as the Docker CLI spells them: `--name`, `-p`/`--publish [ip:][public:]private[/proto]`,
  `-P`, `-e`/`--env`, `-l`/`--label`, `-v`/`--volume source:destination[:ro]` (a source starting with `/` is a bind, else a volume;
  a lone destination is an anonymous volume), `--mount type=…,source=…,target=…[,readonly]`, `--tmpfs destination[:size=<n>]`,
  `--network` (repeatable: the first is the mode or the first network), `--network-alias`, `--ip`, `--ip6`, `--dns`, `--dns-search`,
  `--dns-option`, `--add-host`, `--restart policy[:n]`, `-m`/`--memory`, `--memory-reservation`, `--memory-swap`, `--cpus`,
  `--cpu-shares`, `--cpuset-cpus`, `--pids-limit`, `--shm-size`, `--ulimit name=soft[:hard]`, `--health-cmd`, `--health-interval`,
  `--health-timeout`, `--health-start-period`, `--health-retries`, `--no-healthcheck`, `--stop-signal`, `--stop-timeout`, `--init`,
  `--read-only`, `--rm`, `--log-driver`, `--log-opt`, `--sysctl`, `--cap-add`, `--cap-drop`, `--privileged`, `--device`, `--security-opt`,
  `--pid`, `--ipc`, `--userns`, `--cgroupns`, `--platform`, `-w`, `-u`, `-h`, `--domainname`, `--entrypoint` (one word), `-t`, `-i`
  (sets `openStdin`; the terminal does not attach, `docker exec -it` does), `-d` (accepted, always detached) and `--pull missing|always|never`.
  Sizes take `b`, `k`, `m`, `g` (1024-based), durations `ms`, `s`, `m`, `h`. `--env-file` is 400 `--env-file is not supported`; any other
  option is 400 `unknown option <option>`. There are no structured MCP tools for creating or editing (the commands are tools like every command).

## Compose

Stacks can be created, updated and removed from their compose file. This runs the `docker compose` CLI on the machine
the server runs on (the Engine API cannot do it), so **the CLI must be installed there**, for example in the server's own
container image, and the files must be under `composeRoots`: no root, no compose feature (every route answers 409 with the
text of `GET /compose`).

- Settings: `composeRoots` (the only folders files are read from, written to and run from; absolute paths only),
  `composeCommand` (default `docker compose`; `docker-compose` works, except on a TLS host) and `composeTimeoutSeconds` (900).
- Compose runs on the server's machine and **resolves `env_file`, build contexts, file secrets and `include`s on the server's disk**
  (and sends them to the engine), so compose is on for the host `local` only unless `composeHosts` lists more hosts.
- The file of stack `<name>` is the first of: the stack's `com.docker.compose.project.config_files` label (when the host is
  a unix socket and it passes the checks of the roots), `<root>/<name>/compose.yaml`, `compose.yml`, `docker-compose.yml`,
  `docker-compose.yaml` (the folder `<root>/<name>` must be a real folder directly under the root, not a link). Every path is
  checked the same way: absolute, `.yml`/`.yaml`, real path under a root, regular file, at most 256 KB. A folder directly
  under a root with one of those files and a valid name (`^[a-z0-9][a-z0-9_-]{0,62}$`) is a stack even without containers:
  it is listed with the state `down` (at most 200 folders per root); a project that has containers, hidden ones too, is never
  `down`, and a project whose containers are all hidden does not exist (`GET /stacks/<name>` is 404).
- `PUT .../compose` checks the content with `<composeCommand> --project-name=<name> --file=<temp file in the same folder> config --quiet`
  (a failure is 400 with compose's message, the temp file's path replaced by `compose.yaml`; nothing changes), then renames
  the temp file over the target: the existing file (it keeps the file's mode; a new file is 0644), or
  `<first existing root>/<name>/compose.yaml` (the folder is created, and removed again when the write fails). The target and
  its folder are never links.
- Rules for the file: after `config --quiet`, `PUT .../compose` and every `up` run `<composeCommand> -p <name> -f <file> config --format json` and check each service like a container spec: `privileged`, `cap_add`, `devices`, `security_opt`, `network_mode`/`pid`/`ipc`/`userns_mode`/`cgroup` `host` need `allowPrivileged` (400 `service <s>: <field> needs the allowPrivileged setting`); `container:` modes and `volumes_from` containers are resolved like references (404 hidden/unknown, 409 protected) and `service:` modes are free; bind sources must be under `bindMounts` or the stack's own folder (400 `service <s>: bind mount <path> is outside the allowed folders`); volumes follow the volume rules above; `container_name` (or the default `<project>-<service>-1`) and labels must not match `hide`/`protect` (409 `service <s>: container <name> would be hidden or protected`). A refused write changes nothing; a refused `up` starts nothing and creates no operation (audited). `stop`, `start` and `down` still work.
- Second review, compose: more fields need `allowPrivileged` (`device_cgroup_rules`, `uts: host`, `runtime`, `cgroup_parent`, `gpus`, `deploy.resources.reservations.devices`; a compose network named `host` or the host network's id is `network_mode`; a top-level volume with `driver_opts` or a driver other than `local`: 400 `volume <name>: driver options need the allowPrivileged setting`). Top-level `secrets` and `configs` with `file` are bind mounts (400 `secret <name>: file <path> is outside the allowed folders`, `config <name>: ...`). The stack's own folder is a bind root only when the file's real folder is exactly `<root>/<name>` and the host is `local`; a source is resolved with its real path on the server, must exist and stay under the folder (or `bindMounts`). `build`: the context and every `additional_contexts` path must be under the stack's own folder (400 `service <s>: build context <path> is outside the stack folder`; `service:` and `docker-image://` contexts are fine), and `build.ssh`, `build.secrets`, `build.entitlements`, `build.privileged`, `build.network: host` are 400 `service <s>: build.<field> is not allowed` (also with `allowPrivileged`). `volumes_from: container:<x>` is refused when `<x>` has a bind outside the allowed folders or any power the setting gates (400 `service <s>: volumes_from <x> needs the allowPrivileged setting`). Replicas: `<project>-<service>-<n>` for n up to `scale` or `deploy.replicas` (100 at most) are checked against hide and protect.
- Third review, compose: the file is checked against the keys that are allowed (`compose_rules.py`): top level `name`, `services`, `networks`, `volumes`, `secrets`, `configs` (and inert `x-` extensions; anything else is 400 `<key> is not supported`), the service keys compose's `config` writes for ordinary services, the `build` keys (`cache_from`/`cache_to` only of the registry type) and the `networks`/`volumes` entry keys. Any other service key (`use_api_socket`, `provider`, `models`, `isolation`, `group_add`, future keys, a hook with `privileged: true` reported as `post_start`/`pre_stop`, `deploy.<unlisted>`) is 400 `service <s>: <key> needs the allowPrivileged setting`; `build.<key>` outside the list is 400 `service <s>: build.<key> is not allowed` (also with `allowPrivileged`); a network with `driver_opts` or a driver other than `bridge` is 400 `network <name>: driver options need the allowPrivileged setting`. A second `config --format json --no-env-resolution` (compose 2.24 or newer, else 409 `compose <version> is too old (2.24 or newer)`) keeps `env_file`, `label_file` and `build.dockerfile` as paths: each must resolve under the stack's own folder (400 `service <s>: <key> <path> is outside the stack folder`). The stack folder itself is never a bind source (400 `service <s>: bind mount <source> would expose the stack folder`) and no bind of the stack lies inside another read-write bind of it. A compose error in a 400 is its first line, 300 characters at most.
- Fourth review, one resolution checked and run: the plugin runs `config --format json --no-env-resolution` once on the stack's file and checks the paths in it (`env_file`, `label_file`, `build.dockerfile`, build contexts); it then inlines what `up` would read again (each `label_file` merged into `labels` and removed, explicit labels win; the Dockerfile read through its real path, 1 MB at most, into `build.dockerfile_inline` with `dockerfile` removed; 400 `service <s>: build.dockerfile <path> is not a file of 1 MB or less`), writes that to a private file and runs `config --format json` on it (`--project-directory=<stack folder> --env-file=/dev/null`: it reads only the env files that were checked), runs every key check on that output and writes it to a second private file: `up` runs exactly that (`--project-name=<name> --file=<second file> --project-directory=<stack folder> --env-file=/dev/null up -d --remove-orphans`), so changing the compose file, `.env`, an env file, a label file, a Dockerfile or an included file after the check changes nothing. Verified with Docker Compose v5.7.1 (parse only): `env_file` paths in the private file are read and merged into `environment`, `labels` and `dockerfile_inline` survive, and the original files are not needed again. Files the plugin reads for a stack (Dockerfile, label files, env files) are opened with `O_NOFOLLOW`, checked on the open file (regular, 1 MB at most), their real path is checked again under the stack folder and against the open file's device and inode, and they are read from that open file. Text put into `dockerfile_inline` and `labels` has every `$` doubled (compose interpolates the private file again and prints the escaped form, which `up` reads once more, so the text arrives literal; verified with `docker compose config`); env files are copied into the private folder and `env_file` points at the copies. The private files live in `<dataDir>/plugin-data/docker/tmp/c-<random>` (0700; files 0600), never the system temporary folder (without a data folder: a fresh 0700 `qcli-docker-<random>` straight under it; a data-folder `tmp` that the server's user does not own is refused), and are removed afterwards.
- Build contexts, `additional_contexts` and secret/config files must not lie inside a read-write bind source of the stack (400 `service <s>: build context <path> lies inside the read-write bind <outer>`, `secret <name>: file <path> lies inside the read-write bind <outer>`, `config <name>: ...`). Logging: without `allowPrivileged` only the drivers `json-file`, `local`, `journald` and `none` (400 `service <s>: logging driver <driver> needs the allowPrivileged setting`; a spec's `logDriver`: 400 `logDriver <driver> needs the allowPrivileged setting`; kept when the container already has it). Annotations starting `run.oci.` or `io.containerd.`: 400 `service <s>: annotation <key> needs the allowPrivileged setting`. An external compose network, or a spec network (by name or id), whose engine driver is not `bridge` or `overlay` (the built-in `none` excepted): 400 `network <name>: driver <driver> needs the allowPrivileged setting`. A `bindMounts` entry that covers the server's data folder is ignored and logged.
- `POST .../up` is an operation of kind `stack-up` (`--project-name=<name> --file=<real path> up -d --remove-orphans`,
  `--pull always` with `pull`, in the file's folder, killed at `composeTimeoutSeconds`). `file` only serves a stack with no
  file by the rule. Its `log` holds the last 200 lines of the CLI's output (stdout and stderr merged, ANSI codes stripped,
  lines cut at 2000 characters); `message` is the last line. The `log` and `message` of a `stack-up` are shown only to
  `docker:admin` (`GET /operations`, `GET /operations/{id}` and the `docker:operation` event, personalised per socket; the
  others get `log: []` and no `message`), because compose output can quote values. One stack has at most one running `up`
  (409), it counts towards the 5 running operations, and `down`, a write and a delete of that stack are 409
  `stack <name> is already being updated` meanwhile. At most 5 other compose processes (checks, `down`) run at once.
  `down` with a file is `compose down` (`--volumes` with `volumes`), 120 s, 504 on timeout; `volumes` without a file is 400
  `volumes needs a compose file`.
- The CLI is started without a shell from an argument list, with the host's connection always as docker's global flags, the
  default socket included (`--host`, `--tlsverify --tlscacert --tlscert --tlskey`; `docker-compose` gets `DOCKER_HOST`), so a
  docker context or `DOCKER_HOST` of the server can never pick another engine. Its environment is minimal: `PATH`, `HOME`,
  `USER`, `LANG`, `TMPDIR`, the names in `composeEnv`, and `COMPOSE_INTERACTIVE_NO_CLI=1`, `COMPOSE_MENU=false`, `NO_COLOR=1`.
  Its output is never interpreted, only shown. The running processes are killed (with their process group) at the time limit
  and when the plugin stops. The audit of a failed write or `up` says `compose exited with code <n>`, never compose's message.
- `up` and compose `down` are refused (409) when the stack has a protected container (`container <name> is protected`) or
  a hidden one (`stack <name> has containers this plugin may not change`). Changes are audited (`docker.stack.up`,
  `docker.stack.down`, `docker.stack.compose.write`, `docker.stack.compose.remove`; the content is not recorded).
- The demo reads `QCLI_DOCKER_COMPOSE_ROOTS` (comma separated).

## MCP tools

The commands are MCP tools like every command (with their permissions); besides them the provider `docker` offers
structured tools returning the REST shapes: `docker_list_containers`, `docker_inspect_container`, `docker_logs`,
`docker_stats`, `docker_list_images`, `docker_list_stacks`, `docker_system_info` (`docker:read`, read-only hint),
`docker_start`, `docker_stop`, `docker_restart` (`docker:manage`) and `docker_exec` (`docker:exec`, destructive hint).
The structured provider has no remove or prune tool.

## Rules that hold for routes, commands, the socket and MCP alike

- Sign-in: the Docker socket is root-equivalent, so unless `allowUnprotected` is on a call without a signed-in caller (a
  server that is not protected) is refused everywhere: routes 403 `the Docker plugin needs a protected server (sign-in);
  see its allowUnprotected setting`, commands the same text after `Error: `, MCP tools the same error, the exec socket
  closes 4401 `login required`. The check is one method of the service, `assert_caller`, called once per call.
- `readOnly` refuses every change, including exec and creating or editing containers. Hidden containers do not exist. Protected containers can be read but
  not changed (actions, rm, exec, prune, stack actions on them).
- Every change is recorded in the server's audit log when it has one: event `docker.<object>.<action>`
  (`docker.container.restart`, `docker.image.pull`, `docker.exec.run`, `docker.exec.session`, `docker.stack.down`,
  `docker.volumes.prune`, `docker.container.create`, `docker.container.update`, ...), `target` `docker:<host>/<kind>/<name>`, `properties` `{ host, ... }`; the command of an exec
  is recorded, its output is not; failures carry `properties.error`, and so do changes refused by read-only mode or
  protection (hidden containers do not exist, so they leave no entry).
- A protected container, running or not, refuses `stacks down` of its stack whole; with hidden containers in the stack,
  `stacks down` leaves them and the stack's networks alone. `networks prune` is done by the plugin (not the engine's
  prune): it removes the unused custom networks and leaves those a hidden or protected container is attached to.
- Hidden containers also stay out of events: an event of another type that names one in its attributes is dropped.
- The exec socket's `exit` message carries the exec's real exit code; the exec of a client that leaves while the session
  starts is ended. An open exec session ends (close 4401 `permission removed`) when its user loses `docker:exec`, and with 4401
  `session ended` when its session ends (logout, revoke, expiry, user disabled); re-checked on every change and every 30 s
  like the shell socket.
- A stack's compose file is the first of the label `com.docker.compose.project.config_files` (only on a unix socket host and
  only when it passes the checks of `composeRoots`) and the file of the root's sub-folder (see Compose). The label is
  written by whoever created the container, so it is never trusted; anything that fails a check is `composeFile: null`.
- Cross-site: with `allowUnprotected`, a change by a caller without a principal (any route but GET, HEAD and OPTIONS, and the exec socket) that carries an `Origin` whose host:port differs from the request's `Host` is refused: 403 / close 4403 `cross-site requests are refused` (an absent Origin passes, `null` counts as cross-site). A principal always needs `docker:exec` on the exec socket, also on a server that is not protected.
- The `log` and `message` of a `stack-up` go to `docker:admin`, and to a caller without a principal only with `allowUnprotected`.
- A timed-out one-off exec (`504`) may keep running in the container: the Engine API cannot kill an exec.
- Pulls: at most 5 run at once (`409 too many operations are running (5 at most)`); a pull whose connection drops or that
  receives nothing for 120 s fails. `GET /stats` takes at most 100 ids (`400 too many ids (100 at most)`) and samples at
  most 10 containers at a time. A log line longer than 16 KB is cut and ends with `…`.
- Error texts never contain file-system paths of TLS files: an unreadable one is `cannot read the TLS files of <host>`.
- Nothing the plugin answers contains TLS key paths, registry credentials or unmasked secret-like environment values
  (names containing password, passwd, secret, token, key, credential or auth show `••••••`).

## Console page

The page is the Console module `@qodalis/console-module-docker` (group Operations, `docker:read`, with an Overview card),
embedded into the wheel by `scripts/copy_console.py` and served at `/qcli/modules/docker`; `set_console_dir(False)` leaves
it out (as does a build without the module: the plugin works without the page).

## Engine client

The plugin talks to the Engine API with a small HTTP/1.1 client on `asyncio` streams (unix socket, TCP, TLS; chunked
streams and the connection upgrade of an exec), not with `aiodocker` or `httpx`: it has no dependency besides FastAPI, and
the streams it needs (logs, events, pulls, a hijacked exec) are controlled byte by byte.

## Tests

`tests/test_docker_*.py` of the server run against a fake Engine API (`tests/docker_fake_engine.py`) fed from
`fixtures/engine/*.json`; `fixtures/README.md` says which engine request maps to which file. The expected `/execute`
answers (`fixtures/expected/commands.v2.jsonl`, `commands.v1.jsonl`) and REST answers (`fixtures/expected/rest/*.json`)
are copied from the Node server (its generator writes them); the Python tests (`tests/test_docker_expected.py`) must
produce the same, byte for byte for the commands.
