Documentation
¶
Overview ¶
Package shell is the RemoHop remote shell service: interactive persistent terminal sessions (`remohop <ID> shell`), non-interactive commands (`remohop <ID> shell -c`) and detached background jobs (`remohop <ID> spawn`, `jobs`, `logs`, `kill`). It owns the host handlers, the Go client API used by the CLI and the MCP server, and the CLI commands.
Wire protocol ¶
Four host services, each request carried in the stream header:
- "exec": one command. Client sends input frames ('i'), one input-EOF frame ('e') and resize frames ('r', rows/cols as two big-endian uint16); host sends stdout ('o') and stderr ('E') frames, then one exit frame ('x', JSON). The client keeps its direction open until the exit frame: the host treats its end, or a stream reset, as the client going away and kills the process group.
- "shell": interactive sessions, op "attach" | "list" | "kill". An attach answers with an attached frame ('a', JSON), then output frames (replay of recent output first), and finally an exit frame (the shell ended) or a detached frame ('d': another client took over). The client sends input and resize frames, and detaches by closing the stream. "list" and "kill" answer with one JSON message.
- "spawn": start a background job; one JSON reply.
- "jobs": op "list" | "kill" | "wait" | "remove" answer with one JSON message; "logs" streams output frames and ends with a log-end frame ('z', JSON with the job's state).
Frames use the internal/wire binary framing; this package refuses frames above 256 KiB from either side.
Sessions ¶
Sessions belong to the host process, not to a connection, and survive their client for KeepAlive. One client is attached at a time; a second attach takes the session over and the previous client is detached.
Jobs ¶
Jobs run in their own session with stdin from /dev/null and stdout and stderr appended to <config dir>/jobs/<id>.log, with metadata in <id>.json, so they outlive both the client and the host daemon. Logs are not rotated; finished jobs are deleted with RemoveJobs (`jobs rm`).
Platforms ¶
Linux and macOS share the unix code path (creack/pty, process groups, waitid/kqueue to observe exits without reaping). Windows hosts create processes directly with CreateProcess: each one suspended, put in its own kill-on-close job object, then resumed, so a kill or timeout ends the whole tree. Terminals are ConPTY pseudo consoles; commands and jobs run through PowerShell (-EncodedCommand, UTF-8 output) or, without it, cmd.exe. Background jobs are killed with taskkill /T, the only way to reach a tree after the host restarted. Windows clients put the console in raw mode with virtual terminal input and output.
Index ¶
- Constants
- Variables
- func KillSession(ctx context.Context, conn *peer.Conn, name string) error
- func RemoveJobs(ctx context.Context, conn *peer.Conn, req RemoveRequest) ([]string, error)
- type AttachIO
- type AttachRequest
- type AttachResult
- type CaptureResult
- type DetachReason
- type ExecRequest
- type ExecResult
- type Job
- type LogReader
- type LogsRequest
- type RemoveRequest
- type SessionInfo
- type SpawnRequest
- type StartError
- type WinSize
Constants ¶
const ( JobRunning = "running" JobExited = "exited" // JobUnknown is a job that is no longer running but whose exit status // was never recorded, because the host process that spawned it was not // around to reap it (remohop host restarted while it ran). JobUnknown = "unknown" )
Job states.
const DefaultCaptureLimit = 1 << 20
DefaultCaptureLimit is the per-stream cap Capture uses when given 0.
Variables ¶
var KeepAlive = 30 * time.Minute
KeepAlive is how long a detached interactive session keeps running on the host before it is killed. 0 kills a session as soon as its client goes away. The REMOHOP_SHELL_KEEPALIVE environment variable (a Go duration such as "45m", or "0") overrides the default when the package initialises; hosts may also set it directly before serving. It applies when a session detaches.
Functions ¶
func KillSession ¶
KillSession ends an interactive session (its shell is hung up).
func RemoveJobs ¶
RemoveJobs deletes finished jobs and returns the removed IDs.
Types ¶
type AttachIO ¶
type AttachIO struct {
// Stdin carries keystrokes. Its EOF detaches (the session keeps
// running). Attach does not wait for a Read still blocked when it
// returns; whatever that Read yields afterwards is discarded.
Stdin io.Reader
// Stdout receives the terminal output, starting with the replay of
// recent output when re-attaching.
Stdout io.Writer
// Resize delivers local window size changes.
Resize <-chan WinSize
// Escape is the escape character, recognised only at the start of a
// line as in ssh: Escape followed by '.' detaches, by '?' prints help,
// and doubled sends one literal Escape. 0 disables escapes.
Escape byte
// OnAttach, if set, runs once the host has attached the session,
// before any output is written.
OnAttach func(*AttachResult)
}
AttachIO is the local side of an attached terminal.
type AttachRequest ¶
type AttachRequest struct {
// Name is the session; "" means "main". It is created if missing.
Name string
// New always starts a fresh session, called Name or, if that is taken,
// Name-2, Name-3, ...
New bool
// Term is the client's TERM; Rows and Cols its window size.
Term string
Rows, Cols int
}
AttachRequest selects the interactive session to attach to.
type AttachResult ¶
type AttachResult struct {
Session string `json:"session"`
PID int `json:"pid"`
Created bool `json:"created"`
// KeepAlive is how long the host keeps the session once detached.
KeepAlive time.Duration `json:"keepalive_ns"`
// Exited is set when the shell ended; the session is gone.
Exited bool `json:"exited,omitempty"`
ExitCode int `json:"exit_code,omitempty"`
Signal int `json:"signal,omitempty"`
SignalName string `json:"signal_name,omitempty"`
// Detached is set when the client left and the session keeps running.
Detached DetachReason `json:"detached,omitempty"`
}
AttachResult describes the attached session and how the attach ended.
func Attach ¶
func Attach(ctx context.Context, conn *peer.Conn, req AttachRequest, aio AttachIO) (*AttachResult, error)
Attach connects to an interactive session on the host and relays the terminal until the shell exits, the user detaches, Stdin ends, another client takes over or ctx is cancelled. Except when the shell exited, the session keeps running on the host for the keep-alive period.
If the connection fails after the session was attached, Attach returns the partial result (so callers can say how to resume) with the error.
type CaptureResult ¶
type CaptureResult struct {
ExecResult
Stdout []byte `json:"stdout"`
Stderr []byte `json:"stderr"`
StdoutTruncated bool `json:"stdout_truncated,omitempty"`
StderrTruncated bool `json:"stderr_truncated,omitempty"`
// StdoutBytes and StderrBytes count everything the command wrote,
// including what was dropped.
StdoutBytes int64 `json:"stdout_bytes"`
StderrBytes int64 `json:"stderr_bytes"`
}
CaptureResult is an ExecResult plus the captured output.
func Capture ¶
func Capture(ctx context.Context, conn *peer.Conn, req ExecRequest, limit int) (*CaptureResult, error)
Capture runs a command and collects its output, keeping at most limit bytes of each stream (the beginning; the rest is counted and dropped). limit <= 0 means DefaultCaptureLimit. req.Stdout and req.Stderr are ignored. This is the "run it and tell me what happened" call AI agents use.
type DetachReason ¶
type DetachReason string
DetachReason says why an attach ended with the session still running.
const ( DetachEscape DetachReason = "escape" // the user typed the escape sequence DetachTakeover DetachReason = "takeover" // another client attached DetachInputClosed DetachReason = "input-closed" // Stdin reached EOF DetachCanceled DetachReason = "canceled" // ctx was cancelled )
type ExecRequest ¶
type ExecRequest struct {
Command string
// Cwd is the working directory on the host; empty, "~" and relative
// paths are relative to the host user's home.
Cwd string
// Env holds KEY=VALUE overrides on top of the host's environment.
Env []string
// Stdin is streamed to the command; its EOF closes the command's
// stdin. nil gives the command an empty stdin. Exec does not wait for a
// Read that is still blocked when the command exits.
Stdin io.Reader
// Stdout and Stderr receive the command's output; nil discards it.
// With TTY both streams arrive merged on Stdout. Writes are synchronous,
// so a slow writer slows the remote command down instead of buffering.
Stdout io.Writer
Stderr io.Writer
// Timeout, if positive, kills the remote process group after that long
// and reports ExecResult.TimedOut.
Timeout time.Duration
// TTY runs the command on a pseudo-terminal of Rows x Cols with TERM
// set to Term. Resize, if set, delivers window size changes.
TTY bool
Term string
Rows, Cols int
Resize <-chan WinSize
}
ExecRequest describes one non-interactive command run on the host through the user's shell (`$SHELL -c`, cmd.exe /C on Windows).
type ExecResult ¶
type ExecResult struct {
// ExitCode is the command's exit status, or 128+n if it died from
// signal n (including the kill on timeout).
ExitCode int `json:"exit_code"`
Signal int `json:"signal,omitempty"`
SignalName string `json:"signal_name,omitempty"`
TimedOut bool `json:"timed_out,omitempty"`
Duration time.Duration `json:"duration_ns"`
}
ExecResult is how a command ended.
func Exec ¶
func Exec(ctx context.Context, conn *peer.Conn, req ExecRequest) (*ExecResult, error)
Exec runs req.Command on the host and streams its I/O. It returns when the command has exited and all its output has been written. Cancelling ctx (or losing the session) kills the remote process group; Exec then returns ctx.Err() or the transport error.
type Job ¶
type Job struct {
ID string `json:"id"`
Name string `json:"name,omitempty"`
Command string `json:"command"`
Cwd string `json:"cwd"`
PID int `json:"pid"`
State string `json:"state"`
// ExitCode is meaningful in state "exited": the exit status, or 128+n
// for death by signal n. Windows has no signals: a job killed there
// reports exit code 1, with Signal and SignalName naming what Kill sent.
ExitCode int `json:"exit_code"`
Signal int `json:"signal,omitempty"`
SignalName string `json:"signal_name,omitempty"`
Started time.Time `json:"started"`
Ended *time.Time `json:"ended,omitempty"`
// Log is the log file's path on the host, LogSize its current size.
Log string `json:"log"`
LogSize int64 `json:"log_size"`
// Grant is the grant the job was spawned under, empty for full
// access. Owner is who spawned it: the grant and the client's
// identity (grant.OwnerOf). A session under a grant sees and handles
// only the jobs of its own owner, so two identities on one grant an
// authorizer gives do not share them.
Grant string `json:"grant,omitempty"`
Owner string `json:"owner,omitempty"`
}
Job is a background job on the host. Jobs run in their own session with stdin from /dev/null and stdout+stderr appended to Log; they outlive the client session that spawned them and the host process itself. Logs are not rotated: they grow until the job is removed.
func Kill ¶
Kill sends signal (a name such as "TERM" or "KILL", or a number; "" means TERM) to a running job's whole process group. job is an ID or a unique name.
type LogReader ¶
type LogReader struct {
// contains filtered or unexported fields
}
LogReader streams a job's log. Read returns io.EOF at the end of the log (with Follow: once the job has ended and all its output was read); Job then reports the job's state.
type LogsRequest ¶
type LogsRequest struct {
Job string
// Follow keeps streaming new output until the job ends.
Follow bool
// Tail starts at the last Tail lines (0 = from the beginning).
Tail int
}
LogsRequest selects a job's log.
type RemoveRequest ¶
type RemoveRequest struct {
Jobs []string // IDs or unique names; running jobs are refused
// Exited also selects every job that is not running.
Exited bool
}
RemoveRequest selects finished jobs to delete along with their logs.
type SessionInfo ¶
type SessionInfo struct {
Name string `json:"name"`
PID int `json:"pid"`
Created time.Time `json:"created"`
AgeSeconds float64 `json:"age_seconds"`
Attached bool `json:"attached"`
IdleSeconds float64 `json:"idle_seconds"`
Rows int `json:"rows"`
Cols int `json:"cols"`
// ExpiresInSeconds is set for a detached session: the time left before
// the keep-alive reaps it.
ExpiresInSeconds float64 `json:"expires_in_seconds,omitempty"`
}
SessionInfo describes one interactive session on the host. Durations are computed on the host so clock skew does not distort them.
type SpawnRequest ¶
type SpawnRequest struct {
// Command runs through the host user's shell.
Command string
// Name is an optional label; jobs can be referred to by unique name.
Name string
// Cwd and Env work as in ExecRequest.
Cwd string
Env []string
}
SpawnRequest starts a background job.
type StartError ¶
type StartError struct{ Msg string }
StartError reports that the host could not start the command at all (missing working directory, bad request, ...).
func (*StartError) Error ¶
func (e *StartError) Error() string