hammerspoon

Writes, fixes and explains Hammerspoon macOS automation in JavaScript (init.js, the hs.* API, Spoons). Use when the user wants Hammerspoon hotkeys, window management, app launching, menu bar items, timers, watchers, alerts or custom UI, clipboard, Wi-Fi, USB or power events, AppleScript or shell tasks, or says automate my Mac with a script and Hammerspoon fits, even if the user does not name the API.

Qu'est-ce que hammerspoon ?

hammerspoon is a Cursor agent skill that writes, fixes and explains Hammerspoon macOS automation in JavaScript (init.js, the hs.* API, Spoons). Use when the user wants Hammerspoon hotkeys, window management, app launching, menu bar items, timers, watchers, alerts or custom UI, clipboard, Wi-Fi, USB or power events, AppleScript or shell tasks, or says automate my Mac with a script and Hammerspoon fits, even if the user does not name the API.

Compatible avec~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/devastion/ai/tree/HEAD/agent/skills/ops/hammerspoon

Installed? Explore more Développement et programmation skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Hammerspoon (JavaScript API)

Hammerspoon is a macOS app that runs the user's JavaScript (JavaScriptCore) and exposes system APIs under the global hs object. This skill covers that JavaScript API.

Read this first: memory is not a reliable source here

Most Hammerspoon code on the web and in your training data is written in Lua for a different, older API. None of it runs here. Lua syntax (function() ... end, obj:method(), {"cmd"} tables), and modules such as hs.alert, hs.logger, hs.grid or hs.caffeinate, cause errors in this runtime. Many names look familiar but have different signatures.

So: check every hs.* call you write against the API reference before you give it to the user. If a call isn't in the reference, don't use it. See "Looking things up" below.

Present this API simply as Hammerspoon. Don't compare it with other versions or add migration notes unless the user asks.

Common replacements for names that don't exist here:

Don't writeUse instead
hs.alert.show(msg)hs.ui.alert(msg).duration(2).show()
hs.logger, printconsole.log/.warn/.error/.info/.debug
hs.grid, hs.layout, moveToUnitwin.frame = unitRect.fromUnitRect(win.screen.frame) with an HSRect
hs.geometrynew HSRect(x, y, w, h), new HSPoint(x, y), new HSSize(w, h)
hs.caffeinate, hs.batteryhs.power (preventSleep, lockScreen, percentage, ...)
hs.drawinghs.canvas (absolute drawing) or hs.ui (layout UI)
hs.webviewhs.ui.webview()
hs.settingshs.userdefaults
hs.execute(cmd)hs.task.shell(cmd).then(r => r.stdout)
hs.json, hs.inspectJSON.parse/stringify, require('util').inspect
hs.base64hs.hashing.base64Encode/base64Decode
hs.imageHSImage.fromPath/fromSymbol/fromAppBundle/...
hs.spacesHSSpace via hs.screen and hs.window
hs.loadSpoon(...)hs.spoons.load(...) or hs.spoons.use(...)

Looking things up

  • Docs site. Fetch the page with the web fetch tool and ask for the exact signatures, parameter types, return values and examples of the members you need:

    • module: https://www.hammerspoon.org/2/main/js/<module>.html (for example https://www.hammerspoon.org/2/main/js/hs.window.html)
    • object type: https://www.hammerspoon.org/2/main/js/<Type>.html (for example https://www.hammerspoon.org/2/main/js/HSWindow.html)
    • guides: getting-started.html, canvas-guide.html, spoons-guide.html and typescript-guide.html under https://www.hammerspoon.org/2/main/js/
  • Installed docs. hs.docs.show() opens the offline docs of the installed version. Use it when the site is unreachable or the user's version may differ.

    A module's object types have their own pages, so fetch both the module page and the type page. The fetch returns a summary, so ask for exact signatures. If a detail is still missing, rely on the page's examples and tell the user which detail you couldn't confirm.

Workflow

  1. Work out which modules the task needs, using the module table below.
  2. Look up those modules (see above). Read a guide when the task is mainly about its topic.
  3. Write the code following the conventions below.
  4. Before answering, check each hs.* call, its argument order and its return type (property or method? Promise or value? can it return null?) against the reference.
  5. Give complete, runnable code that can go in init.js, or in a file init.js requires. Mention any macOS permission it needs (see Permissions).

Runtime essentials

Config. One file, init.js, in the config directory (usually ~/.config/Hammerspoon2/; hs.appinfo.configPath and hs.appinfo.configDir give the exact paths). It runs top to bottom once, at launch and on each reload. There is no entry-point function. Reload with "Reload Config" in the menu bar icon or hs.reload(). hs.openConsole() shows the log and REPL; uncaught exceptions appear there with file and line. hs.docs.show() opens the offline docs.

