termapp

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 26 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 termapp opens hopsesh's launches in the user's own terminal app (iTerm2, Terminal, Windows Terminal, a Linux terminal), finds the tab a running session is in, and brings it forward. It never reads what a terminal shows and never types into one.

Every launch runs only hopsesh itself, by an opaque ticket: `<hopsesh> terminal-open <id>` (or `terminal-step <id>` for a hand-off step). hopsesh's own verb then prints the tab's labels, records its terminal and its child's process id, and starts the agent's command from the ticket. So what goes to a terminal app (an AppleScript string, a PowerShell line) carries an absolute path and an id, never a session's title or a prompt.

The only verb a terminal must have is Open. Finder (find a tab by its TTY), Focuser (bring a tab forward) and Watcher (learn that a tab's program ended) are optional, and found by interface assertion. Reading a terminal's output is deliberately not a capability: what a step printed reaches hopsesh only through the step's own relay.

Index

Constants

View Source
const (
	IDITerm2          = "iterm2"
	IDTerminalApp     = "terminal-app"
	IDWindowsTerminal = "windows-terminal"
	IDLinux           = "linux"
)

Terminal ids.

Variables

View Source
var (
	// ErrNotInstalled means the terminal app is not on this machine.
	ErrNotInstalled = errors.New("not installed")
	// ErrDenied means macOS did not let hopsesh control the app (Privacy & Security ›
	// Automation).
	ErrDenied = errors.New("macOS did not allow hopsesh to control it")
	// ErrNoTerminal means no terminal could be opened: copy the command instead.
	ErrNoTerminal = errors.New("no terminal could be opened")
	// ErrGone means the tab hopsesh found is no longer there (or no longer runs the same
	// terminal device).
	ErrGone = errors.New("the tab is no longer there")
)

Functions

func ClearSequences

func ClearSequences(getenv func(string) string) []byte

ClearSequences take the labels off again (when the agent has ended and the tab goes on as a shell); nil where Sequences would be.

func DevTTY

func DevTTY(ps string) string

DevTTY is the device of a terminal as ps names it ("ttys003" → "/dev/ttys003", "pts/3" → "/dev/pts/3"); "" for none ("??", "?") or anything else.

func ExecShell

func ExecShell(dir string) error

ExecShell replaces this process with the user's login shell in dir: a tab whose command has ended stays open as a shell instead of closing.

func IsTicket

func IsTicket(id string) bool

IsTicket reports whether id looks like a ticket's id.

func Line

func Line(l Launch) string

Line is the launch as a line for this machine's shell: change to its folder, then run hopsesh's verb.

func Osascript

func Osascript(ctx context.Context, script string) (string, error)

Osascript runs a script with macOS's osascript (from standard input, so no argument list carries it), and maps its errors: -1743/-1744 (not authorised to send Apple events) to ErrDenied, -1728/-10814 (no such application) to ErrNotInstalled.

func Sanitize

func Sanitize(s string, max int) string

Sanitize makes untrusted text (a session's title from a vendor's files) safe to show: control characters (C0, DEL, C1, so ESC and BEL too) and bidirectional overrides become spaces, runs of spaces one, invalid UTF-8 is dropped, and the result is cut to max characters (with "…").

func Sequences

func Sequences(l Labels, getenv func(string) string) []byte

Sequences are the bytes that label this tab: user variables (iTerm2 and WezTerm) and a badge (iTerm2), wrapped for tmux when $TMUX is set; nil in any other terminal. Values go in base64, as the protocol has them; the badge's format is hopsesh's own constant text that names the variables, so no value is ever read as a format.

func Show

func Show(ctx context.Context, procs Procs, f Found) error

Show brings a found tab forward, after checking again that its process still runs on the same terminal device (a tab's device can be reused once its program ends).

func VetScript

func VetScript(script string) error

VetScript reports the first line of a script that is not one hopsesh may run.

Types

type Candidate

type Candidate struct {
	PID int
	TTY string
}

Candidate is a process that may run the session: the agent's own (TTY "": whatever terminal it is on) or one hopsesh started (TTY: the device it started on, which must still be its).

type Caps

type Caps struct {
	Find  bool `json:"find"`
	Focus bool `json:"focus"`
	Watch bool `json:"watch"`
	// Labels: the terminal shows hopsesh's labels (a badge and user variables).
	Labels bool `json:"labels"`
	// Tabs: it opens launches as tabs in its front window (else as windows).
	Tabs bool `json:"tabs"`
	// Hold: a launch's tab closes when its program ends unless hopsesh keeps it open.
	Hold bool `json:"hold"`
}

Caps is what a terminal can do besides Open.

func CapsOf

func CapsOf(t Terminal) Caps

CapsOf is what t can do.

type Emulator

type Emulator string

Emulator is a terminal that shows labels, as its environment says.

const (
	EmulatorNone    Emulator = ""
	EmulatorITerm2  Emulator = "iterm2"
	EmulatorWezTerm Emulator = "wezterm"
)

func DetectEmulator

func DetectEmulator(getenv func(string) string) Emulator

DetectEmulator reads the environment: iTerm2 sets TERM_PROGRAM=iTerm.app (and LC_TERMINAL=iTerm2, which survives tmux and ssh); WezTerm sets TERM_PROGRAM=WezTerm.

type ExitSource

type ExitSource func(h Handle) (code int, ok bool)

ExitSource reads a launch's exit code from hopsesh's own records: the code its verb wrote when the agent or step ended (false: not ended, or not known). Terminals never report it (iTerm2's API says only that a tab closed, and with --hold the tab outlives the agent).

type Finder

type Finder interface {
	FindTTY(ctx context.Context, tty string) (Handle, bool, error)
}

Finder finds the tab whose terminal device is tty (false: none, or the app is not running; it is never started to look).

type Focuser

type Focuser interface {
	Focus(ctx context.Context, h Handle) error
}

Focuser brings a found tab forward.

type Found

type Found struct {
	Terminal Terminal
	Handle   Handle
	PID      int
}

Found is a session's tab: the terminal that has it, the tab, and the process on it.

func (Found) Name

func (f Found) Name() string

Name is the terminal's name, for people ("iTerm2").

type Handle

type Handle struct {
	Terminal string `json:"terminal"`
	Ref      string `json:"ref,omitempty"`
	TTY      string `json:"tty,omitempty"`
	// Verb and Ticket are the hopsesh verb and id the tab runs ("terminal-open" and a
	// ticket, or "terminal-step" and a step), for its exit code (ExitSource).
	Verb   string `json:"verb,omitempty"`
	Ticket string `json:"ticket,omitempty"`
}

Handle names a tab (or window) a terminal opened or found. Ref is the terminal's own id for it (iTerm2's session id); TTY its terminal device ("/dev/ttys003"), when known.

type Info

type Info struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Installed bool   `json:"installed"`
	Caps      Caps   `json:"caps"`
}

Info describes one terminal for a picker.

type Kind

type Kind string

Kind is what a launch runs; it decides the labels and the bookkeeping.

const (
	// KindSession resumes an agent's session: labelled with its title, and recorded so
	// "Show" can find its tab.
	KindSession Kind = "session"
	// KindStep is a step a driver runs (a hand-off, a teleport): labelled, not recorded.
	KindStep Kind = "step"
	// KindSignIn is a vendor's sign-in: a fixed label, nothing recorded or read back.
	KindSignIn Kind = "sign-in"
	// KindShell is a plain shell: a fixed label, nothing recorded or read back.
	KindShell Kind = "shell"
)

func (Kind) Valid

func (k Kind) Valid() bool

Valid reports whether k is a known kind.

type Labels

type Labels struct {
	Title   string `json:"title,omitempty"`
	Agent   string `json:"agent,omitempty"`   // "Claude Code"
	Machine string `json:"machine,omitempty"` // where it runs
}

Labels name a tab for people: iTerm2 shows them as a badge, and iTerm2 and WezTerm keep them as user variables (user.hopsesh_title, …) a title or status bar can show. hopsesh's own verb prints them in the tab before the agent starts; it never sets the tab's title, which the agent sets itself (Claude Code from --name and /rename).

Labels are for people only. Anything in a tab can print the same sequences, so hopsesh never reads them back to decide which session a tab holds (that comes from the agent's own files, the process table and hopsesh's launch records).

func (Labels) For

func (l Labels) For(k Kind) Labels

For is the labels a launch of kind k shows: the launch's own, sanitised, or for a sign-in or shell a fixed label whatever was asked.

type Launch

type Launch struct {
	// Program is hopsesh's absolute path; Args its verb and the ticket's id (each a
	// plain word: letters, digits and dashes).
	Program string
	Args    []string
	// Dir is where the tab starts (the verb changes to the ticket's folder itself).
	Dir   string
	Kind  Kind
	Where Placement
}

Launch is what a terminal opens: hopsesh's own program with a verb and a ticket.

type Opened

type Opened struct {
	Handle   Handle `json:"handle"`
	Terminal string `json:"terminal"` // the name of the one that opened it
	FellBack bool   `json:"fellBack,omitempty"`
	Reason   string `json:"reason,omitempty"`
}

Opened is how a launch was opened: in which terminal, and whether hopsesh fell back from the chosen one (Reason says why).

type Placement

type Placement string

Placement is where a launch opens; terminals that cannot do one open a new window.

const (
	// NewTab opens a tab in the terminal's front window (a new window when it has none).
	NewTab Placement = "tab"
	// NewWindow opens a new window.
	NewWindow Placement = "window"
	// Beside opens a split pane beside the session the user is in, where the terminal can
	// (iTerm2 with its Python API on); elsewhere it is NewTab.
	Beside Placement = "beside"
)

type Procs

type Procs interface {
	Alive(pid int) bool
	// TTY is the process's controlling terminal ("/dev/ttys003"; "" for none).
	TTY(ctx context.Context, pid int) string
}

Procs is what finding a session's tab needs to know about this machine's processes.

func SystemProcs

func SystemProcs() Procs

SystemProcs reads this machine's process table (ps for terminals; none on Windows).

type Record

type Record struct {
	Ticket  string    `json:"ticket"`
	Key     string    `json:"key"`
	TTY     string    `json:"tty,omitempty"`
	PID     int       `json:"pid"`
	Program string    `json:"program,omitempty"` // TERM_PROGRAM, for people
	Started time.Time `json:"started"`
}

Record is a running launch of a session: which tab (by terminal device) and which process.

type Script

type Script func(ctx context.Context, script string) (string, error)

Script runs an AppleScript and returns what it returned (osascript, or a test's fake).

type Set

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

Set is the terminals this system has adapters for, best first.

func NewSet

func NewSet(ts ...Terminal) Set

NewSet is a set of the given terminals, best first (tests).

func System

func System() Set

System is the set for this operating system.

func (Set) All

func (s Set) All() []Terminal

All lists the set's terminals.

func (Set) ByID

func (s Set) ByID(id string) (Terminal, bool)

ByID is the set's terminal with this id.

func (Set) Choose

func (s Set) Choose(ctx context.Context, id string) Terminal

Choose is the terminal for a configured id: that one when it is installed, else the best installed one ("" picks the best: iTerm2 before Terminal on macOS).

func (Set) Detect

func (s Set) Detect(ctx context.Context) []Info

Detect lists the set's terminals and whether each is installed.

func (Set) FindTab

func (s Set) FindTab(ctx context.Context, procs Procs, first Terminal, cands []Candidate) (Found, bool, error)

FindTab finds the tab of the first candidate that runs and is on a terminal, asking first (the user's terminal) and then the set's other terminals that can find tabs. False with a nil error: no tab hopsesh can show (the process is not in a terminal app hopsesh knows).

func (Set) Open

func (s Set) Open(ctx context.Context, t Terminal, l Launch) (Opened, error)

Open opens l in t, and when t is not installed or macOS denies hopsesh control of it, in the set's next installed terminal (Terminal, for iTerm2). When none opens it, the error wraps ErrNoTerminal: the person copies the command instead.

func (Set) WithExits

func (s Set) WithExits(src ExitSource) Set

WithExits is the set with its terminals that watch launches reading exit codes from src.

type Store

type Store struct{ Dir string }

Store keeps tickets and records under a folder (<state>/terminal).

func (Store) Drop

func (s Store) Drop(id string)

Drop removes a ticket that never ran (its terminal did not open).

func (Store) Exit

func (s Store) Exit(ticket string, code int) error

Exit writes the exit code of a ticket's launch (-1: stopped, or it never started), and removes codes older than a day.

func (Store) ExitOf

func (s Store) ExitOf(ticket string) (int, bool)

ExitOf is a ticket's launch's exit code, once its verb wrote one.

func (Store) Forget

func (s Store) Forget(ticket string)

Forget removes a launch's record (its agent ended).

func (Store) Record

func (s Store) Record(r Record) error

Record writes a running launch's record.

func (Store) Running

func (s Store) Running(key string, alive func(pid int) bool) []Record

Running lists the records of a session (key "": all) whose process alive says runs, removing the others.

func (Store) Save

func (s Store) Save(t Ticket) (string, error)

Save writes a ticket and returns its id.

func (Store) Take

func (s Store) Take(id string, maxAge time.Duration) (Ticket, error)

Take reads a ticket and removes it (a ticket runs once), refusing one older than maxAge.

type Terminal

type Terminal interface {
	ID() string
	Name() string // for people: "iTerm2"
	// Available is nil when the app is installed here (ErrNotInstalled otherwise).
	Available(ctx context.Context) error
	// Open opens the launch. ErrDenied: macOS refused hopsesh the Automation permission.
	Open(ctx context.Context, l Launch) (Handle, error)
}

Terminal is a terminal app hopsesh can open launches in.

func ITerm2

func ITerm2() Terminal

ITerm2 is iTerm2 on this Mac, with its Python API as the richer path when the user has turned it on.

func ITerm2Using

func ITerm2Using(run Script, installed func() bool) Terminal

ITerm2Using is iTerm2 driven by run, installed as installed says, AppleScript only (tests).

func LineTerminal

func LineTerminal(id, name string, open func(line string) error) Terminal

LineTerminal is a terminal that opens a launch by running Line(l) with open (tests, and the browser tests' stand-in that runs the line in the background).

func Linux

func Linux() Terminal

Linux is the first terminal emulator found on a Linux machine.

func TerminalApp

func TerminalApp() Terminal

TerminalApp is Terminal on this Mac.

func TerminalAppUsing

func TerminalAppUsing(run Script, installed func() bool) Terminal

TerminalAppUsing is Terminal driven by run, installed as installed says (tests).

func WindowsTerminal

func WindowsTerminal() Terminal

WindowsTerminal is Windows Terminal, or a PowerShell console when it is not installed.

type Ticket

type Ticket struct {
	Kind  Kind     `json:"kind"`
	Argv  []string `json:"argv"`
	Dir   string   `json:"dir"`
	Env   []string `json:"env,omitempty"`
	Unset []string `json:"unset,omitempty"`
	// LoginEnv are the agent's folder variables as the app saw them (CLAUDE_CONFIG_DIR, …),
	// set for the agent only where the terminal's environment lacks them.
	LoginEnv map[string]string `json:"loginEnv,omitempty"`
	// Key is the session (agent/session) a KindSession launch resumes.
	Key    string    `json:"key,omitempty"`
	Labels Labels    `json:"labels"`
	Made   time.Time `json:"made"`
}

Ticket is one launch's command, for hopsesh's own verb to run.

type Watcher

type Watcher interface {
	Exited(ctx context.Context, h Handle) (<-chan int, error)
}

Watcher reports a launch's exit code once it ends: the exit only, never output. The code comes from hopsesh's own records (ExitSource); the terminal adds that the tab was closed, which ends the launch with -1 when the agent left no code. Only iTerm2 with its Python API turned on by the user implements it; check CapsOf(t).Watch, which is false while the API is off.

Directories

Path Synopsis
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).
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).
fakeiterm2
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