# pi-caps-blink

Pi extension for macOS that blinks the MacBook Caps Lock LED while any Pi agent is actively running on the machine, and restores the system-managed LED when all agents settle.

## Requirements

- macOS 26 or later (Darwin 25+)
- Node.js 22.19+
- Xcode Command Line Tools (or Xcode) so `/usr/bin/xcrun swift` can run the packaged daemon script
- A Mac with a built-in keyboard HID service (`Built-In == true`); external keyboards are never used

The npm manifest rejects non-macOS installation. Older macOS versions, or local
loads on unsupported platforms, disable the extension with a warning.

## Install

From npm:

```bash
pi install npm:pi-caps-blink
```

From a local checkout while developing:

```bash
pi install /absolute/path/to/pi-caps-blink
# or
pi install ./relative/path/to/pi-caps-blink
```

Use `-l` for a project-local install. To try one run without persisting settings: `pi -e ./path/to/pi-caps-blink`.

## Busy semantics

Busy is agent activity, not idle TUI presence:

| Event | Behavior |
| --- | --- |
| `agent_start` | Acquire (desired busy) |
| `agent_settled` | Release only if `ctx.isIdle()` is true |
| `session_start` | Acquire if the session is already non-idle |
| `session_shutdown` | Always release |

`agent_settled` is used instead of `agent_end` because retries, compaction retries, and queued follow-ups can remain after `agent_end`.

Handlers update desired state synchronously and reconcile in the background. They never await daemon startup or delay agent work. Failures warn at most once per active period and degrade to no blinking.

## Machine-wide aggregation

Multiple Pi processes share one per-user Swift daemon. An open Unix-domain socket connection is one active lease; there is no heartbeat protocol. The daemon blinks while the lease count is greater than zero and stops only when the last lease closes. Kernel EOF drops a lease if a client crashes or is SIGKILL’d, so one process cannot turn the LED off while another remains busy.

## Behavior

- Blink cadence: **250 ms On / 750 ms Off**, starting On as soon as the first lease appears
- Idle restore: on transition to zero leases, the daemon synchronously stops the timer and sets `HIDCapsLockLED` to **Auto**
- Daemon idle exit: after 5 minutes with no leases, the daemon exits, allowing updates and uninstall without leaving an orphan process while avoiding Swift startup between adjacent runs
- Startup always restores **Auto** before accepting leases

## Caps Lock LED caveat

The LED is controlled via the private, unsupported `HIDCapsLockLED` property (`On` / `Off` / `Auto`) on a passive IOHID event-system client. This is not a public API and may break or be rejected by future macOS releases. The extension feature-detects and fails soft.

No root, Accessibility, or Input Monitoring permission is expected for this path on currently tested hardware. Logical Caps Lock state (`HIDCapsLockState`) is not written.

## Auto restoration

`HIDCapsLockLED=Auto` is restored when:

- The last lease closes
- The daemon starts (before accepting clients)
- Catchable termination (`SIGINT` / `SIGTERM`) or clean idle exit

**Limitation:** SIGKILL of the daemon or sudden power loss can leave an On/Off override stranded. Recovery is best-effort: the next daemon start restores Auto before accepting leases. Starting any Pi session that becomes busy (or otherwise spawning the daemon) triggers that recovery.

## Architecture

```
Pi extension (TypeScript)
  └─ CapsBlinkClient (desiredBusy / socket / retry / generation)
       └─ Unix socket lease ──► CapsBlinkDaemon.swift (singleton)
                                  ├─ flock on runtime lock file
                                  ├─ count same-UID accepted fds
                                  └─ HID LED On/Off/Auto (built-in keyboard only)
```

Runtime directory: Darwin per-user temp (`getconf DARWIN_USER_TEMP_DIR` / `confstr(_CS_DARWIN_USER_TEMP_DIR)`) + `pi-caps-blink-v1/`, with short `l` (lock) and `s` (socket) names. Directory mode `0700`, socket/lock `0600`, no symlinks, UID ownership checks, `getpeereid` same-UID enforcement, and socket path length under 104 bytes. TypeScript passes the canonical path; Swift independently derives it and rejects mismatches. On connect failure, the extension spawns `/usr/bin/xcrun swift <packaged-script>` detached and retries with exponential backoff + jitter; only the flock winner binds the socket.

## Development

```bash
npm install
npm run check
```

The daemon accepts `--fake-led-file <path>` for LED-free local checks of lease/blink lifecycle.

## Manual hardware test

On a MacBook (or other Mac with a built-in keyboard) running macOS 26+:

1. Install this package into Pi and start a session; confirm Caps Lock still reflects real Caps Lock when idle (Auto).
2. Start an agent turn; the Caps Lock LED should blink ~250 ms on / 750 ms off without changing typing Caps Lock behavior.
3. Open a second Pi process and run an agent there too; settling one session must not stop the blink while the other remains busy.
4. Settle all agents; the LED should return to normal Caps Lock indication promptly.
5. Optional: kill a busy Pi process mid-turn; its lease should drop via EOF and blinking should continue or stop according to remaining leases.
6. Optional recovery check: if the LED is stuck after a forced daemon kill, start Pi again and become busy once—daemon startup should restore Auto first.

## Privacy and security

- No network I/O; coordination is a per-user local Unix socket under the Darwin user temp directory
- No agent transcripts, prompts, or tool output are read or sent
- Same-UID peer checks and restrictive file modes limit cross-user access to the lease socket
- The extension and daemon run as your user; like other Pi packages, review source before installing from untrusted origins

## License

MIT — Copyright (c) 2026 Boston Cartwright. See [LICENSE](LICENSE).
