Skip to content

Agent Zero AI framework

Update system prototype

frdel94edfeaf8d0f
diff --git a/api/self_update_get.py b/api/self_update_get.py
new file mode 100644
index 000000000..fed66c844
--- /dev/null
+++ b/api/self_update_get.py
@@ -0,0 +1,27 @@
+from helpers.api import ApiHandler, Request, Response
+
+from helpers import runtime
+from helpers import self_update
+
+
+class SelfUpdateGet(ApiHandler):
+ @classmethod
+ def get_methods(cls) -> list[str]:
+ return ["GET", "POST"]
+
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ try:
+ info = self_update.get_update_info()
+ return {
+ "success": True,
+ "supported": runtime.is_dockerized(),
+ **info,
+ }
+ except Exception as e:
+ return {
+ "success": False,
+ "supported": runtime.is_dockerized(),
+ "error": str(e),
+ "pending": self_update.load_pending_update(),
+ "last_status": self_update.load_last_status(),
+ }
diff --git a/api/self_update_schedule.py b/api/self_update_schedule.py
new file mode 100644
index 000000000..395b852ff
--- /dev/null
+++ b/api/self_update_schedule.py
@@ -0,0 +1,35 @@
+from helpers.api import ApiHandler, Request, Response
+
+from helpers import runtime
+from helpers import self_update
+
+
+class SelfUpdateSchedule(ApiHandler):
+ async def process(self, input: dict, request: Request) -> dict | Response:
+ if not runtime.is_dockerized():
+ return {
+ "success": False,
+ "error": "Self-update is only available in dockerized installations.",
+ }
+
+ try:
+ pending = self_update.schedule_update(
+ branch=str(input.get("branch", "")),
+ tag=str(input.get("tag", "")),
+ backup_usr=bool(input.get("backup_usr", True)),
+ backup_path=str(input.get("backup_path", "")),
+ backup_name=str(input.get("backup_name", "")),
+ backup_conflict_policy=str(input.get("backup_conflict_policy", "rename")),
+ )
+ return {
+ "success": True,
+ "pending": pending,
+ "message": (
+ "Self-update was scheduled. Restart Agent Zero to apply the requested branch/tag."
+ ),
+ }
+ except Exception as e:
+ return {
+ "success": False,
+ "error": str(e),
+ }
diff --git a/docker/run/fs/exe/run_A0.sh b/docker/run/fs/exe/run_A0.sh
index 5c4124490..350020d7b 100644
--- a/docker/run/fs/exe/run_A0.sh
+++ b/docker/run/fs/exe/run_A0.sh
@@ -3,11 +3,5 @@
. "/ins/setup_venv.sh" "$@"
. "/ins/copy_A0.sh" "$@"
-python /a0/prepare.py --dockerized=true
-# python /a0/preload.py --dockerized=true # no need to run preload if it's done during container build
-
-echo "Starting A0..."
-exec python /a0/run_ui.py \
- --dockerized=true \
- --port=80 \
- --host="0.0.0.0"
+echo "Starting A0 bootstrap manager..."
+exec python /exe/self_update_manager.py docker-run-ui
diff --git a/docker/run/fs/exe/self_update_manager.py b/docker/run/fs/exe/self_update_manager.py
new file mode 100644
index 000000000..c24a25a4d
--- /dev/null
+++ b/docker/run/fs/exe/self_update_manager.py
@@ -0,0 +1,723 @@
+#!/usr/bin/env python3
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.request
+import zipfile
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+import yaml
+
+
+OFFICIAL_REPO_URL = os.environ.get(
+ "A0_SELF_UPDATE_REMOTE_URL",
+ "https://github.com/agent0ai/agent-zero.git",
+)
+REPO_DIR = Path("/a0")
+TRIGGER_FILE = Path("/exe/a0-self-update.yaml")
+STATUS_FILE = Path("/exe/a0-self-update-status.yaml")
+LOG_FILE = Path("/exe/a0-self-update.log")
+DEFAULT_HEALTH_URL = os.environ.get(
+ "A0_SELF_UPDATE_HEALTH_URL",
+ "http://127.0.0.1:80/api/health",
+)
+DEFAULT_HEALTH_TIMEOUT_SECONDS = int(
+ os.environ.get("A0_SELF_UPDATE_HEALTH_TIMEOUT_SECONDS", "120")
+)
+DEFAULT_HEALTH_POLL_INTERVAL_SECONDS = float(
+ os.environ.get("A0_SELF_UPDATE_HEALTH_POLL_INTERVAL_SECONDS", "2")
+)
+
+
+def now_iso() -> str:
+ return datetime.now(UTC).isoformat().replace("+00:00", "Z")
+
+
+class AttemptLogger:
+ def __init__(self, path: Path):
+ self.path = path
+
+ def reset(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ self.path.write_text("", encoding="utf-8")
+
+ def log(self, message: str = "") -> None:
+ line = f"[{now_iso()}] {message}".rstrip()
+ print(f"[a0-self-update] {message}", flush=True)
+ with self.path.open("a", encoding="utf-8") as handle:
+ handle.write(line + "\n")
+
+ def log_block(self, title: str, content: str) -> None:
+ cleaned = content.rstrip()
+ self.log(f"{title}:")
+ if not cleaned:
+ self.log("(empty)")
+ return
+ with self.path.open("a", encoding="utf-8") as handle:
+ for line in cleaned.splitlines():
+ handle.write(f" {line}\n")
+
+
+class NullLogger:
+ def reset(self) -> None:
+ return
+
+ def log(self, message: str = "") -> None:
+ return
+
+ def log_block(self, title: str, content: str) -> None:
+ return
+
+
+def load_yaml(path: Path) -> dict[str, Any] | None:
+ if not path.exists():
+ return None
+ loaded = yaml.safe_load(path.read_text(encoding="utf-8"))
+ return loaded if isinstance(loaded, dict) else None
+
+
+def write_yaml(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ yaml.safe_dump(payload, allow_unicode=True, sort_keys=False),
+ encoding="utf-8",
+ )
+
+
+def write_status(payload: dict[str, Any]) -> None:
+ write_yaml(STATUS_FILE, payload)
+
+
+def git_output(repo_dir: Path, *args: str) -> str:
+ completed = subprocess.run(
+ ["git", "-C", str(repo_dir), *args],
+ check=True,
+ text=True,
+ capture_output=True,
+ env={**os.environ, "GIT_TERMINAL_PROMPT": "0"},
+ )
+ return completed.stdout.strip()
+
+
+def normalize_describe_to_version(describe: str) -> str:
+ match = re.fullmatch(r"(.+)-\d+-g[0-9a-f]+", describe)
+ if match:
+ return match.group(1)
+ return describe
+
+
+def get_repo_version_info(repo_dir: Path) -> dict[str, str]:
+ describe = git_output(repo_dir, "describe", "--tags", "--always")
+ commit = git_output(repo_dir, "rev-parse", "HEAD")
+ return {
+ "describe": describe,
+ "short_tag": normalize_describe_to_version(describe),
+ "commit": commit,
+ "short_commit": commit[:7],
+ }
+
+
+def normalize_rel_path(value: str | Path) -> str:
+ normalized = str(value).replace("\\", "/").strip("/")
+ if normalized in {"", "."}:
+ return ""
+ while normalized.startswith("./"):
+ normalized = normalized[2:]
+ while "//" in normalized:
+ normalized = normalized.replace("//", "/")
+ return normalized.rstrip("/")
+
+
+def is_protected_path(relative_path: str, protected_paths: set[str]) -> bool:
+ normalized = normalize_rel_path(relative_path)
+ if not normalized:
+ return False
+ return any(
+ normalized == protected or normalized.startswith(f"{protected}/")
+ for protected in protected_paths
+ )
+
+
+def list_protected_paths(repo_dir: Path) -> set[str]:
+ output = git_output(
+ repo_dir,
+ "ls-files",
+ "--others",
+ "-i",
+ "--exclude-standard",
+ "--directory",
+ )
+ protected: set[str] = set()
+ for raw_line in output.splitlines():
+ normalized = normalize_rel_path(raw_line)
+ if not normalized:
+ continue
+ current = Path(normalized)
+ while True:
+ candidate = normalize_rel_path(current.as_posix())
+ if candidate:
+ protected.add(candidate)
+ if str(current.parent) in {"", "."}:
+ break
+ current = current.parent
+ return protected
+
+
+def remove_path(path: Path) -> None:
+ if path.is_symlink() or path.is_file():
+ path.unlink(missing_ok=True)
+ return
+ if path.exists():
+ shutil.rmtree(path)
+
+
+def sync_tree(source_dir: Path, target_dir: Path, *, protected_paths: set[str]) -> None:
+ target_dir.mkdir(parents=True, exist_ok=True)
+ protected = {normalize_rel_path(path) for path in protected_paths if path}
+
+ def _sync(src: Path, dst: Path, relative_root: str) -> None:
+ source_entries = {item.name: item for item in src.iterdir()} if src.exists() else {}
+ target_entries = {item.name: item for item in dst.iterdir()} if dst.exists() else {}
+
+ for name, src_entry in source_entries.items():
+ relative_path = normalize_rel_path(Path(relative_root, name).as_posix())
+ if is_protected_path(relative_path, protected):
+ continue
+
+ dst_entry = dst / name
+ if src_entry.is_symlink():
+ link_target = os.readlink(src_entry)
+ if dst_entry.is_symlink() and os.readlink(dst_entry) == link_target:
+ continue
+ remove_path(dst_entry)
+ os.symlink(link_target, dst_entry)
+ continue
+
+ if src_entry.is_dir():
+ if dst_entry.exists() and not dst_entry.is_dir():
+ remove_path(dst_entry)
+ dst_entry.mkdir(parents=True, exist_ok=True)
+ _sync(src_entry, dst_entry, relative_path)
+ try:
+ shutil.copystat(src_entry, dst_entry, follow_symlinks=False)
+ except OSError:
+ pass
+ continue
+
+ if dst_entry.exists() and dst_entry.is_dir():
+ remove_path(dst_entry)
+ dst_entry.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(src_entry, dst_entry, follow_symlinks=False)
+
+ for name, dst_entry in target_entries.items():
+ relative_path = normalize_rel_path(Path(relative_root, name).as_posix())
+ if name in source_entries:
+ continue
+ if is_protected_path(relative_path, protected):
+ continue
+ remove_path(dst_entry)
+
+ _sync(source_dir, target_dir, "")
+
+
+def sanitize_filename(name: str, default_name: str) -> str:
+ raw = (name or "").strip()
+ if not raw:
+ raw = default_name
+ raw = Path(raw).name
+ raw = re.sub(r"[^A-Za-z0-9._-]+", "-", raw).strip(".-") or default_name
+ if not raw.lower().endswith(".zip"):
+ raw = f"{raw}.zip"
+ return raw
+
+
+def resolve_backup_destination(
+ directory: Path,
+ filename: str,
+ conflict_policy: str,
+) -> Path:
+ normalized_policy = conflict_policy.strip().lower()
+ directory.mkdir(parents=True, exist_ok=True)
+ destination = directory / filename
+ if not destination.exists():
+ return destination
+
+ if normalized_policy == "overwrite":
+ remove_path(destination)
+ return destination
+ if normalized_policy == "fail":
+ raise FileExistsError(f"Backup file already exists: {destination}")
+ if normalized_policy != "rename":
+ raise ValueError("backup_conflict_policy must be rename, overwrite, or fail.")
+
+ stem = destination.stem
+ suffix = destination.suffix
+ index = 2
+ while True:
+ candidate = directory / f"{stem}-{index}{suffix}"
+ if not candidate.exists():
+ return candidate
+ index += 1
+
+
+def create_usr_backup(
+ *,
+ repo_dir: Path,
+ backup_path: str,
+ backup_name: str,
+ conflict_policy: str,
+ logger: AttemptLogger,
+) -> Path:
+ usr_dir = repo_dir / "usr"
+ if not usr_dir.exists():
+ raise FileNotFoundError(f"User directory not found: {usr_dir}")
+
+ destination_dir = Path(backup_path)
+ if not destination_dir.is_absolute():
+ destination_dir = (repo_dir / destination_dir).resolve()
+ else:
+ destination_dir = destination_dir.resolve()
+ destination_name = sanitize_filename(backup_name, "agent-zero-usr-backup.zip")
+ destination = resolve_backup_destination(destination_dir, destination_name, conflict_policy)
+
+ temp_fd, temp_path = tempfile.mkstemp(suffix=".zip")
+ os.close(temp_fd)
+ temporary_backup = Path(temp_path)
+
+ try:
+ with zipfile.ZipFile(
+ temporary_backup,
+ "w",
+ compression=zipfile.ZIP_DEFLATED,
+ compresslevel=6,
+ ) as archive:
+ for root, _, files in os.walk(usr_dir):
+ root_path = Path(root)
+ for filename in files:
+ source_file = root_path / filename
+ archive_name = Path("usr") / source_file.relative_to(usr_dir)
+ archive.write(source_file, archive_name.as_posix())
+
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(temporary_backup), str(destination))
+ logger.log(f"Created usr backup at {destination}")
+ return destination
+ finally:
+ if temporary_backup.exists():
+ temporary_backup.unlink(missing_ok=True)
+
+
+def run_command(command: list[str], *, cwd: Path | None, logger: AttemptLogger) -> None:
+ logger.log(f"$ {' '.join(command)}")
+ completed = subprocess.run(
+ command,
+ cwd=cwd,
+ text=True,
+ capture_output=True,
+ env={**os.environ, "GIT_TERMINAL_PROMPT": "0"},
+ )
+ if completed.stdout:
+ logger.log_block("stdout", completed.stdout)
+ if completed.stderr:
+ logger.log_block("stderr", completed.stderr)
+ if completed.returncode != 0:
+ raise RuntimeError(
+ f"Command failed with exit code {completed.returncode}: {' '.join(command)}"
+ )
+
+
+def clone_release(branch: str, tag: str, destination: Path, logger: AttemptLogger) -> None:
+ logger.log(f"Fetching branch {branch} and tag {tag} from {OFFICIAL_REPO_URL}")
+ run_command(
+ [
+ "git",
+ "clone",
+ "--depth",
+ "1",
+ "--branch",
+ branch,
+ "--single-branch",
+ OFFICIAL_REPO_URL,
+ str(destination),
+ ],
+ cwd=None,
+ logger=logger,
+ )
+ run_command(
+ [
+ "git",
+ "-C",
+ str(destination),
+ "fetch",
+ "--depth",
+ "1",
+ "origin",
+ f"refs/tags/{tag}:refs/tags/{tag}",
+ ],
+ cwd=None,
+ logger=logger,
+ )
+ run_command(
+ [
+ "git",
+ "-C",
+ str(destination),
+ "checkout",
+ "--detach",
+ f"refs/tags/{tag}",
+ ],
+ cwd=None,
+ logger=logger,
+ )
+
+
+def launch_ui_process(repo_dir: Path, logger: AttemptLogger) -> subprocess.Popen[bytes]:
+ prepare_script = repo_dir / "prepare.py"
+ if prepare_script.exists():
+ logger.log("Running prepare.py before UI start")
+ run_command([sys.executable, str(prepare_script), "--dockerized=true"], cwd=repo_dir, logger=logger)
+ else:
+ logger.log("prepare.py not found, skipping prepare step")
+
+ logger.log("Starting Agent Zero UI")
+ return subprocess.Popen(
+ [
+ sys.executable,
+ str(repo_dir / "run_ui.py"),
+ "--dockerized=true",
+ "--port=80",
+ "--host=0.0.0.0",
+ ],
+ cwd=repo_dir,
+ )
+
+
+def wait_for_health(
+ process: subprocess.Popen[bytes],
+ *,
+ health_url: str,
+ timeout_seconds: int,
+ poll_interval_seconds: float,
+ expected_version: str | None = None,
+ logger: AttemptLogger,
+) -> tuple[bool, dict[str, Any] | str]:
+ deadline = time.monotonic() + timeout_seconds
+ last_error = "Health check did not return a successful response."
+
+ while time.monotonic() < deadline:
+ if process.poll() is not None:
+ return (
+ False,
+ f"UI process exited with code {process.returncode} before passing the health check.",
+ )
+ try:
+ request = urllib.request.Request(
+ health_url,
+ headers={"Cache-Control": "no-cache"},
+ method="GET",
+ )
+ with urllib.request.urlopen(request, timeout=5) as response:
+ body = response.read().decode("utf-8")
+ payload = json.loads(body) if body else {}
+ git_info = payload.get("gitinfo") or {}
+ current_version = (git_info.get("short_tag") or "").strip()
+ if expected_version and current_version and current_version != expected_version:
+ last_error = (
+ f"Health check responded, but version {current_version} does not match "
+ f"expected {expected_version}."
+ )
+ elif response.status == 200:
+ logger.log(f"Health check passed at {health_url}")
+ return True, payload
+ except (urllib.error.URLError, TimeoutError, ValueError, json.JSONDecodeError) as exc:
+ last_error = str(exc)
+
+ time.sleep(poll_interval_seconds)
+
+ return False, last_error
+
+
+def terminate_process(process: subprocess.Popen[bytes], timeout_seconds: int = 20) -> None:
+ if process.poll() is not None:
+ return
+ process.terminate()
+ try:
+ process.wait(timeout=timeout_seconds)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+
+
+def wait_for_process(process: subprocess.Popen[bytes]) -> int:
+ def forward_signal(signum, _frame) -> None:
+ if process.poll() is None:
+ process.send_signal(signum)
+
+ for sig in (signal.SIGTERM, signal.SIGINT):
+ try:
+ signal.signal(sig, forward_signal)
+ except ValueError:
+ pass
+
+ return process.wait()
+
+
+def record_result(
+ *,
+ status: str,
+ message: str,
+ request_data: dict[str, Any],
+ source_info: dict[str, str],
+ current_version: str,
+ started_at: str,
+ backup_zip_path: str = "",
+ rollback_applied: bool = False,
+ error: str = "",
+) -> None:
+ payload: dict[str, Any] = {
+ "status": status,
+ "message": message,
+ "branch": str(request_data.get("branch", "")),
+ "tag": str(request_data.get("tag", "")),
+ "source_version": source_info["short_tag"],
+ "source_commit": source_info["commit"],
+ "current_version": current_version,
+ "requested_at": str(request_data.get("requested_at", "")),
+ "started_at": started_at,
+ "finished_at": now_iso(),
+ "log_file_path": str(LOG_FILE),
+ "update_file_path": str(TRIGGER_FILE),
+ "rollback_applied": rollback_applied,
+ }
+ if backup_zip_path:
+ payload["backup_zip_path"] = backup_zip_path
+ if error:
+ payload["error"] = error
+ write_status(payload)
+
+
+def execute_pending_update(
+ request_data: dict[str, Any],
+ *,
+ logger: AttemptLogger,
+) -> subprocess.Popen[bytes]:
+ source_info = get_repo_version_info(REPO_DIR)
+ started_at = now_iso()
+ protected_paths = list_protected_paths(REPO_DIR)
+ temp_root = Path(tempfile.mkdtemp(prefix="a0-self-update-"))
+ staging_repo = temp_root / "release"
+ snapshot_dir = temp_root / "snapshot"
+ backup_zip_path = ""
+ repository_changed = False
+ branch = str(request_data.get("branch", "")).strip()
+ tag = str(request_data.get("tag", "")).strip()
+
+ try:
+ if not branch:
+ raise ValueError("Update file is missing the branch field.")
+ if not tag:
+ raise ValueError("Update file is missing the tag field.")
+
+ if bool(request_data.get("backup_usr", True)):
+ backup_zip_path = str(
+ create_usr_backup(
+ repo_dir=REPO_DIR,
+ backup_path=str(request_data.get("backup_path", "/a0/tmp/self-update-backups")),
+ backup_name=str(request_data.get("backup_name", "agent-zero-usr-backup.zip")),
+ conflict_policy=str(request_data.get("backup_conflict_policy", "rename")),
+ logger=logger,
+ )
+ )
+
+ logger.log("Creating rollback snapshot")
+ sync_tree(REPO_DIR, snapshot_dir, protected_paths=protected_paths)
+
+ clone_release(branch, tag, staging_repo, logger)
+
+ logger.log("Applying release into /a0 while preserving ignored paths")
+ sync_tree(staging_repo, REPO_DIR, protected_paths=protected_paths)
+ repository_changed = True
+
+ current_info = get_repo_version_info(REPO_DIR)
+ if current_info["short_tag"] != tag:
+ raise RuntimeError(
+ "Release sync completed but the repository version does not match the requested tag. "
+ f"Expected {tag}, got {current_info['short_tag']}."
+ )
+
+ updated_process = launch_ui_process(REPO_DIR, logger)
+ healthy, details = wait_for_health(
+ updated_process,
+ health_url=DEFAULT_HEALTH_URL,
+ timeout_seconds=DEFAULT_HEALTH_TIMEOUT_SECONDS,
+ poll_interval_seconds=DEFAULT_HEALTH_POLL_INTERVAL_SECONDS,
+ expected_version=tag,
+ logger=logger,
+ )
+ if healthy:
+ record_result(
+ status="success",
+ message=f"Updated Agent Zero to branch {branch}, tag {tag}.",
+ request_data=request_data,
+ source_info=source_info,
+ current_version=current_info["short_tag"],
+ started_at=started_at,
+ backup_zip_path=backup_zip_path,
+ rollback_applied=False,
+ )
+ return updated_process
+
+ logger.log(f"Updated UI failed health check, rolling back: {details}")
+ terminate_process(updated_process)
+ sync_tree(snapshot_dir, REPO_DIR, protected_paths=protected_paths)
+
+ rollback_process = launch_ui_process(REPO_DIR, logger)
+ rollback_healthy, rollback_details = wait_for_health(
+ rollback_process,
+ health_url=DEFAULT_HEALTH_URL,
+ timeout_seconds=DEFAULT_HEALTH_TIMEOUT_SECONDS,
+ poll_interval_seconds=DEFAULT_HEALTH_POLL_INTERVAL_SECONDS,
+ expected_version=source_info["short_tag"],
+ logger=logger,
+ )
+
+ if rollback_healthy:
+ record_result(
+ status="rolled_back",
+ message=(
+ "Updated version failed its health check and the previous version was restored. "
+ f"Reason: {details}"
+ ),
+ request_data=request_data,
+ source_info=source_info,
+ current_version=source_info["short_tag"],
+ started_at=started_at,
+ backup_zip_path=backup_zip_path,
+ rollback_applied=True,
+ error=str(details),
+ )
+ return rollback_process
+
+ terminate_process(rollback_process)
+ record_result(
+ status="rollback_failed",
+ message=(
+ "Updated version failed its health check and rollback also failed to become healthy."
+ ),
+ request_data=request_data,
+ source_info=source_info,
+ current_version=source_info["short_tag"],
+ started_at=started_at,
+ backup_zip_path=backup_zip_path,
+ rollback_applied=True,
+ error=f"Update error: {details}. Rollback error: {rollback_details}",
+ )
+ raise RuntimeError(str(rollback_details))
+ except Exception as exc:
+ if repository_changed and snapshot_dir.exists():
+ logger.log(f"Restoring rollback snapshot after error: {exc}")
+ sync_tree(snapshot_dir, REPO_DIR, protected_paths=protected_paths)
+
+ record_result(
+ status="failed" if not repository_changed else "rolled_back",
+ message=str(exc),
+ request_data=request_data,
+ source_info=source_info,
+ current_version=source_info["short_tag"],
+ started_at=started_at,
+ backup_zip_path=backup_zip_path,
+ rollback_applied=repository_changed,
+ error=str(exc),
+ )
+ logger.log(f"Update flow failed: {exc}")
+ return launch_ui_process(REPO_DIR, logger)
+ finally:
+ shutil.rmtree(temp_root, ignore_errors=True)
+
+
+def load_request_file() -> tuple[dict[str, Any] | None, str]:
+ if not TRIGGER_FILE.exists():
+ return None, ""
+ raw_text = TRIGGER_FILE.read_text(encoding="utf-8")
+ try:
+ loaded = yaml.safe_load(raw_text)
+ return (loaded if isinstance(loaded, dict) else None), raw_text
+ finally:
+ TRIGGER_FILE.unlink(missing_ok=True)
+
+
+def docker_run_ui() -> int:
+ request_data, raw_text = load_request_file()
+ logger = AttemptLogger(LOG_FILE)
+ quiet_logger = NullLogger()
+
+ if request_data:
+ logger.reset()
+ logger.log(f"Consumed update file at {TRIGGER_FILE}")
+ logger.log_block("Trigger file content", raw_text)
+
+ try:
+ current = get_repo_version_info(REPO_DIR)
+ requested_tag = str(request_data.get("tag", "")).strip()
+ if requested_tag and current["short_tag"] == requested_tag:
+ logger.log(
+ "Requested tag already matches the installed version, skipping file replacement."
+ )
+ record_result(
+ status="skipped",
+ message="Requested tag already matches the installed version.",
+ request_data=request_data,
+ source_info=current,
+ current_version=current["short_tag"],
+ started_at=now_iso(),
+ rollback_applied=False,
+ )
+ process = launch_ui_process(REPO_DIR, logger)
+ else:
+ process = execute_pending_update(request_data, logger=logger)
+ except Exception as exc:
+ logger.log(f"Self-update bootstrap failed unexpectedly: {exc}")
+ process = launch_ui_process(REPO_DIR, logger)
+ elif raw_text:
+ logger.reset()
+ logger.log(f"Consumed invalid update file at {TRIGGER_FILE}")
+ logger.log_block("Trigger file content", raw_text)
+ source_info = get_repo_version_info(REPO_DIR)
+ record_result(
+ status="failed",
+ message="Update file was not valid YAML.",
+ request_data={},
+ source_info=source_info,
+ current_version=source_info["short_tag"],
+ started_at=now_iso(),
+ rollback_applied=False,
+ error="Update file was not valid YAML.",
+ )
+ process = launch_ui_process(REPO_DIR, logger)
+ else:
+ process = launch_ui_process(REPO_DIR, quiet_logger)
+
+ return wait_for_process(process)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = list(argv if argv is not None else sys.argv[1:])
+ if args and args[0] not in {"docker-run-ui"}:
+ print(f"Unknown command: {args[0]}", file=sys.stderr)
+ return 1
+ return docker_run_ui()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/helpers/self_update.py b/helpers/self_update.py
new file mode 100644
index 000000000..332bb0d74
--- /dev/null
+++ b/helpers/self_update.py
@@ -0,0 +1,266 @@
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Literal, TypedDict
+
+from helpers import git, yaml
+
+
+OFFICIAL_REPO_AUTHOR = "agent0ai"
+OFFICIAL_REPO_NAME = "agent-zero"
+BRANCH_OPTIONS = [
+ {"value": "main", "label": "main"},
+ {"value": "testing", "label": "testing"},
+ {"value": "development", "label": "development"},
+]
+BACKUP_CONFLICT_POLICIES = {"rename", "overwrite", "fail"}
+
+UPDATE_FILE_PATH = Path("/exe/a0-self-update.yaml")
+STATUS_FILE_PATH = Path("/exe/a0-self-update-status.yaml")
+LOG_FILE_PATH = Path("/exe/a0-self-update.log")
+
+
+class PendingUpdateConfig(TypedDict):
+ branch: Literal["main", "testing", "development"]
+ tag: str
+ source_version: str
+ source_describe: str
+ source_commit: str
+ requested_at: str
+ backup_usr: bool
+ backup_path: str
+ backup_name: str
+ backup_conflict_policy: Literal["rename", "overwrite", "fail"]
+
+
+class UpdateStatus(TypedDict, total=False):
+ status: str
+ message: str
+ branch: str
+ tag: str
+ source_version: str
+ source_commit: str
+ current_version: str
+ requested_at: str
+ started_at: str
+ finished_at: str
+ backup_zip_path: str
+ log_file_path: str
+ update_file_path: str
+ rollback_applied: bool
+ error: str
+
+
+def _now_iso() -> str:
+ return datetime.now(UTC).isoformat().replace("+00:00", "Z")
+
+
+def get_update_file_path() -> Path:
+ return UPDATE_FILE_PATH
+
+
+def get_status_file_path() -> Path:
+ return STATUS_FILE_PATH
+
+
+def get_log_file_path() -> Path:
+ return LOG_FILE_PATH
+
+
+def _load_yaml(path: Path) -> dict[str, Any] | None:
+ if not path.exists():
+ return None
+ loaded = yaml.loads(path.read_text(encoding="utf-8"))
+ return loaded if isinstance(loaded, dict) else None
+
+
+def _write_yaml(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(yaml.dumps(payload), encoding="utf-8")
+
+
+def load_pending_update() -> PendingUpdateConfig | None:
+ loaded = _load_yaml(get_update_file_path())
+ return loaded if loaded is not None else None
+
+
+def load_last_status() -> UpdateStatus | None:
+ loaded = _load_yaml(get_status_file_path())
+ return loaded if loaded is not None else None
+
+
+def get_log_text() -> str:
+ path = get_log_file_path()
+ if not path.exists():
+ return ""
+ return path.read_text(encoding="utf-8")
+
+
+def get_default_backup_dir(repo_dir: str | Path | None = None) -> Path:
+ repository = get_repo_dir(repo_dir)
+ return repository / "tmp" / "self-update-backups"
+
+
+def get_repo_dir(repo_dir: str | Path | None = None) -> Path:
+ if repo_dir is not None:
+ return Path(repo_dir).resolve()
+ return Path(__file__).resolve().parents[1]
+
+
+def _run_git(repo_dir: str | Path, *args: str) -> str:
+ completed = subprocess.run(
+ ["git", "-C", str(get_repo_dir(repo_dir)), *args],
+ check=True,
+ text=True,
+ capture_output=True,
+ env={**os.environ, "GIT_TERMINAL_PROMPT": "0"},
+ )
+ return completed.stdout.strip()
+
+
+def _normalize_describe_to_version(describe: str) -> str:
+ match = re.fullmatch(r"(.+)-\d+-g[0-9a-f]+", describe)
+ if match:
+ return match.group(1)
+ return describe
+
+
+def get_repo_version_info(repo_dir: str | Path | None = None) -> dict[str, str]:
+ repository = get_repo_dir(repo_dir)
+ describe = _run_git(repository, "describe", "--tags", "--always")
+ commit = _run_git(repository, "rev-parse", "HEAD")
+ return {
+ "describe": describe,
+ "short_tag": _normalize_describe_to_version(describe),
+ "commit": commit,
+ "short_commit": commit[:7],
+ }
+
+
+def _sanitize_filename(name: str, default_name: str) -> str:
+ raw = (name or "").strip()
+ if not raw:
+ raw = default_name
+ raw = Path(raw).name
+ raw = re.sub(r"[^A-Za-z0-9._-]+", "-", raw).strip(".-") or default_name
+ if not raw.lower().endswith(".zip"):
+ raw = f"{raw}.zip"
+ return raw
+
+
+def _slugify_version(text: str) -> str:
+ cleaned = re.sub(r"[^A-Za-z0-9._-]+", "-", text.strip()).strip("-")
+ return cleaned or "unknown"
+
+
+def build_default_backup_name(
+ current_version: str,
+ target_tag: str | None = None,
+) -> str:
+ timestamp = datetime.now(UTC).strftime("%Y%m%d-%H%M%S")
+ current_slug = _slugify_version(current_version)
+ target_slug = _slugify_version(target_tag or current_version)
+ return f"agent-zero-usr-{current_slug}-to-{target_slug}-{timestamp}.zip"
+
+
+def _resolve_backup_path(
+ backup_path: str,
+ repo_dir: str | Path | None = None,
+) -> Path:
+ raw = (backup_path or "").strip()
+ if not raw:
+ return get_default_backup_dir(repo_dir)
+ path = Path(raw)
+ if not path.is_absolute():
+ path = get_repo_dir(repo_dir) / path
+ return path.resolve()
+
+
+def get_available_tags() -> tuple[list[str], str]:
+ result = git.get_remote_releases(OFFICIAL_REPO_AUTHOR, OFFICIAL_REPO_NAME)
+ if result.error:
+ return [], result.error
+ return [release.tag for release in result.releases], ""
+
+
+def get_update_info(repo_dir: str | Path | None = None) -> dict[str, Any]:
+ repository = get_repo_dir(repo_dir)
+ version_info = get_repo_version_info(repository)
+ current_version = version_info["short_tag"]
+ tags, tags_error = get_available_tags()
+ return {
+ "repo_dir": str(repository),
+ "current": version_info,
+ "pending": load_pending_update(),
+ "last_status": load_last_status(),
+ "branches": BRANCH_OPTIONS,
+ "available_tags": tags,
+ "available_tags_error": tags_error,
+ "paths": {
+ "update_file": str(get_update_file_path()),
+ "status_file": str(get_status_file_path()),
+ "log_file": str(get_log_file_path()),
+ },
+ "defaults": {
+ "branch": "main",
+ "tag": current_version,
+ "backup_usr": True,
+ "backup_path": str(get_default_backup_dir(repository)),
+ "backup_name": build_default_backup_name(current_version, current_version),
+ "backup_conflict_policy": "rename",
+ },
+ }
+
+
+def schedule_update(
+ *,
+ branch: str,
+ tag: str,
+ backup_usr: bool,
+ backup_path: str,
+ backup_name: str,
+ backup_conflict_policy: str,
+ repo_dir: str | Path | None = None,
+) -> PendingUpdateConfig:
+ repository = get_repo_dir(repo_dir)
+ version_info = get_repo_version_info(repository)
+
+ normalized_branch = branch.strip().lower()
+ if normalized_branch not in {option["value"] for option in BRANCH_OPTIONS}:
+ raise ValueError("Branch must be one of: main, testing, development.")
+
+ normalized_tag = tag.strip()
+ if not normalized_tag:
+ raise ValueError("A release tag is required.")
+
+ normalized_policy = backup_conflict_policy.strip().lower()
+ if normalized_policy not in BACKUP_CONFLICT_POLICIES:
+ raise ValueError(
+ "Backup conflict policy must be one of: rename, overwrite, fail."
+ )
+
+ resolved_backup_path = _resolve_backup_path(backup_path, repository)
+ resolved_backup_name = _sanitize_filename(
+ backup_name,
+ build_default_backup_name(version_info["short_tag"], normalized_tag),
+ )
+
+ payload: PendingUpdateConfig = {
+ "branch": normalized_branch, # type: ignore[assignment]
+ "tag": normalized_tag,
+ "source_version": version_info["short_tag"],
+ "source_describe": version_info["describe"],
+ "source_commit": version_info["commit"],
+ "requested_at": _now_iso(),
+ "backup_usr": bool(backup_usr),
+ "backup_path": str(resolved_backup_path),
+ "backup_name": resolved_backup_name,
+ "backup_conflict_policy": normalized_policy, # type: ignore[assignment]
+ }
+
+ _write_yaml(get_update_file_path(), payload)
+ return payload
diff --git a/webui/components/settings/external/self-update-modal.html b/webui/components/settings/external/self-update-modal.html
new file mode 100644
index 000000000..932181fcd
--- /dev/null
+++ b/webui/components/settings/external/self-update-modal.html
@@ -0,0 +1,351 @@
+<html>
+ <head>
+ <title>Self Update</title>
+ <script type="module">
+ import { store } from "/components/settings/external/self-update-store.js";
+ </script>
+ </head>
+
+ <body>
+ <div x-data>
+ <template x-if="$store.selfUpdateStore">
+ <div
+ x-init="$store.selfUpdateStore.init()"
+ x-destroy="$store.selfUpdateStore.cleanup()"
+ class="self-update-modal"
+ >
+ <div class="self-update-copy">
+ <p>
+ Agent Zero saves this request into
+ <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>,
+ restarts once, applies the requested branch and release tag before the UI
+ starts again, then reloads this page when <code>/api/health</code> is healthy.
+ </p>
+ <p>
+ If the updated UI does not become healthy within 2 minutes, the bootstrap
+ manager in <code>/exe</code> restores the previous checkout and starts that
+ version again, so even an older downgraded <code>/a0</code> can be upgraded back
+ by creating the YAML file manually.
+ </p>
+ </div>
+
+ <div class="self-update-summary-grid">
+ <div class="self-update-summary-card">
+ <div class="summary-label">Current version</div>
+ <div class="summary-value" x-text="$store.selfUpdateStore.currentVersion"></div>
+ <div class="summary-meta" x-text="$store.selfUpdateStore.info?.current?.short_commit || ''"></div>
+ </div>
+
+ <div class="self-update-summary-card" x-show="$store.selfUpdateStore.info?.pending">
+ <div class="summary-label">Pending request</div>
+ <div
+ class="summary-value"
+ x-text="$store.selfUpdateStore.formatBranchTag($store.selfUpdateStore.info?.pending?.branch, $store.selfUpdateStore.info?.pending?.tag)"
+ ></div>
+ <div
+ class="summary-meta"
+ x-text="$store.selfUpdateStore.formatTimestamp($store.selfUpdateStore.info?.pending?.requested_at)"
+ ></div>
+ </div>
+ </div>
+
+ <template x-if="!$store.selfUpdateStore.isSupported">
+ <div class="self-update-warning">
+ Self-update is currently available only in dockerized Agent Zero deployments
+ that boot through <code>/exe/run_A0.sh</code>.
+ </div>
+ </template>
+
+ <template x-if="$store.selfUpdateStore.info?.last_status">
+ <div class="self-update-status-card">
+ <div class="section-title">Last Attempt</div>
+ <div class="status-pill" x-text="$store.selfUpdateStore.info?.last_status?.status || 'unknown'"></div>
+ <div class="status-message" x-text="$store.selfUpdateStore.info?.last_status?.message || ''"></div>
+ <div class="summary-meta">
+ Trigger:
+ <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>
+ </div>
+ <div class="summary-meta">
+ Log:
+ <code x-text="$store.selfUpdateStore.info?.paths?.log_file || '/exe/a0-self-update.log'"></code>
+ </div>
+ <div
+ class="summary-meta"
+ x-text="$store.selfUpdateStore.formatTimestamp($store.selfUpdateStore.info?.last_status?.finished_at)"
+ ></div>
+ <template x-if="$store.selfUpdateStore.info?.last_status?.backup_zip_path">
+ <div class="status-path">
+ Backup:
+ <code x-text="$store.selfUpdateStore.info?.last_status?.backup_zip_path"></code>
+ </div>
+ </template>
+ </div>
+ </template>
+
+ <template x-if="$store.selfUpdateStore.isSupported">
+ <div>
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Target branch</div>
+ <div class="field-description">
+ Choose which official branch context should be used when resolving the requested tag.
+ </div>
+ </div>
+ <div class="field-control">
+ <select
+ x-model="$store.selfUpdateStore.form.branch"
+ :disabled="$store.selfUpdateStore.isBusy"
+ >
+ <template x-for="branch in ($store.selfUpdateStore.info?.branches || [])" :key="branch.value">
+ <option :value="branch.value" x-text="branch.label"></option>
+ </template>
+ </select>
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Target release tag</div>
+ <div class="field-description">
+ Start typing or pick one of the tags fetched from the official repo. Downgrades are allowed.
+ </div>
+ <template x-if="$store.selfUpdateStore.info?.available_tags_error">
+ <div class="field-description">
+ Tag lookup failed:
+ <span x-text="$store.selfUpdateStore.info?.available_tags_error"></span>
+ </div>
+ </template>
+ </div>
+ <div class="field-control">
+ <input
+ type="text"
+ list="self-update-tag-list"
+ x-model="$store.selfUpdateStore.form.tag"
+ placeholder="v0.9.0"
+ :disabled="$store.selfUpdateStore.isBusy"
+ />
+ <datalist id="self-update-tag-list">
+ <template x-for="tag in $store.selfUpdateStore.availableTags" :key="tag">
+ <option :value="tag"></option>
+ </template>
+ </datalist>
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Back up <code>/a0/usr</code> first</div>
+ <div class="field-description">
+ Creates a zip backup before the release files are replaced.
+ </div>
+ </div>
+ <div class="field-control">
+ <label class="toggle">
+ <input
+ type="checkbox"
+ x-model="$store.selfUpdateStore.form.backup_usr"
+ :disabled="$store.selfUpdateStore.isBusy"
+ />
+ <span class="toggler"></span>
+ </label>
+ </div>
+ </div>
+
+ <div x-show="$store.selfUpdateStore.form.backup_usr">
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Backup directory</div>
+ <div class="field-description">
+ Absolute or repo-relative path where the <code>usr</code> zip should be written.
+ </div>
+ </div>
+ <div class="field-control">
+ <input
+ type="text"
+ x-model="$store.selfUpdateStore.form.backup_path"
+ :disabled="$store.selfUpdateStore.isBusy"
+ />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Backup filename</div>
+ <div class="field-description">
+ The manager normalizes this into a safe <code>.zip</code> filename.
+ </div>
+ </div>
+ <div class="field-control">
+ <input
+ type="text"
+ x-model="$store.selfUpdateStore.form.backup_name"
+ :disabled="$store.selfUpdateStore.isBusy"
+ />
+ </div>
+ </div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">If the filename already exists</div>
+ <div class="field-description">
+ Choose whether to rename the backup, replace it, or stop the update.
+ </div>
+ </div>
+ <div class="field-control">
+ <select
+ x-model="$store.selfUpdateStore.form.backup_conflict_policy"
+ :disabled="$store.selfUpdateStore.isBusy"
+ >
+ <option value="rename">Rename with suffix</option>
+ <option value="overwrite">Overwrite existing zip</option>
+ <option value="fail">Fail before restart</option>
+ </select>
+ </div>
+ </div>
+ </div>
+
+ <div class="self-update-file-hint">
+ The durable trigger, status, and log files live outside <code>/a0</code>:
+ <code x-text="$store.selfUpdateStore.info?.paths?.update_file || '/exe/a0-self-update.yaml'"></code>,
+ <code x-text="$store.selfUpdateStore.info?.paths?.status_file || '/exe/a0-self-update-status.yaml'"></code>,
+ <code x-text="$store.selfUpdateStore.info?.paths?.log_file || '/exe/a0-self-update.log'"></code>.
+ </div>
+ </div>
+ </template>
+
+ <div class="self-update-error" x-show="$store.selfUpdateStore.error">
+ <span x-text="$store.selfUpdateStore.error"></span>
+ </div>
+
+ <div class="self-update-loading" x-show="$store.selfUpdateStore.loading">
+ Loading update status...
+ </div>
+ <div class="self-update-loading" x-show="$store.selfUpdateStore.restarting">
+ Restarting Agent Zero and waiting for the health check...
+ </div>
+
+ <div class="modal-footer" data-modal-footer>
+ <button
+ class="btn btn-ok"
+ @click="$store.selfUpdateStore.scheduleUpdate()"
+ :disabled="!$store.selfUpdateStore.isSupported || $store.selfUpdateStore.isBusy"
+ >
+ Schedule Update And Restart
+ </button>
+ <button
+ class="btn btn-field"
+ @click="$store.selfUpdateStore.refresh()"
+ :disabled="$store.selfUpdateStore.isBusy"
+ >
+ Refresh Status
+ </button>
+ <button
+ class="btn btn-cancel"
+ @click="$store.selfUpdateStore.close()"
+ :disabled="$store.selfUpdateStore.restarting"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ </template>
+ </div>
+
+ <style>
+ .self-update-modal {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ }
+
+ .self-update-copy {
+ color: var(--color-text-secondary);
+ line-height: 1.5;
+ }
+
+ .self-update-copy p {
+ margin: 0 0 0.75rem;
+ }
+
+ .self-update-summary-grid {
+ display: grid;
+ gap: 0.75rem;
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ }
+
+ .self-update-summary-card,
+ .self-update-status-card {
+ border: 1px solid var(--color-border);
+ border-radius: 10px;
+ padding: 0.9rem 1rem;
+ background: var(--color-bg-secondary);
+ }
+
+ .summary-label {
+ font-size: 0.8rem;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--color-text-secondary);
+ }
+
+ .summary-value {
+ font-size: 1.1rem;
+ font-weight: 600;
+ margin-top: 0.35rem;
+ }
+
+ .summary-meta,
+ .status-path {
+ margin-top: 0.35rem;
+ color: var(--color-text-secondary);
+ font-size: 0.9rem;
+ word-break: break-word;
+ }
+
+ .self-update-warning,
+ .self-update-error,
+ .self-update-loading {
+ padding: 0.8rem 0.9rem;
+ border-radius: 8px;
+ }
+
+ .self-update-warning {
+ background: var(--color-warning-bg);
+ color: var(--color-warning);
+ }
+
+ .self-update-error {
+ background: var(--color-error-bg);
+ color: var(--color-error);
+ }
+
+ .self-update-loading {
+ background: var(--color-bg-secondary);
+ color: var(--color-text-secondary);
+ }
+
+ .self-update-file-hint {
+ color: var(--color-text-secondary);
+ line-height: 1.5;
+ font-size: 0.95rem;
+ }
+
+ .status-pill {
+ display: inline-flex;
+ align-items: center;
+ border: 1px solid var(--color-border);
+ border-radius: 999px;
+ padding: 0.2rem 0.55rem;
+ margin-top: 0.35rem;
+ font-size: 0.82rem;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ }
+
+ .status-message {
+ margin-top: 0.7rem;
+ line-height: 1.5;
+ }
+ </style>
+ </body>
+</html>
diff --git a/webui/components/settings/external/self-update-store.js b/webui/components/settings/external/self-update-store.js
new file mode 100644
index 000000000..01c60fcd1
--- /dev/null
+++ b/webui/components/settings/external/self-update-store.js
@@ -0,0 +1,210 @@
+import { createStore } from "/js/AlpineStore.js";
+import * as API from "/js/api.js";
+import { store as notificationStore } from "/components/notifications/notification-store.js";
+
+const HEALTH_POLL_INTERVAL_MS = 2000;
+const HEALTH_WAIT_BUFFER_MS = 30000;
+
+const model = {
+ loading: false,
+ saving: false,
+ restarting: false,
+ error: "",
+ info: null,
+ form: {
+ branch: "main",
+ tag: "",
+ backup_usr: true,
+ backup_path: "",
+ backup_name: "",
+ backup_conflict_policy: "rename",
+ },
+ _reconnectTimer: null,
+
+ get isBusy() {
+ return this.loading || this.saving || this.restarting;
+ },
+
+ get isSupported() {
+ return Boolean(this.info?.supported);
+ },
+
+ get currentVersion() {
+ return this.info?.current?.short_tag || "unknown";
+ },
+
+ get availableTags() {
+ return Array.isArray(this.info?.available_tags) ? this.info.available_tags : [];
+ },
+
+ async init() {
+ await this.refresh();
+ },
+
+ cleanup() {
+ this.clearReconnectTimer();
+ this.error = "";
+ this.loading = false;
+ this.saving = false;
+ this.restarting = false;
+ },
+
+ clearReconnectTimer() {
+ if (this._reconnectTimer) {
+ clearTimeout(this._reconnectTimer);
+ this._reconnectTimer = null;
+ }
+ },
+
+ formatTimestamp(value) {
+ if (!value) return "";
+ try {
+ return new Date(value).toLocaleString();
+ } catch {
+ return value;
+ }
+ },
+
+ formatBranchTag(branch, tag) {
+ return `${branch || "main"} / ${tag || "None"}`;
+ },
+
+ async refresh() {
+ this.loading = true;
+ this.error = "";
+ try {
+ const response = await API.callJsonApi("self_update_get", {});
+ if (!response?.success) {
+ throw new Error(response?.error || "Failed to load self-update info.");
+ }
+ this.info = response;
+ this.applyFormState(response.pending || response.defaults || {});
+ } catch (error) {
+ console.error("Failed to load self-update info:", error);
+ this.error = error.message || "Failed to load self-update info.";
+ } finally {
+ this.loading = false;
+ }
+ },
+
+ applyFormState(source) {
+ this.form.branch = source?.branch || "main";
+ this.form.tag = source?.tag || this.currentVersion;
+ this.form.backup_usr =
+ typeof source?.backup_usr === "boolean" ? source.backup_usr : true;
+ this.form.backup_path = source?.backup_path || "";
+ this.form.backup_name = source?.backup_name || "";
+ this.form.backup_conflict_policy =
+ source?.backup_conflict_policy || "rename";
+ },
+
+ async scheduleUpdate() {
+ if (!this.form.branch?.trim()) {
+ this.error = "Choose a branch.";
+ return;
+ }
+
+ if (!this.form.tag?.trim()) {
+ this.error = "Enter a release tag to schedule.";
+ return;
+ }
+
+ this.saving = true;
+ this.error = "";
+ try {
+ const response = await API.callJsonApi("self_update_schedule", {
+ branch: this.form.branch,
+ tag: this.form.tag,
+ backup_usr: this.form.backup_usr,
+ backup_path: this.form.backup_path,
+ backup_name: this.form.backup_name,
+ backup_conflict_policy: this.form.backup_conflict_policy,
+ });
+ if (!response?.success) {
+ throw new Error(response?.error || "Failed to schedule the self-update.");
+ }
+
+ if (this.info) {
+ this.info.pending = response.pending;
+ }
+ await notificationStore.frontendWarning(
+ "Agent Zero is restarting to apply the requested branch and release tag.",
+ "Self Update",
+ 10,
+ "self-update-restart",
+ undefined,
+ true,
+ );
+ await this.restartAndReload();
+ } catch (error) {
+ console.error("Failed to schedule self-update:", error);
+ this.error = error.message || "Failed to schedule the self-update.";
+ } finally {
+ this.saving = false;
+ }
+ },
+
+ async restartAndReload() {
+ this.restarting = true;
+ this.clearReconnectTimer();
+
+ try {
+ await API.fetchApi("/restart", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({}),
+ });
+ } catch (_error) {
+ // The restart request often terminates the backend mid-flight.
+ }
+
+ const maxWaitMs =
+ ((this.info?.pending?.health_timeout_seconds ||
+ this.info?.defaults?.health_timeout_seconds ||
+ 120) *
+ 1000) +
+ HEALTH_WAIT_BUFFER_MS;
+ const deadline = Date.now() + maxWaitMs;
+ let lastError = "";
+
+ while (Date.now() < deadline) {
+ try {
+ const response = await fetch("/api/health", {
+ method: "GET",
+ credentials: "same-origin",
+ cache: "no-store",
+ });
+ if (response.ok) {
+ window.location.reload();
+ return;
+ }
+ lastError = `Health check returned HTTP ${response.status}.`;
+ } catch (error) {
+ lastError = error?.message || String(error);
+ }
+
+ await new Promise((resolve) => {
+ this._reconnectTimer = setTimeout(() => {
+ this._reconnectTimer = null;
+ resolve();
+ }, HEALTH_POLL_INTERVAL_MS);
+ });
+ }
+
+ this.restarting = false;
+ this.error =
+ "Agent Zero did not come back within the expected window. It may still be rolling back. " +
+ (lastError ? `Last health check error: ${lastError}` : "");
+ await this.refresh();
+ },
+
+ close() {
+ window.closeModal("settings/external/self-update-modal.html");
+ },
+};
+
+const store = createStore("selfUpdateStore", model);
+
+export { store };
diff --git a/webui/components/settings/external/update_checker.html b/webui/components/settings/external/update_checker.html
index c9cec85fb..aa886ec99 100644
--- a/webui/components/settings/external/update_checker.html
+++ b/webui/components/settings/external/update_checker.html
@@ -24,6 +24,32 @@
</label>
</div>
</div>
+
+ <div class="field">
+ <div class="field-label">
+ <div class="field-title">Manual Self Update</div>
+ <div class="field-description">
+ Schedule a branch plus release tag, optionally zip <code>/a0/usr</code>,
+ restart Agent Zero, and let the durable bootstrap manager in
+ <code>/exe</code> either finish the update or automatically roll back if
+ the UI never becomes healthy.
+ </div>
+ <template x-if="!$store.settings.additional?.is_dockerized">
+ <div class="field-description">
+ This action is currently available only in dockerized installs.
+ </div>
+ </template>
+ </div>
+ <div class="field-control">
+ <button
+ class="btn btn-field"
+ @click="openModal('settings/external/self-update-modal.html')"
+ :disabled="!$store.settings.additional?.is_dockerized"
+ >
+ Open Self Update
+ </button>
+ </div>
+ </div>
</div>
</template>
</div>