it2

package module
v0.0.0-...-fa37776 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2025 License: MIT Imports: 0 Imported by: 0

README

it2

Go Reference

A powerful command-line tool for controlling iTerm2 through its API. Automate terminal sessions, manage tabs and windows, monitor events, and integrate iTerm2 into your workflows.

Installation

Requirements
  • iTerm2 (macOS only, for now)
  • Go 1.21+
Install with Go
go install github.com/tmc/it2/cmd/it2@latest

Make sure ~/go/bin is in your PATH:

export PATH="$HOME/go/bin:$PATH"
Install from GitHub Releases

Download pre-built binaries from GitHub Releases.

Verify Installation
it2 auth check

The first time you run it2, iTerm2 will prompt you to allow API access. Click "Allow" to continue.

Plugin Scripts

Plugin scripts provide additional functionality for Claude Code integration and session management. They are automatically embedded in the it2 binary and extracted on first use to ~/.it2/plugins/{version}/.

The plugin discovery system searches for plugins in this priority order:

  1. Executables in your PATH (highest priority)
  2. Directories from IT2_PLUGIN_PATHS environment variable
  3. Embedded plugins extracted from the binary (fallback)

List available plugins:

it2 plugins list

Available plugin scripts (embedded):

  • it2-session-has-no-queued-claude-messages - Detect if Claude is idle
  • it2-session-claude-suggest-action - Suggest interventions for stuck Claude sessions
  • it2-session-is-at-prompt - Check if session is at a shell prompt
  • it2-session-claude-has-modal - Check if Claude has a modal dialog
  • it2-session-claude-auto-approve - Auto-approve safe operations
  • And other session management utilities

To override embedded plugins, place your own version in your PATH.

Quick Start

Try these commands to get started:

# List all terminal sessions
it2 session list

# Send text to the current session
it2 session send-text "echo Hello, iTerm2!"

# Create a new tab
it2 tab create "Default"

# Split current pane vertically
it2 session split --vertical

# Split current pane horizontally
it2 session split --horizontal
Your First Automation Script

Create a development environment with one command:

# Create a new tab and split it into three panes
it2 tab create "Default"
it2 session send-text "cd ~/project && vim"
it2 session split --horizontal
it2 session send-text "npm run dev"
it2 session split --vertical
it2 session send-text "git status && git log --oneline -5"

Common Use Cases

Development Workflow

Setup a complete development environment:

# Create a new tab with editor, dev server, and git status
it2 tab create "Default"
it2 session send-text "cd ~/project && vim"
it2 session split --vertical
it2 session send-text "npm run dev"
it2 session split --horizontal
it2 session send-text "git status"
Multi-Server Management

Connect to multiple servers at once:

for server in web1 web2 db1; do
    it2 tab create "Default"
    it2 session send-text "ssh $server"
done
Broadcast Commands

Run the same command in all sessions:

for session in $(it2 session list --format json | jq -r '.[].id'); do
    it2 session send-text "$session" "git pull && git status"
done
Save and Restore Layouts

Save your current window arrangement:

it2 arrangement save "my-dev-setup"

# Later, restore it
it2 arrangement list
it2 arrangement restore "my-dev-setup"

Command Reference

Essential Commands

Sessions & Tabs:

  • it2 session list - List all terminal sessions
  • it2 session split [--vertical|--horizontal] - Split current pane
  • it2 session send-text <text> - Send text to session
  • it2 tab create <profile> - Create new tab
  • it2 window create - Create new window

Text & Content:

  • it2 text get-buffer - Get session buffer content
  • it2 clipboard paste - Paste from clipboard
  • it2 badge set <text> - Set session badge

Monitoring:

  • it2 notification monitor --type <type> - Monitor events
  • it2 variable monitor <scope> <name> - Watch variable changes
All Command Categories
Click to expand full command list

