mcpField
C
computer-use-agents

computer-use-agents

github.com/davila7エージェントワークフロー33.0k454 回インストール今日更新
リポジトリ

computer-use-agents について

コンピューター操作エージェントの構成、実装パターン、安全上の注意を解説するスキルです。画面を観察してデスクトップを操作するエージェントの開発・導入向けに、サンドボックス化や Anthropic の実装パターンを扱います。

主な機能

  1. 01知覚・推論・行動ループのパターン
  2. 02サンドボックス分離の要件
  3. 03Anthropic のコンピューター操作実装パターン
  4. 04マウス、キーボード、スクリーンショット、シェルの操作
  5. 05リスクと対策の指針

活用シーン

  1. 01コンピューター操作エージェントの新規構築
  2. 02ビジョンモデルとデスクトップ操作の連携
  3. 03分離環境での自動化テスト
  4. 04デスクトップ全体を操作するエージェントの導入

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/davila7/claude-code-templates --skill computer-use-agents

インストール後、Claude Code で/computer-use-agentsを入力して読み込まれたか確認します。

詳細

Computer Use Agents

パターン

知覚-推論-行動ループ

コンピュータ操作エージェントの基本的なアーキテクチャです。画面を観察し、次の行動を推論し、行動を実行し、これを繰り返します。このループは、反復的なパイプラインを通じて、ビジョンモデルと行動の実行を統合します。

主要なコンポーネント:

  1. PERCEPTION: スクリーンショットで現在の画面状態を取得する
  2. REASONING: ビジョン言語モデルが分析し、計画を立てる
  3. ACTION: マウスとキーボードの操作を実行する
  4. FEEDBACK: 結果を観察し、続行するか修正する

重要な知見: ビジョンエージェントは「思考」フェーズ(1〜5秒)の間、完全に静止しており、検出可能な一時停止パターンを生じさせます。

使用するタイミング: ['ゼロからコンピュータ操作エージェントを構築する場合', 'ビジョンモデルとデスクトップ制御を統合する場合', 'エージェントの動作パターンを理解する場合']

from anthropic import Anthropic
from PIL import Image
import base64
import pyautogui
import time

class ComputerUseAgent:
    """
    Perception-Reasoning-Action loop implementation.
    Based on Anthropic Computer Use patterns.
    """

    def __init__(self, client: Anthropic, model: str = "claude-sonnet-4-20250514"):
        self.client = client
        self.model = model
        self.max_steps = 50  # Prevent runaway loops
        self.action_delay = 0.5  # Seconds between actions

    def capture_screenshot(self) -> str:
        """Capture screen and return base64 encoded image."""
        screenshot = pyautogui.screenshot()
        # Resize for token efficiency (1280x800 is good balance)
        screenshot = screenshot.resize((1280, 800), Image.LANCZOS)

        import io
        buffer = io.BytesIO()
        screenshot.save(buffer, format="PNG")
        return base64.b64encode(buffer.getvalue()).decode()

    def execute_action(self, action: dict) -> dict:
        """Execute mouse/keyboard action on the computer."""
        action_type = action.get("type")

        if action_type == "click":
            x, y = action["x"], action["y"]
            button = action.get("button", "left")
            pyautogui.click(x, y, button=button)
            return {"success": True, "action": f"clicked at ({x}, {y})"}

        elif action_type == "type":
            text = action["text"]
            pyautogui.typewrite(text, interval=0.02)
            return {"success": True, "action": f"typed {len(text)} chars"}

        elif action_type == "key":
            key = action["key"]
            pyautogui.press(key)
            return {"success": True, "action": f"pressed {key}"}

        elif action_type == "scroll":
            direction = action.get("direction", "down")
            amount = action.get("amount", 3)
            scroll = -amount if direction == "down" else amount
            pyautogui.scroll(scroll)
            return {"success": True, "action": f"scrolled {dir
サンドボックス環境パターン

コンピュータ操作エージェントは、必ず隔離されたサンドボックス環境で実行する必要があります。エージェントにメインシステムへの直接アクセスを許可しないでください。セキュリティリスクが高すぎます。仮想デスクトップを備えたDockerコンテナを使用してください。

主要な隔離要件:

  1. NETWORK: 必要なエンドポイントのみに制限する
  2. FILESYSTEM: 読み取り専用にするか、一時ディレクトリに限定する
  3. CREDENTIALS: ホストの認証情報へのアクセスを許可しない
  4. SYSCALLS: 危険なシステムコールをフィルタリングする
  5. RESOURCES: CPU、メモリ、時間を制限する

目標は「被害範囲の最小化(blast radius minimization)」です。エージェントが誤動作しても、被害はサンドボックス内に封じ込められます。

使用するタイミング: ['コンピュータ操作エージェントをデプロイする場合', 'エージェントの動作を安全にテストする場合', '信頼されていない自動化タスクを実行する場合']

# Dockerfile for sandboxed computer use environment
# Based on Anthropic's reference implementation pattern

FROM ubuntu:22.04

# Install desktop environment
RUN apt-get update && apt-get install -y \
    xvfb \
    x11vnc \
    fluxbox \
    xterm \
    firefox \
    python3 \
    python3-pip \
    supervisor

# Security: Create non-root user
RUN useradd -m -s /bin/bash agent && \
    mkdir -p /home/agent/.vnc

# Install Python dependencies
COPY requirements.txt /tmp/
RUN pip3 install -r /tmp/requirements.txt

# Security: Drop capabilities
RUN apt-get install -y --no-install-recommends libcap2-bin && \
    setcap -r /usr/bin/python3 || true

# Copy agent code
COPY --chown=agent:agent . /app
WORKDIR /app

# Supervisor config for virtual display + VNC
COPY supervisord.conf /etc/supervisor/conf.d/

# Expose VNC port only (not desktop directly)
EXPOSE 5900

# Run as non-root
USER agent

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]

---

# docker-compose.yml with security constraints
version: '3.8'

services:
  computer-use-agent:
    build: .
    ports:
      - "5900:5900"  # VNC for observation
      - "8080:8080"  # API for control

    # Security constraints
    security_opt:
      - no-new-privileges:true
      - seccomp:seccomp-profile.json

    # Resource limits
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 4G
        reservations:
          cpus: '0.5'
          memory: 1G

    # Network isolation
    networks:
      - agent-network

    # No access to host filesystem
    volumes:
      - agent-tmp:/tmp

    # Read-only root filesystem
    read_only: true
    tmpfs:
      - /run
      - /var/run

    # Environment
    environment:
      - DISPLAY=:99
      - NO_PROXY=localhost

networks:
  agent-network:
    driver: bridge
    internal: true  # No internet by default

volumes:
  agent-tmp:

---

# Python wrapper with additional runtime sandboxing
import subprocess
import os
from dataclasses im
Anthropic Computer Use の実装

Claudeのコンピュータ操作機能を用いた公式の実装パターンです。Claude 3.5 Sonnetは、コンピュータ操作機能を提供した最初のフロンティアモデルでした。Claude Opus 4.5は現在、「コンピュータ操作において世界最高のモデル」とされています。

主要な機能:

  • screenshot: 現在の画面状態を取得する
  • mouse: クリック、移動、ドラッグの操作
  • keyboard: テキストの入力、キーの押下
  • bash: シェルコマンドを実行する
  • text_editor: ファイルを表示および編集する

ツールのバージョン:

  • computer_20251124 (Opus 4.5): 詳細な確認のためのzoomアクションを追加
  • computer_20250124 (その他すべてのモデル): 標準機能

重大な制限: 「一部のUI要素(ドロップダウンやスクロールバーなど)は、Claudeが操作するのが難しい場合があります」 - Anthropicのドキュメント

使用するタイミング: ['本番環境向けのコンピュータ操作エージェントを構築する場合', '最高品質のビジョン理解が必要な場合', 'ブラウザだけでなくデスクトップ全体を制御する場合']

from anthropic import Anthropic
from anthropic.types.beta import (
    BetaToolComputerUse20241022,
    BetaToolBash20241022,
    BetaToolTextEditor20241022,
)
import subprocess
import base64
from PIL import Image
import io

class AnthropicComputerUse:
    """
    Official Anthropic Computer Use implementation.

    Requires:
    - Docker container with virtual display
    - VNC for viewing agent actions
    - Proper tool implementations
    """

    def __init__(self):
        self.client = Anthropic()
        self.model = "claude-sonnet-4-6"  # Best for computer use
        self.screen_size = (1280, 800)

    def get_tools(self) -> list:
        """Define computer use tools."""
        return [
            BetaToolComputerUse20241022(
                type="computer_20241022",
                name="computer",
                display_width_px=self.screen_size[0],
                display_height_px=self.screen_size[1],
            ),
            BetaToolBash20241022(
                type="bash_20241022",
                name="bash",
            ),
            BetaToolTextEditor20241022(
                type="text_editor_20241022",
                name="str_replace_editor",
            ),
        ]

    def execute_tool(self, name: str, input: dict) -> dict:
        """Execute a tool and return result."""

        if name == "computer":
            return self._handle_computer_action(input)
        elif name == "bash":
            return self._handle_bash(input)
        elif name == "str_replace_editor":
            return self._handle_editor(input)
        else:
            return {"error": f"Unknown tool: {name}"}

    def _handle_computer_action(self, input: dict) -> dict:
        """Handle computer control actions."""
        action = input.get("action")

        if action == "screenshot":
            # Capture via xdotool/scrot
            subprocess.run(["scrot", "/tmp/screenshot.png"])

            with open("/tmp/screenshot.png", "rb") as f:
            

⚠️ 注意すべき落とし穴

IssueSeveritySolution
Issuecritical## Defense in depth - no single solution works
Issuemedium## Add human-like variance to actions
Issuehigh## Use keyboard alternatives when possible
Issuemedium## Accept the tradeoff
Issuehigh## Implement context management
Issuehigh## Monitor and limit costs
Issuecritical## ALWAYS use sandboxing

コメント