iterm2api

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package iterm2api is a small, opt-in client for iTerm2's scripting API (the protocol iTerm2 calls its "Python API": protobuf messages over a WebSocket on a Unix socket).

hopsesh uses it only when the user has turned the API on in iTerm2 themselves, and only for three things the AppleScript path cannot do well: learning that a tab hopsesh opened has closed (an event, not polling), opening a split beside the session the user is in, and finding and focusing a session precisely by its TTY. Every caller treats an error from Connect as "use the AppleScript path instead"; nothing here is required.

What the client can say

The client is hand-written and speaks a deliberately tiny part of the protocol. The only requests it can encode are:

  • list sessions (windows, tabs and session ids; no titles, no contents)
  • focus state (which window is key)
  • create a tab, and split a pane, running a command in a directory
  • activate (select and bring forward) a session
  • read a session's "tty" variable, and set "user.hopsesh_*" variables
  • subscribe to new-session, session-terminated and focus-changed notifications

It has no way to send text, inject bytes, read a screen, buffer, selection, prompt or screenshot, monitor keystrokes, register functions, change profiles or preferences, or invoke menu items: those requests are not in this package at all, and allowlist_test.go fails the build's tests if one is added. Notifications other than the three above are skipped undecoded.

Credentials

iTerm2 authenticates a connection with a single-use cookie and key. The client asks for one through AppleScript (`request cookie and key for app named "hopsesh"`, which macOS gates behind one Automation consent prompt), and only after a credential-free handshake has shown that the API server is actually listening, so a user who has not enabled the API is never prompted. When iTerm2 itself launched hopsesh with ITERM2_COOKIE and ITERM2_KEY set, those are used once and removed from the process environment. The cookie and key live in memory for the handshake only: they are never logged, written to disk, put in an error, or passed to a child process (ScrubEnv removes them from a child's environment). hopsesh never enables the API, never changes an iTerm2 or Claude setting, and never uses iTerm2's admin bypass file.

Exit status

iTerm2's protocol reports that a session terminated, not how its program exited: there is no exit status in the notification and no exit-status variable. The exit code of a hopsesh step or session comes from hopsesh's own launch record (the outcome file that `hopsesh terminal-step` writes), and this package supplies the "it has closed" event.

Provenance

iTerm2 and its protocol definition (api.proto) are GPLv2, which hopsesh's Apache-2.0 licence cannot absorb, so no iTerm2 file is vendored, translated or generated from here. The messages are written from the protocol's public facts (message and field numbers, header names, the socket path), the minimum needed to interoperate, and only for the requests listed above. See NOTICE.md in this directory.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnavailable: the API server is not listening (iTerm2 is not running, the user has
	// not enabled the API, or this is not macOS).
	ErrUnavailable = errors.New("iterm2api: iTerm2's API is not available")
	// ErrNotAuthorized: the API is on but refused hopsesh, or the user declined the macOS
	// Automation prompt for hopsesh to control iTerm2.
	ErrNotAuthorized = errors.New("iterm2api: iTerm2's API did not authorize hopsesh")
	// ErrTooOld: this iTerm2 cannot hand out API credentials to other apps, or does not
	// speak this protocol.
	ErrTooOld = errors.New("iterm2api: this iTerm2 is too old for its API")
)

Errors from Connect and Probe. Every one of them means "use the AppleScript path": the API is optional and its absence is never shown to the user as a failure.

View Source
var ErrClosed = errors.New("iterm2api: connection closed")

ErrClosed is returned by requests on a connection that has ended.

Functions

func CookieScript

func CookieScript(appName string) string

CookieScript is the AppleScript that asks a running iTerm2 for a cookie and key. It never launches iTerm2 (an empty result when it is not running), and the client runs it only after a handshake showed the API listening. termapp checks it against its AppleScript allowlist.

func DefaultSocketPath

func DefaultSocketPath() string

DefaultSocketPath is where iTerm2 listens for API connections: the Unix socket under its Application Support folder. It is empty off macOS.

func Probe

func Probe(ctx context.Context, opts Options) error

Probe reports whether iTerm2's API is listening, without credentials and without any prompt: nil if it is (and would accept a cookie), ErrUnavailable otherwise.

func QuoteArgv

func QuoteArgv(argv []string) string

QuoteArgv joins argv into one command line for Launch.Command, single-quoting every argument that is not plainly safe (iTerm2 splits the command with shell-like quoting).

func ScrubEnv

func ScrubEnv(env []string) []string

ScrubEnv returns env (in os.Environ form) without iTerm2's API credentials. Every child hopsesh starts from a context that might hold them should get its environment through this.

func ValidLabel

func ValidLabel(v string) bool

ValidLabel reports whether a label value is already clean: no C0 or C1 controls (so no ESC or BEL), no DEL, no bidirectional controls, valid UTF-8, at most 80 characters. The caller cleans labels with termapp.Sanitize; this package only refuses unclean ones.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is one authenticated connection to iTerm2's API. Its methods are safe for concurrent use.

func Connect

func Connect(ctx context.Context, opts Options) (*Client, error)

Connect opens an authenticated connection to iTerm2's API. Any error means the caller should use its AppleScript path.

Order: the API socket must exist; a credential-free handshake must show the server listening (so a user who has not enabled the API never sees a consent prompt); only then is a cookie requested, once, and used for one handshake.

func (*Client) Close

func (c *Client) Close() error

Close ends the connection.

func (*Client) Done

func (c *Client) Done() <-chan struct{}

Done is closed when the connection ends; Err then says why.

func (*Client) Err

func (c *Client) Err() error

Err is why the connection ended (nil while it is open, or after Close).

func (*Client) Events

func (c *Client) Events() <-chan Event

Events delivers the notifications the client subscribed to, in order. It is closed when the connection ends.

func (*Client) FindTTY

func (c *Client) FindTTY(ctx context.Context, tty string) (Located, bool, error)

FindTTY finds the session whose TTY is tty ("/dev/ttys003" or "ttys003"). The TTY must come from hopsesh's own knowledge (a vendor registry's PID through ps, or hopsesh's launch record), never from anything shown in a tab; the caller re-checks that PID right before focusing.

func (*Client) Focus

func (c *Client) Focus(ctx context.Context, session string) error

Focus selects a session's tab and pane, brings its window to the front and activates iTerm2.

func (*Client) KeyWindow

func (c *Client) KeyWindow(ctx context.Context) (string, error)

KeyWindow returns the id of the current terminal window (the key window, or the last one that was), or "" if there is none.

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context) (Layout, error)

