terminput

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package terminput types text and keys into Claude Code sessions that are open in a terminal, after checking what the screen shows.

Index

Constants

View Source
const (
	KeyEscape    = harness.KeyEscape
	KeyEnter     = harness.KeyEnter
	KeySpace     = harness.KeySpace
	KeyBackspace = harness.KeyBackspace
	KeyClear     = harness.KeyClear
)

Keys other than digits that a driver can press.

Variables

View Source
var (
	ErrDisabled         = newErr("disabled", "terminal input is off")
	ErrNotInTerminal    = newErr("not_in_terminal", "session is not open in a terminal")
	ErrNotClaude        = newErr("not_claude", "the terminal is not running this session's claude")
	ErrMacInUse         = newErr("mac_in_use", "the owner is using this session on the Mac")
	ErrNoDriver         = newErr("no_terminal_driver", "no driver reaches this terminal")
	ErrAutomationDenied = newErr("automation_denied", "macOS denied automation access")
	ErrNotAtInput       = newErr("not_at_input", "the session is not waiting at its input box")
	ErrNoPrompt         = newErr("no_prompt", "no permission prompt is showing")
	ErrPromptChanged    = newErr("prompt_changed", "a different prompt is showing")
	ErrBadText          = newErr("bad_text", "the text holds control characters or starts with ! or /")
	ErrNotSubmitted     = newErr("not_submitted", "the text is in the input box but was not submitted")
	ErrNotCleared       = newErr("box_not_cleared", "the text in the input box could not be cleared; nothing was sent")
	ErrDraftInBox       = newErr("draft_in_box", "a draft left in the input box is kept (keep_drafts); nothing was sent")
	ErrBoxHasUnsent     = newErr("box_has_unsent", "Your earlier message is still in the box on your Mac; Retry it, or clear the box")
	// ErrUnsentUnconfirmed: the box shows a paste marker for the same text,
	// but it may be the owner's paste; a retry would only be refused again.
	ErrUnsentUnconfirmed = newErr("unsent_unconfirmed", "Your message may still be in the box on your Mac, but aimux can't confirm it's yours. Send or clear it at the Mac.")
	ErrBusy              = newErr("busy", "Claude is working on a turn in this session")
	// Submit's answers when the input box does not hold the message.
	ErrBoxEmpty = newErr("box_empty", "the input box is empty")
	ErrNotInBox = newErr("not_in_box", "the input box holds other text")
)

Errors with stable codes.

Functions

func CheckMessage

func CheckMessage(text string, allowSlash bool) error

CheckMessage applies every text rule a message for Claude Code must pass before it is typed: CheckText, and no leading "/" unless allowSlash. It answers ErrBadText or nil.

func CheckText

func CheckText(text string) error

