Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(desktop): bundle the Computer tools so computer use works

claude-opus-5-5-mediumc8f0c7e40f26
diff --git a/Makefile b/Makefile
index 62e813ff..16dc6f47 100644
--- a/Makefile
+++ b/Makefile
@@ -119,6 +119,7 @@ check-desktop:
pnpm --filter @linger/desktop typecheck
pnpm --filter @linger/desktop lint
pnpm --filter @linger/desktop test
+ python3 -m unittest discover -s apps/desktop/packaging -p '*_test.py'
# The Go daemon that packaging bundles, for every platform the app ships on.
cd apps/desktop && node scripts/build-daemon.mjs --all
diff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go
index b28305ef..b12d484d 100644
--- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go
+++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go
@@ -228,6 +228,11 @@ func run(args []string) (resultErr error) {
if err != nil {
return err
}
+ if toolInstallation == nil {
+ // Agents on this computer then have no browser or computer-control
+ // tools; say so instead of leaving them silently missing.
+ slog.Warn("computer_tools.missing: browser and computer-control tools are disabled", "expected", localtools.ToolsDirectory(executable))
+ }
var toolManager *localtools.Manager
var toolBinder daemon.LocalToolBinder
var piExtension string
diff --git a/apps/computer/local-daemon/internal/linger/localtools/installation.go b/apps/computer/local-daemon/internal/linger/localtools/installation.go
index b2e34810..c699d14c 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/installation.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/installation.go
@@ -25,13 +25,20 @@ func osMetadataFile(name string) bool {
return (strings.HasPrefix(name, "._") && len(name) > 2) || strings.EqualFold(name, ".DS_Store") || strings.EqualFold(name, "Thumbs.db") || strings.EqualFold(name, "desktop.ini")
}
+// ToolsDirectory is where Installed looks for the tools: cli/computer-tools
+// two folders above the executable. The Desktop app's daemon runs from
+// resources/computer/, so its tools are resources/cli/computer-tools.
+func ToolsDirectory(executable string) string {
+ return filepath.Join(filepath.Dir(filepath.Dir(executable)), "cli", "computer-tools")
+}
+
// Installed resolves only sibling release assets and verifies their frozen
// manifest. An unbundled development daemon has no implicit PATH fallback.
func Installed(executable string) (*Installation, error) {
root := filepath.Dir(filepath.Dir(executable))
// An installed bundle links cli/computer-tools to its verified deps
// directory; the checks below apply to the files it points at.
- tools, err := filepath.EvalSymlinks(filepath.Join(root, "cli", "computer-tools"))
+ tools, err := filepath.EvalSymlinks(ToolsDirectory(executable))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
diff --git a/apps/computer/local-daemon/internal/linger/localtools/installation_test.go b/apps/computer/local-daemon/internal/linger/localtools/installation_test.go
index adcadc16..f8d55a35 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/installation_test.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/installation_test.go
@@ -225,3 +225,47 @@ func TestWindowsInstalledToolsUseExtractedBundle(t *testing.T) {
t.Fatal("unlisted tool asset accepted")
}
}
+
+// The Desktop app runs the daemon from resources/computer/ and packages the
+// tools as resources/cli/computer-tools and resources/runtime.
+func TestInstalledToolsInTheDesktopLayout(t *testing.T) {
+ resources := t.TempDir()
+ executable := filepath.Join(resources, "computer", "linger-computer-daemon")
+ if got := ToolsDirectory(executable); got != filepath.Join(resources, "cli", "computer-tools") {
+ t.Fatalf("tools directory = %s", got)
+ }
+ if result, err := Installed(executable); result != nil || err != nil {
+ t.Fatalf("desktop without tools: %+v %v", result, err)
+ }
+ tools := ToolsDirectory(executable)
+ entries := []string{"node_modules/@playwright/mcp/cli.js", "extensions/pi-mcp.mjs"}
+ assets := make([]map[string]any, 0, len(entries))
+ for _, name := range entries {
+ file := filepath.Join(tools, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(file), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(file, []byte("fixture"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ assets = append(assets, map[string]any{"path": name, "size_bytes": 7})
+ }
+ manifest, err := json.Marshal(map[string]any{"schema_version": 1, "versions": map[string]string{"playwright": "0.0.83", "pi": "1.2.0", "cua": "0.35.4"}, "playwright_entry": entries[0], "pi_extension": entries[1], "assets": assets})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(tools, "manifest.json"), manifest, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ node := filepath.Join(resources, "runtime", "bin", "node")
+ if err := os.MkdirAll(filepath.Dir(node), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(node, []byte("fixture"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ result, err := Installed(executable)
+ if err != nil || result == nil || result.NodePath != node || result.PlaywrightEntry != filepath.Join(tools, filepath.FromSlash(entries[0])) {
+ t.Fatalf("desktop installation: %+v %v", result, err)
+ }
+}
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index 7d5ea872..5800c40e 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -303,6 +303,12 @@ Gateway and runs Agents. The daemon exits with the app.
handshake that this needs; the bridge itself was deleted.
- `scripts/build-daemon.mjs`: cross-compiles the daemon, stamped with the
`apps/computer` release the Gateway checks.
+- `scripts/stage-computer-tools.mjs`: stages the browser and computer-control
+ tools and their Node.js for each daemon target into
+ `dist/computer-tools/<target>/` with the root
+ `scripts/computer-tool-bundle.mjs`; `packaging/computer_tools.py` puts them in
+ `resources/cli/` and `resources/runtime/` and checks every package for them
+ (see [Computer Tools](../../docs/desktop-release.md#computer-tools)).
## Important Conventions
diff --git a/apps/desktop/build.mjs b/apps/desktop/build.mjs
index 71e08c3d..a4cc69d8 100644
--- a/apps/desktop/build.mjs
+++ b/apps/desktop/build.mjs
@@ -10,6 +10,7 @@ import path from "node:path";
import { build } from "esbuild";
import { buildDaemon } from "./scripts/build-daemon.mjs";
+import { stageDesktopComputerTools } from "./scripts/stage-computer-tools.mjs";
import { hostedDiagnosticsUploadUrl } from "./scripts/diagnostics-upload-url.mjs";
import { buildTeamhub, TEAMHUB_TARGETS } from "./scripts/build-teamhub.mjs";
import {
@@ -314,5 +315,8 @@ set ELECTRON_RUN_AS_NODE=1\r
);
// The Go Local Computer daemon (dist/computer/<platform>-<arch>/) for each
-// target.
+// target, and the browser and computer-control tools it loads
+// (dist/computer-tools/<platform>-<arch>/). Without the tools the daemon runs
+// but offers Agents no browser or computer use.
await buildDaemon(daemonTargets);
+await stageDesktopComputerTools(daemonTargets);
diff --git a/apps/desktop/packaging/computer_tools.py b/apps/desktop/packaging/computer_tools.py
new file mode 100644
index 00000000..999eb024
--- /dev/null
+++ b/apps/desktop/packaging/computer_tools.py
@@ -0,0 +1,116 @@
+"""The browser and computer-control tools the Go daemon loads.
+
+build.mjs stages them per target in dist/computer-tools/<target>/
+(scripts/stage-computer-tools.mjs): cli/computer-tools/ with its frozen
+manifest.json, and runtime/bin/node, the pinned Node.js they run on. They are
+the same files as the Local Computer dependency package. The daemon looks for
+them two folders above its executable (localtools.Installed in
+apps/computer/local-daemon), so every package script copies both next to
+resources/computer/ and checks the result: without them the daemon starts but
+offers no browser or computer-control tool.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tarfile
+import zipfile
+
+DESKTOP = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+STAGED = os.path.join(DESKTOP, "dist", "computer-tools")
+TOOLS = os.path.join("cli", "computer-tools")
+# The frozen manifest's rules live in one place, shared with the Local
+# Computer dependency package.
+BUNDLE_SCRIPT = os.path.join(DESKTOP, "..", "..", "scripts", "computer-tool-bundle.mjs")
+
+
+class Invalid(Exception):
+ pass
+
+
+def node_path(target):
+ return os.path.join("runtime", "bin", "node.exe" if target.startswith("win32-") else "node")
+
+
+def _bundle_script(*args):
+ result = subprocess.run(["node", BUNDLE_SCRIPT, *args], capture_output=True, text=True)
+ if result.returncode:
+ raise Invalid(result.stderr.strip() or f"computer-tool-bundle.mjs {args[0]} failed")
+
+
+def copy(resources, target, staged=STAGED):
+ """Copies the target's staged tools into resources/ and checks them."""
+ source = os.path.join(staged, target)
+ if not os.path.isdir(os.path.join(source, TOOLS)):
+ sys.exit(f"dist/ is missing the Computer tools for {target}; run "
+ f"`LINGER_DESKTOP_DAEMON_TARGETS={target} node build.mjs` first")
+ for name in ("cli", "runtime"):
+ shutil.copytree(os.path.join(source, name), os.path.join(resources, name))
+ check(resources, target)
+
+
+def verify(resources, target):
+ """Raises Invalid unless resources/ holds the tools as the daemon expects:
+ every file of the frozen manifest and nothing else, and an executable
+ Node.js."""
+ _bundle_script("verify", resources, target)
+
+
+def check(resources, target):
+ """Exits unless resources/ holds the tools as the daemon expects."""
+ try:
+ verify(resources, target)
+ except Invalid as error:
+ sys.exit(f"Computer tools in {resources}: {error}")
+
+
+def refresh_signed(resources, kept=()):
+ """Records the bytes code signing wrote into the tools' Mach-O files.
+
+ Only Mach-O assets may differ from the manifest; any other change still
+ fails the check that follows. Paths in kept were put back as the vendor
+ signed them and must match as before.
+ """
+ _bundle_script("record-signed", resources, *kept)
+
+
+def _archive_members(archive):
+ """{name: size} of the archive's files and a reader of one of them."""
+ if archive.endswith(".zip"):
+ source = zipfile.ZipFile(archive)
+ sizes = {info.filename: info.file_size for info in source.infolist() if not info.is_dir()}
+ return source, sizes, source.read
+ source = tarfile.open(archive, "r:gz")
+ sizes = {info.name: info.size for info in source.getmembers() if info.isfile()}
+ return source, sizes, lambda name: source.extractfile(name).read()
+
+
+def verify_archive(archive, resources, target):
+ """Raises Invalid unless the finished archive holds the tools at resources,
+ its folder of the app's resources/ (for example Linger/resources/)."""
+ source, sizes, read = _archive_members(archive)
+ with source:
+ name = f"{resources}cli/computer-tools/manifest.json"
+ if name not in sizes:
+ raise Invalid(f"{os.path.basename(archive)} has no {name}")
+ manifest = json.loads(read(name))
+ if manifest.get("target") != target or not isinstance(manifest.get("assets"), list):
+ raise Invalid(f"{name} is not the Computer tool manifest for {target}")
+ for asset in manifest["assets"]:
+ member = f"{resources}cli/computer-tools/{asset['path']}"
+ if sizes.get(member) != asset["size_bytes"]:
+ raise Invalid(f"{os.path.basename(archive)} lacks {member} as listed")
+ node = resources + node_path(target).replace(os.sep, "/")
+ if not sizes.get(node):
+ raise Invalid(f"{os.path.basename(archive)} has no {node}")
+ return len(manifest["assets"])
+
+
+def check_archive(archive, resources, target):
+ """Exits unless the finished archive holds the tools; prints what it found."""
+ try:
+ count = verify_archive(archive, resources, target)
+ except Invalid as error:
+ sys.exit(f"Computer tools: {error}")
+ print(f"{os.path.basename(archive)}: Computer tools for {target} present ({count} files and Node.js)")
diff --git a/apps/desktop/packaging/computer_tools_test.py b/apps/desktop/packaging/computer_tools_test.py
new file mode 100644
index 00000000..45f4d755
--- /dev/null
+++ b/apps/desktop/packaging/computer_tools_test.py
@@ -0,0 +1,195 @@
+"""Checks of the Computer tools every desktop package must carry.
+
+ python3 -m unittest discover -s apps/desktop/packaging -p '*_test.py'
+"""
+import hashlib
+import importlib.util
+import io
+import json
+import os
+import shutil
+import subprocess
+import tarfile
+import tempfile
+import unittest
+import zipfile
+
+import computer_tools
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+MACHO = b"\xcf\xfa\xed\xfe" + b"\0" * 28
+PLAYWRIGHT_ENTRY = "node_modules/@playwright/mcp/cli.js"
+PI_EXTENSION = "extensions/pi-mcp.mjs"
+# The pins the shared validator holds the manifest to.
+FROZEN = json.loads(subprocess.check_output([
+ "node", "--input-type=module", "-e",
+ "import { COMPUTER_TOOL_VERSIONS as versions, CUA_ARCHIVES as cua } from "
+ + json.dumps("file://" + os.path.join(HERE, "..", "..", "..", "scripts", "computer-tool-bundle.mjs"))
+ + "; console.log(JSON.stringify({ versions, cua }))",
+]))
+
+
+def sha256(path):
+ with open(path, "rb") as source:
+ return hashlib.sha256(source.read()).hexdigest()
+
+
+def stage(root, target):
+ """A resources/ folder holding tools laid out as stage-computer-tools.mjs writes them."""
+ tools = os.path.join(root, "cli", "computer-tools")
+ files = {
+ PLAYWRIGHT_ENTRY: b"console.log('playwright')\n",
+ PI_EXTENSION: b"export default {}\n",
+ "node_modules/native/prebuilt.node": MACHO,
+ }
+ cua = FROZEN["cua"].get(target, {})
+ for relative in cua.get("required", []):
+ files[relative] = MACHO + relative.encode()
+ assets = []
+ for relative in sorted(files):
+ path = os.path.join(tools, *relative.split("/"))
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "wb") as out:
+ out.write(files[relative])
+ assets.append({"path": relative, "size_bytes": len(files[relative]),
+ "sha256": sha256(path), "mode": 0o644})
+ # JSON.stringify of the asset list, as bundle-computer-tools.mjs digests it.
+ digest = hashlib.sha256(json.dumps(assets, separators=(",", ":")).encode()).hexdigest()
+ manifest = {"schema_version": 1, "versions": FROZEN["versions"], "target": target,
+ "playwright_entry": PLAYWRIGHT_ENTRY, "pi_extension": PI_EXTENSION,
+ "cua_entry": cua.get("entry", ""), "packages": [],
+ "assets": assets, "artifact_sha256": digest}
+ with open(os.path.join(tools, "manifest.json"), "w") as out:
+ json.dump(manifest, out)
+ node = os.path.join(root, computer_tools.node_path(target))
+ os.makedirs(os.path.dirname(node))
+ with open(node, "wb") as out:
+ out.write(b"node")
+ os.chmod(node, 0o755)
+ return tools
+
+
+class ComputerToolsTest(unittest.TestCase):
+ def setUp(self):
+ self.root = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, self.root)
+
+ def resources(self, target="linux-x64"):
+ resources = os.path.join(self.root, target, "resources")
+ return resources, stage(resources, target)
+
+ def test_accepts_the_staged_tools_of_every_shipped_target(self):
+ for target in ("darwin-arm64", "linux-x64", "win32-x64"):
+ resources, _ = self.resources(target)
+ computer_tools.verify(resources, target)
+
+ def test_rejects_resources_without_the_tools(self):
+ resources = os.path.join(self.root, "resources")
+ os.makedirs(os.path.join(resources, "computer"))
+ with self.assertRaisesRegex(computer_tools.Invalid, "manifest.json"):
+ computer_tools.verify(resources, "linux-x64")
+ with self.assertRaises(SystemExit):
+ computer_tools.check(resources, "linux-x64")
+
+ def test_rejects_changed_unlisted_or_missing_files(self):
+ resources, tools = self.resources()
+ with open(os.path.join(tools, PI_EXTENSION), "ab") as out:
+ out.write(b"//")
+ with self.assertRaisesRegex(computer_tools.Invalid, "do not match their manifest"):
+ computer_tools.verify(resources, "linux-x64")
+
+ resources, tools = self.resources("win32-x64")
+ with open(os.path.join(tools, "extra.js"), "w") as out:
+ out.write("1")
+ with self.assertRaisesRegex(computer_tools.Invalid, "do not match their manifest"):
+ computer_tools.verify(resources, "win32-x64")
+
+ resources, _ = self.resources("darwin-arm64")
+ os.remove(os.path.join(resources, "runtime", "bin", "node"))
+ with self.assertRaisesRegex(computer_tools.Invalid, "missing or not executable"):
+ computer_tools.verify(resources, "darwin-arm64")
+
+ def test_rejects_tools_for_another_target(self):
+ resources, _ = self.resources("darwin-arm64")
+ with self.assertRaisesRegex(computer_tools.Invalid, "Invalid Computer tool manifest"):
+ computer_tools.verify(resources, "darwin-x64")
+
+ def test_copy_places_the_staged_tools_next_to_the_daemon_folder(self):
+ staged = os.path.join(self.root, "dist", "computer-tools")
+ stage(os.path.join(staged, "linux-x64"), "linux-x64")
+ resources = os.path.join(self.root, "app", "resources")
+ os.makedirs(resources)
+ computer_tools.copy(resources, "linux-x64", staged=staged)
+ computer_tools.verify(resources, "linux-x64")
+ with self.assertRaises(SystemExit):
+ computer_tools.copy(resources, "win32-x64", staged=staged)
+
+ def test_refresh_records_only_resigned_macho_files(self):
+ resources, tools = self.resources("darwin-arm64")
+ for relative in ("node_modules/native/prebuilt.node", "cua/cua-driver"):
+ with open(os.path.join(tools, relative), "ab") as out:
+ out.write(b"signature")
+ computer_tools.refresh_signed(resources, kept=["cua/cua-driver"])
+ # The vendor-signed driver must come back unchanged.
+ with self.assertRaisesRegex(computer_tools.Invalid, "do not match their manifest"):
+ computer_tools.verify(resources, "darwin-arm64")
+
+ resources, tools = self.resources("linux-x64")
+ with open(os.path.join(tools, "node_modules/native/prebuilt.node"), "ab") as out:
+ out.write(b"signature")
+ computer_tools.refresh_signed(resources)
+ computer_tools.verify(resources, "linux-x64")
+ with open(os.path.join(tools, PLAYWRIGHT_ENTRY), "ab") as out:
+ out.write(b"//")
+ computer_tools.refresh_signed(resources)
+ with self.assertRaisesRegex(computer_tools.Invalid, "do not match their manifest"):
+ computer_tools.verify(resources, "linux-x64")
+
+ def test_finished_archives_must_hold_the_tools(self):
+ resources, _ = self.resources("linux-x64")
+ app = os.path.dirname(resources)
+ archive = os.path.join(self.root, "Linger.tar.gz")
+ with tarfile.open(archive, "w:gz") as out:
+ out.add(app, arcname="Linger")
+ self.assertEqual(computer_tools.verify_archive(archive, "Linger/resources/", "linux-x64"), 3)
+
+ resources, _ = self.resources("win32-x64")
+ archive = os.path.join(self.root, "Linger.zip")
+ with zipfile.ZipFile(archive, "w") as out:
+ for root, _, files in os.walk(resources):
+ for name in files:
+ path = os.path.join(root, name)
+ out.write(path, "Linger/resources/" + os.path.relpath(path, resources))
+ self.assertEqual(computer_tools.verify_archive(archive, "Linger/resources/", "win32-x64"), 4)
+
+ bare = os.path.join(self.root, "bare.tar.gz")
+ with tarfile.open(bare, "w:gz") as out:
+ info = tarfile.TarInfo("Linger/resources/computer/linger-computer-daemon")
+ info.size = 4
+ out.addfile(info, io.BytesIO(b"bin\n"))
+ with self.assertRaisesRegex(computer_tools.Invalid, "has no Linger/resources/cli"):
+ computer_tools.verify_archive(bare, "Linger/resources/", "linux-x64")
+ with self.assertRaises(SystemExit):
+ computer_tools.check_archive(bare, "Linger/resources/", "linux-x64")
+
+
+class MacSigningTest(unittest.TestCase):
+ def setUp(self):
+ spec = importlib.util.spec_from_file_location("mac_package", os.path.join(HERE, "mac", "package.py"))
+ self.mac = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(self.mac)
+
+ def test_tools_node_gets_the_node_entitlements(self):
+ self.assertTrue(self.mac.bundled_node("Contents/Resources/runtime/bin/node"))
+ self.assertFalse(self.mac.bundled_node("Contents/Resources/computer/linger-computer-daemon"))
+
+ def test_cua_app_keeps_its_vendor_signature(self):
+ app = tempfile.mkdtemp()
+ self.addCleanup(shutil.rmtree, app)
+ args = self.mac.Signing("rcodesign").app_args(app)
+ self.assertIn("Contents/Resources/cli/computer-tools/cua/CuaDriver.app",
+ args[args.index("--exclude") + 1])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/apps/desktop/packaging/linux/package.py b/apps/desktop/packaging/linux/package.py
index fbe177f5..f9198ec2 100644
--- a/apps/desktop/packaging/linux/package.py
+++ b/apps/desktop/packaging/linux/package.py
@@ -9,7 +9,9 @@ daemon) and the official Electron zip for linux-x64.
The archive holds one folder, Linger-<version>-linux-x64/, with the
`linger` executable at the top; it runs from wherever it is unpacked. The Go
-daemon goes to resources/computer/. With a bundled source package, the
+daemon goes to resources/computer/ and the browser and computer-control tools
+it loads to resources/cli/ and resources/runtime/ (../computer_tools.py); the
+finished archive is checked for them. With a bundled source package, the
TeamHub binaries and the Native runtime build.mjs built from it must be there
and match their manifests and that package (../native_bundle.py). The
runtime and the bundled PostgreSQL need glibc 2.35 or newer (Ubuntu 22.04,
@@ -29,6 +31,7 @@ import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
DESKTOP = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, os.path.dirname(HERE))
+import computer_tools # noqa: E402
from native_bundle import check_runtime, check_teamhub # noqa: E402
TARGET = "linux-x64"
@@ -69,13 +72,14 @@ def stage_app(version, electron_version, root, cache):
app_dir = os.path.join(resources, "app")
shutil.copytree(os.path.join(DESKTOP, "dist"), os.path.join(app_dir, "dist"),
- ignore=shutil.ignore_patterns("*.map", "computer"), symlinks=True)
+ ignore=shutil.ignore_patterns("*.map", "computer", "computer-tools"), symlinks=True)
with open(os.path.join(app_dir, "package.json"), "w") as out:
json.dump({"name": "linger-desktop", "productName": "Linger", "version": version,
"type": "module", "main": "dist/main/index.mjs"}, out, indent=2)
computer = os.path.join(resources, "computer")
os.makedirs(computer)
shutil.copy2(DAEMON, computer)
+ computer_tools.copy(resources, TARGET)
shutil.copy2(os.path.join(DESKTOP, "resources", "icon.png"), resources)
os.rename(os.path.join(root, "electron"), os.path.join(root, "linger"))
@@ -117,6 +121,7 @@ def main():
output = os.path.join(args.out, f"{name}.tar.gz")
with tarfile.open(output, "w:gz") as archive:
archive.add(root, arcname=name, filter=owned_by_root)
+ computer_tools.check_archive(output, f"{name}/resources/", TARGET)
print(f"{output} {os.path.getsize(output)} sha256={sha256(output)}")
finally:
shutil.rmtree(workdir, ignore_errors=True)
diff --git a/apps/desktop/packaging/mac/package.py b/apps/desktop/packaging/mac/package.py
index 69d54fb1..95d4755d 100644
--- a/apps/desktop/packaging/mac/package.py
+++ b/apps/desktop/packaging/mac/package.py
@@ -20,7 +20,14 @@ app and the DMG and staples both tickets, so Gatekeeper opens the DMG
directly. Key and password files are only passed to rcodesign.
The Go daemon goes to Contents/Resources/computer/ and is signed with the
-app like every other Mach-O file. So are the Native services, Node.js and
+app like every other Mach-O file. The browser and computer-control tools it
+loads go to Contents/Resources/cli/ and runtime/ (../computer_tools.py); their
+Node.js gets node-entitlements.plist like the Native one, and their manifest
+records the signed bytes of the Mach-O files signing rewrote. Cua's driver
+keeps the Developer ID signature Cua shipped it with: CuaDriver.app is
+excluded from signing and the standalone cua-driver is put back after it, as
+macOS grants it Accessibility and Screen Recording by that identity. The
+signed app is checked for the tools. So are the Native services, Node.js and
TeamHub binaries build.mjs bundles for Apple silicon (dist/installer/native/,
checked by ../native_bundle.py): Node.js gets node-entitlements.plist for its
JIT and, as it keeps the hardened runtime of its release signature, for the
@@ -49,6 +56,7 @@ import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
DESKTOP = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, os.path.dirname(HERE))
+import computer_tools # noqa: E402
from native_bundle import check_runtime, check_teamhub, refresh # noqa: E402
BUNDLE_ID = "com.simplexai.linger.desktop.preview"
# Prompt text for the privacy permissions tasks need. Without
@@ -67,6 +75,13 @@ MINIMUM_MACOS = "14.0"
# from the network.
NATIVE_TARGETS = {"darwin-arm64"}
NATIVE = os.path.join("Contents", "Resources", "app", "dist", "installer", "native")
+RESOURCES = os.path.join("Contents", "Resources")
+TOOLS_NODE = "Contents/Resources/runtime/bin/node"
+CUA = "Contents/Resources/cli/computer-tools/cua"
+# Signed by Cua with its own entitlements; signing leaves the app bundle alone
+# and package.py puts the standalone driver back after it.
+CUA_APP = f"{CUA}/CuaDriver.app"
+CUA_VENDOR_SIGNED = ["cua/cua-driver"]
def run(*args, **kwargs):
@@ -155,7 +170,7 @@ def stage_app(arch, version, electron_version, workdir, cache):
target = f"darwin-{arch}"
def ignore(directory, names):
- ignored = set(shutil.ignore_patterns("*.map", "computer")(directory, names))
+ ignored = set(shutil.ignore_patterns("*.map", "computer", "computer-tools")(directory, names))
# The other arch's Native services.
if os.path.basename(directory) == "native":
ignored |= {name for name in names if name.startswith(("runtime-", "teamhub-"))
@@ -169,6 +184,7 @@ def stage_app(arch, version, electron_version, workdir, cache):
computer = os.path.join(resources, "computer")
os.makedirs(computer)
shutil.copy2(daemon_binary(arch), computer)
+ computer_tools.copy(resources, target)
write_icon(resources)
os.rename(os.path.join(contents, "MacOS", "Electron"), os.path.join(contents, "MacOS", "Linger"))
@@ -201,9 +217,10 @@ def daemon_binary(arch):
def bundled_node(path):
- """Whether the bundle-relative path is the Node.js of a Native runtime."""
+ """Whether the bundle-relative path is the Node.js of a Native runtime or
+ of the Computer tools."""
parts = path.split("/")
- return (path.startswith(NATIVE + "/") and len(parts) == 10
+ return path == TOOLS_NODE or (path.startswith(NATIVE + "/") and len(parts) == 10
and parts[6].startswith("runtime-") and parts[7:] == ["node", "bin", "node"])
@@ -264,7 +281,8 @@ class Signing:
scoped += ["--entitlements-xml-file", f"{path}:{entitlements}"]
check = ["--for-notarization"] if self.notary_key else []
depth = ["--shallow"] if shallow else []
- return [self.rcodesign, "sign", *self._identity(), *check, *depth, *scoped, app]
+ return [self.rcodesign, "sign", *self._identity(), *check, *depth, *scoped,
+ "--exclude", CUA_APP, app]
def dmg_args(self, dmg):
return [self.rcodesign, "sign", *self._identity(), dmg]
@@ -272,11 +290,19 @@ class Signing:
def sign_app(self, app, target):
run(*self.app_args(app))
# Signing rewrote the bundled Mach-O files; their manifests are
- # resources, which a shallow signature seals again.
+ # resources, which a shallow signature seals again. It signs no
+ # Mach-O file, so the vendor-signed driver put back stays as it is.
native = os.path.join(app, NATIVE)
if os.path.isdir(native):
refresh(native, target)
- run(*self.app_args(app, shallow=True))
+ resources = os.path.join(app, RESOURCES)
+ staged = os.path.join(computer_tools.STAGED, target, computer_tools.TOOLS)
+ for relative in CUA_VENDOR_SIGNED:
+ shutil.copy2(os.path.join(staged, relative),
+ os.path.join(resources, computer_tools.TOOLS, relative))
+ computer_tools.refresh_signed(resources, kept=CUA_VENDOR_SIGNED)
+ run(*self.app_args(app, shallow=True))
+ computer_tools.check(resources, target)
def sign_dmg(self, dmg):
# An ad-hoc DMG signature adds nothing; Gatekeeper needs a Developer ID.
@@ -356,6 +382,7 @@ def main():
signing.sign_app(app, f"darwin-{arch}")
# The stapled app carries its ticket into the DMG and the update.
signing.notarize(app)
+ computer_tools.check(os.path.join(app, RESOURCES), f"darwin-{arch}")
output = os.path.join(args.out, f"Linger-{version}-{arch}.dmg")
build_dmg(stage, workdir, output, f"Linger {version}")
signing.sign_dmg(output)
@@ -364,7 +391,9 @@ def main():
digest = hashlib.sha256(dmg.read()).hexdigest()
print(f"{output} {os.path.getsize(output)} sha256={digest}")
if args.update_archive:
- update_archive(app, os.path.join(args.out, f"Linger-{version}-{arch}.app.tar.gz"))
+ archive = os.path.join(args.out, f"Linger-{version}-{arch}.app.tar.gz")
+ update_archive(app, archive)
+ computer_tools.check_archive(archive, "Linger.app/Contents/Resources/", f"darwin-{arch}")
finally:
shutil.rmtree(workdir, ignore_errors=True)
diff --git a/apps/desktop/packaging/win/package.py b/apps/desktop/packaging/win/package.py
index 2b83fa07..3cbba05f 100644
--- a/apps/desktop/packaging/win/package.py
+++ b/apps/desktop/packaging/win/package.py
@@ -19,7 +19,9 @@ the first start. The desktop updater runs a newer setup program with
/S /relaunch: it stops Linger, replaces the installed version and starts it
again. The zip has no self-update.
-The Go daemon goes to resources/computer/. With a bundled source package, the
+The Go daemon goes to resources/computer/ and the browser and computer-control
+tools it loads to resources/cli/ and resources/runtime/ (../computer_tools.py);
+the finished zip is checked for them. With a bundled source package, the
TeamHub binaries and the Native runtime build.mjs built from it must be there
and match their manifests and that package (../native_bundle.py).
"""
@@ -37,6 +39,7 @@ import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
DESKTOP = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, os.path.dirname(HERE))
+import computer_tools # noqa: E402
from native_bundle import check_runtime, check_teamhub # noqa: E402
DAEMON = os.path.join(DESKTOP, "dist", "computer", "win32-x64", "linger-computer-daemon.exe")
@@ -92,13 +95,14 @@ def stage_app(version, electron_version, workdir, cache):
dist = os.path.join(DESKTOP, "dist")
app_dir = os.path.join(resources, "app")
shutil.copytree(dist, os.path.join(app_dir, "dist"),
- ignore=shutil.ignore_patterns("*.map", "computer"))
+ ignore=shutil.ignore_patterns("*.map", "computer", "computer-tools"))
with open(os.path.join(app_dir, "package.json"), "w") as out:
json.dump({"name": "linger-desktop", "productName": "Linger", "version": version,
"type": "module", "main": "dist/main/index.mjs"}, out, indent=2)
computer = os.path.join(resources, "computer")
os.makedirs(computer)
shutil.copy2(DAEMON, computer)
+ computer_tools.copy(resources, "win32-x64")
write_icon(os.path.join(resources, "linger.ico"))
os.rename(os.path.join(stage, "electron.exe"), os.path.join(stage, "Linger.exe"))
@@ -155,6 +159,7 @@ def main():
report(setup)
archive = os.path.join(args.out, f"Linger-{version}-x64.zip")
build_zip(stage, archive)
+ computer_tools.check_archive(archive, "Linger/resources/", "win32-x64")
report(archive)
finally:
shutil.rmtree(workdir, ignore_errors=True)
diff --git a/apps/desktop/scripts/stage-computer-tools.d.mts b/apps/desktop/scripts/stage-computer-tools.d.mts
new file mode 100644
index 00000000..917dbaff
--- /dev/null
+++ b/apps/desktop/scripts/stage-computer-tools.d.mts
@@ -0,0 +1,11 @@
+export function computerToolsDirectory(target: string, dist?: string): string;
+export function stageDesktopComputerTools(
+ targets: string[],
+ options?: {
+ dist?: string;
+ host?: string;
+ stage?: (bundle: string, target: string) => Promise<string[]>;
+ validate?: (bundle: string, target: string) => Promise<string[]>;
+ nodeReleases?: Readonly<Record<string, unknown>>;
+ },
+): Promise<void>;
diff --git a/apps/desktop/scripts/stage-computer-tools.mjs b/apps/desktop/scripts/stage-computer-tools.mjs
new file mode 100644
index 00000000..3dd78d69
--- /dev/null
+++ b/apps/desktop/scripts/stage-computer-tools.mjs
@@ -0,0 +1,73 @@
+// Stages the browser and computer-control tools the Go daemon loads, per
+// target, into dist/computer-tools/<target>/: cli/computer-tools/ with its
+// frozen manifest.json and runtime/bin/node, the pinned Node.js they run on.
+// scripts/computer-tool-bundle.mjs builds them with the same code and from the
+// same pins (Node.js and Cua archive checksums, the frozen pnpm lockfile) as
+// the Local Computer dependency package.
+//
+// The daemon looks for them two folders above its executable
+// (localtools.Installed): packaging puts them next to resources/computer/
+// (packaging/computer_tools.py). From source, dist/computer/ links to this
+// machine's tools, so `pnpm start` runs with them too.
+import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ NODE_RUNTIME_RELEASES,
+ stageComputerToolBundle,
+ validatedComputerToolBundle,
+} from "../../../scripts/computer-tool-bundle.mjs";
+
+const desktop = fileURLToPath(new URL("../", import.meta.url));
+
+export const computerToolsDirectory = (
+ target,
+ dist = path.join(desktop, "dist"),
+) => path.join(dist, "computer-tools", target);
+
+export const stageDesktopComputerTools = async (
+ targets,
+ {
+ dist = path.join(desktop, "dist"),
+ host = `${process.platform}-${process.arch}`,
+ stage = stageComputerToolBundle,
+ validate = validatedComputerToolBundle,
+ nodeReleases = NODE_RUNTIME_RELEASES,
+ } = {},
+) => {
+ // One target at a time: the darwin targets share one cached Cua archive.
+ for (const target of targets) {
+ const bundle = computerToolsDirectory(target, dist);
+ // A source build keeps tools that still match the frozen manifest and the
+ // pinned Node.js, recorded beside them, so `pnpm start` needs no download;
+ // release builds start from an empty dist/.
+ const node = JSON.stringify(nodeReleases[target] ?? null);
+ const pinned = `${bundle}.node.json`;
+ const kept =
+ (await readFile(pinned, "utf8").catch(() => null)) === node &&
+ (await validate(bundle, target).catch(() => null));
+ if (kept) {
+ console.log(`Computer tools for ${target}: ${kept.length} files, kept`);
+ continue;
+ }
+ await rm(pinned, { force: true });
+ await rm(bundle, { recursive: true, force: true });
+ await mkdir(bundle, { recursive: true });
+ const entries = await stage(bundle, target);
+ await writeFile(pinned, node);
+ console.log(`Computer tools for ${target}: ${entries.length} files`);
+ }
+ if (targets.includes(host)) {
+ const computer = path.join(dist, "computer");
+ await mkdir(computer, { recursive: true });
+ for (const name of ["cli", "runtime"]) {
+ await rm(path.join(computer, name), { recursive: true, force: true });
+ await symlink(
+ path.join(computerToolsDirectory(host, dist), name),
+ path.join(computer, name),
+ "junction",
+ );
+ }
+ }
+};
diff --git a/apps/desktop/src/main/stage-computer-tools.test.ts b/apps/desktop/src/main/stage-computer-tools.test.ts
new file mode 100644
index 00000000..b65f96a8
--- /dev/null
+++ b/apps/desktop/src/main/stage-computer-tools.test.ts
@@ -0,0 +1,119 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+import { afterEach, expect, it } from "vitest";
+
+import {
+ computerToolsDirectory,
+ stageDesktopComputerTools,
+} from "../../scripts/stage-computer-tools.mjs";
+
+const roots: string[] = [];
+afterEach(() => {
+ for (const root of roots.splice(0))
+ rmSync(root, { recursive: true, force: true });
+});
+
+const dist = () => {
+ const root = mkdtempSync(path.join(tmpdir(), "stage-computer-tools-"));
+ roots.push(root);
+ return root;
+};
+
+// Stands in for scripts/computer-tool-bundle.mjs: the staged bundle is valid
+// when it holds the target's manifest and Node.js.
+const staged: string[] = [];
+const stage = async (bundle: string, target: string) => {
+ staged.push(target);
+ mkdirSync(path.join(bundle, "cli/computer-tools"), { recursive: true });
+ mkdirSync(path.join(bundle, "runtime/bin"), { recursive: true });
+ writeFileSync(path.join(bundle, "cli/computer-tools/manifest.json"), target);
+ writeFileSync(path.join(bundle, "runtime/bin/node"), "node");
+ return ["cli/computer-tools/manifest.json"];
+};
+const validate = async (bundle: string, target: string) => {
+ if (
+ readFileSync(
+ path.join(bundle, "cli/computer-tools/manifest.json"),
+ "utf8",
+ ) !== target
+ )
+ throw new Error("Invalid Computer tool manifest");
+ return ["cli/computer-tools/manifest.json"];
+};
+
+it("stages each target's tools and links this machine's for the source daemon", async () => {
+ const root = dist();
+ staged.length = 0;
+ await stageDesktopComputerTools(["linux-x64", "linux-arm64"], {
+ dist: root,
+ host: "linux-x64",
+ stage,
+ validate,
+ });
+ expect(staged).toEqual(["linux-x64", "linux-arm64"]);
+ // dist/computer/<target>/linger-computer-daemon finds them two folders up.
+ expect(realpathSync(path.join(root, "computer/cli/computer-tools"))).toBe(
+ realpathSync(
+ path.join(
+ computerToolsDirectory("linux-x64", root),
+ "cli/computer-tools",
+ ),
+ ),
+ );
+ expect(existsSync(path.join(root, "computer/runtime/bin/node"))).toBe(true);
+});
+
+it("keeps tools that still validate and restages the others", async () => {
+ const root = dist();
+ await stageDesktopComputerTools(["linux-x64", "linux-arm64"], {
+ dist: root,
+ stage,
+ validate,
+ });
+ writeFileSync(
+ path.join(
+ computerToolsDirectory("linux-arm64", root),
+ "cli/computer-tools/manifest.json",
+ ),
+ "changed",
+ );
+ staged.length = 0;
+ await stageDesktopComputerTools(["linux-x64", "linux-arm64"], {
+ dist: root,
+ stage,
+ validate,
+ });
+ expect(staged).toEqual(["linux-arm64"]);
+
+ // A new Node.js pin restages the tools that run on it.
+ staged.length = 0;
+ await stageDesktopComputerTools(["linux-x64", "linux-arm64"], {
+ dist: root,
+ stage,
+ validate,
+ nodeReleases: { "linux-x64": { archive: "node-next.tar.xz" } },
+ });
+ expect(staged).toEqual(["linux-x64", "linux-arm64"]);
+});
+
+it("fails the build when staging fails", async () => {
+ await expect(
+ stageDesktopComputerTools(["linux-x64"], {
+ dist: dist(),
+ stage: async () => {
+ throw new Error("Computer tool assets do not match their manifest");
+ },
+ validate,
+ }),
+ ).rejects.toThrow("do not match their manifest");
+});
diff --git a/docs/desktop-release.md b/docs/desktop-release.md
index 329dd581..56371457 100644
--- a/docs/desktop-release.md
+++ b/docs/desktop-release.md
@@ -290,6 +290,37 @@ the setup page does not offer installing on this computer. `src/main/distributio
target's PostgreSQL and the localmodels release `scripts/installs/stack.sh`
pins.
+### Computer Tools
+
+The daemon offers Agents browser and computer-control tools only when it
+finds `cli/computer-tools/` (with its frozen `manifest.json`) and
+`runtime/bin/node` two folders above its executable
+(`localtools.Installed` in `apps/computer/local-daemon`). The app runs the
+daemon from `resources/computer/`, so every package carries them as
+`resources/cli/computer-tools/` and `resources/runtime/` (on macOS under
+`Contents/Resources/`). Without them the daemon still starts and logs
+`computer_tools.missing` in `computer-daemon.log`.
+
+`build.mjs` stages them for each daemon target into
+`dist/computer-tools/<target>/` (`scripts/stage-computer-tools.mjs`) with
+`scripts/computer-tool-bundle.mjs`, the code and pins of the Local Computer
+dependency package: the Node.js archive checksums in
+`scripts/local-computer-node-distributions.mjs`, the Cua driver checksums in
+`apps/computer/scripts/bundle-computer-tools.mjs` and the frozen pnpm
+lockfile. A source build keeps staged tools that still validate against the
+manifest and the Node.js pin recorded beside them, and links
+`dist/computer/cli` and `dist/computer/runtime` to this machine's tools; delete
+`dist/computer-tools/` to stage them again. `packaging/computer_tools.py`
+copies them into the app, checks them with the same validator and checks the
+finished `.tar.gz`, `.zip` or update archive for them; a package without them
+fails.
+On macOS the tools' Node.js is signed with `node-entitlements.plist`, and Cua's
+driver (`CuaDriver.app` and the standalone `cua-driver`) keeps Cua's own
+Developer ID signature, which macOS grants Accessibility and Screen Recording
+to. Compressed, they add about 66 MB to the Linux archive, 73 MB to the
+Windows zip, 46 MB to the Windows setup program and 115 MB to the macOS disk
+image, most of it Node.js and the universal Cua driver.
+
### Release
Each desktop target (`darwin-arm64`, `linux-x64`) gets its own distribution
diff --git a/scripts/computer-tool-bundle.d.mts b/scripts/computer-tool-bundle.d.mts
new file mode 100644
index 00000000..0775b958
--- /dev/null
+++ b/scripts/computer-tool-bundle.d.mts
@@ -0,0 +1,20 @@
+export const COMPUTER_TOOL_VERSIONS: Readonly<Record<string, string>>;
+export const CUA_ARCHIVES: Readonly<
+ Record<string, { readonly entry: string; readonly required: string[] }>
+>;
+export const NODE_RUNTIME_RELEASES: Readonly<
+ Record<string, { readonly archive: string; readonly sha256: string }>
+>;
+export function nodeRuntimeEntry(target: string): string;
+export function validatedComputerToolBundle(
+ bundle: string,
+ target: string,
+): Promise<string[]>;
+export function stageComputerToolBundle(
+ bundle: string,
+ target: string,
+): Promise<string[]>;
+export function recordSignedComputerTools(
+ bundle: string,
+ kept?: readonly string[],
+): Promise<void>;
diff --git a/scripts/computer-tool-bundle.mjs b/scripts/computer-tool-bundle.mjs
new file mode 100644
index 00000000..80f2256f
--- /dev/null
+++ b/scripts/computer-tool-bundle.mjs
@@ -0,0 +1,91 @@
+// The browser and computer-control tools of the Local Computer dependency
+// package, as the desktop app ships them too: under one bundle folder,
+// cli/computer-tools/ with its frozen manifest.json and runtime/bin/node, the
+// pinned Node.js they run on. apps/desktop stages them with
+// stageComputerToolBundle and its packaging (packaging/computer_tools.py)
+// checks them with this script:
+//
+// node scripts/computer-tool-bundle.mjs verify <bundle> <target>
+// node scripts/computer-tool-bundle.mjs record-signed <bundle> [<kept asset>...]
+import { createHash } from "node:crypto";
+import { readFile, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+
+import {
+ stageComputerTools,
+ validatedComputerToolAssets,
+} from "../apps/computer/scripts/bundle-computer-tools.mjs";
+import { stagePinnedNodeRuntime } from "./prepare-local-computer-release.mjs";
+
+export {
+ COMPUTER_TOOL_VERSIONS,
+ CUA_ARCHIVES,
+} from "../apps/computer/scripts/bundle-computer-tools.mjs";
+export { NODE_RUNTIME_RELEASES } from "./local-computer-node-distributions.mjs";
+
+const windows = (target) => target.startsWith("win32-");
+
+export const nodeRuntimeEntry = (target) =>
+ `runtime/bin/node${windows(target) ? ".exe" : ""}`;
+
+// The manifest's files and an executable Node.js; returns the files.
+export const validatedComputerToolBundle = async (bundle, target) => {
+ const entries = await validatedComputerToolAssets(bundle, target);
+ const node = await stat(path.join(bundle, nodeRuntimeEntry(target))).catch(
+ () => null,
+ );
+ if (!node?.isFile() || (!windows(target) && !(node.mode & 0o111)))
+ throw new Error(
+ `The Node.js runtime for ${target} is missing or not executable`,
+ );
+ return entries;
+};
+
+export const stageComputerToolBundle = async (bundle, target) => {
+ await stagePinnedNodeRuntime(bundle, target);
+ await stageComputerTools(bundle, { target });
+ return await validatedComputerToolBundle(bundle, target);
+};
+
+const MACHO = new Set(["cffaedfe", "cafebabe"]);
+const sha256 = (data) => createHash("sha256").update(data).digest("hex");
+
+// macOS code signing rewrites the tools' Mach-O files. This records their new
+// size and sha256; any other change still fails the validation that follows.
+// Kept assets were put back as their vendor signed them and must match as
+// before.
+export const recordSignedComputerTools = async (bundle, kept = []) => {
+ const root = path.join(bundle, "cli/computer-tools");
+ const file = path.join(root, "manifest.json");
+ const manifest = JSON.parse(await readFile(file, "utf8"));
+ for (const asset of manifest.assets) {
+ if (kept.includes(asset.path)) continue;
+ const data = await readFile(path.join(root, asset.path)).catch(() => null);
+ if (!data || !MACHO.has(data.subarray(0, 4).toString("hex"))) continue;
+ asset.size_bytes = data.length;
+ asset.sha256 = sha256(data);
+ }
+ manifest.artifact_sha256 = sha256(JSON.stringify(manifest.assets));
+ await writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`);
+};
+
+if (
+ process.argv[1] &&
+ pathToFileURL(process.argv[1]).href === import.meta.url
+) {
+ const [command, bundle, ...rest] = process.argv.slice(2);
+ try {
+ if (command === "verify" && bundle && rest.length === 1)
+ await validatedComputerToolBundle(bundle, rest[0]);
+ else if (command === "record-signed" && bundle)
+ await recordSignedComputerTools(bundle, rest);
+ else
+ throw new Error(
+ "usage: computer-tool-bundle.mjs verify <bundle> <target> | record-signed <bundle> [<kept asset>...]",
+ );
+ } catch (error) {
+ console.error(error.message);
+ process.exit(1);
+ }
+}
diff --git a/scripts/computer-tool-bundle.test.ts b/scripts/computer-tool-bundle.test.ts
new file mode 100644
index 00000000..4b9dc47a
--- /dev/null
+++ b/scripts/computer-tool-bundle.test.ts
@@ -0,0 +1,166 @@
+import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ chmod,
+ mkdir,
+ mkdtemp,
+ readFile,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ nodeRuntimeEntry,
+ recordSignedComputerTools,
+ validatedComputerToolBundle,
+} from "./computer-tool-bundle.mjs";
+
+const temporaryRoots: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ temporaryRoots
+ .splice(0)
+ .map((root) => rm(root, { force: true, recursive: true })),
+ );
+});
+
+const checksum = (content: Buffer) =>
+ createHash("sha256").update(content).digest("hex");
+const macho = (text: string) =>
+ Buffer.concat([Buffer.from("cffaedfe", "hex"), Buffer.from(text)]);
+
+// What stageComputerTools and stagePinnedNodeRuntime write, without the
+// packages and the downloads.
+async function stagedBundle(target: string) {
+ const bundle = await mkdtemp(path.join(os.tmpdir(), "computer-tool-bundle-"));
+ temporaryRoots.push(bundle);
+ const tools = path.join(bundle, "cli/computer-tools");
+ const files: Record<string, Buffer> = {
+ "extensions/pi-mcp.mjs": Buffer.from("export default {}\n"),
+ "node_modules/@playwright/mcp/cli.js": Buffer.from("console.log(1)\n"),
+ "node_modules/native/prebuilt.node": macho("native"),
+ };
+ if (target.startsWith("darwin-")) {
+ files["cua/CuaDriver.app/Contents/MacOS/cua-driver"] = macho("app");
+ files["cua/cua-driver"] = macho("driver");
+ }
+ const assets = [];
+ for (const name of Object.keys(files).sort()) {
+ await mkdir(path.dirname(path.join(tools, name)), { recursive: true });
+ await writeFile(path.join(tools, name), files[name]);
+ assets.push({
+ path: name,
+ size_bytes: files[name].length,
+ sha256: checksum(files[name]),
+ mode: 0o644,
+ });
+ }
+ await writeFile(
+ path.join(tools, "manifest.json"),
+ JSON.stringify({
+ schema_version: 1,
+ versions: { playwright: "0.0.83", pi: "1.2.0", cua: "0.35.4" },
+ target,
+ playwright_entry: "node_modules/@playwright/mcp/cli.js",
+ pi_extension: "extensions/pi-mcp.mjs",
+ cua_entry: target.startsWith("darwin-") ? "cua/cua-driver" : "",
+ packages: [],
+ assets,
+ artifact_sha256: checksum(Buffer.from(JSON.stringify(assets))),
+ }),
+ );
+ const node = path.join(bundle, nodeRuntimeEntry(target));
+ await mkdir(path.dirname(node), { recursive: true });
+ await writeFile(node, "node");
+ await chmod(node, 0o755);
+ return { bundle, tools };
+}
+
+describe("Computer tool bundle", () => {
+ it("accepts the staged tools with an executable Node.js", async () => {
+ const { bundle } = await stagedBundle("linux-x64");
+ expect(await validatedComputerToolBundle(bundle, "linux-x64")).toContain(
+ "cli/computer-tools/manifest.json",
+ );
+ });
+
+ it("rejects missing, changed or misplaced tools and a non-executable Node.js", async () => {
+ const empty = await mkdtemp(
+ path.join(os.tmpdir(), "computer-tool-bundle-"),
+ );
+ temporaryRoots.push(empty);
+ await expect(
+ validatedComputerToolBundle(empty, "linux-x64"),
+ ).rejects.toThrow();
+
+ const changed = await stagedBundle("linux-x64");
+ await writeFile(
+ path.join(changed.tools, "extensions/pi-mcp.mjs"),
+ "changed\n",
+ );
+ await expect(
+ validatedComputerToolBundle(changed.bundle, "linux-x64"),
+ ).rejects.toThrow("do not match their manifest");
+
+ const other = await stagedBundle("linux-x64");
+ await expect(
+ validatedComputerToolBundle(other.bundle, "linux-arm64"),
+ ).rejects.toThrow("Invalid Computer tool manifest");
+
+ const { bundle } = await stagedBundle("linux-x64");
+ await chmod(path.join(bundle, nodeRuntimeEntry("linux-x64")), 0o644);
+ await expect(
+ validatedComputerToolBundle(bundle, "linux-x64"),
+ ).rejects.toThrow("not executable");
+ });
+
+ it("records re-signed Mach-O files but keeps vendor-signed ones as they were", async () => {
+ const { bundle, tools } = await stagedBundle("darwin-arm64");
+ for (const name of ["node_modules/native/prebuilt.node", "cua/cua-driver"])
+ await writeFile(
+ path.join(tools, name),
+ Buffer.concat([await readFile(path.join(tools, name)), macho("sig")]),
+ );
+ await recordSignedComputerTools(bundle, ["cua/cua-driver"]);
+ await expect(
+ validatedComputerToolBundle(bundle, "darwin-arm64"),
+ ).rejects.toThrow("do not match their manifest");
+
+ await writeFile(path.join(tools, "cua/cua-driver"), macho("driver"));
+ await validatedComputerToolBundle(bundle, "darwin-arm64");
+
+ // Only Mach-O files: any other change still fails.
+ await writeFile(path.join(tools, "extensions/pi-mcp.mjs"), "changed\n");
+ await recordSignedComputerTools(bundle);
+ await expect(
+ validatedComputerToolBundle(bundle, "darwin-arm64"),
+ ).rejects.toThrow("do not match their manifest");
+ });
+
+ it("checks a bundle from the command line for the packaging scripts", async () => {
+ const script = path.join(import.meta.dirname, "computer-tool-bundle.mjs");
+ const { bundle } = await stagedBundle("linux-x64");
+ await promisify(execFile)(process.execPath, [
+ script,
+ "verify",
+ bundle,
+ "linux-x64",
+ ]);
+ await expect(
+ promisify(execFile)(process.execPath, [
+ script,
+ "verify",
+ bundle,
+ "win32-x64",
+ ]),
+ ).rejects.toMatchObject({
+ stderr: expect.stringContaining("Invalid Computer tool manifest"),
+ });
+ });
+});
diff --git a/scripts/prepare-local-computer-release.mjs b/scripts/prepare-local-computer-release.mjs
index a2e018b2..541a6980 100644
--- a/scripts/prepare-local-computer-release.mjs
+++ b/scripts/prepare-local-computer-release.mjs
@@ -373,7 +373,8 @@ const buildBundle = async (outputDirectory) => {
);
};
-const stagePinnedNodeRuntime = async (bundle, target) => {
+// The desktop app stages the same runtime (scripts/computer-tool-bundle.mjs).
+export const stagePinnedNodeRuntime = async (bundle, target) => {
const release = NODE_RUNTIME_RELEASES[target];
if (!release) {
throw new Error(`Missing pinned Node runtime for ${target}.`);