ListSessions returns iTerm2's windows, tabs and sessions by id.

func (*Client) OpenSplit

func (c *Client) OpenSplit(ctx context.Context, session string, side SplitSide, l Launch) (Opened, error)

OpenSplit splits session's pane and runs l in the new one.

func (*Client) OpenTab

func (c *Client) OpenTab(ctx context.Context, window string, l Launch) (Opened, error)

OpenTab opens a new tab in window (a new window if window is "") running l.

func (*Client) ProtocolVersion

func (c *Client) ProtocolVersion() string

ProtocolVersion is the protocol version iTerm2 reported ("1.18"), or "" if it did not.

func (*Client) SessionTTY

func (c *Client) SessionTTY(ctx context.Context, session string) (string, error)

SessionTTY returns the TTY device of a session ("/dev/ttys003"), as iTerm2's own process bookkeeping knows it.

func (*Client) SetLabels

func (c *Client) SetLabels(ctx context.Context, session string, labels map[string]string) error

SetLabels sets user.hopsesh_<name> variables on a session (for badges and titles that interpolate them). Names are lower-case letters, digits and underscores; values must already be clean (termapp.Sanitize), and one that is not is refused. Labels are for people: hopsesh never reads them back as identity.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context) error

Subscribe asks for new-session, session-terminated and focus-changed notifications; they arrive on Events, which the caller must then drain until it is closed (or Close the client). Notifications that arrive before Subscribe are discarded.