CheckText returns ErrBadText when text holds a C0 control other than newline and tab, DEL or a C1 control, or when Claude Code would not take it as a message even with slash commands allowed (a leading "!", see claude.Composer.RefuseText). Control bytes would reach the pty as keys: CR submits, ESC[201~ ends a paste, Ctrl-Z suspends the harness.

func Code

func Code(err error) string

Code returns the stable code for err: "ok" for nil, the sentinel's code, or "error" for anything else.

func OpenLog

func OpenLog(path string) (io.WriteCloser, error)

OpenLog opens (creating it and its directory) the append-only attempt log with mode 0600.

func ParseTTY

func ParseTTY(out string) (string, error)

ParseTTY maps `ps -o tty=` output to /dev/<tty>, or "" when the process has none.

func PasteText

func PasteText(text string) bool

PasteText reports whether text goes in as a bracketed paste (harness.PasteText); drivers paste such text.

Types

type Composer

type Composer = harness.Composer

Composer is the harness knowledge the Service relies on: what its screen shows, which foreground process is the harness, which texts it refuses and which keys make room in its input box.

type Driver

type Driver interface {
	Name() string
	// Locate reports false when the pane is not this driver's.
	Locate(ctx context.Context, t Target) (Pane, bool, error)
	// Type types text without Enter; text for which PasteText is true goes
	// in as a bracketed paste. The service presses Enter itself, after
	// reading the screen again.
	Type(ctx context.Context, p Pane, text string) error
	Key(ctx context.Context, p Pane, k Key) error
	Screen(ctx context.Context, p Pane) (string, error)
}

Driver moves bytes for one terminal. Every safety check lives in Service.

type FocusReporter

type FocusReporter interface {
	Focused(ctx context.Context) (frontmost bool, tty string, err error)
}

FocusReporter is a driver that can say whether its terminal is the frontmost app and which session has keyboard focus, by tty. Keystrokes reach only that session, so only it can mix with the owner's typing. It must never activate or focus anything.

type FocusSystem

type FocusSystem interface {
	IdleSeconds() (float64, error)
	TTYs(pids []int) (map[int]string, error)
}

FocusSystem is what LastFocus asks the machine: how long it has been idle and the ttys of some processes (SystemProbe: one ps for all).

type Key

type Key = harness.Key

Key is a single key sent to a terminal, such as "1" for a prompt option.

type LastFocus

type LastFocus struct {
	Enabled bool // remote_access.terminal_input.enabled; off, Probe asks nothing
	Sys     FocusSystem
	Focus   FocusReporter
	// Sessions maps each session open in a terminal to the pid holding it,
	// by the registry rule the terminal routes use.
	Sessions func() map[string]int
	Now      func() time.Time
	// contains filtered or unexported fields
}

LastFocus remembers the session last in front on the Mac: the terminal session with keyboard focus while the Mac was in use (idle under 2 minutes). It only reads: it never types, focuses or starts anything. Nothing is stored on disk.

func (*LastFocus) Last

func (f *LastFocus) Last() (id string, at time.Time, ok bool)

Last is the session last in front and when it was seen; ok is false until one was seen.

func (*LastFocus) Probe

func (f *LastFocus) Probe(ctx context.Context)

Probe looks once. Anything unknown (the Mac idle, a probe error, the terminal not in front, a pane holding no session) keeps the last value.

func (*LastFocus) Run

func (f *LastFocus) Run(ctx context.Context, every time.Duration)

Run probes every interval until ctx ends.

type LayoutReader

type LayoutReader struct {
	Source LayoutSource
	Sys    LayoutSystem
	// Sessions maps each open session to the pid holding it.
	Sessions  func() map[string]int
	LastOnMac func() (string, time.Time, bool) // may be nil
	Now       func() time.Time                 // nil means time.Now
	Log       io.Writer                        // may be nil

	// FirstWait bounds how long a call with no usable layout (none yet, or
	// one older than 30 s) waits for the refresh (0 means 1.5 s).
	FirstWait time.Duration
	// contains filtered or unexported fields
}

LayoutReader joins the terminal layout to open sessions by tty. It only reads. A read is reused for 3 s, and a failed read falls back to the last good one for 30 s.

func (*LayoutReader) Places

func (r *LayoutReader) Places(ctx context.Context) map[string]MacPlace

Places returns each placed session's place; nil when unknown. A session whose pid has no tty, whose tty is in no pane, or which is not its tty's foreground is absent.

While the cached layout is at most 30 s old, Places never waits: it returns it and, when it is older than 3 s, starts one background refresh. A failed read backs off for 3 s. With no layout yet, or one older than 30 s, it waits for the running refresh (one for all callers), for the request ctx and at most FirstWait.

type LayoutSource

type LayoutSource interface {
	Layout(ctx context.Context) ([]PaneRef, error)
}

LayoutSource reads the terminal's windows, tabs and panes.

type LayoutSystem

type LayoutSystem interface {
	TTYs(pids []int) (map[int]string, error)
	Foreground(pids []int) (map[int]bool, error)
}

LayoutSystem is what the join asks the machine, each in one call for all pids (SystemProbe: one ps each).

type MacPlace

type MacPlace struct {
	Window      MacWindow `json:"window"`
	Tab         MacTab    `json:"tab"`
	Pane        int       `json:"pane"`
	Panes       int       `json:"panes"`
	LastInFront bool      `json:"lastInFront"`
}

MacPlace is where a session sits in the terminal on the Mac.

type MacTab

type MacTab struct {
	Index int    `json:"index"`
	Name  string `json:"name"`
}

type MacWindow

type MacWindow struct {
	ID    string `json:"id"`
	Index int    `json:"index"`
	Name  string `json:"name"`
}

type Option

type Option = harness.Option

Option is one numbered choice in a permission prompt.

type Pane

type Pane struct{ Driver, ID string }

Pane is a driver's own handle, opaque to callers.

type PaneRef

type PaneRef struct {
	WindowID   int    // terminal's window id
	WindowName string // as the terminal shows it
	ActiveName string // name of the window's current session
	Tab        int    // 1-based position in the window
	TabName    string // name of the tab's current session
	Pane       int    // 1-based position in the tab
	Panes      int    // panes in the tab
	TTY        string
}

PaneRef is where a terminal shows one pane: its window, tab and position, as the terminal orders them.

type Prompt

type Prompt = harness.Prompt

Prompt is a permission prompt read from the screen.

type RegistryStatuses

type RegistryStatuses interface {
	RegistryStatus(sessionID string) string
}

RegistryStatuses is Sessions that also reports a session's status in Claude's registry ("busy", "idle" or ""). Send then refuses a session the registry calls busy, as the chat queue's dispatcher does.

type Service

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

Service applies the safety checks and delegates byte-moving to drivers.

func NewService

func NewService(cfg config.TerminalInputConfig, sessions Sessions, sys System, log io.Writer, drivers ...Driver) *Service

NewService builds a Service for Claude Code sessions. log may be nil.

func NewServiceFor

func NewServiceFor(cfg config.TerminalInputConfig, sessions Sessions, sys System, composer Composer, log io.Writer, drivers ...Driver) *Service

NewServiceFor is NewService for the harness that composer describes. A nil composer is a programming error and panics.

func (*Service) LeftInBox

func (s *Service) LeftInBox(sessionID string) bool

LeftInBox reports whether the input box holds a message a send typed but did not submit, as of the latest screen read: it answers from the record without reading the screen again. Any read (Status, Send) that shows the box without the message drops the record; within leftSettle of typing a read never does.

func (*Service) Press

func (s *Service) Press(ctx context.Context, sessionID, promptID string, option Key, idemKey string) error

Press presses option on the prompt identified by promptID, if that prompt is still the one showing.

func (*Service) Send

func (s *Service) Send(ctx context.Context, sessionID, text, idemKey string) error

Send types text into the session's pane when its input box is empty.

func (*Service) SendNow

func (s *Service) SendNow(ctx context.Context, sessionID, text, idemKey string) error

SendNow is Send that is allowed while Claude works on a turn: the harness takes the message during the turn. Every other check is Send's, and the box is never touched mid-turn: a permission prompt is ErrNotAtInput, text in the box other than aimux's own unsent message is ErrDraftInBox (or ErrBoxHasUnsent, ErrUnsentUnconfirmed by Send's rules), nothing pressed. While Claude is not working it is Send.

func (*Service) SendReplacing

func (s *Service) SendReplacing(ctx context.Context, sessionID, text, idemKey string) error

SendReplacing is Send that replaces a draft left in the input box even with keep_drafts. Every other check is Send's: the box is never touched while the owner uses this session at the Mac, Claude works, or a prompt shows. ErrNotCleared: the box did not read empty after clearRounds; nothing was typed.

func (*Service) Status

func (s *Service) Status(ctx context.Context, sessionID, registryStatus string) Status

Status reports state and whether Send would be accepted, without typing.

func (*Service) Submit

func (s *Service) Submit(ctx context.Context, sessionID, text string) error

Submit presses Enter for text a Send left in the input box (ErrNotSubmitted), only if the box visibly holds exactly that text (TextShownInBox), or, for pasted text a send left (leftText), exactly the paste marker that send saw in the box right after pasting, while the same claude runs and the Mac has had no input since (markerOK). Any other marker, or that one after Mac input, could stand for the owner's own paste and is ErrNotInBox. It types nothing. ErrBoxEmpty: the box is empty; ErrNotInBox: it holds something else; ErrNotAtInput: a prompt shows; ErrBusy: Claude is working. The other checks are Send's; the in-use guard runs again right before Enter.

type Sessions

type Sessions interface {
	TerminalPID(sessionID string) (int, bool)
}

Sessions maps a session id to the pid of the terminal process holding it, excluding sessions aimux itself owns.

type Status

type Status struct {
	State   string // busy, idle or unknown
	CanType bool
	Reason  string // why CanType is false
	Prompt  *Prompt
	// Working is true while the screen shows Claude Code working on a turn;
	// Send then answers ErrBusy. CanType does not include it, so clients
	// without a queue keep their composer and get a fixed busy message.
	Working bool
	// BoxHasText: the input box holds text (a draft, or Claude Code's grey
	// suggestion; the screen does not say which). SendReplacing may clear it.
	BoxHasText bool
	// WorkingSeconds: how long the working line says the turn has run; 0
	// when it shows no time.
	WorkingSeconds int
}

Status is what a client needs to decide whether to offer a composer.

type System

type System interface {
	TTY(pid int) (string, error)
	ForegroundIsPID(tty string, pid int) (bool, error)
	// ForegroundCommand is the command name of the tty's foreground process
	// group leader, such as "claude" or "/usr/local/bin/node".
	ForegroundCommand(tty string) (string, error)
	IdleSeconds() (float64, error)
}

System answers questions about the machine.

type SystemProbe

type SystemProbe struct{}

SystemProbe is the real System, backed by ps and ioreg.

func (SystemProbe) Foreground

func (SystemProbe) Foreground(pids []int) (map[int]bool, error)

Foreground reports, for each pid, whether its process group is the foreground group of its tty, from one ps.

func (SystemProbe) ForegroundCommand

func (SystemProbe) ForegroundCommand(tty string) (string, error)

ForegroundCommand is the command of the tty's foreground process group leader, as ps reports it (a name or a path).

func (SystemProbe) ForegroundIsPID

func (SystemProbe) ForegroundIsPID(tty string, pid int) (bool, error)

ForegroundIsPID reports whether the tty's foreground process group is pid's.

func (SystemProbe) IdleSeconds

func (SystemProbe) IdleSeconds() (float64, error)

IdleSeconds is the time since the last keyboard or mouse input.

func (SystemProbe) TTY

func (SystemProbe) TTY(pid int) (string, error)

TTY returns the pid's controlling tty such as "/dev/ttys001", or "" if none.

func (SystemProbe) TTYs

func (SystemProbe) TTYs(pids []int) (map[int]string, error)

TTYs returns the controlling ttys of pids that have one, from one ps.

type Target

type Target struct {
	PID int
	TTY string
}

Target is the session's claude process and its tty, e.g. "/dev/ttys001".

Directories

Path Synopsis
Package iterm2 is the terminput driver for iTerm2.
Package iterm2 is the terminput driver for iTerm2.

Jump to

Keyboard shortcuts

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