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.
feat(platform): add single-container distribution (#13758)
Nicholas Tindle18608f5b2202
diff --git a/.github/scripts/platform-single-container-smoke.sh b/.github/scripts/platform-single-container-smoke.shnew file mode 100644index 0000000000..35cbf3d955--- /dev/null+++ b/.github/scripts/platform-single-container-smoke.sh@@ -0,0 +1,850 @@+#!/usr/bin/env bash++set -Eeuo pipefail++: "${SMOKE_IMAGE:?SMOKE_IMAGE is required}"+: "${SMOKE_PLATFORM:?SMOKE_PLATFORM is required}"++readonly PUBLIC_URL=http://localhost:3300+readonly TIMEOUT_SECONDS="${SMOKE_TIMEOUT_SECONDS:-2700}"+readonly SAFE_PLATFORM="${SMOKE_PLATFORM//\//-}"+readonly RUN_TOKEN="${GITHUB_RUN_ID:-local}-${GITHUB_RUN_ATTEMPT:-0}-${SAFE_PLATFORM}-${RANDOM}"+readonly RUN_CONTAINER_NAME="autogpt-single-smoke-${RUN_TOKEN}"+readonly NEGATIVE_CONTAINER_NAME="${RUN_CONTAINER_NAME}-negative"+HEADERS_FILE="$(mktemp)"+readonly HEADERS_FILE+AUTH_COOKIE_FILE="$(mktemp)"+readonly AUTH_COOKIE_FILE++CONTAINER_NAME="${RUN_CONTAINER_NAME}"+DATA_VOLUME=++diagnostics() {+ if docker container inspect "${CONTAINER_NAME}" >/dev/null 2>&1; then+ docker inspect --format '{{json .State}}' "${CONTAINER_NAME}" || true+ docker logs --timestamps --tail 2000 "${CONTAINER_NAME}" || true+ fi+}++cleanup() {+ local result=$?+ local container+ trap - EXIT INT TERM+ if ((result != 0)); then+ diagnostics+ fi+ for container in "${CONTAINER_NAME}" "${NEGATIVE_CONTAINER_NAME}"; do+ if docker container inspect "${container}" >/dev/null 2>&1; then+ docker stop --timeout 360 "${container}" >/dev/null 2>&1 || true+ docker rm --force --volumes "${container}" >/dev/null 2>&1 || true+ fi+ done+ if [[ -n "${DATA_VOLUME}" ]] && docker volume inspect "${DATA_VOLUME}" >/dev/null 2>&1; then+ docker volume rm "${DATA_VOLUME}" >/dev/null 2>&1 || true+ fi+ rm -f "${HEADERS_FILE}" "${AUTH_COOKIE_FILE}"+ exit "${result}"+}++trap cleanup EXIT+trap 'exit 130' INT+trap 'exit 143' TERM++[[ "${TIMEOUT_SECONDS}" =~ ^[0-9]+$ ]] || {+ echo "SMOKE_TIMEOUT_SECONDS must be an integer" >&2+ exit 2+}++appliance_is_healthy_and_armed() {+ docker exec "${CONTAINER_NAME}" \+ /usr/bin/test -f /run/autogpt/watchdog-armed >/dev/null 2>&1 &&+ docker exec "${CONTAINER_NAME}" \+ /usr/local/bin/autogpt-healthcheck >/dev/null 2>&1+}++wait_for_healthy() {+ local deadline=$((SECONDS + TIMEOUT_SECONDS))+ local state+ local health+ local exit_code+ while ((SECONDS < deadline)); do+ read -r state health exit_code < <(+ docker inspect \+ --format '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}missing{{end}} {{.State.ExitCode}}' \+ "${CONTAINER_NAME}"+ )+ case "${state}:${health}" in+ running:healthy)+ if appliance_is_healthy_and_armed; then+ return 0+ fi+ ;;+ exited:* | dead:* | removing:* | *:unhealthy)+ echo "container failed while waiting for health: state=${state} health=${health} exit=${exit_code}" >&2+ return 1+ ;;+ esac+ sleep 10+ done+ echo "container did not become healthy within ${TIMEOUT_SECONDS}s" >&2+ return 1+}++wait_for_automatic_restart() {+ local minimum_restart_count="$1"+ local deadline=$((SECONDS + TIMEOUT_SECONDS))+ local state+ local health+ local restart_count+ while ((SECONDS < deadline)); do+ read -r state health restart_count < <(+ docker inspect \+ --format '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}missing{{end}} {{.RestartCount}}' \+ "${CONTAINER_NAME}"+ )+ if [[ "${state}:${health}" == running:healthy ]] &&+ ((restart_count >= minimum_restart_count)) &&+ appliance_is_healthy_and_armed; then+ return 0+ fi+ case "${state}" in+ dead | removing)+ echo "container failed while waiting for automatic restart: state=${state}" >&2+ return 1+ ;;+ esac+ sleep 10+ done+ echo "container did not automatically restart and become healthy" >&2+ return 1+}++runtime_config_hash() {+ docker exec "${CONTAINER_NAME}" sha256sum /data/config/runtime.env | awk '{print $1}'+}++discover_data_volume() {+ local mount_record+ local mount_type+ mount_record="$(+ docker inspect \+ --format '{{range .Mounts}}{{if eq .Destination "/data"}}{{.Type}} {{.Name}}{{println}}{{end}}{{end}}' \+ "${CONTAINER_NAME}"+ )"+ read -r mount_type DATA_VOLUME <<<"${mount_record}"+ [[ "${mount_type}" == volume && "${DATA_VOLUME}" =~ ^[A-Za-z0-9_.-]+$ ]] || {+ echo "image did not create one Docker volume at /data" >&2+ return 1+ }+}++preseed_hostile_backend_config() {+ docker run --rm \+ --platform "${SMOKE_PLATFORM}" \+ --volume "${DATA_VOLUME}:/data" \+ --entrypoint /app/autogpt_platform/backend/.venv/bin/python \+ "${SMOKE_IMAGE}" -c '+import json+import os+from pathlib import Path++path = Path("/data/config/backend.json")+path.write_text(json.dumps({+ "pyro_host": "0.0.0.0",+ "websocket_server_host": "0.0.0.0",+ "websocket_server_port": 18001,+ "execution_manager_port": 18002,+ "execution_scheduler_port": 18003,+ "database_api_port": 18005,+ "agent_api_host": "0.0.0.0",+ "agent_api_port": 18006,+ "notification_service_port": 18007,+ "copilot_executor_port": 18008,+ "platform_linking_service_port": 18009,+ "copilot_chat_bridge_port": 18010,+ "batch_executor_port": 18011,+}) + "\n", encoding="utf-8")+os.chown(path, 10001, 10001)+os.chmod(path, 0o600)+' >/dev/null+}++assert_pinned_topology_environment() {+ local pid+ local process_env+ pid="$(+ docker exec "${CONTAINER_NAME}" \+ supervisorctl -c /opt/autogpt/single-container/supervisor/supervisord.conf pid rest+ )"+ [[ "${pid}" =~ ^[0-9]+$ ]]+ # Docker Desktop can deny cross-UID /proc reads even to container root.+ # Read the service environment as the same unprivileged UID instead.+ process_env="$(+ docker exec --user autogpt "${CONTAINER_NAME}" \+ /bin/bash -Eeuo pipefail -c 'tr "\0" "\n" <"/proc/${1}/environ"' \+ bash "${pid}"+ )"+ for expected in \+ PYRO_HOST=127.0.0.1 \+ WEBSOCKET_SERVER_HOST=127.0.0.1 WEBSOCKET_SERVER_PORT=8001 \+ EXECUTION_MANAGER_PORT=8002 EXECUTION_SCHEDULER_PORT=8003 \+ DATABASE_API_PORT=8005 AGENT_API_HOST=127.0.0.1 AGENT_API_PORT=8006 \+ NOTIFICATION_SERVICE_PORT=8007 COPILOT_EXECUTOR_PORT=8008 \+ PLATFORM_LINKING_SERVICE_PORT=8009 COPILOT_CHAT_BRIDGE_PORT=8010 \+ BATCH_EXECUTOR_PORT=8011 FORCE_FLAG_GRAPHITI_MEMORY=true; do+ grep -Fxq "${expected}" <<<"${process_env}"+ done+}++assert_frontend_database_isolation() {+ local next_pid+ local nginx_pid+ local rest_pid+ local next_uid+ local nginx_uid+ local rest_uid+ local assertions++ next_pid="$(+ docker exec "${CONTAINER_NAME}" \+ supervisorctl -c /opt/autogpt/single-container/supervisor/supervisord.conf \+ pid next+ )"+ rest_pid="$(+ docker exec "${CONTAINER_NAME}" \+ supervisorctl -c /opt/autogpt/single-container/supervisor/supervisord.conf \+ pid rest+ )"+ nginx_pid="$(+ docker exec "${CONTAINER_NAME}" \+ supervisorctl -c /opt/autogpt/single-container/supervisor/supervisord.conf \+ pid nginx+ )"+ [[ "${next_pid}" =~ ^[0-9]+$ && "${rest_pid}" =~ ^[0-9]+$ && \+ "${nginx_pid}" =~ ^[0-9]+$ ]]++ next_uid="$(docker exec "${CONTAINER_NAME}" stat -c '%u' "/proc/${next_pid}")"+ rest_uid="$(docker exec "${CONTAINER_NAME}" stat -c '%u' "/proc/${rest_pid}")"+ nginx_uid="$(docker exec "${CONTAINER_NAME}" stat -c '%u' "/proc/${nginx_pid}")"+ [[ "${next_uid}" == 10005 && "${nginx_uid}" == 10006 && \+ "${rest_uid}" == 10001 && "${next_uid}" != "${rest_uid}" && \+ "${nginx_uid}" != "${rest_uid}" ]] || {+ echo "public and backend process identities are not isolated" >&2+ return 1+ }++ docker exec --user autogpt_frontend "${CONTAINER_NAME}" \+ /bin/bash -Eeuo pipefail -c '+ [[ ! -r /data/config/runtime.env ]]+ [[ ! -r "/proc/${1}/environ" ]]+ ' bash "${rest_pid}"++ docker exec --user autogpt_proxy "${CONTAINER_NAME}" \+ /bin/bash -Eeuo pipefail -c '+ [[ ! -r /data/config/runtime.env ]]+ [[ ! -r "/proc/${1}/environ" ]]+ [[ ! -r "/proc/${2}/environ" ]]+ ' bash "${rest_pid}" "${next_pid}"++ docker exec --interactive --user autogpt_frontend "${CONTAINER_NAME}" \+ /app/autogpt_platform/backend/.venv/bin/python - "${next_pid}" <<'PY'+import sys+from pathlib import Path+from urllib.parse import parse_qs, urlsplit++environment = {}+for item in Path(f"/proc/{sys.argv[1]}/environ").read_bytes().split(b"\0"):+ if item:+ name, value = item.split(b"=", 1)+ environment[name.decode("ascii")] = value.decode("utf-8")++forbidden = {+ "AUTH_DATABASE_URL",+ "DB_PASS",+ "DIRECT_URL",+ "ENCRYPTION_KEY",+ "GRAPHITI_FALKORDB_PASSWORD",+ "POSTGRES_PASSWORD",+ "RABBITMQ_DEFAULT_PASS",+ "REDIS_PASSWORD",+ "UNSUBSCRIBE_SECRET_KEY",+ "VAPID_PRIVATE_KEY",+}+assert forbidden.isdisjoint(environment)++database_url = urlsplit(environment["DATABASE_URL"])+query = parse_qs(database_url.query, strict_parsing=True)+assert database_url.scheme == "postgresql"+assert database_url.hostname is None+assert database_url.username is None+assert database_url.password is None+assert database_url.path == "/postgres"+assert query == {+ "host": ["/run/postgresql"],+ "user": ["autogpt_frontend"],+}+PY++ assertions="$(+ docker exec --interactive --user autogpt_frontend "${CONTAINER_NAME}" \+ /usr/bin/env -i \+ PATH=/usr/lib/postgresql/15/bin:/usr/bin:/bin \+ PGHOST=/run/postgresql \+ PGDATABASE=postgres \+ PGUSER=autogpt_frontend \+ psql --no-psqlrc --tuples-only --no-align --set=ON_ERROR_STOP=1 <<'SQL'+SELECT current_user = 'autogpt_frontend'+ AND NOT rolsuper+ AND NOT rolcreatedb+ AND NOT rolcreaterole+ AND NOT rolinherit+ AND NOT rolreplication+ AND NOT rolbypassrls+ AND rolconnlimit = 10+FROM pg_catalog.pg_roles+WHERE rolname = current_user;++SELECT count(*) = 0+FROM pg_catalog.pg_auth_members membership+JOIN pg_catalog.pg_roles role ON role.oid = membership.member+WHERE role.rolname = current_user;++SELECT has_database_privilege(current_user, 'postgres', 'CONNECT')+ AND NOT has_database_privilege(current_user, 'postgres', 'TEMPORARY')+ AND has_schema_privilege(current_user, 'platform', 'USAGE')+ AND NOT has_schema_privilege(current_user, 'platform', 'CREATE')+ AND NOT has_schema_privilege(current_user, 'public', 'CREATE')+ AND NOT has_schema_privilege(current_user, 'auth', 'USAGE');++SELECT COALESCE(+ bool_and(NOT has_function_privilege(current_user, function.oid, 'EXECUTE')),+ true+)+FROM pg_catalog.pg_proc function+JOIN pg_catalog.pg_namespace namespace ON namespace.oid = function.pronamespace+WHERE namespace.nspname = 'platform';++WITH required_table(name) AS (+ VALUES+ ('UserAuthIdentity'),+ ('UserAuthSession'),+ ('UserAuthAccount'),+ ('UserAuthVerification'),+ ('UserAuthJwks')+), required_privilege(name) AS (+ VALUES ('SELECT'), ('INSERT'), ('UPDATE'), ('DELETE')+)+SELECT bool_and(+ has_table_privilege(+ current_user,+ format('platform.%I', required_table.name),+ required_privilege.name+ )+)+FROM required_table CROSS JOIN required_privilege;++WITH required_table(name) AS (+ VALUES+ ('UserAuthIdentity'),+ ('UserAuthSession'),+ ('UserAuthAccount'),+ ('UserAuthVerification'),+ ('UserAuthJwks')+)+SELECT bool_and(+ NOT has_table_privilege(+ current_user,+ format('platform.%I', required_table.name),+ 'TRUNCATE'+ )+)+FROM required_table;++SELECT has_column_privilege(current_user, 'platform."User"', 'id', 'SELECT')+ AND has_column_privilege(current_user, 'platform."User"', 'email', 'SELECT')+ AND has_column_privilege(current_user, 'platform."User"', 'email', 'UPDATE')+ AND has_column_privilege(current_user, 'platform."User"', 'updatedAt', 'UPDATE')+ AND NOT has_column_privilege(current_user, 'platform."User"', 'metadata', 'SELECT')+ AND NOT has_column_privilege(current_user, 'platform."User"', 'metadata', 'UPDATE')+ AND NOT has_table_privilege(current_user, 'platform."User"', 'SELECT')+ AND NOT has_table_privilege(current_user, 'platform."User"', 'UPDATE');+SQL+ )"+ [[ "${assertions}" == $'t\nt\nt\nt\nt\nt\nt' ]] || {+ echo "frontend database privileges are broader or narrower than expected" >&2+ printf 'database privilege assertions:\n%s\n' "${assertions}" >&2+ return 1+ }+ if docker exec --user autogpt_frontend "${CONTAINER_NAME}" \+ /usr/bin/env -i \+ PATH=/usr/lib/postgresql/15/bin:/usr/bin:/bin \+ PGHOST=/run/postgresql \+ PGDATABASE=postgres \+ PGUSER=autogpt_frontend \+ psql --no-psqlrc --set=ON_ERROR_STOP=1 \+ --command='SET ROLE postgres' >/dev/null 2>&1; then+ echo "frontend database role can assume postgres" >&2+ return 1+ fi++ if docker exec --user autogpt_proxy "${CONTAINER_NAME}" \+ /usr/bin/env -i \+ PATH=/usr/bin:/bin \+ /app/autogpt_platform/backend/.venv/bin/python \+ /opt/autogpt/single-container/probe.py redis --port 17000 \+ >/dev/null 2>&1; then+ echo "nginx operating-system user can access Valkey without authentication" >&2+ return 1+ fi++ [[ "$(+ docker exec --user postgres "${CONTAINER_NAME}" \+ /usr/bin/env -i \+ PATH=/usr/lib/postgresql/15/bin:/usr/bin:/bin \+ PGHOST=/run/postgresql \+ PGDATABASE=postgres \+ PGUSER=postgres \+ psql --no-psqlrc --tuples-only --no-align --set=ON_ERROR_STOP=1 \+ --command="SELECT rolpassword IS NULL FROM pg_catalog.pg_authid WHERE rolname = 'autogpt_frontend'"+ )" == t ]] || {+ echo "frontend database role unexpectedly has a password" >&2+ return 1+ }++ if docker exec --user autogpt_frontend "${CONTAINER_NAME}" \+ /usr/bin/env -i \+ PATH=/usr/lib/postgresql/15/bin:/usr/bin:/bin \+ PGHOST=/run/postgresql \+ PGDATABASE=postgres \+ PGUSER=postgres \+ psql --no-psqlrc --set=ON_ERROR_STOP=1 \+ --command='SELECT 1' >/dev/null 2>&1; then+ echo "frontend operating-system user can authenticate as postgres" >&2+ return 1+ fi++ if docker exec --user autogpt_frontend "${CONTAINER_NAME}" \+ /usr/bin/env -i \+ PATH=/usr/bin:/bin \+ /app/autogpt_platform/backend/.venv/bin/python \+ /opt/autogpt/single-container/probe.py redis --port 17000 \+ >/dev/null 2>&1; then+ echo "frontend operating-system user can access Valkey without authentication" >&2+ return 1+ fi++ docker exec "${CONTAINER_NAME}" \+ curl --fail --silent --show-error --max-time 30 \+ http://127.0.0.1:3001/api/auth/jwks >/dev/null+}++assert_email_auth_flow() {+ local email="single-container-${RUN_TOKEN}@example.com"+ local password=single-container-smoke-password # pragma: allowlist secret++ curl --fail-with-body --silent --show-error --max-time 30 \+ --cookie-jar "${AUTH_COOKIE_FILE}" \+ --request POST --header 'Content-Type: application/json' \+ --header "Origin: ${PUBLIC_URL}" \+ --data "{\"name\":\"Single Container Smoke\",\"email\":\"${email}\",\"password\":\"${password}\"}" \+ "${PUBLIC_URL}/api/auth/sign-up/email" >/dev/null++ curl --fail-with-body --silent --show-error --max-time 30 \+ --cookie "${AUTH_COOKIE_FILE}" \+ "${PUBLIC_URL}/api/auth/get-session" |+ python3 -c \+ 'import json, sys; assert json.load(sys.stdin)["user"]["email"] == sys.argv[1]' \+ "${email}"++ curl --fail-with-body --silent --show-error --max-time 30 \+ --cookie "${AUTH_COOKIE_FILE}" --cookie-jar "${AUTH_COOKIE_FILE}" \+ --request POST --header 'Content-Type: application/json' \+ --header "Origin: ${PUBLIC_URL}" --data '{}' \+ "${PUBLIC_URL}/api/auth/sign-out" >/dev/null++ curl --fail-with-body --silent --show-error --max-time 30 \+ --cookie-jar "${AUTH_COOKIE_FILE}" \+ --request POST --header 'Content-Type: application/json' \+ --header "Origin: ${PUBLIC_URL}" \+ --data "{\"email\":\"${email}\",\"password\":\"${password}\"}" \+ "${PUBLIC_URL}/api/auth/sign-in/email" >/dev/null++ curl --fail-with-body --silent --show-error --max-time 30 \+ --cookie "${AUTH_COOKIE_FILE}" \+ "${PUBLIC_URL}/api/auth/get-session" |+ python3 -c \+ 'import json, sys; assert json.load(sys.stdin)["user"]["email"] == sys.argv[1]' \+ "${email}"+}++assert_request_tokens_absent_from_logs() {+ local sentinel=AUTOGPT_LOG_SENTINEL_6f2b3cb87e9a+ local websocket_key=dGhlIHNhbXBsZSBub25jZQ== # pragma: allowlist secret # gitleaks:allow+ local websocket_status++ curl --fail --silent --show-error --max-time 30 \+ "${PUBLIC_URL}/_agpt/health?token=${sentinel}" >/dev/null+ curl --silent --show-error --max-time 30 \+ "${PUBLIC_URL}/link/${sentinel}?token=${sentinel}" >/dev/null+ websocket_status="$(+ curl --silent --show-error --max-time 30 --http1.1 \+ --output /dev/null --write-out '%{http_code}' \+ --header 'Connection: Upgrade' \+ --header 'Upgrade: websocket' \+ --header 'Sec-WebSocket-Version: 13' \+ --header "Sec-WebSocket-Key: ${websocket_key}" \+ --header "Origin: ${PUBLIC_URL}" \+ "${PUBLIC_URL}/_agpt/ws?token=${sentinel}"+ )"+ [[ "${websocket_status}" == 403 ]] || {+ echo "invalid-token WebSocket handshake returned ${websocket_status}, expected 403" >&2+ return 1+ }+ sleep 2+ # Do not use grep -q here: with pipefail an early grep exit can SIGPIPE+ # `docker logs` and accidentally turn a positive match into a false result.+ if docker logs "${CONTAINER_NAME}" 2>&1 | grep -F "${sentinel}" >/dev/null; then+ echo "request token sentinel leaked into container logs" >&2+ return 1+ fi+}++assert_internal_tooling_is_private() {+ local path+ local status+ for path in \+ /_agpt/docs /_agpt/redoc /_agpt/openapi.json /_agpt/metrics \+ /_agpt/external-api/docs /_agpt/external-api/redoc \+ /_agpt/external-api/openapi.json /_agpt/external-api/metrics; do+ status="$(+ curl --silent --show-error --max-time 30 \+ --output /dev/null --write-out '%{http_code}' "${PUBLIC_URL}${path}"+ )"+ [[ "${status}" == 404 ]] || {+ echo "internal tooling path ${path} returned ${status}, expected 404" >&2+ return 1+ }+ done+}++assert_runtime_config_mode() {+ local ownership_and_mode+ ownership_and_mode="$(+ docker exec "${CONTAINER_NAME}" stat -c '%u:%g:%a' /data/config/runtime.env+ )"+ [[ "${ownership_and_mode}" == 0:0:600 ]] || {+ echo "runtime config ownership/mode is not root:root 0600" >&2+ return 1+ }+}++assert_prisma_cli_is_prebundled() {+ docker exec "${CONTAINER_NAME}" \+ /usr/bin/test -f \+ /opt/prisma-python/binaries/node_modules/prisma/build/index.js+ if docker logs "${CONTAINER_NAME}" 2>&1 | \+ grep -F "Installing Prisma CLI" >/dev/null; then+ echo "Prisma CLI was installed during container startup" >&2+ return 1+ fi+}++assert_falkordb_binary_contract() {+ local linkage+ local listeners+ linkage="$(+ docker exec "${CONTAINER_NAME}" /bin/bash -Eeuo pipefail -c '+ ldd /opt/falkordb/redis-server+ ldd /opt/falkordb/falkordb.so+ '+ )"+ if grep -F "not found" <<<"${linkage}" >/dev/null; then+ echo "FalkorDB has an unresolved shared-library dependency" >&2+ return 1+ fi++ listeners="$(docker exec "${CONTAINER_NAME}" ss -lnt)"+ grep -Eq '127\.0\.0\.1:6380([[:space:]]|$)' <<<"${listeners}" || {+ echo "FalkorDB is not listening on the private loopback address" >&2+ return 1+ }+ if grep -Eq '(0\.0\.0\.0|\[::\]):6380([[:space:]]|$)' <<<"${listeners}"; then+ echo "FalkorDB is listening on a public container interface" >&2+ return 1+ fi+ if [[ -n "$(docker port "${CONTAINER_NAME}" 6380 2>/dev/null)" ]]; then+ echo "FalkorDB port 6380 is published by Docker" >&2+ return 1+ fi+}++assert_memory_contract() {+ local action="$1"+ docker exec --interactive \+ --workdir /app/autogpt_platform/backend \+ "${CONTAINER_NAME}" \+ /app/autogpt_platform/backend/.venv/bin/python - "${action}" <<'PY'+import asyncio+import shlex+import sys+from pathlib import Path++from falkordb import FalkorDB+from redis import Redis+from redis.exceptions import AuthenticationError+++def runtime_value(name: str) -> str:+ for line in Path("/data/config/runtime.env").read_text().splitlines():+ if line.startswith(f"{name}="):+ values = shlex.split(line.split("=", 1)[1])+ if len(values) == 1:+ return values[0]+ raise AssertionError(f"missing {name} in runtime config")+++password = runtime_value("GRAPHITI_FALKORDB_PASSWORD")+try:+ Redis(host="127.0.0.1", port=6380, password="wrong-password").ping()+except AuthenticationError:+ pass+else:+ raise AssertionError("FalkorDB accepted an invalid password")++redis = Redis(host="127.0.0.1", port=6380, password=password)+assert redis.ping()+assert "graph" in repr(redis.execute_command("MODULE", "LIST")).lower()+for setting, expected in {+ "MAX_QUEUED_QUERIES": "25",+ "TIMEOUT": "1000",+ "RESULTSET_SIZE": "10000",+}.items():+ configured = redis.execute_command("GRAPH.CONFIG", "GET", setting)+ assert expected in repr(configured), (setting, configured)++graph = FalkorDB(host="127.0.0.1", port=6380, password=password).select_graph(+ "autogpt_single_container_smoke"+)+action = sys.argv[1]+if action == "seed":+ graph.query("CREATE (:MemorySmoke {id: 'persistent-memory'})")++result = graph.query(+ "MATCH (n:MemorySmoke {id: 'persistent-memory'}) RETURN count(n)"+)+assert int(result.result_set[0][0]) == 1, result.result_set++from backend.copilot.graphiti.config import is_enabled_for_user++assert asyncio.run(is_enabled_for_user("single-container-smoke")) is True++if action == "cleanup":+ redis.execute_command("GRAPH.DELETE", graph.name)+PY+}++wait_for_falkordb_restart() {+ local previous_pid="$1"+ local deadline=$((SECONDS + TIMEOUT_SECONDS))+ local current_pid+ while ((SECONDS < deadline)); do+ current_pid="$(+ docker exec "${CONTAINER_NAME}" \+ supervisorctl -c /opt/autogpt/single-container/supervisor/supervisord.conf \+ pid falkordb 2>/dev/null || true+ )"+ if [[ "${current_pid}" =~ ^[0-9]+$ ]] &&+ [[ "${current_pid}" != "${previous_pid}" ]] &&+ appliance_is_healthy_and_armed; then+ return 0+ fi+ sleep 5+ done+ echo "FalkorDB did not restart and return the container to healthy" >&2+ return 1+}++assert_redirect() {+ local request_url="$1"+ shift+ local status+ local location+ status="$(+ curl --silent --show-error --max-time 30 \+ --dump-header "${HEADERS_FILE}" --output /dev/null \+ --write-out '%{http_code}' "$@" "${request_url}"+ )"+ location="$(+ tr -d '\r' <"${HEADERS_FILE}" |+ awk 'tolower($1) == "location:" {sub(/^[^:]+:[[:space:]]*/, ""); print; exit}'+ )"+ [[ "${status}" == 307 ]] || {+ echo "protected route returned ${status}, expected 307" >&2+ return 1+ }+ [[ "${location}" == "${PUBLIC_URL}/login?next=%2Fcopilot" ]] || {+ echo "unexpected protected-route Location: ${location}" >&2+ return 1+ }+}++assert_prefixed_backend_redirect() {+ local status+ local location+ status="$(+ curl --silent --show-error --max-time 30 \+ --request POST --dump-header "${HEADERS_FILE}" --output /dev/null \+ --write-out '%{http_code}' "${PUBLIC_URL}/_agpt/api/email"+ )"+ location="$(+ tr -d '\r' <"${HEADERS_FILE}" |+ awk 'tolower($1) == "location:" {sub(/^[^:]+:[[:space:]]*/, ""); print; exit}'+ )"+ [[ "${status}" == 307 ]] || {+ echo "backend slash redirect returned ${status}, expected 307" >&2+ return 1+ }+ [[ "${location}" == "${PUBLIC_URL}/_agpt/api/email/" ]] || {+ echo "backend slash redirect lost its public prefix: ${location}" >&2+ return 1+ }+}++assert_unsupported_email_verification_rejected() {+ local output+ local status+ if output="$(+ timeout --signal=TERM --kill-after=30s 300s docker run --rm \+ --platform "${SMOKE_PLATFORM}" \+ --name "${NEGATIVE_CONTAINER_NAME}" \+ --env AUTH_REQUIRE_EMAIL_VERIFICATION=true \+ "${SMOKE_IMAGE}" 2>&1+ )"; then+ status=0+ else+ status=$?+ fi+ docker rm --force --volumes "${NEGATIVE_CONTAINER_NAME}" >/dev/null 2>&1 || true+ ((status != 0)) || {+ echo "image accepted unsupported email verification" >&2+ return 1+ }+ ((status != 124 && status != 137)) || {+ echo "email-verification rejection probe timed out" >&2+ return 1+ }+ grep -Fq \+ "email verification is not supported by the single-container distribution" \+ <<<"${output}" || {+ echo "unsupported email verification failed without an actionable error" >&2+ return 1+ }+}++# Phase one deliberately supplies no environment, port, volume, entrypoint, or+# command override. This is the CI proof for literal `docker run IMAGE`.+assert_unsupported_email_verification_rejected+docker run --detach \+ --platform "${SMOKE_PLATFORM}" \+ --name "${CONTAINER_NAME}" \+ "${SMOKE_IMAGE}" >/dev/null+discover_data_volume+wait_for_healthy+assert_prisma_cli_is_prebundled+assert_falkordb_binary_contract+assert_memory_contract seed++first_hash="$(runtime_config_hash)"+[[ "${first_hash}" =~ ^[0-9a-f]{64}$ ]] || {+ echo "runtime config checksum is invalid" >&2+ exit 1+}+assert_runtime_config_mode+assert_frontend_database_isolation++docker stop --timeout 360 "${CONTAINER_NAME}" >/dev/null+[[ "$(docker inspect --format '{{.State.ExitCode}}' "${CONTAINER_NAME}")" == 0 ]] || {+ echo "container did not exit cleanly after docker stop" >&2+ exit 1+}+docker rm "${CONTAINER_NAME}" >/dev/null++# A persistent user config must not be able to move internal listeners or bind+# them publicly. Environment-pinned topology has higher Pydantic precedence.+preseed_hostile_backend_config++# Phase two proves explicit public-origin configuration, container replacement,+# and reuse of the exact state volume discovered above.+docker run --detach \+ --platform "${SMOKE_PLATFORM}" \+ --name "${CONTAINER_NAME}" \+ --restart unless-stopped \+ --publish 127.0.0.1:3300:3000 \+ --env "AUTOGPT_PUBLIC_URL=${PUBLIC_URL}" \+ --env AUTH_ALLOW_NEW_ACCOUNTS=true \+ --volume "${DATA_VOLUME}:/data" \+ "${SMOKE_IMAGE}" >/dev/null+wait_for_healthy++[[ "$(runtime_config_hash)" == "${first_hash}" ]] || {+ echo "runtime config changed across container replacement" >&2+ exit 1+}+assert_runtime_config_mode+assert_frontend_database_isolation+assert_pinned_topology_environment+assert_email_auth_flow+assert_falkordb_binary_contract+assert_memory_contract verify+curl --fail --silent --show-error "${PUBLIC_URL}/healthz" >/dev/null+assert_redirect "${PUBLIC_URL}/copilot" --resolve localhost:3300:127.0.0.1+assert_redirect http://127.0.0.1:3300/copilot \+ --header 'Host: attacker.invalid' \+ --header 'X-Forwarded-Proto: https'+assert_prefixed_backend_redirect+assert_internal_tooling_is_private+assert_request_tokens_absent_from_logs++falkordb_pid="$(+ docker exec "${CONTAINER_NAME}" \+ supervisorctl -c /opt/autogpt/single-container/supervisor/supervisord.conf \+ pid falkordb+)"+[[ "${falkordb_pid}" =~ ^[0-9]+$ ]]+falkordb_restart_count="$(+ docker inspect --format '{{.RestartCount}}' "${CONTAINER_NAME}"+)"+docker exec "${CONTAINER_NAME}" kill -TERM "${falkordb_pid}"+wait_for_falkordb_restart "${falkordb_pid}"+[[ "$(docker inspect --format '{{.RestartCount}}' "${CONTAINER_NAME}")" == \+ "${falkordb_restart_count}" ]] || {+ echo "FalkorDB recovery unexpectedly restarted the whole container" >&2+ exit 1+}+assert_memory_contract verify+wait_for_healthy++restart_count="$(docker inspect --format '{{.RestartCount}}' "${CONTAINER_NAME}")"+docker exec "${CONTAINER_NAME}" \+ supervisorctl \+ -c /opt/autogpt/single-container/supervisor/supervisord.conf \+ stop nginx >/dev/null+wait_for_automatic_restart "$((restart_count + 1))"+[[ "$(runtime_config_hash)" == "${first_hash}" ]] || {+ echo "runtime config changed across automatic Docker restart" >&2+ exit 1+}+assert_runtime_config_mode+assert_frontend_database_isolation+assert_redirect "${PUBLIC_URL}/copilot" --resolve localhost:3300:127.0.0.1+assert_falkordb_binary_contract+assert_memory_contract cleanup++docker stop --timeout 360 "${CONTAINER_NAME}" >/dev/null+[[ "$(docker inspect --format '{{.State.ExitCode}}' "${CONTAINER_NAME}")" == 0 ]] || {+ echo "container did not exit cleanly after the restart test" >&2+ exit 1+}+docker rm "${CONTAINER_NAME}" >/dev/null++echo "single-container smoke test passed for ${SMOKE_PLATFORM}"diff --git a/.github/workflows/platform-single-container-docker.yml b/.github/workflows/platform-single-container-docker.ymlnew file mode 100644index 0000000000..5c9e31e022--- /dev/null+++ b/.github/workflows/platform-single-container-docker.yml@@ -0,0 +1,100 @@+name: AutoGPT Platform - Single-container image++on:+ push:+ branches: [dev]+ paths:+ - ".dockerignore"+ - ".github/scripts/platform-single-container-smoke.sh"+ - ".github/workflows/platform-single-container-docker.yml"+ - "autogpt_platform/**"+ pull_request:+ paths:+ - ".dockerignore"+ - ".github/scripts/platform-single-container-smoke.sh"+ - ".github/workflows/platform-single-container-docker.yml"+ - "autogpt_platform/**"+ workflow_dispatch:++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ build-and-scan:+ name: Build, smoke, and scan (${{ matrix.platform }})+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 240+ strategy:+ fail-fast: false+ matrix:+ include:+ - platform: linux/amd64+ runner: ubuntu-24.04+ suffix: amd64+ - platform: linux/arm64+ runner: ubuntu-24.04-arm+ suffix: arm64+ steps:+ - name: Check out repository+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - name: Test appliance runtime helpers+ shell: bash+ run: python3 -m unittest discover -s autogpt_platform/single-container/tests -p 'test_*.py' -v++ - name: Set up Docker Buildx+ uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0+ with:+ version: v0.36.0+ driver-opts: |+ image=docker.io/moby/buildkit:v0.32.0@sha256:1f8167fcb0eca5b7126353d35299386945cbb8949cc516c592a49f80cfce4fa2++ - name: Build image without publishing+ uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7.3.0+ with:+ source: .+ files: autogpt_platform/single-container/docker-bake.hcl+ targets: single-container+ set: |+ *.platform=${{ matrix.platform }}+ backend-server.cache-from=type=gha,scope=platform-single-container-backend-${{ matrix.suffix }}+ backend-server.cache-to=type=gha,scope=platform-single-container-backend-${{ matrix.suffix }},mode=max,ignore-error=true+ single-container.args.IMAGE_VERSION=${{ github.sha }}+ single-container.args.VCS_REF=${{ github.sha }}+ single-container.cache-from=type=gha,scope=platform-single-container-${{ matrix.suffix }}+ single-container.cache-to=type=gha,scope=platform-single-container-${{ matrix.suffix }},mode=max,ignore-error=true+ single-container.output=type=docker+ single-container.tags=autogpt-platform-single-container:ci-${{ matrix.suffix }}++ - name: Smoke-test the complete image+ shell: bash+ env:+ SMOKE_IMAGE: autogpt-platform-single-container:ci-${{ matrix.suffix }}+ SMOKE_PLATFORM: ${{ matrix.platform }}+ run: bash .github/scripts/platform-single-container-smoke.sh++ - name: Scan for fixable critical vulnerabilities+ uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0+ with:+ image-ref: autogpt-platform-single-container:ci-${{ matrix.suffix }}+ format: table+ ignore-unfixed: true+ severity: CRITICAL+ exit-code: "1"+ timeout: 30m++ - name: Scan image filesystem for embedded secrets+ uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0+ with:+ image-ref: autogpt-platform-single-container:ci-${{ matrix.suffix }}+ scanners: secret+ format: table+ severity: HIGH,CRITICAL+ exit-code: "1"+ timeout: 30mdiff --git a/autogpt_platform/single-container/.env.example b/autogpt_platform/single-container/.env.examplenew file mode 100644index 0000000000..0f0056eae0--- /dev/null+++ b/autogpt_platform/single-container/.env.example@@ -0,0 +1,90 @@+# Runtime settings for `docker run --env-file`. The public URL must exactly+# match the browser-visible origin. For example, `-p 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+AUTOGPT_ENABLE_BOT_SERVICES=false+AUTOGPT_ENABLE_LEGACY_AUTH=false++# Account policy. New-account signup is closed by default, including on+# localhost. To bootstrap the first administrator: set this to true,+# recreate the container, create the account, then run+# `docker exec <container> autogpt-admin promote <email>`. Set this back to+# false and recreate the container after all intended accounts exist.+AUTH_ALLOW_NEW_ACCOUNTS=false+AUTH_SIGNUP_ALLOWLIST=+# Email verification is unsupported and must remain false. Setting it to true+# intentionally stops startup instead of silently running an incomplete flow.+AUTH_REQUIRE_EMAIL_VERIFICATION=false++# Per-backend-role Prisma pool controls. DB_CONNECTION_LIMIT accepts 1-5; the+# default of five keeps all bundled roles within PostgreSQL's connection budget.+DB_CONNECTION_LIMIT=5+DB_CONNECT_TIMEOUT=60+DB_POOL_TIMEOUT=300++# RFC 8292 contact used for web-push delivery reports. Replace for remote use.+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.+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.+OPENAI_API_KEY=+ANTHROPIC_API_KEY=+GROQ_API_KEY=++# AutoPilot uses OpenRouter by default. Set false with ANTHROPIC_API_KEY for a+# direct Anthropic profile. Local/custom transport takes priority when enabled.+CHAT_USE_OPENROUTER=true++# OpenAI-compatible local inference, for example Ollama on the Docker host.+# Leave these unset in cloud-provider mode. When local mode is enabled, set the+# base URL, a non-empty API key, and the fast-standard model together.+CHAT_USE_LOCAL=false+CHAT_BASE_URL=+CHAT_API_KEY=+# CHAT_FAST_STANDARD_MODEL=hf.co/unsloth/Qwen3.5-4B-GGUF:Q4_K_M+# CHAT_FAST_ADVANCED_MODEL=qwen3:14b-q4_K_M+# CHAT_THINKING_STANDARD_MODEL=+# CHAT_THINKING_ADVANCED_MODEL=+# CHAT_TITLE_MODEL=+# CHAT_SIMULATION_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.+AUTH_GOOGLE_CLIENT_ID=+AUTH_GOOGLE_CLIENT_SECRET=+AUTH_GITHUB_CLIENT_ID=+AUTH_GITHUB_CLIENT_SECRET=+AUTH_DISCORD_CLIENT_ID=+AUTH_DISCORD_CLIENT_SECRET=++# Agent block OAuth integrations use separate credentials. The prebuilt+# self-hosted frontend does not support configuring Google Picker at runtime.+GOOGLE_CLIENT_ID=+GOOGLE_CLIENT_SECRET=+GITHUB_CLIENT_ID=+GITHUB_CLIENT_SECRET=+DISCORD_CLIENT_ID=+DISCORD_CLIENT_SECRET=++# Transactional email for password-reset and email-change links only. The+# single-container distribution does not send account-verification email.+POSTMARK_SERVER_API_TOKEN=+POSTMARK_SENDER_EMAIL=+POSTMARK_WEBHOOK_TOKEN=++# Legacy Supabase session migration only. Do not set for a fresh install.+# SUPABASE_JWT_SECRET=+# SUPABASE_BRIDGE_MAX_TOKEN_AGE_DAYS=30diff --git a/autogpt_platform/single-container/Dockerfile b/autogpt_platform/single-container/Dockerfilenew file mode 100644index 0000000000..ccd002cfd4--- /dev/null+++ b/autogpt_platform/single-container/Dockerfile@@ -0,0 +1,252 @@+# syntax=docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e++# Build the relocatable frontend on glibc so its standalone native modules can+# be copied into the Debian appliance image. Browser-facing service URLs are+# intentionally same-origin paths; the in-container reverse proxy decides+# where they land at runtime.+FROM node:24.18.0-bookworm-slim@sha256:6f7b03f7c2c8e2e784dcf9295400527b9b1270fd37b7e9a7285cf83b6951452d AS frontend++WORKDIR /app+RUN corepack enable++COPY autogpt_platform/frontend/package.json autogpt_platform/frontend/pnpm-lock.yaml ./+RUN --mount=type=cache,target=/root/.local/share/pnpm \+ pnpm install --frozen-lockfile++COPY autogpt_platform/frontend/ ./++ENV NODE_ENV=production \+ NEXT_TELEMETRY_DISABLED=1 \+ NEXT_PUBLIC_AGPT_SERVER_URL=/_agpt/api \+ NEXT_PUBLIC_AGPT_WS_SERVER_URL=/_agpt/ws \+ NEXT_PUBLIC_FRONTEND_BASE_URL="" \+ NEXT_PUBLIC_APP_ENV=local \+ NEXT_PUBLIC_BEHAVE_AS=LOCAL \+ NEXT_PUBLIC_LAUNCHDARKLY_ENABLED=false \+ NEXT_PUBLIC_SOURCEMAPS=false \+ NEXT_PUBLIC_TURNSTILE=disabled \+ NEXT_PUBLIC_VAPID_PUBLIC_KEY="" \+ BETTER_AUTH_SECRET=build-only-placeholder-not-used-at-runtime \+ DATABASE_URL="postgresql:///postgres?host=%2Frun%2Fpostgresql&user=autogpt_frontend"++RUN pnpm run generate:api \+ && NODE_OPTIONS="--max-old-space-size=8192" pnpm build \+ && rm -f .env .env.local .env.production++FROM node:24.18.0-bookworm-slim@sha256:6f7b03f7c2c8e2e784dcf9295400527b9b1270fd37b7e9a7285cf83b6951452d AS node-runtime++ARG NPM_VERSION=12.0.2+RUN npm install --global "npm@${NPM_VERSION}" \+ && npm cache clean --force++# RabbitMQ's official image ships a self-contained Erlang/OpenSSL runtime.+# Pin the current supported 4.1.x patch by its multi-platform manifest.+FROM rabbitmq:4.1.8@sha256:b921426eabfb39e201c60f0623f6b45a3160cf97b2dc3af2f5340365f65b5be3 AS rabbitmq++# FalkorDB provides the Graphiti memory store. Copy only the server and module;+# its browser UI is not part of the appliance image.+FROM falkordb/falkordb-server:v4.20.1@sha256:8b676c2e72271f5d06541136eb214b0db50180636cc86f7ee38d63287e9b8d13 AS falkordb++# autogpt-backend is supplied by Docker Bake from the existing backend+# Dockerfile's server target. This keeps the backend image contract independent+# from the opt-in single-container distribution.+FROM autogpt-backend AS single-container++ARG IMAGE_VERSION=dev+ARG VCS_REF=unknown++# The normal backend image stores generated Prisma engines under root's cache.+# Appliance services run unprivileged, so relocate those inherited engines to a+# traversable path without changing the backend image used by cloud deployments.+RUN install -d -m 0755 /opt/prisma-python \+ && cp -a /root/.cache/prisma-python/binaries /opt/prisma-python/binaries \+ && set -- /opt/prisma-python/binaries/*/*/node_modules/prisma/build/index.js \+ && test "$#" -eq 1 \+ && prisma_cli="$1" \+ && test -f "${prisma_cli}" \+ && prisma_node_modules="${prisma_cli%/prisma/build/index.js}" \+ && set -- "${prisma_node_modules}"/prisma/query-engine-* \+ && test "$#" -eq 1 \+ && query_engine="$1" \+ && test -f "${query_engine}" \+ && test -x "${query_engine}" \+ && ln -s "${prisma_node_modules}" /opt/prisma-python/binaries/node_modules \+ && ln -s "${query_engine}" /opt/prisma-python/query-engine++LABEL org.opencontainers.image.title="AutoGPT Platform single-container" \+ org.opencontainers.image.description="Experimental single-node AutoGPT Platform distribution" \+ org.opencontainers.image.source="https://github.com/Significant-Gravitas/AutoGPT" \+ org.opencontainers.image.licenses="LicenseRef-PolyForm-Shield-1.0.0 AND SSPL-1.0" \+ org.opencontainers.image.version="${IMAGE_VERSION}" \+ org.opencontainers.image.revision="${VCS_REF}"++ENV DEBIAN_FRONTEND=noninteractive++# Block service auto-start during package installation; Supervisor owns every+# daemon at runtime. PostgreSQL comes from PGDG to retain PG15 parity on Debian+# 13, while Valkey comes from Debian's security-maintained BSD build.+# Persistent volume ownership must remain stable across package upgrades.+# Pre-create the accounts with the IDs used by the first image release; fail+# the build rather than silently shifting them if the base ever claims an ID.+RUN printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d \+ && chmod 0755 /usr/sbin/policy-rc.d \+ && groupadd --system --gid 102 postgres \+ && useradd --system --uid 100 --gid postgres --home-dir /var/lib/postgresql --shell /bin/bash postgres \+ && apt-get update \+ && apt-get install -y --no-install-recommends \+ ca-certificates \+ curl \+ gnupg \+ postgresql-common \+ && install -d -m 0755 /etc/apt/keyrings \+ && curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \+ | gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg \+ && printf 'deb [signed-by=/etc/apt/keyrings/postgresql.gpg] https://apt.postgresql.org/pub/repos/apt trixie-pgdg main\n' \+ > /etc/apt/sources.list.d/pgdg.list \+ && printf 'create_main_cluster = false\n' > /etc/postgresql-common/createcluster.conf \+ && apt-get update \+ && apt-get install -y --no-install-recommends \+ bash \+ libgomp1 \+ netcat-openbsd \+ nginx \+ openssl \+ postgresql-15 \+ postgresql-client-15 \+ postgresql-15-pgvector \+ procps \+ supervisor \+ tini \+ util-linux \+ valkey-server \+ valkey-tools \+ && rm -f /usr/sbin/policy-rc.d \+ /etc/ssl/private/ssl-cert-snakeoil.key \+ /etc/ssl/certs/ssl-cert-snakeoil.pem \+ && find /etc/ssl/certs -maxdepth 1 -type l \+ -lname '*ssl-cert-snakeoil.pem' -delete \+ && test ! -e /etc/ssl/private/ssl-cert-snakeoil.key \+ && test ! -e /etc/ssl/certs/ssl-cert-snakeoil.pem \+ && test -x /usr/bin/setpriv \+ && test -z "$(find /etc/ssl/certs -maxdepth 1 -type l \+ -lname '*ssl-cert-snakeoil.pem' -print -quit)" \+ && rm -rf /var/lib/apt/lists/* /var/lib/postgresql/15/main++# Node 24 is required by the frontend. Backend Prisma and agent-browser also+# use this binary through PATH; their npm packages remain from the server stage.+COPY --from=frontend /usr/local/bin/node /usr/local/bin/node+COPY --from=frontend /usr/local/LICENSE /usr/share/licenses/nodejs/LICENSE+RUN rm -rf /usr/lib/node_modules/npm+COPY --from=node-runtime /usr/local/lib/node_modules/npm /usr/lib/node_modules/npm++# RabbitMQ + Erlang runtime and their bundled third-party license files.+COPY --from=rabbitmq /opt/erlang /opt/erlang+COPY --from=rabbitmq /opt/openssl /opt/openssl+COPY --from=rabbitmq /opt/rabbitmq /opt/rabbitmq++# FalkorDB server only (no bundled Browser UI).+COPY --from=falkordb /usr/local/bin/redis-server /opt/falkordb/redis-server+COPY --from=falkordb /var/lib/falkordb/bin/falkordb.so /opt/falkordb/falkordb.so++# Next standalone server and immutable assets.+COPY --from=frontend /app/.next/standalone /app/frontend+COPY --from=frontend /app/.next/static /app/frontend/.next/static+COPY --from=frontend /app/public /app/frontend/public++# Next's standalone trace over-includes Orval's build-only esbuild dependency.+# It is never used by the production server and must not ship as runtime code.+RUN rm -rf \+ /app/frontend/node_modules/.pnpm/esbuild@* \+ /app/frontend/node_modules/.pnpm/@esbuild+linux-*@* \+ && find /app/frontend/node_modules -type l \+ \( -name esbuild -o -path '*/node_modules/@esbuild/linux-*' \) -delete++# Runtime orchestration, proxy, health tooling, and database compatibility shim.+COPY autogpt_platform/single-container/bootstrap.sh \+ autogpt_platform/single-container/common.sh \+ autogpt_platform/single-container/disabled-service.sh \+ autogpt_platform/single-container/entrypoint.sh \+ autogpt_platform/single-container/fatal_listener.py \+ autogpt_platform/single-container/healthcheck.sh \+ autogpt_platform/single-container/probe.py \+ autogpt_platform/single-container/promote-admin.sh \+ autogpt_platform/single-container/run-app.sh \+ autogpt_platform/single-container/run-frontend.sh \+ autogpt_platform/single-container/run-optional-app.sh \+ autogpt_platform/single-container/run-service.sh \+ autogpt_platform/single-container/runtime_config.py \+ autogpt_platform/single-container/watchdog.sh \+ /opt/autogpt/single-container/+COPY autogpt_platform/single-container/nginx /opt/autogpt/single-container/nginx+COPY autogpt_platform/single-container/python /opt/autogpt/single-container/python+COPY autogpt_platform/single-container/rabbitmq /opt/autogpt/single-container/rabbitmq+COPY autogpt_platform/single-container/supervisor /opt/autogpt/single-container/supervisor+COPY autogpt_platform/db/init/00-init.sql /opt/autogpt/single-container/00-init.sql+COPY autogpt_platform/LICENSE.md /usr/share/licenses/autogpt-platform/LICENSE.md+COPY autogpt_platform/single-container/licenses/FalkorDB-SSPL-1.0.txt /usr/share/licenses/falkordb/SSPL-1.0.txt+COPY autogpt_platform/single-container/licenses/FalkorDB-SOURCE.txt /usr/share/licenses/falkordb/SOURCE.txt+COPY autogpt_platform/single-container/licenses/Redis-LICENSE.txt /usr/share/licenses/redis/LICENSE.txt+COPY autogpt_platform/single-container/licenses/Redis-REDISCONTRIBUTIONS.txt /usr/share/licenses/redis/REDISCONTRIBUTIONS.txt+COPY autogpt_platform/single-container/licenses/Redis-SOURCE.txt /usr/share/licenses/redis/SOURCE.txt+COPY autogpt_platform/single-container/licenses/redis/deps /usr/share/licenses/redis/deps+COPY autogpt_platform/single-container/licenses/redis/src /usr/share/licenses/redis/src++RUN groupadd --system --gid 10001 autogpt \+ && useradd --system --uid 10001 --gid autogpt --home-dir /data/home --shell /usr/sbin/nologin autogpt \+ && groupadd --system --gid 10002 rabbitmq \+ && useradd --system --uid 10002 --gid rabbitmq --home-dir /data/rabbitmq --shell /usr/sbin/nologin rabbitmq \+ && groupadd --system --gid 10003 autogpt-valkey \+ && useradd --system --uid 10003 --gid autogpt-valkey --home-dir /data/valkey --shell /usr/sbin/nologin autogpt-valkey \+ && groupadd --system --gid 10004 autogpt-falkor \+ && useradd --system --uid 10004 --gid autogpt-falkor --home-dir /data/falkordb --shell /usr/sbin/nologin autogpt-falkor \+ && groupadd --system --gid 10005 autogpt_frontend \+ && useradd --system --uid 10005 --gid autogpt_frontend --home-dir /data/frontend-home --shell /usr/sbin/nologin autogpt_frontend \+ && groupadd --system --gid 10006 autogpt_proxy \+ && useradd --system --uid 10006 --gid autogpt_proxy --home-dir /run/autogpt/nginx/home --shell /usr/sbin/nologin autogpt_proxy \+ && chmod -R a+rX /opt/autogpt/single-container /usr/share/licenses/autogpt-platform /usr/share/licenses/falkordb /usr/share/licenses/redis \+ && find /opt/autogpt/single-container -type f \( -name '*.sh' -o -name 'entrypoint' -o -name 'autogpt-*' \) -exec chmod 0755 {} + \+ && ln -sf /opt/autogpt/single-container/healthcheck.sh /usr/local/bin/autogpt-healthcheck \+ && ln -sf /opt/autogpt/single-container/promote-admin.sh /usr/local/bin/autogpt-admin \+ && rm -f /app/autogpt_platform/backend/config.json \+ && ln -s /data/config/backend.json /app/autogpt_platform/backend/config.json \+ && rm -rf /app/frontend/.next/cache \+ && ln -s /data/cache/next /app/frontend/.next/cache \+ && site_packages="$(/app/autogpt_platform/backend/.venv/bin/python -c \+ 'import sysconfig; print(sysconfig.get_paths()["purelib"])')" \+ && rm -f \+ "${site_packages}/ldclient/testing/selfsigned.key" \+ "${site_packages}/ldclient/testing/selfsigned.pem" \+ && test ! -e "${site_packages}/ldclient/testing/selfsigned.key" \+ && test ! -e "${site_packages}/ldclient/testing/selfsigned.pem"++ENV PATH="/opt/rabbitmq/sbin:/opt/erlang/bin:/opt/openssl/bin:/usr/lib/postgresql/15/bin:/app/autogpt_platform/backend/.venv/bin:${PATH}" \+ ERLANG_INSTALL_PATH_PREFIX=/opt/erlang \+ OPENSSL_INSTALL_PATH_PREFIX=/opt/openssl \+ RABBITMQ_HOME=/opt/rabbitmq \+ RABBITMQ_DATA_DIR=/data/rabbitmq \+ RUNNING_UNDER_SYSTEMD=true \+ PGDATA=/data/postgres \+ PORT=3001 \+ HOSTNAME=127.0.0.1 \+ LANG=C.UTF-8 \+ LANGUAGE=C.UTF-8 \+ LC_ALL=C.UTF-8 \+ NODE_ENV=production \+ NEXT_TELEMETRY_DISABLED=1 \+ PRISMA_BINARY_CACHE_DIR=/opt/prisma-python/binaries \+ PRISMA_QUERY_ENGINE_BINARY=/opt/prisma-python/query-engine \+ PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ FORCE_FLAG_GRAPHITI_MEMORY=true \+ AUTOGPT_PUBLIC_URL=http://localhost:3000++WORKDIR /app/autogpt_platform/backend++VOLUME ["/data"]+EXPOSE 3000++HEALTHCHECK --interval=30s --timeout=45s --start-period=5m --retries=10 \+ CMD ["/usr/local/bin/autogpt-healthcheck"]++ENTRYPOINT ["/usr/bin/tini", "--", "/opt/autogpt/single-container/entrypoint.sh"]+CMD ["/usr/bin/supervisord", "-n", "-c", "/opt/autogpt/single-container/supervisor/supervisord.conf"]diff --git a/autogpt_platform/single-container/Dockerfile.dockerignore b/autogpt_platform/single-container/Dockerfile.dockerignorenew file mode 100644index 0000000000..44afdbde58--- /dev/null+++ b/autogpt_platform/single-container/Dockerfile.dockerignore@@ -0,0 +1,37 @@+# This image combines frontend and appliance files. The backend target has its+# own Bake context. No env file belongs in this context or exported cache.+*++!autogpt_platform/frontend/+!autogpt_platform/single-container/+!autogpt_platform/db/init/00-init.sql+!autogpt_platform/LICENSE.md++**/.*++**/__pycache__/+**/*.pyc+**/*.pyo+**/.venv/+**/.ruff_cache/+**/.pytest_cache/+**/.coverage+**/htmlcov/++**/node_modules/+**/.next/+**/coverage/+**/storybook-static/+**/playwright-report/+**/test-results/+**/next-env.d.ts+**/tsconfig.tsbuildinfo+**/src/app/api/__generated__/++**/dist/+**/build/+!autogpt_platform/frontend/src/**/build/+**/target/++**/*.log+**/*.tmpdiff --git a/autogpt_platform/single-container/bootstrap.sh b/autogpt_platform/single-container/bootstrap.shnew file mode 100755index 0000000000..ac343d05a4--- /dev/null+++ b/autogpt_platform/single-container/bootstrap.sh@@ -0,0 +1,224 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++readonly PROBE=("${AUTOGPT_BACKEND_DIR}/.venv/bin/python" "${AUTOGPT_ASSET_DIR}/probe.py")+readonly POSTGRES_BINDIR="${POSTGRES_BINDIR:-/usr/lib/postgresql/15/bin}"+readonly INIT_SQL="${AUTOGPT_DB_INIT_SQL:-${AUTOGPT_ASSET_DIR}/00-init.sql}"++main() {+ load_runtime_config+ rm -f "${AUTOGPT_READY_FILE}"+ wait_for_infrastructure+ ensure_valkey_cluster+ verify_rabbitmq_user+ migrate_database+ configure_frontend_database_role+ publish_readiness+ log "bootstrap complete"+}++wait_for_infrastructure() {+ wait_until "PostgreSQL" 180 \+ "${POSTGRES_BINDIR}/pg_isready" -q -h 127.0.0.1 -p 5432 -U postgres+ wait_until "Valkey node 17000" 120 "${PROBE[@]}" redis --port 17000 \+ --password-env REDIS_PASSWORD+ wait_until "Valkey node 17001" 120 "${PROBE[@]}" redis --port 17001 \+ --password-env REDIS_PASSWORD+ wait_until "Valkey node 17002" 120 "${PROBE[@]}" redis --port 17002 \+ --password-env REDIS_PASSWORD+ wait_until "RabbitMQ" 240 run_rabbitmq_cli /opt/rabbitmq/sbin/rabbitmq-diagnostics -q check_running+ wait_until "FalkorDB" 120 "${PROBE[@]}" redis --port 6380 \+ --password-env GRAPHITI_FALKORDB_PASSWORD+}++wait_until() {+ local description="$1"+ local timeout="$2"+ shift 2+ local elapsed=0+ until "$@" >/dev/null 2>&1; do+ ((elapsed < timeout)) || fatal "${description} was not ready within ${timeout}s"+ sleep 1+ ((elapsed += 1))+ done+ log "${description} is ready"+}++ensure_valkey_cluster() {+ if "${PROBE[@]}" redis --port 17000 --cluster \+ --password-env REDIS_PASSWORD >/dev/null 2>&1; then+ log "Valkey cluster is already healthy"+ return 0+ fi++ local known_nodes+ local fresh_cluster=true+ local port+ for port in 17000 17001 17002; do+ known_nodes="$(+ REDISCLI_AUTH="${REDIS_PASSWORD}" \+ valkey-cli -h 127.0.0.1 -p "${port}" cluster info 2>/dev/null |+ awk -F: '$1 == "cluster_known_nodes" {gsub("\r", "", $2); print $2}'+ )"+ [[ "${known_nodes}" == "1" ]] || fresh_cluster=false+ done++ if [[ "${fresh_cluster}" == true ]]; then+ log "forming three-node Valkey cluster"+ REDISCLI_AUTH="${REDIS_PASSWORD}" valkey-cli --cluster create \+ 127.0.0.1:17000 127.0.0.1:17001 127.0.0.1:17002 \+ --cluster-replicas 0 --cluster-yes >/dev/null+ wait_until "Valkey cluster" 60 "${PROBE[@]}" redis --port 17000 --cluster \+ --password-env REDIS_PASSWORD+ return 0+ fi++ # Existing nodes normally need only gossip time after all three processes+ # restart. Never destructively recreate a partially known cluster.+ local elapsed=0+ while ((elapsed < 90)); do+ if "${PROBE[@]}" redis --port 17000 --cluster \+ --password-env REDIS_PASSWORD >/dev/null 2>&1; then+ log "Valkey cluster recovered"+ return 0+ fi+ sleep 1+ ((elapsed += 1))+ done+ fatal "Valkey cluster did not recover; refusing to erase persistent state"+}++verify_rabbitmq_user() {+ local users+ users="$(run_rabbitmq_cli /opt/rabbitmq/sbin/rabbitmqctl -q list_users)"+ awk '{print $1}' <<<"${users}" | grep -Fqx "${RABBITMQ_DEFAULT_USER}" || \+ fatal "RabbitMQ did not initialize the application user"+ if awk '{print $1}' <<<"${users}" | grep -Fqx guest; then+ fatal "RabbitMQ initialized the built-in guest user unexpectedly"+ fi+ log "RabbitMQ application user is present"+}++migrate_database() {+ [[ -f "${INIT_SQL}" ]] || fatal "database initialization SQL is missing: ${INIT_SQL}"+ log "ensuring platform database schemas exist"+ PGPASSWORD="${POSTGRES_PASSWORD}" \+ "${POSTGRES_BINDIR}/psql" \+ --host=127.0.0.1 \+ --port=5432 \+ --username=postgres \+ --dbname=postgres \+ --set=ON_ERROR_STOP=1 \+ --file="${INIT_SQL}" >/dev/null++ log "applying Prisma migrations"+ (+ cd "${AUTOGPT_BACKEND_DIR}"+ prisma migrate deploy+ )+}++configure_frontend_database_role() {+ log "configuring least-privilege frontend database role"+ PGPASSWORD="${POSTGRES_PASSWORD}" \+ "${POSTGRES_BINDIR}/psql" \+ --host=127.0.0.1 \+ --port=5432 \+ --username=postgres \+ --dbname=postgres \+ --set=ON_ERROR_STOP=1 \+ --quiet <<'SQL'+BEGIN;++DO $role$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = 'autogpt_frontend'+ ) THEN+ CREATE ROLE autogpt_frontend LOGIN;+ END IF;+END+$role$;++ALTER ROLE autogpt_frontend+ LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS+ CONNECTION LIMIT 10 PASSWORD NULL;+ALTER ROLE autogpt_frontend RESET ALL;+ALTER ROLE autogpt_frontend IN DATABASE postgres RESET ALL;++REVOKE ALL PRIVILEGES ON DATABASE postgres FROM autogpt_frontend;+REVOKE TEMPORARY ON DATABASE postgres FROM PUBLIC;+GRANT CONNECT ON DATABASE postgres TO autogpt_frontend;++REVOKE ALL PRIVILEGES ON SCHEMA platform FROM PUBLIC, autogpt_frontend;+GRANT USAGE ON SCHEMA platform TO autogpt_frontend;++REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA platform+ FROM PUBLIC, autogpt_frontend;+ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA platform+ REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;++REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA platform+ FROM PUBLIC, autogpt_frontend;+REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA platform+ FROM PUBLIC, autogpt_frontend;++GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE+ platform."UserAuthIdentity",+ platform."UserAuthSession",+ platform."UserAuthAccount",+ platform."UserAuthVerification",+ platform."UserAuthJwks"+TO autogpt_frontend;++GRANT SELECT (id, email), UPDATE (email, "updatedAt")+ ON TABLE platform."User"+ TO autogpt_frontend;++DO $membership$+DECLARE+ frontend_role_oid oid;+BEGIN+ SELECT oid INTO STRICT frontend_role_oid+ FROM pg_catalog.pg_roles+ WHERE rolname = 'autogpt_frontend';++ IF EXISTS (+ SELECT 1+ FROM pg_catalog.pg_auth_members membership+ WHERE membership.member = frontend_role_oid+ ) THEN+ RAISE EXCEPTION 'autogpt_frontend must not belong to another database role';+ END IF;++ IF EXISTS (+ SELECT 1 FROM pg_catalog.pg_database WHERE datdba = frontend_role_oid+ UNION ALL+ SELECT 1 FROM pg_catalog.pg_namespace WHERE nspowner = frontend_role_oid+ UNION ALL+ SELECT 1 FROM pg_catalog.pg_class WHERE relowner = frontend_role_oid+ UNION ALL+ SELECT 1 FROM pg_catalog.pg_proc WHERE proowner = frontend_role_oid+ ) THEN+ RAISE EXCEPTION 'autogpt_frontend must not own database objects';+ END IF;+END+$membership$;++COMMIT;+SQL+}++publish_readiness() {+ local temporary+ temporary="$(mktemp "${AUTOGPT_RUNTIME_DIR}/ready.XXXXXX")"+ printf 'ready\n' >"${temporary}"+ chmod 0644 "${temporary}"+ mv -f "${temporary}" "${AUTOGPT_READY_FILE}"+}++main "$@"diff --git a/autogpt_platform/single-container/common.sh b/autogpt_platform/single-container/common.shnew file mode 100755index 0000000000..052ebd1625--- /dev/null+++ b/autogpt_platform/single-container/common.sh@@ -0,0 +1,107 @@+#!/usr/bin/env bash++set -Eeuo pipefail++readonly AUTOGPT_RUNTIME_DIR="${AUTOGPT_RUNTIME_DIR:-/run/autogpt}"+readonly AUTOGPT_READY_FILE="${AUTOGPT_READY_FILE:-${AUTOGPT_RUNTIME_DIR}/ready}"+readonly AUTOGPT_RUNTIME_ENV="${AUTOGPT_RUNTIME_ENV:-/data/config/runtime.env}"+readonly AUTOGPT_ASSET_DIR="${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}"+readonly AUTOGPT_BACKEND_DIR="${AUTOGPT_BACKEND_DIR:-/app/autogpt_platform/backend}"+readonly AUTOGPT_FRONTEND_DIR="${AUTOGPT_FRONTEND_DIR:-/app/frontend}"+readonly AUTOGPT_INTERNAL_HEALTH_PATH=/health_check+readonly AUTOGPT_WEBSOCKET_PORT=8001+readonly AUTOGPT_EXECUTION_MANAGER_PORT=8002+readonly AUTOGPT_EXECUTION_SCHEDULER_PORT=8003+readonly AUTOGPT_DATABASE_API_PORT=8005+readonly AUTOGPT_AGENT_API_PORT=8006+readonly AUTOGPT_NOTIFICATION_SERVICE_PORT=8007+readonly AUTOGPT_COPILOT_EXECUTOR_PORT=8008+readonly AUTOGPT_PLATFORM_LINKING_SERVICE_PORT=8009+readonly AUTOGPT_COPILOT_CHAT_BRIDGE_PORT=8010+readonly AUTOGPT_BATCH_EXECUTOR_PORT=8011++log() {+ printf '%s [single-container] %s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "$*"+}++fatal() {+ log "ERROR: $*" >&2+ exit 1+}++require_command() {+ command -v "$1" >/dev/null 2>&1 || fatal "required command is missing: $1"+}++validate_legacy_auth() {+ case "${AUTOGPT_ENABLE_LEGACY_AUTH:-false}" in+ true)+ if [[ -n "${JWT_VERIFY_KEY:-}" && -n "${SUPABASE_JWT_SECRET:-}" && \+ "${JWT_VERIFY_KEY}" != "${SUPABASE_JWT_SECRET}" ]]; then+ fatal "JWT_VERIFY_KEY and SUPABASE_JWT_SECRET must match during legacy auth migration"+ fi+ local legacy_secret="${JWT_VERIFY_KEY:-${SUPABASE_JWT_SECRET:-}}"+ ((${#legacy_secret} >= 32)) || \+ fatal "legacy auth requires a shared secret of at least 32 characters"+ JWT_VERIFY_KEY="${legacy_secret}"+ SUPABASE_JWT_SECRET="${legacy_secret}"+ export JWT_VERIFY_KEY SUPABASE_JWT_SECRET+ log "legacy symmetric JWT verification is explicitly enabled"+ ;;+ false | "")+ if [[ -n "${JWT_VERIFY_KEY:-}" || -n "${SUPABASE_JWT_SECRET:-}" ]]; then+ fatal "legacy JWT secrets were supplied; remove them or explicitly set AUTOGPT_ENABLE_LEGACY_AUTH=true"+ fi+ JWT_VERIFY_KEY=''+ SUPABASE_JWT_SECRET=''+ export JWT_VERIFY_KEY SUPABASE_JWT_SECRET+ ;;+ *)+ fatal "AUTOGPT_ENABLE_LEGACY_AUTH must be true or false"+ ;;+ esac+}++load_runtime_config() {+ [[ -f "${AUTOGPT_RUNTIME_ENV}" ]] || fatal "missing runtime config: ${AUTOGPT_RUNTIME_ENV}"+ while IFS= read -r line || [[ -n "${line}" ]]; do+ [[ -z "${line}" || "${line}" == \#* ]] && continue+ local name="${line%%=*}"+ local value="${line#*=}"+ [[ "${name}" != "${line}" ]] || fatal "malformed runtime config entry"+ case "${name}" in+ AUTOGPT_RUNTIME_CONFIG_VERSION | POSTGRES_PASSWORD | RABBITMQ_DEFAULT_USER | RABBITMQ_DEFAULT_PASS | REDIS_PASSWORD | BETTER_AUTH_SECRET | ENCRYPTION_KEY | UNSUBSCRIBE_SECRET_KEY | GRAPHITI_FALKORDB_PASSWORD | VAPID_PRIVATE_KEY | VAPID_PUBLIC_KEY)+ export "${name}=${value}"+ ;;+ *)+ fatal "unknown key in runtime config: ${name}"+ ;;+ esac+ done <"${AUTOGPT_RUNTIME_ENV}"+}++wait_for_ready_file() {+ local timeout="${AUTOGPT_STARTUP_TIMEOUT:-600}"+ local elapsed=0+ while [[ ! -f "${AUTOGPT_READY_FILE}" ]]; do+ ((elapsed < timeout)) || fatal "startup did not complete within ${timeout}s"+ sleep 1+ ((elapsed += 1))+ done+}++run_as() {+ local user="$1"+ shift+ runuser --user "${user}" -- "$@"+}++run_rabbitmq_cli() {+ run_as rabbitmq /usr/bin/env -i \+ PATH=/opt/rabbitmq/sbin:/opt/erlang/bin:/opt/openssl/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \+ HOME=/data/rabbitmq \+ LANG=C.UTF-8 \+ RABBITMQ_NODENAME=rabbit@localhost \+ ERL_EPMD_ADDRESS=127.0.0.1 \+ "$@"+}diff --git a/autogpt_platform/single-container/disabled-service.sh b/autogpt_platform/single-container/disabled-service.shnew file mode 100755index 0000000000..4c8461e2d3--- /dev/null+++ b/autogpt_platform/single-container/disabled-service.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++log "${1:-optional service} is disabled by configuration"+exec sleep infinitydiff --git a/autogpt_platform/single-container/docker-bake.hcl b/autogpt_platform/single-container/docker-bake.hclnew file mode 100644index 0000000000..f7b731fca8--- /dev/null+++ b/autogpt_platform/single-container/docker-bake.hcl@@ -0,0 +1,19 @@+group "default" {+ targets = ["single-container"]+}++target "backend-server" {+ context = "."+ dockerfile = "autogpt_platform/backend/Dockerfile"+ target = "server"+}++target "single-container" {+ context = "."+ dockerfile = "autogpt_platform/single-container/Dockerfile"+ target = "single-container"+ contexts = {+ autogpt-backend = "target:backend-server"+ }+ tags = ["autogpt-platform:single-container-dev"]+}diff --git a/autogpt_platform/single-container/entrypoint.sh b/autogpt_platform/single-container/entrypoint.shnew file mode 100755index 0000000000..dc2ba4b556--- /dev/null+++ b/autogpt_platform/single-container/entrypoint.sh@@ -0,0 +1,326 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++readonly AUTOGPT_PYTHON="${AUTOGPT_PYTHON:-${AUTOGPT_BACKEND_DIR}/.venv/bin/python}"+readonly POSTGRES_BINDIR="${POSTGRES_BINDIR:-/usr/lib/postgresql/15/bin}"++main() {+ [[ "$(id -u)" -eq 0 ]] || fatal "entrypoint must start as root so services can drop privileges"+ [[ -x "${AUTOGPT_PYTHON}" ]] || fatal "backend Python is missing: ${AUTOGPT_PYTHON}"++ prepare_directories+ initialize_backend_config+ "${AUTOGPT_PYTHON}" "${AUTOGPT_ASSET_DIR}/runtime_config.py" ensure \+ --path "${AUTOGPT_RUNTIME_ENV}"+ chown root:root "${AUTOGPT_RUNTIME_ENV}"+ chmod 0600 "${AUTOGPT_RUNTIME_ENV}"+ load_runtime_config+ configure_environment+ write_valkey_configs+ initialize_postgres+ write_rabbitmq_config+ write_falkordb_config+ rm -f "${AUTOGPT_READY_FILE}"++ if (($# == 0)); then+ set -- supervisord -c "${AUTOGPT_ASSET_DIR}/supervisor/supervisord.conf"+ fi+ log "starting process supervisor"+ exec "$@"+}++prepare_directories() {+ local managed_path+ for managed_path in \+ /data/config /data/postgres /data/rabbitmq /data/valkey \+ /data/valkey/17000 /data/valkey/17001 /data/valkey/17002 /data/falkordb \+ /data/workspaces /data/home /data/frontend-home \+ /data/cache /data/cache/backend /data/cache/next; do+ [[ ! -L "${managed_path}" ]] || fatal "refusing symlink at managed data path: ${managed_path}"+ done+ install -d -m 0710 -o root -g autogpt /data/config+ install -d -m 0700 -o postgres -g postgres /data/postgres+ install -d -m 0750 -o rabbitmq -g rabbitmq /data/rabbitmq+ install -d -m 0750 -o autogpt-valkey -g autogpt-valkey /data/valkey+ install -d -m 0750 -o autogpt-valkey -g autogpt-valkey /data/valkey/17000+ install -d -m 0750 -o autogpt-valkey -g autogpt-valkey /data/valkey/17001+ install -d -m 0750 -o autogpt-valkey -g autogpt-valkey /data/valkey/17002+ install -d -m 0750 -o autogpt-falkor -g autogpt-falkor /data/falkordb+ install -d -m 0750 -o autogpt -g autogpt /data/workspaces+ install -d -m 0750 -o autogpt -g autogpt /data/home+ install -d -m 0700 -o autogpt_frontend -g autogpt_frontend /data/frontend-home+ install -d -m 0711 -o root -g root /data/cache+ install -d -m 0750 -o autogpt -g autogpt /data/cache/backend+ install -d -m 0700 -o autogpt_frontend -g autogpt_frontend /data/cache/next+ install -d -m 0755 -o postgres -g postgres /run/postgresql+ # Service-specific runtime directories and files carry the restrictive+ # permissions. Keep only execute permission on their common parent so the+ # unprivileged PostgreSQL, RabbitMQ, FalkorDB, and app users can traverse to+ # their own assets without being able to list or modify sibling state.+ install -d -m 0711 -o root -g root "${AUTOGPT_RUNTIME_DIR}"+ install -d -m 0700 -o rabbitmq -g rabbitmq "${AUTOGPT_RUNTIME_DIR}/rabbitmq"+ install -d -m 0711 -o root -g root "${AUTOGPT_RUNTIME_DIR}/valkey"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx/home"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx/cache"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx/client"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx/proxy"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx/fastcgi"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx/uwsgi"+ install -d -m 0700 -o autogpt_proxy -g autogpt_proxy "${AUTOGPT_RUNTIME_DIR}/nginx/scgi"+}++initialize_backend_config() {+ local path=/data/config/backend.json+ [[ ! -L "${path}" ]] || fatal "refusing symlink at backend config path"+ if [[ ! -e "${path}" ]]; then+ printf '{}\n' >"${path}"+ fi+ [[ -f "${path}" ]] || fatal "backend config must be a regular file"+ chown autogpt:autogpt "${path}"+ chmod 0600 "${path}"+ "${AUTOGPT_PYTHON}" -m json.tool "${path}" >/dev/null || \+ fatal "backend config is not valid JSON"+}++configure_environment() {+ validate_legacy_auth+ normalize_toggle AUTOGPT_ENABLE_BOT_SERVICES false+ if [[ "${AUTH_REQUIRE_EMAIL_VERIFICATION:-false}" != false ]]; then+ fatal "email verification is not supported by the single-container distribution"+ fi+ normalize_integer DB_CONNECTION_LIMIT 5 1 5+ normalize_integer DB_CONNECT_TIMEOUT 60 1 600+ normalize_integer DB_POOL_TIMEOUT 300 1 3600++ AUTOGPT_PUBLIC_URL="$(+ "${AUTOGPT_PYTHON}" "${AUTOGPT_ASSET_DIR}/runtime_config.py" \+ validate-public-url "${AUTOGPT_PUBLIC_URL:-http://localhost:3000}"+ )"+ export AUTOGPT_PUBLIC_URL+ log "public URL: ${AUTOGPT_PUBLIC_URL}"+ configure_account_registration+ write_nginx_public_url_config++ export PGDATA=/data/postgres+ export POSTGRES_USER=postgres POSTGRES_DB=postgres+ export DB_HOST=127.0.0.1 DB_PORT=5432 DB_USER=postgres DB_NAME=postgres+ export DB_PASS="${POSTGRES_PASSWORD}" DB_SCHEMA=platform+ export DATABASE_URL="postgresql://postgres:${POSTGRES_PASSWORD}@127.0.0.1:5432/postgres?schema=platform&connection_limit=${DB_CONNECTION_LIMIT}&connect_timeout=${DB_CONNECT_TIMEOUT}&pool_timeout=${DB_POOL_TIMEOUT}"+ # DIRECT_URL is also consumed by APScheduler's SQLAlchemy/psycopg2 job+ # store. Keep Prisma-only pool parameters on DATABASE_URL so that the+ # standard PostgreSQL driver never receives unsupported DSN options.+ export DIRECT_URL="postgresql://postgres:${POSTGRES_PASSWORD}@127.0.0.1:5432/postgres?schema=platform&connect_timeout=${DB_CONNECT_TIMEOUT}"+ export PRISMA_SCHEMA="${AUTOGPT_BACKEND_DIR}/schema.prisma" AUTH_DB_SCHEMA=platform++ export REDIS_HOST=127.0.0.1 REDIS_PORT=17000 REDIS_PASSWORD+ export REDIS_CLUSTER_HOST=127.0.0.1 REDIS_CLUSTER_PORT=17000+ export REDIS_USE_ANNOUNCED_ADDRESS=false+ export RABBITMQ_HOST=127.0.0.1 RABBITMQ_PORT=5672+ export RABBITMQ_CLUSTER_HOST=127.0.0.1 RABBITMQ_CLUSTER_PORT=5672+ export RABBITMQ_VHOST=/+ export RABBITMQ_MNESIA_BASE=/data/rabbitmq/mnesia+ export RABBITMQ_NODENAME=rabbit@localhost+ export RABBITMQ_CONFIG_FILE="${AUTOGPT_RUNTIME_DIR}/rabbitmq/rabbitmq"+ export GRAPHITI_FALKORDB_HOST=127.0.0.1 GRAPHITI_FALKORDB_PORT=6380+ # The appliance bundles no antivirus daemon. Force the scanner off so uploads+ # short-circuit as clean instead of failing on an unreachable ClamAV service.+ export CLAMAV_SERVICE_ENABLED=false++ export PYRO_HOST=127.0.0.1+ export AGENTSERVER_HOST=127.0.0.1 SCHEDULER_HOST=127.0.0.1+ export DATABASEMANAGER_HOST=127.0.0.1 EXECUTIONMANAGER_HOST=127.0.0.1+ export NOTIFICATIONMANAGER_HOST=127.0.0.1 PLATFORMLINKINGMANAGER_HOST=127.0.0.1+ export COPILOTEXECUTOR_HOST=127.0.0.1 COPILOTCHATBRIDGE_HOST=127.0.0.1+ export AGENT_API_HOST=127.0.0.1 WEBSOCKET_SERVER_HOST=127.0.0.1+ # The persistent backend JSON contains user-tunable product settings, but it+ # must not be able to move or expose appliance services. Environment values+ # have higher Pydantic priority, so pin the fixed internal topology here.+ export WEBSOCKET_SERVER_PORT="${AUTOGPT_WEBSOCKET_PORT}"+ export EXECUTION_MANAGER_PORT="${AUTOGPT_EXECUTION_MANAGER_PORT}"+ export EXECUTION_SCHEDULER_PORT="${AUTOGPT_EXECUTION_SCHEDULER_PORT}"+ export DATABASE_API_PORT="${AUTOGPT_DATABASE_API_PORT}"+ export AGENT_API_PORT="${AUTOGPT_AGENT_API_PORT}"+ export NOTIFICATION_SERVICE_PORT="${AUTOGPT_NOTIFICATION_SERVICE_PORT}"+ export COPILOT_EXECUTOR_PORT="${AUTOGPT_COPILOT_EXECUTOR_PORT}"+ export PLATFORM_LINKING_SERVICE_PORT="${AUTOGPT_PLATFORM_LINKING_SERVICE_PORT}"+ export COPILOT_CHAT_BRIDGE_PORT="${AUTOGPT_COPILOT_CHAT_BRIDGE_PORT}"+ export BATCH_EXECUTOR_PORT="${AUTOGPT_BATCH_EXECUTOR_PORT}"+ # Keep self-hosted product behavior without enabling LOCAL-only API docs and+ # asyncio debug mode on the public REST process.+ export APP_ENV=dev BEHAVE_AS=local ENABLE_AUTH=true++ export BETTER_AUTH_URL="${AUTOGPT_PUBLIC_URL}"+ export BETTER_AUTH_INTERNAL_URL=http://127.0.0.1:3001+ export JWT_JWKS_URL=http://127.0.0.1:3001/api/auth/jwks+ export FRONTEND_BASE_URL="${AUTOGPT_PUBLIC_URL}"+ export PLATFORM_BASE_URL="${AUTOGPT_PUBLIC_URL}/_agpt"+ export PLATFORM_LINK_BASE_URL="${AUTOGPT_PUBLIC_URL}/link"+ export AGPT_SERVER_URL="http://127.0.0.1:${AUTOGPT_AGENT_API_PORT}/api"+ export AGPT_WS_SERVER_URL="ws://127.0.0.1:${AUTOGPT_WEBSOCKET_PORT}/ws"+ export WORKSPACE_STORAGE_DIR=/data/workspaces+ export VAPID_CLAIM_EMAIL="${VAPID_CLAIM_EMAIL:-mailto:admin@localhost}"+ export AUTH_REQUIRE_EMAIL_VERIFICATION=false+ export NODE_ENV=production+ # Python imports this directory's sitecustomize module before each service+ # entry point, suppressing HTTP access targets and redacting WS query tokens.+ export PYTHONPATH="${AUTOGPT_ASSET_DIR}/python"+}++configure_account_registration() {+ normalize_toggle AUTH_ALLOW_NEW_ACCOUNTS false+ if [[ "${AUTH_ALLOW_NEW_ACCOUNTS}" == true ]]; then+ log "WARNING: open account registration is enabled; disable it after creating the intended accounts"+ else+ log "account registration is closed; temporarily set AUTH_ALLOW_NEW_ACCOUNTS=true to create intended accounts"+ log "after signup, run 'docker exec <container> autogpt-admin promote <email>', disable registration, and restart"+ fi+}++write_nginx_public_url_config() {+ local path="${AUTOGPT_RUNTIME_DIR}/nginx/public-url.conf"+ local public_scheme="${AUTOGPT_PUBLIC_URL%%://*}"+ local public_host="${AUTOGPT_PUBLIC_URL#*://}"+ [[ ! -L "${path}" ]] || fatal "refusing symlink at nginx public URL config"+ install -m 0600 -o autogpt_proxy -g autogpt_proxy /dev/null "${path}"+ {+ printf "set \$autogpt_public_url \"%s\";\n" "${AUTOGPT_PUBLIC_URL}"+ printf "set \$autogpt_public_host \"%s\";\n" "${public_host}"+ printf "set \$autogpt_public_scheme \"%s\";\n" "${public_scheme}"+ } >"${path}"+}++normalize_integer() {+ local name="$1"+ local default="$2"+ local minimum="$3"+ local maximum="$4"+ local value="${!name:-${default}}"+ [[ "${value}" =~ ^[0-9]+$ ]] || fatal "${name} must be an integer"+ ((value >= minimum && value <= maximum)) || \+ fatal "${name} must be between ${minimum} and ${maximum}"+ printf -v "${name}" '%s' "${value}"+ export "${name?}"+}++normalize_toggle() {+ local name="$1"+ local default="$2"+ local value="${!name:-${default}}"+ case "${value}" in+ true | false) ;;+ *) fatal "${name} must be true or false" ;;+ esac+ printf -v "${name}" '%s' "${value}"+ export "${name?}"+}++initialize_postgres() {+ [[ -x "${POSTGRES_BINDIR}/initdb" ]] || fatal "PostgreSQL 15 initdb is missing"+ [[ ! -e "${PGDATA}/PG_VERSION" || -f "${PGDATA}/PG_VERSION" ]] || \+ fatal "invalid PostgreSQL data directory"+ [[ ! -f "${PGDATA}/PG_VERSION" ]] || return 0++ log "initializing PostgreSQL data directory"+ local password_file+ password_file="$(mktemp "${AUTOGPT_RUNTIME_DIR}/postgres-password.XXXXXX")"+ trap 'rm -f "${password_file}"' RETURN+ printf '%s\n' "${POSTGRES_PASSWORD}" >"${password_file}"+ chown postgres:postgres "${password_file}"+ chmod 0600 "${password_file}"+ run_as postgres "${POSTGRES_BINDIR}/initdb" \+ --pgdata="${PGDATA}" \+ --username=postgres \+ --pwfile="${password_file}" \+ --auth-local=peer \+ --auth-host=scram-sha-256 \+ --encoding=UTF8 \+ --locale=C.UTF-8++ {+ printf "\nlisten_addresses = '127.0.0.1'\n"+ printf "port = 5432\n"+ printf "unix_socket_directories = '/run/postgresql'\n"+ printf "password_encryption = 'scram-sha-256'\n" # pragma: allowlist secret+ } >>"${PGDATA}/postgresql.conf"+ rm -f "${password_file}"+ trap - RETURN+}++write_valkey_configs() {+ local port+ local target+ local temporary+ for port in 17000 17001 17002; do+ target="${AUTOGPT_RUNTIME_DIR}/valkey/${port}.conf"+ [[ ! -L "${target}" ]] || fatal "refusing symlink at Valkey config path"+ temporary="$(mktemp "${AUTOGPT_RUNTIME_DIR}/valkey/.${port}.conf.XXXXXX")"+ trap 'rm -f "${temporary}"' RETURN+ chmod 0600 "${temporary}"+ {+ printf 'bind 127.0.0.1\n'+ printf 'protected-mode yes\n'+ printf 'port %s\n' "${port}"+ printf 'dir /data/valkey/%s\n' "${port}"+ printf 'appendonly yes\n'+ printf 'cluster-enabled yes\n'+ printf 'cluster-config-file nodes.conf\n'+ printf 'cluster-node-timeout 5000\n'+ printf 'cluster-require-full-coverage no\n'+ printf 'cluster-announce-ip 127.0.0.1\n'+ printf 'cluster-announce-port %s\n' "${port}"+ printf 'cluster-announce-bus-port %s\n' "$((port + 10000))"+ printf 'requirepass %s\n' "${REDIS_PASSWORD}"+ printf 'masterauth %s\n' "${REDIS_PASSWORD}"+ } >"${temporary}"+ chown autogpt-valkey:autogpt-valkey "${temporary}"+ chmod 0400 "${temporary}"+ mv -f "${temporary}" "${target}"+ trap - RETURN+ done+}++write_rabbitmq_config() {+ local temporary+ temporary="$(mktemp "${AUTOGPT_RUNTIME_DIR}/rabbitmq/rabbitmq.conf.XXXXXX")"+ trap 'rm -f "${temporary}"' RETURN+ chmod 0600 "${temporary}"+ {+ cat "${AUTOGPT_ASSET_DIR}/rabbitmq/rabbitmq.conf"+ printf 'default_user = %s\n' "${RABBITMQ_DEFAULT_USER}"+ printf 'default_pass = %s\n' "${RABBITMQ_DEFAULT_PASS}"+ printf 'default_vhost = /\n'+ } >"${temporary}"+ chown rabbitmq:rabbitmq "${temporary}"+ mv -f "${temporary}" "${AUTOGPT_RUNTIME_DIR}/rabbitmq/rabbitmq.conf"+ trap - RETURN+}++write_falkordb_config() {+ local temporary+ temporary="$(mktemp "${AUTOGPT_RUNTIME_DIR}/falkordb.conf.XXXXXX")"+ trap 'rm -f "${temporary}"' RETURN+ chmod 0600 "${temporary}"+ {+ printf 'bind 127.0.0.1\n'+ printf 'protected-mode yes\n'+ printf 'port 6380\n'+ printf 'daemonize no\n'+ printf 'dir /data/falkordb\n'+ printf 'appendonly yes\n'+ printf 'requirepass %s\n' "${GRAPHITI_FALKORDB_PASSWORD}"+ printf '%s\n' \+ 'loadmodule /opt/falkordb/falkordb.so MAX_QUEUED_QUERIES 25 TIMEOUT 1000 RESULTSET_SIZE 10000'+ } >"${temporary}"+ chown autogpt-falkor:autogpt-falkor "${temporary}"+ mv -f "${temporary}" "${AUTOGPT_RUNTIME_DIR}/falkordb.conf"+ trap - RETURN+}++if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then+ main "$@"+fidiff --git a/autogpt_platform/single-container/fatal_listener.py b/autogpt_platform/single-container/fatal_listener.pynew file mode 100644index 0000000000..87e0d41364--- /dev/null+++ b/autogpt_platform/single-container/fatal_listener.py@@ -0,0 +1,99 @@+#!/usr/bin/env python3+"""Stop Supervisor for fatal services and unexpected bootstrap exits."""++from __future__ import annotations++import os+import re+import signal+import sys+from collections.abc import Callable+from typing import TextIO++SAFE_PROCESS_NAME = re.compile(r"^[A-Za-z0-9_.:-]+$")+MAX_PAYLOAD_LENGTH = 64 * 1024+++def main() -> int:+ while True:+ sys.stdout.write("READY\n")+ sys.stdout.flush()+ header = sys.stdin.readline()+ if not header:+ return 0+ handle_event(header, sys.stdin, sys.stdout, _terminate_supervisor)+++def handle_event(+ header: str,+ input_stream: TextIO,+ output_stream: TextIO,+ terminate: Callable[[], None],+) -> None:+ fields = _parse_fields(header)+ try:+ length = int(fields["len"])+ except (KeyError, ValueError) as exc:+ raise RuntimeError("Supervisor event has an invalid payload length") from exc+ if not 0 <= length <= MAX_PAYLOAD_LENGTH:+ raise RuntimeError("Supervisor event payload is too large")++ payload = input_stream.read(length)+ if len(payload) != length:+ raise RuntimeError("Supervisor event payload ended unexpectedly")+ event_name = fields.get("eventname")+ if event_name not in {"PROCESS_STATE_FATAL", "PROCESS_STATE_EXITED"}:+ raise RuntimeError("Supervisor event has an unsupported type")++ payload_fields = _parse_fields(payload)+ process_name = _safe_process_name(payload, payload_fields)+ if event_name == "PROCESS_STATE_EXITED" and not (+ process_name == "bootstrap" and payload_fields.get("expected") == "0"+ ):+ _acknowledge(output_stream)+ return++ reason = (+ "exited unexpectedly"+ if event_name == "PROCESS_STATE_EXITED"+ else "entered FATAL state"+ )+ print(+ f"[single-container] required process {reason}: {process_name}; "+ "terminating Supervisor for container restart",+ file=sys.stderr,+ flush=True,+ )+ _acknowledge(output_stream)+ terminate()+++def _acknowledge(output_stream: TextIO) -> None:+ output_stream.write("RESULT 2\nOK")+ output_stream.flush()+++def _parse_fields(line: str) -> dict[str, str]:+ fields: dict[str, str] = {}+ for item in line.strip().split():+ name, separator, value = item.partition(":")+ if separator:+ fields[name] = value+ return fields+++def _safe_process_name(payload: str, fields: dict[str, str]) -> str:+ if any(character in payload for character in "\r\n\0"):+ return "unknown"+ process_name = fields.get("processname", "unknown")+ return process_name if SAFE_PROCESS_NAME.fullmatch(process_name) else "unknown"+++def _terminate_supervisor() -> None:+ os.kill(os.getppid(), signal.SIGTERM)+ while True:+ signal.pause()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/autogpt_platform/single-container/healthcheck.sh b/autogpt_platform/single-container/healthcheck.shnew file mode 100755index 0000000000..62d9c4d5e9--- /dev/null+++ b/autogpt_platform/single-container/healthcheck.sh@@ -0,0 +1,75 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++readonly PROBE=("${AUTOGPT_BACKEND_DIR}/.venv/bin/python" "${AUTOGPT_ASSET_DIR}/probe.py")+readonly SUPERVISOR_CONFIG="${AUTOGPT_ASSET_DIR}/supervisor/supervisord.conf"+readonly POSTGRES_BINDIR="${POSTGRES_BINDIR:-/usr/lib/postgresql/15/bin}"++main() {+ [[ -f "${AUTOGPT_READY_FILE}" ]] || fatal "bootstrap readiness marker is absent"+ load_runtime_config+ check_supervised_processes+ check_infrastructure+ check_application_services+}++check_supervised_processes() {+ local programs=(+ fatal-exit postgres valkey-0 valkey-1 valkey-2 rabbitmq falkordb+ database-manager scheduler batch-executor notification executor+ copilot-executor copilot-bot platform-linking-manager websocket rest next nginx+ watchdog+ )+ local program+ local statuses+ # `supervisorctl status` exits non-zero when any program is not RUNNING. The+ # bootstrap program is intentionally one-shot, so validate only the required+ # long-running programs below instead of treating its expected EXITED state as+ # a failed Supervisor connection.+ statuses="$(supervisorctl -c "${SUPERVISOR_CONFIG}" status 2>/dev/null || true)"+ [[ -n "${statuses}" ]] || fatal "could not read supervisor process status"+ for program in "${programs[@]}"; do+ grep -Eq "^${program}[[:space:]]+RUNNING([[:space:]]|$)" <<<"${statuses}" || \+ fatal "supervisor process is not running: ${program}"+ done+}++check_infrastructure() {+ "${POSTGRES_BINDIR}/pg_isready" -q -h 127.0.0.1 -p 5432 -U postgres+ "${PROBE[@]}" redis --port 17000 --cluster \+ --password-env REDIS_PASSWORD+ "${PROBE[@]}" amqp --port 5672 \+ --username-env RABBITMQ_DEFAULT_USER \+ --password-env RABBITMQ_DEFAULT_PASS+ "${PROBE[@]}" redis --port 6380 \+ --password-env GRAPHITI_FALKORDB_PASSWORD+}++check_application_services() {+ local urls=(+ "http://127.0.0.1:${AUTOGPT_DATABASE_API_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ "http://127.0.0.1:${AUTOGPT_EXECUTION_SCHEDULER_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ "http://127.0.0.1:${AUTOGPT_BATCH_EXECUTOR_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ "http://127.0.0.1:${AUTOGPT_NOTIFICATION_SERVICE_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ "http://127.0.0.1:${AUTOGPT_EXECUTION_MANAGER_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ "http://127.0.0.1:${AUTOGPT_COPILOT_EXECUTOR_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ "http://127.0.0.1:${AUTOGPT_WEBSOCKET_PORT}/health"+ "http://127.0.0.1:${AUTOGPT_AGENT_API_PORT}/health"+ http://127.0.0.1:3001/+ http://127.0.0.1:3000/healthz+ )+ if [[ "${AUTOGPT_ENABLE_BOT_SERVICES:-false}" == true ]]; then+ urls+=(+ "http://127.0.0.1:${AUTOGPT_COPILOT_CHAT_BRIDGE_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ "http://127.0.0.1:${AUTOGPT_PLATFORM_LINKING_SERVICE_PORT}${AUTOGPT_INTERNAL_HEALTH_PATH}"+ )+ fi+ "${PROBE[@]}" http --timeout 10 "${urls[@]}" || \+ fatal "one or more application health probes failed"+}++main "$@"diff --git a/autogpt_platform/single-container/licenses/FalkorDB-SOURCE.txt b/autogpt_platform/single-container/licenses/FalkorDB-SOURCE.txtnew file mode 100644index 0000000000..47c86f6b62--- /dev/null+++ b/autogpt_platform/single-container/licenses/FalkorDB-SOURCE.txt@@ -0,0 +1,23 @@+FalkorDB server 4.20.1++Upstream source:+https://github.com/FalkorDB/FalkorDB/tree/efea8d99f8492f3eeaadcafeae29967c66d825a0++Upstream tag:+https://github.com/FalkorDB/FalkorDB/releases/tag/v4.20.1++License source:+https://github.com/FalkorDB/FalkorDB/blob/efea8d99f8492f3eeaadcafeae29967c66d825a0/LICENSE.txt++License SHA-256:+34e94c5087ba6e9fb34f35ae71df5e6533c5fc7cbbf6c44186a71e82806b69e1++Container source:+falkordb/falkordb-server:v4.20.1@sha256:8b676c2e72271f5d06541136eb214b0db50180636cc86f7ee38d63287e9b8d13++This AutoGPT image copies the Redis server inherited by the pinned FalkorDB+container to /opt/falkordb/redis-server and copies the unmodified FalkorDB+module to /opt/falkordb/falkordb.so. Redis provenance and notices are stored+in /usr/share/licenses/redis. FalkorDB is licensed under the Server Side+Public License version 1. The complete license text is provided in+SSPL-1.0.txt in this directory.diff --git a/autogpt_platform/single-container/licenses/FalkorDB-SSPL-1.0.txt b/autogpt_platform/single-container/licenses/FalkorDB-SSPL-1.0.txtnew file mode 100644index 0000000000..ea3921393f--- /dev/null+++ b/autogpt_platform/single-container/licenses/FalkorDB-SSPL-1.0.txt@@ -0,0 +1,557 @@+ Server Side Public License+ VERSION 1, OCTOBER 16, 2018++ Copyright © 2018 MongoDB, Inc.++ Everyone is permitted to copy and distribute verbatim copies of this+ license document, but changing it is not allowed.++ TERMS AND CONDITIONS++ 0. Definitions.++ “This License” refers to Server Side Public License.++ “Copyright” also means copyright-like laws that apply to other kinds of+ works, such as semiconductor masks.++ “The Program” refers to any copyrightable work licensed under this+ License. Each licensee is addressed as “you”. “Licensees” and+ “recipients” may be individuals or organizations.++ To “modify” a work means to copy from or adapt all or part of the work in+ a fashion requiring copyright permission, other than the making of an+ exact copy. The resulting work is called a “modified version” of the+ earlier work or a work “based on” the earlier work.++ A “covered work” means either the unmodified Program or a work based on+ the Program.++ To “propagate” a work means to do anything with it that, without+ permission, would make you directly or secondarily liable for+ infringement under applicable copyright law, except executing it on a+ computer or modifying a private copy. Propagation includes copying,+ distribution (with or without modification), making available to the+ public, and in some countries other activities as well.++ To “convey” a work means any kind of propagation that enables other+ parties to make or receive copies. Mere interaction with a user through a+ computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays “Appropriate Legal Notices” to the+ extent that it includes a convenient and prominently visible feature that+ (1) displays an appropriate copyright notice, and (2) tells the user that+ there is no warranty for the work (except to the extent that warranties+ are provided), that licensees may convey the work under this License, and+ how to view a copy of this License. If the interface presents a list of+ user commands or options, such as a menu, a prominent item in the list+ meets this criterion.++ 1. Source Code.++ The “source code” for a work means the preferred form of the work for+ making modifications to it. “Object code” means any non-source form of a+ work.++ A “Standard Interface” means an interface that either is an official+ standard defined by a recognized standards body, or, in the case of+ interfaces specified for a particular programming language, one that is+ widely used among developers working in that language. The “System+ Libraries” of an executable work include anything, other than the work as+ a whole, that (a) is included in the normal form of packaging a Major+ Component, but which is not part of that Major Component, and (b) serves+ only to enable use of the work with that Major Component, or to implement+ a Standard Interface for which an implementation is available to the+ public in source code form. A “Major Component”, in this context, means a+ major essential component (kernel, window system, and so on) of the+ specific operating system (if any) on which the executable work runs, or+ a compiler used to produce the work, or an object code interpreter used+ to run it.++ The “Corresponding Source” for a work in object code form means all the+ source code needed to generate, install, and (for an executable work) run+ the object code and to modify the work, including scripts to control+ those activities. However, it does not include the work's System+ Libraries, or general-purpose tools or generally available free programs+ which are used unmodified in performing those activities but which are+ not part of the work. For example, Corresponding Source includes+ interface definition files associated with source files for the work, and+ the source code for shared libraries and dynamically linked subprograms+ that the work is specifically designed to require, such as by intimate+ data communication or control flow between those subprograms and other+ parts of the work.++ The Corresponding Source need not include anything that users can+ regenerate automatically from other parts of the Corresponding Source.++ The Corresponding Source for a work in source code form is that same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+ copyright on the Program, and are irrevocable provided the stated+ conditions are met. This License explicitly affirms your unlimited+ permission to run the unmodified Program, subject to section 13. The+ output from running a covered work is covered by this License only if the+ output, given its content, constitutes a covered work. This License+ acknowledges your rights of fair use or other equivalent, as provided by+ copyright law. Subject to section 13, you may make, run and propagate+ covered works that you do not convey, without conditions so long as your+ license otherwise remains in force. You may convey covered works to+ others for the sole purpose of having them make modifications exclusively+ for you, or provide you with facilities for running those works, provided+ that you comply with the terms of this License in conveying all+ material for which you do not control copyright. Those thus making or+ running the covered works for you must do so exclusively on your+ behalf, under your direction and control, on terms that prohibit them+ from making any copies of your copyrighted material outside their+ relationship with you.++ Conveying under any other circumstances is permitted solely under the+ conditions stated below. Sublicensing is not allowed; section 10 makes it+ unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+ measure under any applicable law fulfilling obligations under article 11+ of the WIPO copyright treaty adopted on 20 December 1996, or similar laws+ prohibiting or restricting circumvention of such measures.++ When you convey a covered work, you waive any legal power to forbid+ circumvention of technological measures to the extent such circumvention is+ effected by exercising rights under this License with respect to the+ covered work, and you disclaim any intention to limit operation or+ modification of the work as a means of enforcing, against the work's users,+ your or third parties' legal rights to forbid circumvention of+ technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+ receive it, in any medium, provided that you conspicuously and+ appropriately publish on each copy an appropriate copyright notice; keep+ intact all notices stating that this License and any non-permissive terms+ added in accord with section 7 apply to the code; keep intact all notices+ of the absence of any warranty; and give all recipients a copy of this+ License along with the Program. You may charge any price or no price for+ each copy that you convey, and you may offer support or warranty+ protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+ produce it from the Program, in the form of source code under the terms+ of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified it,+ and giving a relevant date.++ b) The work must carry prominent notices stating that it is released+ under this License and any conditions added under section 7. This+ requirement modifies the requirement in section 4 to “keep intact all+ notices”.++ c) You must license the entire work, as a whole, under this License to+ anyone who comes into possession of a copy. This License will therefore+ apply, along with any applicable section 7 additional terms, to the+ whole of the work, and all its parts, regardless of how they are+ packaged. This License gives no permission to license the work in any+ other way, but it does not invalidate such permission if you have+ separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your work+ need not make them do so.++ A compilation of a covered work with other separate and independent+ works, which are not by their nature extensions of the covered work, and+ which are not combined with it such as to form a larger program, in or on+ a volume of a storage or distribution medium, is called an “aggregate” if+ the compilation and its resulting copyright are not used to limit the+ access or legal rights of the compilation's users beyond what the+ individual works permit. Inclusion of a covered work in an aggregate does+ not cause this License to apply to the other parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms of+ sections 4 and 5, provided that you also convey the machine-readable+ Corresponding Source under the terms of this License, in one of these+ ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium customarily+ used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a written+ offer, valid for at least three years and valid for as long as you+ offer spare parts or customer support for that product model, to give+ anyone who possesses the object code either (1) a copy of the+ Corresponding Source for all the software in the product that is+ covered by this License, on a durable physical medium customarily used+ for software interchange, for a price no more than your reasonable cost+ of physically performing this conveying of source, or (2) access to+ copy the Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This alternative is+ allowed only occasionally and noncommercially, and only if you received+ the object code with such an offer, in accord with subsection 6b.++ d) Convey the object code by offering access from a designated place+ (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to copy+ the object code is a network server, the Corresponding Source may be on+ a different server (operated by you or a third party) that supports+ equivalent copying facilities, provided you maintain clear directions+ next to the object code saying where to find the Corresponding Source.+ Regardless of what server hosts the Corresponding Source, you remain+ obligated to ensure that it is available for as long as needed to+ satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided you+ inform other peers where the object code and Corresponding Source of+ the work are being offered to the general public at no charge under+ subsection 6d.++ A separable portion of the object code, whose source code is excluded+ from the Corresponding Source as a System Library, need not be included+ in conveying the object code work.++ A “User Product” is either (1) a “consumer product”, which means any+ tangible personal property which is normally used for personal, family,+ or household purposes, or (2) anything designed or sold for incorporation+ into a dwelling. In determining whether a product is a consumer product,+ doubtful cases shall be resolved in favor of coverage. For a particular+ product received by a particular user, “normally used” refers to a+ typical or common use of that class of product, regardless of the status+ of the particular user or of the way in which the particular user+ actually uses, or expects or is expected to use, the product. A product+ is a consumer product regardless of whether the product has substantial+ commercial, industrial or non-consumer uses, unless such uses represent+ the only significant mode of use of the product.++ “Installation Information” for a User Product means any methods,+ procedures, authorization keys, or other information required to install+ and execute modified versions of a covered work in that User Product from+ a modified version of its Corresponding Source. The information must+ suffice to ensure that the continued functioning of the modified object+ code is in no case prevented or interfered with solely because+ modification has been made.++ If you convey an object code work under this section in, or with, or+ specifically for use in, a User Product, and the conveying occurs as part+ of a transaction in which the right of possession and use of the User+ Product is transferred to the recipient in perpetuity or for a fixed term+ (regardless of how the transaction is characterized), the Corresponding+ Source conveyed under this section must be accompanied by the+ Installation Information. But this requirement does not apply if neither+ you nor any third party retains the ability to install modified object+ code on the User Product (for example, the work has been installed in+ ROM).++ The requirement to provide Installation Information does not include a+ requirement to continue to provide support service, warranty, or updates+ for a work that has been modified or installed by the recipient, or for+ the User Product in which it has been modified or installed. Access+ to a network may be denied when the modification itself materially+ and adversely affects the operation of the network or violates the+ rules and protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided, in+ accord with this section must be in a format that is publicly documented+ (and with an implementation available to the public in source code form),+ and must require no special password or key for unpacking, reading or+ copying.++ 7. Additional Terms.++ “Additional permissions” are terms that supplement the terms of this+ License by making exceptions from one or more of its conditions.+ Additional permissions that are applicable to the entire Program shall be+ treated as though they were included in this License, to the extent that+ they are valid under applicable law. If additional permissions apply only+ to part of the Program, that part may be used separately under those+ permissions, but the entire Program remains governed by this License+ without regard to the additional permissions. When you convey a copy of+ a covered work, you may at your option remove any additional permissions+ from that copy, or from any part of it. (Additional permissions may be+ written to require their own removal in certain cases when you modify the+ work.) You may place additional permissions on material, added by you to+ a covered work, for which you have or can give appropriate copyright+ permission.++ Notwithstanding any other provision of this License, for material you add+ to a covered work, you may (if authorized by the copyright holders of+ that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some trade+ names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that material+ by anyone who conveys the material (or modified versions of it) with+ contractual assumptions of liability to the recipient, for any+ liability that these contractual assumptions directly impose on those+ licensors and authors.++ All other non-permissive additional terms are considered “further+ restrictions” within the meaning of section 10. If the Program as you+ received it, or any part of it, contains a notice stating that it is+ governed by this License along with a term that is a further restriction,+ you may remove that term. If a license document contains a further+ restriction but permits relicensing or conveying under this License, you+ may add to a covered work material governed by the terms of that license+ document, provided that the further restriction does not survive such+ relicensing or conveying.++ If you add terms to a covered work in accord with this section, you must+ place, in the relevant source files, a statement of the additional terms+ that apply to those files, or a notice indicating where to find the+ applicable terms. Additional terms, permissive or non-permissive, may be+ stated in the form of a separately written license, or stated as+ exceptions; the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+ provided under this License. Any attempt otherwise to propagate or modify+ it is void, and will automatically terminate your rights under this+ License (including any patent licenses granted under the third paragraph+ of section 11).++ However, if you cease all violation of this License, then your license+ from a particular copyright holder is reinstated (a) provisionally,+ unless and until the copyright holder explicitly and finally terminates+ your license, and (b) permanently, if the copyright holder fails to+ notify you of the violation by some reasonable means prior to 60 days+ after the cessation.++ Moreover, your license from a particular copyright holder is reinstated+ permanently if the copyright holder notifies you of the violation by some+ reasonable means, this is the first time you have received notice of+ violation of this License (for any work) from that copyright holder, and+ you cure the violation prior to 30 days after your receipt of the notice.++ Termination of your rights under this section does not terminate the+ licenses of parties who have received copies or rights from you under+ this License. If your rights have been terminated and not permanently+ reinstated, you do not qualify to receive new licenses for the same+ material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or run a+ copy of the Program. Ancillary propagation of a covered work occurring+ solely as a consequence of using peer-to-peer transmission to receive a+ copy likewise does not require acceptance. However, nothing other than+ this License grants you permission to propagate or modify any covered+ work. These actions infringe copyright if you do not accept this License.+ Therefore, by modifying or propagating a covered work, you indicate your+ acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically receives+ a license from the original licensors, to run, modify and propagate that+ work, subject to this License. You are not responsible for enforcing+ compliance by third parties with this License.++ An “entity transaction” is a transaction transferring control of an+ organization, or substantially all assets of one, or subdividing an+ organization, or merging organizations. If propagation of a covered work+ results from an entity transaction, each party to that transaction who+ receives a copy of the work also receives whatever licenses to the work+ the party's predecessor in interest had or could give under the previous+ paragraph, plus a right to possession of the Corresponding Source of the+ work from the predecessor in interest, if the predecessor has it or can+ get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the rights+ granted or affirmed under this License. For example, you may not impose a+ license fee, royalty, or other charge for exercise of rights granted+ under this License, and you may not initiate litigation (including a+ cross-claim or counterclaim in a lawsuit) alleging that any patent claim+ is infringed by making, using, selling, offering for sale, or importing+ the Program or any portion of it.++ 11. Patents.++ A “contributor” is a copyright holder who authorizes use under this+ License of the Program or a work on which the Program is based. The work+ thus licensed is called the contributor's “contributor version”.++ A contributor's “essential patent claims” are all patent claims owned or+ controlled by the contributor, whether already acquired or hereafter+ acquired, that would be infringed by some manner, permitted by this+ License, of making, using, or selling its contributor version, but do not+ include claims that would be infringed only as a consequence of further+ modification of the contributor version. For purposes of this definition,+ “control” includes the right to grant patent sublicenses in a manner+ consistent with the requirements of this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+ patent license under the contributor's essential patent claims, to make,+ use, sell, offer for sale, import and otherwise run, modify and propagate+ the contents of its contributor version.++ In the following three paragraphs, a “patent license” is any express+ agreement or commitment, however denominated, not to enforce a patent+ (such as an express permission to practice a patent or covenant not to+ sue for patent infringement). To “grant” such a patent license to a party+ means to make such an agreement or commitment not to enforce a patent+ against the party.++ If you convey a covered work, knowingly relying on a patent license, and+ the Corresponding Source of the work is not available for anyone to copy,+ free of charge and under the terms of this License, through a publicly+ available network server or other readily accessible means, then you must+ either (1) cause the Corresponding Source to be so available, or (2)+ arrange to deprive yourself of the benefit of the patent license for this+ particular work, or (3) arrange, in a manner consistent with the+ requirements of this License, to extend the patent license to downstream+ recipients. “Knowingly relying” means you have actual knowledge that, but+ for the patent license, your conveying the covered work in a country, or+ your recipient's use of the covered work in a country, would infringe+ one or more identifiable patents in that country that you have reason+ to believe are valid.++ If, pursuant to or in connection with a single transaction or+ arrangement, you convey, or propagate by procuring conveyance of, a+ covered work, and grant a patent license to some of the parties receiving+ the covered work authorizing them to use, propagate, modify or convey a+ specific copy of the covered work, then the patent license you grant is+ automatically extended to all recipients of the covered work and works+ based on it.++ A patent license is “discriminatory” if it does not include within the+ scope of its coverage, prohibits the exercise of, or is conditioned on+ the non-exercise of one or more of the rights that are specifically+ granted under this License. You may not convey a covered work if you are+ a party to an arrangement with a third party that is in the business of+ distributing software, under which you make payment to the third party+ based on the extent of your activity of conveying the work, and under+ which the third party grants, to any of the parties who would receive the+ covered work from you, a discriminatory patent license (a) in connection+ with copies of the covered work conveyed by you (or copies made from+ those copies), or (b) primarily for and in connection with specific+ products or compilations that contain the covered work, unless you+ entered into that arrangement, or that patent license was granted, prior+ to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting any+ implied license or other defenses to infringement that may otherwise be+ available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+ otherwise) that contradict the conditions of this License, they do not+ excuse you from the conditions of this License. If you cannot use,+ propagate or convey a covered work so as to satisfy simultaneously your+ obligations under this License and any other pertinent obligations, then+ as a consequence you may not use, propagate or convey it at all. For+ example, if you agree to terms that obligate you to collect a royalty for+ further conveying from those to whom you convey the Program, the only way+ you could satisfy both those terms and this License would be to refrain+ entirely from conveying the Program.++ 13. Offering the Program as a Service.++ If you make the functionality of the Program or a modified version+ available to third parties as a service, you must make the Service Source+ Code available via network download to everyone at no charge, under the+ terms of this License. Making the functionality of the Program or+ modified version available to third parties as a service includes,+ without limitation, enabling third parties to interact with the+ functionality of the Program or modified version remotely through a+ computer network, offering a service the value of which entirely or+ primarily derives from the value of the Program or modified version, or+ offering a service that accomplishes for users the primary purpose of the+ Program or modified version.++ “Service Source Code” means the Corresponding Source for the Program or+ the modified version, and the Corresponding Source for all programs that+ you use to make the Program or modified version available as a service,+ including, without limitation, management software, user interfaces,+ application program interfaces, automation software, monitoring software,+ backup software, storage software and hosting software, all such that a+ user could run an instance of the service using the Service Source Code+ you make available.++ 14. Revised Versions of this License.++ MongoDB, Inc. may publish revised and/or new versions of the Server Side+ Public License from time to time. Such new versions will be similar in+ spirit to the present version, but may differ in detail to address new+ problems or concerns.++ Each version is given a distinguishing version number. If the Program+ specifies that a certain numbered version of the Server Side Public+ License “or any later version” applies to it, you have the option of+ following the terms and conditions either of that numbered version or of+ any later version published by MongoDB, Inc. If the Program does not+ specify a version number of the Server Side Public License, you may+ choose any version ever published by MongoDB, Inc.++ If the Program specifies that a proxy can decide which future versions of+ the Server Side Public License can be used, that proxy's public statement+ of acceptance of a version permanently authorizes you to choose that+ version for the Program.++ Later license versions may give you additional or different permissions.+ However, no additional obligations are imposed on any author or copyright+ holder as a result of your choosing to follow a later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING+ ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF+ THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO+ LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU+ OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+ POSSIBILITY OF SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided above+ cannot be given local legal effect according to their terms, reviewing+ courts shall apply local law that most closely approximates an absolute+ waiver of all civil liability in connection with the Program, unless a+ warranty or assumption of liability accompanies a copy of the Program in+ return for a fee.++ END OF TERMS AND CONDITIONSdiff --git a/autogpt_platform/single-container/licenses/Redis-LICENSE.txt b/autogpt_platform/single-container/licenses/Redis-LICENSE.txtnew file mode 100644index 0000000000..4657905cf6--- /dev/null+++ b/autogpt_platform/single-container/licenses/Redis-LICENSE.txt@@ -0,0 +1,1399 @@+Starting with Redis 8, Redis Open Source is moving to a tri-licensing model with all new Redis code+contributions governed by the updated Redis Software Grant and Contributor License Agreement.+After this release, contributions are subject to your choice of: (a) the Redis Source Available License v2+(RSALv2);or (b) the Server Side Public License v1 (SSPLv1); or (c) the GNU Affero General Public License v3 (AGPLv3).+Redis Open Source 7.2 and prior releases remain subject to the BSDv3 clause license as referenced+in the REDISCONTRIBUTIONS.txt file.++The licensing structure for Redis 8.0 and subsequent releases is as follows:+++1. Redis Source Available License 2.0 (RSALv2) Agreement+========================================================++Last Update: December 30, 2023++Acceptance+----------++This Agreement sets forth the terms and conditions on which the Licensor+makes available the Software. By installing, downloading, accessing,+Using, or distributing any of the Software, You agree to all of the+terms and conditions of this Agreement.++If You are receiving the Software on behalf of Your Company, You+represent and warrant that You have the authority to agree to this+Agreement on behalf of such entity.++The Licensor reserves the right to update this Agreement from time to+time.++The terms below have the meanings set forth below for purposes of this+Agreement:++Definitions+-----------++Agreement: this Redis Source Available License 2.0 Agreement.++Control: ownership, directly or indirectly, of substantially all the+assets of an entity, or the power to direct its management and policies+by vote, contract, or otherwise.++License: the License as described in the License paragraph below.++Licensor: the entity offering these terms, which includes Redis Ltd. on+behalf of itself and its subsidiaries and affiliates worldwide.++Modify, Modified, or Modification: copy from or adapt all or part of the+work in a fashion requiring copyright permission other than making an+exact copy. The resulting work is called a Modified version of the+earlier work.++Redis: the Redis software as described in redis.com redis.io.++Software: certain Software components designed to work with Redis and+provided to You under this Agreement.++Trademark: the trademarks, service marks, and any other similar rights.++Use: anything You do with the Software requiring one of Your Licenses.++You: the recipient of the Software, the individual or entity on whose+behalf You are agreeing to this Agreement.++Your Company: any legal entity, sole proprietorship, or other kind of+organization that You work for, plus all organizations that have control+over, are under the control of, or are under common control with that+organization.++Your Licenses: means all the Licenses granted to You for the Software+under this Agreement.++License+-------++The Licensor grants You a non-exclusive, royalty-free, worldwide,+non-sublicensable, non-transferable license to use, copy, distribute,+make available, and prepare derivative works of the Software, in each+case subject to the limitations and conditions below.++Limitations+-----------++You may not make the functionality of the Software or a Modified version+available to third parties as a service or distribute the Software or a+Modified version in a manner that makes the functionality of the+Software available to third parties.++Making the functionality of the Software or Modified version available+to third parties includes, without limitation, enabling third parties to+interact with the functionality of the Software or Modified version in+distributed form or remotely through a computer network, offering a+product or service, the value of which entirely or primarily derives+from the value of the Software or Modified version, or offering a+product or service that accomplishes for users the primary purpose of+the Software or Modified version.++You may not alter, remove, or obscure any licensing, copyright, or other+notices of the Licensor in the Software. Any use of the Licensor's+Trademarks is subject to applicable law.++Patents+-------++The Licensor grants You a License, under any patent claims the Licensor+can License, or becomes able to License, to make, have made, use, sell,+offer for sale, import and have imported the Software, in each case+subject to the limitations and conditions in this License. This License+does not cover any patent claims that You cause to be infringed by+Modifications or additions to the Software. If You or Your Company make+any written claim that the Software infringes or contributes to+infringement of any patent, your patent License for the Software granted+under this Agreement ends immediately. If Your Company makes such a+claim, your patent License ends immediately for work on behalf of Your+Company.++Notices+-------++You must ensure that anyone who gets a copy of any part of the Software+from You also gets a copy of the terms and conditions in this Agreement.++If You modify the Software, You must include in any Modified copies of+the Software prominent notices stating that You have Modified the+Software.++No Other Rights+---------------++The terms and conditions of this Agreement do not imply any Licenses+other than those expressly granted in this Agreement.++Termination+-----------++If You Use the Software in violation of this Agreement, such Use is not+Licensed, and Your Licenses will automatically terminate. If the+Licensor provides You with a notice of your violation, and You cease all+violations of this License no later than 30 days after You receive that+notice, Your Licenses will be reinstated retroactively. However, if You+violate this Agreement after such reinstatement, any additional+violation of this Agreement will cause your Licenses to terminate+automatically and permanently.++No Liability+------------++As far as the law allows, the Software comes as is, without any+warranty or condition, and the Licensor will not be liable to You for+any damages arising out of this Agreement or the Use or nature of the+Software, under any kind of legal claim.++Governing Law and Jurisdiction+------------------------------++If You are located in Asia, Pacific, Americas, or other jurisdictions+not listed below, the Agreement will be construed and enforced in all+respects in accordance with the laws of the State of California, U.S.A.,+without reference to its choice of law rules. The courts located in the+County of Santa Clara, California, have exclusive jurisdiction for all+purposes relating to this Agreement.++If You are located in Israel, the Agreement will be construed and+enforced in all respects in accordance with the laws of the State of+Israel without reference to its choice of law rules. The courts located+in the Central District of the State of Israel have exclusive+jurisdiction for all purposes relating to this Agreement.++If You are located in Europe, United Kingdom, Middle East or Africa, the+Agreement will be construed and enforced in all respects in accordance+with the laws of England and Wales without reference to its choice of+law rules. The competent courts located in London, England, have+exclusive jurisdiction for all purposes relating to this Agreement.++++2. Server Side Public License (SSPL)+====================================++ Server Side Public License+ VERSION 1, OCTOBER 16, 2018++ Copyright (c) 2018 MongoDB, Inc.++ Everyone is permitted to copy and distribute verbatim copies of this+ license document, but changing it is not allowed.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to Server Side Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+ works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+ License. Each licensee is addressed as "you". "Licensees" and+ "recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work in+ a fashion requiring copyright permission, other than the making of an+ exact copy. The resulting work is called a "modified version" of the+ earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based on+ the Program.++ To "propagate" a work means to do anything with it that, without+ permission, would make you directly or secondarily liable for+ infringement under applicable copyright law, except executing it on a+ computer or modifying a private copy. Propagation includes copying,+ distribution (with or without modification), making available to the+ public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+ parties to make or receive copies. Mere interaction with a user through a+ computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices" to the+ extent that it includes a convenient and prominently visible feature that+ (1) displays an appropriate copyright notice, and (2) tells the user that+ there is no warranty for the work (except to the extent that warranties+ are provided), that licensees may convey the work under this License, and+ how to view a copy of this License. If the interface presents a list of+ user commands or options, such as a menu, a prominent item in the list+ meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work for+ making modifications to it. "Object code" means any non-source form of a+ work.++ A "Standard Interface" means an interface that either is an official+ standard defined by a recognized standards body, or, in the case of+ interfaces specified for a particular programming language, one that is+ widely used among developers working in that language. The "System+ Libraries" of an executable work include anything, other than the work as+ a whole, that (a) is included in the normal form of packaging a Major+ Component, but which is not part of that Major Component, and (b) serves+ only to enable use of the work with that Major Component, or to implement+ a Standard Interface for which an implementation is available to the+ public in source code form. A "Major Component", in this context, means a+ major essential component (kernel, window system, and so on) of the+ specific operating system (if any) on which the executable work runs, or+ a compiler used to produce the work, or an object code interpreter used+ to run it.++ The "Corresponding Source" for a work in object code form means all the+ source code needed to generate, install, and (for an executable work) run+ the object code and to modify the work, including scripts to control+ those activities. However, it does not include the work's System+ Libraries, or general-purpose tools or generally available free programs+ which are used unmodified in performing those activities but which are+ not part of the work. For example, Corresponding Source includes+ interface definition files associated with source files for the work, and+ the source code for shared libraries and dynamically linked subprograms+ that the work is specifically designed to require, such as by intimate+ data communication or control flow between those subprograms and other+ parts of the work.++ The Corresponding Source need not include anything that users can+ regenerate automatically from other parts of the Corresponding Source.++ The Corresponding Source for a work in source code form is that same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+ copyright on the Program, and are irrevocable provided the stated+ conditions are met. This License explicitly affirms your unlimited+ permission to run the unmodified Program, subject to section 13. The+ output from running a covered work is covered by this License only if the+ output, given its content, constitutes a covered work. This License+ acknowledges your rights of fair use or other equivalent, as provided by+ copyright law. Subject to section 13, you may make, run and propagate+ covered works that you do not convey, without conditions so long as your+ license otherwise remains in force. You may convey covered works to+ others for the sole purpose of having them make modifications exclusively+ for you, or provide you with facilities for running those works, provided+ that you comply with the terms of this License in conveying all+ material for which you do not control copyright. Those thus making or+ running the covered works for you must do so exclusively on your+ behalf, under your direction and control, on terms that prohibit them+ from making any copies of your copyrighted material outside their+ relationship with you.++ Conveying under any other circumstances is permitted solely under the+ conditions stated below. Sublicensing is not allowed; section 10 makes it+ unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+ measure under any applicable law fulfilling obligations under article 11+ of the WIPO copyright treaty adopted on 20 December 1996, or similar laws+ prohibiting or restricting circumvention of such measures.++ When you convey a covered work, you waive any legal power to forbid+ circumvention of technological measures to the extent such circumvention is+ effected by exercising rights under this License with respect to the+ covered work, and you disclaim any intention to limit operation or+ modification of the work as a means of enforcing, against the work's users,+ your or third parties' legal rights to forbid circumvention of+ technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+ receive it, in any medium, provided that you conspicuously and+ appropriately publish on each copy an appropriate copyright notice; keep+ intact all notices stating that this License and any non-permissive terms+ added in accord with section 7 apply to the code; keep intact all notices+ of the absence of any warranty; and give all recipients a copy of this+ License along with the Program. You may charge any price or no price for+ each copy that you convey, and you may offer support or warranty+ protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+ produce it from the Program, in the form of source code under the terms+ of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified it,+ and giving a relevant date.++ b) The work must carry prominent notices stating that it is released+ under this License and any conditions added under section 7. This+ requirement modifies the requirement in section 4 to "keep intact all+ notices".++ c) You must license the entire work, as a whole, under this License to+ anyone who comes into possession of a copy. This License will therefore+ apply, along with any applicable section 7 additional terms, to the+ whole of the work, and all its parts, regardless of how they are+ packaged. This License gives no permission to license the work in any+ other way, but it does not invalidate such permission if you have+ separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your work+ need not make them do so.++ A compilation of a covered work with other separate and independent+ works, which are not by their nature extensions of the covered work, and+ which are not combined with it such as to form a larger program, in or on+ a volume of a storage or distribution medium, is called an "aggregate" if+ the compilation and its resulting copyright are not used to limit the+ access or legal rights of the compilation's users beyond what the+ individual works permit. Inclusion of a covered work in an aggregate does+ not cause this License to apply to the other parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms of+ sections 4 and 5, provided that you also convey the machine-readable+ Corresponding Source under the terms of this License, in one of these+ ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium customarily+ used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a written+ offer, valid for at least three years and valid for as long as you+ offer spare parts or customer support for that product model, to give+ anyone who possesses the object code either (1) a copy of the+ Corresponding Source for all the software in the product that is+ covered by this License, on a durable physical medium customarily used+ for software interchange, for a price no more than your reasonable cost+ of physically performing this conveying of source, or (2) access to+ copy the Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This alternative is+ allowed only occasionally and noncommercially, and only if you received+ the object code with such an offer, in accord with subsection 6b.++ d) Convey the object code by offering access from a designated place+ (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to copy+ the object code is a network server, the Corresponding Source may be on+ a different server (operated by you or a third party) that supports+ equivalent copying facilities, provided you maintain clear directions+ next to the object code saying where to find the Corresponding Source.+ Regardless of what server hosts the Corresponding Source, you remain+ obligated to ensure that it is available for as long as needed to+ satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided you+ inform other peers where the object code and Corresponding Source of+ the work are being offered to the general public at no charge under+ subsection 6d.++ A separable portion of the object code, whose source code is excluded+ from the Corresponding Source as a System Library, need not be included+ in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+ tangible personal property which is normally used for personal, family,+ or household purposes, or (2) anything designed or sold for incorporation+ into a dwelling. In determining whether a product is a consumer product,+ doubtful cases shall be resolved in favor of coverage. For a particular+ product received by a particular user, "normally used" refers to a+ typical or common use of that class of product, regardless of the status+ of the particular user or of the way in which the particular user+ actually uses, or expects or is expected to use, the product. A product+ is a consumer product regardless of whether the product has substantial+ commercial, industrial or non-consumer uses, unless such uses represent+ the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+ procedures, authorization keys, or other information required to install+ and execute modified versions of a covered work in that User Product from+ a modified version of its Corresponding Source. The information must+ suffice to ensure that the continued functioning of the modified object+ code is in no case prevented or interfered with solely because+ modification has been made.++ If you convey an object code work under this section in, or with, or+ specifically for use in, a User Product, and the conveying occurs as part+ of a transaction in which the right of possession and use of the User+ Product is transferred to the recipient in perpetuity or for a fixed term+ (regardless of how the transaction is characterized), the Corresponding+ Source conveyed under this section must be accompanied by the+ Installation Information. But this requirement does not apply if neither+ you nor any third party retains the ability to install modified object+ code on the User Product (for example, the work has been installed in+ ROM).++ The requirement to provide Installation Information does not include a+ requirement to continue to provide support service, warranty, or updates+ for a work that has been modified or installed by the recipient, or for+ the User Product in which it has been modified or installed. Access+ to a network may be denied when the modification itself materially+ and adversely affects the operation of the network or violates the+ rules and protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided, in+ accord with this section must be in a format that is publicly documented+ (and with an implementation available to the public in source code form),+ and must require no special password or key for unpacking, reading or+ copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+ License by making exceptions from one or more of its conditions.+ Additional permissions that are applicable to the entire Program shall be+ treated as though they were included in this License, to the extent that+ they are valid under applicable law. If additional permissions apply only+ to part of the Program, that part may be used separately under those+ permissions, but the entire Program remains governed by this License+ without regard to the additional permissions. When you convey a copy of+ a covered work, you may at your option remove any additional permissions+ from that copy, or from any part of it. (Additional permissions may be+ written to require their own removal in certain cases when you modify the+ work.) You may place additional permissions on material, added by you to+ a covered work, for which you have or can give appropriate copyright+ permission.++ Notwithstanding any other provision of this License, for material you add+ to a covered work, you may (if authorized by the copyright holders of+ that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some trade+ names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that material+ by anyone who conveys the material (or modified versions of it) with+ contractual assumptions of liability to the recipient, for any+ liability that these contractual assumptions directly impose on those+ licensors and authors.++ All other non-permissive additional terms are considered "further+ restrictions" within the meaning of section 10. If the Program as you+ received it, or any part of it, contains a notice stating that it is+ governed by this License along with a term that is a further restriction,+ you may remove that term. If a license document contains a further+ restriction but permits relicensing or conveying under this License, you+ may add to a covered work material governed by the terms of that license+ document, provided that the further restriction does not survive such+ relicensing or conveying.++ If you add terms to a covered work in accord with this section, you must+ place, in the relevant source files, a statement of the additional terms+ that apply to those files, or a notice indicating where to find the+ applicable terms. Additional terms, permissive or non-permissive, may be+ stated in the form of a separately written license, or stated as+ exceptions; the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+ provided under this License. Any attempt otherwise to propagate or modify+ it is void, and will automatically terminate your rights under this+ License (including any patent licenses granted under the third paragraph+ of section 11).++ However, if you cease all violation of this License, then your license+ from a particular copyright holder is reinstated (a) provisionally,+ unless and until the copyright holder explicitly and finally terminates+ your license, and (b) permanently, if the copyright holder fails to+ notify you of the violation by some reasonable means prior to 60 days+ after the cessation.++ Moreover, your license from a particular copyright holder is reinstated+ permanently if the copyright holder notifies you of the violation by some+ reasonable means, this is the first time you have received notice of+ violation of this License (for any work) from that copyright holder, and+ you cure the violation prior to 30 days after your receipt of the notice.++ Termination of your rights under this section does not terminate the+ licenses of parties who have received copies or rights from you under+ this License. If your rights have been terminated and not permanently+ reinstated, you do not qualify to receive new licenses for the same+ material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or run a+ copy of the Program. Ancillary propagation of a covered work occurring+ solely as a consequence of using peer-to-peer transmission to receive a+ copy likewise does not require acceptance. However, nothing other than+ this License grants you permission to propagate or modify any covered+ work. These actions infringe copyright if you do not accept this License.+ Therefore, by modifying or propagating a covered work, you indicate your+ acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically receives+ a license from the original licensors, to run, modify and propagate that+ work, subject to this License. You are not responsible for enforcing+ compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+ organization, or substantially all assets of one, or subdividing an+ organization, or merging organizations. If propagation of a covered work+ results from an entity transaction, each party to that transaction who+ receives a copy of the work also receives whatever licenses to the work+ the party's predecessor in interest had or could give under the previous+ paragraph, plus a right to possession of the Corresponding Source of the+ work from the predecessor in interest, if the predecessor has it or can+ get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the rights+ granted or affirmed under this License. For example, you may not impose a+ license fee, royalty, or other charge for exercise of rights granted+ under this License, and you may not initiate litigation (including a+ cross-claim or counterclaim in a lawsuit) alleging that any patent claim+ is infringed by making, using, selling, offering for sale, or importing+ the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+ License of the Program or a work on which the Program is based. The work+ thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims owned or+ controlled by the contributor, whether already acquired or hereafter+ acquired, that would be infringed by some manner, permitted by this+ License, of making, using, or selling its contributor version, but do not+ include claims that would be infringed only as a consequence of further+ modification of the contributor version. For purposes of this definition,+ "control" includes the right to grant patent sublicenses in a manner+ consistent with the requirements of this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+ patent license under the contributor's essential patent claims, to make,+ use, sell, offer for sale, import and otherwise run, modify and propagate+ the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+ agreement or commitment, however denominated, not to enforce a patent+ (such as an express permission to practice a patent or covenant not to+ sue for patent infringement). To "grant" such a patent license to a party+ means to make such an agreement or commitment not to enforce a patent+ against the party.++ If you convey a covered work, knowingly relying on a patent license, and+ the Corresponding Source of the work is not available for anyone to copy,+ free of charge and under the terms of this License, through a publicly+ available network server or other readily accessible means, then you must+ either (1) cause the Corresponding Source to be so available, or (2)+ arrange to deprive yourself of the benefit of the patent license for this+ particular work, or (3) arrange, in a manner consistent with the+ requirements of this License, to extend the patent license to downstream+ recipients. "Knowingly relying" means you have actual knowledge that, but+ for the patent license, your conveying the covered work in a country, or+ your recipient's use of the covered work in a country, would infringe+ one or more identifiable patents in that country that you have reason+ to believe are valid.++ If, pursuant to or in connection with a single transaction or+ arrangement, you convey, or propagate by procuring conveyance of, a+ covered work, and grant a patent license to some of the parties receiving+ the covered work authorizing them to use, propagate, modify or convey a+ specific copy of the covered work, then the patent license you grant is+ automatically extended to all recipients of the covered work and works+ based on it.++ A patent license is "discriminatory" if it does not include within the+ scope of its coverage, prohibits the exercise of, or is conditioned on+ the non-exercise of one or more of the rights that are specifically+ granted under this License. You may not convey a covered work if you are+ a party to an arrangement with a third party that is in the business of+ distributing software, under which you make payment to the third party+ based on the extent of your activity of conveying the work, and under+ which the third party grants, to any of the parties who would receive the+ covered work from you, a discriminatory patent license (a) in connection+ with copies of the covered work conveyed by you (or copies made from+ those copies), or (b) primarily for and in connection with specific+ products or compilations that contain the covered work, unless you+ entered into that arrangement, or that patent license was granted, prior+ to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting any+ implied license or other defenses to infringement that may otherwise be+ available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+ otherwise) that contradict the conditions of this License, they do not+ excuse you from the conditions of this License. If you cannot use,+ propagate or convey a covered work so as to satisfy simultaneously your+ obligations under this License and any other pertinent obligations, then+ as a consequence you may not use, propagate or convey it at all. For+ example, if you agree to terms that obligate you to collect a royalty for+ further conveying from those to whom you convey the Program, the only way+ you could satisfy both those terms and this License would be to refrain+ entirely from conveying the Program.++ 13. Offering the Program as a Service.++ If you make the functionality of the Program or a modified version+ available to third parties as a service, you must make the Service Source+ Code available via network download to everyone at no charge, under the+ terms of this License. Making the functionality of the Program or+ modified version available to third parties as a service includes,+ without limitation, enabling third parties to interact with the+ functionality of the Program or modified version remotely through a+ computer network, offering a service the value of which entirely or+ primarily derives from the value of the Program or modified version, or+ offering a service that accomplishes for users the primary purpose of the+ Program or modified version.++ "Service Source Code" means the Corresponding Source for the Program or+ the modified version, and the Corresponding Source for all programs that+ you use to make the Program or modified version available as a service,+ including, without limitation, management software, user interfaces,+ application program interfaces, automation software, monitoring software,+ backup software, storage software and hosting software, all such that a+ user could run an instance of the service using the Service Source Code+ you make available.++ 14. Revised Versions of this License.++ MongoDB, Inc. may publish revised and/or new versions of the Server Side+ Public License from time to time. Such new versions will be similar in+ spirit to the present version, but may differ in detail to address new+ problems or concerns.++ Each version is given a distinguishing version number. If the Program+ specifies that a certain numbered version of the Server Side Public+ License "or any later version" applies to it, you have the option of+ following the terms and conditions either of that numbered version or of+ any later version published by MongoDB, Inc. If the Program does not+ specify a version number of the Server Side Public License, you may+ choose any version ever published by MongoDB, Inc.++ If the Program specifies that a proxy can decide which future versions of+ the Server Side Public License can be used, that proxy's public statement+ of acceptance of a version permanently authorizes you to choose that+ version for the Program.++ Later license versions may give you additional or different permissions.+ However, no additional obligations are imposed on any author or copyright+ holder as a result of your choosing to follow a later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING+ ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF+ THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO+ LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU+ OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+ POSSIBILITY OF SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided above+ cannot be given local legal effect according to their terms, reviewing+ courts shall apply local law that most closely approximates an absolute+ waiver of all civil liability in connection with the Program, unless a+ warranty or assumption of liability accompanies a copy of the Program in+ return for a fee.++ END OF TERMS AND CONDITIONS+++3. GNU AFFERO GENERAL PUBLIC LICENSE, Version 3, 19 Nov 2007+========================================================++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU Affero General Public License is a free, copyleft license for+software and other kinds of works, specifically designed to ensure+cooperation with the community in the case of network server software.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+our General Public Licenses are intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ Developers that use our General Public Licenses protect your rights+with two steps: (1) assert copyright on the software, and (2) offer+you this License which gives you legal permission to copy, distribute+and/or modify the software.++ A secondary benefit of defending all users' freedom is that+improvements made in alternate versions of the program, if they+receive widespread use, become available for other developers to+incorporate. Many developers of free software are heartened and+encouraged by the resulting cooperation. However, in the case of+software used on network servers, this result may fail to come about.+The GNU General Public License permits making a modified version and+letting the public access it on a server without ever releasing its+source code to the public.++ The GNU Affero General Public License is designed specifically to+ensure that, in such cases, the modified source code becomes available+to the community. It requires the operator of a network server to+provide the source code of the modified version running there to the+users of that server. Therefore, public use of a modified version, on+a publicly accessible server, gives the public access to the source+code of the modified version.++ An older license, called the Affero General Public License and+published by Affero, was designed to accomplish similar goals. This is+a different license, not a version of the Affero GPL, but Affero has+released a new version of the Affero GPL which permits relicensing under+this license.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU Affero General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Remote Network Interaction; Use with the GNU General Public License.++ Notwithstanding any other provision of this License, if you modify the+Program, your modified version must prominently offer all users+interacting with it remotely through a computer network (if your version+supports such interaction) an opportunity to receive the Corresponding+Source of your version by providing access to the Corresponding Source+from a network server at no charge, through some standard or customary+means of facilitating copying of software. This Corresponding Source+shall include the Corresponding Source for any work covered by version 3+of the GNU General Public License that is incorporated pursuant to the+following paragraph.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the work with which it is combined will remain governed by version+3 of the GNU General Public License.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU Affero General Public License from time to time. Such new versions+will be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU Affero General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU Affero General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU Affero General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU Affero General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If your software can interact with users remotely through a computer+network, you should also make sure that it provides a way for users to+get its source. For example, if your program is a web application, its+interface could display a "Source" link that leads users to an archive+of the code. There are many ways you could offer source, and different+solutions will be better for different programs; see section 13 for the+specific requirements.++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU AGPL, see+<https://www.gnu.org/licenses/>.diff --git a/autogpt_platform/single-container/licenses/Redis-REDISCONTRIBUTIONS.txt b/autogpt_platform/single-container/licenses/Redis-REDISCONTRIBUTIONS.txtnew file mode 100644index 0000000000..0819e5f43a--- /dev/null+++ b/autogpt_platform/single-container/licenses/Redis-REDISCONTRIBUTIONS.txt@@ -0,0 +1,31 @@+Copyright (c) 2006-Present, Redis Ltd. and Contributors+All rights reserved.++Note: Continued Applicability of the BSD-3-Clause License++Despite the shift to the dual-licensing model with version 7.4 (RSALv2 or SSPLv1) and+the shift to a tri-license option with version 8.0 (RSALv2/SSPLv1/AGPLv3), portions of+Redis Open Source remain available subject to the BSD-3-Clause License (BSD).+See below for the full BSD license:++Redistribution and use in source and binary forms, with or without modification, are permitted+provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this list of conditions+and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions+and the following disclaimer in the documentation and/or other materials provided with the+distribution.++3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse+or promote products derived from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND+FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER+IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF+THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/autogpt_platform/single-container/licenses/Redis-SOURCE.txt b/autogpt_platform/single-container/licenses/Redis-SOURCE.txtnew file mode 100644index 0000000000..a0d642b8d9--- /dev/null+++ b/autogpt_platform/single-container/licenses/Redis-SOURCE.txt@@ -0,0 +1,45 @@+Redis server 8.6.3++Upstream source:+https://github.com/redis/redis/tree/bd3b38d41070b478c58bc8b72d2af89cbccd1a40++Upstream tag:+https://github.com/redis/redis/releases/tag/8.6.3++FalkorDB image definition using Redis 8.6.3:+https://github.com/FalkorDB/FalkorDB/blob/efea8d99f8492f3eeaadcafeae29967c66d825a0/build/docker/Dockerfile.server++Official Redis image manifest:+redis:8.6.3@sha256:4d25e2fe601f7ffaeb4437cb6ced3518bc36edf34ebe98863c80836943d94529++Official image packaging source:+https://github.com/redis/docker-library-redis/tree/0e8b375a38d5b818b5baf23372e395ff8ee99d8e++Redis source archive SHA-256 used by that packaging:+58d0d1eb49a1ea6c2179659707fec171b1e2e2b8d5157ed2ec59d1d66ad5a654++fast_float v6.1.4 license source:+https://github.com/fastfloat/fast_float/blob/3e57d8dcfb0a04b5a8a26b486b54490a2e9b310f/LICENSE-MIT++License bundle source:+https://github.com/redis/redis/blob/bd3b38d41070b478c58bc8b72d2af89cbccd1a40/LICENSE.txt++License bundle SHA-256:+4a0e416b9537688f30dfe69ddaceb2ca64d96b7df02a0a6760d376890ddc4e40++Contributions notice SHA-256:+aa6a56234e5ca27f09010693d1c31ca83988d7a0dc80fb253603e052d1d7f0d1++FalkorDB 4.20.1 is built on the official redis:8.6.3 image. This AutoGPT+image copies /usr/local/bin/redis-server from the pinned FalkorDB container+image to /opt/falkordb/redis-server. Redis 8.6.3 is offered under its+upstream tri-license. The complete upstream license bundle and contributions+notice are provided beside this file. The license and copyright notices for+the dependencies linked into the upstream Redis server are preserved under+deps/ and src/ using component-corresponding paths. Redis embeds fast_float's+MIT notice in its vendored header, so the standalone LICENSE-MIT here comes+from the matching upstream fast_float v6.1.4 tag. The official Redis image+packaging modifies the default protected-mode setting and jemalloc build+configuration; the exact packaging source above records those changes.+Publication remains subject to the project's legal approval of the selected+Redis license path and whole-image notice bundle.diff --git a/autogpt_platform/single-container/licenses/redis/deps/fast_float/LICENSE-MIT b/autogpt_platform/single-container/licenses/redis/deps/fast_float/LICENSE-MITnew file mode 100644index 0000000000..2fb2a37ad7--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/fast_float/LICENSE-MIT@@ -0,0 +1,27 @@+MIT License++Copyright (c) 2021 The fast_float authors++Permission is hereby granted, free of charge, to any+person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the+Software without restriction, including without+limitation the rights to use, copy, modify, merge,+publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software+is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice+shall be included in all copies or substantial portions+of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/autogpt_platform/single-container/licenses/redis/deps/fpconv/LICENSE.txt b/autogpt_platform/single-container/licenses/redis/deps/fpconv/LICENSE.txtnew file mode 100644index 0000000000..36b7cd93cd--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/fpconv/LICENSE.txt@@ -0,0 +1,23 @@+Boost Software License - Version 1.0 - August 17th, 2003++Permission is hereby granted, free of charge, to any person or organization+obtaining a copy of the software and accompanying documentation covered by+this license (the "Software") to use, reproduce, display, distribute,+execute, and transmit the Software, and to prepare derivative works of the+Software, and to permit third-parties to whom the Software is furnished to+do so, all subject to the following:++The copyright notices in the Software and this entire statement, including+the above license grant, this restriction and the following disclaimer,+must be included in all copies of the Software, in whole or in part, and+all derivative works of the Software, unless such copies or derivative+works are solely in the form of machine-executable object code generated by+a source language processor.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/autogpt_platform/single-container/licenses/redis/deps/hdr_histogram/COPYING.txt b/autogpt_platform/single-container/licenses/redis/deps/hdr_histogram/COPYING.txtnew file mode 100644index 0000000000..0e259d42c9--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/hdr_histogram/COPYING.txt@@ -0,0 +1,121 @@+Creative Commons Legal Code++CC0 1.0 Universal++ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED+ HEREUNDER.++Statement of Purpose++The laws of most jurisdictions throughout the world automatically confer+exclusive Copyright and Related Rights (defined below) upon the creator+and subsequent owner(s) (each and all, an "owner") of an original work of+authorship and/or a database (each, a "Work").++Certain owners wish to permanently relinquish those rights to a Work for+the purpose of contributing to a commons of creative, cultural and+scientific works ("Commons") that the public can reliably and without fear+of later claims of infringement build upon, modify, incorporate in other+works, reuse and redistribute as freely as possible in any form whatsoever+and for any purposes, including without limitation commercial purposes.+These owners may contribute to the Commons to promote the ideal of a free+culture and the further production of creative, cultural and scientific+works, or to gain reputation or greater distribution for their Work in+part through the use and efforts of others.++For these and/or other purposes and motivations, and without any+expectation of additional consideration or compensation, the person+associating CC0 with a Work (the "Affirmer"), to the extent that he or she+is an owner of Copyright and Related Rights in the Work, voluntarily+elects to apply CC0 to the Work and publicly distribute the Work under its+terms, with knowledge of his or her Copyright and Related Rights in the+Work and the meaning and intended legal effect of CC0 on those rights.++1. Copyright and Related Rights. A Work made available under CC0 may be+protected by copyright and related or neighboring rights ("Copyright and+Related Rights"). Copyright and Related Rights include, but are not+limited to, the following:++ i. the right to reproduce, adapt, distribute, perform, display,+ communicate, and translate a Work;+ ii. moral rights retained by the original author(s) and/or performer(s);+iii. publicity and privacy rights pertaining to a person's image or+ likeness depicted in a Work;+ iv. rights protecting against unfair competition in regards to a Work,+ subject to the limitations in paragraph 4(a), below;+ v. rights protecting the extraction, dissemination, use and reuse of data+ in a Work;+ vi. database rights (such as those arising under Directive 96/9/EC of the+ European Parliament and of the Council of 11 March 1996 on the legal+ protection of databases, and under any national implementation+ thereof, including any amended or successor version of such+ directive); and+vii. other similar, equivalent or corresponding rights throughout the+ world based on applicable law or treaty, and any national+ implementations thereof.++2. Waiver. To the greatest extent permitted by, but not in contravention+of, applicable law, Affirmer hereby overtly, fully, permanently,+irrevocably and unconditionally waives, abandons, and surrenders all of+Affirmer's Copyright and Related Rights and associated claims and causes+of action, whether now known or unknown (including existing as well as+future claims and causes of action), in the Work (i) in all territories+worldwide, (ii) for the maximum duration provided by applicable law or+treaty (including future time extensions), (iii) in any current or future+medium and for any number of copies, and (iv) for any purpose whatsoever,+including without limitation commercial, advertising or promotional+purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each+member of the public at large and to the detriment of Affirmer's heirs and+successors, fully intending that such Waiver shall not be subject to+revocation, rescission, cancellation, termination, or any other legal or+equitable action to disrupt the quiet enjoyment of the Work by the public+as contemplated by Affirmer's express Statement of Purpose.++3. Public License Fallback. Should any part of the Waiver for any reason+be judged legally invalid or ineffective under applicable law, then the+Waiver shall be preserved to the maximum extent permitted taking into+account Affirmer's express Statement of Purpose. In addition, to the+extent the Waiver is so judged Affirmer hereby grants to each affected+person a royalty-free, non transferable, non sublicensable, non exclusive,+irrevocable and unconditional license to exercise Affirmer's Copyright and+Related Rights in the Work (i) in all territories worldwide, (ii) for the+maximum duration provided by applicable law or treaty (including future+time extensions), (iii) in any current or future medium and for any number+of copies, and (iv) for any purpose whatsoever, including without+limitation commercial, advertising or promotional purposes (the+"License"). The License shall be deemed effective as of the date CC0 was+applied by Affirmer to the Work. Should any part of the License for any+reason be judged legally invalid or ineffective under applicable law, such+partial invalidity or ineffectiveness shall not invalidate the remainder+of the License, and in such case Affirmer hereby affirms that he or she+will not (i) exercise any of his or her remaining Copyright and Related+Rights in the Work or (ii) assert any associated claims and causes of+action with respect to the Work, in either case contrary to Affirmer's+express Statement of Purpose.++4. Limitations and Disclaimers.++ a. No trademark or patent rights held by Affirmer are waived, abandoned,+ surrendered, licensed or otherwise affected by this document.+ b. Affirmer offers the Work as-is and makes no representations or+ warranties of any kind concerning the Work, express, implied,+ statutory or otherwise, including without limitation warranties of+ title, merchantability, fitness for a particular purpose, non+ infringement, or the absence of latent or other defects, accuracy, or+ the present or absence of errors, whether or not discoverable, all to+ the greatest extent permissible under applicable law.+ c. Affirmer disclaims responsibility for clearing rights of other persons+ that may apply to the Work or any use thereof, including without+ limitation any person's Copyright and Related Rights in the Work.+ Further, Affirmer disclaims responsibility for obtaining any necessary+ consents, permissions or other rights required for any use of the+ Work.+ d. Affirmer understands and acknowledges that Creative Commons is not a+ party to this document and has no duty or obligation with respect to+ this CC0 or use of the Work.diff --git a/autogpt_platform/single-container/licenses/redis/deps/hdr_histogram/LICENSE.txt b/autogpt_platform/single-container/licenses/redis/deps/hdr_histogram/LICENSE.txtnew file mode 100644index 0000000000..9b4e66ed7d--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/hdr_histogram/LICENSE.txt@@ -0,0 +1,41 @@+The code in this repository code was Written by Gil Tene, Michael Barker,+and Matt Warren, and released to the public domain, as explained at+http://creativecommons.org/publicdomain/zero/1.0/++For users of this code who wish to consume it under the "BSD" license+rather than under the public domain or CC0 contribution text mentioned+above, the code found under this directory is *also* provided under the+following license (commonly referred to as the BSD 2-Clause License). This+license does not detract from the above stated release of the code into+the public domain, and simply represents an additional license granted by+the Author.++-----------------------------------------------------------------------------+** Beginning of "BSD 2-Clause License" text. **++ Copyright (c) 2012, 2013, 2014 Gil Tene+ Copyright (c) 2014 Michael Barker+ Copyright (c) 2014 Matt Warren+ All rights reserved.++ Redistribution and use in source and binary forms, with or without+ modification, are permitted provided that the following conditions are met:++ 1. Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++ 2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF+ THE POSSIBILITY OF SUCH DAMAGE.diff --git a/autogpt_platform/single-container/licenses/redis/deps/hiredis/COPYING b/autogpt_platform/single-container/licenses/redis/deps/hiredis/COPYINGnew file mode 100644index 0000000000..a5fc973955--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/hiredis/COPYING@@ -0,0 +1,29 @@+Copyright (c) 2009-2011, Salvatore Sanfilippo <antirez at gmail dot com>+Copyright (c) 2010-2011, Pieter Noordhuis <pcnoordhuis at gmail dot com>++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice,+ this list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++* Neither the name of Redis nor the names of its contributors may be used+ to endorse or promote products derived from this software without specific+ prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/autogpt_platform/single-container/licenses/redis/deps/jemalloc/COPYING b/autogpt_platform/single-container/licenses/redis/deps/jemalloc/COPYINGnew file mode 100644index 0000000000..3b7fd3585d--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/jemalloc/COPYING@@ -0,0 +1,27 @@+Unless otherwise specified, files in the jemalloc source distribution are+subject to the following license:+--------------------------------------------------------------------------------+Copyright (C) 2002-present Jason Evans <[email protected]>.+All rights reserved.+Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.+Copyright (C) 2009-present Facebook, Inc. All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:+1. Redistributions of source code must retain the above copyright notice(s),+ this list of conditions and the following disclaimer.+2. Redistributions in binary form must reproduce the above copyright notice(s),+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS+OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO+EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT,+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE+OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF+ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.+--------------------------------------------------------------------------------diff --git a/autogpt_platform/single-container/licenses/redis/deps/lua/COPYRIGHT b/autogpt_platform/single-container/licenses/redis/deps/lua/COPYRIGHTnew file mode 100644index 0000000000..a86026803a--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/lua/COPYRIGHT@@ -0,0 +1,34 @@+Lua License+-----------++Lua is licensed under the terms of the MIT license reproduced below.+This means that Lua is free software and can be used for both academic+and commercial purposes at absolutely no cost.++For details and rationale, see http://www.lua.org/license.html .++===============================================================================++Copyright (C) 1994-2012 Lua.org, PUC-Rio.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.++===============================================================================++(end of COPYRIGHT)diff --git a/autogpt_platform/single-container/licenses/redis/deps/xxhash/LICENSE b/autogpt_platform/single-container/licenses/redis/deps/xxhash/LICENSEnew file mode 100644index 0000000000..e4c5da7234--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/deps/xxhash/LICENSE@@ -0,0 +1,26 @@+xxHash Library+Copyright (c) 2012-2021 Yann Collet+All rights reserved.++BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)++Redistribution and use in source and binary forms, with or without modification,+are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright notice, this+ list of conditions and the following disclaimer in the documentation and/or+ other materials provided with the distribution.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/autogpt_platform/single-container/licenses/redis/src/lzf_c.c b/autogpt_platform/single-container/licenses/redis/src/lzf_c.cnew file mode 100644index 0000000000..e958489520--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/src/lzf_c.c@@ -0,0 +1,308 @@+/*+ * Copyright (c) 2000-2010 Marc Alexander Lehmann <[email protected]>+ *+ * Redistribution and use in source and binary forms, with or without modifica-+ * tion, are permitted provided that the following conditions are met:+ *+ * 1. Redistributions of source code must retain the above copyright notice,+ * this list of conditions and the following disclaimer.+ *+ * 2. Redistributions in binary form must reproduce the above copyright+ * notice, this list of conditions and the following disclaimer in the+ * documentation and/or other materials provided with the distribution.+ *+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED+ * OF THE POSSIBILITY OF SUCH DAMAGE.+ *+ * Alternatively, the contents of this file may be used under the terms of+ * the GNU General Public License ("GPL") version 2 or any later version,+ * in which case the provisions of the GPL are applicable instead of+ * the above. If you wish to allow the use of your version of this file+ * only under the terms of the GPL and not to allow others to use your+ * version of this file under the BSD license, indicate your decision+ * by deleting the provisions above and replace them with the notice+ * and other provisions required by the GPL. If you do not delete the+ * provisions above, a recipient may use your version of this file under+ * either the BSD or the GPL.+ */++#include "lzfP.h"++#define HSIZE (1 << (HLOG))++/*+ * don't play with this unless you benchmark!+ * the data format is not dependent on the hash function.+ * the hash function might seem strange, just believe me,+ * it works ;)+ */+#ifndef FRST+# define FRST(p) (((p[0]) << 8) | p[1])+# define NEXT(v,p) (((v) << 8) | p[2])+# if ULTRA_FAST+# define IDX(h) ((( h >> (3*8 - HLOG)) - h ) & (HSIZE - 1))+# elif VERY_FAST+# define IDX(h) ((( h >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))+# else+# define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))+# endif+#endif+/*+ * IDX works because it is very similar to a multiplicative hash, e.g.+ * ((h * 57321 >> (3*8 - HLOG)) & (HSIZE - 1))+ * the latter is also quite fast on newer CPUs, and compresses similarly.+ *+ * the next one is also quite good, albeit slow ;)+ * (int)(cos(h & 0xffffff) * 1e6)+ */++#if 0+/* original lzv-like hash function, much worse and thus slower */+# define FRST(p) (p[0] << 5) ^ p[1]+# define NEXT(v,p) ((v) << 5) ^ p[2]+# define IDX(h) ((h) & (HSIZE - 1))+#endif++#define MAX_LIT (1 << 5)+#define MAX_OFF (1 << 13)+#define MAX_REF ((1 << 8) + (1 << 3))++#if __GNUC__ >= 3+# define expect(expr,value) __builtin_expect ((expr),(value))+# define inline inline+#else+# define expect(expr,value) (expr)+# define inline static+#endif++#define expect_false(expr) expect ((expr) != 0, 0)+#define expect_true(expr) expect ((expr) != 0, 1)++#if defined(__has_attribute)+# if __has_attribute(no_sanitize)+# define NO_SANITIZE(sanitizer) __attribute__((no_sanitize(sanitizer)))+# endif+#endif++#if !defined(NO_SANITIZE)+# define NO_SANITIZE(sanitizer)+#endif++#if defined(__clang__)+#define NO_SANITIZE_MSAN(sanitizer) NO_SANITIZE(sanitizer)+#else+#define NO_SANITIZE_MSAN(sanitizer)+#endif++/*+ * compressed format+ *+ * 000LLLLL <L+1> ; literal, L+1=1..33 octets+ * LLLooooo oooooooo ; backref L+1=1..7 octets, o+1=1..4096 offset+ * 111ooooo LLLLLLLL oooooooo ; backref L+8 octets, o+1=1..4096 offset+ *+ */+NO_SANITIZE("alignment")+NO_SANITIZE_MSAN("memory")+size_t+lzf_compress (const void *const in_data, size_t in_len,+ void *out_data, size_t out_len+#if LZF_STATE_ARG+ , LZF_STATE htab+#endif+ )+{+#if !LZF_STATE_ARG+ LZF_STATE htab;+#endif+ const u8 *ip = (const u8 *)in_data;+ u8 *op = (u8 *)out_data;+ const u8 *in_end = ip + in_len;+ u8 *out_end = op + out_len;+ const u8 *ref;++ /* off requires a type wide enough to hold a general pointer difference.+ * ISO C doesn't have that (size_t might not be enough and ptrdiff_t only+ * works for differences within a single object). We also assume that no+ * no bit pattern traps. Since the only platform that is both non-POSIX+ * and fails to support both assumptions is windows 64 bit, we make a+ * special workaround for it.+ */+#if defined (WIN32) && defined (_M_X64)+ unsigned _int64 off; /* workaround for missing POSIX compliance */+#else+ size_t off;+#endif+ unsigned int hval;+ int lit;++ if (!in_len || !out_len)+ return 0;++#if INIT_HTAB+ memset (htab, 0, sizeof (htab));+#endif++ lit = 0; op++; /* start run */++ hval = FRST (ip);+ while (ip < in_end - 2)+ {+ LZF_HSLOT *hslot;++ hval = NEXT (hval, ip);+ hslot = htab + IDX (hval);+ ref = *hslot ? (*hslot + LZF_HSLOT_BIAS) : NULL; /* avoid applying zero offset to null pointer */+ *hslot = ip - LZF_HSLOT_BIAS;++ if (1+#if INIT_HTAB+ && ref < ip /* the next test will actually take care of this, but this is faster */+#endif+ && (off = ip - ref - 1) < MAX_OFF+ && ref > (u8 *)in_data+ && ref[2] == ip[2]+#if STRICT_ALIGN+ && ((ref[1] << 8) | ref[0]) == ((ip[1] << 8) | ip[0])+#else+ && *(u16 *)ref == *(u16 *)ip+#endif+ )+ {+ /* match found at *ref++ */+ unsigned int len = 2;+ size_t maxlen = in_end - ip - len;+ maxlen = maxlen > MAX_REF ? MAX_REF : maxlen;++ if (expect_false (op + 3 + 1 >= out_end)) /* first a faster conservative test */+ if (op - !lit + 3 + 1 >= out_end) /* second the exact but rare test */+ return 0;++ op [- lit - 1] = lit - 1; /* stop run */+ op -= !lit; /* undo run if length is zero */++ for (;;)+ {+ if (expect_true (maxlen > 16))+ {+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;++ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;++ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;++ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ len++; if (ref [len] != ip [len]) break;+ }++ do+ len++;+ while (len < maxlen && ref[len] == ip[len]);++ break;+ }++ len -= 2; /* len is now #octets - 1 */+ ip++;++ if (len < 7)+ {+ *op++ = (off >> 8) + (len << 5);+ }+ else+ {+ *op++ = (off >> 8) + ( 7 << 5);+ *op++ = len - 7;+ }++ *op++ = off;++ lit = 0; op++; /* start run */++ ip += len + 1;++ if (expect_false (ip >= in_end - 2))+ break;++#if ULTRA_FAST || VERY_FAST+ --ip;+# if VERY_FAST && !ULTRA_FAST+ --ip;+# endif+ hval = FRST (ip);++ hval = NEXT (hval, ip);+ htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;+ ip++;++# if VERY_FAST && !ULTRA_FAST+ hval = NEXT (hval, ip);+ htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;+ ip++;+# endif+#else+ ip -= len + 1;++ do+ {+ hval = NEXT (hval, ip);+ htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;+ ip++;+ }+ while (len--);+#endif+ }+ else+ {+ /* one more literal byte we must copy */+ if (expect_false (op >= out_end))+ return 0;++ lit++; *op++ = *ip++;++ if (expect_false (lit == MAX_LIT))+ {+ op [- lit - 1] = lit - 1; /* stop run */+ lit = 0; op++; /* start run */+ }+ }+ }++ if (op + 3 > out_end) /* at most 3 bytes can be missing here */+ return 0;++ while (ip < in_end)+ {+ lit++; *op++ = *ip++;++ if (expect_false (lit == MAX_LIT))+ {+ op [- lit - 1] = lit - 1; /* stop run */+ lit = 0; op++; /* start run */+ }+ }++ op [- lit - 1] = lit - 1; /* end run */+ op -= !lit; /* undo run if length is zero */++ return op - (u8 *)out_data;+}diff --git a/autogpt_platform/single-container/licenses/redis/src/lzf_d.c b/autogpt_platform/single-container/licenses/redis/src/lzf_d.cnew file mode 100644index 0000000000..ff32be892a--- /dev/null+++ b/autogpt_platform/single-container/licenses/redis/src/lzf_d.c@@ -0,0 +1,191 @@+/*+ * Copyright (c) 2000-2010 Marc Alexander Lehmann <[email protected]>+ *+ * Redistribution and use in source and binary forms, with or without modifica-+ * tion, are permitted provided that the following conditions are met:+ *+ * 1. Redistributions of source code must retain the above copyright notice,+ * this list of conditions and the following disclaimer.+ *+ * 2. Redistributions in binary form must reproduce the above copyright+ * notice, this list of conditions and the following disclaimer in the+ * documentation and/or other materials provided with the distribution.+ *+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED+ * OF THE POSSIBILITY OF SUCH DAMAGE.+ *+ * Alternatively, the contents of this file may be used under the terms of+ * the GNU General Public License ("GPL") version 2 or any later version,+ * in which case the provisions of the GPL are applicable instead of+ * the above. If you wish to allow the use of your version of this file+ * only under the terms of the GPL and not to allow others to use your+ * version of this file under the BSD license, indicate your decision+ * by deleting the provisions above and replace them with the notice+ * and other provisions required by the GPL. If you do not delete the+ * provisions above, a recipient may use your version of this file under+ * either the BSD or the GPL.+ */++#include "lzfP.h"++#if AVOID_ERRNO+# define SET_ERRNO(n)+#else+# include <errno.h>+# define SET_ERRNO(n) errno = (n)+#endif++#if USE_REP_MOVSB /* small win on amd, big loss on intel */+#if (__i386 || __amd64) && __GNUC__ >= 3+# define lzf_movsb(dst, src, len) \+ asm ("rep movsb" \+ : "=D" (dst), "=S" (src), "=c" (len) \+ : "0" (dst), "1" (src), "2" (len));+#endif+#endif++#if defined(__GNUC__) && __GNUC__ >= 7+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"+#endif+size_t+lzf_decompress (const void *const in_data, size_t in_len,+ void *out_data, size_t out_len)+{+ u8 const *ip = (const u8 *)in_data;+ u8 *op = (u8 *)out_data;+ u8 const *const in_end = ip + in_len;+ u8 *const out_end = op + out_len;++ while (ip < in_end)+ {+ unsigned int ctrl;+ ctrl = *ip++;++ if (ctrl < (1 << 5)) /* literal run */+ {+ ctrl++;++ if (op + ctrl > out_end)+ {+ SET_ERRNO (E2BIG);+ return 0;+ }++#if CHECK_INPUT+ if (ip + ctrl > in_end)+ {+ SET_ERRNO (EINVAL);+ return 0;+ }+#endif++#ifdef lzf_movsb+ lzf_movsb (op, ip, ctrl);+#else+ switch (ctrl)+ {+ case 32: *op++ = *ip++; case 31: *op++ = *ip++; case 30: *op++ = *ip++; case 29: *op++ = *ip++;+ case 28: *op++ = *ip++; case 27: *op++ = *ip++; case 26: *op++ = *ip++; case 25: *op++ = *ip++;+ case 24: *op++ = *ip++; case 23: *op++ = *ip++; case 22: *op++ = *ip++; case 21: *op++ = *ip++;+ case 20: *op++ = *ip++; case 19: *op++ = *ip++; case 18: *op++ = *ip++; case 17: *op++ = *ip++;+ case 16: *op++ = *ip++; case 15: *op++ = *ip++; case 14: *op++ = *ip++; case 13: *op++ = *ip++;+ case 12: *op++ = *ip++; case 11: *op++ = *ip++; case 10: *op++ = *ip++; case 9: *op++ = *ip++;+ case 8: *op++ = *ip++; case 7: *op++ = *ip++; case 6: *op++ = *ip++; case 5: *op++ = *ip++;+ case 4: *op++ = *ip++; case 3: *op++ = *ip++; case 2: *op++ = *ip++; case 1: *op++ = *ip++;+ }+#endif+ }+ else /* back reference */+ {+ unsigned int len = ctrl >> 5;++ u8 *ref = op - ((ctrl & 0x1f) << 8) - 1;++#if CHECK_INPUT+ if (ip >= in_end)+ {+ SET_ERRNO (EINVAL);+ return 0;+ }+#endif+ if (len == 7)+ {+ len += *ip++;+#if CHECK_INPUT+ if (ip >= in_end)+ {+ SET_ERRNO (EINVAL);+ return 0;+ }+#endif+ }++ ref -= *ip++;++ if (op + len + 2 > out_end)+ {+ SET_ERRNO (E2BIG);+ return 0;+ }++ if (ref < (u8 *)out_data)+ {+ SET_ERRNO (EINVAL);+ return 0;+ }++#ifdef lzf_movsb+ len += 2;+ lzf_movsb (op, ref, len);+#else+ switch (len)+ {+ default:+ len += 2;++ if (op >= ref + len)+ {+ /* disjunct areas */+ memcpy (op, ref, len);+ op += len;+ }+ else+ {+ /* overlapping, use octte by octte copying */+ do+ *op++ = *ref++;+ while (--len);+ }++ break;++ case 9: *op++ = *ref++; /* fall-thru */+ case 8: *op++ = *ref++; /* fall-thru */+ case 7: *op++ = *ref++; /* fall-thru */+ case 6: *op++ = *ref++; /* fall-thru */+ case 5: *op++ = *ref++; /* fall-thru */+ case 4: *op++ = *ref++; /* fall-thru */+ case 3: *op++ = *ref++; /* fall-thru */+ case 2: *op++ = *ref++; /* fall-thru */+ case 1: *op++ = *ref++; /* fall-thru */+ case 0: *op++ = *ref++; /* two octets more */+ *op++ = *ref++; /* fall-thru */+ }+#endif+ }+ }++ return op - (u8 *)out_data;+}+#if defined(__GNUC__) && __GNUC__ >= 5+#pragma GCC diagnostic pop+#endifdiff --git a/autogpt_platform/single-container/nginx/nginx.conf b/autogpt_platform/single-container/nginx/nginx.confnew file mode 100644index 0000000000..6db19d347e--- /dev/null+++ b/autogpt_platform/single-container/nginx/nginx.conf@@ -0,0 +1,135 @@+worker_processes auto;+# Nginx error messages at lower levels can include full request targets. Keep+# bearer query strings and one-time path tokens out of container logs.+error_log stderr crit;+pid /run/autogpt/nginx/nginx.pid;++events {+ worker_connections 2048;+}++http {+ include /etc/nginx/mime.types;+ default_type application/octet-stream;+ server_tokens off;+ sendfile on;+ keepalive_timeout 65;+ client_max_body_size 256m;+ # Application services provide structured operational logs. Do not keep a+ # second, unbounded request log under /run, and never log OAuth query tokens.+ access_log off;+ client_body_temp_path /run/autogpt/nginx/client;+ proxy_temp_path /run/autogpt/nginx/proxy;+ fastcgi_temp_path /run/autogpt/nginx/fastcgi;+ uwsgi_temp_path /run/autogpt/nginx/uwsgi;+ scgi_temp_path /run/autogpt/nginx/scgi;++ map $http_upgrade $connection_upgrade {+ default upgrade;+ '' '';+ }++ upstream autogpt_frontend {+ server 127.0.0.1:3001;+ keepalive 32;+ }++ upstream autogpt_rest {+ server 127.0.0.1:8006;+ keepalive 32;+ }++ upstream autogpt_websocket {+ server 127.0.0.1:8001;+ }++ server {+ listen 3000 default_server;+ listen [::]:3000 default_server;+ include /run/autogpt/nginx/public-url.conf;++ location = /healthz {+ access_log off;+ add_header Content-Type text/plain;+ return 200 'ok\n';+ }++ # The WebSocket bearer token is a query parameter. Never put it in an+ # access log, even when nginx runs with verbose request logging.+ location = /_agpt/ws {+ access_log off;+ proxy_pass http://autogpt_websocket/ws;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $connection_upgrade;+ proxy_set_header Host $autogpt_public_host;+ proxy_set_header X-Forwarded-For $remote_addr;+ proxy_set_header X-Forwarded-Proto $autogpt_public_scheme;+ proxy_read_timeout 1d;+ proxy_send_timeout 1d;+ proxy_buffering off;+ }++ location = /_agpt/ws/ {+ access_log off;+ proxy_pass http://autogpt_websocket/ws;+ proxy_http_version 1.1;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $connection_upgrade;+ proxy_set_header Host $autogpt_public_host;+ proxy_set_header X-Forwarded-For $remote_addr;+ proxy_set_header X-Forwarded-Proto $autogpt_public_scheme;+ proxy_read_timeout 1d;+ proxy_send_timeout 1d;+ proxy_buffering off;+ }++ # This distribution exposes one application port, not internal API+ # documentation or process metrics. Keep LOCAL/development tooling off+ # the public proxy even if an upstream dependency changes its defaults.+ location ~ ^/_agpt/(?:(?:docs|redoc)(?:/|$)|(?:openapi\.json|metrics)/?$|external-api/(?:(?:docs|redoc)(?:/|$)|(?:openapi\.json|metrics)/?$)) {+ return 404;+ }++ # A trailing slash on proxy_pass strips /_agpt/ before forwarding.+ # Buffering stays disabled so CoPilot's long-lived SSE stream reaches+ # the browser immediately instead of accumulating in nginx.+ location /_agpt/ {+ proxy_pass http://autogpt_rest/;+ proxy_http_version 1.1;+ proxy_set_header Connection "";+ proxy_set_header Host $autogpt_public_host;+ proxy_set_header X-Forwarded-For $remote_addr;+ proxy_set_header X-Forwarded-Proto $autogpt_public_scheme;+ proxy_set_header X-Forwarded-Host $autogpt_public_host;+ proxy_read_timeout 1h;+ proxy_send_timeout 1h;+ proxy_request_buffering off;+ proxy_buffering off;+ proxy_cache off;+ add_header X-Accel-Buffering no always;+ # FastAPI builds slash-normalization redirects after nginx strips+ # /_agpt. Restore the public prefix for its internal API targets.+ proxy_redirect ~^https?://[^/]+(/(?:api|external-api)(?:/.*)?$) $autogpt_public_url/_agpt$1;+ proxy_redirect ~^(/(?:api|external-api)(?:/.*)?$) $autogpt_public_url/_agpt$1;+ }++ location / {+ proxy_pass http://autogpt_frontend;+ proxy_http_version 1.1;+ proxy_set_header Host $autogpt_public_host;+ proxy_set_header X-Forwarded-For $remote_addr;+ proxy_set_header X-Forwarded-Proto $autogpt_public_scheme;+ proxy_set_header X-Forwarded-Host $autogpt_public_host;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection $connection_upgrade;+ # Next standalone constructs middleware redirects from its private+ # HOSTNAME/PORT (127.0.0.1:3001), even though the forwarded Host is+ # public. Rewrite only that private origin to the operator's+ # validated AUTOGPT_PUBLIC_URL. This avoids leaking container+ # topology and avoids using an arbitrary Host as a redirect target.+ proxy_redirect ~^https?://(?:localhost|127\.0\.0\.1):3001(/.*)$ $autogpt_public_url$1;+ proxy_read_timeout 5m;+ }+ }+}diff --git a/autogpt_platform/single-container/probe.py b/autogpt_platform/single-container/probe.pynew file mode 100755index 0000000000..d621c4738d--- /dev/null+++ b/autogpt_platform/single-container/probe.py@@ -0,0 +1,188 @@+#!/usr/bin/env python3+"""Small health probes for the bundled services."""++from __future__ import annotations++import argparse+import os+import socket+import sys+import urllib.request+from concurrent.futures import ThreadPoolExecutor+from typing import BinaryIO+++def main() -> int:+ parser = argparse.ArgumentParser()+ subparsers = parser.add_subparsers(dest="command", required=True)++ tcp_parser = subparsers.add_parser("tcp")+ _add_address_arguments(tcp_parser)++ http_parser = subparsers.add_parser("http")+ http_parser.add_argument("urls", nargs="+")+ http_parser.add_argument("--timeout", type=float, default=5)++ amqp_parser = subparsers.add_parser("amqp")+ _add_address_arguments(amqp_parser)+ amqp_parser.add_argument("--username-env", required=True)+ amqp_parser.add_argument("--password-env", required=True)++ redis_parser = subparsers.add_parser("redis")+ _add_address_arguments(redis_parser)+ redis_parser.add_argument("--password-env")+ redis_parser.add_argument("--cluster", action="store_true")++ args = parser.parse_args()+ try:+ if args.command == "tcp":+ probe_tcp(args.host, args.port, args.timeout)+ elif args.command == "http":+ probe_http_many(args.urls, args.timeout)+ elif args.command == "amqp":+ probe_amqp(+ args.host,+ args.port,+ args.timeout,+ os.environ.get(args.username_env, ""),+ os.environ.get(args.password_env, ""),+ )+ else:+ password = (+ os.environ.get(args.password_env, "") if args.password_env else ""+ )+ probe_redis(args.host, args.port, args.timeout, password, args.cluster)+ except (OSError, RuntimeError, TimeoutError) as exc:+ print(f"probe failed: {exc}", file=sys.stderr)+ return 1+ return 0+++def probe_tcp(host: str, port: int, timeout: float) -> None:+ with socket.create_connection((host, port), timeout=timeout):+ pass+++def probe_http(url: str, timeout: float) -> None:+ request = urllib.request.Request(url, headers={"User-Agent": "autogpt-healthcheck"})+ with urllib.request.urlopen(request, timeout=timeout) as response:+ if not 200 <= response.status < 300:+ raise RuntimeError(f"HTTP {response.status} from {url}")+++def probe_http_many(urls: list[str], timeout: float) -> None:+ with ThreadPoolExecutor(max_workers=len(urls)) as executor:+ futures = [executor.submit(probe_http, url, timeout) for url in urls]+ for future in futures:+ future.result()+++def probe_amqp(+ host: str,+ port: int,+ timeout: float,+ username: str,+ password: str,+) -> None:+ if not username or not password:+ raise RuntimeError("AMQP credentials are missing")+ try:+ import pika++ parameters = pika.ConnectionParameters(+ host=host,+ port=port,+ virtual_host="/",+ credentials=pika.PlainCredentials(username, password),+ connection_attempts=1,+ retry_delay=0,+ socket_timeout=timeout,+ stack_timeout=timeout,+ blocked_connection_timeout=timeout,+ heartbeat=0,+ )+ connection = pika.BlockingConnection(parameters)+ connection.close()+ except Exception as exc:+ raise RuntimeError("AMQP connection failed") from exc+++def probe_redis(+ host: str,+ port: int,+ timeout: float,+ password: str,+ cluster: bool,+) -> None:+ with socket.create_connection((host, port), timeout=timeout) as connection:+ stream = connection.makefile("rwb", buffering=0)+ if password:+ _send_resp_command(stream, "AUTH", password)+ if _read_resp(stream) != "OK":+ raise RuntimeError("Redis authentication failed")+ if cluster:+ _send_resp_command(stream, "CLUSTER", "INFO")+ response = _read_resp(stream)+ if not isinstance(response, str) or "cluster_state:ok" not in response:+ raise RuntimeError("Redis cluster is not healthy")+ else:+ _send_resp_command(stream, "PING")+ if _read_resp(stream) != "PONG":+ raise RuntimeError("Redis did not return PONG")+++def _add_address_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--host", default="127.0.0.1")+ parser.add_argument("--port", type=int, required=True)+ parser.add_argument("--timeout", type=float, default=5)+++def _send_resp_command(stream: BinaryIO, *parts: str) -> None:+ stream.write(f"*{len(parts)}\r\n".encode("ascii"))+ for part in parts:+ encoded = part.encode("utf-8")+ stream.write(f"${len(encoded)}\r\n".encode("ascii"))+ stream.write(encoded + b"\r\n")+++def _read_exactly(stream: BinaryIO, count: int) -> bytes:+ chunks: list[bytes] = []+ remaining = count+ while remaining:+ chunk = stream.read(remaining)+ if not chunk:+ raise RuntimeError("Redis closed the connection")+ chunks.append(chunk)+ remaining -= len(chunk)+ return b"".join(chunks)+++def _read_resp(stream: BinaryIO) -> str | int | None:+ prefix = stream.read(1)+ if not prefix:+ raise RuntimeError("Redis closed the connection")+ line = stream.readline()+ if not line.endswith(b"\r\n"):+ raise RuntimeError("invalid Redis response")+ payload = line[:-2]+ if prefix == b"+":+ return payload.decode("utf-8")+ if prefix == b"-":+ raise RuntimeError(payload.decode("utf-8", errors="replace"))+ if prefix == b":":+ return int(payload)+ if prefix == b"$":+ length = int(payload)+ if length == -1:+ return None+ if length < -1:+ raise RuntimeError("invalid Redis bulk length")+ value = _read_exactly(stream, length)+ if _read_exactly(stream, 2) != b"\r\n":+ raise RuntimeError("invalid Redis bulk response")+ return value.decode("utf-8")+ raise RuntimeError("unsupported Redis response type")+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/autogpt_platform/single-container/promote-admin.sh b/autogpt_platform/single-container/promote-admin.shnew file mode 100755index 0000000000..39f9d4980a--- /dev/null+++ b/autogpt_platform/single-container/promote-admin.sh@@ -0,0 +1,57 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++readonly POSTGRES_BINDIR="${POSTGRES_BINDIR:-/usr/lib/postgresql/15/bin}"++main() {+ local email+ if (($# == 2)) && [[ "$1" == promote ]]; then+ email="$2"+ elif (($# == 1)); then+ # Retain the original direct-script form for compatibility.+ email="$1"+ else+ fatal "usage: autogpt-admin promote EMAIL"+ fi+ [[ "${email}" =~ ^[^[:space:]]+@[^[:space:]]+$ ]] || fatal "invalid email address"++ load_runtime_config+ wait_for_ready_file++ local updated+ updated="$(+ PGPASSWORD="${POSTGRES_PASSWORD}" \+ "${POSTGRES_BINDIR}/psql" \+ --host=127.0.0.1 \+ --port=5432 \+ --username=postgres \+ --dbname=postgres \+ --no-psqlrc \+ --tuples-only \+ --no-align \+ --set=ON_ERROR_STOP=1 \+ --set="target_email=${email}" <<'SQL'+WITH target AS (+ SELECT id+ FROM platform."UserAuthIdentity"+ WHERE lower(email) = lower(:'target_email')+), promoted AS (+ UPDATE platform."UserAuthIdentity"+ SET role = 'admin', "updatedAt" = now()+ WHERE id = (SELECT id FROM target LIMIT 1)+ AND (SELECT count(*) FROM target) = 1+ RETURNING id+)+SELECT count(*) FROM promoted;+SQL+ )"++ [[ "${updated}" == "1" ]] || fatal "no unique Better Auth user found for ${email}"+ log "promoted ${email} to administrator; sign out and back in to refresh the session role"+}++main "$@"diff --git a/autogpt_platform/single-container/python/sitecustomize.py b/autogpt_platform/single-container/python/sitecustomize.pynew file mode 100644index 0000000000..65c01c6716--- /dev/null+++ b/autogpt_platform/single-container/python/sitecustomize.py@@ -0,0 +1,29 @@+"""Logging safeguards loaded automatically by appliance Python processes."""++import logging+++class _RedactWebSocketQuery(logging.Filter):+ """Strip bearer query strings from Uvicorn WebSocket status messages."""++ def filter(self, record: logging.LogRecord) -> bool:+ if (+ record.name == "uvicorn.error"+ and isinstance(record.msg, str)+ and "WebSocket %s" in record.msg+ and isinstance(record.args, tuple)+ and len(record.args) >= 2+ and isinstance(record.args[1], str)+ ):+ args = list(record.args)+ args[1] = args[1].partition("?")[0]+ record.args = tuple(args)+ return True+++# Uvicorn's HTTP access records include the complete target, including query+# parameters. Application logs remain enabled; only automatic request logs are+# suppressed. WebSocket lifecycle messages use uvicorn.error, so retain those+# after redacting their query string.+logging.getLogger("uvicorn.access").disabled = True+logging.getLogger("uvicorn.error").addFilter(_RedactWebSocketQuery())diff --git a/autogpt_platform/single-container/rabbitmq/rabbitmq.conf b/autogpt_platform/single-container/rabbitmq/rabbitmq.confnew file mode 100644index 0000000000..c99d901f7d--- /dev/null+++ b/autogpt_platform/single-container/rabbitmq/rabbitmq.conf@@ -0,0 +1,6 @@+listeners.tcp.default = 127.0.0.1:5672+distribution.listener.interface = 127.0.0.1+loopback_users.guest = true+log.console = true+log.console.level = info+log.file = falsediff --git a/autogpt_platform/single-container/run-app.sh b/autogpt_platform/single-container/run-app.shnew file mode 100755index 0000000000..35bd6622f6--- /dev/null+++ b/autogpt_platform/single-container/run-app.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++name="${1:-application}"+shift || true+(($# > 0)) || fatal "no command supplied for ${name}"++wait_for_ready_file+log "starting ${name}"+export HOME="${AUTOGPT_HOME:-/data/home}"+export XDG_CACHE_HOME="${AUTOGPT_CACHE_DIR:-/data/cache/backend}"+exec "$@"diff --git a/autogpt_platform/single-container/run-frontend.sh b/autogpt_platform/single-container/run-frontend.shnew file mode 100755index 0000000000..710d0dd1cc--- /dev/null+++ b/autogpt_platform/single-container/run-frontend.sh@@ -0,0 +1,90 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++readonly FRONTEND_DATABASE_URL='postgresql:///postgres?host=%2Frun%2Fpostgresql&user=autogpt_frontend'++readonly -a REQUIRED_FRONTEND_ENV=(+ AGPT_SERVER_URL+ AGPT_WS_SERVER_URL+ AUTH_ALLOW_NEW_ACCOUNTS+ AUTH_DB_SCHEMA+ AUTH_REQUIRE_EMAIL_VERIFICATION+ BETTER_AUTH_INTERNAL_URL+ BETTER_AUTH_SECRET+ BETTER_AUTH_URL+)++readonly -a OPTIONAL_FRONTEND_ENV=(+ AUTH_CALLBACK_URL+ AUTH_DISCORD_CLIENT_ID+ AUTH_DISCORD_CLIENT_SECRET+ AUTH_GITHUB_CLIENT_ID+ AUTH_GITHUB_CLIENT_SECRET+ AUTH_GOOGLE_CLIENT_ID+ AUTH_GOOGLE_CLIENT_SECRET+ AUTH_SIGNUP_ALLOWLIST+ OPENAI_API_BASE_URL+ OPENAI_API_KEY+ SUPABASE_BRIDGE_MAX_TOKEN_AGE_DAYS+ SUPABASE_JWT_SECRET+ TRANSCRIPTION_API_BASE_URL+ TRANSCRIPTION_API_KEY+ TRANSCRIPTION_MODEL+)++declare -a frontend_env=()++build_frontend_environment() {+ local name+ frontend_env=(+ PATH=/usr/local/bin:/usr/bin:/bin+ HOME=/data/frontend-home+ XDG_CACHE_HOME=/data/cache/next+ USER=autogpt_frontend+ LOGNAME=autogpt_frontend+ DATABASE_URL="${FRONTEND_DATABASE_URL}"+ LANG=C.UTF-8+ LC_ALL=C.UTF-8+ NODE_ENV=production+ NEXT_TELEMETRY_DISABLED=1+ PORT=3001+ HOSTNAME=127.0.0.1+ )++ for name in "${REQUIRED_FRONTEND_ENV[@]}"; do+ [[ -n "${!name:-}" ]] || fatal "required frontend setting is missing: ${name}"+ frontend_env+=("${name}=${!name}")+ done+ for name in "${OPTIONAL_FRONTEND_ENV[@]}"; do+ if [[ -v "${name}" ]]; then+ frontend_env+=("${name}=${!name}")+ fi+ done+}++main() {+ [[ "$(id -u)" -eq 0 ]] || fatal "frontend launcher must start as root"+ build_frontend_environment++ wait_for_ready_file+ (($# > 0)) || set -- node /app/frontend/server.js+ log "starting next"+ exec /usr/bin/env -i "${frontend_env[@]}" \+ /usr/bin/setpriv \+ --reuid=autogpt_frontend \+ --regid=autogpt_frontend \+ --clear-groups \+ --nnp \+ --bounding-set=-all \+ --inh-caps=-all \+ --ambient-caps=-all \+ -- "$@"+}++if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then+ main "$@"+fidiff --git a/autogpt_platform/single-container/run-optional-app.sh b/autogpt_platform/single-container/run-optional-app.shnew file mode 100755index 0000000000..3bea350506--- /dev/null+++ b/autogpt_platform/single-container/run-optional-app.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++toggle_name="${1:-}"+name="${2:-optional application}"+shift 2 || true+(($# > 0)) || fatal "no command supplied for ${name}"++case "${!toggle_name:-}" in+ true)+ exec "${AUTOGPT_ASSET_DIR}/run-app.sh" "${name}" "$@"+ ;;+ false)+ wait_for_ready_file+ exec "${AUTOGPT_ASSET_DIR}/disabled-service.sh" "${name}"+ ;;+ *)+ fatal "${toggle_name} must be true or false"+ ;;+esacdiff --git a/autogpt_platform/single-container/run-service.sh b/autogpt_platform/single-container/run-service.shnew file mode 100755index 0000000000..1c212b2a96--- /dev/null+++ b/autogpt_platform/single-container/run-service.sh@@ -0,0 +1,29 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++service="${1:-}"++case "${service}" in+ postgres)+ postgres_bindir="${POSTGRES_BINDIR:-/usr/lib/postgresql/15/bin}"+ exec "${postgres_bindir}/postgres" -D "${PGDATA:-/data/postgres}"+ ;;+ valkey-0 | valkey-1 | valkey-2)+ index="${service##*-}"+ port="$((17000 + index))"+ exec valkey-server "${AUTOGPT_RUNTIME_DIR}/valkey/${port}.conf"+ ;;+ rabbitmq)+ exec /opt/rabbitmq/sbin/rabbitmq-server+ ;;+ falkordb)+ exec /opt/falkordb/redis-server "${AUTOGPT_RUNTIME_DIR}/falkordb.conf"+ ;;+ *)+ fatal "unknown bundled service: ${service:-<empty>}"+ ;;+esacdiff --git a/autogpt_platform/single-container/runtime_config.py b/autogpt_platform/single-container/runtime_config.pynew file mode 100755index 0000000000..93683c6d91--- /dev/null+++ b/autogpt_platform/single-container/runtime_config.py@@ -0,0 +1,301 @@+#!/usr/bin/env python3+"""Create and validate the persistent secrets used by the all-in-one image."""++from __future__ import annotations++import argparse+import base64+import binascii+import ipaddress+import os+import re+import secrets+import stat+import sys+from collections.abc import Callable, Mapping+from pathlib import Path+from urllib.parse import urlsplit, urlunsplit++CONFIG_VERSION = "1"+SAFE_SECRET = re.compile(r"^[A-Za-z0-9._~-]+={0,2}$")+SAFE_USERNAME = re.compile(r"^[A-Za-z0-9._-]+$")+SAFE_DNS_LABEL = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")+++def main() -> int:+ parser = argparse.ArgumentParser()+ subparsers = parser.add_subparsers(dest="command", required=True)++ ensure_parser = subparsers.add_parser("ensure")+ ensure_parser.add_argument("--path", type=Path, required=True)++ url_parser = subparsers.add_parser("validate-public-url")+ url_parser.add_argument("url")++ args = parser.parse_args()+ try:+ if args.command == "ensure":+ ensure_runtime_config(args.path, os.environ)+ else:+ print(validate_public_url(args.url))+ except (OSError, ValueError) as exc:+ print(f"runtime configuration error: {exc}", file=sys.stderr)+ return 2+ return 0+++def ensure_runtime_config(path: Path, environment: Mapping[str, str]) -> dict[str, str]:+ """Return the existing secrets or atomically create them on first boot."""+ if path.is_symlink():+ raise ValueError(f"refusing symlink at {path}")+ if path.exists():+ values = _read_config(path)+ _verify_environment_matches(values, environment)+ path.chmod(0o600)+ return values++ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)+ values = _new_values(environment)+ _write_config(path, values)+ return values+++def validate_public_url(value: str) -> str:+ """Validate and normalize the externally reachable origin."""+ parsed = urlsplit(value)+ if parsed.scheme not in {"http", "https"}:+ raise ValueError("AUTOGPT_PUBLIC_URL must use http or https")+ if not parsed.hostname:+ raise ValueError("AUTOGPT_PUBLIC_URL must include a host")+ if parsed.username is not None or parsed.password is not None:+ raise ValueError("AUTOGPT_PUBLIC_URL must not include credentials")+ if parsed.path not in {"", "/"} or parsed.query or parsed.fragment:+ raise ValueError(+ "AUTOGPT_PUBLIC_URL must be an origin without path, query, or fragment"+ )+ try:+ port = parsed.port+ except ValueError as exc:+ raise ValueError("AUTOGPT_PUBLIC_URL has an invalid port") from exc++ host = _normalize_public_host(parsed.hostname)+ netloc = host if port is None else f"{host}:{port}"+ return urlunsplit((parsed.scheme, netloc, "", "", ""))+++def _normalize_public_host(host: str) -> str:+ """Return a config-safe IP literal or IDNA DNS name."""+ try:+ address = ipaddress.ip_address(host)+ except ValueError:+ try:+ ascii_host = host.rstrip(".").encode("idna").decode("ascii").lower()+ except UnicodeError as exc:+ raise ValueError("AUTOGPT_PUBLIC_URL has an invalid host") from exc+ labels = ascii_host.split(".")+ if (+ not ascii_host+ or len(ascii_host) > 253+ or any(not SAFE_DNS_LABEL.fullmatch(label) for label in labels)+ ):+ raise ValueError("AUTOGPT_PUBLIC_URL has an invalid host")+ return ascii_host+ return f"[{address.compressed}]" if address.version == 6 else address.compressed+++def _new_values(environment: Mapping[str, str]) -> dict[str, str]:+ vapid_private, vapid_public = _configured_or_generated_vapid(environment)+ values = {+ "AUTOGPT_RUNTIME_CONFIG_VERSION": CONFIG_VERSION,+ "POSTGRES_PASSWORD": _configured_or_generated(+ environment, "POSTGRES_PASSWORD", lambda: secrets.token_urlsafe(36)+ ),+ "RABBITMQ_DEFAULT_USER": environment.get("RABBITMQ_DEFAULT_USER") or "autogpt",+ "RABBITMQ_DEFAULT_PASS": _configured_or_generated(+ environment, "RABBITMQ_DEFAULT_PASS", lambda: secrets.token_urlsafe(36)+ ),+ "REDIS_PASSWORD": _configured_or_generated(+ environment, "REDIS_PASSWORD", lambda: secrets.token_urlsafe(36)+ ),+ "BETTER_AUTH_SECRET": _configured_or_generated(+ environment, "BETTER_AUTH_SECRET", lambda: secrets.token_urlsafe(48)+ ),+ "ENCRYPTION_KEY": _configured_or_generated(+ environment, "ENCRYPTION_KEY", _fernet_key+ ),+ "UNSUBSCRIBE_SECRET_KEY": _configured_or_generated(+ environment, "UNSUBSCRIBE_SECRET_KEY", lambda: secrets.token_urlsafe(36)+ ),+ "GRAPHITI_FALKORDB_PASSWORD": _configured_or_generated(+ environment,+ "GRAPHITI_FALKORDB_PASSWORD",+ lambda: secrets.token_urlsafe(36),+ ),+ "VAPID_PRIVATE_KEY": vapid_private,+ "VAPID_PUBLIC_KEY": vapid_public,+ }+ _validate_values(values)+ return values+++def _configured_or_generated(+ environment: Mapping[str, str], name: str, generator: Callable[[], str]+) -> str:+ return environment.get(name) or generator()+++def _configured_or_generated_vapid(+ environment: Mapping[str, str],+) -> tuple[str, str]:+ private = environment.get("VAPID_PRIVATE_KEY")+ public = environment.get("VAPID_PUBLIC_KEY")+ if bool(private) != bool(public):+ raise ValueError("VAPID_PRIVATE_KEY and VAPID_PUBLIC_KEY must be set together")+ return (private, public) if private and public else _generate_vapid_keypair()+++def _generate_vapid_keypair() -> tuple[str, str]:+ try:+ from cryptography.hazmat.primitives.asymmetric import ec+ except ImportError as exc:+ raise ValueError("cryptography is required to generate VAPID keys") from exc++ key = ec.generate_private_key(ec.SECP256R1())+ numbers = key.private_numbers()+ private = numbers.private_value.to_bytes(32, "big")+ public_numbers = numbers.public_numbers+ public = (+ b"\x04"+ + public_numbers.x.to_bytes(32, "big")+ + public_numbers.y.to_bytes(32, "big")+ )+ return _base64url(private), _base64url(public)+++def _fernet_key() -> str:+ return base64.urlsafe_b64encode(os.urandom(32)).decode("ascii")+++def _base64url(value: bytes) -> str:+ return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")+++def _validate_values(values: dict[str, str]) -> None:+ expected = {+ "AUTOGPT_RUNTIME_CONFIG_VERSION",+ "POSTGRES_PASSWORD",+ "RABBITMQ_DEFAULT_USER",+ "RABBITMQ_DEFAULT_PASS",+ "REDIS_PASSWORD",+ "BETTER_AUTH_SECRET",+ "ENCRYPTION_KEY",+ "UNSUBSCRIBE_SECRET_KEY",+ "GRAPHITI_FALKORDB_PASSWORD",+ "VAPID_PRIVATE_KEY",+ "VAPID_PUBLIC_KEY",+ }+ if set(values) != expected:+ raise ValueError("runtime configuration has missing or unknown keys")+ if values["AUTOGPT_RUNTIME_CONFIG_VERSION"] != CONFIG_VERSION:+ raise ValueError("unsupported runtime configuration version")+ if not SAFE_USERNAME.fullmatch(values["RABBITMQ_DEFAULT_USER"]):+ raise ValueError("RABBITMQ_DEFAULT_USER contains unsupported characters")+ if values["RABBITMQ_DEFAULT_USER"] == "guest":+ raise ValueError("RABBITMQ_DEFAULT_USER may not use the built-in guest account")++ for name in expected - {"AUTOGPT_RUNTIME_CONFIG_VERSION", "RABBITMQ_DEFAULT_USER"}:+ value = values[name]+ if len(value) < 32 or not SAFE_SECRET.fullmatch(value):+ raise ValueError(f"{name} must be at least 32 URL-safe characters")++ try:+ decoded_key = base64.urlsafe_b64decode(values["ENCRYPTION_KEY"])+ except (ValueError, binascii.Error) as exc:+ raise ValueError("ENCRYPTION_KEY must be a Fernet-compatible key") from exc+ if len(decoded_key) != 32:+ raise ValueError("ENCRYPTION_KEY must decode to exactly 32 bytes")++ vapid_private = _decode_base64url(values["VAPID_PRIVATE_KEY"])+ vapid_public = _decode_base64url(values["VAPID_PUBLIC_KEY"])+ if len(vapid_private) != 32:+ raise ValueError("VAPID_PRIVATE_KEY must decode to exactly 32 bytes")+ if len(vapid_public) != 65 or vapid_public[0] != 4:+ raise ValueError("VAPID_PUBLIC_KEY must be an uncompressed P-256 public key")+++def _decode_base64url(value: str) -> bytes:+ padded = value + "=" * (-len(value) % 4)+ try:+ return base64.urlsafe_b64decode(padded)+ except (ValueError, binascii.Error) as exc:+ raise ValueError("invalid URL-safe base64 value") from exc+++def _read_config(path: Path) -> dict[str, str]:+ mode = path.stat().st_mode+ if not stat.S_ISREG(mode):+ raise ValueError(f"runtime configuration is not a regular file: {path}")++ values: dict[str, str] = {}+ for line_number, raw_line in enumerate(+ path.read_text(encoding="ascii").splitlines(), 1+ ):+ if not raw_line or raw_line.startswith("#"):+ continue+ name, separator, value = raw_line.partition("=")+ if not separator or not name or name in values:+ raise ValueError(f"invalid runtime configuration line {line_number}")+ values[name] = value+ _validate_values(values)+ return values+++def _verify_environment_matches(+ values: dict[str, str], environment: Mapping[str, str]+) -> None:+ for name, persisted in values.items():+ configured = environment.get(name)+ if configured and configured != persisted:+ raise ValueError(+ f"{name} differs from the value persisted on first boot; "+ "restore the original value or start with a new data volume"+ )+++def _write_config(path: Path, values: dict[str, str]) -> None:+ temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}.tmp")+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ descriptor = os.open(temporary, flags, 0o600)+ try:+ try:+ stream = os.fdopen(descriptor, "w", encoding="ascii")+ except BaseException:+ os.close(descriptor)+ raise+ with stream:+ os.fchmod(stream.fileno(), 0o600)+ stream.write("# Generated once by the AutoGPT all-in-one image.\n")+ for name, value in values.items():+ stream.write(f"{name}={value}\n")+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, path)+ directory_flags = os.O_RDONLY+ if hasattr(os, "O_DIRECTORY"):+ directory_flags |= os.O_DIRECTORY+ if hasattr(os, "O_CLOEXEC"):+ directory_flags |= os.O_CLOEXEC+ directory_descriptor = os.open(path.parent, directory_flags)+ try:+ os.fsync(directory_descriptor)+ finally:+ os.close(directory_descriptor)+ except BaseException:+ temporary.unlink(missing_ok=True)+ raise+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/autogpt_platform/single-container/supervisor/supervisord.conf b/autogpt_platform/single-container/supervisor/supervisord.confnew file mode 100644index 0000000000..c7a402073b--- /dev/null+++ b/autogpt_platform/single-container/supervisor/supervisord.conf@@ -0,0 +1,305 @@+[unix_http_server]+file=/run/autogpt/supervisor.sock+chmod=0700++[supervisord]+nodaemon=true+user=root+logfile=/dev/null+logfile_maxbytes=0+pidfile=/run/autogpt/supervisord.pid+childlogdir=/run/autogpt+strip_ansi=true++[rpcinterface:supervisor]+supervisor.rpcinterface_factory=supervisor.rpcinterface:make_main_rpcinterface++[supervisorctl]+serverurl=unix:///run/autogpt/supervisor.sock++[eventlistener:fatal-exit]+command=/usr/bin/env -i PATH=/usr/bin:/bin /app/autogpt_platform/backend/.venv/bin/python /opt/autogpt/single-container/fatal_listener.py+user=root+events=PROCESS_STATE_FATAL,PROCESS_STATE_EXITED+buffer_size=10+priority=1+startsecs=1+startretries=3+autorestart=true+stopasgroup=true+killasgroup=true+stderr_logfile=/dev/fd/2+stderr_logfile_maxbytes=0++[program:postgres]+command=/usr/bin/env -i PATH=/usr/lib/postgresql/15/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 PGDATA=/data/postgres /opt/autogpt/single-container/run-service.sh postgres+user=postgres+priority=10+startsecs=5+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=90+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:valkey-0]+command=/usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 /opt/autogpt/single-container/run-service.sh valkey-0+user=autogpt-valkey+priority=10+startsecs=3+autorestart=unexpected+stopasgroup=true+killasgroup=true+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:valkey-1]+command=/usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 /opt/autogpt/single-container/run-service.sh valkey-1+user=autogpt-valkey+priority=10+startsecs=3+autorestart=unexpected+stopasgroup=true+killasgroup=true+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:valkey-2]+command=/usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 /opt/autogpt/single-container/run-service.sh valkey-2+user=autogpt-valkey+priority=10+startsecs=3+autorestart=unexpected+stopasgroup=true+killasgroup=true+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:rabbitmq]+command=/usr/bin/env -i PATH=/opt/rabbitmq/sbin:/opt/erlang/bin:/opt/openssl/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin HOME=/data/rabbitmq LANG=C.UTF-8 ERLANG_INSTALL_PATH_PREFIX=/opt/erlang OPENSSL_INSTALL_PATH_PREFIX=/opt/openssl RABBITMQ_HOME=/opt/rabbitmq RABBITMQ_DATA_DIR=/data/rabbitmq RABBITMQ_MNESIA_BASE=/data/rabbitmq/mnesia RABBITMQ_NODENAME=rabbit@localhost RABBITMQ_CONFIG_FILE=/run/autogpt/rabbitmq/rabbitmq RUNNING_UNDER_SYSTEMD=true ERL_EPMD_ADDRESS=127.0.0.1 ERL_CRASH_DUMP=/data/rabbitmq/erl_crash.dump /opt/autogpt/single-container/run-service.sh rabbitmq+user=rabbitmq+priority=10+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=120+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:falkordb]+command=/usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 AUTOGPT_RUNTIME_DIR=/run/autogpt /opt/autogpt/single-container/run-service.sh falkordb+user=autogpt-falkor+priority=10+startsecs=5+autorestart=true+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0+++++[program:bootstrap]+command=/opt/autogpt/single-container/bootstrap.sh+user=root+priority=20+startsecs=0+startretries=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=30+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:database-manager]+command=/opt/autogpt/single-container/run-app.sh database-manager db+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:scheduler]+command=/opt/autogpt/single-container/run-app.sh scheduler scheduler+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:batch-executor]+command=/opt/autogpt/single-container/run-app.sh batch-executor batch-executor+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=120+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:notification]+command=/opt/autogpt/single-container/run-app.sh notification notification+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:executor]+command=/opt/autogpt/single-container/run-app.sh executor executor+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=120+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:copilot-executor]+command=/opt/autogpt/single-container/run-app.sh copilot-executor copilot-executor+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=120+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:copilot-bot]+command=/opt/autogpt/single-container/run-optional-app.sh AUTOGPT_ENABLE_BOT_SERVICES copilot-bot copilot-bot+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:platform-linking-manager]+command=/opt/autogpt/single-container/run-optional-app.sh AUTOGPT_ENABLE_BOT_SERVICES platform-linking-manager platform-linking-manager+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:websocket]+command=/opt/autogpt/single-container/run-app.sh websocket ws+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:rest]+command=/opt/autogpt/single-container/run-app.sh rest rest+directory=/app/autogpt_platform/backend+user=autogpt+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:next]+command=/opt/autogpt/single-container/run-frontend.sh+directory=/app/frontend+user=root+priority=30+startsecs=10+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=60+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:nginx]+command=/usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin AUTOGPT_HOME=/run/autogpt/nginx/home AUTOGPT_CACHE_DIR=/run/autogpt/nginx/cache AUTOGPT_RUNTIME_DIR=/run/autogpt /opt/autogpt/single-container/run-app.sh nginx nginx -c /opt/autogpt/single-container/nginx/nginx.conf -g "daemon off;"+user=autogpt_proxy+priority=40+startsecs=5+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=30+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0++[program:watchdog]+command=/opt/autogpt/single-container/watchdog.sh+user=root+priority=50+startsecs=1+startretries=3+autorestart=unexpected+stopasgroup=true+killasgroup=true+stopwaitsecs=10+redirect_stderr=true+stdout_logfile=/dev/fd/1+stdout_logfile_maxbytes=0diff --git a/autogpt_platform/single-container/tests/test_entrypoint.py b/autogpt_platform/single-container/tests/test_entrypoint.pynew file mode 100644index 0000000000..186e707cd1--- /dev/null+++ b/autogpt_platform/single-container/tests/test_entrypoint.py@@ -0,0 +1,200 @@+from __future__ import annotations++import ast+import os+import subprocess+import unittest+from pathlib import Path+++ASSET_DIR = Path(__file__).resolve().parents[1]+COMMON_PATH = ASSET_DIR / "common.sh"+ENTRYPOINT_PATH = ASSET_DIR / "entrypoint.sh"+HEALTHCHECK_PATH = ASSET_DIR / "healthcheck.sh"+RUN_SERVICE_PATH = ASSET_DIR / "run-service.sh"+DOCKERFILE_PATH = ASSET_DIR / "Dockerfile"+SUPERVISOR_PATH = ASSET_DIR / "supervisor" / "supervisord.conf"+BACKEND_SERVICE_PATH = ASSET_DIR.parent / "backend" / "backend" / "util" / "service.py"+++class InternalServiceTopologyTest(unittest.TestCase):+ def test_rpc_health_path_matches_backend(self) -> None:+ module = ast.parse(BACKEND_SERVICE_PATH.read_text(encoding="utf-8"))+ route_paths = {+ ast.literal_eval(node.args[0])+ for node in ast.walk(module)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "add_api_route"+ and node.args+ and isinstance(node.args[0], ast.Constant)+ and isinstance(node.args[0].value, str)+ }+ result = subprocess.run(+ [+ "bash",+ "-Eeuo",+ "pipefail",+ "-c",+ 'source "$1"; printf "%s" "$AUTOGPT_INTERNAL_HEALTH_PATH"',+ "bash",+ str(COMMON_PATH),+ ],+ check=False,+ capture_output=True,+ encoding="utf-8",+ env={"PATH": os.environ.get("PATH", "/usr/bin:/bin")},+ )++ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn(result.stdout, route_paths)+ self.assertIn(+ "${AUTOGPT_INTERNAL_HEALTH_PATH}",+ HEALTHCHECK_PATH.read_text(encoding="utf-8"),+ )+++class AccountRegistrationTest(unittest.TestCase):+ def test_defaults_closed_for_all_origins(self) -> None:+ for public_url in (+ "http://localhost:3000",+ "http://127.0.0.1:3000",+ "http://[::1]:3000",+ "https://autogpt.example.com",+ ):+ for allow_new_accounts in (None, ""):+ with self.subTest(+ public_url=public_url,+ allow_new_accounts=allow_new_accounts,+ ):+ result = self._configure(public_url, allow_new_accounts)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("account registration is closed", result.stdout)+ self.assertIn("autogpt-admin promote", result.stdout)+ self.assertTrue(result.stdout.endswith("false\n"))++ def test_remote_signup_requires_explicit_opt_in(self) -> None:+ result = self._configure(+ "https://autogpt.example.com", allow_new_accounts="true"+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("open account registration is enabled", result.stdout)+ self.assertTrue(result.stdout.endswith("true\n"))++ def test_explicit_false_overrides_loopback_default(self) -> None:+ result = self._configure("http://localhost:3000", allow_new_accounts="false")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("account registration is closed", result.stdout)+ self.assertTrue(result.stdout.endswith("false\n"))++ def _configure(+ self, public_url: str, allow_new_accounts: str | None = None+ ) -> subprocess.CompletedProcess[str]:+ environment = {+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),+ "AUTOGPT_ASSET_DIR": str(ASSET_DIR),+ "AUTOGPT_PUBLIC_URL": public_url,+ }+ if allow_new_accounts is not None:+ environment["AUTH_ALLOW_NEW_ACCOUNTS"] = allow_new_accounts+ return subprocess.run(+ [+ "bash",+ "-Eeuo",+ "pipefail",+ "-c",+ 'source "$1"; configure_account_registration; '+ 'printf "%s\\n" "$AUTH_ALLOW_NEW_ACCOUNTS"',+ "bash",+ str(ENTRYPOINT_PATH),+ ],+ check=False,+ capture_output=True,+ encoding="utf-8",+ env=environment,+ )+++class NormalizationTest(unittest.TestCase):+ def test_rejects_invalid_integer_values(self) -> None:+ for value, error in (+ ("not-a-number", "must be an integer"),+ ("0", "must be between 1 and 5"),+ ("6", "must be between 1 and 5"),+ ):+ with self.subTest(value=value):+ result = self._run(+ 'DB_CONNECTION_LIMIT="$2"; '+ "normalize_integer DB_CONNECTION_LIMIT 5 1 5",+ value,+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(error, result.stderr)++ def test_rejects_invalid_toggle(self) -> None:+ invalid = self._run(+ 'AUTOGPT_ENABLE_BOT_SERVICES="$2"; normalize_toggle AUTOGPT_ENABLE_BOT_SERVICES false',+ "yes",+ )+ self.assertNotEqual(invalid.returncode, 0)+ self.assertIn("must be true or false", invalid.stderr)++ def test_normalizes_named_toggle(self) -> None:+ result = self._run(+ 'CUSTOM_TOGGLE="$2"; normalize_toggle CUSTOM_TOGGLE false; '+ 'printf "%s\\n" "$CUSTOM_TOGGLE"',+ "true",+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(result.stdout, "true\n")++ def _run(self, expression: str, value: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [+ "bash",+ "-Eeuo",+ "pipefail",+ "-c",+ f'source "$1"; {expression}',+ "bash",+ str(ENTRYPOINT_PATH),+ value,+ ],+ check=False,+ capture_output=True,+ encoding="utf-8",+ env={+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),+ "AUTOGPT_ASSET_DIR": str(ASSET_DIR),+ },+ )+++class ValkeyConfigurationTest(unittest.TestCase):+ def test_password_is_kept_out_of_process_arguments(self) -> None:+ entrypoint = ENTRYPOINT_PATH.read_text(encoding="utf-8")+ service_runner = RUN_SERVICE_PATH.read_text(encoding="utf-8")++ self.assertIn("printf 'requirepass %s", entrypoint)+ self.assertIn("printf 'masterauth %s", entrypoint)+ self.assertIn("chmod 0400", entrypoint)+ self.assertNotIn("--requirepass", service_runner)+ self.assertNotIn("--masterauth", service_runner)+++class ProxyIsolationTest(unittest.TestCase):+ def test_nginx_uses_a_dedicated_operating_system_user(self) -> None:+ dockerfile = DOCKERFILE_PATH.read_text(encoding="utf-8")+ supervisor = SUPERVISOR_PATH.read_text(encoding="utf-8")+ nginx_program = supervisor.split("[program:nginx]", 1)[1].split(+ "[program:watchdog]", 1+ )[0]++ self.assertIn("--uid 10006", dockerfile)+ self.assertIn("user=autogpt_proxy", nginx_program)+ self.assertIn("AUTOGPT_HOME=/run/autogpt/nginx/home", nginx_program)+ self.assertNotIn("user=autogpt\n", nginx_program)+++if __name__ == "__main__":+ unittest.main()diff --git a/autogpt_platform/single-container/tests/test_frontend_environment.py b/autogpt_platform/single-container/tests/test_frontend_environment.pynew file mode 100644index 0000000000..603ef1b8c2--- /dev/null+++ b/autogpt_platform/single-container/tests/test_frontend_environment.py@@ -0,0 +1,194 @@+from __future__ import annotations++import json+import os+import subprocess+import tempfile+import unittest+from pathlib import Path+++SINGLE_CONTAINER_DIR = Path(__file__).resolve().parents[1]+RUN_FRONTEND_PATH = SINGLE_CONTAINER_DIR / "run-frontend.sh"+SUPERVISOR_PATH = SINGLE_CONTAINER_DIR / "supervisor" / "supervisord.conf"+BOOTSTRAP_PATH = SINGLE_CONTAINER_DIR / "bootstrap.sh"+++class FrontendEnvironmentTest(unittest.TestCase):+ def test_preserves_only_frontend_runtime_settings(self) -> None:+ required = {+ "AGPT_SERVER_URL": "http://127.0.0.1:8006/api",+ "AGPT_WS_SERVER_URL": "ws://127.0.0.1:8001/ws",+ "AUTH_ALLOW_NEW_ACCOUNTS": "false",+ "AUTH_DB_SCHEMA": "platform",+ "AUTH_REQUIRE_EMAIL_VERIFICATION": "false",+ "BETTER_AUTH_INTERNAL_URL": "http://127.0.0.1:3001",+ "BETTER_AUTH_SECRET": "better-auth-secret",+ "BETTER_AUTH_URL": "https://autogpt.example.com",+ }+ optional = {+ "AUTH_CALLBACK_URL": "/auth/callback",+ "AUTH_DISCORD_CLIENT_ID": "discord-client",+ "AUTH_DISCORD_CLIENT_SECRET": "discord-secret",+ "AUTH_GITHUB_CLIENT_ID": "github-client",+ "AUTH_GITHUB_CLIENT_SECRET": "github-secret",+ "AUTH_GOOGLE_CLIENT_ID": "google-client",+ "AUTH_GOOGLE_CLIENT_SECRET": "value with spaces",+ "AUTH_SIGNUP_ALLOWLIST": "@example.com,[email protected]",+ "OPENAI_API_BASE_URL": "https://api.openai.com/v1",+ "OPENAI_API_KEY": "openai-transcription-fallback",+ "SUPABASE_BRIDGE_MAX_TOKEN_AGE_DAYS": "30",+ "SUPABASE_JWT_SECRET": "legacy-bridge-secret",+ "TRANSCRIPTION_API_BASE_URL": "https://transcribe.example.com/v1",+ "TRANSCRIPTION_API_KEY": "transcription-secret",+ "TRANSCRIPTION_MODEL": "whisper-1",+ }+ forbidden = {+ "DATABASE_URL": "postgresql://postgres:[email protected]/postgres", # pragma: allowlist secret+ "DB_PASS": "database-password",+ "DIRECT_URL": "postgresql://superuser:[email protected]/postgres",+ "ENCRYPTION_KEY": "master-encryption-key",+ "GRAPHITI_FALKORDB_PASSWORD": "falkor-password",+ "JWT_VERIFY_KEY": "legacy-backend-secret",+ "POSTGRES_PASSWORD": "postgres-superuser-password",+ "RABBITMQ_DEFAULT_PASS": "rabbitmq-password",+ "REDIS_PASSWORD": "redis-password",+ "UNSUBSCRIBE_SECRET_KEY": "unsubscribe-secret",+ "VAPID_PRIVATE_KEY": "vapid-private-key",+ }++ with tempfile.TemporaryDirectory() as temporary_directory:+ ready_file = Path(temporary_directory) / "ready"+ ready_file.touch()+ environment = {+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),+ "AUTOGPT_ASSET_DIR": str(SINGLE_CONTAINER_DIR),+ "AUTOGPT_READY_FILE": str(ready_file),+ **required,+ **optional,+ **forbidden,+ }+ shell = (+ 'source "$1"; build_frontend_environment; '+ '/usr/bin/env -i "${frontend_env[@]}" python3 -c '+ "'import json, os; print(json.dumps(dict(os.environ)))'"+ )+ result = subprocess.run(+ [+ "bash",+ "-Eeuo",+ "pipefail",+ "-c",+ shell,+ "bash",+ str(RUN_FRONTEND_PATH),+ ],+ check=False,+ capture_output=True,+ encoding="utf-8",+ env=environment,+ )++ self.assertEqual(result.returncode, 0, result.stderr)+ child_environment = json.loads(result.stdout.splitlines()[-1])+ for name, value in {**required, **optional}.items():+ self.assertEqual(child_environment[name], value)+ self.assertEqual(+ child_environment["DATABASE_URL"],+ "postgresql:///postgres?host=%2Frun%2Fpostgresql&user=autogpt_frontend",+ )+ for name in forbidden:+ if name != "DATABASE_URL":+ self.assertNotIn(name, child_environment)+ self.assertNotEqual(+ child_environment["DATABASE_URL"], forbidden["DATABASE_URL"]+ )+ self.assertEqual(child_environment["HOME"], "/data/frontend-home")+ self.assertEqual(child_environment["XDG_CACHE_HOME"], "/data/cache/next")+ self.assertEqual(child_environment["USER"], "autogpt_frontend")+ self.assertEqual(child_environment["LOGNAME"], "autogpt_frontend")+ self.assertEqual(child_environment["PORT"], "3001")+ self.assertEqual(child_environment["HOSTNAME"], "127.0.0.1")+ self.assertEqual(child_environment["NODE_ENV"], "production")++ def test_rejects_missing_required_setting(self) -> None:+ result = subprocess.run(+ [+ "bash",+ "-Eeuo",+ "pipefail",+ "-c",+ 'source "$1"; build_frontend_environment',+ "bash",+ str(RUN_FRONTEND_PATH),+ ],+ check=False,+ capture_output=True,+ encoding="utf-8",+ env={+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),+ "AUTOGPT_ASSET_DIR": str(SINGLE_CONTAINER_DIR),+ },+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("required frontend setting is missing", result.stderr)++ def test_supervisor_uses_scrubbed_frontend_launcher(self) -> None:+ supervisor_config = SUPERVISOR_PATH.read_text(encoding="utf-8")+ next_program = supervisor_config.split("[program:next]", 1)[1].split(+ "[program:nginx]", 1+ )[0]+ self.assertIn(+ "command=/opt/autogpt/single-container/run-frontend.sh", next_program+ )+ self.assertNotIn("run-app.sh", next_program)+ self.assertIn("user=root", next_program)++ launcher = RUN_FRONTEND_PATH.read_text(encoding="utf-8")+ self.assertIn("/usr/bin/env -i", launcher)+ self.assertLess(+ launcher.index("/usr/bin/env -i"), launcher.index("/usr/bin/setpriv")+ )+ self.assertIn("--reuid=autogpt_frontend", launcher)+ self.assertIn("--regid=autogpt_frontend", launcher)+ self.assertIn("--bounding-set=-all", launcher)++ def test_frontend_database_policy_is_explicitly_least_privilege(self) -> None:+ bootstrap = BOOTSTRAP_PATH.read_text(encoding="utf-8")+ policy = bootstrap.split("configure_frontend_database_role() {", 1)[1].split(+ "publish_readiness() {", 1+ )[0]++ for attribute in (+ "NOSUPERUSER",+ "NOCREATEDB",+ "NOCREATEROLE",+ "NOINHERIT",+ "NOREPLICATION",+ "NOBYPASSRLS",+ "PASSWORD NULL",+ ):+ self.assertIn(attribute, policy)+ for table in (+ 'platform."UserAuthIdentity"',+ 'platform."UserAuthSession"',+ 'platform."UserAuthAccount"',+ 'platform."UserAuthVerification"',+ 'platform."UserAuthJwks"',+ ):+ self.assertEqual(policy.count(table), 1)+ self.assertIn('GRANT SELECT (id, email), UPDATE (email, "updatedAt")', policy)+ self.assertIn(+ "ALTER ROLE autogpt_frontend IN DATABASE postgres RESET ALL", policy+ )+ self.assertIn("REVOKE TEMPORARY ON DATABASE postgres FROM PUBLIC", policy)+ self.assertIn(+ "REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA platform", policy+ )+ self.assertIn("REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC", policy)+ self.assertNotIn("GRANT ALL", policy)+ self.assertNotIn("GRANT CREATE", policy)+++if __name__ == "__main__":+ unittest.main()diff --git a/autogpt_platform/single-container/tests/test_legacy_auth.py b/autogpt_platform/single-container/tests/test_legacy_auth.pynew file mode 100644index 0000000000..246b7ec3f0--- /dev/null+++ b/autogpt_platform/single-container/tests/test_legacy_auth.py@@ -0,0 +1,76 @@+from __future__ import annotations++import os+import subprocess+import unittest+from pathlib import Path+++COMMON_PATH = Path(__file__).resolve().parents[1] / "common.sh"+++class LegacyAuthTest(unittest.TestCase):+ def test_rejects_unsafe_legacy_auth_configurations(self) -> None:+ cases = [+ (+ {"JWT_VERIFY_KEY": "x" * 32},+ "legacy JWT secrets were supplied",+ ),+ (+ {+ "AUTOGPT_ENABLE_LEGACY_AUTH": "true",+ "JWT_VERIFY_KEY": "x" * 32,+ "SUPABASE_JWT_SECRET": "y" * 32,+ },+ "must match",+ ),+ (+ {+ "AUTOGPT_ENABLE_LEGACY_AUTH": "true",+ "JWT_VERIFY_KEY": "too-short",+ },+ "at least 32 characters",+ ),+ ]+ for environment, error in cases:+ with self.subTest(environment=environment):+ result = self._run_validation(environment)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn(error, result.stderr)++ def test_accepts_and_exports_explicit_legacy_secret(self) -> None:+ secret = "x" * 32+ result = self._run_validation(+ {+ "AUTOGPT_ENABLE_LEGACY_AUTH": "true",+ "JWT_VERIFY_KEY": secret,+ }+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertTrue(result.stdout.rstrip().endswith(f"{secret}|{secret}"))++ def _run_validation(+ self, environment: dict[str, str]+ ) -> subprocess.CompletedProcess[str]:+ clean_environment = {"PATH": os.environ.get("PATH", "/usr/bin:/bin")}+ clean_environment.update(environment)+ return subprocess.run(+ [+ "bash",+ "-Eeuo",+ "pipefail",+ "-c",+ 'source "$1"; validate_legacy_auth; '+ 'printf "%s|%s\\n" "$JWT_VERIFY_KEY" "$SUPABASE_JWT_SECRET"',+ "bash",+ str(COMMON_PATH),+ ],+ check=False,+ capture_output=True,+ encoding="utf-8",+ env=clean_environment,+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/autogpt_platform/single-container/tests/test_probe.py b/autogpt_platform/single-container/tests/test_probe.pynew file mode 100644index 0000000000..93b346796c--- /dev/null+++ b/autogpt_platform/single-container/tests/test_probe.py@@ -0,0 +1,176 @@+from __future__ import annotations++import importlib.util+import io+import sys+import types+import unittest+from pathlib import Path+from unittest import mock++MODULE_PATH = Path(__file__).parents[1] / "probe.py"+SPEC = importlib.util.spec_from_file_location("single_container_probe", MODULE_PATH)+assert SPEC is not None and SPEC.loader is not None+probe = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(probe)+++class ChunkedStream(io.BytesIO):+ def read(self, size: int = -1) -> bytes:+ return super().read(min(size, 1) if size >= 0 else 1)+++class DuplexStream:+ def __init__(self, response: bytes) -> None:+ self.reader = io.BytesIO(response)+ self.written = io.BytesIO()++ def read(self, size: int = -1) -> bytes:+ return self.reader.read(size)++ def readline(self, size: int = -1) -> bytes:+ return self.reader.readline(size)++ def write(self, value: bytes) -> int:+ return self.written.write(value)+++class FakeConnection:+ def __init__(self, response: bytes) -> None:+ self.stream = DuplexStream(response)+ self.response = response+ self.sent = b""++ def __enter__(self) -> FakeConnection:+ return self++ def __exit__(self, *_args: object) -> None:+ return None++ def makefile(self, _mode: str, buffering: int) -> DuplexStream:+ del buffering+ return self.stream++ def sendall(self, value: bytes) -> None:+ self.sent = value++ def recv(self, size: int) -> bytes:+ return self.response[:size]+++class RespTest(unittest.TestCase):+ def test_reads_fragmented_bulk_response(self) -> None:+ self.assertEqual(probe._read_resp(ChunkedStream(b"$5\r\nhello\r\n")), "hello")++ def test_rejects_truncated_bulk_response(self) -> None:+ with self.assertRaisesRegex(RuntimeError, "closed the connection"):+ probe._read_resp(ChunkedStream(b"$5\r\nhel"))++ def test_parses_supported_response_types(self) -> None:+ cases = [+ (b"+PONG\r\n", "PONG"),+ (b":42\r\n", 42),+ (b"$-1\r\n", None),+ ]+ for response, expected in cases:+ with self.subTest(response=response):+ self.assertEqual(probe._read_resp(io.BytesIO(response)), expected)++ def test_rejects_error_response(self) -> None:+ with self.assertRaisesRegex(RuntimeError, "NOAUTH"):+ probe._read_resp(io.BytesIO(b"-NOAUTH authentication required\r\n"))++ def test_rejects_invalid_negative_bulk_length(self) -> None:+ with self.assertRaisesRegex(RuntimeError, "invalid Redis bulk length"):+ probe._read_resp(io.BytesIO(b"$-2\r\n"))++ def test_encodes_resp_command(self) -> None:+ stream = io.BytesIO()+ probe._send_resp_command(stream, "AUTH", "secret")+ self.assertEqual(stream.getvalue(), b"*2\r\n$4\r\nAUTH\r\n$6\r\nsecret\r\n")+++class ServiceProbeTest(unittest.TestCase):+ def test_http_rejects_error_status(self) -> None:+ for status in (302, 503):+ with self.subTest(status=status):+ response = mock.MagicMock()+ response.status = status+ response.__enter__.return_value = response+ with (+ mock.patch.object(+ probe.urllib.request, "urlopen", return_value=response+ ),+ self.assertRaisesRegex(RuntimeError, f"HTTP {status}"),+ ):+ probe.probe_http("http://127.0.0.1/health", 1)++ def test_http_many_checks_every_url(self) -> None:+ urls = ["http://127.0.0.1/one", "http://127.0.0.1/two"]+ with mock.patch.object(probe, "probe_http") as probe_http:+ probe.probe_http_many(urls, 1)+ probe_http.assert_has_calls(+ [mock.call(urls[0], 1), mock.call(urls[1], 1)], any_order=True+ )++ def test_amqp_connects_with_runtime_credentials(self) -> None:+ connection = mock.Mock()+ pika = types.SimpleNamespace(+ PlainCredentials=mock.Mock(return_value="credentials"),+ ConnectionParameters=mock.Mock(return_value="parameters"),+ BlockingConnection=mock.Mock(return_value=connection),+ )+ with mock.patch.dict(sys.modules, {"pika": pika}):+ probe.probe_amqp("127.0.0.1", 5672, 1, "autogpt", "secret")+ pika.PlainCredentials.assert_called_once_with("autogpt", "secret")+ pika.BlockingConnection.assert_called_once_with("parameters")+ connection.close.assert_called_once_with()++ def test_redis_rejects_failed_authentication(self) -> None:+ connection = FakeConnection(b"+NOPE\r\n")+ with (+ mock.patch.object(+ probe.socket, "create_connection", return_value=connection+ ),+ self.assertRaisesRegex(RuntimeError, "authentication failed"),+ ):+ probe.probe_redis("127.0.0.1", 6380, 1, "secret", False)++ def test_redis_rejects_unhealthy_cluster(self) -> None:+ connection = FakeConnection(b"$18\r\ncluster_state:fail\r\n")+ with (+ mock.patch.object(+ probe.socket, "create_connection", return_value=connection+ ),+ self.assertRaisesRegex(RuntimeError, "cluster is not healthy"),+ ):+ probe.probe_redis("127.0.0.1", 17000, 1, "", True)++ def test_redis_rejects_wrong_ping_response(self) -> None:+ connection = FakeConnection(b"+NOPE\r\n")+ with (+ mock.patch.object(+ probe.socket, "create_connection", return_value=connection+ ),+ self.assertRaisesRegex(RuntimeError, "did not return PONG"),+ ):+ probe.probe_redis("127.0.0.1", 17000, 1, "", False)++ def test_redis_accepts_pong(self) -> None:+ connection = FakeConnection(b"+PONG\r\n")+ with mock.patch.object(+ probe.socket, "create_connection", return_value=connection+ ):+ probe.probe_redis("127.0.0.1", 17000, 1, "", False)++ def test_redis_accepts_healthy_cluster(self) -> None:+ connection = FakeConnection(b"$16\r\ncluster_state:ok\r\n")+ with mock.patch.object(+ probe.socket, "create_connection", return_value=connection+ ):+ probe.probe_redis("127.0.0.1", 17000, 1, "", True)++++if __name__ == "__main__":+ unittest.main()diff --git a/autogpt_platform/single-container/tests/test_promote_admin.py b/autogpt_platform/single-container/tests/test_promote_admin.pynew file mode 100644index 0000000000..5d5fe6d2f6--- /dev/null+++ b/autogpt_platform/single-container/tests/test_promote_admin.py@@ -0,0 +1,130 @@+from __future__ import annotations++import os+import subprocess+import tempfile+import unittest+from dataclasses import dataclass+from pathlib import Path+++SINGLE_CONTAINER_DIR = Path(__file__).resolve().parents[1]+PROMOTE_ADMIN_PATH = SINGLE_CONTAINER_DIR / "promote-admin.sh"+++@dataclass+class Invocation:+ result: subprocess.CompletedProcess[str]+ arguments: list[str]+ sql: str+ password: str+++class PromoteAdminTest(unittest.TestCase):+ def test_rejects_invalid_arguments_and_email(self) -> None:+ cases = [+ ((), "usage: autogpt-admin promote EMAIL"),+ (("promote",), "invalid email address"),+ (("delete", "[email protected]"), "usage: autogpt-admin promote EMAIL"),+ (("promote", "not-an-email"), "invalid email address"),+ ]+ for arguments, error in cases:+ with self.subTest(arguments=arguments):+ invocation = self._run_script(arguments)+ self.assertNotEqual(invocation.result.returncode, 0)+ self.assertIn(error, invocation.result.stderr)+ self.assertEqual(invocation.arguments, [])++ def test_promotes_exactly_one_user_with_parameterized_email(self) -> None:+ email = "o'[email protected]"+ invocation = self._run_script(("promote", email), psql_result="1")++ self.assertEqual(invocation.result.returncode, 0, invocation.result.stderr)+ self.assertIn(f"promoted {email} to administrator", invocation.result.stdout)+ self.assertIn(f"--set=target_email={email}", invocation.arguments)+ self.assertIn("lower(:'target_email')", invocation.sql)+ self.assertNotIn(email, invocation.sql)+ self.assertEqual(invocation.password, "test-postgres-password")++ def test_rejects_non_unique_user(self) -> None:+ email = "[email protected]"+ invocation = self._run_script(("promote", email), psql_result="0")++ self.assertNotEqual(invocation.result.returncode, 0)+ self.assertIn("AND (SELECT count(*) FROM target) = 1", invocation.sql)+ self.assertIn(+ f"no unique Better Auth user found for {email}",+ invocation.result.stderr,+ )++ def _run_script(+ self, arguments: tuple[str, ...], psql_result: str = "1"+ ) -> Invocation:+ with tempfile.TemporaryDirectory() as temporary_directory:+ root = Path(temporary_directory)+ runtime_dir = root / "runtime"+ runtime_dir.mkdir()+ ready_file = runtime_dir / "ready"+ ready_file.touch()+ runtime_config = root / "runtime.env"+ runtime_config.write_text(+ "POSTGRES_PASSWORD=test-postgres-password\n",+ encoding="utf-8",+ )++ postgres_bindir = root / "postgres" / "bin"+ postgres_bindir.mkdir(parents=True)+ fake_psql = postgres_bindir / "psql"+ fake_psql.write_text(+ """#!/usr/bin/env bash+set -Eeuo pipefail+printf '%s\\n' "$@" >"${FAKE_PSQL_ARGS_FILE}"+cat >"${FAKE_PSQL_SQL_FILE}"+printf '%s' "${PGPASSWORD:-}" >"${FAKE_PSQL_PASSWORD_FILE}"+printf '%s\\n' "${FAKE_PSQL_RESULT}"+""",+ encoding="utf-8",+ )+ fake_psql.chmod(0o755)++ args_file = root / "psql.args"+ sql_file = root / "psql.sql"+ password_file = root / "psql.password"+ environment = {+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),+ "AUTOGPT_ASSET_DIR": str(SINGLE_CONTAINER_DIR),+ "AUTOGPT_RUNTIME_DIR": str(runtime_dir),+ "AUTOGPT_READY_FILE": str(ready_file),+ "AUTOGPT_RUNTIME_ENV": str(runtime_config),+ "POSTGRES_BINDIR": str(postgres_bindir),+ "FAKE_PSQL_ARGS_FILE": str(args_file),+ "FAKE_PSQL_SQL_FILE": str(sql_file),+ "FAKE_PSQL_PASSWORD_FILE": str(password_file),+ "FAKE_PSQL_RESULT": psql_result,+ }+ result = subprocess.run(+ ["bash", str(PROMOTE_ADMIN_PATH), *arguments],+ check=False,+ capture_output=True,+ encoding="utf-8",+ env=environment,+ )++ return Invocation(+ result=result,+ arguments=(+ args_file.read_text(encoding="utf-8").splitlines()+ if args_file.exists()+ else []+ ),+ sql=(sql_file.read_text(encoding="utf-8") if sql_file.exists() else ""),+ password=(+ password_file.read_text(encoding="utf-8")+ if password_file.exists()+ else ""+ ),+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/autogpt_platform/single-container/tests/test_runtime_config.py b/autogpt_platform/single-container/tests/test_runtime_config.pynew file mode 100644index 0000000000..4738be2d75--- /dev/null+++ b/autogpt_platform/single-container/tests/test_runtime_config.py@@ -0,0 +1,417 @@+from __future__ import annotations++import base64+import importlib.util+import io+import re+import stat+import tempfile+import unittest+from pathlib import Path+from unittest import mock++MODULE_PATH = Path(__file__).parents[1] / "runtime_config.py"+COMMON_PATH = Path(__file__).parents[1] / "common.sh"+SPEC = importlib.util.spec_from_file_location(+ "single_container_runtime_config", MODULE_PATH+)+assert SPEC is not None and SPEC.loader is not None+runtime_config = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(runtime_config)++LISTENER_PATH = Path(__file__).parents[1] / "fatal_listener.py"+LISTENER_SPEC = importlib.util.spec_from_file_location(+ "single_container_fatal_listener", LISTENER_PATH+)+assert LISTENER_SPEC is not None and LISTENER_SPEC.loader is not None+fatal_listener = importlib.util.module_from_spec(LISTENER_SPEC)+LISTENER_SPEC.loader.exec_module(fatal_listener)+++class RuntimeConfigTest(unittest.TestCase):+ def test_shell_loader_allowlist_matches_generated_runtime_keys(self) -> None:+ common = COMMON_PATH.read_text(encoding="utf-8")+ match = re.search(+ r'case "\$\{name\}" in\s+(?P<keys>[A-Z0-9_ |]+)\)\s+'+ r'export "\$\{name\}=\$\{value\}"',+ common,+ )+ self.assertIsNotNone(match)+ assert match is not None+ shell_keys = {name.strip() for name in match.group("keys").split("|")}+ with tempfile.TemporaryDirectory() as directory:+ generated_keys = set(+ runtime_config.ensure_runtime_config(+ Path(directory) / "runtime.env", {}+ )+ )++ self.assertEqual(shell_keys, generated_keys)++ def test_first_boot_generates_complete_private_config_and_reuses_it(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "runtime.env"++ first = runtime_config.ensure_runtime_config(path, {})+ second = runtime_config.ensure_runtime_config(path, {})++ self.assertEqual(first, second)+ self.assertEqual(+ set(first),+ {+ "AUTOGPT_RUNTIME_CONFIG_VERSION",+ "POSTGRES_PASSWORD",+ "RABBITMQ_DEFAULT_USER",+ "RABBITMQ_DEFAULT_PASS",+ "REDIS_PASSWORD",+ "BETTER_AUTH_SECRET",+ "ENCRYPTION_KEY",+ "UNSUBSCRIBE_SECRET_KEY",+ "GRAPHITI_FALKORDB_PASSWORD",+ "VAPID_PRIVATE_KEY",+ "VAPID_PUBLIC_KEY",+ },+ )+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)++ def test_first_boot_honors_explicit_values(self) -> None:+ vapid_private = base64.urlsafe_b64encode(b"p" * 32).rstrip(b"=").decode()+ vapid_public = (+ base64.urlsafe_b64encode(b"\x04" + b"q" * 64).rstrip(b"=").decode()+ )+ environment = {+ "POSTGRES_PASSWORD": "p" * 40,+ "RABBITMQ_DEFAULT_USER": "self_hosted",+ "RABBITMQ_DEFAULT_PASS": "r" * 40,+ "REDIS_PASSWORD": "d" * 40,+ "BETTER_AUTH_SECRET": "b" * 40,+ "ENCRYPTION_KEY": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",+ "UNSUBSCRIBE_SECRET_KEY": "u" * 40,+ "GRAPHITI_FALKORDB_PASSWORD": "f" * 40,+ "VAPID_PRIVATE_KEY": vapid_private,+ "VAPID_PUBLIC_KEY": vapid_public,+ }+ with tempfile.TemporaryDirectory() as directory:+ values = runtime_config.ensure_runtime_config(+ Path(directory) / "runtime.env", environment+ )++ for name, value in environment.items():+ self.assertEqual(values[name], value)++ def test_first_boot_fsyncs_file_and_parent_directory(self) -> None:+ real_fsync = runtime_config.os.fsync+ events: list[tuple[str, bool] | tuple[str]] = []++ def record_fsync(descriptor: int) -> None:+ events.append(+ ("fsync", stat.S_ISDIR(runtime_config.os.fstat(descriptor).st_mode))+ )+ real_fsync(descriptor)++ def record_replace(source: Path, destination: Path) -> None:+ events.append(("replace",))+ runtime_config.os.rename(source, destination)++ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "runtime.env"+ with (+ mock.patch.object(runtime_config.os, "fsync", side_effect=record_fsync),+ mock.patch.object(+ runtime_config.os, "replace", side_effect=record_replace+ ),+ ):+ runtime_config.ensure_runtime_config(path, {})++ self.assertIn(("fsync", False), events)+ self.assertIn(("fsync", True), events)+ self.assertLess(events.index(("fsync", False)), events.index(("replace",)))+ self.assertLess(events.index(("replace",)), events.index(("fsync", True)))++ def test_first_boot_closes_descriptor_when_fdopen_fails(self) -> None:+ real_close = runtime_config.os.close+ closed_descriptors: list[int] = []++ def record_close(descriptor: int) -> None:+ closed_descriptors.append(descriptor)+ real_close(descriptor)++ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "runtime.env"+ with (+ mock.patch.object(+ runtime_config.os, "fdopen", side_effect=MemoryError("test")+ ),+ mock.patch.object(runtime_config.os, "close", side_effect=record_close),+ self.assertRaisesRegex(MemoryError, "test"),+ ):+ runtime_config.ensure_runtime_config(path, {})++ self.assertEqual(len(closed_descriptors), 1)+ self.assertFalse(path.exists())+ self.assertEqual(list(Path(directory).iterdir()), [])++ def test_existing_config_rejects_secret_rotation_by_environment(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "runtime.env"+ values = runtime_config.ensure_runtime_config(path, {})+ environment = {"POSTGRES_PASSWORD": values["POSTGRES_PASSWORD"] + "x"}++ with self.assertRaisesRegex(ValueError, "persisted on first boot"):+ runtime_config.ensure_runtime_config(path, environment)++ def test_rejects_symlink_target(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ target = Path(directory) / "target"+ target.write_text("not a config", encoding="ascii")+ link = Path(directory) / "runtime.env"+ link.symlink_to(target)++ with self.assertRaisesRegex(ValueError, "refusing symlink"):+ runtime_config.ensure_runtime_config(link, {})++ def test_rejects_unsafe_explicit_secret(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ with self.assertRaisesRegex(ValueError, "POSTGRES_PASSWORD"):+ runtime_config.ensure_runtime_config(+ Path(directory) / "runtime.env",+ {"POSTGRES_PASSWORD": "contains whitespace and shell syntax $(id)"},+ )++ def test_rejects_builtin_rabbitmq_guest_user(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ with self.assertRaisesRegex(ValueError, "built-in guest"):+ runtime_config.ensure_runtime_config(+ Path(directory) / "runtime.env",+ {"RABBITMQ_DEFAULT_USER": "guest"},+ )++ def test_rejects_one_sided_vapid_configuration(self) -> None:+ cases = [+ {"VAPID_PRIVATE_KEY": "p" * 43},+ {"VAPID_PUBLIC_KEY": "q" * 87},+ ]+ for environment in cases:+ with (+ self.subTest(environment=environment),+ tempfile.TemporaryDirectory() as directory,+ self.assertRaisesRegex(ValueError, "must be set together"),+ ):+ runtime_config.ensure_runtime_config(+ Path(directory) / "runtime.env", environment+ )++ def test_rejects_corrupt_existing_config(self) -> None:+ invalid_vapid_public = (+ base64.urlsafe_b64encode(b"\x03" + b"q" * 64).rstrip(b"=").decode()+ )+ cases = [+ (+ "duplicate key",+ lambda content: content + "POSTGRES_PASSWORD=duplicate\n",+ "invalid runtime configuration line",+ ),+ (+ "malformed line",+ lambda content: content + "malformed\n",+ "invalid runtime configuration line",+ ),+ (+ "unsupported version",+ lambda content: content.replace(+ "AUTOGPT_RUNTIME_CONFIG_VERSION=1",+ "AUTOGPT_RUNTIME_CONFIG_VERSION=2",+ ),+ "unsupported runtime configuration version",+ ),+ (+ "invalid encryption key",+ lambda content: _replace_config_value(+ content, "ENCRYPTION_KEY", "A" * 32+ ),+ "ENCRYPTION_KEY",+ ),+ (+ "invalid VAPID public key",+ lambda content: _replace_config_value(+ content, "VAPID_PUBLIC_KEY", invalid_vapid_public+ ),+ "VAPID_PUBLIC_KEY",+ ),+ ]+ for name, mutate, error in cases:+ with self.subTest(name=name), tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "runtime.env"+ runtime_config.ensure_runtime_config(path, {})+ path.write_text(+ mutate(path.read_text(encoding="ascii")), encoding="ascii"+ )+ with self.assertRaisesRegex(ValueError, error):+ runtime_config.ensure_runtime_config(path, {})++ def test_rejects_non_regular_existing_config(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "runtime.env"+ path.mkdir()+ with self.assertRaisesRegex(ValueError, "not a regular file"):+ runtime_config.ensure_runtime_config(path, {})+++class PublicUrlTest(unittest.TestCase):+ def test_normalizes_origin(self) -> None:+ self.assertEqual(+ runtime_config.validate_public_url("https://Example.COM:8443/"),+ "https://example.com:8443",+ )++ def test_normalizes_idna_hostname(self) -> None:+ self.assertEqual(+ runtime_config.validate_public_url("https://BÜCHER.example/"),+ "https://xn--bcher-kva.example",+ )++ def test_accepts_ipv6_origin(self) -> None:+ self.assertEqual(+ runtime_config.validate_public_url("http://[::1]:3000"),+ "http://[::1]:3000",+ )++ def test_rejects_non_origin_values(self) -> None:+ invalid = [+ "ftp://example.com",+ "https://example.com/path",+ "https://example.com?token=secret",+ "https://user:[email protected]",+ "http:///missing-host",+ "http://bad_host.example",+ "http://bad$variable.example",+ "http://example..com",+ "http://example.com:99999",+ ]+ for value in invalid:+ with self.subTest(value=value), self.assertRaises(ValueError):+ runtime_config.validate_public_url(value)+++class FatalListenerTest(unittest.TestCase):+ def test_fatal_event_acknowledges_before_terminating_supervisor(self) -> None:+ payload = "processname:rest groupname:rest from_state:BACKOFF"+ header = f"eventname:PROCESS_STATE_FATAL len:{len(payload)}\n"+ input_stream = io.StringIO(payload)+ output_stream = io.StringIO()+ calls: list[str] = []++ with mock.patch.object(fatal_listener.sys, "stderr", io.StringIO()):+ fatal_listener.handle_event(+ header,+ input_stream,+ output_stream,+ lambda: calls.append(output_stream.getvalue()),+ )++ self.assertEqual(output_stream.getvalue(), "RESULT 2\nOK")+ self.assertEqual(calls, ["RESULT 2\nOK"])++ def test_fatal_event_does_not_echo_untrusted_payload(self) -> None:+ payload = "processname:rest\nsecret-value groupname:rest"+ header = f"eventname:PROCESS_STATE_FATAL len:{len(payload)}\n"+ with mock.patch.object(fatal_listener.sys, "stderr", io.StringIO()) as stderr:+ fatal_listener.handle_event(+ header,+ io.StringIO(payload),+ io.StringIO(),+ lambda: None,+ )++ self.assertNotIn("secret-value", stderr.getvalue())+ self.assertIn("unknown", stderr.getvalue())++ def test_unexpected_bootstrap_exit_terminates_supervisor(self) -> None:+ payload = "processname:bootstrap groupname:bootstrap expected:0"+ output_stream = io.StringIO()+ calls: list[str] = []++ with mock.patch.object(fatal_listener.sys, "stderr", io.StringIO()):+ fatal_listener.handle_event(+ f"eventname:PROCESS_STATE_EXITED len:{len(payload)}\n",+ io.StringIO(payload),+ output_stream,+ lambda: calls.append("terminated"),+ )++ self.assertEqual(output_stream.getvalue(), "RESULT 2\nOK")+ self.assertEqual(calls, ["terminated"])++ def test_expected_bootstrap_exit_is_ignored(self) -> None:+ self._assert_exit_ignored("processname:bootstrap expected:1")++ def test_other_process_exit_is_ignored(self) -> None:+ self._assert_exit_ignored("processname:rest expected:0")++ def test_supervisor_subscribes_to_exited_events(self) -> None:+ config = (+ Path(__file__).parents[1] / "supervisor" / "supervisord.conf"+ ).read_text(encoding="utf-8")+ self.assertIn("events=PROCESS_STATE_FATAL,PROCESS_STATE_EXITED", config)++ def test_rejects_malformed_events_without_terminating(self) -> None:+ cases = [+ ("eventname:PROCESS_STATE_FATAL\n", "", "invalid payload length"),+ (+ "eventname:PROCESS_STATE_FATAL len:not-a-number\n",+ "",+ "invalid payload length",+ ),+ (+ "eventname:PROCESS_STATE_FATAL "+ f"len:{fatal_listener.MAX_PAYLOAD_LENGTH + 1}\n",+ "",+ "payload is too large",+ ),+ (+ "eventname:PROCESS_STATE_FATAL len:5\n",+ "abc",+ "ended unexpectedly",+ ),+ ("eventname:TICK_5_SECONDS len:0\n", "", "unsupported type"),+ ]+ for header, payload, error in cases:+ terminate = mock.Mock()+ with (+ self.subTest(header=header),+ self.assertRaisesRegex(RuntimeError, error),+ ):+ fatal_listener.handle_event(+ header,+ io.StringIO(payload),+ io.StringIO(),+ terminate,+ )+ terminate.assert_not_called()++ def _assert_exit_ignored(self, payload: str) -> None:+ output_stream = io.StringIO()+ calls: list[str] = []++ fatal_listener.handle_event(+ f"eventname:PROCESS_STATE_EXITED len:{len(payload)}\n",+ io.StringIO(payload),+ output_stream,+ lambda: calls.append("terminated"),+ )++ self.assertEqual(output_stream.getvalue(), "RESULT 2\nOK")+ self.assertEqual(calls, [])+++def _replace_config_value(content: str, name: str, value: str) -> str:+ prefix = f"{name}="+ lines = [+ f"{prefix}{value}" if line.startswith(prefix) else line+ for line in content.splitlines()+ ]+ return "\n".join(lines) + "\n"+++if __name__ == "__main__":+ unittest.main()diff --git a/autogpt_platform/single-container/tests/test_sitecustomize.py b/autogpt_platform/single-container/tests/test_sitecustomize.pynew file mode 100644index 0000000000..432a51c754--- /dev/null+++ b/autogpt_platform/single-container/tests/test_sitecustomize.py@@ -0,0 +1,94 @@+import importlib.util+import logging+import unittest+from pathlib import Path+++MODULE_PATH = Path(__file__).resolve().parents[1] / "python" / "sitecustomize.py"+SPEC = importlib.util.spec_from_file_location(+ "single_container_sitecustomize", MODULE_PATH+)+assert SPEC is not None and SPEC.loader is not None+sitecustomize = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(sitecustomize)+++class SiteCustomizeTest(unittest.TestCase):+ def test_disables_uvicorn_http_access_logger(self) -> None:+ self.assertTrue(logging.getLogger("uvicorn.access").disabled)++ def test_redacts_websocket_query_string(self) -> None:+ record = logging.LogRecord(+ name="uvicorn.error",+ level=logging.INFO,+ pathname=__file__,+ lineno=1,+ msg='%s - "WebSocket %s" [accepted]',+ args=(("127.0.0.1", 1234), "/ws?token=do-not-log&other=value"),+ exc_info=None,+ )++ for log_filter in logging.getLogger("uvicorn.error").filters:+ log_filter.filter(record)++ rendered = record.getMessage()+ self.assertIn('"WebSocket /ws"', rendered)+ self.assertNotIn("do-not-log", rendered)+ self.assertNotIn("other=value", rendered)++ def test_leaves_websocket_target_without_query_unchanged(self) -> None:+ record = self._record(+ name="uvicorn.error",+ msg='%s - "WebSocket %s" [accepted]',+ args=(("127.0.0.1", 1234), "/ws"),+ )++ self._apply_filters(record)++ self.assertEqual(record.args[1], "/ws")++ def test_malformed_records_are_safe_no_ops(self) -> None:+ cases = (+ self._record(+ name="application",+ msg='%s - "WebSocket %s" [accepted]',+ args=(("127.0.0.1", 1234), "/ws?token=secret"),+ ),+ self._record(name="uvicorn.error", msg=123, args=()),+ self._record(name="uvicorn.error", msg="WebSocket %s", args=("/ws",)),+ self._record(+ name="uvicorn.error",+ msg='%(client)s - "WebSocket %(path)s" [accepted]',+ args={"client": "local", "path": "/ws?token=secret"},+ ),+ )+ original_args = [record.args for record in cases]++ for record in cases:+ with self.subTest(name=record.name, msg=record.msg, args=record.args):+ self.assertTrue(self._apply_filters(record))++ self.assertEqual([record.args for record in cases], original_args)++ def _apply_filters(self, record: logging.LogRecord) -> bool:+ return all(+ log_filter.filter(record)+ for log_filter in logging.getLogger("uvicorn.error").filters+ )++ def _record(+ self,+ *,+ name: str,+ msg: object,+ args: tuple[object, ...] | dict[str, object],+ ) -> logging.LogRecord:+ return logging.LogRecord(+ name=name,+ level=logging.INFO,+ pathname=__file__,+ lineno=1,+ msg=msg,+ args=args,+ exc_info=None,+ )diff --git a/autogpt_platform/single-container/watchdog.sh b/autogpt_platform/single-container/watchdog.shnew file mode 100644index 0000000000..1f21afb57a--- /dev/null+++ b/autogpt_platform/single-container/watchdog.sh@@ -0,0 +1,72 @@+#!/usr/bin/env bash++set -Eeuo pipefail++# shellcheck source=common.sh+source "${AUTOGPT_ASSET_DIR:-/opt/autogpt/single-container}/common.sh"++readonly SUPERVISOR_PID_FILE="${AUTOGPT_RUNTIME_DIR}/supervisord.pid"+readonly WATCHDOG_ARMED_FILE="${AUTOGPT_RUNTIME_DIR}/watchdog-armed"+readonly FAILURE_LIMIT=3+readonly CHECK_INTERVAL=30+readonly CHECK_TIMEOUT=60+readonly INITIAL_HEALTH_TIMEOUT=600++main() {+ local failures=0+ local output+ rm -f "${WATCHDOG_ARMED_FILE}"+ output="$(mktemp "${AUTOGPT_RUNTIME_DIR}/watchdog-health.XXXXXX")"+ trap 'rm -f "${output}" "${WATCHDOG_ARMED_FILE}"' EXIT++ wait_for_ready_file+ wait_for_initial_health "${output}"+ while true; do+ sleep "${CHECK_INTERVAL}"+ if run_healthcheck "${output}"; then+ failures=0+ continue+ fi++ ((failures += 1))+ log "watchdog health failure ${failures}/${FAILURE_LIMIT}" >&2+ sed -n '1,120p' "${output}" >&2+ if ((failures >= FAILURE_LIMIT)); then+ stop_appliance \+ "watchdog stopping the unhealthy appliance; a Docker restart policy is required to restart it automatically"+ fi+ done+}++run_healthcheck() {+ local output="$1"+ timeout --signal=TERM --kill-after=5s "${CHECK_TIMEOUT}" \+ /usr/local/bin/autogpt-healthcheck >"${output}" 2>&1+}++wait_for_initial_health() {+ local output="$1"+ local deadline=$((SECONDS + INITIAL_HEALTH_TIMEOUT))+ while ((SECONDS < deadline)); do+ if run_healthcheck "${output}"; then+ install -m 0600 /dev/null "${WATCHDOG_ARMED_FILE}"+ log "watchdog armed after initial healthy state; automatic fatal recovery requires a Docker restart policy"+ return 0+ fi+ log "watchdog waiting for initial healthy state" >&2+ sed -n '1,120p' "${output}" >&2+ sleep "${CHECK_INTERVAL}"+ done+ stop_appliance \+ "watchdog did not observe a healthy appliance within ${INITIAL_HEALTH_TIMEOUT}s"+}++stop_appliance() {+ local reason="$1"+ [[ -s "${SUPERVISOR_PID_FILE}" ]] || fatal "supervisor PID file is missing"+ log "${reason}" >&2+ kill -TERM "$(<"${SUPERVISOR_PID_FILE}")"+ exit 0+}++main "$@"