type CredentialSource

type CredentialSource func(ctx context.Context, appName string) (Credentials, error)

CredentialSource asks iTerm2 for a fresh cookie and key on behalf of appName.

type Credentials

type Credentials struct {
	// contains filtered or unexported fields
}

Credentials is the cookie and key iTerm2 issues for one connection. Its value never appears in formatted output, so it cannot reach a log or an error by accident.

func AppleScriptCredentials

func AppleScriptCredentials(ctx context.Context, appName string) (Credentials, error)

AppleScriptCredentials asks iTerm2 for a cookie and key through AppleScript. The first call shows macOS's "hopsesh wants to control iTerm2" prompt; a declined prompt maps to ErrNotAuthorized.

func NewCredentials

func NewCredentials(cookie, key string) Credentials

NewCredentials makes Credentials from a cookie and key (for tests and the fake server).

func (Credentials) Format

func (c Credentials) Format(f fmt.State, _ rune)

Format hides the secret for every verb.

func (Credentials) GoString

func (Credentials) GoString() string

GoString hides the secret.

func (Credentials) String

func (Credentials) String() string

String hides the secret.

type Event

type Event struct {
	Kind      EventKind
	SessionID string      // SessionTerminated, SessionCreated
	Focus     FocusChange // FocusChanged
}

Event is one notification from iTerm2.

type EventKind

type EventKind int

EventKind is what a notification reports.

const (
	// SessionTerminated: a session ended and left its tab (its pane closed). The protocol
	// carries no exit status.
	SessionTerminated EventKind = iota + 1
	// SessionCreated: a new session appeared.
	SessionCreated
	// FocusChanged: the key window, selected tab, active pane or app activation changed.
	FocusChanged
	// Reconnected (Monitor only): the connection was lost and is back. Watched sessions
	// that disappeared meanwhile have already been reported as SessionTerminated.
	Reconnected
)

func (EventKind) String

func (k EventKind) String() string

type FocusChange

type FocusChange struct {
	// AppActive is set when iTerm2 became (true) or stopped being (false) the active app.
	AppActive *bool
	// WindowID is set when a window's key state changed; WindowKey tells whether it is now
	// the key window (or the current terminal window while another app's window is key).
	WindowID  string
	WindowKey bool
	// TabID is set when a window's selected tab changed.
	TabID string
	// SessionID is set when a session became the active pane of its tab.
	SessionID string
}

FocusChange is one FocusChangedNotification. Exactly one of its parts is set.

type Launch

type Launch struct {
	Profile string // empty: the default profile
	Command string
	Dir     string
}

Launch is what a new tab or split runs. Command replaces the profile's command for this session only (iTerm2 parses it into arguments itself; QuoteArgv builds one); Dir is its working directory. Neither changes the profile.

type Layout

type Layout struct {
	Windows []Window
	// Buried lists sessions that are running but not in any tab.
	Buried []string
}

Layout is iTerm2's windows, tabs and sessions, by id only.

func (Layout) Locate

func (l Layout) Locate(session string) (windowID, tabID string, ok bool)

Locate returns the window and tab holding a session.

func (Layout) Sessions

func (l Layout) Sessions() []string

Sessions lists every session id in the layout, buried ones included.

type Located

type Located struct {
	WindowID, TabID, SessionID string
}

Located is a session found in iTerm2's layout.

type Monitor

type Monitor struct {
	// contains filtered or unexported fields
}

Monitor holds one long-lived connection for notifications, reconnecting when iTerm2 drops it (iTerm2 quit and came back, or the user restarted the API). Each reconnection asks for a fresh cookie, which does not prompt again once the user has consented.

When the connection comes back, every watched session that is no longer in iTerm2's layout is reported as terminated, so a tab that closed while the connection was down is not missed.

func NewMonitor

