Documentation
¶
Overview ¶
Package executor abstracts "run a command / move a file on a machine". Everything above this layer is target-kind agnostic.
Index ¶
- Constants
- Variables
- func BridgeCommand(ctx context.Context, addr string, wrap func(relay string) string) (net.Conn, error)
- func ConfigFileArgs() []string
- func Probe(ctx context.Context, ex Executor) (map[string]any, error)
- func SetTargetEnv(ex Executor, env TargetEnv)
- func ShellQuote(s string) string
- func Wrap(vmid, cmd, cwd string) string
- func WriteFileChunks(ctx context.Context, ...) error
- type ConnStatus
- type Dialer
- type Error
- type Executor
- type Local
- func (l *Local) Close() error
- func (l *Local) DialTarget(ctx context.Context, addr string) (net.Conn, error)
- func (l *Local) ReadFile(_ context.Context, path string, offset int64) ([]byte, error)
- func (l *Local) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)
- func (l *Local) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)
- func (l *Local) WriteFile(_ context.Context, path string, data []byte) error
- type Mock
- func (m *Mock) Close() error
- func (m *Mock) CmdLog() []string
- func (m *Mock) ExitPaneAgent(sess string)
- func (m *Mock) Files() map[string][]byte
- func (m *Mock) PaneText(sess string) string
- func (m *Mock) Probe() map[string]any
- func (m *Mock) ReadFile(_ context.Context, path string, offset int64) ([]byte, error)
- func (m *Mock) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)
- func (m *Mock) SetPaneLimit(sess, message string) bool
- func (m *Mock) WriteFile(_ context.Context, path string, data []byte) error
- type OpenSSH
- func (o *OpenSSH) Args() []string
- func (o *OpenSSH) Close() error
- func (o *OpenSSH) ConnStatus() ConnStatus
- func (o *OpenSSH) Destination() string
- func (o *OpenSSH) DialTarget(ctx context.Context, addr string) (net.Conn, error)
- func (o *OpenSSH) ReadFile(ctx context.Context, path string, offset int64) ([]byte, error)
- func (o *OpenSSH) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)
- func (o *OpenSSH) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)
- func (o *OpenSSH) WriteFile(ctx context.Context, path string, data []byte) error
- type Pct
- func (p *Pct) Close() error
- func (p *Pct) DialTarget(ctx context.Context, addr string) (net.Conn, error)
- func (p *Pct) ReadFile(ctx context.Context, filePath string, offset int64) ([]byte, error)
- func (p *Pct) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)
- func (p *Pct) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)
- func (p *Pct) WriteFile(ctx context.Context, filePath string, data []byte) error
- type Registry
- type Result
- type RunOpts
- type SSH
- func (s *SSH) Close() error
- func (s *SSH) ConnStatus() ConnStatus
- func (s *SSH) DialTarget(ctx context.Context, addr string) (net.Conn, error)
- func (s *SSH) ReadFile(ctx context.Context, path string, offset int64) ([]byte, error)
- func (s *SSH) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)
- func (s *SSH) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)
- func (s *SSH) WithOptions(o SSHOptions) *SSH
- func (s *SSH) WriteFile(ctx context.Context, path string, data []byte) error
- type SSHOptions
- type StatusReporter
- type Streamer
- type TargetEnv
Constants ¶
const ( MockPollEnd = "ADK-POLL-END-v2" MockPaneDelimiter = "\x1e---LECTERN-PANE---\x1e" MockDiscoverDelimiter = "\x1e---LECTERN-PS---\x1e" // MockAgentProbeMarker must match sessions.AgentProbeMarker. MockAgentProbeMarker = ": LECTERN-AGENT-PROBE;" )
The mock's half of the interactive-session protocol.
These two literals must match `sessions.PollDelimiter` and `sessions.DiscoverDelimiter`. They are duplicated rather than imported because the sessions package depends on this one; TestMockDelimitersMatchSessions asserts they have not drifted.
const MockDiff = `` /* 205-byte string literal not displayed */
MockDiff is the patch every mock attempt "produces".
const MockNumstat = "4\t1\tapp.py\n"
MockNumstat is the matching --numstat output.
Variables ¶
var ErrNoDial = errors.New("this kind of target cannot forward ports")
ErrNoDial is returned by targets whose loopback cannot be reached this way.
var ErrNoStdin = errors.New("this target's command wrapper does not pass input through, so its " +
"loopback cannot be reached (for docker exec, add -i)")
ErrNoStdin means the target's command path does not pass input through, so nothing can be bridged over it.
Functions ¶
func BridgeCommand ¶ added in v2.6.0
func BridgeCommand(ctx context.Context, addr string, wrap func(relay string) string) (net.Conn, error)
BridgeCommand dials addr on a machine reached through a local command: wrap turns the relay's command line into the full local invocation (a `docker exec -i`, say), which must pass stdin through.
func ConfigFileArgs ¶ added in v2.6.0
func ConfigFileArgs() []string
ConfigFileArgs points ssh(1) at LECTERN_SSH_CONFIG when set, the same file hosts are imported from, so an imported alias resolves the same way.
func SetTargetEnv ¶ added in v2.7.0
SetTargetEnv records what is known about the target ex drives.
func Wrap ¶
Wrap renders the `sudo pct exec` invocation for a command. Exported because the quoting round-trip is worth testing directly.
func WriteFileChunks ¶ added in v2.6.0
func WriteFileChunks(ctx context.Context, run func(context.Context, string, RunOpts) (Result, error), file string, data []byte, size int) error
WriteFileChunks is writeFileChunks for executors outside this package (a sandbox provider's), whose command path may not pass stdin through.
Types ¶
type ConnStatus ¶ added in v2.6.0
type ConnStatus struct {
// State is "idle" (never used), "connected", "reconnecting" (dropped;
// the next command dials again) or "down" (the last dial failed).
State string `json:"state"`
Since float64 `json:"since,omitempty"`
LastOK float64 `json:"last_ok,omitempty"`
LastError string `json:"last_error,omitempty"`
Reconnects int `json:"reconnects"`
Transport string `json:"transport"`
Via string `json:"via,omitempty"`
}
ConnStatus is what the UI shows about a remote connection: whether it is up, whether Lectern is reconnecting after a drop, and how often that happened. Every command re-dials a dropped connection on its own; this only makes that visible.
type Dialer ¶
Dialer is an executor that can open a TCP connection as the target sees it, so "127.0.0.1" means the target's loopback and not the control plane's. It is what lets the control plane carry a connection to a service that only listens on the target's own localhost.
type Error ¶
type Error struct{ Msg string }
Error marks a target that could not be reached at all, as opposed to a command that ran and failed.
type Executor ¶
type Executor interface {
// Run executes a shell command, optionally in cwd, bounded by timeout.
Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)
// ReadFile returns bytes from offset to EOF; empty (not an error) if missing.
ReadFile(ctx context.Context, path string, offset int64) ([]byte, error)
// WriteFile writes data, creating parent directories.
WriteFile(ctx context.Context, path string, data []byte) error
// Close releases any pooled connection.
Close() error
}
Executor is one machine lectern can drive. One instance per target.
type Local ¶
type Local struct {
// contains filtered or unexported fields
}
Local runs commands on the control-plane host itself.
It is not zero-sized: Go may give every zero-sized allocation the same address, and each executor is a key of its own TargetEnv (SetTargetEnv), so one local target's backend would otherwise become every Local's.
func (*Local) DialTarget ¶
DialTarget on the control-plane host is an ordinary dial.
func (*Local) ReadFile ¶
ReadFile reads from offset to EOF, treating a missing file as empty — the scheduler polls for an agent log that does not exist yet on every tick.
type Mock ¶
type Mock struct {
// Delay paces the fake agent between events.
Delay time.Duration
// HTTP is the client the fake agent uses for hook callbacks. Tests point it
// at their httptest server's transport; production demo mode uses the default.
HTTP *http.Client
// Intercept, when set, runs synchronously at the top of every Run call.
// It exists purely as a test seam for controlling timing — e.g. blocking
// on a specific command to deterministically create the overlap a
// coalescing test needs — and is never set in production code.
Intercept func(cmd string)
// RemoteControlConsent makes /remote-control in a scripted pane show
// Claude Code's one-time "Enable Remote Control" question instead of
// connecting, the way a login that never accepted it behaves.
RemoteControlConsent bool
// contains filtered or unexported fields
}
Mock is a scripted fake target. It powers the whole hermetic test suite and LECTERN_MOCK=1 demo mode, and emits REAL claude stream-json shapes so the parser is exercised end to end rather than stubbed out.
Scenario markers in the prompt:
[mock:approval] agent requests a hook approval mid-run (real HTTP) [mock:fail] agent exits non-zero [mock:limit] agent is stopped by its usage limit (Claude's real rejected rate_limit_event + limit result) [mock:slow] agent takes ~3x longer [mock:subtask] agent files a follow-up card through the task hook [mock:note] agent leaves a project note [mock:approve-verdict] agent ends with VERDICT: APPROVE [mock:reject-verdict] agent ends with VERDICT: REQUEST_CHANGES [mock:judge:N] agent ends with JUDGE: attempt N (for judge-task tests) [mock:eval-judge:match|no-match] agent ends with EVAL_JUDGE: MATCH|NO_MATCH (replay eval judge tests)
func (*Mock) ExitPaneAgent ¶ added in v2.4.0
ExitPaneAgent makes a scripted pane's agent quit, leaving a shell prompt.
func (*Mock) Files ¶
Files returns a copy of the fake filesystem, for assertions about what was actually staged onto the target.
func (*Mock) SetPaneLimit ¶ added in v2.4.0
SetPaneLimit scripts a usage limit for an interactive session: the message is printed now, and every message sent while it is set is answered with it again. An empty message lifts the limit, so the next message is worked on.
type OpenSSH ¶ added in v2.6.0
type OpenSSH struct {
Host string
User string
Port int
KeyPath string
Wrapper string
Opts SSHOptions
// Binary is the ssh client; tests point it at a fake.
Binary string
// contains filtered or unexported fields
}
OpenSSH runs a target's commands through the system ssh(1) client instead of the built-in one. It exists for everything only OpenSSH does: a ~/.ssh/config alias with its Include and Match blocks, Kerberos/GSSAPI, FIDO2 security keys used directly, certificates, and ProxyCommand the operator put in their own config. One multiplexed master connection (ControlMaster) carries every command, so a security-key touch or a Kerberos exchange happens once, not per command.
func NewOpenSSH ¶ added in v2.6.0
func NewOpenSSH(host, user string, port int, keyPath, wrapper string, opts SSHOptions) *OpenSSH
NewOpenSSH builds an OpenSSH-transport executor.
func (*OpenSSH) ConnStatus ¶ added in v2.6.0
func (o *OpenSSH) ConnStatus() ConnStatus
ConnStatus reports the master connection's state as the last command saw it.
func (*OpenSSH) Destination ¶ added in v2.6.0
Destination is what ssh connects to: the alias when there is one.
func (*OpenSSH) DialTarget ¶ added in v2.6.0
DialTarget is `ssh -W`: a TCP stream to the target's loopback over the master connection. A wrapped target gets the python relay instead, like the built-in transport.
type Pct ¶
type Pct struct {
VMID string
// contains filtered or unexported fields
}
Pct drives an LXC on this Proxmox node through `pct exec` — no SSH and no per-container keys. The control-plane user needs passwordless sudo for pct. Target kind 'pct', with host holding the vmid.
func (*Pct) DialTarget ¶ added in v2.6.0
DialTarget reaches a Proxmox container's loopback through a relay started with `pct exec` (see bridge.go): the container has no route of its own from here, and needs none.
type Registry ¶
type Registry struct {
// Mock forces every target onto the scripted MockExecutor.
Mock bool
MockDelay time.Duration
// MockHTTP is the client fake agents use for hook callbacks. Tests point it
// at their own server.
MockHTTP *http.Client
// Env, when set, resolves what is known about a target (its session
// backend, its lectern binary) once its executor is made; see TargetEnv.
// It runs under the registry's lock, so it must not reach the target:
// it decides from the row (and its stored probe) and this host alone.
Env func(t *store.Target, ex Executor) TargetEnv
// contains filtered or unexported fields
}
Registry hands out one cached executor per target id.
func NewRegistry ¶
NewRegistry builds an executor registry.
func (*Registry) Any ¶
Any returns one cached executor. Tests use it to inspect what reached "the target" without knowing which target id won the race.
func (*Registry) Cached ¶ added in v2.6.0
Cached returns the executor already made for a target, without making one, so asking how a connection is doing never opens it.
func (*Registry) Forget ¶ added in v2.6.0
Forget drops one target's executor, so the next command dials fresh.
type SSH ¶
type SSH struct {
Host string
User string
Port int
KeyPath string
// Wrapper, when set, transforms every command before it is sent. It is how a
// host whose SSH lands somewhere other than the work becomes an ordinary
// target. Two placeholders:
//
// {cmd} the command, POSIX shell-quoted
// {b64} the command, base64-encoded
//
// {b64} is the one to reach for on a Windows host: its SSH server hands the
// line to cmd.exe, which does not understand POSIX quoting, and anything
// that survives that still gets $-expanded by the outer bash. Base64 is
// alphanumeric, so it passes through both untouched:
//
// wsl -e bash -lc "echo {b64} | base64 -d | bash"
//
// A wrapper with no placeholder is treated as a prefix and given the
// shell-quoted command, which is what a POSIX host wants.
Wrapper string
// Opts are the target's extra SSH settings: ProxyJump, ssh-agent use
// and forwarding (docs/ssh.md). Alias and Options only apply to the
// OpenSSH transport; this one cannot read ~/.ssh/config.
Opts SSHOptions
// contains filtered or unexported fields
}
SSH is a remote target reached over SSH. Key auth only, one reused connection with bounded setup and command execution.
func (*SSH) ConnStatus ¶ added in v2.6.0
func (s *SSH) ConnStatus() ConnStatus
ConnStatus reports the pooled connection's state.
func (*SSH) DialTarget ¶
DialTarget rides the SSH connection the executor already holds, which is the same thing `ssh -L` does, without a second process to supervise.
A wrapped target runs its commands somewhere else again — inside a container on the SSH host, say — so the SSH host's loopback is not the loopback the session sees, and forwarding to it would reach the wrong machine's services.
func (*SSH) ReadFile ¶
ReadFile tails from a byte offset.
`tail -c +N` is 1-indexed and streams in big blocks. The obvious `dd bs=1` spelling costs one syscall per byte, which is pathological when a growing agent log is re-read on every poll.
func (*SSH) WithOptions ¶ added in v2.6.0
func (s *SSH) WithOptions(o SSHOptions) *SSH
WithOptions sets the target's extra SSH settings.
type SSHOptions ¶ added in v2.6.0
type SSHOptions struct {
// Alias is a Host entry in the control plane's ~/.ssh/config. The OpenSSH
// transport and the web terminal connect to it by name, so everything the
// entry says (Include, Match, certificates, GSSAPI...) applies.
Alias string `json:"alias,omitempty"`
// ProxyJump is OpenSSH's -J: [user@]host[:port], comma-separated hops.
ProxyJump string `json:"proxy_jump,omitempty"`
// ForwardAgent forwards the control plane's ssh-agent to the target for
// the length of each command (git over SSH, for one).
ForwardAgent bool `json:"forward_agent,omitempty"`
// NoAgent stops the built-in transport offering keys from ssh-agent.
NoAgent bool `json:"no_agent,omitempty"`
// IdentityAgent is the agent socket; empty means $SSH_AUTH_SOCK.
IdentityAgent string `json:"identity_agent,omitempty"`
// Options are extra OpenSSH Key=Value options, from an allowlist.
Options []string `json:"options,omitempty"`
// Transport picks what runs commands: "" (built in) or "openssh".
Transport string `json:"transport,omitempty"`
// EditorHost is the name your own computer knows this machine by, for
// "Open in editor" links. Empty means the alias or host.
EditorHost string `json:"editor_host,omitempty"`
}
SSHOptions are a target's SSH settings beyond host, user, port and key (docs/ssh.md). They live in targets.ssh_json.
func ParseSSHOptions ¶ added in v2.6.0
func ParseSSHOptions(raw string) SSHOptions
ParseSSHOptions reads targets.ssh_json; anything unreadable is no options.
func (SSHOptions) JSON ¶ added in v2.6.0
func (o SSHOptions) JSON() string
JSON renders the options for storage.
func (SSHOptions) OpenSSHArgs ¶ added in v2.6.0
func (o SSHOptions) OpenSSHArgs() []string
OpenSSHArgs are the ssh(1) arguments these options add: jump hosts, agent forwarding and extra options. Shared by the OpenSSH transport and the web terminal so both reach the machine the same way.
func (SSHOptions) Validate ¶ added in v2.6.0
func (o SSHOptions) Validate() error
Validate refuses options Lectern will not pass to ssh.
type StatusReporter ¶ added in v2.6.0
type StatusReporter interface {
ConnStatus() ConnStatus
}
StatusReporter is an executor that knows its connection state.
type Streamer ¶ added in v2.6.0
type Streamer interface {
Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)
}
Streamer is an executor that can copy a command's output straight to a writer instead of holding it in memory: how a folder download reaches the browser as it is produced.
type TargetEnv ¶ added in v2.7.0
type TargetEnv struct {
// SessionBackend is "tmux" or "pty"; "" means tmux. It is the backend
// new sessions start in; a session already running stays in the one
// recorded on its row (backend.ForSession).
SessionBackend string
// Backends lists every backend the target can drive, SessionBackend
// included; nil means SessionBackend alone.
Backends []string
// Lectern is the lectern binary's path on the target, in a form the
// target's shell accepts, or "" when there is none. Target-side helpers
// then fall back to their Python versions.
Lectern string
// Helpers lists the helpers that lectern has; nil means all of this
// build's (the local target runs this very binary). A remote lectern
// may be older than the server, so only what its probe listed is used.
Helpers []string
}
TargetEnv is what Lectern knows about the machine an executor drives, beyond how to reach it: which session backend keeps its terminals (docs/ptyhost.md) and where the lectern binary is on it, if anywhere.
It is kept beside the executor rather than in it, so every executor kind — and every test double — carries it without knowing about it. An executor nobody resolved (tests, a sandbox's per-attempt container) has the zero value: tmux, and no lectern binary.
func TargetEnvOf ¶ added in v2.7.0
TargetEnvOf returns what was recorded for ex, or the zero TargetEnv.