Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(machina): drop pydantic + bootstrap CLI deps from system Python
trohitgd854b2d3e27f
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.ymlindex 19d41541..5983761b 100644--- a/.github/actions/setup/action.yml+++ b/.github/actions/setup/action.yml@@ -43,6 +43,14 @@ runs:shell: bashrun: npm install -g temporal-server+ # machina (the project supervisor CLI at the repo root) is invoked by+ # pnpm scripts as `python -m machina ...` from the runner's system+ # Python. Install its runtime deps eagerly via the root pyproject.toml+ # so the first `pnpm run build` doesn't trip the self-bootstrap path.+ - name: Install machina CLI dependencies+ shell: bash+ run: uv pip install --system -e .+- name: Verify installationsshell: bashrun: |@@ -52,3 +60,4 @@ runs:echo "Python: $(python --version)"echo "uv: $(uv --version)"echo "temporal-server: $(temporal --version 2>/dev/null || echo 'installed')"+ echo "machina: $(python -c 'import machina; print(machina.__version__)' 2>/dev/null || echo 'failed to import')"diff --git a/machina/__main__.py b/machina/__main__.pyindex 3972b1c7..d9ba3472 100644--- a/machina/__main__.py+++ b/machina/__main__.py@@ -1,6 +1,34 @@-"""Entry point for ``python -m machina``."""+"""Entry point for ``python -m machina``.-from machina.cli import app+pnpm scripts call ``python -m machina ...`` from the system Python,+which only has ``uv`` -- not typer / rich / anyio / psutil. On first+run we detect the missing imports, pip-install the declared runtime+deps, and retry, so the user never has to ``pip install -e .`` by hand.+"""++import subprocess+import sys++_RUNTIME_DEPS = (+ "typer>=0.12",+ "rich>=13.0",+ "anyio>=4.0",+ "psutil>=6.0",+)+++def _bootstrap_deps() -> None:+ print("machina: installing runtime dependencies (first run)...", file=sys.stderr)+ subprocess.check_call(+ [sys.executable, "-m", "pip", "install", "--quiet", *_RUNTIME_DEPS]+ )+++try:+ from machina.cli import app+except ImportError:+ _bootstrap_deps()+ from machina.cli import appif __name__ == "__main__":diff --git a/machina/commands/build.py b/machina/commands/build.pyindex d8ec3356..3492f1a4 100644--- a/machina/commands/build.py+++ b/machina/commands/build.py@@ -1,8 +1,8 @@"""``machina build`` -- replaces ``scripts/build.js``.Checks toolchain (node, npm, python, uv, temporal-server), then runs-the 5-step build: ``.env`` bootstrap -> ``pnpm install`` -> client-build -> ``uv sync`` -> Playwright -> verify edgymeow binary.+the 4-step build: ``.env`` bootstrap -> ``pnpm install`` -> client+build -> ``uv sync`` -> verify edgymeow binary.The ``MACHINAOS_BUILDING`` env var is set so ``scripts/postinstall.js``skips its own ``install.js`` invocation when build is the orchestrator.@@ -151,20 +151,12 @@ def build_command() -> None:console.log("[2/5] Building client...")run(["pnpm", "--filter", "react-flow-client", "run", "build"], cwd=root)- console.log("[3/5] Installing Python dependencies...")+ console.log("[3/4] Installing Python dependencies...")if not (server_dir / ".venv").exists():run(["uv", "venv"], cwd=server_dir)run(["uv", "sync"], cwd=server_dir)- console.log("[4/5] Installing Playwright browser...")- rc = run(["playwright", "install", "chromium"], cwd=server_dir, check=False)- if rc != 0:- console.print(- " [yellow]Warning: Playwright browser install failed. "- "JS-rendered scraping unavailable.[/]"- )-- console.log("[5/5] Verifying edgymeow binary...")+ console.log("[4/4] Verifying edgymeow binary...")bin_name = "edgymeow-server.exe" if sys.platform == "win32" else "edgymeow-server"edgymeow_bin = root / "node_modules" / "edgymeow" / "bin" / bin_nameif edgymeow_bin.exists():diff --git a/machina/config.py b/machina/config.pyindex 2c78fb7f..6cbd07c9 100644--- a/machina/config.py+++ b/machina/config.py@@ -1,43 +1,61 @@"""Project configuration -- ports + flags from ``.env``.-Backed by ``pydantic-settings``: typed fields with automatic env-var-coercion, no hand-rolled int/bool parsers. The model loads ``.env``-(or ``.env.template`` as fallback) from the project root.+Stdlib-only env-var loader. ``.env`` is parsed as plain ``KEY=VALUE``+lines (with ``#`` comments and surrounding ``"`` / ``'`` stripped); the+backend has python-dotenv if full shell semantics are needed. Process+env wins over file env, matching the prior pydantic-settings behaviour."""from __future__ import annotations+import os+from dataclasses import dataclassfrom functools import lru_cachefrom pathlib import Path-from pydantic import Field-from pydantic_settings import BaseSettings, SettingsConfigDict-from machina.platform_ import project_root-def _env_file(root: Path) -> Path:- primary = root / ".env"- fallback = root / ".env.template"- return primary if primary.exists() else fallback+def _load_env_file(path: Path) -> dict[str, str]:+ out: dict[str, str] = {}+ if not path.exists():+ return out+ for raw in path.read_text(encoding="utf-8").splitlines():+ line = raw.strip()+ if not line or line.startswith("#") or "=" not in line:+ continue+ key, _, value = line.partition("=")+ value = value.strip()+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):+ value = value[1:-1]+ out[key.strip()] = value+ return out-class Config(BaseSettings):- """Typed view over ``.env``; defaults match the JS ``loadEnvConfig``."""+def _int(env: dict[str, str], key: str, default: int) -> int:+ try:+ return int(env.get(key, default))+ except (ValueError, TypeError):+ return default- model_config = SettingsConfigDict(- env_file_encoding="utf-8",- case_sensitive=False,- extra="ignore",- populate_by_name=True,- )- client_port: int = Field(default=3000, alias="VITE_CLIENT_PORT")- backend_port: int = Field(default=3010, alias="PYTHON_BACKEND_PORT")- whatsapp_port: int = Field(default=9400, alias="WHATSAPP_RPC_PORT")- nodejs_port: int = Field(default=3020, alias="NODEJS_EXECUTOR_PORT")- temporal_address: str = Field(default="localhost:7233", alias="TEMPORAL_SERVER_ADDRESS")- temporal_enabled: bool = Field(default=True, alias="TEMPORAL_ENABLED")+def _bool(env: dict[str, str], key: str, default: bool) -> bool:+ raw = env.get(key)+ if raw is None:+ return default+ return raw.strip().lower() in ("1", "true", "yes", "on")+++@dataclass(frozen=True)+class Config:+ """Typed view over ``.env``; defaults match the JS ``loadEnvConfig``."""++ client_port: int = 3000+ backend_port: int = 3010+ whatsapp_port: int = 9400+ nodejs_port: int = 3020+ temporal_address: str = "localhost:7233"+ temporal_enabled: bool = True@propertydef temporal_port(self) -> int:@@ -60,4 +78,16 @@ class Config(BaseSettings):@lru_cache(maxsize=1)def load_config(root: Path | None = None) -> Config:root = root or project_root()- return Config(_env_file=str(_env_file(root)))+ primary = root / ".env"+ fallback = root / ".env.template"+ file_env = _load_env_file(primary if primary.exists() else fallback)+ env = {**file_env, **os.environ}++ return Config(+ client_port=_int(env, "VITE_CLIENT_PORT", 3000),+ backend_port=_int(env, "PYTHON_BACKEND_PORT", 3010),+ whatsapp_port=_int(env, "WHATSAPP_RPC_PORT", 9400),+ nodejs_port=_int(env, "NODEJS_EXECUTOR_PORT", 3020),+ temporal_address=env.get("TEMPORAL_SERVER_ADDRESS", "localhost:7233"),+ temporal_enabled=_bool(env, "TEMPORAL_ENABLED", True),+ )diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 00000000..58c5b72e--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,21 @@+[project]+name = "machinaos-cli"+version = "0.1.0"+description = "MachinaOS project supervisor CLI (machina)."+requires-python = ">=3.12"+dependencies = [+ "typer>=0.12",+ "rich>=13.0",+ "anyio>=4.0",+ "psutil>=6.0",+]++[project.scripts]+machina = "machina.cli:app"++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["machina"]