npm package: @shadr/iterm2-ts
Description: TypeScript client library for iTerm2's native WebSocket/Protobuf API
Latest version: 0.1.3

# @shadr/iterm2-ts

TypeScript client library for iTerm2's native WebSocket/Protobuf API. Control iTerm2 programmatically from Node.js — no Python dependency required.

## Requirements

- macOS
- iTerm2 with "Enable Python API" enabled (Preferences > General > Magic)
- Node.js 18+

## Install

```bash
npm install @shadr/iterm2-ts
```

## Quick Start

```typescript
import { connect } from "@shadr/iterm2-ts";

const iterm = await connect();

try {
  const app = await iterm.getApp();

  // App → windows → tabs → sessions
  const window = app.windows[0];       // { id, tabs, frame?, number? }
  const tab = window.tabs[0];          // { id, sessions }
  const session = tab.sessions[0];     // { id, name, frame?, gridSize? }

  await iterm.sendText(session.id, "echo hello\n");
} finally {
  iterm.disconnect();
}
```

## API Overview

### Connection

```typescript
import { connect } from "@shadr/iterm2-ts";

// Default connection
const iterm = await connect();

// With options — advisoryName identifies your script in iTerm2's API permissions dialog
const iterm = await connect({ advisoryName: "my-script" });
```

### Sessions

```typescript
// Send keystrokes to a session
await iterm.sendText(session.id, "ls -la\n");

// Read visible screen contents as a string
const screen = await iterm.getScreenContents(session.id);

// Read scrollback buffer — returns an array of { text, hardNewline } per line
const lines = await iterm.getBuffer(session.id, 50);

// Split the session into two panes
const newSession = await iterm.splitPane(session.id, { direction: "horizontal" });
```

### Windows & Tabs

```typescript
const { windowId, tabId, sessionId } = await iterm.createWindow();
const tab = await iterm.createTab(windowId);
await iterm.activate({ type: "session", id: sessionId });
await iterm.close({ type: "window", ids: [windowId] });
```

### Profiles

```typescript
const profiles = await iterm.listProfiles();
const bgColor = await iterm.getProfileProperty(session.id, "Background Color");
await iterm.setProfileProperty(session.id, "Background Color", newColor);
```

### Events

```typescript
// Callback — returns an unsubscribe function
const off = await iterm.on("sessionCreated", (event) => {
  console.log("New session:", event.sessionId);
});

// Async iterator — blocks until the next event, good for loops
for await (const event of iterm.notifications("focusChanged")) {
  console.log("Focus changed:", event);
}
```

### Available Events

- **keystroke** — key press/release in a session (characters, modifiers, key code)
- **screenUpdate** — screen contents changed in a session
- **prompt** — shell prompt appeared, command started, or command ended (with exit status)
- **customEscapeSequence** — app-defined escape sequence received (sender identity + payload)
- **newSession** — a new session was created
- **terminateSession** — a session was destroyed
- **layoutChanged** — window/tab/pane layout changed (splits, reorder, resize)
- **focusChanged** — app activation, window focus, tab selection, or session focus changed
- **variableChanged** — a user/session/app variable changed value
- **profileChanged** — a profile was modified
- **broadcastDomainsChanged** — broadcast input domains changed
- **serverOriginatedRpc** — iTerm2 invoked a registered RPC from your script
- ~~**locationChange**~~ — hostname/username/directory changed (deprecated)

### Cleanup

```typescript
iterm.disconnect();
```

## Use Cases

- Automate dev environment setup (open windows, split panes, run commands)
- Build MCP servers that control iTerm2
- Script terminal layouts for presentations or demos
- Monitor session output programmatically
- React to terminal events (focus changes, keystrokes, new sessions)

## Auth

The library authenticates with iTerm2 using a cookie-based system:

1. Checks the `ITERM2_COOKIE` environment variable
2. Falls back to requesting a cookie via `osascript` (AppleScript)

iTerm2 must be running with the Python API enabled.

## CLI (`it2`)

The package includes an `it2` CLI:

```bash
npx tsx src/cli.ts list                          # list sessions with process trees and buffer
npx tsx src/cli.ts list --lines 5 --filter node  # filter by process name, limit buffer lines
npx tsx src/cli.ts list --md                     # markdown output for LLM consumption
npx tsx src/cli.ts watch                         # stream all events as JSON
npx tsx src/cli.ts activate session <id>         # focus a session, tab, or window
```

After `npm run build`, the CLI is also available as `node dist/cli.js` or via the `it2` bin.

## Documentation

- [Architecture](docs/architecture.md) — layer overview and design decisions
- [Protocol](docs/protocol.md) — wire protocol details and auth flow
- [API Reference](docs/api-reference.md) — all public methods with examples

## License

MIT