Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(docker): add a one-container self-hosting image
trohitg3b4c452a865c
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 00000000..c3453e4e--- /dev/null+++ b/.dockerignore@@ -0,0 +1,65 @@+# Build context for docker/Dockerfile. The image builds everything from+# source, so keep local state, secrets, VCS metadata and build output out of it+# (Docker does not read .gitignore).++# VCS and tooling state. Leaving out .git also stops Claude Code / Codex agent+# runs inside the container from branching worktrees off the app's own source.+.git+.agents+.claude+.tmp+.uv-cache+.ruff_cache+.pytest_cache+.pytest-tmp-*+**/__pycache__+MagicMock+test-temp-v2+media+import.json+**/*.log++# Env files: a local .env may hold real keys. Only the template ships.+**/.env+**/.env.*+!.env.template++# Keys and credential files (the same patterns .gitignore keeps out).+**/*.pem+**/*.key+**/*.crt+**/*.p12+**/*.pfx+**/credentials.json+**/secrets.json+**/apikeys.json++# Build output and environments; the image rebuilds them.+**/node_modules+**/.venv+.cli-venv+client/dist+server/nodejs/dist+*.tgz++# The Electron shell is not part of the server image.+desktop++# Terraform providers and state (state files carry secrets).+**/.terraform+**/*.tfstate*+**/*.tfvars*++# Local runtime data, including SQLite's side files and the data dirs a local+# DATA_DIR may point at (data/, the pre-rebrand .machina/). Keep only the+# git-tracked seed workflows.+**/*.db+**/*.db-journal+**/*.db-shm+**/*.db-wal+**/*.sqlite+**/*.sqlite3+.opencompany/*+!.opencompany/workflows+.machina+datadiff --git a/.gitattributes b/.gitattributesindex b6f3a321..fce745de 100644--- a/.gitattributes+++ b/.gitattributes@@ -6,6 +6,7 @@ bin/cli.js text eol=lf*.sh text eol=lf*.tftpl text eol=lf*.service text eol=lf+docker/Dockerfile text eol=lf# Signed brand assets (C2PA manifest over the exact bytes): never normalise# line endings, or the signature and the pinned sha256 indiff --git a/CLAUDE.md b/CLAUDE.mdindex 03a3ecf5..57d4fc54 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -82,6 +82,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Memory Lifecycle](./docs-internal/ARCHIVE/memory_lifecycle.md)** | *Archived — pre-RFC-0002.* Documented the retired `input-memory` markdown model. See "Context and Memory (RFC-0002)" below, [Agent Context Flow](./docs-internal/agent_context_flow.md) and [Memory Compaction](./docs-internal/memory_compaction.md). || **[Node Parameter Panel](./docs-internal/node_panels.md)** | Three-section node config UI (Input / Parameters / Output) logic-flow reference. || **[Deployment (legacy reference)](./docs-internal/deployment_legacy.md)** | `company deploy` CLI summary + the historical Docker Compose topology. |+| **[Docker (self-hosting)](./docs-internal/docker.md)** | One-container image built from source (`docker/Dockerfile`, `docker-compose.yml`). The build stage runs the canonical `bun install --frozen-lockfile` + `bun run build` (then `uv sync --no-dev`); the runtime stage keeps only what `core/approot.py` reads. uvicorn runs directly, the way the desktop shell runs it (never `company serve`, whose supervisor kills the backend 5 s after SIGTERM and can skip the clean-shutdown record). All state on one `/data` volume; secrets minted on first start into `OPENCOMPANY_ENV_FILE=/data/opencompany.env`; Temporal embedded (CLI pre-seeded through named-volume copy-up); no Redis; no Node (`/usr/local/bin/node` links to bun). Optional system tools come only through the `EXTRAS` build arg (`browser`: Chromium + Xvfb + uv; `git`). Compose publishes the port on `127.0.0.1` only, because `/ws/internal` runs nodes without a login. || **[GCP VM Deploy Runbook](./docs-internal/gcp_vm_deploy_runbook.md)** | Manual gcloud + Cloudflare runbook for deploying the released `@zeenie-ai/opencompany` tarball with `bun add -g` (non-Terraform path). |## Design Principles & Standards@@ -805,7 +806,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.✅ **Node Rename System**: n8n-style node renaming via F2 keyboard shortcut, double-click on label, or right-click context menu with inline editing✅ **UI State Persistence**: localStorage persistence for sidebar visibility, component palette visibility, dev mode, and collapsed sections✅ **Normal/Dev Mode**: Normal mode (Home: hire and supervise AI employees) is the landing screen; the Normal/Dev switch in the editor toolbar and the Home header (or Ctrl/Cmd+Shift+D) moves to Dev mode, the workflow editor. `VITE_NORMAL_MODE=false` restores the old palette-filter toggle-✅ **Production Deployment**: `company deploy` provisions a login-gated VM via Terraform + cloud-init running `company serve` under systemd; the Docker Compose topology was removed (see [deployment_legacy.md](./docs-internal/deployment_legacy.md))+✅ **Production Deployment**: `company deploy` provisions a login-gated VM via Terraform + cloud-init running `company serve` under systemd; `docker compose up -d --build` runs a one-container self-hosting image built from source (see [docker.md](./docs-internal/docker.md)); the old 4-container Docker Compose topology was removed (see [deployment_legacy.md](./docs-internal/deployment_legacy.md))✅ **Authentication System**: n8n-style JWT authentication with HttpOnly cookies, single-owner and multi-user modes, rate-limited login. Note `AUTH_MODE=multi` authenticates but does NOT isolate data — see Known Limitations in [authentication.md](./docs-internal/authentication.md)✅ **Cache System**: n8n-pattern cache with Redis (production) / SQLite (local dev) / Memory fallback hierarchy✅ **AI Thinking/Reasoning**: Extended thinking for Claude, Gemini 2.5/3, OpenAI GPT-5/GPT-6/o-series, Groq Qwen3 with output available in Input Data & Variables for downstream nodes@@ -1214,8 +1215,11 @@ Terraform replacement or strand live state. Fresh deployments use `opencompany`.The `machina` executable remains only as a deprecated legacy alias; use `company`for all new commands and automation.-The legacy `deploy.sh` (docker-compose images over SCP to a GCE box) was removed. The Docker-Compose notes below are retained for reference for the historical container topology.+The legacy `deploy.sh` (docker-compose images over SCP to a GCE box) was removed.++### Docker (self-hosting)++`docker compose up -d --build` builds a single image from source and runs it with all state on one named volume. The image runs the backend the way the desktop shell does (uvicorn directly, env file on the data volume, readiness on `/health/ready`), not through `company serve`. Full guide: **[docker.md](./docs-internal/docker.md)**.### Docker Deployment (legacy reference)@@ -2712,9 +2716,7 @@ This function:- Supports TTL expiration and automatic cleanup of expired entries- **Conditional Redis (historical)**: the Docker Compose topology (Redis profiles, `scripts/docker.js` wrapper) is historical — see [docs-internal/deployment_legacy.md](./docs-internal/deployment_legacy.md)- **WebSocket Reconnect via PartySocket** (`partysocket/ws` from Cloudflare): native-WS-compatible class handles jittered exponential backoff, message replay (`maxEnqueuedMessages: 200`), and intentional-close (RFC 6455 §7.4.1 code 1000) automatically. Replaces the previous flat 3 s `setTimeout(connect, 3000)` loop. Reconnect envelope (`MIN_DELAY_MS: 250`, `MAX_DELAY_MS: 8000`, `GROW_FACTOR: 1.3`) lives in `client/src/lib/connectionConfig.ts`. The +12 s WS-drop-and-reconnect cycle observed under React Strict Mode is gone — verified across two consecutive cold launches with zero `Client disconnected` events through 130+ s of activity. See `docs-internal/performance.md` for measurements.-- **Docker Backend Fix**: Backend container uses Python uvicorn directly- - Changed from `npm run start` (failed - npm not in Python image) to `python -m uvicorn`- - CMD: `["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "3010"]`+- **Docker image runs uvicorn, not `company serve`**: `docker/entrypoint.sh` writes the three secrets into `/data/opencompany.env` once (the container env's value when set there, else a random one), then execs the desktop shell's uvicorn argv (`--timeout-graceful-shutdown 5`, port resolved through `core.env_defaults`). `company serve` would need root `node_modules` + the CLI venv, ignores `OPENCOMPANY_ENV_FILE`, and its supervisor tree-kills the backend 5 s after SIGTERM. `HOST` stays `127.0.0.1` (the backend dials itself at `ws://HOST:PORT/ws/internal`); the external bind is the `--host 0.0.0.0` argument. The image has no Node: `/usr/local/bin/node` links to bun, so the `#!/usr/bin/env node` bin scripts (agent-browser, vercel, cf) run. With the `browser` extra, Debian's `/usr/bin/chromium` launcher resets `CHROMIUM_FLAGS` from the environment and reads flags only from `/etc/chromium.d/` (hence the `no-sandbox` drop-in; Chrome refuses to run as root otherwise), and `AGENT_BROWSER_EXECUTABLE_PATH=/usr/bin/chromium` points agent-browser at it. The compose project is named `opencompany-selfhost` so it never merges with another compose project called `opencompany`. See [docker.md](./docs-internal/docker.md).- **Configurable Authentication**: `VITE_AUTH_ENABLED` environment variable- Set to `false` to bypass login entirely (useful for local development)- Frontend creates anonymous user with owner privileges when disableddiff --git a/README.md b/README.mdindex ceadb90b..fb522f39 100644--- a/README.md+++ b/README.md@@ -43,6 +43,19 @@ The script installs bun, Python and uv when they are missing, then the `@zeenie-</details>+<details>+<summary><b>Docker (self-hosting)</b></summary>++```bash+git clone https://github.com/zeenie-ai/OpenCompany.git+cd OpenCompany+docker compose up -d --build+```++Builds the image from source and starts one container, with all data in the `opencompany-selfhost_data` volume. Open http://localhost:5678 and register the owner account. The port is published on this machine only. See [docker.md](docs-internal/docker.md).++</details>+<details><summary><b>Run from source (contributors)</b></summary>diff --git a/cli/tests/test_release_pipeline_config.py b/cli/tests/test_release_pipeline_config.pyindex 0027ffe6..551497ca 100644--- a/cli/tests/test_release_pipeline_config.py+++ b/cli/tests/test_release_pipeline_config.py@@ -775,3 +775,42 @@ def test_desktop_release_refuses_a_version_that_does_not_match_the_tag(assert guard["if"] == "github.event_name == 'push'"assert guard["shell"] == "bash"assert "exit 1" in guard["run"]+++# ---------------------------------------------------------------------------+# Docker image — toolchain pins shared with CI and the desktop bundle+# ---------------------------------------------------------------------------+++def test_docker_image_pins_match_the_bun_and_uv_pins(root: Path, root_pkg: dict):+ """``docker/Dockerfile`` copies bun and uv out of their official images.+ Those tags repeat pins that live elsewhere: bun in the root+ ``packageManager`` (what CI's setup-bun reads) and uv in+ ``desktop/runtimes.json`` (the desktop bundle). A bump in one place must+ move the other, or the image builds with a different toolchain than CI+ and the desktop app.+ """+ dockerfile = (root / "docker" / "Dockerfile").read_text(encoding="utf-8")+ bun = re.search(r"^FROM oven/bun:(\d+\.\d+\.\d+)\S* AS bun$", dockerfile, re.MULTILINE)+ uv = re.search(r"^FROM ghcr\.io/astral-sh/uv:(\d+\.\d+\.\d+) AS uv$", dockerfile, re.MULTILINE)+ assert bun and uv, "docker/Dockerfile must copy bun and uv from pinned official images"++ assert f"bun@{bun.group(1)}" == root_pkg["packageManager"]+ runtimes = json.loads((root / "desktop" / "runtimes.json").read_text(encoding="utf-8"))+ assert uv.group(1) == runtimes["uv"]["version"]+++def test_docker_port_matches_the_template_port(root: Path):+ """``EXPOSE`` and the compose mapping repeat ``PORT`` from+ ``.env.template`` (the image resolves the real bind at start). A template+ change that left them behind would publish a port nothing listens on.+ """+ from cli.config import _load_env_file++ port = _load_env_file(root / ".env.template")["PORT"]+ dockerfile = (root / "docker" / "Dockerfile").read_text(encoding="utf-8")+ assert re.findall(r"^EXPOSE (\d+)$", dockerfile, re.MULTILINE) == [port]++ compose = yaml.safe_load((root / "docker-compose.yml").read_text(encoding="utf-8"))+ ports = compose["services"]["opencompany"]["ports"]+ assert [mapping.rsplit(":", 1)[1] for mapping in ports] == [port]diff --git a/docker-compose.yml b/docker-compose.ymlnew file mode 100644index 00000000..0be6cda2--- /dev/null+++ b/docker-compose.yml@@ -0,0 +1,44 @@+# Self-hosted OpenCompany: one container, all state in one named volume.+# docker compose up -d --build then open http://localhost:5678+# Guide: docs-internal/docker.md++# An explicit project name. Without it compose names the project after the+# checkout directory ("opencompany"), which can collide with another stack of+# that name and mix both in `docker compose ps` / `down --remove-orphans`.+name: opencompany-selfhost++services:+ opencompany:+ build:+ context: .+ dockerfile: docker/Dockerfile+ args:+ # Optional tools, space separated; the default image has none+ # (docs-internal/docker.md). Then rebuild: docker compose up -d --build+ # browser Chromium for the browser node, uv for browser-harness+ # git git for the Claude Code and Codex agent nodes+ EXTRAS: ""+ image: opencompany:local+ # Docker's init (tini) reaps the processes the backend spawns: the+ # Temporal dev server, the bun code sidecar and plugin daemons.+ init: true+ ports:+ # host:container. The container port is PORT in .env.template. Published+ # on this machine only: to serve other hosts, drop the 127.0.0.1 prefix+ # and put TLS in front (docs-internal/docker.md).+ - "127.0.0.1:5678:5678"+ volumes:+ - data:/data+ restart: unless-stopped+ # Room for the backend to drain its Temporal workers and record a clean+ # shutdown. A hard kill before that makes the next start pause every+ # running deployment.+ stop_grace_period: 120s+ # Optional: create the owner account on first start instead of+ # registering it in the browser.+ # environment:+ # OPENCOMPANY_OWNER_EMAIL: [email protected]+ # OPENCOMPANY_OWNER_PASSWORD: change-me-now++volumes:+ data:diff --git a/docker/Dockerfile b/docker/Dockerfilenew file mode 100644index 00000000..fbf1ff86--- /dev/null+++ b/docker/Dockerfile@@ -0,0 +1,136 @@+# OpenCompany self-hosting image. See docs-internal/docker.md.+#+# Build: the canonical cross-platform build, exactly as CI runs it+# (bun install --frozen-lockfile, then bun run build), in a+# throwaway stage.+# Run: a slim stage holding only what the backend reads at run time, run+# the way the desktop shell runs it: uvicorn directly, settings and+# secrets in an env file on the data volume, readiness on+# /health/ready.+#+# The default image carries no optional tools. EXTRAS adds them, space+# separated:+# browser Chromium, fonts and Xvfb for the browser node, and uv, which+# the browser-harness node installs itself with+# git git, for the Claude Code and Codex agent nodes (they work in git+# worktrees)+#+# From the repo root: docker compose up -d --build+# With extras: set EXTRAS under build.args in docker-compose.yml++# bun matches the root package.json "packageManager"; uv matches+# desktop/runtimes.json. cli/tests/test_release_pipeline_config.py keeps the+# three in step.+FROM oven/bun:1.4.0-slim AS bun+FROM ghcr.io/astral-sh/uv:0.12.13 AS uv++# ---------------------------------------------------------------------------+# build+# ---------------------------------------------------------------------------+# glibc Debian with Python 3.12 as both `python` and `python3` (the root+# package.json scripts call bare `python`). The venv built here links to this+# interpreter, so the runtime stage uses the same base image.+FROM python:3.12-slim-trixie AS build++COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun+COPY --from=uv /uv /usr/local/bin/++# The build fetches the Temporal CLI into DATA_DIR (company build step+# [6/6]); the runtime stage copies it into /data, so a new named volume starts+# with it (Docker copies the image's content into an empty named volume on+# first mount).+ENV DATA_DIR=/data++WORKDIR /app+COPY . .++# CI=true keeps the root install hooks inert, as on GitHub runners+# (scripts/preinstall.js, scripts/postinstall.js). company build syncs the+# venv with the dev group (pytest, ruff) for contributors; the second,+# --frozen sync removes it. The tests and the sidecar's TypeScript source+# stay behind in this stage.+RUN CI=true bun install --frozen-lockfile \+ && bun run build \+ && cd server \+ && uv sync --frozen --no-dev --extra docs \+ && rm -rf tests nodejs/src nodejs/node_modules++# Only the browser extra ships uv. Staged here because COPY has no condition;+# the runtime stage copies this directory whether or not it is empty.+ARG EXTRAS=""+RUN mkdir -p /extras/bin \+ && case " $EXTRAS " in *" browser "*) cp /usr/local/bin/uv /extras/bin/ ;; esac++# ---------------------------------------------------------------------------+# runtime+# ---------------------------------------------------------------------------+FROM python:3.12-slim-trixie++ARG EXTRAS=""++COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun+COPY --from=build /extras/bin/ /usr/local/bin/++# The image has no Node. npm CLIs whose bin scripts start+# `#!/usr/bin/env node` (agent-browser, vercel, cf) run on bun under that+# name, as in the official oven/bun images.+RUN ln -s /usr/local/bin/bun /usr/local/bin/node++# browser: Debian's /usr/bin/chromium launcher takes extra flags only from+# /etc/chromium.d/ (it resets CHROMIUM_FLAGS from the environment) and+# already adds --disable-dev-shm-usage when /dev/shm is small; the drop-in+# adds --no-sandbox, without which Chrome refuses to run as root. The+# browser node runs headed by default and agent-browser starts a private Xvfb+# display when DISPLAY is unset.+RUN set -eu; \+ pkgs=""; \+ for extra in $EXTRAS; do \+ case "$extra" in \+ browser) pkgs="$pkgs chromium fonts-liberation xvfb" ;; \+ git) pkgs="$pkgs git" ;; \+ *) echo "unknown EXTRAS entry: $extra (known: browser git)" >&2; exit 1 ;; \+ esac; \+ done; \+ if [ -n "$pkgs" ]; then \+ apt-get update; \+ apt-get install -y --no-install-recommends $pkgs; \+ rm -rf /var/lib/apt/lists/*; \+ fi; \+ if [ -d /etc/chromium.d ]; then \+ echo 'export CHROMIUM_FLAGS="$CHROMIUM_FLAGS --no-sandbox"' > /etc/chromium.d/no-sandbox; \+ fi++# What the backend reads at run time (core/approot.py): the server tree with+# its venv, the built UI, the env template, the version, the seed workflows.+# The sidecar bundle is server/nodejs/dist and needs no node_modules.+WORKDIR /app+COPY --from=build /app/.env.template /app/package.json ./+COPY --from=build /app/.opencompany/workflows .opencompany/workflows+COPY --from=build /app/client/dist client/dist+COPY --from=build /app/docker/entrypoint.sh docker/entrypoint.sh+COPY --from=build /app/server server+COPY --from=build /data /data++# Runtime settings; everything else keeps its .env.template default.+# HOME lives on the volume so CLI logins (gh, stripe, cf, codex) and caches+# survive upgrades. AGENT_BROWSER_EXECUTABLE_PATH points agent-browser at the+# system Chromium of the browser extra, which the browser node needs.+ENV DATA_DIR=/data \+ HOME=/data/home \+ OPENCOMPANY_ENV_FILE=/data/opencompany.env \+ DEPLOYMENT_MODE=self_hosted \+ VITE_AUTH_ENABLED=true \+ NODEJS_EXECUTOR_HOST=127.0.0.1 \+ NODEJS_USER_PACKAGES_DIR=/data/nodejs-user-packages \+ AGENT_BROWSER_EXECUTABLE_PATH=/usr/bin/chromium \+ PYTHONUNBUFFERED=1++WORKDIR /app/server++# The app port: PORT / PYTHON_BACKEND_PORT in .env.template.+EXPOSE 5678++HEALTHCHECK --interval=30s --timeout=5s --start-period=180s --retries=3 \+ CMD ["/app/server/.venv/bin/python", "-c", "import urllib.request; from core.env_defaults import env_value; urllib.request.urlopen('http://127.0.0.1:%s/health/ready' % env_value('PORT'), timeout=4)"]++ENTRYPOINT ["sh", "/app/docker/entrypoint.sh"]diff --git a/docker/entrypoint.sh b/docker/entrypoint.shnew file mode 100644index 00000000..0be337bd--- /dev/null+++ b/docker/entrypoint.sh@@ -0,0 +1,41 @@+#!/bin/sh+# OpenCompany container entrypoint. See docs-internal/docker.md.+#+# 1. Write SECRET_KEY, JWT_SECRET_KEY and API_KEY_ENCRYPTION_KEY into the env+# file on the data volume ($OPENCOMPANY_ENV_FILE) the first time they are+# missing, so they survive container recreation. API_KEY_ENCRYPTION_KEY must+# never change afterwards, or credentials.db can no longer be decrypted.+# A key already in the file is kept. A missing one takes the value from the+# container environment when set there (so dropping it from compose later+# changes nothing), otherwise a fresh random one. The environment still+# wins over the file at runtime.+# 2. Run the backend without the CLI supervisor: the uvicorn argv of+# cli/commands/serve.py and desktop/src/main/backend.ts, bound to 0.0.0.0+# so the published port reaches it. The port resolves through+# core.env_defaults, so .env.template stays its single source of truth.+set -eu++cd /app/server++mkdir -p "$HOME"+touch "$OPENCOMPANY_ENV_FILE"+chmod 600 "$OPENCOMPANY_ENV_FILE"+# A hand-edited file can lack its final newline; appending would then glue a+# key onto its last line.+[ -z "$(tail -c 1 "$OPENCOMPANY_ENV_FILE")" ] || echo >>"$OPENCOMPANY_ENV_FILE"+for key in SECRET_KEY JWT_SECRET_KEY API_KEY_ENCRYPTION_KEY; do+ # The line shapes core/env_defaults reads (`KEY=v`, ` KEY = v`); an empty+ # value counts as missing, and the line appended below then wins.+ grep -Eq "^[[:space:]]*$key[[:space:]]*=[[:space:]]*[^[:space:]]" "$OPENCOMPANY_ENV_FILE" && continue+ value=$(printenv "$key" || true)+ if [ -z "$value" ]; then+ # Its own assignment, so a failure stops the start under `set -e`+ # instead of writing an empty key.+ value=$(python -c 'import secrets; print(secrets.token_hex(24))')+ fi+ echo "$key=$value" >>"$OPENCOMPANY_ENV_FILE"+done++port=$(.venv/bin/python -c 'from core.env_defaults import env_value; print(env_value("PORT"))')+exec .venv/bin/python -m uvicorn main:app --host 0.0.0.0 --port "$port" \+ --log-level warning --timeout-graceful-shutdown 5diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.mdindex b4690915..0aacfae1 100644--- a/docs-internal/SCRIPTS.md+++ b/docs-internal/SCRIPTS.md@@ -138,9 +138,11 @@ The Temporal dev server is backend-owned: the FastAPI lifespan starts it via `Te(`serve-client.js` was retired July 2026: `company start` is single-port —the backend serves the built SPA itself via `SERVE_STATIC_CLIENT`.)-There is no Docker tooling: Docker Compose support was removed-(historical topology preserved in-[deployment_legacy.md](./deployment_legacy.md)); deployment is+Docker: `docker compose up -d --build` builds a one-container+self-hosting image from source (`docker/Dockerfile`,+`docker-compose.yml`); see [docker.md](./docker.md). No script or CLI+verb wraps it. The old multi-container topology is preserved in+[deployment_legacy.md](./deployment_legacy.md). Cloud VM deployment is`company deploy` (Terraform → GCP VM → systemd).---diff --git a/docs-internal/SETUP.md b/docs-internal/SETUP.mdindex 4bda67e4..52f99c8b 100644--- a/docs-internal/SETUP.md+++ b/docs-internal/SETUP.md@@ -202,9 +202,10 @@ When `VITE_AUTH_ENABLED=false` (the default):- API keys can be saved/retrieved without user authentication- Useful for local development and testing-**Redis (optional):** Set `REDIS_ENABLED=true` in `.env`-(Docker Compose tooling was removed; the historical topology is in-[deployment_legacy.md](./deployment_legacy.md).)+**Redis (optional):** Set `REDIS_ENABLED=true` in `.env`.++**Docker:** `docker compose up -d --build` runs a self-hosting image+built from source; see [docker.md](./docker.md).## Local Commandsdiff --git a/docs-internal/deployment_legacy.md b/docs-internal/deployment_legacy.mdindex 94e03c87..bca8bd93 100644--- a/docs-internal/deployment_legacy.md+++ b/docs-internal/deployment_legacy.md@@ -2,9 +2,10 @@This doc is the single home for OpenCompany deployment topology. The **current** path is the`company deploy` self-deploy CLI (top section). The **Docker Compose** path below it is a-**legacy reference only** — the compose files, `docker/` directory, and `scripts/docker.js`-wrapper have all been removed from the repo. It is retained solely as documentation of the-historical container topology.+**legacy reference only** — that topology's compose files, `docker/` directory, and+`scripts/docker.js` wrapper were removed from the repo. It is retained solely as documentation+of the historical container topology. The current container path is a single self-hosting+image built from source: see [docker.md](./docker.md).---@@ -58,10 +59,12 @@ The legacy `deploy.sh` (docker-compose images over SCP to a GCE box) was removed## Docker Deployment (LEGACY REFERENCE — removed from repo)-> **Legacy reference only.** The compose files (`docker-compose.yml`, `docker-compose.prod.yml`),-> the `docker/` directory (incl. `docker/Dockerfile.whatsapp`), `client/Dockerfile`,-> `server/Dockerfile`, and `scripts/docker.js` are **no longer in the repository**. This section-> documents the historical 4-container topology for reference; it is not a runnable path today.+> **Legacy reference only.** The 4-container stack's files (its `docker-compose.yml` and+> `docker-compose.prod.yml`, `docker/Dockerfile.whatsapp`, `client/Dockerfile`,+> `server/Dockerfile`, and `scripts/docker.js`) are **no longer in the repository**. This section+> documents that historical topology for reference; it is not a runnable path today. The+> `docker-compose.yml` and `docker/` in the repo now are the one-container self-hosting image+> described in [docker.md](./docker.md).The project previously deployed using Docker Compose with an nginx reverse proxy.@@ -111,7 +114,7 @@ serial port block once in `.env.template` (`PYTHON_BACKEND_PORT`, `NODEJS_EXECUT- Persistent volume: `redis_data`- No authentication (internal network only)-**Development Compose (`docker-compose.yml`):**+**Development Compose (the legacy `docker-compose.yml`):**```yamlservices:# Redis uses profiles - only starts when REDIS_ENABLED=truediff --git a/docs-internal/docker.md b/docs-internal/docker.mdnew file mode 100644index 00000000..22892692--- /dev/null+++ b/docs-internal/docker.md@@ -0,0 +1,129 @@+# Docker (self-hosting)++One container runs the whole app. uvicorn serves the API, the WebSocket and the built UI on one port, and the backend spawns the Temporal dev server, the bun code sidecar and plugin daemons itself when it needs them. There is no Redis; the cache falls back to SQLite.++| File | Role |+|---|---|+| `docker/Dockerfile` | Two stages. The build stage runs the canonical build, the same two commands CI runs (`bun install --frozen-lockfile`, then `bun run build`). The runtime stage keeps only what the backend reads at run time, and optional tools come back through the `EXTRAS` build argument. |+| `docker/entrypoint.sh` | Writes the server secrets on first start, then runs uvicorn directly, the way the desktop shell does. |+| `docker-compose.yml` | One service, one named volume, the port published on this machine only. |++## Quick start++From the repository root:++```bash+docker compose up -d --build+```++Open http://localhost:5678. The app requires a login: the first account you register becomes the owner, and registration closes after that. To create the owner at first start instead, uncomment `OPENCOMPANY_OWNER_EMAIL` and `OPENCOMPANY_OWNER_PASSWORD` in `docker-compose.yml`. The password needs at least 8 characters; a shorter one is only logged as an error, and the app then waits for you to register in the browser. The seed runs only while no account exists, so changing these values later does not change the owner's password. The port is published on `127.0.0.1` only; see [Serving other machines](#serving-other-machines) to open it up.++`docker compose ps` reports the container as `healthy` once `/health/ready` answers, meaning the database is up and the Temporal workers have started. `docker compose logs -f` follows the backend log.++## Optional tools (`EXTRAS`)++The default image has no browser, git or uv. Add them through the `EXTRAS` build argument in `docker-compose.yml` (for example `EXTRAS: "browser git"`), then run `docker compose up -d --build`.++| Extra | Installs | Needed by |+|---|---|---|+| `browser` | Chromium, fonts, Xvfb, uv | The browser node; the browser-harness node, which installs itself with uv |+| `git` | git | The Claude Code and Codex agent nodes, which work in git worktrees |++Without its extra, the browser node fails because the Chromium the image names (`AGENT_BROWSER_EXECUTABLE_PATH`) is not there, browser-harness reports that uv is missing, and Claude Code and Codex tasks fail with `working_directory_not_git_repo`.++## Where state lives++Everything the app keeps is in the `opencompany-selfhost_data` volume, mounted at `/data`. The compose project is named `opencompany-selfhost` so it never mixes with another compose project called `opencompany`.++| Path | Contents |+|---|---|+| `opencompany.env` | The secrets generated on first start, plus any settings you add |+| `workflow.db`, `credentials.db`, `temporal.db` | App data, encrypted credentials, Temporal history |+| `packages/` | The Temporal CLI and the tools plugins install on first use |+| `workspaces/` | Per-workflow files |+| `claude/`, `whatsapp/` | Claude Code login, WhatsApp session |+| `home/` | `$HOME`: gh, stripe, cf and codex logins, bun and uv caches |++`opencompany.env` holds `API_KEY_ENCRYPTION_KEY`, the key that decrypts `credentials.db`. Back the two up together and keep the file private. If the key changes, stored credentials can no longer be decrypted.++Back up `/data` while the container is stopped. `temporal.db` runs in SQLite's WAL mode, so recent commits live in a `-wal` file next to it until SQLite folds them back in: a copy taken while the app runs needs the `-wal` and `-shm` files too, and a `-wal` file must never be deleted. SQLite needs working file locks, so keep `/data` on the named volume or a local disk, never NFS or SMB.++## Configuration++Settings resolve in this order, the later one winning: `.env.template` (baked into the image), then `/data/opencompany.env`, then the container environment (`environment:` in `docker-compose.yml`). To change a setting, add a `KEY=value` line to `/data/opencompany.env` or an entry under `environment:`, then restart the container.++A secret you pass under `environment:` before the first start is written into `/data/opencompany.env` instead of a random one, so removing it from `docker-compose.yml` later changes nothing.++The image sets these on top of the template:++| Variable | Value | Why |+|---|---|---|+| `DATA_DIR` | `/data` | All state on the volume |+| `OPENCOMPANY_ENV_FILE` | `/data/opencompany.env` | Secrets and your settings on the volume |+| `HOME` | `/data/home` | CLI logins and caches survive upgrades |+| `DEPLOYMENT_MODE` | `self_hosted` | Server posture: full Temporal concurrency, API docs not public |+| `VITE_AUTH_ENABLED` | `true` | Login required |+| `NODEJS_EXECUTOR_HOST` | `127.0.0.1` | The code sidecar binds IPv4 loopback, which exists even where container IPv6 is off |+| `NODEJS_USER_PACKAGES_DIR` | `/data/nodejs-user-packages` | Packages installed for code nodes persist |+| `AGENT_BROWSER_EXECUTABLE_PATH` | `/usr/bin/chromium` | The browser node drives the `browser` extra's Chromium |+| `PYTHONUNBUFFERED` | `1` | Log lines reach `docker compose logs` as they are written |++The image has no Node. It links `/usr/local/bin/node` to bun, so the plugin CLIs whose entry scripts start `#!/usr/bin/env node` (agent-browser, vercel, cf) run on bun, as in the official oven/bun images.++With the `browser` extra: Chrome refuses to run as root with its sandbox on, so the image adds `--no-sandbox` through a drop-in, `/etc/chromium.d/no-sandbox`. Debian's launcher reads flags only from that directory and ignores a `CHROMIUM_FLAGS` environment variable. Debian's own `dev-shm` drop-in already adds `--disable-dev-shm-usage` when Docker's `/dev/shm` is small.++Leave `HOST` and `PORT` at their template values. The backend uses `HOST` to reach itself; the published bind comes from the entrypoint's `--host 0.0.0.0`. `PORT` is repeated in the Dockerfile's `EXPOSE` and the compose mapping, which do not follow a change made in `/data/opencompany.env`. Publish only the app port: the code sidecar, the WhatsApp bridge and Temporal listen on internal ports without authentication.++### Serving other machines++Compose publishes the app on `127.0.0.1` only, so only this machine reaches it. To serve other machines, drop the `127.0.0.1:` prefix from the `ports:` mapping, put a TLS proxy in front, and set `JWT_COOKIE_SECURE=true`. Until you do, the log warns at every start that the session cookie travels over plain HTTP.++The proxy must also refuse `/ws/internal`. That is where the backend's Temporal workers call back in; it skips the login check and runs any node a message names, `shell` included. The workers reach it inside the container, so blocking it at the proxy costs nothing. Without such a proxy, anyone who can reach the port can run commands in the container, which is why compose keeps the `127.0.0.1` mapping by default.++## Upgrading++```bash+git pull+docker compose up -d --build+```++The volume keeps all state. An upgrade does not refresh the tools downloaded into `/data/packages`; delete a tool's directory there and the app fetches the current version the next time it needs it.++## Stopping++`docker compose stop` gives the backend up to 120 seconds to drain its Temporal workers and record a clean shutdown. If the container is killed before that, the next start treats it as a crash and pauses the running deployments; resume them from the canvas.++With plain `docker run`, pass `--init` and `--stop-timeout 120` to get the same behaviour.++## Limitations++- **Temporal Web UI.** The dev server binds loopback inside the container, so its UI is not reachable from outside.+- **Claude Code login.** The login button in the credentials panel waits for a browser callback on the container's own localhost, so it cannot finish. Log in from an interactive shell in the container (`docker compose exec opencompany sh`) with `CLAUDE_CONFIG_DIR=/data/claude` set, or supply `ANTHROPIC_API_KEY` through `environment:`. Codex has no login button at all; run its login from the same shell.+- **Owner-checked panels under login.** The image always requires a login, and the editor saves workflows through a REST route that records the placeholder owner `owner` rather than the logged-in account. The Canvas, Memory, Context and dataSource panels check that owner, so they can refuse the logged-in user for such a workflow. `company deploy` VMs, which also require a login, behave the same.+- **A second browser download.** With the `browser` extra, the browser node's first run still downloads agent-browser's own Chrome for Testing (a few hundred MB) into the volume, though agent-browser then drives the system Chromium.+- **Agent nodes need the `git` extra and a git repository.** Claude Code and Codex agents work in git worktrees, and the image contains no `.git`. Run `git init` in a workflow's workspace and make a first commit before pointing an agent at it. Set a commit identity once from a shell in the container (`git config --global user.name ...` and `user.email ...`); it is stored in `/data/home` and survives upgrades.+- **Bind mounts.** A bind mount works in place of the named volume, but the Temporal CLI is then downloaded on first start (a new named volume receives the copy baked into the image), and the directory must allow executables, symlinks and Unix sockets. Prefer the named volume on Windows and macOS hosts.+- **Memory.** Give the container at least 1 GB. At idle the backend holds about 180 MB of process memory and the Temporal dev server about 115 MB; `docker stats` shows up to about 450 MiB because it also counts the page cache of the code they run.+- **Disk.** The image is about 1.3 GB, and the `browser` extra adds about 1.2 GB. A build needs room for its layers on top of that. On Docker Desktop they land on the drive that holds Docker's disk image, which is C: on Windows unless you move it (Settings > Resources > Advanced > Disk image location). A build that fills that drive makes Docker's filesystem read-only and takes down every running container.+- Built and tested on linux/amd64.++## Optional external services++- Redis: `REDIS_ENABLED=true` and `REDIS_URL=redis://<host>:6379`.+- A Temporal cluster: `TEMPORAL_SERVER_ADDRESS=<host>:7233`. With a non-loopback address the backend connects to it instead of spawning its own dev server.++## Maintaining the image++No CI job builds the image. What keeps it in step with the rest of the repo:++- **Toolchain pins.** The `oven/bun` tag must match the root `package.json` `packageManager` (what CI's setup-bun reads), and the `ghcr.io/astral-sh/uv` tag must match `desktop/runtimes.json` (the desktop bundle). `test_docker_image_pins_match_the_bun_and_uv_pins` in `cli/tests/test_release_pipeline_config.py` fails when one moves without the other.+- **The port.** `EXPOSE` and the container side of the compose mapping repeat `PORT` from `.env.template`; `test_docker_port_matches_the_template_port` in the same file fails when the template changes without them.+- **Line endings.** `.gitattributes` pins LF for `*.sh` and `docker/Dockerfile`, so a Windows checkout builds the same image. A CRLF entrypoint fails under `sh` at the first line.+- **The build context.** Docker does not read `.gitignore`. When you add a local state directory or a secret file pattern to `.gitignore`, add it to `.dockerignore` too, or `COPY . .` bakes it into the image.+- **Build steps.** The build stage runs the same two commands as CI (`bun install --frozen-lockfile`, `bun run build`), then a `uv sync --no-dev` that drops the contributor tools. A new build step belongs in `company build`, not in the Dockerfile, so every channel gets it. Step `[6/6]` fetches the Temporal CLI into `DATA_DIR`, which is why a new named volume starts with it.+- **The runtime file list.** The runtime stage copies only what `core/approot.py` reads: `server/`, `client/dist`, `.env.template`, `package.json`, `.opencompany/workflows` and the entrypoint. A new path the backend reads outside `server/` needs a `COPY` line there.+- **Optional tools.** A system package that only some nodes need goes into an `EXTRAS` entry, not the default image.++## Why the container doesn't run `company serve`++`company serve` needs the CLI's own venv and the root `node_modules`, reads only `<app>/.env` (it ignores `OPENCOMPANY_ENV_FILE`), and its supervisor kills the backend 5 seconds after SIGTERM, which can cut the lifespan shutdown short before the clean-shutdown record is written. The entrypoint runs the uvicorn command the desktop shell uses instead; see [desktop_host_contract.md](./desktop_host_contract.md) for the backend's side of that contract.