Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(deploy): self-deploy CLI - machina serve + machina deploy (gcloud preflight + Terraform)
trohitg4b5c9e1d4a2f
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 00000000..6811238e--- /dev/null+++ b/.gitattributes@@ -0,0 +1,8 @@+# Files that execute on Linux (shebangs, cloud-init, systemd) must keep LF+# even on Windows checkouts (core.autocrlf=true would otherwise produce+# CRLF working files, and `npm pack` ships the working tree verbatim —+# a CRLF shebang breaks /usr/bin/env on the deployed VM).+bin/cli.js text eol=lf+*.sh text eol=lf+*.tftpl text eol=lf+*.service text eol=lfdiff --git a/bin/cli.js b/bin/cli.jsindex a071b639..841b1942 100755--- a/bin/cli.js+++ b/bin/cli.js@@ -11,6 +11,8 @@ const PKG = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf-8'));const COMMANDS = {start: 'Start in production mode',dev: 'Start development server (hot-reload)',+ serve: 'Serve on a single public port (API + WS + SPA; used by deploy)',+ deploy: 'Provision a cloud VM running MachinaOs (Terraform)',stop: 'Stop all running services',build: 'Build the project for production',clean: 'Clean build artifacts',@@ -175,9 +177,12 @@ if (cmd === 'help' || cmd === '--help' || cmd === '-h') {console.log(`machina v${PKG.version}`);} else if (cmd === 'doctor') {doctor();-} else if (cmd === 'start' || cmd === 'dev' || cmd === 'build') {+} else if (cmd === 'start' || cmd === 'dev' || cmd === 'build' || cmd === 'serve') {checkDeps();run(cmd, process.argv.slice(3));+} else if (cmd === 'deploy') {+ // Needs sub-verb + flags forwarded (up/status/destroy --provider ...).+ run(cmd, process.argv.slice(3));} else if (COMMANDS[cmd]) {run(cmd);} else {diff --git a/cli/cli.py b/cli/cli.pyindex fc5628cc..b1faf34a 100644--- a/cli/cli.py+++ b/cli/cli.py@@ -90,6 +90,22 @@ def _build() -> None:build_command()+ "serve",+ help="Run on a single public port (API + WebSocket + built SPA + sidecar). Used by `machina deploy`.",+)+def _serve(+ port: int | None = typer.Option(+ None,+ "--port",+ help="Public port (default: $PORT, else PYTHON_BACKEND_PORT).",+ ),+) -> None:+ from cli.commands.serve import serve_command++ serve_command(port=port)++# --------------------------------------------------------------- daemon groupdaemon_app = typer.Typer(@@ -143,6 +159,77 @@ def _daemon_restart() -> None:app.add_typer(daemon_app, name="daemon")+# --------------------------------------------------------------- deploy group++deploy_app = typer.Typer(+ name="deploy",+ help="Provision a fresh cloud VM running MachinaOs (via Terraform).",+ no_args_is_help=True,+ add_completion=False,+)+++@deploy_app.command(+ "up",+ help="Create the 'machinaos' VM, install MachinaOs behind the login gate, and run it.",+)+def _deploy_up(+ provider: str = typer.Option("gcp", "--provider", help="Cloud provider: gcp (aws is a follow-on)."),+ owner_email: str = typer.Option(..., "--owner-email", help="Login email for the owner account."),+ owner_password: str | None = typer.Option(+ None, "--owner-password", help="Login password (>=8 chars). Generated + printed once if omitted."+ ),+ source: str = typer.Option("local", "--source", help="Install source: local (npm pack) or release (npm registry)."),+ version: str = typer.Option("latest", "--version", help="machinaos version when --source release."),+ machine_type: str = typer.Option("e2-standard-2", "--machine-type", help="VM size."),+ port: int = typer.Option(8080, "--port", help="Public port the app binds + the firewall opens."),+ allow_cidr: str = typer.Option("0.0.0.0/0", "--allow-cidr", help="Firewall source range (restrict to your IP/32)."),+ region: str | None = typer.Option(None, "--region", help="Cloud region (provider default if omitted)."),+ zone: str | None = typer.Option(None, "--zone", help="Cloud zone (provider default if omitted)."),+ project: str | None = typer.Option(None, "--project", help="GCP project (defaults to gcloud config)."),+) -> None:+ from cli.commands.deploy.up import up_command++ up_command(+ provider=provider,+ region=region,+ zone=zone,+ machine_type=machine_type,+ port=port,+ owner_email=owner_email,+ owner_password=owner_password,+ source=source,+ version=version,+ allow_cidr=allow_cidr,+ project=project,+ )+++@deploy_app.command(+ "status",+ help="Show the 'machinaos' deployment's URL + health.",+)+def _deploy_status() -> None:+ from cli.commands.deploy.status import status_command++ status_command()+++@deploy_app.command(+ "destroy",+ help="Terraform-destroy the 'machinaos' deployment and remove its local state.",+)+def _deploy_destroy(+ keep_state: bool = typer.Option(False, "--keep-state", help="Keep the local Terraform state dir."),+) -> None:+ from cli.commands.deploy.destroy import destroy_command++ destroy_command(keep_state=keep_state)+++app.add_typer(deploy_app, name="deploy")++# ----------------------------------------------------------------- docs groupdocs_app = typer.Typer(diff --git a/cli/commands/deploy/__init__.py b/cli/commands/deploy/__init__.pynew file mode 100644index 00000000..bcb6d3b6--- /dev/null+++ b/cli/commands/deploy/__init__.py@@ -0,0 +1,13 @@+"""``machina deploy`` -- provision a fresh cloud VM running MachinaOs.++A thin wrapper over **Terraform**: the command generates secrets + a tfvars+file and drives ``terraform init/apply/destroy``. Terraform owns every cloud+resource (VM, firewall, optional artifact bucket) declaratively, with its own+state. Per-provider root modules live under ``cli/terraform/<provider>/`` and+share one variable interface, so a new provider is one new module + no CLI+change.++The Typer group is assembled in ``cli/cli.py`` (lazy-wrapped leaves), mirroring+the ``daemon`` group; this package just holds the verb implementations + shared+helpers (``_config`` / ``_secrets`` / ``_state`` / ``_terraform``).+"""diff --git a/cli/commands/deploy/_secrets.py b/cli/commands/deploy/_secrets.pynew file mode 100644index 00000000..7f011af5--- /dev/null+++ b/cli/commands/deploy/_secrets.py@@ -0,0 +1,65 @@+"""Secret + environment generation for ``machina deploy``.++Generates the cryptographic keys + owner password the login gate needs, and+assembles the full env-var map (``app_env``) that Terraform renders into the+VM's ``/etc/machinaos/machina.env`` (a systemd ``EnvironmentFile``). The map+carries only the deployment overrides + secrets; the VM's ``.env`` (copied+from ``.env.template`` by the package build) supplies the rest of the required+settings, and OS env (the EnvironmentFile) wins over ``.env`` in+pydantic-settings.+"""++from __future__ import annotations++import secrets+import string++_PW_ALPHABET = string.ascii_letters + string.digits+++def new_key() -> str:+ """48-char hex secret (>= the 32-char minimum the app enforces)."""+ return secrets.token_hex(24)+++def new_password(length: int = 20) -> str:+ """Strong alphanumeric password (avoids shell/systemd-quoting pitfalls)."""+ return "".join(secrets.choice(_PW_ALPHABET) for _ in range(length))+++def build_app_env(+ *,+ owner_email: str,+ owner_password: str,+ port: int,+ data_dir: str = "/var/lib/machinaos",+) -> dict[str, str]:+ """The systemd EnvironmentFile map: gate overrides + freshly minted secrets.++ JWT/SECRET/ENCRYPTION keys are generated per deploy. ``JWT_COOKIE_SECURE``+ is ``false`` because the VM is reached over plain HTTP on its IP; flip to+ true once a domain + TLS terminator is in front. Temporal/Redis/event+ framework are off (local execution).+ """+ return {+ "HOST": "0.0.0.0",+ "PORT": str(port),+ "DATA_DIR": data_dir,+ "WORKSPACE_BASE_DIR": "workspaces",+ "SERVE_STATIC_CLIENT": "true",+ "VITE_AUTH_ENABLED": "true",+ "AUTH_MODE": "single",+ "JWT_COOKIE_SECURE": "false",+ "JWT_COOKIE_SAMESITE": "lax",+ "TEMPORAL_ENABLED": "false",+ "EVENT_FRAMEWORK_ENABLED": "false",+ "REDIS_ENABLED": "false",+ "NODEJS_EXECUTOR_PORT": "3020",+ "LOG_FORMAT": "text",+ "JWT_SECRET_KEY": new_key(),+ "SECRET_KEY": new_key(),+ "API_KEY_ENCRYPTION_KEY": new_key(),+ "MACHINA_OWNER_EMAIL": owner_email,+ "MACHINA_OWNER_NAME": "Owner",+ "MACHINA_OWNER_PASSWORD": owner_password,+ }diff --git a/cli/commands/deploy/_state.py b/cli/commands/deploy/_state.pynew file mode 100644index 00000000..6d157201--- /dev/null+++ b/cli/commands/deploy/_state.py@@ -0,0 +1,56 @@+"""Working dir + metadata for the (single) ``machina deploy`` deployment.++The VM instance is always named ``machinaos`` (one deployment per project), so+the working dir is fixed at ``<user-data>/deploy/machinaos/``. That directory+is BOTH the Terraform working dir (rendered module + ``terraform.tfvars.json``++ local state) and the home of a small ``deploy-meta.json`` (provider + port ++owner email) used by ``status`` / ``destroy``.++No module-level side effects -- ``user_data_dir`` (platformdirs) is only+resolved when a function is called.+"""++from __future__ import annotations++import json+from pathlib import Path++from cli.platform_ import user_data_dir++#: The fixed instance / deployment name.+NAME = "machinaos"++_META_FILENAME = "deploy-meta.json"+++def deploy_root() -> Path:+ return user_data_dir() / "deploy"+++def workdir() -> Path:+ """Terraform working dir + state location for the deployment."""+ return deploy_root() / NAME+++def meta_file() -> Path:+ return workdir() / _META_FILENAME+++def write_meta(meta: dict) -> None:+ wd = workdir()+ wd.mkdir(parents=True, exist_ok=True)+ meta_file().write_text(json.dumps(meta, indent=2), encoding="utf-8")+++def read_meta() -> dict | None:+ mf = meta_file()+ if not mf.exists():+ return None+ try:+ return json.loads(mf.read_text(encoding="utf-8"))+ except (ValueError, OSError):+ return None+++def exists() -> bool:+ return meta_file().exists()diff --git a/cli/commands/deploy/_terraform.py b/cli/commands/deploy/_terraform.pynew file mode 100644index 00000000..51c1b93c--- /dev/null+++ b/cli/commands/deploy/_terraform.py@@ -0,0 +1,68 @@+"""Terraform driver for ``machina deploy``.++Thin helpers over the ``terraform`` CLI (via ``cli.run``): preflight that it+exists, copy the chosen provider module into the deployment working dir, write+``terraform.tfvars.json``, and run init/apply/output/destroy. The CLI never+talks to a cloud API directly -- Terraform's providers do, using the same+credentials the cloud CLIs use (gcloud ADC / AWS default chain).+"""++from __future__ import annotations++import json+import shutil+from pathlib import Path++import typer++from cli._common import error_block+from cli.platform_ import project_root+from cli.run import capture, run+++def ensure_terraform() -> None:+ """Abort with guidance if the ``terraform`` binary is not on PATH."""+ if capture(["terraform", "version"]) is None:+ error_block(+ "Terraform is required but was not found on PATH.",+ [+ "Install it: https://developer.hashicorp.com/terraform/install",+ "Then re-run `machina deploy up`.",+ ],+ )+ raise typer.Exit(code=1)+++def module_src(provider: str) -> Path:+ """Path to the shipped HCL module for ``provider``."""+ return project_root() / "cli" / "terraform" / provider+++def prepare_workdir(workdir: Path, provider: str) -> None:+ """Copy the provider module's files into ``workdir`` (preserving state)."""+ src = module_src(provider)+ if not src.is_dir():+ error_block(+ f"No Terraform module for provider {provider!r}.",+ [f"Expected at {src}", "Supported today: gcp (aws is a follow-on)."],+ )+ raise typer.Exit(code=1)+ workdir.mkdir(parents=True, exist_ok=True)+ # Copy module sources (*.tf, *.tftpl). Never touch tfstate / tfvars / meta.+ for f in src.iterdir():+ if f.is_file() and f.suffix in (".tf", ".tftpl"):+ shutil.copy2(f, workdir / f.name)+++def write_tfvars(workdir: Path, variables: dict) -> None:+ (workdir / "terraform.tfvars.json").write_text(+ json.dumps(variables, indent=2), encoding="utf-8"+ )+++def tf(workdir: Path, *args: str, check: bool = True) -> int:+ return run(["terraform", *args], cwd=workdir, check=check)+++def tf_output(workdir: Path, name: str) -> str | None:+ return capture(["terraform", "output", "-raw", name], cwd=workdir)diff --git a/cli/commands/deploy/destroy.py b/cli/commands/deploy/destroy.pynew file mode 100644index 00000000..707e59ab--- /dev/null+++ b/cli/commands/deploy/destroy.py@@ -0,0 +1,34 @@+"""``machina deploy destroy`` -- tear down the deployment's cloud resources."""++from __future__ import annotations++import shutil++import typer++from cli._common import preflight+from cli.colors import console++from . import _state, _terraform+++def destroy_command(*, keep_state: bool = False) -> None:+ # Establish the same DATA_DIR context as `deploy up` so workdir() matches.+ preflight()+ meta = _state.read_meta()+ if meta is None:+ console.print("[yellow]No 'machinaos' deployment found.[/]")+ raise typer.Exit(code=1)++ _terraform.ensure_terraform()+ wd = _state.workdir()++ console.log("terraform destroy (machinaos)...")+ _terraform.tf(wd, "destroy", "-auto-approve", "-input=false")++ if keep_state:+ console.print(f" Destroyed. State kept at {wd}")+ return++ shutil.rmtree(wd, ignore_errors=True)+ console.print(" [green]Destroyed[/] and removed local state for 'machinaos'.")diff --git a/cli/commands/deploy/providers/__init__.py b/cli/commands/deploy/providers/__init__.pynew file mode 100644index 00000000..461a6c10--- /dev/null+++ b/cli/commands/deploy/providers/__init__.py@@ -0,0 +1,34 @@+"""Provider CLI adapters -- Stage 1 of ``machina deploy``.++Each adapter wraps the operator's already-installed cloud CLI (gcloud / aws)+to verify it is present + authenticated, resolve the project/region/zone,+ensure Terraform can authenticate with the same credentials, and enable the+required cloud APIs. Adapters create NO cloud resources -- Terraform (Stage 2)+does that, inheriting the CLI's credentials.+"""++from __future__ import annotations++import typer++from ._base import ProviderCli+++def get_provider(name: str) -> ProviderCli:+ """Resolve the CLI adapter for ``name`` (lazy-imports the impl)."""+ if name == "gcp":+ from .gcp import GcpCli++ return GcpCli()+ if name == "aws":+ from .aws import AwsCli++ return AwsCli()++ from cli._common import error_block++ error_block(f"Unknown provider {name!r}.", ["Supported: gcp (aws is a follow-on)."])+ raise typer.Exit(code=1)+++__all__ = ["ProviderCli", "get_provider"]diff --git a/cli/commands/deploy/providers/_base.py b/cli/commands/deploy/providers/_base.pynew file mode 100644index 00000000..bcd1077b--- /dev/null+++ b/cli/commands/deploy/providers/_base.py@@ -0,0 +1,46 @@+"""The provider-CLI adapter contract (Stage 1 of ``machina deploy``)."""++from __future__ import annotations++from typing import Protocol+++class ProviderCli(Protocol):+ """Auth + context + API-enablement over a cloud provider's own CLI.++ All methods shell out via ``cli.run``; failures abort with ``typer.Exit``+ and ``error_block`` remediation. None of these create cloud resources --+ Terraform (Stage 2) owns that, using the credentials these methods verify.+ """++ name: str++ def check(self) -> None:+ """Abort unless the provider CLI binary is on PATH."""+ ...++ def authed_account(self) -> str | None:+ """Return the logged-in identity, or ``None`` if not authenticated."""+ ...++ def resolve_context(+ self, *, region: str | None, zone: str | None, project: str | None+ ) -> dict:+ """Resolve + validate ``{project, region, zone, ...}`` from CLI config + flags.++ Aborts (with guidance) if the CLI is not logged in or required context+ (e.g. a GCP project) is missing.+ """+ ...++ def ensure_terraform_auth(self) -> None:+ """Ensure Terraform's provider can authenticate (e.g. gcloud ADC)."""+ ...++ def enable_apis(self, ctx: dict) -> None:+ """Enable the cloud APIs Terraform will need."""+ ...++ def tfvars_extra(self, ctx: dict) -> dict:+ """Provider-specific tfvars keys merged into the deployment's tfvars."""+ ...diff --git a/cli/commands/deploy/providers/aws.py b/cli/commands/deploy/providers/aws.pynew file mode 100644index 00000000..cdbb84fe--- /dev/null+++ b/cli/commands/deploy/providers/aws.py@@ -0,0 +1,45 @@+"""aws-cli adapter -- placeholder (the AWS Terraform module is a follow-on).++Implements the ``ProviderCli`` shape so the resolver/wiring is uniform, but+aborts with a clear message until the ``cli/terraform/aws/`` module lands. The+real adapter will mirror gcp.py: ``aws sts get-caller-identity`` for auth, the+default credential chain for Terraform, region from ``aws configure get region``+/ ``$AWS_REGION``, and a security-group + EC2 instance module.+"""++from __future__ import annotations++import typer++from cli._common import error_block+++class AwsCli:+ name = "aws"++ def _not_yet(self) -> None:+ error_block(+ "The aws provider is not implemented yet.",+ ["Use --provider gcp for now; the AWS module is a planned follow-on."],+ )+ raise typer.Exit(code=1)++ def check(self) -> None:+ self._not_yet()++ def authed_account(self) -> str | None:+ return None++ def resolve_context(self, *, region, zone, project) -> dict:+ self._not_yet()+ return {}++ def ensure_terraform_auth(self) -> None:+ self._not_yet()++ def enable_apis(self, ctx: dict) -> None:+ self._not_yet()++ def tfvars_extra(self, ctx: dict) -> dict:+ self._not_yet()+ return {}diff --git a/cli/commands/deploy/providers/gcp.py b/cli/commands/deploy/providers/gcp.pynew file mode 100644index 00000000..8f12f503--- /dev/null+++ b/cli/commands/deploy/providers/gcp.py@@ -0,0 +1,89 @@+"""gcloud adapter -- Stage 1 of ``machina deploy --provider gcp``.++Uses the operator's installed + authenticated ``gcloud`` CLI for auth/context/+API-enablement; Terraform's ``google`` provider then reuses the same+Application Default Credentials to create the resources.+"""++from __future__ import annotations++import typer++from cli._common import error_block+from cli.colors import console+from cli.run import capture, run++_REQUIRED_APIS = [+ "compute.googleapis.com",+ "storage.googleapis.com",+ "iam.googleapis.com",+]+++def _clean(value: str | None) -> str | None:+ """Normalise gcloud config reads (``(unset)`` / empty -> None)."""+ if not value:+ return None+ v = value.strip()+ return None if v in ("", "(unset)") else v+++class GcpCli:+ name = "gcp"++ def check(self) -> None:+ if capture(["gcloud", "version"]) is None:+ error_block(+ "The gcloud CLI was not found on PATH.",+ ["Install the Google Cloud SDK: https://cloud.google.com/sdk/docs/install"],+ )+ raise typer.Exit(code=1)++ def authed_account(self) -> str | None:+ return _clean(+ capture(+ ["gcloud", "auth", "list", "--filter=status:ACTIVE", "--format=value(account)"]+ )+ )++ def resolve_context(self, *, region, zone, project) -> dict:+ account = self.authed_account()+ if not account:+ error_block(+ "gcloud is not logged in.",+ ["Run: gcloud auth login"],+ )+ raise typer.Exit(code=1)++ proj = project or _clean(capture(["gcloud", "config", "get-value", "project"]))+ if not proj:+ error_block(+ "No GCP project is set.",+ ["Pass --project <id>, or run: gcloud config set project <id>"],+ )+ raise typer.Exit(code=1)++ reg = region or _clean(capture(["gcloud", "config", "get-value", "compute/region"])) or "us-central1"+ zn = zone or _clean(capture(["gcloud", "config", "get-value", "compute/zone"])) or "us-central1-a"++ console.print(f" gcloud account: {account}")+ console.print(f" project={proj} region={reg} zone={zn}")+ return {"project": proj, "region": reg, "zone": zn}++ def ensure_terraform_auth(self) -> None:+ # Terraform's google provider authenticates via Application Default+ # Credentials. print-access-token exits non-zero (capture -> None) when+ # ADC is not configured.+ if capture(["gcloud", "auth", "application-default", "print-access-token"]) is None:+ error_block(+ "Terraform needs Application Default Credentials.",+ ["Run: gcloud auth application-default login"],+ )+ raise typer.Exit(code=1)++ def enable_apis(self, ctx: dict) -> None:+ console.log("Enabling required GCP APIs (compute, storage, iam)...")+ run(["gcloud", "services", "enable", *_REQUIRED_APIS, "--project", ctx["project"]])++ def tfvars_extra(self, ctx: dict) -> dict:+ return {"project": ctx["project"], "region": ctx["region"], "zone": ctx["zone"]}diff --git a/cli/commands/deploy/status.py b/cli/commands/deploy/status.pynew file mode 100644index 00000000..021a3794--- /dev/null+++ b/cli/commands/deploy/status.py@@ -0,0 +1,48 @@+"""``machina deploy status`` -- show the deployment's URL + health."""++from __future__ import annotations++import urllib.error+import urllib.request++import typer++from cli._common import preflight+from cli.colors import console++from . import _state, _terraform+++def status_command() -> None:+ # Establish the same DATA_DIR context as `deploy up` (load_config sets it)+ # so workdir() resolves to the directory `up` created.+ preflight()+ meta = _state.read_meta()+ if meta is None:+ console.print("[yellow]No 'machinaos' deployment found.[/]")+ raise typer.Exit(code=1)++ wd = _state.workdir()+ ip = _terraform.tf_output(wd, "external_ip")+ url = _terraform.tf_output(wd, "url") or (+ f"http://{ip}:{meta.get('port', 8080)}" if ip else None+ )++ console.print(" Deployment: machinaos")+ console.print(f" Provider: {meta.get('provider', '?')}")+ console.print(f" External IP: {ip or '(unknown / destroyed)'}")+ console.print(f" URL: {url or '(unknown)'}")+ console.print(f" Login email: {meta.get('owner_email', '?')}")++ if not url:+ raise typer.Exit(code=1)++ healthy = False+ try:+ with urllib.request.urlopen(url.rstrip("/") + "/health", timeout=5) as resp: # noqa: S310+ healthy = resp.status == 200+ except (urllib.error.URLError, OSError):+ healthy = False+ console.print(f" Health: {'[green]OK[/]' if healthy else '[yellow]not ready[/]'}")+ if not healthy:+ raise typer.Exit(code=1)diff --git a/cli/commands/deploy/up.py b/cli/commands/deploy/up.pynew file mode 100644index 00000000..27a06e1f--- /dev/null+++ b/cli/commands/deploy/up.py@@ -0,0 +1,146 @@+"""``machina deploy up`` -- provision + run MachinaOs on a fresh cloud VM.++Two stages:+ STAGE 1 (cloud CLI): the provider adapter verifies the CLI is installed ++ authenticated, resolves project/region/zone, ensures Terraform auth, and+ enables the required cloud APIs.+ STAGE 2 (Terraform): generate secrets + owner creds -> (local source) npm+ pack -> write tfvars -> ``terraform init`` + ``apply`` -> read outputs ->+ poll ``/health`` -> print URL + credentials.++The VM instance is always named ``machinaos`` (one deployment per project).+"""++from __future__ import annotations++import time+import urllib.error+import urllib.request+from pathlib import Path++import typer++from cli._common import error_block, preflight+from cli.colors import console+from cli.run import capture++from . import _secrets, _state, _terraform+from .providers import get_provider+++def _npm_pack(root: Path) -> str:+ """Run ``npm pack`` in the repo root; return the abs path to the tarball."""+ console.log("Packaging local build (npm pack)...")+ out = capture(["npm", "pack"], cwd=root)+ if not out:+ error_block(+ "`npm pack` produced no output.",+ ["Ensure Node/npm are installed and you are in a MachinaOs checkout."],+ )+ raise typer.Exit(code=1)+ tarball = out.strip().splitlines()[-1].strip()+ path = (root / tarball).resolve()+ if not path.is_file():+ error_block(f"npm pack reported {tarball!r} but it is not on disk.", [str(path)])+ raise typer.Exit(code=1)+ return str(path)+++def _poll_health(url: str, *, attempts: int = 40, delay: float = 15.0) -> bool:+ """Poll ``<url>/health`` until 200 or attempts exhausted (~10 min)."""+ health = url.rstrip("/") + "/health"+ for i in range(1, attempts + 1):+ try:+ with urllib.request.urlopen(health, timeout=5) as resp: # noqa: S310+ if resp.status == 200:+ return True+ except (urllib.error.URLError, OSError):+ pass+ console.log(f"waiting for the VM to finish provisioning... ({i}/{attempts})")+ time.sleep(delay)+ return False+++def up_command(+ *,+ provider: str,+ region: str | None,+ zone: str | None,+ machine_type: str,+ port: int,+ owner_email: str,+ owner_password: str | None,+ source: str,+ version: str,+ allow_cidr: str,+ project: str | None,+) -> None:+ _, root = preflight()++ # --- STAGE 1: cloud CLI (auth + context + APIs) ------------------------+ cli = get_provider(provider)+ cli.check()+ _terraform.ensure_terraform()+ ctx = cli.resolve_context(region=region, zone=zone, project=project)+ cli.ensure_terraform_auth()+ cli.enable_apis(ctx)++ if _state.exists() and (_state.workdir() / "terraform.tfstate").exists():+ console.print(+ "[yellow]A 'machinaos' deployment already exists. Re-running will "+ "re-apply Terraform (safe), or run `machina deploy destroy` first.[/]"+ )++ # --- STAGE 2: secrets + source + Terraform -----------------------------+ pw = owner_password or _secrets.new_password()+ pw_generated = owner_password is None+ app_env = _secrets.build_app_env(owner_email=owner_email, owner_password=pw, port=port)++ pack_tarball = _npm_pack(root) if source == "local" else ""++ tfvars: dict = {+ "machine_type": machine_type,+ "port": port,+ "allow_cidr": allow_cidr,+ "app_env": app_env,+ "source_mode": source,+ "machinaos_version": version,+ "pack_tarball": pack_tarball,+ }+ tfvars.update(cli.tfvars_extra(ctx))++ wd = _state.workdir()+ _terraform.prepare_workdir(wd, provider)+ _terraform.write_tfvars(wd, tfvars)+ _state.write_meta({"provider": provider, "port": port, "owner_email": owner_email})++ console.log("terraform init...")+ _terraform.tf(wd, "init", "-input=false")+ console.log("terraform apply (creating cloud resources)...")+ _terraform.tf(wd, "apply", "-auto-approve", "-input=false")++ ip = _terraform.tf_output(wd, "external_ip")+ url = _terraform.tf_output(wd, "url") or (f"http://{ip}:{port}" if ip else None)++ console.print()+ console.print(" [bold green]VM 'machinaos' provisioned.[/]")+ if ip:+ console.print(f" External IP: {ip}")+ if url:+ console.print(f" URL: {url}")+ console.print(f" Login email: {owner_email}")+ if pw_generated:+ console.print(f" Login password (save this now): [bold]{pw}[/]")+ else:+ console.print(" Login password: (the one you provided)")+ console.print()++ if url:+ console.log("The VM is installing MachinaOs (Node + npm + build); this takes a few minutes.")+ if _poll_health(url):+ console.print(f" [bold green]Ready.[/] Open {url} and log in.")+ else:+ console.print(+ " [yellow]Still provisioning.[/] Check again with "+ "`machina deploy status` in a few minutes."+ )diff --git a/cli/commands/serve.py b/cli/commands/serve.pynew file mode 100644index 00000000..eec8e429--- /dev/null+++ b/cli/commands/serve.py@@ -0,0 +1,98 @@+"""``machina serve`` -- single-port production runtime.++Runs the app on ONE public port: uvicorn serves the REST API + WebSocket ++the built React SPA (via the ``SERVE_STATIC_CLIENT`` block in+``server/main.py``), plus the Node.js code-exec sidecar on its own internal+port. Used locally for a production-shaped run AND as the systemd+``ExecStart`` on a VM provisioned by ``machina deploy``.++Unlike ``machina start`` (which runs a separate static-client server + the+backend + temporal on multiple ports), ``serve`` is single-port and serves+the client from the backend itself. The Node sidecar is NOT launched by+``start``/``dev`` today, so ``serve`` adds it (the JS/TS executor nodes need+it).++The long-running uvicorn is invoked via the server venv's interpreter+directly (not ``uv run``) so the systemd service has no runtime dependency+on ``uv`` being on PATH.+"""++from __future__ import annotations++import asyncio+import os+from pathlib import Path++import typer++from cli._common import preflight+from cli.buildenv import validate_build+from cli.colors import console+from cli.platform_ import IS_WINDOWS, server_dir, server_venv+++def _venv_python(root: Path | None = None) -> str:+ """Absolute path to the server venv's Python interpreter."""+ venv = server_venv(root)+ rel = "Scripts/python.exe" if IS_WINDOWS else "bin/python"+ return str(venv / rel)+++def serve_command(port: int | None = None) -> None:+ from cli.supervisor import Manager, ServiceSpec++ cfg, root = preflight()+ os.environ.setdefault("PYTHONUTF8", "1")+ validate_build(root, require_client_dist=True)++ # Public port: --port flag > $PORT (Cloud Run / systemd convention) >+ # PYTHON_BACKEND_PORT from the env files.+ bind_port = port or int(os.environ.get("PORT") or cfg.backend_port)++ # Free the ports we will bind (clears stale orphans; idempotent).+ from cli.ports import kill_port++ for p in {bind_port, cfg.nodejs_port}:+ kill_port(p)++ console.print()+ console.print(" [bold]MachinaOS[/] serve (single-port)")+ console.print(f" App: http://0.0.0.0:{bind_port} (API + WebSocket + SPA)")+ console.print(f" Sidecar: 127.0.0.1:{cfg.nodejs_port} (JS/TS executor)")+ console.print()++ sidecar = server_dir(root) / "nodejs" / "dist" / "index.js"++ specs = [+ ServiceSpec(+ name="server",+ argv=[+ _venv_python(root),+ "-m",+ "uvicorn",+ "main:app",+ "--host",+ "0.0.0.0",+ "--port",+ str(bind_port),+ "--log-level",+ "warning",+ ],+ cwd=server_dir(root),+ env={"SERVE_STATIC_CLIENT": "1", "PORT": str(bind_port)},+ ready_port=bind_port,+ ),+ ServiceSpec(+ name="nodejs",+ argv=["node", str(sidecar)],+ cwd=server_dir(root) / "nodejs",+ env={"NODEJS_EXECUTOR_PORT": str(cfg.nodejs_port)},+ ready_port=cfg.nodejs_port,+ ),+ ]++ manager = Manager()+ manager.add_all(specs)+ rc = asyncio.run(manager.run())+ if rc != 0:+ raise typer.Exit(code=rc)diff --git a/cli/terraform/gcp/main.tf b/cli/terraform/gcp/main.tfnew file mode 100644index 00000000..e99d2685--- /dev/null+++ b/cli/terraform/gcp/main.tf@@ -0,0 +1,116 @@+terraform {+ required_version = ">= 1.3"+ required_providers {+ google = {+ source = "hashicorp/google"+ version = "~> 5.0"+ }+ }+}++provider "google" {+ project = var.project+ region = var.region+}++locals {+ # The instance is always named "machinaos" (one deployment per project).+ use_local = var.source_mode == "local"+ res_name = "machinaos"+ bucket_name = "${var.project}-machinaos"+ object_name = "machinaos.tgz"+}++# --- Artifact bucket + object (local source only) --------------------------++resource "google_storage_bucket" "artifact" {+ count = local.use_local ? 1 : 0+ name = local.bucket_name+ location = var.region+ force_destroy = true+ uniform_bucket_level_access = true+}++resource "google_storage_bucket_object" "pkg" {+ count = local.use_local ? 1 : 0+ name = local.object_name+ bucket = google_storage_bucket.artifact[0].name+ source = var.pack_tarball+}++# --- VM service account (reads the artifact bucket) ------------------------++resource "google_service_account" "vm" {+ account_id = local.res_name+ display_name = "MachinaOs VM"+}++resource "google_storage_bucket_iam_member" "vm_read" {+ count = local.use_local ? 1 : 0+ bucket = google_storage_bucket.artifact[0].name+ role = "roles/storage.objectViewer"+ member = "serviceAccount:${google_service_account.vm.email}"+}++# --- Firewall: app port + SSH ----------------------------------------------++resource "google_compute_firewall" "app" {+ name = "${local.res_name}-app"+ network = "default"++ allow {+ # CF-proxied front door (80 http-redirected, 443 TLS via nginx) + SSH ++ # the app port for direct-IP access.+ protocol = "tcp"+ ports = ["80", "443", tostring(var.port), "22"]+ }++ source_ranges = [var.allow_cidr]+ target_tags = [local.res_name]+}++# --- Instance --------------------------------------------------------------++resource "google_compute_instance" "vm" {+ name = local.res_name+ machine_type = var.machine_type+ zone = var.zone+ tags = [local.res_name]++ boot_disk {+ initialize_params {+ # Ubuntu 24.04 ships Python 3.12 natively — required by the package's+ # install (server needs >=3.11,<3.13; the CLI needs >=3.12). 22.04+ # ships 3.10 and the npm postinstall hard-fails on it.+ image = "ubuntu-os-cloud/ubuntu-2404-lts-amd64"+ size = 40+ type = "pd-balanced"+ }+ }++ network_interface {+ network = "default"+ access_config {} # ephemeral external IP+ }++ service_account {+ email = google_service_account.vm.email+ scopes = ["cloud-platform"]+ }++ metadata = {+ startup-script = templatefile("${path.module}/startup.sh.tftpl", {+ app_env = var.app_env+ source_mode = var.source_mode+ version = var.machinaos_version+ bucket = local.use_local ? google_storage_bucket.artifact[0].name : ""+ object = local.object_name+ })+ }++ # The startup script reads the bucket object; ensure it exists + is readable first.+ depends_on = [+ google_storage_bucket_object.pkg,+ google_storage_bucket_iam_member.vm_read,+ ]+}diff --git a/cli/terraform/gcp/outputs.tf b/cli/terraform/gcp/outputs.tfnew file mode 100644index 00000000..2cb231d8--- /dev/null+++ b/cli/terraform/gcp/outputs.tf@@ -0,0 +1,9 @@+output "external_ip" {+ value = google_compute_instance.vm.network_interface[0].access_config[0].nat_ip+ description = "The VM's public IP."+}++output "url" {+ value = "http://${google_compute_instance.vm.network_interface[0].access_config[0].nat_ip}:${var.port}"+ description = "The app URL (login gate)."+}diff --git a/cli/terraform/gcp/startup.sh.tftpl b/cli/terraform/gcp/startup.sh.tftplnew file mode 100644index 00000000..d2a5bfc4--- /dev/null+++ b/cli/terraform/gcp/startup.sh.tftpl@@ -0,0 +1,65 @@+#!/bin/bash+# MachinaOs VM startup script (rendered by Terraform `templatefile`).+# Installs the toolchain, installs MachinaOs (npm), writes the login-gate env+# file, and runs it under systemd via `machina serve`.+#+# NOTE on syntax: Terraform renders this file with templatefile(), so any+# dollar-brace sequence is a Terraform interpolation. Bash variables are+# therefore written UNBRACED ($TOKEN, $MACHINA_BIN) so Terraform leaves them+# alone. `set -x` is intentionally NOT used so secrets in the env file are+# never echoed to the serial console.+set -euo pipefail+export DEBIAN_FRONTEND=noninteractive++echo "[machinaos] installing toolchain..."+apt-get update+apt-get install -y curl ca-certificates git build-essential pkg-config libffi-dev libssl-dev+curl -fsSL https://deb.nodesource.com/setup_22.x | bash -+apt-get install -y nodejs+corepack enable || true+# uv on a stable system path (machina build uses it to sync the Python venv).+curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh++echo "[machinaos] installing MachinaOs package..."+%{ if source_mode == "local" ~}+TOKEN=$(curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" | python3 -c 'import sys, json; print(json.load(sys.stdin)["access_token"])')+curl -fsS -H "Authorization: Bearer $TOKEN" -o /tmp/machinaos.tgz "https://storage.googleapis.com/storage/v1/b/${bucket}/o/${object}?alt=media"+npm install -g /tmp/machinaos.tgz+%{ else ~}+npm install -g machinaos@${version}+%{ endif ~}++echo "[machinaos] writing login-gate env..."+mkdir -p /etc/machinaos+cat > /etc/machinaos/machina.env <<'MACHINA_ENV_EOF'+%{ for k, v in app_env ~}+${k}=${v}+%{ endfor ~}+MACHINA_ENV_EOF+chmod 600 /etc/machinaos/machina.env++mkdir -p /var/lib/machinaos++echo "[machinaos] installing systemd service..."+MACHINA_BIN=$(command -v machina)+cat > /etc/systemd/system/machinaos.service <<SERVICE_EOF+[Unit]+Description=MachinaOs (single login-gated instance)+After=network-online.target+Wants=network-online.target++[Service]+Type=simple+EnvironmentFile=/etc/machinaos/machina.env+ExecStart=$MACHINA_BIN serve+Restart=on-failure+RestartSec=5+TimeoutStopSec=20++[Install]+WantedBy=multi-user.target+SERVICE_EOF++systemctl daemon-reload+systemctl enable --now machinaos+echo "[machinaos] done."diff --git a/cli/terraform/gcp/variables.tf b/cli/terraform/gcp/variables.tfnew file mode 100644index 00000000..294f8348--- /dev/null+++ b/cli/terraform/gcp/variables.tf@@ -0,0 +1,54 @@+# Shared deployment variable interface (every provider module declares the+# same set, so `machina deploy` writes one tfvars shape regardless of provider).++variable "project" {+ type = string+ description = "GCP project id."+}++variable "region" {+ type = string+ description = "GCP region."+}++variable "zone" {+ type = string+ description = "GCP zone for the instance."+}++variable "machine_type" {+ type = string+ description = "Compute Engine machine type."+}++variable "port" {+ type = number+ description = "Public port the app binds and the firewall opens."+}++variable "allow_cidr" {+ type = string+ description = "Firewall source range (e.g. 0.0.0.0/0 or <your-ip>/32)."+}++variable "source_mode" {+ type = string+ description = "Install source: 'local' (npm pack tarball via bucket) or 'release' (npm registry)."+}++variable "machinaos_version" {+ type = string+ description = "machinaos version to install when source_mode = 'release'."+}++variable "pack_tarball" {+ type = string+ default = ""+ description = "Absolute path to the npm pack tarball (source_mode = 'local')."+}++variable "app_env" {+ type = map(string)+ sensitive = true+ description = "KEY=VALUE map rendered into the VM's /etc/machinaos/machina.env."+}diff --git a/deploy.sh b/deploy.shdeleted file mode 100644index 5a34ced6..00000000--- a/deploy.sh+++ /dev/null@@ -1,205 +0,0 @@-#!/bin/bash--# MachinaOs Deployment to GCP-# Deploys the workflow automation platform using Docker Compose.-# Builds Docker images on the GCP server to avoid local Docker requirement.-#-# Prerequisites:-# - SSH access to GCP instance-# - Docker and Docker Compose installed on GCP instance-#-# Usage:-# ./deploy.sh [GCP_HOST]--set -e--# Load environment variables from .env if exists-if [ -f "$(dirname "$0")/server/.env" ]; then- export $(grep -v '^#' "$(dirname "$0")/server/.env" | grep -E '^DEPLOY_|^ANDROID_RELAY_' | xargs)-fi--GCP_HOST="${1:-${DEPLOY_HOST:-user@your-server-ip}}"-SERVICE_NAME="machina"-DOMAIN="${DEPLOY_DOMAIN:-your-domain.com}"-REMOTE_DIR="/opt/${SERVICE_NAME}"-LOCAL_DIR="$(cd "$(dirname "$0")" && pwd)"-FRONTEND_PORT="3000"-BACKEND_PORT="3010"--echo "========================================"-echo "Deploying MachinaOs"-echo "========================================"-echo "Host: ${GCP_HOST}"-echo "Domain: ${DOMAIN}"-echo "Frontend Port: ${FRONTEND_PORT}"-echo "Backend Port: ${BACKEND_PORT}"-echo "========================================"--# Step 1: Upload source code-echo "[1/5] Uploading source code to GCP..."-ssh ${GCP_HOST} "mkdir -p /tmp/${SERVICE_NAME}"--# Create tarball of required files (excluding node_modules, __pycache__, etc.)-tar --exclude='node_modules' \- --exclude='__pycache__' \- --exclude='.git' \- --exclude='*.pyc' \- --exclude='.env' \- --exclude='*.db' \- --exclude='*.db-*' \- --exclude='data' \- --exclude='bin' \- -czf /tmp/machina-src.tar.gz \- -C "${LOCAL_DIR}" \- client server docker-compose.prod.yml--scp /tmp/machina-src.tar.gz "${GCP_HOST}:/tmp/${SERVICE_NAME}/"--# Upload production .env (prefer .env.production, fallback to .env, then create from template)-if [ -f "${LOCAL_DIR}/server/.env.production" ]; then- scp "${LOCAL_DIR}/server/.env.production" "${GCP_HOST}:/tmp/${SERVICE_NAME}/.env"-elif [ -f "${LOCAL_DIR}/server/.env" ]; then- scp "${LOCAL_DIR}/server/.env" "${GCP_HOST}:/tmp/${SERVICE_NAME}/.env"-elif [ -f "${LOCAL_DIR}/.env.template" ]; then- echo "No .env found, creating from .env.template..."- scp "${LOCAL_DIR}/.env.template" "${GCP_HOST}:/tmp/${SERVICE_NAME}/.env"-elif [ -f "${LOCAL_DIR}/server/.env.template" ]; then- echo "No .env found, creating from server/.env.template..."- scp "${LOCAL_DIR}/server/.env.template" "${GCP_HOST}:/tmp/${SERVICE_NAME}/.env"-else- echo "Warning: No .env or .env.template found. Using docker-compose environment variables only."-fi--# Step 2: Build and deploy on remote-echo "[2/5] Building and deploying on GCP..."-ssh ${GCP_HOST} << 'REMOTE_SCRIPT'-set -e-SERVICE_NAME="machina"-DEPLOY_DIR="/opt/${SERVICE_NAME}"--# Stop existing containers-cd ${DEPLOY_DIR} 2>/dev/null && docker-compose down 2>/dev/null || true--# Setup deployment directory-sudo mkdir -p ${DEPLOY_DIR}-sudo chown -R $USER:$USER ${DEPLOY_DIR}--# Extract source code-cd ${DEPLOY_DIR}-tar -xzf /tmp/${SERVICE_NAME}/machina-src.tar.gz--# Copy .env file to server directory (where docker-compose expects it)-mkdir -p ${DEPLOY_DIR}/server-[ -f /tmp/${SERVICE_NAME}/.env ] && cp /tmp/${SERVICE_NAME}/.env ${DEPLOY_DIR}/server/.env--# Create docker-compose.yml from prod version-mv docker-compose.prod.yml docker-compose.yml--# Build Docker images on server-echo "Building Docker images on server..."-docker-compose build --no-cache--# Start containers-echo "Starting containers..."-docker-compose up -d--# Cleanup temp files and dangling Docker images-rm -rf /tmp/${SERVICE_NAME}-echo "Cleaning up dangling Docker images..."-docker image prune -f-docker system prune -f --volumes=false-REMOTE_SCRIPT--# Step 3: Setup nginx reverse proxy-echo "[3/5] Configuring nginx..."-ssh ${GCP_HOST} << NGINX_SCRIPT-set -e-DOMAIN="${DOMAIN}"-FRONTEND_PORT="${FRONTEND_PORT}"-BACKEND_PORT="${BACKEND_PORT}"--# Create nginx config-sudo tee /etc/nginx/sites-available/\${DOMAIN} > /dev/null <<NGINX_CONF-server {- server_name ${DOMAIN};-- # Frontend- location / {- proxy_pass http://127.0.0.1:3000;- proxy_http_version 1.1;- proxy_set_header Host \$host;- proxy_set_header X-Real-IP \$remote_addr;- proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;- proxy_set_header X-Forwarded-Proto \$scheme;- }-- # Backend API- location /api/ {- proxy_pass http://127.0.0.1:3010/api/;- proxy_http_version 1.1;- proxy_set_header Host \$host;- proxy_set_header X-Real-IP \$remote_addr;- proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;- proxy_set_header X-Forwarded-Proto \$scheme;- }-- # Backend WebSocket- location /ws/ {- proxy_pass http://127.0.0.1:3010/ws/;- proxy_http_version 1.1;- proxy_set_header Upgrade \$http_upgrade;- proxy_set_header Connection "upgrade";- proxy_set_header Host \$host;- proxy_set_header X-Real-IP \$remote_addr;- proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;- proxy_read_timeout 86400;- proxy_send_timeout 86400;- }-- # Webhook endpoint- location /webhook/ {- proxy_pass http://127.0.0.1:3010/webhook/;- proxy_http_version 1.1;- proxy_set_header Host \$host;- proxy_set_header X-Real-IP \$remote_addr;- proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;- proxy_set_header X-Forwarded-Proto \$scheme;- }-- # Health check- location /health {- proxy_pass http://127.0.0.1:3010/health;- proxy_http_version 1.1;- proxy_set_header Host \$host;- }-}-NGINX_CONF--sudo ln -sf /etc/nginx/sites-available/\${DOMAIN} /etc/nginx/sites-enabled/-sudo nginx -t && sudo systemctl reload nginx--# Setup SSL-sudo certbot --nginx -d \${DOMAIN} --non-interactive --agree-tos --register-unsafely-without-email || true-NGINX_SCRIPT--# Step 4: Verify-echo "[4/5] Verifying deployment..."-sleep 5-ssh ${GCP_HOST} "cd /opt/${SERVICE_NAME} && docker-compose ps"--# Cleanup local temp files-rm -f /tmp/machina-src.tar.gz--echo "========================================"-echo "[5/5] Deployment Complete!"-echo "========================================"-echo " URL: https://${DOMAIN}"-echo " Health: https://${DOMAIN}/health"-echo " API: https://${DOMAIN}/api/"-echo " WS: wss://${DOMAIN}/ws/status"-echo "========================================"-echo ""-echo "Useful commands:"-echo " ssh ${GCP_HOST} 'cd /opt/${SERVICE_NAME} && docker-compose logs -f'"-echo " ssh ${GCP_HOST} 'cd /opt/${SERVICE_NAME} && docker-compose restart'"-echo "========================================"diff --git a/package.json b/package.jsonindex b66a4e0c..9e36f538 100644--- a/package.json+++ b/package.json@@ -64,6 +64,7 @@"scripts": {"start": "python -m cli start","dev": "python -m cli dev",+ "serve": "python -m cli serve","start:temporal": "cross-env TEMPORAL_ENABLED=true python -m cli start","client:start": "cd client && npm run start","python:start": "cd server && uv run uvicorn main:app --host 127.0.0.1 --port 3010 --log-level warning",@@ -81,8 +82,7 @@"test:nodes": "cd server && uv run pytest tests/nodes/ -v --cov=services.handlers --cov-report=term-missing","docs:nodes": "python -m cli docs nodes","docs:nodes:check": "python -m cli docs nodes --check",- "deploy": "bash deploy.sh",- "deploy:gcp": "bash deploy.sh",+ "deploy": "python -m cli deploy","daemon:start": "python -m cli daemon start","daemon:stop": "python -m cli daemon stop","daemon:status": "python -m cli daemon status",diff --git a/server/main.py b/server/main.pyindex 5008fcfd..567beaca 100644--- a/server/main.py+++ b/server/main.py@@ -151,6 +151,31 @@ async def lifespan(app: FastAPI):logger.info("Encryption service initialized")_startup_log("Credentials + encryption initialized")+ # Seed the owner login credential from the environment (container+ # login gate). Idempotent: only creates the owner when no user exists,+ # so restarts and in-app password changes are never clobbered. Reuses+ # the built-in auth (UserAuthService.register -> bcrypt User row) — no+ # new auth code. Set MACHINA_OWNER_EMAIL + MACHINA_OWNER_PASSWORD+ # (password >= 8 chars) via Secret Manager to define the secret login.+ import os as _seed_os++ _owner_email = _seed_os.environ.get("MACHINA_OWNER_EMAIL", "").strip()+ _owner_password = _seed_os.environ.get("MACHINA_OWNER_PASSWORD", "")+ if _owner_email and _owner_password:+ try:+ _user_auth = container.user_auth_service()+ if await _user_auth.get_user_count() == 0:+ _owner_name = _seed_os.environ.get("MACHINA_OWNER_NAME", "Owner")+ _seeded, _seed_err = await _user_auth.register(_owner_email, _owner_password, _owner_name)+ if _seeded is not None:+ logger.info("Seeded owner account from environment", email=_owner_email)+ else:+ logger.error("Owner account seed failed", reason=_seed_err)+ else:+ logger.debug("Owner seed skipped: a user already exists")+ except Exception as _seed_exc: # noqa: BLE001 — seeding must never block startup+ logger.error("Owner account seed raised", error=str(_seed_exc))+# Initialize event waiter with cache service for Redis Streams supportfrom services import event_waiter@@ -647,6 +672,61 @@ async def health_check():}+# ---------------------------------------------------------------------------+# Single-port SPA serving (container / Cloud Run)+# ---------------------------------------------------------------------------+#+# In the containerised deployment one uvicorn process must front the API,+# the WebSocket, AND the built React client on a single port ($PORT). The+# CLI dev/start path serves the client from a separate node static server+# (scripts/serve-client.js), so this block is gated on the dist existing ++# SERVE_STATIC_CLIENT so local ``machina dev`` is unaffected.+#+# Registered LAST so every real API / WS / mounted route above wins; this+# only catches otherwise-unmatched GET paths and returns the SPA shell for+# client-side routing. Non-SPA prefixes return 404 so API misses stay JSON.+import os as _spa_os+from pathlib import Path as _SpaPath+from fastapi.staticfiles import StaticFiles+from fastapi.responses import FileResponse++_CLIENT_DIST = _SpaPath(__file__).resolve().parents[1] / "client" / "dist"+_SERVE_STATIC = _spa_os.environ.get("SERVE_STATIC_CLIENT", "true").lower() in ("1", "true", "yes")+# Path prefixes owned by the backend — never shadowed by the SPA fallback.+_NON_SPA_PREFIXES = ("api/", "ws/", "webhook/", "mcp/", "health", "docs", "redoc", "openapi.json")++if _SERVE_STATIC and (_CLIENT_DIST / "index.html").is_file():+ # The nodejs-compat router registers an informational ``GET /`` JSON shim+ # that would shadow the SPA at the root. In the container the SPA must own+ # "/", so drop that single route before installing the fallback. Its+ # ``/api/*`` routes are untouched.+ from starlette.routing import Route as _Route++ app.router.routes = [+ _r+ for _r in app.router.routes+ if not (isinstance(_r, _Route) and _r.path == "/" and "GET" in (_r.methods or set()))+ ]++ _assets_dir = _CLIENT_DIST / "assets"+ if _assets_dir.is_dir():+ app.mount("/assets", StaticFiles(directory=str(_assets_dir)), name="assets")++ @app.get("/{full_path:path}", include_in_schema=False)+ async def _serve_spa(full_path: str):+ """Serve a built static asset when it exists, else the SPA shell."""+ if full_path.startswith(_NON_SPA_PREFIXES):+ return JSONResponse(status_code=404, content={"detail": "Not Found"})+ candidate = (_CLIENT_DIST / full_path).resolve()+ # is_file() + containment check guard against ``..`` path traversal+ # escaping the build directory.+ if full_path and candidate.is_file() and _CLIENT_DIST in candidate.parents:+ return FileResponse(str(candidate))+ return FileResponse(str(_CLIENT_DIST / "index.html"))++ logger.info("Serving built client from %s", _CLIENT_DIST)++if __name__ == "__main__":import uvicorndiff --git a/server/middleware/auth.py b/server/middleware/auth.pyindex 98198915..194ec327 100644--- a/server/middleware/auth.py+++ b/server/middleware/auth.py@@ -24,8 +24,10 @@ PUBLIC_PATHS = frozenset(])-# Path prefixes that are public-PUBLIC_PREFIXES = ("/webhook/",)+# Path prefixes that are public. ``/mcp/`` is the CLI-agent MCP server, which+# enforces its own per-batch bearer-token auth (cookies don't apply to it), so+# it bypasses this cookie gate.+PUBLIC_PREFIXES = ("/webhook/", "/mcp/")class AuthMiddleware(BaseHTTPMiddleware):@@ -38,6 +40,14 @@ class AuthMiddleware(BaseHTTPMiddleware):if self._is_public_path(path):return await call_next(request)+ # Static SPA shell, built assets, and client-side routes carry no+ # secrets and must load BEFORE login (the SPA renders the login page+ # itself). When the container serves the client on a single port, any+ # GET/HEAD that is not an API or WebSocket call is the SPA — treat it+ # as public. The protected surface (/api/*, /ws/*) stays gated below.+ if request.method in ("GET", "HEAD") and not path.startswith(("/api/", "/ws/")):+ return await call_next(request)+# Get settingssettings = container.settings()