func NewMonitor(o MonitorOptions) *Monitor

NewMonitor makes a Monitor; Run starts it.

func (*Monitor) Client

func (m *Monitor) Client() *Client

Client returns the current connection, or nil while there is none. Requests on it may fail with ErrClosed if it drops.

func (*Monitor) Events

func (m *Monitor) Events() <-chan Event

Events delivers every notification (and Reconnected) in order until Run returns. The caller must drain it.

func (*Monitor) Run

func (m *Monitor) Run(ctx context.Context) error

Run connects, subscribes and delivers events until ctx ends. It returns at once with Connect's error if the first connection fails (the caller then uses its AppleScript path), and with ErrNotAuthorized or ErrTooOld if a reconnection is refused, so a declined consent is never asked again in a loop. A lost connection is retried with backoff while iTerm2 is away.

func (*Monitor) Started

func (m *Monitor) Started() <-chan struct{}

Started is closed once the first connection is up and subscribed.

func (*Monitor) Unwatch

func (m *Monitor) Unwatch(session string)

Unwatch forgets a session.

func (*Monitor) Watch

func (m *Monitor) Watch(session string) <-chan struct{}

Watch returns a channel that is closed when session terminates (at once if it already has).

type MonitorOptions

type MonitorOptions struct {
	// Options are passed to Connect.
	Options Options
	// Connect replaces Connect (tests).
	Connect func(ctx context.Context) (*Client, error)
	// MinBackoff and MaxBackoff bound the wait between reconnection attempts; zero means
	// 500 ms and 30 s.
	MinBackoff, MaxBackoff time.Duration
}

MonitorOptions configure a Monitor.

type Opened

type Opened struct {
	WindowID  string
	TabID     string
	SessionID string
}

Opened names the session a created tab or split runs in.

type Options

type Options struct {
	// SocketPath is iTerm2's API socket; empty means DefaultSocketPath.
	SocketPath string
	// TCPAddress, when set, is tried if SocketPath does not exist (iTerm2 before the Unix
	// socket listened on localhost:1912). Off by default: a credential sent to a TCP port
	// could reach any local program listening there.
	TCPAddress string
	// AppName is the advisory name iTerm2 shows for this client; empty means "hopsesh".
	AppName string
	// Credentials fetches a fresh cookie and key; nil means AppleScriptCredentials.
	Credentials CredentialSource
	// Timeout bounds the connection and each handshake; zero means 5 seconds.
	Timeout time.Duration
}

Options configure Connect and Probe. The zero value is right for hopsesh on macOS.

type RequestError

type RequestError struct {
	Request string
	Status  uint64
	Message string
}

RequestError is iTerm2 refusing a request: Status is the response's status enum, or Message is set when iTerm2 called the request malformed.

func (*RequestError) Error

func (e *RequestError) Error() string

type SplitSide

type SplitSide int

SplitSide is where a split goes relative to the session it splits.

const (
	SplitRight SplitSide = iota // beside, on the right (a vertical divider)
	SplitLeft
	SplitBelow // underneath (a horizontal divider)
	SplitAbove
)

type Tab

type Tab struct {
	ID              string
	ActiveSessionID string // empty before protocol 1.18
	Sessions        []string
}

Tab is one tab and the sessions (panes) in it.

type Window

type Window struct {
	ID            string
	SelectedTabID string // empty before protocol 1.18
	Tabs          []Tab
}

Window is one terminal window.

Directories

Path Synopsis
Package fakeiterm2 is a stand-in for iTerm2's API server, for tests: it listens on a Unix socket, speaks the WebSocket subprotocol and the protobuf messages that iterm2api's client uses, and keeps a small model of windows, tabs and sessions.
Package fakeiterm2 is a stand-in for iTerm2's API server, for tests: it listens on a Unix socket, speaks the WebSocket subprotocol and the protobuf messages that iterm2api's client uses, and keeps a small model of windows, tabs and sessions.

Jump to

Keyboard shortcuts

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