Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs: refresh path/OAuth/settings claims after the v0.0.88 refactor
trohitg62086926380d
diff --git a/CLAUDE.md b/CLAUDE.mdindex a64ada4e..f376e6a4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -119,8 +119,8 @@ server/services/├── skill_prompt.py # Skill system prompt builder (injects SKILL.md for personality skills)├── text.py # TextService (text generation nodes)├── chat_client.py # JSON-RPC 2.0 WebSocket client for chat backend-├── claude_code_service.py # Claude Code CLI wrapper (--max-budget-usd, session persistence)-├── claude_oauth.py # Isolated Claude CLI auth (~/.claude-machina, no main-session impact)+│ # (Claude Code CLI wrapper + isolated OAuth moved to+│ # nodes/agent/claude_code_agent/_oauth.py — CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/)├── tracked_http.py # HTTPX event hooks for automatic API cost tracking├── whatsapp_service.py # WhatsApp RPC proxy helpers (used by nodes/whatsapp/*, not an APIRouter)├── handlers/ # Cross-cutting orchestration only (Wave 11: 16 → 4 files, 12.8K → 1.1K LOC)@@ -169,7 +169,7 @@ server/core/├── cache.py # CacheService with Redis/SQLite/Memory fallback├── config.py # Application configuration├── logging.py # Logging configuration-├── paths.py # SSOT for on-disk locations: machina_root()/workspaces_dir()/whatsapp_dir() under ~/.machina/; packages_dir()/package_dir(name) via platformdirs (OS cache) for downloaded binaries; example_workflows_dir() = <repo>/.machina/workflows/ (shipped seeds, NOT under DATA_DIR)+├── paths.py # SSOT for on-disk locations (generic helpers only): machina_root()/data_path()/workspaces_dir()/workspace_dir()/daemons_dir() + packages_dir()/package_dir(name) all under ~/.machina/ (= DATA_DIR); packages/ holds the single shared npm tree + stripe/ + temporal/ binary subdirs; example_workflows_dir() = <repo>/.machina/workflows/ (shipped seeds, NOT under DATA_DIR). Plugin-specific subpaths composed inline at the call site, never added here.├── encryption.py # Fernet encryption with PBKDF2 key derivation├── credentials_database.py # Async SQLite for encrypted API keys and OAuth tokens└── credential_backends.py # Multi-backend abstraction (Fernet, Keyring, AWS)@@ -1402,7 +1402,7 @@ Interactive browser automation via the [agent-browser](https://www.npmjs.com/pac| `server/services/handlers/browser.py` | Handler dispatcher mapping operation+params to agent-browser CLI args || `server/skills/web_agent/browser-skill/SKILL.md` | AI agent skill documenting snapshot-act-snapshot loop |-**Installation Requirement:** `agent-browser` is MachinaOs-managed (NOT a `package.json` dep). On first browser-node invocation, [`server/nodes/browser/_install.py::agent_browser_binary_path`](../server/nodes/browser/_install.py) runs `npm install agent-browser@latest --prefix <package_dir("browser")/npm>` then `<bin> install` for the Chromium runtime. Same shape as [`claude_binary_path`](../server/nodes/agent/claude_code_agent/_oauth.py) (the precedent). Cache root: [`core.paths.packages_dir()`](../server/core/paths.py) → `~/.cache/MachinaOs/browser/` on Linux, `~/Library/Caches/MachinaOs/browser/` on macOS, `%LOCALAPPDATA%\MachinaOs\Cache\browser\` on Windows (XDG-conventional via `platformdirs.user_cache_path`).+**Installation Requirement:** `agent-browser` is MachinaOs-managed (NOT a `package.json` dep). On first browser-node invocation, [`server/nodes/browser/_install.py::agent_browser_binary_path`](../server/nodes/browser/_install.py) runs `npm install agent-browser@latest --prefix <packages_dir()>` then `<bin> install` for the Chromium runtime. Same shape as [`claude_binary_path`](../server/nodes/agent/claude_code_agent/_oauth.py) (the precedent) — both land in the single shared npm tree at [`core.paths.packages_dir()`](../server/core/paths.py) = `<DATA_DIR>/packages/` (= `~/.machina/packages/` by default), resolving to `~/.machina/packages/node_modules/.bin/agent-browser[.cmd]`. Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path` (`~/.cache/MachinaOs/`, `~/Library/Caches/MachinaOs/`, `%LOCALAPPDATA%\MachinaOs\Cache\`); it now sits under DATA_DIR with everything else MachinaOs owns.**Implementation Detail:** `browser_service.py` invokes the resolved binary directly via `subprocess.Popen([binary, ...args], shell=False)`. Reads only the first JSON output line from agent-browser (the daemon holds stdout open), truncates at 100KB, and kills the process tree via `psutil`. `shell=False` with list argv avoids BatBadBut (CVE-2024-1874) on Windows; `npm` itself is located via `shutil.which("npm")` which honours `PATHEXT` for the `.cmd` shim.@@ -2030,7 +2030,7 @@ Each workflow execution gets a persistent workspace directory where nodes save o**Configuration** (`server/core/config.py`):```python-workspace_base_dir: str = Field(default="data/workspaces", env="WORKSPACE_BASE_DIR")+workspace_base_dir: str = Field(default="workspaces", env="WORKSPACE_BASE_DIR") # resolved under DATA_DIR -> ~/.machina/workspaces/```**How it works:**@@ -3528,7 +3528,7 @@ I don't have access to real-time weather data...### claude_code_agent bridge — `--continue` + warm subprocess pool (NOT markdown injection)-When `simpleMemory` is connected to `claude_code_agent`, memory continuity is handled by claude itself — the agent does NOT re-inject markdown as a system prompt. Claude stores per-session transcripts under `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl` where `project_key = re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))` (verified against the on-disk `data/claude-machina/projects/` listing).+When `simpleMemory` is connected to `claude_code_agent`, memory continuity is handled by claude itself — the agent does NOT re-inject markdown as a system prompt. Claude stores per-session transcripts under `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl` where `project_key = re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))` (verified against the on-disk `<DATA_DIR>/claude/projects/` listing; `CLAUDE_CONFIG_DIR = data_path("claude")`).**The three coupled mechanisms** (see [docs-internal/cli_agent_framework.md → Memory bridge](./docs-internal/cli_agent_framework.md#memory-bridge--simplememory--claude_code_agent) for full plumbing):@@ -3550,7 +3550,7 @@ When `simpleMemory` is connected to `claude_code_agent`, memory continuity is ha**Strict tool allowlist — no claude built-ins (except conditional `Skill`), gated by `--permission-mode dontAsk`.** The spawn argv emits `--permission-mode dontAsk` (documented as *"only pre-approved tools, no prompts"* per [code.claude.com/docs/en/permission-modes](https://code.claude.com/docs/en/permission-modes)) so `--allowedTools` is actually enforced. The previous default `bypassPermissions` *"skips the permission layer entirely"* — same doc — which turned the allowlist into documentation-only and let claude's built-in `Read` / `Edit` / `Bash` / `Glob` / `Grep` / `Write` / `Skill` / `WebSearch` / `WebFetch` fire regardless of wiring. The new `--allowedTools` list contains exactly: (a) one `mcp__machinaos__<node_type>` per node wired through the agent's `input-tools` handle, (b) the claude built-in `Skill` **conditionally** — only when at least one skill is wired through `input-skill` (paired with the materialisation helper below; never enabled when no skill is connected), (c) the five MachinaOs MCP infrastructure tools (`getWorkspaceFiles`, `listSkills`, `getSkill`, `getCredential`, `broadcastLog`). Every filesystem / shell / web operation flows through wired MCP tools (`fileRead` / `fileModify` / `fsSearch` / `shell` / `browser` / `perplexitySearch`) — explicit wiring, no built-in escape hatches. Defaults live in [`server/config/ai_cli_providers.json`](./server/config/ai_cli_providers.json) (`default_allowed_tools: ""`, `default_permission_mode: "dontAsk"`); per-task override via `ClaudeTaskSpec.allowed_tools` is honored verbatim (no auto-merge).-**Skill materialisation — per-workflow workspace, live-watched, diff-based.** [`nodes/agent/claude_code_agent/_skills.py::materialise_skills`](./server/nodes/agent/claude_code_agent/_skills.py) writes connected-AND-enabled SKILL.md trees under `<workspace_dir>/.claude/skills/<name>/` where `workspace_dir = data/workspaces/<workflow_slug>/`. The workspace is passed via `--add-dir`, and claude scans `.claude/skills/` inside every `--add-dir` path per [the skills spec's "Automatic discovery from parent and nested directories" rule](https://code.claude.com/docs/en/skills#automatic-discovery-from-parent-and-nested-directories) — gives us per-workflow isolation (workflow A's skills can't bleed into workflow B's subprocess even when both spawn with `cwd=repo_root`). Pool tracks the materialised set in `PooledClaudeSession.materialised_skills: frozenset[str]`; on warm reuse, `acquire` calls `materialise_skills(workspace_dir, new_set, previous_skill_names=session.materialised_skills)` and the helper applies only the diff — `rmtree`'d skills disappear from claude's registry, new ones become invocable, all without respawning. Claude's [live filesystem watcher](https://code.claude.com/docs/en/skills#live-change-detection) picks up both edge events. Same helper drives both pool path and `AICliSession._pre_spawn` (non-pool) — uniform behaviour across transports. **Migration note**: pre-cutover the pool path wrote into `<repo_root>/.claude/skills/` so SKILL.md trees accumulated in the user's actual repo (gitignored but visible). Run `rm -rf .claude/skills/` once from the repo root to clean accumulated trees; future runs only write into per-workflow workspaces. We deliberately do NOT auto-prune because the repo's `.claude/` may contain user-authored skills outside the MachinaOs registry. **Architecture rationale**: surveyed alternatives — MCP `resources`/`prompts` require `@mention`/`/command` (not auto-loaded), hooks fire after skill discovery, `settings.json` doesn't expose per-session paths. Anthropic's own [Agent SDK Skills](https://code.claude.com/docs/en/agent-sdk/skills) uses the same filesystem-first pattern. Workspace-dir + live-watch is canonical.+**Skill materialisation — per-workflow workspace, live-watched, diff-based.** [`nodes/agent/claude_code_agent/_skills.py::materialise_skills`](./server/nodes/agent/claude_code_agent/_skills.py) writes connected-AND-enabled SKILL.md trees under `<workspace_dir>/.claude/skills/<name>/` where `workspace_dir = <DATA_DIR>/workspaces/<workflow_slug>/`. The workspace is passed via `--add-dir`, and claude scans `.claude/skills/` inside every `--add-dir` path per [the skills spec's "Automatic discovery from parent and nested directories" rule](https://code.claude.com/docs/en/skills#automatic-discovery-from-parent-and-nested-directories) — gives us per-workflow isolation (workflow A's skills can't bleed into workflow B's subprocess even when both spawn with `cwd=repo_root`). Pool tracks the materialised set in `PooledClaudeSession.materialised_skills: frozenset[str]`; on warm reuse, `acquire` calls `materialise_skills(workspace_dir, new_set, previous_skill_names=session.materialised_skills)` and the helper applies only the diff — `rmtree`'d skills disappear from claude's registry, new ones become invocable, all without respawning. Claude's [live filesystem watcher](https://code.claude.com/docs/en/skills#live-change-detection) picks up both edge events. Same helper drives both pool path and `AICliSession._pre_spawn` (non-pool) — uniform behaviour across transports. **Migration note**: pre-cutover the pool path wrote into `<repo_root>/.claude/skills/` so SKILL.md trees accumulated in the user's actual repo (gitignored but visible). Run `rm -rf .claude/skills/` once from the repo root to clean accumulated trees; future runs only write into per-workflow workspaces. We deliberately do NOT auto-prune because the repo's `.claude/` may contain user-authored skills outside the MachinaOs registry. **Architecture rationale**: surveyed alternatives — MCP `resources`/`prompts` require `@mention`/`/command` (not auto-loaded), hooks fire after skill discovery, `settings.json` doesn't expose per-session paths. Anthropic's own [Agent SDK Skills](https://code.claude.com/docs/en/agent-sdk/skills) uses the same filesystem-first pattern. Workspace-dir + live-watch is canonical.**Warm-subprocess tool-surface rebind — no respawn cost.** Claude bakes the MCP bearer token into argv (`--mcp-config`) at spawn time and can't rotate without respawning. The pool stashes the spawn-time token on `PooledClaudeSession.batch_token` so subsequent batches can rebind the same persistent `BatchContext` in place. On warm reuse, `ClaudeSessionPool.acquire` calls [`rebind_batch(existing.batch_token, connected_tools=new_ctx.connected_tools, ...)`](./server/services/cli_agent/mcp_server.py) — diffs old vs new tool lists, calls `unexpose_workflow_tools(removed)` to decrement FastMCP refcounts (so a disconnected `duckduckgoSearch` falls off the tool list when its refcount hits zero), `expose_workflow_tools(added)` for newly-wired ones, then unregisters the redundant new token. `_terminate_locked` calls `unregister_batch(session.batch_token)` so refcounts drain on pool eviction / `clear` / `shutdown_all` (closes the long-standing leak where every pooled run permanently incremented every wired tool's refcount). The per-handler scope check in `workflow_tools._build_handler` reads `ctx.connected_tools` at call time, so even if claude's frozen `--allowedTools` argv still references a now-disconnected tool, the handler returns `{"error": "...not connected to this batch", "status": 403}` — double-lock against tool leakage across warm-reuse turns.@@ -3694,7 +3694,7 @@ result = await svc.track(model="claude-opus-4.6",usage={"input_tokens": 5000, "output_tokens": 1000, "total_tokens": 6000})-# result: {"total": 6000, "total_cost": 0.021, "threshold": 500000, "needs_compaction": False}+# result: {"total": 6000, "total_cost": 0.021, "threshold": 800000, "needs_compaction": False} (80% of 1M)# Record compaction event after native API handles itawait svc.record(@@ -3702,14 +3702,14 @@ await svc.record(node_id="agent-1",provider="anthropic",model="claude-opus-4.6",- tokens_before=505000,+ tokens_before=805000,tokens_after=15000,summary="Compacted conversation summary...")# Get session statistics (model-aware threshold when model/provider given)stats = await svc.stats("user-123", model="claude-opus-4.6", provider="anthropic")-# {"session_id": "user-123", "total": 15000, "threshold": 500000, "count": 1}+# {"session_id": "user-123", "total": 15000, "threshold": 800000, "count": 1} (80% of 1M)# Configure per-session custom threshold (overrides model-aware threshold)await svc.configure("user-123", threshold=50000, enabled=True)@@ -5274,7 +5274,7 @@ This function:- **writeTodos Tool Node**: Dedicated AI tool for task planning connecting to any agent's `input-tools` handle. `TodoService` singleton (`server/services/todo_service.py`) stores JSON-based per-session todo state keyed by workflow_id. Handler broadcasts `phase: "todo_update"` via WebSocket on each update for real-time UI; `formatTodoOutput()` in `OutputDisplayPanel.tsx` renders the result as a checklist with `[ ]` / `[~]` / `[x]` icons. Schema uses `TodoItem`/`TodoStatus` Pydantic enum. Skill at `server/skills/assistant/write-todos-skill/SKILL.md` teaches the plan-work-update loop.- **Temporal Activity Heartbeats**: Activities send `activity.heartbeat()` on every non-matching WebSocket broadcast inside the read loop in `services/temporal/activities.py`. This keeps long-running browser and claude_code_agent operations alive past the 2-minute `heartbeat_timeout`. Start/end heartbeats alone were causing `TIMEOUT_TYPE_HEARTBEAT` failures on ops taking 5-10 minutes. Connection config: `heartbeat=30`, `receive_timeout=540` (fits within 10-min `start_to_close_timeout`).- **WebSocket `_safe_send` Guard**: `server/routers/websocket.py` checks `websocket.client_state.name != "CONNECTED"` before sending and logs at `debug` level (not `error`) on failure. Prevents "ASGI message after websocket.close" errors when broadcasts race with disconnects.-- **Claude Code CLI Flag**: `server/services/claude_code_service.py` uses `--max-budget-usd <amount>` (previously incorrectly `--max-cost`, which caused "unknown option" errors on every run).+- **Claude Code CLI Flag**: the Claude Code agent (`nodes/agent/claude_code_agent/`) uses `--max-budget-usd <amount>` (previously incorrectly `--max-cost`, which caused "unknown option" errors on every run).- **Persisted-prefix cache contract**: `PersistQueryClientProvider` hydrates entries with the QueryClient's *default* options, so any prefix in `PERSISTED_KEY_PREFIXES` (`client/src/lib/queryPersist.ts`) MUST also have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in `client/src/lib/queryClient.ts`. Per-call options don't apply on hydration. Canonical set: `nodeSpec`, `nodeGroups`, `skillContent`. `credentialValues` was previously persisted here but was removed per OWASP HTML5 Security Cheat Sheet / ASVS V9.9 — decrypted API keys must never live in `localStorage`. The in-memory TanStack Query cache (`gcTime: ∞`) keeps the credentials form populated for the session lifetime; on reload the panel refetches via WS. `credentialCatalogue` has its own `idb-keyval` warm-start path so it is intentionally not in either list.- **WebSocket `sendRequest` replay queue**: when the socket is not open, requests enqueue with `AbortController`-backed per-request timeouts (default 30s) and replay on reconnect inside `ws.onopen` before `setIsReady(true)`. Queue capped at 200 with FIFO eviction. Intentional close (`event.code === 1000`) drops the queue; transient closes preserve it. Eliminates indefinite spinners during the 3s reconnect window. Implementation in `client/src/contexts/WebSocketContext.tsx` (`pendingSendQueueRef` + `drainPendingSends`).- **`currentWorkflowId` single source**: lives in `useAppStore.currentWorkflow.id` only. Non-React listeners (WS handlers) read via `useAppStore.getState().currentWorkflow?.id` -- the documented Zustand escape hatch. The push to `nodeStatusStore.setCurrentWorkflowId` is driven from one `useEffect` in `Dashboard.tsx`. Removed the prior `currentWorkflowIdRef` mirror inside WebSocketContext that misrouted broadcasts during workflow switches.diff --git a/docs-internal/DESIGN.md b/docs-internal/DESIGN.mdindex d0e120e2..e51de5f8 100644--- a/docs-internal/DESIGN.md+++ b/docs-internal/DESIGN.md@@ -451,7 +451,7 @@ class ExecutionContext:edges: List[Dict] # Edge definitions# Workspace (per-workflow filesystem for nodes and agents)- workspace_dir: str # Absolute path to data/workspaces/<workflow_slug>/+ workspace_dir: str # Absolute path to <DATA_DIR>/workspaces/<workflow_slug>/# (Wave 14 — keyed by the human-readable slug,# not the UUID id; see CLAUDE.md "Workflow Naming")diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.mdindex 642b1d5f..f63e94cd 100644--- a/docs-internal/SCRIPTS.md+++ b/docs-internal/SCRIPTS.md@@ -56,7 +56,7 @@ Run with `npm run <script>` from the project root.| `python:start` | `cd server && uv run uvicorn main:app ...` | Start Python backend || `temporal:worker` | `cd server && uv run python -m services.temporal.worker` | Start standalone Temporal worker |-Temporal server lifecycle is managed by `machina start` / `machina dev` / `machina stop` directly (see [Temporal Architecture](./TEMPORAL_ARCHITECTURE.md)). The official `temporal` CLI is downloaded by `pooch` to a per-OS cache during `machina build` and spawned as a supervised subprocess.+Temporal server lifecycle is managed by `machina start` / `machina dev` / `machina stop` directly (see [Temporal Architecture](./TEMPORAL_ARCHITECTURE.md)). The official `temporal` CLI is downloaded by `pooch` to `<DATA_DIR>/packages/temporal/` (= `~/.machina/packages/temporal/` by default) during `machina build` and spawned as a supervised subprocess.### Docker Scripts (Development)diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex dfdc8190..b192c4b7 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -471,7 +471,7 @@ The Temporal binary + persistence are managed in-process by the plugin-folder pa**What runs**: one process — `temporal server start-dev --port 7233 --ui-port 8080 --db-filename ~/.machina/temporal.db --namespace default`. Both gRPC + Web UI bind to the same process (per docs.temporal.io/cli/server — "all running in a single process"). SQLite-backed durability; history persisted across restarts.**Modern libs doing the heavy lifting** (zero custom infrastructure code):-- **[`pooch`](https://pypi.org/project/pooch/)** — `services/temporal/_install.py` downloads the official `temporal` CLI archive from `https://temporal.download/cli/archive/latest?platform=<os>&arch=<arch>`. Cross-platform (Windows zip / macOS+Linux tar.gz), XDG-cached via `pooch.os_cache("machinaos-temporal")`. Standalone entry: `python -m services.temporal._install` (invoked by `machina build` step [6/6] so first `machina start` doesn't pay the ~114 MB download).+- **[`pooch`](https://pypi.org/project/pooch/)** — `services/temporal/_install.py` downloads the official `temporal` CLI archive from `https://temporal.download/cli/archive/latest?platform=<os>&arch=<arch>`. Cross-platform (Windows zip / macOS+Linux tar.gz), cached at `<DATA_DIR>/packages/temporal/` via `_cache_dir() = core.paths.package_dir("temporal")` (pooch's `path=` argument). Standalone entry: `python -m services.temporal._install` (invoked by `machina build` step [6/6] so first `machina start` doesn't pay the ~114 MB download). Pre-fix this used `pooch.os_cache("machinaos-temporal")` (`~/.cache/MachinaOs/machinaos-temporal/` etc.) — a separate OS-cache namespace operators reported as "not local"; it now sits under DATA_DIR alongside the Stripe binary and the shared npm tree.- **`BaseProcessSupervisor` + `BaseSupervisor`** (`server/services/_supervisor/`) — the in-house supervisor base classes that `server/nodes/whatsapp/_runtime.py` also uses. Provides cross-platform signal handling (POSIX `setsid` + Windows Job Objects + `CREATE_NEW_PROCESS_GROUP` for graceful `CTRL_BREAK_EVENT` shutdown), restart policy via tenacity, log draining, status snapshots. We subclass both — zero custom supervisor logic.**ServiceSpec wiring**: [`cli/commands/_temporal_specs.py`](../cli/commands/_temporal_specs.py) returns one ServiceSpec for the supervised Temporal dev server (env reads happen inside `temporal_specs()` at call time, safe to import before `cli.config.load_config()` runs). Both `start.py` and `dev.py` call it. The generic supervised-runtime shim lives at [`server/services/temporal/_supervised_runtime.py`](../server/services/temporal/_supervised_runtime.py) so the spawned `uv run python -m services.temporal._supervised_runtime services.temporal._runtime:get_temporal_server_runtime` resolves out of the workspace `.venv` without any cross-tree path plumbing.@@ -482,7 +482,7 @@ The Temporal binary + persistence are managed in-process by the plugin-folder pa**Port management**: Temporal owns ports 7233 (gRPC) + 8080 (Web UI). Both bound by the same `temporal.exe` process; both listed in `cli.config.Config.all_ports` so `machina stop`'s port-freeing pre-flight covers them.-**Direct CLI access**: the pooch-installed `temporal` binary lives under `~/.cache/MachinaOs/machinaos-temporal/` (Linux) / `~/Library/Caches/MachinaOs/machinaos-temporal/` (macOS) / `%LOCALAPPDATA%\MachinaOs\Cache\machinaos-temporal\` (Windows). Run `temporal --version`, `temporal workflow list`, etc. directly from there.+**Direct CLI access**: the pooch-installed `temporal` binary lives under `<DATA_DIR>/packages/temporal/` (= `~/.machina/packages/temporal/` by default, on every OS). Run `temporal --version`, `temporal workflow list`, etc. directly from there.**Cluster tunables** — all sourced from `.env.template` (canonical defaults; no Python-side fallbacks). Settings fields with `Field(env="...")` require the env var to be present, surfaced via `cli.config.load_config()`'s `.env.template` → `.env` → `os.environ` merge.@@ -512,8 +512,8 @@ One supervisor-build-time env var (read inside `_temporal_specs.py`, not in `Set# Temporal Web UIopen http://localhost:8080-# List workflows via the local CLI binary (under platformdirs cache)-~/.cache/MachinaOs/machinaos-temporal/.../temporal.exe workflow list --address localhost:7233+# List workflows via the local CLI binary (under <DATA_DIR>/packages/temporal/)+~/.machina/packages/temporal/.../temporal.exe workflow list --address localhost:7233# Re-fetch the binary at any timeuv run python -m services.temporal._installdiff --git a/docs-internal/claude_code_env_vars_reference.md b/docs-internal/claude_code_env_vars_reference.mdindex 3f13fd03..6ef52a93 100644--- a/docs-internal/claude_code_env_vars_reference.md+++ b/docs-internal/claude_code_env_vars_reference.md@@ -119,7 +119,7 @@ sets or relies on.| Variable | Purpose ||---|---|-| `CLAUDE_CONFIG_DIR` | Override the root config directory. Defaults to `~/.claude/`. **MachinaOs sets this** to `<repo>/data/claude-machina` so credentials are project-local — see `services/claude_oauth.py:MACHINA_CLAUDE_DIR`. This is the directory under which claude's session JSONL lives at `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl`. |+| `CLAUDE_CONFIG_DIR` | Override the root config directory. Defaults to `~/.claude/`. **MachinaOs sets this** to `<DATA_DIR>/claude/` (= `~/.machina/claude/` by default) so credentials are project-local and isolated from the user's own `~/.claude/` session — see `nodes/agent/claude_code_agent/_oauth.py:MACHINA_CLAUDE_DIR` (`= data_path("claude")`). This is the directory under which claude's session JSONL lives at `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl`. The npm-installed CLI binary is separate, in the shared tree at `<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]`. || `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` | Default prefix for auto-generated Remote Control session names. |## Timeoutsdiff --git a/docs-internal/cli_agent_canonical_patterns_rfc.md b/docs-internal/cli_agent_canonical_patterns_rfc.mdindex c1aa3773..886233ef 100644--- a/docs-internal/cli_agent_canonical_patterns_rfc.md+++ b/docs-internal/cli_agent_canonical_patterns_rfc.md@@ -391,7 +391,7 @@ cwd + UUID5/last_session_id round-trip. Documented in[cli_agent_framework.md → Memory bridge](./cli_agent_framework.md#memory-bridge--simplememory--claude_code_agent).**Project-key derivation verified empirically** by listing-`data/claude-machina/projects/` on disk and reproducing each name from+`<DATA_DIR>/claude/projects/` on disk and reproducing each name fromits source cwd via `re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))`. Threesample names matched byte-for-byte:diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.mdindex 3dbfa56b..f795ddcd 100644--- a/docs-internal/cli_agent_framework.md+++ b/docs-internal/cli_agent_framework.md@@ -4,7 +4,7 @@ Multi-instance, multi-provider runtime for AI CLI agents (Claude Code, Codex, Ge| Provider | Status | Login flow ||---|---|---|-| Claude Code (`@anthropic-ai/claude-code`) | shipping | Local-install + spawn (`nodes/agent/claude_code_agent/_oauth.py:initiate_claude_oauth`) |+| Claude Code (`@anthropic-ai/claude-code`) | shipping | Shared-tree install + spawn (`nodes/agent/claude_code_agent/_oauth.py:run_claude_login`) || OpenAI Codex (`@openai/codex`) | shipping (no login flow yet) | User runs `codex login` manually; UI returns a graceful "not yet wired" error || Google Gemini (`@google/gemini-cli`) | v2 stub | factory raises `NotImplementedError` |@@ -49,7 +49,7 @@ Reuses (do not duplicate):- `services/skill_loader.py` — `scan_skills` / `load_skill` consumed by MCP `listSkills` / `getSkill`- `services/auth.py` — `AuthService.get_api_key` consumed by MCP `getCredential`- `services/credential_registry.py` — deep-merge `extends` for `_cli_base` entry-- `nodes/agent/claude_code_agent/_oauth.py` — Claude `auth login` / `auth status` / `auth logout` wrappers, project-local npm install at `~/.machina/claude/npm/`, inherited stdio so the CLI opens the browser itself+- `nodes/agent/claude_code_agent/_oauth.py` — Claude `auth login` / `auth status` / `auth logout` wrappers, npm install into the shared MachinaOs tree at `<DATA_DIR>/packages/` (binary resolves to `<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]`), `CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/`. The `login` spawn passes `stdin=PIPE` (un-written) so the native CLI's stdin reader blocks instead of EOFing — keeps its localhost OAuth callback server alive until the browser flow completes- `nodes/stripe/_handlers.py` — pattern reference for marker-token + catalogue broadcast## Provider abstraction (mirrors `services/llm/`)@@ -98,7 +98,7 @@ the interactive billing bucket (entrypoint `claude-vscode`, NOT`sdk-cli`) since `-p` / `--print` is never emitted.```-~/.machina/claude/npm/node_modules/.bin/claude[.cmd]+~/.machina/packages/node_modules/.bin/claude[.cmd]--output-format stream-json # events on stdout--input-format stream-json # user turns to stdin as JSON--verbose # required with stream-json for full event detail@@ -218,14 +218,14 @@ CLI auth is delegated to the CLI's own login flow + a synthetic marker token inSteps:1. Run `claude auth status`. If it exits 0, write the marker + broadcast and return immediately (idempotent re-click).-2. Otherwise call `services.claude_oauth.initiate_claude_oauth()`:- - Project-local install of `@anthropic-ai/claude-code` into `~/.machina/claude/npm/` via `npm install --prefix` (mirrors WhatsApp's `<repo>/node_modules/edgymeow/` layout; skipped if already installed).- - `asyncio.create_subprocess_exec(claude, "auth", "login", env={..., CLAUDE_CONFIG_DIR=<repo>/data/claude-machina})` with **inherited stdio** — same way the VSCode Claude Code extension delegates to the binary. Anthropic doesn't expose `--print-url` or a programmatic OAuth helper (issue [anthropics/claude-code#7100](https://github.com/anthropics/claude-code/issues/7100), closed "not planned"), so we let the CLI open the user's browser via its own OS-level call. Returns `{success: True, pid}` immediately.+2. Otherwise schedule `_finalize_claude_login()` (in `nodes/agent/claude_code_agent/_handlers.py`), which calls `run_claude_login()` from `_oauth.py`:+ - MachinaOs-managed install of `@anthropic-ai/claude-code` into the shared npm tree at `<DATA_DIR>/packages/` via `npm install --prefix <packages_dir>` (same tree as `edgymeow` / `agent-browser`; skipped if already installed). Binary resolves to `<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]`.+ - `claude auth login` via `run_cli_command(..., env={..., CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/}, stdin=asyncio.subprocess.PIPE)` — same way the VSCode Claude Code extension delegates to the binary. Anthropic doesn't expose `--print-url` or a programmatic OAuth helper (issue [anthropics/claude-code#7100](https://github.com/anthropics/claude-code/issues/7100), closed "not planned"), so we let the CLI open the user's browser via its own OS-level call. `stdin=PIPE` is **load-bearing** for claude-code >= 2.1.162's native binary: it reads stdin while waiting for the browser callback, and an inherited (closed) stdin EOFs it into an early exit that kills the localhost callback server before the redirect arrives — `stdin=PIPE` (never written) makes the read block so the server stays up.3. Schedule a background task that polls `claude auth status` every 2s up to 600s. On exit-0, write the synthetic `"cli-managed"` marker via `auth_service.store_oauth_tokens("claude_code", ...)` and broadcast `credential_catalogue_updated`. The catalogue's `stored` flag flips and the existing `OAuthConnect.tsx` primitive renders the modal as Connected.**Logout**: runs `claude auth logout`, drops the marker via `auth_service.remove_oauth_tokens()`, and broadcasts.-**Codex login**: not yet wired. The handler returns a graceful error pointing the user at `npm install -g @openai/codex` + `codex login` manual flow. Follow-up: write `services/codex_oauth.py` mirroring `claude_oauth.py` with `HOME=~/.codex-machina` env redirect (Codex has no `CONFIG_DIR` equivalent).+**Codex login**: not yet wired. The handler returns a graceful error pointing the user at `npm install -g @openai/codex` + `codex login` manual flow. Follow-up: mirror `nodes/agent/claude_code_agent/_oauth.py` for codex with a `HOME=<DATA_DIR>/codex/` env redirect (Codex has no `CONFIG_DIR` equivalent).**Frontend**: no changes. The existing `client/src/components/credentials/primitives/OAuthConnect.tsx:42-44` already documents and supports the Stripe-style fieldless-CLI case (`config.fields = []`, `kind: "oauth"`, `stored` flag drives Connected state).@@ -548,7 +548,7 @@ Plugin contract: `tests/test_plugin_contract.py` + `tests/test_node_spec.py` —Live verification (needs a real Claude install + auth):-1. Empty `~/.machina/claude/`. Open Credentials Modal → click "Login with Claude Code CLI". Confirm the npm install runs (visible in backend logs), `~/.machina/claude/npm/node_modules/.bin/claude[.cmd]` appears, browser opens for Anthropic OAuth. Modal flips Connected within ~2s of CLI exit (background `claude auth status` poll detects success).+1. Empty `~/.machina/claude/` + `~/.machina/packages/`. Open Credentials Modal → click "Login with Claude Code CLI". Confirm the npm install runs (visible in backend logs), `~/.machina/packages/node_modules/.bin/claude[.cmd]` appears, browser opens for Anthropic OAuth. Modal flips Connected within ~2s of CLI exit (background `claude auth status` poll detects success). The browser tab should render the CLI's own "Signed in" success page (this needs the `stdin=PIPE` spawn — without it the native binary exits early and the tab is left on the bare `localhost/callback` URL).2. Refresh the page. Modal stays Connected (`auth_service.get_oauth_tokens("claude_code")` still returns the marker; idempotent re-click also stays Connected).3. Click Disconnect. Modal flips Disconnected (`claude auth logout` clears CLI creds + marker dropped).4. Add a `claude_code_agent` node, set `tasks=[{prompt:"echo A"},{prompt:"echo B"},{prompt:"echo C"}]`, run. Three distinct `claude:<task_id>` Terminal streams interleaved. Three distinct session_ids. Three worktrees created and removed. `summary.wall_clock_ms < sum(duration_ms)` (proves parallelism).@@ -557,11 +557,11 @@ Live verification (needs a real Claude install + auth):## Risks / open considerations-- **Codex login not yet wired.** v1 returns a graceful error directing the user to `npm install -g @openai/codex` + `codex login`. Follow-up: `services/codex_oauth.py` mirroring `claude_oauth.py` with `HOME=~/.codex-machina` env redirect (Codex has no `CONFIG_DIR` env; `HOME` redirect is risky on Windows, so Windows may need a different strategy or accept user-global Codex auth).+- **Codex login not yet wired.** v1 returns a graceful error directing the user to `npm install -g @openai/codex` + `codex login`. Follow-up: a codex `_oauth.py` mirroring `nodes/agent/claude_code_agent/_oauth.py` with a `HOME=<DATA_DIR>/codex/` env redirect (Codex has no `CONFIG_DIR` env; `HOME` redirect is risky on Windows, so Windows may need a different strategy or accept user-global Codex auth).- **Gemini deferred.** `factory.create_cli_provider("gemini")` raises `NotImplementedError`. v2 work: implement `providers/google_gemini.py`, drop the factory branch, add `nodes/agent/gemini_cli_agent.py`. ~430 LoC. No abstraction changes needed.- **`--include-partial-messages`** assumes a recent Claude CLI; older versions fall back gracefully via the parser's `parse_event` returning `None` for unknown shapes.-- **Browser-prompt phrasing** can change between Claude CLI versions; `b"yes\nyes\n"` might land on the wrong question. Defensible because that's exactly what `claude_oauth.py` has been doing in production.+- **Native-binary stdin sensitivity.** claude-code >= 2.1.162 ships a native binary that reads stdin during `auth login`. We spawn it with `stdin=asyncio.subprocess.PIPE` (never written) so the read blocks and the OAuth callback server stays alive; an inherited/closed stdin EOFs the binary into an early exit that drops the browser callback. If a future CLI version changes its stdin contract this is the spot to revisit.- **Marker token written without verifying CLI is actually functional** — we trust `claude auth status`'s exit code. If Anthropic invalidates the token server-side and the CLI hasn't re-checked, the modal still shows Connected until the next session attempt's `detect_auth_error` catches it.- **MCP SDK is pre-1.0-stable.** Pinned at `mcp>=1.0.0`. The surface is isolated in `mcp_server.py` so an SDK breaking change touches one file.-- **Concurrent install safety.** `claude_oauth.py:_get_claude_cmd` doesn't currently use a lock — two simultaneous login clicks within 2s could race the npm install. Low-risk in practice (modal debounces clicks); a follow-up could add an `asyncio.Lock`.+- **Concurrent install safety.** `_oauth.py:claude_binary_path` doesn't currently use a lock — two simultaneous login clicks within 2s could race the npm install into the shared tree. Low-risk in practice (modal debounces clicks); a follow-up could add an `asyncio.Lock`.- **Worktree leak on hard crash.** Out-of-scope cleanup pass; document.diff --git a/docs-internal/cli_services_integration.md b/docs-internal/cli_services_integration.mdindex e73458b5..ad9e4c17 100644--- a/docs-internal/cli_services_integration.md+++ b/docs-internal/cli_services_integration.md@@ -16,7 +16,7 @@ MachinaOS integrates external services that manage their own lifecycle via CLI tWraps the official `temporal` CLI's `server start-dev` mode (per [docs.temporal.io/develop/python/set-up-your-local-python](https://docs.temporal.io/develop/python/set-up-your-local-python)) — SQLite-backed dev server, single process, gRPC + Web UI both embedded.-**Install:** Automated. `machina build` step [6/6] runs `python -m services.temporal._install`, which uses `pooch` to download the official CLI archive from `https://temporal.download/cli/archive/latest?platform=<os>&arch=<arch>` into a per-OS cache (`~/.cache/MachinaOs/machinaos-temporal/` on Linux, `~/Library/Caches/MachinaOs/machinaos-temporal/` on macOS, `%LOCALAPPDATA%\MachinaOs\Cache\machinaos-temporal\` on Windows). No npm package, no system install required.+**Install:** Automated. `machina build` step [6/6] runs `python -m services.temporal._install`, which uses `pooch` to download the official CLI archive from `https://temporal.download/cli/archive/latest?platform=<os>&arch=<arch>` into `<DATA_DIR>/packages/temporal/` (= `~/.machina/packages/temporal/` by default, on every OS — via `core.paths.package_dir("temporal")`). No npm package, no system install required.**Lifecycle:** Managed entirely by the CLI commands (`machina start` / `machina dev` / `machina stop`) — there's no separate `temporal:start` npm script. The supervisor at [cli/supervisor.py](../cli/supervisor.py) spawns the official CLI via the supervised-runtime shim at [server/services/temporal/_supervised_runtime.py](../server/services/temporal/_supervised_runtime.py).diff --git a/docs-internal/credentials_panel.md b/docs-internal/credentials_panel.mdindex 6eba5b57..4c458526 100644--- a/docs-internal/credentials_panel.md+++ b/docs-internal/credentials_panel.md@@ -156,23 +156,26 @@ After validation succeeds, the frontend still calls `saveApiKey` (or backend sto### 2.6 Pattern F — OAuth via isolated subprocess (Claude)-**Credentials stored**: not in encrypted DB. Tokens persist in `~/.claude-machina/.credentials.json`, written by the official `@anthropic-ai/claude-code` CLI which is installed into `~/.claude-machina/npm/` to keep it isolated from the user's main Claude session.+**Credentials stored**: not in MachinaOs's encrypted DB. The official `@anthropic-ai/claude-code` CLI manages its own credentials file under `CLAUDE_CONFIG_DIR = <DATA_DIR>/claude/` (= `~/.machina/claude/` by default), isolated from the user's own `~/.claude/` session. MachinaOs never reads or writes that file; it only writes a synthetic `"cli-managed"` marker OAuth token via `auth_service.store_oauth_tokens` so the catalogue's `stored` flag flips. The CLI binary is npm-installed into the shared MachinaOs tree at `<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]`.-**Happy path**:+**Happy path** (wire keys `claude_code_login` / `claude_code_logout`; handlers in `nodes/agent/claude_code_agent/_handlers.py`, CLI wrappers in `_oauth.py`):```-sendRequest('claude_oauth_login')- -> initiate_claude_oauth (claude_oauth.py:61)- -> ensure CLI installed (npm install --prefix ~/.claude-machina/npm)- -> spawn `claude login` with env CLAUDE_CONFIG_DIR=~/.claude-machina- -> pipe "yes\nyes\n" to stdin to auto-accept prompts- -> CLI opens browser; user authorizes on console.anthropic.com- -> returns {success, pid, config_dir}--Frontend polls sendRequest('claude_oauth_status'):- -> get_claude_credentials (claude_oauth.py:121)- -> reads ~/.claude-machina/.credentials.json- -> returns {success, has_token, access_token, expires_at}+sendRequest('claude_code_login')+ -> handle_claude_code_login+ -> claude auth status (already logged in? sync marker + return)+ -> else asyncio.create_task(_finalize_claude_login()), return immediately+ -> run_claude_login() -> `claude auth login`+ - binary via claude_binary_path() (npm install --prefix <packages_dir> on miss)+ - env CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/+ - stdin=PIPE (never written) so the native CLI's stdin reader+ blocks instead of EOFing -> its localhost callback server+ stays alive until the browser OAuth flow completes+ - CLI opens browser; user authorizes on claude.ai / console.anthropic.com+ -> claude auth status -> {loggedIn, email, orgName, subscriptionType}+ -> mark_logged_in('claude_code', email, name) + broadcast+ credential.oauth.connected -> FE refetches the catalogue```+The handler returns `{success: True}` synchronously; the real connect state arrives later via the `credential_catalogue_updated` broadcast (the modal flips Connected within ~2 s of CLI exit).No logout WebSocket handler — user can manually delete the credentials file or run `claude logout` separately.@@ -375,7 +378,7 @@ These are the non-negotiable behaviours the test suite enforces. The refactor is| DB | [server/core/credentials_database.py](../server/core/credentials_database.py) | Two encrypted tables + metadata || OAuth (Google) | [server/services/google_oauth.py](../server/services/google_oauth.py) | Flow, PKCE, refresh, service builders || OAuth (Twitter) | [server/services/twitter_oauth.py](../server/services/twitter_oauth.py) | Manual PKCE, token exchange/refresh/revoke |-| OAuth (Claude) | [server/services/claude_oauth.py](../server/services/claude_oauth.py) | Subprocess-based isolated login |+| OAuth (Claude) | [server/nodes/agent/claude_code_agent/_oauth.py](../server/nodes/agent/claude_code_agent/_oauth.py) + [_handlers.py](../server/nodes/agent/claude_code_agent/_handlers.py) | CLI-managed `claude auth login` (subprocess, `stdin=PIPE`), `CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/` || OAuth utils | [server/services/oauth_utils.py](../server/services/oauth_utils.py) | Runtime redirect URI derivation || Container | [server/core/container.py](../server/core/container.py) | DI wiring for `auth_service` etc. |diff --git a/docs-internal/errors.md b/docs-internal/errors.mdindex ae092e8d..2cdc2b13 100644--- a/docs-internal/errors.md+++ b/docs-internal/errors.md@@ -182,7 +182,7 @@ FileNotFoundError: temporal binary not found at ...```or pooch fails to download during `machina start`.-**Root cause**: The official `temporal` CLI archive is downloaded by `pooch` to a per-OS cache (`~/.cache/MachinaOs/machinaos-temporal/` on Linux, `~/Library/Caches/MachinaOs/machinaos-temporal/` on macOS, `%LOCALAPPDATA%\MachinaOs\Cache\machinaos-temporal\` on Windows) during `machina build` step [6/6]. If the build was skipped or interrupted, or if network access to `temporal.download` was blocked, the binary is missing.+**Root cause**: The official `temporal` CLI archive is downloaded by `pooch` to `<DATA_DIR>/packages/temporal/` (= `~/.machina/packages/temporal/` by default, on every OS — via `core.paths.package_dir("temporal")`) during `machina build` step [6/6]. If the build was skipped or interrupted, or if network access to `temporal.download` was blocked, the binary is missing.**Fix**:```bash@@ -236,3 +236,38 @@ This accepts Python 3.13, 3.14, etc. even though the project constraint is `<3.1```jsif (major === 3 && minor >= 11 && minor < 13) { return { cmd, version }; }```++---++## 9. Claude Code OAuth: Browser Stuck on Raw `localhost/callback` URL++**Symptom**: After clicking **Authorize** on Anthropic's OAuth page, the browser lands on a bare URL like:+```+http://localhost:52985/callback?code=Gq7kw...&state=0nEN...+```+with no "Signed in" page — yet the backend log shows the login succeeded and credentials were written. The Credentials modal still flips to Connected (via the broadcast), only the browser tab is left ugly.++**Root cause**: `@anthropic-ai/claude-code >= 2.1.162` ships a **native binary** (`bin/claude.exe`, ~240 MB via platform-specific `optionalDependencies`) instead of the prior JS shim. The native binary reads stdin while waiting for the browser OAuth callback. Under the FastAPI daemon (no TTY, parent stdin closed) it sees immediate EOF, exits, and kills its localhost callback server *before* the browser redirect arrives — so the redirect hits a dead socket. Credentials were already written before the early exit, which is why the modal still connects.++**Fix** (landed at tag v0.0.88): `services/events/cli.py::run_cli_command()` gained an optional `stdin` parameter (default `None` = inherit, unchanged for every existing caller). `nodes/agent/claude_code_agent/_oauth.py::_run_auth` passes `stdin=asyncio.subprocess.PIPE` **for the `login` subcommand only** so the CLI's stdin read blocks instead of EOFing, keeping the callback server alive until the flow completes naturally. `status` / `logout` stay on inherit-stdin (one-shot, no stdin read).++Note the binary install path also moved this release: the claude CLI now lives in the shared MachinaOs npm tree at `<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]` (was `<DATA_DIR>/claude/npm/...`). The fresh `npm install` triggered by that move is what pulled the 2.1.162 native binary that surfaced this bug — the path change was the trigger, the `stdin=PIPE` is the actual fix.++---++## 10. Stripe Login Falsely Reports Success / `exceeded max attempts`++**Symptom**: Backend log during a Stripe connect:+```+[Stripe] login step 2 CLI failure: exceeded max attempts | stderr='exceeded max attempts'+[Stripe] auth successful — credentials written to ...config.toml+```+The "auth successful" line fires even when you only *initiated* the login and never authorised in the browser.++**Root cause**: `_complete_login` used two signals that each lie in isolation:+1. **CLI exit code** — `stripe login --complete` is known to exit `1` with `stderr='exceeded max attempts'` *even after* successfully writing credentials. Exit code alone can't confirm failure.+2. **`is_logged_in()`** — only checks for `_api_key` presence in `~/.config/stripe/config.toml`, which is `True` for *any* prior login (the Stripe CLI manages that file globally, outside MachinaOs). On-disk presence alone can't confirm *this* attempt wrote anything.++So an incomplete login against a config left over from a previous session was reported as success.++**Fix** (landed at tag v0.0.88): `nodes/stripe/_handlers.py` snapshots `config.toml`'s mtime at step 1 (`pre_mtime`), threads it into `_complete_login(binary, next_step, pre_mtime)`, and requires `post_mtime > pre_mtime AND is_logged_in()` to declare success. The mtime advance is ground truth for "*this* attempt wrote fresh credentials". The `exceeded max attempts` stderr is forgiven only when the mtime actually advanced.diff --git a/docs-internal/memory_compaction.md b/docs-internal/memory_compaction.mdindex 82a4577f..11bb0405 100644--- a/docs-internal/memory_compaction.md+++ b/docs-internal/memory_compaction.md@@ -7,7 +7,7 @@The compaction service enables automatic memory compaction, token tracking, and **cost calculation** for MachinaOs specialized agents. It uses a hybrid approach leveraging native provider APIs (Anthropic, OpenAI) when available, with comprehensive token and cost tracking for all providers.**Inspired by:** Claude Code's compaction pattern from the Anthropic SDK-**Threshold Strategy:** per-session `custom_threshold` > model-aware (50% of context window) > global default (100K)+**Threshold Strategy:** per-session `custom_threshold` > per-user `UserSettings.compaction_ratio` > env `Settings.compaction_ratio` (default **0.8** = 80% of context window) > JSON `llm_defaults.json:agent.compaction.ratio` fallback**Cost Calculation:** Official pricing from each provider (per 1M tokens)## Architecture@@ -60,9 +60,9 @@ from services.compaction import get_compaction_servicesvc = get_compaction_service()-# Model-aware threshold (50% of context window)+# Model-aware threshold (80% of context window by default)compaction_config = svc.anthropic_config(model="claude-opus-4.6", provider="anthropic")-# Returns: {"enabled": True, "context_token_threshold": 500000} (50% of 1M context)+# Returns: {"enabled": True, "context_token_threshold": 800000} (80% of 1M context)# Or override with explicit thresholdcompaction_config = svc.anthropic_config(threshold=100000)@@ -84,7 +84,7 @@ For direct Messages API usage with the compaction beta:```python# Model-aware thresholdapi_config = svc.anthropic_api_config(model="claude-sonnet-4.5", provider="anthropic")-# Threshold auto-computed from model's context window (50% of 1M = 500000)+# Threshold auto-computed from model's context window (80% of 1M = 800000)# Or override with explicit thresholdapi_config = svc.anthropic_api_config(threshold=100000)@@ -104,7 +104,7 @@ For OpenAI models (including GPT-4 and o-series):```python# Model-aware thresholdopenai_config = svc.openai_config(model="gpt-5.2", provider="openai")-# Returns: {"context_management": {"compact_threshold": 200000}} (50% of 400K)+# Returns: {"context_management": {"compact_threshold": 320000}} (80% of 400K)# Or override with explicit thresholdopenai_config = svc.openai_config(threshold=100000)@@ -240,12 +240,12 @@ result = await svc.track(# result:# {# "total": 6000, # New cumulative total-# "threshold": 500000, # Model-aware: 50% of 1M context window+# "threshold": 800000, # Model-aware: 80% of 1M context window# "total_cost": 0.021, # USD cost# "needs_compaction": False# }#-# Threshold priority: custom_threshold > model-aware (50% context) > global default+# Threshold priority: custom_threshold > per-user UserSettings.compaction_ratio > env Settings.compaction_ratio (80%) > JSON fallback```### Record Compaction Event@@ -272,7 +272,7 @@ stats = await svc.stats("user-session-123", model="claude-opus-4.6", provider="a# {# "session_id": "user-session-123",# "total": 15000,-# "threshold": 500000, # 50% of 1M context window+# "threshold": 800000, # 80% of 1M context window# "count": 1 # Number of compactions# }@@ -457,7 +457,7 @@ if memory_data and memory_data.get('session_id'):3. **Per-Session State**: Each memory session has independent token tracking and thresholds. This allows different agents to have different compaction settings.-4. **Model-Aware Threshold**: Threshold is 50% of the model's context window (via `get_model_threshold()`). For example, Claude Opus 4.6 (1M context) gets a 500K threshold, GPT-5.2 (400K) gets 200K, Groq models (131K) get ~65K. Falls back to global `COMPACTION_THRESHOLD` when model info is unavailable. Per-session `custom_threshold` always takes priority.+4. **Model-Aware Threshold**: Threshold is `compaction_ratio` x the model's context window (default ratio **0.8** = 80%). For example, Claude Opus 4.6 (1M context) gets an 800K threshold, GPT-5.2 (400K) gets 320K, Groq models (131K) get ~105K. Ratio precedence: per-session `custom_threshold` > per-user `UserSettings.compaction_ratio` > env `Settings.compaction_ratio` (`COMPACTION_RATIO`, default 0.8) > JSON `llm_defaults.json:agent.compaction.ratio` fallback.5. **Singleton Pattern**: Service accessible via `get_compaction_service()` for easy integration anywhere in the codebase.diff --git a/docs-internal/memory_lifecycle.md b/docs-internal/memory_lifecycle.mdindex 3492703b..377a4cd7 100644--- a/docs-internal/memory_lifecycle.md+++ b/docs-internal/memory_lifecycle.md@@ -159,7 +159,7 @@ F4.B `AgentWorkflow` runs steps 4-9 as separate Temporal activities (`prepare_pa## 9. Compaction trigger-Compaction is a separate concern documented in [memory_compaction.md](./memory_compaction.md). The trigger point is step 5 in §7. Threshold = `model_context_length * agent.compaction.ratio` (default 0.5; configured in [`server/config/llm_defaults.json`](../server/config/llm_defaults.json)).+Compaction is a separate concern documented in [memory_compaction.md](./memory_compaction.md). The trigger point is step 5 in §7. Threshold = `model_context_length * compaction_ratio` (default **0.8** = 80%, env `COMPACTION_RATIO` via `Settings`; per-user override in `UserSettings.compaction_ratio`; JSON `llm_defaults.json:agent.compaction.ratio` is the last-resort fallback).The compaction service is the SSOT for thresholds, native-API integration (Anthropic `compact-2026-01-12` beta, OpenAI `context_management.compact_threshold`), and client-side summarization fallback. Memory lifecycle (this doc) is the SSOT for storage shape and helper signatures.diff --git a/docs-internal/node-logic-flows/code_fs_process/fileRead.md b/docs-internal/node-logic-flows/code_fs_process/fileRead.mdindex 7794fab0..871d1c2c 100644--- a/docs-internal/node-logic-flows/code_fs_process/fileRead.md+++ b/docs-internal/node-logic-flows/code_fs_process/fileRead.md@@ -14,7 +14,7 @@Reads a file within the per-workflow workspace. Delegates to`LocalShellBackend.read()` from the `deepagents` package. The backend isinstantiated with `virtual_mode=True` and a `root_dir` pinned to-`data/workspaces/<workflow_slug>/` (or the node-level `working_directory`+`<DATA_DIR>/workspaces/<workflow_slug>/` (or the node-level `working_directory`override), so path traversal outside the workspace is rejected by thebackend itself.diff --git a/docs-internal/node-logic-flows/specialized_agents/claudeCodeAgent.md b/docs-internal/node-logic-flows/specialized_agents/claudeCodeAgent.mdindex 819a9df3..a4fbb8c7 100644--- a/docs-internal/node-logic-flows/specialized_agents/claudeCodeAgent.md+++ b/docs-internal/node-logic-flows/specialized_agents/claudeCodeAgent.md@@ -98,11 +98,12 @@ flowchart TD## External Dependencies-- **Binaries**: `claude` on PATH, or `npx` fallback.+- **Binaries**: `@anthropic-ai/claude-code`, MachinaOs-managed — auto-installed on first use into the shared npm tree at `<DATA_DIR>/packages/` (binary at `<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]`); requires `npm` on PATH.- **Python packages**: standard library only(`asyncio.create_subprocess_exec`).- **Credentials**: Claude Code handles its own authentication via- `~/.claude-machina` (see [Claude OAuth](../../claude_code_agent_architecture.md));+ `CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/` (= `~/.machina/claude/` by+ default; see [Claude OAuth](../../claude_code_agent_architecture.md));MachinaOs does not inject an API key.## Edge cases & known limitsdiff --git a/docs-internal/release_build_pipeline.md b/docs-internal/release_build_pipeline.mdindex 2777e453..708bc690 100644--- a/docs-internal/release_build_pipeline.md+++ b/docs-internal/release_build_pipeline.md@@ -60,6 +60,12 @@ Keep `sourcemap: analyze` (already correct), keep React Compiler config.The npm tarball still excludes `__pycache__/` per `package.json` `files` (cross-Python-minor pyc fragility) — `compileall` runs on the user's machine via `machina build` or `scripts/install.js` post-install.+### 4b. Temporal binary fetch + DATA_DIR parity++- Step `[6/6]` runs `uv run python -m services.temporal._install`, which pooch-downloads the official `temporal` CLI into `<DATA_DIR>/packages/temporal/` (= `~/.machina/packages/temporal/` by default). Pre-fetching at build time turns the ~114 MB download into a sub-second cache hit on first `machina start`.+- **`machina build` layers `.env.dev` first.** `build_command()` calls `cli.config.load_dev_overrides(root)` before the install steps, so the build's `DATA_DIR` matches what the runtime sees. Without it, a repo checkout's `machina build` read `DATA_DIR=~/.machina` from `.env.template` and installed Temporal under user home, but `machina dev` then read `DATA_DIR=.machina` from `.env.dev` and re-downloaded into `<repo>/.machina/` — a redundant ~114 MB fetch on every fresh clone.+- **Safe for global installs.** `.env.dev` is git-committed for contributors but is NOT in the npm `files` list, so an npm-distributed copy has no `.env.dev` — `load_dev_overrides` is a no-op and everything falls through to the `.env.template` default (`DATA_DIR=~/.machina`), matching `machina start` / `machina daemon`.+### 5. Wire bundle + compileall into install.js- `scripts/install.js` → after `uv sync`:diff --git a/docs-internal/stripe_service.md b/docs-internal/stripe_service.mdindex 1fb3f0f1..d90169d4 100644--- a/docs-internal/stripe_service.md+++ b/docs-internal/stripe_service.md@@ -112,7 +112,7 @@ handle_stripe_login()│├── ensure_stripe_cli() ← _install.py│ ├── system PATH lookup (brew/scoop/apt)- │ ├── workspace cache: {workspace}/_stripe/bin/stripe[.exe]+ │ ├── package cache: <DATA_DIR>/packages/stripe/bin/stripe[.exe]│ └── on miss: download v1.40.9 from github.com/stripe/stripe-cli/releases│ returns absolute binary path│@@ -123,15 +123,23 @@ handle_stripe_login()├── return {success, url, verification_code} to the frontend│ (modal opens the URL in a new tab, displays the code)│- └── asyncio.create_task(_complete_login(binary, next_step))+ └── pre_mtime = config.toml mtime (0.0 if absent — snapshot BEFORE step 2)+ asyncio.create_task(_complete_login(binary, next_step, pre_mtime))│▼run_cli_command([binary, "login", "--complete", next_step], timeout=600s)││ (CLI polls Stripe; user authorises in browser; CLI writes- │ credentials to ~/.config/stripe/config.toml and exits 0)+ │ credentials to ~/.config/stripe/config.toml. NB: the CLI may+ │ exit 1 with stderr 'exceeded max attempts' even after a+ │ successful write — exit code alone is not trusted.)│- ├── if is_logged_in():+ ├── post_mtime = config.toml mtime+ │ fresh_credentials_written = post_mtime > pre_mtime AND is_logged_in()+ │ (mtime advance is ground truth: is_logged_in() alone is true+ │ for ANY prior login, so it can't tell THIS attempt apart)+ │+ ├── if fresh_credentials_written:│ ├── _mark_logged_in() ← marker-token write│ │ auth_service.store_oauth_tokens(│ │ provider="stripe",@@ -181,7 +189,7 @@ StripeListenSource.start() (lock-protected, idempotent)│ --forward-to http://localhost:{port}/webhook/stripe│ --print-secret", # no --api-key│ workflow_id="_stripe_global",- │ working_directory={workspace}/_stripe,+ │ working_directory=<DATA_DIR>/daemons, # shared daemons_dir() root│ line_handler=self._on_line, # ← per-line callback│ )│ (CLI reads credentials from its config file; binary path is@@ -207,7 +215,7 @@ StripeListenSource.stop()|---|---|| `server/nodes/stripe/__init__.py` | Wiring: 5 `register_*` calls + `make_status_refresh`. || `server/nodes/stripe/_credentials.py` | `StripeCredential(Credential)` — thin marker class. The CLI manages auth at `~/.config/stripe/config.toml`; this class only exposes the captured `stripe_webhook_secret` for the framework's signature-verifier path. |-| `server/nodes/stripe/_install.py` | `ensure_stripe_cli()` — async, idempotent, lock-guarded. Resolves the binary path: in-process cache → system PATH → workspace-local cache at `{workspace}/_stripe/bin/stripe[.exe]` → fresh download from GitHub releases (pinned `_VERSION = "1.40.9"`). Asset-name map covers Windows AMD64, Linux x86_64/arm64, macOS x86_64/arm64. Subsequent calls hit the cache instantly. |+| `server/nodes/stripe/_install.py` | `ensure_stripe_cli()` — async, idempotent, lock-guarded. Resolves the binary path: in-process cache → system PATH → previously-downloaded copy at `<DATA_DIR>/packages/stripe/bin/stripe[.exe]` (`core.paths.package_dir("stripe") / "bin"`) → fresh download from GitHub releases (pinned `_VERSION = "1.40.9"`) into that same dir. Asset-name map covers Windows AMD64, Linux x86_64/arm64, macOS x86_64/arm64. Subsequent calls hit the cache instantly. || `server/skills/payments_agent/stripe-skill/SKILL.md` | LLM teaching markdown for the `stripe_action` tool. ~10K chars covering customers, charges, payment_intents, refunds, invoices, products/prices, subscriptions, the `trigger` command, common workflows, quoting/escaping, idempotency, test vs live mode, error patterns, and webhook delivery. || `server/config/credential_providers.json` | JSON-driven Credentials Modal catalogue. The `payments` category + `stripe` provider entry tell the frontend modal to render a **Login with Stripe** button (no API-key field) wired to the `stripe_login` / `stripe_logout` / `stripe_status` WebSocket handlers. No React file edits required. || `server/services/ai.py` | `DEFAULT_TOOL_NAMES['stripeAction'] = 'stripe_action'` and the matching tool-description entry — what the LLM sees when the action node is wired to an agent's `input-tools` handle. |@@ -275,8 +283,8 @@ plus the per-line callback subscription via `ProcessService`'s| Method / attr | Purpose ||---|---|| `process_name = "stripe-listen"` | Key used by `ProcessService` to track this daemon. |-| `binary_name = ""` | **Empty** — disables `DaemonEventSource`'s built-in `shutil.which` PATH check. The plugin handles install + verification itself via `ensure_stripe_cli()`, which falls back to a workspace-local download. |-| `workflow_namespace = "_stripe"` | The `ProcessService` workflow id and working dir under `{workspace_base}/_stripe`. |+| `binary_name = ""` | **Empty** — disables `DaemonEventSource`'s built-in `shutil.which` PATH check. The plugin handles install + verification itself via `ensure_stripe_cli()`, which falls back to a download into `<DATA_DIR>/packages/stripe/`. |+| `workflow_namespace = "_stripe"` | The `ProcessService` workflow-id key for this daemon. NOTE: `DaemonEventSource.workdir()` now returns `daemons_dir()` itself (the shared `<DATA_DIR>/daemons/` root) — `workflow_namespace` is a logical process key, not a per-namespace directory. Pre-fix it carved `{workspace_base}/_stripe/` and left an empty dir behind under per-workflow scratch. || `install_hint` | Surfaced in the "install failed" error path when the auto-installer can't reach GitHub releases. || `credential = StripeCredential` | Resolved by the framework before `build_command` is called. || `start()` (override) | `await ensure_stripe_cli()` then `super().start()`. Caches the resolved binary path so `build_command` (sync) can pick it up. |@@ -429,11 +437,11 @@ the modal's Connect button are `stripe_login` and `stripe_logout`:| `stripe_trigger` | passes `["trigger", event]` to `run_cli_command` (after `ensure_stripe_cli`) | Synthetic test event || `stripe_connect/disconnect/reconnect` | `source.start/stop/restart()` from the lifecycle factory | Daemon-only lifecycle; used by the auto-reconnect path on WS-client connect |-Background `_complete_login(binary, next_step)` flow:+Background `_complete_login(binary, next_step, pre_mtime)` flow:-1. `next_step` from step 1 is a literal shell command (`stripe login --complete '<URL>'`); extract the auth URL with `shlex.split(next_step)[-1]` before passing it to `--complete`.-2. `run_cli_command([binary, "login", "--complete", complete_url], timeout=600s)` blocks until OAuth completes.-3. `is_logged_in()` flips true (the CLI wrote `_api_key` lines into `config.toml`).+1. `next_step` from step 1 is a literal shell command (`stripe login --complete '<URL>'`); extract the auth URL with `shlex.split(next_step)[-1]` before passing it to `--complete`. `pre_mtime` is the `config.toml` mtime captured by `handle_stripe_login` *before* this task spawned (`0.0` if the file was absent).+2. `run_cli_command([binary, "login", "--complete", complete_url], timeout=600s)` blocks until OAuth completes. The CLI may exit `1` with `stderr='exceeded max attempts'` even after a successful write, so its exit code is not trusted on its own.+3. Success is declared only when `post_mtime > pre_mtime AND is_logged_in()`. The mtime advance is the disambiguator: `is_logged_in()` is a bare "config contains `_api_key`" check that is true for *any* prior login (the Stripe CLI owns that file globally), so it cannot tell *this* attempt apart from a stale leftover. The `exceeded max attempts` stderr is forgiven when the mtime actually advanced.4. `_mark_logged_in()` writes `auth_service.store_oauth_tokens("stripe", "cli-managed", "cli-managed")`.5. `get_listen_source().start()` spawns the supervised `stripe listen` daemon; the `whsec_…` banner is captured via the `line_handler` callback.6. `_broadcast_credential_event("credential.oauth.connected")` emits a CloudEvents v1.0 envelope (`WorkflowEvent`) via `StatusBroadcaster.broadcast_credential_event`, wrapped under the `credential_catalogue_updated` wire-format type. The frontend invalidates the catalogue and `provider.stored = true` flips the connection indicator.@@ -663,7 +671,7 @@ If none of these are present, the first click on **Login with Stripe**triggers `ensure_stripe_cli()` which downloads the platform-matchedrelease archive (~12 MB) from `github.com/stripe/stripe-cli/releases`,extracts the `stripe[.exe]` binary into-`{workspace_base}/_stripe/bin/`, and proceeds with login. Subsequent+`<DATA_DIR>/packages/stripe/bin/`, and proceeds with login. Subsequentcalls hit the cache.If the download fails (no internet, GitHub down), the WS@@ -716,7 +724,7 @@ class attributes:|---|---|---|| Daemon process name | `StripeListenSource.process_name` | `"stripe-listen"` || Binary name | `StripeListenSource.binary_name` | `"stripe"` |-| Workspace subdir | `StripeListenSource.workflow_namespace` | `"_stripe"` (under `Settings().workspace_base_resolved`) |+| Daemon process key | `StripeListenSource.workflow_namespace` | `"_stripe"` (logical `ProcessService` key; cwd is the shared `daemons_dir()` = `<DATA_DIR>/daemons/`, not a per-namespace subdir) || Webhook path | `StripeWebhookSource.path` | `"stripe"` (i.e. `/webhook/stripe`) || Forward-to port | derived from `Settings().port` | typically `3010` || Verifier | `StripeWebhookSource.verifier` | `StripeVerifier` |diff --git a/server/skills/payments_agent/stripe-skill/SKILL.md b/server/skills/payments_agent/stripe-skill/SKILL.mdindex 1564025a..3a93c66f 100644--- a/server/skills/payments_agent/stripe-skill/SKILL.md+++ b/server/skills/payments_agent/stripe-skill/SKILL.md@@ -291,8 +291,8 @@ and runs `stripe logout --all` to clear the config file.- System install (`brew install stripe/stripe-cli/stripe`,`scoop install stripe`, `apt install stripe`, or a directbinary from <https://stripe.com/docs/stripe-cli#install>).- - MachinaOs workspace cache at- `{workspace_base}/_stripe/bin/stripe[.exe]` (populated+ - MachinaOs package cache at+ `<DATA_DIR>/packages/stripe/bin/stripe[.exe]` (populatedautomatically from GitHub releases — pinned to a known-goodCLI version).2. Credentials Modal → Stripe → **Login with Stripe** → a browser