Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(server): run the JS executor sidecar and plugin CLIs on bun
trohitg025860e7e5af
diff --git a/server/core/config.py b/server/core/config.pyindex 5f94e8ca..f8aee57f 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -334,7 +334,7 @@ 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 settings live in the plugin: nodes/code/_runtime.py+ # JS executor sidecar 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).diff --git a/server/core/js_runtime.py b/server/core/js_runtime.pynew file mode 100644index 00000000..405f93cb--- /dev/null+++ b/server/core/js_runtime.py@@ -0,0 +1,107 @@+"""The JavaScript runtime the backend spawns: bun.++One module owns how the backend finds ``bun`` and how it extends the+shared OpenCompany packages tree, so the JS executor sidecar, the CLI+plugins that ship as npm packages (claude-code, edgymeow, agent-browser,+cf, vercel) and the codex provider all resolve the same binary and lay+packages out the same way. There is no Node and no npm anywhere on this+path: bun installs from the npm registry, runs the packages' ``bin``+entries on its own runtime, and shims ``node`` for their lifecycle+scripts.++Resolution: ``OPENCOMPANY_BUN_BIN`` (the desktop shell points it at the+bundled runtime) else the first ``bun`` on PATH. The desktop shell also+prepends its bundled runtime dir to PATH, so the override is belt and+braces.++Shared tree layout (``core.paths.packages_dir()``, ``<DATA_DIR>/packages/``):+one ``package.json`` + ``bun.lock`` + ``node_modules/`` covering every+OpenCompany-managed npm package. ``bun add --cwd <packages_dir> <spec>``+extends it idempotently; the bin shims land in ``node_modules/.bin/``+as ``<name>`` on POSIX and ``<name>.exe`` (plus a ``.bunx`` metadata+file) on Windows.++Stdlib-only apart from :mod:`core.paths`.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++from core.paths import packages_dir++ENV_BUN_BIN = "OPENCOMPANY_BUN_BIN"++INSTALL_HINT = "install bun from https://bun.sh (the desktop app bundles it)"++_TREE_MANIFEST = {"name": "opencompany-packages", "private": True}+++def bun_binary() -> str | None:+ """Absolute path to ``bun``, or ``None`` when it is not available."""+ override = os.environ.get(ENV_BUN_BIN, "").strip()+ if override and Path(override).is_file():+ return override+ return shutil.which("bun")+++def require_bun(purpose: str) -> str:+ """Like :func:`bun_binary` but raises a user-readable error on miss."""+ found = bun_binary()+ if not found:+ raise RuntimeError(f"bun not found on PATH (or {ENV_BUN_BIN}) — {purpose} needs it; {INSTALL_HINT}")+ return found+++def bin_shim_name(name: str) -> str:+ """The ``node_modules/.bin`` entry bun writes for a package ``bin``."""+ return f"{name}.exe" if sys.platform == "win32" else name+++def shared_tree_bin(name: str) -> Path:+ """``<packages_dir>/node_modules/.bin/<name>[.exe]``."""+ return packages_dir() / "node_modules" / ".bin" / bin_shim_name(name)+++def ensure_shared_tree(root: Path | None = None) -> Path:+ """Create the shared tree root with a minimal manifest if missing."""+ tree = root or packages_dir()+ tree.mkdir(parents=True, exist_ok=True)+ manifest = tree / "package.json"+ if not manifest.exists():+ manifest.write_text(json.dumps(_TREE_MANIFEST, indent=2) + "\n", encoding="utf-8")+ return tree+++def add_package(spec: str, *, trust: bool = False, root: Path | None = None) -> subprocess.CompletedProcess[str]:+ """Blocking ``bun add`` of ``spec`` into the shared tree.++ ``trust`` opts the package into running its lifecycle scripts (bun+ blocks them by default); pass it only for packages whose postinstall+ materialises something the plugin needs (edgymeow's Go binary).+ Returns the completed process; callers decide what a failure means.+ """+ bun = require_bun(f"installing {spec}")+ tree = ensure_shared_tree(root)+ argv = [bun, "add", "--cwd", str(tree), "--no-progress"]+ if trust:+ argv.append("--trust")+ argv.append(spec)+ return subprocess.run(argv, capture_output=True, text=True)+++__all__ = [+ "ENV_BUN_BIN",+ "INSTALL_HINT",+ "add_package",+ "bin_shim_name",+ "bun_binary",+ "ensure_shared_tree",+ "require_bun",+ "shared_tree_bin",+]diff --git a/server/core/paths.py b/server/core/paths.pyindex 01f7036a..ea855b1c 100644--- a/server/core/paths.py+++ b/server/core/paths.py@@ -35,12 +35,13 @@ above (Wave 14):- ``<DATA_DIR>/claude/`` Claude Code auth state (CLAUDE_CONFIG_DIR)- ``<DATA_DIR>/packages/`` Single shared OpenCompany install- root. Holds one ``package.json`` + ``package-lock.json`` +- ``node_modules/`` covering every OpenCompany-managed npm package- (``@anthropic-ai/claude-code``, ``edgymeow``, ``agent-browser``).- Each plugin's ``_install.py`` runs- ``npm install <pkg> --prefix <packages_dir>`` to extend the tree- idempotently — npm itself manages the dep graph.+ root. Holds one ``package.json`` + ``bun.lock`` + ``node_modules/``+ covering every OpenCompany-managed npm-registry package+ (``@anthropic-ai/claude-code``, ``edgymeow``, ``agent-browser``,+ ``cf``, ``vercel``). Each plugin's ``_install.py`` calls+ ``core.js_runtime.add_package`` (``bun add --cwd <packages_dir>``)+ to extend the tree idempotently — bun manages the dep graph and+ runs the bin shims on its own runtime; no Node or npm.- ``<DATA_DIR>/packages/stripe/`` Stripe CLI binary (non-npm)- ``<DATA_DIR>/packages/temporal/`` Temporal CLI binary (non-npm,pooch-managed)@@ -61,8 +62,9 @@ under ``<DATA_DIR>/`` means a single ``mv ~/.opencompany /backup``carries the entire OpenCompany footprint.Out of scope: globally-installed binaries (Himalaya — system-package manager) and npm `package.json` deps managed by bun (none-remain after the WhatsApp migration).+package manager) and the dev workspace's own `package.json` deps+(none of the runtime packages remain there after the WhatsApp+migration).Shipped example workflows live at ``<repo>/.opencompany/workflows/`` —git-tracked seed JSONs auto-imported on first launch bydiff --git a/server/main.py b/server/main.pyindex 49e5f512..505379bb 100644--- a/server/main.py+++ b/server/main.py@@ -468,7 +468,7 @@ async def lifespan(app: FastAPI):# Stop every supervisor that registered itself via# services._supervisor.register_supervisor() (WhatsApp runtime,- # Node.js executor runtime, Temporal dev server).+ # JS executor runtime, Temporal dev server).from services._supervisor import shutdown_all_supervisorsawait shutdown_all_supervisors()diff --git a/server/nodejs/package.json b/server/nodejs/package.jsonindex 9219b02c..8f32ff6a 100644--- a/server/nodejs/package.json+++ b/server/nodejs/package.json@@ -1,13 +1,13 @@{"name": "opencompany-nodejs-executor","version": "1.0.0",- "description": "Persistent Node.js server for JavaScript/TypeScript code execution",+ "description": "Persistent bun-hosted server for JavaScript/TypeScript code execution","type": "module","main": "dist/index.js","scripts": {- "build": "esbuild src/index.ts --bundle --platform=node --target=node18 --format=esm --packages=external --outfile=dist/index.js",- "start": "node dist/index.js",- "dev": "tsx watch src/index.ts"+ "build": "bun build src/index.ts --target=bun --outfile=dist/index.js",+ "start": "bun dist/index.js",+ "dev": "bun --watch src/index.ts"},"dependencies": {"express": "^5.2.1"@@ -15,11 +15,9 @@"devDependencies": {"@types/express": "^5.0.6","@types/node": "^22.19.18",- "esbuild": "^0.28.1",- "tsx": "^4.21.0","typescript": "^5.9.3"},"engines": {- "node": ">=18.0.0"+ "bun": ">=1.4.0"}}diff --git a/server/nodejs/src/index.ts b/server/nodejs/src/index.tsindex 9b5ffe0d..af063fe7 100644--- a/server/nodejs/src/index.ts+++ b/server/nodejs/src/index.ts@@ -1,11 +1,12 @@/**- * Node.js Code Execution Server+ * JS Code Execution Server (runs on bun)* Thin HTTP layer - all parameters from environment or requests*/import express, { Request, Response, NextFunction } from 'express';import vm from 'node:vm';import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -22,6 +23,12 @@ const HOST = process.env.NODEJS_EXECUTOR_HOST ?? 'localhost';const BODY_LIMIT = process.env.NODEJS_EXECUTOR_BODY_LIMIT ?? '10mb';const USER_PACKAGES_DIR = process.env.NODEJS_USER_PACKAGES_DIR ?? path.join(__dirname, '..', 'user-packages');+// The runtime this process runs on is also the package manager for the+// user-packages tree: `process.execPath` is bun, and `bun add` installs+// from the npm registry with no node or npm on the machine.+const BUN = process.execPath;+const bunVersion = (globalThis as { Bun?: { version: string } }).Bun?.version ?? null;+const app = express();app.use(express.json({ limit: BODY_LIMIT }));@@ -37,6 +44,10 @@ app.get('/health', (_req: Request, res: Response) => {res.json({status: 'healthy',service: 'nodejs-executor',+ runtime: bunVersion ? 'bun' : 'node',+ runtime_version: bunVersion ?? process.version,+ // Kept for the Python client's health dict; under bun this is the+ // Node API level bun reports, not a Node install.node_version: process.version,});});@@ -71,8 +82,8 @@ app.post('/execute', (req: Request, res: Response) => {try {const context = vm.createContext(sandbox);// This service IS the sandboxed JS executor for the pythonExecutor /- // javascriptExecutor workflow nodes. Node's `vm` is not a security- // boundary (per https://nodejs.org/api/vm.html#vmcreatecontextcontextobject-options);+ // javascriptExecutor workflow nodes. `vm` is not a security boundary+ // (per https://nodejs.org/api/vm.html#vmcreatecontextcontextobject-options);// the deployment context is: server binds to localhost only (line 16,// default 'localhost') and is invoked exclusively by the same-machine// Python backend via NodeJSClient. Public network exposure is the@@ -96,6 +107,16 @@ app.post('/execute', (req: Request, res: Response) => {}});+function ensureUserPackagesTree(): void {+ if (!existsSync(USER_PACKAGES_DIR)) mkdirSync(USER_PACKAGES_DIR, { recursive: true });+ const manifest = path.join(USER_PACKAGES_DIR, 'package.json');+ if (!existsSync(manifest)) {+ // bun add would write one, but a private manifest keeps the tree from+ // ever looking publishable and pins its name.+ writeFileSync(manifest, JSON.stringify({ name: 'opencompany-user-packages', private: true }, null, 2) + '\n');+ }+}+// Install packages - package list from request.// Localhost-only service (see server.listen at the bottom); same trust// boundary as the /execute sandbox. No request-rate limiting because the@@ -117,23 +138,32 @@ app.post('/packages/install', (req: Request, res: Response) => {}try {+ ensureUserPackagesTree();// execFileSync (argv array, no shell) instead of execSync with template// string. The regex above already validates names, but going through// execFileSync removes the shell from the path entirely as// defense-in-depth.- execFileSync('npm', ['install', ...packages], { cwd: USER_PACKAGES_DIR, timeout: 60000 });+ execFileSync(BUN, ['add', '--no-progress', ...packages], { cwd: USER_PACKAGES_DIR, timeout: 60000 });res.json({ success: true, message: `Installed: ${packages.join(', ')}` });} catch (error) {res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) });}});-// List packages — same localhost-only trust boundary as above.+// List packages — same localhost-only trust boundary as above. The tree's+// own manifest is the source of truth (what `bun add` wrote), so no+// package-manager listing command is needed.// codeql[js/missing-rate-limiting]app.get('/packages', (_req: Request, res: Response) => {try {- const output = execFileSync('npm', ['list', '--json', '--depth=0'], { cwd: USER_PACKAGES_DIR, encoding: 'utf-8' });- res.json({ success: true, packages: JSON.parse(output).dependencies || {} });+ const manifest = JSON.parse(readFileSync(path.join(USER_PACKAGES_DIR, 'package.json'), 'utf-8')) as {+ dependencies?: Record<string, string>;+ };+ const installed: Record<string, { version: string }> = {};+ for (const [name, version] of Object.entries(manifest.dependencies ?? {})) {+ if (existsSync(path.join(USER_PACKAGES_DIR, 'node_modules', name))) installed[name] = { version };+ }+ res.json({ success: true, packages: installed });} catch {res.json({ success: true, packages: {} });}@@ -145,5 +175,5 @@ app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {});app.listen(PORT, HOST, () => {- console.log(`Node.js Executor running on http://${HOST}:${PORT}`);+ console.log(`JS Executor running on http://${HOST}:${PORT}`);});diff --git a/server/nodes/agent/claude_code_agent/_oauth.py b/server/nodes/agent/claude_code_agent/_oauth.pyindex 152b6722..4e0415da 100644--- a/server/nodes/agent/claude_code_agent/_oauth.py+++ b/server/nodes/agent/claude_code_agent/_oauth.py@@ -1,10 +1,11 @@"""Claude OAuth — project-local install + the documented `claude auth` subcommands.-The Claude Code CLI lives in the shared OpenCompany npm tree at-``<DATA_DIR>/packages/node_modules/.bin/claude[.cmd]`` (on-demand-``npm install`` on first use, alongside ``edgymeow`` /-``agent-browser`` — one ``package.json`` + ``package-lock.json``-managed by npm itself). ``CLAUDE_CONFIG_DIR`` points at+The Claude Code CLI lives in the shared OpenCompany packages tree at+``<DATA_DIR>/packages/node_modules/.bin/claude[.exe]`` (on-demand+``bun add`` on first use through :mod:`core.js_runtime`, alongside+``edgymeow`` / ``agent-browser`` — one ``package.json`` + ``bun.lock``+managed by bun; the shim runs on the bun runtime, no Node or npm+involved). ``CLAUDE_CONFIG_DIR`` points at``<DATA_DIR>/claude/`` so the CLI manages its own credentialsinside the project tree, isolated from the user's own``~/.claude/`` session. The path constants here are composed@@ -37,11 +38,9 @@ from __future__ import annotationsimport asyncioimport jsonimport os-import shutil-import subprocess-import sysfrom typing import Any, Dict+from core.js_runtime import add_package, shared_tree_binfrom core.logging import get_loggerfrom core.paths import data_path, packages_dirfrom services.events.cli import run_cli_command@@ -60,9 +59,9 @@ logger = get_logger(__name__)## ``OPENCOMPANY_CLAUDE_DIR`` -> ``<DATA_DIR>/claude/`` auth state# (CLAUDE_CONFIG_DIR)-# ``OPENCOMPANY_NPM_ROOT`` -> ``<DATA_DIR>/packages/`` shared npm tree-# (``--prefix`` target;-# also holds+# ``OPENCOMPANY_NPM_ROOT`` -> ``<DATA_DIR>/packages/`` shared packages tree+# (``bun add --cwd``+# target; also holds# ``edgymeow`` /# ``agent-browser``)OPENCOMPANY_CLAUDE_DIR = data_path("claude")@@ -86,13 +85,12 @@ def claude_binary_path() -> str:AND the agent spawn (``_provider.py``) so both surfaces use thesame binary + ``CLAUDE_CONFIG_DIR``-isolated credentials.- Landed under the shared OpenCompany npm tree at+ Landed under the shared OpenCompany packages tree at``OPENCOMPANY_NPM_ROOT`` (= ``<DATA_DIR>/packages/``) so a single- ``package.json`` + ``package-lock.json`` covers claude /- edgymeow / agent-browser.+ ``package.json`` + ``bun.lock`` covers claude / edgymeow /+ agent-browser / cf / vercel."""- bin_name = "claude.cmd" if sys.platform == "win32" else "claude"- bin_path = OPENCOMPANY_NPM_ROOT / "node_modules" / ".bin" / bin_name+ bin_path = shared_tree_bin("claude")if bin_path.exists():return str(bin_path)@@ -109,19 +107,12 @@ def claude_binary_path() -> str:npm_spec = f"{npm_spec}@{cfg.package_version}"logger.info("Installing %s into shared tree %s", npm_spec, OPENCOMPANY_NPM_ROOT)- OPENCOMPANY_NPM_ROOT.mkdir(parents=True, exist_ok=True)- npm_cmd = shutil.which("npm")- if not npm_cmd:- raise FileNotFoundError("npm not found on PATH")-- result = subprocess.run(- [npm_cmd, "install", npm_spec, "--prefix", str(OPENCOMPANY_NPM_ROOT), "--no-audit", "--no-fund"],- capture_output=True,- text=True,- )+ # The package's postinstall stages its native launcher; trust it so+ # the install matches what `npm install` used to produce.+ result = add_package(npm_spec, trust=True, root=OPENCOMPANY_NPM_ROOT)if result.returncode != 0:- logger.error(f"npm install {npm_spec} failed: {result.stderr}")+ logger.error(f"bun add {npm_spec} failed: {result.stderr}")raise RuntimeError(f"Failed to install {npm_spec}: {result.stderr}")if not bin_path.exists():diff --git a/server/nodes/browser/_install.py b/server/nodes/browser/_install.pyindex 131c0259..caf4a1ad 100644--- a/server/nodes/browser/_install.py+++ b/server/nodes/browser/_install.py@@ -1,23 +1,24 @@"""``agent-browser`` local install — landed in the shared OpenCompany-npm tree at :func:`core.paths.packages_dir` (``<DATA_DIR>/packages/``).+packages tree at :func:`core.paths.packages_dir` (``<DATA_DIR>/packages/``).All OpenCompany-managed npm packages (``agent-browser``,-``@anthropic-ai/claude-code``, ``edgymeow``) live under a single-``<packages_dir>/node_modules/`` so npm manages them with one-``package.json`` + ``package-lock.json`` rather than us carving out-per-service install trees. ``npm install <pkg> --prefix <packages_dir>``-extends the shared tree idempotently.+``@anthropic-ai/claude-code``, ``edgymeow``, ``cf``, ``vercel``) live+under a single ``<packages_dir>/node_modules/`` managed by bun through+one ``package.json`` + ``bun.lock`` rather than us carving out+per-service install trees. :func:`core.js_runtime.add_package`+(``bun add --cwd <packages_dir> <spec>``) extends the shared tree+idempotently and the bin shim runs on the bun runtime; no Node or npm+is involved. agent-browser's postinstall is trusted so its platform+binary lands the way the package expects."""from __future__ import annotations-import shutilimport subprocess-import sysfrom typing import Optional+from core.js_runtime import add_package, bun_binary, shared_tree_binfrom core.logging import get_logger-from core.paths import packages_dirlogger = get_logger(__name__)@@ -26,27 +27,19 @@ _NPM_SPEC = "agent-browser@latest"def agent_browser_binary_path() -> Optional[str]:"""Return path to the agent-browser CLI, installing on miss."""- root = packages_dir()- bin_name = "agent-browser.cmd" if sys.platform == "win32" else "agent-browser"- bin_path = root / "node_modules" / ".bin" / bin_name+ bin_path = shared_tree_bin("agent-browser")if bin_path.exists():return str(bin_path)- npm_cmd = shutil.which("npm")- if not npm_cmd:- logger.warning("[browser] npm not on PATH; cannot install %s", _NPM_SPEC)+ if bun_binary() is None:+ logger.warning("[browser] bun not available; cannot install %s", _NPM_SPEC)return None- logger.info("[browser] installing %s into shared tree %s", _NPM_SPEC, root)- root.mkdir(parents=True, exist_ok=True)- result = subprocess.run(- [npm_cmd, "install", _NPM_SPEC, "--prefix", str(root), "--no-audit", "--no-fund"],- capture_output=True,- text=True,- )+ logger.info("[browser] installing %s into the shared packages tree", _NPM_SPEC)+ result = add_package(_NPM_SPEC, trust=True)if result.returncode != 0 or not bin_path.exists():- logger.error("[browser] npm install failed: %s", result.stderr.strip())+ logger.error("[browser] bun add %s failed: %s", _NPM_SPEC, result.stderr.strip())return None# Fetch the Chrome-for-Testing runtime (agent-browser's documenteddiff --git a/server/nodes/browser/_service.py b/server/nodes/browser/_service.pyindex d65f1a6a..5baa5644 100644--- a/server/nodes/browser/_service.py+++ b/server/nodes/browser/_service.py@@ -11,7 +11,7 @@ agent-browser is a OpenCompany-managed local install (see``nodes/browser/_install.py``) — same pattern as Claude Code'sproject-local CLI. The binary lives at``<package_dir("browser")>/npm/node_modules/.bin/agent-browser[.cmd]``-and is installed via ``npm install agent-browser --prefix <...>`` on+and is installed via ``bun add agent-browser`` into the shared packages tree onfirst use. No dependency on the workspace ``package.json`` /``node_modules`` / bun lockfile.@@ -381,7 +381,7 @@ class BrowserService:return linefinally:- # npx -> node -> agent-browser daemon -> Chromium. Killing only+ # bun shim -> bun -> agent-browser daemon -> Chromium. Killing only# proc.pid leaves the daemon orphaned. psutil.children(recursive=True)# walks the tree natively on every platform.try:@@ -440,7 +440,7 @@ async def shutdown_browser_service() -> None:cleanup API -- it stops the background process and releases file locks.Reads the module singleton directly instead of ``get_browser_service()``:- that accessor lazily *installs* agent-browser (``npm install`` over the+ that accessor lazily *installs* agent-browser (``bun add`` over thenetwork) on first call, and a process that never used the browser hasno daemon to close. Running the installer at teardown blocked the eventloop for as long as npm took and wedged every graceful shutdown.diff --git a/server/nodes/browser/browser/__init__.py b/server/nodes/browser/browser/__init__.pyindex 3af335be..4aec49d8 100644--- a/server/nodes/browser/browser/__init__.py+++ b/server/nodes/browser/browser/__init__.py@@ -357,8 +357,8 @@ class BrowserNode(ActionNode):if not svc:raise RuntimeError("agent-browser not installed. OpenCompany installs it on first use "- "with `npm install agent-browser --prefix <DATA_DIR>/packages`; check "- "that npm is on PATH and see the backend log for the install error.",+ "with `bun add agent-browser` into <DATA_DIR>/packages; check that bun is "+ "available and see the backend log for the install error.",)op = params.operationdiff --git a/server/nodes/cloudflare/_handlers.py b/server/nodes/cloudflare/_handlers.pyindex 7013f094..d8eee937 100644--- a/server/nodes/cloudflare/_handlers.py+++ b/server/nodes/cloudflare/_handlers.py@@ -63,7 +63,7 @@ logger = get_logger(__name__)_LOGIN_ARGS = ["auth", "login", "--force"]_LOGIN_TIMEOUT_SECONDS = 600# The frontend drops WS requests after 30s. A first-ever login pays a-# cold npm install inside this handler — answer within this budget no+# cold `bun add` inside this handler — answer within this budget no# matter what and let the flow continue in the background._RESPONSE_BUDGET_SECONDS = 22# Retained head of the CLI's output, used only for the failure log line.@@ -113,7 +113,7 @@ async def _start_login_flow() -> Dict[str, Any]:logger.warning("[Cloudflare] cf CLI install failed: %s", e)return {"success": False,- "error": f"cf CLI install failed ({e}). Manual install: npm i -g cf",+ "error": f"cf CLI install failed ({e}). Manual install: bun add -g cf",}# Fast path: a live session already exists (user logged in via adiff --git a/server/nodes/cloudflare/_install.py b/server/nodes/cloudflare/_install.pyindex 62f1422b..b3c7af4e 100644--- a/server/nodes/cloudflare/_install.py+++ b/server/nodes/cloudflare/_install.py@@ -1,12 +1,14 @@-"""Cloudflare CLI (`cf`) auto-installer — npm, pinned, project-local.+"""Cloudflare CLI (`cf`) auto-installer — bun, pinned, project-local.The official Cloudflare CLI ships as the npm package ``cf`` (a-Technical Preview — "the next version of Wrangler"). It lands in the-shared OpenCompany npm tree at :func:`core.paths.packages_dir`+technical preview, "the next version of Wrangler"). It lands in the+shared OpenCompany packages tree at :func:`core.paths.packages_dir`(``<DATA_DIR>/packages/``), the same single ``package.json`` +-``node_modules/`` that holds ``@anthropic-ai/claude-code`` / ``vercel``-/ ``agent-browser``. ``npm install <pkg> --prefix <packages_dir>``-extends the shared tree idempotently.+``node_modules/`` that holds ``@anthropic-ai/claude-code`` / ``edgymeow``+/ ``agent-browser`` / ``vercel``. :func:`core.js_runtime.add_package`+(``bun add --cwd <packages_dir> <spec>``) extends the shared tree+idempotently and the bin shim executes on the bun runtime; no Node or+npm is involved.Unlike the vercel installer, the system-global ``cf`` is deliberatelyNEVER consulted (the gh philosophy): the preview CLI's command surface@@ -19,23 +21,19 @@ terminal is visible to this pinned binary too.Pin ``_NPM_SPEC`` when bumping and re-verify every wrapped command via``cf <cmd> --help-full`` (whatsapp precedent — ``@latest`` makes cold-installs non-reproducible). cf declares ``engines.node >= 22``, which is-ABOVE OpenCompany's own floor of Node 18+ — so this plugin is the one place-that needs a newer Node than the rest of the app, and its error text says-so instead of implying the app requires 22.+installs non-reproducible). cf declares ``engines.node >= 22``; bun+ignores ``engines`` and runs the CLI on its own runtime (verified on+bun 1.4 with no Node on PATH, including ``cf auth whoami``)."""from __future__ import annotationsimport asyncio-import shutil-import subprocess-import sysfrom pathlib import Pathfrom typing import Optional+from core.js_runtime import add_package, shared_tree_binfrom core.logging import get_logger-from core.paths import packages_dirlogger = get_logger(__name__)@@ -59,52 +57,38 @@ def cf_cli_path() -> Optional[Path]:def _shared_tree_bin() -> Path:- bin_name = "cf.cmd" if sys.platform == "win32" else "cf"- return packages_dir() / "node_modules" / ".bin" / bin_name+ return shared_tree_bin("cf")-def _npm_install() -> Path:- """Blocking npm install into the shared tree. Raises on failure."""- root = packages_dir()+def _install() -> Path:+ """Blocking ``bun add`` into the shared tree. Raises on failure."""bin_path = _shared_tree_bin()-- npm_cmd = shutil.which("npm")- if not npm_cmd:- raise RuntimeError(- "npm not on PATH — the cf CLI ships via npm and needs Node.js 22+ "- "(OpenCompany itself runs on Node 18+; only this node needs 22)"- )-- logger.info("[Cloudflare] installing %s into shared tree %s", _NPM_SPEC, root)- root.mkdir(parents=True, exist_ok=True)- result = subprocess.run(- [npm_cmd, "install", _NPM_SPEC, "--prefix", str(root), "--no-audit", "--no-fund"],- capture_output=True,- text=True,- )+ logger.info("[Cloudflare] installing %s into the shared packages tree", _NPM_SPEC)+ result = add_package(_NPM_SPEC)if result.returncode != 0 or not bin_path.exists():- raise RuntimeError(f"npm install {_NPM_SPEC} failed: {result.stderr.strip()[:500]}")-+ raise RuntimeError(f"bun add {_NPM_SPEC} failed: {result.stderr.strip()[:500]}")logger.info("[Cloudflare] cf CLI installed at %s", bin_path)return bin_pathasync def ensure_cf_cli() -> Path:"""Return absolute path to the project-local cf binary, installing- the pinned npm release on miss. Idempotent + concurrent-safe."""+ the pinned release on miss. Idempotent + concurrent-safe."""global _cached_path- existing = cf_cli_path()- if existing:- return existing+ if _cached_path and _cached_path.exists():+ return _cached_pathasync with _install_lock:- existing = cf_cli_path()- if existing:- return existing- # npm install blocks for tens of seconds — keep the event loop free.- installed = await asyncio.to_thread(_npm_install)+ if _cached_path and _cached_path.exists():+ return _cached_path+ target = _shared_tree_bin()+ if target.exists():+ _cached_path = target+ return target+ # The install blocks for tens of seconds — keep the event loop free.+ installed = await asyncio.to_thread(_install)_cached_path = installedreturn installed-__all__ = ["ensure_cf_cli", "cf_cli_path"]+__all__ = ["cf_cli_path", "ensure_cf_cli"]diff --git a/server/nodes/code/__init__.py b/server/nodes/code/__init__.pyindex be15f244..e6601d23 100644--- a/server/nodes/code/__init__.py+++ b/server/nodes/code/__init__.py@@ -1,6 +1,6 @@"""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+The JS executor sidecar (JS/TS code nodes, runs on bun) is plugin-owned: thesupervisor in :mod:`._runtime` spawns it on demand and is registeredhere so ``shutdown_all_supervisors()`` reaches it at lifespan shutdown."""diff --git a/server/nodes/code/_client.py b/server/nodes/code/_client.pyindex 13d5f209..10e51852 100644--- a/server/nodes/code/_client.py+++ b/server/nodes/code/_client.py@@ -1,4 +1,4 @@-"""HTTP client for Node.js code execution server."""+"""HTTP client for the JS code execution sidecar (runs on bun)."""from typing import Any, Dict, List, Optionalimport aiohttp@@ -8,20 +8,20 @@ logger = get_logger(__name__)class NodeJSClient:- """Async HTTP client for Node.js executor service."""+ """Async HTTP client for the JS executor service."""def __init__(self, base_url: str, timeout: int = 30):"""Initialize client with base URL and timeout.Args:- base_url: Base URL of Node.js server (composed from NODEJS_EXECUTOR_PORT; defaults live in .env.template)+ base_url: Base URL of the sidecar (composed from NODEJS_EXECUTOR_PORT; defaults live in .env.template)timeout: Default request timeout in seconds"""self._base_url = base_url.rstrip("/")self._timeout = aiohttp.ClientTimeout(total=timeout)async def health_check(self) -> Dict[str, Any]:- """Check if Node.js server is healthy.+ """Check if the sidecar is healthy.Returns:Health status dict with status, service, node_versiondiff --git a/server/nodes/code/_nodejs.py b/server/nodes/code/_nodejs.pyindex a3d3d997..3b24304b 100644--- a/server/nodes/code/_nodejs.py+++ b/server/nodes/code/_nodejs.py@@ -1,7 +1,7 @@-"""Shared Node.js executor access for the JS/TS plugins.+"""Shared JS executor sidecar access for the JS/TS plugins.Both ``javascript_executor`` and ``typescript_executor`` dispatch-through the same persistent Node.js sidecar. This helper owns the+through the same persistent bun-hosted sidecar. This helper owns thesingleton HTTP client AND the on-demand spawn: :func:`acquire_client`ensures the backend-supervised runtime (see :mod:`._runtime`) is upbefore handing back the client, so JS/TS nodes work in every modediff --git a/server/nodes/code/_runtime.py b/server/nodes/code/_runtime.pyindex 3e44df28..134895e0 100644--- a/server/nodes/code/_runtime.py+++ b/server/nodes/code/_runtime.py@@ -1,11 +1,12 @@-"""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+"""JS executor runtime — supervises the Express sidecar on bun.++The JS/TS code-executor nodes dispatch to a persistent HTTP server+(source tree at ``server/nodejs/``, bundled by ``bun build`` into a+self-contained ``dist/index.js`` by ``company build``) that runs on the+bun runtime resolved through :mod:`core.js_runtime`. 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 thelifespan's ``shutdown_all_supervisors()``.@@ -24,10 +25,10 @@ from __future__ import annotationsimport asyncioimport os-import shutilimport sysfrom pathlib import Path+from core.js_runtime import ENV_BUN_BIN, INSTALL_HINT, bun_binaryfrom services._supervisor import BaseProcessSupervisor# Sub-second per-attempt probe — a stalled sidecar fails health fast.@@ -39,7 +40,8 @@ async def _probe_tcp_port(port: int, host: str = "localhost") -> bool::data:`_PROBE_TIMEOUT_SECONDS`. Mirrors the Temporal runtime'sloopback readiness check. ``localhost`` (not ``127.0.0.1``) so theprobe resolves the same way the HTTP client and the sidecar's own- bind do — Node binds the IPv6 loopback ``[::1]`` on Windows."""+ bind do — the sidecar listens on whatever ``localhost`` resolves to+ for its runtime, which is the IPv6 loopback ``[::1]`` on Windows."""try:_, writer = await asyncio.wait_for(asyncio.open_connection(host, port),@@ -69,15 +71,6 @@ def _sidecar_dir() -> Path:return server_root() / "nodejs"-def _node_binary() -> str | None:- """The ``node`` executable: ``OPENCOMPANY_NODE_BIN`` (set by the desktop- shell to its bundled runtime) else whatever is first on PATH."""- override = os.environ.get("OPENCOMPANY_NODE_BIN", "").strip()- if override and Path(override).is_file():- return override- return shutil.which("node")--class NodeJSExecutorRuntime(BaseProcessSupervisor):name = "nodejs-executor"@@ -88,19 +81,19 @@ class NodeJSExecutorRuntime(BaseProcessSupervisor):# ---- BaseProcessSupervisor overrides ---------------------------------async def _pre_spawn(self) -> None:- if _node_binary() is None:+ if bun_binary() is None:raise RuntimeError(- "Node.js not found on PATH (or OPENCOMPANY_NODE_BIN) — the JS/TS executor sidecar "- "requires the same Node 18+ install as the rest of OpenCompany."+ f"bun not found on PATH (or {ENV_BUN_BIN}) — the JS/TS executor sidecar "+ f"runs on bun; {INSTALL_HINT}.")if not (_sidecar_dir() / "dist" / "index.js").is_file():raise RuntimeError(- "Node.js executor bundle missing (server/nodejs/dist/index.js). "+ "JS executor bundle missing (server/nodejs/dist/index.js). ""Run `company build` to produce it.")def binary_path(self) -> Path:- return Path(_node_binary() or "node")+ return Path(bun_binary() or "bun")def argv(self) -> list[str]:return [str(self.binary_path()), str(_sidecar_dir() / "dist" / "index.js")]@@ -132,7 +125,7 @@ class NodeJSExecutorRuntime(BaseProcessSupervisor):returnawait asyncio.sleep(0.3)raise RuntimeError(- f"Node.js executor did not become ready on port {executor_port()}"+ f"JS executor did not become ready on port {executor_port()}")def _extra_status(self) -> dict:@@ -141,5 +134,5 @@ class NodeJSExecutorRuntime(BaseProcessSupervisor):def get_nodejs_executor_runtime() -> NodeJSExecutorRuntime:- """Return the Node.js executor runtime singleton."""+ """Return the 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__.pyindex 1aa3b0bc..0133559d 100644--- a/server/nodes/code/javascript_executor/__init__.py+++ b/server/nodes/code/javascript_executor/__init__.py@@ -13,14 +13,14 @@ class JavaScriptExecutorNode(CodeExecutorBase):type = "javascriptExecutor"display_name = "JavaScript Executor"subtitle = "Run JS"- description = "Execute JavaScript code via persistent Node.js server"+ description = "Execute JavaScript code via the persistent JS executor sidecar (bun)"tool_name = "javascript_code"tool_description = "Execute JavaScript code for calculations, data processing, and JSON manipulation. Set output variable with result."@Operation("execute")async def execute_op(self, ctx: NodeContext, params: CodeExecutorParams) -> Any:"""Inlined from handlers/code.py (Wave 11.D.2). Dispatches to the- backend-supervised Node.js sidecar; ``acquire_client`` spawns it+ backend-supervised JS executor sidecar (bun); ``acquire_client`` spawns iton demand (first JS/TS execution) in every run mode."""from aiohttp import ClientConnectorError@@ -44,7 +44,7 @@ class JavaScriptExecutorNode(CodeExecutorBase):# LLM. Tell it what's actually wrong and which tool can# substitute.raise NodeUserError(- "JavaScript executor is unavailable (Node.js sidecar at "+ "JavaScript executor is unavailable (bun sidecar at "f"{executor_base_url()}). Fall back to python_executor "f"for similar logic. Underlying: {exc}") from excdiff --git a/server/nodes/code/typescript_executor/__init__.py b/server/nodes/code/typescript_executor/__init__.pyindex 86900e3d..8e3f5237 100644--- a/server/nodes/code/typescript_executor/__init__.py+++ b/server/nodes/code/typescript_executor/__init__.py@@ -13,9 +13,9 @@ class TypeScriptExecutorNode(CodeExecutorBase):type = "typescriptExecutor"display_name = "TypeScript Executor"subtitle = "Run TS"- description = "Execute TypeScript code via persistent Node.js server with type safety"+ description = "Execute TypeScript code via the persistent JS executor sidecar (bun) with type safety"tool_name = "typescript_code"- tool_description = "Execute TypeScript code via persistent Node.js server with type safety. Set output variable with result."+ tool_description = "Execute TypeScript code via the persistent JS executor sidecar (bun) with type safety. Set output variable with result."@Operation("execute")async def execute_op(self, ctx: NodeContext, params: CodeExecutorParams) -> Any:@@ -39,7 +39,7 @@ class TypeScriptExecutorNode(CodeExecutorBase):)except (ClientConnectorError, RuntimeError) as exc:raise NodeUserError(- "TypeScript executor is unavailable (Node.js sidecar at "+ "TypeScript executor is unavailable (bun sidecar at "f"{executor_base_url()}). Fall back to python_executor "f"for similar logic. Underlying: {exc}") from excdiff --git a/server/nodes/vercel/_handlers.py b/server/nodes/vercel/_handlers.pyindex aaefcd9c..fde8860f 100644--- a/server/nodes/vercel/_handlers.py+++ b/server/nodes/vercel/_handlers.py@@ -49,7 +49,7 @@ _LOGIN_TIMEOUT_SECONDS = 600# output before giving up on this login attempt._URL_DEADLINE_SECONDS = 20# The frontend drops WS requests after 30s (REQUEST_TIMEOUT in-# WebSocketContext). The first-ever login pays a cold `npm install+# WebSocketContext). The first-ever login pays a cold `bun add# vercel` inside this handler, which can blow well past that — so the# handler answers within this budget no matter what, and the login# keeps going in the background (the CLI auto-opens the browser on@@ -170,7 +170,7 @@ async def _start_login_flow() -> Dict[str, Any]:if not binary:return {"success": False,- "error": "Vercel CLI install failed. Manual install: npm i -g vercel (https://vercel.com/docs/cli)",+ "error": "Vercel CLI install failed. Manual install: bun add -g vercel (https://vercel.com/docs/cli)",}auth = vercel_auth_path()@@ -218,7 +218,7 @@ async def handle_vercel_login(data: Dict[str, Any], websocket: WebSocket) -> DicFast path (CLI already installed): the device-flow URL is on theCLI's output within a few seconds — return it so the frontend opens- the browser. Cold path (first run pays ``npm install vercel``): the+ the browser. Cold path (first run pays ``bun add vercel``): thebudget expires first; return a pending success immediately and letthe flow finish in the background — ``vercel login`` opens thebrowser on this machine itself once it reaches the device-flowdiff --git a/server/nodes/vercel/_install.py b/server/nodes/vercel/_install.pyindex 0954d9ee..e9668612 100644--- a/server/nodes/vercel/_install.py+++ b/server/nodes/vercel/_install.py@@ -1,14 +1,16 @@"""Vercel CLI auto-installer.The Vercel CLI ships as the npm package ``vercel`` — it lands in the-shared OpenCompany npm tree at :func:`core.paths.packages_dir`+shared OpenCompany packages tree at :func:`core.paths.packages_dir`(``<DATA_DIR>/packages/``), the same single ``package.json`` +``node_modules/`` that holds ``@anthropic-ai/claude-code`` /-``edgymeow`` / ``agent-browser``. ``npm install <pkg> --prefix-<packages_dir>`` extends the shared tree idempotently.+``edgymeow`` / ``agent-browser`` / ``cf``.+:func:`core.js_runtime.add_package` (``bun add --cwd <packages_dir>+<spec>``) extends the shared tree idempotently and the bin shim runs on+the bun runtime; no Node or npm is involved.-A system install on PATH is preferred; the npm install only fires when-no system binary is found. Pin ``_NPM_SPEC`` when bumping (whatsapp+A system install on PATH is preferred; the install only fires when no+system binary is found. Pin ``_NPM_SPEC`` when bumping (whatsappprecedent — ``@latest`` makes cold installs non-reproducible)."""@@ -16,13 +18,11 @@ from __future__ import annotationsimport asyncioimport shutil-import subprocess-import sysfrom pathlib import Pathfrom typing import Optional+from core.js_runtime import add_package, shared_tree_binfrom core.logging import get_logger-from core.paths import packages_dirlogger = get_logger(__name__)@@ -39,29 +39,16 @@ def vercel_cli_path() -> Optional[Path]:def _shared_tree_bin() -> Path:- bin_name = "vercel.cmd" if sys.platform == "win32" else "vercel"- return packages_dir() / "node_modules" / ".bin" / bin_name+ return shared_tree_bin("vercel")-def _npm_install() -> Path:- """Blocking npm install into the shared tree. Raises on failure."""- root = packages_dir()+def _install() -> Path:+ """Blocking ``bun add`` into the shared tree. Raises on failure."""bin_path = _shared_tree_bin()-- npm_cmd = shutil.which("npm")- if not npm_cmd:- raise RuntimeError("npm not on PATH — install Node.js or the Vercel CLI manually (npm i -g vercel)")-- logger.info("[Vercel] installing %s into shared tree %s", _NPM_SPEC, root)- root.mkdir(parents=True, exist_ok=True)- result = subprocess.run(- [npm_cmd, "install", _NPM_SPEC, "--prefix", str(root), "--no-audit", "--no-fund"],- capture_output=True,- text=True,- )+ logger.info("[Vercel] installing %s into the shared packages tree", _NPM_SPEC)+ result = add_package(_NPM_SPEC)if result.returncode != 0 or not bin_path.exists():- raise RuntimeError(f"npm install {_NPM_SPEC} failed: {result.stderr.strip()[:500]}")-+ raise RuntimeError(f"bun add {_NPM_SPEC} failed: {result.stderr.strip()[:500]}")logger.info("[Vercel] CLI installed at %s", bin_path)return bin_path@@ -73,8 +60,8 @@ async def ensure_vercel_cli() -> Path:Resolution order (stripe idiom):1. Cached path from a prior call (in-process).2. ``shutil.which("vercel")`` — system install on PATH.- 3. Previously-installed shim in the shared npm tree.- 4. Fresh ``npm install`` into the shared tree.+ 3. Previously-installed shim in the shared packages tree.+ 4. Fresh ``bun add`` into the shared tree."""global _cached_pathif _cached_path and _cached_path.exists():@@ -93,8 +80,8 @@ async def ensure_vercel_cli() -> Path:if target.exists():_cached_path = targetreturn target- # npm install blocks for tens of seconds — keep the event loop free.- installed = await asyncio.to_thread(_npm_install)+ # The install blocks for tens of seconds — keep the event loop free.+ installed = await asyncio.to_thread(_install)_cached_path = installedawait _disable_telemetry(installed)return installeddiff --git a/server/nodes/whatsapp/_install.py b/server/nodes/whatsapp/_install.pyindex bd4fe336..a53b8468 100644--- a/server/nodes/whatsapp/_install.py+++ b/server/nodes/whatsapp/_install.py@@ -1,12 +1,19 @@"""``edgymeow`` (WhatsApp Go bridge) local install — landed in the-shared OpenCompany npm tree at :func:`core.paths.packages_dir`+shared OpenCompany packages tree at :func:`core.paths.packages_dir`(``<DATA_DIR>/packages/``).All OpenCompany-managed npm packages (``edgymeow``,-``@anthropic-ai/claude-code``, ``agent-browser``) share a single-``<packages_dir>/node_modules/`` so npm manages them with one-``package.json`` + ``package-lock.json``. ``npm install <pkg>---prefix <packages_dir>`` extends the shared tree idempotently.+``@anthropic-ai/claude-code``, ``agent-browser``, ``cf``, ``vercel``)+share a single ``<packages_dir>/node_modules/`` managed by bun through+one ``package.json`` + ``bun.lock``. :func:`core.js_runtime.add_package`+(``bun add --cwd <packages_dir> <spec>``) extends the shared tree+idempotently; no Node or npm is involved.++edgymeow is the one package whose postinstall matters: it downloads the+platform's Go binary into ``node_modules/edgymeow/bin/``. bun blocks+dependency lifecycle scripts by default, so this install passes+``trust=True`` (bun's ``--trust``), which also records the package in+the tree's ``trustedDependencies``.Pre-fix this lived as a top-level ``edgymeow`` dep in the root``package.json`` and landed at ``<repo>/node_modules/edgymeow/`` via@@ -18,11 +25,10 @@ OpenCompany-managed CLI.from __future__ import annotations-import shutil-import subprocessimport sysfrom typing import Optional+from core.js_runtime import add_package, bun_binaryfrom core.logging import get_loggerfrom core.paths import packages_dir@@ -36,7 +42,7 @@ _NPM_SPEC = "[email protected]"def edgymeow_binary_path() -> Optional[str]:"""Return path to the edgymeow Go binary, installing on miss.- Returns ``None`` if npm is not on PATH or the install failed —+ Returns ``None`` if bun is not available or the install failed —callers should surface this as a user-visible error (the runtimecan't spawn without it). Idempotent: subsequent calls hit theexisting binary on disk.@@ -48,20 +54,14 @@ def edgymeow_binary_path() -> Optional[str]:if bin_path.exists():return str(bin_path)- npm_cmd = shutil.which("npm")- if not npm_cmd:- logger.warning("[whatsapp] npm not on PATH; cannot install %s", _NPM_SPEC)+ if bun_binary() is None:+ logger.warning("[whatsapp] bun not available; cannot install %s", _NPM_SPEC)return None- logger.info("[whatsapp] installing %s into shared tree %s", _NPM_SPEC, root)- root.mkdir(parents=True, exist_ok=True)- result = subprocess.run(- [npm_cmd, "install", _NPM_SPEC, "--prefix", str(root), "--no-audit", "--no-fund"],- capture_output=True,- text=True,- )+ logger.info("[whatsapp] installing %s into the shared packages tree %s", _NPM_SPEC, root)+ result = add_package(_NPM_SPEC, trust=True)if result.returncode != 0 or not bin_path.exists():- logger.error("[whatsapp] npm install failed: %s", result.stderr.strip())+ logger.error("[whatsapp] bun add %s failed: %s", _NPM_SPEC, result.stderr.strip())return Nonelogger.info("[whatsapp] edgymeow installed at %s", bin_path)diff --git a/server/nodes/whatsapp/_runtime.py b/server/nodes/whatsapp/_runtime.pyindex da90fe01..20c9d19c 100644--- a/server/nodes/whatsapp/_runtime.py+++ b/server/nodes/whatsapp/_runtime.py@@ -10,7 +10,7 @@ The binary itself is OpenCompany-managed under the shared OpenCompanynpm tree at ``<DATA_DIR>/packages/`` (resolved by:func:`._install.edgymeow_binary_path` on first use). The installruns through ``asyncio.to_thread`` in ``_pre_spawn`` so the long-``npm install`` (~30 s) doesn't block the asyncio event loop —+``bun add`` (~30 s) doesn't block the asyncio event loop —otherwise the ``StatusBroadcaster._refresh_all_services`` startupfan-out monopolises the loop during boot and uvicorn can't bindthe backend port.@@ -113,7 +113,7 @@ class WhatsAppRuntime(BaseProcessSupervisor):enabled = (os.environ.get("WHATSAPP_RUNTIME_ENABLED") or "true").lower()if enabled not in ("1", "true", "yes"):raise RuntimeError("WhatsApp runtime disabled via WHATSAPP_RUNTIME_ENABLED")- # Run the (potentially long) ``npm install edgymeow`` off the+ # Run the (potentially long) ``bun add edgymeow`` off the# asyncio event loop. ``edgymeow_binary_path`` is sync and# blocks on ``subprocess.run`` for the duration of the install;# without this offload the startup ``_refresh_all_services``@@ -123,7 +123,7 @@ class WhatsAppRuntime(BaseProcessSupervisor):resolved = await asyncio.to_thread(edgymeow_binary_path)if resolved is None:raise RuntimeError(- "WhatsApp runtime install failed: npm not on PATH or `npm install edgymeow` "+ "WhatsApp runtime install failed: bun not available or `bun add edgymeow` ""did not produce the expected binary. See log for details.")self._write_config()diff --git a/server/services/cli_agent/_handlers.py b/server/services/cli_agent/_handlers.pyindex 18add0ef..9412c080 100644--- a/server/services/cli_agent/_handlers.py+++ b/server/services/cli_agent/_handlers.py@@ -42,7 +42,7 @@ async def handle_codex_cli_login("success": False,"error": ("Codex login is not yet wired in OpenCompany. "- "Install with `npm install -g @openai/codex` and run "+ "Install with `bun add -g @openai/codex` and run ""`codex login` in your terminal — then click Login again ""to mark connected."),diff --git a/server/services/cli_agent/protocol.py b/server/services/cli_agent/protocol.pyindex c926c5cb..10bab8c3 100644--- a/server/services/cli_agent/protocol.py+++ b/server/services/cli_agent/protocol.py@@ -111,7 +111,7 @@ class AICliProvider(Protocol):...# Resolve the CLI binary. Resolution chain (Composio pattern):# 1) shutil.which(<binary_name>)- # 2) `npx --yes <package_name>` shim path+ # 2) `bun x <package_name>` (bun from core.js_runtime.bun_binary)# Raises FileNotFoundError if neither is available.def interactive_argv(self, task: Any, *, defaults: Dict[str, Any]) -> List[str]:diff --git a/server/services/cli_agent/providers/openai_codex.py b/server/services/cli_agent/providers/openai_codex.pyindex 7055023d..417c884c 100644--- a/server/services/cli_agent/providers/openai_codex.py+++ b/server/services/cli_agent/providers/openai_codex.py@@ -92,12 +92,17 @@ class OpenAICodexProvider:if which_codex:return Path(which_codex)- npx = shutil.which("npx")- if npx:- return Path(npx)+ # No system codex: `bun x <package>` fetches and runs it on demand+ # (the npm package wraps a native binary, so the runtime does not+ # matter). bun comes from OPENCOMPANY_BUN_BIN or PATH.+ from core.js_runtime import bun_binary++ bun = bun_binary()+ if bun:+ return Path(bun)raise FileNotFoundError(- f"Neither {self.binary_name!r} nor 'npx' found in PATH. " f"Install with: npm install -g {self.package_name}"+ f"Neither {self.binary_name!r} nor 'bun' found in PATH. " f"Install with: bun add -g {self.package_name}")def interactive_argv(@@ -125,10 +130,12 @@ class OpenAICodexProvider:if which_codex:argv: List[str] = [which_codex]else:- npx = shutil.which("npx")- if not npx:- raise FileNotFoundError(f"Neither {self.binary_name!r} nor 'npx' found in PATH")- argv = [npx, "--yes", self.package_name]+ from core.js_runtime import bun_binary++ bun = bun_binary()+ if not bun:+ raise FileNotFoundError(f"Neither {self.binary_name!r} nor 'bun' found in PATH")+ argv = [bun, "x", self.package_name]argv += ["exec", "--json"]diff --git a/server/services/temporal/lifecycle.py b/server/services/temporal/lifecycle.pyindex fd684a38..eb12a820 100644--- a/server/services/temporal/lifecycle.py+++ b/server/services/temporal/lifecycle.py@@ -73,7 +73,7 @@ async def run_temporal_lifecycle(owned = owns_dev_server(settings.temporal_server_address)if owned:# Same BaseSupervisor singleton pattern as the WhatsApp and- # Node.js-executor runtimes; registering makes lifespan teardown+ # JS-executor runtimes; registering makes lifespan teardown# (shutdown_all_supervisors) actually stop the child.from services._supervisor import register_supervisorfrom services.temporal._runtime import get_temporal_server_runtimediff --git a/server/tests/conftest.py b/server/tests/conftest.pyindex f89a1b08..34d440ac 100644--- a/server/tests/conftest.py+++ b/server/tests/conftest.py@@ -202,6 +202,19 @@ _make_submodule(},)+# core.js_runtime — how the backend finds bun and extends the shared+# packages tree. Stdlib + core.paths (the stub above), imported at module+# load by the JS executor runtime and the npm-shipped CLI plugin+# installers, so it must be resolvable under the stubbed package.+_js_runtime_spec = _importlib_util.spec_from_file_location(+ "core.js_runtime",+ SERVER_DIR / "core" / "js_runtime.py",+)+_js_runtime_mod = _importlib_util.module_from_spec(_js_runtime_spec)+sys.modules["core.js_runtime"] = _js_runtime_mod+_js_runtime_spec.loader.exec_module(_js_runtime_mod)+setattr(_core_pkg, "js_runtime", _js_runtime_mod)+# services.pricing -- pre-stub the singleton so handler modules that do# `from services.pricing import get_pricing_service` at module load timediff --git a/server/tests/core_config/test_js_runtime.py b/server/tests/core_config/test_js_runtime.pynew file mode 100644index 00000000..828b08a9--- /dev/null+++ b/server/tests/core_config/test_js_runtime.py@@ -0,0 +1,109 @@+"""core.js_runtime — the one place the backend resolves bun and extends+the shared packages tree. Locks the contract the JS executor sidecar,+the npm-shipped CLI plugins and the codex provider all rely on: bun is+the only JavaScript runtime the backend ever spawns."""++from __future__ import annotations++import inspect+import json+from pathlib import Path++import pytest++from core import js_runtime+++def test_override_wins_over_path(monkeypatch, tmp_path):+ fake = tmp_path / ("bun.exe" if js_runtime.sys.platform == "win32" else "bun")+ fake.write_text("", encoding="utf-8")+ monkeypatch.setenv(js_runtime.ENV_BUN_BIN, str(fake))+ monkeypatch.setattr(js_runtime.shutil, "which", lambda name: "/elsewhere/bun")+ assert js_runtime.bun_binary() == str(fake)+++def test_missing_override_file_falls_back_to_path(monkeypatch, tmp_path):+ monkeypatch.setenv(js_runtime.ENV_BUN_BIN, str(tmp_path / "does-not-exist"))+ monkeypatch.setattr(js_runtime.shutil, "which", lambda name: "/path/bun" if name == "bun" else None)+ assert js_runtime.bun_binary() == "/path/bun"+++def test_require_bun_names_the_purpose_and_the_fix(monkeypatch):+ monkeypatch.delenv(js_runtime.ENV_BUN_BIN, raising=False)+ monkeypatch.setattr(js_runtime.shutil, "which", lambda name: None)+ with pytest.raises(RuntimeError) as exc:+ js_runtime.require_bun("the JS executor")+ assert "the JS executor" in str(exc.value)+ assert "bun.sh" in str(exc.value)+++def test_bin_shim_name_matches_bun_layout(monkeypatch):+ monkeypatch.setattr(js_runtime.sys, "platform", "win32")+ assert js_runtime.bin_shim_name("cf") == "cf.exe"+ monkeypatch.setattr(js_runtime.sys, "platform", "linux")+ assert js_runtime.bin_shim_name("cf") == "cf"+++def test_shared_tree_bin_lives_under_packages_dir(monkeypatch, tmp_path):+ monkeypatch.setattr(js_runtime, "packages_dir", lambda: tmp_path)+ expected = tmp_path / "node_modules" / ".bin" / js_runtime.bin_shim_name("vercel")+ assert js_runtime.shared_tree_bin("vercel") == expected+++def test_ensure_shared_tree_writes_a_private_manifest(tmp_path):+ root = tmp_path / "packages"+ assert js_runtime.ensure_shared_tree(root) == root+ manifest = json.loads((root / "package.json").read_text(encoding="utf-8"))+ assert manifest["private"] is True+ # idempotent: an existing manifest (with whatever bun added) survives+ (root / "package.json").write_text('{"name":"x","dependencies":{"cf":"0.2.0"}}', encoding="utf-8")+ js_runtime.ensure_shared_tree(root)+ assert "cf" in json.loads((root / "package.json").read_text(encoding="utf-8"))["dependencies"]+++def test_add_package_builds_a_bun_add_argv(monkeypatch, tmp_path):+ seen: dict[str, object] = {}++ def fake_run(argv, capture_output, text):+ seen["argv"] = argv+ seen["cwd_manifest"] = (tmp_path / "package.json").exists()++ class Done:+ returncode = 0+ stderr = ""+ stdout = ""++ return Done()++ monkeypatch.setenv(js_runtime.ENV_BUN_BIN, "")+ monkeypatch.setattr(js_runtime.shutil, "which", lambda name: "/opt/bun")+ monkeypatch.setattr(js_runtime.subprocess, "run", fake_run)++ js_runtime.add_package("[email protected]", trust=True, root=tmp_path)+ argv = seen["argv"]+ assert argv[:3] == ["/opt/bun", "add", "--cwd"]+ assert Path(argv[3]) == tmp_path+ assert "--trust" in argv+ assert argv[-1] == "[email protected]"+ assert seen["cwd_manifest"] is True, "the tree manifest must exist before bun add runs"++ js_runtime.add_package("[email protected]", root=tmp_path)+ assert "--trust" not in seen["argv"]+++def test_backend_never_spawns_node_or_npm():+ """The whole point of the module: no other runtime resolution exists.+ A regression that reintroduces ``shutil.which("node")`` /+ ``which("npm")`` / an ``npx`` spawn anywhere under the backend tree+ would silently reintroduce a Node dependency."""+ server = Path(inspect.getsourcefile(js_runtime)).resolve().parents[1]+ offenders: list[str] = []+ for path in server.rglob("*.py"):+ rel = path.relative_to(server).as_posix()+ if rel.startswith(("tests/", ".venv/", "experiments/", "scripts/")) or "/node_modules/" in rel:+ continue+ text = path.read_text(encoding="utf-8", errors="ignore")+ for needle in ('which("node")', "which('node')", 'which("npm")', "which('npm')", 'which("npx")', "which('npx')"):+ if needle in text:+ offenders.append(f"{rel}: {needle}")+ assert offenders == []diff --git a/server/tests/test_cloudflare_plugin.py b/server/tests/test_cloudflare_plugin.pyindex 34a7a187..0a8ed8f1 100644--- a/server/tests/test_cloudflare_plugin.py+++ b/server/tests/test_cloudflare_plugin.py@@ -109,10 +109,12 @@ def test_npm_spec_is_pinned():async def test_ensure_cf_cli_installs_into_shared_tree(monkeypatch, tmp_path):"""The system-global cf is never consulted — the binary comes from- the pinned npm install in the shared packages tree."""+ the pinned ``bun add`` into the shared packages tree."""+ from core import js_runtime+bin_dir = tmp_path / "node_modules" / ".bin"bin_dir.mkdir(parents=True)- fake_bin = bin_dir / ("cf.cmd" if cf_install.sys.platform == "win32" else "cf")+ fake_bin = bin_dir / js_runtime.bin_shim_name("cf")calls = {"installs": 0}@@ -122,8 +124,8 @@ async def test_ensure_cf_cli_installs_into_shared_tree(monkeypatch, tmp_path):return fake_binmonkeypatch.setattr(cf_install, "_cached_path", None)- monkeypatch.setattr(cf_install, "packages_dir", lambda: tmp_path)- monkeypatch.setattr(cf_install, "_npm_install", fake_install)+ monkeypatch.setattr(cf_install, "shared_tree_bin", lambda name: bin_dir / js_runtime.bin_shim_name(name))+ monkeypatch.setattr(cf_install, "_install", fake_install)resolved = await cf_install.ensure_cf_cli()assert resolved == fake_bin@@ -134,14 +136,14 @@ async def test_ensure_cf_cli_installs_into_shared_tree(monkeypatch, tmp_path):def test_cf_binary_never_resolved_from_system_path():- # Project-local contract: PATH lookup is allowed for npm itself,- # never for the cf binary.+ # Project-local contract: PATH lookup is allowed for bun itself+ # (inside core.js_runtime), never for the cf binary.src_install = inspect.getsource(cf_install)src_service = inspect.getsource(cf_service)- assert 'which("cf")' not in src_install+ assert "which(" not in src_installassert "which(" not in src_service# resolution goes through the shared-tree shim only- assert "node_modules" in inspect.getsource(cf_install._shared_tree_bin)+ assert 'shared_tree_bin("cf")' in inspect.getsource(cf_install._shared_tree_bin)# --- operations (no auth pre-flight — Stripe pattern) ---------------------------@@ -576,9 +578,10 @@ def test_login_flow_short_circuits_when_already_logged_in():def test_completion_never_kills_the_login_process():- # The installed binary is an npm .cmd shim on Windows: killing it- # orphans the node child, which keeps holding callback port 8877- # and breaks every later login. cf enforces its own login timeout.+ # The installed binary is a bun bin shim on Windows (a launcher .exe+ # that runs the CLI in a child bun process): killing it orphans that+ # child, which keeps holding callback port 8877 and breaks every+ # later login. cf enforces its own login timeout.src = inspect.getsource(cf_handlers._complete_login)assert ".kill(" not in srcassert ".terminate(" not in srcdiff --git a/server/tests/test_no_root_climb.py b/server/tests/test_no_root_climb.pyindex a0bee0c5..1299a542 100644--- a/server/tests/test_no_root_climb.py+++ b/server/tests/test_no_root_climb.py@@ -31,7 +31,12 @@ SERVER_ROOT = Path(__file__).resolve().parents[1]_EXCLUDED_DIRS = {".venv", "tests", "scripts", "skills", "__pycache__", "nodejs", "static"}-_SANCTIONED = {"core/approot.py"}+_SANCTIONED = {+ "core/approot.py",+ # Writes the shared packages tree's own manifest under DATA_DIR+ # (a bun project file, unrelated to the app root's package.json).+ "core/js_runtime.py",+}# Literal path joins that encode the sibling layout; only approot may spell them._LAYOUT_LITERALS = {("client", "dist"), (".env.template",), ("package.json",)}diff --git a/server/tests/test_vercel_plugin.py b/server/tests/test_vercel_plugin.pyindex 8ca3a149..168f6ce4 100644--- a/server/tests/test_vercel_plugin.py+++ b/server/tests/test_vercel_plugin.py@@ -200,7 +200,7 @@ async def test_custom_requires_command(monkeypatch, tmp_path):async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):- """Regression: the first-ever login pays a cold `npm install vercel`+ """Regression: the first-ever login pays a cold `bun add vercel`inside the handler, which blew past the frontend's 30s WS requesttimeout ("Request timeout: vercel_login") even though the loginitself succeeded. The handler must answer within its response