executor

package
v2.9.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT 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 executor abstracts "run a command / move a file on a machine". Everything above this layer is target-kind agnostic.

Index

Constants

View Source
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.

View Source
const MockDiff = `` /* 205-byte string literal not displayed */

MockDiff is the patch every mock attempt "produces".

View Source
const MockNumstat = "4\t1\tapp.py\n"

MockNumstat is the matching --numstat output.

Variables

View Source
var ErrNoDial = errors.New("this kind of target cannot forward ports")

ErrNoDial is returned by targets whose loopback cannot be reached this way.

View Source
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 Probe

func Probe(ctx context.Context, ex Executor) (map[string]any, error)

Probe is the capability check every target kind shares: versions plus disk.

func SetTargetEnv added in v2.7.0

func SetTargetEnv(ex Executor, env TargetEnv)

SetTargetEnv records what is known about the target ex drives.

func ShellQuote

func ShellQuote(s string) string

ShellQuote renders a value as one shell word.

func Wrap

func Wrap(vmid, cmd, cwd string) string

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

type Dialer interface {
	DialTarget(ctx context.Context, addr string) (net.Conn, error)
}

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.

func Errf

func Errf(format string, args ...any) *Error

Errf builds an executor Error.

func (*Error) Error

func (e *Error) Error() string

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 NewLocal

func NewLocal() *Local

NewLocal builds a Local executor.

func (*Local) Close

func (l *Local) Close() error

Close is a no-op: nothing is pooled.

func (*Local) DialTarget

func (l *Local) DialTarget(ctx context.Context, addr string) (net.Conn, error)

DialTarget on the control-plane host is an ordinary dial.

func (*Local) ReadFile

func (l *Local) ReadFile(_ context.Context, path string, offset int64) ([]byte, error)

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.

func (*Local) Run

func (l *Local) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)

Run shells out on this host.

func (*Local) Stream added in v2.6.0

func (l *Local) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)

Stream on the control plane.

func (*Local) WriteFile

func (l *Local) WriteFile(_ context.Context, path string, data []byte) error

WriteFile writes data, creating parent directories.

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)
	// 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 NewMock

func NewMock(delay time.Duration) *Mock

NewMock builds a mock executor.

func (*Mock) Close

func (m *Mock) Close() error

Close cancels every fake agent still running.

func (*Mock) CmdLog

func (m *Mock) CmdLog() []string

func (*Mock) ExitPaneAgent added in v2.4.0

func (m *Mock) ExitPaneAgent(sess string)

ExitPaneAgent makes a scripted pane's agent quit, leaving a shell prompt.

func (*Mock) Files

func (m *Mock) Files() map[string][]byte

Files returns a copy of the fake filesystem, for assertions about what was actually staged onto the target.

func (*Mock) PaneText added in v2.4.0

func (m *Mock) PaneText(sess string) string

PaneText is the current text of a scripted pane.

func (*Mock) Probe

func (m *Mock) Probe() map[string]any

Probe answers the capability check without shelling out.

func (*Mock) ReadFile

func (m *Mock) ReadFile(_ context.Context, path string, offset int64) ([]byte, error)

ReadFile reads from the fake filesystem.

func (*Mock) Run

func (m *Mock) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)

func (*Mock) SetPaneLimit added in v2.4.0

func (m *Mock) SetPaneLimit(sess, message string) bool

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.

func (*Mock) WriteFile

func (m *Mock) WriteFile(_ context.Context, path string, data []byte) error

WriteFile writes to the fake filesystem.

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) Args added in v2.6.0

func (o *OpenSSH) Args() []string

Args are the ssh(1) arguments before the destination.

func (*OpenSSH) Close added in v2.6.0

func (o *OpenSSH) Close() error

Close ends the master connection.

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

func (o *OpenSSH) Destination() string

Destination is what ssh connects to: the alias when there is one.

func (*OpenSSH) DialTarget added in v2.6.0

func (o *OpenSSH) DialTarget(ctx context.Context, addr string) (net.Conn, error)

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.

func (*OpenSSH) ReadFile added in v2.6.0

func (o *OpenSSH) ReadFile(ctx context.Context, path string, offset int64) ([]byte, error)

ReadFile tails from a byte offset.

func (*OpenSSH) Run added in v2.6.0

