ptyhost

package
v0.112.4 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 24 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 ptyhost keeps an owned session's terminal alive across daemon restarts (ADR-033).

A session Caprock starts used to live inside the daemon: the daemon held the PTY master, so stopping the daemon — an upgrade, `launchctl kickstart -k`, `caprock down` — closed the terminal and took the session with it. Here the PTY belongs to a small process of its own, `caprock pty-host`, one per session: it starts the agent, keeps the PTY master and a scrollback ring, and serves one daemon at a time over a token-guarded loopback socket. The daemon is a client. It can go away and a new one, even a newer binary, can connect to the same holder and carry on.

The holder never signals or types into anything but its own child (rule 7), exits when the child does, and removes its registry entry on the way out.

Wire protocol

Every message is a frame: one type byte, a 4-byte big-endian payload length, the payload. The first frame on a connection is the client's Hello; the holder answers Welcome and then a Snapshot of its ring, and from then on streams Output and, once, Exit.

The protocol is versioned by Proto, carried in Hello and Welcome. A holder started by one release must keep working with the daemon of the next, so the rule is additive: frame types are never renumbered or repurposed, and a side that receives a frame type it does not know ignores it. A change that cannot be made that way raises Proto, and a daemon keeps speaking every older version for as long as a holder of that version can still be running.

Index

Constants

View Source
const Arg = "pty-host"

Arg is the argument that makes a process a holder: `caprock pty-host`, or `caprock-pty-host pty-host` for the holder-only binary. The daemon's sweep for holders recognises one by it.

View Source
const OrphanAge = 2 * time.Minute

OrphanAge is how old a holder must be before it can be judged at all: a holder starting up has, for a moment, neither its child nor its registry entry.

View Source
const Proto = 1

Proto is the protocol version this binary speaks.

View Source
const ReadyTimeout = 15 * time.Second

ReadyTimeout is how long a new holder gets to start its child and report.

View Source
const RegistryEnv = "CAPROCK_PTYHOST_REGISTRY"

RegistryEnv is set in a holder's own environment (never its child's) to the registry directory it registered in. It is how a daemon tells a holder whose Caprock install was deleted from one that belongs to another daemon still running — both are absent from its own registry. Holders started before it existed are recognised by CAPROCK_DATA_DIR instead, when their daemon was started with it.

View Source
const SeqAckTimeout = 5 * time.Second

SeqAckTimeout is how long sequenced input waits for the holder's answer. Past it the input counts as not applied, and the browser resends it.

Variables

This section is empty.

Functions

func Binary added in v0.103.0

func Binary(self string) string

Binary returns the binary a daemon running from self starts holders from: the holder-only binary when one sits beside self, or beside the file self links to, and self otherwise.

Either one runs the same holder. The holder-only binary links nothing else, so a terminal costs less memory in it: the caprock binary pays for the whole daemon's package initialisation in every process it starts (ADR-033). Without it — `go build ./cmd/caprock`, `go install` — sessions run in `caprock pty-host` as they always have.

func BinaryName added in v0.103.0

func BinaryName() string

BinaryName is the file name of the holder-only binary (cmd/caprock-pty-host), which releases ship beside caprock.

func Dir

func Dir(dataDir string) string

Dir is where holders register, under the data directory.

func Main

func Main(stdin io.Reader, stdout io.WriteCloser) int

Main runs a holder: read the LaunchSpec from stdin, start the child, report on stdout, then serve until the child exits. Returns the process exit code.

After the ready line stdout is closed. The holder outlives the daemon that started it, and a write to a pipe whose reader has gone is a SIGPIPE.

Types

type Attached

type Attached struct {
	Record  Record
	Session ptyman.Session
}

Attached is a session a previous daemon left running, now connected.

type ChildProc added in v0.101.0

type ChildProc struct {
	PID  int32
	Name string
	// Busy is set when the child has children of its own: a shell running a
	// command, an agent running a tool.
	Busy bool
}

ChildProc is a holder's child.

type ExitError

type ExitError struct{ Code int }

ExitError is a non-zero exit reported by a holder.

func (ExitError) Error

func (e ExitError) Error() string

func (ExitError) ExitCode

func (e ExitError) ExitCode() int

ExitCode reports the code, for callers that read it through an interface.

type ExitRecord

type ExitRecord struct {
	SessionID string    `json:"session_id"`
	Code      int       `json:"code"`
	At        time.Time `json:"at"`
}

ExitRecord is left behind when a session ends while no daemon is connected, so the next one can record how it ended rather than only that it did.

type HostProc added in v0.101.0

type HostProc struct {
	PID     int32
	StartMs int64
	// Env is the holder's own environment, nil when it cannot be read.
	Env []string
	// Children are the holder's child processes: at most one, the session's
	// agent or shell.
	Children []ChildProc
}

HostProc is a running `caprock pty-host` process, as the process table shows it. The caller fills it; Classify only reads.