Application Control:

  • app - Control iTerm2 application (focus, variables, properties)
  • auth - Manage API authentication and connection
  • arrangement - Save and restore window arrangements

Session & Tab Management:

  • session - Create, list, close, split, activate, restart sessions
  • tab - Create, list, close, move, activate tabs
  • window - Create, list, close, focus windows

Text & Content Operations:

  • text - Buffer operations, cursor control, search, selection
  • selection - Control and retrieve text selection
  • badge - Display informational badges on sessions
  • clipboard - Manage clipboard operations
  • screen - Screen capture utilities

Shell Integration Features (requires Shell Integration):

  • prompt - Access command history, prompts, exit codes
  • job - Monitor running processes and jobs
  • shell - Detect shell state (ready/busy/tui) and wait for prompts

Customization:

  • profile - Manage terminal profiles and their properties
  • color - Import/export color presets and themes
  • variable - Get/set iTerm2 variables with scope control

Monitoring & Events:

  • notification - Subscribe to real-time iTerm2 events
  • broadcast - Manage broadcast input domains
  • statusbar - Configure status bar components

Advanced:

  • tmux - Control tmux integration
  • completion - Generate shell completion scripts
  • config - Manage it2 configuration

Configuration

Global Flags

All commands support these flags:

--format string      # Output format: text, json, yaml (default "text")
--timeout duration   # Connection timeout (default 5s)
--url string         # API URL (auto-detects Unix socket)
Environment Variables
ITERM_SESSION_ID     # Current session ID (auto-set by iTerm2)
ITERM2_COOKIE        # Auth cookie (auto-requested if not set)
ITERM2_KEY           # Auth key (auto-requested if not set)
ITERM2_DEBUG=1       # Enable debug logging
Output Formats

Get data in different formats:

it2 session list                    # Human-readable text
it2 session list --format json      # JSON for scripting
it2 profile get "Default" --format yaml  # YAML for config

Advanced Features

Shell Integration

Enable advanced features by installing iTerm2 Shell Integration:

Menu → iTerm2 → Install Shell Integration

This unlocks:

  • Command history access
  • Exit code tracking
  • Job monitoring
  • Shell state detection
# Show command history with exit codes
it2 prompt list

# Search for failed commands
it2 prompt search "git" | grep "Exit: [^0]"

# Wait for shell to be ready
it2 shell wait-for-prompt && it2 session send-text "echo ready"
Real-time Event Monitoring

Subscribe to live iTerm2 events:

# Monitor keystrokes
it2 notification monitor --type keystroke

# Watch for new sessions
it2 notification monitor --type session

# Monitor variable changes
it2 variable monitor session user.myvar
Authentication

Authentication is automatic:

  1. First connection requests credentials via AppleScript
  2. iTerm2 prompts you to allow API access
  3. Credentials cached for session duration
# Check auth status
it2 auth check

# Force re-authentication
it2 auth request

Usage Tips

Session Identification

Sessions can be referenced by:

  • Full format: w0t1p12:C3D91F33-3805-47E2-A3F6-B8AED6EC2209
  • UUID only: C3D91F33-3805-47E2-A3F6-B8AED6EC2209
  • When omitted, uses $ITERM_SESSION_ID (current session)
Scripting Best Practices
# Use JSON output for parsing
SESSIONS=$(it2 session list --format json)
echo "$SESSIONS" | jq -r '.[].id'

# Always quote variables
it2 session send-text "$SESSION_ID" "$COMMAND"

# Chain commands carefully
it2 session send-text "cd /path && pwd && ls"

Troubleshooting

Connection Problems
# Check if iTerm2 API is enabled
it2 auth check

# Enable debug output
ITERM2_DEBUG=1 it2 session list

# Verify API is enabled in iTerm2
# Preferences → General → Magic → Enable Python API
Shell Integration Not Working
# Verify Shell Integration is installed
echo $ITERM_SESSION_ID  # Should show session ID