Object lifetime (the most important rule). Anything running keeps running, with its callbacks, until it finishes or is stopped, whether or not a reference is kept: bound hotkeys, started timers, watchers, event taps, running tasks, shown windows, canvases, choosers, menu bar items and sounds. Dropping a reference does not stop anything. Call stop(), disable(), hide(), terminate() or destroy() instead. So keep a reference (a top-level const) to anything you might stop, update or re-show later. That includes reactive values that feed a UI. Objects that are not running (a timer never started, a hidden window) are garbage collected like any JS value. hs.reload() stops everything. hs.activeObjects() lists what is running.

Events: on / off / once. Modules that report state changes take the event name first: hs.application.on('didLaunch', app => ...). These include hs.application, hs.audiodevice, hs.camera, hs.distributednotifications, hs.keycodes, hs.locale, hs.pasteboard, hs.power, hs.screen, hs.serial, hs.streamdeck, hs.usb, hs.userdefaults, hs.wifi and hs.windowfilter. Look up the exact event names in the module's reference. off() matches by function identity, so keep the function if you'll remove it. If the underlying watcher can't start, on() throws and registers nothing. Wrap it in try/catch when the config must keep going. hs.ax.on(element, notification, listener) uses a different argument order. A few modules return a watcher object to configure and start() instead: hs.fs.createPathWatcher(), hs.eventtap.addWatcher() and hs.location.

Promises. Slow operations return Promises instead of taking callbacks. Examples are AppleScript, HTTP, hs.application.launchOrFocus(bundleID), hs.task.shell and hs.spoons.use. hs.osascript.applescript() always resolves: check result.success. Other modules reject on failure. Check the reference. Signatures shown as Promise<any> | null resolve to whatever the member's doc describes.

Properties vs methods. Many values are properties, not methods: win.title, win.frame, win.screen, win.application, app.name, app.bundleID, screen.frame. Settable ones are assigned: win.frame = rect. The signature in the reference shows which is which (readonly means not settable).

Geometry. Screen coordinates start at the top-left of the primary display, with y increasing downward. screen.frame excludes the menu bar and Dock; fullFrame includes them. HSRect has fromUnitRect(frame) / toUnitRect(frame) for fractional layouts:

const LEFT_HALF = new HSRect(0, 0, 0.5, 1)
hs.hotkey.bind(["cmd", "alt"], "left", () => {
    const win = hs.window.focusedWindow()
    if (win) win.frame = LEFT_HALF.fromUnitRect(win.screen.frame)
})

Hotkeys. hs.hotkey.bind(mods, key, onPressed, onReleased?, onRepeat?) returns an HSHotkey, or null if binding failed. bindSpec({mods, key, pressed, released, repeat, message}) takes a single options object. createModal(mods, key) creates a modal group. Mods are strings such as "cmd", "alt", "ctrl" and "shift".

UI. hs.ui is a chained, declarative SwiftUI builder: hs.ui.window({x, y, w, h}), then containers (.vstack() / .hstack() / .zstack(), each closed with .end()), content (.text(), .button(), .image(), ...), modifiers that apply to the previous element (.font(), .frame(), .onClick(), ...), and finally .show(). To change content after the window is shown, pass a reactive value (hs.ui.string(...), HSColor, HSImage) and call .set() on it later. To change the window's structure, build a new window. Use hs.ui.alert, .dialog, .textPrompt and .filePicker for standard UI. Use hs.canvas for absolutely positioned drawing (overlays, shapes, gradients, click-through). Canvas elements are plain objects. In canvas colors, an omitted alpha defaults to 1 ({alpha: 1} is opaque black).

Splitting config. require("./file.js") works like Node's require: module.exports, a required ./ or ../ prefix for local files, optional .js, index.js for directories, parsed .json, and caching by path. Each required file has private scope. Only init.js runs at global scope. require('util') and require('node:sqlite') are also available (see the node page on the docs site).

Permissions. Window, accessibility, application-UI and event-tap features need Accessibility permission. Screen and window snapshots need Screen Recording. Other permissions are noted on the members that need them. hs.permissions can check and request each permission (checkAccessibility(), requestAccessibility(), ...). When a feature needs a permission, say so.

Module table

On the docs site, each module and each type has its own page. The last column lists the object types that belong to the module.

