"""Install the ZeuZ SDK from its authenticated server download. After the SDK and its sign-in work, the new runtime writes the ``zeuz`` command onto PATH (``--no-path`` skips it) and runs ``finish-setup``: choose the workspace, check out its test repository and install the ZeuZ controller (``--no-controller`` skips it) and the ZeuZ tray icon in a desktop session (``--no-tray`` skips only the tray). Neither can fail the SDK install. ``--non-interactive`` (CI) installs no controller and edits no shell profile: the ``zeuz`` file is written, but nothing that outlives a throwaway runner, such as a running controller or a live controller key, is left behind. ``--controller`` restores both, to provision a runner machine. """ from __future__ import annotations import argparse import base64 import hashlib import hmac import json import os import re import secrets import shutil import stat import subprocess import sys import tempfile import time import webbrowser from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path from urllib.error import HTTPError, URLError from urllib.parse import parse_qs, urlencode, urlsplit from urllib.request import HTTPRedirectHandler, Request, build_opener from uuid import UUID _CALLBACK = "/zeuz/sdk/callback" _TOKEN = re.compile(r"[A-Za-z0-9_-]{43}") _WAIT_SECONDS = 300 SESSION_PROFILE = ".zeuz-session.json" # The shape of zeuz._client_headers.user_agent(), which this file cannot import: it runs # before the SDK is installed and does not know which version the server will hand it, # so it sends no X-ZeuZ-SDK-Version. tests/test_client_headers.py keeps the two in step. USER_AGENT = f"zeuz-sdk/bootstrap (python {sys.version_info[0]}.{sys.version_info[1]}; {sys.platform})" class BootstrapError(RuntimeError): pass class BindError(BootstrapError): pass class _LoopbackServer(HTTPServer): allow_reuse_address = False def get_request(self): connection, address = super().get_request() connection.settimeout(2) return connection, address def wait_for_code(origin: str, port: int, verifier: str) -> tuple[str, int]: state = secrets.token_urlsafe(32) challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() received = None class Callback(BaseHTTPRequestHandler): def log_message(self, format, *args): pass def do_GET(self): nonlocal received try: url = urlsplit(self.path) query = parse_qs(url.query, max_num_fields=3) except ValueError: self._reply(400, "Invalid ZeuZ sign-in callback.") return code = query.get("code", [""])[0] returned_state = query.get("state", []) valid = ( self.headers.get("Host") == f"127.0.0.1:{port}" and url.path == _CALLBACK and not url.scheme and not url.netloc and len(returned_state) == 1 and _TOKEN.fullmatch(returned_state[0]) and hmac.compare_digest(returned_state[0], state) ) if valid and set(query) == {"state", "code"} and len(query["code"]) == 1 and _TOKEN.fullmatch(code): received = code self._reply(200, "ZeuZ sign-in received. Return to your terminal or coding agent.") elif valid and query == {"state": [state], "error": ["access_denied"]}: received = "" self._reply(200, "ZeuZ sign-in was cancelled. You can close this tab.") else: self._reply(400, "Invalid ZeuZ sign-in callback.") def _reply(self, status: int, message: str) -> None: self.send_response(status) self.send_header("Content-Type", "text/plain; charset=utf-8") self.send_header("Cache-Control", "no-store") self.send_header("Referrer-Policy", "no-referrer") self.end_headers() self.wfile.write(message.encode()) try: server = _LoopbackServer(("127.0.0.1", port), Callback) except OSError: raise BindError(f"Cannot listen on loopback port {port}. Choose another port with --port.") from None with server: port = server.server_port url = origin + "/zeuz-sdk/authorize/?" + urlencode({ "port": port, "state": state, "code_challenge": challenge, }) print(f"Sign in to ZeuZ: {url}", flush=True) try: webbrowser.open(url) except webbrowser.Error: pass deadline = time.monotonic() + _WAIT_SECONDS while received is None and (remaining := deadline - time.monotonic()) > 0: server.timeout = min(remaining, 1) server.handle_request() if received is None: raise BootstrapError("ZeuZ browser sign-in timed out") if not received: raise BootstrapError("ZeuZ browser sign-in was declined") return received, port class _NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def _http_client(headers=None): """``headers`` comes from the installed SDK (local_login), which knows its version.""" http = build_opener(_NoRedirect()) http.addheaders = list((headers or {"User-Agent": USER_AGENT}).items()) return http def _server_origin(value: str) -> str: try: url = urlsplit(value) _ = url.port except ValueError: raise BootstrapError("Provide a valid ZeuZ server origin") from None if ( not url.hostname or url.username is not None or url.path not in {"", "/"} or "?" in value or "#" in value or any(char.isspace() for char in value) or (url.scheme != "https" and (url.scheme != "http" or url.hostname not in {"localhost", "127.0.0.1", "::1"})) ): raise BootstrapError("Provide an HTTPS ZeuZ server origin") return f"{url.scheme}://{url.netloc}" def _post(origin, http, path, payload): request = Request( origin + path, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}, ) try: response = http.open(request, timeout=15) except HTTPError as error: response = error with response: try: data = json.load(response) except ValueError: if response.status == 200: raise data = {} return response.status, data def _desktop_grant(origin, http): verifier = secrets.token_urlsafe(32) code, port = wait_for_code(origin, 0, verifier) try: status, grant = _post(origin, http, "/zeuz-sdk/token/", { "code": code, "code_verifier": verifier, "port": str(port), }) except (URLError, TimeoutError): raise BootstrapError("Could not reach ZeuZ to exchange the browser sign-in code") from None except ValueError: raise BootstrapError("ZeuZ returned an invalid browser sign-in response") from None if status != 200: if isinstance(grant, dict) and grant.get("error") == "invalid_grant": raise BootstrapError("The ZeuZ browser sign-in code expired or was already used. Start sign-in again.") raise BootstrapError(f"Could not exchange the ZeuZ browser sign-in code (HTTP {status})") if ( not isinstance(grant, dict) or not _credential(grant.get("apiKey")) or not isinstance(grant.get("identity"), dict) ): raise BootstrapError("ZeuZ returned an invalid browser sign-in response") return grant def _credential(value): return isinstance(value, str) and re.fullmatch(r"[!-~]+", value) def _device_grant(origin, http): try: status, start = _post(origin, http, "/zeuz-sdk/device/", {}) code = start["device_code"] if status != 200 or not _TOKEN.fullmatch(code): raise ValueError device = hashlib.sha256(code.encode()).hexdigest() link = origin + "/zeuz-sdk/authorize/?" + urlencode({"device": device}) if start["verification_uri_complete"] != link or start["user_code"] != device[:8].upper(): raise ValueError interval = max(5, int(start["interval"])) deadline = time.monotonic() + min(_WAIT_SECONDS, int(start["expires_in"])) except (URLError, TimeoutError, ValueError, TypeError, KeyError): raise BootstrapError("Could not start remote ZeuZ sign-in") from None print(f"Open this ZeuZ sign-in link in your browser: {link}", flush=True) print(f"Confirm this code on the approval page: {device[:8].upper()}", flush=True) while time.monotonic() + interval < deadline: time.sleep(interval) try: status, grant = _post(origin, http, "/zeuz-sdk/device/token/", {"device_code": code}) except (URLError, TimeoutError): interval += 5 continue except (ValueError, TypeError): raise BootstrapError("Invalid response during remote ZeuZ sign-in") from None if not isinstance(grant, dict): raise BootstrapError("Invalid response during remote ZeuZ sign-in") if status == 200 and _credential(grant.get("accessToken")): return grant match grant.get("error"): case "authorization_pending": continue case "slow_down": interval += 5 case "access_denied": raise BootstrapError("Remote ZeuZ sign-in was declined") case "expired_token": break case _: raise BootstrapError("Could not finish remote ZeuZ sign-in") raise BootstrapError("Remote ZeuZ sign-in expired") def _ci_headers(origin, http, workspace): key = os.environ.get("ZEUZ_API_KEY") if not _credential(key) or os.environ.get("ZEUZ_ACCESS_TOKEN"): raise BootstrapError("Set only ZEUZ_API_KEY from the runner's secret store for unattended setup") try: workspace = str(UUID(workspace)) except (ValueError, TypeError, AttributeError): raise BootstrapError("Set ZEUZ_WORKSPACE_ID to the unattended job's workspace UUID") from None headers = {"X-Api-Key": key} request = Request(origin + f"/api/test-studio/workspaces/{workspace}/", headers=headers) try: with http.open(request, timeout=15) as response: if json.load(response).get("id") != workspace: raise ValueError except (URLError, TimeoutError, ValueError, AttributeError): raise BootstrapError("Could not access the configured ZeuZ workspace with the runner's credential") from None return headers def _download(origin, http, directory, headers): request = Request(origin + "/zeuz-sdk/download/", headers=headers) try: with http.open(request, timeout=60) as response: filename = response.headers.get_filename() or "" if not re.fullmatch(r"zeuz_runtime-[A-Za-z0-9_.+-]+-py3-none-any\.whl", filename): raise BootstrapError("ZeuZ did not return an SDK wheel") wheel = directory / filename with wheel.open("wb") as output: shutil.copyfileobj(response, output) except (URLError, TimeoutError): raise BootstrapError("Could not download the private ZeuZ SDK wheel") from None return wheel def write_device_profile(path: Path, origin: str, token: str | None) -> None: data = {"serverUrl": origin} if token is not None: data["accessToken"] = token temporary = None try: with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, encoding="utf-8", delete=False) as output: temporary = Path(output.name) json.dump(data, output) temporary.replace(path) finally: if temporary is not None: temporary.unlink(missing_ok=True) def _remove_read_only(function, target, error): """``rmtree`` ``onexc``: clear the read-only bit and retry a removal once, else re-raise. This file is served on its own as ``zeuz-bootstrap.py`` and runs before the SDK is installed, so it cannot import ``zeuz.installation.remove_tree``. """ if function not in (os.unlink, os.remove, os.rmdir): raise error os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE) function(target) def uv_environment(environ, sdk_dir: Path, *, windows: bool | None = None) -> dict: """``environ`` for ``uv venv``: on Windows, uv's Python lives in ``sdk_dir/python`` and only it is used. The same rule as ``zeuz.installation.uv_environment``, which this file cannot import (it runs before the SDK is installed); tests/test_controller_windows_folders.py keeps the two equal. uv's default folder is under ``%APPDATA%``, which a packaged Windows app makes private to itself.""" windows = sys.platform == "win32" if windows is None else windows env = dict(environ) if windows: for name in ("UV_NO_MANAGED_PYTHON", "UV_PYTHON_PREFERENCE"): env.pop(name, None) env["UV_PYTHON_INSTALL_DIR"] = str(sdk_dir / "python") env["UV_MANAGED_PYTHON"] = "1" return env def install( origin: str, uv: str, sdk_dir: Path, *, mode="desktop", workspace=None, launcher=False, no_path=False, ) -> Path: http = _http_client() grant = None if mode == "ci": headers = _ci_headers(origin, http, workspace) elif mode == "device": grant = _device_grant(origin, http) headers = {"Authorization": grant["accessToken"]} else: grant = _desktop_grant(origin, http) headers = {"X-Api-Key": grant["apiKey"]} sdk_dir.mkdir(parents=True, exist_ok=True, mode=0o700) with tempfile.TemporaryDirectory(prefix="zeuz-sdk-") as directory: wheel = _download(origin, http, Path(directory), headers) runtime = Path(tempfile.mkdtemp(prefix="runtime-", dir=sdk_dir)) python = runtime / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") installed = False install_env = os.environ.copy() install_env.pop("ZEUZ_API_KEY", None) install_env.pop("ZEUZ_ACCESS_TOKEN", None) try: subprocess.run([uv, "--no-config", "venv", "--python", "3.14", str(runtime)], check=True, env=uv_environment(install_env, sdk_dir)) # Copy, never link: a user's UV_LINK_MODE=symlink (which --no-config does # not override) would install the bundled skill as links into uv's cache, # and install-skill rejects linked files as unreadable. subprocess.run( [uv, "--no-config", "pip", "install", "--link-mode", "copy", "--python", str(python), f"{wheel}[browser]"], check=True, env=install_env, ) if mode == "desktop": subprocess.run( [str(python), "-I", "-c", "from zeuz.platform.local_login import _import_login; _import_login()"], input=json.dumps({"serverUrl": origin, "apiKey": grant["apiKey"], "identity": grant["identity"]}), text=True, check=True, ) elif mode == "device": write_device_profile(runtime / SESSION_PROFILE, origin, grant["accessToken"]) installed = True finally: if not installed: shutil.rmtree(runtime, onexc=_remove_read_only) if mode != "ci": # The SDK and its sign-in already work. A skill that cannot be installed # must not discard them, or every retry needs a new browser sign-in. try: subprocess.run( [str(python), "-I", "-m", "zeuz", "install-skill", "--server-url", origin], check=True, env=install_env, ) except (OSError, subprocess.CalledProcessError) as error: print( f"Warning: the ZeuZ SDK is installed but its agent skill was not ({error}). " f"Repair it with: {python} -I -m zeuz install-skill --server-url {origin}", file=sys.stderr, flush=True, ) if mode != "ci" or launcher: # The new SDK records itself, removes this machine's older runtimes # (never one another server's record points at) and writes the `zeuz` # command. The install above already succeeded, so a failure here must # not undo it. command = [str(python), "-I", "-m", "zeuz", "adopt-runtime", "--server-url", origin, "--json"] command += ["--prune"] if mode != "ci" else [] command += ["--launcher"] if launcher else [] command += ["--no-path"] if launcher and no_path else [] command += ["--uv", uv] try: adopted = subprocess.run(command, check=False, env=install_env, capture_output=True, text=True) _print_launcher(json.loads(adopted.stdout.strip().splitlines()[-1]).get("launcher")) except (OSError, ValueError, IndexError, AttributeError): pass return python def _print_launcher(result) -> None: if isinstance(result, dict): for line in [*result.get("done", ()), *result.get("notes", ())]: print(line, flush=True) def finish(python: Path, origin: str, args, mode: str) -> None: """Choose the workspace and install the controller with the new SDK; a failure is reported, never raised.""" env = os.environ.copy() env.pop("ZEUZ_ACCESS_TOKEN", None) if mode != "ci": env.pop("ZEUZ_API_KEY", None) # the browser or device sign-in just saved is the credential command = [str(python), "-I", "-m", "zeuz", "finish-setup", "--server-url", origin] for flag, value in (("--workspace", args.workspace), ("--label", args.label)): if value: command += [flag, value] for flag, on in (("--no-controller", args.no_controller), ("--controller", args.controller), ("--no-path", args.no_path), ("--no-tray", args.no_tray), ("--no-auto-upgrade", args.no_auto_upgrade), ("--non-interactive", mode == "ci")): if on: command.append(flag) try: subprocess.run(command, check=False, env=env) except OSError as error: print(f"The ZeuZ SDK is installed, but setting up this computer did not start ({error}).", file=sys.stderr, flush=True) def unattended_path(mode: str, args) -> bool: """A CI install writes the ``zeuz`` file but edits no shell profile, unless it provisions a runner.""" return mode == "ci" and not args.controller def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--server-url", required=True) modes = parser.add_mutually_exclusive_group() modes.add_argument("--device-code", dest="mode", action="store_const", const="device") modes.add_argument("--non-interactive", dest="mode", action="store_const", const="ci") parser.add_argument("--uv", help="The uv executable to use (default: uv on PATH)") parser.add_argument("--workspace", help="Test Studio workspace UUID for this computer (default: ask)") parser.add_argument("--label", help="Controller label (default: your user name and this computer's name)") parser.add_argument("--no-controller", action="store_true", help="Do not install the ZeuZ controller") parser.add_argument("--controller", action="store_true", help="With --non-interactive: install the ZeuZ controller too (a runner machine)") parser.add_argument("--no-path", action="store_true", help="Do not put the zeuz command on PATH") parser.add_argument("--no-tray", action="store_true", help="Do not install the ZeuZ tray icon") parser.add_argument("--no-auto-upgrade", action="store_true", help="Write auto_upgrade = false: the controller does not upgrade itself") args = parser.parse_args() if args.controller and args.no_controller: parser.error("--controller and --no-controller cannot be used together") uv = args.uv or shutil.which("uv") if uv is None: parser.error("Install uv before starting ZeuZ SDK setup") mode = args.mode or "desktop" try: origin = _server_origin(args.server_url) python = install( origin, uv, Path.home() / ".zeuz" / "sdk", mode=mode, workspace=args.workspace or os.environ.get("ZEUZ_WORKSPACE_ID"), launcher=not args.no_path, no_path=unattended_path(mode, args), ) except (BootstrapError, OSError, subprocess.CalledProcessError) as error: message = str(error) if isinstance(error, BootstrapError) else "Could not install the ZeuZ SDK" parser.exit(1, message + "\n") print(f"ZeuZ SDK Python: {python}", flush=True) finish(python, origin, args, mode) if __name__ == "__main__": main()