# Reinstall if needed
curl -L https://iterm2.com/shell_integration/install_shell_integration_and_utilities.sh | bash
Session ID Not Found
# List all sessions to find the correct ID
it2 session list

# Use UUID format or full format
it2 session send-text C3D91F33-3805-47E2-A3F6-B8AED6EC2209 "echo test"

Go Package

For using it2 as a Go library in your own projects:

go get github.com/tmc/it2

See documentation at pkg.go.dev/github.com/tmc/it2

Resources

Get help for any command:

it2 help [command]
it2 [command] --help

Documentation

Overview

Package it2 provides a powerful CLI tool and Go client library for the iTerm2 API.

The it2 command-line tool enables comprehensive programmatic control of iTerm2 on macOS. For library usage, see the github.com/tmc/it2/internal/client package. All major iTerm2 automation features are supported through Unix socket and WebSocket APIs.

Features

Comprehensive iTerm2 control capabilities:

  • Session Management: Create, list, close, split, activate, restart, monitor
  • Tab Management: Create, list, close, move, activate tabs
  • Window Management: Create, list, close, focus, arrange windows
  • Text Operations: Send text, manipulate buffers, control cursor, search
  • Shell Integration: Access command history, prompts, job monitoring
  • Variable Management: Get/set with session, tab, window, app scopes
  • Profile Management: List profiles, get/set properties dynamically
  • Color Management: Import/export presets, modify appearance
  • Notifications: Subscribe to and monitor iTerm2 events in real-time
  • tmux Integration: Control tmux sessions through iTerm2
  • Broadcast Domains: Manage input broadcasting to multiple sessions
  • Arrangements: Save and restore window arrangements

Installation

Install the CLI tool:

go install github.com/tmc/it2/cmd/it2@latest

For library usage:

import "github.com/tmc/it2/internal/client"

Library Usage

Use the internal/client package for programmatic access:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/tmc/it2/internal/client"
)

func main() {
	// Create and connect to iTerm2
	c := client.New("ws://localhost:1912")
	ctx := context.Background()
	if err := c.Connect(ctx); err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	// List all sessions
	sessions, err := c.ListSessions(ctx)
	if err != nil {
		log.Fatal(err)
	}

	for _, session := range sessions {
		fmt.Printf("Session: %s (Window: %s)\n",
			session.SessionID, session.WindowID)
	}

	// Send text to first session
	if len(sessions) > 0 {
		err = c.SendText(ctx, sessions[0].SessionID, "echo Hello!\n")
		if err != nil {
			log.Fatal(err)
		}
	}
}

Connection

The client automatically chooses the best connection method:

  • Unix socket: ~/Library/Application Support/iTerm2/private/socket (preferred, faster)
  • WebSocket: ws://localhost:1912 (fallback if Unix socket unavailable)

Authentication

The client automatically handles iTerm2 authentication:

  • Auto-requests credentials from iTerm2 when needed (via AppleScript)
  • iTerm2 prompts user to allow API access on first connection
  • Credentials cached for session duration
  • Falls back to ITERM2_COOKIE and ITERM2_KEY environment variables
  • Can be bypassed entirely in trusted environments (see auth package)

Advanced Features

Shell Integration - Access command history and prompts:

// List command history with exit codes
prompts, err := client.ListPrompts(ctx, sessionID)
for _, promptID := range prompts {
	details, _ := client.GetPromptByID(ctx, sessionID, promptID)
	fmt.Printf("Command: %s, Exit: %d\n",
		details.Command, details.ExitStatus)
}

Real-time monitoring of events:

// Subscribe to keystroke notifications
ch, err := client.SubscribeToNotifications(ctx, sessionID, "keystroke")
for notification := range ch {
	// Process keystroke events
	fmt.Printf("Key pressed: %v\n", notification)
}

Variable management with scoping:

// Set user variable at session scope
err = client.SetVariableWithScope(ctx, "session", sessionID,
	"user.myvar", "value")