type LaunchSpec

type LaunchSpec struct {
	Proto     int         `json:"proto"`
	SessionID string      `json:"session_id"`
	Dir       string      `json:"dir"` // registry directory
	Token     string      `json:"token"`
	Version   string      `json:"version,omitempty"`
	Spec      ptyman.Spec `json:"spec"`
}

LaunchSpec is what the daemon hands a new holder on its stdin. Stdin rather than argv or a file: argv is readable by every process on the machine, and the spec carries the token and the child's environment (which can hold an API key), none of which should touch the disk.

type Manager

type Manager struct {
	// Exe is the binary to run as the holder; Args the arguments that select
	// the holder (default: Arg).
	Exe  string
	Args []string
	// Env is the holder process's own environment (nil: this process's).
	// The child's environment is the Spec's, as it always was.
	Env     []string
	DataDir string
	Version string
	Log     *slog.Logger
	// Fallback starts a session in-process when a holder cannot be started.
	// Such a session works as before and ends with the daemon, which beats
	// refusing to start it.
	Fallback ptyman.Manager
}

Manager starts sessions inside pty-host processes and reattaches to the ones a previous daemon left running. It is a ptyman.Manager, so the agents package spawns through it exactly as it spawns in-process.

func (*Manager) Reattach

func (m *Manager) Reattach() ([]Attached, []ExitRecord)

Reattach connects to every holder in the registry. It also returns the exit codes of sessions that ended while no daemon was connected, and removes the files it has read. A registry entry nothing answers for is a holder that died without cleaning up, and is removed; one that answers but refuses is left alone and logged.

func (*Manager) Spawn

func (m *Manager) Spawn(ctx context.Context, spec ptyman.Spec) (ptyman.Session, error)

Spawn starts spec in a new holder, or in-process via Fallback when that is not possible.

type Record

type Record struct {
	Proto     int       `json:"proto"`
	SessionID string    `json:"session_id"`
	HostPID   int       `json:"host_pid"`
	ChildPID  int       `json:"child_pid"`
	Addr      string    `json:"addr"`
	Token     string    `json:"token"`
	Cwd       string    `json:"cwd"`
	Command   string    `json:"command"`
	StartedAt time.Time `json:"started_at"`
	// Version is the Caprock release that started the holder, for the log
	// line a mismatch is diagnosed from. Compatibility is Proto's job.
	Version string `json:"version,omitempty"`
	// Meta is the spawn's ptyman.Spec.Meta, kept for the daemon that
	// reattaches: which agent it is, and anything the daemon needs to keep
	// watching it.
	Meta map[string]string `json:"meta,omitempty"`
}

Record is a running holder's registry entry, <data>/ptyhost/<session>.json. It is how a daemon that did not start the holder finds it: where it listens, the token it wants, and enough about the session to show it.

The file is the holder's to write and remove. The daemon only deletes one whose holder is gone (nothing listens at Addr any more).

type Verdict added in v0.101.0

type Verdict struct {
	PID int32 `json:"pid"`
	// State is one of:
	//   - "registered": in this daemon's registry — one of its sessions.
	//   - "foreign": registered with another Caprock (another data
	//     directory) that still lists it, or a holder whose registry
	//     cannot be told. Not this daemon's to judge.
	//   - "young": too new to judge (OrphanAge).
	//   - "dead": its child has exited and it has not. Nothing runs in it.
	//   - "unreachable-idle": its registry entry is gone (or the whole data
	//     directory), so no daemon can ever attach to it, and its child is a
	//     shell running nothing.
	//   - "unreachable-busy": unreachable, but its child is an agent or a
	//     shell running a command. Never stopped: something is still running.
	State string `json:"state"`
	// Reap is true for "dead" and "unreachable-idle": the two a reap stops.
	Reap bool `json:"reap"`
	// Ours is set when the holder registered in this daemon's own registry
	// directory (whether or not it is still listed there). The daemon's own
	// hourly sweep stops only these; holders of another install wait for
	// someone to press the button.
	Ours bool `json:"ours"`
	// Child names the child, when there is one.
	Child string `json:"child,omitempty"`
}

Verdict is what Classify decided about one holder.

func Classify added in v0.101.0

func Classify(hosts []HostProc, ownDir string, now time.Time) []Verdict

Classify judges each holder against ownDir, this daemon's registry directory. now is the clock; the registry directories it reads are the holders' own (from RegistryEnv, or CAPROCK_DATA_DIR), never guessed from HOME: a daemon started with --data-dir leaves no trace of it in the environment, and a guessed directory that exists without the holder in it would make a running session look unreachable.

func (Verdict) Orphan added in v0.101.0

func (v Verdict) Orphan() bool

Orphan reports whether a verdict counts as an orphan: a holder no daemon will ever attach to again.

Jump to

Keyboard shortcuts

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