Skip to content

Self-improving AI Employees for everyone

build: make bun the install channel and the only shipped JavaScript runtime

trohitge3e5d988916e
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
index 99088ad9..868d552e 100644
--- a/.github/actions/setup/action.yml
+++ b/.github/actions/setup/action.yml
@@ -12,8 +12,11 @@ runs:
steps:
# Reads the bun version from the root package.json "packageManager" pin.
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
- # Node stays the runtime; CI builds on 22 LTS while the published
- # package's floor is 18+ (vite, vitest, eslint, the sidecar run on
+ # Node is a CI-only convenience: bun runs vite / vitest / eslint on it
+ # when present (their bins carry node shebangs), which sidesteps the
+ # open bun-runtime bugs in vitest and eslint. Nothing shipped needs
+ # Node: the sidecar, the plugin CLIs and the `company` shim run on bun.
+ # (vite, vitest, eslint run on
# node via shebang; bun is package manager + script runner only).
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
with:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 83f1ec2a..9e484adc 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,4 +1,6 @@
-# Release workflow: predeploy gate, publish npm + GitHub Packages.
+# Release workflow: predeploy gate, publish the registry tarball to npmjs and
+# GitHub Packages with bun. No npm CLI and no setup-node: bun packs, authenticates
+# (~/.npmrc written from the job's token) and publishes.
# Triggers on version tag push.
name: Release
@@ -21,28 +23,22 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
- id-token: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: ./.github/actions/setup
- - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
- with:
- node-version: '22'
- package-manager-cache: false
- registry-url: 'https://registry.npmjs.org'
- run: bun install --frozen-lockfile
- run: bun run build
- run: python -m cli version sync
- - name: Verify npm credentials
- run: npm whoami
- env:
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- - name: Publish public npm package
- run: npm publish --access public --provenance
+ - name: Configure npmjs credentials
+ run: printf '//registry.npmjs.org/:_authToken=%s\n' "$NPM_TOKEN" > ~/.npmrc
env:
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+ - name: Verify npmjs credentials
+ run: bun pm whoami
+ - name: Publish public package
+ run: bun publish --access public
publish-github-packages:
name: Publish to GitHub Packages
@@ -56,24 +52,20 @@ jobs:
with:
persist-credentials: false
- uses: ./.github/actions/setup
- - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
- with:
- node-version: '22'
- package-manager-cache: false
- registry-url: 'https://npm.pkg.github.com'
- run: bun install --frozen-lockfile
- run: bun run build
- run: python -m cli version sync
- name: Configure scoped package
run: |
- node -e "
+ bun -e "
const pkg = require('./package.json');
pkg.name = '@zeenie-ai/opencompany';
pkg.publishConfig = { registry: 'https://npm.pkg.github.com' };
require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));
"
- # GitHub Packages uses the repository-scoped GITHUB_TOKEN; npm's OIDC
- # trusted-publisher flow applies to npmjs.org, not npm.pkg.github.com.
- - run: npm publish # zizmor: ignore[use-trusted-publishing]
+ # GitHub Packages uses the repository-scoped GITHUB_TOKEN.
+ - name: Configure GitHub Packages credentials
+ run: printf '//npm.pkg.github.com/:_authToken=%s\n' "$NPM_TOKEN" > ~/.npmrc
env:
- NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ NPM_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ - run: bun publish
diff --git a/.npmignore b/.npmignore
index 8a1f3484..2d1601b4 100644
--- a/.npmignore
+++ b/.npmignore
@@ -101,3 +101,9 @@ server/experiments/
# Package lock files
package-lock.json
**/package-lock.json
+
+# Local Terraform state from `company deploy` runs (provider binaries are
+# hundreds of MB) and the backend test suite's scratch data root. Both live
+# inside allowlisted dirs (cli/, server/), so `files` alone cannot drop them.
+**/.terraform/
+server/tests/_test_opencompany_root/
diff --git a/bin/cli.js b/bin/cli.js
index 5b324156..33fcbfef 100755
--- a/bin/cli.js
+++ b/bin/cli.js
@@ -1,6 +1,9 @@
-#!/usr/bin/env node
+#!/usr/bin/env bun
+// The `company` launcher. Installed by `bun add -g @zeenie-ai/opencompany`
+// and run by bun (the shebang); the code itself is plain JavaScript so a
+// legacy npm-installed copy still runs under node.
-import { spawn, execSync } from 'child_process';
+import { spawn, spawnSync, execSync } from 'child_process';
import { basename, dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import { readFileSync, existsSync } from 'fs';
@@ -22,6 +25,7 @@ const COMMANDS = {
clean: 'Clean build artifacts',
docs: 'Documentation tooling (docs nodes [--check])',
doctor: 'Check system dependencies and project health',
+ provision: 'Set up the Python environment (runs automatically on first use; --force re-runs)',
help: 'Show this help message',
version: 'Show version number (version sync [tag] to sync from a git tag)',
};
@@ -53,13 +57,18 @@ Documentation: https://docs.opencompany.sh/
`);
}
-// bun is the dev package manager and script runner for source checkouts.
-// End-user global installs (the npm tarball) may not have it, so every
-// bun use below keeps an npm fallback.
+// bun is the package manager, script runner and JS runtime everywhere.
+// A legacy npm-installed copy may run this file under node without bun
+// on PATH, so every bun use below keeps an npm fallback for that case.
function hasBun() {
return getVersion('bun --version') !== null;
}
+function isSourceCheckout() {
+ // bunfig.toml is committed but excluded from the published tarball.
+ return existsSync(resolve(ROOT, 'bunfig.toml'));
+}
+
function getVersion(cmd) {
try {
return execSync(cmd, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
@@ -89,12 +98,6 @@ function expandPath() {
function checkDeps() {
const errors = [];
- // Node.js version check
- const nodeVersion = parseInt(process.version.slice(1));
- if (nodeVersion < 18) {
- errors.push(`Node.js 18+ required (found ${process.version})`);
- }
-
// Python version check
let pyVersion = getVersion('python --version') || getVersion('python3 --version');
if (!pyVersion) {
@@ -145,9 +148,9 @@ function doctor() {
console.log('');
}
-// Resolve <ROOT>/.cli-venv Python if the postinstall step provisioned it.
-// Returns null on source checkouts (no venv -> fall back to ``bun run``,
-// or ``npm run`` when bun is not installed).
+// Resolve <ROOT>/.cli-venv Python if provisioning has run. Returns null on
+// source checkouts (no venv -> fall back to ``bun run``) and on a fresh
+// global install before its first run.
function venvPython() {
const py = process.platform === 'win32'
? resolve(ROOT, '.cli-venv', 'Scripts', 'python.exe')
@@ -155,14 +158,74 @@ function venvPython() {
return existsSync(py) ? py : null;
}
+// The app port from the shipped .env.template (the single place ports live).
+function appPort() {
+ try {
+ const m = /^PYTHON_BACKEND_PORT=(\d+)/m.exec(readFileSync(resolve(ROOT, '.env.template'), 'utf-8'));
+ return m ? m[1] : '';
+ } catch {
+ return '';
+ }
+}
+
+// Run scripts/install.js (uv, server venv, bytecode, CLI venv, Temporal)
+// under this runtime. Exits the process on failure.
+function runInstallJs() {
+ const installJs = resolve(ROOT, 'scripts', 'install.js');
+ if (!existsSync(installJs)) {
+ console.error('scripts/install.js is missing from this install; reinstall with: bun add -g @zeenie-ai/opencompany');
+ process.exit(1);
+ }
+ const result = spawnSync(process.execPath, [installJs], {
+ cwd: ROOT,
+ stdio: 'inherit',
+ env: { ...process.env, FORCE_COLOR: '1' },
+ });
+ if (result.status !== 0) {
+ console.error('\nProvisioning failed. Fix the error above and re-run: company provision');
+ process.exit(result.status || 1);
+ }
+}
+
+// First-run provisioning for a global install. `bun add -g` does not run a
+// dependency's lifecycle scripts, so the venv the postinstall hook used to
+// create is built here, on the first `company` command. Source checkouts
+// provision through `company build` instead.
+function ensureProvisioned() {
+ if (venvPython() || isSourceCheckout()) return;
+ console.log('First run: provisioning the Python environment (one time)...');
+ runInstallJs();
+}
+
+// `company provision [--force]`: the explicit form of the above, for the
+// installers (which cannot know where bun placed the package, while this
+// file always knows its own ROOT) and for repairing a broken install.
+function provision(force) {
+ if (isSourceCheckout()) {
+ console.log('This is a source checkout; run: company build');
+ return;
+ }
+ if (venvPython() && !force) {
+ console.log('Already provisioned (run `company provision --force` to redo it).');
+ } else {
+ runInstallJs();
+ }
+ const port = appPort();
+ console.log('');
+ console.log('Run: company start');
+ if (port) console.log(`Open: http://localhost:${port}`);
+ console.log('');
+}
+
function run(script, extraArgs = []) {
// Global-install fast path: spawn the venv's Python directly with
- // ``-m cli <cmd>``. Skips the ``npm run`` shim that previously re-
+ // ``-m cli <cmd>``. Skips the script-runner hop that previously re-
// resolved the system ``python`` (which on PEP 668 systems lacks
// the CLI runtime deps -- typer/rich/anyio/psutil). The script-runner
// path stays as the source-checkout fallback: ``bun run <script>``
// when bun is on PATH (source checkouts are bun-only), else ``npm run``
- // for a global install whose .cli-venv provisioning did not happen.
+ // for a legacy npm-installed copy.
+ ensureProvisioned();
const venvPy = venvPython();
if (venvPy) {
const child = spawn(venvPy, ['-m', 'cli', script, ...extraArgs], {
@@ -208,7 +271,13 @@ if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
console.log(`company v${PKG.version}`);
} else if (cmd === 'doctor') {
doctor();
+} else if (cmd === 'provision') {
+ provision(rest.includes('--force'));
} else if (cmd === 'start' || cmd === 'dev' || cmd === 'build' || cmd === 'serve') {
+ // Provision before the dependency check: on a fresh global install uv is
+ // installed BY provisioning (scripts/install.js), so checking for it first
+ // would fail the very first `company start`.
+ ensureProvisioned();
checkDeps();
run(cmd, rest);
} else if (SUBCOMMAND_VERBS.has(cmd)) {
diff --git a/bin/machina.js b/bin/machina.js
index 00ddf2a0..4b81f2e3 100644
--- a/bin/machina.js
+++ b/bin/machina.js
@@ -1,7 +1,7 @@
-#!/usr/bin/env node
+#!/usr/bin/env bun
// Deprecated compatibility entry point. Keeping this wrapper separate from
-// cli.js makes alias detection reliable through npm's Windows .cmd/.ps1 shims,
-// which invoke the target JavaScript file rather than preserving the bin name.
+// cli.js makes alias detection reliable through the Windows bin shims, which
+// invoke the target JavaScript file rather than preserving the bin name.
process.env.OPENCOMPANY_LEGACY_ALIAS = 'machina';
await import('./cli.js');
diff --git a/bun.lock b/bun.lock
index 4617f68f..4ccf11fe 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6,7 +6,6 @@
"name": "@zeenie-ai/opencompany",
"dependencies": {
"cross-env": "^10.1.0",
- "express": "^5.2.1",
},
"devDependencies": {
"typescript": "7.0.2",
@@ -88,8 +87,6 @@
"devDependencies": {
"@types/express": "^5.0.6",
"@types/node": "^22.19.18",
- "esbuild": "^0.28.1",
- "tsx": "^4.21.0",
"typescript": "^5.9.3",
},
},
@@ -2296,8 +2293,6 @@
"tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
- "tsx": ["[email protected]", "", { "dependencies": { "esbuild": "0.28.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-rw55FUaqOoI7RvlQwLbhO4nSDApnQ4/CykPuiQ/EPvtrX3WA9Ig55jIt9VvbBJbzJuj12ueRu4PMZ2SxPVbihg=="],
-
"tw-animate-css": ["[email protected]", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
"type-check": ["[email protected]", "", { "dependencies": { "prelude-ls": "1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="],
diff --git a/cli/commands/build.py b/cli/commands/build.py
index 4eb3a0ca..f0bc6e03 100644
--- a/cli/commands/build.py
+++ b/cli/commands/build.py
@@ -2,7 +2,7 @@
Checks toolchain (node, bun, python, uv), then runs the 6-step
build: ``.env`` bootstrap -> ``bun install`` -> client build ->
-Node.js sidecar bundle -> ``uv sync`` -> compile Python bytecode
+JS executor sidecar bundle (bun build) -> ``uv sync`` -> compile Python bytecode
-> pooch-fetch Temporal binary.
Layers ``.env.dev`` (when present in the checkout) BEFORE running
@@ -182,20 +182,11 @@ def build_command() -> None:
# ---- toolchain ---------------------------------------------------
console.print("[bold]Checking dependencies...[/]\n")
- node_version = capture(["node", "--version"])
- console.print(f" Node.js: {node_version or '[red]not found[/]'}")
- if not node_version:
- error_block("Node.js is required.", [])
- raise typer.Exit(code=1)
-
- # npm is informational only: the build never calls it, but runtime
- # plugins (`npm install --prefix`) and the sidecar's package endpoint do.
- npm_version = capture(["npm", "--version"])
- console.print(f" npm: {npm_version or '[red]not found[/]'}")
-
- # bun installs the workspace and runs every JS build script below
- # (`bun install`, `bun run --filter ...`), so a missing bun is fatal
- # here rather than a confusing failure inside step [1/6].
+ # bun installs the workspace, runs every JS build script below
+ # (`bun install`, `bun run --filter ...`, the sidecar's `bun build`)
+ # and is the runtime for the JS executor sidecar and the plugin CLIs,
+ # so a missing bun is fatal here rather than a confusing failure
+ # inside step [1/6].
bun_version = capture(["bun", "--version"])
console.print(f" bun: {bun_version or '[red]not found[/]'}")
if not bun_version:
@@ -205,6 +196,11 @@ def build_command() -> None:
)
raise typer.Exit(code=1)
+ # Node is optional: when present, bun runs vite / vitest / eslint on it
+ # (their bins carry node shebangs); when absent, bun runs them itself.
+ node_version = capture(["node", "--version"])
+ console.print(f" Node.js: {node_version or 'not found (optional; bun runs the build tools itself)'}")
+
python_cmd = _which_python()
if not python_cmd or not _check_python(python_cmd):
error_block(
@@ -255,12 +251,12 @@ def build_command() -> None:
# treats the next word as a script name).
run(["bun", "run", "--filter", "react-flow-client", "build"], cwd=root)
- # Pre-bundle the Node.js sidecar (server/nodejs) with esbuild so the
- # production `npm start` runs `node dist/index.js` instead of
- # interpreting `tsx src/index.ts`. Saves ~500ms-1s of cold start
- # whenever the executor is launched. The bundle keeps Express
- # external (it stays in node_modules), so the patch flow is intact.
- console.log("[3/6] Building Node.js sidecar...")
+ # Bundle the JS executor sidecar (server/nodejs) with `bun build
+ # --target=bun` into one self-contained dist/index.js (express
+ # inlined) that nodes/code/_runtime.py runs on bun. Saves the
+ # TypeScript transpile on every launch and needs no node_modules at
+ # runtime, which is what lets the desktop bundle copy a single file.
+ console.log("[3/6] Building JS executor sidecar...")
run(["bun", "run", "--filter", "opencompany-nodejs-executor", "build"], cwd=root)
console.log("[4/6] Installing Python dependencies...")
diff --git a/cli/commands/deploy/up.py b/cli/commands/deploy/up.py
index 6f615dc1..b842727c 100644
--- a/cli/commands/deploy/up.py
+++ b/cli/commands/deploy/up.py
@@ -4,7 +4,7 @@ Two stages:
STAGE 1 (cloud CLI): the provider adapter verifies the CLI is installed +
authenticated, resolves project/region/zone, ensures Terraform auth, and
enables the required cloud APIs.
- STAGE 2 (Terraform): generate secrets + owner creds -> (local source) npm
+ STAGE 2 (Terraform): generate secrets + owner creds -> (local source) bun pm
pack -> write tfvars -> ``terraform init`` + ``apply`` -> read outputs ->
poll ``/health`` -> print URL + credentials.
@@ -30,19 +30,20 @@ from .providers import get_provider
def _npm_pack(root: Path) -> str:
- """Run ``npm pack`` in the repo root; return the abs path to the tarball."""
- console.log("Packaging local build (npm pack)...")
- out = capture(["npm", "pack"], cwd=root)
+ """Run ``bun pm pack`` in the repo root; return the abs path to the
+ tarball (the same npm-registry tarball shape ``bun add -g`` installs)."""
+ console.log("Packaging local build (bun pm pack)...")
+ out = capture(["bun", "pm", "pack", "--quiet"], cwd=root)
if not out:
error_block(
- "`npm pack` produced no output.",
- ["Ensure Node/npm are installed and you are in an OpenCompany checkout."],
+ "`bun pm pack` produced no output.",
+ ["Ensure bun is installed and you are in an OpenCompany checkout."],
)
raise typer.Exit(code=1)
tarball = out.strip().splitlines()[-1].strip()
path = (root / tarball).resolve()
if not path.is_file():
- error_block(f"npm pack reported {tarball!r} but it is not on disk.", [str(path)])
+ error_block(f"bun pm pack reported {tarball!r} but it is not on disk.", [str(path)])
raise typer.Exit(code=1)
return str(path)
@@ -153,7 +154,7 @@ def up_command(
console.print()
if url:
- console.log("The VM is installing OpenCompany (Node + npm + build); this takes a few minutes.")
+ console.log("The VM is installing OpenCompany (bun + uv + Python venv); this takes a few minutes.")
if _poll_health(url):
console.print(f" [bold green]Ready.[/] Open {url} and log in.")
else:
diff --git a/cli/ports.py b/cli/ports.py
index b948c406..a9ad1a29 100644
--- a/cli/ports.py
+++ b/cli/ports.py
@@ -35,9 +35,9 @@ def _ancestor_pids() -> set[int]:
Used by the pattern-matching kill functions below so we never
terminate our own parent / grandparent. When invoked through the
- npm bin shim the chain is ``powershell -> node.exe (bin/cli.js)
+ global bin shim the chain is ``powershell -> bun.exe (bin/cli.js)
-> python.exe (-m cli ...)`` -- if ``kill_orphaned_opencompany_processes``
- matches ``node.exe`` (its cmdline carries the npm install path),
+ matches ``bun.exe`` (its cmdline carries the install path),
killing it tears down stdio mid-execution and the Python child
exits with whatever garbage code Windows assigns to an
abruptly-orphaned process (observed: 58). Walk up the tree once
@@ -202,9 +202,11 @@ def kill_by_pattern(pattern: str, *, root_dir: str | None = None) -> list[int]:
def kill_orphaned_opencompany_processes(
root_dir: str, *, exclude_substring: str | None = None
) -> list[int]:
- """Kill stray python/node processes whose cmdline references the project root."""
+ """Kill stray python/bun processes whose cmdline references the project root."""
root_norm = root_dir.lower().replace("\\", "/")
- target_names = {"python", "python3", "python.exe", "node", "node.exe"}
+ # bun runs the JS executor sidecar and the company shim; node is kept
+ # so a sidecar left over from a pre-bun install is still reaped.
+ target_names = {"python", "python3", "python.exe", "bun", "bun.exe", "node", "node.exe"}
safe_pids = _ancestor_pids()
killed: list[int] = []
diff --git a/cli/terraform/aws/startup.sh.tftpl b/cli/terraform/aws/startup.sh.tftpl
index 3222e096..ae4d5fb7 100644
--- a/cli/terraform/aws/startup.sh.tftpl
+++ b/cli/terraform/aws/startup.sh.tftpl
@@ -37,9 +37,9 @@ mkdir -p /var/lib/${instance_name}
chown $APP_USER:$APP_USER /var/lib/${instance_name}
echo "[${instance_name}] installing systemd service..."
-# The shim lives under the user's npm global prefix (install.sh points it at
-# ~/.npm-global when the system prefix is not writable).
-OPENCOMPANY_BIN="$(sudo -u $APP_USER -H npm prefix -g)/bin/company"
+# The shim lives under the user's bun global bin dir (install.sh installs bun
+# for the login user; BUN_INSTALL defaults to ~/.bun).
+OPENCOMPANY_BIN="$APP_HOME/.bun/bin/company"
test -x "$OPENCOMPANY_BIN"
cat > /etc/systemd/system/${instance_name}.service <<SERVICE_EOF
[Unit]
@@ -51,6 +51,7 @@ Wants=network-online.target
Type=simple
User=$APP_USER
WorkingDirectory=$APP_HOME
+Environment=PATH=$APP_HOME/.bun/bin:$APP_HOME/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
EnvironmentFile=/etc/${instance_name}/opencompany.env
ExecStart=$OPENCOMPANY_BIN serve
Restart=on-failure
diff --git a/cli/terraform/gcp/startup.sh.tftpl b/cli/terraform/gcp/startup.sh.tftpl
index dea0ca09..dc289dbe 100644
--- a/cli/terraform/gcp/startup.sh.tftpl
+++ b/cli/terraform/gcp/startup.sh.tftpl
@@ -1,6 +1,7 @@
#!/bin/bash
# OpenCompany VM startup script (rendered by Terraform `templatefile`).
-# Installs the toolchain, installs OpenCompany (npm), writes the login-gate env
+# Installs the toolchain (bun + uv; no Node, no npm), installs OpenCompany
+# with `bun add -g`, provisions the Python venvs, writes the login-gate env
# file, and runs it under systemd via `company serve`.
#
# NOTE on syntax: Terraform renders this file with templatefile(), so any
@@ -13,25 +14,26 @@ export DEBIAN_FRONTEND=noninteractive
echo "[${resource_name}] installing OpenCompany toolchain..."
apt-get update
-apt-get install -y curl ca-certificates git build-essential pkg-config libffi-dev libssl-dev
-curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
-apt-get install -y nodejs
+apt-get install -y curl ca-certificates git unzip build-essential pkg-config libffi-dev libssl-dev
+# bun on a stable system path: the runtime for the `company` shim, the JS
+# executor sidecar and the plugin CLIs, and the installer for the package.
+export BUN_INSTALL=/usr/local
+curl -fsSL https://bun.sh/install | bash
# uv on a stable system path (company build uses it to sync the Python venv).
curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh
echo "[${resource_name}] installing OpenCompany package..."
-# The pre-rebrand package owns the deprecated `machina` binary too. Remove it
-# first so npm can create OpenCompany's compatibility shim during an upgrade.
-if npm list -g --depth=0 machinaos >/dev/null 2>&1; then
- npm uninstall -g machinaos
-fi
%{ if source_mode == "local" ~}
TOKEN=$(curl -s -H "Metadata-Flavor: Google" "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" | python3 -c 'import sys, json; print(json.load(sys.stdin)["access_token"])')
curl -fsS -H "Authorization: Bearer $TOKEN" -o /tmp/${resource_name}.tgz "https://storage.googleapis.com/storage/v1/b/${bucket}/o/${object}?alt=media"
-npm install -g /tmp/${resource_name}.tgz
+bun add -g /tmp/${resource_name}.tgz
%{ else ~}
-npm install -g @zeenie-ai/opencompany@${version}
+bun add -g @zeenie-ai/opencompany@${version}
%{ endif ~}
+# bun runs no lifecycle scripts for a global package; provision the Python
+# side now so the service's first start is warm. The shim lives in bun's
+# global bin dir ($BUN_INSTALL/bin) and knows its own package root.
+"$BUN_INSTALL/bin/company" provision
echo "[${resource_name}] writing login-gate env..."
mkdir -p /etc/${resource_name}
diff --git a/cli/tests/test_cli_branding.py b/cli/tests/test_cli_branding.py
index 791e5409..68987e2b 100644
--- a/cli/tests/test_cli_branding.py
+++ b/cli/tests/test_cli_branding.py
@@ -39,8 +39,8 @@ def test_cloud_service_resolves_company_then_legacy_machina():
encoding="utf-8"
)
- assert "npm install -g @zeenie-ai/opencompany@${version}" in template
- assert "npm uninstall -g machinaos" in template
+ assert "bun add -g @zeenie-ai/opencompany@${version}" in template
+ assert "npm install" not in template and "npm uninstall" not in template and "nodesource" not in template
assert "command -v company || command -v machina" in template
assert "command -v opencompany" not in template
assert "ExecStart=$OPENCOMPANY_BIN serve" in template
@@ -56,24 +56,34 @@ def test_installers_target_scoped_package_without_touching_unscoped_package():
}
# install.sh builds the spec (optionally pinned by OPENCOMPANY_VERSION)
- # into $PKG before the single `npm install -g "$PKG"` call.
- assert 'PKG="@zeenie-ai/opencompany${VERSION:+@$VERSION}"' in installers["install.sh"]
- assert 'npm install -g "$PKG"' in installers["install.sh"]
- assert 'npm install -g "@zeenie-ai/opencompany"' in installers["install.ps1"]
- assert "npm install -g @zeenie-ai/opencompany@${version}" in installers["gcp startup"]
+ # into $PKG before the single `bun add -g "$PKG"` call.
+ assert 'PKG="${PKG_NAME}${VERSION:+@$VERSION}"' in installers["install.sh"]
+ assert 'PKG_NAME="@zeenie-ai/opencompany"' in installers["install.sh"]
+ assert 'bun add -g "$PKG"' in installers["install.sh"]
+ assert '$PKG_NAME = "@zeenie-ai/opencompany"' in installers["install.ps1"]
+ assert "bun add -g $PKG_NAME" in installers["install.ps1"]
+ assert "bun add -g @zeenie-ai/opencompany@${version}" in installers["gcp startup"]
for source in installers.values():
- assert "npm install -g opencompany" not in source
+ assert "npm install -g" not in source
+ assert "bun add -g opencompany" not in source
assert "npm uninstall -g opencompany" not in source
- assert "npm uninstall -g machinaos" in source
+ # The user-facing installers still evict a legacy npm install (the
+ # scoped package or pre-rebrand machinaos) when npm is around, so the
+ # old shim cannot shadow the bun one. The VM script starts clean.
+ for name in ("install.sh", "install.ps1"):
+ assert "machinaos" in installers[name]
+ assert "npm uninstall -g" in installers[name]
def test_uninstaller_removes_only_scoped_and_official_legacy_packages():
uninstaller = (ROOT / "uninstall.sh").read_text(encoding="utf-8")
+ assert "remove_bun_global_package '@zeenie-ai/opencompany'" in uninstaller
assert "remove_global_package '@zeenie-ai/opencompany'" in uninstaller
assert "remove_global_package 'machinaos'" in uninstaller
assert "npm uninstall -g opencompany" not in uninstaller
+ assert "bun remove -g opencompany" not in uninstaller
def test_node_shims_print_canonical_name_and_deprecation_warning():
diff --git a/cli/tests/test_release_pipeline_config.py b/cli/tests/test_release_pipeline_config.py
index b6f3590b..6ac4e18c 100644
--- a/cli/tests/test_release_pipeline_config.py
+++ b/cli/tests/test_release_pipeline_config.py
@@ -101,71 +101,58 @@ def preinstall_js_src(root: Path) -> str:
# ---------------------------------------------------------------------------
-# Node.js sidecar — package.json & .gitignore
+# JS executor sidecar (runs on bun) — package.json & .gitignore
# ---------------------------------------------------------------------------
-def test_sidecar_start_runs_compiled_bundle(sidecar_pkg: dict):
- """``npm start`` runs the esbuild-bundled output, not interpreted
- TypeScript via tsx. tsx adds ~500ms-1s of interpreter startup that
- the bundle eliminates.
+def test_sidecar_start_runs_compiled_bundle_on_bun(sidecar_pkg: dict):
+ """``start`` runs the ``bun build`` output on bun, not interpreted
+ TypeScript. The bundle is what ``nodes/code/_runtime.py`` spawns
+ (``[bun, dist/index.js]``); the runtime is bun, never node.
"""
start = sidecar_pkg["scripts"]["start"]
- assert (
- start == "node dist/index.js"
- ), f"sidecar start must be `node dist/index.js`, got {start!r}"
- assert "tsx" not in start
+ assert start == "bun dist/index.js", f"sidecar start must be `bun dist/index.js`, got {start!r}"
+ assert "node " not in start and "tsx" not in start
-def test_sidecar_dev_keeps_tsx_for_hot_reload(sidecar_pkg: dict):
- """``npm run dev`` keeps tsx watch — the bundle workflow is too slow
- for local iteration. Only production ``start`` uses the bundle.
- """
+def test_sidecar_dev_uses_bun_watch(sidecar_pkg: dict):
+ """``dev`` runs the TS source directly under ``bun --watch`` — bun
+ executes TypeScript natively, so no loader (tsx) is needed."""
dev = sidecar_pkg["scripts"]["dev"]
- assert "tsx" in dev and "watch" in dev
+ assert dev.startswith("bun --watch") and "src/index.ts" in dev
+ assert "tsx" not in dev
@pytest.mark.parametrize(
"flag",
[
- "esbuild",
+ "bun build",
"src/index.ts",
- "--bundle",
- "--platform=node",
- "--target=node18",
- "--format=esm",
- "--packages=external",
+ "--target=bun",
"--outfile=dist/index.js",
],
)
-def test_sidecar_build_script_carries_required_esbuild_flag(
- sidecar_pkg: dict, flag: str
-):
- """Each esbuild flag in the sidecar build script is load-bearing.
-
- - ``--bundle`` — concat the executor's own TS into one file.
- - ``--platform=node`` — preserve Node built-in resolution.
- - ``--target=node18`` — match ``engines.node`` in the same file.
- - ``--format=esm`` — package.json ``type=module`` requires ESM.
- - ``--packages=external`` — keep Express in node_modules; only the
- executor's own TS is concatenated, so patch flow stays intact.
+def test_sidecar_build_script_carries_required_bun_build_flag(sidecar_pkg: dict, flag: str):
+ """Each part of the sidecar build script is load-bearing.
+
+ - ``bun build`` — bun's bundler; no esbuild dependency.
+ - ``--target=bun`` — self-contained bundle with express INLINED, so
+ the desktop stage copies one file and no ``node_modules`` (bun's
+ isolated linker would otherwise ship a dangling express symlink).
- ``--outfile=dist/index.js`` — ``start`` and ``main`` read this
exact path; mismatch breaks the runtime.
"""
cmd = sidecar_pkg["scripts"]["build"]
assert flag in cmd, f"sidecar build script missing {flag!r}: {cmd}"
+ assert "esbuild" not in cmd and "--packages=external" not in cmd
-def test_sidecar_engines_match_esbuild_target(sidecar_pkg: dict):
- """``--target=node18`` and ``engines.node`` must agree. Bumping one
- without the other would silently produce code that runs on a Node
- version the package claims it doesn't support (or vice versa).
- """
- engines_node = sidecar_pkg.get("engines", {}).get("node", "")
- assert "18" in engines_node, (
- f"engines.node must declare ≥18 to match esbuild --target=node18, "
- f"got {engines_node!r}"
- )
+def test_sidecar_engines_declare_bun_not_node(sidecar_pkg: dict):
+ """The sidecar's runtime is bun; ``engines`` must say so and must not
+ reintroduce a Node floor."""
+ engines = sidecar_pkg.get("engines", {})
+ assert "bun" in engines, f"engines must declare bun, got {engines!r}"
+ assert "node" not in engines
def test_sidecar_main_field_points_at_compiled_output(sidecar_pkg: dict):
@@ -175,12 +162,11 @@ def test_sidecar_main_field_points_at_compiled_output(sidecar_pkg: dict):
assert sidecar_pkg.get("main") == "dist/index.js"
-def test_sidecar_esbuild_is_dev_only(sidecar_pkg: dict):
- """esbuild builds the bundle; the runtime never touches it. It must
- be a devDependency so a ``--omit=dev`` install doesn't ship it.
- """
- assert "esbuild" in sidecar_pkg.get("devDependencies", {})
- assert "esbuild" not in sidecar_pkg.get("dependencies", {})
+def test_sidecar_has_no_node_toolchain_dependencies(sidecar_pkg: dict):
+ """bun bundles and runs the sidecar; esbuild and tsx are gone."""
+ deps = {**sidecar_pkg.get("dependencies", {}), **sidecar_pkg.get("devDependencies", {})}
+ assert "esbuild" not in deps
+ assert "tsx" not in deps
def test_sidecar_dist_is_gitignored(sidecar_dir: Path):
@@ -459,26 +445,28 @@ def test_root_package_uses_canonical_github_urls(root_pkg: dict):
def test_npm_release_authenticates_before_publish(
release_yml: dict,
):
+ """``bun pm whoami`` proves the token before ``bun publish`` runs, both
+ reading the same ``~/.npmrc`` the auth step wrote from NPM_TOKEN."""
steps = _run_steps(release_yml["jobs"]["publish-npm"])
- preflight_index = next(
- i for i, step in enumerate(steps) if "npm whoami" in step["run"]
- )
- publish_index = next(
- i for i, step in enumerate(steps) if "npm publish" in step["run"]
- )
- preflight = steps[preflight_index]
+ auth_index = next(i for i, step in enumerate(steps) if "_authToken" in step["run"])
+ preflight_index = next(i for i, step in enumerate(steps) if "bun pm whoami" in step["run"])
+ publish_index = next(i for i, step in enumerate(steps) if "bun publish" in step["run"])
- assert preflight["run"] == "npm whoami"
- assert preflight["env"]["NODE_AUTH_TOKEN"] == "${{ secrets.NPM_TOKEN }}"
- assert preflight_index < publish_index
+ assert steps[auth_index]["env"]["NPM_TOKEN"] == "${{ secrets.NPM_TOKEN }}"
+ assert "registry.npmjs.org" in steps[auth_index]["run"]
+ assert steps[preflight_index]["run"] == "bun pm whoami"
+ assert auth_index < preflight_index < publish_index
-def test_npm_release_publishes_public_package_with_provenance(release_yml: dict):
+def test_npm_release_publishes_public_package_with_bun(release_yml: dict):
+ """The registry tarball is published by bun; no npm CLI anywhere in the
+ release path (npm's provenance attestation went with it)."""
steps = _run_steps(release_yml["jobs"]["publish-npm"])
- publish = next(step for step in steps if "npm publish" in step["run"])
+ publish = next(step for step in steps if "bun publish" in step["run"])
- assert publish["run"] == "npm publish --access public --provenance"
- assert publish["env"]["NODE_AUTH_TOKEN"] == "${{ secrets.NPM_TOKEN }}"
+ assert publish["run"] == "bun publish --access public"
+ assert not any(step["run"].startswith("npm ") for step in steps)
+ assert not any("setup-node" in str(step.get("uses", "")) for step in release_yml["jobs"]["publish-npm"]["steps"])
def test_github_packages_release_keeps_github_owner_scope(release_yml: dict):
@@ -486,6 +474,7 @@ def test_github_packages_release_keeps_github_owner_scope(release_yml: dict):
configure = next(
step for step in steps if "pkg.name = '@zeenie-ai/opencompany'" in step["run"]
)
+ assert configure["run"].lstrip().startswith("bun -e")
registry_assignment = next(
line.strip()
@@ -495,7 +484,10 @@ def test_github_packages_release_keeps_github_owner_scope(release_yml: dict):
assert registry_assignment == (
"pkg.publishConfig = { registry: 'https://npm.pkg.github.com' };"
)
- assert any(step["run"] == "npm publish" for step in steps)
+ assert any(step["run"] == "bun publish" for step in steps)
+ auth = next(step for step in steps if "_authToken" in step["run"])
+ assert "npm.pkg.github.com" in auth["run"]
+ assert auth["env"]["NPM_TOKEN"] == "${{ secrets.GITHUB_TOKEN }}"
@pytest.mark.parametrize("scope", ["@zeenie", "@zeenie-ai"])
@@ -528,11 +520,11 @@ def test_preinstall_never_removes_current_package_directory(preinstall_js_src: s
def test_preinstall_gates_source_checkouts_to_bun(preinstall_js_src: str):
"""The dev-PM gate keys on ``bunfig.toml`` (committed, excluded from
- the npm tarball by the ``files`` allowlist) and on the user agent
+ the published tarball by the ``files`` allowlist) and on the user agent
starting with ``bun``. Bun's UA contains the literal ``npm/?``
substring, so a substring match on ``npm`` would misfire — the gate
- must use a prefix check. End-user tarball installs (no bunfig.toml)
- must stay on npm without triggering the gate.
+ must use a prefix check. A published tarball (no bunfig.toml) never
+ trips the gate, whatever installed it.
"""
assert "bunfig.toml" in preinstall_js_src
assert "agent.startsWith('bun')" in preinstall_js_src
@@ -563,28 +555,61 @@ def test_root_manifest_declares_bun_as_the_dev_package_manager(root_pkg: dict):
)
-def test_root_scripts_never_hop_through_npm(root_pkg: dict):
+def test_root_scripts_never_hop_through_npm_or_node(root_pkg: dict):
"""Every root script that reaches another package's script does so via
``bun --cwd=<dir> run`` (the ``=`` form — bun 1.4 rejects the
- space-separated spelling). The end-user npm lifecycle hooks
- (``preinstall`` / ``postinstall`` / ``preuninstall``) are the deliberate
- exception: they run under the installing user's Node, where bun may be
- absent.
+ space-separated spelling), and the lifecycle hooks run their scripts
+ under bun: there is no Node on the machine of a ``bun add -g`` user.
"""
- lifecycle = {"preinstall", "postinstall", "preuninstall"}
for name, cmd in root_pkg["scripts"].items():
- if name in lifecycle:
- continue
assert "npm run" not in cmd and "npx " not in cmd, (
f"root script {name!r} hops through npm: {cmd!r}"
)
- assert not cmd.startswith("node "), (
+ assert not cmd.startswith("node ") and " node " not in f" {cmd} ", (
f"root script {name!r} invokes node directly: {cmd!r}"
)
+ for hook in ("preinstall", "postinstall", "preuninstall"):
+ assert root_pkg["scripts"][hook].startswith("bun scripts/"), hook
assert root_pkg["scripts"]["client:start"] == "bun --cwd=client run start"
assert root_pkg["scripts"]["test:frontend"] == "bun --cwd=client run test"
+def test_root_package_declares_bun_engine_and_no_express(root_pkg: dict):
+ """``engines`` names bun, the runtime of the launcher and the sidecar;
+ the root ``express`` dependency (once a hack so the npm-tarball install
+ could run the sidecar's external express) is gone — the sidecar bundle
+ inlines it."""
+ engines = root_pkg.get("engines", {})
+ assert "bun" in engines and "node" not in engines
+ assert "express" not in root_pkg.get("dependencies", {})
+
+
+def test_installers_provision_through_the_shim_not_a_guessed_package_root(root: Path):
+ """``bun add -g`` runs no dependency lifecycle scripts, so the installers
+ provision explicitly. They must do it through ``company provision``
+ (the shim knows its own package root) and never by spelling bun's global
+ package directory, which differs by platform and configuration (on
+ Windows 1.4 it landed in the user profile, not under BUN_INSTALL)."""
+ for rel in ("install.sh", "install.ps1", "cli/terraform/gcp/startup.sh.tftpl"):
+ src = (root / rel).read_text(encoding="utf-8")
+ assert "provision" in src, rel
+ assert "install/global/node_modules" not in src, rel
+ assert "scripts/install.js" not in src, rel
+ launcher = (root / "bin" / "cli.js").read_text(encoding="utf-8")
+ assert "function provision(" in launcher
+ assert "function ensureProvisioned(" in launcher
+ assert "cmd === 'provision'" in launcher
+
+
+def test_launcher_and_install_scripts_run_under_bun(root: Path):
+ """The ``company`` bin and the lifecycle scripts carry a bun shebang, so
+ a global install runs them on bun (npm's cmd-shim on Windows and the
+ symlinked bin on POSIX both honour it)."""
+ for rel in ("bin/cli.js", "bin/machina.js", "scripts/install.js", "scripts/preinstall.js", "scripts/postinstall.js"):
+ first = (root / rel).read_text(encoding="utf-8").splitlines()[0]
+ assert first == "#!/usr/bin/env bun", f"{rel}: {first!r}"
+
+
def test_bunfig_pins_the_isolated_linker(root: Path):
"""``linker = "isolated"`` preserves pnpm's phantom-dependency guard
(symlinked layout); the tsgo typeRoots / vite-env.d.ts workarounds
diff --git a/install.ps1 b/install.ps1
index 49fdd1dd..358b31c0 100644
--- a/install.ps1
+++ b/install.ps1
@@ -2,14 +2,17 @@
# Usage: iwr -useb https://raw.githubusercontent.com/zeenie-ai/OpenCompany/main/install.ps1 | iex
#
# This script installs OpenCompany and its dependencies:
-# - Node.js 18+ (installs 22 LTS via winget/choco when absent)
+# - bun (the JavaScript runtime and package manager; no Node.js, no npm)
# - Python 3.12+ (via winget/choco)
# - uv (Python package manager)
+#
+# Prefer the desktop app if you just want to use OpenCompany on a laptop; this
+# path is for terminal use.
$ErrorActionPreference = "Stop"
-$MIN_NODE_VERSION = 18
$MIN_PYTHON_VERSION = "3.12"
+$PKG_NAME = "@zeenie-ai/opencompany"
# Colors
function Write-Color {
@@ -47,43 +50,33 @@ function Refresh-Path {
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
}
+# bun installs to $env:BUN_INSTALL (default ~\.bun) and puts global bin shims
+# in its bin dir. Where it stores the global package itself varies, so nothing
+# below depends on that: the `company` shim knows its own package root and
+# `company provision` does the rest.
+$BUN_HOME = if ($env:BUN_INSTALL) { $env:BUN_INSTALL } else { Join-Path $env:USERPROFILE ".bun" }
+$BUN_BIN_DIR = Join-Path $BUN_HOME "bin"
+
# =============================================================================
# Dependency Checks and Installation
# =============================================================================
-function Check-Node {
- if (Has-Command "node") {
- $version = (node --version) -replace "v", ""
- $major = [int]($version.Split(".")[0])
- if ($major -ge $MIN_NODE_VERSION) {
- Success "Node.js v$version"
- return $true
- }
- Warn "Node.js v$version is too old (need v$MIN_NODE_VERSION+)"
+function Check-Bun {
+ if (Has-Command "bun") {
+ Success "bun $(bun --version)"
+ return $true
}
return $false
}
-function Install-Node {
- Info "Installing Node.js LTS (need v$MIN_NODE_VERSION+)..."
- $pm = Get-PackageManager
-
- switch ($pm) {
- "winget" {
- winget install OpenJS.NodeJS.LTS --accept-package-agreements --accept-source-agreements
- }
- "choco" {
- choco install nodejs-lts -y
- }
- default {
- Error-Exit "Please install winget or chocolatey, or install Node.js manually from https://nodejs.org/"
- }
- }
-
+function Install-Bun {
+ Info "Installing bun (JavaScript runtime and package manager)..."
+ Invoke-RestMethod https://bun.sh/install.ps1 | Invoke-Expression
+ $env:Path = "$BUN_BIN_DIR;$env:Path"
Refresh-Path
-
- if (-not (Check-Node)) {
- Error-Exit "Failed to install Node.js. Please install manually and restart PowerShell."
+ $env:Path = "$BUN_BIN_DIR;$env:Path"
+ if (-not (Check-Bun)) {
+ Error-Exit "Failed to install bun. Install it manually from https://bun.sh and restart PowerShell."
}
}
@@ -159,18 +152,19 @@ function Install-Uv {
}
}
-# The pre-rebrand package owns the deprecated `machina` command too. Remove it
-# before installing OpenCompany so npm does not fail with an existing shim.
-function Remove-LegacyMachinaOs {
- npm list -g --depth=0 machinaos *> $null
- if ($LASTEXITCODE -ne 0) { return }
-
- Info "Removing legacy machinaos package..."
- npm uninstall -g machinaos
- if ($LASTEXITCODE -ne 0) {
- Error-Exit "Unable to remove legacy machinaos. Run PowerShell as Administrator and retry."
+# A previous npm-based install (or the pre-rebrand `machinaos` package) leaves
+# a `company` / `machina` shim on PATH that would shadow the bun one. Remove it
+# when npm happens to be around; skip silently otherwise.
+function Remove-LegacyNpmInstalls {
+ if (-not (Has-Command "npm")) { return }
+ foreach ($pkg in @($PKG_NAME, "machinaos")) {
+ npm list -g --depth=0 $pkg *> $null
+ if ($LASTEXITCODE -eq 0) {
+ Info "Removing legacy npm install of $pkg..."
+ npm uninstall -g $pkg *> $null
+ if ($LASTEXITCODE -ne 0) { Warn "Could not remove $pkg; run: npm uninstall -g $pkg" }
+ }
}
- Success "Legacy machinaos package removed"
}
# =============================================================================
@@ -183,21 +177,30 @@ function Main {
Write-Host ""
# Check and install dependencies
- if (-not (Check-Node)) { Install-Node }
+ if (-not (Check-Bun)) { Install-Bun }
if (-not (Check-Python)) { Install-Python }
if (-not (Check-Uv)) { Install-Uv }
- # Avoid a collision with the deprecated `machina` compatibility shim.
- Remove-LegacyMachinaOs
+ Remove-LegacyNpmInstalls
Write-Host ""
Info "Installing OpenCompany..."
Write-Host ""
- # Install OpenCompany from npm
- npm install -g "@zeenie-ai/opencompany"
+ # Global install as the current user (bun's global root is user-owned).
+ bun add -g $PKG_NAME
+ if ($LASTEXITCODE -ne 0) {
+ Error-Exit "bun add -g $PKG_NAME failed."
+ }
+
+ # bun runs no lifecycle scripts for a global package, so provision the
+ # Python side now rather than on the first `company` command. The shim is
+ # addressed through bun's own answer for the global bin dir.
+ $company = Join-Path (bun pm bin -g) "company.exe"
+ Info "Provisioning the Python environment..."
+ & $company provision
if ($LASTEXITCODE -ne 0) {
- Error-Exit "npm install -g failed. Run PowerShell as Administrator and retry."
+ Error-Exit "Provisioning failed. Re-run with: company provision"
}
Write-Host ""
@@ -208,33 +211,12 @@ function Main {
Write-Host " Start OpenCompany:"
Write-Host " company start"
Write-Host ""
- Write-Host " Open in browser:"
- # .env.template ships inside the installed package. This used to read it
- # from the working directory, which is wherever the user ran the script --
- # so it printed a bare "http://localhost:", and dereferencing .Matches on
- # the null result could fault outright. Resolve through npm's global root.
- $appPort = $null
- $npmRoot = (npm root -g 2>$null | Select-Object -First 1)
- if ($npmRoot) {
- $templatePath = Join-Path $npmRoot "@zeenie-ai/opencompany/.env.template"
- if (Test-Path $templatePath) {
- $match = Select-String -Path $templatePath -Pattern "^PYTHON_BACKEND_PORT=(\d+)" |
- Select-Object -First 1
- if ($match) { $appPort = $match.Matches.Groups[1].Value }
- }
- }
- if ($appPort) {
- Write-Host " http://localhost:$appPort"
- } else {
- Write-Host " the URL printed by 'company start'"
- }
- Write-Host ""
- Write-Host " For development from source, install bun:"
- Write-Host " https://bun.sh"
- Write-Host ""
Write-Host " Run diagnostics:"
Write-Host " company doctor"
Write-Host ""
+ Write-Host " If 'company' is not found, open a new PowerShell window (bun's bin dir"
+ Write-Host " was added to your PATH)."
+ Write-Host ""
}
# Run main
diff --git a/install.sh b/install.sh
index 64f4ab78..25245fcf 100755
--- a/install.sh
+++ b/install.sh
@@ -7,14 +7,17 @@
# unless OPENCOMPANY_VERSION is set.
#
# This script installs OpenCompany and its dependencies:
-# - Node.js 18+ (distro package via brew/apt/dnf/pacman)
+# - bun (the JavaScript runtime and package manager; no Node.js, no npm)
# - Python 3.12+ (via brew/apt/dnf/pacman)
# - uv (Python package manager)
+#
+# Prefer the desktop app if you just want to use OpenCompany on a laptop; this
+# path is for terminal and server use.
set -e
-MIN_NODE_VERSION=18
MIN_PYTHON_VERSION_MINOR=12
+PKG_NAME="@zeenie-ai/opencompany"
# Colors
RED='\033[0;31m'
@@ -52,152 +55,45 @@ detect_os() {
OS=$(detect_os)
-# Detect WSL
-is_wsl() {
- [[ -n "$WSL_DISTRO_NAME" ]] || [[ -n "$WSL_INTEROP" ]] || grep -qi microsoft /proc/version 2>/dev/null
-}
-
-# Configure npm for WSL (fix nvm conflicts and Windows paths)
-setup_wsl_npm() {
- if ! is_wsl; then
- return 0
- fi
-
- info "WSL detected: Checking npm configuration..."
-
- # If using nvm, remove any conflicting prefix from .npmrc
- if [[ -n "$NVM_DIR" ]] || [[ -d "$HOME/.nvm" ]]; then
- if grep -q '^prefix=' "$HOME/.npmrc" 2>/dev/null; then
- info "Removing conflicting npm prefix (nvm detected)..."
- sed -i '/^prefix=/d' "$HOME/.npmrc"
- # Also remove globalconfig if present
- sed -i '/^globalconfig=/d' "$HOME/.npmrc" 2>/dev/null || true
- fi
-
- # Source nvm to ensure proper paths
- export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
- if [[ -s "$NVM_DIR/nvm.sh" ]]; then
- source "$NVM_DIR/nvm.sh"
+# bun installs to $BUN_INSTALL (default ~/.bun) and puts global bin shims in
+# its bin dir. Where it stores the global package itself varies by platform
+# and configuration, so nothing below depends on that: the `company` shim
+# knows its own package root and `company provision` does the rest.
+BUN_HOME="${BUN_INSTALL:-$HOME/.bun}"
+BUN_BIN_DIR="$BUN_HOME/bin"
+
+# A previous npm-based install (or the pre-rebrand `machinaos` package) leaves
+# a `company` / `machina` shim on PATH that would shadow the bun one. Remove it
+# when npm happens to be around; skip silently otherwise.
+remove_legacy_npm_installs() {
+ command -v npm &> /dev/null || return 0
+ for pkg in "$PKG_NAME" machinaos; do
+ if npm list -g --depth=0 "$pkg" &> /dev/null; then
+ info "Removing legacy npm install of $pkg..."
+ npm uninstall -g "$pkg" &> /dev/null || warn "Could not remove $pkg; run: npm uninstall -g $pkg"
fi
-
- success "npm configured for nvm on WSL"
- return 0
- fi
-
- # No nvm - check if npm is using Windows path
- local npm_prefix
- npm_prefix=$(npm config get prefix 2>/dev/null || echo "")
-
- if [[ "$npm_prefix" == /mnt/* ]]; then
- info "Configuring npm to use Linux-native path..."
- mkdir -p "$HOME/.npm-global"
- npm config set prefix "$HOME/.npm-global"
- export PATH="$HOME/.npm-global/bin:$PATH"
-
- # Add to .bashrc if not already there
- if ! grep -q 'npm-global' "$HOME/.bashrc" 2>/dev/null; then
- echo '' >> "$HOME/.bashrc"
- echo '# npm global packages (WSL)' >> "$HOME/.bashrc"
- echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> "$HOME/.bashrc"
- info "Added npm-global to PATH in ~/.bashrc"
- fi
-
- success "npm configured for WSL"
- fi
-}
-
-# The pre-rebrand package owns the deprecated `machina` binary too. Remove it
-# before installing OpenCompany so npm does not fail with an EEXIST shim clash.
-remove_legacy_machinaos() {
- if ! npm list -g --depth=0 machinaos &> /dev/null; then
- return 0
- fi
-
- info "Removing legacy machinaos package..."
- if npm uninstall -g machinaos &> /dev/null; then
- success "Legacy machinaos package removed"
- elif command -v sudo &> /dev/null; then
- info "Retrying legacy package removal with sudo..."
- sudo npm uninstall -g machinaos
- success "Legacy machinaos package removed"
- else
- error_exit "Unable to remove legacy machinaos. Try: sudo npm uninstall -g machinaos"
- fi
+ done
}
# =============================================================================
# Dependency Checks and Installation
# =============================================================================
-check_node() {
- # Clear command hash to ensure we find the latest node binary
+check_bun() {
hash -r 2>/dev/null || true
-
- if command -v node &> /dev/null; then
- version=$(node --version | tr -d 'v')
- major=$(echo "$version" | cut -d. -f1)
- if [ "$major" -ge "$MIN_NODE_VERSION" ]; then
- success "Node.js v$version"
- return 0
- fi
- warn "Node.js v$version is too old (need v$MIN_NODE_VERSION+)"
+ if command -v bun &> /dev/null; then
+ success "bun $(bun --version)"
+ return 0
fi
return 1
}
-install_node() {
- info "Installing Node.js $MIN_NODE_VERSION..."
-
- case "$OS" in
- macos)
- if command -v brew &> /dev/null; then
- brew install node@22
- # Add node@22 to PATH (brew doesn't link it by default)
- export PATH="/opt/homebrew/opt/node@22/bin:/usr/local/opt/node@22/bin:$PATH"
- else
- error_exit "Please install Homebrew first: https://brew.sh/"
- fi
- ;;
- debian)
- # An existing Node >= 18 is kept (checked above). When none is
- # present, install the current LTS: the published package may still
- # require it, and Ubuntu 24.04's apt package is 18.
- curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
- sudo apt-get install -y nodejs
- # Force rehash PATH to find newly installed node
- hash -r 2>/dev/null || true
- # Source profile to update PATH if needed
- [ -f /etc/profile ] && source /etc/profile 2>/dev/null || true
- ;;
- redhat)
- curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
- sudo dnf install -y nodejs
- hash -r 2>/dev/null || true
- ;;
- arch)
- sudo pacman -S --noconfirm nodejs npm
- hash -r 2>/dev/null || true
- ;;
- *)
- error_exit "Please install Node.js 18+ manually from https://nodejs.org/"
- ;;
- esac
-
- # Clear hash and verify using full path as fallback
- hash -r 2>/dev/null || true
-
- # Check using direct path first (distro packages install to /usr/bin/node)
- if [ -x /usr/bin/node ]; then
- version=$(/usr/bin/node --version | tr -d 'v')
- major=$(echo "$version" | cut -d. -f1)
- if [ "$major" -ge "$MIN_NODE_VERSION" ]; then
- success "Node.js v$version installed"
- return 0
- fi
- fi
-
- if ! check_node; then
- error_exit "Failed to install Node.js. Please install manually."
+install_bun() {
+ info "Installing bun (JavaScript runtime and package manager)..."
+ curl -fsSL https://bun.sh/install | bash
+ export PATH="$BUN_BIN_DIR:$PATH"
+ if ! check_bun; then
+ error_exit "Failed to install bun. Install it manually from https://bun.sh and re-run."
fi
}
@@ -278,6 +174,23 @@ install_uv() {
fi
}
+ensure_bun_on_path() {
+ # The bun installer adds ~/.bun/bin to the shell profile; make sure the
+ # `company` shim is reachable from new shells even when bun was already
+ # present but its bin dir was not exported.
+ case ":$PATH:" in
+ *":$BUN_BIN_DIR:"*) ;;
+ *)
+ export PATH="$BUN_BIN_DIR:$PATH"
+ if ! grep -q '\.bun/bin' "$HOME/.bashrc" 2>/dev/null; then
+ echo '' >> "$HOME/.bashrc"
+ echo '# bun global packages (OpenCompany installer)' >> "$HOME/.bashrc"
+ echo 'export PATH="$HOME/.bun/bin:$PATH"' >> "$HOME/.bashrc"
+ fi
+ ;;
+ esac
+}
+
# =============================================================================
# Main Installation Flow
# =============================================================================
@@ -288,43 +201,32 @@ main() {
echo ""
# Check and install dependencies
- check_node || install_node
+ check_bun || install_bun
check_python || install_python
check_uv || install_uv
+ ensure_bun_on_path
- # Configure npm for WSL before installing
- setup_wsl_npm
-
- # Avoid a collision with the deprecated `machina` compatibility shim.
- remove_legacy_machinaos
+ remove_legacy_npm_installs
echo ""
info "Installing OpenCompany..."
echo ""
- # Install OpenCompany from npm, as the current user. If the global npm
- # prefix is not writable (system-wide Node on Linux), switch to a
- # user-owned prefix rather than sudo: a root install leaves the venvs and
- # ~/.opencompany owned by root, and `company start` as the login user
- # then fails with "python: not found" (docs-internal/errors.md #16).
- # https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally
- if [ ! -w "$(npm prefix -g)" ]; then
- info "Global npm prefix is not writable; using ~/.npm-global"
- mkdir -p "$HOME/.npm-global"
- npm config set prefix "$HOME/.npm-global"
- export PATH="$HOME/.npm-global/bin:$PATH"
- if ! grep -q 'npm-global' "$HOME/.bashrc" 2>/dev/null; then
- echo '' >> "$HOME/.bashrc"
- echo '# npm global packages (OpenCompany installer)' >> "$HOME/.bashrc"
- echo 'export PATH="$HOME/.npm-global/bin:$PATH"' >> "$HOME/.bashrc"
- fi
- fi
# OPENCOMPANY_VERSION pins a release (the cli/terraform startup scripts set
# it). Otherwise ask opencompany.sh which release is current; if that is
- # unreachable, fall back to npm's latest tag.
+ # unreachable, fall back to the registry's latest tag.
VERSION="${OPENCOMPANY_VERSION:-$(curl -fsSL --max-time 10 https://opencompany.sh/version 2>/dev/null | tr -d '[:space:]' || true)}"
- PKG="@zeenie-ai/opencompany${VERSION:+@$VERSION}"
- npm install -g "$PKG" || error_exit "npm install -g $PKG failed."
+ PKG="${PKG_NAME}${VERSION:+@$VERSION}"
+ # Global install as the current user: bun's global root is user-owned, so
+ # no sudo and no root-owned venvs (docs-internal/errors.md #16).
+ bun add -g "$PKG" || error_exit "bun add -g $PKG failed."
+
+ # bun runs no lifecycle scripts for a global package, so provision the Python
+ # side now rather than on the first `company` command (which would do it too).
+ # The shim is addressed through bun's own answer for the global bin dir.
+ COMPANY="$(bun pm bin -g)/company"
+ info "Provisioning the Python environment..."
+ "$COMPANY" provision || error_exit "Provisioning failed. Re-run with: company provision"
echo ""
echo -e "${GREEN}============================================${NC}"
@@ -334,33 +236,15 @@ main() {
echo " Start OpenCompany:"
echo " company start"
echo ""
- echo " Open in browser:"
- # `.env.template` ships inside the installed package. This used to grep it
- # from the working directory, which for `curl | bash` is wherever the user
- # happened to be -- so the line rendered as a bare "http://localhost:".
- # Resolve through npm's global root instead, and stay silent about the port
- # rather than hardcoding it if that lookup fails.
- APP_PORT=""
- NPM_ROOT="$(npm root -g 2>/dev/null)"
- if [ -n "$NPM_ROOT" ] && [ -f "$NPM_ROOT/@zeenie-ai/opencompany/.env.template" ]; then
- APP_PORT="$(grep -E '^PYTHON_BACKEND_PORT=' "$NPM_ROOT/@zeenie-ai/opencompany/.env.template" \
- | head -1 | cut -d= -f2 | tr -d '[:space:]')"
- fi
- if [ -n "$APP_PORT" ]; then
- echo " http://localhost:${APP_PORT}"
- else
- echo " the URL printed by 'company start'"
- fi
- echo ""
echo " Optional: Enable JS-rendered web scraping:"
echo " playwright install chromium"
echo ""
- echo " For development from source, install bun:"
- echo " https://bun.sh"
- echo ""
echo " Run diagnostics:"
echo " company doctor"
echo ""
+ echo " New shells pick up the bun bin dir from your profile; in this one run:"
+ echo " export PATH=\"\$HOME/.bun/bin:\$PATH\""
+ echo ""
}
# Run main
diff --git a/package.json b/package.json
index ea9908ea..51218576 100644
--- a/package.json
+++ b/package.json
@@ -34,7 +34,7 @@
"machina": "./bin/machina.js"
},
"engines": {
- "node": ">=18.0.0"
+ "bun": ">=1.4.0"
},
"packageManager": "[email protected]",
"files": [
@@ -58,6 +58,8 @@
"!**/.pytest_cache/",
"!**/node_modules/",
"!**/.vite/",
+ "!**/.terraform/",
+ "!server/tests/_test_opencompany_root/",
".env.template",
"pyproject.toml",
"README.md",
@@ -97,13 +99,12 @@
"version:sync": "python -m cli version sync",
"typecheck": "tsc --noEmit -p client/tsconfig.json",
"prepublishOnly": "python -m cli version sync && bun -e \"const p=require('./package.json'); if(!p.bin||!p.version){process.exit(1)}\"",
- "preinstall": "node scripts/preinstall.js",
- "postinstall": "node scripts/postinstall.js",
- "preuninstall": "node scripts/preinstall.js"
+ "preinstall": "bun scripts/preinstall.js",
+ "postinstall": "bun scripts/postinstall.js",
+ "preuninstall": "bun scripts/preinstall.js"
},
"dependencies": {
- "cross-env": "^10.1.0",
- "express": "^5.2.1"
+ "cross-env": "^10.1.0"
},
"devDependencies": {
"typescript": "7.0.2"
diff --git a/scripts/install.js b/scripts/install.js
index 6d6ffc14..b152c4df 100755
--- a/scripts/install.js
+++ b/scripts/install.js
@@ -1,10 +1,13 @@
-#!/usr/bin/env node
+#!/usr/bin/env bun
/**
* OpenCompany Installation Script
*
- * Called by postinstall.js after npm install.
- * Installs all dependencies including Python and uv.
- * WhatsApp RPC is now an npm dependency with pre-built binaries.
+ * Provisions the Python side of an install: uv, the server venv, bytecode,
+ * the CLI venv and the Temporal binary. Called by postinstall.js in a
+ * source checkout (`bun install`) and by bin/cli.js on the first `company`
+ * command of a global install (`bun add -g` runs no dependency lifecycle
+ * scripts). Plain JavaScript: runs under bun, and under node for a legacy
+ * npm-installed copy.
*/
import { execSync } from 'child_process';
import { existsSync, copyFileSync } from 'fs';
@@ -29,7 +32,7 @@ process.env.PYTHONUTF8 = '1';
function run(cmd, cwd = ROOT, timeoutMs = 300000) {
// Strip VIRTUAL_ENV from the spawned env. When the user runs
- // ``npm install -g @zeenie-ai/opencompany`` from a shell that has activated a
+ // ``bun add -g @zeenie-ai/opencompany`` from a shell that has activated a
// venv (very common during dev), uv emits a noisy ``VIRTUAL_ENV
// ... does not match the project environment path`` warning per
// invocation. uv only honours VIRTUAL_ENV with ``--active``, which
@@ -127,8 +130,7 @@ function installUv(pythonCmd) {
console.log('');
console.log('Checking dependencies...');
console.log('');
-console.log(` Node.js: ${getVersion('node --version')}`);
-console.log(` npm: ${getVersion('npm --version')}`);
+console.log(` bun: ${getVersion('bun --version') || 'not found (JS executor and plugin CLIs need it: https://bun.sh)'}`);
// Check Python (required, user must install)
let python = checkPython();
@@ -173,10 +175,10 @@ console.log(
);
// agent-browser is managed by the Python backend
-// (server/nodes/browser/_install.py) — npm-installed into
-// platformdirs.user_cache_path("OpenCompany")/browser/npm/ on first
-// use, with the Chromium runtime fetched by ``agent-browser install``
-// when the browser node first spawns. No npm dep, no postinstall step.
+// (server/nodes/browser/_install.py) — `bun add`ed into the shared
+// <DATA_DIR>/packages/ tree on first use, with the Chromium runtime
+// fetched by ``agent-browser install`` when the browser node first
+// spawns. No dependency here, no postinstall step.
console.log('');
console.log('Installing...');
@@ -204,19 +206,19 @@ try {
console.log(`[${step}/${totalSteps}] .env exists`);
}
- // Skip client install/build if dist already exists (pre-built in npm package)
+ // Skip client install/build if dist already exists (pre-built in the published package)
if (clientDistExists) {
console.log(`[SKIP] Client already built (dist/index.html exists)`);
} else {
- // Install client dependencies
+ // Install workspace dependencies
step++;
console.log(`[${step}/${totalSteps}] Installing client dependencies...`);
- run('npm install', clientDir, 600000); // 10 min timeout
+ run('bun install', ROOT, 600000); // 10 min timeout
// Build client
step++;
console.log(`[${step}/${totalSteps}] Building client...`);
- run('npm run build', clientDir, 600000); // 10 min timeout
+ run('bun run build', clientDir, 600000); // 10 min timeout
}
// Install Python dependencies (always needed - venv not included in package)
diff --git a/scripts/postinstall.js b/scripts/postinstall.js
index 64176c59..9c44a7eb 100755
--- a/scripts/postinstall.js
+++ b/scripts/postinstall.js
@@ -1,10 +1,12 @@
-#!/usr/bin/env node
+#!/usr/bin/env bun
/**
* Postinstall script for OpenCompany.
*
- * Runs install.js to check deps, install npm/Python packages, build.
- * Plugin daemons (WhatsApp, Stripe, ...) install lazily via their own
- * plugin code on first use.
+ * Runs install.js to check deps, provision the Python venvs and build.
+ * Reached from `bun install` in a source checkout; a global `bun add -g`
+ * runs no dependency lifecycle scripts, so bin/cli.js provisions on the
+ * first `company` command instead. Plugin daemons (WhatsApp, Stripe, ...)
+ * install lazily via their own plugin code on first use.
*/
import { spawn, execSync } from 'child_process';
import { resolve, dirname } from 'path';
@@ -96,7 +98,7 @@ async function main() {
// bin/cli.js, masking the real entry point.
//
// Both call sites that need the Python CLI use `python -m cli
- // <cmd>` (npm run start, .github/workflows/release.yml version
+ // <cmd>` (bun run start, .github/workflows/release.yml version
// sync). `-m` resolves the package from the working directory's
// sys.path entry, which `bin/cli.js` already pins to the npm
// package root via `cwd: ROOT`. No pip install required.
diff --git a/scripts/preinstall.js b/scripts/preinstall.js
index 45d3ff10..feabe2ee 100755
--- a/scripts/preinstall.js
+++ b/scripts/preinstall.js
@@ -1,9 +1,10 @@
-#!/usr/bin/env node
+#!/usr/bin/env bun
/**
* Preinstall cleanup script for OpenCompany.
*
- * Fixes npm ENOTEMPTY error by cleaning up leftover temp directories
- * that npm fails to remove during failed install/uninstall operations.
+ * Gates source checkouts to bun, and fixes npm's ENOTEMPTY error by
+ * cleaning up leftover temp directories that a legacy npm install failed
+ * to remove (a no-op when npm is not installed).
*
* @see https://github.com/anthropics/claude-code/issues/7373
* @see https://bobbyhadz.com/blog/npm-err-code-enotempty
@@ -25,8 +26,9 @@ if (process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true') {
}
// Enforce bun for source checkouts (bunfig.toml is committed but excluded
-// from the npm tarball by the "files" allowlist, so end-user installs of the
-// published package never carry it and stay on npm).
+// from the published tarball by the "files" allowlist, so a global install
+// of the published package never carries it and this gate never fires
+// there; `bun add -g` runs no dependency lifecycle scripts anyway).
try {
statSync(resolve(__dirname, '..', 'bunfig.toml'));
const agent = process.env.npm_config_user_agent || '';
@@ -38,7 +40,7 @@ try {
process.exit(1);
}
} catch {
- // No bunfig.toml = end-user tarball install; npm is allowed.
+ // No bunfig.toml = published tarball; nothing to gate.
}
function getGlobalNodeModules() {
diff --git a/uninstall.sh b/uninstall.sh
index 808efc71..79be012d 100644
--- a/uninstall.sh
+++ b/uninstall.sh
@@ -2,20 +2,41 @@
# OpenCompany Uninstaller
#
# Usage: curl -fsSL https://raw.githubusercontent.com/zeenie-ai/OpenCompany/main/uninstall.sh | bash
+#
+# Removes the bun global install (the current channel) and, when npm happens
+# to be present, any legacy npm install of the scoped package or the official
+# pre-rebrand `machinaos` package. The unrelated unscoped npm package named
+# `opencompany` is never touched. ~/.opencompany (workflows, credentials,
+# downloaded runtimes) is left in place.
set -e
echo "Uninstalling OpenCompany..."
echo ""
-# Remove only OpenCompany's scoped package and the official pre-rebrand
-# package. The unrelated unscoped package named `opencompany` is untouched.
+remove_bun_global_package() {
+ local package_name="$1"
+ local display_name="$2"
+
+ command -v bun &> /dev/null || return 0
+ # `bun remove -g` is the only probe: `bun pm ls -g` aborts on a stray npm
+ # lockfile in bun's global dir, and removing an absent package is harmless.
+ if bun remove -g "$package_name" &> /dev/null; then
+ echo "$display_name removed"
+ else
+ echo "$display_name not installed with bun (or removal failed; try: bun remove -g $package_name)"
+ fi
+}
+
+# Legacy npm channel. Remove only OpenCompany's scoped package and the
+# official pre-rebrand package.
remove_global_package() {
local package_name="$1"
local display_name="$2"
+ command -v npm &> /dev/null || return 0
if ! npm list -g --depth=0 "$package_name" &> /dev/null; then
- echo "$display_name not installed"
+ echo "$display_name not installed with npm"
return 0
fi
@@ -32,7 +53,8 @@ remove_global_package() {
echo "$display_name removed"
}
-remove_global_package '@zeenie-ai/opencompany' '@zeenie-ai/opencompany'
+remove_bun_global_package '@zeenie-ai/opencompany' '@zeenie-ai/opencompany'
+remove_global_package '@zeenie-ai/opencompany' 'legacy npm install of @zeenie-ai/opencompany'
remove_global_package 'machinaos' 'legacy machinaos package'
echo ""