// Get app-level variable
pid, err := client.GetVariableWithScope(ctx, "app", "", "pid")

CLI Tool

The it2 command provides comprehensive terminal control.

Usage:

it2 [command]

Available Commands:

app          Control the iTerm2 application
arrangement  Manage iTerm2 window arrangements
auth         Manage iTerm2 API authentication
broadcast    Manage broadcast domains
color        Manage iTerm2 colors and appearance
completion   Generate the autocompletion script for the specified shell
help         Help about any command
job          Monitor jobs in iTerm2 sessions
notification Subscribe to iTerm2 notifications
profile      Manage iTerm2 profiles
prompt       Manage prompts and command history in iTerm2 sessions
selection    Text selection operations in iTerm2
session      Manage iTerm2 sessions
statusbar    Manage iTerm2 status bar components
tab          Manage iTerm2 tabs
text         Text and buffer operations in iTerm2
tmux         Manage tmux integration
variable     Manage iTerm2 variables
window       Manage iTerm2 windows

Global Flags:

--format string      Output format (text, json, yaml) (default "text")
--timeout duration   Connection timeout (default 5s)
--url string         API URL (default "ws://localhost:1912", auto-detects Unix socket)

Examples:

# List all sessions
it2 session list

# Send text to current session (uses $ITERM_SESSION_ID)
it2 session send-text "echo Hello, iTerm2!"

# Show command history with Shell Integration
it2 prompt list

# Create a new tab
it2 tab create

# Split current pane vertically
it2 session split --vertical

# Monitor keystroke events in real-time
it2 notification monitor --type keystroke

# Get terminal buffer contents
it2 text get-buffer <session-id>

# Search command history
it2 prompt search "git commit"

Use "it2 [command] --help" for more information about a command.

Environment Variables

  • ITERM_SESSION_ID: Current session ID (set by iTerm2)
  • ITERM2_COOKIE: Authentication cookie (optional)
  • ITERM2_KEY: Authentication key (optional)
  • ITERM2_DEBUG: Enable debug logging when set to "1"

Session Identification

Sessions can be identified using either format:

  • Full: "w0t1p12:C3D91F33-3805-47E2-A3F6-B8AED6EC2209"
  • UUID only: "C3D91F33-3805-47E2-A3F6-B8AED6EC2209"

Many commands support automatic fallback to $ITERM_SESSION_ID.

Requirements

  • iTerm2 version 3.3.0 or later
  • Python API enabled: Preferences → General → Magic → Enable Python API
  • macOS (iTerm2 is macOS-only)

See Also

Directories

