antigravity-hands 0.0.0-stage → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/README_ZH.md +100 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +121 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/driver/client.d.ts +19 -0
  9. package/dist/driver/client.js +169 -0
  10. package/dist/driver/client.js.map +1 -0
  11. package/dist/driver/downloader.d.ts +29 -0
  12. package/dist/driver/downloader.js +161 -0
  13. package/dist/driver/downloader.js.map +1 -0
  14. package/dist/driver/locator.d.ts +11 -0
  15. package/dist/driver/locator.js +108 -0
  16. package/dist/driver/locator.js.map +1 -0
  17. package/dist/engine/batch.d.ts +125 -0
  18. package/dist/engine/batch.js +910 -0
  19. package/dist/engine/batch.js.map +1 -0
  20. package/dist/engine/script.d.ts +47 -0
  21. package/dist/engine/script.js +403 -0
  22. package/dist/engine/script.js.map +1 -0
  23. package/dist/engine/snapshot.d.ts +23 -0
  24. package/dist/engine/snapshot.js +175 -0
  25. package/dist/engine/snapshot.js.map +1 -0
  26. package/dist/hooks/runner.d.ts +11 -0
  27. package/dist/hooks/runner.js +118 -0
  28. package/dist/hooks/runner.js.map +1 -0
  29. package/dist/installer/index.d.ts +21 -0
  30. package/dist/installer/index.js +170 -0
  31. package/dist/installer/index.js.map +1 -0
  32. package/dist/mcp/protocol.d.ts +38 -0
  33. package/dist/mcp/protocol.js +135 -0
  34. package/dist/mcp/protocol.js.map +1 -0
  35. package/dist/mcp/server.d.ts +19 -0
  36. package/dist/mcp/server.js +576 -0
  37. package/dist/mcp/server.js.map +1 -0
  38. package/dist/safety/policy.d.ts +26 -0
  39. package/dist/safety/policy.js +216 -0
  40. package/dist/safety/policy.js.map +1 -0
  41. package/dist/sidecar/server.d.ts +45 -0
  42. package/dist/sidecar/server.js +568 -0
  43. package/dist/sidecar/server.js.map +1 -0
  44. package/dist/sidecar/telemetry.d.ts +93 -0
  45. package/dist/sidecar/telemetry.js +257 -0
  46. package/dist/sidecar/telemetry.js.map +1 -0
  47. package/dist/sidecar/ui.html +1245 -0
  48. package/dist/types.d.ts +287 -0
  49. package/dist/types.js +21 -0
  50. package/dist/types.js.map +1 -0
  51. package/package.json +57 -4
  52. package/plugin/assets/logo.svg +15 -0
  53. package/plugin/hooks.json +11 -0
  54. package/plugin/mcp_config.json +8 -0
  55. package/plugin/plugin.json +18 -0
  56. package/plugin/rules/AGENTS.md +8 -0
  57. package/plugin/sidecars/hands_console/sidecar.json +21 -0
  58. package/plugin/skills/computer-use/SKILL.md +46 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ All notable changes to **Antigravity Hands** are documented here.
