Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(paths,oauth,install): unified npm tree, generic-only paths, build/dev parity, OAuth UX fixes
trohitge54145069395
diff --git a/CLAUDE.md b/CLAUDE.mdindex 818c4a93..a64ada4e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5300,7 +5300,7 @@ This function:- **Telegram owner detection — three layers** (f746ddf): the bot owner is captured by THREE independent paths so the realistic setup flows all converge to a working state. (1) **Explicit field**: secondary `FieldDef` in the credentials modal lets the user paste their Telegram user ID directly (recommended; works without DM'ing the bot). (2) **Pre-poll peek** in `connect()` via `_capture_owner_from_pending_updates()` — calls `bot.get_updates(timeout=0)` BEFORE `start_polling(drop_pending_updates=True)` discards the queue, scans for any historical private DM, captures + persists atomically. (3) **Atomic write-through in `_on_message_received`** — persists FIRST, sets in-memory ONLY on success. Invariant: "in-memory has owner ⇒ DB has owner" so a process restart can re-capture cleanly. Failure logged at `ERROR` with `exc_info=True` (was `WARNING` previously, masking persist failures). The lazy fallback in `telegram_send.py` (read DB → `service.set_owner`) sits on top of all three.- **Supervisor Job Object loud-failure (cli/tree.py + cli/supervisor.py)** (8a64eb9): the Windows process-tree mechanism depends entirely on a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (no fallback — `start_new_session` is POSIX-only). `pywin32>=308` is a hard supervisor dependency on Windows; the declaration in the root `pyproject.toml` (where `machinaos-cli` lives — `cli/pyproject.toml` was removed as a stale duplicate) carries an inline comment so future maintainers don't drop it. `_JobObject.__init__` splits failures into explicit `ImportError` (with reinstall command) and `Exception` (with `repr`) branches — both write to `stderr` instead of swallowing. `_JobObject.add()` verifies enrollment via `win32job.IsProcessInJob(handle, self._handle)` after assignment; on mismatch it queries `IsProcessInJob(handle, None)` so the warning explicitly names the wrapper-job hypothesis (npm / pnpm / conhost wrappers occasionally place us in their own non-nesting Job). `supervisor._spawn_once` checks `add_to_job` return value and emits a yellow `WARN: pid=N not enrolled in Job Object` per child if False. Without these guards, a stale pywin32 install or a wrapping Job Object silently leaks orphan Python processes on every Ctrl-C and they accumulate to the point of holding SQLite locks that block subsequent backend startup.- **Credentials envelope-shape invariant** (dc94cde): the `useCredentialPanel` query stores `{values: CredentialFormValues, hadStored: boolean}` (an envelope, NOT a flat dict). The earlier `writeValues` called `setQueryData<CredentialFormValues>` with a spread `(prev) => ({...prev, [key]: value})`, which at runtime merged the typed character at the envelope level next to `values` and `hadStored` instead of inside `.values` — the input selector `panel.values[field.key]` re-rendered with the original (server) value on every keystroke and the input felt frozen. Fix: `writeValues` now preserves the envelope shape and updates only the inner `values` dict; `hadStored` is preserved verbatim (it reflects real server state, not local edits). When introducing other queries shaped as `{data, meta}` envelopes, follow the same pattern — never spread `prev` as if it were the inner payload.-- **`core.paths` is the SSOT for on-disk locations**: everything MachinaOs owns lives under `machina_root()` (= `~/.machina/` per default `DATA_DIR`). Subtree map: `workspaces/<slug>/` (per-workflow scratch), `daemons/` (supervised event-source daemon cwds — `stripe listen` etc.; shared root by default, no per-namespace subdir), `claude/` (Claude Code's `CLAUDE_CONFIG_DIR` state + `claude/npm/` binary install via `claude_npm_dir()`), `packages/<service>/` (downloaded binaries via `package_dir(name)` — `stripe`, `browser`, `temporal`), `whatsapp/` (WhatsApp session DB), `credentials.db` / `workflow.db` / `temporal.db`. Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path("MachinaOs")` (`~/.cache/MachinaOs/` etc.) and the Temporal CLI sat in its own `pooch.os_cache("machinaos-temporal")` namespace — operators reported both as "not local" and the binary-vs-state split bought nothing in practice. Daemon cwds also used to live under `workspaces/_<namespace>/` and polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (Himalaya) and npm `package.json` deps (`edgymeow`). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.machina/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `machina clean` and stay at the same path across `DATA_DIR=~/.machina` vs `DATA_DIR=.machina` configs.+- **`core.paths` is the SSOT for on-disk locations**: only generic helpers (`data_path` / `packages_dir` / `package_dir(name)` / `daemons_dir` / `workspaces_dir` / `workspace_dir(workflow_id)` / `example_workflows_dir`). Plugin-specific subpaths are composed inline at the plugin's call site — adding a new package never requires touching `core.paths`. Reference subtree under `machina_root()` (= `~/.machina/` per default `DATA_DIR`): `workspaces/<slug>/` (per-workflow scratch), `daemons/` (supervised event-source daemon cwds — `stripe listen` etc.; shared root by default, no per-namespace subdir), `claude/` (Claude Code's `CLAUDE_CONFIG_DIR` state — composed as `data_path("claude")` in `nodes/agent/claude_code_agent/_oauth.py`), `packages/` (MachinaOs-managed install root). `packages/` holds a **single shared npm tree** — one `package.json` + `package-lock.json` + `node_modules/` covering every MachinaOs-managed npm package (`@anthropic-ai/claude-code`, `edgymeow`, `agent-browser`). Each plugin's `_install.py` runs `npm install <pkg> --prefix <packages_dir>` which extends the shared tree idempotently; npm manages everything else. Non-npm binaries (Stripe CLI, Temporal CLI) sit under sibling subdirs `packages/stripe/`, `packages/temporal/` via `package_dir(name)`. Also under `<DATA_DIR>/`: `whatsapp/` (WhatsApp session DB), `credentials.db` / `workflow.db` / `temporal.db`. Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path("MachinaOs")` (`~/.cache/MachinaOs/` etc.) and the Temporal CLI sat in its own `pooch.os_cache("machinaos-temporal")` namespace — operators reported both as "not local". The WhatsApp Go bridge (`edgymeow`) used to be a top-level pnpm dep at `<repo>/node_modules/edgymeow/`; now MachinaOs-managed via `nodes/whatsapp/_install.py` like the other CLIs. Daemon cwds used to live under `workspaces/_<namespace>/` and polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (Himalaya — system package manager). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.machina/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `machina clean` and stay at the same path across `DATA_DIR=~/.machina` vs `DATA_DIR=.machina` configs.- **`machina clean` preserves `.machina/workflows/`**: `cli/commands/clean.py` iterates `<repo>/.machina/` children and skips anything in `_MACHINA_KEEP = frozenset({"workflows"})`. Wipes `claude/`, `workspaces/`, `*.db` as before; preserves the shipped seed JSONs so a fresh clone + clean doesn't lose user-importable examples. Test `cli/tests/test_clean.py::test_machina_keep_preserves_workflows` locks the keep-list.- **No raw `print()` outside three sanctioned helpers**: `main._startup_log` (pre-logger boot markers), `core.container._clog` (DI-bootstrap markers), and `nodes.code.python_executor.captured_print` (the sandbox builtin handed to user code). Everything else goes through `logger = get_logger(__name__)`. The supervisor prefixes every aggregated line with `[HH:MM:SS.fff]` so no inner `TimeStamper` is needed; structlog console mode is deliberately timestamp-less. Test `server/tests/test_no_raw_prints.py` AST-walks the tree and flags any unsanctioned `print(...)` call.- **`configure_logging(settings)` must run BEFORE plugin self-registration imports**: in `main.py`, `Settings()` + `configure_logging(settings)` + `init_tracing()` + `get_logger(__name__)` happen ahead of `from core.container import container` and `from routers import …`. Otherwise plugin folders that register on import call `logger.debug(...)` while structlog is still on its default processor chain (which includes `TimeStamper` + no `filter_by_level`) — symptom is double timestamps + debug records leaking despite `LOG_LEVEL=INFO`.diff --git a/cli/commands/build.py b/cli/commands/build.pyindex 688953b2..6aca1cd0 100644--- a/cli/commands/build.py+++ b/cli/commands/build.py@@ -1,8 +1,17 @@"""``machina build`` -- replaces ``scripts/build.js``.-Checks toolchain (node, npm, python, uv, temporal-server), then runs-the 4-step build: ``.env`` bootstrap -> ``pnpm install`` -> client-build -> ``uv sync`` -> verify edgymeow binary.+Checks toolchain (node, npm, python, uv), then runs the 6-step+build: ``.env`` bootstrap -> ``pnpm install`` -> client build ->+Node.js sidecar bundle -> ``uv sync`` -> compile Python bytecode+-> pooch-fetch Temporal binary.++Layers ``.env.dev`` (when present in the checkout) BEFORE running+those steps so the build's ``DATA_DIR`` matches the runtime's+expected location. Without that, ``machina build`` would pooch+Temporal under ``~/.machina/`` and ``machina dev`` would re-fetch+it into ``<repo>/.machina/`` — a redundant download on every fresh+clone. Production (global-install) operators never have+``.env.dev`` in their checkout, so the layering is a no-op there.The ``MACHINAOS_BUILDING`` env var is set so ``scripts/postinstall.js``skips its own ``install.js`` invocation when build is the orchestrator.@@ -97,6 +106,27 @@ def _ensure_uv(python_cmd: str) -> str:def build_command() -> None:root = project_root()+ # Layer ``.env.dev`` (if present) BEFORE the install steps so the+ # build's ``DATA_DIR`` matches what the runtime (``machina dev``)+ # will see. Without this, ``machina build`` reads+ # ``DATA_DIR=~/.machina`` from ``.env.template`` and lands the+ # Temporal CLI under user home, but ``machina dev`` then reads+ # ``DATA_DIR=.machina`` from ``.env.dev`` and re-downloads into+ # ``<repo>/.machina/`` — a cache-miss the operator pays on every+ # fresh checkout.+ #+ # Safe for global installs: ``.env.dev`` is committed to git for+ # repo-clone contributors but is NOT in the npm ``files`` list, so+ # ``npm install -g machinaos`` doesn't ship it. Without+ # ``.env.dev`` on disk, :func:`load_dev_overrides` is a no-op and+ # the build falls through to ``.env.template`` defaults+ # (``DATA_DIR=~/.machina``) — identical to today's behaviour and+ # matching what ``machina start`` / ``machina daemon`` use at+ # runtime.+ from cli.config import load_dev_overrides++ load_dev_overrides(root)+# Prevent the postinstall orchestrator from re-running install.js when# we're orchestrating ourselves (matches the existing JS contract).os.environ["MACHINAOS_BUILDING"] = "true"diff --git a/package.json b/package.jsonindex ed2245fd..b66a4e0c 100644--- a/package.json+++ b/package.json@@ -94,8 +94,7 @@"preuninstall": "node scripts/preinstall.js"},"dependencies": {- "cross-env": "^7.0.3",- "edgymeow": "0.0.20"+ "cross-env": "^7.0.3"},"pnpm": {"peerDependencyRules": {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 614504d1..db197598 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -16,9 +16,6 @@ importers:cross-env:specifier: ^7.0.3version: 7.0.3- edgymeow:- specifier: 0.0.20- version: 0.0.20client:dependencies:@@ -3378,11 +3375,6 @@ packages:resolution: {integrity: sha512-wG99Zcfcys9fZux7Cft8BAX/YrOJLJSZ3jyYPfhZHqN2E+Ffx+QXBDsv3gubEgPtV6dTzJMSQUwk1H98/t/0wQ==}engines: {bun: '>=1', deno: '>=2', node: '>=16'}- resolution: {integrity: sha512-c/3VgIzWAvZa0ffBFdKDwmM0w3zCyGSHILiXDnW6XELWtxFJ/aONAN+xoDzS38hTRKDGTZ1cDRt29Wyi4Vqv5A==}- engines: {node: '>=18.0.0'}- hasBin: true-resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}@@ -3575,10 +3567,6 @@ packages:resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==}engines: {node: '>=10'}- resolution: {integrity: sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==}- engines: {node: '>=16.17'}-resolution: {integrity: sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==}engines: {node: ^18.19.0 || >=20.5.0}@@ -3775,17 +3763,10 @@ packages:resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==}engines: {node: '>=10'}- resolution: {integrity: sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==}- engines: {node: '>=16'}-resolution: {integrity: sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==}engines: {node: '>=18'}- resolution: {integrity: sha512-LRn8Jlk+DwZE4GTlDbT3Hikd1wSHgLMme/+7ddlqKd7ldwR6LjJgTVWzBnR01wnYGe4KgrXjg287RaI22UHmAw==}-resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==}@@ -3934,10 +3915,6 @@ packages:resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==}engines: {node: '>=10.17.0'}- resolution: {integrity: sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==}- engines: {node: '>=16.17.0'}-resolution: {integrity: sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==}engines: {node: '>=18.18.0'}@@ -4094,10 +4071,6 @@ packages:resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}engines: {node: '>=8'}- resolution: {integrity: sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==}- engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}-resolution: {integrity: sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==}engines: {node: '>=18'}@@ -4221,10 +4194,6 @@ packages:resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}- resolution: {integrity: sha512-e0SVOV5jFo0mx8r7bS29maVWp17qGqLBZ5ricNSajON6//kmb7qqqNnml4twNE8Dtj97UQD+gNFOaipS/q1zzQ==}- hasBin: true-resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==}engines: {node: '>=6'}@@ -4644,10 +4613,6 @@ packages:resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==}engines: {node: '>=6'}- resolution: {integrity: sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==}- engines: {node: '>=12'}-resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}engines: {node: '>=18'}@@ -4735,10 +4700,6 @@ packages:resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==}engines: {node: '>=8'}- resolution: {integrity: sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==}- engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}-resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==}engines: {node: '>=18'}@@ -4776,10 +4737,6 @@ packages:resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}engines: {node: '>=6'}- resolution: {integrity: sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==}- engines: {node: '>=12'}-resolution: {integrity: sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==}engines: {node: '>=18'}@@ -5617,9 +5574,6 @@ packages:resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}engines: {node: '>=8'}- resolution: {integrity: sha512-jyVd+kU2X+mWKMmGhx4fpWbPsjvD53k9ivqetutVW/BQ+WIZoDoP4d8vUMGezV6saZsiNoW2f9GIhg9Dondohg==}-resolution: {integrity: sha512-4pz6JGSDmVTTkPJ/ueixHkFAXY4ySCc+unvCaDZV7hqq/sdJZirRxgIXSuNSKgiFlGTgRR97sdu2R8K55sPsrw==}peerDependencies:@@ -5754,10 +5708,6 @@ packages:resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==}engines: {node: '>=6'}- resolution: {integrity: sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==}- engines: {node: '>=12'}-resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==}engines: {node: '>=18'}@@ -9751,13 +9701,6 @@ snapshots:'@noble/curves': 1.9.7'@noble/hashes': 1.8.0- dependencies:- chalk: 5.6.2- commander: 11.1.0- execa: 8.0.1- kill-port: 2.0.1-@@ -10026,18 +9969,6 @@ snapshots:signal-exit: 3.0.7strip-final-newline: 2.0.0- dependencies:- cross-spawn: 7.0.6- get-stream: 8.0.1- human-signals: 5.0.0- is-stream: 3.0.0- merge-stream: 2.0.0- npm-run-path: 5.3.0- onetime: 6.0.0- signal-exit: 4.1.0- strip-final-newline: 3.0.0-dependencies:'@sindresorhus/merge-streams': 4.0.0@@ -10264,15 +10195,11 @@ snapshots:- [email protected]: {}-dependencies:'@sec-ant/readable-stream': 0.4.1is-stream: 4.0.1- [email protected]: {}-dependencies:resolve-pkg-maps: 1.0.0@@ -10516,8 +10443,6 @@ snapshots:- [email protected]: {}-@@ -10622,8 +10547,6 @@ snapshots:- [email protected]: {}-@@ -10747,11 +10670,6 @@ snapshots:- dependencies:- get-them-args: 1.3.2- shell-exec: 1.0.2-@@ -11451,8 +11369,6 @@ snapshots:- [email protected]: {}-@@ -11538,10 +11454,6 @@ snapshots:dependencies:path-key: 3.1.1- dependencies:- path-key: 4.0.0-dependencies:path-key: 4.0.0@@ -11571,10 +11483,6 @@ snapshots:dependencies:mimic-fn: 2.1.0- dependencies:- mimic-fn: 4.0.0-dependencies:mimic-function: 5.0.1@@ -12717,8 +12625,6 @@ snapshots:- [email protected]: {}-dependencies:'@shikijs/core': 3.23.0@@ -12846,8 +12752,6 @@ snapshots:- [email protected]: {}-diff --git a/server/core/database.py b/server/core/database.pyindex 3eaad65f..1b7c0f0d 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -114,7 +114,7 @@ class Database:logger.info("Added memory_window_size column to user_settings")if "compaction_ratio" not in columns:- await conn.execute(text("ALTER TABLE user_settings ADD COLUMN compaction_ratio REAL DEFAULT 0.5"))+ await conn.execute(text("ALTER TABLE user_settings ADD COLUMN compaction_ratio REAL DEFAULT 0.8"))logger.info("Added compaction_ratio column to user_settings")if "default_llm_provider" not in columns:@@ -1586,66 +1586,34 @@ class Database:return Noneasync def save_user_settings(self, settings_data: Dict[str, Any], user_id: str = "default") -> bool:- """Save or update user settings."""+ """Save or update user settings.++ Both branches now read field names off ``UserSettings.model_fields``+ instead of duplicating each setting's name + default. Adding a new+ field to :class:`UserSettings` no longer requires touching this+ method, and the SQLModel field's ``Field(default=...)`` is the+ single source of truth for the default value.+ """try:async with self.get_session() as session:- # Try to get existing settingsstmt = select(UserSettings).where(UserSettings.user_id == user_id)result = await session.execute(stmt)existing = result.scalar_one_or_none()+ # Filter incoming dict to known model fields. ``user_id`` and+ # the bookkeeping columns (id / created_at / updated_at) are+ # never overridden through this path.+ _MANAGED = {"id", "user_id", "created_at", "updated_at"}+ known_fields = set(UserSettings.model_fields.keys()) - _MANAGED+ payload = {k: v for k, v in settings_data.items() if k in known_fields}+if existing:- # Update existing settings- if "auto_save" in settings_data:- existing.auto_save = settings_data["auto_save"]- if "auto_save_interval" in settings_data:- existing.auto_save_interval = settings_data["auto_save_interval"]- if "sidebar_default_open" in settings_data:- existing.sidebar_default_open = settings_data["sidebar_default_open"]- if "component_palette_default_open" in settings_data:- existing.component_palette_default_open = settings_data["component_palette_default_open"]- if "console_panel_default_open" in settings_data:- existing.console_panel_default_open = settings_data["console_panel_default_open"]- if "memory_window_size" in settings_data:- existing.memory_window_size = settings_data["memory_window_size"]- if "compaction_ratio" in settings_data:- existing.compaction_ratio = settings_data["compaction_ratio"]- if "examples_loaded" in settings_data:- existing.examples_loaded = settings_data["examples_loaded"]- if "onboarding_completed" in settings_data:- existing.onboarding_completed = settings_data["onboarding_completed"]- if "onboarding_step" in settings_data:- existing.onboarding_step = settings_data["onboarding_step"]- if "default_llm_provider" in settings_data:- existing.default_llm_provider = settings_data["default_llm_provider"]- if "default_llm_model" in settings_data:- existing.default_llm_model = settings_data["default_llm_model"]- if "auto_add_skill_for_tools" in settings_data:- existing.auto_add_skill_for_tools = settings_data["auto_add_skill_for_tools"]- if "auto_rebind_tools_after_canvas_change" in settings_data:- existing.auto_rebind_tools_after_canvas_change = settings_data["auto_rebind_tools_after_canvas_change"]- if "agent_recursion_limit" in settings_data:- existing.agent_recursion_limit = settings_data["agent_recursion_limit"]+ for key, value in payload.items():+ setattr(existing, key, value)else:- # Create new settings- existing = UserSettings(- user_id=user_id,- auto_save=settings_data.get("auto_save", True),- auto_save_interval=settings_data.get("auto_save_interval", 30),- sidebar_default_open=settings_data.get("sidebar_default_open", True),- component_palette_default_open=settings_data.get("component_palette_default_open", True),- console_panel_default_open=settings_data.get("console_panel_default_open", False),- memory_window_size=settings_data.get("memory_window_size", 100),- compaction_ratio=settings_data.get("compaction_ratio", 0.5),- examples_loaded=settings_data.get("examples_loaded", False),- onboarding_completed=settings_data.get("onboarding_completed", False),- onboarding_step=settings_data.get("onboarding_step", 0),- default_llm_provider=settings_data.get("default_llm_provider"),- default_llm_model=settings_data.get("default_llm_model"),- auto_add_skill_for_tools=settings_data.get("auto_add_skill_for_tools", True),- auto_rebind_tools_after_canvas_change=settings_data.get("auto_rebind_tools_after_canvas_change", True),- agent_recursion_limit=settings_data.get("agent_recursion_limit", 200),- )+ # SQLModel field defaults (``Field(default=...)``) apply+ # for every key the caller did not explicitly pass.+ existing = UserSettings(user_id=user_id, **payload)session.add(existing)await session.commit()diff --git a/server/core/paths.py b/server/core/paths.pyindex fdba0e9f..5164e0f5 100644--- a/server/core/paths.py+++ b/server/core/paths.py@@ -12,55 +12,57 @@ same machine share state instead of each carrying its own copy. The``~/.machina/`` convention matches Stripe's ``~/.config/stripe/``,ngrok's ``~/.ngrok2/``, and claude code's own ``~/.claude/``.-State layout under ``~/.machina/`` (flat, no redundant nesting):-- - ``~/.machina/claude/`` Claude Code's CLAUDE_CONFIG_DIR- state + ``claude/npm/`` binary install- - ``~/.machina/workspaces/`` per-workflow scratch dirs (one- subdir per ``Workflow.slug``)- - ``~/.machina/daemons/`` cwd root for supervised event-source- daemons (``stripe listen``, …);- shared across all daemons by- default to avoid empty per-namespace- subdirs- - ``~/.machina/packages/`` downloaded service binaries- (``stripe``, ``browser``)- - ``~/.machina/whatsapp/`` persistent WhatsApp session DB- - ``~/.machina/credentials.db`` Fernet-encrypted secrets- - ``~/.machina/workflow.db`` SQLite app DB- - ``~/.machina/temporal.db`` Temporal server SQLite (flat under- DATA_DIR like the other ``*.db``)--Binaries that MachinaOs downloads on first use (Stripe CLI,-``agent-browser``'s npm tree, ``@anthropic-ai/claude-code``) all-live under ``<DATA_DIR>/`` — the same operator-visible tree as-auth state, workspaces, and daemon cwds:-- - Stripe CLI: ``<DATA_DIR>/packages/stripe/bin/stripe[.exe]``- - agent-browser: ``<DATA_DIR>/packages/browser/npm/``- - Claude Code: ``<DATA_DIR>/claude/npm/`` (sibling of- ``CLAUDE_CONFIG_DIR`` at ``<DATA_DIR>/claude/`` — see- :func:`claude_npm_dir`)--Supervised event-source daemons (``stripe listen``, future plugins)-keep their cwd under :func:`daemons_dir` (``<DATA_DIR>/daemons/-<namespace>/``) — a sibling of :func:`workspaces_dir` so per-workflow-scratch (workspaces) is never mixed with framework state (daemons).--The split that pre-fix routed binaries through+Generic subtree layout under ``<DATA_DIR>/`` (= ``~/.machina/`` by+default). The module exports only generic helpers — plugin-specific+subpaths (``<DATA_DIR>/claude/``, ``<DATA_DIR>/packages/stripe/bin/``,+etc.) are composed at the plugin's call site, NOT hardcoded here.+That keeps this module from growing one helper per package:++ - :func:`data_path` ``<DATA_DIR>/<subpath>`` — universal state-path+ primitive every plugin composes against+ - :func:`packages_dir` ``<DATA_DIR>/packages/`` — downloaded-binary root+ - :func:`package_dir` ``<DATA_DIR>/packages/<name>/`` — per-service install+ slot (callers compose further, e.g.+ ``package_dir("claude") / "npm"``)+ - :func:`daemons_dir` ``<DATA_DIR>/daemons/`` — supervised daemon cwds+ - :func:`workspaces_dir` ``<DATA_DIR>/workspaces/`` — per-workflow scratch+ - :func:`workspace_dir` ``<DATA_DIR>/workspaces/<workflow_id>/``+ - :func:`example_workflows_dir` git-tracked seed JSONs at+ ``<repo>/.machina/workflows/`` (NOT under DATA_DIR)++Reference layout once typical plugins compose against the helpers+above (Wave 14):++ - ``<DATA_DIR>/claude/`` Claude Code auth state (CLAUDE_CONFIG_DIR)+ - ``<DATA_DIR>/packages/`` Single shared MachinaOs install+ root. Holds one ``package.json`` + ``package-lock.json`` ++ ``node_modules/`` covering every MachinaOs-managed npm package+ (``@anthropic-ai/claude-code``, ``edgymeow``, ``agent-browser``).+ Each plugin's ``_install.py`` runs+ ``npm install <pkg> --prefix <packages_dir>`` to extend the tree+ idempotently — npm itself manages the dep graph.+ - ``<DATA_DIR>/packages/stripe/`` Stripe CLI binary (non-npm)+ - ``<DATA_DIR>/packages/temporal/`` Temporal CLI binary (non-npm,+ pooch-managed)+ - ``<DATA_DIR>/workspaces/<slug>/`` per-workflow scratch+ - ``<DATA_DIR>/daemons/`` supervised daemon cwds (shared root)+ - ``<DATA_DIR>/whatsapp/`` persistent WhatsApp session DB+ - ``<DATA_DIR>/credentials.db`` Fernet-encrypted secrets+ - ``<DATA_DIR>/workflow.db`` SQLite app DB+ - ``<DATA_DIR>/temporal.db`` Temporal server SQLite++The pre-fix layout split binaries under:func:`platformdirs.user_cache_path` (``~/.cache/MachinaOs/`` etc.)-turned out to confuse operators ("not local") without buying anything-in practice — both ``machina clean`` and a manual cache wipe are-operator-driven anyway. Single subtree wins for inspection,-backup, and reasoning about disk usage.+and Temporal under its own ``pooch.os_cache("machinaos-temporal")``+namespace — operators reported both as "not local". Daemon cwds+also used to live under ``workspaces/_<namespace>/`` and polluted+per-workflow scratch with framework state. Consolidating everything+under ``<DATA_DIR>/`` means a single ``mv ~/.machina /backup``+carries the entire MachinaOs footprint.-The Temporal CLI binary lands at ``<DATA_DIR>/packages/temporal/``-too (pooch-managed; see ``services/temporal/_install.py``).--Out of scope: Himalaya (``cargo`` / ``brew`` system install) and-npm packages declared in ``package.json`` whose binaries pnpm-manages directly under ``node_modules/`` (e.g. ``whatsapp-rpc``'s-``edgymeow``).+Out of scope: globally-installed binaries (Himalaya — system+package manager) and npm `package.json` deps managed by pnpm (none+remain after the WhatsApp migration).Shipped example workflows live at ``<repo>/.machina/workflows/`` —git-tracked seed JSONs auto-imported on first launch by@@ -70,10 +72,11 @@ gitignored. ``example_workflows_dir()`` resolves to that fixed seedlocation regardless of ``DATA_DIR`` — operators do NOT relocate theshipped seeds.-Importable as ``from core.paths import claude_config_dir, workspace_dir, …``-so consumers never have to recompute the root themselves (the old-``Path(__file__).resolve().parents[N] / "data" / ...`` idiom was-duplicated across 4+ files and brittle to file moves).+Importable as ``from core.paths import data_path, package_dir,+workspace_dir, …`` so consumers never have to recompute the root+themselves (the old ``Path(__file__).resolve().parents[N] / "data"+/ ...`` idiom was duplicated across 4+ files and brittle to file+moves).DATA_DIR resolution rules (see :func:`machina_root`):@@ -200,33 +203,6 @@ def package_dir(name: str) -> Path:return packages_dir() / name-def claude_config_dir() -> Path:- """``CLAUDE_CONFIG_DIR`` for spawned claude subprocesses.-- Resolves to ``<DATA_DIR>/claude/``. Single source of truth for- the plugin's ``MACHINA_CLAUDE_DIR`` constant (re-exported from- ``nodes/agent/claude_code_agent/_oauth.py`` for back-compat).- Stores OAuth tokens + session state — distinct from- :func:`claude_npm_dir`, which holds the downloaded CLI binary.- """- return data_path("claude")---def claude_npm_dir() -> Path:- """Where ``npm install @anthropic-ai/claude-code`` lands.-- Resolves to ``<DATA_DIR>/claude/npm/`` — sibling of- :func:`claude_config_dir` (the OAuth state dir, exposed to the- CLI via ``CLAUDE_CONFIG_DIR``). Keeps the entire claude footprint- (binary + auth state + IDE lockfiles + session JSONL) under one- operator-visible tree, so a single ``mv ~/.machina/claude /backup``- carries everything claude needs. Deliberate exception to the- binary-vs-state split documented on :func:`packages_dir` — see- the module docstring.- """- return data_path("claude") / "npm"--def daemons_dir() -> Path:"""Root for supervised event-source daemons (``stripe listen``, etc.).@@ -281,41 +257,14 @@ def example_workflows_dir() -> Path:return project_root() / ".machina" / "workflows"-def whatsapp_dir() -> Path:- """Persistent WhatsApp session DB / state dir.-- Routes through ``data_path(Settings().whatsapp_data_subdir)``- (env var ``WHATSAPP_DATA_SUBDIR``) so the WhatsApp tree moves- with ``DATA_DIR``.- """- from core.config import Settings-- return data_path(Settings().whatsapp_data_subdir)---def credentials_db_path() -> Path:- """Encrypted credentials store (Fernet + PBKDF2).-- Routes through ``data_path(Settings().credentials_db_path)`` (env- var ``CREDENTIALS_DB_PATH``) so the DB moves with ``DATA_DIR``.- """- from core.config import Settings-- return data_path(Settings().credentials_db_path)--__all__ = ["project_root","machina_root","data_path","packages_dir","package_dir",- "claude_config_dir",- "claude_npm_dir","daemons_dir","workspaces_dir","workspace_dir","example_workflows_dir",- "whatsapp_dir",- "credentials_db_path",]diff --git a/server/nodes/agent/claude_code_agent/_oauth.py b/server/nodes/agent/claude_code_agent/_oauth.pyindex cc41dec0..1a31a8b5 100644--- a/server/nodes/agent/claude_code_agent/_oauth.py+++ b/server/nodes/agent/claude_code_agent/_oauth.py@@ -1,13 +1,16 @@"""Claude OAuth — project-local install + the documented `claude auth` subcommands.-The Claude Code CLI lives at ``<machina_root>/claude/npm/`` (on-demand-``npm install`` on first use, mirroring the WhatsApp project-local layout).-``CLAUDE_CONFIG_DIR`` points at ``<machina_root>/claude/`` so the CLI-manages its own credentials inside the project tree, isolated from the-user's own ``~/.claude/`` session. Path resolution is centralised in-:mod:`core.paths` — this module just re-exports the constants for-back-compat with consumers that still ``import MACHINA_CLAUDE_DIR``-directly.+The Claude Code CLI lives in the shared MachinaOs npm tree at+``<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]`` (on-demand+``npm install`` on first use, alongside ``edgymeow`` /+``agent-browser`` — one ``package.json`` + ``package-lock.json``+managed by npm itself). ``CLAUDE_CONFIG_DIR`` points at+``<DATA_DIR>/claude/`` so the CLI manages its own credentials+inside the project tree, isolated from the user's own+``~/.claude/`` session. The path constants here are composed+against the generic ``core.paths`` helpers (``data_path`` /+``packages_dir``) — see the module docstring on ``core.paths`` for+the no-per-plugin-wrapper convention.Every subprocess call goes through ``services.events.cli.run_cli_command``— the canonical one-shot CLI helper used by Stripe / future plugins. Auth@@ -31,6 +34,7 @@ import ``MACHINA_CLAUDE_DIR`` from here.from __future__ import annotations+import asyncioimport jsonimport osimport shutil@@ -39,20 +43,30 @@ import sysfrom typing import Any, Dictfrom core.logging import get_logger-from core.paths import claude_config_dir, claude_npm_dir+from core.paths import data_path, packages_dirfrom services.events.cli import run_cli_commandlogger = get_logger(__name__)-# Single source of truth for path resolution lives in ``core.paths``;-# we re-export as module constants so existing imports-# (``from ._oauth import MACHINA_CLAUDE_DIR``) keep working without a-# function-call indirection at every call site. Call ``machina_root``-# / ``claude_config_dir`` at module load — Settings is already-# initialised by the time this module is first imported (node registry-# discovery runs after the FastAPI app is built).-MACHINA_CLAUDE_DIR = claude_config_dir()-MACHINA_NPM_DIR = claude_npm_dir()+# Plugin-specific subpaths composed inline against the generic+# ``core.paths`` helpers — keeps ``core.paths`` from growing one+# wrapper function per plugin. Re-exported as module constants so+# existing consumers (``from ._oauth import MACHINA_CLAUDE_DIR``)+# keep working without a function-call indirection at every call+# site. ``data_path`` / ``packages_dir`` evaluate eagerly here:+# Settings is already initialised by the time this module is first+# imported (node registry discovery runs after the FastAPI app is+# built).+#+# ``MACHINA_CLAUDE_DIR`` -> ``<DATA_DIR>/claude/`` auth state+# (CLAUDE_CONFIG_DIR)+# ``MACHINA_NPM_ROOT`` -> ``<DATA_DIR>/packages/`` shared npm tree+# (``--prefix`` target;+# also holds+# ``edgymeow`` /+# ``agent-browser``)+MACHINA_CLAUDE_DIR = data_path("claude")+MACHINA_NPM_ROOT = packages_dir()# Generous timeout for browser-flow login; Stripe uses the same window.LOGIN_TIMEOUT_SECONDS = 600.0@@ -66,24 +80,27 @@ def claude_binary_path() -> str:Single source of truth shared by the auth handler (``_handlers.py``)AND the agent spawn (``_provider.py``) so both surfaces use thesame binary + ``CLAUDE_CONFIG_DIR``-isolated credentials.++ Landed under the shared MachinaOs npm tree at+ ``MACHINA_NPM_ROOT`` (= ``<DATA_DIR>/packages/``) so a single+ ``package.json`` + ``package-lock.json`` covers claude /+ edgymeow / agent-browser."""- if sys.platform == "win32":- bin_path = MACHINA_NPM_DIR / "node_modules" / ".bin" / "claude.cmd"- else:- bin_path = MACHINA_NPM_DIR / "node_modules" / ".bin" / "claude"+ bin_name = "claude.cmd" if sys.platform == "win32" else "claude"+ bin_path = MACHINA_NPM_ROOT / "node_modules" / ".bin" / bin_nameif bin_path.exists():return str(bin_path)- logger.info("Installing Claude Code CLI in project-local environment...")- MACHINA_NPM_DIR.mkdir(parents=True, exist_ok=True)+ logger.info("Installing Claude Code CLI into shared tree %s", MACHINA_NPM_ROOT)+ MACHINA_NPM_ROOT.mkdir(parents=True, exist_ok=True)npm_cmd = shutil.which("npm")if not npm_cmd:raise FileNotFoundError("npm not found on PATH")result = subprocess.run(- [npm_cmd, "install", "@anthropic-ai/claude-code", "--prefix", str(MACHINA_NPM_DIR)],+ [npm_cmd, "install", "@anthropic-ai/claude-code", "--prefix", str(MACHINA_NPM_ROOT)],capture_output=True,text=True,)@@ -107,7 +124,17 @@ def _claude_env() -> Dict[str, str]:async def _run_auth(subcommand: str, *, timeout: float) -> Dict[str, Any]:"""Run ``claude auth <subcommand>`` via the canonical helper. Returnsthe ``run_cli_command`` envelope (``{success, result, stdout, stderr,- error}``)."""+ error}``).++ ``login`` is spawned with ``stdin=PIPE`` (un-written) so the native+ claude binary's stdin reader blocks indefinitely instead of EOFing+ against the FastAPI parent's closed stdin. Without this guard the+ CLI exits before the browser hits its localhost callback URL and+ the success page never renders — see ``run_cli_command``'s+ ``stdin`` parameter doc for the full failure mode. ``status`` and+ ``logout`` are one-shot, don't read stdin, and stay on the+ inherit-stdin default.+ """try:binary = claude_binary_path()except (FileNotFoundError, RuntimeError) as e:@@ -119,6 +146,7 @@ async def _run_auth(subcommand: str, *, timeout: float) -> Dict[str, Any]:argv=["auth", subcommand],timeout=timeout,env=_claude_env(),+ stdin=asyncio.subprocess.PIPE if subcommand == "login" else None,)logger.info("[claude auth %s] success=%s stdout=%r stderr=%r",diff --git a/server/nodes/browser/_install.py b/server/nodes/browser/_install.pyindex c16aadda..abcec406 100644--- a/server/nodes/browser/_install.py+++ b/server/nodes/browser/_install.py@@ -1,9 +1,12 @@-"""``agent-browser`` local install — mirrors ``claude_binary_path``.+"""``agent-browser`` local install — landed in the shared MachinaOs+npm tree at :func:`core.paths.packages_dir` (``<DATA_DIR>/packages/``).-Same pattern as ``nodes/agent/claude_code_agent/_oauth.py``: ``npm-install <pkg> --prefix <package_dir("browser")/npm>`` on first call,-return the resolved binary path. No coupling to the workspace-``package.json``.+All MachinaOs-managed npm packages (``agent-browser``,+``@anthropic-ai/claude-code``, ``edgymeow``) live under a single+``<packages_dir>/node_modules/`` so npm manages them with one+``package.json`` + ``package-lock.json`` rather than us carving out+per-service install trees. ``npm install <pkg> --prefix <packages_dir>``+extends the shared tree idempotently."""from __future__ import annotations@@ -14,7 +17,7 @@ import sysfrom typing import Optionalfrom core.logging import get_logger-from core.paths import package_dir+from core.paths import packages_dirlogger = get_logger(__name__)@@ -23,9 +26,9 @@ _NPM_SPEC = "agent-browser@latest"def agent_browser_binary_path() -> Optional[str]:"""Return path to the agent-browser CLI, installing on miss."""- npm_root = package_dir("browser") / "npm"+ root = packages_dir()bin_name = "agent-browser.cmd" if sys.platform == "win32" else "agent-browser"- bin_path = npm_root / "node_modules" / ".bin" / bin_name+ bin_path = root / "node_modules" / ".bin" / bin_nameif bin_path.exists():return str(bin_path)@@ -35,10 +38,10 @@ def agent_browser_binary_path() -> Optional[str]:logger.warning("[browser] npm not on PATH; cannot install %s", _NPM_SPEC)return None- logger.info("[browser] installing %s into %s", _NPM_SPEC, npm_root)- npm_root.mkdir(parents=True, exist_ok=True)+ logger.info("[browser] installing %s into shared tree %s", _NPM_SPEC, root)+ root.mkdir(parents=True, exist_ok=True)result = subprocess.run(- [npm_cmd, "install", _NPM_SPEC, "--prefix", str(npm_root), "--no-audit", "--no-fund"],+ [npm_cmd, "install", _NPM_SPEC, "--prefix", str(root), "--no-audit", "--no-fund"],capture_output=True,text=True,)diff --git a/server/nodes/stripe/_handlers.py b/server/nodes/stripe/_handlers.pyindex 69497c46..2f22a58c 100644--- a/server/nodes/stripe/_handlers.py+++ b/server/nodes/stripe/_handlers.py@@ -181,7 +181,15 @@ async def handle_stripe_login(data: Dict[str, Any], websocket: WebSocket) -> Dicinfo.get("verification_code"),_LOGIN_TIMEOUT_SECONDS,)- asyncio.create_task(_complete_login(binary, complete_url))+ # Snapshot the existing config.toml mtime BEFORE step 2 spawns so+ # ``_complete_login`` can tell whether THIS attempt wrote new+ # credentials, vs. a stale file from a previous login. Without+ # this, ``is_logged_in()`` returns True for any non-empty config —+ # even if the current browser flow was never completed — and the+ # handler falsely reports "auth successful".+ cfg = stripe_config_path()+ pre_mtime = cfg.stat().st_mtime if cfg.exists() else 0.0+ asyncio.create_task(_complete_login(binary, complete_url, pre_mtime))return {"success": True,"url": url,@@ -189,12 +197,30 @@ async def handle_stripe_login(data: Dict[str, Any], websocket: WebSocket) -> Dic}-async def _complete_login(binary: str, next_step: str) -> None:+async def _complete_login(binary: str, next_step: str, pre_mtime: float) -> None:"""Step 2: block on ``stripe login --complete`` until the userauthorises (or the 10-min timeout fires). On success, write thesame kind of marker the Google / Twitter callbacks write so thecatalogue's stored-check flips, then auto-start the listen- daemon and trigger the generic catalogue refresh on the frontend."""+ daemon and trigger the generic catalogue refresh on the frontend.++ ``pre_mtime`` is the mtime of ``config.toml`` (0.0 if absent)+ captured at step 1 — the only reliable signal of whether THIS+ flow wrote fresh credentials. Both signals taken in isolation+ lie:++ * ``result.success`` — ``stripe login --complete`` is known to+ exit 1 with ``stderr='exceeded max attempts'`` even after a+ successful write. Don't trust the exit code alone.+ * ``is_logged_in()`` — only checks for the presence of+ ``_api_key`` in the config file, which returns True for any+ prior login (even on a fresh attempt the user never finished).+ Don't trust on-disk presence alone.++ Mtime comparison is the disambiguator: if the file's mtime is+ strictly greater than ``pre_mtime``, the CLI wrote it during+ THIS step 2, so the auth genuinely succeeded.+ """logger.info("[Stripe] login step 2/2 polling for browser confirmation")try:result = await run_cli_command(@@ -208,24 +234,41 @@ async def _complete_login(binary: str, next_step: str) -> None:logger.exception("[Stripe] login step 2 raised unexpectedly: %s", e)return- if not result.get("success"):+ cli_success = bool(result.get("success"))+ cfg = stripe_config_path()+ post_mtime = cfg.stat().st_mtime if cfg.exists() else 0.0+ fresh_credentials_written = post_mtime > pre_mtime and is_logged_in()++ if not fresh_credentials_written:+ if not cli_success:+ logger.warning(+ "[Stripe] login step 2 CLI failure: %s | stderr=%r",+ result.get("error"),+ (result.get("stderr") or "")[:300],+ )logger.warning(- "[Stripe] login step 2 CLI failure: %s | stderr=%r",- result.get("error"),- (result.get("stderr") or "")[:300],+ "[Stripe] step 2 finished but no fresh credentials written to %s "+ "(pre_mtime=%.3f post_mtime=%.3f) — user likely closed the browser "+ "before authorising",+ cfg,+ pre_mtime,+ post_mtime,)+ return- if not is_logged_in():- logger.warning(- "[Stripe] step 2 finished but ``is_logged_in()`` is False — config file %s missing/empty; "- "user likely closed the browser before authorising",- stripe_config_path(),+ # Fresh credentials present. ``cli_success`` may still be False+ # because of Stripe's "exceeded max attempts" stderr quirk — the+ # mtime advance is the ground truth.+ if not cli_success:+ logger.debug(+ "[Stripe] step 2 CLI exited non-zero but credentials WERE written — "+ "treating as success (known Stripe CLI stderr quirk). stderr=%r",+ (result.get("stderr") or "")[:300],)- returnlogger.info("[Stripe] auth successful — credentials written to %s; persisting catalogue marker + starting listen daemon",- stripe_config_path(),+ cfg,)await _mark_logged_in()logger.info("[Stripe] catalogue marker token persisted (auth_service.store_oauth_tokens)")diff --git a/server/nodes/whatsapp/_install.py b/server/nodes/whatsapp/_install.pynew file mode 100644index 00000000..541ce78b--- /dev/null+++ b/server/nodes/whatsapp/_install.py@@ -0,0 +1,71 @@+"""``edgymeow`` (WhatsApp Go bridge) local install — landed in the+shared MachinaOs npm tree at :func:`core.paths.packages_dir`+(``<DATA_DIR>/packages/``).++All MachinaOs-managed npm packages (``edgymeow``,+``@anthropic-ai/claude-code``, ``agent-browser``) share a single+``<packages_dir>/node_modules/`` so npm manages them with one+``package.json`` + ``package-lock.json``. ``npm install <pkg>+--prefix <packages_dir>`` extends the shared tree idempotently.++Pre-fix this lived as a top-level ``edgymeow`` dep in the root+``package.json`` and landed at ``<repo>/node_modules/edgymeow/`` via+``pnpm install``. Operators had to re-run ``pnpm install`` after+``machina clean`` to recover. After this move, the WhatsApp binary+follows the same on-demand install pattern as every other+MachinaOs-managed CLI.+"""++from __future__ import annotations++import shutil+import subprocess+import sys+from typing import Optional++from core.logging import get_logger+from core.paths import packages_dir++logger = get_logger(__name__)++# Pinned for reproducible WhatsApp Go-bridge ABI. Bump when the+# bridge's WebSocket / event schema changes.+_NPM_SPEC = "[email protected]"+++def edgymeow_binary_path() -> Optional[str]:+ """Return path to the edgymeow Go binary, installing on miss.++ Returns ``None`` if npm is not on PATH or the install failed —+ callers should surface this as a user-visible error (the runtime+ can't spawn without it). Idempotent: subsequent calls hit the+ existing binary on disk.+ """+ root = packages_dir()+ bin_name = "edgymeow-server.exe" if sys.platform == "win32" else "edgymeow-server"+ bin_path = root / "node_modules" / "edgymeow" / "bin" / bin_name++ if bin_path.exists():+ return str(bin_path)++ npm_cmd = shutil.which("npm")+ if not npm_cmd:+ logger.warning("[whatsapp] npm not on PATH; cannot install %s", _NPM_SPEC)+ return None++ logger.info("[whatsapp] installing %s into shared tree %s", _NPM_SPEC, root)+ root.mkdir(parents=True, exist_ok=True)+ result = subprocess.run(+ [npm_cmd, "install", _NPM_SPEC, "--prefix", str(root), "--no-audit", "--no-fund"],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0 or not bin_path.exists():+ logger.error("[whatsapp] npm install failed: %s", result.stderr.strip())+ return None++ logger.info("[whatsapp] edgymeow installed at %s", bin_path)+ return str(bin_path)+++__all__ = ["edgymeow_binary_path"]diff --git a/server/nodes/whatsapp/_runtime.py b/server/nodes/whatsapp/_runtime.pyindex 39a4b069..022ebae3 100644--- a/server/nodes/whatsapp/_runtime.py+++ b/server/nodes/whatsapp/_runtime.py@@ -2,8 +2,18 @@Spawns the binary with cwd inside the project (``<data_dir>/whatsapp``)so the SQLite session DB lives next to ``credentials.db`` and survives-``pnpm install``, version bumps, and worktree switches. Lazy-init from-``nodes.whatsapp._service.get_client()``; teardown from FastAPI lifespan.+``machina clean``, version bumps, and worktree switches. Lazy-init+from ``nodes.whatsapp._service.get_client()``; teardown from FastAPI+lifespan.++The binary itself is MachinaOs-managed under the shared MachinaOs+npm tree at ``<DATA_DIR>/packages/`` (resolved by+:func:`._install.edgymeow_binary_path` on first use). The install+runs through ``asyncio.to_thread`` in ``_pre_spawn`` so the long+``npm install`` (~30 s) doesn't block the asyncio event loop —+otherwise the ``StatusBroadcaster._refresh_all_services`` startup+fan-out monopolises the loop during boot and uvicorn can't bind+port 3010.Subclasses :class:`BaseProcessSupervisor` for spawning, tree-kill, statussnapshots, restart policy, and the singleton ``get_instance()`` accessor.@@ -12,15 +22,17 @@ Plugin-specific surface here is just binary discovery + config patching.from __future__ import annotations+import asyncioimport osimport sysfrom pathlib import Pathimport yaml+from core.paths import packages_dirfrom services._supervisor import BaseProcessSupervisor-_PROJECT_ROOT = Path(__file__).resolve().parents[3]+from ._install import edgymeow_binary_pathclass WhatsAppRuntime(BaseProcessSupervisor):@@ -65,7 +77,12 @@ class WhatsAppRuntime(BaseProcessSupervisor):@propertydef _package_dir(self) -> Path:- return (_PROJECT_ROOT / "node_modules" / "edgymeow").resolve()+ # ``edgymeow`` is npm-installed into the shared MachinaOs npm+ # tree at ``<DATA_DIR>/packages/node_modules/edgymeow/`` by+ # :func:`._install.edgymeow_binary_path` (called from+ # ``_pre_spawn``). Same tree holds ``claude-code``,+ # ``agent-browser``, etc. — one package.json + lockfile.+ return packages_dir() / "node_modules" / "edgymeow"# ---- BaseProcessSupervisor overrides ---------------------------------@@ -74,7 +91,6 @@ class WhatsAppRuntime(BaseProcessSupervisor):if override:return Path(override).resolve()name = "edgymeow-server.exe" if sys.platform == "win32" else "edgymeow-server"- # pnpm symlinks node_modules/edgymeow -> .pnpm/edgymeow@<v>/.../edgymeowreturn self._package_dir / "bin" / namedef argv(self) -> list[str]:@@ -89,6 +105,19 @@ class WhatsAppRuntime(BaseProcessSupervisor):async def _pre_spawn(self) -> None:if not getattr(self.settings, "whatsapp_runtime_enabled", True):raise RuntimeError("WhatsApp runtime disabled via WHATSAPP_RUNTIME_ENABLED")+ # Run the (potentially long) ``npm install edgymeow`` off the+ # asyncio event loop. ``edgymeow_binary_path`` is sync and+ # blocks on ``subprocess.run`` for the duration of the install;+ # without this offload the startup ``_refresh_all_services``+ # fan-out monopolises the loop for ~30 s and uvicorn can't+ # bind port 3010 (port-probe times out in the supervisor).+ # Idempotent — instant return when the binary already exists.+ resolved = await asyncio.to_thread(edgymeow_binary_path)+ if resolved is None:+ raise RuntimeError(+ "WhatsApp runtime install failed: npm not on PATH or `npm install edgymeow` "+ "did not produce the expected binary. See log for details."+ )self._write_config()def _extra_status(self) -> dict:diff --git a/server/services/events/cli.py b/server/services/events/cli.pyindex 9cc9affe..7cf678eb 100644--- a/server/services/events/cli.py+++ b/server/services/events/cli.py@@ -23,12 +23,28 @@ async def run_cli_command(api_key_arg: str = "--api-key",timeout: float = 30.0,env: Optional[Dict[str, str]] = None,+ stdin: Optional[int] = None,) -> Dict[str, Any]:"""Run ``<binary> <argv> [api_key_arg <key>]`` once, return parsed JSON.``env``: optional process environment override. When None, the childinherits the parent's environment (asyncio default).+ ``stdin``: optional override for the child's stdin handle. ``None``+ (default) inherits the parent's stdin — what most one-shot CLI+ invocations want. Pass :data:`asyncio.subprocess.PIPE` (left+ un-written) when the CLI reads stdin during the run and the parent+ has no usable stdin — without it, the CLI sees immediate EOF and+ can exit prematurely. Concrete case: ``claude auth login`` (native+ binary, 2.1.162+) reads stdin while waiting for the browser+ callback; under the FastAPI daemon (no TTY, closed stdin) the CLI+ EOFs, exits, and kills its localhost callback server — the+ browser's ``http://localhost:<port>/callback?code=…`` redirect+ then hits a dead socket and the success page never renders, even+ though credentials were written before exit. ``stdin=PIPE`` makes+ the read block forever, keeping the callback server alive until+ the CLI naturally exits after rendering its response.+Returns a uniform envelope:{"success": bool, "result": parsed-JSON-or-None,"stdout": str, "stderr": str, "error": str or None}@@ -54,6 +70,7 @@ async def run_cli_command(try:proc = await asyncio.create_subprocess_exec(*full_argv,+ stdin=stdin,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,env=env,diff --git a/server/tests/conftest.py b/server/tests/conftest.pyindex 656bc575..0e7c61c7 100644--- a/server/tests/conftest.py+++ b/server/tests/conftest.py@@ -102,7 +102,7 @@ _make_submodule("core", "cache", {"CacheService": MagicMock})# real ``Path.home()`` lookup during test collection. Tests that# actually exercise on-disk behaviour use ``tempfile.TemporaryDirectory``# locally; the stub just keeps import-time ``MACHINA_CLAUDE_DIR =-# claude_config_dir()`` calls from blowing up.+# data_path("claude")`` calls from blowing up._TEST_MACHINA_ROOT = Path(__file__).parent / "_test_machina_root"_make_submodule("core",@@ -110,16 +110,13 @@ _make_submodule({"project_root": lambda: _TEST_MACHINA_ROOT.parent,"machina_root": lambda: _TEST_MACHINA_ROOT,+ "data_path": lambda sub="": _TEST_MACHINA_ROOT / sub if sub else _TEST_MACHINA_ROOT,"packages_dir": lambda: _TEST_MACHINA_ROOT / "packages","package_dir": lambda name: _TEST_MACHINA_ROOT / "packages" / name,- "claude_config_dir": lambda: _TEST_MACHINA_ROOT / "claude",- "claude_npm_dir": lambda: _TEST_MACHINA_ROOT / "claude" / "npm","daemons_dir": lambda: _TEST_MACHINA_ROOT / "daemons","workspaces_dir": lambda: _TEST_MACHINA_ROOT / "workspaces","workspace_dir": lambda wf: _TEST_MACHINA_ROOT / "workspaces" / wf,"example_workflows_dir": lambda: _TEST_MACHINA_ROOT / "workflows",- "whatsapp_dir": lambda: _TEST_MACHINA_ROOT / "whatsapp",- "credentials_db_path": lambda: _TEST_MACHINA_ROOT / "credentials.db",},)