Skip to content

Self-improving AI Employees for everyone

refactor(code): Node.js executor becomes a plugin-owned on-demand daemon

trohitgca39056cd669
diff --git a/.env.template b/.env.template
index 6eaac03a..07062e2b 100644
--- a/.env.template
+++ b/.env.template
@@ -7,6 +7,9 @@
# 5682 Temporal gRPC, 5683 Temporal Web UI.
VITE_CLIENT_PORT=5678
PYTHON_BACKEND_PORT=5678
+# Plugin-owned (read by nodes/code/, not core Settings). Related
+# optional vars: NODEJS_EXECUTOR_URL (external executor override),
+# NODEJS_EXECUTOR_TIMEOUT.
NODEJS_EXECUTOR_PORT=5680
# Plugin-owned (read by nodes/whatsapp/, not core Settings). Related
# optional vars: WHATSAPP_RUNTIME_ENABLED, WHATSAPP_DATA_SUBDIR,
diff --git a/CLAUDE.md b/CLAUDE.md
index 2cb0c547..1829f519 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -118,7 +118,6 @@ server/services/
├── parameter_resolver.py # Template variable resolution
├── agent_team.py # AgentTeamService for multi-agent coordination
├── model_registry.py # ModelRegistryService - model constraints from OpenRouter + llm_defaults
-├── nodejs_client.py # HTTP client for Node.js code executor
├── pricing.py # LLM and API cost calculation (loads config/pricing.json)
├── markdown_formatter.py # GFM markdown to platform-specific formatting (Telegram HTML, WhatsApp, plain)
├── ws_handler_registry.py # Plugin-owned WS commands self-register here (Wave 11.H)
@@ -212,15 +211,15 @@ server/nodejs/ # Persistent Node.js server for JS/TS execution
OpenCompany can optionally integrate with the sibling **polyglot-server** repo (a plugin-registry microservice exposing REST + MCP + WebSocket). NOTE: the OpenCompany-side client/handler (`polyglot_client.py`, `handlers/polyglot.py`) are not currently present in the tree — this is a possible future integration, not wired. See [Polyglot Server](../polyglot-server/ARCHITECTURE.md).
### Node.js Code Executor
-Persistent Node.js server for JavaScript/TypeScript code execution, replacing subprocess spawning per execution.
+Persistent Node.js server for JavaScript/TypeScript code execution, replacing subprocess spawning per execution. **Plugin-owned (July 2026):** the sidecar is supervised by `nodes/code/_runtime.py` (`NodeJSExecutorRuntime`, same `BaseProcessSupervisor` pattern as WhatsApp/Temporal) and spawns on demand from `acquire_client()` on the first JS/TS node execution — in every run mode, with no CLI service wiring. Client + config are plugin-owned too (`nodes/code/_client.py`, `NODEJS_EXECUTOR_*` env vars; core `Settings` carries no executor fields).
**Architecture:**
```
┌─────────────────────────────────────────────────────────────┐
-│ Python Backend (port 5678) │
+│ Python Backend (PYTHON_BACKEND_PORT) │
│ ┌────────────────┐ HTTP/JSON ┌──────────────────┐ │
│ │ NodeJSClient │◄──────────────────►│ Node.js Server │ │
-│ │ (aiohttp) │ localhost:5680 │ (Express + tsx) │ │
+│ │ (aiohttp) │ NODEJS_EXECUTOR_PORT │ (Express + tsx)│ │
│ └────────────────┘ └──────────────────┘ │
│ ▲ │
│ │ │
@@ -242,7 +241,6 @@ server/nodejs/
└── package.json
server/services/
-└── nodejs_client.py # Async HTTP client for Node.js server
server/nodes/code/ # Executor plugins (javascript_executor, typescript_executor)
```
@@ -258,9 +256,9 @@ server/nodes/code/ # Executor plugins (javascript_executor, types
**Environment Variables:**
| Variable | Default | Description |
|----------|---------|-------------|
-| `NODEJS_EXECUTOR_URL` | `http://localhost:5680` | Server URL for Python client |
+| `NODEJS_EXECUTOR_URL` | `http://localhost:${NODEJS_EXECUTOR_PORT}` | Server URL for Python client |
| `NODEJS_EXECUTOR_TIMEOUT` | `30` | Request timeout in seconds |
-| `NODEJS_EXECUTOR_PORT` | `5680` | Server port |
+| `NODEJS_EXECUTOR_PORT` | see `.env.template` | Server port |
| `NODEJS_EXECUTOR_HOST` | `localhost` | Server host |
| `NODEJS_EXECUTOR_BODY_LIMIT` | `10mb` | Max request body size |
@@ -623,8 +621,8 @@ Node groups (palette categories): agent, model, skill, tool, trigger, workflow,
## Backend Services
### Python Backend (FastAPI)
-- **Port**: 5678
-- **Base URL**: http://localhost:5678
+- **Port**: `PYTHON_BACKEND_PORT` (defaults in `.env.template`)
+- **Base URL**: `http://localhost:${PYTHON_BACKEND_PORT}`
- **Main File**: `server/main.py`
### API Endpoints
@@ -687,7 +685,7 @@ Node groups (palette categories): agent, model, skill, tool, trigger, workflow,
### Temporal Distributed Execution
-Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step.v1` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC 5682 + Web UI 5683, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, all 16 F4.B `agent.*.v1` activities, heartbeat semantics, delegation input contract, resumption toggle (`TEMPORAL_TERMINATE_RUNNING_ON_STARTUP`), the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).
+Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step.v1` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC `TEMPORAL_FRONTEND_GRPC_PORT` + Web UI `TEMPORAL_UI_PORT`, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, all 16 F4.B `agent.*.v1` activities, heartbeat semantics, delegation input contract, resumption toggle (`TEMPORAL_TERMINATE_RUNNING_ON_STARTUP`), the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).
**Temporal tracing ownership is strict.** Register the SDK `TracingInterceptor` exactly once on the shared `Client.connect(...)`; the Python SDK automatically prepends compatible client interceptors to every worker. Never repeat `TracingInterceptor` in `Worker(..., interceptors=...)`. Worker lists contain the distinct `ObservabilityWorkerInterceptor` and plugin-specific worker interceptors only. Exact paired `StartActivity` / `RunActivity` / `CompleteWorkflow` console spans with identical Temporal identities indicate duplicate instrumentation, not duplicate execution; use Temporal Event History and the `node.<type>.execute` application span to verify actual attempts. See the tracing and debugging sections in [TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md) and [errors.md](./docs-internal/errors.md).
@@ -735,7 +733,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.
✅ **Process Management**: Robust stop scripts with duplicate process detection
✅ **WhatsApp Integration**: Square node design with QR code viewer, group/sender name persistence, newsletter channel support (send, query, follow/unfollow, create, mute, mark viewed, react, live updates), media download, profile pics, and proper error handling
✅ **Backend Stability**: Fixed dependency injection and error handling preventing crashes
-✅ **Development Server**: the app is **http://localhost:5678** in every mode. `company dev` = Vite HMR on 5678 proxying /api /ws /webhook to the backend on :5679; `company start` (production) = uvicorn alone on 5678 (API + WS + SPA)
+✅ **Development Server**: the app is **`http://localhost:${PYTHON_BACKEND_PORT}`** in every mode (defaults in `.env.template`). `company dev` = Vite HMR on that port proxying /api /ws /webhook to the backend (dev override in `.env.dev`); `company start` (production) = uvicorn alone on it (API + WS + SPA)
✅ **WebSocket Integration**: Persistent WebSocket connections for remote Android devices with background tasks and message queue
✅ **Real-time Status WebSocket**: Frontend-backend WebSocket at `/ws/status` for live Android status, node status, and variable updates
✅ **Event-Driven Trigger Nodes**: WhatsApp Receive and Webhook Trigger with asyncio.Future-based event waiting, filter builders, and cancel support
@@ -1122,7 +1120,7 @@ Full reference — agent loop, skill injection, tool building, input/auto-prompt
## Testing & Validation
```bash
# Development server test
-curl -I http://localhost:5678
+curl -I http://localhost:${PYTHON_BACKEND_PORT:-5678}
# TypeScript validation
npx tsc --noEmit
@@ -1781,11 +1779,11 @@ export interface AndroidStatus {
## WhatsApp Integration
### Overview
-WhatsApp nodes use square design with integrated QR code viewing and proper error handling. The integration proxies all requests through the Python backend to the WhatsApp RPC service (default port 5681, configurable via `WHATSAPP_RPC_PORT` env var or `--port` CLI flag). Supports individual chats, groups, and newsletter channels (sending, querying, follow/unfollow, create, mute, mark viewed, react, live updates, media download, profile pics). All 14 WhatsApp events handled.
+WhatsApp nodes use square design with integrated QR code viewing and proper error handling. The integration proxies all requests through the Python backend to the WhatsApp RPC service (port from `WHATSAPP_RPC_PORT`, or the `--port` CLI flag). Supports individual chats, groups, and newsletter channels (sending, querying, follow/unfollow, create, mute, mark viewed, react, live updates, media download, profile pics). All 14 WhatsApp events handled.
### Architecture
```
-Frontend (WhatsAppNode.tsx) → Python Backend (/api/whatsapp/*) → WhatsApp RPC Service (localhost:${WHATSAPP_RPC_PORT:-5681})
+Frontend (WhatsAppNode.tsx) → Python Backend (/api/whatsapp/*) → WhatsApp RPC Service (localhost:${WHATSAPP_RPC_PORT})
```
### Key Features
@@ -2583,7 +2581,7 @@ This function:
- **WhatsApp Integration**: Square node design with QR code viewer, proper error handling, no crashes
- Critical fix: Added "routers.whatsapp" to dependency injection wiring
- All endpoints use safe JSON parsing with comprehensive error handling
- - Backend proxies all requests to WhatsApp RPC service (default port 5681, configurable)
+ - Backend proxies all requests to WhatsApp RPC service (`WHATSAPP_RPC_PORT`)
- Returns proper HTTP status codes (503, 504, 410) instead of mock data
- Python server never crashes when WhatsApp service is unavailable
- WebSocket handlers for status, QR code, send message, and start connection
@@ -2634,7 +2632,7 @@ This function:
- Published to PyPI as `whatsapp-rpc` (async Python client)
- Cross-platform binaries built via GitHub Actions (linux/amd64, linux/arm64, darwin/amd64, darwin/arm64, windows/amd64)
- Binary downloaded from GitHub releases during npm postinstall
- - Configurable port via `--port` CLI flag, `PORT` or `WHATSAPP_RPC_PORT` env vars (OpenCompany passes 5681; the package's own default is 9400)
+ - Configurable port via `--port` CLI flag, `PORT` or `WHATSAPP_RPC_PORT` env vars (OpenCompany passes WHATSAPP_RPC_PORT; the npm package's own default is 9400)
- QR codes generated as base64 PNG in memory (no file I/O, no `data/qr` directory)
- Source: https://github.com/trohitg/whatsapp-rpc
- **Node Data Architecture**: `node.data` only stores `label` (display name). All parameters are stored in the database via `save_node_parameters` WebSocket handler. This prevents parameter bloat in workflow JSON exports and keeps React Flow state lightweight. `useDragAndDrop.ts` saves default parameters to DB on drop, not to `node.data`.
@@ -2642,7 +2640,7 @@ This function:
- **Skill System Architecture**: Skills organized in `server/skills/<folder>/` subfolders. Each folder appears in Master Skill dropdown. DB/Master Skill customization is authoritative. Standard skills use progressive disclosure without modifying the agent system prompt: the dynamically connected `Skill` tool carries the bounded name/description catalogue, loads instructions, then separately reads/searches declared resources. Personality skills remain eager. Duplicate connected names block with `DUPLICATE_CONNECTED_SKILL_NAME`. Runtime state and sanitized `agent.skill.*` observability live in [`skill_runtime.py`](./server/services/skill_runtime.py); tool results persist in the current conversation while canvas badges clear at turn end. Icon resolution mirrors `BaseNode._metadata_dict`: per-plugin `<plugin>/icon.svg` (served as `/api/schemas/nodes/<type>/icon`) → `visuals.json` (emoji / `lobehub:<brand>`); color: per-plugin `<plugin>/meta.json` → `visuals.json`. Lives in [`skill_loader.py::_parse_skill_metadata`](./server/services/skill_loader.py). Native DOM keydown handler prevents React Flow from intercepting Ctrl shortcuts in skill editor. **Mutation broadcasts use the CloudEvents-typed `skill_lifecycle` wire key** with stages `created` / `updated` / `deleted` / `content_saved` — see "Plugin-folder location for plugin-specific CloudEvents factories" below.
- **Example Workflows**: Auto-load example workflow seeds from `<repo>/.opencompany/workflows/` on first use (git-tracked; the only non-ignored content under `<repo>/.opencompany/`). Path resolved by `core.paths.example_workflows_dir()` — fixed, NOT under `DATA_DIR`, preserved by `company clean` via `_OPENCOMPANY_KEEP`. Uses `UserSettings.examples_loaded` flag; supports anonymous users (`user_id="default"`); embedded `nodeParameters` saved to DB on import.
- **Onboarding Service**: 5-step welcome wizard (Welcome, Concepts, API Keys, Canvas Tour, Get Started) using shadcn primitives + lucide icons. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from Settings "Help" section. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.
-- **Node.js Code Executor**: Persistent Node.js server (Express + tsx) at port 5680 for JavaScript/TypeScript execution, replacing subprocess spawning per execution. The code executor plugins under `server/nodes/code/` call `NodeJSClient` which makes HTTP requests to the Node.js server. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc.).
+- **Node.js Code Executor**: Persistent Node.js server (Express + tsx) at `NODEJS_EXECUTOR_PORT` for JavaScript/TypeScript execution, replacing subprocess spawning per execution. The code executor plugins under `server/nodes/code/` call `NodeJSClient` which makes HTTP requests to the Node.js server. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc.).
- **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. (The former checklist rendering — `formatTodoOutput()` — lived only in the legacy `ui/OutputDisplayPanel.tsx`, which was deleted as dead code; the active `components/output/OutputPanel.tsx` shows todo results as regular JSON.) 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.
@@ -2658,7 +2656,7 @@ This function:
- **Process manager port admission + middle panel**: server commands declare listener `ports` (with compatibility inference for `--port`, `-p`, `PORT`, and `*_PORT`). `ProcessService.start()` serializes admission, checks managed reservations plus OS TCP listeners, and returns structured `PORT_IN_USE` without killing the owner or allowing framework auto-port fallback. Explicit ports/environment survive restart. The `isProcessManagerPanel` UI hint gives only `processManager` a full-height workflow-scoped process table with PID/ports/timestamps/elapsed/output and stop/restart controls. See [docs-internal/process_manager.md](./docs-internal/process_manager.md).
- **Telegram message auto-split**: Telegram Bot API caps `sendMessage.text` at 4096 chars (per https://core.telegram.org/bots/api). `TelegramService.send_message` splits longer text at paragraph → line → sentence → space → hard-cut boundaries via `_split_text` helper, sends each chunk threaded under the previous (`reply_to_message_id` cascade), returns first message's metadata + `parts` + `message_ids[]`. Captions on `send_photo` / `send_document` still take the legacy path and will fail on >1024 chars — separate fix once needed (constants `_TG_TEXT_LIMIT=3500`, `_TG_CAPTION_LIMIT=900` in `_service.py` already account for ~20% HTML expansion from markdown→HTML conversion in `_resolve_body`).
- **Google OAuth scope expansion**: Google's authorisation server legitimately returns a wider scope set than requested when the OAuth Client's "Data Access" page lists extra scopes (commonly `cloud-platform`) or when `include_granted_scopes` replays a previously-granted scope. `oauthlib` does strict set-equality and aborts with `Warning: Scope has changed`. As of 2026 (`google-auth-oauthlib` 1.2.4, `oauthlib` upstream issue #562 still open), no constructor flag, context manager, or `expected_scopes` argument exists — the documented relief is the env var. `services/google_oauth.py` sets `OAUTHLIB_RELAX_TOKEN_SCOPE=1` via `os.environ.setdefault` BEFORE the `google_auth_oauthlib.flow` import (oauthlib reads it once at parameters-module import; request-time setting races under uvicorn workers), paired with `warnings.filterwarnings(message=r"Scope has changed.*")` to keep the operator log clean. Long-term root cause: audit the Cloud Console Data Access page and remove `cloud-platform` if no handler uses it.
-- **Code-executor error mapping** (`pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`): wrap user-code execution and sidecar calls in `try/except`. Python: detect `ImportError("__import__ not found")` (the LLM tried `import X` against the sandboxed builtins) and surface the pre-injected names list (`math, json, datetime, timedelta, re, random, Counter, defaultdict`) plus the suggestion to use `process_manager` for unsupported modules; other exceptions get formatted as `<ErrorName> at line N: <message>` (line N walked from `<string>` frame in the traceback) plus any captured stdout. JS/TS: detect `aiohttp.ClientConnectorError` and surface "JavaScript executor not running on localhost:5680. Start the dev runner or fall back to python_executor." All raise `NodeUserError` so the framework logs one WARN line — no aiohttp/CreateProcessW noise in the operator log.
+- **Code-executor error mapping** (`pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`): wrap user-code execution and sidecar calls in `try/except`. Python: detect `ImportError("__import__ not found")` (the LLM tried `import X` against the sandboxed builtins) and surface the pre-injected names list (`math, json, datetime, timedelta, re, random, Counter, defaultdict`) plus the suggestion to use `process_manager` for unsupported modules; other exceptions get formatted as `<ErrorName> at line N: <message>` (line N walked from `<string>` frame in the traceback) plus any captured stdout. JS/TS: detect `aiohttp.ClientConnectorError` and surface "JavaScript executor not running on NODEJS_EXECUTOR_PORT. Start the dev runner or fall back to python_executor." All raise `NodeUserError` so the framework logs one WARN line — no aiohttp/CreateProcessW noise in the operator log.
- **Workflow-scoped chat + console history**: chat messages persist with `chat_messages.session_id == <workflow_id>` (or `"default"` when no workflow is open); console logs persist with `console_logs.workflow_id`. Backend `database.get_console_logs(limit, workflow_id=None)` and `clear_console_logs(workflow_id=None)` filter by workflow when given. `handle_clear_console_logs` broadcasts `console_logs_cleared` carrying the `workflow_id` so the existing frontend filter in `WebSocketContext` keeps other workflows' panels intact. Frontend reads `currentWorkflow.id` via the documented Zustand escape hatch (`useAppStore.getState().currentWorkflow?.id`) at call time for `clearChatMessages` / `clearConsoleLogs` / `sendChatMessage` so the callbacks don't re-create on every workflow switch. A dedicated `useEffect([currentWorkflowId, isReady])` resets local `chatMessages` / `consoleLogs` and refetches both when the user opens / switches workflow. Incoming `console_log` broadcasts are filtered by `currentWorkflow.id` so a parallel run on another workflow never bleeds into the active panel. Legacy logs without `workflow_id` still surface (transition guard).
- **Auto-derived `isConfigNode` uiHint**: `_derive_auto_ui_hints(group)` in `services/plugin/base.py` automatically sets `uiHints.isConfigNode: True` on any plugin whose `group` tuple contains `memory` or `tool` (centralized as `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})`). Explicit `cls.ui_hints` always wins (merge order: auto first, then `dict.update`). Frontend `InputSection.tsx` and `OutputPanel.tsx` consume the flag via `definition?.uiHints?.isConfigNode === true` — the old `groups.includes('memory') || groups.includes('tool')` heuristic is gone. Pytest invariant `test_ui_hints_only_carry_known_flags` locks the flag name. Adding a new auxiliary node type costs zero per-plugin code; opting out costs one line (`ui_hints = {"isConfigNode": False}`).
- **`isMasterSkillEditor` uiHint replaces `node.type === 'masterSkill'` checks**: 6 frontend callsites (`Dashboard.tsx:98` component dispatch, `useAutoSkillEdges.ts` constant + edge filter, `MiddleSection.tsx` × 3) now read `getCachedNodeSpec(type)?.uiHints?.isMasterSkillEditor === true` instead of comparing the type string. The `MasterSkillNode` plugin already declared the hint — no backend change. Renaming the plugin's `type` is now a single backend edit followed by a NodeSpec deploy; the frontend never needs to know the string.
diff --git a/cli/commands/serve.py b/cli/commands/serve.py
index 54589a53..e890fbe6 100644
--- a/cli/commands/serve.py
+++ b/cli/commands/serve.py
@@ -2,15 +2,13 @@
Runs the app on ONE public port: uvicorn serves the REST API + WebSocket +
the built React SPA (via the ``SERVE_STATIC_CLIENT`` block in
-``server/main.py``), plus the Node.js code-exec sidecar on its own internal
-port. Used locally for a production-shaped run AND as the systemd
-``ExecStart`` on a VM provisioned by ``company deploy``.
+``server/main.py``). Used locally for a production-shaped run AND as the
+systemd ``ExecStart`` on a VM provisioned by ``company deploy``.
-Unlike ``company start`` (which runs a separate static-client server + the
-backend + temporal on multiple ports), ``serve`` is single-port and serves
-the client from the backend itself. The Node sidecar is NOT launched by
-``start``/``dev`` today, so ``serve`` adds it (the JS/TS executor nodes need
-it).
+Optional daemons are backend-owned and spawn on demand — the Node.js
+code-exec sidecar (``nodes/code/_runtime.py``), WhatsApp, and the
+Temporal dev server all start from the backend, so ``serve`` supervises
+exactly one process.
The long-running uvicorn is invoked via the server venv's interpreter
directly (not ``uv run``) so the systemd service has no runtime dependency
@@ -42,20 +40,16 @@ def serve_command(port: int | None = None) -> None:
# PYTHON_BACKEND_PORT from the env files.
bind_port = port or int(os.environ.get("PORT") or cfg.backend_port)
- # Free the ports we will bind (clears stale orphans; idempotent).
+ # Free the port we will bind (clears stale orphans; idempotent).
from cli.ports import kill_port
- for p in {bind_port, cfg.nodejs_port}:
- kill_port(p)
+ kill_port(bind_port)
console.print()
console.print(" [bold]OpenCompany[/] serve (single-port)")
console.print(f" App: http://0.0.0.0:{bind_port} (API + WebSocket + SPA)")
- console.print(f" Sidecar: 127.0.0.1:{cfg.nodejs_port} (JS/TS executor)")
console.print()
- sidecar = server_dir(root) / "nodejs" / "dist" / "index.js"
-
specs = [
ServiceSpec(
name="server",
@@ -75,13 +69,6 @@ def serve_command(port: int | None = None) -> None:
env={"SERVE_STATIC_CLIENT": "1", "PORT": str(bind_port)},
ready_port=bind_port,
),
- ServiceSpec(
- name="nodejs",
- argv=["node", str(sidecar)],
- cwd=server_dir(root) / "nodejs",
- env={"NODEJS_EXECUTOR_PORT": str(cfg.nodejs_port)},
- ready_port=cfg.nodejs_port,
- ),
]
manager = Manager()
diff --git a/cli/config.py b/cli/config.py
index 4de047da..8dae0c34 100644
--- a/cli/config.py
+++ b/cli/config.py
@@ -77,7 +77,6 @@ class Config:
client_port: int
backend_port: int
- nodejs_port: int
temporal_address: str
temporal_enabled: bool
temporal_ui_port: int
@@ -93,15 +92,14 @@ class Config:
# ``temporal_ui_port`` are bound by the same ``temporal server
# start-dev`` process, so killing one kills both — listing both
# only matters when cleaning up stale orphans on either port.
- # Plugin-owned daemons (e.g. WhatsApp's edgymeow on
- # WHATSAPP_RPC_PORT) are NOT listed: the backend supervises them
- # (tree-kill on shutdown), and the CLI carries no plugin
- # knowledge. A crashed-backend orphan surfaces as a bind error
- # on the plugin's next start, which the plugin reports.
+ # Plugin-owned daemons (WhatsApp's edgymeow, the Node.js executor
+ # sidecar) are NOT listed: the backend supervises them (tree-kill
+ # on shutdown), and the CLI carries no plugin knowledge. A
+ # crashed-backend orphan surfaces as a bind error on the plugin's
+ # next start, which the plugin reports.
return [
self.client_port,
self.backend_port,
- self.nodejs_port,
self.temporal_port,
self.temporal_ui_port,
]
@@ -166,7 +164,6 @@ def load_config(root: Path | None = None) -> Config:
return Config(
client_port=_int(env, "VITE_CLIENT_PORT"),
backend_port=_int(env, "PYTHON_BACKEND_PORT"),
- nodejs_port=_int(env, "NODEJS_EXECUTOR_PORT"),
temporal_address=_require(env, "TEMPORAL_SERVER_ADDRESS"),
temporal_enabled=_bool(env, "TEMPORAL_ENABLED"),
temporal_ui_port=_int(env, "TEMPORAL_UI_PORT"),
diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.md
index 5bd70847..5aa2128c 100644
--- a/docs-internal/SCRIPTS.md
+++ b/docs-internal/SCRIPTS.md
@@ -22,7 +22,7 @@ deprecation warning; kept for upgrade compatibility).
|---------|-------------|
| `company start` | Production mode, single port: uvicorn serves API + WS + built SPA on :5678. Optional daemons (Temporal dev server, WhatsApp) are backend-owned, started from the lifespan when enabled |
| `company dev` | Start in dev mode (Vite HMR + uvicorn). `--force` re-bundles Vite deps (recovers "Outdated Optimize Dep"); `--daemon` binds backend to 0.0.0.0 |
-| `company serve` | Single-port production runtime (uvicorn serves API + WS + built SPA + Node sidecar) — the systemd `ExecStart` on deployed VMs |
+| `company serve` | Single-port production runtime (uvicorn serves API + WS + built SPA; optional daemons incl. the Node.js executor are backend-spawned on demand) — the systemd `ExecStart` on deployed VMs |
| `company stop` | Stop all services and free configured ports |
| `company build` | Full production build (pnpm install → client → sidecar → uv sync → bytecode → temporal binary). Step [0/6] scaffolds `.env` from `.env.template` when missing, generating fresh random secrets (`secrets.token_hex(24)`) for `SECRET_KEY` / `JWT_SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` instead of the dev placeholders; an existing `.env` is untouched |
| `company clean` | Stop services, then remove build artifacts, node_modules, `.venv`, repo-local state (preserves `.opencompany/{workflows,deploy,packages}`) |
diff --git a/server/core/config.py b/server/core/config.py
index fe429662..3c6a4dc8 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -246,10 +246,9 @@ class Settings(BaseSettings):
anthropic_api_key: Optional[str] = Field(default=None, env="ANTHROPIC_API_KEY")
google_ai_api_key: Optional[str] = Field(default=None, env="GOOGLE_AI_API_KEY")
- # Node.js Executor Configuration
- nodejs_executor_url: str = Field(default="http://localhost:5680", env="NODEJS_EXECUTOR_URL")
- nodejs_executor_timeout: int = Field(default=30, env="NODEJS_EXECUTOR_TIMEOUT", ge=5, le=300)
- nodejs_executor_port: int = Field(default=5680, env="NODEJS_EXECUTOR_PORT", ge=1024, le=65535)
+ # Node.js executor settings live in the plugin: nodes/code/_runtime.py
+ # and _nodejs.py read the NODEJS_EXECUTOR_* env vars directly
+ # (plugin-owned config, same as the WhatsApp runtime).
# AI Proxy Configuration (Ollama-style proxy)
ai_proxy_default_port: int = Field(default=11434, env="AI_PROXY_DEFAULT_PORT")
diff --git a/server/nodes/code/__init__.py b/server/nodes/code/__init__.py
index 7c80892a..be15f244 100644
--- a/server/nodes/code/__init__.py
+++ b/server/nodes/code/__init__.py
@@ -1 +1,17 @@
-"""Plugins for the 'code' palette group. See ../__init__.py for the package layout."""
+"""Plugins for the 'code' palette group. See ../__init__.py for the package layout.
+
+The Node.js executor sidecar (JS/TS code nodes) is plugin-owned: the
+supervisor in :mod:`._runtime` spawns it on demand and is registered
+here so ``shutdown_all_supervisors()`` reaches it at lifespan shutdown.
+"""
+
+from services._supervisor import register_supervisor
+
+from ._runtime import NodeJSExecutorRuntime, get_nodejs_executor_runtime
+
+register_supervisor(NodeJSExecutorRuntime.get_instance())
+
+__all__ = [
+ "NodeJSExecutorRuntime",
+ "get_nodejs_executor_runtime",
+]
diff --git a/server/services/nodejs_client.py b/server/nodes/code/_client.py
similarity index 100%
rename from server/services/nodejs_client.py
rename to server/nodes/code/_client.py
diff --git a/server/nodes/code/_nodejs.py b/server/nodes/code/_nodejs.py
index c2f1bae8..a3d3d997 100644
--- a/server/nodes/code/_nodejs.py
+++ b/server/nodes/code/_nodejs.py
@@ -1,22 +1,48 @@
-"""Shared Node.js executor client for JS/TS plugins.
+"""Shared Node.js executor access for the JS/TS plugins.
-Both ``javascript_executor.py`` and ``typescript_executor.py`` dispatch
-through the same persistent Node.js server (see ``services/nodejs/``).
-This helper owns the singleton client so both plugins share one HTTP
-session.
+Both ``javascript_executor`` and ``typescript_executor`` dispatch
+through the same persistent Node.js sidecar. This helper owns the
+singleton HTTP client AND the on-demand spawn: :func:`acquire_client`
+ensures the backend-supervised runtime (see :mod:`._runtime`) is up
+before handing back the client, so JS/TS nodes work in every mode
+without any CLI-side service wiring.
"""
from __future__ import annotations
+import os
from typing import Optional
-from services.nodejs_client import NodeJSClient
+from ._client import NodeJSClient
+from ._runtime import executor_port, get_nodejs_executor_runtime
_client: Optional[NodeJSClient] = None
-def get_nodejs_client(base_url: str = "http://localhost:5680", timeout: int = 30) -> NodeJSClient:
+def executor_base_url() -> str:
+ """Configured sidecar URL — env-driven, no hardcoded port.
+
+ ``NODEJS_EXECUTOR_URL`` wins outright (remote/external executor);
+ otherwise the URL composes from the plugin-owned port.
+ """
+ return os.environ.get("NODEJS_EXECUTOR_URL") or (
+ f"http://localhost:{executor_port()}"
+ )
+
+
+def get_nodejs_client(base_url: str | None = None, timeout: int = 30) -> NodeJSClient:
global _client
if _client is None:
- _client = NodeJSClient(base_url, timeout)
+ _client = NodeJSClient(base_url or executor_base_url(), timeout)
return _client
+
+
+async def acquire_client() -> NodeJSClient:
+ """Ensure the executor sidecar is running, then return the client.
+
+ When ``NODEJS_EXECUTOR_URL`` points at an external executor the
+ spawn step is skipped entirely — that URL is authoritative.
+ """
+ if not os.environ.get("NODEJS_EXECUTOR_URL"):
+ await get_nodejs_executor_runtime().ensure_started()
+ return get_nodejs_client()
diff --git a/server/nodes/code/_runtime.py b/server/nodes/code/_runtime.py
new file mode 100644
index 00000000..fcc2d39c
--- /dev/null
+++ b/server/nodes/code/_runtime.py
@@ -0,0 +1,131 @@
+"""Node.js executor runtime — supervises the Express/tsx sidecar.
+
+The JS/TS code-executor nodes dispatch to a persistent Node.js HTTP
+server (source tree at ``server/nodejs/``, esbuild-bundled to
+``dist/index.js`` by ``company build``). Historically only ``company
+serve`` spawned it as a CLI ServiceSpec, so JS/TS nodes were dead in
+``dev`` / ``start`` modes. It is now backend-owned like every other
+optional daemon: spawned on demand from the plugin's own
+:func:`ensure_started` (first JS/TS node execution), torn down by the
+lifespan's ``shutdown_all_supervisors()``.
+
+Same :class:`BaseProcessSupervisor` idiom as ``nodes/whatsapp/_runtime``
+and ``services/temporal/_runtime`` — including the TCP probe-before-spawn
+from the Temporal runtime, so an externally managed executor (or one
+started by another backend process, e.g. a standalone Temporal worker)
+is detected and left alone.
+
+Config is plugin-owned: the ``NODEJS_EXECUTOR_*`` env vars are read
+here directly (pushed into ``os.environ`` from ``.env`` by the CLI) —
+core ``Settings`` carries no executor fields.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import shutil
+import sys
+from pathlib import Path
+
+from services._supervisor import BaseProcessSupervisor
+
+# Sub-second per-attempt probe — a stalled sidecar fails health fast.
+_PROBE_TIMEOUT_SECONDS = 1.0
+
+
+async def _probe_tcp_port(port: int, host: str = "localhost") -> bool:
+ """True iff a TCP connection to ``host:port`` succeeds within
+ :data:`_PROBE_TIMEOUT_SECONDS`. Mirrors the Temporal runtime's
+ loopback readiness check. ``localhost`` (not ``127.0.0.1``) so the
+ probe resolves the same way the HTTP client and the sidecar's own
+ bind do — Node binds the IPv6 loopback ``[::1]`` on Windows."""
+ try:
+ _, writer = await asyncio.wait_for(
+ asyncio.open_connection(host, port),
+ timeout=_PROBE_TIMEOUT_SECONDS,
+ )
+ writer.close()
+ try:
+ await writer.wait_closed()
+ except (ConnectionResetError, OSError):
+ pass
+ return True
+ except (asyncio.TimeoutError, ConnectionRefusedError, OSError):
+ return False
+
+
+def executor_port() -> int:
+ return int(os.environ.get("NODEJS_EXECUTOR_PORT") or 5680)
+
+
+def _sidecar_dir() -> Path:
+ # <server>/nodes/code/_runtime.py -> <server>/nodejs
+ return Path(__file__).resolve().parents[2] / "nodejs"
+
+
+class NodeJSExecutorRuntime(BaseProcessSupervisor):
+ name = "nodejs-executor"
+
+ pipe_streams = True
+ terminate_grace_seconds = 5.0
+ graceful_shutdown = sys.platform == "win32"
+
+ # ---- BaseProcessSupervisor overrides ---------------------------------
+
+ async def _pre_spawn(self) -> None:
+ if shutil.which("node") is None:
+ raise RuntimeError(
+ "Node.js not found on PATH — the JS/TS executor sidecar "
+ "requires the same Node 22+ install as the rest of OpenCompany."
+ )
+ if not (_sidecar_dir() / "dist" / "index.js").is_file():
+ raise RuntimeError(
+ "Node.js executor bundle missing (server/nodejs/dist/index.js). "
+ "Run `company build` to produce it."
+ )
+
+ def binary_path(self) -> Path:
+ return Path(shutil.which("node") or "node")
+
+ def argv(self) -> list[str]:
+ return [str(self.binary_path()), str(_sidecar_dir() / "dist" / "index.js")]
+
+ def cwd(self) -> Path:
+ return _sidecar_dir()
+
+ def env(self) -> dict[str, str]:
+ return {**os.environ, "NODEJS_EXECUTOR_PORT": str(executor_port())}
+
+ async def health_check(self) -> bool:
+ if not self.is_running():
+ return False
+ return await _probe_tcp_port(executor_port())
+
+ async def ensure_started(self) -> None:
+ """Start the sidecar unless something already serves the port,
+ then wait until it accepts connections.
+
+ A listening port means a previously spawned instance (possibly by
+ another backend process) or an externally managed executor — both
+ are left alone. Idempotent like ``start()``.
+ """
+ if await _probe_tcp_port(executor_port()):
+ return
+ await self.start()
+ for _ in range(50): # ~15 s ceiling; the bundled sidecar boots in <2 s
+ if await _probe_tcp_port(executor_port()):
+ return
+ await asyncio.sleep(0.3)
+ raise RuntimeError(
+ f"Node.js executor did not become ready on port {executor_port()}"
+ )
+
+ def _extra_status(self) -> dict:
+ base = super()._extra_status()
+ return {**base, "port": executor_port()}
+
+
+def get_nodejs_executor_runtime() -> NodeJSExecutorRuntime:
+ """Return the Node.js executor runtime singleton."""
+ return NodeJSExecutorRuntime.get_instance()
diff --git a/server/nodes/code/javascript_executor/__init__.py b/server/nodes/code/javascript_executor/__init__.py
index 38b1c47c..1aa3b0bc 100644
--- a/server/nodes/code/javascript_executor/__init__.py
+++ b/server/nodes/code/javascript_executor/__init__.py
@@ -20,10 +20,11 @@ class JavaScriptExecutorNode(CodeExecutorBase):
@Operation("execute")
async def execute_op(self, ctx: NodeContext, params: CodeExecutorParams) -> Any:
"""Inlined from handlers/code.py (Wave 11.D.2). Dispatches to the
- persistent Node.js server via the shared NodeJSClient singleton."""
+ backend-supervised Node.js sidecar; ``acquire_client`` spawns it
+ on demand (first JS/TS execution) in every run mode."""
from aiohttp import ClientConnectorError
- from .._nodejs import get_nodejs_client
+ from .._nodejs import acquire_client, executor_base_url
if not params.code.strip():
raise NodeUserError("No code provided")
@@ -31,22 +32,21 @@ class JavaScriptExecutorNode(CodeExecutorBase):
input_data["workspace_dir"] = ctx.workspace_dir or ""
try:
- result = await get_nodejs_client().execute(
+ client = await acquire_client()
+ result = await client.execute(
code=params.code,
input_data=input_data,
timeout=params.timeout * 1000,
language="javascript",
)
- except ClientConnectorError as exc:
- # Sidecar not running -- bare aiohttp.ClientConnectorError is
- # opaque to the LLM. Tell it what's actually wrong and which
- # tool can substitute.
+ except (ClientConnectorError, RuntimeError) as exc:
+ # Spawn or connect failed -- bare errors are opaque to the
+ # LLM. Tell it what's actually wrong and which tool can
+ # substitute.
raise NodeUserError(
- "JavaScript executor is not running (cannot reach the "
- "Node.js sidecar on localhost:5680). Start the dev runner "
- "(it spawns the Node executor automatically), or fall back "
- "to python_executor for similar logic. Underlying: "
- f"{exc}"
+ "JavaScript executor is unavailable (Node.js sidecar at "
+ f"{executor_base_url()}). Fall back to python_executor "
+ f"for similar logic. Underlying: {exc}"
) from exc
if not result.get("success"):
diff --git a/server/nodes/code/typescript_executor/__init__.py b/server/nodes/code/typescript_executor/__init__.py
index bd0372d3..86900e3d 100644
--- a/server/nodes/code/typescript_executor/__init__.py
+++ b/server/nodes/code/typescript_executor/__init__.py
@@ -22,7 +22,7 @@ class TypeScriptExecutorNode(CodeExecutorBase):
"""Inlined from handlers/code.py (Wave 11.D.2)."""
from aiohttp import ClientConnectorError
- from .._nodejs import get_nodejs_client
+ from .._nodejs import acquire_client, executor_base_url
if not params.code.strip():
raise NodeUserError("No code provided")
@@ -30,19 +30,18 @@ class TypeScriptExecutorNode(CodeExecutorBase):
input_data["workspace_dir"] = ctx.workspace_dir or ""
try:
- result = await get_nodejs_client().execute(
+ client = await acquire_client()
+ result = await client.execute(
code=params.code,
input_data=input_data,
timeout=params.timeout * 1000,
language="typescript",
)
- except ClientConnectorError as exc:
+ except (ClientConnectorError, RuntimeError) as exc:
raise NodeUserError(
- "TypeScript executor is not running (cannot reach the "
- "Node.js sidecar on localhost:5680). Start the dev runner "
- "(it spawns the Node executor automatically), or fall back "
- "to python_executor for similar logic. Underlying: "
- f"{exc}"
+ "TypeScript executor is unavailable (Node.js sidecar at "
+ f"{executor_base_url()}). Fall back to python_executor "
+ f"for similar logic. Underlying: {exc}"
) from exc
if not result.get("success"):
diff --git a/server/services/_supervisor/client.py b/server/services/_supervisor/client.py
index febff021..2d6133be 100644
--- a/server/services/_supervisor/client.py
+++ b/server/services/_supervisor/client.py
@@ -1,7 +1,7 @@
"""Client / in-process-task supervisor.
For services that don't own a subprocess but still have a lifecycle:
-HTTP clients pointed at an externally-spawned daemon (nodejs_client),
+HTTP clients pointed at an externally-spawned daemon,
or in-process tasks like the python-telegram-bot polling loop.
"""
diff --git a/server/tests/nodes/test_code_fs_process.py b/server/tests/nodes/test_code_fs_process.py
index 3fe55de6..0695b9eb 100644
--- a/server/tests/nodes/test_code_fs_process.py
+++ b/server/tests/nodes/test_code_fs_process.py
@@ -178,7 +178,7 @@ class TestJavascriptExecutor:
)
with patch(
- "nodes.code._nodejs.get_nodejs_client",
+ "nodes.code._nodejs.acquire_client",
return_value=fake_client,
):
result = await harness.execute(
@@ -217,7 +217,7 @@ class TestJavascriptExecutor:
)
with patch(
- "nodes.code._nodejs.get_nodejs_client",
+ "nodes.code._nodejs.acquire_client",
return_value=fake_client,
):
result = await harness.execute("javascriptExecutor", {"code": "oops"})
@@ -231,7 +231,7 @@ class TestJavascriptExecutor:
fake_client.execute = AsyncMock(side_effect=ConnectionRefusedError("Cannot connect to host localhost:5680"))
with patch(
- "nodes.code._nodejs.get_nodejs_client",
+ "nodes.code._nodejs.acquire_client",
return_value=fake_client,
):
result = await harness.execute("javascriptExecutor", {"code": "output = 1"})
@@ -258,7 +258,7 @@ class TestTypescriptExecutor:
)
with patch(
- "nodes.code._nodejs.get_nodejs_client",
+ "nodes.code._nodejs.acquire_client",
return_value=fake_client,
):
result = await harness.execute(
@@ -289,7 +289,7 @@ class TestTypescriptExecutor:
)
with patch(
- "nodes.code._nodejs.get_nodejs_client",
+ "nodes.code._nodejs.acquire_client",
return_value=fake_client,
):
result = await harness.execute("typescriptExecutor", {"code": "output = foo"})
diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.py
index 31114f93..548791e9 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -109,6 +109,7 @@ _FORBIDDEN_IMPORT_FRAGMENTS = (
"services.claude_code_service",
"services.maps", # Wave 11.I, N: -> nodes/location/_service
"services.node_option_loaders", # Wave 11.I, M: -> nodes/<plugin>/_option_loaders
+ "services.nodejs_client", # July 2026: -> nodes/code/_client (plugin-owned)
"routers.twitter",
"routers.google",
"routers.android",
@@ -273,6 +274,7 @@ _STALE_SERVICE_PATHS = (
"services/websocket_client.py", # dead re-export shim, deleted in E
"services/maps.py", # Wave 11.I, N: -> nodes/location/_service.py
"services/node_option_loaders", # Wave 11.I, M: -> nodes/<plugin>/_option_loaders.py
+ "services/nodejs_client.py", # July 2026: -> nodes/code/_client.py (plugin-owned)
"routers/twitter.py",
"routers/google.py",
"routers/android.py",