ModuleUse it forObject types in the same file
hsreload, console, activeObjects(), onRelaunch, onOpenFile, accessibilityTimeout
consoleconsole.log and related functions
hs.appinfoHammerspoon's version, config paths
hs.applicationrunning apps, launch or focus, hide, menus, app eventsHSApplication
hs.audiodeviceaudio input and output devices, volume, muteHSAudioDevice
hs.axraw Accessibility elements and notificationsHSAXElement
hs.bluetoothBluetooth devices and BLE peripheralsHSBluetoothDevice, HSBluetoothPeripheral
hs.bonjourdiscover and publish mDNS servicesHSBonjourSearch, HSBonjourService
hs.cameracameras and in-use eventsHSCamera
hs.canvasabsolutely positioned drawing and overlaysHSCanvas
hs.chooserSpotlight-style fuzzy pickerHSChooser
hs.distributednotificationspost and receive distributed notifications
hs.dockiconHammerspoon's own Dock icon
hs.docsopen the bundled API docs
hs.eventtapwatch, suppress and synthesize keyboard, mouse and scroll events; keystrokesHSEventTap, HSEventTapEvent, HSEventTapHotkey
hs.fsfiles, directories, attributes, file handles, path and volume watchersHSFile, HSPathWatcher, HSVolumeWatcher
hs.hashinghashes, HMAC, base64
hs.hotkeyglobal hotkeys, modal hotkeysHSHotkey, HSHotkeyModal (JS)
hs.httpHTTP client, WebSocket clientHSWebSocket
hs.httpserverHTTP and WebSocket serverHSHTTPServer, HSWebSocketConnection
hs.ipcthe hs2 command-line tool
hs.keyboardCaps Lock, LEDs, attached keyboards
hs.keycodeskeyboard layouts, input sources, key codes
hs.localelanguage and region settings
hs.locationLocation Services, geocoding, sunrise and sunsetHSLocationWatcher, HSLocationGeocoder
hs.menubarmenu bar items and menusHSMenuBarItem
hs.midiMIDI devices and messagesHSMIDIDevice
hs.mousepointer position, tracking speed, cursor
hs.mqttMQTT clientHSMQTTClient
hs.networkinterfaces, DNS, reachability, ping, network configuration watchingHSNetworkPing, HSNetworkReachability, HSNetworkConfigurationWatcher
hs.notifymacOS notificationsHSNotification
hs.ocrtext recognition in imagesHSOCRResult, HSOCRObservation
hs.osascriptrun AppleScript and JXA
hs.pasteboardclipboard read, write and change events
hs.permissionscheck and request TCC permissions
hs.plistread and write plist files
hs.powerprevent sleep, lock, battery, power and session events
hs.screendisplays, modes, screenshots, Spaces, Mission ControlHSScreen, HSSpace
hs.serialserial portsHSSerialPort
hs.sharingmacOS share servicesHSSharingService
hs.shortcutsrun Shortcuts
hs.socketTCP, UDP and Unix socketsHSSocket, HSUDPSocket, HSUnixDatagramSocket
hs.soundplay soundsHSSound
hs.spoonsinstall, load and use Spoons
hs.spotlightSpotlight metadata queriesHSSpotlightQuery, HSSpotlightItem, HSSpotlightGroup
hs.streamdeckElgato Stream Deck hardwareHSStreamDeckDevice
hs.taskrun processes (shell, runAsync, builder)HSTask, TaskBuilder (JS)
hs.timerone-shot, repeating and time-of-day timersHSTimer
hs.translationon-device translationHSTranslationSession
hs.uiwindows built from stacks, alerts, dialogs, prompts, file pickers, web viewsHSUIWindow, HSUIAlert, HSUIDialog, HSUITextPrompt, HSUIFilePicker, UIWebView
hs.urleventhandle hammerspoon2:// URLs
hs.usbUSB attach and detach events
hs.userdefaultssmall persistent key/value storage
hs.wifiWi-Fi state, scanning, events
hs.windowfind, move, resize and focus windowsHSWindow
hs.windowfilterfiltered window sets and window eventsHSWindowFilter
node (file)require('util'), require('node:sqlite')DatabaseSync, StatementSync, StatementSyncIterator

The value types shared by all modules are HSRect, HSPoint, HSSize, HSColor, HSFont, HSImage, HSString and HSVideo (docs site: one page each).

Some modules have a "JavaScript additions" section. Those members are written in JS on top of the native module (for example hs.hotkey.bindSpec, hs.window.moveToLeftHalf, hs.task.shell) and work like any other member.

Guides

Read these for narrative explanations and worked examples. Each is a page under https://www.hammerspoon.org/2/main/js/.

  • getting-started.html: config file, lifetime, hotkeys, watchers, Promises, windows, hs.ui, require. Read it for any task that builds a config from scratch.
  • canvas-guide.html: the canvas element dictionaries (types, actions, colors, gradients, clipping) and demos. Method signatures alone aren't enough for canvas work.
  • spoons-guide.html: installing, using and writing Spoons (.spoon2 bundles, spoon.json, bindings, lifecycle).
  • typescript-guide.html: writing the config in TypeScript with hammerspoon.d.ts.

Source

Based on the Hammerspoon 2 source and docs (https://github.com/Hammerspoon/Hammerspoon2, MIT licence). The live reference is at https://www.hammerspoon.org/2/main/js/index.html. If the user's installed version behaves differently from these references, trust the app: hs.docs.show() always matches the installed version.

Skills associés