4
+
5
+ ## [0.6.2] - 2026-11-27
6
+ - **macOS Bilingual App Resolution (`Notes` ↔ `备忘录`, `Calculator` ↔ `计算器`, etc.)**: `list_windows`, `resolveWindow`, and `focus_app` now match `localizedName`, `.app` bundle filename, `bundleIdentifier`, and localized display names across `/Applications` and `/System/Applications` with a 2s startup poll — fixing `window_not_found` on localized macOS systems.
7
+ - **Batched macOS AX IPC (`AXUIElementCopyMultipleAttributeValues`)**: Replaced 14–15 per-node serial IPC calls with a single batched Mach IPC call plus lazy action/settable probing, dramatically accelerating `hands_observe` on large macOS apps like Notes, Finder, and Safari.
8
+ - **Proxy-Aware Prebuilt Driver Downloader**: Added automatic `curl -fsSL` fallback (honoring `HTTPS_PROXY` / `ALL_PROXY` / macOS system proxies) and `ANTIGRAVITY_HANDS_RELEASE_BASE_URL` mirror support with strict SHA-256 verification.
9
+
10
+ ## [0.6.1] - 2026-11-27
11
+ - **Automated npm Trusted Publishing (OIDC + Provenance)**: Added `publish-npm` job to `.github/workflows/release.yml` so every `v*` release automatically publishes prebuilt drivers to GitHub Releases first and then publishes the verified npm package with cryptographic provenance attestation.
12
+
13
+ ## [0.6.0] - 2026-11-27
14
+ - **Antigravity Desktop App Native Sidecar (`Hands Live Console`)**: Added native `sidecars/hands_console/sidecar.json` (`SIDECAR_UI_ENTRYPOINT_AUX_PANE`) and zero-dependency HTTP/SSE live console backend (`antigravity-hands sidecar`).
15
+ - **Real-Time Telemetry & One-Click Emergency Stop**: Added atomic cross-process `TelemetryStore` streaming live screenshots, Set-of-Marks captures, click target reticles, action timeline (`BG AX` / `UI` / `SCRIPT` / `OBSERVE` / `BLOCKED`), KPI metrics, and instant one-click Emergency Stop that signals active drivers (`SIGUSR1`) and halts in-flight `hands_script` / `hands_batch` loops.
16
+ - **Interactive Window Switcher & Diagnostics**: Inspect visible/minimized desktop windows, un-minimize/focus or capture SoM frames directly from the Aux Pane, and view real-time driver permissions & capabilities.
17
+ - **npm Packaging Hygiene**: Normalized `bin` (`dist/cli.js`) and `repository.url` (`git+https://...`) fields for zero-warning npm publishing.
18
+
19
+ ## [0.5.1] - 2026-11-27
20
+ - **Zero-Compile `npx` Distribution**: `npx -y antigravity-hands install` now downloads the platform-matched prebuilt native driver from GitHub Releases, strictly verifies it against `SHA256SUMS.txt`, and ad-hoc signs it on macOS.
21
+ - **Self-Contained Plugin Runtime**: Installer copies compiled runtime (`dist/`, `package.json`) and native binary (`bin/`) into `<pluginDir>/runtime/`, ensuring installed Antigravity plugins keep working permanently after ephemeral `npx` caches are cleaned.
22
+ - **macOS Intel (`x64`) Prebuilt Binary**: Release pipeline now builds and publishes all 4 prebuilt drivers (`macos-arm64`, `macos-x64`, `windows.exe`, `linux-x64`) with `SHA256SUMS.txt`.
23
+
24
+ ## [0.5.0] - 2026-11-27
25
+ - **macOS In-Memory `ScreenCaptureKit`**: Upgraded silent window capture & OCR from shelling out to `screencapture` temp PNG files to native macOS 14+ `SCScreenshotManager.captureImage` in-memory frames (with seamless `screencapture -l` fallback).
26
+ - **Compact `hands_script` Returns**: Added `obs.lines` (deduplicated text array) and `obs.items` (`{ref, role, label, value}`) to `hands.observe()` inside scripts, plus automatic nested-observe compaction and output length capping to prevent host temp-file spill (`output.txt`).
27
+ - **Open-Source Showcase**: Added live Set-of-Marks visual demo (`docs/media/som-demo.png`) and full v0.5.0 documentation.
28
+
29
+ ## [0.4.0] - 2026-11-27
30
+ - **Codex-Style Persistent JS Sandbox (`hands_script`)**: Added zero-dependency `node:vm` async JavaScript sandbox with `hands` API, cross-turn persistent `state`, FIFO serial execution queue, `max_ops` & timeout guardrails, and full safety/HUD/`Esc` enforcement.
31
+ - **Native High-Speed `repeat`**: Added native `repeat` + `delay_ms` bursting on `key` and `scroll` across macOS, Windows, and Linux with per-step `Esc` abort checks.
32
+ - **Fast Compact Outputs & JPEG Default**: Switched `hands_screenshot` default to compact JPEG (`max_width: 1024`) and single-line compact formatting for `marks`, `hands_batch`, and `hands_status`.
33
+
34
+ ## [0.3.0] - 2026-11-27
35
+ - **4-Step Smart macOS `focus_app`**: Added `unhide` → `activate` → `AXMinimized=false` + `AXRaise` → LaunchServices reopen/launch, returning fresh `window_id` and `bounds`.
36
+ - **Blank/Black Frame Guard**: Added `<0.2ms` 16×16 sampling check returning `window_not_visible` instead of passing black minimized frames to the model.
37
+ - **Lean 12-Tool Surface + Compact `hands_list_windows`**: Grouped `[VISIBLE]` & `[MINIMIZED / OTHER SPACE]` windows in one compact call (~85% smaller); shortened MCP namespace to `antigravity-hands_cua/*`.
38
+ - **Apple Silicon Codesign Fix**: Updated `build:macos` to unlink before copy + ad-hoc `codesign --force --sign -` to avoid kernel inode signature `SIGKILL`.
39
+
40
+ ## [0.2.0] - 2026-11-27
41
+ - **Hybrid `hands_observe` + Set-of-Marks (`annotate: true`)**: Added AX + native offline Chinese/English OCR fusion, numbered SoM badge rendering (`@m1..@mN`), and direct `ocr_text` clicks with destructive-action safety checks.
42
+ - **Full Windows & Linux Drivers**: Implemented Windows UIA tree + `WDA_EXCLUDEFROMCAPTURE` click-through HUD + `WH_KEYBOARD_LL` `Esc` hook, and Linux window/clipboard/screenshot/`tesseract` OCR support.
43
+ - **Live `<1ms` Stop Hook (`SIGUSR1`)**: Added PID registration and `SIGUSR1` signaling so Antigravity `Stop` hooks immediately hide HUDs and release modifier keys.
44
+
45
+ ## [0.1.0] - 2026-11-27
46
+ - Initial cross-platform TypeScript MCP Core, SafetyPolicyEngine, SnapshotStore, BatchEngine, macOS Swift driver, and native Antigravity plugin bundle.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Antigravity Hands Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ # Antigravity Hands
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Give Google Antigravity Codex-level hands and eyes across macOS, Windows, and Linux.**
4
+
5
+ English | [简体中文](./README_ZH.md) | [Changelog](./CHANGELOG.md)
6
+
7
+ `antigravity-hands` is an open-source, native **Computer Use plugin & MCP server** built specifically for **Google Antigravity** — working seamlessly across **Antigravity CLI (`agy`)**, **Antigravity Desktop App**, and **Antigravity IDE**.
8
+
9
+ It combines **accessibility-tree-first semantic control**, **a Codex `cua_repl`-inspired persistent JS sandbox (`hands_script`)**, **in-memory `ScreenCaptureKit` + native offline Chinese/English OCR**, **Set-of-Marks numbered screenshot grounding**, **lossless CJK/Unicode input**, **screenshot-invisible HUD glow**, and **instant `Esc` / mouse-takeover emergency stop**.
10
+
11
+ <p align="center">
12
+ <img src="https://raw.githubusercontent.com/ye4wzp/antigravity-hands/main/docs/media/som-demo.png" alt="Set-of-Marks numbered UI grounding on macOS Calculator (computed 7x8=56 in the background via AXPress)" width="260" />
13
+ <br />
14
+ <sub>Real macOS capture: <code>7 × 8 = 56</code> executed 100% in the background via <code>AXPress</code> (zero focus steal), followed by Set-of-Marks (<code>annotate: true</code>) numbered grounding with screenshot-invisible HUD.</sub>
15
+ </p>
16
+
17
+ ---
18
+
19
+ ## Why Antigravity Hands?
20
+
21
+ | Capability | Typical Screenshot MCP | Antigravity Hands (v0.6) |
22
+ | :--- | :--- | :--- |
23
+ | **Multi-Step Loops** | 1 LLM turn per click/scroll | **Codex-style `hands_script` JS sandbox** (`if`/`for`/`while`, persistent `state`) + native `repeat` bursting |
24
+ | **Element Targeting** | Fragile pixel coordinates | **Hybrid `hands_observe`** (AX/UIA tree `@e1` + auto native CJK/EN OCR `@m1`) + **Set-of-Marks** badges |
25
+ | **Capture Speed** | Slow CLI temp PNGs (1.5MB+) | **In-memory macOS `ScreenCaptureKit`** + compact JPEG + blank/black-frame guard |
26
+ | **Focus & Cursor** | Constantly hijacks your screen | **Background AX/UIA first**; 4-step smart un-minimize/reopen; automatic focus, cursor & clipboard restore |
27
+ | **Chinese / CJK / IME** | Garbled keys or broken IME | **Lossless clipboard paste** with automatic binary clipboard backup & restore |
28
+ | **Human-in-the-Loop UX** | Blind cursor movement | **Screenshot-invisible window glow HUD + click pulse**, **`Esc` stop**, mouse-takeover yield, `<1ms` `SIGUSR1` Stop hook |
29
+ | **Antigravity.app Native** | Manual JSON wiring | Full **Antigravity Plugin + Aux Pane Sidecar (`Hands Live Console`)** with live viewport, SoM preview, timeline & one-click Stop |
30
+
31
+ ---
32
+
33
+ ## Codex-Style `hands_script` Example
34
+
35
+ Instead of spending 10 LLM round-trips scrolling and guessing coordinates, Antigravity can drive an entire multi-step desktop workflow in **one `hands_script` call** (all guarded by password-field refusal, destructive-action blocking, HUD glow, and `Esc` abort):
36
+
37
+ ```js
38
+ await hands.focus("WPS Office");
39
+ await hands.doubleClick({ app: "WPS Office", ocr_text: "Quarterly_Deck.pptx" });
40
+ await hands.waitFor({ app: "WPS Office", ocr_text: "/38", timeout_ms: 8000 });
41
+ await hands.key("pagedown", { repeat: 29, delay_ms: 35 }); // native ~1s burst
42
+ await hands.wait(250);
43
+ const p30 = await hands.observe("WPS Office");
44
+ return { title: p30.window_title, lines: p30.lines.slice(0, 10) };
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Quick Start
50
+
51
+ ### One-Command Install (macOS / Windows / Linux)
52
+
53
+ Requires **Node.js 22+** — no Swift, .NET, or Rust toolchain needed. The installer automatically downloads the SHA-256-verified prebuilt native driver for your platform from GitHub Releases and installs a self-contained plugin into Antigravity (`agy` CLI, Desktop App, and IDE):
54
+
55
+ ```bash
56
+ npx -y antigravity-hands install
57
+ npx -y antigravity-hands doctor
58
+ ```
59
+
60
+ > Prefer a workspace-only install? Run `npx -y antigravity-hands install --workspace`.
61
+
62
+ ### Grant macOS System Permissions
63
+ Open **System Settings → Privacy & Security** and enable your host app (**Terminal / iTerm / Antigravity**):
64
+ 1. **Accessibility**
65
+ 2. **Screen & System Audio Recording**
66
+
67
+ Restart Antigravity / your terminal once after granting permissions, then try:
68
+
69
+ ```text
70
+ /antigravity-hands:computer-use Open Notes, create a note titled "Daily Plan", and add 3 items.
71
+ ```
72
+
73
+ Press **`Esc`** (or move your mouse sharply away) at any time to immediately halt automation and release all modifier keys.
74
+
75
+ ### Antigravity Desktop App Native Sidecar (`Hands Live Console`)
76
+ In **Antigravity Desktop App**, `antigravity-hands` ships with a built-in right-hand Aux Pane Sidecar (**Hands Live Console**) featuring:
77
+ - **Live Viewport & Set-of-Marks Preview** with pulsing click-target reticles streamed over SSE
78
+ - **Real-Time Action Timeline** showing Background AX (`BG AX`) vs Foreground (`UI`) vs `SCRIPT` vs `BLOCKED` events with per-step latency
79
+ - **Window Switcher** with one-click **Focus** (un-minimizes Dock windows) and **Snap SoM**
80
+ - **One-Click Emergency Stop / Resume** + live driver/permission health diagnostics
81
+
82
+ You can also launch the console standalone in any browser via `npx -y antigravity-hands sidecar --port 48120`.
83
+
84
+ ### Build from Source (Contributors)
85
+
86
+ ```bash
87
+ git clone https://github.com/ye4wzp/antigravity-hands.git
88
+ cd antigravity-hands
89
+
90
+ npm install
91
+ npm run build:all # Builds TypeScript core + signed macOS Swift driver
92
+ npm test # Runs unit, sandbox & MCP protocol tests
93
+ node dist/cli.js install
94
+ node dist/cli.js doctor
95
+ ```
96
+
97
+ ---
98
+
99
+ ## MCP Tools (13 High-Cohesion Tools)
100
+
101
+ | Tool | Purpose |
102
+ | :--- | :--- |
103
+ | `hands_script` | **Codex-style persistent async JS sandbox** for loops, conditionals, and multi-step workflows |
104
+ | `hands_observe` | Hybrid observer (`mode: "auto" \| "ax" \| "ocr" \| "both"`) merging `@e1` AX nodes + `@m1` offline OCR |
105
+ | `hands_screenshot` | Silent window capture (fast compact JPEG) with `annotate: true` Set-of-Marks numbered badges |
106
+ | `hands_list_windows` | Single-call compact `[VISIBLE]` + `[MINIMIZED / OTHER SPACE]` window listing |
107
+ | `hands_focus_app` | Smart 4-step wake (unhide → activate → un-minimize → reopen/launch) returning fresh `window_id` & `bounds` |
108
+ | `hands_click` | Click / double-click / right-click by `@ref`, semantic `{label, role}`, `ocr_text`, or `(x, y)` |
109
+ | `hands_type_text` | Lossless CJK/Unicode clipboard paste or background `AXSetValue` (blocks password fields) |
110
+ | `hands_key` | Single key or shortcut chord with native `repeat` & `delay_ms` bursting |
111
+ | `hands_scroll` / `hands_drag` | Scroll (with native `repeat`) and smooth mouse drag |
112
+ | `hands_wait_for` | Poll live AX tree or native OCR until target appears |
113
+ | `hands_batch` | Linear multi-step batching with auto HUD glow and optional `final_observe: true` |
114
+ | `hands_status` | Compact health, permissions, capabilities, and emergency-stop check/reset |
115
+
116
+ ---
117
+
118
+ ## Platform Support Matrix
119
+
120
+ | Platform | Driver | Status |
121
+ | :--- | :--- | :--- |
122
+ | **macOS** (Apple Silicon & Intel) | `drivers/macos` (Swift) | **v0.5 Complete** (In-memory `ScreenCaptureKit`, AX dedup + background `AXPress`/`AXSetValue`, Vision CJK OCR, SoM badges, lossless clipboard, smart un-minimize, blank-frame guard, native `repeat`, multi-monitor glow HUD + click pulse, `Esc`/mouse-yield, `SIGUSR1` Stop hook) |
123
+ | **Windows** (x64 & ARM64) | `drivers/windows` (C# .NET 8) | **v0.5 Feature-Complete + CI Ready** (UIA tree + background `Invoke`/`Value`, `PrintWindow` + SoM badges, WinRT OCR, `SendInput` + native `repeat` + lossless clipboard, `WDA_EXCLUDEFROMCAPTURE` glow HUD, `WH_KEYBOARD_LL` `Esc` hook) |
124
+ | **Linux** (X11 / Wayland) | `drivers/linux` (Rust) | **v0.5 Functional + CI Ready** (`wmctrl`/`xdotool` windows & native `repeat` input, lossless `xclip`/`wl-copy` clipboard, `import`/`scrot`/`grim` screenshots, `tesseract` CJK/EN OCR) |
125
+
126
+ ---
127
+
128
+ ## Documentation & Contributing
129
+
130
+ - [Architecture Guide](./docs/ARCHITECTURE.md)
131
+ - [Native Driver Protocol (v1.0)](./docs/DRIVER_PROTOCOL.md)
132
+ - [Contributing Guide](./CONTRIBUTING.md)
133
+
134
+ ## License
135
+
136
+ [MIT](./LICENSE)
package/README_ZH.md ADDED
@@ -0,0 +1,100 @@
1
+ # Antigravity Hands(反重力之手)
2
+
3
+ **为 Google Antigravity(反重力)打造的跨平台开源 Computer Use 插件与 MCP 服务,带来接近 Codex 的丝滑桌面操控体验。**
4
+
5
+ [English](./README.md) | 简体中文 | [更新日志](./CHANGELOG.md)
6
+
7
+ 一套标准插件同时原生适配 **Antigravity 全形态**(`agy` CLI、Antigravity Desktop App、Antigravity IDE)与 **三大桌面平台**(macOS / Windows / Linux)。
8
+
9
+ <p align="center">
10
+ <img src="https://raw.githubusercontent.com/ye4wzp/antigravity-hands/main/docs/media/som-demo.png" alt="macOS 计算器后台无抢焦操作与 Set-of-Marks 编号叠图实测效果" width="260" />
11
+ <br />
12
+ <sub>实机演示:系统「计算器」在后台通过 <code>AXPress</code> 无抢焦算完 <code>7 × 8 = 56</code>(鼠标纹丝不动),随后生成的 Set-of-Marks(<code>annotate: true</code>)编号叠图,且蓝色 HUD 光晕对截屏完全隐身。</sub>
13
+ </p>
14
+
15
+ ---
16
+
17
+ ## 核心特性(v0.6)
18
+
19
+ - **Antigravity.app 原生 Sidecar 实时控制台(`Hands Live Console`)**:在 Antigravity 桌面端右侧辅助面板(Aux Pane)直接打开离线零依赖的可视化控制台——实时 SSE 推送桌面画面与 Set-of-Marks 叠图、脉冲点击坐标指示器、每步耗时与后台占比时间线、窗口一键唤起/截图标注、以及**一键可视化急停(立即触发 `SIGUSR1` 隐藏 HUD 并中断正在运行的脚本循环)**。也可通过 `npx -y antigravity-hands sidecar --port 48120` 独立在浏览器打开。
20
+ - **类 Codex `cua_repl` 持久化 JS 沙盒(`hands_script`)**:内置零依赖 `node:vm` 受限异步沙盒,支持 `if/for/while`、跨轮持久化 `state`、FIFO 串行队列防竞态与 `max_ops` 保护;像「打开 WPS PPT → 连翻 30 页 → 读标题」一次脚本几秒跑完,不再一轮一轮盲试。
21
+ - **三层混合感知(专治微信 / WPS / 飞书 / Electron)**:
22
+ 1. 优先读系统无障碍树(`@e1..@eN`,不截屏、后台可读);
23
+ 2. 节点稀疏时自动触发**原生离线中英文 OCR**(macOS Apple Vision / Windows WinRT / Linux Tesseract),去重合并为可点击的 `@m1..@mN`;
24
+ 3. 视觉场景支持 **`hands_screenshot(annotate: true)` Set-of-Marks 编号叠图**,模型看号点击、零坐标换算。
25
+ - **macOS 原生 `ScreenCaptureKit` 内存零落盘取帧**:直接内存拿 `CGImage`(保留 `screencapture -l` 自动兜底),搭配 0.2ms 全黑帧拦截(`window_not_visible`)与默认高效 JPEG 输出,速度翻倍、杜绝临时文件刷屏。
26
+ - **四步智能唤起 & 原生高速连发**:`hands_focus_app` 完整支持 `unhide → activate → 取消 Dock 最小化 + AXRaise → 重开/启动主窗口` 并直接返回最新 `window_id`;`key`/`scroll` 原生支持 `repeat` 高速连发(每步校验 `Esc` 急停)。
27
+ - **中文无损输入 & Codex 级人机共存**:
28
+ - 中文/Emoji 走「备份原剪贴板 → 写入 → 粘贴 → 还原」,告别输入法串键乱码;
29
+ - 被控窗口自动亮起**截屏不可见的蓝色呼吸光晕 + 悬浮状态条 + 点击涟漪**;
30
+ - 随时按 **`Esc`** 或大幅移动鼠标即刻急停,Antigravity `Stop` 钩子通过 `SIGUSR1` 毫秒级隐藏 HUD 并释放修饰键;默认拦截密码框、密码管理器与中英文破坏性按钮(发送/删除/支付等)。
31
+
32
+ ---
33
+
34
+ ## `hands_script` 代码示例
35
+
36
+ ```js
37
+ await hands.focus("WPS Office");
38
+ await hands.doubleClick({ app: "WPS Office", ocr_text: "OPC社区讲解_子非鱼讲解版.pptx" });
39
+ await hands.waitFor({ app: "WPS Office", ocr_text: "/38", timeout_ms: 8000 });
40
+ await hands.key("pagedown", { repeat: 29, delay_ms: 35 }); // 原生约 1 秒连翻完
41
+ await hands.wait(250);
42
+ const p30 = await hands.observe("WPS Office");
43
+ return { title: p30.window_title, lines: p30.lines.slice(0, 10) };
44
+ ```
45
+
46
+ ---
47
+
48
+ ## 快速开始
49
+
50
+ ### 一键零编译安装(macOS / Windows / Linux)
51
+
52
+ 仅需 **Node.js 22+**,无需本地安装 Swift / .NET / Rust 编译器。安装器会自动从 GitHub Releases 下载并做 **SHA-256 校验**的对应平台原生驱动,并把完整自包含插件安装到 `~/.gemini/config/plugins/antigravity-hands`(一次覆盖 `agy` CLI / Desktop App / IDE):
53
+
54
+ ```bash
55
+ npx -y antigravity-hands install
56
+ npx -y antigravity-hands doctor
57
+ ```
58
+
59
+ > 如仅需当前项目生效,可执行 `npx -y antigravity-hands install --workspace`。
60
+
61
+ 在 **系统设置 → 隐私与安全性** 为宿主应用(**Terminal / iTerm / Antigravity**)开启 **辅助功能** 与 **录屏与系统录音** 权限,重启后即可在对话中直接输入:
62
+
63
+ ```text
64
+ /antigravity-hands:computer-use 打开系统「备忘录」,新建一条测试笔记并写入今天的 3 条待办。
65
+ ```
66
+
67
+ ### 从源码编译(开发者)
68
+
69
+ ```bash
70
+ git clone https://github.com/ye4wzp/antigravity-hands.git
71
+ cd antigravity-hands
72
+
73
+ npm install
74
+ npm run build:all # 编译 TypeScript 核心 + 签名 macOS Swift 原生驱动
75
+ npm test # 运行单元测试、沙盒安全与 MCP 协议测试
76
+ node dist/cli.js install
77
+ node dist/cli.js doctor
78
+ ```
79
+
80
+ ---
81
+
82
+ ## 平台支持矩阵
83
+
84
+ | 平台 | 底层驱动 | 状态 |
85
+ | :--- | :--- | :--- |
86
+ | **macOS** (ARM64 / x64) | `drivers/macos`(Swift) | **v0.5 完整版**(`ScreenCaptureKit` 内存取帧、AX 去重与后台操作、Vision 中英文 OCR、SoM 叠图、无损剪贴板、四步智能唤起、黑屏帧拦截、原生 `repeat`、多屏光晕 HUD + 点击涟漪、`Esc`/鼠标让权、`SIGUSR1` 实时钩子) |
87
+ | **Windows** (x64 / ARM64) | `drivers/windows`(C# .NET 8) | **v0.5 全协议实现 + CI 就绪**(UIA 树与后台 `Invoke`/`Value`、`PrintWindow` + SoM 叠图、WinRT OCR、`SendInput` 原生 `repeat` + 无损粘贴、`WDA_EXCLUDEFROMCAPTURE` 隐身光晕 HUD、`WH_KEYBOARD_LL` 全局 `Esc`) |
88
+ | **Linux** (X11 / Wayland) | `drivers/linux`(Rust) | **v0.5 实用版 + CI 就绪**(`wmctrl`/`xdotool` 窗口与原生 `repeat` 键鼠、无损 `xclip`/`wl-copy` 剪贴板、截屏与 `tesseract` 中英文 OCR) |
89
+
90
+ ---
91
+
92
+ ## 文档与贡献
93
+
94
+ - [系统架构设计](./docs/ARCHITECTURE.md)
95
+ - [跨平台 Driver JSON-RPC 协议规范 (v1.0)](./docs/DRIVER_PROTOCOL.md)
96
+ - [参与贡献指南](./CONTRIBUTING.md)
97
+
98
+ ## 开源协议
99
+
100
+ [MIT](./LICENSE)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ import { StdioDriverClient } from "./driver/client.js";
3
+ import { runHook } from "./hooks/runner.js";
4
+ import { installPlugin, runDoctor, uninstallPlugin } from "./installer/index.js";
5
+ import { McpStdioTransport } from "./mcp/protocol.js";
6
+ import { HandsMcpServer, SERVER_VERSION } from "./mcp/server.js";
7
+ import { runSidecarCli } from "./sidecar/server.js";
8
+ function printHelp() {
9
+ console.log(`antigravity-hands v${SERVER_VERSION}
10
+
11
+ Cross-platform Computer Use plugin & MCP server for Google Antigravity (CLI, App, IDE).
12
+
13
+ Usage:
14
+ antigravity-hands mcp Start MCP stdio server
15
+ antigravity-hands sidecar [--port <n>] Start Antigravity.app Live Console sidecar
16
+ antigravity-hands install [--workspace | --scope global|workspace] [--no-download]
17
+ Install as Antigravity plugin
18
+ antigravity-hands uninstall [--workspace | --scope global|workspace]
19
+ Remove Antigravity plugin
20
+ antigravity-hands doctor Verify driver & OS permissions
21
+ antigravity-hands hook <stop|post-tool-use> Run Antigravity lifecycle hook
22
+ antigravity-hands --version Show version
23
+ `);
24
+ }
25
+ function parseScope(args) {
26
+ if (args.includes("--workspace")) {
27
+ return "workspace";
28
+ }
29
+ const idx = args.indexOf("--scope");
30
+ if (idx !== -1 && args[idx + 1] === "workspace") {
31
+ return "workspace";
32
+ }
33
+ return "global";
34
+ }
35
+ async function main() {
36
+ const args = process.argv.slice(2);
37
+ const cmd = args[0];
38
+ if (!cmd || cmd === "-h" || cmd === "--help" || cmd === "help") {
39
+ printHelp();
40
+ return;
41
+ }
42
+ if (cmd === "-v" || cmd === "--version") {
43
+ console.log(SERVER_VERSION);
44
+ return;
45
+ }
46
+ if (cmd === "mcp") {
47
+ const driver = new StdioDriverClient();
48
+ const server = new HandsMcpServer(driver);
49
+ const transport = new McpStdioTransport(process.stdin, process.stdout, (req) => server.handleRequest(req));
50
+ let shuttingDown = false;
51
+ const shutdown = async (waitForPending) => {
52
+ if (shuttingDown)
53
+ return;
54
+ shuttingDown = true;
55
+ if (waitForPending) {
56
+ await transport.waitForIdle();
57
+ }
58
+ await driver.call("release_keys").catch(() => undefined);
59
+ await driver.close();
60
+ process.exit(0);
61
+ };
62
+ process.on("SIGINT", () => void shutdown(false));
63
+ process.on("SIGTERM", () => void shutdown(false));
64
+ process.stdin.on("end", () => void shutdown(true));
65
+ transport.start();
66
+ return;
67
+ }
68
+ if (cmd === "sidecar") {
69
+ const portIdx = args.indexOf("--port");
70
+ const portVal = portIdx !== -1 && args[portIdx + 1]
71
+ ? Number.parseInt(args[portIdx + 1], 10)
72
+ : undefined;
73
+ await runSidecarCli({
74
+ port: Number.isFinite(portVal) ? portVal : undefined,
75
+ });
76
+ return;
77
+ }
78
+ if (cmd === "install") {
79
+ const scope = parseScope(args.slice(1));
80
+ const allowDownload = !args.includes("--no-download");
81
+ const res = await installPlugin({ scope, allowDownload });
82
+ console.log(`Installed Antigravity plugin (${scope}) at:\n ${res.targetDir}`);
83
+ if (res.driverPath) {
84
+ console.log(`Native driver (${res.driverSource}):\n ${res.driverPath}`);
85
+ console.log("\nRun `npx -y antigravity-hands doctor` to verify permissions, then restart Antigravity / agy.");
86
+ }
87
+ else {
88
+ console.log("\nWarning: Native platform driver binary could not be resolved.");
89
+ if (res.downloadError)
90
+ console.log(`Download error: ${res.downloadError}`);
91
+ console.log("Build your platform driver locally (e.g. `npm run build:macos`) or check GitHub Releases.");
92
+ }
93
+ return;
94
+ }
95
+ if (cmd === "uninstall") {
96
+ const scope = parseScope(args.slice(1));
97
+ const res = uninstallPlugin({ scope });
98
+ console.log(res.removed
99
+ ? `Removed Antigravity plugin from ${res.targetDir}`
100
+ : `Plugin was not installed at ${res.targetDir}`);
101
+ return;
102
+ }
103
+ if (cmd === "doctor") {
104
+ const code = await runDoctor();
105
+ process.exitCode = code;
106
+ return;
107
+ }
108
+ if (cmd === "hook") {
109
+ const eventName = args[1] ?? "stop";
110
+ await runHook(eventName);
111
+ return;
112
+ }
113
+ console.error(`Unknown command: ${cmd}\n`);
114
+ printHelp();
115
+ process.exitCode = 1;
116
+ }
117
+ main().catch((err) => {
118
+ console.error(err instanceof Error ? err.message : String(err));
119
+ process.exitCode = 1;
120
+ });
121
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,eAAe,EAAqB,MAAM,sBAAsB,CAAC;AACpG,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,SAAS,SAAS;IAChB,OAAO,CAAC,GAAG,CAAC,sBAAsB,cAAc;;;;;;;;;;;;;;CAcjD,CAAC,CAAC;AACH,CAAC;AAED,SAAS,UAAU,CAAC,IAAc;IAChC,IAAI,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC;QACjC,OA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AC;QACxB,OAAO;IACT,CAAC;IAED,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;QACnB,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC;QACpC,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;QACzB,OAAO;IACT,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAAC;IAC3C,SAAS,EAAE,CAAC;IACZ,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAChE,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { type IDriverClient } from "../types.js";
2
+ export declare class StdioDriverClient implements IDriverClient {
3
+ private proc;
4
+ private pending;
5
+ private reqCounter;
6
+ private stderrTail;
7
+ private binaryPathOverride?;
8
+ private defaultTimeoutMs;
9
+ constructor(options?: {
10
+ binaryPath?: string;
11
+ defaultTimeoutMs?: number;
12
+ });
13
+ getStderrTail(): string[];
14
+ private ensureProcess;
15
+ private handleLine;
16
+ private failAllPending;
17
+ call<T = unknown>(method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<T>;
18
+ close(): Promise<void>;
19
+ }
@@ -0,0 +1,169 @@
1
+ import { spawn } from "node:child_process";
2
+ import readline from "node:readline";
3
+ import { HandsError } from "../types.js";
4
+ import { locateDriverBinary } from "./locator.js";
5
+ export class StdioDriverClient {
6
+ proc = null;
7
+ pending = new Map();
8
+ reqCounter = 0;
9
+ stderrTail = [];
10
+ binaryPathOverride;
11
+ defaultTimeoutMs;
12
+ constructor(options) {
13
+ this.binaryPathOverride = options?.binaryPath;
14
+ this.defaultTimeoutMs = options?.defaultTimeoutMs ?? 20_000;
15
+ }
16
+ getStderrTail() {
17
+ return [...this.stderrTail];
18
+ }
19
+ ensureProcess() {
20
+ if (this.proc && !this.proc.killed && this.proc.exitCode === null) {
21
+ return this.proc;
22
+ }
23
+ const located = locateDriverBinary();
24
+ const binaryPath = this.binaryPathOverride ?? located.resolvedPath;
25
+ if (!binaryPath) {
26
+ throw new HandsError({
27
+ code: "driver_unavailable",
28
+ message: `Native driver binary (${located.binaryName}) not found. ${located.buildHint}`,
29
+ retryable: false,
30
+ details: { searchedPaths: located.searchedPaths },
31
+ });
32
+ }
33
+ const child = spawn(binaryPath, [], {
34
+ stdio: ["pipe", "pipe", "pipe"],
35
+ env: { ...process.env },
36
+ });
37
+ this.proc = child;
38
+ const rl = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
39
+ rl.on("line", (line) => this.handleLine(line));
40
+ child.stderr.on("data", (chunk) => {
41
+ const text = chunk.toString("utf8").trim();
42
+ if (!text)
43
+ return;
44
+ for (const l of text.split(/\r?\n/)) {
45
+ this.stderrTail.push(l);
46
+ if (this.stderrTail.length > 50)
47
+ this.stderrTail.shift();
48
+ }
49
+ });
50
+ child.on("error", (err) => {
51
+ this.failAllPending(new HandsError({
52
+ code: "driver_unavailable",
53
+ message: `Failed to spawn driver (${binaryPath}): ${err.message}`,
54
+ retryable: true,
55
+ }));
56
+ this.proc = null;
57
+ });
58
+ child.on("exit", (code, signal) => {
59
+ const detail = this.stderrTail.slice(-5).join(" | ");
60
+ this.failAllPending(new HandsError({
61
+ code: "driver_unavailable",
62
+ message: `Native driver exited unexpectedly (code=${code}, signal=${signal})${detail ? `: ${detail}` : ""}`,
63
+ retryable: true,
64
+ }));
65
+ this.proc = null;
66
+ });
67
+ return child;
68
+ }
69
+ handleLine(line) {
70
+ const trimmed = line.trim();
71
+ if (!trimmed)
72
+ return;
73
+ let msg;
74
+ try {
75
+ msg = JSON.parse(trimmed);
76
+ }
77
+ catch {
78
+ this.stderrTail.push(`[non-json stdout] ${trimmed.slice(0, 200)}`);
79
+ return;
80
+ }
81
+ const entry = this.pending.get(msg.id);
82
+ if (!entry)
83
+ return;
84
+ this.pending.delete(msg.id);
85
+ clearTimeout(entry.timer);
86
+ if (msg.ok) {
87
+ entry.resolve(msg.result);
88
+ }
89
+ else {
90
+ entry.reject(new HandsError(msg.error));
91
+ }
92
+ }
93
+ failAllPending(err) {
94
+ for (const [id, entry] of this.pending.entries()) {
95
+ clearTimeout(entry.timer);
96
+ entry.reject(err);
97
+ this.pending.delete(id);
98
+ }
99
+ }
100
+ async call(method, params, timeoutMs) {
101
+ const proc = this.ensureProcess();
102
+ const id = `r_${++this.reqCounter}`;
103
+ const req = params ? { id, method, params } : { id, method };
104
+ const effectiveTimeout = timeoutMs ?? this.defaultTimeoutMs;
105
+ return new Promise((resolve, reject) => {
106
+ const timer = setTimeout(() => {
107
+ this.pending.delete(id);
108
+ reject(new HandsError({
109
+ code: "timeout",
110
+ message: `Driver call "${method}" timed out after ${effectiveTimeout}ms`,
111
+ retryable: true,
112
+ }));
113
+ }, effectiveTimeout);
114
+ this.pending.set(id, {
115
+ resolve: resolve,
116
+ reject,
117
+ timer,
118
+ method,
119
+ });
120
+ const payload = JSON.stringify(req) + "\n";
121
+ proc.stdin.write(payload, "utf8", (writeErr) => {
122
+ if (writeErr) {
123
+ clearTimeout(timer);
124
+ this.pending.delete(id);
125
+ reject(new HandsError({
126
+ code: "driver_unavailable",
127
+ message: `Failed writing to driver stdin: ${writeErr.message}`,
128
+ retryable: true,
129
+ }));
130
+ }
131
+ });
132
+ });
133
+ }
134
+ async close() {
135
+ if (!this.proc)
136
+ return;
137
+ const child = this.proc;
138
+ this.proc = null;
139
+ try {
140
+ child.stdin.end();
141
+ }
142
+ catch {
143
+ // ignore
144
+ }
145
+ await new Promise((resolve) => {
146
+ const timer = setTimeout(() => {
147
+ try {
148
+ child.kill("SIGKILL");
149
+ }
150
+ catch {
151
+ // ignore
152
+ }
153
+ resolve();
154
+ }, 1000);
155
+ child.once("exit", () => {
156
+ clearTimeout(timer);
157
+ resolve();
158
+ });
159
+ try {
160
+ child.kill("SIGTERM");
161
+ }
162
+ catch {
163
+ clearTimeout(timer);
164
+ resolve();
165
+ }
166
+ });
167
+ }
168
+ }
169
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/driver/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAuC,MAAM,oBAAoB,CAAC;AAChF,OAAO,QAAQ,MAAM,eAAe,CAAC;AACrC,OAAO,EAAE,UAAU,EAA+D,MAAM,aAAa,CAAC;AACtG,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AASlD,MAAM,OAAO,iBAAiB;IACpB,IAAI,GAA0C,IAAI,CAAC;IACnD,OAAO,GAAG,IAAI,GAAG,EAAuB,CAAC;IACzC,UAAU,GAAG,CAAC,CAAC;IACf,UAAU,GAAa,EAAE,CAAC;IAC1B,kBAAkB,CAAU;IAC5B,gBAAgB,CAAS;IAEjC,YAAY,OAA4D;QACtE,IAAI,CAAC,kBAAkB,GAAG,OAAO,EAAE,UAAU,CAAC;QAC9C,IAAI,CAAC,gBAAgB,GAAG,OAAO,EAAE,gBAAgB,IAAI,MAAM,CAAC;IAC9D,CAAC;IAEM,aAAa;QAClB,OAAO,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;IAC9B,CAAC;IAEO,aAAa;QACnB,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YAClE,OAAO,IAAI,CAAC,IAAI,CAAC;QACnB,CAAC;QAED,MAAM,OAAO,GAAG,kBAAkB,EAAE,CAAC;QACrC,MAAM,UAAU,GAAG,IAAI,CAAC,kBAAkB,IAAI,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