👾 Open Computer Use – Open-Source Alternative to Codex Computer Use
Swift accessibilityai-agentai-agentsclaude-codecodexcodex-computer-usecomputer-usecomputer-use-agentcross-platformcuadesktop-automationgemini-cligui-automationmacosmcpmodel-context-protocolopen-computer-useopen-computer-use-mcpopenai-codexopencode
feat(cli): add JavaScript and REPL commands (#80)
Leo07610f09b0c1
diff --git a/Makefile b/Makefileindex 8dc979f..b07b4cc 100644--- a/Makefile+++ b/Makefile@@ -17,7 +17,7 @@ app:test:swift test- node --test scripts/node-repl/open-computer-use-repl.test.mjs+ node --test scripts/node-repl/*.test.mjssmoke:./scripts/run-tool-smoke-tests.shdiff --git a/README.md b/README.mdindex d9dff90..876c2a3 100644--- a/README.md+++ b/README.md@@ -135,6 +135,18 @@ open-computer-use call list_appsocu call list_appsopen-computer-use call get_app_state --args '{"app":"TextEdit"}'+# Inspect code-first runtime availability+ocu capabilities+ocu capabilities --json++# Run one JavaScript evaluation, from an argument, stdin, or a file+ocu js 'var apps = await cua.listApps({ emit: false }); nodeRepl.write(apps)'+printf '%s' 'nodeRepl.write(6 * 7)' | ocu js -+ocu js --file ./automation.mjs++# Keep JavaScript and cua bindings for the current terminal session+ocu repl+# Run a sequence in one process so element_index state can be reused# Sequence runs sleep 1s between successful operations by defaultopen-computer-use call --calls '[{"tool":"get_app_state","args":{"app":"TextEdit"}},{"tool":"press_key","args":{"app":"TextEdit","key":"Return"}}]'@@ -161,6 +173,18 @@ open-computer-use -hocu -h```+`ocu js` closes its JavaScript Worker and native MCP child after one+evaluation. `ocu repl` keeps them for the current terminal session until+`.exit`, Ctrl-D, or termination; `.reset` clears its bindings. On macOS, the+separate hidden `Open Computer Use.app` permission agent may remain resident so+later commands reuse the same permission identity. `ocu mcp` continues to expose+the native nine-tool compatibility surface.++The npm launcher itself currently requires Node.js 18 or newer. Its help always lists+`js` / `repl`, while `ocu capabilities --json` reports whether Node, the REPL+adapter/kernel, and the native runtime are available. Once started, it reuses+the current Node executable instead of looking up another `node` on PATH.+## Cursor MotionCursor Motion is an open-source cursor motion system for macOS, based on public information shared by members of the Software.Inc team. You can download the app from the [Releases page](https://github.com/iFurySt/open-codex-computer-use/releases).diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 5807086..c425e55 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -27,7 +27,7 @@- `experiments/StandaloneCursor`新的独立 Swift cursor viewer,直接复用 `scripts/cursor-motion-re/official_cursor_motion.py` 里收敛出来的候选路径、score 与 raw spring timeline,用来观察更贴近 binary lift 的表现。- `scripts/`- 仓库级自动化命令,包括 smoke test、`.app` 打包入口、Windows `.exe` / Linux binary 构建入口、npm 分发脚本、`scripts/node-repl/` 的 JS REPL adapter,以及 `scripts/computer-use-cli/` 这个用于探测官方 bundled `computer-use` 的 Go helper。+ 仓库级自动化命令,包括 smoke test、`.app` 打包入口、Windows `.exe` / Linux binary 构建入口、npm 分发脚本、`scripts/node-repl/` 的 JS REPL adapter 与 npm CLI controller,以及 `scripts/computer-use-cli/` 这个用于探测官方 bundled `computer-use` 的 Go helper。- `skills/`面向 agent runtime 的可安装 skill。当前 `skills/open-computer-use/SKILL.md` 只作为轻量入口和目录,安装、MCP/CLI 使用、排障等细节拆到相邻 `references/` 文件里按需加载;`scripts/package-skill.sh` 负责校验并打包 `.zip` / `.skill` 制品。- `docs/`@@ -64,6 +64,8 @@- `ComputerUseService` 负责把 Computer Use tool 请求映射到本地能力,`ComputerUseToolDispatcher` 则把 9 个 tool 的参数解析与 service 方法分发收敛成 MCP server 和 `open-computer-use call` 共用的一层。- Codex plugin 的 `.mcp.json` 默认不再把这 9 个 tools 直接暴露给模型,而是启动 `scripts/node-repl/open-computer-use-repl.mjs`。adapter 以 child MCP client 连接同一个 native runtime,并只对外列出 `js` / `js_reset`;JavaScript 通过异步 app-bound API(`cua.getApp(...)`、`app.click(...)`、`app.getAXState()` 等)调用 native tools。- REPL 使用 Node.js 自带的 evaluator,因此保留 top-level `await` 和跨调用 lexical bindings;真正执行代码的 kernel 位于 Worker 中,超时会终止 Worker 并重建干净 session,避免 `while (true)` 挂死 MCP transport。+- npm launcher 还直接提供 `ocu js` 和 `ocu repl`:前者为一次性 Worker/native MCP session,后者在当前终端内保留同一个 session 和 binding;两者退出后都会关闭 Worker 与 native MCP child。`ocu capabilities [--json]` 在不启动 native MCP 的情况下报告 Node、adapter、kernel 和当前平台 native artifact 是否齐全。help 始终显示 code-first 命令并标记 availability,不按环境动态隐藏接口。+- npm bin 当前本身通过 `#!/usr/bin/env node` 启动,因此完全没有 Node 的 shell 无法进入 help/capability 检测;launcher 启动后会复用 `process.execPath`,不会再次从 PATH 解析 Node。若未来要求零 Node 前置,应把最外层入口替换成 native bootstrap 或随包分发 Node。- 这是增量迁移:`open-computer-use mcp` 仍是原生 9-tool compatibility surface,已有 CLI、其他 MCP host 和 smoke 不需要切换。- `list_apps` 通过 Spotlight metadata query 拉取标准 application 目录里的 app bundle,并读取 `kMDItemUseCount` / `kMDItemLastUsedDate_Ranking` 这类系统元数据;再与 `NSWorkspace` 的运行态 app 合并,输出“当前运行中 + 近 14 天用过”的视图。- `get_app_state` 优先走真实 AX / 窗口截图;真实 app 必须同时有未最小化的 `AXWindow` 和可匹配的 on-screen `CGWindow`。如果目标 app 只是隐藏或暂时没有 on-screen window,会先 best-effort unhide / activate / `open -b` / `AXRaise` 并短暂重试,以贴近官方 `computer-use` 会把 Lark / Electron 窗口拉回再采集的行为;恢复后仍无法匹配时返回官方风格的 `Apple event error -10005: cgWindowNotFound`,不再把 application 根节点或无截图窗口伪装成可操作状态。当目标是仓库内 fixture app 时,回退到 fixture 导出的合成状态。真实 AX tree 默认在 macOS、Linux、Windows 上最多渲染 1200 个节点、64 层深度;显式 `get_app_state` / `snapshot` 可通过 `max_tree_nodes` / `max_tree_depth` 覆盖预算,action tools 的刷新结果仍使用默认预算。snapshot 文本默认截断到 500 字符;显式 `get_app_state` / `snapshot` 可通过 `text_limit` 正整数或 `"max"` 覆盖,action tools 的刷新结果仍使用 500 字符默认值。对 Electron/WebView 这类深层 UI 会压缩空 `AXGroup` / `AXUnknown` wrapper、过滤 `AXScrollToVisible` 噪音和空字符串属性,避免 action-critical 的输入框被无语义容器挤出节点预算;但通用节点中的 `AXPress` / `AXConfirm` / `AXOpen` 子节点会形成文本摘要边界,避免多个可点击选项被合并成一个 container。这类动作节点如果 frame 有效、尺寸紧凑且不包含带 URL 的 `AXLink` 后代,会保留为带窗口相对 `Frame` 的 `button`,并用短文本后代作为按钮摘要,让 icon-only 和文字 Web 控件都能获得可区分的 `element_index`;包含带 URL 的 `AXLink` 后代时保留通用 wrapper 和链接子节点,避免导航链接被摘要吞掉。对原生 open panel / Finder column view 这类把内容放在 `AXContents` / `AXVisibleChildren` 里的控件,也会把可见文件项纳入元素树。@@ -143,7 +145,7 @@## 主要验证路径- 单元测试:`swift test`-- JS REPL contract:`node --test scripts/node-repl/open-computer-use-repl.test.mjs`+- JS REPL 与 CLI contract:`node --test scripts/node-repl/*.test.mjs`- standalone cursor 构建:`swift build --product StandaloneCursor`- cursor lab 构建:`swift build --product CursorMotion`- 端到端 smoke:`./scripts/run-tool-smoke-tests.sh`(标准 9-tool smoke + visual cursor idle smoke;脚本默认以 headless 模式启动内部 fixture,避免在用户桌面弹出测试窗口)diff --git a/docs/RELIABILITY.md b/docs/RELIABILITY.mdindex 11c34df..689cf56 100644--- a/docs/RELIABILITY.md+++ b/docs/RELIABILITY.md@@ -4,7 +4,7 @@- 构建:`swift build`- 单元测试:`swift test`-- JS REPL:`node --test scripts/node-repl/open-computer-use-repl.test.mjs`+- JS REPL 与 CLI:`node --test scripts/node-repl/*.test.mjs`- 端到端 smoke:`./scripts/run-tool-smoke-tests.sh`- macOS SkyLight 实机回归:`OPEN_COMPUTER_USE_RUN_SKY_CLICK_LIVE_TEST=1 swift test --filter SkyClickLiveTests`- Linux runtime:`(cd apps/OpenComputerUseLinux && go test ./...)`、`./scripts/build-open-computer-use-linux.sh --arch arm64`@@ -16,6 +16,8 @@- macOS 上必须给 `Open Computer Use.app` 授权 `Accessibility` 与 `Screen Recording`;终端本身不应该再是必需授权对象。- Codex plugin 的 code-first surface 需要可执行的 `node`。REPL adapter 会为 native MCP 保留独立 child lifecycle,JavaScript kernel 则放在 Worker 中;脚本超时会丢弃该 Worker 的全部 bindings,并由下一次调用使用新的 kernel。+- npm CLI 本身也由 Node 启动。`ocu js` 只在一次执行期间保留 Worker/native MCP child;`ocu repl` 在当前 terminal session 内保留它们;`ocu mcp` 则跟随 stdio connection。macOS 的隐藏 app agent 是独立的权限身份,可能在这些前台命令退出后继续驻留。+- `ocu --help` 始终展示 `js` / `repl`;`ocu capabilities --json` 可在不启动 native MCP 的情况下检查 Node、adapter、kernel 和 native artifact。当前 npm shebang 仍要求 shell 能从 PATH 启动 Node,所以“完全无 Node”必须在更外层用 native bootstrap 解决。- macOS `click_method=sky_click` 额外依赖 SkyLight / ApplicationServices 私有符号 `SLEventPostToPid`、`SLEventSetIntegerValueField`、`CGEventSetWindowLocation`、`SLPSPostEventRecordTo` 和 `GetProcessForPID`。运行时会动态探测并 fail closed,但 macOS 更新、签名方式或目标 app 输入策略变化仍可能让后台投递失效。受控实机回归除 DOM、前台 PID、鼠标和 z-order 外,还必须验证前台 AppKit active、key window、first responder 以及 resign/key-loss 计数。- smoke suite 依赖本地 GUI session,不能把它当成无头环境命令。- 普通 app 的 `get_app_state` 结果依赖 AX tree 和窗口截图,复杂 app 上输出会有差异;Electron/WebView app 的 AX tree 通常很深,当前会压缩空 wrapper 并放宽遍历深度,以优先保留可操作文本、按钮和输入框。@@ -30,6 +32,7 @@4. 如果只有 `sky_click` 失败,先重新执行 `get_app_state`,确认窗口仍为 on-screen、未隐藏/最小化且没有切换 Space;错误里出现 `missing SkyLight symbols` 时不要改用隐式 fallback,应按当前 macOS 版本重新验证私有 SPI。被遮挡的 Chromium 页面仍无效果时,再用受控页面区分 renderer 策略变化与坐标/window-local 映射问题。5. 如果只想验证仓库基线,直接跑 fixture + smoke,不要先在复杂第三方 app 上排查。6. 排查 Linux runtime 时,先确认目标命令是否由桌面用户运行,再用 `open-computer-use call list_apps` 和 `open-computer-use snapshot <app>` 区分 session/env 问题与 AT-SPI tree/action 问题。如果是 Codex MCP,重新执行 `open-computer-use install-codex-mcp` 后重启 Codex,确认配置仍是 `open-computer-use mcp`。+7. 排查 `ocu js` / `ocu repl` 时先执行 `ocu capabilities --json`。缺少 adapter、kernel 或 native artifact 时重新安装 npm 包;若 shell 报 `node: command not found`,说明 npm launcher 本身尚未启动,需要先安装 Node 或等待未来 native bootstrap 方案。## 后续补强方向diff --git a/docs/SECURITY.md b/docs/SECURITY.mdindex 361fc92..0a20dc4 100644--- a/docs/SECURITY.md+++ b/docs/SECURITY.md@@ -3,7 +3,7 @@## 当前实现边界- 对 MCP host 暴露的接口仍是本地 `stdio`;macOS CLI 与 `.app` app agent 之间会使用用户临时目录下的 Unix domain socket,socket 创建后会收紧为当前用户读写,且不对外监听 TCP/HTTP 端口。未设置 `OPEN_COMPUTER_USE_AGENT_SOCKET_NAMESPACE` 时继续使用历史 Socket;设置后仅以 namespace 摘要派生私有文件名,不把宿主目录或原始 namespace 写入 Socket 路径。-- Codex plugin 默认把一个本地 Node.js REPL 放在 native MCP 前面。`js` 是任意本地 JavaScript 执行能力,不是受限表达式语言:代码可按启动进程权限读取文件、环境、模块和网络。只应在 host 已经具备并允许 model-code execution 的信任边界内启用;不接受这条边界的 host 应继续直连 `open-computer-use mcp` 的离散 native tools。+- Codex plugin 默认把一个本地 Node.js REPL 放在 native MCP 前面,npm CLI 的 `ocu js` / `ocu repl` 也直接使用同一 runtime。`js` 是任意本地 JavaScript 执行能力,不是受限表达式语言:代码可按启动进程权限读取文件、环境、模块和网络。只应在 host 已经具备并允许 model-code execution 的信任边界内启用;不接受这条边界的 host 应继续直连 `open-computer-use mcp` 的离散 native tools。- REPL 里的 Computer Use 调用仍经过 native MCP,因此密码管理器 denylist、`OPEN_COMPUTER_USE_ALLOW_GLOBAL_POINTER_FALLBACKS` 等 native safety gate 不会被 JavaScript adapter 绕过。JS kernel 在 Worker 中运行,超时会终止整个 Worker 并清空 bindings。- 所有动作都必须显式带 `app` 参数;当前不会在后台自动扫描并控制任意 app。- macOS 真实 app 路径依赖 `Open Computer Use.app` 已获得 `Accessibility` 与 `Screen Recording` 权限;终端里的 CLI / Node launcher 会把 `mcp`、`doctor`、`call`、`snapshot` 和 `list-apps` 转发给由 LaunchServices 启动的本地 app agent,避免把权限要求落到 iTerm / Terminal 身上。diff --git a/docs/exec-plans/completed/20260922-ocu-js-repl-cli.md b/docs/exec-plans/completed/20260922-ocu-js-repl-cli.mdnew file mode 100644index 0000000..fe00396--- /dev/null+++ b/docs/exec-plans/completed/20260922-ocu-js-repl-cli.md@@ -0,0 +1,85 @@+# `ocu js` / `ocu repl` CLI++## 目标++让 npm 分发的 `open-computer-use` / `ocu` 在保留原生 9-tool MCP compatibility surface 的同时,正式提供一次性 `js` 执行和终端内持久 `repl`,并以稳定、可机器读取的 capability 诊断说明 Node、adapter 与 native runtime 是否可用。++## 范围++- 包含:+ - `ocu js '<code>'`、`ocu js -`、`ocu js --file <path>` 与 `--timeout`。+ - `ocu repl`,在当前终端会话内复用同一 JavaScript kernel 与 native MCP child。+ - `ocu capabilities` / `ocu capabilities --json`,以及 help 中稳定展示 `js` / `repl` 的可用状态。+ - 将 npm launcher 的命令分发逻辑移到可复用、可测试的 Node 模块。+ - npm staging、自动测试、CLI 实机验证和文档同步。+- 不包含:+ - 修改原生 `ocu mcp` 的 9-tool surface。+ - 把 `repl` 伪装成 MCP tool。+ - 本轮内置或下载一份独立 Node distribution。+ - 合入独立的 PR #79 修复。++## 背景++- 相关文档:+ - `docs/ARCHITECTURE.md`+ - `docs/references/js-repl.md`+ - `docs/RELIABILITY.md`+ - `docs/SECURITY.md`+- 相关代码路径:+ - `scripts/npm/build-packages.mjs`+ - `scripts/node-repl/open-computer-use-repl.mjs`+ - `scripts/node-repl/open-computer-use-kernel.mjs`+- 已知约束:+ - 当前 npm bin 使用 `#!/usr/bin/env node`,所以 PATH 完全缺少 Node 时,launcher 无法运行到 help 或 capability 检测阶段。+ - 已经运行起来的 launcher 应使用 `process.execPath` 对应的 Node,不应再次依赖 PATH 查找 `node`。+ - help 的命令面必须稳定;缺依赖时应显示 unavailable 与修复提示,而不是隐藏命令。+ - 不得在 commit 或 PR 中加入禁止的 Co-authored-by trailer。++## 风险++- 风险:`js` / `repl` 新增一层 native MCP child 与 Worker lifecycle,异常退出可能留下子进程。+ - 缓解方式:统一在 `finally`、stdin EOF 和 signal 路径关闭 Worker 与 native child,并增加集成测试。+- 风险:把 code-first 能力混入 `ocu mcp` 会破坏既有 host。+ - 缓解方式:launcher 只拦截 CLI 子命令;`mcp` 原样转发 native runtime。+- 风险:任意 JavaScript 具备启动进程用户的本地权限。+ - 缓解方式:延续现有安全文档与 native safety gate,并在 CLI help 中明确这一信任边界。+- 风险:动态隐藏命令会让 Agent 无法形成稳定调用策略。+ - 缓解方式:始终列出命令,以结构化 capability 状态表达可用性。++## 里程碑++1. 收敛生命周期、命令面和 capability contract。+2. 实现可测试 launcher、`js`、`repl` 与诊断。+3. 完成自动测试、npm 打包、Terminal 实测、文档与交付。++## 验证方式++- 命令:+ - `node --test scripts/node-repl/*.test.mjs`+ - `node ./scripts/npm/build-packages.mjs --skip-build`+ - `make check-docs`+ - `swift test`+ - `./scripts/run-tool-smoke-tests.sh`+- 手工检查:+ - `ocu --help` 稳定列出 `js` / `repl` 和当前状态。+ - `ocu capabilities --json` 返回 Node、adapter、native runtime 与两种 JS 模式的结构化状态。+ - positional、stdin、file 三种 `js` 输入都能执行,错误返回非零状态。+ - `repl` 连续输入保留 binding,`.reset` 清空,`.exit` / Ctrl-D 清理进程。+ - `ocu mcp` 的 `tools/list` 仍恰好为 9 个 native tools。+- 观测检查:+ - `js` 完成或失败后没有残留 adapter、Worker 或 native MCP child。+ - `repl` 只在当前 terminal session 内长驻。++## 进度记录++- [x] 确认进程生命周期与稳定 capability 展示策略。+- [x] 完成 CLI 模块、npm launcher 接入与 capability contract。+- [x] 完成测试、文档、history 与本机、Linux devbox 实机验证。+- [ ] 同步远端并交付 PR。++## 决策记录++- 2026-09-22:help 始终展示 `js` / `repl`,并新增 `capabilities` 状态;不根据 PATH 动态删除命令。+- 2026-09-22:`js` 是一次性 session,`repl` 在当前终端会话内持久,`mcp` 继续是 native 9-tool stdio server。+- 2026-09-22:当前 npm launcher 已依赖 Node,因此运行时直接复用 `process.execPath`。无 Node bootstrap 属于后续 native launcher / bundled Node 设计,不以不可靠的 PATH 探测伪装解决。+- 2026-09-22:最终验证覆盖 18 个 Node contract/integration tests、167 个 Swift tests、Linux/Windows Go tests、Linux Python tests、9-tool smoke、release 全平台构建、本机隔离 tgz 安装和 Linux x64 devbox 隔离安装。两端都验证了 help/capabilities、一次性 `js`、stdin、持久 binding、`.editor`、`.reset`、SIGTERM child cleanup 和原生 MCP 恰好 9 tools。完整 `scripts/ci.sh` 只被 `main` 已存在的 repository-hygiene 缺失文件阻断,其余子步骤均单独通过。diff --git a/docs/histories/2026-09/20260922-1739-add-ocu-js-repl-cli.md b/docs/histories/2026-09/20260922-1739-add-ocu-js-repl-cli.mdnew file mode 100644index 0000000..92587bf--- /dev/null+++ b/docs/histories/2026-09/20260922-1739-add-ocu-js-repl-cli.md@@ -0,0 +1,47 @@+## [2026-09-22 17:39] | Task: Add `ocu js` and `ocu repl`++### 🤖 Execution Context+* **Agent ID**: `TRAE CLI`+* **Base Model**: `GPT-5.4`+* **Runtime**: `local macOS repository workspace`++### 📥 User Query+> Add both direct `ocu js` and persistent `ocu repl` commands, clarify whether OCU stays resident, and expose code-first capability status without hiding commands when Node or another component is unavailable.++### 🛠 Changes Overview+**Scope:** npm launcher, JavaScript REPL CLI, capability diagnostics, tests, and user/developer documentation.++**Key Actions:**+- **Direct code execution**: Added positional, stdin, and file-backed `ocu js` execution with configurable timeout and optional JSON result output.+- **Terminal REPL**: Added `ocu repl` with persistent top-level bindings, `.help`, `.editor` / `.end`, `.reset`, `.exit`, piped line mode, and deterministic Worker/native child cleanup.+- **Capability contract**: Added human-readable and JSON `ocu capabilities` output for Node, adapter, kernel, native MCP, `js`, and `repl`; help keeps the commands visible and marks current availability.+- **Compatibility**: Kept `ocu mcp` as the existing native 9-tool stdio server and left the Codex plugin's separate `js` / `js_reset` MCP surface unchanged.+- **Launcher structure**: Reduced generated npm bin files to a small bootstrap and moved command behavior into a reusable, directly tested module.+- **Runtime boundary**: Documented that the npm launcher requires Node.js 18+, reuses its current Node executable, and is separate from the macOS app agent that may stay resident for permission identity reuse.++### 🧠 Design Intent (Why)+Stable command discovery is more useful to users and agents than silently removing commands based on environment state. The CLI therefore always documents `js` and `repl`, while a separate structured preflight reports exactly which runtime component is missing. One-shot and persistent modes reuse the same proven Worker/native MCP bridge, without widening or changing the native MCP protocol.++### 📁 Files Modified+- `scripts/node-repl/open-computer-use-cli.mjs`+- `scripts/node-repl/open-computer-use-cli.test.mjs`+- `scripts/npm/build-packages.mjs`+- `scripts/ci.sh`+- `Makefile`+- `README.md`+- `docs/references/js-repl.md`+- `docs/ARCHITECTURE.md`+- `docs/RELIABILITY.md`+- `docs/SECURITY.md`+- `skills/open-computer-use/SKILL.md`+- `skills/open-computer-use/references/usage.md`++### ✅ Validation+- `node --test scripts/node-repl/*.test.mjs` — 18/18 passed.+- npm staging launcher — help, JSON capabilities, positional/stdin `js`, piped persistent `repl`, `.reset`, and real `cua.listApps()` passed against the bundled macOS runtime.+- Raw `ocu mcp` JSON-RPC `tools/list` — still exactly 9 native tools.+- `swift test` — 167 tests, 0 failures, 1 opt-in live test skipped; 9-tool/cursor smoke passed.+- Linux/Windows Go tests, Linux Python tests, shell/Node syntax, docs, action pinning, DSH installer tests, and diff checks passed.+- Release build produced macOS universal, Linux arm64/amd64, and Windows arm64/amd64 artifacts. Isolated tgz installs passed on local macOS Node 22.22.1 and Linux x64 devbox Node 22.16.0, including capability detection, multiline REPL, native bridge, exact 9-tool compatibility, and SIGTERM child cleanup.+- A PATH restricted to `/usr/bin:/bin` on the local machine reproduces the documented npm bootstrap boundary: the shebang exits 127 with `env: node: No such file or directory` before CLI code can run.+- Full `scripts/ci.sh` remains blocked only by the existing repository-hygiene gate: the `main` checkout lacks `.editorconfig`, `.markdownlint.json`, and several expected `.github` templates/workflows. All later CI substeps were run separately and passed.diff --git a/docs/references/js-repl.md b/docs/references/js-repl.mdindex b7ac1f5..9760522 100644--- a/docs/references/js-repl.md+++ b/docs/references/js-repl.md@@ -72,6 +72,36 @@ REPL does not close applications or erase their UI state.model-facing surface is `js` plus `js_reset`.- `open-computer-use mcp` remains the native 9-tool compatibility surface forother MCP clients.+- The npm CLI also exposes the same runtime directly:++```sh+# One evaluation, then close the Worker and native MCP child.+ocu js 'var apps = await cua.listApps({ emit: false }); nodeRepl.write(apps)'++# Read one evaluation from stdin or a file.+printf '%s' 'nodeRepl.write(6 * 7)' | ocu js -+ocu js --file ./automation.mjs++# Keep bindings for multiple terminal inputs.+ocu repl+```++`ocu js` also accepts `--timeout <milliseconds>` and `--json`. The interactive+REPL supports `.help`, `.editor` / `.end`, `.reset`, and `.exit`; when stdin is+piped, each non-empty line is evaluated in the same persistent session. Use+`nodeRepl.write(value)` for explicit output.++Use `ocu capabilities` for a human-readable preflight or+`ocu capabilities --json` for a stable structured report. The commands remain+visible in `ocu --help` even if the adapter, kernel, or native runtime is+missing; the report marks them unavailable and execution fails with the missing+component and path.++The npm entrypoint itself currently has a `#!/usr/bin/env node` shebang. Once+the launcher is running, `js` and `repl` reuse `process.execPath` and do not+look up a second `node` on PATH. A shell with no Node executable cannot start+the npm command at all; supporting that case requires a future native bootstrap+or bundled Node distribution, not dynamic command hiding.- The adapter can be run directly for development:```sh@@ -89,3 +119,17 @@ apply their own password-manager denylist and explicit global-pointer gate.The native MCP compatibility surface remains available when arbitraryJavaScript is not an acceptable host boundary.++## Process lifecycle++| Entry | Lifetime | Persistent state |+| --- | --- | --- |+| `ocu js` | One evaluation | A Worker and native MCP child exist only for that invocation. |+| `ocu repl` | Current terminal session | JavaScript bindings and native snapshot state persist until `.reset`, `.exit`, Ctrl-D, or termination. |+| `ocu mcp` | Current stdio MCP connection | Native MCP state persists until stdin EOF or host termination. |+| Codex plugin adapter | Current plugin MCP connection | `js` bindings persist across tool calls until `js_reset` or connection shutdown. |++On macOS, these short-lived CLI layers proxy automation to the hidden+`Open Computer Use.app` permission agent. That app agent may remain resident so+future calls reuse the same permission identity; it is separate from the Node+Worker and native MCP child owned by `js` / `repl`.diff --git a/docs/releases/feature-release-notes.md b/docs/releases/feature-release-notes.mdindex 42cee7f..e0fa939 100644--- a/docs/releases/feature-release-notes.md+++ b/docs/releases/feature-release-notes.md@@ -4,6 +4,7 @@| 日期 | 功能域 | 用户价值 | 变更摘要 || --- | --- | --- | --- |+| 2026-09-22 | JS REPL CLI | 用户无需先配置 MCP host,也可以直接用 `ocu js` 执行一次性 Computer Use JavaScript,或用 `ocu repl` 在终端中复用持久 binding;Agent 还能先读取结构化 capability 状态。 | npm launcher 新增 positional/stdin/file 三种 `js` 输入、持久 terminal REPL、`capabilities [--json]` 和稳定 help availability;`ocu mcp` 仍保持原生 9-tool surface。 || 2026-09-21 | JS REPL Computer Use | Agent 可以用异步 JavaScript 绑定 app,并在一个 tool round trip 内完成 inspect、action、条件和最终验证,不必在多轮间搬运所有中间状态。 | Codex plugin 通过持久 Node.js Worker 和 app-bound `cua` API 暴露 `js` / `js_reset`;`open-computer-use mcp` 继续保留既有 9-tool compatibility surface。 || 2026-09-17 | DeepSeek Harness 集成 | DSH 用户可以用一条命令安装 Open Computer Use,并在写入配置前发现错误的可执行文件或不兼容的 MCP server。 | 新增 DSH MCP 兼容安装器、turn-boundary 光标清理 hook 和非破坏性 skill 安装;安装前校验 server identity 与非空工具目录但不锁死工具数量,显式安装在 MCP 启动失败时 fail loud,并明确该路径不注册 DSH 的 first-class computer-use provider。 || 2026-09-10 | macOS 拖拽修复 | 显式开启全局指针路径后,窗口移动、文本拖选与 Finder 拖放可收到启动真实拖拽所需的事件;默认路径的限制也会明确呈现。 | 发布 `0.3.5`:补齐拖拽位移、手势事件编号与 HID 投递时序,增加投递路径说明;同步升级 Go MCP SDK 到 `v1.4.1`。 |diff --git a/scripts/ci.sh b/scripts/ci.shindex 424b21a..76cb3e7 100755--- a/scripts/ci.sh+++ b/scripts/ci.sh@@ -17,7 +17,7 @@ while IFS= read -r file; donode --check "$file"done < <(find "${repo_root}/scripts" -type f -name '*.mjs' | sort)-node --test "${repo_root}/scripts/node-repl/open-computer-use-repl.test.mjs"+node --test "${repo_root}"/scripts/node-repl/*.test.mjs(cd "${repo_root}/apps/OpenComputerUseLinux"diff --git a/scripts/node-repl/open-computer-use-cli.mjs b/scripts/node-repl/open-computer-use-cli.mjsnew file mode 100644index 0000000..f1f1055--- /dev/null+++ b/scripts/node-repl/open-computer-use-cli.mjs@@ -0,0 +1,520 @@+import { spawn } from "node:child_process";+import { constants as fsConstants, accessSync, existsSync, readFileSync } from "node:fs";+import path from "node:path";+import process from "node:process";+import readline from "node:readline";+import { pathToFileURL } from "node:url";++const DEFAULT_TIMEOUT_MS = 30_000;+const MAX_TIMEOUT_MS = 300_000;++const installCommands = new Map([+ ["install-claude-mcp", "install-claude-mcp.sh"],+ ["install-clauce-mcp", "install-claude-mcp.sh"],+ ["install-gemini-mcp", "install-gemini-mcp.sh"],+ ["install-codex-mcp", "install-codex-mcp.sh"],+ ["install-opencode-mcp", "install-opencode-mcp.sh"],+ ["install-dsh-mcp", "install-dsh-mcp.sh"],+ ["install-codex-plugin", "install-codex-plugin.sh"],+]);++function asError(error) {+ return error instanceof Error ? error : new Error(String(error));+}++function canExecute(filePath, platform) {+ if (!existsSync(filePath)) return false;+ if (platform === "win32") return true;+ try {+ accessSync(filePath, fsConstants.X_OK);+ return true;+ } catch {+ return false;+ }+}++export function runtimePaths({ packageRoot, platformPackages, platform, arch }) {+ const platformKey = `${platform}-${arch}`;+ const target = platformPackages[platformKey];+ return {+ platformKey,+ supported: Boolean(target),+ nativePath: target ? path.join(packageRoot, ...target.executablePath) : undefined,+ adapterPath: path.join(packageRoot, "scripts", "node-repl", "open-computer-use-repl.mjs"),+ kernelPath: path.join(packageRoot, "scripts", "node-repl", "open-computer-use-kernel.mjs"),+ };+}++export function inspectCapabilities({+ packageRoot,+ platformPackages,+ platform = process.platform,+ arch = process.arch,+ execPath = process.execPath,+ nodeVersion = process.version,+}) {+ const paths = runtimePaths({ packageRoot, platformPackages, platform, arch });+ const nodeMajor = Number.parseInt(String(nodeVersion).replace(/^v/, "").split(".")[0], 10);+ const node = {+ available: Boolean(execPath && nodeVersion && Number.isInteger(nodeMajor) && nodeMajor >= 18),+ version: nodeVersion,+ executable: execPath,+ minimumVersion: "18.0.0",+ source: "launcher",+ bootstrapNote: "The npm launcher itself requires Node.js 18 or newer; a shell with no node on PATH cannot start this command.",+ };+ const adapter = { available: existsSync(paths.adapterPath), path: paths.adapterPath };+ const kernel = { available: existsSync(paths.kernelPath), path: paths.kernelPath };+ const native = {+ available: Boolean(paths.nativePath && canExecute(paths.nativePath, platform)),+ path: paths.nativePath ?? null,+ platform: paths.platformKey,+ supported: paths.supported,+ };+ const unavailableReasons = [];+ if (!node.available) unavailableReasons.push(`Node.js >= ${node.minimumVersion} is unavailable`);+ if (!adapter.available) unavailableReasons.push(`REPL adapter is missing at ${adapter.path}`);+ if (!kernel.available) unavailableReasons.push(`JavaScript kernel is missing at ${kernel.path}`);+ if (!native.supported) unavailableReasons.push(`platform ${paths.platformKey} is unsupported`);+ else if (!native.available) unavailableReasons.push(`native runtime is missing or not executable at ${native.path}`);+ const codeAvailable = unavailableReasons.length === 0;++ return {+ schemaVersion: 1,+ runtime: { node, adapter, kernel, native },+ capabilities: {+ nativeMcp: {+ available: native.available,+ lifecycle: "stdio-session",+ toolSurface: "9 native computer-use tools",+ },+ js: {+ available: codeAvailable,+ lifecycle: "one-shot",+ requires: ["node", "adapter", "kernel", "native"],+ unavailableReasons,+ },+ repl: {+ available: codeAvailable,+ lifecycle: "terminal-session",+ requires: ["node", "adapter", "kernel", "native"],+ unavailableReasons,+ },+ },+ };+}++function availabilityLabel(capabilities) {+ const js = capabilities.capabilities.js;+ return js.available ? "available" : `unavailable: ${js.unavailableReasons.join("; ")}`;+}++export function launcherHelp(capabilities) {+ const codeStatus = availabilityLabel(capabilities);+ return `Open Computer Use++Usage:+ open-computer-use [command] [options]+ ocu [command] [options]+ open-computer-use++Commands:+ mcp Start the native 9-tool stdio MCP server.+ js <code> Run JavaScript once with the asynchronous cua API.+ repl Start a persistent interactive JavaScript session.+ capabilities Report Node, adapter, native, js, and repl availability.+ doctor Print permission status and launch onboarding if needed on macOS.+ list-apps Print running or recently used apps.+ snapshot <app> Print the current accessibility snapshot for an app.+ call <tool> Call one tool, or run a JSON array of tool calls.+ turn-ended Notify the running MCP process that the host turn ended.+ install-claude-mcp Install the MCP server into ~/.claude.json for this project.+ install-gemini-mcp Install the MCP server into Gemini CLI config.+ install-codex-mcp Install the MCP server into ~/.codex/config.toml.+ install-opencode-mcp Install the MCP server into ~/.config/opencode.+ install-dsh-mcp Install the MCP server into a DeepSeek Harness profile.+ install-codex-plugin Install this npm package into the local Codex plugin cache.+ help [command] Show general or command-specific help.+ version Print the CLI version.++Global options:+ -h, --help Show help.+ -v, --version Show version.++Code-first status:+ js / repl ${codeStatus}++Notes:+ js creates one adapter/native session and exits after the evaluation.+ repl keeps one adapter/native session alive until .exit, Ctrl-D, or termination.+ The npm launcher requires Node.js 18 or newer to start; run 'ocu capabilities --json' for component details.+ 'ocu mcp' intentionally keeps the native 9-tool compatibility surface.+ Use 'open-computer-use help <command>' for command-specific help.`;+}++function jsHelp() {+ return `Usage:+ ocu js [--timeout <ms>] [--json] '<code>'+ ocu js [--timeout <ms>] [--json] -+ ocu js [--timeout <ms>] [--json] --file <path>++Runs one JavaScript evaluation with top-level await and the asynchronous cua API, then closes its Worker and native MCP child. Source passed as '-' is read from stdin. The timeout defaults to 30000 ms and is capped at 300000 ms.`;+}++function replHelp() {+ return `Usage:+ ocu repl [--timeout <ms>] [--json]++Starts a JavaScript session whose top-level bindings and cua app bindings persist until exit.++REPL commands:+ .help Show this help.+ .editor Enter multiline mode; finish the block with .end.+ .reset Discard all JavaScript bindings and start a fresh kernel.+ .exit Close the kernel and native MCP child.++Use nodeRepl.write(value) for explicit output. When stdin is not a TTY, each non-empty input line is evaluated in the same session; .editor / .end also works in piped input.`;+}++function capabilitiesHelp() {+ return `Usage:+ ocu capabilities [--json]++Reports whether the current package has a usable Node runtime, REPL adapter, JavaScript kernel, and native runtime. Commands remain visible in help even when a component is unavailable.`;+}++function installHelp(scriptName, usage) {+ return `Usage:+ ${usage}++This helper updates a local MCP or plugin config to run:+ open-computer-use mcp++Script:+ ${scriptName}`;+}++function parseTimeout(value) {+ const parsed = Number(value);+ if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`--timeout expects a positive integer, received: ${value ?? "<missing>"}`);+ return Math.min(parsed, MAX_TIMEOUT_MS);+}++export function parseJavaScriptArgs(argv, { replMode = false } = {}) {+ const options = { timeoutMs: DEFAULT_TIMEOUT_MS, json: false, filePath: undefined, sourceParts: [] };+ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ if (arg === "--timeout") {+ options.timeoutMs = parseTimeout(argv[index + 1]);+ index += 1;+ } else if (arg === "--file") {+ if (replMode) throw new Error("--file is only supported by 'ocu js'");+ if (!argv[index + 1]) throw new Error("--file expects a path");+ options.filePath = argv[index + 1];+ index += 1;+ } else if (arg === "--json") {+ options.json = true;+ } else if (arg === "-h" || arg === "--help") {+ options.help = true;+ } else if (arg === "--") {+ options.sourceParts.push(...argv.slice(index + 1));+ break;+ } else if (arg.startsWith("-") && arg !== "-") {+ throw new Error(`Unknown option: ${arg}`);+ } else {+ options.sourceParts.push(arg);+ }+ }+ if (options.filePath && options.sourceParts.length > 0) throw new Error("use exactly one JavaScript source: positional code, '-', or --file");+ if (replMode && options.sourceParts.length > 0) throw new Error("'ocu repl' does not accept positional JavaScript; enter code after it starts");+ return options;+}++async function readStream(stream) {+ let source = "";+ for await (const chunk of stream) source += chunk;+ return source;+}++function writeLine(stream, value = "") {+ stream.write(`${value}\n`);+}++export function renderCapabilityReport(report) {+ const status = value => value ? "available" : "unavailable";+ const reasons = report.capabilities.js.unavailableReasons;+ return [+ `Node.js: ${status(report.runtime.node.available)} (${report.runtime.node.version} at ${report.runtime.node.executable})`,+ `REPL adapter: ${status(report.runtime.adapter.available)} (${report.runtime.adapter.path})`,+ `JS kernel: ${status(report.runtime.kernel.available)} (${report.runtime.kernel.path})`,+ `Native MCP: ${status(report.runtime.native.available)} (${report.runtime.native.platform}${report.runtime.native.path ? ` at ${report.runtime.native.path}` : ""})`,+ `ocu js: ${status(report.capabilities.js.available)} (one-shot)`,+ `ocu repl: ${status(report.capabilities.repl.available)} (terminal-session)`,+ ...(reasons.length ? ["", "Unavailable because:", ...reasons.map(reason => `- ${reason}`)] : []),+ "",+ report.runtime.node.bootstrapNote,+ ].join("\n");+}++function assertCodeCapability(report) {+ if (report.capabilities.js.available) return;+ throw new Error(`JavaScript capability is unavailable:\n${report.capabilities.js.unavailableReasons.map(reason => `- ${reason}`).join("\n")}\n\nRun 'ocu capabilities --json' for details, then reinstall the package if files are missing.`);+}++async function loadReplRuntime(paths) {+ const adapter = await import(pathToFileURL(paths.adapterPath).href);+ return {+ JsonLinePeer: adapter.JsonLinePeer,+ WorkerJavaScriptSession: adapter.WorkerJavaScriptSession,+ };+}++async function openSession({ paths, env }) {+ const { JsonLinePeer, WorkerJavaScriptSession } = await loadReplRuntime(paths);+ const native = new JsonLinePeer({ command: paths.nativePath, args: ["mcp"], env });+ try {+ await native.initialize();+ const session = new WorkerJavaScriptSession({ native });+ let closing;+ return {+ native,+ session,+ async close() {+ if (!closing) {+ closing = session.close().finally(() => native.close());+ }+ await closing;+ },+ };+ } catch (error) {+ native.close();+ throw error;+ }+}++function installSessionSignalHandlers(runtime, onSignal) {+ let handling = false;+ const exitCodes = new Map([["SIGHUP", 129], ["SIGINT", 130], ["SIGTERM", 143]]);+ const handlers = new Map();+ for (const [signal, exitCode] of exitCodes) {+ const handler = () => {+ if (handling) return;+ handling = true;+ onSignal?.();+ void runtime.close().finally(() => process.exit(exitCode));+ };+ handlers.set(signal, handler);+ process.once(signal, handler);+ }+ return () => {+ for (const [signal, handler] of handlers) process.off(signal, handler);+ };+}++function printEvaluation(result, { json, output }) {+ if (json) {+ writeLine(output, JSON.stringify(result));+ return;+ }+ for (const item of result.content ?? []) {+ if (item.type === "text") writeLine(output, item.text);+ else if (item.type === "image") writeLine(output, `[image ${item.mimeType ?? "application/octet-stream"}, ${Buffer.byteLength(item.data ?? "", "base64")} bytes]`);+ }+}++async function runJavaScript({ options, paths, env, input, output }) {+ let source;+ if (options.filePath) source = readFileSync(options.filePath, "utf8");+ else if (options.sourceParts.length === 1 && options.sourceParts[0] === "-") source = await readStream(input);+ else source = options.sourceParts.join(" ");+ if (!source.trim()) throw new Error("'ocu js' expects JavaScript source, '-' for stdin, or --file <path>");++ const runtime = await openSession({ paths, env });+ const removeSignalHandlers = installSessionSignalHandlers(runtime);+ try {+ const result = await runtime.session.run(source, options.timeoutMs);+ printEvaluation(result, { json: options.json, output });+ return result.isError ? 1 : 0;+ } finally {+ removeSignalHandlers();+ await runtime.close();+ }+}++async function runInteractiveRepl({ options, paths, env, input, output, errorOutput }) {+ const runtime = await openSession({ paths, env });+ const terminal = Boolean(input.isTTY && output.isTTY);+ const lines = readline.createInterface({ input, output: terminal ? output : undefined, terminal, prompt: "ocu> " });+ const removeSignalHandlers = installSessionSignalHandlers(runtime, () => lines.close());+ let editorLines;+ if (terminal) {+ writeLine(output, "Open Computer Use JavaScript REPL. Use nodeRepl.write(value) for output; type .help for commands.");+ lines.prompt();+ }+ try {+ for await (const line of lines) {+ const source = line.trim();+ if (editorLines) {+ if (source === ".end") {+ const block = editorLines.join("\n");+ editorLines = undefined;+ if (block.trim()) {+ const result = await runtime.session.run(block, options.timeoutMs);+ printEvaluation(result, { json: options.json, output });+ }+ if (terminal) {+ lines.setPrompt("ocu> ");+ lines.prompt();+ }+ } else {+ editorLines.push(line);+ if (terminal) lines.prompt();+ }+ continue;+ }+ if (!source) {+ if (terminal) lines.prompt();+ continue;+ }+ if (source === ".exit") break;+ if (source === ".help") writeLine(output, replHelp());+ else if (source === ".editor") {+ editorLines = [];+ if (terminal) {+ writeLine(output, "Enter JavaScript. Finish with .end on its own line.");+ lines.setPrompt("... ");+ }+ } else if (source === ".reset") {+ await runtime.session.reset();+ printEvaluation({ content: [{ type: "text", text: "Open Computer Use JavaScript session reset" }], isError: false }, { json: options.json, output });+ } else {+ const result = await runtime.session.run(line, options.timeoutMs);+ printEvaluation(result, { json: options.json, output });+ }+ if (terminal) lines.prompt();+ }+ return 0;+ } catch (error) {+ writeLine(errorOutput, `open-computer-use repl: ${asError(error).message}`);+ return 1;+ } finally {+ removeSignalHandlers();+ lines.close();+ await runtime.close();+ }+}++function runChild(executable, executableArgs, { env, spawnFn = spawn }) {+ return new Promise((resolve, reject) => {+ const child = spawnFn(executable, executableArgs, { stdio: "inherit", windowsHide: false, env });+ const forward = signal => child.kill(signal);+ const signalHandlers = new Map();+ for (const signal of ["SIGINT", "SIGTERM"]) {+ const handler = () => forward(signal);+ signalHandlers.set(signal, handler);+ process.on(signal, handler);+ }+ const cleanup = () => {+ for (const [signal, handler] of signalHandlers) process.off(signal, handler);+ };+ child.on("error", error => { cleanup(); reject(error); });+ child.on("exit", (code, signal) => { cleanup(); resolve(signal ? 1 : (code ?? 0)); });+ });+}++function resolveNativeExecutable(report) {+ const native = report.runtime.native;+ if (!native.supported) throw new Error(`Unsupported platform ${native.platform}.`);+ if (!native.available) throw new Error(`Missing or non-executable bundled native runtime at ${native.path}.\n\nReinstall with:\n npm install -g open-computer-use`);+ return native.path;+}++function installerUsage(command) {+ const usages = {+ "install-dsh-mcp": "open-computer-use install-dsh-mcp [--profile <name>] [--command <path>] [--no-hook] [--no-skill]",+ "install-codex-plugin": "open-computer-use install-codex-plugin",+ "install-codex-mcp": "open-computer-use install-codex-mcp",+ "install-gemini-mcp": "open-computer-use install-gemini-mcp [--scope project|user]",+ "install-opencode-mcp": "open-computer-use install-opencode-mcp",+ "install-claude-mcp": "open-computer-use install-claude-mcp",+ "install-clauce-mcp": "open-computer-use install-claude-mcp",+ };+ return usages[command];+}++export async function main({+ packageRoot,+ platformPackages,+ argv = process.argv.slice(2),+ input = process.stdin,+ output = process.stdout,+ errorOutput = process.stderr,+ env = process.env,+ platform = process.platform,+ arch = process.arch,+ execPath = process.execPath,+ nodeVersion = process.version,+ spawnFn = spawn,+} = {}) {+ const command = argv[0] ?? "";+ const report = inspectCapabilities({ packageRoot, platformPackages, platform, arch, execPath, nodeVersion });+ const paths = runtimePaths({ packageRoot, platformPackages, platform, arch });+ try {+ if (command === "-h" || command === "--help" || (command === "help" && argv.length <= 1)) {+ writeLine(output, launcherHelp(report));+ return 0;+ }+ if (command === "help" && argv[1] === "js") {+ writeLine(output, jsHelp());+ return 0;+ }+ if (command === "help" && argv[1] === "repl") {+ writeLine(output, replHelp());+ return 0;+ }+ if (command === "help" && argv[1] === "capabilities") {+ writeLine(output, capabilitiesHelp());+ return 0;+ }+ if (command === "help" && installCommands.has(argv[1])) {+ writeLine(output, installHelp(installCommands.get(argv[1]), installerUsage(argv[1])));+ return 0;+ }+ if (command === "capabilities") {+ const extra = argv.slice(1);+ if (extra.includes("-h") || extra.includes("--help")) writeLine(output, capabilitiesHelp());+ else if (extra.length === 0) writeLine(output, renderCapabilityReport(report));+ else if (extra.length === 1 && extra[0] === "--json") writeLine(output, JSON.stringify(report, null, 2));+ else throw new Error(`Unknown capabilities option: ${extra.join(" ")}`);+ return 0;+ }+ if (command === "js") {+ const options = parseJavaScriptArgs(argv.slice(1));+ if (options.help) {+ writeLine(output, jsHelp());+ return 0;+ }+ assertCodeCapability(report);+ return await runJavaScript({ options, paths, env, input, output });+ }+ if (command === "repl") {+ const options = parseJavaScriptArgs(argv.slice(1), { replMode: true });+ if (options.help) {+ writeLine(output, replHelp());+ return 0;+ }+ assertCodeCapability(report);+ return await runInteractiveRepl({ options, paths, env, input, output, errorOutput });+ }+ if (installCommands.has(command)) {+ if (platform === "win32") throw new Error(`${command} currently requires a POSIX shell. Configure your MCP client with command "open-computer-use" and args ["mcp"] on Windows.`);+ const scriptPath = path.join(packageRoot, "scripts", installCommands.get(command));+ if (!existsSync(scriptPath)) throw new Error(`Missing installer helper at ${scriptPath}.`);+ return await runChild(scriptPath, argv.slice(1), { env, spawnFn });+ }+ return await runChild(resolveNativeExecutable(report), argv, { env, spawnFn });+ } catch (error) {+ writeLine(errorOutput, `open-computer-use: ${asError(error).message}`);+ return 1;+ }+}diff --git a/scripts/node-repl/open-computer-use-cli.test.mjs b/scripts/node-repl/open-computer-use-cli.test.mjsnew file mode 100644index 0000000..01259ca--- /dev/null+++ b/scripts/node-repl/open-computer-use-cli.test.mjs@@ -0,0 +1,193 @@+import assert from "node:assert/strict";+import { chmodSync, cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { PassThrough } from "node:stream";+import test from "node:test";+import { fileURLToPath } from "node:url";+import {+ inspectCapabilities,+ launcherHelp,+ main,+ parseJavaScriptArgs,+ renderCapabilityReport,+} from "./open-computer-use-cli.mjs";++const HERE = path.dirname(fileURLToPath(import.meta.url));++function captureStream() {+ const stream = new PassThrough();+ let value = "";+ stream.setEncoding("utf8");+ stream.on("data", chunk => { value += chunk; });+ return { stream, value: () => value };+}++function makePackage() {+ const packageRoot = mkdtempSync(path.join(os.tmpdir(), "ocu-cli-test-"));+ const scripts = path.join(packageRoot, "scripts", "node-repl");+ const nativePath = path.join(packageRoot, "dist", "fake-native");+ mkdirSync(scripts, { recursive: true });+ mkdirSync(path.dirname(nativePath), { recursive: true });+ for (const name of ["open-computer-use-repl.mjs", "open-computer-use-kernel.mjs"]) {+ cpSync(path.join(HERE, name), path.join(scripts, name));+ }+ writeFileSync(nativePath, `#!${process.execPath}+let buffer = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", chunk => {+ buffer += chunk;+ for (;;) {+ const newline = buffer.indexOf("\\n");+ if (newline < 0) break;+ const line = buffer.slice(0, newline).trim();+ buffer = buffer.slice(newline + 1);+ if (!line) continue;+ const request = JSON.parse(line);+ if (request.id === undefined) continue;+ let result = {};+ if (request.method === "initialize") result = { protocolVersion: "2025-06-18", capabilities: { tools: {} } };+ else if (request.method === "tools/call") result = { content: [{ type: "text", text: request.params.name }], isError: false };+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }) + "\\n");+ }+});+`, "utf8");+ chmodSync(nativePath, 0o755);+ const platformPackages = {+ [`${process.platform}-${process.arch}`]: { executablePath: ["dist", "fake-native"] },+ };+ return { packageRoot, platformPackages, nativePath, cleanup: () => rmSync(packageRoot, { recursive: true, force: true }) };+}++test("capability report keeps js and repl discoverable when components are missing", () => {+ const packageRoot = mkdtempSync(path.join(os.tmpdir(), "ocu-capability-test-"));+ try {+ const report = inspectCapabilities({+ packageRoot,+ platformPackages: { [`${process.platform}-${process.arch}`]: { executablePath: ["missing-native"] } },+ });+ assert.equal(report.runtime.node.available, true);+ assert.equal(report.capabilities.js.available, false);+ assert.equal(report.capabilities.repl.available, false);+ assert.match(report.capabilities.js.unavailableReasons.join("\n"), /adapter is missing/);+ assert.match(launcherHelp(report), /js <code>/);+ assert.match(launcherHelp(report), /repl/);+ assert.match(launcherHelp(report), /unavailable:/);+ assert.match(renderCapabilityReport(report), /ocu js:\s+unavailable/);+ } finally {+ rmSync(packageRoot, { recursive: true, force: true });+ }+});++test("parses positional, stdin, file, timeout, and JSON options", () => {+ assert.deepEqual(parseJavaScriptArgs(["--timeout", "60000", "--json", "nodeRepl.write(42)"]), {+ timeoutMs: 60_000,+ json: true,+ filePath: undefined,+ sourceParts: ["nodeRepl.write(42)"],+ });+ assert.equal(parseJavaScriptArgs(["--timeout", "900000", "-"]).timeoutMs, 300_000);+ assert.equal(parseJavaScriptArgs(["--file", "script.mjs"]).filePath, "script.mjs");+ assert.deepEqual(parseJavaScriptArgs(["--", "-1", "+", "2"]).sourceParts, ["-1", "+", "2"]);+ assert.throws(() => parseJavaScriptArgs(["--file", "script.mjs", "source"]), /exactly one/);+ assert.throws(() => parseJavaScriptArgs(["source"], { replMode: true }), /does not accept positional/);+});++test("main reports structured capabilities without starting native MCP", async () => {+ const fixture = makePackage();+ const output = captureStream();+ const errorOutput = captureStream();+ try {+ const code = await main({+ packageRoot: fixture.packageRoot,+ platformPackages: fixture.platformPackages,+ argv: ["capabilities", "--json"],+ output: output.stream,+ errorOutput: errorOutput.stream,+ });+ assert.equal(code, 0);+ assert.equal(errorOutput.value(), "");+ const report = JSON.parse(output.value());+ assert.equal(report.capabilities.js.available, true);+ assert.equal(report.capabilities.repl.available, true);+ assert.equal(report.runtime.native.path, fixture.nativePath);+ } finally {+ fixture.cleanup();+ }+});++test("ocu js executes positional, stdin, and file source", async t => {+ const fixture = makePackage();+ t.after(fixture.cleanup);+ const cases = [+ { argv: ["js", "nodeRepl.write(6 * 7)"], input: "", expected: "42\n" },+ { argv: ["js", "-"], input: "nodeRepl.write(await Promise.resolve('stdin'))", expected: "stdin\n" },+ ];+ const sourcePath = path.join(fixture.packageRoot, "source.mjs");+ writeFileSync(sourcePath, "nodeRepl.write('file')", "utf8");+ cases.push({ argv: ["js", "--file", sourcePath], input: "", expected: "file\n" });++ for (const entry of cases) {+ const input = new PassThrough();+ input.end(entry.input);+ const output = captureStream();+ const errorOutput = captureStream();+ const code = await main({+ packageRoot: fixture.packageRoot,+ platformPackages: fixture.platformPackages,+ argv: entry.argv,+ input,+ output: output.stream,+ errorOutput: errorOutput.stream,+ });+ assert.equal(code, 0, errorOutput.value());+ assert.equal(output.value(), entry.expected);+ }+});++test("ocu js returns a non-zero exit when evaluation times out", async t => {+ const fixture = makePackage();+ t.after(fixture.cleanup);+ const output = captureStream();+ const errorOutput = captureStream();+ const code = await main({+ packageRoot: fixture.packageRoot,+ platformPackages: fixture.platformPackages,+ argv: ["js", "--timeout", "100", "while (true) {}"],+ output: output.stream,+ errorOutput: errorOutput.stream,+ });+ assert.equal(code, 1);+ assert.match(output.value(), /timed out after 100 ms/);+});++test("ocu repl preserves bindings and reset discards them", async t => {+ const fixture = makePackage();+ t.after(fixture.cleanup);+ const input = new PassThrough();+ input.end([+ "var answer = 40; nodeRepl.write(answer)",+ "answer += 2; nodeRepl.write(answer)",+ ".editor",+ "var object = {",+ " value: answer,",+ "};",+ "nodeRepl.write(object.value)",+ ".end",+ ".reset",+ "nodeRepl.write(typeof answer)",+ ".exit",+ ].join("\n"));+ const output = captureStream();+ const errorOutput = captureStream();+ const code = await main({+ packageRoot: fixture.packageRoot,+ platformPackages: fixture.platformPackages,+ argv: ["repl"],+ input,+ output: output.stream,+ errorOutput: errorOutput.stream,+ });+ assert.equal(code, 0, errorOutput.value());+ assert.equal(output.value(), "40\n42\n42\nOpen Computer Use JavaScript session reset\nundefined\n");+});diff --git a/scripts/npm/build-packages.mjs b/scripts/npm/build-packages.mjsindex 79258a7..81d47e4 100644--- a/scripts/npm/build-packages.mjs+++ b/scripts/npm/build-packages.mjs@@ -213,170 +213,20 @@ function platformLaunchTable() {function renderLauncher() {return `#!/usr/bin/env node-const { spawn } = require("node:child_process");-const fs = require("node:fs");const path = require("node:path");+const { pathToFileURL } = require("node:url");const platformPackages = ${JSON.stringify(platformLaunchTable(), null, 2)};const packageRoot = path.resolve(__dirname, "..");-const args = process.argv.slice(2);-const command = args[0] || "";-const installCommands = new Map([- ["install-claude-mcp", "install-claude-mcp.sh"],- ["install-clauce-mcp", "install-claude-mcp.sh"],- ["install-gemini-mcp", "install-gemini-mcp.sh"],- ["install-codex-mcp", "install-codex-mcp.sh"],- ["install-opencode-mcp", "install-opencode-mcp.sh"],- ["install-dsh-mcp", "install-dsh-mcp.sh"],- ["install-codex-plugin", "install-codex-plugin.sh"],-]);--function printLauncherHelp() {- console.log(\`Open Computer Use--Usage:- open-computer-use [command] [options]- ocu [command] [options]- open-computer-use--Commands:- mcp Start the stdio MCP server.- doctor Print permission status and launch onboarding if needed on macOS.- list-apps Print running or recently used apps.- snapshot <app> Print the current accessibility snapshot for an app.- call <tool> Call one tool, or run a JSON array of tool calls.- turn-ended Notify the running MCP process that the host turn ended.- install-claude-mcp Install the MCP server into ~/.claude.json for this project.- install-gemini-mcp Install the MCP server into Gemini CLI config.- install-codex-mcp Install the MCP server into ~/.codex/config.toml.- install-opencode-mcp Install the MCP server into ~/.config/opencode.- install-dsh-mcp Install the MCP server into a DeepSeek Harness profile.- install-codex-plugin Install this npm package into the local Codex plugin cache.- help [command] Show general or command-specific help.- version Print the CLI version.--Global options:- -h, --help Show help.- -v, --version Show version.--Notes:- This npm package bundles native runtimes for supported platforms and selects the current os-arch at launch.- Use 'open-computer-use help <command>' for command-specific help.\`);-}--function printInstallHelp(scriptName, usage) {- console.log(\`Usage:- \${usage}--This helper updates a local MCP or plugin config to run:- open-computer-use mcp--Script:- \${scriptName}\`);-}--function fail(message) {- console.error(message);- process.exit(1);-}--function spawnAndExit(executable, executableArgs) {- const child = spawn(executable, executableArgs, {- stdio: "inherit",- windowsHide: false,- });-- child.on("error", (error) => {- fail(\`Failed to start \${executable}: \${error.message}\`);+const cliModule = pathToFileURL(path.join(packageRoot, "scripts", "node-repl", "open-computer-use-cli.mjs")).href;++import(cliModule)+ .then(({ main }) => main({ packageRoot, platformPackages }))+ .then(code => { process.exitCode = Number.isInteger(code) ? code : 1; })+ .catch(error => {+ console.error(\`open-computer-use: \${error instanceof Error ? error.message : String(error)}\`);+ process.exitCode = 1;});-- for (const signal of ["SIGINT", "SIGTERM"]) {- process.on(signal, () => {- child.kill(signal);- });- }-- child.on("exit", (code, signal) => {- if (signal) {- process.exit(1);- }- process.exit(code ?? 0);- });-}--function runInstallCommand(scriptName, scriptArgs) {- if (process.platform === "win32") {- fail(\`\${command} currently requires a POSIX shell. Configure your MCP client with command "open-computer-use" and args ["mcp"] on Windows.\`);- }-- const scriptPath = path.join(packageRoot, "scripts", scriptName);- if (!fs.existsSync(scriptPath)) {- fail(\`Missing installer helper at \${scriptPath}.\`);- }-- spawnAndExit(scriptPath, scriptArgs);-}--function resolveNativeExecutable() {- const platformKey = \`\${process.platform}-\${process.arch}\`;- const target = platformPackages[platformKey];- if (!target) {- const supported = Object.keys(platformPackages).sort().join(", ");- fail(\`Unsupported platform \${platformKey}. Supported platforms: \${supported}.\`);- }-- const executablePath = path.join(packageRoot, ...target.executablePath);- if (!fs.existsSync(executablePath)) {- fail(\`Missing bundled native runtime for \${platformKey} at \${executablePath}.--Reinstall with:- npm install -g open-computer-use\`);- }-- return executablePath;-}--if (command === "-h" || command === "--help" || (command === "help" && args.length <= 1)) {- printLauncherHelp();- process.exit(0);-}--if (command === "help" && args[1] === "install-dsh-mcp") {- printInstallHelp("install-dsh-mcp.sh", "open-computer-use install-dsh-mcp [--profile <name>] [--command <path>] [--no-hook] [--no-skill]");- process.exit(0);-}--if (command === "help" && args[1] === "install-codex-plugin") {- printInstallHelp("install-codex-plugin.sh", "open-computer-use install-codex-plugin");- process.exit(0);-}--if (command === "help" && args[1] === "install-codex-mcp") {- printInstallHelp("install-codex-mcp.sh", "open-computer-use install-codex-mcp");- process.exit(0);-}--if (command === "help" && args[1] === "install-gemini-mcp") {- printInstallHelp("install-gemini-mcp.sh", "open-computer-use install-gemini-mcp [--scope project|user]");- process.exit(0);-}--if (command === "help" && args[1] === "install-opencode-mcp") {- printInstallHelp("install-opencode-mcp.sh", "open-computer-use install-opencode-mcp");- process.exit(0);-}--if (command === "help" && (args[1] === "install-claude-mcp" || args[1] === "install-clauce-mcp")) {- printInstallHelp("install-claude-mcp.sh", "open-computer-use install-claude-mcp");- process.exit(0);-}--if (installCommands.has(command)) {- const scriptName = installCommands.get(command);- runInstallCommand(scriptName, args.slice(1));-} else {- spawnAndExit(resolveNativeExecutable(), args);-}`;}@@ -398,8 +248,8 @@ const lines = ["Native runtime will be selected from bundled artifacts for " + process.platform + "-" + process.arch + ".","","Next:",- "1. Run open-computer-use --version or ocu --version",- "2. Add the MCP config below to your host client",+ "1. Run open-computer-use --version or ocu capabilities",+ "2. Add the MCP config below to your host client, or use ocu js / ocu repl directly","3. On macOS, run open-computer-use doctor and grant Accessibility / Screen Recording if prompted","","MCP config:",@@ -461,6 +311,10 @@ ocu --versionopen-computer-use --helpopen-computer-use mcpocu mcp+ocu capabilities+ocu capabilities --json+ocu js 'nodeRepl.write(6 * 7)'+printf 'var answer = 40\nanswer += 2; nodeRepl.write(answer)\n.exit\n' | ocu replopen-computer-use call list_apps# macOS permission check and onboarding@@ -479,6 +333,9 @@ open-computer-use install-codex-plugin- Version: \`${version}\`- Supported npm platforms: \`darwin-arm64\`, \`darwin-x64\`, \`linux-arm64\`, \`linux-x64\`, \`win32-arm64\`, \`win32-x64\`+- \`ocu js\` creates a one-shot JavaScript/native session; \`ocu repl\` keeps one session for the current terminal and preserves bindings between evaluations.+- Both code-first commands use the Node executable that started the npm launcher. The npm launcher itself still requires Node.js 18 or newer to be available when the command starts.+- \`ocu mcp\` intentionally continues to expose the native 9-tool compatibility surface; the Codex plugin adapter exposes \`js\` / \`js_reset\` separately.- macOS still requires \`Accessibility\` and \`Screen Recording\` permissions.- Linux requires a signed-in desktop session with AT-SPI2 / D-Bus accessibility available for real app control.- Windows requires a signed-in desktop session for UI Automation access.@@ -515,6 +372,9 @@ function renderMetaPackageJson(packageName, version) {url: "https://github.com/iFurySt/open-codex-computer-use/issues",},keywords: packageKeywords(),+ engines: {+ node: ">=18",+ },preferGlobal: true,publishConfig: {access: "public",@@ -545,6 +405,7 @@ function renderMetaPackageJson(packageName, version) {"scripts/install-opencode-mcp.sh","scripts/install-dsh-mcp.sh","scripts/install-codex-plugin.sh",+ "scripts/node-repl/","scripts/postinstall.mjs","skills/open-computer-use/","README.md",@@ -562,6 +423,17 @@ function copyInstallerScripts(packageRoot) {cpSync(path.join(repoRoot, "scripts", "install-dsh-mcp.sh"), path.join(packageRoot, "scripts", "install-dsh-mcp.sh"));cpSync(path.join(repoRoot, "scripts", "install-codex-plugin.sh"), path.join(packageRoot, "scripts", "install-codex-plugin.sh"));cpSync(path.join(repoRoot, "skills", "open-computer-use"), path.join(packageRoot, "skills", "open-computer-use"), { recursive: true });+ mkdirSync(path.join(packageRoot, "scripts", "node-repl"), { recursive: true });+ for (const scriptName of [+ "open-computer-use-cli.mjs",+ "open-computer-use-repl.mjs",+ "open-computer-use-kernel.mjs",+ ]) {+ cpSync(+ path.join(repoRoot, "scripts", "node-repl", scriptName),+ path.join(packageRoot, "scripts", "node-repl", scriptName),+ );+ }cpSync(path.join(repoRoot, "scripts", "node-repl", "open-computer-use-repl.mjs"),path.join(packageRoot, "plugins", "open-computer-use", "scripts", "open-computer-use-repl.mjs")diff --git a/skills/open-computer-use/SKILL.md b/skills/open-computer-use/SKILL.mdindex 1120536..ace070b 100644--- a/skills/open-computer-use/SKILL.md+++ b/skills/open-computer-use/SKILL.md@@ -27,7 +27,8 @@ It supports the same core tool surface across macOS, Linux, and Windows:8. Prefer element-targeted actions using `element_index` from the latest `get_app_state` result.9. For multi-step CLI work, use `open-computer-use call --calls '<json-array>'` so one process can reuse the latest element index mapping.10. For agent runtimes that support local MCP servers, configure `open-computer-use mcp` or `ocu mcp` and call the exposed Computer Use tools directly. Read [references/usage.md](references/usage.md).-11. If communication, permission, or desktop-session access fails, read [references/troubleshooting.md](references/troubleshooting.md).+11. For direct code-first orchestration, run `ocu capabilities` and then use one-shot `ocu js` or persistent `ocu repl`. Read [references/usage.md](references/usage.md).+12. If communication, permission, or desktop-session access fails, read [references/troubleshooting.md](references/troubleshooting.md).## Operating Rules@@ -44,6 +45,9 @@ It supports the same core tool surface across macOS, Linux, and Windows:```shopen-computer-use -hocu -h+ocu capabilities --json+ocu js 'nodeRepl.write(6 * 7)'+ocu replopen-computer-use doctoropen-computer-use call list_appsocu call list_appsdiff --git a/skills/open-computer-use/references/usage.md b/skills/open-computer-use/references/usage.mdindex 37a153e..5bff5f2 100644--- a/skills/open-computer-use/references/usage.md+++ b/skills/open-computer-use/references/usage.md@@ -54,6 +54,24 @@ await app.getAXState();Bindings persist across `js` calls until `js_reset`. See`docs/references/js-repl.md` for the full API and security boundary.+The npm CLI can use the same code-first runtime without an MCP host:++```sh+ocu capabilities+ocu js 'var apps = await cua.listApps({ emit: false }); nodeRepl.write(apps)'+printf '%s' 'nodeRepl.write(6 * 7)' | ocu js -+ocu js --file ./automation.mjs+ocu repl+```++`ocu js` owns one short-lived Worker/native MCP session. `ocu repl` keeps the+session and top-level bindings for the current terminal until `.exit`, Ctrl-D,+or termination; `.editor` / `.end` accepts multiline input and `.reset`+discards JavaScript bindings. Use `nodeRepl.write(value)` for explicit output.+The native `ocu mcp` surface remains the nine tools listed above. Run+`ocu capabilities --json` to inspect component availability instead of+inferring support from a command being present in help.+## Direct CLI Tool CallsUse `call` for one-off checks: