# applescript

Adopt this skill: https://proskills.md/skills/other/haoyiyin-applescript-skill

Page: https://proskills.md/skills/other/haoyiyin-applescript-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 7346
sha: e3e92eeadde3f773f5ad61c50b0996f126197513
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/SKILL.md

````text
---
name: applescript
description: Universal AppleScript automation for macOS. Control Chrome, Finder, Mail, Calendar, Messages, Music, Terminal, and any scriptable app. Use when asked to automate macOS apps, control browsers, manage files, send messages, or perform system actions. Triggers on "AppleScript", "osascript", "control Chrome", "automate Mac", or any macOS app automation request.
---

# AppleScript Skill - Universal macOS Automation

Control any scriptable macOS application via AppleScript. Works with Chrome, Finder, Mail, Calendar, Messages, Music, Terminal, and more.

---

## How It Works

```
Claude → osascript → macOS App (native control)
```

- **Native macOS technology** — built into every Mac
- **Direct app control** — no web scraping, no API tokens
- **Uses existing sessions** — logged-in cookies, open windows, current state
- **Undetectable** — apps can't distinguish from human interaction

---

## Prerequisites

- **macOS only** (AppleScript doesn't exist on Windows/Linux)
- For Chrome/Safari: Enable "Allow JavaScript from Apple Events" in Developer menu
- Some apps may require Accessibility permissions

---

## Method Detection (Run First)

Always check if the target app is controllable:

```bash
# Check if app is running
osascript -e 'tell application "System Events" to count processes whose name is "APP_NAME"'

# Check if app has windows (for browsers)
osascript -e 'tell application "APP_NAME" to return count of windows'
```

If count is 0 but app should be open → restart app:

```bash
osascript -e 'tell application "APP_NAME" to quit'
pkill -x "APP_NAME"
sleep 2
open -a "APP_NAME"
sleep 3
```

---

## Quick Reference by App

### Google Chrome / Safari

| Action | Command |
|--------|---------|
| Open URL | `tell app "Chrome" to tell active tab of first window to set URL to "https://..."` |
| Get current URL | `tell app "Chrome" to tell active tab of first window to return URL` |
| Execute JS | `tell app "Chrome" to tell active tab of first window to execute javascript "..."` |
| New window | `tell app "Chrome" to make new window` |
| New tab | `tell app "Chrome" to tell first window to make new tab with URL "..."` |

### Finder

| Action | Command |
|--------|---------|
| Open folder | `tell app "Finder" to open folder "path/to/folder"` |
| Create folder | `tell app "Finder" to make new folder at desktop with properties {name:"Test"}` |
| List files | `tell app "Finder" to get name of every file of folder "path"` |
| Move file | `tell app "Finder" to move file "old" to folder "new"` |
| Delete file | `tell app "Finder" to delete file "path"` |

### Mail

| Action | Command |
|--------|---------|
| Send email | See `references/mail.applescript` |
| Get unread count | `tell app "Mail" to return unread count of inbox` |
| Open mailbox | `tell app "Mail" to open inbox` |

### Messages (iMessage)

| Action | Command |
|--------|---------|
| Send message | `tell app "Messages" to send "Hello" to buddy "contact@email.com"` |
| Open chat | `tell app "Messages" to chat with "contact@email.com"` |

### Music (iTunes)

| Action | Command |
|--------|---------|
| Play | `tell app "Music" to play` |
| Pause | `tell app "Music" to pause` |
| Next track | `tell app "Music" to next track` |
| Set volume | `set volume output volume 50` |

### Terminal

| Action | Command |
|--------|---------|
| Run command | `tell app "Terminal" to do script "ls -la"` |
| New tab | `tell app "Terminal" to tell window 1 to create tab with default profile` |
| Get output | Use `references/terminal.applescript` |

### System

| Action | Command |
|--------|---------|
| Set volume | `set volume output volume 50` |
| Get volume | `get volume settings` |
| Set brightness | Use `references/brightness.applescript` |
| Sleep display | `tell app "System Events" to key code 125 using {control down}` |

---

## Two Methods

### Method 1: Direct AppleScript (Preferred)

Use when app is visible to AppleScript:

```bash
osascript -e 'tell application "Chrome" to tell active tab of first window to set URL to "https://example.com"'
```

### Method 2: System Events (Fallback)

Use when app is not directly controllable (multi-profile Chrome bug):

```bash
osascript -e '
tell application "System Events"
    tell process "Chrome"
        set frontmost to true
        keystroke "l" using {command down}  -- Focus address bar
        delay 0.2
        keystroke "https://example.com"
        delay 0.2
        key code 36  -- Enter
    end tell
end tell'
```

---

## JavaScript Execution (for Browsers)

### Simple JS (no escaping needed with JXA)

```bash
osascript -l JavaScript -e '
var chrome = Application("Google Chrome");
var tab = chrome.windows[0].activeTab;
tab.execute({javascript: "document.title = \"Hello\""});
'
```

### Complex JS with Result (document.title trick)

```bash
# Run JS that writes result to document.title
osascript -e 'tell app "Chrome" to tell active tab of first window to execute javascript "fetch(\"/api/me\").then(r=>r.json()).then(d=>{document.title=\"R:\"+JSON.stringify(d)})"'

# Wait and read title
sleep 2
osascript -e 'tell app "Chrome" to return title of active tab of first window'
```

---

## Error Handling

| Error | Solution |
|-------|----------|
| "Application isn't running" | `open -a "AppName"` first |
| "count of windows = 0" | Hard restart app (quit + pkill + open) |
| "Not authorized" | System Preferences → Privacy → Accessibility |
| JS execution fails | Enable "Allow JavaScript from Apple Events" in browser Dev menu |
| Timeout | Add `with timeout of 30 seconds` wrapper |

---

## Best Practices

1. **Always verify prerequisites** before executing
2. **Use Method 1** when possible (more reliable than keyboard simulation)
3. **Add delays** between rapid actions (0.2-0.5s)
4. **Check app state** before assuming success
5. **Handle multi-profile** Chrome by restarting if windows = 0
6. **Use JXA** (`-l JavaScript`) for complex scripts (avoids escaping hell)

---

## Security Notes

- AppleScript requires user permissions (Accessibility, Automation)
- Apps can see AppleScript events (but can't distinguish from human)
- Never use for malicious automation (spam, fraud, etc.)
- Respect rate limits and terms of service

---

## Examples

See `references/` for complete scripts:
- `references/chrome.applescript` — Browser automation patterns
- `references/finder.applescript` — File management patterns
- `references/mail.applescript` — Email automation patterns
- `references/messages.applescript` — iMessage patterns
- `references/terminal.applescript` — Terminal automation

---

## When to Use This Skill

✅ **Use this skill when:**
- User asks to control a macOS app
- Need to automate browser actions
- Want to send messages, emails, or notifications
- Need to manage files via Finder
- Want to control system settings (volume, brightness)

❌ **Don't use this skill when:**
- On Windows or Linux (use computer-use MCP instead)
- App doesn't support AppleScript (check with `tell app "AppName" to get scriptable`)
- Need visual recognition (use computer-use with screenshots)

---

## Testing Scriptability

Check if an app supports AppleScript:

```bash
osascript -e 'tell application "AppName" to get scriptable'
```

Or open Script Editor → File → Open Dictionary → select app.
````

## File: README.md
size: 7031
sha: 2acb540491f8f7db93b861729058de8514931a09
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/README.md

````text
# AppleScript Automation Agent Skill

🤖 An agent skill for macOS automation via AppleScript — enables AI agents to control macOS applications through natural language commands or direct script execution.

**Agent-compatible** — Supports the [Agent Skills specification](https://agentskills.io/specification). Works with any AI agent framework (Claude Code, OpenClaw, Hermes, Codex, Cursor, or standalone).

[中文文档](README.zh.md) · [Report Issues](https://github.com/haoyiyin/applescript-skill/issues)

---

## ✨ Features

- **🌐 Browser Automation** — Control Chrome, Safari, Firefox (navigate, execute JS, extract data)
- **📁 File Management** — Finder operations (create, move, copy, delete, organize files)
- **💬 Communication** — Mail & Messages (iMessage) automation
- **⚙️ System Control** — Volume, brightness, notifications, clipboard, power management
- **💻 Terminal Automation** — Run commands, manage windows/tabs, capture output
- **🎵 Media Control** — Music (iTunes), Calendar, Contacts, Reminders

---

## 🚀 Quick Start

### Prerequisites

- macOS 10.15 or later
- Accessibility permissions enabled (System Settings → Privacy & Security → Accessibility)

### Installation

#### 🤖 Via AI Agent (Recommended)

Tell any AI coding agent:

> "Install the AppleScript automation skill from `haoyiyin/applescript-skill`"

Your agent will clone, configure, and set up the skill automatically. Works with Pi, Claude Code, Cursor, Codex, Copilot, and any agent supporting the [Agent Skills specification](https://agentskills.io/specification).

#### 🛠️ Manual Installation

```bash
# Clone the repository
git clone https://github.com/haoyiyin/applescript-skill.git
cd applescript-skill
```

### Usage Examples

**With AI Agents:**
```
"Open Chrome and visit GitHub"
"Organize all PDFs on my desktop"
"Send iMessage to John saying 'Meeting at 3pm'"
"Set volume to 50%"
"Run ls -la in Terminal"
```

**Direct AppleScript:**
```bash
osascript -e 'tell application "Google Chrome" to set URL of active tab of first window to "https://github.com"'
```

**From Python:**
```python
import subprocess

def run_applescript(script):
    result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True)
    return result.stdout

run_applescript('tell application "Finder" to return name of every item of desktop')
```

**From Node.js:**
```javascript
const { execSync } = require('child_process');

function runAppleScript(script) {
    return execSync(`osascript -e '${script}'`, { encoding: 'utf8' });
}

console.log(runAppleScript('tell application "Finder" to return count of every item of desktop'));
```

---

## 📁 Structure

```
applescript-skill/
├── SKILL.md                    # Agent skill definition (OpenClaw format)
├── README.md                   # English documentation (this file)
├── README.zh.md                # Chinese documentation
├── LICENSE                     # MIT License
├── references/                 # Ready-to-use script templates
│   ├── chrome.applescript      # Browser automation
│   ├── finder.applescript      # File management
│   ├── mail.applescript        # Email automation
│   ├── messages.applescript    # iMessage automation
│   ├── system.applescript      # System control
│   └── terminal.applescript    # Terminal automation
└── scripts/                    # Custom automation scripts
```

---

## 📖 Documentation

### Supported Applications

| Category | Applications |
|----------|-------------|
| **Browsers** | Chrome, Safari, Firefox |
| **File System** | Finder |
| **Communication** | Mail, Messages (iMessage) |
| **System** | Volume, Brightness, Notifications, Clipboard |
| **Development** | Terminal, VS Code |
| **Media** | Music (iTunes), QuickTime |
| **Productivity** | Calendar, Contacts, Reminders, Notes |

### Example Workflows

#### 1. Browser Automation
```applescript
tell application "Google Chrome"
    tell active tab of first window
        set URL to "https://github.com/trending"
        delay 2
        return title
    end tell
end tell
```

#### 2. File Organization
```applescript
tell application "Finder"
    set desktopFiles to every item of desktop whose name ends with ".pdf"
    repeat with file in desktopFiles
        move file to folder "Documents" of home folder
    end repeat
end tell
```

#### 3. Send Message
```applescript
tell application "Messages"
    set theBuddy to buddy "contact@example.com" of (service 1 whose service type is iMessage)
    send "Hello! Are you free?" to theBuddy
end tell
```

#### 4. System Control
```applescript
-- Set volume to 50%
set volume output volume 50

-- Copy to clipboard
set the clipboard to "Hello, World!"

-- Display notification
display notification "Task completed!" with title "Automation"
```

---

## 🔧 Configuration

### Enable Accessibility Permissions

1. Open **System Settings** → **Privacy & Security** → **Accessibility**
2. Click the **+** button
3. Add these applications:
   - `Google Chrome` (or your browser)
   - `Terminal`
   - `Messages`
   - `Mail`
   - Your AI agent application (if applicable)

### Grant Automation Permissions

1. Open **System Settings** → **Privacy & Security** → **Automation**
2. Enable permissions for:
   - `System Events`
   - `Finder`
   - `Messages`
   - `Mail`

---

## 🛡️ Security Considerations

- AppleScript can control your entire Mac — only run scripts from trusted sources
- Review scripts before execution, especially those that:
  - Delete or move files
  - Send messages or emails
  - Execute terminal commands
  - Access sensitive data
- Scripts run locally — no data is sent to external servers unless explicitly coded

---

## 🤝 Integration with AI Agents

This skill follows the [Agent Skills specification](https://agentskills.io/specification). Once installed (see [Installation](#installation) above), any compliant agent can execute AppleScript automation directly.

### Usage in Prompts

```
Use the AppleScript skill to open Chrome and navigate to GitHub.
Send iMessage to John saying "Meeting at 3pm".
Set volume to 50%.
```

### Custom Tool Integration

For custom agent frameworks, implement AppleScript execution as a tool:

```python
def execute_applescript_file(path):
    result = subprocess.run(['osascript', path], capture_output=True, text=True)
    return {'output': result.stdout, 'error': result.stderr}
```

---

## 📄 License

MIT License — See [LICENSE](LICENSE) file for details.

---

## 🔗 Resources

- [AppleScript Language Guide](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html)
- [macOS Automation Community](https://macscripter.net/)
- [AppleScript Essentials](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptingBasic/)

---

**Built with ❤️ for the AI agent community**
````

## File: references/chrome.applescript
size: 2857
sha: c40acc4b1ae918d419eccb50f301ce922324b512
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/references/chrome.applescript

```text
#!/usr/bin/osascript
# Chrome Browser Automation Patterns
# Usage: osascript chrome.applescript <action> [params]

-- ============================================
-- NAVIGATION
-- ============================================

-- Open URL in current tab
on openURL(theURL)
    tell application "Google Chrome"
        tell active tab of first window
            set URL to theURL
        end tell
    end tell
end tell

-- Open URL in new tab
on openInNewTab(theURL)
    tell application "Google Chrome"
        tell first window
            make new tab with properties {URL:theURL}
        end tell
    end tell
end tell

-- Get current URL
on getCurrentURL()
    tell application "Google Chrome"
        tell active tab of first window
            return URL
        end tell
    end tell
end tell

-- ============================================
-- JAVASCRIPT EXECUTION
-- ============================================

-- Execute JS and read result from document.title
on executeJSWithTitle(theJS)
    tell application "Google Chrome"
        tell active tab of first window
            execute javascript "(function(){" & theJS & "})()"
        end tell
    end tell
    delay 2
    tell application "Google Chrome"
        tell active tab of first window
            return title
        end tell
    end tell
end tell

-- Execute JS using JXA (no escaping needed)
on executeJXA(theJS)
    set jsCode to "
    var chrome = Application('Google Chrome');
    var tab = chrome.windows[0].activeTab;
    tab.execute({javascript: " & theJS & "});
    "
    do shell script "osascript -l JavaScript -e '" & jsCode & "'"
end tell

-- ============================================
-- UTILITY
-- ============================================

-- Check if Chrome is controllable
on checkChrome()
    try
        set windowCount to count of windows of application "Google Chrome"
        return windowCount
    on error
        return 0
    end try
end tell

-- Hard restart Chrome
on restartChrome()
    tell application "Google Chrome" to quit
    delay 1
    do shell script "pkill -x 'Google Chrome' 2>/dev/null || true"
    delay 1
    tell application "Google Chrome" to activate
    delay 3
end tell

-- ============================================
-- EXAMPLES
-- ============================================

-- Example: Fetch user data from Reddit
-- executeJSWithTitle("fetch('/api/me.json',{credentials:'include'}).then(r=>r.json()).then(d=>{document.title='R:'+JSON.stringify({name:d.data.name,karma:d.data.total_karma})})")

-- Example: Get page title
-- executeJSWithTitle("document.title")

-- Example: Click element by ID
-- executeJSWithTitle("document.getElementById('myButton').click()")

-- Example: Fill form and submit
-- executeJSWithTitle("document.querySelector('#email').value='test@example.com'; document.querySelector('form').submit()")
```

## File: references/finder.applescript
size: 3425
sha: 5d1277db3e6410fe781b8846e26ae383f73b045b
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/references/finder.applescript

```text
#!/usr/bin/osascript
# Finder File Management Patterns
# Usage: osascript finder.applescript <action> [params]

-- ============================================
-- FOLDER OPERATIONS
-- ============================================

-- Create folder at path
on createFolder(folderPath, folderName)
    tell application "Finder"
        if not (exists folder (folderPath & folderName)) then
            make new folder at folder folderPath with properties {name:folderName}
        end if
    end tell
end tell

-- Create folder on desktop
on createFolderOnDesktop(folderName)
    tell application "Finder"
        make new folder at desktop with properties {name:folderName}
    end tell
end tell

-- Open folder in new window
on openFolder(folderPath)
    tell application "Finder"
        open folder folderPath
    end tell
end tell

-- ============================================
-- FILE OPERATIONS
-- ============================================

-- List files in folder
on listFiles(folderPath)
    tell application "Finder"
        set fileList to name of every file of folder folderPath
        return fileList
    end tell
end tell

-- List subfolders
on listFolders(folderPath)
    tell application "Finder"
        set folderList to name of every folder of folder folderPath
        return folderList
    end tell
end tell

-- Move file
on moveFile(filePath, destinationPath)
    tell application "Finder"
        move file filePath to folder destinationPath
    end tell
end tell

-- Copy file
on copyFile(filePath, destinationPath)
    tell application "Finder"
        duplicate file filePath to folder destinationPath
    end tell
end tell

-- Delete file (move to trash)
on deleteFile(filePath)
    tell application "Finder"
        delete file filePath
    end tell
end tell

-- Get file info
on getFileInfo(filePath)
    tell application "Finder"
        set theFile to file filePath
        return {name:name of theFile, size:size of theFile, kind:kind of theFile, modificationDate:modification date of theFile}
    end tell
end tell

-- ============================================
-- DESKTOP OPERATIONS
-- ============================================

-- Get desktop path
on getDesktopPath()
    tell application "Finder"
        return path to desktop folder as string
    end tell
end tell

-- List desktop items
on listDesktop()
    tell application "Finder"
        return name of every item of desktop
    end tell
end tell

-- ============================================
-- UTILITY
-- ============================================

-- Convert POSIX path to AppleScript path
on posixToMacPath(posixPath)
    set macPath to POSIX file posixPath as alias
    return macPath as string
end tell

-- Convert AppleScript path to POSIX path
on macToPosixPath(macPath)
    return POSIX path of (macPath as alias)
end tell

-- ============================================
-- EXAMPLES
-- ============================================

-- Example: Create "Downloads" backup folder
-- createFolder((path to downloads folder as string), "Backup")

-- Example: List all PDFs on desktop
-- set items to listDesktop()
-- repeat with item in items
--     if item ends with ".pdf" then log item
-- end repeat

-- Example: Move all downloads to archive
-- set downloads to path to downloads folder as string
-- set archive to (path to documents folder as string) & "Archive:"
-- moveFile(downloads & "file.pdf", archive)
```

## File: references/mail.applescript
size: 6062
sha: 0e67c133eafbb471c07cdb3b43235630d160e5b1
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/references/mail.applescript

```text
#!/usr/bin/osascript
# Mail App Automation Patterns
# Usage: osascript mail.applescript <action> [params]

-- ============================================
-- SENDING EMAIL
-- ============================================

-- Send simple email
on sendEmail(subjectLine, theContent, theRecipient)
    tell application "Mail"
        set newMessage to make new outgoing message with properties {subject:subjectLine, content:theContent}
        tell newMessage
            make new to recipient at end of to recipients with properties {address:theRecipient}
        end tell
        send newMessage
    end tell
end tell

-- Send email with multiple recipients
on sendEmailToMultiple(subjectLine, theContent, recipientList)
    tell application "Mail"
        set newMessage to make new outgoing message with properties {subject:subjectLine, content:theContent}
        tell newMessage
            repeat with recipientAddr in recipientList
                make new to recipient at end of to recipients with properties {address:recipientAddr}
            end repeat
        end tell
        send newMessage
    end tell
end tell

-- Send email with attachment
on sendEmailWithAttachment(subjectLine, theContent, theRecipient, attachmentPath)
    tell application "Mail"
        set newMessage to make new outgoing message with properties {subject:subjectLine, content:theContent}
        tell newMessage
            make new to recipient at end of to recipients with properties {address:theRecipient}
            make new attachment with properties {file name:attachmentPath} at after the last paragraph
        end tell
        send newMessage
    end tell
end tell

-- Send HTML email
on sendHTMLEmail(subjectLine, htmlContent, theRecipient)
    tell application "Mail"
        set newMessage to make new outgoing message with properties {subject:subjectLine}
        tell newMessage
            set content to htmlContent
            make new to recipient at end of to recipients with properties {address:theRecipient}
        end tell
        send newMessage
    end tell
end tell

-- ============================================
-- INBOX MANAGEMENT
-- ============================================

-- Get unread count
on getUnreadCount()
    tell application "Mail"
        return unread count of inbox
    end tell
end tell

-- Get unread messages
on getUnreadMessages()
    tell application "Mail"
        set unreadList to every message of inbox whose read status is false
        return unreadList
    end tell
end tell

-- Get unread message details
on getUnreadMessageDetails()
    tell application "Mail"
        set unreadList to every message of inbox whose read status is false
        set details to {}
        repeat with msg in unreadList
            set end of details to {subject:subject of msg, sender:sender of msg, dateReceived:date received of msg}
        end repeat
        return details
    end tell
end tell

-- Mark message as read
on markAsRead(theMessage)
    tell application "Mail"
        set read status of theMessage to true
    end tell
end tell

-- Mark all inbox as read
on markAllAsRead()
    tell application "Mail"
        set read status of every message of inbox to true
    end tell
end tell

-- ============================================
-- SEARCH & FILTER
-- ============================================

-- Find messages by subject
on findMessagesBySubject(searchTerm)
    tell application "Mail"
        set foundMessages to every message of inbox whose subject contains searchTerm
        return foundMessages
    end tell
end tell

-- Find messages from sender
on findMessagesFromSender(senderEmail)
    tell application "Mail"
        set foundMessages to every message of inbox whose sender contains senderEmail
        return foundMessages
    end tell
end tell

-- Find messages with attachments
on findMessagesWithAttachments()
    tell application "Mail"
        set foundMessages to every message of inbox whose attachment count > 0
        return foundMessages
    end tell
end tell

-- ============================================
-- DRAFTS
-- ============================================

-- Create draft (don't send)
on createDraft(subjectLine, theContent, theRecipient)
    tell application "Mail"
        set draftMessage to make new outgoing message with properties {subject:subjectLine, content:theContent, visible:false}
        tell draftMessage
            make new to recipient at end of to recipients with properties {address:theRecipient}
        end tell
        -- Don't send, just save as draft
    end tell
end tell

-- ============================================
-- UTILITY
-- ============================================

-- Check if Mail is running
on checkMail()
    tell application "System Events"
        return (name of processes) contains "Mail"
    end tell
end tell

-- Open Mail app
on openMail()
    tell application "Mail"
        activate
    end tell
end tell

-- Get account info
on getAccountInfo()
    tell application "Mail"
        set accounts to every account
        set info to {}
        repeat with acc in accounts
            set end of info to {name:name of acc, email:email address of acc}
        end repeat
        return info
    end tell
end tell

-- ============================================
-- EXAMPLES
-- ============================================

-- Example: Send meeting reminder
-- sendEmail("Meeting Reminder", "Hi, just reminding you about our meeting at 3pm today.", "colleague@example.com")

-- Example: Send report with attachment
-- sendEmailWithAttachment("Weekly Report", "Please find attached the weekly report.", "boss@example.com", "/Users/jax/Documents/weekly-report.pdf")

-- Example: Check unread and notify
-- set count to getUnreadCount()
-- if count > 10 then
--     display notification "You have " & count & " unread emails!"
-- end if

-- Example: Find all emails from specific sender
-- set messages to findMessagesFromSender("newsletter@example.com")
-- repeat with msg in messages
--     markAsRead(msg)
-- end repeat
```

## File: references/messages.applescript
size: 3535
sha: cdc89de82b00c80ab655eba8743fb6b8979563b4
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/references/messages.applescript

```text
#!/usr/bin/osascript
# Messages (iMessage) Automation Patterns
# Usage: osascript messages.applescript <action> [params]

-- ============================================
-- MESSAGING
-- ============================================

-- Send message to contact (by email or phone)
on sendMessage(theMessage, theRecipient)
    tell application "Messages"
        set theBuddy to buddy theRecipient of (service 1 whose service type is iMessage)
        send theMessage to theBuddy
    end tell
end tell

-- Send message to multiple recipients
on sendGroupMessage(theMessage, recipientList)
    tell application "Messages"
        set theChat to chat with recipients recipientList
        send theMessage to theChat
    end tell
end tell

-- ============================================
-- CHAT MANAGEMENT
-- ============================================

-- Open chat with contact
on openChat(theRecipient)
    tell application "Messages"
        set theBuddy to buddy theRecipient of (service 1 whose service type is iMessage)
        chat with theBuddy
    end tell
end tell

-- Get recent chats
on getRecentChats()
    tell application "Messages"
        set chatList to chats
        return chatList
    end tell
end tell

-- ============================================
-- CONTACT INFO
-- ============================================

-- Get buddy status
on getBuddyStatus(theRecipient)
    tell application "Messages"
        set theBuddy to buddy theRecipient of (service 1 whose service type is iMessage)
        return presence status of theBuddy
    end tell
end tell

-- Check if contact is available
on isContactAvailable(theRecipient)
    try
        set status to getBuddyStatus(theRecipient)
        return status is available
    on error
        return false
    end try
end tell

-- ============================================
-- MESSAGE HISTORY
-- ============================================

-- Get last message from chat
on getLastMessage(theRecipient)
    tell application "Messages"
        set theChat to chat with buddy theRecipient of (service 1 whose service type is iMessage)
        set messageList to every message of theChat
        if (count messageList) > 0 then
            return content of last item of messageList
        else
            return ""
        end if
    end tell
end tell

-- ============================================
-- UTILITY
-- ============================================

-- Check if Messages is running
on checkMessages()
    tell application "System Events"
        return (name of processes) contains "Messages"
    end tell
end tell

-- Open Messages app
on openMessages()
    tell application "Messages"
        activate
    end tell
end tell

-- Quit Messages
on quitMessages()
    tell application "Messages" to quit
end tell

-- ============================================
-- EXAMPLES
-- ============================================

-- Example: Send message to contact
-- sendMessage("Hello! Are you free for a call?", "contact@example.com")

-- Example: Send to multiple people
-- sendGroupMessage("Meeting in 5 minutes", {"person1@example.com", "person2@example.com"})

-- Example: Check if someone is available before messaging
-- if isContactAvailable("contact@example.com") then
--     sendMessage("Quick question!", "contact@example.com")
-- end if

-- Example: Send message only if not already sent
-- set lastMsg to getLastMessage("contact@example.com")
-- if lastMsg does not contain "Hello" then
--     sendMessage("Hello!", "contact@example.com")
-- end if
```

## File: references/system.applescript
size: 4904
sha: ddac1aba6bc745abcbeef5745c912481de147460
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/references/system.applescript

```text
#!/usr/bin/osascript
# System Control Automation Patterns
# Usage: osascript system.applescript <action> [params]

-- ============================================
-- VOLUME CONTROL
-- ============================================

-- Set output volume (0-100)
on setOutputVolume(level)
    set volume output volume level
end tell

-- Get current output volume
on getOutputVolume()
    return output volume of (get volume settings)
end tell

-- Set input volume (0-100)
on setInputVolume(level)
    set volume input volume level
end tell

-- Get current input volume
on getInputVolume()
    return input volume of (get volume settings)
end tell

-- Set alert volume (0-100)
on setAlertVolume(level)
    set volume alert volume level
end tell

-- Mute/unmute
on muteOutput()
    set volume output muted true
end tell

on unmuteOutput()
    set volume output muted false
end tell

-- Get mute status
on isOutputMuted()
    return output muted of (get volume settings)
end tell

-- ============================================
-- BRIGHTNESS CONTROL
-- ============================================

-- Set display brightness (requires third-party tool)
-- Note: Native AppleScript doesn't support brightness directly
-- Use one of these alternatives:

-- Method 1: Using brightness CLI tool (install via brew)
on setBrightness(level)
    do shell script "brightness " & (level as string)
end tell

-- Method 2: Using AppleScript with System Events (limited)
on setBrightnessSystemEvents(level)
    -- This only works on some Mac models
    tell application "System Events"
        -- Brightness keys
        if level > 50 then
            repeat (level - 50) div 10 times
                key code 144 -- F2 (brightness up)
            end repeat
        else
            repeat (50 - level) div 10 times
                key code 122 -- F1 (brightness down)
            end repeat
        end if
    end tell
end tell

-- ============================================
-- DISPLAY SLEEP
-- ============================================

-- Turn off display
on turnOffDisplay()
    tell application "System Events"
        key code 125 using {control down} -- Control+Shift+Eject (or Power)
    end tell
end tell

-- Put computer to sleep
on sleepComputer()
    tell application "System Events" to sleep
end tell

-- Lock screen (macOS 10.10+)
on lockScreen()
    tell application "System Events"
        keystroke "q" using {command down, control down}
    end tell
end tell

-- ============================================
-- POWER MANAGEMENT
-- ============================================

-- Get battery info (for laptops)
on getBatteryInfo()
    try
        set info to do shell script "pmset -g batt | grep -o '[0-9]*%' | tr -d '%'"
        return info as integer
    on error
        return -1
    end try
end tell

-- Check if on battery power
on isOnBattery()
    try
        set powerStatus to do shell script "pmset -g batt | grep -o 'Battery'"
        return powerStatus is not ""
    on error
        return false
    end try
end tell

-- ============================================
-- NOTIFICATIONS
-- ============================================

-- Display notification
on showNotification(theTitle, theSubtitle, theMessage)
    display notification theMessage with title theTitle subtitle theSubtitle
end tell

-- Display notification with sound
on showNotificationWithSound(theTitle, theSubtitle, theMessage, soundName)
    display notification theMessage with title theTitle subtitle theSubtitle sound name soundName
end tell

-- ============================================
-- CLIPBOARD
-- ============================================

-- Copy text to clipboard
on copyToClipboard(theText)
    set the clipboard to theText
end tell

-- Get text from clipboard
on getFromClipboard()
    return the clipboard as text
end tell

-- ============================================
-- DATE & TIME
-- ============================================

-- Get current date and time
on getCurrentDateTime()
    return current date
end tell

-- Get current timestamp (Unix epoch)
on getCurrentTimestamp()
    return do shell script "date +%s"
end tell

-- Format date
on formatDate(theDate)
    return theDate as string
end tell

-- ============================================
-- EXAMPLES
-- ============================================

-- Example: Set volume to 50%
-- setOutputVolume(50)

-- Example: Gradual volume fade in
-- repeat with i from 0 to 50 by 5
--     setOutputVolume(i)
--     delay 0.2
-- end repeat

-- Example: Mute if meeting starts
-- if getCurrentTimestamp() mod 86400 < 32400 then -- before 9 AM
--     muteOutput()
-- end if

-- Example: Battery warning
-- if isOnBattery() and getBatteryInfo() < 20 then
--     showNotification("Low Battery", "Power", "Battery is at " & getBatteryInfo() & "%")
-- end if

-- Example: Copy important info
-- copyToClipboard("Meeting ID: 123-456-789")
```

## File: references/terminal.applescript
size: 5412
sha: 2e007ee752bed3f66ad4a8d4142a99954cfb1acb
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/references/terminal.applescript

```text
#!/usr/bin/osascript
# Terminal Automation Patterns
# Usage: osascript terminal.applescript <action> [params]

-- ============================================
-- BASIC COMMANDS
-- ============================================

-- Run command in new window
on runCommand(commandString)
    tell application "Terminal"
        activate
        do script commandString
    end tell
end tell

-- Run command in existing window
on runCommandInWindow(commandString, windowIndex)
    tell application "Terminal"
        do script commandString in window windowIndex
    end tell
end tell

-- Run command in specific tab
on runCommandInTab(commandString, windowIndex, tabIndex)
    tell application "Terminal"
        do script commandString in tab tabIndex of window windowIndex
    end tell
end tell

-- ============================================
-- WINDOW & TAB MANAGEMENT
-- ============================================

-- Open new Terminal window
on openNewWindow()
    tell application "Terminal"
        activate
        do script ""
    end tell
end tell

-- Open new tab in first window
on openNewTab()
    tell application "Terminal"
        tell window 1
            create tab with default profile
        end tell
        activate
    end tell
end tell

-- Close specific window
on closeWindow(windowIndex)
    tell application "Terminal"
        close window windowIndex
    end tell
end tell

-- Close all windows
on closeAllWindows()
    tell application "Terminal"
        repeat while (count of windows) > 0
            close first window
        end repeat
    end tell
end tell

-- ============================================
-- GETTING OUTPUT
-- ============================================

-- Get last output from tab (limited)
on getLastOutput(windowIndex, tabIndex)
    tell application "Terminal"
        return content of tab tabIndex of window windowIndex
    end tell
end tell

-- Get selected text from tab
on getSelectedText(windowIndex, tabIndex)
    tell application "Terminal"
        return selected text of tab tabIndex of window windowIndex
    end tell
end tell

-- ============================================
-- PROFILES & SETTINGS
-- ============================================

-- Run command with specific profile
on runCommandWithProfile(commandString, profileName)
    tell application "Terminal"
        do script commandString in tab 1 of window 1 using settings set profileName
    end tell
end tell

-- Set window title
on setWindowTitle(windowIndex, titleString)
    tell application "Terminal"
        set custom title of window windowIndex to titleString
    end tell
end tell

-- ============================================
-- INTERACTIVE COMMANDS
-- ============================================

-- Send keystroke to Terminal
on sendKeystroke(keystrokeString, windowIndex)
    tell application "System Events"
        tell process "Terminal"
            set frontmost to true
            keystroke keystrokeString
        end tell
    end tell
end tell

-- Send special key (Enter, Ctrl+C, etc.)
on sendSpecialKey(keyCode, windowIndex)
    tell application "System Events"
        tell process "Terminal"
            set frontmost to true
            key code keyCode
        end tell
    end tell
end tell

-- Send Ctrl+C to interrupt
on sendInterrupt(windowIndex)
    tell application "System Events"
        tell process "Terminal"
            set frontmost to true
            keystroke "c" using {control down}
        end tell
    end tell
end tell

-- Send Ctrl+D for EOF
on sendEOF(windowIndex)
    tell application "System Events"
        tell process "Terminal"
            set frontmost to true
            keystroke "d" using {control down}
        end tell
    end tell
end tell

-- ============================================
-- UTILITY
-- ============================================

-- Check if Terminal is running
on checkTerminal()
    tell application "System Events"
        return (name of processes) contains "Terminal"
    end tell
end tell

-- Get number of open windows
on countWindows()
    tell application "Terminal"
        return count of windows
    end tell
end tell

-- Get number of tabs in window
on countTabs(windowIndex)
    tell application "Terminal"
        return count of tabs of window windowIndex
    end tell
end tell

-- Activate Terminal (bring to front)
on activateTerminal()
    tell application "Terminal"
        activate
    end tell
end tell

-- ============================================
-- KEY CODES REFERENCE
-- ============================================
-- Return/Enter: 36
-- Tab: 48
-- Space: 49
-- Delete: 51
-- Escape: 53
-- Up Arrow: 126
-- Down Arrow: 125
-- Left Arrow: 123
-- Right Arrow: 124

-- ============================================
-- EXAMPLES
-- ============================================

-- Example: Run ls in new window
-- runCommand("ls -la")

-- Example: Run multiple commands
-- runCommand("cd /Users/jax && git status")

-- Example: Run top in new tab and monitor
-- openNewTab()
-- delay 1
-- runCommandInTab("top -l 1", 1, 2)
-- delay 3
-- set output to getLastOutput(1, 2)

-- Example: Interrupt running process
-- sendInterrupt(1)

-- Example: Set custom title for session
-- runCommand("echo 'Starting build...'")
-- setWindowTitle(1, "Build Session")

-- Example: Run command and get output
-- runCommand("pwd")
-- delay 1
-- set currentDir to getLastOutput(1, 1)
```

## File: .gitignore
size: 194
sha: edcb90848efe7118d9f75a00c119fb98009e4082
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/.gitignore

```text
# macOS
.DS_Store
.AppleDouble
.LSOverride
._*

# Logs
*.log

# Backup files
*.backup
*.bak
*~

# Editor directories and files
.vscode/
.idea/
*.swp
*.swo
*~

# Temporary files
tmp/
temp/
*.tmp
```

## File: LICENSE
size: 1059
sha: f363ca9861ea96f0830f9af0dc6db7e35410355e
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 Yi

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.
```

## File: README.zh.md
size: 7792
sha: 0093ef5c1ea037b4631b8383871ca689cdd44883
upstream: https://github.com/haoyiyin/applescript-skill/blob/HEAD/README.zh.md

````text
# AppleScript 自动化技能

🤖 一个通用的 AppleScript 自动化工具包，让 AI 代理和开发者能够通过自然语言命令或直接脚本执行来控制 macOS 应用程序。

**与 Agent 无关** — 适用于任何 AI 代理框架（OpenClaw、Claude Code、Cursor、Codex 或独立使用）

[English Documentation](README.md) · [问题反馈](https://github.com/haoyiyin/applescript-skill/issues)

---

## ✨ 功能特性

- **🌐 浏览器自动化** — 控制 Chrome、Safari、Firefox（导航、执行 JS、提取数据）
- **📁 文件管理** — Finder 操作（创建、移动、复制、删除、整理文件）
- **💬 通讯自动化** — 邮件和 iMessage 自动化
- **⚙️ 系统控制** — 音量、亮度、通知、剪贴板、电源管理
- **💻 Terminal 自动化** — 运行命令、管理窗口/标签页、捕获输出
- **🎵 媒体控制** — Music (iTunes)、日历、联系人、提醒事项

---

## 🚀 快速开始

### 前置要求

- macOS 10.15 或更高版本
- 已启用辅助功能权限（系统设置 → 隐私与安全性 → 辅助功能）

### 安装

#### 🤖 通过 AI Agent 安装（推荐）

告诉任何 AI 编程助手：

> "安装 haoyiyin/applescript-skill 这个 skill"

你的 agent 会自动完成克隆、配置和安装。支持 Pi、Claude Code、Cursor、Codex、Copilot 等任何遵循 [Agent Skills 规范](https://agentskills.io/specification) 的 agent。

#### 🛠️ 手动安装

```bash
# 克隆仓库
git clone https://github.com/haoyiyin/applescript-skill.git
cd applescript-skill
```

### 使用示例

**配合 AI 代理：**
```
"打开 Chrome 访问 GitHub"
"整理桌面上的所有 PDF 文件"
"给张三发 iMessage 说'下午 3 点开会'"
"把音量调到 50%"
"在 Terminal 里运行 ls -la"
```

**直接使用 AppleScript：**
```bash
osascript -e 'tell application "Google Chrome" to set URL of active tab of first window to "https://github.com"'
```

**Python 调用：**
```python
import subprocess

def run_applescript(script):
    result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True)
    return result.stdout

run_applescript('tell application "Finder" to return name of every item of desktop')
```

**Node.js 调用：**
```javascript
const { execSync } = require('child_process');

function runAppleScript(script) {
    return execSync(`osascript -e '${script}'`, { encoding: 'utf8' });
}

console.log(runAppleScript('tell application "Finder" to return count of every item of desktop'));
```

---

## 📁 目录结构

```
applescript-skill/
├── SKILL.md                    # Agent 技能定义（OpenClaw 格式）
├── README.md                   # 英文文档
├── README.zh.md                # 中文文档（本文件）
├── LICENSE                     # MIT 许可证
├── references/                 # 即拿即用的脚本模板
│   ├── chrome.applescript      # 浏览器自动化
│   ├── finder.applescript      # 文件管理
│   ├── mail.applescript        # 邮件自动化
│   ├── messages.applescript    # iMessage 自动化
│   ├── system.applescript      # 系统控制
│   └── terminal.applescript    # Terminal 自动化
└── scripts/                    # 自定义自动化脚本
```

---

## 📖 文档

### 支持的应用程序

| 类别 | 应用程序 |
|------|---------|
| **浏览器** | Chrome, Safari, Firefox |
| **文件系统** | Finder |
| **通讯** | Mail, Messages (iMessage) |
| **系统** | 音量、亮度、通知、剪贴板 |
| **开发** | Terminal, VS Code |
| **媒体** | Music (iTunes), QuickTime |
| **生产力** | Calendar, Contacts, Reminders, Notes |

### 示例工作流

#### 1. 浏览器自动化
```applescript
tell application "Google Chrome"
    tell active tab of first window
        set URL to "https://github.com/trending"
        delay 2
        return title
    end tell
end tell
```

#### 2. 文件整理
```applescript
tell application "Finder"
    set desktopFiles to every item of desktop whose name ends with ".pdf"
    repeat with file in desktopFiles
        move file to folder "Documents" of home folder
    end repeat
end tell
```

#### 3. 发送消息
```applescript
tell application "Messages"
    set theBuddy to buddy "contact@example.com" of (service 1 whose service type is iMessage)
    send "你好！有空吗？" to theBuddy
end tell
```

#### 4. 系统控制
```applescript
-- 设置音量为 50%
set volume output volume 50

-- 复制到剪贴板
set the clipboard to "Hello, World!"

-- 显示通知
display notification "任务完成！" with title "自动化"
```

---

## 🔧 配置

### 启用辅助功能权限

1. 打开 **系统设置** → **隐私与安全性** → **辅助功能**
2. 点击 **+** 按钮
3. 添加这些应用程序：
   - `Google Chrome`（或你的浏览器）
   - `Terminal`
   - `Messages`
   - `Mail`
   - 你的 AI 代理应用（如适用）

### 授予自动化权限

1. 打开 **系统设置** → **隐私与安全性** → **自动化**
2. 启用以下权限：
   - `System Events`
   - `Finder`
   - `Messages`
   - `Mail`

---

## 🛡️ 安全考虑

- AppleScript 可以控制你的整个 Mac — 只运行来自可信来源的脚本
- 在执行前审查脚本，特别是那些：
   - 删除或移动文件的
   - 发送消息或邮件的
   - 执行终端命令的
   - 访问敏感数据的
- 脚本在本地运行 — 除非明确编码，否则不会将数据发送到外部服务器

---

## 🤝 与 AI 代理集成

### OpenClaw
```bash
# 复制到 OpenClaw 工作区
cp -r applescript-skill ~/.openclaw/workspace/skills/applescript/
```

### Claude Code / Cursor / Codex
在你的 prompt 中直接引用 `references/` 脚本：
```
使用 AppleScript 技能打开 Chrome 并导航到 GitHub。
参考：./applescript-skill/references/chrome.applescript
```

### 自定义 Agent
在你的 agent 工具层实现 AppleScript 执行：
```python
def execute_applescript_file(path):
    result = subprocess.run(['osascript', path], capture_output=True, text=True)
    return {'output': result.stdout, 'error': result.stderr}
```

---

## 💡 实用场景

### 日常工作
- 自动打开工作相关的网页（邮箱、日历、任务管理）
- 整理下载文件夹
- 批量重命名文件
- 自动发送日报/周报邮件

### 开发工作
- 自动运行测试脚本
- 查看日志文件
- 管理 git 仓库
- 快速切换开发环境

### 生活助手
- 发送定时消息
- 整理照片
- 控制音乐播放
- 创建提醒事项

---

## ❓ 常见问题

### Q: 为什么 AppleScript 无法控制 Chrome？
A: 确保：
1. Chrome 已授予辅助功能权限
2. Chrome 已打开（至少有一个窗口）
3. macOS 版本兼容

### Q: 如何调试 AppleScript？
A: 使用 `Script Editor` 应用（macOS 自带）：
1. 打开 Script Editor
2. 粘贴脚本
3. 点击运行查看结果和错误信息

### Q: 可以控制 Windows 应用吗？
A: 不行，AppleScript 仅适用于 macOS。Windows 用户可以考虑使用 PowerShell 或 AutoHotkey。

### Q: 如何在 CI/CD 中使用？
A: 不推荐在 CI/CD 中使用 AppleScript，因为它需要 GUI 访问权限。考虑使用纯命令行工具替代。

---

## 📄 许可证

MIT 许可证 — 详见 [LICENSE](LICENSE) 文件。

---

## 🔗 资源

- [AppleScript 语言指南](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html)
- [macOS 自动化社区](https://macscripter.net/)
- [AppleScript 基础教程](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptingBasic/)

---

**为 AI 代理社区打造 ❤️**
````