Path Synopsis
cmd
gen-docs command
it2 command
Command it2 provides comprehensive control over iTerm2 through its WebSocket API.
Command it2 provides comprehensive control over iTerm2 through its WebSocket API.
internal
cmd
Package cmd provides command implementations for the it2 CLI.
Package cmd provides command implementations for the it2 CLI.
cmd/alert
Package alert provides iTerm2 alert and dialog commands.
Package alert provides iTerm2 alert and dialog commands.
cmd/app
Package app provides commands for controlling the iTerm2 application.
Package app provides commands for controlling the iTerm2 application.
cmd/auth
Package auth provides commands for iTerm2 API authentication.
Package auth provides commands for iTerm2 API authentication.
cmd/color
Package color provides commands for managing iTerm2 colors and appearance.
Package color provides commands for managing iTerm2 colors and appearance.
cmd/colorpreset
Package colorpreset provides commands for managing iTerm2 color presets.
Package colorpreset provides commands for managing iTerm2 color presets.
cmd/control
Package control provides iTerm2 custom control management commands.
Package control provides iTerm2 custom control management commands.
cmd/event
Package event provides commands for managing iTerm2 event subscriptions.
Package event provides commands for managing iTerm2 event subscriptions.
cmd/filepanel
Package filepanel provides iTerm2 file panel dialog commands.
Package filepanel provides iTerm2 file panel dialog commands.
cmd/focus
Package focus provides commands for managing focus in iTerm2.
Package focus provides commands for managing focus in iTerm2.
cmd/job
Package job provides commands for job monitoring in iTerm2.
Package job provides commands for job monitoring in iTerm2.
cmd/keyboard
Package keyboard provides commands for managing keyboard bindings in iTerm2.
Package keyboard provides commands for managing keyboard bindings in iTerm2.
cmd/lifecycle
Package lifecycle provides iTerm2 session lifecycle management commands.
Package lifecycle provides iTerm2 session lifecycle management commands.
cmd/notification
Package notification provides commands for iTerm2 notification system.
Package notification provides commands for iTerm2 notification system.
cmd/preference
Package preference provides iTerm2 preference management commands.
Package preference provides iTerm2 preference management commands.
cmd/profile
Package profile provides commands for iTerm2 profile management.
Package profile provides commands for iTerm2 profile management.
cmd/prompt
Package prompt provides commands for managing prompts and command history in iTerm2 sessions using Shell Integration features.
Package prompt provides commands for managing prompts and command history in iTerm2 sessions using Shell Integration features.
cmd/selection
Package selection provides commands for managing text selection in iTerm2.
Package selection provides commands for managing text selection in iTerm2.
cmd/session
Package session provides commands for iTerm2 session management.
Package session provides commands for iTerm2 session management.
cmd/shell
Package shell provides commands for shell state detection and prompt tracking in iTerm2 sessions using Shell Integration features.
Package shell provides commands for shell state detection and prompt tracking in iTerm2 sessions using Shell Integration features.
cmd/shortcuts
Package shortcuts provides top-level convenience commands that wrap commonly used session commands.
Package shortcuts provides top-level convenience commands that wrap commonly used session commands.
cmd/snippet
Package snippet provides text snippet storage and retrieval commands.
Package snippet provides text snippet storage and retrieval commands.
cmd/tab
Package tab provides commands for iTerm2 tab management.
Package tab provides commands for iTerm2 tab management.
cmd/text
Package text provides commands for text operations in iTerm2.
Package text provides commands for text operations in iTerm2.
cmd/utility
Package utility provides iTerm2 utility and helper commands.
Package utility provides iTerm2 utility and helper commands.
cmd/variable
Package variable provides commands for iTerm2 variable management.
Package variable provides commands for iTerm2 variable management.
cmd/window
Package window provides commands for iTerm2 window management.
Package window provides commands for iTerm2 window management.
cmdcore
Package cmdcore provides core command infrastructure for iTerm2 CLI operations.
Package cmdcore provides core command infrastructure for iTerm2 CLI operations.
cmderr
Package cmderr provides standardized error handling for iTerm2 CLI commands.
Package cmderr provides standardized error handling for iTerm2 CLI commands.
cmdutil
Package cmdutil provides command utilities for iTerm2 CLI operations
Package cmdutil provides command utilities for iTerm2 CLI operations
iterm2settings
Package iterm2settings provides utilities for checking iTerm2 application state and settings.
Package iterm2settings provides utilities for checking iTerm2 application state and settings.
jqutil
Package jqutil provides jq filtering utilities for JSON output.
Package jqutil provides jq filtering utilities for JSON output.
scope
Package scope provides session filtering based on scope settings.
Package scope provides session filtering based on scope settings.
sessionid
Package sessionid provides utilities for managing iTerm2 session identifiers.
Package sessionid provides utilities for managing iTerm2 session identifiers.
validate
Package validate provides validation functions for iTerm2 CLI command inputs.
Package validate provides validation functions for iTerm2 CLI command inputs.
waitstable
Package waitstable provides utilities for detecting when a stream or buffer has stabilized (no changes for a configured duration).
Package waitstable provides utilities for detecting when a stream or buffer has stabilized (no changes for a configured duration).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL