32029cf58f
Resolved docs/install.md, internal/cli/app.go, internal/statusview and scripts/setup-native.py: no ntfy anywhere (connection, status, installer constants, troubleshooting ports), keeping the first-run next steps, the unreachable-server and tool/Docker install hints. README drops the C compiler (ntfy was its only user). The installer summary's password wording is now per run (a reinstall in the same process no longer says "you just chose"), and its test checks the URLs then the next steps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
910 lines
48 KiB
Python
910 lines
48 KiB
Python
#!/usr/bin/env python3
|
|
"""Install Pipelines natively on the host (macOS and Linux).
|
|
|
|
The installer only detects the tools it needs (go, python3, node, git and curl);
|
|
it never installs or upgrades them, and it never installs, upgrades or downloads
|
|
OpenCode or Pi. It builds the server and CLI from source into a per-user prefix
|
|
and writes the manifest scripts/manage.py loads. Reinstalling over an install
|
|
from before ntfy was removed stops and removes that ntfy (see docs/install.md).
|
|
It reuses existing host OpenCode configuration; it writes host (non-Docker)
|
|
harness profiles for the harnesses it detects and never invents a model.
|
|
"""
|
|
import argparse
|
|
import importlib.util
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
import platform
|
|
import getpass
|
|
import plistlib
|
|
import secrets
|
|
import time
|
|
import shlex
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
from urllib.parse import urlsplit
|
|
|
|
from zoneinfo import ZoneInfoNotFoundError
|
|
|
|
|
|
def module(name, file):
|
|
spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(file))
|
|
result = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(result)
|
|
return result
|
|
|
|
|
|
configure = module("configure_compose", "configure-compose.py")
|
|
lan = module("lan_address", "lan-address.py")
|
|
manage = module("pipelines_manage", "manage.py")
|
|
app_build = module("app_build", "app_build.py")
|
|
web_access = module("web_access", "web_access.py")
|
|
web_password = module("pipelines_password", "password.py")
|
|
|
|
DEFAULT_PREFIX = Path.home() / ".local/share/pipelines"
|
|
MARKER = "pipelines-install.json"
|
|
LABEL = "net.a-wan.pipelines"
|
|
SERVICE_MARKER = "Managed by Pipelines native installer"
|
|
REQUIRED_TOOLS = ("go", "python3", "git", "curl", "node")
|
|
# Where a missing prerequisite comes from; the installer itself never installs it.
|
|
TOOL_SOURCES = {
|
|
"go": "Go: https://go.dev/dl/",
|
|
"python3": "Python 3.9 or newer: https://www.python.org/downloads/",
|
|
"git": "git: your package manager (Xcode Command Line Tools on macOS)",
|
|
"curl": "curl: your package manager",
|
|
"node": "Node.js 18 or newer: https://nodejs.org/ (or your package manager)",
|
|
}
|
|
DOCKER_SOURCE = "https://docs.docker.com/get-docker/ (Docker Desktop on macOS)"
|
|
DEFAULT_SERVER_PORT = 8080
|
|
# Only the authenticated web proxy is exposed; the control API stays loopback.
|
|
DEFAULT_BIND_ADDRESS = "127.0.0.1"
|
|
|
|
|
|
class Setup:
|
|
def __init__(self, directory, prefix=None, runner=subprocess.run, environ=None):
|
|
self.directory = Path(directory)
|
|
self.prefix_argument = prefix
|
|
self.runner = runner
|
|
self.environ = environ if environ is not None else os.environ
|
|
self.verbose = False
|
|
self.install_log = None
|
|
|
|
def command(self, arguments, **kwargs):
|
|
"""Run an installer command, keeping tool output out of normal output."""
|
|
if self.verbose:
|
|
return self.runner(arguments, **kwargs)
|
|
kwargs = dict(kwargs)
|
|
kwargs.update(capture_output=True, text=True)
|
|
result = self.runner(arguments, **kwargs)
|
|
if self.install_log:
|
|
self.install_log.parent.mkdir(parents=True, exist_ok=True)
|
|
with self.install_log.open("a") as log:
|
|
log.write(f"$ {shlex.join(map(str, arguments))}\n")
|
|
if result.stdout:
|
|
log.write(result.stdout)
|
|
if result.stderr:
|
|
log.write(result.stderr)
|
|
log.write(f"[exit {result.returncode}]\n")
|
|
return result
|
|
|
|
def step(self, text):
|
|
print(f"• {text}")
|
|
|
|
# --- detection -------------------------------------------------------
|
|
|
|
def require_tools(self):
|
|
found, missing = {}, []
|
|
for tool in REQUIRED_TOOLS:
|
|
path = shutil.which(tool)
|
|
if path:
|
|
found[tool] = str(Path(path).resolve())
|
|
else:
|
|
missing.append(tool)
|
|
if missing:
|
|
raise ValueError(
|
|
"Missing required tool(s): " + ", ".join(missing) + ". Install them, then rerun ./install:\n"
|
|
+ "".join(f" - {TOOL_SOURCES.get(tool, tool)}\n" for tool in missing)
|
|
+ "(this installer never installs tools or uses a package manager)")
|
|
return found["python3"]
|
|
|
|
def harness(self):
|
|
"""Detect existing harnesses only; never install, upgrade or download them."""
|
|
opencode = shutil.which("opencode")
|
|
if not opencode:
|
|
raise ValueError(
|
|
"OpenCode was not found on PATH. It is required: it runs pipeline stages and chat by default. "
|
|
"Install it yourself (this installer never installs, upgrades or downloads it): "
|
|
"curl -fsSL https://opencode.ai/install | bash -- then rerun ./install.")
|
|
pi = shutil.which("pi")
|
|
return {"opencode": str(Path(opencode).resolve()), "pi": str(Path(pi).resolve()) if pi else ""}
|
|
|
|
def service_path(self):
|
|
system = platform.system()
|
|
if system == "Darwin":
|
|
path = Path.home() / "Library/LaunchAgents" / (LABEL + ".plist")
|
|
tool = "launchctl"
|
|
elif system == "Linux":
|
|
root = Path(self.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
path = root / "systemd/user" / (LABEL + ".service")
|
|
tool = "systemctl"
|
|
else:
|
|
raise ValueError("Native installation supports macOS (launchd) and Linux (systemd --user) only")
|
|
if not shutil.which(tool):
|
|
raise ValueError(f"{tool} is required for login autostart; run setup in a logged-in user session")
|
|
if path.is_symlink() or (path.exists() and SERVICE_MARKER not in path.read_text()):
|
|
raise ValueError(f"Refusing to replace an unmanaged autostart definition: {path}")
|
|
return path
|
|
|
|
def register_service(self, path, manifest):
|
|
"""Register the paired native services, not a second standalone server."""
|
|
prefix = Path(manifest["prefix"])
|
|
command = [manifest["python"], str(prefix / "lib/manage.py"),
|
|
"supervise", "--prefix", str(prefix)]
|
|
if platform.system() == "Darwin":
|
|
content = plistlib.dumps({
|
|
"Label": LABEL, "Comment": SERVICE_MARKER,
|
|
"ProgramArguments": command, "RunAtLoad": True,
|
|
"KeepAlive": {"SuccessfulExit": False}, "ThrottleInterval": 5,
|
|
"EnvironmentVariables": {"HOME": str(Path.home()), "PATH": manifest["path"]},
|
|
"StandardOutPath": str(prefix / "logs/supervisor.log"),
|
|
"StandardErrorPath": str(prefix / "logs/supervisor.log"), "Umask": 0o077,
|
|
})
|
|
else:
|
|
def quote(value):
|
|
if any(char in value for char in "\r\n\x00"):
|
|
raise ValueError("Autostart paths cannot contain line breaks or NUL")
|
|
return '"' + value.replace('\\', '\\\\').replace('"', '\\"').replace('%', '%%').replace('$', '$$') + '"'
|
|
|
|
content = (f"# {SERVICE_MARKER}\n[Unit]\nDescription=Pipelines native services\n"
|
|
"\n[Service]\nType=simple\nExecStart=" + " ".join(map(quote, command))
|
|
+ "\nRestart=on-failure\nRestartSec=5\nTimeoutStopSec=90\nUMask=0077\n"
|
|
# The supervisor stops its own children. Only it is
|
|
# signalled, so a Claude Code chat host (its own
|
|
# session) outlives a restart as it does under launchd.
|
|
"KillMode=process\n"
|
|
"\n[Install]\nWantedBy=default.target\n").encode()
|
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
self._write_atomic(path, content, 0o600)
|
|
manifest["registration"] = str(path)
|
|
|
|
# --- host harness profiles ------------------------------------------
|
|
|
|
MODEL_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_./:-"
|
|
|
|
@classmethod
|
|
def _valid_model(cls, value):
|
|
if not isinstance(value, str) or len(value) > 501 or "/" not in value:
|
|
return False
|
|
provider, model = value.split("/", 1)
|
|
if not provider or not model or value in ("default/default", "provider/model"):
|
|
return False
|
|
return all(char in cls.MODEL_CHARS for char in value)
|
|
|
|
def harness_config_path(self):
|
|
root = Path(self.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
return root / "pipelines" / "harnesses.json"
|
|
|
|
def _existing_harness_config(self):
|
|
path = self.harness_config_path()
|
|
if path.is_symlink() or not path.is_file():
|
|
return {}
|
|
try:
|
|
data = json.loads(path.read_text())
|
|
except (OSError, ValueError):
|
|
return {}
|
|
return data if isinstance(data, dict) else {}
|
|
|
|
def opencode_default_model(self, executable):
|
|
"""Read V2's resolved Model.Info, with OpenCode's own JSONC/auth handling.
|
|
|
|
Run in HOME, not the install checkout, so a repository's model override
|
|
does not accidentally become the host installation's global default.
|
|
No login, sessions, prompts or inference are involved.
|
|
"""
|
|
try:
|
|
result = self.runner([executable, "api", "get", "/api/model/default"],
|
|
cwd=str(Path.home()), env=dict(self.environ),
|
|
capture_output=True, text=True, timeout=30)
|
|
if result.returncode or len(result.stdout or "") > 4 * 1024 * 1024:
|
|
return ""
|
|
response = json.loads(result.stdout)
|
|
data = response.get("data") if isinstance(response, dict) else None
|
|
if not isinstance(data, dict) or data.get("enabled") is not True or data.get("status") == "deprecated":
|
|
return ""
|
|
provider, model = data.get("providerID"), data.get("modelID")
|
|
if not isinstance(provider, str) or "/" in provider or not isinstance(model, str):
|
|
return ""
|
|
value = provider + "/" + model
|
|
return value if self._valid_model(value) else ""
|
|
except (OSError, ValueError, subprocess.SubprocessError):
|
|
# Never echo raw CLI output: provider discovery can include secrets.
|
|
return ""
|
|
|
|
def configure_harnesses(self, harness, model="", allow_picker=True):
|
|
"""Write host (non-Docker) profiles for the harnesses detected on PATH.
|
|
|
|
The native install launches host harnesses, so a Docker-era
|
|
``docker_directory`` must be cleared rather than kept. Models come from
|
|
existing valid profile, the explicit ``--model`` (also recorded as
|
|
PIPELINES_DEFAULT_MODEL), or OpenCode's resolved host default; they are
|
|
never invented. Unrelated keys and
|
|
profiles for harnesses that are not detected are preserved, matching
|
|
harness.Save. No harness is installed, upgraded or downloaded.
|
|
"""
|
|
if model and not self._valid_model(model):
|
|
raise ValueError("Invalid --model; supply an actual PROVIDER/MODEL, not a default placeholder")
|
|
existing = self._existing_harness_config()
|
|
profiles = existing.get("profiles")
|
|
if not isinstance(profiles, dict):
|
|
profiles = {}
|
|
merged = {name: dict(value) for name, value in profiles.items() if isinstance(value, dict)}
|
|
order = [name for name in ("opencode", "pi") if harness.get(name)]
|
|
configured = []
|
|
for name in order:
|
|
current = merged.get(name, {})
|
|
harness_model = current.get("model") if self._valid_model(current.get("model")) else ""
|
|
pipeline_model = current.get("pipeline_model") if self._valid_model(current.get("pipeline_model")) else ""
|
|
if name == "opencode" and self._valid_model(model):
|
|
harness_model = harness_model or model
|
|
pipeline_model = pipeline_model or model
|
|
if name == "opencode" and (not harness_model or not pipeline_model):
|
|
resolved = self.opencode_default_model(harness[name])
|
|
harness_model = harness_model or resolved
|
|
pipeline_model = pipeline_model or resolved
|
|
if not harness_model or not pipeline_model:
|
|
continue
|
|
# Host mode: no docker_directory, executable is the detected host binary.
|
|
profile = dict(current)
|
|
profile.pop("docker_directory", None)
|
|
profile.update(executable=harness[name], model=harness_model, pipeline_model=pipeline_model)
|
|
merged[name] = profile
|
|
configured.append(name)
|
|
if not configured:
|
|
if allow_picker and sys.stdin.isatty():
|
|
print("No usable OpenCode default model was found. Choose the defaults below to finish ./install.")
|
|
command = [str(self.resolve_prefix() / "bin/pipelines"), "harness", "setup", "opencode",
|
|
"--host", "--executable", harness["opencode"]]
|
|
current = merged.get("opencode", {})
|
|
for field, flag in (("model", "--model"), ("pipeline_model", "--pipeline-model")):
|
|
if self._valid_model(current.get(field)):
|
|
command.extend([flag, current[field]])
|
|
result = self.command(command, cwd=str(Path.home()), env=dict(self.environ))
|
|
if result.returncode:
|
|
raise ValueError("Model selection did not complete; native setup is not ready. Rerun ./install or supply --model PROVIDER/MODEL.")
|
|
return self.configure_harnesses(harness, model, allow_picker=False)
|
|
raise ValueError("No usable configured harness model was found; native setup is not ready. "
|
|
"Rerun ./install in a terminal to choose models, or use ./install --model PROVIDER/MODEL. "
|
|
"Existing credentials and harness settings were retained.")
|
|
# Keep a configured host default; only a stale Docker default must change.
|
|
default = existing.get("default")
|
|
if default not in configured or profiles.get(default, {}).get("docker_directory"):
|
|
default = "opencode" if "opencode" in configured else configured[0]
|
|
data = dict(existing)
|
|
data["default"] = default
|
|
data["profiles"] = merged
|
|
path = self.harness_config_path()
|
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
self._write_atomic(path, (json.dumps(data, indent=2) + "\n").encode(), 0o600)
|
|
print(f"Host harness profiles written for {', '.join(configured)}; default {default} ({path}).")
|
|
return path
|
|
|
|
def resolve_prefix(self):
|
|
default = Path.home() / ".local/share/pipelines"
|
|
raw = self.prefix_argument or self.environ.get("PIPELINES_PREFIX") or default
|
|
return Path(raw).expanduser().resolve()
|
|
|
|
def authoring_role(self, prefix, requested):
|
|
"""Fresh single-user installs author; never widen an existing server's role."""
|
|
if requested is not None:
|
|
return requested
|
|
path = prefix / MARKER
|
|
if not path.exists() and not path.is_symlink():
|
|
return True
|
|
if path.is_symlink() or not path.is_file():
|
|
raise ValueError("Refusing to read authoring role from a non-regular installation manifest")
|
|
existing = json.loads(path.read_text())
|
|
if not isinstance(existing, dict) or not isinstance(existing.get("allow_authoring", False), bool):
|
|
raise ValueError("Invalid existing authoring role; no permission changes were made")
|
|
return existing.get("allow_authoring", False)
|
|
|
|
def preserve_network_settings(self, prefix, args):
|
|
"""A plain reinstall keeps the installed addresses; flags override them."""
|
|
path = prefix / MARKER
|
|
if not path.exists() and not path.is_symlink():
|
|
return
|
|
if path.is_symlink() or not path.is_file():
|
|
raise ValueError("Refusing to read network settings from a non-regular installation manifest")
|
|
existing = json.loads(path.read_text())
|
|
web = existing.get("web") or {}
|
|
saved = {"port": existing.get("server_port"),
|
|
"bind_address": existing.get("bind_address"),
|
|
"web_port": web.get("port"), "web_host": web.get("host"),
|
|
"web_lan": web.get("lan"), "web_lan_plain_login": web.get("lan_plain_login")}
|
|
supplied = {argument.split("=", 1)[0] for argument in args.argv}
|
|
for name, value in saved.items():
|
|
flag = name.replace("_", "-")
|
|
if value is not None and not {"--" + flag, "--no-" + flag} & supplied:
|
|
setattr(args, name, value)
|
|
|
|
# --- prefix layout ---------------------------------------------------
|
|
|
|
def prepare_layout(self, prefix):
|
|
prefix.mkdir(parents=True, exist_ok=True)
|
|
for name in ("bin", "lib", "data", "logs", "secrets"):
|
|
(prefix / name).mkdir(exist_ok=True)
|
|
(prefix / "secrets").chmod(0o700)
|
|
(prefix / "data").chmod(0o700)
|
|
source = Path(__file__).with_name("manage.py")
|
|
target = prefix / "lib/manage.py"
|
|
if target.is_symlink():
|
|
raise ValueError("Refusing to replace a symlinked lib/manage.py")
|
|
shutil.copyfile(source, target)
|
|
os.chmod(target, 0o700)
|
|
return target
|
|
|
|
def configure_web(self, prefix, args, web_build=None):
|
|
# Tool-manager shims dispatch by their invoked name (for example Volta).
|
|
# Resolving the symlink would run volta-shim instead of node.
|
|
node = str(Path(shutil.which("node")).absolute())
|
|
version = self.command([node, "--version"], capture_output=True, text=True)
|
|
try:
|
|
major = int(version.stdout.strip().removeprefix("v").split(".")[0])
|
|
except (ValueError, AttributeError):
|
|
major = 0
|
|
if version.returncode or major < 18:
|
|
raise ValueError("Node.js 18 or newer is required for the authenticated web proxy; "
|
|
f"install it ({TOOL_SOURCES['node']}) and rerun ./install")
|
|
# Reuse the proxy's existing credential location; never disable its gate.
|
|
auth = Path(self.environ.get("PIPELINES_WEB_AUTH_FILE")
|
|
or Path.home() / ".config/pipelines/web-auth.json").expanduser().resolve()
|
|
if auth.exists():
|
|
data = json.loads(auth.read_text())
|
|
if not web_password.valid_auth(data):
|
|
raise ValueError(f"Invalid existing web auth file; retained unchanged: {auth}")
|
|
if auth.stat().st_mode & 0o077:
|
|
raise ValueError(f"Web auth file must be private (chmod 600): {auth}")
|
|
else:
|
|
password = self.choose_password()
|
|
self.chosen_web_password = password
|
|
auth.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
# Only a scrypt hash is stored (see scripts/password.py).
|
|
self._write_atomic(auth, (json.dumps({"password_hash": web_password.hash_password(password),
|
|
"password_weak": False, "generation": 0,
|
|
"secret": secrets.token_urlsafe(48)}) + "\n").encode(), 0o600)
|
|
server_token = self.ensure_server_token(auth.parent / "server-token")
|
|
target = prefix / "lib/web"
|
|
shutil.copytree(Path(__file__).resolve().parents[1] / "web", target, dirs_exist_ok=True,
|
|
ignore=shutil.ignore_patterns("test", "node_modules", ".DS_Store"))
|
|
updates = prefix / "lib/app-updates"
|
|
updates.mkdir(parents=True, exist_ok=True)
|
|
return {"node": node, "script": str(target / "serve.mjs"),
|
|
"auth_file": str(auth), "host": args.web_host, "port": args.web_port,
|
|
"server_token_file": str(server_token),
|
|
"lan": args.web_lan, "lan_plain_login": args.web_lan_plain_login,
|
|
"root": self.install_app_web(prefix, args, web_build), "updates": str(updates)}
|
|
|
|
def ensure_server_token(self, path):
|
|
"""The proxy/CLI ↔ server shared secret (docs/notes/security-boundary.md).
|
|
|
|
Created once (0600, beside the web auth file) and kept across reinstalls."""
|
|
if path.is_symlink() or (path.exists() and not path.is_file()):
|
|
raise ValueError(f"Refusing a server token that is not a regular file: {path}")
|
|
if path.exists():
|
|
if path.stat().st_mode & 0o077 or path.stat().st_uid != os.getuid():
|
|
raise ValueError(f"Server token must be owned by you and private (chmod 600): {path}")
|
|
if len(path.read_text().strip()) >= 32:
|
|
return path
|
|
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
self._write_atomic(path, (secrets.token_urlsafe(48) + "\n").encode(), 0o600)
|
|
return path
|
|
|
|
def choose_password(self):
|
|
"""The web sign-in password for a new computer, chosen by the operator.
|
|
|
|
PIPELINES_WEB_PASSWORD answers it without a terminal (automation)."""
|
|
given = self.environ.get("PIPELINES_WEB_PASSWORD")
|
|
if given is not None:
|
|
problem = web_password.password_problem(given)
|
|
if problem:
|
|
raise ValueError(f"PIPELINES_WEB_PASSWORD is too weak. {problem}")
|
|
return given
|
|
if not sys.stdin.isatty():
|
|
raise ValueError("Choose the web sign-in password: rerun ./install in a terminal, "
|
|
"or set PIPELINES_WEB_PASSWORD. " + web_password.PASSWORD_RULE)
|
|
print("Choose the password for signing in to the Pipelines web app (and the phone app).")
|
|
print("You will need it right after this install; only a hash of it is stored.")
|
|
print(web_password.PASSWORD_RULE)
|
|
while True:
|
|
first = getpass.getpass("Web password: ")
|
|
problem = web_password.password_problem(first)
|
|
if problem:
|
|
print(problem)
|
|
continue
|
|
if getpass.getpass("Repeat the password: ") != first:
|
|
print("The passwords did not match; try again.")
|
|
continue
|
|
return first
|
|
|
|
def build_app_web(self):
|
|
"""Builds the Flutter web app in Docker (reused while its sources are
|
|
unchanged). The web app ships with the server: the install stops here,
|
|
before anything is replaced, when it cannot be built."""
|
|
if not app_build.docker_available(self.runner):
|
|
if not shutil.which("docker"):
|
|
raise ValueError("Docker is required to build the web app but was not found on PATH. "
|
|
f"Install it ({DOCKER_SOURCE}), start it, and rerun ./install. Nothing was installed.")
|
|
raise ValueError("Docker is installed but not running, or this user cannot use it, so the web app "
|
|
"cannot be built. Start Docker (Linux: systemctl start docker, and add yourself "
|
|
"to the docker group) and rerun ./install. Nothing was installed.")
|
|
try:
|
|
built = app_build.build("web", runner=self.command,
|
|
arguments=app_build.update_signing.dart_defines(self.environ))
|
|
except RuntimeError as error:
|
|
raise ValueError(f"The web app build failed ({error}); nothing was installed") from None
|
|
if not (Path(built) / "index.html").is_file():
|
|
raise ValueError(f"The web app build in {built} has no index.html; nothing was installed")
|
|
return built
|
|
|
|
def install_app_web(self, prefix, args, built=None):
|
|
"""Installs the built web app for the web proxy."""
|
|
target = prefix / "lib/app-web"
|
|
app_build.install_tree(built or self.build_app_web(), target)
|
|
return str(target)
|
|
|
|
# --- one web app ---------------------------------------------------
|
|
|
|
# A standalone web proxy agent from before the native install. It served
|
|
# a second copy of the web app, so the tailnet address showed an old build.
|
|
LEGACY_WEB_LABEL = "net.awan.pipelines.web"
|
|
|
|
def retire_legacy_web(self):
|
|
"""Stops the pre-native standalone web agent; its plist is kept as
|
|
.disabled. The installed web proxy is the only web app."""
|
|
if platform.system() != "Darwin":
|
|
return
|
|
plist = Path.home() / f"Library/LaunchAgents/{self.LEGACY_WEB_LABEL}.plist"
|
|
if not plist.is_file():
|
|
return
|
|
self.command(["launchctl", "bootout", f"gui/{os.getuid()}/{self.LEGACY_WEB_LABEL}"],
|
|
capture_output=True, text=True)
|
|
plist.rename(plist.with_name(plist.name + ".disabled"))
|
|
print(f"Retired the old standalone web agent {self.LEGACY_WEB_LABEL} (kept as {plist.name}.disabled).")
|
|
|
|
def serve_on_tailnet(self, public_url, web_port):
|
|
"""Points the tailnet HTTPS address recorded as the public web URL at
|
|
the installed web proxy, so every address serves the same web app."""
|
|
parsed = urlsplit(public_url)
|
|
if parsed.scheme != "https" or not (parsed.hostname or "").endswith(".ts.net"):
|
|
return
|
|
tailscale = shutil.which("tailscale")
|
|
if not tailscale:
|
|
raise ValueError(f"The public web URL {public_url} is a tailnet address but tailscale is not on PATH")
|
|
port = parsed.port or 443
|
|
result = self.command([tailscale, "serve", "--bg", f"--https={port}", f"http://127.0.0.1:{web_port}"],
|
|
capture_output=True, text=True)
|
|
if result.returncode:
|
|
raise ValueError(f"tailscale serve could not point {public_url} at the web app: "
|
|
+ ((result.stderr or "").strip().splitlines() or ["failed"])[-1])
|
|
print(f"Tailnet: {public_url} serves the installed web app (port {web_port}).")
|
|
|
|
# --- build and skill -------------------------------------------------
|
|
|
|
# Detachable hosts retain Claude processes and Codex interaction callbacks
|
|
# across server restarts; the server finds them beside its own executable.
|
|
COMMANDS = ("pipelines-server", "pipelines", "pipelines-claude-host", "pipelines-codex-host")
|
|
|
|
def build(self, prefix):
|
|
"""Builds the server and CLI into bin/.next; install_binaries moves
|
|
them into place once the web app is installed too."""
|
|
staging = prefix / "bin/.next"
|
|
shutil.rmtree(staging, ignore_errors=True)
|
|
staging.mkdir(parents=True)
|
|
for command in self.COMMANDS:
|
|
result = self.command(
|
|
["go", "build", "-trimpath", "-o", str(staging / command), "./cmd/" + command],
|
|
cwd=str(self.directory))
|
|
if result.returncode:
|
|
shutil.rmtree(staging, ignore_errors=True)
|
|
raise ValueError(f"go build failed for ./cmd/{command}; nothing was installed")
|
|
|
|
def install_binaries(self, prefix):
|
|
staging = prefix / "bin/.next"
|
|
for command in self.COMMANDS:
|
|
os.replace(staging / command, prefix / "bin" / command)
|
|
shutil.rmtree(staging, ignore_errors=True)
|
|
|
|
# --- stale-CLI-on-PATH guard -----------------------------------------
|
|
|
|
def check_path_shadow(self, prefix):
|
|
"""Warn when a different ``pipelines`` earlier on PATH shadows this install.
|
|
|
|
Detection is read-only and bounded: one ``shutil.which`` check plus one
|
|
bounded ``version --json`` read per binary. The installer never modifies,
|
|
moves, deletes or upgrades the other binary; it only names the shadowing
|
|
path and both versions so an older CLI is not used silently in front of
|
|
the freshly built server. Naming both versions requires reading each
|
|
binary once, so a detected shadow costs exactly two short, read-only
|
|
subprocesses (none when the prefix binary is the one PATH already
|
|
resolves). Returns the shadowing path, or None when the prefix binary is
|
|
the one PATH resolves.
|
|
"""
|
|
installed = prefix / "bin/pipelines"
|
|
found = shutil.which("pipelines")
|
|
if not found:
|
|
return None
|
|
found_path = Path(found).resolve()
|
|
try:
|
|
if found_path == installed.resolve():
|
|
return None
|
|
except OSError:
|
|
pass
|
|
other = self._binary_version(found_path)
|
|
current = self._binary_version(installed)
|
|
print(
|
|
f"WARNING: a different pipelines resolves earlier on PATH than the freshly "
|
|
f"installed CLI: {found_path} (version {other}) shadows {installed} "
|
|
f"(version {current}); the installer left it untouched. Put {prefix / 'bin'} "
|
|
"first on PATH so the CLI matches the running server.")
|
|
return found_path
|
|
|
|
def _binary_version(self, path):
|
|
"""Read a binary's ``version --json`` once; never a hot path."""
|
|
if not Path(path).is_file():
|
|
return "unknown"
|
|
try:
|
|
result = self.runner([str(path), "version", "--json"], capture_output=True, text=True)
|
|
except OSError:
|
|
return "unknown"
|
|
if result.returncode:
|
|
return "unknown"
|
|
text = (result.stdout or "").strip()
|
|
try:
|
|
data = json.loads(text)
|
|
except ValueError:
|
|
return text or "unknown"
|
|
if not isinstance(data, dict):
|
|
return "unknown"
|
|
version = data.get("version") or "unknown"
|
|
commit = data.get("commit")
|
|
return f"{version} (commit {commit})" if commit else str(version)
|
|
|
|
def install_skill(self, prefix):
|
|
result = self.command([str(prefix / "bin/pipelines"), "skill", "install"], cwd=str(self.directory))
|
|
if result.returncode:
|
|
raise ValueError("pipelines skill install failed; the native install is incomplete")
|
|
|
|
# --- Docker migration ------------------------------------------------
|
|
|
|
def docker_volumes(self):
|
|
try:
|
|
result = self.command(["docker", "volume", "ls", "--format", "{{.Name}}"],
|
|
capture_output=True, text=True)
|
|
except FileNotFoundError:
|
|
# No Docker CLI at all: there is no Docker installation to migrate.
|
|
return ()
|
|
except OSError as error:
|
|
raise ValueError(
|
|
f"Could not inspect Docker volumes for migration ({error}); refusing to start empty") from None
|
|
if result.returncode:
|
|
# A present-but-unusable Docker daemon must not silently skip migration:
|
|
# Docker data may still exist, so fail instead of starting empty.
|
|
raise ValueError(
|
|
"Could not inspect Docker volumes for migration; refusing a possibly empty start")
|
|
names = set(result.stdout.split())
|
|
return tuple(name for name in ("pipelines_pipelines-data",) if name in names)
|
|
|
|
def _migration_image(self):
|
|
result = self.command(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"],
|
|
capture_output=True, text=True)
|
|
if result.returncode:
|
|
return None
|
|
for line in result.stdout.splitlines():
|
|
name = line.strip()
|
|
repository = name.rsplit(":", 1)[0]
|
|
if repository == "pipelines" or repository.endswith("/pipelines") or repository.endswith("-pipelines"):
|
|
return name
|
|
return None
|
|
|
|
def _docker_copy_out(self, image, volume, inner, destination, replace):
|
|
if destination.exists() and not replace:
|
|
print(f"Keeping existing native {destination.name}; not overwriting it during migration.")
|
|
return False
|
|
name = f"pipelines-migrate-{os.getpid()}"
|
|
created = self.command(["docker", "create", "--name", name, "--volume", f"{volume}:/mnt:ro", image],
|
|
capture_output=True, text=True)
|
|
if created.returncode:
|
|
raise ValueError(f"Could not open Docker volume {volume} for migration; install aborted")
|
|
try:
|
|
result = self.command(["docker", "cp", f"{name}:/mnt/{inner}", str(destination)],
|
|
capture_output=True, text=True)
|
|
if result.returncode:
|
|
raise ValueError(f"Could not copy {inner} from Docker volume {volume}; install aborted")
|
|
# The live server keeps recent commits in the SQLite write-ahead log,
|
|
# so copy the -wal sidecar too or the newest definitions and runs are
|
|
# lost. SQLite recovers it on next open and rebuilds -shm itself.
|
|
for suffix in ("-wal",):
|
|
sidecar = Path(str(destination) + suffix)
|
|
sidecar.unlink(missing_ok=True)
|
|
copy = self.command(["docker", "cp", f"{name}:/mnt/{inner}{suffix}", str(sidecar)],
|
|
capture_output=True, text=True)
|
|
if copy.returncode or not sidecar.exists() or sidecar.stat().st_size == 0:
|
|
sidecar.unlink(missing_ok=True)
|
|
finally:
|
|
self.command(["docker", "rm", "-f", name], capture_output=True, text=True, check=False)
|
|
return True
|
|
|
|
def migrate_docker(self, prefix, replace=False):
|
|
volumes = self.docker_volumes()
|
|
if not volumes:
|
|
return False
|
|
image = self._migration_image()
|
|
if not image:
|
|
raise ValueError(
|
|
"Docker volumes exist but no local Pipelines image is available to read them; "
|
|
"refusing to pull an image. Build the Docker image or rerun without migration.")
|
|
(prefix / "data").mkdir(exist_ok=True)
|
|
if "pipelines_pipelines-data" in volumes:
|
|
self._docker_copy_out(image, "pipelines_pipelines-data", "pipelines.db",
|
|
prefix / "data/pipelines.db", replace)
|
|
print("Existing Docker data was migrated where it did not already exist.")
|
|
return True
|
|
|
|
# --- retired ntfy ----------------------------------------------------
|
|
|
|
def previous_manifest(self, prefix):
|
|
"""The installed manifest before this run, or {} for a fresh prefix."""
|
|
path = prefix / MARKER
|
|
if path.is_symlink() or not path.is_file():
|
|
return {}
|
|
try:
|
|
data = json.loads(path.read_text())
|
|
except (OSError, ValueError):
|
|
return {}
|
|
return data if isinstance(data, dict) else {}
|
|
|
|
def retire_ntfy(self, prefix, previous):
|
|
"""Stops and removes the ntfy an older install ran (idempotent).
|
|
|
|
The install log records what was removed and the old ntfy version first;
|
|
no credential is ever written there."""
|
|
def note(line):
|
|
if self.install_log:
|
|
self.install_log.parent.mkdir(parents=True, exist_ok=True)
|
|
with self.install_log.open("a") as log:
|
|
log.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {line}\n")
|
|
|
|
removed = manage.retire_ntfy(dict(previous, prefix=str(prefix)), note=note)
|
|
if removed:
|
|
where = f" (details in {self.install_log})" if self.install_log else ""
|
|
self.step("Retired the old ntfy notification server; notifications now come through the Pipelines apps"
|
|
+ where)
|
|
return removed
|
|
|
|
# --- manifest --------------------------------------------------------
|
|
|
|
def write_manifest(self, prefix, values):
|
|
path = prefix / MARKER
|
|
if path.is_symlink():
|
|
raise ValueError("Refusing to replace a symlinked installation manifest")
|
|
self._write_atomic(path, (json.dumps(values, indent=2, sort_keys=True) + "\n").encode(), 0o600)
|
|
return path
|
|
|
|
def _write_atomic(self, path, data, mode):
|
|
handle, temporary = tempfile.mkstemp(dir=str(path.parent), prefix=".pipelines-")
|
|
try:
|
|
os.chmod(temporary, mode)
|
|
with os.fdopen(handle, "wb") as file:
|
|
file.write(data)
|
|
if path.is_symlink():
|
|
raise ValueError(f"Refusing to replace a symlinked file {path}")
|
|
os.replace(temporary, path)
|
|
finally:
|
|
if os.path.exists(temporary):
|
|
os.unlink(temporary)
|
|
|
|
# --- run -------------------------------------------------------------
|
|
|
|
def run(self, args):
|
|
python = self.require_tools()
|
|
# Set by this run only when it creates the web sign-in, for the summary.
|
|
self.chosen_web_password = None
|
|
if args.prefix:
|
|
self.prefix_argument = args.prefix
|
|
prefix = self.resolve_prefix()
|
|
self.preserve_network_settings(prefix, args)
|
|
if not 1024 <= args.port <= 65535:
|
|
raise ValueError("Invalid server port; choose a value between 1024 and 65535")
|
|
if not 1024 <= args.web_port <= 65535 or args.web_port == args.port:
|
|
raise ValueError("Web port must be between 1024 and 65535 and differ from the server port")
|
|
try:
|
|
ipaddress.IPv4Address(args.bind_address)
|
|
except ValueError:
|
|
raise ValueError("Invalid API bind address; use an IPv4 address such as 127.0.0.1") from None
|
|
listen, web_warnings = web_access.resolve(args.web_host, args.web_lan, args.web_lan_plain_login,
|
|
{argument.split("=", 1)[0] for argument in args.argv})
|
|
args.web_host, args.web_lan, args.web_lan_plain_login = listen["host"], listen["lan"], listen["lan_plain_login"]
|
|
allow_authoring = self.authoring_role(prefix, args.allow_authoring)
|
|
web_public_url = self.environ.get("PIPELINES_WEB_PUBLIC_URL", "")
|
|
previous = prefix / MARKER
|
|
if not web_public_url and previous.is_file() and not previous.is_symlink():
|
|
web_public_url = json.loads(previous.read_text()).get("opencode_env", {}).get("PIPELINES_WEB_PUBLIC_URL", "")
|
|
if web_public_url:
|
|
parsed = urlsplit(web_public_url)
|
|
if (parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username is not None
|
|
or parsed.password is not None or parsed.query or parsed.fragment or parsed.path not in ("", "/")
|
|
or any(ord(c) < 33 for c in web_public_url)):
|
|
raise ValueError("PIPELINES_WEB_PUBLIC_URL must be an HTTP(S) web origin without credentials, path, query or fragment")
|
|
harness = self.harness()
|
|
service_path = self.service_path()
|
|
previous_manifest = self.previous_manifest(prefix)
|
|
# All or nothing: the web app and the server are both built before
|
|
# either is installed, and a failed build leaves the old pair running.
|
|
self.step("Building the web app")
|
|
web_build = self.build_app_web()
|
|
self.prepare_layout(prefix)
|
|
self.step("Building Pipelines")
|
|
self.build(prefix)
|
|
self.step("Configuring the installation")
|
|
web = self.configure_web(prefix, args, web_build)
|
|
self.install_binaries(prefix)
|
|
self.check_path_shadow(prefix)
|
|
self.install_skill(prefix)
|
|
# The native install launches host harnesses, so write host profiles for
|
|
# the detected harnesses and clear any Docker-era link. Uses only the
|
|
# explicit --model or the existing valid profile/host configuration.
|
|
harness_path = self.configure_harnesses(harness, args.model or "")
|
|
harness_config = json.loads(harness_path.read_text())
|
|
pipeline_model = harness_config["profiles"][harness_config["default"]]["pipeline_model"]
|
|
try:
|
|
lan_ip = lan.detect_lan()
|
|
except ValueError:
|
|
# Only the printed LAN web address needs it.
|
|
lan_ip = "127.0.0.1"
|
|
if args.fresh:
|
|
print("Starting empty (--fresh); existing Docker volumes are left untouched.")
|
|
else:
|
|
self.migrate_docker(prefix, args.replace_data)
|
|
# The new server and web app are in place: the old ntfy goes now,
|
|
# before the new manifest (which has no ntfy) replaces the old one.
|
|
self.retire_ntfy(prefix, previous_manifest)
|
|
timezone = args.timezone
|
|
if not timezone:
|
|
try:
|
|
timezone = configure.host_timezone()
|
|
except (ValueError, ZoneInfoNotFoundError):
|
|
timezone = "UTC"
|
|
opencode_env = {}
|
|
for key in ("XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME",
|
|
"OPENCODE_SERVER", "OPENCODE_DB"):
|
|
if self.environ.get(key):
|
|
opencode_env[key] = self.environ[key]
|
|
opencode_env["PIPELINES_DEFAULT_MODEL"] = args.model or pipeline_model
|
|
web_url = f"http://{web_access.default_url_host(web, lan_ip, web_access.tailnet_ipv4(self.command))}:{args.web_port}"
|
|
opencode_env["PIPELINES_WEB_PUBLIC_URL"] = web_public_url or web_url
|
|
path_value = str(prefix / "bin") + os.pathsep + self.environ.get("PATH", "")
|
|
manifest = {
|
|
"format": 1,
|
|
# Marks the native installer (older manifests used ntfy.mode).
|
|
"mode": "native",
|
|
"allow_authoring": allow_authoring,
|
|
"prefix": str(prefix),
|
|
"python": python,
|
|
"server_port": args.port,
|
|
"bind_address": args.bind_address,
|
|
"opencode": harness["opencode"],
|
|
"pi": harness["pi"],
|
|
"opencode_env": opencode_env,
|
|
"path": path_value,
|
|
"workspace": str(Path.home()),
|
|
"launcher": str(prefix / "bin/pipelines"),
|
|
"registration": None,
|
|
"label": LABEL,
|
|
"docker": "docker",
|
|
"project": "pipelines",
|
|
"timezone": timezone,
|
|
"web": web,
|
|
# `pipelines update` re-runs this installer from here, the same way.
|
|
"source": str(self.directory),
|
|
"install_args": list(getattr(args, "argv", [])),
|
|
}
|
|
self.register_service(service_path, manifest)
|
|
self.write_manifest(prefix, manifest)
|
|
# Save the address the host CLI/TUI dials by default, so a plain
|
|
# `pipelines` (or its TUI) reaches this installation instead of a stale
|
|
# Docker address.
|
|
endpoint = f"ws://127.0.0.1:{args.port}/connect"
|
|
client_path = configure.configure_client(endpoint, self.environ)
|
|
self.step("Starting the services")
|
|
# Parity with the Docker installer: leave the server and web proxy running.
|
|
started = self.command([python, str(prefix / "lib/manage.py"), "start", "--prefix", str(prefix)])
|
|
if started.returncode:
|
|
raise ValueError(
|
|
"The native services were installed but could not be started; run "
|
|
f"'PIPELINES_PREFIX={prefix} {prefix}/bin/pipelines start' to see the error. "
|
|
"Check your login service manager and that ports "
|
|
f"{args.port} and {args.web_port} are free (a running Docker installation may use them).")
|
|
self.retire_legacy_web()
|
|
self.serve_on_tailnet(opencode_env["PIPELINES_WEB_PUBLIC_URL"], args.web_port)
|
|
self.print_summary(prefix, manifest, lan_ip, harness_config["default"])
|
|
|
|
def print_summary(self, prefix, manifest, lan_ip, default_harness):
|
|
"""The last thing a new user reads: where to go and what to do next."""
|
|
print("\nPipelines installed")
|
|
print(f"Install location: {prefix}")
|
|
app_build.print_web_urls(manifest, lan_host=lan_ip)
|
|
bin_dir = prefix / "bin"
|
|
cli = "pipelines"
|
|
if str(bin_dir) not in self.environ.get("PATH", "").split(os.pathsep):
|
|
cli = str(bin_dir / "pipelines")
|
|
shell = Path(self.environ.get("SHELL", "")).name
|
|
rc = "~/.bashrc" if shell == "bash" else "~/.zshrc" if shell == "zsh" else "~/.profile"
|
|
displayed_bin = "$HOME/.local/share/pipelines/bin" if bin_dir == Path.home() / ".local/share/pipelines/bin" else str(bin_dir)
|
|
print(f"\nAdd the commands to your PATH: echo 'export PATH=\"{displayed_bin}:$PATH\"' >> {rc}")
|
|
password = ("the web password you just chose" if getattr(self, "chosen_web_password", None) is not None
|
|
else "your existing web password")
|
|
print("\nNext steps:")
|
|
print(f" 1. Open the address above and sign in with {password}.")
|
|
print(f" 2. {default_harness} is ready as the default harness. Add others you use:")
|
|
print(f" {cli} harness setup claude|codex|opencode|pi")
|
|
print(" 3. Start a chat, or run one of the example pipelines on the Pipelines page.")
|
|
print(f"\nCheck the services: {cli} doctor · Update later: {cli} update")
|
|
|
|
|
|
def arguments(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--prefix", type=Path, help="Installation prefix (default: ~/.local/share/pipelines)")
|
|
parser.add_argument("--timezone", help="Override the detected timezone (fallback: UTC)")
|
|
parser.add_argument("--port", type=int, default=DEFAULT_SERVER_PORT, help="Pipelines server port")
|
|
parser.add_argument("--web-port", type=int, default=8082, help="Authenticated web proxy port (default 8082)")
|
|
parser.add_argument("--web-host", help="Web proxy access: 'tailnet' (default for new installs: loopback and "
|
|
"this machine's Tailscale addresses only) or an IPv4 bind address such as 0.0.0.0 "
|
|
"(plain HTTP on every interface); reinstalls keep the saved value")
|
|
parser.add_argument("--web-lan", action=argparse.BooleanOptionalAction, default=None,
|
|
help="Also accept plain-HTTP connections from the LAN (with --web-host tailnet); "
|
|
"sign-in over them still needs --web-lan-plain-login")
|
|
parser.add_argument("--web-lan-plain-login", action=argparse.BooleanOptionalAction, default=None,
|
|
help="Allow the password and signed-in pages over plain-HTTP LAN connections "
|
|
"(unencrypted; only on a trusted network)")
|
|
parser.add_argument("--bind-address", default=DEFAULT_BIND_ADDRESS,
|
|
help="Unauthenticated server bind address (default 127.0.0.1; expose only the web proxy)")
|
|
parser.add_argument("--model", help="Explicit PROVIDER/MODEL for starter defaults and missing profile fields; "
|
|
"otherwise reuse saved/default OpenCode models or choose within this installer")
|
|
role = parser.add_mutually_exclusive_group()
|
|
role.add_argument("--allow-authoring", dest="allow_authoring", action="store_true", default=None,
|
|
help="Explicitly enable pipeline publication; fresh native installs default to enabled")
|
|
role.add_argument("--no-authoring", dest="allow_authoring", action="store_false",
|
|
help="Execution-only server; disable pipeline publication (reinstalls otherwise preserve the recorded role)")
|
|
parser.add_argument("--fresh", action="store_true",
|
|
help="Start with empty data even when an earlier Docker installation's volumes exist")
|
|
parser.add_argument("--replace-data", action="store_true",
|
|
help="Allow Docker migration to replace an existing native database")
|
|
parser.add_argument("--verbose", action="store_true", help="Show full build and tool output")
|
|
parsed = parser.parse_args(argv)
|
|
parsed.argv = list(sys.argv[1:] if argv is None else argv)
|
|
return parsed
|
|
|
|
|
|
if __name__ == "__main__":
|
|
installer = Setup(Path(__file__).resolve().parents[1])
|
|
try:
|
|
parsed = arguments()
|
|
installer.verbose = parsed.verbose
|
|
app_build.VERBOSE = parsed.verbose
|
|
prefix = parsed.prefix or Path(os.environ.get("PIPELINES_PREFIX") or DEFAULT_PREFIX).expanduser().resolve()
|
|
(prefix / "logs").mkdir(parents=True, exist_ok=True)
|
|
installer.install_log = prefix / "logs/install.log"
|
|
installer.run(parsed)
|
|
except KeyboardInterrupt:
|
|
print("\nNative setup canceled; existing configuration and data were retained.", file=sys.stderr)
|
|
sys.exit(130)
|
|
except (ValueError, OSError, json.JSONDecodeError, subprocess.SubprocessError,
|
|
ZoneInfoNotFoundError) as error:
|
|
if installer.install_log and installer.install_log.is_file() and not installer.verbose:
|
|
tail = installer.install_log.read_text(errors="replace").splitlines()[-8:]
|
|
detail = "\n".join(tail)
|
|
sys.exit(f"Native setup incomplete: {error}\nBuild/tool log: {installer.install_log}\n{detail}")
|
|
sys.exit(f"Native setup incomplete: {error}")
|