Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

feat(marketplace): desktop-act companion co-install with ops (#724)

Aurora Capital45969812a9e5
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 924f15b3..92433ec1 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -1,7 +1,7 @@
{
"$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
"name": "ops-marketplace",
- "description": "Local marketplace for claude-ops plugin",
+ "description": "Marketplace for the ops plugin and its desktop-act computer-use companion",
"owner": {
"name": "Lifecycle Innovations Limited",
"email": "[email protected]"
@@ -9,7 +9,7 @@
"plugins": [
{
"name": "ops",
- "description": "Business operations command center for Claude Code — 61 skills, 21 agents, smart background daemon. Manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (AWS), revenue (Stripe+RevenueCat), e-commerce, marketing, monitoring (Datadog/New Relic/OTEL), voice, and smart home (Homey Pro). Includes /ops:ops-ar A&R (audio analysis + demo verdict cards), /gtm go-to-market planner, /ops:projects portfolio dashboard, /ops:ops-mac macOS diagnose-and-fix (macos-toolkit CLI suite), /ops:ops-home control surface, and YOLO autonomous mode with 4 parallel C-suite agents.",
+ "description": "Business operations command center for Claude Code \u2014 61 skills, 21 agents, smart background daemon. Manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (AWS), revenue (Stripe+RevenueCat), e-commerce, marketing, monitoring (Datadog/New Relic/OTEL), voice, and smart home (Homey Pro). Includes /ops:ops-ar A&R (audio analysis + demo verdict cards), /gtm go-to-market planner, /ops:projects portfolio dashboard, /ops:ops-mac macOS diagnose-and-fix (macos-toolkit CLI suite), /ops:ops-home control surface, and YOLO autonomous mode with 4 parallel C-suite agents.",
"source": "./claude-ops",
"version": "2.46.2",
"category": "productivity",
@@ -34,6 +34,24 @@
"smart-home",
"iot"
]
+ },
+ {
+ "name": "desktop-act",
+ "description": "Computer-use MCP companion for /ops:desktop \u2014 screenshot, click, type, multi-desktop pool, autonomous act() loop. Co-installed with the ops plugin.",
+ "source": "./desktop-act",
+ "version": "0.2.0",
+ "category": "automation",
+ "keywords": [
+ "computer-use",
+ "desktop",
+ "automation",
+ "mcp",
+ "fastmcp",
+ "screenshot",
+ "vnc",
+ "x11",
+ "agentic"
+ ]
}
]
}
diff --git a/README.md b/README.md
index 44752707..2bc56b26 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ v2 turns claude-ops from a _briefing + comms surface_ into an **autonomy layer f
```bash
# 1. Upgrade
-/plugin update ops@lifecycle-innovations-limited-claude-ops
+/plugin update ops@ops-marketplace
# 2. Run the wizard (hits new steps 6.5a–6.5d for v2 toggles)
/ops:setup
@@ -79,13 +79,15 @@ Per-repo budget caps (default 3/hour), single-flight locks, and content-hash ded
## Quick Start
```bash
-# 1. Add the marketplace
+# 1. Add the marketplace (ships ops + desktop-act companion)
/plugin marketplace add Lifecycle-Innovations-Limited/claude-ops
-# 2. Install the plugin
-/plugin install ops@lifecycle-innovations-limited-claude-ops
+# 2. Install the ops plugin
+/plugin install ops@ops-marketplace
+# Optional explicit companion (also run by /ops:setup and /ops:update):
+# /plugin install desktop-act@ops-marketplace
-# 3. Run the guided setup wizard
+# 3. Run the guided setup wizard (co-installs desktop-act by default)
/ops:setup
```
diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.json
index dc92e871..ca00fe8a 100644
--- a/claude-ops/.claude-plugin/plugin.json
+++ b/claude-ops/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ops",
"version": "2.46.2",
- "description": "Business operations command center for Claude Code — 61 skills, 21 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /ops:ops-ar A&R (audio analysis + demo verdict cards), /gtm go-to-market planner, /ops:projects portfolio dashboard, /ops:ops-mac macOS diagnose-and-fix (bundles the macos-toolkit CLI suite — security, launchd, network, disk, system health), YOLO mode for autonomous operation with 4 parallel C-suite agents, /ops:ops-home smart home control via Homey Pro, /ops:ops-unifi UniFi network control (Site Manager + Network + Protect APIs), and /ops:ops-feature-dev overlay for the feature-dev companion plugin.",
+ "description": "Business operations command center for Claude Code \u2014 61 skills, 21 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /ops:ops-ar A&R (audio analysis + demo verdict cards), /gtm go-to-market planner, /ops:projects portfolio dashboard, /ops:ops-mac macOS diagnose-and-fix (bundles the macos-toolkit CLI suite \u2014 security, launchd, network, disk, system health), YOLO mode for autonomous operation with 4 parallel C-suite agents, /ops:ops-home smart home control via Homey Pro, /ops:ops-unifi UniFi network control (Site Manager + Network + Protect APIs), and /ops:ops-feature-dev overlay for the feature-dev companion plugin.",
"author": {
"name": "Lifecycle Innovations Limited",
"url": "https://github.com/Lifecycle-Innovations-Limited"
@@ -66,7 +66,7 @@
"no_rm_rf_anchor": {
"type": "boolean",
"title": "Block rm -rf against root anchors",
- "description": "PreToolUse hook denies `rm -rf` targeting /, ~, $HOME, .., or . — protecting against catastrophic filesystem wipes. Specific subpaths (./node_modules, /tmp/foo) are allowed.",
+ "description": "PreToolUse hook denies `rm -rf` targeting /, ~, $HOME, .., or . \u2014 protecting against catastrophic filesystem wipes. Specific subpaths (./node_modules, /tmp/foo) are allowed.",
"default": true
},
"warn_mainpush": {
@@ -83,7 +83,7 @@
},
"monitor_post_merge": {
"type": "boolean",
- "title": "Monitor PR merges → deploys",
+ "title": "Monitor PR merges \u2192 deploys",
"description": "After `gh pr merge` to dev/main, watch the deploy workflow + audit service health.",
"default": true
},
@@ -96,7 +96,7 @@
"auto_dispatch_fixer": {
"type": "boolean",
"title": "Auto-dispatch headless Claude fixer",
- "description": "When off, failures are logged + notified only — no agent runs.",
+ "description": "When off, failures are logged + notified only \u2014 no agent runs.",
"default": true
},
"allow_dangerous": {
@@ -148,7 +148,7 @@
"registry_path": {
"type": "file",
"title": "Service registry JSON",
- "description": "Maps owner/repo:base → health/version URLs. Project .claude/post-merge-services.json overrides.",
+ "description": "Maps owner/repo:base \u2192 health/version URLs. Project .claude/post-merge-services.json overrides.",
"default": "~/.claude/config/post-merge-services.json"
},
"repo_search_roots": {
@@ -210,33 +210,33 @@
"suggest_specialized_agents": {
"type": "boolean",
"title": "Suggest specialized subagents",
- "description": "PreToolUse hook on Agent — when subagent_type=general-purpose, asks if a domain-specific agent fits better.",
+ "description": "PreToolUse hook on Agent \u2014 when subagent_type=general-purpose, asks if a domain-specific agent fits better.",
"default": true
},
"telegram_api_id": {
"title": "Telegram API ID",
- "description": "Numeric API ID from https://my.telegram.org/apps. Optional — run /ops:setup telegram to auto-configure.",
+ "description": "Numeric API ID from https://my.telegram.org/apps. Optional \u2014 run /ops:setup telegram to auto-configure.",
"type": "string",
"sensitive": true,
"default": ""
},
"telegram_api_hash": {
"title": "Telegram API Hash",
- "description": "API hash from https://my.telegram.org/apps. Optional — run /ops:setup telegram to auto-configure. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "API hash from https://my.telegram.org/apps. Optional \u2014 run /ops:setup telegram to auto-configure. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"telegram_phone": {
"title": "Telegram Phone Number",
- "description": "Your phone number in E.164 format. Optional — run /ops:setup telegram to auto-configure.",
+ "description": "Your phone number in E.164 format. Optional \u2014 run /ops:setup telegram to auto-configure.",
"type": "string",
"sensitive": true,
"default": ""
},
"telegram_session": {
"title": "Telegram Session String",
- "description": "gram.js StringSession. Optional — run /ops:setup telegram to auto-configure. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "gram.js StringSession. Optional \u2014 run /ops:setup telegram to auto-configure. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -264,14 +264,14 @@
},
"klaviyo_private_key": {
"title": "Klaviyo Private API Key",
- "description": "Private API key from Klaviyo Settings > API Keys (starts with pk_ or ck_) If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Private API key from Klaviyo Settings > API Keys (starts with pk_ or ck_) If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"meta_ads_token": {
"title": "Meta Ads Access Token",
- "description": "Meta Marketing API access token from Facebook Business If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Meta Marketing API access token from Facebook Business If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -307,49 +307,49 @@
},
"shopify_admin_token": {
"title": "Shopify Admin API Token",
- "description": "Admin API access token from Shopify Partners or custom app If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Admin API access token from Shopify Partners or custom app If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"shipbob_access_token": {
"title": "ShipBob Access Token",
- "description": "ShipBob Personal Access Token for fulfillment tracking (optional) If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "ShipBob Personal Access Token for fulfillment tracking (optional) If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"bland_ai_api_key": {
"title": "Bland AI API Key",
- "description": "API key from https://app.bland.ai — used for /ops:ops-voice call If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "API key from https://app.bland.ai \u2014 used for /ops:ops-voice call If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"elevenlabs_api_key": {
"title": "ElevenLabs API Key",
- "description": "API key from https://elevenlabs.io — used for /ops:ops-voice tts If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "API key from https://elevenlabs.io \u2014 used for /ops:ops-voice tts If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"groq_api_key": {
"title": "Groq API Key",
- "description": "API key from https://console.groq.com — used for /ops:ops-voice transcribe (Whisper) If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "API key from https://console.groq.com \u2014 used for /ops:ops-voice transcribe (Whisper) If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"stripe_secret_key": {
"title": "Stripe Secret Key",
- "description": "Stripe secret key (sk_live_... or sk_test_...) for revenue tracking. Prefer Doppler reference. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Stripe secret key (sk_live_... or sk_test_...) for revenue tracking. Prefer Doppler reference. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"revenuecat_api_key": {
"title": "RevenueCat API Key",
- "description": "RevenueCat API key for mobile subscription revenue tracking (V2 API). If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "RevenueCat API key for mobile subscription revenue tracking (V2 API). If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -363,21 +363,21 @@
},
"datadog_api_key": {
"title": "Datadog API Key",
- "description": "From Datadog Organization Settings > API Keys — used for /ops:monitor If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "From Datadog Organization Settings > API Keys \u2014 used for /ops:monitor If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"datadog_app_key": {
"title": "Datadog Application Key",
- "description": "From Datadog Organization Settings > Application Keys If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "From Datadog Organization Settings > Application Keys If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"newrelic_api_key": {
"title": "New Relic API Key",
- "description": "User API Key from one.newrelic.com/api-keys — used for /ops:monitor If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "User API Key from one.newrelic.com/api-keys \u2014 used for /ops:monitor If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -413,21 +413,21 @@
},
"pushover_user_key": {
"title": "Pushover User Key",
- "description": "From https://pushover.net/ — paired with pushover_app_token. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "From https://pushover.net/ \u2014 paired with pushover_app_token. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"pushover_app_token": {
"title": "Pushover App Token",
- "description": "App-specific token from https://pushover.net/apps/build If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "App-specific token from https://pushover.net/apps/build If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"telegram_bot_token": {
"title": "Telegram Bot Token",
- "description": "Bot token for outbound notifications + channel-mcp DM polling. From @BotFather. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Bot token for outbound notifications + channel-mcp DM polling. From @BotFather. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -441,28 +441,28 @@
},
"discord_bot_token": {
"title": "Discord Bot Token",
- "description": "Bot token from Discord Developer Portal — used for channel reads and DMs. Prefer Doppler reference. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Bot token from Discord Developer Portal \u2014 used for channel reads and DMs. Prefer Doppler reference. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"discord_guild_id": {
"title": "Discord Guild ID",
- "description": "Server/guild ID (right-click server in Discord → Copy ID with Developer Mode enabled)",
+ "description": "Server/guild ID (right-click server in Discord \u2192 Copy ID with Developer Mode enabled)",
"type": "string",
"sensitive": false,
"default": ""
},
"discord_default_webhook_url": {
"title": "Discord Default Webhook URL",
- "description": "Optional default webhook URL (https://discord.com/api/webhooks/…) for /ops:comms discord send. Shared with the ops-fires notification sink (which also reads discord_webhook_url). If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Optional default webhook URL (https://discord.com/api/webhooks/\u2026) for /ops:comms discord send. Shared with the ops-fires notification sink (which also reads discord_webhook_url). If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
},
"doppler_token": {
"title": "Doppler Token",
- "description": "Doppler service or personal token for the @dopplerhq/mcp-server MCP integration. Generated by /ops:setup or paste manually. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Doppler service or personal token for the @dopplerhq/mcp-server MCP integration. Generated by /ops:setup or paste manually. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -483,35 +483,35 @@
},
"myparcel_api_key": {
"title": "MyParcel.nl API Key",
- "description": "Plain API key from backoffice.myparcel.nl → Settings → API. Used by /ops:ops-package. Script base64-encodes it at runtime — do NOT pre-encode.",
+ "description": "Plain API key from backoffice.myparcel.nl \u2192 Settings \u2192 API. Used by /ops:ops-package. Script base64-encodes it at runtime \u2014 do NOT pre-encode.",
"type": "string",
"sensitive": true,
"default": ""
},
"sendcloud_public_key": {
"title": "Sendcloud Public Key",
- "description": "Public key from Sendcloud Panel → Settings → Integrations → Sendcloud API. Paired with sendcloud_private_key.",
+ "description": "Public key from Sendcloud Panel \u2192 Settings \u2192 Integrations \u2192 Sendcloud API. Paired with sendcloud_private_key.",
"type": "string",
"sensitive": true,
"default": ""
},
"sendcloud_private_key": {
"title": "Sendcloud Private Key",
- "description": "Private key from Sendcloud Panel → Settings → Integrations → Sendcloud API. Paired with sendcloud_public_key.",
+ "description": "Private key from Sendcloud Panel \u2192 Settings \u2192 Integrations \u2192 Sendcloud API. Paired with sendcloud_public_key.",
"type": "string",
"sensitive": true,
"default": ""
},
"dhl_parcel_user_id": {
"title": "DHL Parcel NL User ID",
- "description": "User ID issued in My DHL Parcel → User settings → API settings. Paired with dhl_parcel_key.",
+ "description": "User ID issued in My DHL Parcel \u2192 User settings \u2192 API settings. Paired with dhl_parcel_key.",
"type": "string",
"sensitive": true,
"default": ""
},
"dhl_parcel_key": {
"title": "DHL Parcel NL API Key",
- "description": "API key from My DHL Parcel → User settings → API settings. Paired with dhl_parcel_user_id.",
+ "description": "API key from My DHL Parcel \u2192 User settings \u2192 API settings. Paired with dhl_parcel_user_id.",
"type": "string",
"sensitive": true,
"default": ""
@@ -546,7 +546,7 @@
},
"dpd_password": {
"title": "DPD Password",
- "description": "Password for the DelisID. Exchanged at login for a short-lived token. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Password for the DelisID. Exchanged at login for a short-lived token. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -560,7 +560,7 @@
},
"ups_client_secret": {
"title": "UPS OAuth Client Secret",
- "description": "Client secret for the UPS app. Used for OAuth2 client_credentials. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Client secret for the UPS app. Used for OAuth2 client_credentials. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -581,7 +581,7 @@
},
"fedex_client_secret": {
"title": "FedEx OAuth Client Secret",
- "description": "Secret Key for the FedEx project. Used for OAuth2 client_credentials. If already configured via /ops:setup or stored in keychain/Doppler, leave blank — runtime resolves automatically.",
+ "description": "Secret Key for the FedEx project. Used for OAuth2 client_credentials. If already configured via /ops:setup or stored in keychain/Doppler, leave blank \u2014 runtime resolves automatically.",
"type": "string",
"sensitive": true,
"default": ""
@@ -596,7 +596,7 @@
"telegram_enabled": {
"type": "boolean",
"title": "Enable Telegram integration",
- "description": "Use Telegram for inbox + notifications. Requires telegram_api_id/hash/phone/session — run /ops:setup telegram.",
+ "description": "Use Telegram for inbox + notifications. Requires telegram_api_id/hash/phone/session \u2014 run /ops:setup telegram.",
"default": false
},
"discord_enabled": {
@@ -759,11 +759,17 @@
},
"desktop_act_repo": {
"title": "desktop-act source repository",
- "description": "Git URL the launcher clones from when bootstrapping a fresh install. Defaults to the public your-org/desktop-act repo.",
+ "description": "Git URL the launcher clones from when bootstrapping a fresh install if the co-installed marketplace plugin is missing. Leave blank to use the Lifecycle-Innovations-Limited/desktop-act default (overridable via DESKTOP_ACT_REPO).",
"type": "string",
"sensitive": false,
"default": ""
},
+ "desktop_act_co_install": {
+ "type": "boolean",
+ "title": "Co-install desktop-act companion",
+ "description": "When true (default), /ops:setup and /ops:update install desktop-act@ops-marketplace alongside ops so /ops:desktop and captcha cascade resolve without a manual marketplace add.",
+ "default": true
+ },
"desktop_act_branch": {
"title": "desktop-act branch / tag",
"description": "Branch or tag to clone when bootstrapping. Defaults to main.",
@@ -796,7 +802,7 @@
},
"ip_whitelist_desc_prefix": {
"title": "IP-whitelist rule description prefix",
- "description": "Description prefix for managed rules — e.g. 'mylaptop'. Defaults to <hostname>-laptop. Rules with this prefix are reaped when older than ip_whitelist_keep_recent.",
+ "description": "Description prefix for managed rules \u2014 e.g. 'mylaptop'. Defaults to <hostname>-laptop. Rules with this prefix are reaped when older than ip_whitelist_keep_recent.",
"type": "string",
"sensitive": false,
"default": ""
@@ -810,5 +816,16 @@
"min": 0,
"max": 20
}
+ },
+ "dependencies": {
+ "plugins": [
+ {
+ "name": "desktop-act",
+ "marketplace": "ops-marketplace",
+ "coInstall": true,
+ "required": false,
+ "reason": "MCP companion for /ops:desktop and unattended captcha cascade"
+ }
+ ]
}
}
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index 824d7d93..45e5b88a 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -4,6 +4,8 @@
### Added
+- **ops-update companions:** step 9 runs `scripts/install-companions.sh` from `plugin-dependencies.json` — always co-install/update `desktop-act@ops-marketplace`; update `gsd`, `superpowers`, and `feature-dev` only if already installed. `gstack` is not managed. Flag: `--no-companions`.
+- **desktop-act marketplace companion:** `desktop-act` is published in `ops-marketplace` next to `ops` (source `./desktop-act`). Declared as a co-install dependency in `plugin.json` + `plugin-dependencies.json`. `scripts/install-desktop-act-companion.sh` installs via `claude plugin install desktop-act@ops-marketplace` (idempotent). `/ops:setup` and `/ops:update` co-install by default (`desktop_act_co_install`). Launcher resolves `ops-marketplace/desktop-act` before cache clone; default bootstrap repo is Lifecycle-Innovations-Limited/desktop-act.
- **magic-link-autoloop reauth env (portable):** unattended re-auth child now inherits an env-templated headed seat + captcha cascade contract (`reauth-env.mjs`, `CAPTCHA-CASCADE.md`). Defaults: headed display from `CLAUDE_DESKTOP_DISPLAY` / `DESKTOP_ACT_DISPLAY`, visual + desktop-act + VNC layers on when present, 20m rotate timeout, no steal-lock, sticky `SKIP_TOKEN_SOLVERS=1` cleared. Dispatch mode `setup` (default) or `magic-link` via `$CRS_MAGIC_LINK_DISPATCH` / `crs.magicLinkDispatch`. Shell wrapper resolves plugin via `$CLAUDE_PLUGIN_ROOT` (no host hardcodes). Launchd template + `config.example.json` document the knobs.
- **installer (`claude-ops-installer`, v0.1.0):** cross-CLI `npx claude-ops-installer install` — auto-detects Claude Code, Codex, Gemini CLI, OpenClaw, Hermes, and OpenCode, mirrors upstream skills + binstubs into each agent's expected layout, ships with a central `~/.config/claude-ops-installer/config.yaml`, and supports `install` / `update` / `verify` / `doctor` / `uninstall` / `agents` subcommands. One source of truth (the upstream marketplace repo at the pinned ref); per-agent manifest at `~/.cache/claude-ops-installer/manifest.json` enables surgical uninstall. Public-repo clean: no PII, no hardcoded paths, no embedded credentials.
diff --git a/claude-ops/README.md b/claude-ops/README.md
index 214d4a61..b5094f7b 100644
--- a/claude-ops/README.md
+++ b/claude-ops/README.md
@@ -34,7 +34,7 @@ Purely additive — no v1 behaviour changes by default. Full migration guide: [`
### v2 quick start — deploy auto-fix in 60 seconds
```bash
-/plugin update ops@lifecycle-innovations-limited-claude-ops
+/plugin update ops@ops-marketplace
/ops:setup # walks through new steps 2d, 3o, 6.5a–6.5d
/ops:deploy-fix configure # map your repos → /health + /version URLs
# done — every future `gh pr merge` is now watched + verified + auto-fixed
@@ -196,11 +196,13 @@ The setup wizard (`/ops:setup`) walks through each one interactively. You choose
`claude-ops` is distributed as a Claude Code marketplace plugin. Install it directly from inside Claude Code — you don't need to clone anything manually or edit any settings files.
```bash
-# 1. Add the marketplace (one-time)
+# 1. Add the marketplace (one-time; ships ops + desktop-act companion)
/plugin marketplace add Lifecycle-Innovations-Limited/claude-ops
-# 2. Install the plugin
-/plugin install ops@lifecycle-innovations-limited-claude-ops
+# 2. Install the ops plugin
+/plugin install ops@ops-marketplace
+# Companion (also co-installed by /ops:setup and /ops:update by default):
+# /plugin install desktop-act@ops-marketplace
# 3. Configure integrations (Telegram, Slack, AWS, etc.)
/ops:setup
diff --git a/claude-ops/bin/ops-update b/claude-ops/bin/ops-update
index 3d7e473b..30a4d578 100755
--- a/claude-ops/bin/ops-update
+++ b/claude-ops/bin/ops-update
@@ -15,7 +15,9 @@
# 6. Rewrite stale version-pinned paths in live configs/scripts (never logs/history)
# 7. Run per-version idempotent migrations (ops-post-update-migrate)
# 8. Fast-forward a linked local source checkout's main → origin/main (if clean)
-# 9. Report old→new + what changed, and how to apply (/reload-plugins or restart)
+# 9. Companion plugins (plugin-dependencies.json): desktop-act always;
+# gsd / superpowers / feature-dev if installed. gstack is not managed.
+# 10. Report old→new + what changed, and how to apply (/reload-plugins or restart)
#
# Canonical CLI per Claude Code docs:
# https://code.claude.com/docs/en/discover-plugins (marketplace update / plugin update)
@@ -23,7 +25,7 @@
#
# Usage:
# ops-update [--dry-run] [--force] [--to X.Y.Z] [--no-prune] [--no-patches]
-# [--no-rewrite] [--no-localsync]
+# [--no-rewrite] [--no-localsync] [--no-companions]
#
# --dry-run show everything that would happen; change nothing
# --force force-reinstall even if the CLI says "already at latest" (bug #61954)
@@ -32,6 +34,7 @@
# --no-patches skip the cache-patch reapply step
# --no-rewrite skip the stale-version-path rewrite step
# --no-localsync skip fast-forwarding a linked local source checkout's main
+# --no-companions skip companion install/update
#
# Public repo: no personal data. All paths derive from $HOME / env. (Rule 0)
@@ -47,7 +50,7 @@ INSTALLED="$PLUGINS_DIR/installed_plugins.json"
DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$PLUGINS_DIR/data/ops-${MARKETPLACE}}"
THIS_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
-DRY=0; FORCE=0; PRUNE=1; PATCHES=1; REWRITE=1; LOCALSYNC=1; TARGET=""
+DRY=0; FORCE=0; PRUNE=1; PATCHES=1; REWRITE=1; LOCALSYNC=1; COMPANIONS=1; TARGET=""
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run) DRY=1; shift ;;
@@ -57,7 +60,8 @@ while [[ $# -gt 0 ]]; do
--no-patches) PATCHES=0; shift ;;
--no-rewrite) REWRITE=0; shift ;;
--no-localsync) LOCALSYNC=0; shift ;;
- -h|--help) sed -n '2,35p' "$0"; exit 0 ;;
+ --no-companions) COMPANIONS=0; shift ;;
+ -h|--help) sed -n '2,40p' "$0"; exit 0 ;;
*) echo "ops-update: unknown arg '$1'" >&2; exit 2 ;;
esac
done
@@ -85,7 +89,7 @@ say "${c_dim}ops-update — claude-ops local upgrade$([[ $DRY -eq 1 ]] && echo '
say "current installed: ${CUR:-<none>}"
# ── 1. Refresh marketplace catalogue ───────────────────────────────────────
-step "1/9 Refresh marketplace catalogue ($MARKETPLACE)"
+step "1/10 Refresh marketplace catalogue ($MARKETPLACE)"
if [[ "$DRY" -eq 1 ]]; then
say " ${c_dim}[dry-run] claude plugin marketplace update $MARKETPLACE${c_rst}"
else
@@ -98,7 +102,7 @@ else
fi
# ── 2. Resolve target version ──────────────────────────────────────────────
-step "2/9 Resolve target version"
+step "2/10 Resolve target version"
if [[ -n "$TARGET" ]]; then
NEW="$TARGET"
else
@@ -111,7 +115,7 @@ if [[ "$CUR" == "$NEW" && "$FORCE" -eq 0 ]]; then
fi
# ── 3. Update the installed plugin ─────────────────────────────────────────
-step "3/9 Update installed plugin → $NEW"
+step "3/10 Update installed plugin → $NEW"
if [[ "$DRY" -eq 1 ]]; then
say " ${c_dim}[dry-run] claude plugin update $PLUGIN@$MARKETPLACE${c_rst}"
[[ "$FORCE" -eq 1 ]] && say " ${c_dim}[dry-run] (force) rm -rf $CACHE_ROOT/$NEW && claude plugin install $PLUGIN@$MARKETPLACE${c_rst}"
@@ -127,7 +131,7 @@ fi
NEW_CACHE="$CACHE_ROOT/$NEW"
# ── 4. Reapply idempotent local cache patches ──────────────────────────────
-step "4/9 Reapply cache patches"
+step "4/10 Reapply cache patches"
PATCH_DIR="$THIS_ROOT/scripts/cache-patches"
if [[ "$PATCHES" -eq 0 ]]; then
say " ${c_dim}(skipped: --no-patches)${c_rst}"
@@ -142,7 +146,7 @@ else
fi
# ── 5. Prune old cache versions everywhere ─────────────────────────────────
-step "5/9 Prune old cache versions"
+step "5/10 Prune old cache versions"
if [[ "$PRUNE" -eq 0 ]]; then
say " ${c_dim}(skipped: --no-prune)${c_rst}"
else
@@ -161,7 +165,7 @@ fi
# ── 6. Rewrite stale version-pinned paths in LIVE configs/scripts ──────────
# Only touch live, editable configs that hardcode cache/<mp>/<plugin>/<OLDVER>/.
# NEVER rewrite logs, memory notes, session transcripts, the cache, or the clone.
-step "6/9 Rewrite stale version-pinned paths → $NEW"
+step "6/10 Rewrite stale version-pinned paths → $NEW"
if [[ "$REWRITE" -eq 0 ]]; then
say " ${c_dim}(skipped: --no-rewrite)${c_rst}"
else
@@ -204,7 +208,7 @@ else
fi
# ── 7. Per-version idempotent migrations ───────────────────────────────────
-step "7/9 Post-update migrations"
+step "7/10 Post-update migrations"
MIGRATE="$NEW_CACHE/bin/ops-post-update-migrate"
if [[ "$DRY" -eq 1 ]]; then
say " ${c_dim}[dry-run] CLAUDE_PLUGIN_ROOT=$NEW_CACHE $MIGRATE${c_rst}"
@@ -219,7 +223,7 @@ fi
# up to date with origin/main — but ONLY when it is safely on a clean main, so we
# never clobber uncommitted WIP or a feature branch. Purely a developer
# convenience; absence of a checkout is the common case and is a no-op.
-step "8/9 Sync linked local source checkout"
+step "8/10 Sync linked local source checkout"
if [[ "$LOCALSYNC" -eq 0 ]]; then
say " ${c_dim}(skipped: --no-localsync)${c_rst}"
else
@@ -255,11 +259,37 @@ else
fi
fi
-# ── 9. Report ──────────────────────────────────────────────────────────────
-step "9/9 Summary"
+# ── 9. Companion plugins (desktop-act always; others if installed) ─────────
+# SSOT: plugin-dependencies.json — desktop-act co-install; gsd / superpowers /
+# feature-dev update only when already present. gstack is not managed.
+step "9/10 Companion plugins"
+if [[ "$COMPANIONS" -eq 0 ]]; then
+ say " ${c_dim}(skipped: --no-companions)${c_rst}"
+else
+ COMP_SCRIPT="$NEW_CACHE/scripts/install-companions.sh"
+ [[ -f "$COMP_SCRIPT" ]] || COMP_SCRIPT="$THIS_ROOT/scripts/install-companions.sh"
+ if [[ -f "$COMP_SCRIPT" ]]; then
+ if [[ "$DRY" -eq 1 ]]; then
+ say " ${c_dim}[dry-run] CLAUDE_PLUGIN_ROOT=$NEW_CACHE bash $COMP_SCRIPT --update-only${c_rst}"
+ # also show install of always-coInstall (desktop-act) when missing
+ say " ${c_dim}[dry-run] CLAUDE_PLUGIN_ROOT=$NEW_CACHE bash $COMP_SCRIPT${c_rst}"
+ else
+ # Full pass: install always-coInstall missing + update if-installed
+ CLAUDE_PLUGIN_ROOT="${NEW_CACHE:-$THIS_ROOT}" bash "$COMP_SCRIPT" \
+ && ok "companions install/update finished" \
+ || warn "companions script non-zero (non-fatal)"
+ fi
+ else
+ say " ${c_dim}no install-companions.sh in new cache (skipped)${c_rst}"
+ fi
+fi
+
+# ── 10. Report ─────────────────────────────────────────────────────────────
+step "10/10 Summary"
say " plugin: $PLUGIN@$MARKETPLACE"
say " version: ${CUR:-<none>} → ${c_grn}$NEW${c_rst}"
say " cache: $(ls -1 "$CACHE_ROOT" 2>/dev/null | grep -E '^[0-9]+\.' | tr '\n' ' ')"
+say " companions: desktop-act (always) · gsd/superpowers/feature-dev (if installed) · gstack (not managed)"
if [[ "$DRY" -eq 1 ]]; then
warn "DRY RUN — nothing changed. Re-run without --dry-run to apply."
else
diff --git a/claude-ops/mcp-servers/desktop-act-launcher.py b/claude-ops/mcp-servers/desktop-act-launcher.py
index 091aff5c..4340afca 100755
--- a/claude-ops/mcp-servers/desktop-act-launcher.py
+++ b/claude-ops/mcp-servers/desktop-act-launcher.py
@@ -15,10 +15,10 @@ Resolution order:
If absent and ``DESKTOP_ACT_REPO`` is set, we ``git clone`` it,
bootstrap a venv, ``pip install -r requirements.txt``, then exec.
-Linux (X11/Xvnc) and macOS (screencapture + cliclick) both have native
-desktop-automation backends and bootstrap/exec identically. Windows has no
-native backend yet, so on Windows the launcher surfaces a clear message if it
-cannot locate or bootstrap a server, instead of hanging the MCP host.
+Linux (X11/Xvnc), macOS (screencapture + cliclick), and Windows
+(ImageGrab + pyautogui/SendInput) all have native backends. The launcher
+bootstrap/exec is identical across platforms; on any OS it surfaces a clear
+message if it cannot locate or bootstrap a server, instead of hanging the MCP host.
"""
from __future__ import annotations
@@ -30,7 +30,8 @@ import subprocess
import sys
from pathlib import Path
-_DEFAULT_REPO = "https://github.com/your-org/desktop-act.git"
+# Default bootstrap URL — overridable via DESKTOP_ACT_REPO (no personal paths).
+_DEFAULT_REPO = "https://github.com/Lifecycle-Innovations-Limited/desktop-act.git"
_DEFAULT_BRANCH = "main"
# MCP may inject empty strings from userConfig; treat those as unset so fallbacks apply.
DEFAULT_REPO = os.environ.get("DESKTOP_ACT_REPO") or _DEFAULT_REPO
@@ -105,10 +106,35 @@ def _resolve_existing() -> Path | None:
if runner:
return runner
+ # Co-installed companion: ops-marketplace ships ./desktop-act next to ./claude-ops
+ plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT")
+ if plugin_root:
+ pr = Path(plugin_root)
+ for candidate in (
+ pr.parent / "desktop-act", # …/ops-marketplace/desktop-act
+ pr / "desktop-act",
+ ):
+ runner = _runner_in(candidate)
+ if runner:
+ return runner
+
for cfg in _claude_config_dirs():
- runner = _runner_in(cfg / "plugins" / "marketplaces" / "desktop-act")
- if runner:
- return runner
+ # Prefer same marketplace as ops (ops-marketplace/desktop-act)
+ for rel in (
+ Path("plugins") / "marketplaces" / "ops-marketplace" / "desktop-act",
+ Path("plugins") / "marketplaces" / "desktop-act",
+ Path("plugins") / "cache" / "ops-marketplace" / "desktop-act",
+ ):
+ runner = _runner_in(cfg / rel)
+ if runner:
+ return runner
+ # Any installed desktop-act plugin cache version
+ cache_root = cfg / "plugins" / "cache" / "ops-marketplace"
+ if cache_root.is_dir():
+ for child in sorted(cache_root.glob("desktop-act/*"), reverse=True):
+ runner = _runner_in(child)
+ if runner:
+ return runner
cache_src = _cache_root() / "src"
runner = _runner_in(cache_src)
diff --git a/claude-ops/plugin-dependencies.json b/claude-ops/plugin-dependencies.json
new file mode 100644
index 00000000..4ee07238
--- /dev/null
+++ b/claude-ops/plugin-dependencies.json
@@ -0,0 +1,74 @@
+{
+ "_comment": "SSOT for companion plugins. Read by scripts/install-companions.sh and bin/ops-update. No host paths, no personal data.",
+ "marketplace": "ops-marketplace",
+ "companions": [
+ {
+ "name": "desktop-act",
+ "marketplaceId": "ops-marketplace",
+ "marketplaceAdd": null,
+ "installCli": "claude plugin install desktop-act@ops-marketplace",
+ "updateCli": "claude plugin update desktop-act@ops-marketplace",
+ "installScript": "scripts/install-desktop-act-companion.sh",
+ "sameMarketplaceAsOps": true,
+ "coInstallDefault": true,
+ "updateWithOps": "always",
+ "userConfigGate": "desktop_act_co_install",
+ "prefsKey": "plugins.desktop_act",
+ "detect": {
+ "find": "*/desktop-act/*plugin.json"
+ },
+ "reason": "MCP companion for /ops:desktop and unattended captcha cascade"
+ },
+ {
+ "name": "gsd",
+ "marketplaceId": "gsd-build-get-shit-done",
+ "marketplaceAdd": "gsd-build/get-shit-done",
+ "installCli": "claude plugin install gsd@gsd-build-get-shit-done",
+ "updateCli": "claude plugin update gsd@gsd-build-get-shit-done",
+ "sameMarketplaceAsOps": false,
+ "coInstallDefault": true,
+ "updateWithOps": "if-installed",
+ "prefsKey": "plugins.gsd",
+ "detect": {
+ "find": "*/skills/gsd-progress*"
+ },
+ "reason": "Project roadmap phases for /ops:go and /ops:projects"
+ },
+ {
+ "name": "superpowers",
+ "marketplaceId": "superpowers-marketplace",
+ "marketplaceAdd": "obra/superpowers-marketplace",
+ "installCli": "claude plugin install superpowers@superpowers-marketplace",
+ "updateCli": "claude plugin update superpowers@superpowers-marketplace",
+ "sameMarketplaceAsOps": false,
+ "coInstallDefault": true,
+ "updateWithOps": "if-installed",
+ "prefsKey": "plugins.superpowers",
+ "detect": {
+ "find": "*/superpowers/skills/using-superpowers*"
+ },
+ "reason": "Verification/dispatch/debug guardrails for ops merge and triage skills"
+ },
+ {
+ "name": "feature-dev",
+ "marketplaceId": "claude-plugins-official",
+ "marketplaceAdd": null,
+ "installCli": "claude plugin install feature-dev@claude-plugins-official",
+ "updateCli": "claude plugin update feature-dev@claude-plugins-official",
+ "sameMarketplaceAsOps": false,
+ "coInstallDefault": true,
+ "updateWithOps": "if-installed",
+ "prefsKey": "plugins.feature_dev",
+ "detect": {
+ "find": "*/feature-dev/*/agents/code-explorer.md"
+ },
+ "reason": "Structured explore/architect/review agents for /ops:ops-feature-dev"
+ }
+ ],
+ "_not_managed": [
+ {
+ "name": "gstack",
+ "note": "Not installed or registered by claude-ops setup. Do not co-update unless added to companions with a verified marketplace id."
+ }
+ ]
+}
diff --git a/claude-ops/scripts/install-companions.sh b/claude-ops/scripts/install-companions.sh
new file mode 100755
index 00000000..90250f54
--- /dev/null
+++ b/claude-ops/scripts/install-companions.sh
@@ -0,0 +1,178 @@
+#!/usr/bin/env bash
+# install-companions.sh — install and/or update companion plugins declared in
+# plugin-dependencies.json (same repo as ops).
+#
+# Usage:
+# bash scripts/install-companions.sh # install missing + update always
+# bash scripts/install-companions.sh --update-only # only updateWithOps companions
+# bash scripts/install-companions.sh --status
+# bash scripts/install-companions.sh --dry-run
+# bash scripts/install-companions.sh --no-external # same-marketplace only
+#
+# Env:
+# CLAUDE_PLUGIN_ROOT ops plugin root
+# OPS_SKIP_COMPANIONS=1 no-op exit 0
+# desktop_act_co_install / userConfig gates via prefs optional (best-effort)
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "${SCRIPT_DIR}/.." && pwd)}"
+DEPS_JSON="${PLUGIN_ROOT}/plugin-dependencies.json"
+PLUGINS_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/plugins"
+
+STATUS_ONLY=0
+DRY_RUN=0
+UPDATE_ONLY=0
+NO_EXTERNAL=0
+for arg in "$@"; do
+ case "$arg" in
+ --status) STATUS_ONLY=1 ;;
+ --dry-run) DRY_RUN=1 ;;
+ --update-only) UPDATE_ONLY=1 ;;
+ --no-external) NO_EXTERNAL=1 ;;
+ -h|--help) sed -n '2,20p' "$0"; exit 0 ;;
+ esac
+done
+
+if [[ "${OPS_SKIP_COMPANIONS:-0}" == "1" ]]; then
+ echo "companions: skipped (OPS_SKIP_COMPANIONS=1)"
+ exit 0
+fi
+
+if [[ ! -f "$DEPS_JSON" ]]; then
+ echo "companions: no plugin-dependencies.json at $DEPS_JSON" >&2
+ exit 0
+fi
+
+command -v jq >/dev/null 2>&1 || { echo "companions: jq required" >&2; exit 1; }
+
+is_installed() {
+ local name="$1" find_pat="$2"
+ if [[ -n "$find_pat" ]]; then
+ find "$PLUGINS_DIR" -path "$find_pat" 2>/dev/null | head -1 | grep -q . && return 0
+ fi
+ # cache dir presence
+ find "$PLUGINS_DIR/cache" -type d -name "$name" 2>/dev/null | head -1 | grep -q . && return 0
+ # installed_plugins.json mention
+ if [[ -f "$PLUGINS_DIR/installed_plugins.json" ]]; then
+ jq -e --arg n "$name" '..|strings?|select(test($n))' "$PLUGINS_DIR/installed_plugins.json" >/dev/null 2>&1 && return 0
+ fi
+ return 1
+}
+
+run_cmd() {
+ if [[ "$DRY_RUN" -eq 1 ]]; then
+ echo " [dry-run] $*"
+ return 0
+ fi
+ eval "$@"
+}
+
+n_ok=0
+n_skip=0
+n_fail=0
+
+while IFS= read -r row; do
+ name="$(echo "$row" | jq -r '.name')"
+ mkt="$(echo "$row" | jq -r '.marketplaceId // empty')"
+ mkt_add="$(echo "$row" | jq -r '.marketplaceAdd // empty')"
+ install_cli="$(echo "$row" | jq -r '.installCli // empty')"
+ update_cli="$(echo "$row" | jq -r '.updateCli // empty')"
+ install_script="$(echo "$row" | jq -r '.installScript // empty')"
+ same_mp="$(echo "$row" | jq -r '.sameMarketplaceAsOps // false')"
+ update_mode="$(echo "$row" | jq -r '.updateWithOps // "never"')"
+ find_pat="$(echo "$row" | jq -r '.detect.find // empty')"
+ co_default="$(echo "$row" | jq -r '.coInstallDefault // false')"
+
+ if [[ "$NO_EXTERNAL" -eq 1 && "$same_mp" != "true" ]]; then
+ echo "skip $name (external marketplace, --no-external)"
+ n_skip=$((n_skip + 1))
+ continue
+ fi
+
+ installed=0
+ if is_installed "$name" "$find_pat"; then
+ installed=1
+ fi
+
+ if [[ "$STATUS_ONLY" -eq 1 ]]; then
+ if [[ "$installed" -eq 1 ]]; then
+ echo "$name: installed"
+ else
+ echo "$name: missing"
+ fi
+ continue
+ fi
+
+ # updateWithOps: always | if-installed | never
+ if [[ "$update_mode" == "never" ]]; then
+ echo "skip $name (updateWithOps=never)"
+ n_skip=$((n_skip + 1))
+ continue
+ fi
+
+ if [[ "$UPDATE_ONLY" -eq 1 && "$installed" -eq 0 ]]; then
+ echo "skip $name (not installed, --update-only)"
+ n_skip=$((n_skip + 1))
+ continue
+ fi
+
+ if [[ "$installed" -eq 0 && "$UPDATE_ONLY" -eq 0 ]]; then
+ # install path
+ if [[ "$co_default" != "true" && "$update_mode" != "always" ]]; then
+ echo "skip $name (not installed, coInstallDefault=false)"
+ n_skip=$((n_skip + 1))
+ continue
+ fi
+ echo "install $name …"
+ if [[ -n "$install_script" && -f "$PLUGIN_ROOT/$install_script" ]]; then
+ if run_cmd "bash \"$PLUGIN_ROOT/$install_script\""; then
+ echo "ok: $name (script)"; n_ok=$((n_ok + 1)); continue
+ fi
+ fi
+ if [[ -n "$mkt_add" ]]; then
+ run_cmd "claude plugin marketplace add \"$mkt_add\" >/dev/null 2>&1 || true"
+ fi
+ if [[ -n "$install_cli" ]]; then
+ if run_cmd "$install_cli >/dev/null 2>&1"; then
+ echo "ok: $name (install)"; n_ok=$((n_ok + 1))
+ else
+ echo "fail: $name install" >&2; n_fail=$((n_fail + 1))
+ fi
+ else
+ echo "fail: $name no installCli" >&2; n_fail=$((n_fail + 1))
+ fi
+ continue
+ fi
+
+ # update path (installed)
+ echo "update $name …"
+ if [[ "$same_mp" != "true" && -n "$mkt" ]]; then
+ run_cmd "claude plugin marketplace update \"$mkt\" >/dev/null 2>&1 || true"
+ fi
+ if [[ -n "$update_cli" ]]; then
+ if run_cmd "$update_cli >/dev/null 2>&1"; then
+ echo "ok: $name (update)"; n_ok=$((n_ok + 1))
+ else
+ # reinstall fallback
+ if [[ -n "$install_cli" ]] && run_cmd "$install_cli >/dev/null 2>&1"; then
+ echo "ok: $name (reinstall fallback)"; n_ok=$((n_ok + 1))
+ else
+ echo "warn: $name update non-zero (non-fatal)" >&2
+ n_fail=$((n_fail + 1))
+ fi
+ fi
+ elif [[ -n "$install_script" && -f "$PLUGIN_ROOT/$install_script" ]]; then
+ run_cmd "bash \"$PLUGIN_ROOT/$install_script\"" && echo "ok: $name (script)" && n_ok=$((n_ok + 1))
+ else
+ echo "skip $name (no updateCli)"; n_skip=$((n_skip + 1))
+ fi
+done < <(jq -c '.companions[]' "$DEPS_JSON")
+
+if [[ "$STATUS_ONLY" -eq 1 ]]; then
+ exit 0
+fi
+
+echo "companions: ok=$n_ok skip=$n_skip fail=$n_fail"
+# never fail ops-update over companions
+exit 0
diff --git a/claude-ops/scripts/install-desktop-act-companion.sh b/claude-ops/scripts/install-desktop-act-companion.sh
new file mode 100755
index 00000000..37ed6f83
--- /dev/null
+++ b/claude-ops/scripts/install-desktop-act-companion.sh
@@ -0,0 +1,107 @@
+#!/usr/bin/env bash
+# install-desktop-act-companion.sh — co-install the desktop-act plugin from the
+# same ops-marketplace that ships claude-ops.
+#
+# Idempotent. No host-specific paths. Prefer Claude plugin CLI; fall back to
+# ensuring the marketplace checkout contains ./desktop-act (vendored source).
+#
+# Usage:
+# bash scripts/install-desktop-act-companion.sh
+# bash scripts/install-desktop-act-companion.sh --status
+# bash scripts/install-desktop-act-companion.sh --dry-run
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "${SCRIPT_DIR}/.." && pwd)}"
+# Marketplace root is parent of the ops plugin source when layout is repo/claude-ops/
+MARKETPLACE_ROOT="${OPS_MARKETPLACE_ROOT:-}"
+if [[ -z "$MARKETPLACE_ROOT" ]]; then
+ if [[ -f "${PLUGIN_ROOT}/../.claude-plugin/marketplace.json" ]]; then
+ MARKETPLACE_ROOT="$(cd "${PLUGIN_ROOT}/.." && pwd)"
+ elif [[ -f "${PLUGIN_ROOT}/.claude-plugin/marketplace.json" ]]; then
+ MARKETPLACE_ROOT="$PLUGIN_ROOT"
+ else
+ # Installed cache: …/cache/ops-marketplace/ops/<ver> → marketplaces/ops-marketplace
+ CANDIDATE="$(cd "${PLUGIN_ROOT}/../../.." 2>/dev/null && pwd || true)"
+ if [[ -n "$CANDIDATE" && -f "${CANDIDATE}/.claude-plugin/marketplace.json" ]]; then
+ MARKETPLACE_ROOT="$CANDIDATE"
+ fi
+ fi
+fi
+
+STATUS_ONLY=0
+DRY_RUN=0
+for arg in "$@"; do
+ case "$arg" in
+ --status) STATUS_ONLY=1 ;;
+ --dry-run) DRY_RUN=1 ;;
+ -h|--help)
+ sed -n '2,20p' "$0"
+ exit 0
+ ;;
+ esac
+done
+
+desktop_act_present() {
+ # Installed as a Claude Code plugin
+ if find "${HOME}/.claude/plugins" -path '*/desktop-act/*plugin.json' 2>/dev/null | head -1 | grep -q .; then
+ return 0
+ fi
+ # Vendored next to marketplace / ops plugin
+ if [[ -n "${MARKETPLACE_ROOT:-}" && -f "${MARKETPLACE_ROOT}/desktop-act/.claude-plugin/plugin.json" ]]; then
+ return 0
+ fi
+ if [[ -f "${PLUGIN_ROOT}/../desktop-act/.claude-plugin/plugin.json" ]]; then
+ return 0
+ fi
+ return 1
+}
+
+if [[ "$STATUS_ONLY" -eq 1 ]]; then
+ if desktop_act_present; then
+ echo "desktop-act: installed"
+ exit 0
+ fi
+ echo "desktop-act: missing"
+ exit 1
+fi
+
+if desktop_act_present; then
+ echo "ok: desktop-act already available"
+ exit 0
+fi
+
+if [[ "$DRY_RUN" -eq 1 ]]; then
+ echo "dry-run: would install desktop-act@ops-marketplace"
+ exit 0
+fi
+
+# Prefer Claude Code plugin CLI (registers MCP + skills)
+if command -v claude >/dev/null 2>&1; then
+ # Marketplace already present when ops is installed from ops-marketplace
+ if claude plugin install desktop-act@ops-marketplace 2>/dev/null; then
+ echo "ok: desktop-act installed via claude plugin CLI"
+ exit 0
+ fi
+ # Retry after ensuring marketplace is registered
+ if [[ -n "${MARKETPLACE_ROOT:-}" ]]; then
+ claude plugin marketplace add "$MARKETPLACE_ROOT" 2>/dev/null || true
+ else
+ claude plugin marketplace add Lifecycle-Innovations-Limited/claude-ops 2>/dev/null || true
+ fi
+ if claude plugin install desktop-act@ops-marketplace 2>/dev/null; then
+ echo "ok: desktop-act installed via claude plugin CLI (after marketplace add)"
+ exit 0
+ fi
+fi
+
+# Vendored source is enough for the launcher (mcp-servers/desktop-act-launcher.py)
+if [[ -n "${MARKETPLACE_ROOT:-}" && -f "${MARKETPLACE_ROOT}/desktop-act/mcp-server/run.sh" ]]; then
+ echo "ok: desktop-act source present at ${MARKETPLACE_ROOT}/desktop-act (launcher will use it)"
+ exit 0
+fi
+
+echo "error: could not install desktop-act companion" >&2
+echo " try: claude plugin install desktop-act@ops-marketplace" >&2
+echo " or set DESKTOP_ACT_HOME to a checkout with mcp-server/run.sh" >&2
+exit 1
diff --git a/claude-ops/skills/ops-desktop/SKILL.md b/claude-ops/skills/ops-desktop/SKILL.md
index 7587df47..cf0b67ee 100644
--- a/claude-ops/skills/ops-desktop/SKILL.md
+++ b/claude-ops/skills/ops-desktop/SKILL.md
@@ -41,8 +41,8 @@ ToolSearch select:mcp__desktop-act__acquire_desktop,mcp__desktop-act__screenshot
Before any route runs, resolve:
1. **Plugin root**: `${CLAUDE_PLUGIN_ROOT}` — used to locate the launcher.
-2. **MCP launcher**: `${CLAUDE_PLUGIN_ROOT}/mcp-servers/desktop-act-launcher.py` — auto-discovers an installed desktop-act marketplace or, if absent, clones from `$DESKTOP_ACT_REPO` (default `https://github.com/your-org/desktop-act.git`) and bootstraps a venv on first run.
-3. **noVNC default**: `http://<box-host>:6081` — primary desktop. `acquire_desktop()` provisions extra sessions on `:6082+`.
+2. **MCP launcher**: `${CLAUDE_PLUGIN_ROOT}/mcp-servers/desktop-act-launcher.py` — auto-discovers an installed desktop-act marketplace or, if absent, clones from `$DESKTOP_ACT_REPO` (default `https://github.com/Lifecycle-Innovations-Limited/desktop-act.git`) and bootstraps a venv on first run.
+3. **noVNC default**: `http://<box-host>:6082` — primary desktop. `acquire_desktop()` provisions extra sessions on `:6082+`.
4. **Mobile / SSH mode**: if `$SSH_CONNECTION`, `$SSH_CLIENT`, or `$SSH_TTY` is set, emit compact text-only output per Rule 7 (no banners, no tables, plain lines). The noVNC URL is the one piece the user definitely needs — print it once on a copy-able line.
## Routing table
@@ -144,7 +144,7 @@ mcp__desktop-act__screenshot(session_id) # verify
result = mcp__desktop-act__act(
session_id=session_id,
goal="$ARGUMENTS",
- max_steps=20,
+ max_iterations=20,
)
```
diff --git a/claude-ops/skills/ops-update/SKILL.md b/claude-ops/skills/ops-update/SKILL.md
index 9cdb38ea..7604c26e 100644
--- a/claude-ops/skills/ops-update/SKILL.md
+++ b/claude-ops/skills/ops-update/SKILL.md
@@ -25,6 +25,20 @@ The workhorse is **`${CLAUDE_PLUGIN_ROOT}/bin/ops-update`**. It runs a 9-step lo
7. **Migrate** — runs `ops-post-update-migrate` (idempotent, per-version). It also maintains a stable `cache/.../ops/current/` directory (rsynced from the new version and repointed in `installed_plugins.json`) so Claude Code GC'ing the old versioned dir mid-session never causes "Plugin directory does not exist" hook errors.
8. **Local sync** — if a linked local source checkout of this repo is present under `~/Projects`, fast-forwards its `main` to `origin/main` so a dev clone never silently drifts behind the published release. Acts only on a clean `main` (never clobbers uncommitted WIP, a feature branch, or unpushed commits); a no-op when no checkout exists. Skip with `--no-localsync`.
9. **Report** — old→new, what changed, and that a restart / `/reload-plugins` is needed to load it.
+10. **Companions** — `bin/ops-update` step 9 runs `scripts/install-companions.sh`
+ against `plugin-dependencies.json`:
+ - **desktop-act** (`ops-marketplace`) — always co-install/update (gate:
+ `desktop_act_co_install`)
+ - **gsd**, **superpowers**, **feature-dev** — update only if already installed
+ - **gstack** — not managed by claude-ops (not in the matrix)
+
+```bash
+# manual companion pass
+bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-companions.sh"
+bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-companions.sh --status"
+# skip from ops-update:
+${CLAUDE_PLUGIN_ROOT}/bin/ops-update --no-companions
+```
## How to run it
@@ -77,6 +91,7 @@ Code constraint, not a failure.
| `--no-patches` | Skip the cache-patch reapply step. |
| `--no-rewrite` | Skip the stale-version-path rewrite step. |
| `--no-localsync` | Skip fast-forwarding a linked local source checkout's `main`. |
+| `--no-companions` | Skip companion install/update (desktop-act, gsd, superpowers, …). |
## Mobile / SSH (Rule 7)
diff --git a/claude-ops/skills/setup/SKILL.md b/claude-ops/skills/setup/SKILL.md
index b5b11286..95d736d0 100644
--- a/claude-ops/skills/setup/SKILL.md
+++ b/claude-ops/skills/setup/SKILL.md
@@ -247,7 +247,7 @@ Use `AskUserQuestion` with `multiSelect: true`. Offer **only sections that need
| Option | Header | Description |
| ------------------ | -------- | ----------------------------------------------- |
| Configure channels | channels | Set tokens for Telegram, WhatsApp, Email, Slack |
-| Companion plugins | plugins | Install GSD, Superpowers, and feature-dev companion plugins |
+| Companion plugins | plugins | Install desktop-act (ops dep), GSD, Superpowers, feature-dev |
| Save preferences | prefs | Owner name, timezone, default priorities |
| Shell env | env | Export `CLAUDE_PLUGIN_ROOT` in shell profile |
@@ -306,6 +306,49 @@ After installation, re-run `ops-setup-detect` to refresh status before continuin
## Step 2b — Companion plugins (if selected)
+### desktop-act (co-installed ops dependency — default on)
+
+`desktop-act` is listed in the same `ops-marketplace` as the ops plugin and is
+declared in `plugin-dependencies.json` / `plugin.json` `dependencies`. It powers
+`/ops:desktop` and the unattended captcha cascade. Prefer co-install whenever
+ops is installed; do not require a second marketplace add.
+
+Check:
+
+```bash
+bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-desktop-act-companion.sh" --status \
+ && echo "installed" || echo "not_installed"
+```
+
+If `not_installed` and `desktop_act_co_install` is not explicitly false in
+userConfig / prefs, **install without prompting** when the user chose
+"Set up everything" or selected Companion plugins. Otherwise ask:
+
+```
+desktop-act (computer-use MCP) is a companion of ops.
+ Powers /ops:desktop and captcha cascade for unattended re-auth.
+ [Install desktop-act (Recommended)] [Skip]
+```
+
+On install (RULE ZERO — background Bash):
+
+```bash
+bash "${CLAUDE_PLUGIN_ROOT}/scripts/install-desktop-act-companion.sh"
+```
+
+Record `plugins.desktop_act = "installed"` in `$PREFS_PATH` when `--status` passes.
+
+If they skip:
+
+```
+Skipped desktop-act. Install later:
+ claude plugin install desktop-act@ops-marketplace
+ # or
+ bash ${CLAUDE_PLUGIN_ROOT}/scripts/install-desktop-act-companion.sh
+```
+
+---
+
### GSD (Get Shit Done)
GSD is a third-party Claude Code plugin that adds project roadmap tracking. When installed, claude-ops dashboards (`/ops:go`, `/ops:projects`, `/ops:next`, `/ops:yolo`) automatically show active phases, progress, and next actions per project. Without it, those sections are simply omitted.
@@ -422,7 +465,7 @@ On install, try the Claude Code plugin CLI when available:
```bash
# Cursor / Claude Code — plugin id varies by marketplace; verify with: claude plugin list
-claude plugin install feature-dev 2>/dev/null || true
+claude plugin install feature-dev@claude-plugins-official 2>/dev/null || true
```
Re-check with the find command above. If still `not_installed`, tell the user to install **feature-dev** from Cursor Settings → Plugins (or their Claude Code marketplace UI), then re-run `/ops:setup`.
diff --git a/desktop-act/.claude-plugin/marketplace.json b/desktop-act/.claude-plugin/marketplace.json
new file mode 100644
index 00000000..6f18a163
--- /dev/null
+++ b/desktop-act/.claude-plugin/marketplace.json
@@ -0,0 +1,32 @@
+{
+ "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
+ "name": "desktop-act",
+ "description": "Single-plugin marketplace for the desktop-act MCP server",
+ "owner": {
+ "name": "Lifecycle Innovations Limited"
+ },
+ "plugins": [
+ {
+ "name": "desktop-act",
+ "description": "Computer-use primitives + multi-desktop pool + autonomous act() loop. Screenshot, click, type, keypress, scroll, launch_app over platform backends (X11/Xvnc, macOS, Windows). Auth via claude-agent-sdk OAuth \u2014 no API key required.",
+ "source": "./",
+ "version": "0.2.0",
+ "category": "automation",
+ "keywords": [
+ "computer-use",
+ "desktop",
+ "automation",
+ "x11",
+ "vnc",
+ "novnc",
+ "screenshot",
+ "browser",
+ "mcp",
+ "fastmcp",
+ "oauth",
+ "claude-agent-sdk",
+ "agentic"
+ ]
+ }
+ ]
+}
diff --git a/desktop-act/.claude-plugin/plugin.json b/desktop-act/.claude-plugin/plugin.json
new file mode 100644
index 00000000..c2e1e143
--- /dev/null
+++ b/desktop-act/.claude-plugin/plugin.json
@@ -0,0 +1,34 @@
+{
+ "name": "desktop-act",
+ "version": "0.2.0",
+ "description": "Computer-use primitives + multi-desktop pool + autonomous act() loop. Screenshot, click, type, keypress, scroll, launch_app over platform backends (X11/Xvnc, macOS, Windows). Auth via claude-agent-sdk OAuth \u2014 no API key required.",
+ "author": {
+ "name": "Lifecycle Innovations Limited",
+ "url": "https://github.com/Lifecycle-Innovations-Limited"
+ },
+ "homepage": "https://github.com/Lifecycle-Innovations-Limited/desktop-act",
+ "repository": "https://github.com/Lifecycle-Innovations-Limited/desktop-act",
+ "license": "MIT",
+ "keywords": [
+ "computer-use",
+ "desktop",
+ "automation",
+ "mcp",
+ "fastmcp",
+ "x11",
+ "vnc",
+ "screenshot"
+ ],
+ "skills": [
+ "skills/desktop-act"
+ ],
+ "commands": [
+ "commands/act.md"
+ ],
+ "mcpServers": {
+ "desktop-act": {
+ "type": "stdio",
+ "command": "${CLAUDE_PLUGIN_ROOT}/mcp-server/run.sh"
+ }
+ }
+}
diff --git a/desktop-act/.cursor/approval-policies/ROUTING.md b/desktop-act/.cursor/approval-policies/ROUTING.md
new file mode 100644
index 00000000..7be5b41d
--- /dev/null
+++ b/desktop-act/.cursor/approval-policies/ROUTING.md
@@ -0,0 +1,19 @@
+- product: Documentation
+ boundary: "{docs/**,**/README.md,**/CHANGELOG.md,**/*.md}"
+ policies:
+ - .cursor/approval-policies/docs-policy.md
+
+- product: CI and workflows
+ boundary: ".github/workflows/**"
+ policies:
+ - .cursor/approval-policies/ci-policy.md
+
+- product: Tests
+ boundary: "{**/test/**,**/tests/**,**/*.test.*,**/*.spec.*,e2e/**}"
+ policies:
+ - .cursor/approval-policies/tests-policy.md
+
+- product: Application runtime
+ boundary: "{src/**,app/**,lib/**,packages/**,convex/**,agents/**,lambdas/**}"
+ policies:
+ - .cursor/approval-policies/runtime-policy.md
diff --git a/desktop-act/.cursor/approval-policies/ci-policy.md b/desktop-act/.cursor/approval-policies/ci-policy.md
new file mode 100644
index 00000000..1dd872c7
--- /dev/null
+++ b/desktop-act/.cursor/approval-policies/ci-policy.md
@@ -0,0 +1,9 @@
+# CI workflow approval policy
+
+## Default posture
+Never auto-approve workflow changes.
+
+## Human review must verify
+- Required checks are not removed without replacement
+- Permissions blocks are not unnecessarily broadened
+- Deploy/release gates remain intact
diff --git a/desktop-act/.cursor/approval-policies/docs-policy.md b/desktop-act/.cursor/approval-policies/docs-policy.md
new file mode 100644
index 00000000..31ab7650
--- /dev/null
+++ b/desktop-act/.cursor/approval-policies/docs-policy.md
@@ -0,0 +1,9 @@
+# Documentation approval policy
+
+## Auto-approve when
+- Markdown/copy-only changes with no executable code
+- Bugbot and Security Agent report no findings
+
+## Never auto-approve
+- Embedded secrets, tokens, or private infrastructure endpoints
+- Bundled runtime changes in the same PR
diff --git a/desktop-act/.cursor/approval-policies/runtime-policy.md b/desktop-act/.cursor/approval-policies/runtime-policy.md
new file mode 100644
index 00000000..f71676be
--- /dev/null
+++ b/desktop-act/.cursor/approval-policies/runtime-policy.md
@@ -0,0 +1,8 @@
+# Application runtime approval policy
+
+## Auto-approve when
+- Small localized fix with tests and clean automated review
+- No auth, billing, health-data, or deploy config impact
+
+## Never auto-approve
+- Broad refactors, new external integrations, or removed guardrails
diff --git a/desktop-act/.cursor/approval-policies/tests-policy.md b/desktop-act/.cursor/approval-policies/tests-policy.md
new file mode 100644
index 00000000..07057434
--- /dev/null
+++ b/desktop-act/.cursor/approval-policies/tests-policy.md
@@ -0,0 +1,8 @@
+# Tests approval policy
+
+## Auto-approve when
+- Test-only changes with unchanged production logic
+- CI green; Bugbot/Security clean
+
+## Never auto-approve
+- Disabled/skipped tests paired with production logic changes
diff --git a/desktop-act/.github/workflows/ci.yml b/desktop-act/.github/workflows/ci.yml
new file mode 100644
index 00000000..6c2f3c19
--- /dev/null
+++ b/desktop-act/.github/workflows/ci.yml
@@ -0,0 +1,90 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ lint-test:
+ name: lint + unit (${{ matrix.os }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ python-version: ["3.11"]
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install tooling
+ run: |
+ python -m pip install --upgrade pip
+ pip install ruff pytest
+ pip install -r requirements.txt
+
+ - name: Ruff check
+ run: ruff check mcp-server cli tests
+
+ - name: Ruff format check
+ run: ruff format --check mcp-server cli tests
+
+ - name: Syntax compile
+ run: |
+ python -m py_compile mcp-server/server.py
+ python -m py_compile cli/desktop_act_cli.py
+
+ - name: Unit tests (lease helpers)
+ env:
+ DESKTOP_ACT_REAP_INTERVAL: "0"
+ DESKTOP_ACT_RELEASE_ON_EXIT: "0"
+ run: pytest -q tests/
+
+ - name: CLI help smoke
+ shell: bash
+ run: python cli/desktop_act_cli.py -h | head -40
+
+ e2e-linux-pool:
+ name: e2e pool ensure (linux)
+ runs-on: ubuntu-latest
+ needs: lint-test
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Install system deps
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y -qq tigervnc-standalone-server websockify openbox xterm
+ - name: Bootstrap venv
+ run: |
+ python -m venv .venv
+ .venv/bin/pip install -q -r requirements.txt
+ - name: Dual-owner ensure smoke
+ env:
+ DESKTOP_ACT_HOME: ${{ github.workspace }}
+ DESKTOP_ACT_COMMAND: ${{ github.workspace }}/mcp-server/run.sh
+ DESKTOP_ACT_VENV: ${{ github.workspace }}/.venv
+ DESKTOP_ACT_GEOMETRY: 1280x800
+ DESKTOP_ACT_LEASE_TTL: "120"
+ DESKTOP_ACT_REAP_INTERVAL: "0"
+ DESKTOP_ACT_RELEASE_ON_EXIT: "0"
+ run: |
+ chmod +x cli/desktop-act mcp-server/run.sh
+ set -euo pipefail
+ A=$(./cli/desktop-act ensure --owner-id ci-a --geometry 1280x800)
+ B=$(./cli/desktop-act ensure --owner-id ci-b --geometry 1280x800)
+ echo "$A" | python -c "import sys,json;d=json.load(sys.stdin);assert d.get('ok') and d.get('session_id');print('A',d['display'],d['session_id'])"
+ echo "$B" | python -c "import sys,json;d=json.load(sys.stdin);assert d.get('ok') and d.get('session_id');print('B',d['display'],d['session_id'])"
+ SID_A=$(echo "$A" | python -c "import sys,json;print(json.load(sys.stdin)['session_id'])")
+ SID_B=$(echo "$B" | python -c "import sys,json;print(json.load(sys.stdin)['session_id'])")
+ test "$SID_A" != "$SID_B"
+ ./cli/desktop-act release --session-id "$SID_A"
+ ./cli/desktop-act release --session-id "$SID_B"
diff --git a/desktop-act/.gitignore b/desktop-act/.gitignore
new file mode 100644
index 00000000..3ea007c0
--- /dev/null
+++ b/desktop-act/.gitignore
@@ -0,0 +1,9 @@
+daemon/*
+!daemon/.gitkeep
+.DS_Store
+logs/*
+!logs/.gitkeep
+*.pyc
+__pycache__/
+*.pyo
+.venv/
diff --git a/desktop-act/APPROVAL_POLICY.md b/desktop-act/APPROVAL_POLICY.md
new file mode 100644
index 00000000..62535e95
--- /dev/null
+++ b/desktop-act/APPROVAL_POLICY.md
@@ -0,0 +1,37 @@
+# desktop-act — default approval policy
+
+Repository-wide rules for Cursor Approval Agents evaluating pull requests in this repo.
+
+## Purpose
+
+desktop-act default approval policy for Cursor Approval Agents.
+
+Default posture: **approve only when risk is low and automated review is clean**.
+
+## Auto-approve when ALL are true
+
+- Bugbot Review Context reports no findings requiring human review
+- Security Review Context reports no findings requiring human review (when enabled)
+- Risk score is at or below the agent's configured maximum threshold
+- CI checks required for the changed paths are green
+- PR does not modify approval policy files or routing files
+- Documentation-only or test-only PRs (≤ 300 lines excluding lockfiles)
+
+## Never auto-approve
+
+- GitHub Actions workflow changes that weaken CI, skip tests, or broaden deploy permissions
+- Deletions or relaxations of auth, security, or safety guardrails
+- Changes that remove tests, disable lint/typecheck, or bypass pre-commit hooks
+- PRs labeled `security`, `breaking`, or `do-not-auto-approve`
+
+## Reviewer routing
+
+When auto-approval is not allowed, request repo maintainers or the appropriate team for the changed area. Leave the PR unapproved with a short comment if reviewer assignment is unavailable.
+
+## Deploy expectations
+
+For changes shipping dev → staging → main → production: do not auto-approve solely on green CI if production paths, migrations, or release config changed.
+
+## Conflict resolution
+
+Follow the most specific applicable policy. If unclear, follow the stricter rule and do not auto-approve.
diff --git a/desktop-act/LICENSE b/desktop-act/LICENSE
new file mode 100644
index 00000000..9483c070
--- /dev/null
+++ b/desktop-act/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Lifecycle Innovations Limited
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/desktop-act/README.md b/desktop-act/README.md
new file mode 100644
index 00000000..732c5294
--- /dev/null
+++ b/desktop-act/README.md
@@ -0,0 +1,311 @@
+# desktop-act
+
+> Computer-use primitives + multi-desktop pool + autonomous `act()` loop for
+> Claude Code. One MCP server, no API key.
+
+`desktop-act` lets Claude (or any MCP client) drive a desktop: screenshot it,
+click, type, scroll, launch apps, run a goal-driven loop. It is **OS-agnostic** —
+a backend is selected at startup from `platform.system()`:
+
+- **Linux (`X11Backend`):** python-xlib primitives + a pooled Xvnc/websockify
+ backend so you can spin up isolated desktops on demand, each streamed over
+ noVNC for live viewing.
+- **macOS (`MacBackend`):** `screencapture` for frames, `cliclick`/`osascript`
+ for input, and the single real logged-in session (no Xvnc pool). Built-in
+ Screen Sharing (VNC :5900) is bridged to noVNC via `websockify` when enabled.
+- **Windows (`WinBackend`):** Pillow `ImageGrab` for frames, `pyautogui` (or
+ ctypes `SendInput` fallback) for mouse/keyboard, `EnumWindows` for window
+ list, `os.startfile` / shell for launch. Single interactive desktop (lease
+ model matches macOS — no multi-seat VNC pool).
+
+All tool signatures and return shapes are identical across backends, so callers
+never need to know which platform they're on.
+
+Auth path is **Claude CLI OAuth via `claude-agent-sdk`** — costs ride on a
+Claude Max subscription, no `ANTHROPIC_API_KEY` needed.
+
+---
+
+## Install
+
+### With claude-ops (recommended)
+
+[`claude-ops`](https://github.com/Lifecycle-Innovations-Limited/claude-ops) ships
+this plugin in the same **ops-marketplace** and co-installs it with ops:
+
+```text
+/plugin marketplace add Lifecycle-Innovations-Limited/claude-ops
+/plugin install ops@ops-marketplace
+/plugin install desktop-act@ops-marketplace
+# or let /ops:setup and /ops:update run scripts/install-companions.sh
+```
+
+The ops `desktop-act-launcher.py` resolves the marketplace checkout first, then
+falls back to a per-user cache clone (`$XDG_CACHE_HOME/desktop-act-mcp` on
+Linux, `~/Library/Caches/desktop-act-mcp` on macOS, `%LOCALAPPDATA%\desktop-act-mcp`
+on Windows) when `$DESKTOP_ACT_REPO` is set.
+
+### Standalone Claude Code plugin
+
+```text
+/plugin marketplace add Lifecycle-Innovations-Limited/desktop-act
+/plugin install desktop-act@desktop-act
+```
+
+### Manual
+
+```bash
+git clone https://github.com/Lifecycle-Innovations-Limited/desktop-act.git
+# Point your MCP host at desktop-act/mcp-server/run.sh (stdio transport)
+```
+
+The first invocation auto-bootstraps a Python venv at `${CLAUDE_PLUGIN_ROOT}/.venv`
+(or `$DESKTOP_ACT_VENV` if set) from `requirements.txt` (**Python 3.11+**).
+
+### System dependencies
+
+#### Linux (X11Backend)
+
+You need an X11 stack and a VNC server reachable as `Xvnc` (TigerVNC):
+
+```bash
+# Amazon Linux 2023 / RHEL / Fedora
+sudo dnf install -y tigervnc-server websockify metacity xterm python3
+
+# Ubuntu / Debian
+sudo apt install -y tigervnc-standalone-server websockify metacity xterm python3-venv
+```
+
+Optional but recommended: `openbox`, `xdotool`, `firefox`, `nautilus`,
+`libreoffice` (whatever GUI apps you want to drive).
+
+#### macOS (MacBackend)
+
+Input is driven by [`cliclick`](https://github.com/BlueM/cliclick); everything
+else (`screencapture`, `osascript`, `open`) is built into macOS.
+
+```bash
+brew install cliclick
+# Optional — for a live noVNC view bridged off built-in Screen Sharing:
+brew install websockify # (or: pip install websockify)
+```
+
+**Required macOS permissions** (System Settings → Privacy & Security):
+
+- **Screen Recording** — for `screenshot`/`observe`/`act_step` (the
+ `screencapture` capture path). Without it, captures fail with
+ `could not create image from display`.
+- **Accessibility** — for `click`/`type_text`/`keypress`/`scroll` (the
+ `cliclick` and System Events input path).
+
+Grant both to the host process driving the MCP server (your terminal, Claude
+Code, etc.). For a live view, optionally enable **Screen Sharing** (System
+Settings → General → Sharing → Screen Sharing); `acquire_desktop` still returns
+a session without it and surfaces a `vnc_hint`.
+
+#### Windows (WinBackend)
+
+Runs against the **logged-in interactive session** (same machine the MCP host
+is on). No Xvnc pool — multi-agent exclusive leases still apply, but there is
+only one real desktop (`win-main`).
+
+```powershell
+# Python 3.11+ (see pyproject.toml requires-python); venv from requirements.txt
+py -3 -m venv .venv
+.\.venv\Scripts\pip install -r requirements.txt
+# pyautogui is installed only on win32 (see requirements marker)
+```
+
+**Requirements / limits:**
+
+- An interactive desktop session (console or RDP with a real desktop). Pure
+ headless / Session 0 service accounts cannot drive GUI input.
+- Optional: install a browser or app you want `launch_app` to start
+ (`chrome`, `notepad`, path to `.exe` / `.lnk`).
+- `pyautogui` is preferred; if it is missing, WinBackend uses ctypes
+ `SendInput` + clipboard paste for `type_text`.
+- Multi-seat isolation is Linux-only. On Windows, concurrent agents share one
+ screen and must coordinate via leases (`ensure_desktop` / `heartbeat_desktop`).
+
+---
+
+## Tools exposed by the MCP server
+
+| Tool | Purpose |
+|-----------------------|--------------------------------------------------------------|
+| `ensure_desktop` | Exclusive lease; Linux auto-spawns seat if busy |
+| `acquire_desktop` | Spawn/attach desktop (Linux pool; single seat on mac/Win) |
+| `heartbeat_desktop` | Refresh exclusive lease during long work |
+| `release_desktop` | Free lease; Linux stops pool VNC |
+| `list_desktops` | Inspect pool / lease state |
+| `reap_idle_desktops` | Free expired leases (Linux also stops idle VNC) |
+| `screenshot` | Grab the display (JPEG default, SHA-deduped) |
+| `observe` | Screenshot + window list in one round-trip |
+| `list_windows` | Enumerate top-level windows + geometry |
+| `launch_app` | Spawn a GUI app (`command` argument) |
+| `click` | Absolute-coord mouse click |
+| `keypress` | Press a key chord |
+| `type_text` | Type a string into the focused window |
+| `scroll` | Scroll wheel |
+| `batch` | Execute many primitives in one MCP round-trip |
+| `act` | Goal loop via `claude-agent-sdk` (`max_iterations`, default model `claude-sonnet-5`) |
+| `act_step` | Single-step variant |
+| `status` | Pool + binary inventory |
+
+A `/desktop:act <goal>` slash command is also registered.
+
+---
+
+## Configuration
+
+All knobs are environment variables — no config file required.
+
+| Env var | Default | Meaning |
+|----------------------------------|---------------------------------|-----------------------------------------|
+| `CLAUDE_PLUGIN_ROOT` | (set by Claude Code) | Plugin root for logs + venv |
+| `DESKTOP_ACT_DISPLAY` | `:1` | Default display when no `session_id` |
+| `DESKTOP_ACT_DISPLAY_MIN`/`MAX` | `50` / `99` | Pool display number range |
+| `DESKTOP_ACT_VNC_PORT_BASE` | `5900` | Pool VNC port base (display N → 5900+N) |
+| `DESKTOP_ACT_NOVNC_PORT_BASE` | `6082` | noVNC websockify port base |
+| `DESKTOP_ACT_GEOMETRY` | `2560x1440` | Default geometry for new desktops |
+| `DESKTOP_ACT_OWNER` | (process/agent id) | Exclusive lease owner id |
+| `DESKTOP_ACT_LEASE_TTL` | `600` | Lease seconds; idle past this → reaped |
+| `DESKTOP_ACT_REAP_INTERVAL` | `30` | Background reaper tick (0 = off) |
+| `DESKTOP_ACT_REAP_ON_IDLE` | `1` | Free lock + stop VNC when lease expires |
+| `DESKTOP_ACT_AUTO_SPAWN` | `1` | Spawn new desktop if others are busy |
+| `DESKTOP_ACT_RELEASE_ON_EXIT` | `1` (CLI forces `0`) | Free owned pool seats when process ends |
+| `DESKTOP_ACT_TMP` | `/tmp` | Where pool state + screenshots live |
+| `DESKTOP_ACT_LOG_DIR` | `$CLAUDE_PLUGIN_ROOT/logs` | Where session logs go |
+| `DESKTOP_ACT_VENV` | `$CLAUDE_PLUGIN_ROOT/.venv` | Venv location |
+| `DESKTOP_ACT_PYTHON` | `python3` | Bootstrap interpreter |
+| `CLAUDE_CLI_PATH` | `which claude` | Path to `claude` CLI for `act()` |
+
+---
+
+## Usage patterns
+
+### Streaming primitives (recommended)
+
+Let the parent session drive the loop — call primitives, Read screenshots,
+decide, repeat. Every action is visible in the chat transcript.
+
+```text
+mcp__desktop-act__ensure_desktop(owner_id="agent-a") # → exclusive session_id
+mcp__desktop-act__launch_app(session_id, "firefox")
+mcp__desktop-act__screenshot(session_id) # → /tmp/desktop-act-shots/…jpg
+mcp__desktop-act__click(session_id, 640, 400)
+mcp__desktop-act__heartbeat_desktop(session_id) # keep lease during long work
+mcp__desktop-act__release_desktop(session_id) # always on agent stop
+```
+
+### Multi-agent (concurrent desktops)
+
+Each agent must use its own `owner_id` (or set `DESKTOP_ACT_OWNER`):
+
+1. `ensure_desktop(owner_id=…)` reuses that agent's lease, or **auto-spawns** a new
+ Xvnc + noVNC on the next free display/port if every seat is leased.
+2. Leases expire after `DESKTOP_ACT_LEASE_TTL` (default 600s) without heartbeat.
+3. Background reaper (every `DESKTOP_ACT_REAP_INTERVAL`) and process exit/SIGTERM:
+ **free the lock and stop pool VNC** (Xvnc + websockify) so idle seats do not
+ thrash the host. The host default display (e.g. reauth Chrome on `:1`) is never
+ reaped — only pool sessions (`:50`–`:99`).
+
+```text
+# Agent A
+ensure_desktop(owner_id="agent-a", geometry="2560x1440") # → :50
+# Agent B (while A still holds :50)
+ensure_desktop(owner_id="agent-b", geometry="2560x1440") # → :51 auto-spawn
+# Agent A stops / idle past TTL
+release_desktop / reaper → free lock, kill VNC on :50
+```
+
+CLI:
+
+```bash
+./cli/desktop-act ensure --owner-id agent-a --geometry 2560x1440
+./cli/desktop-act heartbeat --session-id desk-… --owner-id agent-a
+./cli/desktop-act reap
+./cli/desktop-act release --session-id desk-…
+```
+
+### Autonomous goal loop
+
+```text
+/desktop:act open firefox, navigate to example.com, and screenshot the page
+```
+
+`act()` spawns a sub-session via `claude-agent-sdk`. Use this when you want
+hands-off; otherwise streaming primitives give better transparency.
+
+### Stdio CLI (no MCP host)
+
+For scripts, CI, or agents that only have a shell, use the bundled client:
+
+```bash
+./cli/desktop-act which
+./cli/desktop-act status
+./cli/desktop-act run --goal "Open a browser and go to example.com" --timeout 180
+```
+
+It speaks JSON-RPC over stdio to the same server. Paths resolve from
+`DESKTOP_ACT_COMMAND` / `DESKTOP_ACT_HOME`, this checkout, or the per-user
+cache — nothing host-specific is hard-coded. See [cli/README.md](./cli/README.md).
+
+**Note:** `act()` takes `max_iterations` (and `timeout_seconds`), not `max_steps`.
+
+### Watching live
+
+Every desktop session returns a `novnc_url`. Open it in any browser:
+
+```
+http://<box-host>:6082 # first pool desktop
+http://<box-host>:6083 # second, etc.
+```
+
+---
+
+## Architecture notes
+
+- **OS-agnostic backend.** A module-level `BACKEND` is chosen at startup from
+ `platform.system()` — `MacBackend` on macOS, `WinBackend` on Windows,
+ `X11Backend` on Linux. All three implement the same `Backend` protocol; every
+ `@mcp.tool` simply delegates to `BACKEND.<method>`, so tool signatures and
+ return shapes are identical across platforms. Platform-only imports
+ (`Xlib`, `ImageGrab`/`ctypes.windll`, Quartz) stay inside backend methods so
+ the module imports cleanly on any host.
+- **Persistent X11 connections (Linux).** One `Xlib.Display` per display name,
+ cached for the life of the MCP process. Saves the connection-establishment
+ hit per primitive call.
+- **File-locked pool + exclusive leases.** Pool state lives under
+ `$DESKTOP_ACT_TMP` (default `/tmp` on Unix, `%TEMP%` on Windows), guarded by
+ `flock` / `msvcrt` locking. Each session carries `owner_id` + `lease_until`.
+ On Linux, busy seats auto-spawn Xvnc and idle seats are reaped (lock free +
+ VNC stop). On macOS/Windows the reaper clears lease metadata only.
+- **SHA-deduped screenshots.** Identical frames return the same path without
+ re-encoding. Keeps token/byte cost down across tight loops.
+- **JPEG by default.** Switch to PNG with `fmt="png"` when you need lossless.
+
+---
+
+## Project layout
+
+```
+desktop-act/
+├── .claude-plugin/plugin.json # plugin manifest (registers MCP server)
+├── commands/act.md # /desktop:act slash command
+├── skills/desktop-act/SKILL.md # when-to-use skill doc
+├── cli/
+│ ├── desktop-act # shell entrypoint
+│ ├── desktop_act_cli.py # stdio JSON-RPC client
+│ └── README.md # CLI usage
+├── mcp-server/
+│ ├── run.sh # launcher (auto-bootstraps venv)
+│ └── server.py # FastMCP server (single file)
+└── requirements.txt
+```
+
+---
+
+## License
+
+MIT — see [LICENSE](./LICENSE).
diff --git a/desktop-act/cli/README.md b/desktop-act/cli/README.md
new file mode 100644
index 00000000..7249928f
--- /dev/null
+++ b/desktop-act/cli/README.md
@@ -0,0 +1,73 @@
+# desktop-act CLI
+
+Shell-friendly client for the desktop-act MCP server. Talks JSON-RPC over
+stdio — no MCP host required. Useful for scripts, CI smoke checks, and agents
+that only have a shell.
+
+## Quick start
+
+From a full checkout (after `mcp-server/run.sh` has bootstrapped the venv once):
+
+```bash
+./cli/desktop-act which # show resolved server command
+./cli/desktop-act status
+./cli/desktop-act acquire # → JSON with session_id + novnc_url
+./cli/desktop-act screenshot --session-id <id>
+./cli/desktop-act act --goal "Open a terminal and list the home directory"
+./cli/desktop-act release --session-id <id>
+```
+
+One-shot goal loop (acquire → act → release):
+
+```bash
+./cli/desktop-act run --goal "Open a browser and navigate to example.com" --timeout 180
+```
+
+## Path resolution
+
+No machine-specific paths are baked in. First match wins:
+
+| Priority | Source |
+| -------- | ------ |
+| 1 | `DESKTOP_ACT_COMMAND` — full argv or path to `run.sh` / `server.py` |
+| 2 | `DESKTOP_ACT_HOME` — install root containing `mcp-server/` |
+| 3 | Repo root next to this `cli/` directory |
+| 4 | Per-user cache: `$XDG_CACHE_HOME/desktop-act-mcp/src` (Linux) or `~/Library/Caches/desktop-act-mcp/src` (macOS) |
+
+Optional:
+
+| Env | Meaning |
+| --- | ------- |
+| `DESKTOP_ACT_VENV` | Venv with server deps |
+| `DESKTOP_ACT_PYTHON` | Bootstrap / client interpreter |
+| `DESKTOP_ACT_DISPLAY` | Default X11 display (Linux) |
+| `DESKTOP_ACT_MAX_ITERATIONS` | Default for `act` / `run` |
+| `DESKTOP_ACT_ACT_TIMEOUT` | Default wall-clock for `act` / `run` (seconds) |
+| `DESKTOP_ACT_MODEL` | Optional model id for `act` |
+| `DESKTOP_ACT_RPC_TIMEOUT` | Per-request JSON-RPC wait (seconds) |
+
+## Subcommands
+
+| Command | Purpose |
+| ------- | ------- |
+| `which` | Print resolved server launch command |
+| `status` | Health + pool + binary inventory |
+| `list` | Active pool sessions |
+| `ensure [--owner-id ID]` | Multi-agent: reuse lease or auto-spawn |
+| `acquire [--owner-id ID] [--force-new]` | Ensure by default; force-new always spawns |
+| `heartbeat --session-id ID` | Refresh lease TTL (avoid idle reap) |
+| `reap` | Free locks + stop VNC for idle/dead seats |
+| `release --session-id ID` | Tear down a session |
+| `screenshot [--session-id ID]` | Capture frame |
+| `observe [--session-id ID]` | Screenshot + windows |
+| `act --goal "…"` | Autonomous loop (`max_iterations`, not `max_steps`) |
+| `run --goal "…"` | Ensure → act → release |
+| `call TOOL --arg k=v` | Raw `tools/call` |
+
+Exit codes: `0` success, `1` act reported failure, `2` usage / transport error.
+
+## Notes
+
+- `act()` requires a working Claude CLI OAuth session on the host (see main README).
+- On Linux, ensure Xvnc / websockify / a window manager are installed before `acquire`.
+- Output is JSON on stdout so scripts can pipe to `jq`.
diff --git a/desktop-act/cli/desktop-act b/desktop-act/cli/desktop-act
new file mode 100755
index 00000000..7b80eeed
--- /dev/null
+++ b/desktop-act/cli/desktop-act
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+# Portable entrypoint for the desktop-act stdio CLI.
+# Resolves the Python next to this repo (venv if present), else system python3.
+# Follows symlinks so ~/.local/bin/desktop-act works when linked to this file.
+set -euo pipefail
+
+SOURCE="${BASH_SOURCE[0]}"
+while [[ -L "$SOURCE" ]]; do
+ DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
+ LINK="$(readlink "$SOURCE")"
+ if [[ "$LINK" == /* ]]; then
+ SOURCE="$LINK"
+ else
+ SOURCE="$DIR/$LINK"
+ fi
+done
+ROOT="$(cd -P "$(dirname "$SOURCE")/.." && pwd)"
+VENV_PY="${DESKTOP_ACT_VENV:-$ROOT/.venv}/bin/python"
+if [[ -x "$VENV_PY" ]]; then
+ exec "$VENV_PY" "$ROOT/cli/desktop_act_cli.py" "$@"
+fi
+exec "${DESKTOP_ACT_PYTHON:-python3}" "$ROOT/cli/desktop_act_cli.py" "$@"
diff --git a/desktop-act/cli/desktop_act_cli.py b/desktop-act/cli/desktop_act_cli.py
new file mode 100755
index 00000000..5f54de43
--- /dev/null
+++ b/desktop-act/cli/desktop_act_cli.py
@@ -0,0 +1,646 @@
+#!/usr/bin/env python3
+"""desktop-act stdio CLI — call the MCP server without an MCP host.
+
+Use this from shell scripts, CI, or other agents when you need
+status / acquire / screenshot / act / release over JSON-RPC stdio.
+
+Path resolution (first match wins):
+
+ 1. ``DESKTOP_ACT_COMMAND`` — executable that starts the server (e.g. run.sh)
+ 2. ``DESKTOP_ACT_HOME`` — install root; uses ``$DESKTOP_ACT_HOME/mcp-server/run.sh``
+ or ``server.py`` with ``$DESKTOP_ACT_VENV/bin/python``
+ 3. This repo checkout — ``<repo>/mcp-server/run.sh`` next to this file
+ 4. ``$XDG_CACHE_HOME/desktop-act-mcp/src`` (Linux) or
+ ``~/Library/Caches/desktop-act-mcp/src`` (macOS)
+
+No host-specific paths are hard-coded. Override with env vars as needed.
+
+Examples::
+
+ desktop-act status
+ desktop-act acquire
+ desktop-act screenshot --session-id SID
+ desktop-act act --goal "Open a browser and go to example.com"
+ desktop-act run --goal "Take a screenshot of the desktop"
+ desktop-act call list_windows --arg session_id=SID
+ desktop-act release --session-id SID
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import platform
+import subprocess
+import sys
+import time
+from pathlib import Path
+from typing import Any
+
+# ─── discovery ───────────────────────────────────────────────────────────────
+
+
+def _cache_src() -> Path:
+ system = platform.system().lower()
+ if system == "darwin":
+ return Path.home() / "Library" / "Caches" / "desktop-act-mcp" / "src"
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
+ return Path(base) / "desktop-act-mcp" / "src"
+
+
+def _repo_root() -> Path:
+ """cli/ lives one level under the repo root."""
+ return Path(__file__).resolve().parent.parent
+
+
+def resolve_server_cmd() -> list[str]:
+ """Return argv that launches the desktop-act MCP server on stdio."""
+ # 1. Explicit command (may be a multi-word string)
+ explicit = (os.environ.get("DESKTOP_ACT_COMMAND") or "").strip()
+ if explicit:
+ # Allow "python /path/server.py" or a single run.sh path
+ parts = explicit.split()
+ if len(parts) == 1 and Path(parts[0]).is_file():
+ return parts
+ if len(parts) >= 2:
+ return parts
+ if Path(parts[0]).exists():
+ return parts
+
+ candidates: list[Path] = []
+ home = (os.environ.get("DESKTOP_ACT_HOME") or "").strip()
+ if home:
+ candidates.append(Path(home))
+ candidates.append(_repo_root())
+ candidates.append(_cache_src())
+
+ venv = (os.environ.get("DESKTOP_ACT_VENV") or "").strip()
+ py_override = (os.environ.get("DESKTOP_ACT_PYTHON") or "").strip()
+
+ for root in candidates:
+ if not root.is_dir():
+ continue
+ run_sh = root / "mcp-server" / "run.sh"
+ server_py = root / "mcp-server" / "server.py"
+ if run_sh.is_file() and os.access(run_sh, os.X_OK):
+ return [str(run_sh)]
+ if server_py.is_file():
+ venv_root = Path(venv) if venv else root / ".venv"
+ py = Path(py_override) if py_override else venv_root / "bin" / "python"
+ if not py.is_file():
+ py = Path(py_override or sys.executable)
+ return [str(py), str(server_py)]
+
+ raise FileNotFoundError(
+ "desktop-act server not found. Set DESKTOP_ACT_HOME or DESKTOP_ACT_COMMAND, "
+ "or run this CLI from a full checkout (mcp-server/run.sh present)."
+ )
+
+
+# ─── MCP client ──────────────────────────────────────────────────────────────
+
+
+class McpClient:
+ """Minimal JSON-RPC-over-stdio MCP client (initialize + tools/call)."""
+
+ def __init__(self, cmd: list[str], env: dict[str, str] | None = None, timeout: float = 120.0):
+ self.timeout = timeout
+ merged = os.environ.copy()
+ if env:
+ merged.update(env)
+ # Inherit stderr so server INFO logs do not fill a PIPE and deadlock act/run.
+ # stdout stays piped for JSON-RPC; stderr is diagnostic only.
+ self.proc = subprocess.Popen(
+ cmd,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=None,
+ text=True,
+ env=merged,
+ bufsize=1,
+ )
+ self._id = 0
+
+ def _send(self, method: str, params: dict | None = None, *, notify: bool = False) -> Any:
+ self._id += 1
+ msg: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
+ if not notify:
+ msg["id"] = self._id
+ if params is not None:
+ msg["params"] = params
+ if not self.proc.stdin or not self.proc.stdout:
+ raise RuntimeError("MCP process has no stdio")
+ self.proc.stdin.write(json.dumps(msg) + "\n")
+ self.proc.stdin.flush()
+ if notify:
+ return None
+ deadline = time.time() + self.timeout
+ while time.time() < deadline:
+ line = self.proc.stdout.readline()
+ if not line:
+ rc = self.proc.poll()
+ raise RuntimeError(
+ f"MCP EOF while waiting for {method}"
+ + (f" (exit {rc})" if rc is not None else "")
+ )
+ line = line.strip()
+ if not line.startswith("{"):
+ continue
+ try:
+ obj = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if obj.get("id") != self._id:
+ continue
+ if "error" in obj:
+ raise RuntimeError(json.dumps(obj["error"])[:500])
+ return obj.get("result")
+ raise TimeoutError(f"timeout waiting for {method}")
+
+ def initialize(self) -> None:
+ self._send(
+ "initialize",
+ {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {},
+ "clientInfo": {"name": "desktop-act-cli", "version": "1.0.0"},
+ },
+ )
+ self._send("notifications/initialized", notify=True)
+
+ def call_tool(self, name: str, arguments: dict | None = None) -> Any:
+ return self._send("tools/call", {"name": name, "arguments": arguments or {}})
+
+ def close(self) -> None:
+ try:
+ if self.proc.poll() is None:
+ self.proc.terminate()
+ try:
+ self.proc.wait(timeout=3)
+ except subprocess.TimeoutExpired:
+ self.proc.kill()
+ except Exception:
+ pass
+
+
+def unwrap_tool_result(result: Any) -> Any:
+ """Normalize FastMCP / MCP tool result envelopes to a plain value."""
+ if not isinstance(result, dict):
+ return result
+ if "structuredContent" in result and result["structuredContent"] is not None:
+ return result["structuredContent"]
+ content = result.get("content")
+ if isinstance(content, list) and content:
+ texts = [
+ c.get("text", "") for c in content if isinstance(c, dict) and c.get("type") == "text"
+ ]
+ joined = "\n".join(t for t in texts if t)
+ if joined.strip().startswith("{") or joined.strip().startswith("["):
+ try:
+ return json.loads(joined)
+ except json.JSONDecodeError:
+ pass
+ if joined:
+ return {"text": joined}
+ # already a plain dict from some servers
+ if "ok" in result or "session_id" in result or "error" in result:
+ return result
+ return result
+
+
+def emit(data: Any) -> None:
+ if isinstance(data, (dict, list)):
+ print(json.dumps(data, indent=2, default=str))
+ else:
+ print(data)
+
+
+# ─── commands ────────────────────────────────────────────────────────────────
+
+
+def _client_from_args(args: argparse.Namespace) -> McpClient:
+ cmd = resolve_server_cmd()
+ env: dict[str, str] = {}
+ if getattr(args, "display", None):
+ env["DISPLAY"] = args.display
+ env.setdefault("DESKTOP_ACT_DISPLAY", args.display)
+ # CLI is short-lived; do not free pool desktops when the stdio server exits.
+ # Long-lived MCP hosts keep default RELEASE_ON_EXIT=1.
+ env.setdefault("DESKTOP_ACT_RELEASE_ON_EXIT", "0")
+ if getattr(args, "owner_id", None):
+ env.setdefault("DESKTOP_ACT_OWNER", args.owner_id)
+ if getattr(args, "geometry", None):
+ env.setdefault("DESKTOP_ACT_GEOMETRY", args.geometry)
+ timeout = float(getattr(args, "rpc_timeout", 120) or 120)
+ client = McpClient(cmd, env=env or None, timeout=timeout)
+ try:
+ client.initialize()
+ except Exception:
+ client.close()
+ raise
+ return client
+
+
+def cmd_status(args: argparse.Namespace) -> int:
+ client = _client_from_args(args)
+ try:
+ emit(unwrap_tool_result(client.call_tool("status", {})))
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_list(args: argparse.Namespace) -> int:
+ client = _client_from_args(args)
+ try:
+ emit(unwrap_tool_result(client.call_tool("list_desktops", {})))
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_acquire(args: argparse.Namespace) -> int:
+ client = _client_from_args(args)
+ try:
+ params: dict[str, Any] = {}
+ if getattr(args, "geometry", None):
+ params["geometry"] = args.geometry
+ if getattr(args, "owner_id", None):
+ params["owner_id"] = args.owner_id
+ if getattr(args, "force_new", False):
+ params["force_new"] = True
+ out = unwrap_tool_result(client.call_tool("acquire_desktop", params))
+ emit(out)
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_ensure(args: argparse.Namespace) -> int:
+ """Multi-agent entry: reuse own lease or auto-spawn if busy."""
+ client = _client_from_args(args)
+ try:
+ params: dict[str, Any] = {}
+ if getattr(args, "geometry", None):
+ params["geometry"] = args.geometry
+ if getattr(args, "owner_id", None):
+ params["owner_id"] = args.owner_id
+ out = unwrap_tool_result(client.call_tool("ensure_desktop", params))
+ emit(out)
+ return 0 if not (isinstance(out, dict) and out.get("ok") is False) else 1
+ finally:
+ client.close()
+
+
+def cmd_heartbeat(args: argparse.Namespace) -> int:
+ if not args.session_id:
+ print("error: --session-id required", file=sys.stderr)
+ return 2
+ client = _client_from_args(args)
+ try:
+ params: dict[str, Any] = {"session_id": args.session_id}
+ if getattr(args, "owner_id", None):
+ params["owner_id"] = args.owner_id
+ out = unwrap_tool_result(client.call_tool("heartbeat_desktop", params))
+ emit(out)
+ return 0 if not (isinstance(out, dict) and out.get("ok") is False) else 1
+ finally:
+ client.close()
+
+
+def cmd_reap(args: argparse.Namespace) -> int:
+ client = _client_from_args(args)
+ try:
+ out = unwrap_tool_result(client.call_tool("reap_idle_desktops", {}))
+ emit(out)
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_release(args: argparse.Namespace) -> int:
+ if not args.session_id:
+ print("error: --session-id required", file=sys.stderr)
+ return 2
+ client = _client_from_args(args)
+ try:
+ emit(
+ unwrap_tool_result(client.call_tool("release_desktop", {"session_id": args.session_id}))
+ )
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_screenshot(args: argparse.Namespace) -> int:
+ client = _client_from_args(args)
+ try:
+ params: dict[str, Any] = {}
+ if args.session_id:
+ params["session_id"] = args.session_id
+ if args.fmt:
+ params["fmt"] = args.fmt
+ emit(unwrap_tool_result(client.call_tool("screenshot", params)))
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_observe(args: argparse.Namespace) -> int:
+ client = _client_from_args(args)
+ try:
+ params: dict[str, Any] = {}
+ if args.session_id:
+ params["session_id"] = args.session_id
+ emit(unwrap_tool_result(client.call_tool("observe", params)))
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_act(args: argparse.Namespace) -> int:
+ if not args.goal:
+ print("error: --goal required", file=sys.stderr)
+ return 2
+ client = _client_from_args(args)
+ # act() can run for a long time — raise RPC wait
+ client.timeout = float(args.timeout) + 30
+ try:
+ params: dict[str, Any] = {
+ "goal": args.goal,
+ "max_iterations": args.max_iterations,
+ "timeout_seconds": args.timeout,
+ }
+ if args.session_id:
+ params["session_id"] = args.session_id
+ if args.model:
+ params["model"] = args.model
+ result = unwrap_tool_result(client.call_tool("act", params))
+ emit(result)
+ if isinstance(result, dict) and result.get("ok") is False:
+ return 1
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_run(args: argparse.Namespace) -> int:
+ """Acquire -> act(goal) -> release. Exit 0 only if act reports ok."""
+ if not args.goal:
+ print("error: --goal required", file=sys.stderr)
+ return 2
+ client = _client_from_args(args)
+ client.timeout = float(args.timeout) + 30
+ session_id = args.session_id or ""
+ acquired = False
+ try:
+ if not session_id:
+ acq_params: dict[str, Any] = {}
+ if getattr(args, "owner_id", None):
+ acq_params["owner_id"] = args.owner_id
+ if getattr(args, "geometry", None):
+ acq_params["geometry"] = args.geometry
+ acq = unwrap_tool_result(client.call_tool("ensure_desktop", acq_params))
+ emit({"phase": "ensure", "result": acq})
+ if isinstance(acq, dict):
+ session_id = acq.get("session_id") or acq.get("id") or ""
+ acquired = bool(session_id)
+
+ try:
+ shot = unwrap_tool_result(
+ client.call_tool("screenshot", {"session_id": session_id} if session_id else {})
+ )
+ emit({"phase": "screenshot", "result": shot})
+ except Exception as exc: # noqa: BLE001
+ emit({"phase": "screenshot", "warn": str(exc)})
+
+ params: dict[str, Any] = {
+ "goal": args.goal,
+ "max_iterations": args.max_iterations,
+ "timeout_seconds": args.timeout,
+ }
+ if session_id:
+ params["session_id"] = session_id
+ if args.model:
+ params["model"] = args.model
+ result = unwrap_tool_result(client.call_tool("act", params))
+ emit({"phase": "act", "result": result})
+ ok = True
+ if isinstance(result, dict):
+ if result.get("ok") is False:
+ ok = False
+ elif result.get("error") and not result.get("ok"):
+ ok = False
+ return 0 if ok else 1
+ except Exception as exc: # noqa: BLE001
+ print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)
+ return 2
+ finally:
+ if acquired and session_id:
+ try:
+ client.call_tool("release_desktop", {"session_id": session_id})
+ except Exception:
+ pass
+ client.close()
+
+
+def cmd_call(args: argparse.Namespace) -> int:
+ """Raw tools/call for any server tool."""
+ tool_args: dict[str, Any] = {}
+ for item in args.arg or []:
+ if "=" not in item:
+ print(f"error: --arg expects key=value, got {item!r}", file=sys.stderr)
+ return 2
+ key, raw = item.split("=", 1)
+ # try JSON coerce
+ try:
+ tool_args[key] = json.loads(raw)
+ except json.JSONDecodeError:
+ tool_args[key] = raw
+ client = _client_from_args(args)
+ client.timeout = float(getattr(args, "timeout", 120) or 120)
+ try:
+ emit(unwrap_tool_result(client.call_tool(args.tool, tool_args)))
+ return 0
+ finally:
+ client.close()
+
+
+def cmd_which(args: argparse.Namespace) -> int:
+ """Print resolved server command (debug / smoke)."""
+ try:
+ cmd = resolve_server_cmd()
+ emit({"ok": True, "command": cmd})
+ return 0
+ except FileNotFoundError as exc:
+ emit({"ok": False, "error": str(exc)})
+ return 1
+
+
+# ─── argparse ────────────────────────────────────────────────────────────────
+
+
+def _add_common(p: argparse.ArgumentParser) -> None:
+ p.add_argument(
+ "--display",
+ default=os.environ.get("DISPLAY") or os.environ.get("DESKTOP_ACT_DISPLAY") or None,
+ help="X11 DISPLAY to pass through (Linux). Default: $DISPLAY or $DESKTOP_ACT_DISPLAY",
+ )
+ p.add_argument(
+ "--rpc-timeout",
+ type=float,
+ default=float(os.environ.get("DESKTOP_ACT_RPC_TIMEOUT", "120")),
+ help="Seconds to wait for a single MCP response (default 120)",
+ )
+
+
+def _add_session(p: argparse.ArgumentParser, required: bool = False) -> None:
+ p.add_argument("--session-id", default="", required=required, help="Pool session id")
+
+
+def _add_owner(p: argparse.ArgumentParser) -> None:
+ p.add_argument(
+ "--owner-id",
+ default=os.environ.get("DESKTOP_ACT_OWNER") or "",
+ help="Exclusive lease owner (default: $DESKTOP_ACT_OWNER or process id)",
+ )
+ p.add_argument(
+ "--geometry",
+ default=os.environ.get("DESKTOP_ACT_GEOMETRY") or "",
+ help="Desktop geometry e.g. 2560x1440 (default server/env)",
+ )
+
+
+def _add_act_opts(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--goal", default="", help="Natural-language goal for act()")
+ p.add_argument(
+ "--max-iterations",
+ type=int,
+ default=int(os.environ.get("DESKTOP_ACT_MAX_ITERATIONS", "20")),
+ help="act() max_iterations (server param name; not max_steps)",
+ )
+ p.add_argument(
+ "--timeout",
+ type=int,
+ default=int(os.environ.get("DESKTOP_ACT_ACT_TIMEOUT", "600")),
+ help="act() timeout_seconds wall clock",
+ )
+ p.add_argument(
+ "--model",
+ default=os.environ.get("DESKTOP_ACT_MODEL") or "",
+ help="Optional model id for act()",
+ )
+
+
+def build_parser() -> argparse.ArgumentParser:
+ ap = argparse.ArgumentParser(
+ prog="desktop-act",
+ description="Call desktop-act MCP tools over stdio without an MCP host.",
+ )
+ sub = ap.add_subparsers(dest="command", required=True)
+
+ p = sub.add_parser("which", help="Print resolved server launch command")
+ _add_common(p)
+ p.set_defaults(func=cmd_which)
+
+ p = sub.add_parser("status", help="Pool + binary inventory")
+ _add_common(p)
+ p.set_defaults(func=cmd_status)
+
+ p = sub.add_parser("list", help="List pool desktops")
+ _add_common(p)
+ p.set_defaults(func=cmd_list)
+
+ p = sub.add_parser(
+ "ensure",
+ help="Multi-agent: reuse own lease or auto-spawn if another agent holds a desktop",
+ )
+ _add_common(p)
+ _add_owner(p)
+ p.set_defaults(func=cmd_ensure)
+
+ p = sub.add_parser(
+ "acquire", help="Acquire a desktop (ensure by default; --force-new always spawns)"
+ )
+ _add_common(p)
+ _add_owner(p)
+ p.add_argument(
+ "--force-new",
+ action="store_true",
+ help="Always spawn a fresh exclusive desktop",
+ )
+ p.set_defaults(func=cmd_acquire)
+
+ p = sub.add_parser(
+ "heartbeat", help="Refresh lease TTL so idle reaper will not free the session"
+ )
+ _add_common(p)
+ _add_session(p, required=True)
+ _add_owner(p)
+ p.set_defaults(func=cmd_heartbeat)
+
+ p = sub.add_parser("reap", help="Free locks + stop VNC for idle/dead pool sessions")
+ _add_common(p)
+ p.set_defaults(func=cmd_reap)
+
+ p = sub.add_parser("release", help="Release a session (free lock + stop pool VNC)")
+ _add_common(p)
+ _add_session(p, required=True)
+ p.set_defaults(func=cmd_release)
+
+ p = sub.add_parser("screenshot", help="Capture a screenshot")
+ _add_common(p)
+ _add_session(p)
+ p.add_argument("--fmt", default="jpeg", choices=("jpeg", "png"))
+ p.set_defaults(func=cmd_screenshot)
+
+ p = sub.add_parser("observe", help="Screenshot + window list")
+ _add_common(p)
+ _add_session(p)
+ p.set_defaults(func=cmd_observe)
+
+ p = sub.add_parser("act", help="Run autonomous act() on an existing or default session")
+ _add_common(p)
+ _add_session(p)
+ _add_act_opts(p)
+ p.set_defaults(func=cmd_act)
+
+ p = sub.add_parser(
+ "run",
+ help="Ensure desktop -> screenshot -> act(goal) -> release (one-shot goal loop)",
+ )
+ _add_common(p)
+ _add_session(p)
+ _add_owner(p)
+ _add_act_opts(p)
+ p.set_defaults(func=cmd_run)
+
+ p = sub.add_parser("call", help="Raw tools/call by name")
+ _add_common(p)
+ p.add_argument("tool", help="MCP tool name, e.g. list_windows")
+ p.add_argument(
+ "--arg",
+ action="append",
+ default=[],
+ help="Tool arg key=value (value JSON-parsed when possible). Repeatable.",
+ )
+ p.add_argument(
+ "--timeout",
+ type=float,
+ default=120.0,
+ help="RPC wait seconds for this call",
+ )
+ p.set_defaults(func=cmd_call)
+
+ return ap
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ return int(args.func(args))
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/desktop-act/commands/act.md b/desktop-act/commands/act.md
new file mode 100644
index 00000000..ae5a3582
--- /dev/null
+++ b/desktop-act/commands/act.md
@@ -0,0 +1,24 @@
+---
+description: "Live agentic desktop + browser control via OAuth (no API key)"
+allowed-tools: [Bash, Read]
+---
+
+# /desktop:act — autonomous goal execution
+
+Routes the goal through the desktop-act MCP server. The server uses
+claude-agent-sdk (bundled CLI + OAuth) so no Anthropic API key is required —
+costs are covered by a Claude Max subscription.
+
+Usage:
+- `/desktop:act <goal>` — kick off the loop (`act` tool, `max_iterations`)
+- Live view: use the `novnc_url` returned by `ensure_desktop` / `acquire_desktop`
+ (pool noVNC base defaults to port **6082**, not a fixed host port)
+- Reasoning streams as normal chat output
+
+For finer control with full reasoning visibility, call the MCP primitives
+directly: `mcp__desktop-act__screenshot()`, then Read the path, then
+`mcp__desktop-act__click(x, y)`, etc.
+
+## Goal
+
+$ARGUMENTS
diff --git a/desktop-act/daemon/.gitkeep b/desktop-act/daemon/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/desktop-act/logs/.gitkeep b/desktop-act/logs/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/desktop-act/mcp-server/run.sh b/desktop-act/mcp-server/run.sh
new file mode 100755
index 00000000..4b04d411
--- /dev/null
+++ b/desktop-act/mcp-server/run.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# desktop-act MCP launcher — auto-bootstraps a venv on first run, then execs server.
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+VENV="${DESKTOP_ACT_VENV:-$ROOT/.venv}"
+PY="${DESKTOP_ACT_PYTHON:-python3}"
+
+if [ ! -x "$VENV/bin/python" ]; then
+ echo "[desktop-act] bootstrapping venv at $VENV" >&2
+ "$PY" -m venv "$VENV"
+ "$VENV/bin/pip" install --quiet --upgrade pip
+ "$VENV/bin/pip" install --quiet -r "$ROOT/requirements.txt"
+fi
+
+exec "$VENV/bin/python" "$ROOT/mcp-server/server.py" "$@"
diff --git a/desktop-act/mcp-server/server.py b/desktop-act/mcp-server/server.py
new file mode 100755
index 00000000..669c1ad3
--- /dev/null
+++ b/desktop-act/mcp-server/server.py
@@ -0,0 +1,2770 @@
+#!/usr/bin/env python3
+"""desktop-act MCP — computer-use primitives + multi-desktop pool + autonomous act() loop.
+
+Architecture:
+ * OS-agnostic backend abstraction dispatched on platform.system():
+ - X11Backend (Linux): persistent Xlib connection cache + Xvnc/websockify pool.
+ - MacBackend (macOS): screencapture + cliclick/osascript, single real session.
+ - WinBackend (Windows): Pillow ImageGrab + pyautogui/ctypes SendInput,
+ EnumWindows, single interactive desktop (lease model matches macOS).
+ * Multi-desktop pool (Xvnc + websockify) with file-locked allocation in /tmp (X11).
+ * Optimized primitives: cached SHA-dedupe screenshots, JPEG default, batch syncs.
+ * High-level act(goal) via claude-agent-sdk (CLI OAuth, no ANTHROPIC_API_KEY).
+
+Auth path: claude-agent-sdk only (bundled CLI OAuth, Claude Max subscription).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import atexit
+import hashlib
+import json
+import logging
+import os
+import platform
+import re
+import shutil
+import signal
+import socket
+import subprocess
+import sys
+import threading
+import time
+import uuid
+from pathlib import Path
+from typing import Any, Optional, Protocol, runtime_checkable
+
+from fastmcp import FastMCP
+
+# ─── Module constants ────────────────────────────────────────────────────────
+# Auto-detect plugin root: ${CLAUDE_PLUGIN_ROOT} (set by Claude Code) → __file__ parent → cwd.
+PLUGIN_ROOT = Path(
+ os.environ.get("CLAUDE_PLUGIN_ROOT")
+ or os.environ.get("DESKTOP_ACT_ROOT")
+ or Path(__file__).resolve().parent.parent
+)
+_SYS = platform.system().lower()
+IS_MAC: bool = _SYS == "darwin"
+IS_WIN: bool = _SYS.startswith("win")
+
+LOG_DIR = Path(os.environ.get("DESKTOP_ACT_LOG_DIR", PLUGIN_ROOT / "logs"))
+LOG_DIR.mkdir(parents=True, exist_ok=True)
+# Prefer OS temp on Windows; Linux/mac keep /tmp for shared multi-agent pool paths.
+if os.environ.get("DESKTOP_ACT_TMP"):
+ TMP_ROOT = Path(os.environ["DESKTOP_ACT_TMP"])
+elif IS_WIN:
+ import tempfile as _tempfile
+
+ TMP_ROOT = Path(_tempfile.gettempdir())
+else:
+ TMP_ROOT = Path("/tmp")
+SHOT_DIR = TMP_ROOT / "desktop-act-shots"
+SHOT_DIR.mkdir(parents=True, exist_ok=True)
+POOL_PATH = TMP_ROOT / "desktop-act-pool.json"
+POOL_LOCK = TMP_ROOT / "desktop-act-pool.lock"
+SESSIONS_DIR = TMP_ROOT / "desktop-act-sessions"
+SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
+
+DEFAULT_DISPLAY: str = os.environ.get(
+ "DESKTOP_ACT_DISPLAY",
+ "mac:main" if IS_MAC else ("win:main" if IS_WIN else ":1"),
+)
+DISPLAY_NUM_MIN: int = int(os.environ.get("DESKTOP_ACT_DISPLAY_MIN", "50"))
+DISPLAY_NUM_MAX: int = int(os.environ.get("DESKTOP_ACT_DISPLAY_MAX", "99"))
+VNC_PORT_BASE: int = int(os.environ.get("DESKTOP_ACT_VNC_PORT_BASE", "5900"))
+NOVNC_PORT_BASE: int = int(os.environ.get("DESKTOP_ACT_NOVNC_PORT_BASE", "6082"))
+# Wide default so multiple agents can place windows side-by-side on one seat;
+# concurrent agents should still each hold an exclusive leased session.
+DEFAULT_GEOMETRY: str = os.environ.get("DESKTOP_ACT_GEOMETRY", "2560x1440")
+# Exclusive lease TTL (seconds). Heartbeat / ensure refresh the lease.
+# Idle past this → reaper frees the lock and tears down Xvnc/websockify.
+LEASE_TTL_SEC: int = int(os.environ.get("DESKTOP_ACT_LEASE_TTL", "600"))
+# Background reaper interval (seconds). 0 disables the background loop.
+REAP_INTERVAL_SEC: int = int(os.environ.get("DESKTOP_ACT_REAP_INTERVAL", "30"))
+# When an owner is set and session_id is empty/busy, auto-spawn a free desktop.
+AUTO_SPAWN: bool = os.environ.get("DESKTOP_ACT_AUTO_SPAWN", "1").lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+)
+# Tear down pool VNC when lease expires (idle) or owner process ends.
+REAP_ON_IDLE: bool = os.environ.get("DESKTOP_ACT_REAP_ON_IDLE", "1").lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+)
+# On process exit, release sessions owned by this process.
+# Default on for long-lived MCP hosts. Stdio CLI sets DESKTOP_ACT_RELEASE_ON_EXIT=0
+# so one-shot ensure/list does not immediately kill the desktop it just created.
+RELEASE_ON_EXIT: bool = os.environ.get("DESKTOP_ACT_RELEASE_ON_EXIT", "1").lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+)
+# macOS single-session id (stable across the process lifetime).
+MAC_SESSION_ID: str = "mac-main"
+MAC_DISPLAY: str = "mac:main"
+MAC_VNC_PORT: int = int(os.environ.get("DESKTOP_ACT_MAC_VNC_PORT", "5900"))
+MAC_NOVNC_PORT: int = int(os.environ.get("DESKTOP_ACT_MAC_NOVNC_PORT", "6080"))
+# The macOS system-framework Python always ships Quartz/pyobjc, which the venv
+# (requirements.txt) does not. We shell out to it to synthesize scroll-wheel
+# CGEvents — AppleScript has no working scroll verb.
+MAC_SYSTEM_PYTHON: str = os.environ.get("DESKTOP_ACT_MAC_PYTHON", "/usr/bin/python3")
+# Posts `amount` line-unit scroll-wheel events. argv: <dy> <dx>.
+_MAC_SCROLL_PY = (
+ "import sys\n"
+ "from Quartz import (CGEventCreateScrollWheelEvent, CGEventPost, "
+ "kCGHIDEventTap, kCGScrollEventUnitLine)\n"
+ "dy, dx = int(sys.argv[1]), int(sys.argv[2])\n"
+ "n = max(abs(dy), abs(dx)) or 1\n"
+ "sy = (1 if dy > 0 else -1) if dy else 0\n"
+ "sx = (1 if dx > 0 else -1) if dx else 0\n"
+ "for _ in range(n):\n"
+ " ev = CGEventCreateScrollWheelEvent(None, kCGScrollEventUnitLine, 2, sy, sx)\n"
+ " CGEventPost(kCGHIDEventTap, ev)\n"
+)
+# Locate `claude` CLI: env override → PATH lookup → ~/.local/bin → ~/.claude/local.
+_claude_default = shutil.which("claude") or str(Path.home() / ".local/bin/claude")
+CLAUDE_CLI = Path(os.environ.get("CLAUDE_CLI_PATH", _claude_default))
+
+# ─── Logging (stderr — visible in FastMCP startup) ───────────────────────────
+logging.basicConfig(
+ stream=sys.stderr,
+ level=logging.INFO,
+ format="[desktop-act] %(asctime)s %(levelname)s %(message)s",
+ datefmt="%H:%M:%S",
+)
+log = logging.getLogger("desktop-act")
+
+
+# ─── Binary discovery (cached at startup) ────────────────────────────────────
+def _which(*names: str) -> Optional[str]:
+ """Return the first existing path among candidates."""
+ for n in names:
+ p = shutil.which(n)
+ if p:
+ return p
+ return None
+
+
+BIN: dict[str, Optional[str]] = {
+ "Xvnc": _which("Xvnc"),
+ "vncserver": _which("vncserver"),
+ "websockify": _which("websockify"),
+ "x11vnc": _which("x11vnc"),
+ # WM preference order: openbox → fluxbox → metacity → mutter
+ "wm": _which("openbox", "fluxbox", "metacity", "mutter"),
+ "xterm": _which("xterm"),
+ "xdotool": _which("xdotool"),
+ # macOS system binaries (no-op on Linux).
+ "cliclick": _which("cliclick", "/opt/homebrew/bin/cliclick", "/usr/local/bin/cliclick"),
+ "screencapture": _which("screencapture", "/usr/sbin/screencapture"),
+ "osascript": _which("osascript", "/usr/bin/osascript"),
+ "open": _which("open", "/usr/bin/open"),
+}
+log.info("binaries: %s", {k: v for k, v in BIN.items() if v})
+if IS_MAC:
+ _missing_critical = [k for k in ("cliclick", "screencapture") if BIN[k] is None]
+ if _missing_critical:
+ log.warning(
+ "missing critical macOS binaries: %s — primitives will fail (brew install cliclick)",
+ _missing_critical,
+ )
+elif not IS_WIN:
+ _missing_critical = [k for k in ("Xvnc", "websockify") if BIN[k] is None]
+ if _missing_critical:
+ log.warning("missing critical binaries: %s — pool spawn will fail", _missing_critical)
+
+
+# ─── Pool persistence (file-locked) ──────────────────────────────────────────
+def _read_pool() -> dict[str, dict]:
+ if not POOL_PATH.exists():
+ return {}
+ try:
+ return json.loads(POOL_PATH.read_text())
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def _write_pool(pool: dict[str, dict]) -> None:
+ POOL_PATH.write_text(json.dumps(pool, indent=2, sort_keys=True))
+
+
+class _PoolLock:
+ """Cross-process exclusive lock for pool mutations.
+
+ Unix: fcntl.flock. Windows: msvcrt.locking on a 1-byte region (fcntl is
+ unavailable). Pool multi-desktop is Linux-primary; Windows only guards the
+ lease JSON for the limited hybrid backend.
+ """
+
+ def __enter__(self):
+ # "a+" so the file exists and is readable for msvcrt byte locks.
+ self.fd = POOL_LOCK.open("a+")
+ if IS_WIN:
+ import msvcrt
+
+ self.fd.seek(0, os.SEEK_END)
+ if self.fd.tell() == 0:
+ self.fd.write("0")
+ self.fd.flush()
+ self.fd.seek(0)
+ # LK_LOCK blocks until the region is free.
+ msvcrt.locking(self.fd.fileno(), msvcrt.LK_LOCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(self.fd.fileno(), fcntl.LOCK_EX)
+ return self
+
+ def __exit__(self, *exc):
+ try:
+ if IS_WIN:
+ import msvcrt
+
+ self.fd.seek(0)
+ try:
+ msvcrt.locking(self.fd.fileno(), msvcrt.LK_UNLCK, 1)
+ except OSError:
+ pass
+ else:
+ import fcntl
+
+ fcntl.flock(self.fd.fileno(), fcntl.LOCK_UN)
+ finally:
+ self.fd.close()
+
+
+def _now() -> int:
+ return int(time.time())
+
+
+def _default_owner_id() -> str:
+ """Stable-enough owner id for this process when caller omits owner_id."""
+ env = (os.environ.get("DESKTOP_ACT_OWNER") or "").strip()
+ if env:
+ return env
+ # Prefer explicit agent/session ids if present (Claude/Grok/etc.).
+ for key in (
+ "CLAUDE_SESSION_ID",
+ "CLAUDE_AGENT_ID",
+ "GROK_SESSION_ID",
+ "AGENT_ID",
+ "SESSION_ID",
+ ):
+ v = (os.environ.get(key) or "").strip()
+ if v:
+ return f"{key.lower()}:{v[:48]}"
+ return f"pid-{os.getpid()}"
+
+
+def _lease_expired(sess: dict, now: Optional[int] = None) -> bool:
+ now = _now() if now is None else now
+ until = int(sess.get("lease_until") or 0)
+ if until <= 0:
+ # No lease recorded → treat as free for claim.
+ return True
+ return until < now
+
+
+def _lease_held_by_other(sess: dict, owner_id: str, now: Optional[int] = None) -> bool:
+ """True if sess has a live exclusive lease for a different owner."""
+ now = _now() if now is None else now
+ held = (sess.get("owner_id") or "").strip()
+ if not held:
+ return False
+ if held == owner_id:
+ return False
+ return not _lease_expired(sess, now)
+
+
+def _apply_lease(sess: dict, owner_id: str, ttl: Optional[int] = None) -> dict:
+ ttl = LEASE_TTL_SEC if ttl is None else int(ttl)
+ owner = (owner_id or "").strip() or _default_owner_id()
+ sess["owner_id"] = owner
+ sess["lease_until"] = _now() + max(30, ttl)
+ sess["lease_ttl_sec"] = max(30, ttl)
+ sess["leased_at"] = _now()
+ return sess
+
+
+def _clear_lease(sess: dict) -> dict:
+ sess["owner_id"] = ""
+ sess["lease_until"] = 0
+ return sess
+
+
+def _kill_session_procs(sess: dict, grace: float = 0.3) -> list[dict]:
+ """SIGTERM then SIGKILL Xvnc/WM/websockify for a pool session. Returns killed list."""
+ killed: list[dict] = []
+ for key in ("websockify_pid", "wm_pid", "xvnc_pid"):
+ pid = int(sess.get(key) or 0)
+ if pid and _pid_alive(pid):
+ try:
+ os.kill(pid, signal.SIGTERM)
+ killed.append({key: pid})
+ except OSError:
+ pass
+ if grace > 0:
+ time.sleep(grace)
+ for key in ("websockify_pid", "wm_pid", "xvnc_pid"):
+ pid = int(sess.get(key) or 0)
+ if pid and _pid_alive(pid):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ # Cleanup X lock sockets (Linux pool only).
+ dnum = sess.get("display_num")
+ if dnum is not None:
+ for lock in (
+ Path(f"/tmp/.X{dnum}-lock"),
+ Path(f"/tmp/.X11-unix/X{dnum}"),
+ ):
+ try:
+ lock.unlink(missing_ok=True)
+ except OSError:
+ pass
+ return killed
+
+
+def _port_free(port: int) -> bool:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ try:
+ s.bind(("127.0.0.1", port))
+ return True
+ except OSError:
+ return False
+
+
+def _port_open(port: int, host: str = "127.0.0.1") -> bool:
+ """True if something is listening on host:port (connect succeeds)."""
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.settimeout(0.5)
+ try:
+ s.connect((host, port))
+ return True
+ except OSError:
+ return False
+
+
+def _display_in_use(display_num: int) -> bool:
+ return Path(f"/tmp/.X{display_num}-lock").exists() or not _port_free(
+ VNC_PORT_BASE + display_num
+ )
+
+
+def _pid_alive(pid: int) -> bool:
+ if pid <= 0:
+ return False
+ try:
+ os.kill(pid, 0)
+ return True
+ except (OSError, ProcessLookupError):
+ return False
+
+
+# ─── SHA-dedupe screenshot cache (shared across backends) ────────────────────
+_LAST_SHOT: dict[str, dict] = {}
+
+
+def _encode_screenshot(
+ img: Any,
+ display: str,
+ grab_ms: int,
+ fmt: str,
+ max_width: int,
+ use_cache: bool,
+) -> dict:
+ """Shared PIL pipeline: SHA-dedupe, optional downscale, save, cache. Returns metadata.
+
+ `img` must be a PIL RGB Image already grabbed by the backend.
+ """
+ from PIL import Image
+
+ w, h = img.width, img.height
+ sha = hashlib.sha256(img.tobytes()).hexdigest()[:16]
+
+ if use_cache:
+ prev = _LAST_SHOT.get(display)
+ if prev and prev["sha"] == sha and Path(prev["path"]).exists():
+ return {**prev, "cached": True, "grab_ms": grab_ms}
+
+ if max_width and w > max_width:
+ new_h = int(h * max_width / w)
+ img = img.resize((max_width, new_h), Image.BILINEAR)
+
+ ext = "jpg" if fmt == "jpeg" else "png"
+ out = str(SHOT_DIR / f"shot-{sha[:8]}.{ext}")
+ t1 = time.time()
+ if fmt == "jpeg":
+ img.save(out, "JPEG", quality=80, optimize=True)
+ else:
+ img.save(out, "PNG", optimize=False)
+ save_ms = int((time.time() - t1) * 1000)
+
+ result = {
+ "path": out,
+ "width": img.width,
+ "height": img.height,
+ "sha": sha,
+ "cached": False,
+ "grab_ms": grab_ms,
+ "save_ms": save_ms,
+ }
+ _LAST_SHOT[display] = result
+ return result
+
+
+# ─── Backend protocol ────────────────────────────────────────────────────────
+@runtime_checkable
+class Backend(Protocol):
+ """OS-agnostic desktop primitive surface.
+
+ Methods mirror the @mcp.tool primitives 1:1. All return the same dict shapes
+ the tools expose so callers never need to know which backend is active.
+ Async to allow non-blocking subprocess / sleep within primitives.
+ """
+
+ name: str
+
+ async def screenshot(
+ self,
+ session_id: str,
+ region: str,
+ fmt: str,
+ max_width: int,
+ use_cache: bool,
+ ) -> dict: ...
+
+ async def click(self, x: int, y: int, button: int, double: bool, session_id: str) -> dict: ...
+
+ async def type_text(self, text: str, session_id: str, delay_ms: int) -> dict: ...
+
+ async def keypress(self, key: str, modifiers: Optional[list[str]], session_id: str) -> dict: ...
+
+ async def scroll(
+ self, direction: str, amount: int, x: int, y: int, session_id: str
+ ) -> dict: ...
+
+ async def list_windows(self, session_id: str) -> dict: ...
+
+ async def launch_app(self, command: str, session_id: str) -> dict: ...
+
+ async def acquire_desktop(
+ self, geometry: str, owner_id: str = "", force_new: bool = False
+ ) -> dict: ...
+
+ async def ensure_desktop(self, geometry: str, owner_id: str = "") -> dict: ...
+
+ async def heartbeat_desktop(self, session_id: str, owner_id: str = "") -> dict: ...
+
+ async def release_desktop(self, session_id: str) -> dict: ...
+
+ async def list_desktops(self) -> dict: ...
+
+ async def reap_idle_desktops(self) -> dict: ...
+
+
+# ─── X11 backend (Linux) ─────────────────────────────────────────────────────
+# ASCII printable -> X11 keysym name. python-xlib's XK.string_to_keysym() needs the
+# keysym name, not the literal character, so e.g. string_to_keysym("@") returns 0
+# but string_to_keysym("at") returns the right keysym. Without this map, typing
+# strings containing punctuation silently drops the offending characters.
+_CHAR_TO_KEYSYM_NAME: dict[str, str] = {
+ " ": "space",
+ "\n": "Return",
+ "\t": "Tab",
+ "!": "exclam",
+ '"': "quotedbl",
+ "#": "numbersign",
+ "$": "dollar",
+ "%": "percent",
+ "&": "ampersand",
+ "'": "apostrophe",
+ "(": "parenleft",
+ ")": "parenright",
+ "*": "asterisk",
+ "+": "plus",
+ ",": "comma",
+ "-": "minus",
+ ".": "period",
+ "/": "slash",
+ ":": "colon",
+ ";": "semicolon",
+ "<": "less",
+ "=": "equal",
+ ">": "greater",
+ "?": "question",
+ "@": "at",
+ "[": "bracketleft",
+ "\\": "backslash",
+ "]": "bracketright",
+ "^": "asciicircum",
+ "_": "underscore",
+ "`": "grave",
+ "{": "braceleft",
+ "|": "bar",
+ "}": "braceright",
+ "~": "asciitilde",
+}
+
+# Keysym NAMES that live at the shifted level on a US PC layout — when the caller
+# does `keypress("at")` we must hold Shift, otherwise fake_input sends the base
+# keycode for "2" and the wrong character lands in the focused widget.
+_SHIFT_REQUIRED_KEYSYMS: frozenset[str] = frozenset(
+ {
+ "exclam",
+ "at",
+ "numbersign",
+ "dollar",
+ "percent",
+ "asciicircum",
+ "ampersand",
+ "asterisk",
+ "parenleft",
+ "parenright",
+ "underscore",
+ "plus",
+ "braceleft",
+ "braceright",
+ "bar",
+ "colon",
+ "quotedbl",
+ "less",
+ "greater",
+ "question",
+ "asciitilde",
+ }
+)
+
+
+class X11Backend:
+ """X11/Xvnc backend. Behavior is byte-for-byte identical to the original server."""
+
+ name = "x11"
+
+ def __init__(self) -> None:
+ # Persistent X11 display connection cache (lazy-init per process).
+ self._displays: dict[str, Any] = {}
+
+ # ── X11 connection helpers ────────────────────────────────────────────
+ def _get_display(self, name: str) -> Any:
+ """Return a long-lived Xlib display, lazy-init per process."""
+ from Xlib import display as xd
+
+ d = self._displays.get(name)
+ if d is None:
+ d = xd.Display(name)
+ self._displays[name] = d
+ return d
+
+ def _resolve_display(self, session_id: str = "") -> str:
+ """Resolve a session_id to a display name. Empty → DEFAULT_DISPLAY."""
+ if not session_id:
+ return DEFAULT_DISPLAY
+ pool = _read_pool()
+ sess = pool.get(session_id)
+ if not sess:
+ raise ValueError(f"unknown session_id: {session_id}")
+ return sess["display"]
+
+ def _take_screenshot(
+ self,
+ display: str,
+ region: str = "",
+ fmt: str = "jpeg",
+ max_width: int = 0,
+ use_cache: bool = True,
+ ) -> dict:
+ """Grab screen, dedupe by SHA, optional downscale, return path + metadata."""
+ from PIL import Image
+ from Xlib import X
+
+ d = self._get_display(display)
+ root = d.screen().root
+ g = root.get_geometry()
+ if region:
+ x, y, w, h = (int(v) for v in region.split(","))
+ else:
+ x, y, w, h = 0, 0, g.width, g.height
+ t0 = time.time()
+ raw = root.get_image(x, y, w, h, X.ZPixmap, 0xFFFFFFFF)
+ grab_ms = int((time.time() - t0) * 1000)
+
+ img = Image.frombytes("RGB", (w, h), raw.data, "raw", "BGRX")
+ return _encode_screenshot(img, display, grab_ms, fmt, max_width, use_cache)
+
+ # ── Primitives ────────────────────────────────────────────────────────
+ async def screenshot(self, session_id, region, fmt, max_width, use_cache) -> dict:
+ display = self._resolve_display(session_id)
+ r = self._take_screenshot(display, region, fmt, max_width, use_cache)
+ return {"ok": True, "display": display, **r}
+
+ async def click(self, x, y, button, double, session_id) -> dict:
+ from Xlib import X
+ from Xlib.ext.xtest import fake_input
+
+ display = self._resolve_display(session_id)
+ d = self._get_display(display)
+ d.screen().root.warp_pointer(x, y)
+ d.sync()
+ for _ in range(2 if double else 1):
+ fake_input(d, X.ButtonPress, button)
+ fake_input(d, X.ButtonRelease, button)
+ d.sync()
+ if double:
+ await asyncio.sleep(0.05)
+ return {
+ "ok": True,
+ "x": x,
+ "y": y,
+ "button": button,
+ "double": double,
+ "display": display,
+ }
+
+ async def type_text(self, text, session_id, delay_ms) -> dict:
+ from Xlib import XK, X
+ from Xlib.ext.xtest import fake_input
+
+ display = self._resolve_display(session_id)
+ d = self._get_display(display)
+ shift_kc = d.keysym_to_keycode(XK.XK_Shift_L)
+ for ch in text:
+ name = _CHAR_TO_KEYSYM_NAME.get(ch, ch)
+ ks = XK.string_to_keysym(name)
+ if not ks:
+ continue
+ kc = d.keysym_to_keycode(ks)
+ shift = ch.isupper() or ch in '~!@#$%^&*()_+{}|:"<>?'
+ if shift:
+ fake_input(d, X.KeyPress, shift_kc)
+ fake_input(d, X.KeyPress, kc)
+ fake_input(d, X.KeyRelease, kc)
+ if shift:
+ fake_input(d, X.KeyRelease, shift_kc)
+ d.sync()
+ if delay_ms:
+ await asyncio.sleep(delay_ms / 1000)
+ return {"ok": True, "chars": len(text), "display": display}
+
+ async def keypress(self, key, modifiers, session_id) -> dict:
+ from Xlib import XK, X
+ from Xlib.ext.xtest import fake_input
+
+ display = self._resolve_display(session_id)
+ d = self._get_display(display)
+ mods = list(modifiers or [])
+ # Auto-add Shift when the requested keysym sits at the shifted level of
+ # its keycode (e.g. "at", "exclam", "question"); without this, fake_input
+ # sends the base keycode and types "2", "1", "/" instead.
+ if key in _SHIFT_REQUIRED_KEYSYMS and not any(m.lower() == "shift" for m in mods):
+ mods.append("Shift")
+ mcodes = [d.keysym_to_keycode(XK.string_to_keysym(m + "_L")) for m in mods]
+ kc = d.keysym_to_keycode(XK.string_to_keysym(key))
+ for m in mcodes:
+ fake_input(d, X.KeyPress, m)
+ fake_input(d, X.KeyPress, kc)
+ fake_input(d, X.KeyRelease, kc)
+ for m in reversed(mcodes):
+ fake_input(d, X.KeyRelease, m)
+ d.sync()
+ return {"ok": True, "key": key, "modifiers": mods, "display": display}
+
+ async def scroll(self, direction, amount, x, y, session_id) -> dict:
+ from Xlib import X
+ from Xlib.ext.xtest import fake_input
+
+ display = self._resolve_display(session_id)
+ d = self._get_display(display)
+ if x >= 0 and y >= 0:
+ d.screen().root.warp_pointer(x, y)
+ d.sync()
+ btn = {"up": 4, "down": 5, "left": 6, "right": 7}.get(direction.lower(), 5)
+ for _ in range(amount):
+ fake_input(d, X.ButtonPress, btn)
+ fake_input(d, X.ButtonRelease, btn)
+ d.sync()
+ if amount > 1:
+ await asyncio.sleep(0.03)
+ return {
+ "ok": True,
+ "direction": direction,
+ "amount": amount,
+ "display": display,
+ }
+
+ async def list_windows(self, session_id) -> dict:
+ display = self._resolve_display(session_id)
+ d = self._get_display(display)
+ wins = []
+ for w in d.screen().root.query_tree().children:
+ try:
+ name = w.get_wm_name()
+ g = w.get_geometry()
+ if name:
+ wins.append({"name": name, "x": g.x, "y": g.y, "w": g.width, "h": g.height})
+ except Exception: # noqa: BLE001
+ pass
+ return {"ok": True, "windows": wins, "display": display}
+
+ async def launch_app(self, command, session_id) -> dict:
+ display = self._resolve_display(session_id)
+ env = {**os.environ, "DISPLAY": display}
+ proc = await asyncio.create_subprocess_shell(
+ f"{command} &",
+ env=env,
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ await asyncio.sleep(1.5)
+ return {"ok": True, "command": command, "pid": proc.pid, "display": display}
+
+ # ── Pool ──────────────────────────────────────────────────────────────
+ def _spawn_desktop(self, display_num: int, geometry: str) -> dict:
+ """Synchronously spawn Xvnc + WM + websockify. Returns session record. Blocking."""
+ if not BIN["Xvnc"]:
+ raise RuntimeError("Xvnc not installed")
+ if not BIN["websockify"]:
+ raise RuntimeError("websockify not installed")
+
+ display = f":{display_num}"
+ vnc_port = VNC_PORT_BASE + display_num
+ novnc_port = NOVNC_PORT_BASE + (display_num - DISPLAY_NUM_MIN)
+ session_id = f"desk-{uuid.uuid4().hex[:8]}"
+ log_path = SESSIONS_DIR / f"{session_id}.log"
+ log_fh = log_path.open("a")
+
+ # Xvnc — no auth (loopback-bound), depth 24
+ xvnc_cmd = [
+ BIN["Xvnc"],
+ display,
+ "-geometry",
+ geometry,
+ "-depth",
+ "24",
+ "-SecurityTypes",
+ "None",
+ "-AlwaysShared",
+ "-rfbport",
+ str(vnc_port),
+ "-interface",
+ "127.0.0.1",
+ ]
+ xvnc = subprocess.Popen(
+ xvnc_cmd,
+ stdout=log_fh,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+
+ # Wait up to 5s for X server to come up
+ ready = False
+ for _ in range(50):
+ if Path(f"/tmp/.X{display_num}-lock").exists() and not _port_free(vnc_port):
+ ready = True
+ break
+ if xvnc.poll() is not None:
+ raise RuntimeError(f"Xvnc exited early (code={xvnc.returncode}) — see {log_path}")
+ time.sleep(0.1)
+ if not ready:
+ xvnc.terminate()
+ raise RuntimeError(
+ f"Xvnc :{display_num} did not become ready within 5s — see {log_path}"
+ )
+
+ # Spawn WM if available (best-effort, non-fatal)
+ wm_pid: Optional[int] = None
+ if BIN["wm"]:
+ try:
+ wm = subprocess.Popen(
+ [BIN["wm"]],
+ env={**os.environ, "DISPLAY": display},
+ stdout=log_fh,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ wm_pid = wm.pid
+ except Exception as e: # noqa: BLE001
+ log.warning("WM spawn failed for %s: %s", display, e)
+
+ # Spawn websockify (noVNC bridge)
+ websockify = subprocess.Popen(
+ [BIN["websockify"], str(novnc_port), f"127.0.0.1:{vnc_port}"],
+ stdout=log_fh,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+
+ # Best-effort xterm so the screen isn't entirely empty
+ if BIN["xterm"]:
+ try:
+ subprocess.Popen(
+ [BIN["xterm"], "-geometry", "80x24+10+10"],
+ env={**os.environ, "DISPLAY": display},
+ stdout=log_fh,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ except Exception: # noqa: BLE001
+ pass
+
+ return {
+ "session_id": session_id,
+ "display": display,
+ "display_num": display_num,
+ "vnc_port": vnc_port,
+ "novnc_port": novnc_port,
+ "novnc_url": f"http://localhost:{novnc_port}",
+ "geometry": geometry,
+ "xvnc_pid": xvnc.pid,
+ "wm_pid": wm_pid,
+ "wm_bin": BIN["wm"],
+ "websockify_pid": websockify.pid,
+ "log_path": str(log_path),
+ "created_at": int(time.time()),
+ }
+
+ def _close_display_cache(self, display: str) -> None:
+ d = self._displays.pop(display, None)
+ if d is not None:
+ try:
+ d.close()
+ except Exception: # noqa: BLE001
+ pass
+ _LAST_SHOT.pop(display, None)
+
+ def _pick_free_display_num(self, pool: dict) -> Optional[int]:
+ used_nums = {s.get("display_num") for s in pool.values() if "display_num" in s}
+ for n in range(DISPLAY_NUM_MIN, DISPLAY_NUM_MAX + 1):
+ if n in used_nums:
+ continue
+ if _display_in_use(n):
+ continue
+ return n
+ return None
+
+ def _spawn_and_lease(self, geometry: str, owner_id: str, pool: dict) -> dict:
+ """Spawn under pool lock (caller holds lock). Returns result dict."""
+ chosen = self._pick_free_display_num(pool)
+ if chosen is None:
+ return {
+ "ok": False,
+ "error": f"no free display in :{DISPLAY_NUM_MIN}-:{DISPLAY_NUM_MAX}",
+ }
+ # Spawn outside? Xvnc can take seconds — still under lock to avoid races.
+ session = self._spawn_desktop(chosen, geometry)
+ _apply_lease(session, owner_id)
+ session["owner_pid"] = os.getpid()
+ pool[session["session_id"]] = session
+ _write_pool(pool)
+ return {"ok": True, "reused": False, "spawned": True, **session}
+
+ async def ensure_desktop(self, geometry: str = DEFAULT_GEOMETRY, owner_id: str = "") -> dict:
+ """Return an exclusive desktop for owner_id.
+
+ - Reuse owner's live leased session (refresh TTL).
+ - Else claim an idle/expired pool session (refresh + re-lease).
+ - Else spawn a new Xvnc on the next free display/port.
+ Never steals a non-expired lease from another owner.
+ """
+ owner = (owner_id or "").strip() or _default_owner_id()
+ geo = geometry or DEFAULT_GEOMETRY
+
+ def _sync() -> dict:
+ with _PoolLock():
+ pool = _read_pool()
+ # Drop dead processes first (free slots without waiting for reaper).
+ self._reap_pool_locked(pool, reason="ensure-precheck")
+ # 1) Owner already holds a live session.
+ for sid, s in list(pool.items()):
+ if (s.get("owner_id") or "") == owner and self._session_alive(s):
+ _apply_lease(s, owner)
+ pool[sid] = s
+ _write_pool(pool)
+ return {"ok": True, "reused": True, "spawned": False, **s}
+ # 2) Claim free / lease-expired but still-alive desktop.
+ for sid, s in list(pool.items()):
+ if not self._session_alive(s):
+ continue
+ if _lease_held_by_other(s, owner):
+ continue
+ _apply_lease(s, owner)
+ s["owner_pid"] = os.getpid()
+ pool[sid] = s
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "reused": True,
+ "claimed": True,
+ "spawned": False,
+ **s,
+ }
+ # 3) Auto-spawn new exclusive desktop.
+ if not AUTO_SPAWN:
+ return {
+ "ok": False,
+ "error": "no free desktop and DESKTOP_ACT_AUTO_SPAWN=0",
+ "owner_id": owner,
+ }
+ return self._spawn_and_lease(geo, owner, pool)
+
+ return await asyncio.get_event_loop().run_in_executor(None, _sync)
+
+ async def acquire_desktop(
+ self, geometry: str = DEFAULT_GEOMETRY, owner_id: str = "", force_new: bool = False
+ ) -> dict:
+ """Acquire a desktop for this agent.
+
+ Default (force_new=False): ensure_desktop — reuse own lease or spawn if busy.
+ force_new=True: always spawn a fresh exclusive session (old always-new behavior).
+ """
+ owner = (owner_id or "").strip() or _default_owner_id()
+ geo = geometry or DEFAULT_GEOMETRY
+ if not force_new:
+ return await self.ensure_desktop(geo, owner)
+
+ def _sync() -> dict:
+ with _PoolLock():
+ pool = _read_pool()
+ self._reap_pool_locked(pool, reason="acquire-force-new")
+ return self._spawn_and_lease(geo, owner, pool)
+
+ return await asyncio.get_event_loop().run_in_executor(None, _sync)
+
+ async def heartbeat_desktop(self, session_id: str, owner_id: str = "") -> dict:
+ """Refresh lease TTL so the idle reaper does not tear the session down."""
+ owner = (owner_id or "").strip() or _default_owner_id()
+
+ def _sync() -> dict:
+ with _PoolLock():
+ pool = _read_pool()
+ sess = pool.get(session_id)
+ if not sess:
+ return {"ok": False, "error": f"unknown session_id: {session_id}"}
+ if _lease_held_by_other(sess, owner):
+ return {
+ "ok": False,
+ "error": "lease held by another owner",
+ "owner_id": sess.get("owner_id"),
+ "lease_until": sess.get("lease_until"),
+ }
+ _apply_lease(sess, owner)
+ pool[session_id] = sess
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "session_id": session_id,
+ "owner_id": sess.get("owner_id"),
+ "lease_until": sess.get("lease_until"),
+ }
+
+ return await asyncio.get_event_loop().run_in_executor(None, _sync)
+
+ def _release_locked(self, pool: dict, session_id: str) -> dict:
+ """Release under held pool lock. Kills VNC stack and drops lease."""
+ sess = pool.get(session_id)
+ if not sess:
+ return {"ok": False, "error": f"unknown session_id: {session_id}"}
+ display = sess.get("display") or ""
+ if display:
+ self._close_display_cache(display)
+ killed = _kill_session_procs(sess)
+ del pool[session_id]
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "released": session_id,
+ "killed": killed,
+ "owner_id": sess.get("owner_id") or "",
+ }
+
+ async def release_desktop(self, session_id: str) -> dict:
+ def _sync() -> dict:
+ with _PoolLock():
+ pool = _read_pool()
+ return self._release_locked(pool, session_id)
+
+ return await asyncio.get_event_loop().run_in_executor(None, _sync)
+
+ @staticmethod
+ def _session_alive(sess: dict) -> bool:
+ return _pid_alive(int(sess.get("xvnc_pid") or 0))
+
+ def _reap_pool_locked(self, pool: dict, reason: str = "reap") -> list[dict]:
+ """Free locks + kill VNC for dead or idle-expired pool sessions. Mutates pool."""
+ if not REAP_ON_IDLE and reason.startswith("idle"):
+ return []
+ now = _now()
+ reaped: list[dict] = []
+ for sid in list(pool.keys()):
+ s = pool[sid]
+ # Never reap non-pool / mac-main style records without xvnc.
+ if "xvnc_pid" not in s and "display_num" not in s:
+ continue
+ dead = not self._session_alive(s)
+ # Only idle-reap sessions that actually held a timed lease.
+ had_lease = int(s.get("lease_until") or 0) > 0 or bool(s.get("owner_id"))
+ idle = (
+ REAP_ON_IDLE
+ and had_lease
+ and _lease_expired(s, now)
+ and int(s.get("lease_until") or 0) > 0
+ )
+ # Dead Xvnc always reaped; idle lease-expired also reaped (stop VNC load).
+ if not (dead or idle):
+ continue
+ display = s.get("display") or ""
+ if display:
+ self._close_display_cache(display)
+ killed = _kill_session_procs(s)
+ del pool[sid]
+ reaped.append(
+ {
+ "session_id": sid,
+ "reason": "dead" if dead else "lease_expired",
+ "via": reason,
+ "owner_id": s.get("owner_id") or "",
+ "killed": killed,
+ }
+ )
+ log.info(
+ "reaped session %s reason=%s owner=%s",
+ sid,
+ "dead" if dead else "lease_expired",
+ s.get("owner_id"),
+ )
+ if reaped:
+ _write_pool(pool)
+ return reaped
+
+ async def reap_idle_desktops(self) -> dict:
+ """Tear down pool sessions whose lease expired or whose Xvnc died.
+
+ Frees the exclusive lock and stops Xvnc + websockify to avoid load.
+ Does not touch the host default display (e.g. :1 reauth Chrome).
+ """
+
+ def _sync() -> dict:
+ with _PoolLock():
+ pool = _read_pool()
+ reaped = self._reap_pool_locked(pool, reason="idle-reap")
+ return {
+ "ok": True,
+ "reaped": reaped,
+ "count": len(reaped),
+ "remaining": len(pool),
+ }
+
+ return await asyncio.get_event_loop().run_in_executor(None, _sync)
+
+ async def list_desktops(self) -> dict:
+ # Opportunistic reap so list stays honest under multi-agent load.
+ with _PoolLock():
+ pool = _read_pool()
+ self._reap_pool_locked(pool, reason="list-precheck")
+ pool = _read_pool()
+ sessions = []
+ now = _now()
+ for _sid, s in pool.items():
+ sessions.append(
+ {
+ **s,
+ "alive": self._session_alive(s),
+ "lease_expired": _lease_expired(s, now),
+ }
+ )
+ return {"ok": True, "count": len(sessions), "sessions": sessions}
+
+
+# ─── macOS backend ───────────────────────────────────────────────────────────
+class MacBackend:
+ """macOS backend: screencapture + cliclick/osascript driving the one logged-in session.
+
+ There is exactly one user desktop on macOS, so there is no Xvnc pool. acquire/list/
+ release operate on a single stable session bound to the real display (mac:main), and
+ release_desktop only tears down the optional websockify/VNC bridge — never the user
+ session. Screen Sharing (built-in VNC, port 5900) is bridged to noVNC via websockify
+ when available; if Screen Sharing is off, the session is still returned with a hint.
+ """
+
+ name = "mac"
+
+ # button → (single-click verb, double-click verb). macOS/cliclick has no
+ # native middle-click, so button=2 is reported as unsupported rather than
+ # silently mis-mapped to a right-click. button 4/5 are scroll, handled in click().
+ _BTN = {1: ("c", "dc"), 3: ("rc", "rc")}
+
+ def __init__(self) -> None:
+ self._bridge_pid: Optional[int] = None
+
+ # ── helpers ───────────────────────────────────────────────────────────
+ def _resolve_display(self, session_id: str = "") -> str:
+ """macOS has exactly one session. Empty or MAC_SESSION_ID → the real display;
+ any other id is rejected (there is no pool to look it up in)."""
+ if not session_id or session_id == MAC_SESSION_ID:
+ return MAC_DISPLAY
+ raise ValueError(
+ f"unknown session_id: {session_id} (macOS has a single session: {MAC_SESSION_ID!r})"
+ )
+
+ async def _run(self, *argv: str) -> tuple[int, str, str]:
+ """Run a system binary directly (no shell), return (rc, stdout, stderr)."""
+ proc = await asyncio.create_subprocess_exec(
+ *argv,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ out, err = await proc.communicate()
+ return (
+ proc.returncode or 0,
+ out.decode(errors="replace"),
+ err.decode(errors="replace"),
+ )
+
+ def _cliclick(self) -> str:
+ c = BIN["cliclick"]
+ if not c:
+ raise RuntimeError("cliclick not installed — run: brew install cliclick")
+ return c
+
+ # ── primitives ────────────────────────────────────────────────────────
+ async def screenshot(self, session_id, region, fmt, max_width, use_cache) -> dict:
+ from PIL import Image
+
+ display = self._resolve_display(session_id)
+ if not BIN["screencapture"]:
+ raise RuntimeError("screencapture not found")
+ ext = "jpg" if fmt == "jpeg" else "png"
+ cap_fmt = "jpg" if fmt == "jpeg" else "png"
+ raw_path = SHOT_DIR / f"raw-{uuid.uuid4().hex[:8]}.{ext}"
+ # -x silent, -t format, capture main display (default).
+ argv = ["-x", "-t", cap_fmt]
+ if region:
+ x, y, w, h = (int(v) for v in region.split(","))
+ argv += ["-R", f"{x},{y},{w},{h}"]
+ argv.append(str(raw_path))
+ t0 = time.time()
+ rc, _out, err = await self._run(BIN["screencapture"], *argv)
+ grab_ms = int((time.time() - t0) * 1000)
+ if rc != 0 or not raw_path.exists():
+ raise RuntimeError(f"screencapture failed (rc={rc}): {err.strip()}")
+ try:
+ img = Image.open(raw_path).convert("RGB")
+ r = _encode_screenshot(img, display, grab_ms, fmt, max_width, use_cache)
+ finally:
+ try:
+ raw_path.unlink(missing_ok=True)
+ except OSError:
+ pass
+ return {"ok": True, "display": display, **r}
+
+ async def click(self, x, y, button, double, session_id) -> dict:
+ display = self._resolve_display(session_id)
+ cc = self._cliclick()
+ # 4/5 scroll buttons → delegate to scroll for X11 parity.
+ if button in (4, 5):
+ return await self.scroll("up" if button == 4 else "down", 1, x, y, session_id)
+ verbs = self._BTN.get(button)
+ if verbs is None:
+ return {
+ "ok": False,
+ "error": f"button {button} unsupported on macOS "
+ "(no middle-click; use 1=left or 3=right)",
+ "x": x,
+ "y": y,
+ "button": button,
+ "double": double,
+ "display": display,
+ }
+ # cliclick has no double-right verb, so synthesize it with two right-clicks.
+ if double and button == 3:
+ rc, _out, err = await self._run(cc, f"rc:{x},{y}", f"rc:{x},{y}")
+ else:
+ prefix = verbs[1] if double else verbs[0]
+ rc, _out, err = await self._run(cc, f"{prefix}:{x},{y}")
+ if rc != 0:
+ raise RuntimeError(f"cliclick failed (rc={rc}): {err.strip()}")
+ return {
+ "ok": True,
+ "x": x,
+ "y": y,
+ "button": button,
+ "double": double,
+ "display": display,
+ }
+
+ async def type_text(self, text, session_id, delay_ms) -> dict:
+ display = self._resolve_display(session_id)
+ cc = self._cliclick()
+ # cliclick t: types literally; w:<ms> sets inter-keystroke wait.
+ args = []
+ if delay_ms:
+ args.append(f"w:{delay_ms}")
+ args.append(f"t:{text}")
+ rc, _out, err = await self._run(cc, *args)
+ if rc != 0:
+ raise RuntimeError(f"cliclick failed (rc={rc}): {err.strip()}")
+ return {"ok": True, "chars": len(text), "display": display}
+
+ async def keypress(self, key, modifiers, session_id) -> dict:
+ display = self._resolve_display(session_id)
+ cc = self._cliclick()
+ mods = modifiers or []
+ # Map X11-style modifier names → cliclick kd/ku modifier names.
+ mod_map = {
+ "control": "ctrl",
+ "ctrl": "ctrl",
+ "alt": "alt",
+ "option": "alt",
+ "meta": "cmd",
+ "super": "cmd",
+ "command": "cmd",
+ "cmd": "cmd",
+ "shift": "shift",
+ }
+ cmods = [mod_map.get(m.lower(), m.lower()) for m in mods]
+ # Map common X11 keysyms → cliclick key-press tokens (kp:).
+ key_map = {
+ "Return": "return",
+ "Enter": "return",
+ "Tab": "tab",
+ "Escape": "esc",
+ "space": "space",
+ "BackSpace": "delete",
+ "Delete": "fwd-delete",
+ "Up": "arrow-up",
+ "Down": "arrow-down",
+ "Left": "arrow-left",
+ "Right": "arrow-right",
+ "Home": "home",
+ "End": "end",
+ "Page_Up": "page-up",
+ "Page_Down": "page-down",
+ }
+ args: list[str] = []
+ for m in cmods:
+ args.append(f"kd:{m}")
+ tok = key_map.get(key)
+ if tok:
+ args.append(f"kp:{tok}")
+ elif len(key) == 1:
+ # single character → type it (with modifiers held, e.g. cmd+a).
+ args.append(f"t:{key}")
+ else:
+ args.append(f"kp:{key.lower()}")
+ for m in reversed(cmods):
+ args.append(f"ku:{m}")
+ rc, _out, err = await self._run(cc, *args)
+ if rc != 0:
+ raise RuntimeError(f"cliclick failed (rc={rc}): {err.strip()}")
+ return {"ok": True, "key": key, "modifiers": mods, "display": display}
+
+ async def scroll(self, direction, amount, x, y, session_id) -> dict:
+ display = self._resolve_display(session_id)
+ # Optionally warp the pointer first (cliclick m:) so the scroll lands there.
+ if x >= 0 and y >= 0 and BIN["cliclick"]:
+ await self._run(BIN["cliclick"], f"m:{x},{y}")
+ # Synthesize line-unit scroll-wheel CGEvents. AppleScript "System Events"
+ # has no working `scroll` verb (errors -1708), so post the event via the
+ # macOS system framework Python (always ships Quartz/pyobjc) — no new dep.
+ # Wheel deltas: +y scrolls up, +x scrolls left.
+ d = direction.lower()
+ dy = dx = 0
+ if d == "up":
+ dy = amount
+ elif d == "down":
+ dy = -amount
+ elif d == "left":
+ dx = amount
+ elif d == "right":
+ dx = -amount
+ else:
+ dy = -amount
+ rc, _out, err = await self._run(MAC_SYSTEM_PYTHON, "-c", _MAC_SCROLL_PY, str(dy), str(dx))
+ if rc != 0:
+ raise RuntimeError(f"scroll failed (rc={rc}): {err.strip()}")
+ return {
+ "ok": True,
+ "direction": direction,
+ "amount": amount,
+ "display": display,
+ }
+
+ async def list_windows(self, session_id) -> dict:
+ display = self._resolve_display(session_id)
+ if not BIN["osascript"]:
+ raise RuntimeError("osascript not found")
+ # Enumerate visible app windows + bounds via System Events; tab-delimited rows.
+ script = (
+ 'set out to ""\n'
+ 'tell application "System Events"\n'
+ " repeat with p in (every process whose visible is true)\n"
+ " repeat with w in (every window of p)\n"
+ " try\n"
+ " set pos to position of w\n"
+ " set sz to size of w\n"
+ ' set out to out & (name of p) & "\\t" & (name of w) & "\\t" & '
+ '(item 1 of pos) & "\\t" & (item 2 of pos) & "\\t" & '
+ '(item 1 of sz) & "\\t" & (item 2 of sz) & "\\n"\n'
+ " end try\n"
+ " end repeat\n"
+ " end repeat\n"
+ "end tell\n"
+ "return out"
+ )
+ rc, out, err = await self._run(BIN["osascript"], "-e", script)
+ if rc != 0:
+ # Accessibility not granted, or transient — degrade gracefully like X11.
+ log.warning("list_windows osascript failed (rc=%s): %s", rc, err.strip())
+ return {"ok": True, "windows": [], "display": display}
+ wins: list[dict] = []
+ for line in out.splitlines():
+ parts = line.split("\t")
+ if len(parts) != 6:
+ continue
+ app, wname, px, py, sw, sh = parts
+ try:
+ wins.append(
+ {
+ "name": f"{app}: {wname}" if wname else app,
+ "x": int(px),
+ "y": int(py),
+ "w": int(sw),
+ "h": int(sh),
+ }
+ )
+ except ValueError:
+ continue
+ return {"ok": True, "windows": wins, "display": display}
+
+ async def launch_app(self, command, session_id) -> dict:
+ display = self._resolve_display(session_id)
+ if not BIN["open"]:
+ raise RuntimeError("open not found")
+ # Heuristic: a bare token → treat as app name (open -a); else open the path/URL.
+ if " " not in command and "/" not in command:
+ argv = [BIN["open"], "-a", command]
+ else:
+ argv = [BIN["open"], command]
+ proc = await asyncio.create_subprocess_exec(
+ *argv,
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ _out, err = await proc.communicate()
+ await asyncio.sleep(1.5)
+ if proc.returncode != 0:
+ return {
+ "ok": False,
+ "error": f"open failed: {err.decode(errors='replace').strip()}",
+ "command": command,
+ "display": display,
+ }
+ return {"ok": True, "command": command, "pid": proc.pid, "display": display}
+
+ # ── single-session "pool" ────────────────────────────────────────────
+ async def _start_bridge(self) -> dict:
+ """Bridge built-in Screen Sharing (VNC :5900) → noVNC via websockify if possible.
+
+ Never fails the acquire. Returns fields merged into the session record.
+ """
+ vnc_up = _port_open(MAC_VNC_PORT)
+ extra: dict[str, Any] = {
+ "vnc_port": MAC_VNC_PORT,
+ "screen_sharing_enabled": vnc_up,
+ }
+ if not vnc_up:
+ extra["vnc_hint"] = (
+ "macOS Screen Sharing (VNC) is off — enable it in System Settings → "
+ "General → Sharing → Screen Sharing to get a live noVNC view."
+ )
+ return extra
+ if not BIN["websockify"]:
+ extra["vnc_hint"] = (
+ "Screen Sharing is on but websockify is missing — "
+ "pip install websockify (or brew install websockify) for a noVNC bridge."
+ )
+ return extra
+ if self._bridge_pid and _pid_alive(self._bridge_pid):
+ extra["websockify_pid"] = self._bridge_pid
+ extra["novnc_port"] = MAC_NOVNC_PORT
+ extra["novnc_url"] = f"http://localhost:{MAC_NOVNC_PORT}"
+ return extra
+ if not _port_free(MAC_NOVNC_PORT):
+ # Something already bridging on this port — reuse it.
+ extra["novnc_port"] = MAC_NOVNC_PORT
+ extra["novnc_url"] = f"http://localhost:{MAC_NOVNC_PORT}"
+ return extra
+ log_path = SESSIONS_DIR / f"{MAC_SESSION_ID}.log"
+ log_fh = log_path.open("a")
+ ws = subprocess.Popen(
+ [BIN["websockify"], str(MAC_NOVNC_PORT), f"127.0.0.1:{MAC_VNC_PORT}"],
+ stdout=log_fh,
+ stderr=subprocess.STDOUT,
+ start_new_session=True,
+ )
+ self._bridge_pid = ws.pid
+ extra["websockify_pid"] = ws.pid
+ extra["novnc_port"] = MAC_NOVNC_PORT
+ extra["novnc_url"] = f"http://localhost:{MAC_NOVNC_PORT}"
+ extra["log_path"] = str(log_path)
+ return extra
+
+ def _session_record(self, geometry: str, bridge: dict) -> dict:
+ return {
+ "session_id": MAC_SESSION_ID,
+ "display": MAC_DISPLAY,
+ "geometry": geometry,
+ "created_at": int(time.time()),
+ "novnc_url": bridge.get("novnc_url"),
+ **bridge,
+ }
+
+ @staticmethod
+ def _session_alive(sess: dict) -> bool:
+ """A mac session is live iff its real display is up (VNC reachable) — or, when
+ Screen Sharing is off, the bridge port we recorded for it. Falls back to the
+ VNC port for the canonical session."""
+ if sess.get("session_id") == MAC_SESSION_ID:
+ return _port_open(MAC_VNC_PORT)
+ ws = sess.get("websockify_pid")
+ if ws:
+ return _pid_alive(ws)
+ return False
+
+ async def ensure_desktop(self, geometry: str = DEFAULT_GEOMETRY, owner_id: str = "") -> dict:
+ # Single real desktop — lease is advisory; second agent is warned but can share.
+ return await self.acquire_desktop(geometry, owner_id=owner_id, force_new=False)
+
+ async def acquire_desktop(
+ self, geometry: str = DEFAULT_GEOMETRY, owner_id: str = "", force_new: bool = False
+ ) -> dict:
+ # macOS: one real session. Persist a stable record; bridge VNC best-effort.
+ owner = (owner_id or "").strip() or _default_owner_id()
+ bridge = await self._start_bridge()
+ session = self._session_record(geometry, bridge)
+ _apply_lease(session, owner)
+ session["owner_pid"] = os.getpid()
+ with _PoolLock():
+ pool = _read_pool()
+ prev = pool.get(MAC_SESSION_ID) or {}
+ if not force_new and prev.get("owner_id") and _lease_held_by_other(prev, owner):
+ # Cannot spawn a second real desktop on macOS.
+ return {
+ "ok": True,
+ "reused": True,
+ "spawned": False,
+ "shared": True,
+ "warning": (
+ "macOS has one desktop; another owner holds the lease. "
+ "Primitives still target the real session (limited isolation)."
+ ),
+ "other_owner": prev.get("owner_id"),
+ **{
+ **session,
+ **{k: prev.get(k, session.get(k)) for k in ("owner_id", "lease_until")},
+ },
+ "session_id": MAC_SESSION_ID,
+ }
+ # Pool hygiene: drop stale Linux desk-* entries if any.
+ pool = {MAC_SESSION_ID: session}
+ _write_pool(pool)
+ return {"ok": True, "reused": False, "spawned": False, **session}
+
+ async def heartbeat_desktop(self, session_id: str, owner_id: str = "") -> dict:
+ owner = (owner_id or "").strip() or _default_owner_id()
+ with _PoolLock():
+ pool = _read_pool()
+ sess = pool.get(session_id) or pool.get(MAC_SESSION_ID)
+ if not sess:
+ return {"ok": False, "error": f"unknown session_id: {session_id}"}
+ _apply_lease(sess, owner)
+ pool[sess["session_id"]] = sess
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "session_id": sess["session_id"],
+ "owner_id": sess.get("owner_id"),
+ "lease_until": sess.get("lease_until"),
+ }
+
+ async def reap_idle_desktops(self) -> dict:
+ # macOS: only drop expired lease metadata + optional websockify bridge.
+ # Never terminate the user's login session / Screen Sharing.
+ reaped: list[dict] = []
+ with _PoolLock():
+ pool = _read_pool()
+ sess = pool.get(MAC_SESSION_ID)
+ if (
+ sess
+ and REAP_ON_IDLE
+ and int(sess.get("lease_until") or 0) > 0
+ and _lease_expired(sess)
+ ):
+ _clear_lease(sess)
+ pid = sess.get("websockify_pid") or self._bridge_pid
+ killed: list[dict] = []
+ if pid and _pid_alive(int(pid)):
+ try:
+ os.kill(int(pid), signal.SIGTERM)
+ killed.append({"websockify_pid": int(pid)})
+ except OSError:
+ pass
+ self._bridge_pid = None
+ pool[MAC_SESSION_ID] = sess
+ _write_pool(pool)
+ reaped.append(
+ {
+ "session_id": MAC_SESSION_ID,
+ "reason": "lease_expired",
+ "killed": killed,
+ "note": "user desktop kept; bridge only",
+ }
+ )
+ return {"ok": True, "reaped": reaped, "count": len(reaped), "remaining": 1}
+
+ async def release_desktop(self, session_id) -> dict:
+ # Only tear down the optional websockify bridge — never the user's session.
+ with _PoolLock():
+ pool = _read_pool()
+ sess = pool.get(session_id)
+ if not sess:
+ return {"ok": False, "error": f"unknown session_id: {session_id}"}
+ killed: list[dict] = []
+ pid = sess.get("websockify_pid") or self._bridge_pid
+ did_term = False
+ if pid and _pid_alive(pid):
+ try:
+ os.kill(pid, signal.SIGTERM)
+ killed.append({"websockify_pid": pid})
+ did_term = True
+ except OSError:
+ pass
+ if did_term:
+ await asyncio.sleep(0.3)
+ if pid and _pid_alive(pid):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ _clear_lease(sess)
+ pool[session_id] = sess
+ _write_pool(pool)
+ self._bridge_pid = None
+ _LAST_SHOT.pop(sess["display"], None)
+ pool.pop(session_id, None)
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "released": session_id,
+ "killed": killed,
+ "note": "macOS user session is never terminated — only the noVNC bridge.",
+ }
+
+ async def list_desktops(self) -> dict:
+ # Only ever surface the single mac session; drop any stale X11 entries.
+ pool = _read_pool()
+ sessions = []
+ for _sid, s in pool.items():
+ if s.get("session_id") != MAC_SESSION_ID:
+ continue
+ sessions.append({**s, "alive": self._session_alive(s)})
+ return {"ok": True, "count": len(sessions), "sessions": sessions}
+
+
+# ─── Windows backend (native desktop — single interactive session) ───────────
+class WinBackend:
+ """Windows native computer-use backend (single interactive desktop).
+
+ Multi-desktop Xvnc pools are Linux-only. On Windows we drive the real
+ logged-in session with the same tool signatures:
+
+ - screenshot: Pillow ImageGrab (GDI)
+ - click / type / keypress / scroll: pyautogui (optional) or ctypes SendInput
+ - list_windows: user32 EnumWindows
+ - launch_app: subprocess / os.startfile
+
+ Multi-agent: exclusive leases still apply, but there is only one real
+ desktop (shared warning if another owner holds the lease) — same model
+ as macOS.
+ """
+
+ name = "windows"
+ WIN_SESSION_ID = "win-main"
+
+ # Virtual-key map for common keypress names (subset of X11-style names).
+ _VK = {
+ "return": 0x0D,
+ "enter": 0x0D,
+ "tab": 0x09,
+ "escape": 0x1B,
+ "esc": 0x1B,
+ "backspace": 0x08,
+ "delete": 0x2E,
+ "space": 0x20,
+ "up": 0x26,
+ "down": 0x28,
+ "left": 0x25,
+ "right": 0x27,
+ "home": 0x24,
+ "end": 0x23,
+ "page_up": 0x21,
+ "page_down": 0x22,
+ "f1": 0x70,
+ "f2": 0x71,
+ "f3": 0x72,
+ "f4": 0x73,
+ "f5": 0x74,
+ "f6": 0x75,
+ "f7": 0x76,
+ "f8": 0x77,
+ "f9": 0x78,
+ "f10": 0x79,
+ "f11": 0x7A,
+ "f12": 0x7B,
+ }
+ _MOD_VK = {
+ "control": 0x11,
+ "ctrl": 0x11,
+ "alt": 0x12,
+ "shift": 0x10,
+ "win": 0x5B,
+ "meta": 0x5B,
+ "super": 0x5B,
+ "cmd": 0x5B,
+ }
+
+ def __init__(self) -> None:
+ self._session: dict = {
+ "session_id": self.WIN_SESSION_ID,
+ "display": "win:main",
+ "geometry": DEFAULT_GEOMETRY,
+ "novnc_url": None,
+ "created_at": _now(),
+ "limited": False,
+ "platform_note": (
+ "Windows native backend: single interactive desktop "
+ "(no Xvnc multi-seat pool). Requires an interactive session; "
+ "RDP/headless may need 'console' session."
+ ),
+ }
+ self._pyautogui = None
+ if IS_WIN:
+ try:
+ import pyautogui # type: ignore
+
+ pyautogui.FAILSAFE = False
+ pyautogui.PAUSE = 0.02
+ self._pyautogui = pyautogui
+ except Exception as e: # noqa: BLE001
+ log.warning("pyautogui unavailable (%s) — using ctypes SendInput", e)
+
+ def _resolve_display(self, session_id: str = "") -> str:
+ if session_id and session_id not in ("", self.WIN_SESSION_ID):
+ # Unknown pool ids are rejected so agents notice they are on Windows.
+ pool = _read_pool()
+ if session_id not in pool and session_id != self.WIN_SESSION_ID:
+ raise ValueError(
+ f"unknown session_id: {session_id} "
+ f"(Windows has a single session: {self.WIN_SESSION_ID!r})"
+ )
+ return "win:main"
+
+ @staticmethod
+ def _session_alive(sess: dict) -> bool:
+ return True
+
+ def _screen_size(self) -> tuple[int, int]:
+ if self._pyautogui is not None:
+ sz = self._pyautogui.size()
+ return int(sz.width), int(sz.height)
+ import ctypes
+
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ return int(user32.GetSystemMetrics(0)), int(user32.GetSystemMetrics(1))
+
+ def _take_screenshot(
+ self,
+ region: str = "",
+ fmt: str = "jpeg",
+ max_width: int = 0,
+ use_cache: bool = True,
+ ) -> dict:
+ from PIL import ImageGrab
+
+ t0 = time.time()
+ bbox = None
+ if region:
+ parts = [int(x.strip()) for x in region.split(",")]
+ if len(parts) == 4:
+ x, y, w, h = parts
+ bbox = (x, y, x + w, y + h)
+ img = ImageGrab.grab(bbox=bbox, all_screens=True)
+ path, meta = _encode_screenshot(img, fmt=fmt, max_width=max_width, use_cache=use_cache)
+ w, h = self._screen_size()
+ return {
+ "ok": True,
+ "path": str(path),
+ "display": "win:main",
+ "width": meta.get("width") or img.width,
+ "height": meta.get("height") or img.height,
+ "screen": f"{w}x{h}",
+ "sha": meta.get("sha"),
+ "cached": meta.get("cached", False),
+ "ms": int((time.time() - t0) * 1000),
+ }
+
+ def _sendinput_mouse(self, flags: int, dx: int = 0, dy: int = 0, data: int = 0) -> None:
+ import ctypes
+ from ctypes import wintypes
+
+ class MOUSEINPUT(ctypes.Structure):
+ _fields_ = [
+ ("dx", wintypes.LONG),
+ ("dy", wintypes.LONG),
+ ("mouseData", wintypes.DWORD),
+ ("dwFlags", wintypes.DWORD),
+ ("time", wintypes.DWORD),
+ ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong)),
+ ]
+
+ class INPUT(ctypes.Structure):
+ class _I(ctypes.Union):
+ _fields_ = [("mi", MOUSEINPUT)]
+
+ _anonymous_ = ("i",)
+ _fields_ = [("type", wintypes.DWORD), ("i", _I)]
+
+ inp = INPUT()
+ inp.type = 0 # INPUT_MOUSE
+ inp.mi = MOUSEINPUT(dx, dy, data, flags, 0, None)
+ ctypes.windll.user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(inp)) # type: ignore[attr-defined]
+
+ def _sendinput_key(self, vk: int, up: bool = False) -> None:
+ import ctypes
+ from ctypes import wintypes
+
+ class KEYBDINPUT(ctypes.Structure):
+ _fields_ = [
+ ("wVk", wintypes.WORD),
+ ("wScan", wintypes.WORD),
+ ("dwFlags", wintypes.DWORD),
+ ("time", wintypes.DWORD),
+ ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong)),
+ ]
+
+ class INPUT(ctypes.Structure):
+ class _I(ctypes.Union):
+ _fields_ = [("ki", KEYBDINPUT)]
+
+ _anonymous_ = ("i",)
+ _fields_ = [("type", wintypes.DWORD), ("i", _I)]
+
+ KEYEVENTF_KEYUP = 0x0002
+ inp = INPUT()
+ inp.type = 1 # INPUT_KEYBOARD
+ inp.ki = KEYBDINPUT(vk, 0, KEYEVENTF_KEYUP if up else 0, 0, None)
+ ctypes.windll.user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(inp)) # type: ignore[attr-defined]
+
+ def _click_impl(self, x: int, y: int, button: int = 1, double: bool = False) -> None:
+ if self._pyautogui is not None:
+ btn = {1: "left", 2: "middle", 3: "right"}.get(button, "left")
+ clicks = 2 if double else 1
+ self._pyautogui.click(x=x, y=y, button=btn, clicks=clicks)
+ return
+ import ctypes
+
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ user32.SetCursorPos(int(x), int(y))
+ down_up = {
+ 1: (0x0002, 0x0004), # LEFTDOWN/UP
+ 2: (0x0020, 0x0040), # MIDDLE
+ 3: (0x0008, 0x0010), # RIGHT
+ }.get(button, (0x0002, 0x0004))
+ n = 2 if double else 1
+ for _ in range(n):
+ self._sendinput_mouse(down_up[0])
+ self._sendinput_mouse(down_up[1])
+ time.sleep(0.03)
+
+ def _type_impl(self, text: str, delay_ms: int = 5) -> None:
+ if self._pyautogui is not None:
+ # interval in seconds
+ self._pyautogui.write(text, interval=max(0.0, delay_ms / 1000.0))
+ return
+ # Fallback: clipboard paste for reliability with unicode
+ try:
+ import ctypes
+
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
+ CF_UNICODETEXT = 13
+ GMEM_MOVEABLE = 0x0002
+ data = text.encode("utf-16-le") + b"\x00\x00"
+ user32.OpenClipboard(0)
+ user32.EmptyClipboard()
+ h = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
+ ptr = kernel32.GlobalLock(h)
+ ctypes.memmove(ptr, data, len(data))
+ kernel32.GlobalUnlock(h)
+ user32.SetClipboardData(CF_UNICODETEXT, h)
+ user32.CloseClipboard()
+ # Ctrl+V
+ self._sendinput_key(0x11, up=False) # VK_CONTROL
+ self._sendinput_key(0x56, up=False) # V
+ self._sendinput_key(0x56, up=True)
+ self._sendinput_key(0x11, up=True)
+ except Exception as e: # noqa: BLE001
+ raise RuntimeError(f"type_text failed without pyautogui: {e}") from e
+
+ def _keypress_impl(self, key: str, modifiers: Optional[list[str]] = None) -> None:
+ mods = [m.lower() for m in (modifiers or [])]
+ k = (key or "").lower()
+ if self._pyautogui is not None:
+ keys = []
+ for m in mods:
+ if m in ("control", "ctrl"):
+ keys.append("ctrl")
+ elif m in ("alt",):
+ keys.append("alt")
+ elif m in ("shift",):
+ keys.append("shift")
+ elif m in ("win", "meta", "super", "cmd"):
+ keys.append("win")
+ # map common names
+ pg_map = {
+ "return": "enter",
+ "escape": "esc",
+ "page_up": "pageup",
+ "page_down": "pagedown",
+ }
+ keys.append(pg_map.get(k, k))
+ self._pyautogui.hotkey(*keys) if len(keys) > 1 else self._pyautogui.press(keys[0])
+ return
+ held = [self._MOD_VK[m] for m in mods if m in self._MOD_VK]
+ vk = self._VK.get(k)
+ if vk is None and len(k) == 1:
+ import ctypes
+
+ vk = ctypes.windll.user32.VkKeyScanW(ord(k)) & 0xFF # type: ignore[attr-defined]
+ if vk is None:
+ raise ValueError(f"unsupported key on Windows: {key!r}")
+ for m in held:
+ self._sendinput_key(m, up=False)
+ self._sendinput_key(vk, up=False)
+ self._sendinput_key(vk, up=True)
+ for m in reversed(held):
+ self._sendinput_key(m, up=True)
+
+ def _scroll_impl(self, direction: str, amount: int, x: int, y: int) -> None:
+ if x >= 0 and y >= 0:
+ if self._pyautogui is not None:
+ self._pyautogui.moveTo(x, y)
+ else:
+ import ctypes
+
+ ctypes.windll.user32.SetCursorPos(int(x), int(y)) # type: ignore[attr-defined]
+ d = (direction or "down").lower()
+ if self._pyautogui is not None:
+ if d == "up":
+ self._pyautogui.scroll(amount)
+ elif d == "down":
+ self._pyautogui.scroll(-amount)
+ elif d == "left":
+ self._pyautogui.hscroll(-amount)
+ else:
+ self._pyautogui.hscroll(amount)
+ return
+ # MOUSEEVENTF_WHEEL = 0x0800, HWHEEL = 0x01000; data is wheel delta * 120
+ WHEEL = 0x0800
+ HWHEEL = 0x01000
+ delta = 120 * int(amount)
+ if d == "up":
+ self._sendinput_mouse(WHEEL, data=delta)
+ elif d == "down":
+ self._sendinput_mouse(WHEEL, data=-delta)
+ elif d == "left":
+ self._sendinput_mouse(HWHEEL, data=-delta)
+ else:
+ self._sendinput_mouse(HWHEEL, data=delta)
+
+ def _list_windows_impl(self) -> list[dict]:
+ import ctypes
+ from ctypes import wintypes
+
+ user32 = ctypes.windll.user32 # type: ignore[attr-defined]
+ EnumWindows = user32.EnumWindows
+ IsWindowVisible = user32.IsWindowVisible
+ GetWindowTextLengthW = user32.GetWindowTextLengthW
+ GetWindowTextW = user32.GetWindowTextW
+ GetWindowRect = user32.GetWindowRect
+ GetClassNameW = user32.GetClassNameW
+
+ results: list[dict] = []
+
+ class RECT(ctypes.Structure):
+ _fields_ = [
+ ("left", wintypes.LONG),
+ ("top", wintypes.LONG),
+ ("right", wintypes.LONG),
+ ("bottom", wintypes.LONG),
+ ]
+
+ @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
+ def _cb(hwnd, _lparam): # type: ignore[misc]
+ if not IsWindowVisible(hwnd):
+ return True
+ n = GetWindowTextLengthW(hwnd)
+ if n <= 0:
+ return True
+ buf = ctypes.create_unicode_buffer(n + 1)
+ GetWindowTextW(hwnd, buf, n + 1)
+ title = buf.value.strip()
+ if not title:
+ return True
+ rect = RECT()
+ GetWindowRect(hwnd, ctypes.byref(rect))
+ cls = ctypes.create_unicode_buffer(256)
+ GetClassNameW(hwnd, cls, 256)
+ results.append(
+ {
+ "name": title,
+ "class": cls.value,
+ "x": int(rect.left),
+ "y": int(rect.top),
+ "w": int(rect.right - rect.left),
+ "h": int(rect.bottom - rect.top),
+ "hwnd": int(hwnd),
+ }
+ )
+ return True
+
+ EnumWindows(_cb, 0)
+ return results
+
+ async def screenshot(self, session_id, region, fmt, max_width, use_cache) -> dict:
+ if not IS_WIN:
+ return {"ok": False, "error": "WinBackend only runs on Windows"}
+ self._resolve_display(session_id)
+ return await asyncio.get_event_loop().run_in_executor(
+ None, lambda: self._take_screenshot(region, fmt, max_width, use_cache)
+ )
+
+ async def click(self, x, y, button, double, session_id) -> dict:
+ if not IS_WIN:
+ return {"ok": False, "error": "WinBackend only runs on Windows"}
+ self._resolve_display(session_id)
+ await asyncio.get_event_loop().run_in_executor(
+ None, lambda: self._click_impl(int(x), int(y), int(button), bool(double))
+ )
+ return {
+ "ok": True,
+ "x": x,
+ "y": y,
+ "button": button,
+ "double": double,
+ "display": "win:main",
+ }
+
+ async def type_text(self, text, session_id, delay_ms) -> dict:
+ if not IS_WIN:
+ return {"ok": False, "error": "WinBackend only runs on Windows"}
+ self._resolve_display(session_id)
+ await asyncio.get_event_loop().run_in_executor(
+ None, lambda: self._type_impl(text, int(delay_ms))
+ )
+ return {"ok": True, "chars": len(text or ""), "display": "win:main"}
+
+ async def keypress(self, key, modifiers, session_id) -> dict:
+ if not IS_WIN:
+ return {"ok": False, "error": "WinBackend only runs on Windows"}
+ self._resolve_display(session_id)
+ await asyncio.get_event_loop().run_in_executor(
+ None, lambda: self._keypress_impl(key, modifiers)
+ )
+ return {"ok": True, "key": key, "modifiers": modifiers or [], "display": "win:main"}
+
+ async def scroll(self, direction, amount, x, y, session_id) -> dict:
+ if not IS_WIN:
+ return {"ok": False, "error": "WinBackend only runs on Windows"}
+ self._resolve_display(session_id)
+ await asyncio.get_event_loop().run_in_executor(
+ None, lambda: self._scroll_impl(direction, int(amount), int(x), int(y))
+ )
+ return {
+ "ok": True,
+ "direction": direction,
+ "amount": amount,
+ "display": "win:main",
+ }
+
+ async def list_windows(self, session_id) -> dict:
+ if not IS_WIN:
+ return {"ok": True, "windows": [], "display": "win:main", "note": "not on Windows"}
+ self._resolve_display(session_id)
+ wins = await asyncio.get_event_loop().run_in_executor(None, self._list_windows_impl)
+ return {"ok": True, "windows": wins, "display": "win:main", "count": len(wins)}
+
+ async def launch_app(self, command, session_id) -> dict:
+ if not IS_WIN:
+ return {"ok": False, "error": "WinBackend only runs on Windows"}
+ self._resolve_display(session_id)
+ cmd = (command or "").strip()
+ if not cmd:
+ return {"ok": False, "error": "empty command"}
+ try:
+ # Prefer startfile for apps/paths; fall back to shell.
+ if os.path.exists(cmd) or cmd.lower().endswith((".exe", ".bat", ".cmd", ".lnk")):
+ os.startfile(cmd) # type: ignore[attr-defined]
+ return {"ok": True, "command": cmd, "method": "startfile", "display": "win:main"}
+ proc = subprocess.Popen(
+ cmd,
+ shell=True,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ return {
+ "ok": True,
+ "command": cmd,
+ "pid": proc.pid,
+ "method": "shell",
+ "display": "win:main",
+ }
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}", "command": cmd}
+
+ async def ensure_desktop(self, geometry: str = DEFAULT_GEOMETRY, owner_id: str = "") -> dict:
+ owner = (owner_id or "").strip() or _default_owner_id()
+ geo = geometry or DEFAULT_GEOMETRY
+ w, h = (0, 0)
+ if IS_WIN:
+ try:
+ w, h = self._screen_size()
+ geo = f"{w}x{h}"
+ except Exception: # noqa: BLE001
+ pass
+ with _PoolLock():
+ pool = _read_pool()
+ prev = pool.get(self.WIN_SESSION_ID) or {}
+ if prev and _lease_held_by_other(prev, owner):
+ return {
+ **dict(self._session),
+ **prev,
+ "geometry": prev.get("geometry") or geo,
+ "ok": True,
+ "reused": True,
+ "spawned": False,
+ "shared": True,
+ "warning": (
+ "Windows has a single interactive desktop; "
+ "another owner holds the exclusive lease."
+ ),
+ "other_owner": prev.get("owner_id"),
+ }
+ s = dict(self._session)
+ _apply_lease(s, owner)
+ s["geometry"] = geo
+ s["owner_pid"] = os.getpid()
+ s["limited"] = False
+ if w and h:
+ s["screen"] = f"{w}x{h}"
+ pool[self.WIN_SESSION_ID] = s
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "reused": bool(prev),
+ "spawned": False,
+ "limited": False,
+ **s,
+ }
+
+ async def acquire_desktop(
+ self, geometry: str = DEFAULT_GEOMETRY, owner_id: str = "", force_new: bool = False
+ ) -> dict:
+ # force_new is a no-op: Windows cannot spawn a second interactive desktop.
+ return await self.ensure_desktop(geometry, owner_id=owner_id)
+
+ async def heartbeat_desktop(self, session_id: str, owner_id: str = "") -> dict:
+ owner = (owner_id or "").strip() or _default_owner_id()
+ with _PoolLock():
+ pool = _read_pool()
+ s = pool.get(session_id) or pool.get(self.WIN_SESSION_ID) or dict(self._session)
+ if _lease_held_by_other(s, owner):
+ return {
+ "ok": False,
+ "error": "lease held by another owner",
+ "owner_id": s.get("owner_id"),
+ "lease_until": s.get("lease_until"),
+ }
+ _apply_lease(s, owner)
+ pool[s.get("session_id") or self.WIN_SESSION_ID] = s
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "session_id": s.get("session_id") or self.WIN_SESSION_ID,
+ "owner_id": s.get("owner_id"),
+ "lease_until": s.get("lease_until"),
+ }
+
+ async def release_desktop(self, session_id: str) -> dict:
+ with _PoolLock():
+ pool = _read_pool()
+ if session_id in pool:
+ del pool[session_id]
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "released": session_id,
+ "killed": [],
+ "note": "Windows: interactive session kept; lease only released",
+ }
+
+ async def list_desktops(self) -> dict:
+ pool = _read_pool()
+ sessions = [{**s, "alive": True} for s in pool.values()]
+ if not sessions:
+ sessions = [{**self._session, "alive": True}]
+ return {"ok": True, "count": len(sessions), "sessions": sessions}
+
+ async def reap_idle_desktops(self) -> dict:
+ reaped: list[dict] = []
+ with _PoolLock():
+ pool = _read_pool()
+ for sid in list(pool.keys()):
+ s = pool[sid]
+ if int(s.get("lease_until") or 0) > 0 and _lease_expired(s):
+ del pool[sid]
+ reaped.append({"session_id": sid, "reason": "lease_expired"})
+ if reaped:
+ _write_pool(pool)
+ return {
+ "ok": True,
+ "reaped": reaped,
+ "count": len(reaped),
+ "remaining": len(_read_pool()),
+ "note": "Windows: lease metadata only (no VNC process teardown)",
+ }
+
+
+# ─── Backend dispatch ─────────────────────────────────────────────────────────
+if IS_MAC:
+ BACKEND: Backend = MacBackend()
+elif IS_WIN:
+ BACKEND = WinBackend()
+else:
+ BACKEND = X11Backend()
+log.info("active backend: %s (platform=%s)", BACKEND.name, platform.system())
+
+
+def _resolve_display(session_id: str = "") -> str:
+ """Module-level convenience used by compound tools — delegates to the backend."""
+ return BACKEND._resolve_display(session_id) # type: ignore[attr-defined]
+
+
+# ─── FastMCP instance ────────────────────────────────────────────────────────
+mcp = FastMCP(
+ name="desktop-act",
+ instructions=(
+ "Computer-use primitives + multi-desktop pool + autonomous act() loop. "
+ "OS-agnostic: X11/Xvnc pool on Linux; screencapture+cliclick on macOS; "
+ "ImageGrab+pyautogui/SendInput on Windows (single interactive desktop). "
+ "Multi-agent: call ensure_desktop(owner_id=…) — exclusive lease per agent; "
+ "on Linux, busy seats auto-spawn a new Xvnc; on macOS/Windows only one "
+ "real desktop exists (shared lease warning if another owner holds it). "
+ "Idle/lease-expired sessions are reaped (Linux also stops VNC). "
+ "Pass session_id to primitives. Optimized: SHA-dedupe screenshot cache, JPEG default."
+ ),
+)
+
+
+# ─── Primitive tools (delegate to BACKEND) ───────────────────────────────────
+async def screenshot(
+ session_id: str = "",
+ region: str = "",
+ fmt: str = "jpeg",
+ max_width: int = 1280,
+ use_cache: bool = True,
+) -> dict:
+ """Capture the desktop with SHA dedupe cache + optional downscale.
+
+ Args:
+ session_id: pool session (empty → default desktop).
+ region: "x,y,w,h" sub-rect (empty → full screen).
+ fmt: 'jpeg' (default, smaller/faster) or 'png' (lossless).
+ max_width: downscale width preserving aspect; 0 = full res.
+ use_cache: skip resave when SHA matches previous frame.
+ """
+ try:
+ return await BACKEND.screenshot(session_id, region, fmt, max_width, use_cache)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def click(
+ x: int, y: int, button: int = 1, double: bool = False, session_id: str = ""
+) -> dict:
+ """Click at absolute coords. button: 1=L 2=M 3=R 4=scrollUp 5=scrollDown."""
+ try:
+ return await BACKEND.click(x, y, button, double, session_id)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def type_text(text: str, session_id: str = "", delay_ms: int = 5) -> dict:
+ """Type a string into the focused window. Default delay_ms=5."""
+ try:
+ return await BACKEND.type_text(text, session_id, delay_ms)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def keypress(key: str, modifiers: Optional[list[str]] = None, session_id: str = "") -> dict:
+ """Press a key chord. e.g. key='Return', modifiers=['Control']."""
+ try:
+ return await BACKEND.keypress(key, modifiers, session_id)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def scroll(
+ direction: str, amount: int = 3, x: int = -1, y: int = -1, session_id: str = ""
+) -> dict:
+ """Scroll up|down|left|right. amount=clicks. Optional warp to x,y first."""
+ try:
+ return await BACKEND.scroll(direction, amount, x, y, session_id)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def list_windows(session_id: str = "") -> dict:
+ """Enumerate top-level windows + geometry."""
+ try:
+ return await BACKEND.list_windows(session_id)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def launch_app(command: str, session_id: str = "") -> dict:
+ """Spawn a GUI app (Linux: 'chromium'/'xterm'; macOS: app name or path via open)."""
+ try:
+ return await BACKEND.launch_app(command, session_id)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def batch(actions: list[dict], session_id: str = "") -> dict:
+ """Execute multiple primitives in one MCP round-trip.
+
+ Each action: {"op": "click"|"type_text"|"keypress"|"scroll"|"sleep_ms", ...args}
+ """
+ results: list[dict] = []
+ try:
+ for a in actions:
+ op = a.get("op")
+ if op == "click":
+ r = await click(
+ a["x"],
+ a["y"],
+ a.get("button", 1),
+ a.get("double", False),
+ session_id,
+ )
+ elif op == "type_text":
+ r = await type_text(a["text"], session_id, a.get("delay_ms", 5))
+ elif op == "keypress":
+ r = await keypress(a["key"], a.get("modifiers"), session_id)
+ elif op == "scroll":
+ r = await scroll(
+ a["direction"],
+ a.get("amount", 3),
+ a.get("x", -1),
+ a.get("y", -1),
+ session_id,
+ )
+ elif op == "sleep_ms":
+ await asyncio.sleep(int(a.get("ms", 100)) / 1000)
+ r = {"ok": True, "slept_ms": a.get("ms")}
+ else:
+ r = {"ok": False, "error": f"unknown op: {op}"}
+ results.append(r)
+ if not r.get("ok"):
+ break
+ return {
+ "ok": all(x.get("ok") for x in results),
+ "results": results,
+ "count": len(results),
+ }
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}", "results": results}
+
+
+# ─── Compound single-round-trip tools ────────────────────────────────────────
+async def observe(
+ session_id: str = "",
+ screenshot_format: str = "jpeg",
+ screenshot_max_width: int = 1280,
+) -> dict:
+ """Screenshot + window list in one round-trip (no action taken)."""
+ from fastmcp.utilities.types import Image
+
+ try:
+ t0 = time.time()
+ display = _resolve_display(session_id)
+ windows = await list_windows(session_id)
+ shot = await BACKEND.screenshot(
+ session_id, "", screenshot_format, screenshot_max_width, True
+ )
+ return {
+ "ok": True,
+ "display": display,
+ "screenshot": shot,
+ "image": Image(path=shot["path"]).to_image_content(),
+ "windows": windows.get("windows", []),
+ "total_ms": int((time.time() - t0) * 1000),
+ }
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def act_step(
+ action: dict,
+ settle_ms: int = 200,
+ screenshot_format: str = "jpeg",
+ screenshot_max_width: int = 1280,
+ session_id: str = "",
+) -> dict:
+ """ONE round-trip: execute action → settle → screenshot → return inline image + hint.
+
+ action: {"op":"click","x":...,"y":...} or {"op":"type_text","text":"..."} etc.
+ Use {"op":"batch","actions":[...]} for multi-step sequences.
+ """
+ from fastmcp.utilities.types import Image
+
+ try:
+ t0 = time.time()
+ display = _resolve_display(session_id)
+ op = action.get("op", "noop")
+ if op == "batch":
+ action_result = await batch(action.get("actions", []), session_id)
+ elif op == "click":
+ action_result = await click(
+ action["x"],
+ action["y"],
+ action.get("button", 1),
+ action.get("double", False),
+ session_id,
+ )
+ elif op == "type_text":
+ action_result = await type_text(action["text"], session_id, action.get("delay_ms", 5))
+ elif op == "keypress":
+ action_result = await keypress(action["key"], action.get("modifiers"), session_id)
+ elif op == "scroll":
+ action_result = await scroll(
+ action["direction"],
+ action.get("amount", 3),
+ action.get("x", -1),
+ action.get("y", -1),
+ session_id,
+ )
+ elif op == "launch_app":
+ action_result = await launch_app(action["command"], session_id)
+ elif op == "noop":
+ action_result = {"ok": True, "noop": True}
+ else:
+ return {"ok": False, "error": f"unknown action.op: {op}"}
+
+ pre_windows = await list_windows(session_id)
+ if settle_ms:
+ await asyncio.sleep(settle_ms / 1000)
+ post_windows = await list_windows(session_id)
+ shot = await BACKEND.screenshot(
+ session_id, "", screenshot_format, screenshot_max_width, True
+ )
+
+ pre_n = len(pre_windows.get("windows", []))
+ post_n = len(post_windows.get("windows", []))
+ delta = post_n - pre_n
+ if delta > 0:
+ hint = f"new window(s) appeared ({delta}) — likely menu/dialog/launched app"
+ elif delta < 0:
+ hint = f"window(s) closed ({-delta}) — action may have triggered close"
+ elif shot.get("cached"):
+ hint = "screen unchanged — action may not have taken effect; verify focus/selector"
+ else:
+ hint = "screen changed (no window delta) — focus/content change; reason from screenshot"
+
+ return {
+ "ok": action_result.get("ok", False),
+ "action_result": action_result,
+ "screenshot": shot,
+ "image": Image(path=shot["path"]).to_image_content(),
+ "window_count_delta": delta,
+ "hint": hint,
+ "display": display,
+ "total_ms": int((time.time() - t0) * 1000),
+ }
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+# ─── Multi-desktop pool tools (delegate to BACKEND) ──────────────────────────
+async def ensure_desktop(
+ geometry: str = DEFAULT_GEOMETRY,
+ owner_id: str = "",
+) -> dict:
+ """Get an exclusive desktop for this agent (multi-agent safe).
+
+ - Reuses this owner_id's live leased session (refreshes TTL).
+ - Else claims an idle/expired pool seat.
+ - Else auto-spawns a new Xvnc + noVNC on the next free display/port.
+ Never steals a non-expired lease from another owner.
+
+ Pass owner_id (or set DESKTOP_ACT_OWNER). Returns session_id + novnc_url.
+ """
+ try:
+ return await BACKEND.ensure_desktop(geometry, owner_id=owner_id)
+ except Exception as e: # noqa: BLE001
+ log.exception("ensure_desktop failed")
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def acquire_desktop(
+ geometry: str = DEFAULT_GEOMETRY,
+ owner_id: str = "",
+ force_new: bool = False,
+) -> dict:
+ """Acquire a desktop session (multi-agent aware).
+
+ Linux: by default same as ensure_desktop (reuse own lease or spawn if busy).
+ force_new=True always spawns a fresh exclusive Xvnc seat.
+ macOS: returns the single real logged-in session (no second Xvnc).
+
+ Returns {session_id, display, novnc_url, geometry, owner_id, lease_until, ...}.
+ """
+ try:
+ return await BACKEND.acquire_desktop(geometry, owner_id=owner_id, force_new=force_new)
+ except Exception as e: # noqa: BLE001
+ log.exception("acquire_desktop failed")
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def heartbeat_desktop(session_id: str, owner_id: str = "") -> dict:
+ """Refresh the exclusive lease TTL so the idle reaper will not free this session.
+
+ Call periodically during long runs, or after idle gaps, while still using the desktop.
+ """
+ try:
+ return await BACKEND.heartbeat_desktop(session_id, owner_id=owner_id)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def release_desktop(session_id: str) -> dict:
+ """Release a session: free the exclusive lock and stop pool VNC processes.
+
+ Linux: kill the Xvnc + WM + websockify and free its ports.
+ macOS: tear down only the noVNC bridge — the user session is never terminated.
+ Call on agent stop / task end.
+ """
+ try:
+ return await BACKEND.release_desktop(session_id)
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def list_desktops() -> dict:
+ """Return all active sessions in the pool (reaps dead/idle seats first)."""
+ try:
+ return await BACKEND.list_desktops()
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+async def reap_idle_desktops() -> dict:
+ """Free locks and stop VNC for lease-expired or dead pool sessions.
+
+ Reduces host load when agents crash, stop, or go idle past DESKTOP_ACT_LEASE_TTL.
+ Does not touch the host default display (e.g. reauth Chrome on :1).
+ """
+ try:
+ return await BACKEND.reap_idle_desktops()
+ except Exception as e: # noqa: BLE001
+ return {"ok": False, "error": f"{type(e).__name__}: {e}"}
+
+
+# ─── High-level act() — claude-agent-sdk OAuth loop ──────────────────────────
+ACT_SYSTEM = """You are the desktop-act executor. You drive a desktop via the
+desktop-act MCP primitives (screenshot, click, type_text, keypress, scroll, list_windows,
+launch_app, observe, act_step, batch). The human watches via noVNC.
+
+Loop tightly: observe → reason → act_step → check result → repeat. Stay concise.
+Stop when the goal is complete or 3 consecutive actions fail."""
+
+
+async def act(
+ goal: str,
+ max_iterations: int = 20,
+ timeout_seconds: int = 600,
+ model: str = "claude-sonnet-5",
+ session_id: str = "",
+) -> dict:
+ """Autonomous goal execution via claude-agent-sdk (CLI OAuth, no API key).
+
+ Args:
+ goal: natural-language objective.
+ max_iterations: turn cap for the inner loop.
+ timeout_seconds: hard wall-clock cap.
+ model: model id for the inner agent (default: Claude Sonnet 5).
+ session_id: target a specific pool session (empty → default desktop).
+ """
+ run_id = uuid.uuid4().hex[:10]
+ log_path = LOG_DIR / f"act-{run_id}.log"
+ start = time.time()
+
+ try:
+ from claude_agent_sdk import ClaudeAgentOptions, query
+ except ImportError as e:
+ return {
+ "ok": False,
+ "error": f"claude-agent-sdk not installed: {e}",
+ "hint": "venv missing — re-run plugin install",
+ }
+
+ sys_prompt = ACT_SYSTEM
+ if session_id:
+ sys_prompt += f"\n\nTarget desktop session_id={session_id} for all primitives."
+
+ opts = ClaudeAgentOptions(
+ system_prompt=sys_prompt,
+ permission_mode="bypassPermissions",
+ max_turns=max_iterations,
+ model=model,
+ )
+
+ chunks: list[str] = []
+ try:
+
+ async def _run():
+ async for msg in query(prompt=goal, options=opts):
+ chunks.append(str(msg))
+
+ await asyncio.wait_for(_run(), timeout=timeout_seconds)
+ except asyncio.TimeoutError:
+ log_path.write_text(
+ "\n---\n".join(chunks) + f"\n\n*** TIMEOUT after {timeout_seconds}s ***"
+ )
+ return {
+ "ok": False,
+ "error": f"timeout after {timeout_seconds}s",
+ "turns_seen": len(chunks),
+ "log_path": str(log_path),
+ }
+ except Exception as e: # noqa: BLE001
+ log_path.write_text("\n---\n".join(chunks) + f"\n\n*** ERROR {type(e).__name__}: {e} ***")
+ return {
+ "ok": False,
+ "error": f"{type(e).__name__}: {e}",
+ "turns_seen": len(chunks),
+ "log_path": str(log_path),
+ }
+
+ log_path.write_text("\n---\n".join(chunks))
+ final = chunks[-1] if chunks else ""
+ shots = list(
+ dict.fromkeys(
+ re.findall(
+ r"/tmp/desktop-act-shots/[A-Za-z0-9_.-]+\.(?:png|jpg)",
+ "\n".join(chunks),
+ )
+ )
+ )
+
+ return {
+ "ok": True,
+ "result": final[-3000:],
+ "turns": len(chunks),
+ "screenshots": [p for p in shots if Path(p).exists()],
+ "log_path": str(log_path),
+ "duration_seconds": int(time.time() - start),
+ "backend": "claude-agent-sdk (OAuth/Max sub)",
+ "session_id": session_id or None,
+ }
+
+
+# ─── Status ──────────────────────────────────────────────────────────────────
+async def status() -> dict:
+ """Report MCP health, active backend, binary discovery, and pool state."""
+ try:
+ import claude_agent_sdk
+
+ sdk_ver = getattr(claude_agent_sdk, "__version__", "?")
+ sdk_ok = True
+ except ImportError:
+ sdk_ok = False
+ sdk_ver = "missing"
+
+ pool = _read_pool()
+ return {
+ "ok": sdk_ok and CLAUDE_CLI.exists(),
+ "platform": platform.system(),
+ "backend": BACKEND.name,
+ "claude_agent_sdk": sdk_ver,
+ "claude_cli": str(CLAUDE_CLI) if CLAUDE_CLI.exists() else "missing",
+ "auth_path": "OAuth via Claude Max subscription (no API key)",
+ "default_display": DEFAULT_DISPLAY,
+ "shot_dir": str(SHOT_DIR),
+ "log_dir": str(LOG_DIR),
+ "binaries": {k: v or "MISSING" for k, v in BIN.items()},
+ "pool_size": len(pool),
+ "default_geometry": DEFAULT_GEOMETRY,
+ "lease_ttl_sec": LEASE_TTL_SEC,
+ "reap_interval_sec": REAP_INTERVAL_SEC,
+ "auto_spawn": AUTO_SPAWN,
+ "pool_sessions": [
+ {
+ "session_id": s["session_id"],
+ "display": s["display"],
+ "novnc_url": s.get("novnc_url"),
+ "geometry": s["geometry"],
+ "owner_id": s.get("owner_id") or "",
+ "lease_until": s.get("lease_until") or 0,
+ "lease_expired": _lease_expired(s),
+ # Per-session liveness via the active backend (not a blanket probe).
+ "alive": BACKEND._session_alive(s), # type: ignore[attr-defined]
+ }
+ for s in pool.values()
+ # On mac, only surface the canonical session — never stale X11 rows.
+ if not IS_MAC or s.get("session_id") == MAC_SESSION_ID
+ ],
+ "display_range": "mac:main (single session)"
+ if IS_MAC
+ else f":{DISPLAY_NUM_MIN}-:{DISPLAY_NUM_MAX}",
+ }
+
+
+def _start_idle_reaper() -> None:
+ """Background thread: free locks + kill idle/dead pool VNC stacks."""
+ if REAP_INTERVAL_SEC <= 0 or not REAP_ON_IDLE:
+ log.info(
+ "idle reaper disabled (REAP_INTERVAL=%s REAP_ON_IDLE=%s)",
+ REAP_INTERVAL_SEC,
+ REAP_ON_IDLE,
+ )
+ return
+
+ def _loop() -> None:
+ while True:
+ try:
+ time.sleep(max(5, REAP_INTERVAL_SEC))
+ if hasattr(BACKEND, "reap_idle_desktops"):
+ # Sync path via asyncio.run is heavy; call locked reap when available.
+ if hasattr(BACKEND, "_reap_pool_locked"):
+ with _PoolLock():
+ pool = _read_pool()
+ reaped = BACKEND._reap_pool_locked(pool, reason="bg-idle") # type: ignore[attr-defined]
+ if reaped:
+ log.info("bg reaper removed %d session(s)", len(reaped))
+ else:
+ # macOS: use async tool path via new event loop
+ try:
+ asyncio.run(BACKEND.reap_idle_desktops()) # type: ignore[misc]
+ except Exception: # noqa: BLE001
+ pass
+ except Exception as e: # noqa: BLE001
+ log.warning("idle reaper tick failed: %s", e)
+
+ t = threading.Thread(target=_loop, name="desktop-act-reaper", daemon=True)
+ t.start()
+ log.info(
+ "idle reaper started interval=%ss lease_ttl=%ss",
+ REAP_INTERVAL_SEC,
+ LEASE_TTL_SEC,
+ )
+
+
+def _shutdown_owned_sessions() -> None:
+ """On process exit / signal: release sessions owned by this process or owner id."""
+ owner = _default_owner_id()
+ pid = os.getpid()
+ try:
+ with _PoolLock():
+ pool = _read_pool()
+ to_release = [
+ sid
+ for sid, s in pool.items()
+ if (s.get("owner_id") or "") == owner or int(s.get("owner_pid") or 0) == pid
+ ]
+ for sid in to_release:
+ if hasattr(BACKEND, "_release_locked"):
+ BACKEND._release_locked(pool, sid) # type: ignore[attr-defined]
+ log.info("shutdown released session %s", sid)
+ else:
+ # mac: clear lease + bridge only
+ s = pool.get(sid)
+ if s:
+ _clear_lease(s)
+ pool[sid] = s
+ if to_release and not hasattr(BACKEND, "_release_locked"):
+ _write_pool(pool)
+ except Exception as e: # noqa: BLE001
+ log.warning("shutdown release failed: %s", e)
+
+
+def _install_signal_handlers() -> None:
+ if RELEASE_ON_EXIT:
+ atexit.register(_shutdown_owned_sessions)
+ else:
+ log.info("RELEASE_ON_EXIT=0 — atexit will not free pool desktops (CLI mode)")
+
+ def _handle(signum, _frame): # type: ignore[no-untyped-def]
+ log.info("signal %s — releasing owned desktops", signum)
+ if RELEASE_ON_EXIT:
+ _shutdown_owned_sessions()
+ # Re-raise default for SIGTERM/SIGINT so the process exits.
+ signal.signal(signum, signal.SIG_DFL)
+ os.kill(os.getpid(), signum)
+
+ for sig in (signal.SIGTERM, signal.SIGINT):
+ try:
+ signal.signal(sig, _handle)
+ except Exception: # noqa: BLE001
+ pass
+
+
+_start_idle_reaper()
+_install_signal_handlers()
+
+if __name__ == "__main__":
+ log.info(
+ "desktop-act MCP starting — backend=%s pool=%s default_display=%s geometry=%s lease_ttl=%ss",
+ BACKEND.name,
+ POOL_PATH,
+ DEFAULT_DISPLAY,
+ DEFAULT_GEOMETRY,
+ LEASE_TTL_SEC,
+ )
+ mcp.run()
diff --git a/desktop-act/pyproject.toml b/desktop-act/pyproject.toml
new file mode 100644
index 00000000..d59a6f65
--- /dev/null
+++ b/desktop-act/pyproject.toml
@@ -0,0 +1,26 @@
+[project]
+name = "desktop-act"
+version = "0.2.0"
+description = "Computer-use MCP server with multi-desktop pool and multi-agent leases"
+requires-python = ">=3.11"
+readme = "README.md"
+license = { text = "MIT" }
+
+[tool.ruff]
+line-length = 100
+target-version = "py311"
+src = ["mcp-server", "cli", "tests"]
+
+[tool.ruff.lint]
+select = ["E", "F", "I", "W"]
+ignore = [
+ "E501", # long lines in system prompts / X11 tables
+]
+
+[tool.ruff.lint.per-file-ignores]
+"mcp-server/server.py" = ["E402"] # atexit/threading wiring after BACKEND
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+addopts = "-q"
+filterwarnings = ["ignore::DeprecationWarning"]
diff --git a/desktop-act/requirements.txt b/desktop-act/requirements.txt
new file mode 100644
index 00000000..1a9b9ec7
--- /dev/null
+++ b/desktop-act/requirements.txt
@@ -0,0 +1,20 @@
+aiohttp==3.14.3
+anthropic==0.120.2
+claude-agent-sdk==0.2.128
+fastmcp==3.4.5
+fastmcp-slim==3.4.5
+httpx==0.28.1
+httpx-sse==0.4.3
+# mcp 2.x exists on PyPI but claude-agent-sdk and fastmcp require mcp<2.0.
+mcp==1.29.0
+pillow==12.3.0
+pydantic==2.13.4
+pydantic-settings==2.14.2
+# pydantic 2.13.4 pins pydantic-core==2.46.4 exactly.
+pydantic_core==2.46.4
+# Linux-only: X11 primitives. On macOS the MacBackend uses system binaries
+# (screencapture, cliclick, osascript, open) and never imports Xlib.
+python-xlib==0.33; sys_platform == "linux"
+# Windows-only: optional high-level input. WinBackend falls back to ctypes
+# SendInput + clipboard paste if pyautogui is missing.
+pyautogui==0.9.54; sys_platform == "win32"
diff --git a/desktop-act/skills/desktop-act/SKILL.md b/desktop-act/skills/desktop-act/SKILL.md
new file mode 100644
index 00000000..e6f7ad84
--- /dev/null
+++ b/desktop-act/skills/desktop-act/SKILL.md
@@ -0,0 +1,58 @@
+---
+name: desktop-act
+description: "Cross-OS computer-use MCP: multi-agent exclusive desktop leases, Xvnc pool on Linux, single-session macOS/Windows. Use for GUI/desktop automation and concurrent agent desktops."
+---
+
+# desktop-act
+
+Computer-use primitives via `mcp__desktop-act__*` plus `act(goal)` (OAuth via
+claude-agent-sdk — no Anthropic API key).
+
+## Multi-agent (required pattern)
+
+```text
+ensure_desktop(owner_id="<agent-id>", geometry="2560x1440") # exclusive seat
+# … primitives with session_id …
+heartbeat_desktop(session_id) # long runs
+release_desktop(session_id) # on stop / idle done
+```
+
+If another agent holds every free seat, Linux **auto-spawns** a new Xvnc on the
+next free display/port. Leases expire (`DESKTOP_ACT_LEASE_TTL`); reaper frees
+the lock and **stops pool VNC** so idle seats do not thrash the host.
+
+## Architecture
+
+- Parent agent is the brain — primitives + screenshots, or hands-off `act(goal)`.
+- **Linux:** X11 + Xvnc/websockify pool (`:50`–`:99`), file-locked leases.
+- **macOS:** single interactive session (Screen Sharing → noVNC optional).
+- **Windows:** full WinBackend (ImageGrab + pyautogui/SendInput); single
+ interactive desktop only (no multi-seat pool). Needs a logged-in session.
+
+## Watching the desktop
+
+Pool session returns `novnc_url` (port base `DESKTOP_ACT_NOVNC_PORT_BASE`,
+default **6082**). Host default display (often `:1`) is separate and is never
+reaped by the idle reaper. Always prefer the returned URL over hardcoding ports.
+
+## Install
+
+- **With claude-ops:** `desktop-act@ops-marketplace` (co-installed by `/ops:setup`
+ and `/ops:update` via `plugin-dependencies.json`).
+- **Standalone:** marketplace add `Lifecycle-Innovations-Limited/desktop-act`,
+ then `desktop-act@desktop-act`.
+
+## When to use
+
+| Task | Approach |
+|------|----------|
+| Local app you need to click/type into | `desktop-act` primitives |
+| Concurrent agents needing isolated seats | Linux pool + `ensure_desktop(owner_id=…)` |
+| Hands-off goal | `mcp__desktop-act__act(goal, max_iterations=…)` |
+| Browser-only automation | Prefer browser MCP tools when no OS UI is required |
+
+## Defaults
+
+- `act` model: `claude-sonnet-5`
+- `act` max_iterations: `20` (not `max_steps`)
+- Python: `>=3.11`
diff --git a/desktop-act/tests/test_leases.py b/desktop-act/tests/test_leases.py
new file mode 100644
index 00000000..b229b4cc
--- /dev/null
+++ b/desktop-act/tests/test_leases.py
@@ -0,0 +1,99 @@
+"""Unit tests for multi-agent lease helpers (no Xvnc required)."""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+from pathlib import Path
+
+# Disable background reaper / exit release before loading the server module.
+os.environ["DESKTOP_ACT_REAP_INTERVAL"] = "0"
+os.environ["DESKTOP_ACT_RELEASE_ON_EXIT"] = "0"
+
+ROOT = Path(__file__).resolve().parents[1]
+SERVER = ROOT / "mcp-server" / "server.py"
+
+spec = importlib.util.spec_from_file_location("desktop_act_server", SERVER)
+assert spec and spec.loader
+mod = importlib.util.module_from_spec(spec)
+sys.modules["desktop_act_server"] = mod
+
+try:
+ import fastmcp # noqa: F401
+except ImportError: # pragma: no cover
+ import types
+
+ fake = types.ModuleType("fastmcp")
+
+ class _FastMCP:
+ def __init__(self, *a, **k):
+ pass
+
+ def tool(self, *a, **k):
+ def deco(fn):
+ return fn
+
+ return deco
+
+ def run(self):
+ pass
+
+ fake.FastMCP = _FastMCP
+ sys.modules["fastmcp"] = fake
+
+spec.loader.exec_module(mod)
+
+
+def test_lease_expired_when_no_lease():
+ assert mod._lease_expired({}) is True
+ assert mod._lease_expired({"lease_until": 0}) is True
+
+
+def test_apply_and_hold():
+ s: dict = {}
+ mod._apply_lease(s, "agent-a", ttl=120)
+ assert s["owner_id"] == "agent-a"
+ assert s["lease_until"] > mod._now()
+ assert mod._lease_held_by_other(s, "agent-b") is True
+ assert mod._lease_held_by_other(s, "agent-a") is False
+ s["lease_until"] = mod._now() - 10
+ assert mod._lease_held_by_other(s, "agent-b") is False
+ assert mod._lease_expired(s) is True
+
+
+def test_clear_lease():
+ s = {"owner_id": "x", "lease_until": 999999}
+ mod._clear_lease(s)
+ assert s["owner_id"] == ""
+ assert s["lease_until"] == 0
+
+
+def test_default_owner_env():
+ os.environ["DESKTOP_ACT_OWNER"] = "env-owner-xyz"
+ try:
+ assert mod._default_owner_id() == "env-owner-xyz"
+ finally:
+ del os.environ["DESKTOP_ACT_OWNER"]
+
+
+def test_backend_name_matches_platform():
+ assert mod.BACKEND.name in ("x11", "mac", "windows")
+
+
+if __name__ == "__main__":
+ test_lease_expired_when_no_lease()
+ test_apply_and_hold()
+ test_clear_lease()
+ test_default_owner_env()
+ test_backend_name_matches_platform()
+ print("ok")
+
+
+def test_pool_lock_roundtrip():
+ """Portable lock must enter/exit without error (fcntl or msvcrt)."""
+ with mod._PoolLock():
+ pool = mod._read_pool()
+ assert isinstance(pool, dict)
+ # Nested re-entry is not supported; just verify write under lock.
+ mod._write_pool(pool)
diff --git a/desktop-act/tests/test_win_backend.py b/desktop-act/tests/test_win_backend.py
new file mode 100644
index 00000000..e94c1568
--- /dev/null
+++ b/desktop-act/tests/test_win_backend.py
@@ -0,0 +1,153 @@
+"""WinBackend unit tests runnable on Linux CI (no Windows GUI required)."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import os
+import sys
+from pathlib import Path
+
+os.environ["DESKTOP_ACT_REAP_INTERVAL"] = "0"
+os.environ["DESKTOP_ACT_RELEASE_ON_EXIT"] = "0"
+
+ROOT = Path(__file__).resolve().parents[1]
+SERVER = ROOT / "mcp-server" / "server.py"
+
+spec = importlib.util.spec_from_file_location("desktop_act_server_win", SERVER)
+assert spec and spec.loader
+mod = importlib.util.module_from_spec(spec)
+sys.modules["desktop_act_server_win"] = mod
+
+try:
+ import fastmcp # noqa: F401
+except ImportError: # pragma: no cover
+ import types
+
+ fake = types.ModuleType("fastmcp")
+
+ class _FastMCP:
+ def __init__(self, *a, **k):
+ pass
+
+ def tool(self, *a, **k):
+ def deco(fn):
+ return fn
+
+ return deco
+
+ def run(self):
+ pass
+
+ fake.FastMCP = _FastMCP
+ sys.modules["fastmcp"] = fake
+
+spec.loader.exec_module(mod)
+
+
+REQUIRED_METHODS = (
+ "screenshot",
+ "click",
+ "type_text",
+ "keypress",
+ "scroll",
+ "list_windows",
+ "launch_app",
+ "ensure_desktop",
+ "acquire_desktop",
+ "heartbeat_desktop",
+ "release_desktop",
+ "list_desktops",
+ "reap_idle_desktops",
+)
+
+
+def test_winbackend_class_exists_with_full_surface():
+ assert hasattr(mod, "WinBackend")
+ wb = mod.WinBackend()
+ assert wb.name == "windows"
+ assert wb.WIN_SESSION_ID == "win-main"
+ for name in REQUIRED_METHODS:
+ assert callable(getattr(wb, name)), f"missing method {name}"
+
+
+def test_winbackend_primitives_guard_off_windows():
+ """On non-Windows hosts, GUI primitives must not call SendInput/ImageGrab."""
+ if mod.IS_WIN:
+ return # real Windows host: skip the off-platform guard
+ wb = mod.WinBackend()
+
+ async def _run():
+ shot = await wb.screenshot("", "", "jpeg", 0, True)
+ assert shot.get("ok") is False
+ assert "Windows" in (shot.get("error") or "")
+
+ click = await wb.click(10, 10, 1, False, "")
+ assert click.get("ok") is False
+
+ typed = await wb.type_text("hi", "", 5)
+ assert typed.get("ok") is False
+
+ key = await wb.keypress("return", [], "")
+ assert key.get("ok") is False
+
+ scroll = await wb.scroll("down", 3, -1, -1, "")
+ assert scroll.get("ok") is False
+
+ wins = await wb.list_windows("")
+ assert wins.get("ok") is True
+ assert wins.get("windows") == []
+
+ launch = await wb.launch_app("notepad", "")
+ assert launch.get("ok") is False
+
+ asyncio.run(_run())
+
+
+def test_winbackend_leases_on_any_platform():
+ """Lease metadata works without a real Windows desktop."""
+ wb = mod.WinBackend()
+ owner = f"win-test-{os.getpid()}"
+
+ async def _run():
+ ens = await wb.ensure_desktop(owner_id=owner)
+ assert ens.get("ok") is True
+ assert ens.get("session_id") == wb.WIN_SESSION_ID
+ assert ens.get("owner_id") == owner
+ assert int(ens.get("lease_until") or 0) > 0
+
+ hb = await wb.heartbeat_desktop(wb.WIN_SESSION_ID, owner_id=owner)
+ assert hb.get("ok") is True
+
+ other = await wb.ensure_desktop(owner_id="other-owner")
+ # Exclusive lease: other owner sees shared warning while first holds lease
+ if other.get("shared"):
+ assert other.get("other_owner") == owner
+
+ listed = await wb.list_desktops()
+ assert listed.get("ok") is True
+ assert listed.get("count", 0) >= 1
+
+ rel = await wb.release_desktop(wb.WIN_SESSION_ID)
+ assert rel.get("ok") is True
+ assert rel.get("released") == wb.WIN_SESSION_ID
+
+ reaped = await wb.reap_idle_desktops()
+ assert reaped.get("ok") is True
+
+ asyncio.run(_run())
+
+
+def test_backend_dispatch_names():
+ assert mod.BACKEND.name in ("x11", "mac", "windows")
+ if mod.IS_WIN:
+ assert mod.BACKEND.name == "windows"
+ assert isinstance(mod.BACKEND, mod.WinBackend)
+
+
+if __name__ == "__main__":
+ test_winbackend_class_exists_with_full_surface()
+ test_winbackend_primitives_guard_off_windows()
+ test_winbackend_leases_on_any_platform()
+ test_backend_dispatch_names()
+ print("ok")