func (o *OpenSSH) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)

Run executes a command over the multiplexed connection.

func (*OpenSSH) Stream added in v2.6.0

func (o *OpenSSH) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)

Stream runs cmd and copies its stdout to w as it arrives.

func (*OpenSSH) WriteFile added in v2.6.0

func (o *OpenSSH) WriteFile(ctx context.Context, path string, data []byte) error

WriteFile streams bytes over stdin; a wrapped target gets bounded chunks.

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 NewPct

func NewPct(vmid string) *Pct

NewPct builds a pct executor for a container id.

func (*Pct) Close

func (p *Pct) Close() error

Close is a no-op: pct exec pools nothing.

func (*Pct) DialTarget added in v2.6.0

func (p *Pct) DialTarget(ctx context.Context, addr string) (net.Conn, error)

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.

func (*Pct) ReadFile

func (p *Pct) ReadFile(ctx context.Context, filePath string, offset int64) ([]byte, error)

ReadFile tails a file inside the container from a byte offset.

func (*Pct) Run

func (p *Pct) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)

Run executes inside the container.

func (*Pct) Stream added in v2.6.0

func (p *Pct) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)

Stream inside a Proxmox container.

func (*Pct) WriteFile

func (p *Pct) WriteFile(ctx context.Context, filePath string, data []byte) error

WriteFile streams bytes into the container without shell argument limits.

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

func NewRegistry(mock bool, mockDelay time.Duration) *Registry

NewRegistry builds an executor registry.

func (*Registry) Any

func (r *Registry) Any() Executor

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

func (r *Registry) Cached(id int64) Executor

Cached returns the executor already made for a target, without making one, so asking how a connection is doing never opens it.

func (*Registry) For

func (r *Registry) For(t *store.Target) (Executor, error)

For returns the executor for a target, creating and caching it on first use.

func (*Registry) Forget added in v2.6.0

func (r *Registry) Forget(id int64)

Forget drops one target's executor, so the next command dials fresh.

func (*Registry) Refresh added in v2.7.0

func (r *Registry) Refresh(t *store.Target)

Refresh re-resolves what is known about a target whose row changed (a new probe), keeping its executor and connection.

func (*Registry) Reset

func (r *Registry) Reset()

Reset drops the cache — called whenever a target's connection details change.

type Result

type Result struct {
	RC     int
	Stdout string
	Stderr string
}

Result is the outcome of one command.

func (Result) OK

func (r Result) OK() bool

OK reports a zero exit status.

type RunOpts

type RunOpts struct {
	Cwd     string
	Timeout float64 // seconds; 0 means 120
}

RunOpts carries the optional arguments of Run.

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 NewSSH

func NewSSH(host, user string, port int, keyPath, wrapper string) *SSH

NewSSH builds an SSH executor for a target.

func (*SSH) Close

func (s *SSH) Close() error

Close drops the pooled connection.

func (*SSH) ConnStatus added in v2.6.0

func (s *SSH) ConnStatus() ConnStatus

ConnStatus reports the pooled connection's state.

func (*SSH) DialTarget

func (s *SSH) DialTarget(ctx context.Context, addr string) (net.Conn, error)

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

func (s *SSH) ReadFile(ctx context.Context, path string, offset int64) ([]byte, error)

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) Run

func (s *SSH) Run(ctx context.Context, cmd string, opts RunOpts) (Result, error)

Run executes a command over a fresh SSH channel on the pooled connection.

func (*SSH) Stream added in v2.6.0

func (s *SSH) Stream(ctx context.Context, cmd string, w io.Writer, timeout float64) (Result, error)

Stream over the pooled SSH connection.

func (*SSH) WithOptions added in v2.6.0

func (s *SSH) WithOptions(o SSHOptions) *SSH

WithOptions sets the target's extra SSH settings.

func (*SSH) WriteFile

func (s *SSH) WriteFile(ctx context.Context, path string, data []byte) error

WriteFile streams file bytes on native SSH targets. Wrapped targets may consume stdin themselves (e.g. Windows -> WSL), so use bounded commands there.

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

func TargetEnvOf(ex Executor) TargetEnv

TargetEnvOf returns what was recorded for ex, or the zero TargetEnv.

Jump to

Keyboard shortcuts

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