Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

docs(platform): sync GitBook documentation into dev (#14170)

Nicholas Tindle5f250c8d3ad0
diff --git a/.github/workflows/platform-single-container-docker.yml b/.github/workflows/platform-single-container-docker.yml
index abb94601d3..c2cc938fd9 100644
--- a/.github/workflows/platform-single-container-docker.yml
+++ b/.github/workflows/platform-single-container-docker.yml
@@ -9,6 +9,7 @@ on:
- ".github/scripts/platform-single-container-smoke.sh"
- ".github/workflows/platform-single-container-docker.yml"
- "autogpt_platform/**"
+ - "docs/platform/single-container.md"
pull_request:
paths:
- ".dockerignore"
@@ -16,6 +17,7 @@ on:
- ".github/scripts/platform-single-container-smoke.sh"
- ".github/workflows/platform-single-container-docker.yml"
- "autogpt_platform/**"
+ - "docs/platform/single-container.md"
release:
types: [published]
workflow_dispatch:
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/profile.py b/autogpt_platform/backend/backend/blocks/stripe_link/profile.py
index 6fd2c74088..033c648ddc 100644
--- a/autogpt_platform/backend/backend/blocks/stripe_link/profile.py
+++ b/autogpt_platform/backend/backend/blocks/stripe_link/profile.py
@@ -87,11 +87,11 @@ class StripeLinkGetUserInfoBlock(Block):
) -> BlockOutput:
try:
info = await self._link_api_request(credentials, "GET", "/userinfo")
- yield "name", info.get("name", "")
- yield "first_name", info.get("first_name", "")
- yield "last_name", info.get("last_name", "")
- yield "email", info.get("email", "")
- yield "phone", info.get("phone", "")
+ yield "name", info.get("name") or ""
+ yield "first_name", info.get("first_name") or ""
+ yield "last_name", info.get("last_name") or ""
+ yield "email", info.get("email") or ""
+ yield "phone", info.get("phone") or ""
except Exception as e:
yield "error", str(e)
diff --git a/autogpt_platform/backend/backend/blocks/stripe_link/profile_test.py b/autogpt_platform/backend/backend/blocks/stripe_link/profile_test.py
new file mode 100644
index 0000000000..8cbb761932
--- /dev/null
+++ b/autogpt_platform/backend/backend/blocks/stripe_link/profile_test.py
@@ -0,0 +1,34 @@
+import pytest
+
+from backend.blocks.stripe_link._auth import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT
+from backend.blocks.stripe_link.profile import StripeLinkGetUserInfoBlock
+
+
+async def test_user_info_normalizes_null_profile_fields():
+ block = StripeLinkGetUserInfoBlock()
+
+ async def null_profile(credentials, method, path, body=None):
+ return {
+ "name": None,
+ "first_name": None,
+ "last_name": None,
+ "email": None,
+ "phone": None,
+ }
+
+ object.__setattr__(block, "_link_api_request", null_profile)
+ input_data = block.Input.model_validate({"credentials": TEST_CREDENTIALS_INPUT})
+
+ outputs = {
+ name: value
+ async for name, value in block.run(input_data, credentials=TEST_CREDENTIALS)
+ }
+
+ assert outputs == {
+ "name": "",
+ "first_name": "",
+ "last_name": "",
+ "email": "",
+ "phone": "",
+ }
diff --git a/autogpt_platform/backend/scripts/generate_block_docs.py b/autogpt_platform/backend/scripts/generate_block_docs.py
index c37acf5180..3294b0a9ff 100644
--- a/autogpt_platform/backend/scripts/generate_block_docs.py
+++ b/autogpt_platform/backend/scripts/generate_block_docs.py
@@ -234,7 +234,7 @@ def file_path_to_title(file_path: str) -> str:
"Linkedin": "LinkedIn",
"Tiktok": "TikTok",
"Youtube": "YouTube",
- "Dataforb2B": "DataForB2B",
+ "Dataforb2B": "DataForB2B", # str.title() key across the digit boundary
}
def apply_fixes(text: str) -> str:
diff --git a/autogpt_platform/backend/scripts/test_generate_block_docs.py b/autogpt_platform/backend/scripts/test_generate_block_docs.py
index b17842a71a..cf670b6111 100644
--- a/autogpt_platform/backend/scripts/test_generate_block_docs.py
+++ b/autogpt_platform/backend/scripts/test_generate_block_docs.py
@@ -1,16 +1,32 @@
#!/usr/bin/env python3
"""Tests for the block documentation generator."""
+
import pytest
from scripts.generate_block_docs import (
class_name_to_display_name,
extract_manual_content,
+ file_path_to_title,
generate_anchor,
generate_overview_table,
type_to_readable,
)
+class TestFilePathToTitle:
+ @pytest.mark.parametrize(
+ ("file_path", "expected"),
+ [
+ ("dataforb2b/enrich.md", "DataForB2B Enrich"),
+ ("allquiet/on_call.md", "All Quiet On Call"),
+ ("stripe_link/mpp.md", "Stripe Link MPP"),
+ ("stripe/triggers.md", "Stripe Triggers"),
+ ],
+ )
+ def test_integration_title(self, file_path: str, expected: str):
+ assert file_path_to_title(file_path) == expected
+
+
class TestClassNameToDisplayName:
"""Tests for class_name_to_display_name function."""
diff --git a/autogpt_platform/single-container/.env.example b/autogpt_platform/single-container/.env.example
index f613c605e9..7e4f855910 100644
--- a/autogpt_platform/single-container/.env.example
+++ b/autogpt_platform/single-container/.env.example
@@ -1,18 +1,23 @@
# Runtime settings for `docker run --env-file`. The public URL must exactly
-# match the browser-visible origin. For example, `-p 8080:3000` requires
+# match the browser-visible origin. For example,
+# `-p 127.0.0.1:8080:3000` requires
# `AUTOGPT_PUBLIC_URL=http://localhost:8080`; use the externally reachable
# scheme and hostname when publishing the container beyond the Docker host.
AUTOGPT_PUBLIC_URL=http://localhost:3000
-# Bundled services
+# Bundled services. Set the bot toggle true only after configuring an adapter.
AUTOGPT_ENABLE_BOT_SERVICES=false
AUTOGPT_ENABLE_LEGACY_AUTH=false
+AUTOPILOT_BOT_DISCORD_TOKEN=
+AUTOPILOT_BOT_TELEGRAM_TOKEN=
+AUTOPILOT_BOT_TELEGRAM_USERNAME=
+AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET=
# Account policy. New-account signup is open by default so a fresh container is
# usable. Create the intended accounts, run
# `docker exec <container> autogpt-admin promote <email>`, then set this to
-# false and recreate the container to close registration. While this is true,
-# anyone who can reach the app can create an account.
+# false and recreate the container to close registration. While this is true
+# and the allowlist is empty, anyone who can reach the app can create an account.
AUTH_ALLOW_NEW_ACCOUNTS=true
AUTH_SIGNUP_ALLOWLIST=
# Email verification is unsupported and must remain false. Setting it to true
@@ -29,10 +34,11 @@ DB_POOL_TIMEOUT=300
VAPID_CLAIM_EMAIL=mailto:admin@localhost
# LLM providers. Configure only the providers you use.
-# Core memory is enabled and stored in the bundled FalkorDB. Remote memory
-# extraction needs both OPEN_ROUTER_API_KEY and OPENAI_API_KEY because the
-# latter supplies embeddings. Local memory also needs the nomic-embed-text
-# model installed on the configured OpenAI-compatible server.
+# FalkorDB always runs; Graphiti memory is enabled by the image's default
+# feature configuration. Remote memory extraction needs both
+# OPEN_ROUTER_API_KEY and OPENAI_API_KEY because the latter supplies embeddings.
+# Local memory also needs the nomic-embed-text model installed on the configured
+# OpenAI-compatible server.
OPEN_ROUTER_API_KEY=
# OPENAI_API_KEY is for OpenAI-backed blocks/transcription. For AutoPilot's
# default remote route, use OPEN_ROUTER_API_KEY rather than an OpenAI key.
@@ -56,13 +62,21 @@ CHAT_API_KEY=
# CHAT_THINKING_ADVANCED_MODEL=
# CHAT_TITLE_MODEL=
# CHAT_SIMULATION_MODEL=
+# If the local server does not provide the default Graphiti model slugs, set
+# all three overrides to models installed on that server.
+# GRAPHITI_LLM_MODEL=
+# GRAPHITI_RERANKER_MODEL=
+# GRAPHITI_EMBEDDER_MODEL=
# Optional OpenAI-compatible transcription override.
# TRANSCRIPTION_API_BASE_URL=https://transcription.example.com/v1
# TRANSCRIPTION_API_KEY=
# TRANSCRIPTION_MODEL=
-# Login providers. Each provider is enabled only when both values are set.
+# Setting both values for a provider registers reachable OAuth sign-in and
+# callback endpoints even though the bundled local-mode frontend renders no
+# social-login buttons. Leave each pair empty unless you intentionally use that
+# direct flow. Signup policy still gates first-time account creation.
AUTH_GOOGLE_CLIENT_ID=
AUTH_GOOGLE_CLIENT_SECRET=
AUTH_GITHUB_CLIENT_ID=
diff --git a/autogpt_platform/single-container/README.md b/autogpt_platform/single-container/README.md
index f7c614b7d9..1861c980ac 100644
--- a/autogpt_platform/single-container/README.md
+++ b/autogpt_platform/single-container/README.md
@@ -15,6 +15,9 @@ docker run -d \
--restart unless-stopped \
--shm-size 2g \
--ulimit nofile=65536:65536 \
+ --log-driver json-file \
+ --log-opt max-size=50m \
+ --log-opt max-file=5 \
-p 127.0.0.1:3000:3000 \
-e AUTOGPT_PUBLIC_URL=http://localhost:3000 \
-v autogpt-data:/data \
@@ -24,8 +27,9 @@ docker run -d \
The first boot can take several minutes, and it applies the database migrations.
Let it finish: stopping the container during that window can interrupt a
migration, and the next boot will refuse to start until you resolve it (the log
-names the migration and the command). Wait until Docker reports the container
-as `healthy`, then open [http://localhost:3000](http://localhost:3000).
+names the migration and the recovery options described in the canonical guide
+below). Wait until Docker reports the container as `healthy`, then open
+[http://localhost:3000](http://localhost:3000).
Registration starts open; the loopback-only port binding above keeps it local.
If you expose the app to a network, anyone who can reach it can register until
you close signup.
@@ -42,16 +46,15 @@ and generated application secrets survive container replacement.
## Stopping
-`docker stop` completes in well under Docker's stock 10-second timeout, so the
-appliance shuts down cleanly on a default host and needs no change to Docker's
-host-wide stop timeout. The bundled PostgreSQL, RabbitMQ, Valkey and FalkorDB
-are drained last and in full; everything stateless is stopped first, and is
-terminated rather than waited on once it has released what it holds.
+The image is designed and tested to stop inside Docker's stock 10-second
+timeout. Its measured margin is narrow, and a longer Docker timeout does not
+extend Supervisor's internal five-second state-service cap. Larger or slower
+state may therefore require normal crash recovery on the next boot.
-Agent runs that are still executing do not survive the stop. They are not
-resumed on the next boot, so re-run them.
+Agent runs that are still executing are abandoned and may remain displayed as
+`RUNNING`. They are not resumed on the next boot, so start a new run.
-Supervisor's process names are group-qualified inside the container -- use
+Supervisor's process names are group-qualified inside the container — use
`supervisorctl status` to see them (`runtime:rest`, `state:postgres`, and so
on) rather than assuming a bare name.
@@ -62,8 +65,9 @@ example, publishing host port `8080` requires
`AUTOGPT_PUBLIC_URL=http://localhost:8080` and `-p 127.0.0.1:8080:3000`.
Configure model providers and optional integrations with environment variables.
-Core memory is enabled and stored in the bundled FalkorDB; memory extraction
-also needs a configured chat model and embedding provider.
+The FalkorDB service always runs, while Graphiti memory is enabled by the
+image's default feature configuration; memory extraction also needs a
+configured chat model and embedding provider.
The image supports `linux/amd64` and `linux/arm64`. Test installations used
about 5–6 GiB of memory during startup and steady-state health checks, though
@@ -79,8 +83,11 @@ memory rather than the container's writable layer.
- `vX.Y.Z` — immutable AutoGPT Platform release.
- `sha-<git-sha>` — immutable build for an exact source revision.
+`canary-sha-*` tags are unsupported pre-release validation artifacts.
+
## More information
+- [Canonical single-container operations guide](https://docs.agpt.co/platform/self-hosting/single-container)
- [AutoGPT repository](https://github.com/Significant-Gravitas/AutoGPT)
- [Security policy](https://github.com/Significant-Gravitas/AutoGPT/security/policy)
- [License](https://github.com/Significant-Gravitas/AutoGPT/blob/master/autogpt_platform/LICENSE.md)
diff --git a/autogpt_platform/single-container/bootstrap.sh b/autogpt_platform/single-container/bootstrap.sh
index fea8d84752..aedc0dc671 100755
--- a/autogpt_platform/single-container/bootstrap.sh
+++ b/autogpt_platform/single-container/bootstrap.sh
@@ -269,4 +269,6 @@ publish_readiness() {
mv -f "${temporary}" "${AUTOGPT_READY_FILE}"
}
-main "$@"
+if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
+ main "$@"
+fi
diff --git a/autogpt_platform/single-container/tests/fake_docker.py b/autogpt_platform/single-container/tests/fake_docker.py
new file mode 100644
index 0000000000..29a7c84f5d
--- /dev/null
+++ b/autogpt_platform/single-container/tests/fake_docker.py
@@ -0,0 +1,392 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import tarfile
+import time
+from pathlib import Path, PurePosixPath
+
+
+ROOT = Path(os.environ["FAKE_DOCKER_ROOT"])
+STATE_DIR = ROOT / "state"
+VOLUME_DIR = ROOT / "volumes"
+VOLUME_LABEL_DIR = STATE_DIR / "volume-labels"
+LOG_PATH = ROOT / "commands.jsonl"
+ARGS = sys.argv[1:]
+RESTORE_OWNER_LABEL = "org.agpt.restore.owner"
+
+
+def finish(status: int, output: str = "", error: str = "") -> None:
+ if output:
+ print(output)
+ if error:
+ print(error, file=sys.stderr)
+ raise SystemExit(status)
+
+
+def record() -> None:
+ with LOG_PATH.open("a", encoding="utf-8") as log_file:
+ log_file.write(json.dumps(ARGS) + "\n")
+
+
+def should_fail(operation: str) -> bool:
+ failures = os.environ.get("FAKE_DOCKER_FAIL", "").split(",")
+ return operation in failures
+
+
+def volume_label_path(volume_name: str) -> Path:
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", volume_name):
+ finish(2, error=f"invalid fake volume name: {volume_name}")
+ return VOLUME_LABEL_DIR / f"{volume_name}.json"
+
+
+def read_volume_labels(volume_name: str) -> dict[str, str]:
+ metadata_path = volume_label_path(volume_name)
+ if not metadata_path.is_file():
+ return {}
+ labels = json.loads(metadata_path.read_text(encoding="utf-8"))
+ if not isinstance(labels, dict):
+ finish(2, error=f"invalid fake volume labels: {volume_name}")
+ return {str(key): str(value) for key, value in labels.items()}
+
+
+def write_volume_labels(volume_name: str, labels: dict[str, str]) -> None:
+ VOLUME_LABEL_DIR.mkdir(exist_ok=True)
+ metadata_path = volume_label_path(volume_name)
+ temporary_path = metadata_path.with_suffix(f".{os.getpid()}.tmp")
+ temporary_path.write_text(json.dumps(labels, sort_keys=True), encoding="utf-8")
+ temporary_path.replace(metadata_path)
+
+
+def requested_volume_labels() -> dict[str, str]:
+ labels: dict[str, str] = {}
+ for index, argument in enumerate(ARGS[:-1]):
+ if argument == "--label":
+ label = ARGS[index + 1]
+ elif argument.startswith("--label="):
+ label = argument.removeprefix("--label=")
+ else:
+ continue
+ key, separator, value = label.partition("=")
+ if not separator or not key:
+ finish(2, error=f"invalid fake volume label: {label}")
+ labels[key] = value
+ return labels
+
+
+def require_network_none() -> None:
+ if "--network" not in ARGS:
+ finish(2, error="documented helper did not disable networking")
+ if ARGS[ARGS.index("--network") + 1] != "none":
+ finish(2, error="documented helper used an unexpected network mode")
+
+
+def running() -> bool:
+ return (STATE_DIR / "running").read_text(encoding="utf-8").strip() == "true"
+
+
+def set_running(value: bool) -> None:
+ (STATE_DIR / "running").write_text("true" if value else "false", encoding="utf-8")
+
+
+def mounted_paths() -> dict[str, Path]:
+ mounts: dict[str, Path] = {}
+ for index, argument in enumerate(ARGS[:-1]):
+ if argument != "--volume":
+ continue
+ parts = ARGS[index + 1].split(":")
+ source, destination = parts[:2]
+ mounts[destination] = (
+ Path(source) if source.startswith("/") else VOLUME_DIR / source
+ )
+ return mounts
+
+
+def host_path(container_path: str, mounts: dict[str, Path]) -> Path:
+ requested = PurePosixPath(container_path)
+ for destination, source in sorted(
+ mounts.items(), key=lambda item: len(item[0]), reverse=True
+ ):
+ mount_path = PurePosixPath(destination)
+ try:
+ relative = requested.relative_to(mount_path)
+ except ValueError:
+ continue
+ return source.joinpath(*relative.parts)
+ finish(2, error=f"No fake mount covers {container_path}")
+
+
+def archive_volume(mounts: dict[str, Path]) -> None:
+ require_network_none()
+ archive_argument = ARGS[ARGS.index("-czf") + 1]
+ archive_path = host_path(archive_argument, mounts)
+ data_path = mounts["/data"]
+ if os.environ["FAKE_DOCKER_IMAGE_ID"] not in ARGS:
+ finish(2, error="backup tar did not use the inspected local image ID")
+ if should_fail("signal-term"):
+ os.kill(os.getppid(), signal.SIGTERM)
+ time.sleep(0.1)
+ finish(143, error="injected TERM during tar")
+ if should_fail("tar"):
+ finish(1, error="injected tar failure")
+ time.sleep(float(os.environ.get("FAKE_DOCKER_DELAY_TAR", "0")))
+ exclude_cache = "--exclude=./cache" in ARGS
+ with tarfile.open(archive_path, "w:gz") as archive:
+ for child in sorted(data_path.iterdir()):
+ if child.name == "cache" and exclude_cache:
+ continue
+ archive.add(child, arcname=child.name)
+
+
+def extract_archive(mounts: dict[str, Path]) -> None:
+ require_network_none()
+ if os.environ["RESTORE_IMAGE"] not in ARGS:
+ finish(2, error="restore tar did not use RESTORE_IMAGE")
+ archive_argument = ARGS[ARGS.index("-xzf") + 1]
+ archive_path = host_path(archive_argument, mounts)
+ data_path = mounts["/data"]
+ if should_fail("extract"):
+ finish(1, error="injected restore extraction failure")
+ with tarfile.open(archive_path, "r:gz") as archive:
+ for member in archive.getmembers():
+ member_path = PurePosixPath(member.name)
+ if member_path.is_absolute() or ".." in member_path.parts:
+ finish(2, error="unsafe test archive member")
+ destination = data_path.joinpath(*member_path.parts)
+ if member.isdir():
+ destination.mkdir(parents=True, exist_ok=True)
+ continue
+ if not member.isfile():
+ finish(2, error="unsupported test archive member")
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ source = archive.extractfile(member)
+ if source is None:
+ finish(2, error="unreadable test archive member")
+ with source, destination.open("wb") as destination_file:
+ shutil.copyfileobj(source, destination_file)
+
+
+def checksum(mounts: dict[str, Path]) -> None:
+ require_network_none()
+ if should_fail("checksum"):
+ finish(1, error="injected checksum failure")
+ if should_fail("malformed-checksum"):
+ finish(0, output="not-a-sha256 requested-file")
+ requested_path = ARGS[-1]
+ expected_image = (
+ os.environ["FAKE_DOCKER_IMAGE_ID"]
+ if requested_path.endswith(".partial")
+ else os.environ["RESTORE_IMAGE"]
+ )
+ if expected_image not in ARGS:
+ finish(2, error="checksum did not use the expected image")
+ file_path = host_path(requested_path, mounts)
+ digest = hashlib.sha256(file_path.read_bytes()).hexdigest()
+ finish(0, output=f"{digest} {requested_path}")
+
+
+def validate_layout(mounts: dict[str, Path]) -> None:
+ require_network_none()
+ if os.environ["RESTORE_IMAGE"] not in ARGS:
+ finish(2, error="validation did not use RESTORE_IMAGE")
+ script = ARGS[-1]
+ requirements = re.findall(r"test (-[sd]) (/data/[^\s]+)", script)
+ if not requirements:
+ finish(2, error="documented validation supplied no requirements")
+ missing_requirements = []
+ for predicate, container_path in requirements:
+ path = host_path(container_path, mounts)
+ valid = (
+ path.is_dir()
+ if predicate == "-d"
+ else path.is_file() and path.stat().st_size > 0
+ )
+ if not valid:
+ missing_requirements.append(container_path)
+ data_path = mounts["/data"]
+ try:
+ relative_data_path = data_path.relative_to(ROOT)
+ except ValueError:
+ finish(2, error="fake validation data path escaped its root")
+ if not all(
+ re.fullmatch(r"[A-Za-z0-9_.-]+", part) for part in relative_data_path.parts
+ ):
+ finish(2, error="fake validation data path is not shell-safe")
+ shell_data_path = f"./{relative_data_path.as_posix()}"
+ host_script = re.sub(
+ r"(?<![A-Za-z0-9_./-])/data(?=/|[\s:;,)\"']|$)",
+ shell_data_path,
+ script,
+ )
+ validation = subprocess.run(
+ ["/bin/sh", "-ceu", host_script],
+ cwd=ROOT,
+ env={"PATH": os.environ.get("PATH", os.defpath)},
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ )
+ if validation.returncode == 0 and missing_requirements:
+ finish(2, error="documented validation did not reject a missing path")
+ if validation.returncode != 0:
+ error_parts = [
+ part.strip()
+ for part in (validation.stderr, validation.stdout)
+ if part.strip()
+ ]
+ error_parts.extend(
+ f"missing required restore path: {container_path}"
+ for container_path in missing_requirements
+ )
+ finish(
+ validation.returncode,
+ error="\n".join(error_parts) or "documented restore validation failed",
+ )
+
+
+if not ARGS:
+ finish(2, error="missing fake docker command")
+record()
+
+if ARGS[0] == "inspect":
+ template = ARGS[ARGS.index("--format") + 1]
+ if ".Config.Image" in template:
+ finish(0, output=os.environ["FAKE_DOCKER_IMAGE_REF"])
+ if ".Image" in template:
+ finish(0, output=os.environ["FAKE_DOCKER_IMAGE_ID"])
+ if ".Mounts" in template:
+ finish(0, output=os.environ["FAKE_DOCKER_VOLUME"])
+ if ".State.Running" in template:
+ finish(0, output="true" if running() else "false")
+ if ".State.Status" in template:
+ finish(0, output="running" if running() else "exited")
+ finish(2, error=f"unsupported inspect template: {template}")
+
+if ARGS[:2] == ["image", "inspect"]:
+ if ARGS[-1] != os.environ["FAKE_DOCKER_IMAGE_ID"]:
+ finish(2, error="image metadata lookup did not use the local image ID")
+ finish(0, output=os.environ["FAKE_DOCKER_IMAGE_DIGEST"])
+
+if ARGS[0] == "create":
+ name = ARGS[ARGS.index("--name") + 1]
+ if name != "autogpt-backup-lock":
+ finish(2, error=f"unsupported fake lock container: {name}")
+ lock_path = STATE_DIR / "backup-lock"
+ if lock_path.exists():
+ finish(1, error="lock container already exists")
+ if os.environ["FAKE_DOCKER_IMAGE_ID"] not in ARGS:
+ finish(2, error="lock container did not use the inspected image ID")
+ lock_path.write_text("locked", encoding="utf-8")
+ finish(0, output="fake-lock-container-id")
+
+if ARGS[0] == "rm" and ARGS[-1] == "autogpt-backup-lock":
+ if "--volumes" not in ARGS:
+ finish(2, error="lock cleanup did not remove anonymous volumes")
+ lock_path = STATE_DIR / "backup-lock"
+ if not lock_path.exists():
+ finish(1, error="lock container does not exist")
+ lock_path.unlink()
+ finish(0, output="autogpt-backup-lock")
+
+if ARGS[:2] == ["container", "inspect"]:
+ exists = os.environ.get("FAKE_DOCKER_EXISTING_CONTAINER") == "true"
+ finish(0 if exists else 1)
+
+if ARGS[:2] == ["volume", "inspect"]:
+ volume_name = ARGS[-1]
+ volume_path = VOLUME_DIR / volume_name
+ if not volume_path.is_dir():
+ finish(1)
+ if "--format" in ARGS:
+ template = ARGS[ARGS.index("--format") + 1]
+ metadata_path = volume_label_path(volume_name)
+ if "json .Labels" in template:
+ if (
+ not metadata_path.is_file()
+ and volume_name == os.environ["FAKE_DOCKER_VOLUME"]
+ ):
+ finish(0, output=os.environ.get("FAKE_DOCKER_LABELS", "{}"))
+ finish(0, output=json.dumps(read_volume_labels(volume_name)))
+ label_match = re.search(r'index \.Labels "([^"]+)"', template)
+ if label_match:
+ finish(
+ 0, output=read_volume_labels(volume_name).get(label_match.group(1), "")
+ )
+ finish(2, error=f"unsupported fake volume inspect template: {template}")
+ finish(0)
+
+if ARGS[:2] == ["volume", "create"]:
+ volume_name = ARGS[-1]
+ volume_path = VOLUME_DIR / volume_name
+ race_owner = os.environ.get("FAKE_DOCKER_PRECREATE_VOLUME_OWNER")
+ if race_owner and not volume_path.exists():
+ try:
+ volume_path.mkdir()
+ except FileExistsError:
+ pass
+ else:
+ write_volume_labels(volume_name, {RESTORE_OWNER_LABEL: race_owner})
+ (volume_path / "other-owner.txt").write_text(
+ "preserve this volume\n", encoding="utf-8"
+ )
+ try:
+ volume_path.mkdir()
+ except FileExistsError:
+ pass
+ else:
+ write_volume_labels(volume_name, requested_volume_labels())
+ finish(0, output=volume_name)
+
+if ARGS[:2] == ["volume", "rm"]:
+ volume_name = ARGS[-1]
+ volume_path = VOLUME_DIR / volume_name
+ if not volume_path.is_dir():
+ finish(1, error="volume does not exist")
+ shutil.rmtree(volume_path)
+ volume_label_path(volume_name).unlink(missing_ok=True)
+ finish(0, output=volume_name)
+
+if ARGS[0] == "stop":
+ if should_fail("stop"):
+ finish(1, error="injected stop failure")
+ set_running(False)
+ finish(0, output="autogpt")
+
+if ARGS[0] == "start":
+ if should_fail("start"):
+ finish(1, error="injected start failure")
+ set_running(True)
+ finish(0, output="autogpt")
+
+if ARGS[0] == "run":
+ mounts = mounted_paths()
+ entrypoint = ARGS[ARGS.index("--entrypoint") + 1] if "--entrypoint" in ARGS else ""
+ if entrypoint == "tar" and "-czf" in ARGS:
+ archive_volume(mounts)
+ finish(0)
+ if entrypoint == "tar" and "-xzf" in ARGS:
+ extract_archive(mounts)
+ finish(0)
+ if entrypoint == "sha256sum":
+ checksum(mounts)
+ if entrypoint == "/bin/sh":
+ validate_layout(mounts)
+ finish(0)
+ if "--detach" in ARGS and "--name" in ARGS:
+ if os.environ["RESTORE_IMAGE"] not in ARGS:
+ finish(1, error="restored launch did not use RESTORE_IMAGE")
+ environment_file = Path(ARGS[ARGS.index("--env-file") + 1])
+ if not environment_file.is_file():
+ finish(1, error="launch environment file does not exist")
+ if not mounts["/data"].is_dir():
+ finish(1, error="launch restore volume does not exist")
+ finish(0, output="fake-container-id")
+
+finish(2, error=f"unsupported fake docker invocation: {ARGS}")
diff --git a/autogpt_platform/single-container/tests/test_bootstrap.py b/autogpt_platform/single-container/tests/test_bootstrap.py
new file mode 100644
index 0000000000..a13c64521d
--- /dev/null
+++ b/autogpt_platform/single-container/tests/test_bootstrap.py
@@ -0,0 +1,117 @@
+from __future__ import annotations
+
+import os
+import subprocess
+import unittest
+from pathlib import Path
+
+
+ASSET_DIR = Path(__file__).resolve().parents[1]
+BOOTSTRAP_PATH = ASSET_DIR / "bootstrap.sh"
+
+
+class InterruptedMigrationPolicyTest(unittest.TestCase):
+ def test_sourcing_bootstrap_does_not_run_main(self) -> None:
+ result = self._run('printf "sourced-only\\n"')
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, "sourced-only\n")
+
+ def test_executing_bootstrap_runs_main(self) -> None:
+ missing_runtime = ASSET_DIR / "tests" / ".missing-bootstrap-runtime.env"
+ self.assertFalse(missing_runtime.exists())
+
+ result = subprocess.run(
+ ["bash", str(BOOTSTRAP_PATH)],
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ env={
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ "AUTOGPT_ASSET_DIR": str(ASSET_DIR),
+ "AUTOGPT_RUNTIME_ENV": str(missing_runtime),
+ },
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn(f"missing runtime config: {missing_runtime}", result.stderr)
+
+ def test_checks_for_interrupted_migration_before_deploy(self) -> None:
+ result = self._run("declare -f migrate_database")
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertLess(
+ result.stdout.index("report_interrupted_migration"),
+ result.stdout.index("prisma migrate deploy"),
+ )
+
+ def test_query_selects_only_unfinished_migrations(self) -> None:
+ result = self._run("declare -f report_interrupted_migration")
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("finished_at IS NULL AND rolled_back_at IS NULL", result.stdout)
+
+ def test_missing_migrations_table_is_a_clean_boot(self) -> None:
+ result = self._run(
+ 'query_scalar() { printf "f\\n"; }; '
+ 'report_interrupted_migration; printf "completed\\n"'
+ )
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, "completed\n")
+ self.assertEqual(result.stderr, "")
+
+ def test_no_unfinished_migrations_is_a_clean_boot(self) -> None:
+ result = self._run(
+ "query_scalar() { "
+ 'if [[ "$1" == *to_regclass* ]]; then printf "t\\n"; '
+ 'else printf "\\n"; fi; }; '
+ 'report_interrupted_migration; printf "completed\\n"'
+ )
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, "completed\n")
+ self.assertEqual(result.stderr, "")
+
+ def test_unfinished_migration_fails_closed(self) -> None:
+ result = self._run(
+ "query_scalar() { "
+ 'if [[ "$1" == *to_regclass* ]]; then printf "t\\n"; '
+ 'else printf "20260825_interrupted\\n"; fi; }; '
+ "report_interrupted_migration"
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("20260825_interrupted", result.stdout)
+ self.assertIn(
+ "prisma migrate resolve --rolled-back 20260825_interrupted",
+ result.stdout,
+ )
+ self.assertIn("prisma migrate resolve --applied", result.stdout)
+ self.assertIn(
+ "refusing to migrate over an interrupted migration", result.stderr
+ )
+
+ def _run(self, command: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [
+ "bash",
+ "-Eeuo",
+ "pipefail",
+ "-c",
+ f'source "$1"; {command}',
+ "bash",
+ str(BOOTSTRAP_PATH),
+ ],
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ env={
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ "AUTOGPT_ASSET_DIR": str(ASSET_DIR),
+ },
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/autogpt_platform/single-container/tests/test_documented_operations.py b/autogpt_platform/single-container/tests/test_documented_operations.py
new file mode 100644
index 0000000000..4be730b6ba
--- /dev/null
+++ b/autogpt_platform/single-container/tests/test_documented_operations.py
@@ -0,0 +1,886 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import tarfile
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+
+ASSET_DIR = Path(__file__).resolve().parents[1]
+DOC_PATH = ASSET_DIR.parents[1] / "docs" / "platform" / "single-container.md"
+COMMON_PATH = ASSET_DIR / "common.sh"
+ENTRYPOINT_PATH = ASSET_DIR / "entrypoint.sh"
+SUPERVISOR_PATH = ASSET_DIR / "supervisor" / "supervisord.conf"
+
+
+def extract_bash_block(marker: str) -> str:
+ blocks = re.findall(
+ r"^```bash\n(.*?)\n```$",
+ DOC_PATH.read_text(encoding="utf-8"),
+ flags=re.MULTILINE | re.DOTALL,
+ )
+ matching_blocks = [block for block in blocks if marker in block]
+ if len(matching_blocks) != 1:
+ raise AssertionError(
+ f"Expected one documented Bash block containing {marker!r}, "
+ f"found {len(matching_blocks)}"
+ )
+ return matching_blocks[0]
+
+
+COLD_BACKUP_BLOCK = extract_bash_block("BACKUP_IMAGE_ID=")
+RESTORE_BLOCK = extract_bash_block("RESTORE_CREATED=false")
+STRUCTURAL_VALIDATION_BLOCK = extract_bash_block("test -s /data/config/runtime.env")
+RESTORED_LAUNCH_BLOCK = extract_bash_block(
+ ': "${ENV_FILE:?Set ENV_FILE to the recorded host environment-file path}"'
+)
+
+
+def extract_restore_requirements(block: str) -> tuple[tuple[str, str], ...]:
+ requirements = re.findall(
+ r"^\s*test (-[sd]) /data/([^\s]+)\s*$", block, flags=re.MULTILINE
+ )
+ if not requirements:
+ raise AssertionError("Documented structural validation has no requirements")
+ return tuple(
+ (relative_path, "directory" if predicate == "-d" else "file")
+ for predicate, relative_path in requirements
+ )
+
+
+REQUIRED_RESTORE_PATHS = extract_restore_requirements(STRUCTURAL_VALIDATION_BLOCK)
+
+FAKE_DOCKER_PATH = Path(__file__).with_name("fake_docker.py")
+POSTGRESQL_CONF = "listen_addresses = '127.0.0.1'\n"
+PG_HBA_CONF = (
+ "local all all peer\n"
+ "host all all 127.0.0.1/32 scram-sha-256\n"
+ "host all all ::1/128 scram-sha-256\n"
+ "local replication all peer\n"
+ "host replication all 127.0.0.1/32 scram-sha-256\n"
+ "host replication all ::1/128 scram-sha-256\n"
+)
+
+
+class DocumentedOperationsTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.temporary_directory = tempfile.TemporaryDirectory()
+ self.work_dir = Path(self.temporary_directory.name)
+ self.fake_root = self.work_dir / "fake-docker"
+ self.volume_root = self.fake_root / "volumes"
+ self.source_volume = self.volume_root / "autogpt-data"
+ self.state_dir = self.fake_root / "state"
+ self.bin_dir = self.work_dir / "bin"
+ self.log_path = self.fake_root / "commands.jsonl"
+ self.state_dir.mkdir(parents=True)
+ self.source_volume.mkdir(parents=True)
+ self.bin_dir.mkdir()
+ self._set_running(True)
+ self._seed_source_volume()
+ fake_docker = self.bin_dir / "docker"
+ shutil.copyfile(FAKE_DOCKER_PATH, fake_docker)
+ fake_docker.chmod(0o755)
+ fake_date = self.bin_dir / "date"
+ fake_date.write_text(
+ "#!/bin/sh\n"
+ 'if [ -n "${FAKE_DATE_OUTPUT:-}" ]; then\n'
+ " printf '%s\\n' \"${FAKE_DATE_OUTPUT}\"\n"
+ "else\n"
+ ' exec /bin/date "$@"\n'
+ "fi\n",
+ encoding="utf-8",
+ )
+ fake_date.chmod(0o755)
+ host_environment = {
+ name: os.environ[name]
+ for name in ("LANG", "LC_ALL", "TMPDIR", "TZ")
+ if name in os.environ
+ }
+ self.environment = {
+ **host_environment,
+ "PATH": f"{self.bin_dir}:{os.environ.get('PATH', os.defpath)}",
+ "FAKE_DOCKER_ROOT": str(self.fake_root),
+ "FAKE_DOCKER_VOLUME": "autogpt-data",
+ "FAKE_DOCKER_LABELS": "{}",
+ "FAKE_DOCKER_IMAGE_ID": "sha256:local-image-id",
+ "FAKE_DOCKER_IMAGE_REF": "ghcr.io/example/autogpt:v1.2.3",
+ "FAKE_DOCKER_IMAGE_DIGEST": (
+ "ghcr.io/example/autogpt@sha256:"
+ "0123456789abcdef0123456789abcdef"
+ "0123456789abcdef0123456789abcdef"
+ ),
+ }
+ resolved_docker = shutil.which("docker", path=self.environment["PATH"])
+ self.assertIsNotNone(resolved_docker)
+ self.assertEqual(Path(resolved_docker or "").resolve(), fake_docker.resolve())
+ execution_probe = subprocess.run(
+ [str(fake_docker)],
+ cwd=self.work_dir,
+ env=self.environment,
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ timeout=10,
+ )
+ self.assertEqual(execution_probe.returncode, 2, execution_probe.stderr)
+ self.assertIn("missing fake docker command", execution_probe.stderr)
+
+ def tearDown(self) -> None:
+ self.temporary_directory.cleanup()
+
+ def test_backup_restore_validation_and_restored_launch(self) -> None:
+ backup = self._run(COLD_BACKUP_BLOCK)
+
+ self.assertEqual(backup.returncode, 0, backup.stderr)
+ self.assertTrue(self._is_running())
+ self.assertIn("Image reference: ghcr.io/example/autogpt:v1.2.3", backup.stdout)
+ self.assertIn("Image digest: ghcr.io/example/autogpt@sha256:", backup.stdout)
+ backup_commands = self._commands()
+ image_inspect = next(
+ command
+ for command in backup_commands
+ if command[:2] == ["image", "inspect"]
+ )
+ self.assertEqual(image_inspect[-1], self.environment["FAKE_DOCKER_IMAGE_ID"])
+ backup_tar = next(command for command in backup_commands if "-czf" in command)
+ self.assertIn("--exclude=./cache", backup_tar)
+ self.assertIn(self.environment["FAKE_DOCKER_IMAGE_ID"], backup_tar)
+ backup_checksum = next(
+ command
+ for command in backup_commands
+ if "sha256sum" in command and command[-1].endswith(".partial")
+ )
+ self.assertIn(self.environment["FAKE_DOCKER_IMAGE_ID"], backup_checksum)
+ backup_tar_index = backup_commands.index(backup_tar)
+ restart_index = next(
+ index
+ for index, command in enumerate(backup_commands)
+ if command[0] == "start"
+ )
+ checksum_index = backup_commands.index(backup_checksum)
+ self.assertLess(backup_tar_index, restart_index)
+ self.assertLess(restart_index, checksum_index)
+ archive_path, checksum_path = self._backup_artifacts()
+ self.assertEqual(
+ checksum_path.read_text(encoding="utf-8").split()[0],
+ hashlib.sha256(archive_path.read_bytes()).hexdigest(),
+ )
+ with tarfile.open(archive_path, "r:gz") as archive:
+ archived_paths = {
+ Path(member.name).parts[0]
+ for member in archive.getmembers()
+ if Path(member.name).parts
+ }
+ self.assertNotIn("cache", archived_paths)
+ self.assertIn("config", archived_paths)
+ self.assertIn("workspaces", archived_paths)
+
+ restore = self._run(
+ RESTORE_BLOCK,
+ BACKUP_DIR=str(archive_path.parent),
+ BACKUP_FILE=archive_path.name,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+
+ self.assertEqual(restore.returncode, 0, restore.stderr)
+ restore_commands = self._commands()[len(backup_commands) :]
+ create_index = next(
+ index
+ for index, command in enumerate(restore_commands)
+ if command[:2] == ["volume", "create"]
+ )
+ create_command = restore_commands[create_index]
+ self.assertIn("--label", create_command)
+ self.assertRegex(
+ create_command[create_command.index("--label") + 1],
+ r"^org[.]agpt[.]restore[.]owner=restore-",
+ )
+ owner_inspect_indexes = [
+ index
+ for index, command in enumerate(restore_commands)
+ if command[:2] == ["volume", "inspect"] and "--format" in command
+ ]
+ self.assertEqual(len(owner_inspect_indexes), 1)
+ extract_index = next(
+ index for index, command in enumerate(restore_commands) if "-xzf" in command
+ )
+ self.assertLess(create_index, owner_inspect_indexes[0])
+ self.assertLess(owner_inspect_indexes[0], extract_index)
+ match = re.search(r"Restored .* into volume (\S+)", restore.stdout)
+ self.assertIsNotNone(match, restore.stdout)
+ restore_volume = match.group(1) if match else ""
+ restored_data = self.volume_root / restore_volume
+ self.assertTrue((restored_data / "config" / "runtime.env").is_file())
+ self.assertFalse((restored_data / "cache").exists())
+ self.assertEqual(
+ (restored_data / "workspaces" / "example.txt").read_text(encoding="utf-8"),
+ "durable workspace\n",
+ )
+
+ validation = self._run(
+ STRUCTURAL_VALIDATION_BLOCK,
+ RESTORE_VOLUME=restore_volume,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertEqual(validation.returncode, 0, validation.stderr)
+ validation_command = self._commands()[-1]
+ self.assertIn("--network", validation_command)
+ self.assertEqual(
+ validation_command[validation_command.index("--network") + 1], "none"
+ )
+
+ environment_file = self.work_dir / "autogpt.env"
+ environment_file.write_text("OPENAI_API_KEY=test\n", encoding="utf-8")
+ launch = self._run(
+ RESTORED_LAUNCH_BLOCK,
+ ENV_FILE=str(environment_file),
+ RESTORE_VOLUME=restore_volume,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ PUBLISH_SPEC="127.0.0.1:3300:3000",
+ ADD_HOST_SPEC="host.docker.internal:host-gateway",
+ )
+ self.assertEqual(launch.returncode, 0, launch.stderr)
+ launch_command = self._commands()[-1]
+ self.assertIn(f"{restore_volume}:/data", launch_command)
+ self.assertIn("127.0.0.1:3300:3000", launch_command)
+ self.assertIn("host.docker.internal:host-gateway", launch_command)
+ self.assertIn(str(environment_file), launch_command)
+
+ for index, (relative_path, path_type) in enumerate(REQUIRED_RESTORE_PATHS):
+ with self.subTest(required_path=relative_path):
+ incomplete_volume = f"incomplete-restore-{index}"
+ incomplete_data = self.volume_root / incomplete_volume
+ shutil.copytree(restored_data, incomplete_data)
+ missing_path = incomplete_data / relative_path
+ if path_type == "file":
+ missing_path.unlink()
+ else:
+ shutil.rmtree(missing_path)
+ invalid = self._run(
+ STRUCTURAL_VALIDATION_BLOCK,
+ RESTORE_VOLUME=incomplete_volume,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertNotEqual(
+ invalid.returncode,
+ 0,
+ f"missing {relative_path} unexpectedly passed",
+ )
+ self.assertIn(f"/data/{relative_path}", invalid.stderr)
+
+ invalid_postgres_settings = (
+ (
+ "later-listen-override",
+ "postgres/postgresql.conf",
+ POSTGRESQL_CONF + "Listen_Addresses '*'\n",
+ ),
+ (
+ "auto-conf-listen-override",
+ "postgres/postgresql.auto.conf",
+ "listen_addresses = '*'\n",
+ ),
+ (
+ "postgres-config-include",
+ "postgres/postgresql.conf",
+ POSTGRESQL_CONF + "InClUdE = 'unsafe.conf'\n",
+ ),
+ (
+ "postgres-hba-file",
+ "postgres/postgresql.conf",
+ POSTGRESQL_CONF + "hba_file = '/tmp/unsafe-hba.conf'\n",
+ ),
+ (
+ "auto-conf-hba-file",
+ "postgres/postgresql.auto.conf",
+ "HBA_FILE '/tmp/unsafe-hba.conf'\n",
+ ),
+ (
+ "shared-preload-library",
+ "postgres/postgresql.conf",
+ POSTGRESQL_CONF + "SHARED_PRELOAD_LIBRARIES 'unsafe'\n",
+ ),
+ (
+ "local-preload-library",
+ "postgres/postgresql.auto.conf",
+ "local_preload_libraries = 'unsafe'\n",
+ ),
+ (
+ "session-preload-library",
+ "postgres/postgresql.conf",
+ POSTGRESQL_CONF + "session_preload_libraries 'unsafe'\n",
+ ),
+ (
+ "archive-mode",
+ "postgres/postgresql.auto.conf",
+ "Archive_Mode = always\n",
+ ),
+ (
+ "archive-command",
+ "postgres/postgresql.conf",
+ POSTGRESQL_CONF + "archive_command 'unsafe'\n",
+ ),
+ (
+ "earlier-broad-trust-rule",
+ "postgres/pg_hba.conf",
+ "host all all 0.0.0.0/0 trust\n" + PG_HBA_CONF,
+ ),
+ (
+ "replication-trust-rule",
+ "postgres/pg_hba.conf",
+ PG_HBA_CONF.replace(
+ "host replication all 127.0.0.1/32 scram-sha-256",
+ "host replication all 127.0.0.1/32 trust",
+ ),
+ ),
+ (
+ "hba-include",
+ "postgres/pg_hba.conf",
+ "include 'unsafe.conf'\n" + PG_HBA_CONF,
+ ),
+ )
+ for index, (case, relative_path, content) in enumerate(
+ invalid_postgres_settings
+ ):
+ with self.subTest(invalid_postgres_setting=case):
+ invalid_volume = f"invalid-postgres-settings-{index}"
+ invalid_data = self.volume_root / invalid_volume
+ shutil.copytree(restored_data, invalid_data)
+ (invalid_data / relative_path).write_text(content, encoding="utf-8")
+ invalid = self._run(
+ STRUCTURAL_VALIDATION_BLOCK,
+ RESTORE_VOLUME=invalid_volume,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertNotEqual(
+ invalid.returncode,
+ 0,
+ f"{case} unexpectedly passed:\n{invalid.stdout}\n{invalid.stderr}",
+ )
+
+ def test_restore_race_preserves_foreign_volume(self) -> None:
+ backup = self._run(COLD_BACKUP_BLOCK)
+ self.assertEqual(backup.returncode, 0, backup.stderr)
+ archive_path, _ = self._backup_artifacts()
+ command_count = len(self._commands())
+ restore_volume = "contended-restore-volume"
+
+ result = self._run(
+ RESTORE_BLOCK,
+ BACKUP_DIR=str(archive_path.parent),
+ BACKUP_FILE=archive_path.name,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ RESTORE_VOLUME=restore_volume,
+ FAKE_DOCKER_PRECREATE_VOLUME_OWNER="other-restore-run",
+ FAKE_DOCKER_FAIL="extract",
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("Refusing to populate", result.stderr)
+ foreign_volume = self.volume_root / restore_volume
+ self.assertTrue(foreign_volume.is_dir())
+ self.assertEqual(
+ (foreign_volume / "other-owner.txt").read_text(encoding="utf-8"),
+ "preserve this volume\n",
+ )
+ self.assertFalse((foreign_volume / "config").exists())
+ labels = json.loads(
+ (self.state_dir / "volume-labels" / f"{restore_volume}.json").read_text(
+ encoding="utf-8"
+ )
+ )
+ self.assertEqual(labels, {"org.agpt.restore.owner": "other-restore-run"})
+ restore_commands = self._commands()[command_count:]
+ volume_operations = [
+ command
+ for command in restore_commands
+ if command[:2] in (["volume", "inspect"], ["volume", "create"])
+ ]
+ self.assertEqual(
+ [command[:2] for command in volume_operations],
+ [
+ ["volume", "inspect"],
+ ["volume", "create"],
+ ["volume", "inspect"],
+ ],
+ )
+ self.assertFalse(any("-xzf" in command for command in restore_commands))
+ self.assertFalse(
+ any(command[:2] == ["volume", "rm"] for command in restore_commands)
+ )
+
+ def test_fake_validation_rewrites_only_data_mount_root(self) -> None:
+ restore_volume = "boundary-aware-validation"
+ shutil.copytree(self.source_volume, self.volume_root / restore_volume)
+ validation_block = STRUCTURAL_VALIDATION_BLOCK.replace(
+ ' quote="$(printf "\\047")"',
+ " literal=/database\n"
+ ' test "${#literal}" -eq 9\n'
+ ' test -s "/data/config/runtime.env"\n'
+ ' quote="$(printf "\\047")"',
+ )
+ self.assertNotEqual(validation_block, STRUCTURAL_VALIDATION_BLOCK)
+
+ result = self._run(
+ validation_block,
+ RESTORE_VOLUME=restore_volume,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_backup_can_leave_the_container_stopped_for_upgrade(self) -> None:
+ result = self._run(COLD_BACKUP_BLOCK, RESTART_AFTER_BACKUP="false")
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertFalse(self._is_running())
+ self._backup_artifacts()
+ self.assertFalse(any(command[0] == "start" for command in self._commands()))
+
+ def test_backup_failures_clean_up_and_attempt_safe_recovery(self) -> None:
+ expected_errors = {
+ "stop": "injected stop failure",
+ "tar": "injected tar failure",
+ "checksum": "injected checksum failure",
+ "malformed-checksum": "Backup checksum is not a valid SHA-256 digest",
+ "start": "injected start failure",
+ }
+ for operation, expected_error in expected_errors.items():
+ with self.subTest(operation=operation):
+ self._reset_backup_state()
+ result = self._run(COLD_BACKUP_BLOCK, FAKE_DOCKER_FAIL=operation)
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn(expected_error, result.stderr)
+ self._assert_no_backup_artifacts()
+ self.assertEqual(self._is_running(), operation != "start")
+ if operation in {"tar", "checksum", "malformed-checksum", "start"}:
+ self.assertTrue(
+ any(command[0] == "start" for command in self._commands())
+ )
+
+ def test_reset_backup_state_clears_stale_lock(self) -> None:
+ lock_path = self.state_dir / "backup-lock"
+ lock_path.write_text("stale", encoding="utf-8")
+
+ self._reset_backup_state()
+
+ self.assertFalse(lock_path.exists())
+
+ def test_upgrade_mode_failure_restarts_and_cleans_up(self) -> None:
+ expected_errors = {
+ "tar": "injected tar failure",
+ "checksum": "injected checksum failure",
+ "malformed-checksum": "Backup checksum is not a valid SHA-256 digest",
+ }
+ for operation, expected_error in expected_errors.items():
+ with self.subTest(operation=operation):
+ self._reset_backup_state()
+ result = self._run(
+ COLD_BACKUP_BLOCK,
+ FAKE_DOCKER_FAIL=operation,
+ RESTART_AFTER_BACKUP="false",
+ )
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn(expected_error, result.stderr)
+ self._assert_no_backup_artifacts()
+ self.assertTrue(self._is_running())
+ self.assertFalse((self.state_dir / "backup-lock").exists())
+ self.assertTrue(
+ any(command[0] == "start" for command in self._commands())
+ )
+
+ def test_term_during_archive_cleans_up_and_restarts(self) -> None:
+ result = self._run(COLD_BACKUP_BLOCK, FAKE_DOCKER_FAIL="signal-term")
+
+ self.assertNotEqual(result.returncode, 0)
+ self._assert_no_backup_artifacts()
+ self.assertTrue(self._is_running())
+ self.assertTrue(any(command[0] == "start" for command in self._commands()))
+
+ def test_anonymous_volume_guards_and_unlabeled_named_volume(self) -> None:
+ anonymous = self._run(
+ COLD_BACKUP_BLOCK,
+ FAKE_DOCKER_LABELS='{"com.docker.volume.anonymous":""}',
+ )
+ self.assertNotEqual(anonymous.returncode, 0)
+ self.assertIn("anonymous volume", anonymous.stderr)
+ self.assertTrue(self._is_running())
+
+ hexadecimal_name = "a" * 64
+ (self.volume_root / hexadecimal_name).mkdir()
+ hexadecimal = self._run(
+ COLD_BACKUP_BLOCK,
+ FAKE_DOCKER_VOLUME=hexadecimal_name,
+ FAKE_DOCKER_LABELS="null",
+ )
+ self.assertNotEqual(hexadecimal.returncode, 0)
+ self.assertIn("anonymous volume", hexadecimal.stderr)
+ self.assertTrue(self._is_running())
+
+ named = self._run(COLD_BACKUP_BLOCK, FAKE_DOCKER_LABELS="null")
+ self.assertEqual(named.returncode, 0, named.stderr)
+ self.assertTrue(self._is_running())
+ self._backup_artifacts()
+
+ def test_backup_refuses_nonrunning_and_existing_artifacts(self) -> None:
+ self._set_running(False)
+ nonrunning = self._run(COLD_BACKUP_BLOCK)
+
+ self.assertNotEqual(nonrunning.returncode, 0)
+ self.assertIn("container is not running", nonrunning.stderr)
+ self.assertFalse(self._is_running())
+ self.assertFalse(any(command[0] == "start" for command in self._commands()))
+ self.assertFalse((self.state_dir / "backup-lock").exists())
+
+ self._set_running(True)
+ backup_dir = self.work_dir / "autogpt-backups"
+ backup_dir.mkdir(exist_ok=True)
+ existing = backup_dir / "autogpt-data-20260825T123456Z.tgz"
+ existing.write_text("existing backup", encoding="utf-8")
+ collision = self._run(
+ COLD_BACKUP_BLOCK,
+ FAKE_DATE_OUTPUT="20260825T123456Z",
+ )
+
+ self.assertNotEqual(collision.returncode, 0)
+ self.assertIn("Refusing to overwrite", collision.stderr)
+ self.assertEqual(existing.read_text(encoding="utf-8"), "existing backup")
+ self.assertFalse((self.state_dir / "backup-lock").exists())
+
+ def test_documented_restore_layout_matches_service_owners(self) -> None:
+ entrypoint = ENTRYPOINT_PATH.read_text(encoding="utf-8")
+ supervisor = SUPERVISOR_PATH.read_text(encoding="utf-8")
+ common = COMMON_PATH.read_text(encoding="utf-8")
+ installed_paths = {
+ match.removeprefix("/data/")
+ for match in re.findall(
+ r"^\s*install -d [^\n]* (/data/[^\s]+)$",
+ entrypoint,
+ flags=re.MULTILINE,
+ )
+ if not match.startswith("/data/cache")
+ }
+ documented_paths = {
+ relative_path for relative_path, _ in REQUIRED_RESTORE_PATHS
+ }
+ self.assertEqual(
+ {path.split("/", maxsplit=1)[0] for path in installed_paths},
+ {path.split("/", maxsplit=1)[0] for path in documented_paths},
+ )
+ implementation_leaf_directories = {
+ path
+ for path in installed_paths
+ if path not in {"config", "postgres", "rabbitmq", "valkey"}
+ }
+ # RabbitMQ creates mnesia itself, so supervisor owns this durable path.
+ implementation_leaf_directories.add("rabbitmq/mnesia")
+ documented_directories = {
+ relative_path
+ for relative_path, path_type in REQUIRED_RESTORE_PATHS
+ if path_type == "directory"
+ }
+ self.assertEqual(implementation_leaf_directories, documented_directories)
+ self.assertIn(
+ "RABBITMQ_MNESIA_BASE=/data/rabbitmq/mnesia",
+ supervisor,
+ )
+ self.assertIn(
+ 'AUTOGPT_RUNTIME_ENV="${AUTOGPT_RUNTIME_ENV:-/data/config/runtime.env}"',
+ common,
+ )
+ self.assertIn("local path=/data/config/backend.json", entrypoint)
+ self.assertIn("${PGDATA}/PG_VERSION", entrypoint)
+ self.assertIn("listen_addresses = '127.0.0.1'", entrypoint)
+ self.assertIn("--auth-local=peer", entrypoint)
+ self.assertIn("--auth-host=scram-sha-256", entrypoint)
+
+ def test_restored_launch_supports_bash_3_when_available(self) -> None:
+ stock_bash = Path("/bin/bash")
+ if not stock_bash.is_file():
+ self.skipTest("/bin/bash is unavailable")
+ version = subprocess.run(
+ [str(stock_bash), "--version"],
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ timeout=10,
+ )
+ if version.returncode != 0 or not re.search(
+ r"version 3[.]", version.stdout.splitlines()[0]
+ ):
+ self.skipTest("/bin/bash is not Bash 3.x")
+ environment_file = self.work_dir / "stock-bash.env"
+ environment_file.write_text(
+ "AUTOGPT_PUBLIC_URL=http://localhost:3000\n", encoding="utf-8"
+ )
+
+ result = subprocess.run(
+ [str(stock_bash), "-c", RESTORED_LAUNCH_BLOCK],
+ cwd=self.work_dir,
+ env={
+ **self.environment,
+ "ENV_FILE": str(environment_file),
+ "RESTORE_VOLUME": "autogpt-data",
+ "RESTORE_IMAGE": self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ },
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ timeout=10,
+ )
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_concurrent_backup_is_refused_without_deleting_the_winner(self) -> None:
+ first = subprocess.Popen(
+ ["bash", "-c", COLD_BACKUP_BLOCK],
+ cwd=self.work_dir,
+ env={
+ **self.environment,
+ "BACKUP_DIR": "first-backups",
+ "FAKE_DOCKER_DELAY_TAR": "0.5",
+ },
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ encoding="utf-8",
+ )
+ try:
+ lock_path = self.state_dir / "backup-lock"
+ deadline = time.monotonic() + 5
+ while not lock_path.is_file() and first.poll() is None:
+ self.assertLess(time.monotonic(), deadline)
+ time.sleep(0.01)
+ self.assertTrue(lock_path.is_file())
+
+ second = self._run(COLD_BACKUP_BLOCK, BACKUP_DIR="second-backups")
+ first_stdout, first_stderr = first.communicate(timeout=10)
+ finally:
+ if first.poll() is None:
+ first.kill()
+ first.wait(timeout=10)
+
+ self.assertEqual(first.returncode, 0, first_stderr)
+ self.assertIn("Backup written", first_stdout)
+ self.assertNotEqual(second.returncode, 0)
+ self.assertIn("another backup may be running", second.stderr)
+ archive_path, checksum_path = self._backup_artifacts(
+ self.work_dir / "first-backups"
+ )
+ self.assertEqual(
+ checksum_path.read_text(encoding="utf-8").split()[0],
+ hashlib.sha256(archive_path.read_bytes()).hexdigest(),
+ )
+ second_backup_dir = self.work_dir / "second-backups"
+ self.assertTrue(second_backup_dir.is_dir())
+ self.assertFalse(list(second_backup_dir.iterdir()))
+ self.assertFalse(lock_path.exists())
+
+ def test_relative_backup_directory_and_restore_rejections(self) -> None:
+ relative_backup_dir = "relative-backups"
+ backup = self._run(COLD_BACKUP_BLOCK, BACKUP_DIR=relative_backup_dir)
+
+ self.assertEqual(backup.returncode, 0, backup.stderr)
+ backup_dir = self.work_dir / relative_backup_dir
+ archive_path = next(backup_dir.glob("*.tgz"))
+ checksum_path = next(backup_dir.glob("*.tgz.sha256"))
+ archive_command = next(
+ command for command in self._commands() if "-czf" in command
+ )
+ archive_mounts = [
+ archive_command[index + 1]
+ for index, argument in enumerate(archive_command[:-1])
+ if argument == "--volume"
+ ]
+ canonical_backup_dir = backup_dir.resolve()
+ self.assertIn(f"{canonical_backup_dir}:/backup", archive_mounts)
+
+ restore = self._run(
+ RESTORE_BLOCK,
+ BACKUP_DIR=relative_backup_dir,
+ BACKUP_FILE=archive_path.name,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertEqual(restore.returncode, 0, restore.stderr)
+ restore_checksum = next(
+ command
+ for command in reversed(self._commands())
+ if "sha256sum" in command and command[-1].endswith(".tgz")
+ )
+ self.assertIn(f"{canonical_backup_dir}:/backup:ro", restore_checksum)
+
+ volume_create_count = sum(
+ command[:2] == ["volume", "create"] for command in self._commands()
+ )
+ invalid_name = self._run(
+ RESTORE_BLOCK,
+ BACKUP_DIR=relative_backup_dir,
+ BACKUP_FILE="../outside.tgz",
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertNotEqual(invalid_name.returncode, 0)
+ self.assertIn("must be a filename", invalid_name.stderr)
+
+ original_checksum = checksum_path.read_text(encoding="utf-8")
+ checksum_path.write_text("not-a-digest\n", encoding="utf-8")
+ invalid_checksum = self._run(
+ RESTORE_BLOCK,
+ BACKUP_DIR=relative_backup_dir,
+ BACKUP_FILE=archive_path.name,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertNotEqual(invalid_checksum.returncode, 0)
+ self.assertIn("not a valid SHA-256", invalid_checksum.stderr)
+
+ checksum_path.write_text(f"{'0' * 64} {archive_path.name}\n", encoding="utf-8")
+ mismatch = self._run(
+ RESTORE_BLOCK,
+ BACKUP_DIR=relative_backup_dir,
+ BACKUP_FILE=archive_path.name,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertNotEqual(mismatch.returncode, 0)
+ self.assertIn("checksum verification failed", mismatch.stderr)
+ self.assertEqual(
+ sum(command[:2] == ["volume", "create"] for command in self._commands()),
+ volume_create_count,
+ )
+ checksum_path.write_text(original_checksum, encoding="utf-8")
+
+ volumes_before_failure = {
+ path.name for path in self.volume_root.iterdir() if path.is_dir()
+ }
+ failure_command_count = len(self._commands())
+ failed_extract = self._run(
+ RESTORE_BLOCK,
+ BACKUP_DIR=relative_backup_dir,
+ BACKUP_FILE=archive_path.name,
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ FAKE_DOCKER_FAIL="extract",
+ )
+ self.assertNotEqual(failed_extract.returncode, 0)
+ self.assertIn("partial restore volume was removed", failed_extract.stderr)
+ self.assertEqual(
+ {path.name for path in self.volume_root.iterdir() if path.is_dir()},
+ volumes_before_failure,
+ )
+ failed_restore_commands = self._commands()[failure_command_count:]
+ owner_inspect_indexes = [
+ index
+ for index, command in enumerate(failed_restore_commands)
+ if command[:2] == ["volume", "inspect"] and "--format" in command
+ ]
+ remove_index = next(
+ index
+ for index, command in enumerate(failed_restore_commands)
+ if command[:2] == ["volume", "rm"]
+ )
+ self.assertEqual(len(owner_inspect_indexes), 2)
+ self.assertLess(owner_inspect_indexes[-1], remove_index)
+
+ environment_file = self.work_dir / "restore.env"
+ environment_file.write_text(
+ "AUTOGPT_PUBLIC_URL=http://localhost:3000\n", encoding="utf-8"
+ )
+ missing_volume = self._run(
+ RESTORED_LAUNCH_BLOCK,
+ ENV_FILE=str(environment_file),
+ RESTORE_VOLUME="missing-restored-volume",
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ )
+ self.assertNotEqual(missing_volume.returncode, 0)
+ self.assertIn("Restored volume does not exist", missing_volume.stderr)
+
+ existing_container = self._run(
+ RESTORED_LAUNCH_BLOCK,
+ ENV_FILE=str(environment_file),
+ RESTORE_VOLUME="autogpt-data",
+ RESTORE_IMAGE=self.environment["FAKE_DOCKER_IMAGE_DIGEST"],
+ FAKE_DOCKER_EXISTING_CONTAINER="true",
+ )
+ self.assertNotEqual(existing_container.returncode, 0)
+ self.assertIn("existing container named autogpt", existing_container.stderr)
+
+ def _seed_source_volume(self) -> None:
+ files = {
+ "config/runtime.env": "POSTGRES_PASSWORD=test\n",
+ "config/backend.json": '{"config": true}\n',
+ "postgres/PG_VERSION": "16\n",
+ "postgres/postgresql.conf": POSTGRESQL_CONF,
+ "postgres/pg_hba.conf": PG_HBA_CONF,
+ "workspaces/example.txt": "durable workspace\n",
+ "cache/regenerable.txt": "do not archive\n",
+ }
+ for relative_path, content in files.items():
+ path = self.source_volume / relative_path
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content, encoding="utf-8")
+ for relative_path in (
+ "rabbitmq/mnesia",
+ "valkey/17000",
+ "valkey/17001",
+ "valkey/17002",
+ "falkordb",
+ "home",
+ "frontend-home",
+ ):
+ (self.source_volume / relative_path).mkdir(parents=True)
+
+ def _run(self, block: str, **environment: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["bash", "-c", block],
+ cwd=self.work_dir,
+ env={**self.environment, **environment},
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ timeout=10,
+ )
+
+ def _backup_artifacts(self, backup_dir: Path | None = None) -> tuple[Path, Path]:
+ backup_dir = backup_dir or self.work_dir / "autogpt-backups"
+ archives = list(backup_dir.glob("*.tgz"))
+ checksums = list(backup_dir.glob("*.tgz.sha256"))
+ self.assertEqual(len(archives), 1)
+ self.assertEqual(len(checksums), 1)
+ self.assertFalse(list(backup_dir.glob("*.partial")))
+ return archives[0], checksums[0]
+
+ def _assert_no_backup_artifacts(self) -> None:
+ backup_dir = self.work_dir / "autogpt-backups"
+ self.assertFalse(list(backup_dir.iterdir()) if backup_dir.exists() else [])
+
+ def _reset_backup_state(self) -> None:
+ backup_dir = self.work_dir / "autogpt-backups"
+ if backup_dir.exists():
+ shutil.rmtree(backup_dir)
+ (self.state_dir / "backup-lock").unlink(missing_ok=True)
+ self.log_path.unlink(missing_ok=True)
+ self._set_running(True)
+
+ def _commands(self) -> list[list[str]]:
+ if not self.log_path.exists():
+ return []
+ return [
+ json.loads(line)
+ for line in self.log_path.read_text(encoding="utf-8").splitlines()
+ ]
+
+ def _is_running(self) -> bool:
+ return (self.state_dir / "running").read_text(encoding="utf-8") == "true"
+
+ def _set_running(self, value: bool) -> None:
+ (self.state_dir / "running").write_text(
+ "true" if value else "false", encoding="utf-8"
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/autogpt_platform/single-container/tests/test_entrypoint.py b/autogpt_platform/single-container/tests/test_entrypoint.py
index fbc991cb97..f241b5ad47 100644
--- a/autogpt_platform/single-container/tests/test_entrypoint.py
+++ b/autogpt_platform/single-container/tests/test_entrypoint.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import ast
import os
import subprocess
+import sys
import unittest
from pathlib import Path
@@ -114,6 +115,66 @@ class AccountRegistrationTest(unittest.TestCase):
)
+class EnvironmentPolicyTest(unittest.TestCase):
+ def test_rejects_required_email_verification(self) -> None:
+ result = self._configure(AUTH_REQUIRE_EMAIL_VERIFICATION="true")
+
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn(
+ "email verification is not supported by the single-container distribution",
+ result.stderr,
+ )
+
+ def test_defaults_to_local_behavior(self) -> None:
+ result = self._configure()
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.splitlines()[-1], "local")
+
+ def test_preserves_cloud_behavior_override(self) -> None:
+ result = self._configure(BEHAVE_AS="cloud")
+
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout.splitlines()[-1], "cloud")
+
+ def _configure(self, **overrides: str) -> subprocess.CompletedProcess[str]:
+ environment = {
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ "AUTOGPT_ASSET_DIR": str(ASSET_DIR),
+ "AUTOGPT_BACKEND_DIR": str(ASSET_DIR.parent / "backend"),
+ "AUTOGPT_PYTHON": sys.executable,
+ "AUTOGPT_PUBLIC_URL": "http://localhost:3000",
+ "AUTH_ALLOW_NEW_ACCOUNTS": "false",
+ "POSTGRES_PASSWORD": "test-postgres",
+ "RABBITMQ_DEFAULT_USER": "test-rabbitmq",
+ "RABBITMQ_DEFAULT_PASS": "test-rabbitmq",
+ "REDIS_PASSWORD": "test-redis",
+ "BETTER_AUTH_SECRET": "test-better-auth",
+ "ENCRYPTION_KEY": "test-encryption",
+ "UNSUBSCRIBE_SECRET_KEY": "test-unsubscribe",
+ "GRAPHITI_FALKORDB_PASSWORD": "test-falkordb",
+ "VAPID_PRIVATE_KEY": "test-vapid-private",
+ "VAPID_PUBLIC_KEY": "test-vapid-public",
+ }
+ environment.update(overrides)
+ return subprocess.run(
+ [
+ "bash",
+ "-Eeuo",
+ "pipefail",
+ "-c",
+ 'source "$1"; write_nginx_public_url_config() { :; }; '
+ 'configure_environment; printf "%s\\n" "$BEHAVE_AS"',
+ "bash",
+ str(ENTRYPOINT_PATH),
+ ],
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ env=environment,
+ )
+
+
class PublicOriginConfigurationTest(unittest.TestCase):
def test_backend_cors_uses_the_validated_public_origin(self) -> None:
result = subprocess.run(
@@ -123,7 +184,7 @@ class PublicOriginConfigurationTest(unittest.TestCase):
"pipefail",
"-c",
'source "$1"; AUTOGPT_PUBLIC_URL="$2"; '
- 'configure_backend_cors_origin; '
+ "configure_backend_cors_origin; "
'printf "%s\\n" "$BACKEND_CORS_ALLOW_ORIGINS"',
"bash",
str(ENTRYPOINT_PATH),
diff --git a/docs/integrations/block-integrations/stripe_link/mpp.md b/docs/integrations/block-integrations/stripe_link/mpp.md
index 1f9ce65840..2f28db2515 100644
--- a/docs/integrations/block-integrations/stripe_link/mpp.md
+++ b/docs/integrations/block-integrations/stripe_link/mpp.md
@@ -1,6 +1,11 @@
# Stripe Link MPP
<!-- MANUAL: file_description -->
-_Add a description of this category of blocks._
+Use these blocks to purchase from HTTP endpoints that implement the Machine
+Payments Protocol (MPP). The flow reads a merchant's HTTP 402 Stripe challenge,
+creates a Shared Payment Token spend request for the user to approve, and then
+retries the purchase with that token. The token is not exposed as a graph
+output; the pay block sends it to the guarded merchant request only inside an
+`Authorization: Payment` credential.
<!-- END MANUAL -->
## Stripe Link Get Payment Challenge
@@ -10,7 +15,14 @@ MPP step 1 of 3: read a merchant's HTTP 402 payment challenge to learn its netwo
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block sends the requested method and JSON body without authentication and
+does not follow redirects. A guarded HTTP client rejects disallowed URLs. For a
+Stripe `Payment` challenge, the block decodes the bounded base64url request and
+returns its network ID, amount, and currency. A successful response without a
+402 sets `supports_mpp` to false. A 402 with no challenge or no Stripe challenge
+sets `payment_required` to true; a selected Stripe challenge that is malformed
+or oversized produces an `error` instead. Other HTTP failures also return an
+error because support could not be determined.
<!-- END MANUAL -->
### Inputs
@@ -35,7 +47,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Paid API Discovery**: Probe an API endpoint for a Stripe MPP challenge before constructing a payment.
+
+**Spend Request Setup**: Pass `network_id`, `amount`, and `currency` to Create Token Spend Request when `supports_mpp` is true.
+
+**Unsupported Payment Routing**: Stop or choose an advertised payment method when `payment_required` is true but MPP support is false.
<!-- END MANUAL -->
---
@@ -47,7 +63,13 @@ MPP step 3 of 3: spend an approved Shared Payment Token at the merchant's endpoi
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block retrieves the spend request from Link and requires both an `approved`
+status and a Shared Payment Token. It then probes for the merchant's Stripe
+challenge without a Link payment credential and retries once with a generated
+`Authorization: Payment` credential. The probe carries caller-supplied headers
+other than `Authorization`. Redirects are disabled, and every merchant URL goes
+through the guarded HTTP client. `paid` is true only when that
+credential-bearing retry was attempted and returned a 2xx response.
<!-- END MANUAL -->
### Inputs
@@ -71,7 +93,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Paid API Purchase**: Submit an approved token spend request to the same merchant endpoint that supplied the challenge.
+
+**Receipt Capture**: Keep the merchant response as the order or receipt only when `paid` is true.
+
+**Failed Payment Recovery**: Create and approve a new spend request after a failed payment instead of reusing the token.
<!-- END MANUAL -->
---
diff --git a/docs/integrations/block-integrations/stripe_link/profile.md b/docs/integrations/block-integrations/stripe_link/profile.md
index fd27329b93..894a61e256 100644
--- a/docs/integrations/block-integrations/stripe_link/profile.md
+++ b/docs/integrations/block-integrations/stripe_link/profile.md
@@ -1,6 +1,8 @@
# Stripe Link Profile
<!-- MANUAL: file_description -->
-_Add a description of this category of blocks._
+These read-only blocks retrieve the connected Link account's saved contact and
+shipping information. They can supply checkout fields, but they do not create
+or approve a spend request.
<!-- END MANUAL -->
## Stripe Link Get Shipping Address
@@ -10,7 +12,11 @@ Get the delivery addresses saved on the user's Link wallet, with the default one
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block makes an authenticated `GET /shipping_addresses` request to Link and
+returns the complete list under `addresses`. For `default_address`, it selects
+the address marked as default, falls back to the first saved address, and
+returns an empty object when the account has no addresses. If the authenticated
+Link request fails, the block emits `error` instead of address outputs.
<!-- END MANUAL -->
### Outputs
@@ -23,7 +29,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Default Delivery**: Prefill a physical purchase with the wallet's `default_address`.
+
+**Address Choice**: Present `addresses` when the user should choose among several saved destinations.
+
+**Fulfillment Validation**: Confirm that the selected address meets the merchant's country and postal-code requirements.
<!-- END MANUAL -->
---
@@ -35,7 +45,10 @@ Get the Link account holder's name, email and phone. Use it to fill in a checkou
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block makes an authenticated `GET /userinfo` request to Link and maps the
+returned name, first name, last name, email, and phone fields directly to block
+outputs. Missing keys and explicit null values become empty strings so they
+satisfy the output schema. A failed Link request is reported through `error`.
<!-- END MANUAL -->
### Outputs
@@ -51,7 +64,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Checkout Prefill**: Fill buyer-name and contact fields from the connected Link profile.
+
+**Physical Orders**: Combine contact details with Get Shipping Address for a delivered purchase.
+
+**Missing Data Recovery**: Ask the user for any required value returned as an empty string.
<!-- END MANUAL -->
---
diff --git a/docs/integrations/block-integrations/stripe_link/spend_request.md b/docs/integrations/block-integrations/stripe_link/spend_request.md
index 31238f7ab6..e25d8b6de1 100644
--- a/docs/integrations/block-integrations/stripe_link/spend_request.md
+++ b/docs/integrations/block-integrations/stripe_link/spend_request.md
@@ -1,6 +1,11 @@
# Stripe Link Spend Request
<!-- MANUAL: file_description -->
-_Add a description of this category of blocks._
+Use these blocks to choose a saved Link payment method, create a spend request,
+and wait for the user's decision. Shared Payment Token requests work with the
+MPP blocks on every deployment. The virtual-card create and retrieve blocks are
+self-hosted only because Retrieve Card emits a PAN and CVC that are persisted
+with the execution, while allowing Create Card without retrieval would leave an
+unusable flow.
<!-- END MANUAL -->
## Stripe Link Create Card Spend Request
@@ -10,7 +15,15 @@ Create a Stripe Link spend request for a one-time virtual card. Self-hosted only
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block posts the selected payment-method ID, merchant name and URL, purchase
+context, amount, currency, test-mode setting, and optional approval-sheet fields
+to Link. The context must be at least 100 characters, the amount must be from 1
+through 50,000 in the currency's smallest unit, and the amount on any supplied
+`totals` entry whose type is `total` must equal that amount. When
+`request_approval` is true, the create request also asks Link to start approval;
+the block returns the resulting status and any approval URL. It does not
+retrieve the card. Validation, processing, or Link request failures emit
+`error`; callers must not continue to Retrieve Card after a failure.
<!-- END MANUAL -->
### Inputs
@@ -40,7 +53,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Standard Checkout**: Request a virtual card for a merchant that accepts payment through a conventional checkout form.
+
+**Approval-Gated Purchase**: Show exact purchase details, then pass the approved request to Retrieve Card.
+
+**Self-Hosted Automation**: Use this flow only where persisting the eventual card number and CVC is acceptable.
<!-- END MANUAL -->
---
@@ -52,7 +69,12 @@ MPP step 2 of 3: ask the user to authorize a payment to a merchant that answers
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block posts the same approval and amount fields as the card request, but
+identifies the merchant with the nonblank `network_id` from its HTTP 402
+challenge and sets `credential_type` to `shared_payment_token`. It does not
+send a merchant name or URL. When `request_approval` is true, Link starts the
+approval flow as part of creation; use the returned spend-request ID to poll
+for the result.
<!-- END MANUAL -->
### Inputs
@@ -81,7 +103,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Paid API Access**: Authorize an MPP-protected API call without exposing a card number.
+
+**Challenge-Based Request**: Carry `network_id`, `amount`, and `currency` from Get Payment Challenge into the approval flow.
+
+**Token Payment Handoff**: Pass the spend-request ID to MPP Pay only after its status becomes `approved`.
<!-- END MANUAL -->
---
@@ -93,7 +119,13 @@ Check whether a Stripe Link spend request has been approved yet. Poll this after
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block validates the `lsrq_...` ID and retrieves that spend request from
+Link. On a successful retrieval it returns the current status. A failed Link
+request yields only `error`. For `requires_action`, a successful response also
+provides the action type, message, URL, and whether Link will resume the request
+automatically. Only an explicit `new_spend_request` resolution sets
+`auto_resumes` to false; missing or unfamiliar resolutions keep polling to
+avoid creating a second request while the first can still resume.
<!-- END MANUAL -->
### Inputs
@@ -115,7 +147,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Approval Polling**: Wait for `approved` before continuing to MPP Pay or Retrieve Card.
+
+**Required-Action Recovery**: Send the user to `next_action_url` when present or surface the action message and type otherwise.
+
+**Safe Retry Routing**: Keep polling when `auto_resumes` is true and create a new request only when it is false.
<!-- END MANUAL -->
---
@@ -127,7 +163,10 @@ List the cards and bank accounts in the user's Link wallet. Use this first to pi
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+The block makes an authenticated `GET /payment-details` request and projects
+each result onto a fixed set of selection fields: ID, type, name, default flag,
+and, for cards, brand, last four digits, and expiry. It does not pass through a
+card number, CVC, or unknown fields that Link may add to its response.
<!-- END MANUAL -->
### Outputs
@@ -139,7 +178,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Default Method Selection**: Choose the saved default payment method when it matches the user's intent.
+
+**Explicit User Choice**: Present method names and masked card details when the user should select one.
+
+**Spend Request Wiring**: Pass the chosen method's `id` into a create block as `payment_method_id`.
<!-- END MANUAL -->
---
@@ -151,7 +194,12 @@ Get the one-time virtual card number and CVC for an approved spend request, to t
### How it works
<!-- MANUAL: how_it_works -->
-_Add technical explanation here._
+This self-hosted-only block validates the `lsrq_...` ID and requests the spend
+request with its card data included. It returns the status first and emits card
+fields only when the status is `approved`; denied, expired, or otherwise
+unapproved requests produce an error without emitting a number or CVC. When
+emitted, those values are ordinary block outputs and remain in the execution
+record.
<!-- END MANUAL -->
### Inputs
@@ -175,7 +223,11 @@ _Add technical explanation here._
### Possible use case
<!-- MANUAL: use_case -->
-_Add practical use case examples here._
+**Conventional Checkout**: Complete a standard payment form with the card from an approved spend request.
+
+**Approved-Only Retrieval**: Stop when the request is denied or expired instead of trying old card details.
+
+**Sensitive-Data Boundary**: Keep the card number and CVC inside an operator-controlled environment designed to handle them.
<!-- END MANUAL -->
---
diff --git a/docs/platform/SUMMARY.md b/docs/platform/SUMMARY.md
index 60bb3c31d4..5fe5cbcf57 100644
--- a/docs/platform/SUMMARY.md
+++ b/docs/platform/SUMMARY.md
@@ -20,6 +20,7 @@
* [Setting Up AutoGPT (Self-Host)](getting-started.md)
* [AutoGPT Platform Installer](installer.md)
+* [Run AutoGPT in One Docker Container (Experimental)](single-container.md)
* [Advanced Setup](advanced_setup.md)
## Tutorials
diff --git a/docs/platform/getting-started.md b/docs/platform/getting-started.md
index dfb5199a2a..35fbf793aa 100644
--- a/docs/platform/getting-started.md
+++ b/docs/platform/getting-started.md
@@ -45,7 +45,7 @@ Docker containerizes applications, while Docker Compose orchestrates multi-conta
If you need assistance installing docker:
https://docs.docker.com/desktop/
-Docker-compose is included in Docker Desktop, but if you need assistance installing docker compose:
+Docker-compose is included in Docker Desktop, but if you need assistance installing docker compose:
https://docs.docker.com/compose/install/
You can check if you have Docker installed by running the following command:
@@ -72,6 +72,12 @@ powershell -c "iwr https://setup.agpt.co/install.bat -o install.bat; ./install.b
This method is ideal if you're setting up for development or testing and want to skip manual configuration.
+## Experimental single-container image
+
+For a small self-hosted installation that does not need a source checkout, see
+[Run AutoGPT in one Docker container](single-container.md). The image bundles
+the platform and its stateful services for one host; it is not the development
+setup or a high-availability deployment.
## Manual Setup
@@ -154,8 +160,8 @@ make help
You can check if the server is running by visiting [http://localhost:3000](http://localhost:3000) in your browser.
**Notes:**
-
-By default the application for different services run on the following ports:
+
+By default the application for different services run on the following ports:
Frontend UI Server: 3000
Backend Websocket Server: 8001
@@ -476,7 +482,7 @@ make format
To run the tests:
```sh
-poetry run pytest -s
+poetry run pytest -s
```
## Adding a New Agent Block
diff --git a/docs/platform/installer.md b/docs/platform/installer.md
index 173625e74a..0bb368038f 100644
--- a/docs/platform/installer.md
+++ b/docs/platform/installer.md
@@ -36,6 +36,10 @@ curl -fsSL https://setup.agpt.co/install.sh -o install.sh && bash install.sh
powershell -c "iwr https://setup.agpt.co/install.bat -o install.bat; ./install.bat"
```
+For a prebuilt, experimental alternative intended for small self-hosted
+installations, see [Run AutoGPT in one Docker container](single-container.md).
+That image is separate from the development-oriented installer described here.
+
## Manual Installation
If you prefer, you can manually download and run the installer scripts:
@@ -105,4 +109,4 @@ If you encounter any issues during installation:
1. Make sure all prerequisites are correctly installed
2. Check that Docker is running
3. Ensure you have a stable internet connection
-4. Verify you have sufficient permissions to create directories and run Docker
\ No newline at end of file
+4. Verify you have sufficient permissions to create directories and run Docker
diff --git a/docs/platform/single-container.md b/docs/platform/single-container.md
new file mode 100644
index 0000000000..438b229b8b
--- /dev/null
+++ b/docs/platform/single-container.md
@@ -0,0 +1,1129 @@
+# Run AutoGPT in One Docker Container (Experimental)
+
+The image packages the AutoGPT Platform frontend and backend together with
+PostgreSQL, a three-node Valkey cluster, RabbitMQ, nginx, and FalkorDB.
+Only nginx listens on the container's public interface, on port `3000`.
+The FalkorDB service is a core part of this image and always runs; Graphiti
+memory is enabled by the image's default configuration and still requires a
+working model-provider profile.
+
+All durable state is stored under `/data`. Use a named Docker volume for every
+installation you intend to keep.
+
+## Requirements
+
+- Docker Engine or Docker Desktop capable of running Linux containers on
+ `linux/amd64` or `linux/arm64`. Building locally also requires Docker Buildx.
+- More than the measured 5–6 GiB of appliance memory use, with additional
+ headroom for agents, local models, and workload growth.
+- Host storage with enough capacity and throughput for the image, the growing
+ `/data` volume, and at least one complete compressed backup archive alongside
+ the live data. Shutdown and backup time depend on storage throughput and fsync
+ latency; SSD-class storage is recommended but not a measured support floor.
+
+There is no measured minimum CPU count or supported concurrent-run ceiling;
+performance depends on the enabled services and workload.
+
+## Get an image
+
+Use `latest` for the most recent fully verified stable AutoGPT Platform image:
+
+```bash
+IMAGE=significantgravitas/autogpt:latest
+docker pull "${IMAGE}"
+```
+
+For a reproducible installation, replace `latest` with an immutable `vX.Y.Z`
+tag or manifest digest. Docker image tags map to source releases as follows:
+
+- `latest` points to the newest stable AutoGPT Platform release.
+- `vX.Y.Z` is the immutable image for GitHub release
+ `autogpt-platform-beta-vX.Y.Z`.
+- `sha-<git-sha>` is the immutable image for an exact `dev` or release source
+ revision.
+
+Older `canary-sha-*` tags are legacy pre-release validation artifacts, not a
+currently published or supported tag family.
+
+To build from source instead, run Docker Buildx Bake from the repository root:
+
+```bash
+docker buildx bake \
+ --file autogpt_platform/single-container/docker-bake.hcl \
+ --load \
+ single-container
+IMAGE=autogpt-platform:single-container-dev
+```
+
+Commands below use the shell variable `IMAGE`, whether it identifies the
+Docker Hub image, a pinned digest, or the local build.
+
+The image has a complete default command, so you can optionally perform a
+foreground boot check:
+
+```bash
+docker run --rm "${IMAGE}"
+```
+
+Skip this check if you want to proceed directly to a persistent installation;
+Quick start performs the same first-boot work against its named volume. The
+check runs in the foreground. First boot may take several minutes and use
+roughly 5–6 GiB of memory; press Ctrl-C to stop it. That interruption is safe
+for this check because `--rm` discards its anonymous `/data` volume. Do not
+generalize it to an installation that uses a named volume. The command does not
+publish the web port. Use the full setup below for a usable installation.
+
+## Quick start
+
+Create a private environment file:
+
+```bash
+umask 077
+touch autogpt.env
+chmod 600 autogpt.env
+```
+
+When working from a source checkout, you can copy
+`autogpt_platform/single-container/.env.example` instead to see common optional
+settings. The backend-only `BEHAVE_AS` control and its limits are documented in
+[Security boundary](#security-boundary).
+
+Edit the file and set at least the public URL and exact address for the first
+account:
+
+```dotenv
+AUTOGPT_PUBLIC_URL=http://localhost:3000
+```
+
+Replace `[email protected]` with the email address for the intended first
+account. Passwords must contain at least 12 characters. Exact-address
+allowlisting compares the email string asserted during signup; because this
+image does not support required email verification, it is not proof of mailbox
+ownership. New-account creation defaults open when the allowlist is empty; the
+value above immediately restricts signup to that address. If the allowlist is
+omitted, anyone who can reach the published port can create an account until
+`AUTH_ALLOW_NEW_ACCOUNTS=false` is applied. The run command below binds the app
+only to loopback. Create and promote the administrator and close signup while
+the app is still loopback-only. Configure an HTTPS origin before entering
+credentials on any LAN or remote deployment.
+
+Provider keys are not required to boot, create an account, use Builder, or run
+provider-free blocks. Model-backed functions return their normal actionable
+missing-credential error until you configure a profile from
+[Models and memory](#models-and-memory).
+
+Start the appliance:
+
+```bash
+docker run --detach --name autogpt \
+ --restart unless-stopped \
+ --shm-size 2g \
+ --ulimit nofile=65536:65536 \
+ --log-driver json-file \
+ --log-opt max-size=50m \
+ --log-opt max-file=5 \
+ --env-file autogpt.env \
+ --publish 127.0.0.1:3000:3000 \
+ --volume autogpt-data:/data \
+ "${IMAGE}"
+```
+
+The `--shm-size 2g` allocation keeps temporary ChatGPT/Codex authentication
+homes in memory instead of the container's writable layer. The `nofile` limit
+sets a predictable per-process file-descriptor ceiling for the bundled services.
+The JSON log options retain about five 50 MB files instead of allowing container
+logs to grow without a bound.
+
+Wait for the complete appliance to become healthy:
+
+```bash
+docker inspect --format '{{.State.Health.Status}}' autogpt
+docker logs --tail 100 --follow autogpt
+```
+
+Do not stop the container while the first boot is applying database migrations.
+If a migration is interrupted, later boots refuse to continue and the logs
+identify the migration and recovery choices. For a brand-new empty installation,
+remove that installation's unused `/data` volume and start again. For an existing
+installation, restore the pre-upgrade backup. Use `prisma migrate resolve` only
+after determining whether that migration's changes reached the database.
+
+For an empty first boot that used the exact Quick start names, first verify that
+the volume contains no user data, then discard that failed installation:
+
+```bash
+docker stop autogpt
+docker rm autogpt
+docker volume rm autogpt-data
+```
+
+Repeat Quick start afterward. The failed appliance can remain in a restart loop
+until explicitly stopped, so `docker exec` is not a reliable way to run
+`prisma migrate resolve`; that advanced path requires PostgreSQL running against
+the affected volume from a separate recovery environment. Do not use it without
+inspecting whether the migration's database changes completed.
+
+Test installations used about 5–6 GiB of memory during startup and steady-state
+health checks. This is measured guidance, not a guaranteed minimum; allow
+headroom for enabled services, agents, local models, and workload growth. On
+Docker Desktop, make sure the VM's memory allocation in **Settings → Resources**
+exceeds that observed use and leaves the same headroom.
+
+Open `http://localhost:3000`, create the intended account, and promote it:
+
+```bash
+docker exec autogpt autogpt-admin promote [email protected]
+```
+
+Replace `[email protected]` with the email address of the account you created.
+Sign out and back in after promotion so the new session has the administrator
+role.
+
+Then set this in the environment file:
+
+```dotenv
+AUTH_ALLOW_NEW_ACCOUNTS=false
+```
+
+Apply the change by replacing only the container. Keep the same named volume:
+
+```bash
+docker stop autogpt
+docker rm autogpt
+```
+
+Repeat the `docker run` command above. Removing the container does not remove
+the `autogpt-data` volume.
+
+## Stopping
+
+`docker stop autogpt` is designed and tested to complete inside Docker's stock
+10-second timeout, so no host-wide timeout change is needed; a longer host
+timeout does not extend the internal Supervisor caps. The shipped one-second
+runtime, five-second state, and one-second event-listener phases measured about
+8.4 seconds in the shutdown test setup. That is a narrow measured margin, not a
+graceful-shutdown guarantee for slower storage, so do not shorten Docker's
+timeout. Runtime processes are signaled first. PostgreSQL, RabbitMQ, Valkey,
+and FalkorDB are signaled afterward and each gets at most five seconds to exit
+before Supervisor forces it down. The event listener stops last. Larger or
+slower state may require normal crash recovery on the next boot.
+
+Agent runs still executing when the container stops are abandoned. Their queue
+messages can be dropped and their execution rows can remain `RUNNING`, but they
+do not resume. Start a new run after restart.
+
+Supervisor process names are group-qualified. Use `supervisorctl status` to see
+names such as `runtime:rest` and `state:postgres`.
+
+## Port and public URL
+
+Container port `3000` does not change. To use host port `3300`, change the run
+command to:
+
+```text
+--publish 127.0.0.1:3300:3000
+```
+
+and set:
+
+```dotenv
+AUTOGPT_PUBLIC_URL=http://localhost:3300
+```
+
+`AUTOGPT_PUBLIC_URL` must be the exact origin used in the browser, including
+the scheme and any non-default port. Docker cannot discover the host-side port
+mapping from inside the container. A mismatch breaks authentication actions,
+callbacks, cookies, and generated links.
+
+For LAN or remote access, keep AutoGPT bound to loopback and place it behind a
+TLS reverse proxy running outside the AutoGPT container. The proxy provides
+HTTPS and forwards requests to port `3000`; AutoGPT handles application routing
+internally.
+
+Before exposing the proxy, complete the [Account policy](#account-policy)
+bootstrap, promote the intended administrator, and close new-account signup.
+The bundled nginx records the external proxy as the immediate client, so the
+proxy must preserve its own client-attribution logs and enforce any per-client
+IP rate limits or access rules.
+
+Set `AUTOGPT_PUBLIC_URL` to the browser-visible HTTPS origin, for example:
+
+```dotenv
+AUTOGPT_PUBLIC_URL=https://agents.example.com
+```
+
+Do not expose the container's plaintext port directly or leave the URL at the
+localhost default.
+
+## Account policy
+
+New-account creation defaults open so the first administrator can sign up. A
+nonempty allowlist immediately restricts who can create an account. Existing
+accounts can still sign in after signup is closed.
+
+To allow only selected accounts during provisioning, keep signup enabled and
+set an allowlist:
+
+```dotenv
+AUTH_ALLOW_NEW_ACCOUNTS=true
+```
+
+The allowlist accepts exact email addresses and entries beginning with `@` for
+an entire domain. Separate multiple entries with commas, for example
+email/password signup and any first-time account creation through a configured
+provider endpoint; the bundled UI does not show social-login buttons. Prefer
+exact addresses; use a domain entry only for a domain you fully control, then
+narrow the list after bootstrap. Domain matching trusts the identity provider's
+asserted email; public email domains such as `@gmail.com` are not safe allowlist
+entries.
+
+Setting `AUTH_ALLOW_NEW_ACCOUNTS=false` blocks all new accounts regardless of
+the allowlist; recreate the container with the same volume to apply the setting
+after promoting the intended administrator.
+
+Fresh installations should keep `AUTOGPT_ENABLE_LEGACY_AUTH=false`. Enable it
+only when intentionally migrating an existing legacy symmetric-JWT setup.
+
+Required email verification is not supported by this image and intentionally
+stops startup if enabled. Keep:
+
+```dotenv
+AUTH_REQUIRE_EMAIL_VERIFICATION=false
+```
+
+Postmark can provide password-reset and email-change messages:
+
+```dotenv
+POSTMARK_SERVER_API_TOKEN=
+POSTMARK_SENDER_EMAIL=
+POSTMARK_WEBHOOK_TOKEN=
+```
+
+Set `POSTMARK_SENDER_EMAIL` to a sender verified by your Postmark account. This
+does not add account-verification support. Without these Postmark settings,
+there is no self-service password-reset email or appliance CLI for resetting a
+password. Store the administrator password securely before closing signup.
+
+### Add or recover an administrator
+
+To add an account after signup is closed, temporarily bind the appliance to
+loopback, set `AUTH_ALLOW_NEW_ACCOUNTS=true`, and set
+`AUTH_SIGNUP_ALLOWLIST` to that account's exact email address. Replace the
+container with the same named volume and original launch options, create the
+account, and promote it:
+
+```bash
+docker exec autogpt autogpt-admin promote [email protected]
+```
+
+Then set `AUTH_ALLOW_NEW_ACCOUNTS=false` and replace the container again. If an
+administrator password is lost and Postmark password reset was not configured,
+this procedure creates a replacement administrator; it does not reset the
+existing account's password. Keep the port loopback-only throughout recovery,
+or enforce equivalent HTTPS and network access controls before reopening
+signup.
+
+Setting both `AUTH_*_CLIENT_ID` and `AUTH_*_CLIENT_SECRET` values for a social
+provider registers reachable OAuth sign-in and callback endpoints. The bundled
+local-mode frontend does not render buttons for them, so leave each pair empty
+unless you intentionally use that direct provider flow. `AUTH_SIGNUP_ALLOWLIST`
+and `AUTH_ALLOW_NEW_ACCOUNTS` still gate first-time account creation through
+those endpoints. Agent block OAuth integrations use the separate unprefixed
+credentials. The prebuilt frontend does not support configuring Google Picker
+public keys at runtime.
+
+## Models and memory
+
+The FalkorDB service always runs and persists under `/data`; it has no supported
+process toggle in this distribution. Graphiti memory is enabled by the image's
+default feature configuration.
+
+The image does not include model-provider credentials. This does not block
+startup, authentication, Builder, or provider-free blocks. Configure one of
+the following profiles before expecting AutoPilot and memory extraction to
+work; until then, provider-backed requests return the same missing-credential
+errors as other AutoGPT deployment modes.
+
+### OpenRouter with OpenAI embeddings
+
+The default remote profile uses OpenRouter for chat and memory extraction and
+OpenAI for embeddings:
+
+```dotenv
+CHAT_USE_LOCAL=false
+CHAT_USE_OPENROUTER=true
+OPEN_ROUTER_API_KEY=YOUR_OPENROUTER_KEY
+OPENAI_API_KEY=YOUR_OPENAI_KEY
+```
+
+Both keys are needed for the complete memory path. `OPENAI_API_KEY` alone does
+not select direct OpenAI routing for AutoPilot.
+
+### Anthropic chat with remote memory
+
+To route AutoPilot directly to Anthropic:
+
+```dotenv
+CHAT_USE_LOCAL=false
+CHAT_USE_OPENROUTER=false
+ANTHROPIC_API_KEY=YOUR_ANTHROPIC_KEY
+OPEN_ROUTER_API_KEY=YOUR_OPENROUTER_KEY
+OPENAI_API_KEY=YOUR_OPENAI_KEY
+```
+
+The Anthropic key changes the AutoPilot chat transport. The OpenRouter and
+OpenAI keys are still required by Graphiti's default remote extraction and
+embedding clients.
+
+### Ollama or another local OpenAI-compatible server
+
+For the default local profile, install both the chat model and memory embedding
+model on the Docker host:
+
+```bash
+ollama pull hf.co/unsloth/Qwen3.5-4B-GGUF:Q4_K_M
+ollama pull nomic-embed-text
+```
+
+Configure the host's Ollama service with `OLLAMA_CONTEXT_LENGTH=32768` and
+restart Ollama before using AutoPilot. This is an Ollama-server setting, not an
+`autogpt.env` entry; Ollama's smaller default context cannot hold AutoPilot's
+roughly 8k-token system prompt.
+
+The chat model and exact `Q4_K_M` artifact are published in the
+[Unsloth Qwen3.5-4B-GGUF repository](https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/tree/main).
+Keep the model identifier in the pull command and environment setting
+identical. The 4B model is the smaller default chosen for this all-in-one
+appliance's shared memory budget; larger models remain optional when the host
+has sufficient resources.
+
+Then set:
+
+```dotenv
+CHAT_USE_LOCAL=true
+CHAT_BASE_URL=http://host.docker.internal:11434/v1
+CHAT_API_KEY=ollama
+CHAT_FAST_STANDARD_MODEL=hf.co/unsloth/Qwen3.5-4B-GGUF:Q4_K_M
+```
+
+`CHAT_API_KEY` must be non-empty even if the local server ignores it. The
+local transport makes Graphiti inherit the same base URL and API key. With the
+default profile above, Graphiti rewrites its extraction and reranker models to
+`hf.co/unsloth/Qwen3.5-4B-GGUF:Q4_K_M` and uses `nomic-embed-text` for
+embeddings. If you choose another chat model, also set `GRAPHITI_LLM_MODEL`
+and `GRAPHITI_RERANKER_MODEL` to a model that the endpoint serves. Set
+`GRAPHITI_EMBEDDER_MODEL` too when its embedding model uses another slug.
+
+On Docker Engine, add `--add-host host.docker.internal:host-gateway` to the run
+command for this local-model profile. Docker Desktop provides that hostname
+without the extra option. To apply the flag to an existing container, stop and
+remove the container, then repeat the Quick start command with the same named
+volume and the added flag. Small quantized models reduce memory requirements,
+but latency and answer quality remain hardware-, model-, and workload-dependent;
+select another compatible model when the default does not meet your needs.
+
+Check connectivity from the running appliance:
+
+```bash
+docker exec autogpt \
+ curl --fail --show-error http://host.docker.internal:11434/api/tags
+```
+
+The same settings can point at a remote vLLM, LocalAI, LM Studio, LiteLLM, or
+other OpenAI-compatible HTTPS endpoint, provided it serves every configured
+chat and Graphiti model slug. Do not expose an unauthenticated model server to
+the internet. See the
+[AutoPilot local-LLM guide](copilot-local-llm.md)
+for model and context-window guidance.
+
+Additional provider keys consumed by backend blocks may be placed in the same
+environment file. Most remain backend-only. The Next.js server process always
+receives the required `BETTER_AUTH_SECRET` and can receive configured `AUTH_*`
+provider client secrets, `OPENAI_API_KEY`, `TRANSCRIPTION_API_KEY`, and the
+legacy `SUPABASE_JWT_SECRET`. These values remain server-side process
+environment and are not baked into the browser bundle.
+
+### Database connection tuning
+
+`DB_CONNECTION_LIMIT` controls each backend role's Prisma connection pool and
+accepts `1` through `5` (default `5`). `DB_CONNECT_TIMEOUT` controls connection
+setup and accepts `1` through `600` seconds (default `60`), while
+`DB_POOL_TIMEOUT` controls how long a request can wait for a pooled connection
+and accepts `1` through `3600` seconds (default `300`). All roles share the
+bundled PostgreSQL instance, so do not raise per-role limits beyond the enforced
+range. If requests stall under concurrent runs, inspect service and PostgreSQL
+logs for pool exhaustion before changing these values.
+
+## Security boundary
+
+`BEHAVE_AS` defaults to `local`, which bypasses subscription entitlement gating
+for policies that opt into a local exemption, which currently includes every
+defined entitlement. `local` is a broader product behavior profile: it can also
+enable blocks intentionally disabled in hosted mode, select self-host model
+routing, and change diagnostics or telemetry behavior. This is appropriate for
+single-tenant self-hosting. Any
+multi-tenant or hosted deployment must set `BEHAVE_AS=cloud` for backend
+entitlement enforcement, but that setting is not a complete hosted-mode switch:
+the bundled frontend is compiled in local mode. Cloud mode also expects the
+hosted model catalog, subscription tiers, and payment controls. Do not treat
+this image as a turnkey multi-tenant hosted distribution. Use the supported
+cloud deployment and build, and review its full security boundary.
+
+The browser-facing nginx and Next.js processes run under Unix identities that
+are separate from backend services. The frontend receives an explicit runtime
+environment allowlist and connects to PostgreSQL through a passwordless local
+peer role restricted to the Better Auth tables and columns it needs. It does
+receive `BETTER_AUTH_SECRET`, configured `AUTH_*` social-login client secrets,
+and optional OpenAI, transcription, and legacy-JWT values because the Next.js
+server uses them. Those values remain server-side and are not baked into the
+browser bundle. The frontend does not receive the PostgreSQL superuser password,
+RabbitMQ or Valkey passwords, the FalkorDB password, or encryption keys.
+
+Generated database, queue, cache, memory, encryption, authentication, and
+signing secrets are created on first boot and stored in
+`/data/config/runtime.env` as `root:root` mode `0600`. Reusing the named volume
+reuses those secrets. Supplying a different value for a persisted secret on a
+later boot fails instead of silently rotating it.
+
+### Suspected secret exposure
+
+There is no supported in-place rotation for the generated secrets in
+`/data/config/runtime.env`. If that file or a plaintext backup is exposed,
+isolate the installation and revoke external provider and OAuth credentials.
+Create a replacement installation on a new volume, transfer only non-secret
+agent definitions through supported export/import flows, and reconnect
+credentials. Every backup from the old installation contains the same generated
+secrets, so restoring an older one does not rotate them. Do not edit
+`runtime.env`, selectively mix state directories, or treat a same-installation
+backup as secret-exposure recovery.
+
+These controls limit compromise between co-located processes, but Docker daemon
+administrators and anyone who can read the data volume remain fully trusted.
+Treat the host environment file, `/data`, backups, and unredacted diagnostic
+output as secret-bearing material.
+
+Only port `3000` should be published. Internal AppService RPC is bound to the
+container's loopback interface, and Valkey traffic requires authentication.
+On Linux, Docker-managed forwarding can bypass firewall policy expressed only
+through tools such as UFW. The loopback address in
+`--publish 127.0.0.1:3000:3000` is the exposure control; changing it to a
+non-loopback address can expose the app regardless of an INPUT-chain rule.
+
+## Optional processes
+
+FalkorDB is mandatory. Bot services and their internal linking manager default
+off. After configuring a supported chat adapter and its public routes, enable
+both optional processes with:
+
+```dotenv
+AUTOGPT_ENABLE_BOT_SERVICES=true
+```
+
+For Discord, configure `AUTOPILOT_BOT_DISCORD_TOKEN`. Telegram requires both
+`AUTOPILOT_BOT_TELEGRAM_TOKEN` and
+`AUTOPILOT_BOT_TELEGRAM_WEBHOOK_SECRET`, plus a public HTTPS webhook registered
+with Telegram. Leave the toggle `false` until the chosen adapter credentials
+and routes are ready. This setting stops processes; it does not make the image
+smaller.
+
+## Persistence
+
+The named volume mounted at `/data` contains all durable appliance state:
+
+| Path | Contents |
+| --- | --- |
+| `/data/config` | Generated runtime secrets and backend configuration |
+| `/data/postgres` | Authentication and platform data |
+| `/data/rabbitmq` | Queue state |
+| `/data/valkey` | Three-node Valkey state |
+| `/data/falkordb` | Graphiti memory data |
+| `/data/workspaces` | User workspaces |
+| `/data/home` and `/data/frontend-home` | Application home directories |
+| `/data/cache` | Regenerable backend and Next.js caches (excluded from backups) |
+
+Do not mount one volume into two running AutoGPT containers. Use a different
+named volume for every installation.
+
+To confirm which volume a container uses:
+
+```bash
+docker inspect --format \
+ '{{range .Mounts}}{{if eq .Destination "/data"}}{{.Name}}{{end}}{{end}}' \
+ autogpt
+```
+
+## Cold backup
+
+The block below stops the running appliance before archiving its coupled
+service state. It uses the running container's exact local image ID captured
+before the stop, writes to a unique partial file, and promotes it to the final
+timestamped name only after `tar` succeeds. This produces a stopped-volume
+snapshot. If a state service exceeds its five-second shutdown cap, the snapshot
+reflects a crash stop rather than a fully graceful shutdown. Rehearse
+restoration and verify service recovery before relying on it.
+The appliance remains unavailable while `tar` creates and gzip-compresses the
+archive; duration depends on `/data`, host storage, and CPU performance. Before
+stopping it, ensure the host filesystem that contains `BACKUP_DIR` has room for
+a complete compressed archive. The block enforces owner-only mode `0700` on
+that directory, including when it already exists:
+
+Start the appliance and verify full health before backing it up. The block
+intentionally refuses an already stopped or crashed appliance because it must
+own the coordinated transition from running to stopped state.
+
+There is no supported consistent hot-backup procedure for this coupled volume.
+If this outage is unacceptable, use a distributed deployment and the
+service-native backup procedures for its independently managed data services.
+
+```bash
+(
+ set -euo pipefail
+ BACKUP_IMAGE_ID="$(docker inspect --format '{{.Image}}' autogpt)"
+ BACKUP_IMAGE_REF="$(docker inspect --format '{{.Config.Image}}' autogpt)"
+ BACKUP_IMAGE_DIGEST="$(docker image inspect --format \
+ '{{if .RepoDigests}}{{index .RepoDigests 0}}{{end}}' \
+ "${BACKUP_IMAGE_ID}")"
+ BACKUP_VOLUME="$(docker inspect --format \
+ '{{range .Mounts}}{{if eq .Destination "/data"}}{{.Name}}{{end}}{{end}}' \
+ autogpt)"
+ BACKUP_DIR="${BACKUP_DIR:-${PWD}/autogpt-backups}"
+ RESTART_AFTER_BACKUP="${RESTART_AFTER_BACKUP:-true}"
+ BACKUP_COMPLETE=false
+ ARTIFACTS_STARTED=false
+ LOCK_HELD=false
+ MANAGE_CONTAINER=false
+ BACKUP_FILE=''
+ PARTIAL_FILE=''
+ CHECKSUM_FILE=''
+ CHECKSUM_PARTIAL=''
+
+ if [[ "${RESTART_AFTER_BACKUP}" != true && \
+ "${RESTART_AFTER_BACKUP}" != false ]]; then
+ echo "RESTART_AFTER_BACKUP must be true or false" >&2
+ exit 1
+ fi
+ : "${BACKUP_VOLUME:?Container has no named volume mounted at /data}"
+ BACKUP_VOLUME_LABELS="$(docker volume inspect --format '{{json .Labels}}' \
+ "${BACKUP_VOLUME}")"
+ if [[ "${BACKUP_VOLUME_LABELS}" == *'"com.docker.volume.anonymous"'* || \
+ "${BACKUP_VOLUME}" =~ ^[0-9a-f]{64}$ ]]; then
+ echo "Refusing backup because /data uses an anonymous volume" >&2
+ exit 1
+ fi
+ mkdir -p "${BACKUP_DIR}"
+ BACKUP_DIR="$(cd "${BACKUP_DIR}" && pwd -P)"
+ chmod 700 "${BACKUP_DIR}"
+ LOCK_CONTAINER=autogpt-backup-lock
+
+ # Invoked by the EXIT and signal traps below.
+ # shellcheck disable=SC2329
+ finish_backup() {
+ local exit_status="$1"
+ local container_running
+ trap - EXIT HUP INT TERM
+ if [[ "${exit_status}" -ne 0 && "${ARTIFACTS_STARTED}" == true && \
+ "${BACKUP_COMPLETE}" != true ]]; then
+ if ! rm -f \
+ "${BACKUP_DIR}/${PARTIAL_FILE}" \
+ "${BACKUP_DIR}/${CHECKSUM_PARTIAL}" \
+ "${BACKUP_DIR}/${BACKUP_FILE}" \
+ "${BACKUP_DIR}/${CHECKSUM_FILE}"; then
+ echo "Backup failed and partial files could not be removed" >&2
+ exit_status=1
+ else
+ echo "Backup failed; no incomplete backup artifacts were kept" >&2
+ fi
+ fi
+ container_running=''
+ if [[ "${MANAGE_CONTAINER}" == true ]]; then
+ container_running="$(docker inspect --format '{{.State.Running}}' \
+ autogpt 2>/dev/null || true)"
+ fi
+ if [[ "${MANAGE_CONTAINER}" == true && \
+ ( "${exit_status}" -ne 0 || \
+ "${RESTART_AFTER_BACKUP}" == true ) ]]; then
+ if [[ "${container_running}" != true ]] && \
+ ! docker start autogpt >/dev/null; then
+ echo "AutoGPT is not running; automatic restart failed" >&2
+ exit_status=1
+ fi
+ fi
+ if [[ "${LOCK_HELD}" == true ]] && \
+ ! docker rm --volumes "${LOCK_CONTAINER}" >/dev/null; then
+ echo "Backup finished but its lock container could not be removed" >&2
+ exit_status=1
+ fi
+ exit "${exit_status}"
+ }
+
+ trap 'finish_backup "$?"' EXIT
+ trap 'finish_backup 129' HUP
+ trap 'finish_backup 130' INT
+ trap 'finish_backup 143' TERM
+
+ if docker create --name "${LOCK_CONTAINER}" \
+ --entrypoint /bin/true "${BACKUP_IMAGE_ID}" >/dev/null; then
+ LOCK_HELD=true
+ else
+ echo "Refusing backup because another backup may be running or its lock is stale" >&2
+ exit 1
+ fi
+ BACKUP_FILE="autogpt-data-$(date -u +%Y%m%dT%H%M%SZ).tgz"
+ PARTIAL_FILE="${BACKUP_FILE}.partial"
+ CHECKSUM_FILE="${BACKUP_FILE}.sha256"
+ CHECKSUM_PARTIAL="${CHECKSUM_FILE}.partial"
+ if [[ -e "${BACKUP_DIR}/${BACKUP_FILE}" || \
+ -e "${BACKUP_DIR}/${PARTIAL_FILE}" || \
+ -e "${BACKUP_DIR}/${CHECKSUM_FILE}" || \
+ -e "${BACKUP_DIR}/${CHECKSUM_PARTIAL}" ]]; then
+ echo "Refusing to overwrite an existing backup: ${BACKUP_FILE}" >&2
+ exit 1
+ fi
+ if [[ "$(docker inspect --format '{{.State.Running}}' autogpt)" != true ]]; then
+ echo "Refusing backup because the autogpt container is not running" >&2
+ exit 1
+ fi
+
+ MANAGE_CONTAINER=true
+ docker stop autogpt
+ umask 077
+ ARTIFACTS_STARTED=true
+ touch "${BACKUP_DIR}/${PARTIAL_FILE}"
+ chmod 600 "${BACKUP_DIR}/${PARTIAL_FILE}"
+
+ docker run --rm \
+ --network none \
+ --entrypoint tar \
+ --volume "${BACKUP_VOLUME}:/data:ro" \
+ --volume "${BACKUP_DIR}:/backup" \
+ "${BACKUP_IMAGE_ID}" \
+ --exclude='./cache' -czf "/backup/${PARTIAL_FILE}" -C /data .
+
+ if [[ "${RESTART_AFTER_BACKUP}" == true ]]; then
+ docker start autogpt >/dev/null
+ fi
+
+ BACKUP_SHA256="$(docker run --rm \
+ --network none \
+ --entrypoint sha256sum \
+ --volume "${BACKUP_DIR}:/backup:ro" \
+ "${BACKUP_IMAGE_ID}" \
+ "/backup/${PARTIAL_FILE}" | awk '{print $1}')"
+ if [[ ! "${BACKUP_SHA256}" =~ ^[0-9a-f]{64}$ ]]; then
+ echo "Backup checksum is not a valid SHA-256 digest" >&2
+ exit 1
+ fi
+ printf '%s %s\n' "${BACKUP_SHA256}" "${BACKUP_FILE}" \
+ > "${BACKUP_DIR}/${CHECKSUM_PARTIAL}"
+ mv "${BACKUP_DIR}/${PARTIAL_FILE}" "${BACKUP_DIR}/${BACKUP_FILE}"
+ mv "${BACKUP_DIR}/${CHECKSUM_PARTIAL}" \
+ "${BACKUP_DIR}/${CHECKSUM_FILE}"
+ BACKUP_COMPLETE=true
+ printf 'Backup written to %s with checksum %s\n' \
+ "${BACKUP_DIR}/${BACKUP_FILE}" "${BACKUP_SHA256}"
+ printf 'Image reference: %s\nImage digest: %s\nLocal image ID: %s\n' \
+ "${BACKUP_IMAGE_REF}" "${BACKUP_IMAGE_DIGEST:-unavailable}" \
+ "${BACKUP_IMAGE_ID}"
+)
+```
+
+By default, the block restarts the unchanged installation as soon as the
+archive completes, before calculating its checksum. The exit trap also attempts
+a restart if a backup command fails. For an upgrade, export
+`RESTART_AFTER_BACKUP=false` only for that one block and immediately `unset`
+it afterward, whether the backup succeeds or fails. A successful upgrade backup
+then leaves the appliance stopped at the cutover snapshot. With the default
+setting, verify that it is running again:
+
+```bash
+docker inspect --format '{{.State.Status}}' autogpt
+```
+
+The atomic lock is a stopped helper container named `autogpt-backup-lock`, so it
+serializes backups of `autogpt` even when callers choose different backup
+directories. Catchable exits and signals remove it. After a shell is killed with
+`SIGKILL` or the host crashes, first verify that no backup process is still
+running; then remove only a stale lock with
+`docker rm --volumes autogpt-backup-lock` before retrying. Inspect `BACKUP_DIR`
+for stale `*.partial` files from the interrupted run and remove them only after
+the same check. They can contain plaintext secrets and are not valid backups.
+
+The block writes the checksum to `<archive>.sha256` and prints the container's
+configured image reference, an immutable repository digest when available, and
+the host-local image ID. Record an immutable tag or digest that resolves on the
+restoring host, the environment file, and the Git commit beside the archive.
+For a local-only build, preserve the image separately with an immutable registry
+tag or `docker save`, and load it before restoring. The archive is plaintext and
+contains user content, provider credentials, auth keys, and database passwords.
+Encrypt it with an approved backup mechanism and remove unencrypted staging
+copies.
+
+The anonymous-volume guard also rejects a 64-character lowercase hexadecimal
+volume name as a conservative fallback for Docker engines that omit the
+anonymous-volume label. Use a conventional descriptive name for a manually
+created volume.
+
+## Restore into a new volume
+
+Restore into a new named volume so the source remains recoverable. Set
+`BACKUP_FILE` to the timestamped archive name and `RESTORE_IMAGE` to the
+immutable tag or digest recorded with that backup. If the archive is not under
+`./autogpt-backups`, also set `BACKUP_DIR` before running the block:
+
+```bash
+BACKUP_FILE=autogpt-data-YYYYMMDDTHHMMSSZ.tgz
+RESTORE_IMAGE=significantgravitas/autogpt@sha256:RECORDED_DIGEST
+# BACKUP_DIR=/absolute/path/to/autogpt-backups
+```
+
+```bash
+(
+ set -euo pipefail
+ : "${BACKUP_FILE:?Set BACKUP_FILE to the timestamped archive filename}"
+ : "${RESTORE_IMAGE:?Set RESTORE_IMAGE to the recorded immutable image}"
+ BACKUP_DIR="${BACKUP_DIR:-${PWD}/autogpt-backups}"
+ CHECKSUM_FILE="${BACKUP_FILE}.sha256"
+ DEFAULT_RESTORE_VOLUME="autogpt-data-restored-$(date -u +%Y%m%dT%H%M%SZ)-$$-${RANDOM}${RANDOM}"
+ RESTORE_VOLUME="${RESTORE_VOLUME:-${DEFAULT_RESTORE_VOLUME}}"
+ RESTORE_OWNER_LABEL="org.agpt.restore.owner"
+ RESTORE_OWNER="restore-$(date -u +%Y%m%dT%H%M%SZ)-$$-${RANDOM}${RANDOM}"
+ RESTORE_CREATED=false
+ RESTORE_COMPLETE=false
+
+ if [[ "${BACKUP_FILE}" == */* ]]; then
+ echo "BACKUP_FILE must be a filename within BACKUP_DIR" >&2
+ exit 1
+ fi
+ if [[ ! -d "${BACKUP_DIR}" ]]; then
+ echo "Backup directory does not exist: ${BACKUP_DIR}" >&2
+ exit 1
+ fi
+ BACKUP_DIR="$(cd "${BACKUP_DIR}" && pwd -P)"
+ if [[ ! -f "${BACKUP_DIR}/${BACKUP_FILE}" ]]; then
+ echo "Backup archive does not exist: ${BACKUP_DIR}/${BACKUP_FILE}" >&2
+ exit 1
+ fi
+ if [[ ! -f "${BACKUP_DIR}/${CHECKSUM_FILE}" ]]; then
+ echo "Backup checksum does not exist: ${BACKUP_DIR}/${CHECKSUM_FILE}" >&2
+ exit 1
+ fi
+ EXPECTED_SHA256="$(awk 'NR == 1 {print $1}' \
+ "${BACKUP_DIR}/${CHECKSUM_FILE}")"
+ if [[ ! "${EXPECTED_SHA256}" =~ ^[0-9a-f]{64}$ ]]; then
+ echo "Backup checksum is not a valid SHA-256 digest" >&2
+ exit 1
+ fi
+ ACTUAL_SHA256="$(docker run --rm \
+ --network none \
+ --entrypoint sha256sum \
+ --volume "${BACKUP_DIR}:/backup:ro" \
+ "${RESTORE_IMAGE}" \
+ "/backup/${BACKUP_FILE}" | awk '{print $1}')"
+ if [[ "${ACTUAL_SHA256}" != "${EXPECTED_SHA256}" ]]; then
+ echo "Backup checksum verification failed" >&2
+ exit 1
+ fi
+ if docker volume inspect "${RESTORE_VOLUME}" >/dev/null 2>&1; then
+ echo "Refusing to reuse existing volume: ${RESTORE_VOLUME}" >&2
+ exit 1
+ fi
+
+ # Invoked by the EXIT and signal traps below.
+ # shellcheck disable=SC2329
+ finish_restore() {
+ local exit_status="$1"
+ local current_owner
+ trap - EXIT HUP INT TERM
+ if [[ "${RESTORE_CREATED}" == true && \
+ "${RESTORE_COMPLETE}" != true ]]; then
+ if ! current_owner="$(docker volume inspect \
+ --format "{{ index .Labels \"${RESTORE_OWNER_LABEL}\" }}" \
+ "${RESTORE_VOLUME}" 2>/dev/null)" || \
+ [[ "${current_owner}" != "${RESTORE_OWNER}" ]]; then
+ echo "Restore failed; refusing to remove a volume whose ownership cannot be verified: ${RESTORE_VOLUME}" >&2
+ exit_status=1
+ elif docker volume rm "${RESTORE_VOLUME}" >/dev/null; then
+ echo "Restore failed; the partial restore volume was removed" >&2
+ else
+ echo "Restore failed; remove the partial volume after inspection: docker volume rm ${RESTORE_VOLUME}" >&2
+ exit_status=1
+ fi
+ fi
+ exit "${exit_status}"
+ }
+
+ trap 'finish_restore "$?"' EXIT
+ trap 'finish_restore 129' HUP
+ trap 'finish_restore 130' INT
+ trap 'finish_restore 143' TERM
+ docker volume create \
+ --label "${RESTORE_OWNER_LABEL}=${RESTORE_OWNER}" \
+ "${RESTORE_VOLUME}" >/dev/null
+ if ! CREATED_OWNER="$(docker volume inspect \
+ --format "{{ index .Labels \"${RESTORE_OWNER_LABEL}\" }}" \
+ "${RESTORE_VOLUME}" 2>/dev/null)" || \
+ [[ "${CREATED_OWNER}" != "${RESTORE_OWNER}" ]]; then
+ echo "Refusing to populate a restore volume whose ownership cannot be verified: ${RESTORE_VOLUME}" >&2
+ exit 1
+ fi
+ RESTORE_CREATED=true
+
+ docker run --rm \
+ --network none \
+ --entrypoint tar \
+ --volume "${RESTORE_VOLUME}:/data" \
+ --volume "${BACKUP_DIR}:/backup:ro" \
+ "${RESTORE_IMAGE}" \
+ -xzf "/backup/${BACKUP_FILE}" -C /data
+
+ RESTORE_COMPLETE=true
+ printf 'Restored %s into volume %s\n' \
+ "${BACKUP_FILE}" "${RESTORE_VOLUME}"
+)
+```
+
+A per-run ownership label is checked after volume creation and again before
+failure cleanup. If another run wins the same volume name, this restore refuses
+to populate or remove that volume.
+
+Use only an archive and checksum obtained through a trusted backup process. A
+matching untrusted checksum detects accidental corruption but does not prove
+who created the archive. Restore extraction has no network access, but `tar`
+runs as root and preserves archive ownership and mode bits, including setuid
+bits. Do not extract an archive from an untrusted source or assume network
+isolation makes malicious archive content safe.
+
+Validate the restored layout without starting application services or allowing
+network access. Set `RESTORE_VOLUME` to the volume printed above and reuse the
+same `RESTORE_IMAGE`:
+
+```bash
+(
+ set -euo pipefail
+ : "${RESTORE_VOLUME:?Set RESTORE_VOLUME to the restored volume name}"
+ : "${RESTORE_IMAGE:?Set RESTORE_IMAGE to the recorded immutable image}"
+
+ docker run --rm \
+ --network none \
+ --entrypoint /bin/sh \
+ --volume "${RESTORE_VOLUME}:/data:ro" \
+ "${RESTORE_IMAGE}" \
+ -ceu '
+ test -s /data/config/runtime.env
+ test -s /data/config/backend.json
+ test -s /data/postgres/PG_VERSION
+ test -s /data/postgres/postgresql.conf
+ test -s /data/postgres/pg_hba.conf
+ test -d /data/rabbitmq/mnesia
+ test -d /data/valkey/17000
+ test -d /data/valkey/17001
+ test -d /data/valkey/17002
+ test -d /data/falkordb
+ test -d /data/workspaces
+ test -d /data/home
+ test -d /data/frontend-home
+ quote="$(printf "\047")"
+ setting="^[[:space:]]*listen_addresses([[:space:]]*=[[:space:]]*|[[:space:]]+)"
+ hba_file_setting="^[[:space:]]*hba_file([[:space:]]*=[[:space:]]*|[[:space:]]+)"
+ unsafe_setting="^[[:space:]]*(shared_preload_libraries|local_preload_libraries|"
+ unsafe_setting="${unsafe_setting}session_preload_libraries|archive_mode|"
+ unsafe_setting="${unsafe_setting}archive_command)"
+ unsafe_setting="${unsafe_setting}([[:space:]]*=[[:space:]]*|[[:space:]]+)"
+ include="^[[:space:]]*include(_if_exists|_dir)?([[:space:]]+|[[:space:]]*=)"
+ end="[[:space:]]*(#.*)?$"
+ set -- /data/postgres/postgresql.conf
+ if test -f /data/postgres/postgresql.auto.conf; then
+ set -- "$@" /data/postgres/postgresql.auto.conf
+ fi
+ active_listen="$(grep -hiE "${setting}" "$@" || true)"
+ test "$(printf "%s\n" "${active_listen}" | grep -c .)" -eq 1
+ printf "%s\n" "${active_listen}" | grep -Eiq "${setting}[[:space:]]*${quote}127[.]0[.]0[.]1${quote}${end}"
+ if grep -Eiq "${include}" "$@" || \
+ grep -Eiq "${hba_file_setting}" "$@" || \
+ grep -Eiq "${unsafe_setting}" "$@"; then
+ exit 1
+ fi
+
+ active_hba="$(grep -Ev "^[[:space:]]*(#|$)" /data/postgres/pg_hba.conf || true)"
+ test "$(printf "%s\n" "${active_hba}" | grep -c .)" -eq 6
+ hba_rule="^[[:space:]]*(local[[:space:]]+(all|replication)[[:space:]]+all[[:space:]]+peer|host[[:space:]]+(all|replication)[[:space:]]+all[[:space:]]+(127[.]0[.]0[.]1/32|::1/128)[[:space:]]+scram-sha-256)${end}"
+ if printf "%s\n" "${active_hba}" | grep -Ev "${hba_rule}"; then
+ exit 1
+ fi
+ for required_hba_rule in \
+ "^[[:space:]]*local[[:space:]]+all[[:space:]]+all[[:space:]]+peer${end}" \
+ "^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+127[.]0[.]0[.]1/32[[:space:]]+scram-sha-256${end}" \
+ "^[[:space:]]*host[[:space:]]+all[[:space:]]+all[[:space:]]+::1/128[[:space:]]+scram-sha-256${end}" \
+ "^[[:space:]]*local[[:space:]]+replication[[:space:]]+all[[:space:]]+peer${end}" \
+ "^[[:space:]]*host[[:space:]]+replication[[:space:]]+all[[:space:]]+127[.]0[.]0[.]1/32[[:space:]]+scram-sha-256${end}" \
+ "^[[:space:]]*host[[:space:]]+replication[[:space:]]+all[[:space:]]+::1/128[[:space:]]+scram-sha-256${end}"
+ do
+ printf "%s\n" "${active_hba}" | grep -Eq "${required_hba_rule}"
+ done
+ '
+)
+```
+
+The check also rejects PostgreSQL configuration that enables non-loopback
+listening, loads external configuration fragments or libraries, redirects
+`hba_file`, configures WAL archiving, or weakens the generated local `peer` and
+loopback `scram-sha-256` access rules.
+It does not prove that each database can start. A full
+recovery rehearsal boots live schedules, stored credentials, and executors,
+and some services fetch runtime data during startup. Perform it only on a
+dedicated egress-filtered host or network after revoking or replacing
+production provider and integration credentials. There is no generic appliance
+switch that safely disables every possible outbound action. Retain both
+volumes until the restore is accepted.
+
+Never selectively mix service directories from different backups.
+
+After accepting the restore, make sure no other container uses the `autogpt`
+name or host port. Set `ENV_FILE` to the recorded environment file's absolute
+host path. Set `PUBLISH_SPEC` to the original publish mapping when it was not
+`127.0.0.1:3000:3000`. For a Docker Engine local-model installation, also set
+`ADD_HOST_SPEC=host.docker.internal:host-gateway`; leave it empty otherwise.
+Then launch the restored installation with the recorded image and volume:
+
+```bash
+ENV_FILE=/absolute/path/to/autogpt.env
+RESTORE_VOLUME=autogpt-data-restored-YYYYMMDDTHHMMSSZ-PID-RANDOM
+RESTORE_IMAGE=significantgravitas/autogpt@sha256:RECORDED_DIGEST
+# PUBLISH_SPEC=127.0.0.1:3300:3000
+# ADD_HOST_SPEC=host.docker.internal:host-gateway
+```
+
+```bash
+(
+ set -euo pipefail
+ : "${ENV_FILE:?Set ENV_FILE to the recorded host environment-file path}"
+ : "${RESTORE_VOLUME:?Set RESTORE_VOLUME to the restored volume name}"
+ : "${RESTORE_IMAGE:?Set RESTORE_IMAGE to the recorded immutable image}"
+ PUBLISH_SPEC="${PUBLISH_SPEC:-127.0.0.1:3000:3000}"
+ ADD_HOST_SPEC="${ADD_HOST_SPEC:-}"
+ NETWORK_DOCKER_ARGS=(--publish "${PUBLISH_SPEC}")
+ if [[ -n "${ADD_HOST_SPEC}" ]]; then
+ NETWORK_DOCKER_ARGS+=(--add-host "${ADD_HOST_SPEC}")
+ fi
+
+ [[ "${ENV_FILE}" = /* && -f "${ENV_FILE}" ]] || {
+ printf 'ENV_FILE must be an existing absolute host path: %s\n' \
+ "${ENV_FILE}" >&2
+ exit 1
+ }
+ if ! docker volume inspect "${RESTORE_VOLUME}" >/dev/null 2>&1; then
+ echo "Restored volume does not exist: ${RESTORE_VOLUME}" >&2
+ exit 1
+ fi
+ if docker container inspect autogpt >/dev/null 2>&1; then
+ echo "Refusing to replace an existing container named autogpt" >&2
+ exit 1
+ fi
+
+ docker run --detach --name autogpt \
+ --restart unless-stopped \
+ --shm-size 2g \
+ --ulimit nofile=65536:65536 \
+ --log-driver json-file \
+ --log-opt max-size=50m \
+ --log-opt max-file=5 \
+ "${NETWORK_DOCKER_ARGS[@]}" \
+ --env-file "${ENV_FILE}" \
+ --volume "${RESTORE_VOLUME}:/data" \
+ "${RESTORE_IMAGE}"
+)
+```
+
+## Upgrade and rollback
+
+Before an upgrade:
+
+1. Record the running image reference and image ID.
+2. Pull or build the new image while the old appliance remains available.
+3. Run `export RESTART_AFTER_BACKUP=false`, then run the Cold backup block once.
+ Immediately run `unset RESTART_AFTER_BACKUP` afterward, whether the backup
+ succeeds or fails. A successful backup leaves the appliance stopped; a
+ failed backup restarts the unchanged installation.
+4. Remove only the stopped container with `docker rm autogpt`.
+5. Repeat the Quick start run command with the same environment file, named
+ volume, publish mapping, `--add-host`, and other original launch options, but
+ the new image reference.
+6. Wait for full health, then test login, memory, one agent execution, streaming,
+ WebSockets, and persistence across one restart.
+
+Useful image evidence is available with:
+
+```bash
+docker inspect --format '{{.Config.Image}} {{.Image}}' autogpt
+```
+
+Startup applies database migrations before publishing readiness. Do not run an
+older image against a volume already migrated by a newer image. Rollback means
+running the prior image with its matching pre-upgrade archive restored into a
+new volume.
+
+## Health and troubleshooting
+
+Docker health checks every bundled dependency and application role:
+
+```bash
+docker inspect --format '{{.State.Health.Status}}' autogpt
+docker exec autogpt autogpt-healthcheck
+docker logs --follow --tail 100 autogpt
+```
+
+`GET /healthz` checks nginx only; it is not proof that the whole appliance is
+ready. The watchdog allows 600 seconds for initial full health; if that deadline
+expires, it stops the container and `--restart unless-stopped` begins another
+startup attempt.
+
+| Symptom | What to check |
+| --- | --- |
+| The browser cannot connect after `docker run --rm "${IMAGE}"` | A bare run does not publish a port. Use the complete Quick start command. |
+| Port `3300` opens but auth actions fail | Use `--publish 127.0.0.1:3300:3000` and set `AUTOGPT_PUBLIC_URL=http://localhost:3300`, then replace the container. |
+| Signup shows **Email Not Allowed** | Inspect the API response or container logs to distinguish closed registration from an allowlist miss. Set `AUTH_ALLOW_NEW_ACCOUNTS=true` with an exact-address `[email protected]`, replace the container, create the intended accounts, and close signup again. |
+| The container remains `starting` or becomes `unhealthy` | First boot can take several minutes. Run `autogpt-healthcheck` and inspect container logs for the first failed service. |
+| The container is OOM-killed or repeatedly restarts during startup | The appliance uses about 5–6 GiB before workload headroom. On Docker Desktop, increase the VM memory allocation under **Settings → Resources**. |
+| Startup refuses to continue after an interrupted migration | Follow the empty-install versus existing-install recovery procedure in [Quick start](#quick-start). The restart-looping container cannot reliably run `docker exec`; do not mark the migration applied or rolled back until you verify which database changes completed. |
+| Startup rejects `DB_CONNECTION_LIMIT`, `DB_CONNECT_TIMEOUT`, or `DB_POOL_TIMEOUT` | Use an integer in the supported range: `1`–`5`, `1`–`600`, and `1`–`3600`, respectively. |
+| Startup rejects legacy JWT secrets | Remove `JWT_VERIFY_KEY` and `SUPABASE_JWT_SECRET` for a fresh Better Auth installation. Set `AUTOGPT_ENABLE_LEGACY_AUTH=true` only for an intentional legacy-auth migration, and set both legacy variables to the same shared secret of at least 32 characters. |
+| A run stays `RUNNING` without progress after a restart | The container stopped while the run was in flight. Its message was dropped and the row was not reconciled; start a new run. |
+| Requests stall for minutes under concurrent runs | Inspect backend and PostgreSQL logs for connection-pool exhaustion. `DB_CONNECTION_LIMIT` cannot be raised above its default maximum of `5`; lowering `DB_POOL_TIMEOUT` makes pool exhaustion fail sooner but does not add capacity. Reduce concurrency or move to a distributed deployment when the fixed pools are insufficient. |
+| AutoPilot returns a provider `401` | Configure the key for the selected transport. The default remote route needs `OPEN_ROUTER_API_KEY`; complete remote memory also needs `OPENAI_API_KEY`. |
+| Local chat works but memory ingestion fails | Install the configured embedding model and confirm its `/v1/embeddings` endpoint works. If the server does not provide the default Qwen and `nomic-embed-text` slugs, set and install `GRAPHITI_LLM_MODEL`, `GRAPHITI_RERANKER_MODEL`, and `GRAPHITI_EMBEDDER_MODEL` explicitly. |
+| Ollama cannot be reached | Keep the host-gateway option, ensure Ollama listens on an address Docker can reach, and test `/api/tags` from inside the container. |
+| The container exits after a persistent health failure | The watchdog intentionally stops the appliance. Keep `--restart unless-stopped` so Docker can recover it. |
+| Data appears missing after replacement | The new container is using another or anonymous `/data` volume. Inspect its mount and reattach the original named volume. |
+| Restore launch reports the name `autogpt` or the host port is already in use | Inspect the leftover container and its `/data` mount. Free the intended host port, then run `docker rm autogpt` only after confirming the restored volume and launch settings are the intended replacement. |
+
+## Known limitations
+
+- One container is one failure, maintenance, scaling, and security boundary.
+- The bundled frontend is compiled in local mode. Setting backend
+ `BEHAVE_AS=cloud` does not create a supported multi-tenant hosted deployment.
+- PostgreSQL, Valkey, RabbitMQ, FalkorDB, browser tooling, and the
+ application compete for the same host resources.
+- Valkey and FalkorDB have no appliance-level memory ceiling or eviction policy;
+ their persisted working sets can grow until host memory or disk is exhausted.
+ Monitor both resources and back up before capacity changes.
+- Each backend role's Prisma pool has at most five PostgreSQL connections. The
+ scheduler also has two SQLAlchemy job-store pools of three connections each.
+ FalkorDB is configured for at most 25 queued queries and a 1-second query
+ timeout. These fixed ceilings limit concurrency in the single-container
+ distribution.
+- All durable services share one volume and one backup schedule.
+- There is no supported in-place conversion from the appliance to the
+ multi-container or hosted deployment. Provision the destination separately
+ and use agent export/import where supported; accounts, run history, schedules,
+ credentials, and memory are not migrated automatically.
+- Uploaded files are not scanned for malware. Unlike the hosted platform, this
+ image bundles no antivirus daemon, so treat every upload as trusted input.
+- Required email verification is unsupported.
+- The prebuilt frontend cannot configure Google Picker public keys at runtime.
+- Remote TLS termination is operator-supplied.
+- The local `bash_exec` fallback depends on host support for Bubblewrap user and
+ network namespaces. Do not make the entire appliance privileged to work
+ around a host that disables them.