env

package module
v1.7.34 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 35 Imported by: ? 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.

README

github.com/sky-valley/pi/env

The Go port of @earendil-works/pi-env: remote execution environments, where an agent's tools run on another machine, usually over SSH, while the agent, its storage and credentials stay local.

  • pi-env (cmd/pi-env, daemon/): a small program that runs on the remote machine. It speaks a framed protocol on stdin and stdout (docs/protocol.md) and performs file operations and commands there. Upstream's daemon is written in Rust; this one is Go, and both pass upstream's test suite.
  • RemoteExecutionEnv: an execution environment (coding.ExecutionEnv, plus the rest of Durable's ExecutionEnv as methods) that talks to the daemon through a Connection. Its results match NodeExecutionEnv running on the remote machine; only error messages may differ (docs/semantics.md).
target := env.SSHTarget{Host: "gpu-box", KnownHostsFile: "/data/ssh/known_hosts", HostKeyAlias: "pi-env-gpu"}
// Once: show the host's key fingerprint to the owner, who compares it out of band and accepts it.
scan, err := env.ScanHostKey(ctx, target)
err = env.AcceptHostKey(target, scan.Lines)

// Detects the remote system, deploys the daemon if missing (named by its SHA-256 and verified before every start),
// and returns a connection that starts it over ssh.
connection, remote, err := env.ConnectSSH(ctx, env.SSHConnectOptions{SSHTarget: target})
remoteEnv := env.NewRemoteExecutionEnv(env.RemoteExecutionEnvOptions{Connection: connection, ID: "pi-env:gpu", Cwd: "/home/me/project"})

// Or lazily: nothing happens until the first operation, which detects, deploys and connects. A failure (no network,
// untrusted host key) is that operation's error, and the next operation tries again.
lazy, detected := env.SSHConnection(env.SSHConnectOptions{SSHTarget: target})
lazyEnv := env.NewRemoteExecutionEnv(env.RemoteExecutionEnvOptions{Connection: lazy, ID: "pi-env:gpu", Cwd: "/home/me/project"})

The package embeds the daemon for every supported remote system (bin/, gzipped, built by go generate), and deploys the uncompressed binary. ssh runs with BatchMode, strict host-key checking against the application's own known-hosts file under a fixed alias, no forwarding of any kind, no shared connections or configured commands, and without forwarding the local locale. On Windows, detection and deployment go through PowerShell, and the daemon starts through the server's default shell (cmd.exe or PowerShell).

ListFiles(ctx, path, options) lists the tree below a directory in the daemon, as fd --hidden --exclude .git does without following symbolic links: files, directories and links as relative / paths, skipping what git ignores inside work trees, bounded by MaxEntries, MaxBytes and TimeoutMS with a Truncated flag, and stopped by ending the context. A daemon released before it reports not_supported (hello.features lacks listFiles), and callers fall back to their own walk. For local sessions, LocalExecutionEnv is the local environment (coding.LocalEnv) plus ListFiles through a daemon on the same machine:

daemon, err := env.LocalDaemon() // the embedded daemon for this machine, written to the user's cache directory
local := env.NewConnection(env.ConnectionOptions{Command: []string{daemon}}) // owned by the caller; Close it at shutdown
localEnv := env.NewLocalExecutionEnv(env.LocalExecutionEnvOptions{Cwd: "/home/me/project", Connection: local})
listing, err := localEnv.ListFiles(ctx, ".", &env.ListFilesOptions{Exclude: []string{"node_modules"}})
// listing.Entries: [{Path: "src", Kind: "directory"}, {Path: "src/a.go", Kind: "file"}], listing.Truncated

NodePlatform(info) gives the remote system of connection.Info(ctx) in Node's names (win32, darwin, x64, arm64), as process.platform and process.arch spell them.

OpenTerminal(ctx, connection, options) runs a program, by default the user's login shell, in a pseudo-terminal of the daemon: raw output, input, resizing and its exit code, for interactive terminals. LocalDaemon() is the daemon for this machine, for terminals without SSH. Terminals are not supported on Windows yet.

OpenProcess(ctx, connection, options) runs a program with plain pipes, for programs that speak a protocol on stdin and stdout, such as an MCP server: Write and CloseStdin for its input, raw stdout and stderr bytes through OnStdout and OnStderr, Close to kill its process group, and Wait for its exit code. When the program exits, what it started in its process group is killed too, so a wrapper such as npx leaves nothing running. Nothing is echoed, translated or merged, unlike a terminal; it works on every supported system. A daemon released before it fails the open with not_supported. Argv runs as an argv command does: on Windows, batch files such as npx.cmd are refused, as Node refuses them without a shell, so callers start them through cmd.exe.

server, err := env.OpenProcess(ctx, connection, env.ProcessOptions{
	Cwd:      "/home/me/project",
	Argv:     []string{"npx", "-y", "@modelcontextprotocol/server-filesystem", "."},
	OnStdout: parser.Push,
})
server.Write(append(initialize, '\n'))

Supported remote systems: Linux, macOS, Android (Termux) and Windows, on x86-64 and arm64. On Windows, string commands run through Git Bash as NodeExecutionEnv runs them there; argv commands run directly.

Development

The env module is its own Go module; work on it together with the root module through a workspace (go.work with both) or with GOWORK=off against the published root.

go generate ./... in env builds the eight daemons reproducibly (internal/daemonsource: -trimpath, no VCS stamp or build id, cgo off, the module's own go.mod) into bin/ with their manifest. Run it whenever the daemon's source changes: TestEmbeddedDaemonsAreCurrent fails until then, and TestEmbeddedDaemonsRebuildIdentically rebuilds this machine's daemon and compares it byte for byte when the toolchain is the one that built them.

The client's tests build the daemon from ./cmd/pi-env, or use the binary named by PI_ENV_DAEMON (the Rust daemon of @earendil-works/pi-env, to check the client against it). They run Durable's env conformance suite against RemoteExecutionEnv, compare random operation sequences with NodeExecutionEnv's results, compare the frames the client sends and the ssh calls it makes with upstream's TypeScript client (testdata/*/capture.mts record them), and deploy and run the daemon over a disposable sshd on localhost when one is installed.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AcceptHostKey

func AcceptHostKey(target SSHTarget, lines []string) error

AcceptHostKey trusts host-key lines from ScanHostKey by adding them to the target's known-hosts file. Only plain lines for the target's alias are accepted. A key that differs from a trusted key of the same type is refused with HostKeyChangedError; ForgetHostKey must remove the old keys first.

func ConnectSSH

func ConnectSSH(ctx context.Context, options SSHConnectOptions) (*Connection, RemotePlatform, error)

ConnectSSH detects the remote system and deploys the daemon now, then returns a Connection that starts it over ssh, like SSHConnection. Host keys must already be trusted (ScanHostKey, AcceptHostKey); otherwise it fails with HostKeyUnknownError.

func DeployDaemon

func DeployDaemon(ctx context.Context, target SSHTarget, remote RemotePlatform, binary string) (string, error)

DeployDaemon makes sure the daemon is on the remote machine, verified by its SHA-256 before it ever runs, and removes daemons of other contents. The upload goes to a new temporary file and is renamed into place only once its hash matches. binary is a daemon file to deploy; empty deploys the daemon embedded for remote (PackagedDaemon). It returns the remote path of the daemon.

func ForgetHostKey

func ForgetHostKey(target SSHTarget) error

ForgetHostKey stops trusting every key stored for the target's alias, e.g. after the owner confirmed a changed host key.

func IsConnectionLost

func IsConnectionLost(err error) bool

IsConnectionLost reports whether err means the connection was lost, not that the daemon refused the request.

func LocalDaemon

func LocalDaemon() (string, error)

LocalDaemon is the path of the daemon for the machine this program runs on, e.g. for terminals of local sessions and LocalExecutionEnv's ListFiles: NewConnection(ConnectionOptions{Command: []string{path}}). The embedded daemon is written to the user's cache directory, named by its SHA-256 like a deployed one, and verified before every use: each call, and each start of a Connection running it, writes it again if it is missing or changed.

func NodePlatform

func NodePlatform(info RemoteInfo) (platform, arch string)

NodePlatform gives the daemon's system and architecture in Node's names, which hello reports in Rust's spelling: windows is win32, macos is darwin, x86_64 is x64, aarch64 is arm64, so they compare with process.platform and process.arch. Other names are kept.

func PackagedDaemon

func PackagedDaemon(remote RemotePlatform) ([]byte, error)

PackagedDaemon is the daemon embedded for a remote system (its Platform and Arch), uncompressed and checked against the manifest's SHA-256.

func SSHArguments

func SSHArguments(target SSHTarget) ([]string, error)

SSHArguments are the arguments for ssh up to the host: no prompts, no forwarding of any kind, no shared connections, no commands from the configuration, no locale forwarding (the remote uses its own), and host keys checked strictly against the application's own file under a fixed alias.

Types

type BinaryReader

type BinaryReader interface {
	// Info is the metadata of the opened file, not of whatever its path
	// names now.
	Info(ctx context.Context) (coding.FileInfo, error)
	// Read returns up to length bytes at offset; fewer only at the end of
	// the file.
	Read(ctx context.Context, offset, length int64) ([]byte, error)
	// ScanLines locates lines [StartLine, EndLine) in one pass over the file.
	ScanLines(ctx context.Context, lines LineRange) (LineScan, error)
	// Close releases the file; it is best-effort and idempotent.
	Close() error
}

BinaryReader reads ranges of one opened regular file; all calls see the same file even if its path is renamed (Durable's BinaryReader).

type BinaryReaderOptions

type BinaryReaderOptions struct {
	// NoFollow refuses a symbolic link as the final path component (invalid)
	// instead of following it; earlier components are still resolved.
	NoFollow bool
}

BinaryReaderOptions are OpenBinaryReader's options.

type Connection

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

Connection is one connection to a pi-env daemon: started lazily on the first request and started again after it is lost. Requests in flight when it is lost fail with code unknown; for mutations their outcome is then unknown. A Connection is safe for concurrent use.

func NewConnection

func NewConnection(options ConnectionOptions) *Connection

NewConnection returns a connection that starts nothing until its first request.

func SSHConnection

func SSHConnection(options SSHConnectOptions) (connection *Connection, remote func() *RemotePlatform)

SSHConnection returns a Connection to the target that does nothing until its first request. Each start detects the remote system (the first time), verifies the daemon and deploys it if it is missing or changed, then starts it over ssh. A failure (no network, an untrusted or changed host key) fails the requests waiting for that start with code spawn_error and the ssh diagnostics as message; the next request tries again. remote returns the detected system, once known.

func (*Connection) Close

func (c *Connection) Close()

Close stops the daemon; it kills everything it started.

func (*Connection) Info

func (c *Connection) Info(ctx context.Context) (RemoteInfo, error)

Info connects if needed and returns what the daemon reported about its machine. Ending ctx stops waiting for the start (code aborted), not the start itself.

func (*Connection) Kill

func (c *Connection) Kill(id uint32, session int)

Kill kills one exec without aborting it.

func (*Connection) Request

func (c *Connection) Request(ctx context.Context, op string, fields any, options *RequestOptions) (Reply, error)

Request sends a request for op with fields (a JSON object; nil is {}) and waits for its result, starting the daemon first if needed. Ending ctx while the connection starts fails it at once with code aborted (the start goes on for other requests); after the request was sent, it sends cancel, and the request settles with the daemon's result or error, or with code aborted if the daemon does not answer within a second.

func (*Connection) Session

func (c *Connection) Session(ctx context.Context) (int, error)

Session connects if needed and returns the live session's id.

type ConnectionOptions

type ConnectionOptions struct {
	// Command starts the daemon, before its `serve --token <hex>`
	// arguments, e.g. ["ssh", "-T", "--", "host", "~/.pi/mobile/tools/pi-env"].
	Command []string
	// CommandFunc, when set, computes the command at each start instead
	// (detecting and deploying first, for example); its failure fails that
	// start, and the next request tries again. Its context ends when the
	// connection is closed.
	CommandFunc func(ctx context.Context) ([]string, error)
	// OnLog receives the daemon's and the transport's diagnostic output, in
	// order and one call at a time, on a goroutine of the connection's own;
	// it may use the connection.
	OnLog func(text string)
}

ConnectionOptions configure a Connection.

type CreateDirOptions

type CreateDirOptions struct {
	// Recursive creates missing parents and accepts an existing directory;
	// nil is true.
	Recursive *bool
}

CreateDirOptions are CreateDir's options.

type DirReader

type DirReader interface {
	// Next returns up to maxEntries entries in the order the file system
	// returns them, continuing where the previous call stopped; done marks
	// the end. Entries that disappear before their metadata is read are
	// skipped, as are entries of unsupported kinds.
	Next(ctx context.Context, maxEntries int) (entries []coding.FileInfo, done bool, err error)
	Close() error
}

DirReader pages through one directory's entries (Durable's DirReader).

type ExecutionError

type ExecutionError struct {
	Code    ExecutionErrorCode
	Message string
	// SpillPath is the spill file of a command that timed out or was aborted
	// after its output crossed the spill thresholds.
	SpillPath string
	Cause     error
	// contains filtered or unexported fields
}

ExecutionError is a command that could not run or was cut short: Durable's ExecutionError.

For the coding tools' shell seam, an aborted command matches coding.ErrShellAborted (errors.Is) and a timed-out one converts to a *coding.ShellTimeoutError (errors.As), the two failures that seam classifies.

func (*ExecutionError) As

func (e *ExecutionError) As(target any) bool

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

func (*ExecutionError) Is

func (e *ExecutionError) Is(target error) bool

func (*ExecutionError) Unwrap

func (e *ExecutionError) Unwrap() error

type ExecutionErrorCode

type ExecutionErrorCode string

ExecutionErrorCode is Durable's ExecutionError code.

const (
	ExecAborted          ExecutionErrorCode = "aborted"
	ExecTimeout          ExecutionErrorCode = "timeout"
	ExecShellUnavailable ExecutionErrorCode = "shell_unavailable"
	ExecSpawnError       ExecutionErrorCode = "spawn_error"
	ExecCallbackError    ExecutionErrorCode = "callback_error"
	ExecUnknown          ExecutionErrorCode = "unknown"
)

The codes of ExecutionError (Durable's ExecutionErrorCode).

type FileChange added in v1.5.29

type FileChange struct {
	Kind FileChangeKind
	// Paths is set for FileChangePaths.
	Paths []string
	// Err is set for FileChangeFailed.
	Err *FileError
}

FileChange is what changed (Durable's FileChange), tagged by Kind:

  • FileChangePaths: something at or below each of Paths may have changed (a directory path covers its whole subtree). Calls may be spurious; a change is never missed while the watcher is healthy.
  • FileChangeOverflow: coverage was uncertain for a while (lost events, reconnect); rescan everything that is watched.
  • FileChangeFailed: the watcher stopped with Err, for example because the watched tree grew past the environment's limit; no calls follow.

type FileChangeKind added in v1.5.29

type FileChangeKind string

FileChangeKind is the discriminator of a FileChange.

const (
	FileChangePaths    FileChangeKind = "paths"
	FileChangeOverflow FileChangeKind = "overflow"
	FileChangeFailed   FileChangeKind = "failed"
)

type FileError

type FileError struct {
	Code    FileErrorCode
	Message string
	// Path is the path the failure is about, when there is one.
	Path  string
	Cause error
}

FileError is a failed file operation of an environment: Durable's FileError, which pi-env's environments return. Its message is the one NodeExecutionEnv would give, and it reaches tools (and models) as is, so Error returns only the message.

errors.Is matches not_found with fs.ErrNotExist and permission_denied with fs.ErrPermission, so callers written against the local file system keep working.

func (*FileError) Error

func (e *FileError) Error() string

func (*FileError) Is

func (e *FileError) Is(target error) bool

func (*FileError) Unwrap

func (e *FileError) Unwrap() error

type FileErrorCode

type FileErrorCode string

FileErrorCode is Durable's FileError code.

const (
	FileAborted          FileErrorCode = "aborted"
	FileNotFound         FileErrorCode = "not_found"
	FilePermissionDenied FileErrorCode = "permission_denied"
	FileNotDirectory     FileErrorCode = "not_directory"
	FileIsDirectory      FileErrorCode = "is_directory"
	FileInvalid          FileErrorCode = "invalid"
	FileNotSupported     FileErrorCode = "not_supported"
	FileUnknown          FileErrorCode = "unknown"
)

The codes of FileError (Durable's FileErrorCode).

type FileListEntry

type FileListEntry struct {
	// Path is relative to the listed directory, with / separators on every
	// system.
	Path string
	// Kind is file, directory or symlink; a symbolic link is not followed.
	Kind coding.FileKind
}

FileListEntry is one entry of a FileListing.

type FileListing

type FileListing struct {
	// Entries are depth first, parents before their entries, siblings in
	// byte order of their names.
	Entries []FileListEntry
	// Truncated reports that a bound in ListFilesOptions ended the listing
	// early.
	Truncated bool
}

FileListing is the result of ListFiles.

type HostKeyChangedError

type HostKeyChangedError struct{ Message string }

HostKeyChangedError means the remote host's key differs from the one in KnownHostsFile; it is never accepted automatically.

func (*HostKeyChangedError) Error

func (e *HostKeyChangedError) Error() string

type HostKeyScan

type HostKeyScan struct {
	Lines        []string
	Fingerprints []string
}

HostKeyScan is what ScanHostKey received: known-hosts lines and their fingerprints.

func ScanHostKey

func ScanHostKey(ctx context.Context, target SSHTarget) (HostKeyScan, error)

ScanHostKey connects once with accept-new against a temporary known-hosts file to capture the key the host presents, through the same route (~/.ssh/config, jump hosts) as real connections. Showing a fingerprint is not authentication: compare it with one obtained out of band before accepting it.

type HostKeyUnknownError

type HostKeyUnknownError struct{ Message string }

HostKeyUnknownError means the remote host's key is not in KnownHostsFile; ScanHostKey shows it so the owner can accept it.

func (*HostKeyUnknownError) Error

func (e *HostKeyUnknownError) Error() string

type LineRange

type LineRange struct {
	StartLine int64
	EndLine   int64
}

LineRange selects lines for ScanLines: 0-based, where line k starts after the k-th newline byte. EndLine 0 means to the end of the file (a given end is always above StartLine).

type LineScan

type LineScan struct {
	// Newlines is the count of newline bytes in the whole file; it has
	// Newlines+1 lines.
	Newlines int64 `json:"newlines"`
	// Start and End are the byte range of the selected lines, without the
	// newline that ends the last.
	Start int64 `json:"start"`
	End   int64 `json:"end"`
	// FirstLineEnd is where the first selected line ends.
	FirstLineEnd int64 `json:"firstLineEnd"`
	// LastLineStart is where the last selected line starts.
	LastLineStart int64 `json:"lastLineStart"`
	// SelectedBytes and FirstLineBytes are UTF-8 lengths of the decoded
	// selection and of its first line.
	SelectedBytes  int64 `json:"selectedBytes"`
	FirstLineBytes int64 `json:"firstLineBytes"`
}

LineScan is where lines of a file are, as ScanLines found them (Durable's LineScan).

type ListFilesOptions

type ListFilesOptions struct {
	// Hidden includes names starting with "." (on Windows also files with
	// the hidden attribute); nil is true. Entries named .git are never
	// listed.
	Hidden *bool
	// Gitignore skips, inside a git work tree, what git ignores; nil is
	// true. Outside work trees, .gitignore files have no effect.
	Gitignore *bool
	// Exclude names entries to skip with everything below them, such as
	// node_modules.
	Exclude []string
	// MaxEntries is the most entries to list; nil is 50 000.
	MaxEntries *int64
	// MaxBytes is the most bytes of the listing, each entry's UTF-8 path
	// plus two; nil is 4 MiB, at most 15.9 MiB.
	MaxBytes *int64
	// TimeoutMS is the time after which the listing stops; nil is 10 000.
	TimeoutMS *int64
}

ListFilesOptions say what ListFiles lists (Durable's ListFilesOptions). Nil fields take the daemon's defaults.

type LocalExecutionEnv

type LocalExecutionEnv struct {
	*coding.LocalEnv
	// contains filtered or unexported fields
}

LocalExecutionEnv is the local environment (coding.LocalEnv) with ListFiles through a pi-env daemon on the same machine, so local and remote environments list files with the same code. The connection belongs to the caller, who closes it; several environments may share it.

func NewLocalExecutionEnv

func NewLocalExecutionEnv(options LocalExecutionEnvOptions) *LocalExecutionEnv

NewLocalExecutionEnv returns a local environment listing files through options.Connection.

func (*LocalExecutionEnv) ListFiles

func (e *LocalExecutionEnv) ListFiles(ctx context.Context, path string, options *ListFilesOptions) (FileListing, error)

ListFiles lists the tree below a directory through the daemon.

type LocalExecutionEnvOptions

type LocalExecutionEnvOptions struct {
	// Cwd is the working directory; empty is the process's.
	Cwd string
	// Connection is a connection to this machine's daemon, for ListFiles:
	// NewConnection(ConnectionOptions{Command: []string{daemonPath}}) with
	// the path LocalDaemon returns.
	Connection *Connection
}

LocalExecutionEnvOptions configure a LocalExecutionEnv.

type OutputInfo

type OutputInfo struct {
	// Stream is "stdout" or "stderr".
	Stream string
	// Skipped is output omitted immediately before this chunk, only with a
	// Window.
	Skipped *OutputSkip
}

OutputInfo describes one chunk of output (Durable's ShellOutputInfo).

type OutputSkip

type OutputSkip struct {
	Bytes           int64 `json:"bytes"`
	Newlines        int64 `json:"newlines"`
	EndsWithNewline bool  `json:"endsWithNewline"`
}

OutputSkip is output an environment omitted, measured on the decoded text OnOutput would have received.

type OutputWindow

type OutputWindow struct {
	// MaxBytes of decoded text kept at the end of the output (UTF-8).
	MaxBytes int64 `json:"maxBytes"`
	// MaxLines kept at the end of the output.
	MaxLines int64 `json:"maxLines"`
	// MinIntervalMS is the minimum pause between the caller's samples.
	MinIntervalMS float64 `json:"minIntervalMs"`
	// BytesPerSecond paces each sample in proportion to its size.
	BytesPerSecond float64 `json:"bytesPerSecond"`
}

OutputWindow is the tail of the combined output a caller keeps, and how often it samples it (Durable's ShellOutputWindow).

type ProcessOptions added in v1.5.29

type ProcessOptions struct {
	// Cwd is the working directory of the program; it must exist.
	Cwd string
	// Argv is the program and its arguments, run directly without a shell.
	Argv []string
	// Env is added to the daemon's environment, or is the whole environment
	// with InheritEnv false.
	Env map[string]string
	// InheritEnv nil is the daemon's default (true).
	InheritEnv *bool
	// OnStdout receives the program's stdout, raw bytes in order, from one
	// goroutine; nil drops it (pi's onStdout is required; a Go caller that
	// leaves it out must not crash the program, as RemoteTerminal's OnData).
	OnStdout func(data []byte)
	// OnStderr receives the program's stderr, raw bytes in order, from the
	// same goroutine; nil drops it.
	OnStderr func(data []byte)
}

ProcessOptions configure OpenProcess.

type RemoteError

type RemoteError struct {
	Code    string
	Message string
	// Path is the path the daemon named, if any.
	Path string
	// Fields are all the fields of the daemon's error.
	Fields map[string]any
}

RemoteError is a failure reported by the daemon, with its Node-style code, or a failure of the connection itself (IsConnectionLost).

func (*RemoteError) Error

func (e *RemoteError) Error() string

type RemoteExecutionEnv

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

RemoteExecutionEnv is an execution environment on another machine, reached through a pi-env daemon. Results match NodeExecutionEnv running on that machine: the daemon performs the system calls, and this type applies Node's path, error, and result rules.

It implements coding.ExecutionEnv. The rest of Durable's ExecutionEnv, which has no Go interface yet, is here as methods of the same names: OpenBinaryReader, OpenDirReader, ListFiles, Watch, TruncateFile, FlushFile, CreateDir, Remove, CreateTempDir, CreateTempFile, and Durable's exec as RunShell and RunProgram.

func NewRemoteExecutionEnv

func NewRemoteExecutionEnv(options RemoteExecutionEnvOptions) *RemoteExecutionEnv

NewRemoteExecutionEnv returns an environment over options.Connection.

func (*RemoteExecutionEnv) AbsolutePath

func (e *RemoteExecutionEnv) AbsolutePath(ctx context.Context, path string) (string, error)

AbsolutePath implements coding.FileSystem. As upstream's absolutePath, ctx only bounds the wait for the connection.

func (*RemoteExecutionEnv) AppendFile

func (e *RemoteExecutionEnv) AppendFile(ctx context.Context, path string, content []byte) error

AppendFile implements coding.FileSystem.

func (*RemoteExecutionEnv) CanonicalPath

func (e *RemoteExecutionEnv) CanonicalPath(ctx context.Context, path string) (string, error)

CanonicalPath implements coding.FileSystem.

func (*RemoteExecutionEnv) Cleanup

func (e *RemoteExecutionEnv) Cleanup() error

Cleanup implements coding.Shell: it kills every command this environment still runs, without aborting them, so they settle with their killed status, as NodeExecutionEnv does.

func (*RemoteExecutionEnv) Connection

func (e *RemoteExecutionEnv) Connection() *Connection

Connection is the environment's connection.

func (*RemoteExecutionEnv) CreateDir

func (e *RemoteExecutionEnv) CreateDir(ctx context.Context, path string, options *CreateDirOptions) error

CreateDir creates a directory.

func (*RemoteExecutionEnv) CreateTempDir

func (e *RemoteExecutionEnv) CreateTempDir(ctx context.Context, prefix string) (string, error)

CreateTempDir creates a directory in the remote temporary directory; an empty prefix is "tmp-".

func (*RemoteExecutionEnv) CreateTempFile

func (e *RemoteExecutionEnv) CreateTempFile(ctx context.Context, options *TempFileOptions) (string, error)

CreateTempFile creates an empty file in a new temporary directory.

func (*RemoteExecutionEnv) Cwd

func (e *RemoteExecutionEnv) Cwd() string

Cwd implements coding.FileSystem.

func (*RemoteExecutionEnv) Exec

Exec implements coding.Shell: the command runs through the environment's shell, its output streams to OnStdout and OnStderr and is collected per stream, and a non-zero exit is a result. Failures are *ExecutionError.

func (*RemoteExecutionEnv) Exists

func (e *RemoteExecutionEnv) Exists(ctx context.Context, path string) (bool, error)

Exists implements coding.FileSystem.

func (*RemoteExecutionEnv) FlushFile

func (e *RemoteExecutionEnv) FlushFile(ctx context.Context, path string) error

FlushFile flushes a file's contents and the metadata needed to retrieve them.

func (*RemoteExecutionEnv) ID

func (e *RemoteExecutionEnv) ID() string

ID is the file namespace (FileSystem.id).

func (*RemoteExecutionEnv) JoinPath

func (e *RemoteExecutionEnv) JoinPath(_ context.Context, parts []string) (string, error)

JoinPath implements coding.FileSystem. As upstream's joinPath, it does not look at ctx.

func (*RemoteExecutionEnv) ListDir

func (e *RemoteExecutionEnv) ListDir(ctx context.Context, path string) ([]coding.FileInfo, error)

ListDir implements coding.FileSystem.

func (*RemoteExecutionEnv) ListFiles

func (e *RemoteExecutionEnv) ListFiles(ctx context.Context, path string, options *ListFilesOptions) (FileListing, error)

ListFiles lists the tree below a directory through the daemon; it fails with not_supported with a daemon released before listFiles, so callers fall back to their own walk.

func (*RemoteExecutionEnv) OpenBinaryReader

func (e *RemoteExecutionEnv) OpenBinaryReader(ctx context.Context, path string, options *BinaryReaderOptions) (BinaryReader, error)

OpenBinaryReader opens a regular file for bounded positional reads. A directory fails with is_directory, other non-regular files with invalid.

func (*RemoteExecutionEnv) OpenDirReader

func (e *RemoteExecutionEnv) OpenDirReader(ctx context.Context, path string) (DirReader, error)

OpenDirReader opens a directory for paged reading.

func (*RemoteExecutionEnv) OpenTextLineReader

func (e *RemoteExecutionEnv) OpenTextLineReader(ctx context.Context, path string) (coding.TextLineReader, error)

OpenTextLineReader implements coding.FileSystem.

func (*RemoteExecutionEnv) ReadBinaryFile

func (e *RemoteExecutionEnv) ReadBinaryFile(ctx context.Context, path string) ([]byte, error)

ReadBinaryFile implements coding.FileSystem.

func (*RemoteExecutionEnv) ReadTextFile

func (e *RemoteExecutionEnv) ReadTextFile(ctx context.Context, path string) (string, error)

ReadTextFile implements coding.FileSystem.

func (*RemoteExecutionEnv) ReadTextLines

func (e *RemoteExecutionEnv) ReadTextLines(ctx context.Context, path string, maxLines int) ([]string, error)

ReadTextLines implements coding.FileSystem: maxLines of 0 or less reads every line.

func (*RemoteExecutionEnv) Remove

func (e *RemoteExecutionEnv) Remove(ctx context.Context, path string, options *RemoveOptions) error

Remove removes a file or directory.

func (*RemoteExecutionEnv) RenameFile

func (e *RemoteExecutionEnv) RenameFile(ctx context.Context, sourcePath, destinationPath string) error

RenameFile implements coding.FileSystem.

func (*RemoteExecutionEnv) RunProgram

func (e *RemoteExecutionEnv) RunProgram(ctx context.Context, argv []string, options *RunOptions) (RunResult, error)

RunProgram runs argv[0] with the rest as its arguments, without a shell, so they reach the program unparsed (Durable's exec of an array).

func (*RemoteExecutionEnv) RunShell

func (e *RemoteExecutionEnv) RunShell(ctx context.Context, command string, options *RunOptions) (RunResult, error)

RunShell runs command through the environment's shell (Durable's exec of a string). Ending ctx or the timeout kills only this command's processes.

func (*RemoteExecutionEnv) SetCwd

func (e *RemoteExecutionEnv) SetCwd(cwd string)

SetCwd changes the working directory relative paths resolve against.

func (*RemoteExecutionEnv) Stat

Stat implements coding.FileSystem (Durable's fileInfo).

func (*RemoteExecutionEnv) TruncateFile

func (e *RemoteExecutionEnv) TruncateFile(ctx context.Context, path string, size int64) error

TruncateFile truncates or extends a file to exactly size bytes.

func (*RemoteExecutionEnv) Watch

func (e *RemoteExecutionEnv) Watch(ctx context.Context, targets []WatchTarget, onChange func(FileChange)) (*RemoteWatcher, error)

Watch reports changes to files and directories. When it returns, coverage is established: a host that watches before it loads cannot miss a change made during the load.

func (*RemoteExecutionEnv) WriteFile

func (e *RemoteExecutionEnv) WriteFile(ctx context.Context, path string, content []byte) error

WriteFile implements coding.FileSystem.

type RemoteExecutionEnvOptions

type RemoteExecutionEnvOptions struct {
	Connection *Connection
	// ID is the file namespace: equal ids see the same files, e.g.
	// "pi-env:<env name>".
	ID  string
	Cwd string
	// ShellPath is the shell string commands run with; empty is the daemon's
	// default.
	ShellPath string
	// ShellEnv is added to the remote environment of every command that
	// inherits it, like NodeExecutionEnv's shellEnv.
	ShellEnv map[string]string
	// Watch is how the daemon watches, like NodeExecutionEnv's watch option.
	Watch RemoteWatchOptions
}

RemoteExecutionEnvOptions configure a RemoteExecutionEnv.

type RemoteInfo

type RemoteInfo struct {
	Protocol int    `json:"protocol"`
	Version  string `json:"version"`
	OS       string `json:"os"`
	Arch     string `json:"arch"`
	Home     string `json:"home"`
	Tmpdir   string `json:"tmpdir"`
	// Separator is "/", or "\" on Windows.
	Separator string `json:"separator"`
	// Cwd is the daemon's working directory, where Node's path.resolve would
	// fall back to process.cwd().
	Cwd string `json:"cwd"`
	// DriveCwds are Windows' per-drive working directories (C: → C:\work)
	// of the =C: variables.
	DriveCwds map[string]string `json:"driveCwds"`
	PID       int               `json:"pid"`
	// Features are operations added to protocol 1 that this daemon supports,
	// such as listFiles; nil from older daemons.
	Features []string `json:"features,omitempty"`
}

RemoteInfo is what hello reports about the remote machine.

type RemotePlatform

type RemotePlatform struct {
	// Platform is linux, android, darwin or windows.
	Platform string
	// Arch is x64 or arm64.
	Arch string
	// Home is the remote home directory, in the remote system's own spelling.
	Home string
	// Shell is, on Windows, the shell sshd runs commands with (DefaultShell):
	// cmd or powershell.
	Shell string
	// Warnings are problems worth telling the owner about, such as Termux
	// without termux-exec.
	Warnings []string
}

RemotePlatform is a remote system pi-env ships a daemon for.

func DetectPlatform

func DetectPlatform(ctx context.Context, target SSHTarget) (RemotePlatform, error)

DetectPlatform finds which system the target runs: uname through the login shell, or PowerShell on Windows.

type RemoteProcess added in v1.5.29

type RemoteProcess struct {
	// PID is the program's process id.
	PID int
	// contains filtered or unexported fields
}

RemoteProcess is a program running with plain pipes in a pi-env daemon, for programs that speak a protocol on stdin and stdout, such as an MCP server. It ends when the program exits, Close kills it, or the connection is lost (the daemon then kills it). When the program exits, the daemon kills whatever it started in its process group, so a wrapper such as npx that exits leaves nothing running.

func OpenProcess added in v1.5.29

func OpenProcess(ctx context.Context, connection *Connection, options ProcessOptions) (*RemoteProcess, error)

OpenProcess starts a program with plain pipes in the daemon behind connection. It returns once the program started; ending ctx before then kills it. It fails with not_supported when the daemon was released before the process operation.

func (*RemoteProcess) Close added in v1.5.29

func (p *RemoteProcess) Close()

Close kills the program and its process group.

func (*RemoteProcess) CloseStdin added in v1.5.29

func (p *RemoteProcess) CloseStdin()

CloseStdin closes the program's stdin after the input written before it.

func (*RemoteProcess) Done added in v1.5.29

func (p *RemoteProcess) Done() <-chan struct{}

Done is closed once the program has ended.

func (*RemoteProcess) Wait added in v1.5.29

func (p *RemoteProcess) Wait() (int, error)

Wait waits for the program to end and returns its exit code; it fails with the daemon's error, with code aborted after Close.

func (*RemoteProcess) Write added in v1.5.29

func (p *RemoteProcess) Write(data []byte)

Write writes to the program's stdin, in order across calls; once stdin is closed or the program has ended, input is dropped.

type RemoteTerminal

type RemoteTerminal struct {
	// PID is the program's process id.
	PID int
	// contains filtered or unexported fields
}

RemoteTerminal is a program running in a pseudo-terminal of a pi-env daemon. It ends when the program exits, Close kills it, or the connection is lost (the daemon then kills it).

func OpenTerminal

func OpenTerminal(ctx context.Context, connection *Connection, options TerminalOptions) (*RemoteTerminal, error)

OpenTerminal starts a program in a new pseudo-terminal of the daemon behind connection. It returns once the program started; ending ctx before then kills it.

func (*RemoteTerminal) Close

func (t *RemoteTerminal) Close()

Close kills the program and everything in its session.

func (*RemoteTerminal) Done

func (t *RemoteTerminal) Done() <-chan struct{}

Done is closed once the terminal has ended.

func (*RemoteTerminal) Foreground

func (t *RemoteTerminal) Foreground(ctx context.Context) (*TerminalForeground, error)

Foreground is the job in the terminal's foreground when it is not the program itself: what a shell runs, such as an editor. It is nil while the program is in front (a shell at its prompt), and fails once the terminal has ended.

func (*RemoteTerminal) Resize

func (t *RemoteTerminal) Resize(cols, rows int)

Resize changes the size; the program receives SIGWINCH.

func (*RemoteTerminal) Wait

func (t *RemoteTerminal) Wait() (int, error)

Wait waits for the program to end and returns its exit code; it fails with the daemon's error, with code aborted after Close.

func (*RemoteTerminal) Write

func (t *RemoteTerminal) Write(data []byte)

Write sends input; once the terminal has ended, input is dropped. Input keeps its order across calls.

type RemoteWatchOptions

type RemoteWatchOptions struct {
	// Mode forces "native" or "polling"; by default Windows and file systems
	// that do not report remote changes poll.
	Mode string `json:"mode,omitempty"`
	// PollIntervalMS is the interval between snapshots in polling mode;
	// 0 is 2000 ms.
	PollIntervalMS int64 `json:"pollIntervalMs,omitempty"`
	// MaxDirectories is the most directories one watcher covers; 0 is
	// 10 000.
	MaxDirectories int64 `json:"maxDirectories,omitempty"`
}

RemoteWatchOptions say how the daemon watches, like NodeExecutionEnv's NodeWatchOptions.

type RemoteWatcher

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

RemoteWatcher is a watcher running in the daemon (Durable's NodeFileWatcher next to the files). When the connection is lost, it is opened again once the connection can be started again, and reports an overflow: changes in between were not seen.

func OpenRemoteWatcher

func OpenRemoteWatcher(connection *Connection, targets []WatchTarget, onChange func(FileChange), options RemoteWatchOptions) (*RemoteWatcher, error)

OpenRemoteWatcher watches targets (resolved paths); it fails like NodeFileWatcher.open if coverage cannot be established. onChange receives one change at a time, in order, on a goroutine of the watcher's own (as upstream's callbacks run on one thread); it may call Stop.

func (*RemoteWatcher) Mode

func (w *RemoteWatcher) Mode() string

Mode is "native" (changes are reported within about two seconds) or "polling" (the daemon compares snapshots, because the file system does not report changes reliably).

func (*RemoteWatcher) Stop added in v1.5.29

func (w *RemoteWatcher) Stop()

Stop stops watching and waits for the daemon's watch to end; no onChange call starts after it returns. Called from onChange, it does not wait for that call, as upstream's stop() inside the callback returns at once. It is idempotent.

type RemoveOptions

type RemoveOptions struct {
	Recursive bool
	Force     bool
}

RemoveOptions are Remove's options.

type Reply

type Reply struct {
	JSON    json.RawMessage
	Payload []byte
	// Session is the daemon session that answered; handles from it are only
	// valid while it lives.
	Session int
}

Reply is the daemon's result of a request.

type RequestOptions

type RequestOptions struct {
	Payload []byte
	// OnEvent receives the request's progress events, such as exec output,
	// in order, on the goroutine that waits for the request.
	OnEvent func(json json.RawMessage, payload []byte)
	// OnStart receives the request's id and session, for Kill.
	OnStart func(id uint32, session int)
	// Session, when not zero, runs the request only in this daemon session,
	// for requests on handles it opened. After the connection was lost and
	// started again, such requests fail instead of reaching a daemon that
	// never opened the handle.
	Session int
}

RequestOptions are the optional parts of a request.

type RunOptions

type RunOptions struct {
	// Cwd is the working directory; empty is the environment's.
	Cwd string
	Env map[string]string
	// InheritEnv inherits the daemon's environment and ShellEnv; nil is
	// true.
	InheritEnv *bool
	// Timeout in seconds; 0 is none. It must be finite, positive and at most
	// 2147483.647.
	Timeout float64
	// OnOutput receives every decoded chunk of stdout and stderr as it
	// arrives, in arrival order, with the stream it came from. An error
	// fails the command with callback_error and aborts it.
	OnOutput func(text string, info OutputInfo) error
	// Spill spills the complete output to a temporary file once it exceeds
	// either threshold.
	Spill *SpillOptions
	// Window is the tail of the output the caller keeps, so the daemon may
	// omit output outside it (OutputInfo.Skipped).
	Window *OutputWindow
}

RunOptions are the options of RunShell and RunProgram (Durable's ShellExecOptions).

type RunResult

type RunResult struct {
	ExitCode int
	// SpillPath is the temporary file holding the complete raw output, when
	// the spill thresholds were exceeded.
	SpillPath string
}

RunResult is a finished command.

type SSHConnectOptions

type SSHConnectOptions struct {
	SSHTarget
	// Binary is a daemon file to deploy; empty is the embedded daemon for
	// the remote system.
	Binary string
	// LoginShell starts the daemon (POSIX) through the user's login shell
	// ($SHELL -l), so commands see the environment of ~/.profile and similar
	// files. Off by default: ssh runs commands without a login shell.
	LoginShell bool
	OnLog      func(text string)
}

SSHConnectOptions are the options of SSHConnection and ConnectSSH: the target, plus the daemon to deploy.

type SSHError

type SSHError struct {
	Message  string
	ExitCode *int
	Stderr   string
}

SSHError is an ssh invocation that failed for another reason, with its exit code (nil when it did not exit on its own) and diagnostics.

func (*SSHError) Error

func (e *SSHError) Error() string

type SSHTarget

type SSHTarget struct {
	// Host is a host name or ~/.ssh/config alias.
	Host string
	// User, Port and IdentityFile are left to ssh when empty or zero.
	User         string
	Port         int
	IdentityFile string
	// KnownHostsFile holds the host keys this application trusts;
	// AcceptHostKey adds to it.
	KnownHostsFile string
	// HostKeyAlias is the name keys are stored under, independent of aliases,
	// ports and jump hosts, e.g. "pi-env-<env name>".
	HostKeyAlias string
	// SSH is the ssh program; empty is "ssh".
	SSH string
	// ConfigFile is an ssh configuration file to use instead of
	// ~/.ssh/config (-F).
	ConfigFile string
}

SSHTarget says how to reach a machine with the system ssh.

type SpillOptions

type SpillOptions struct {
	AfterBytes int64 `json:"afterBytes"`
	// AfterLines counts complete or partial lines.
	AfterLines int64 `json:"afterLines"`
}

SpillOptions are the spill thresholds of a command's output.

type TempFileOptions

type TempFileOptions struct {
	Prefix string
	Suffix string
}

TempFileOptions are CreateTempFile's options.

type TerminalForeground

type TerminalForeground struct {
	PID  int
	Name string
}

TerminalForeground is the foreground job of a terminal: its process group id, and its leader's name if the system tells.

type TerminalOptions

type TerminalOptions struct {
	// Cwd is the working directory of the program; it must exist.
	Cwd string
	// Argv is the program and its arguments; nil is the user's shell (SHELL
	// in Env or the daemon's environment) as a login shell.
	Argv []string
	// Env is added to the daemon's environment, or is the whole environment
	// with InheritEnv false. Set TERM here.
	Env map[string]string
	// InheritEnv nil is the daemon's default (true).
	InheritEnv *bool
	Cols       int
	Rows       int
	// OnData receives the terminal's raw output, in order, from one
	// goroutine.
	OnData func(data []byte)
}

TerminalOptions configure OpenTerminal.

type WatchExclude

type WatchExclude struct {
	// Hidden leaves out names starting with ".".
	Hidden bool
	Names  []string
}

WatchExclude is what a WatchTarget leaves out.

type WatchTarget

type WatchTarget struct {
	Path string
	// Recursive watches everything below a directory, not only its entries.
	// Symbolic links below it are not followed.
	Recursive bool
	// Exclude names entries below Path that are neither watched nor
	// reported.
	Exclude WatchExclude
}

WatchTarget is a file or directory to watch (Durable's WatchTarget). It may be missing; creating it is a change.

Directories

Path Synopsis
cmd
pi-env command
Command pi-env is the pi-env daemon: `pi-env serve --token <hex>` speaks the protocol of docs/protocol.md on stdin and stdout.
Command pi-env is the pi-env daemon: `pi-env serve --token <hex>` speaks the protocol of docs/protocol.md on stdin and stdout.
Package daemon is pi-env, a small daemon that gives a Pi Durable host an execution environment on this machine over stdin and stdout (docs/protocol.md).
Package daemon is pi-env, a small daemon that gives a Pi Durable host an execution environment on this machine over stdin and stdout (docs/protocol.md).
internal
daemonsource
Package daemonsource builds the pi-env daemons the env package embeds (env/bin) and fingerprints the source they are built from, for the generator (internal/gendaemons) and for the test that fails when the embedded daemons are stale.
Package daemonsource builds the pi-env daemons the env package embeds (env/bin) and fingerprints the source they are built from, for the generator (internal/gendaemons) and for the test that fails when the embedded daemons are stale.
frame
Package frame is pi-env's wire framing (docs/protocol.md "Frames"), shared by the daemon and its client:
Package frame is pi-env's wire framing (docs/protocol.md "Frames"), shared by the daemon and its client:
gendaemons command
Command gendaemons builds the eight pi-env daemons and writes them, compressed, to env/bin with their manifest, for the env package to embed.
Command gendaemons builds the eight pi-env daemons and writes them, compressed, to env/bin with their manifest, for the env package to embed.
nodepath
Package nodepath is Node's path module for both of its flavours, path.posix and path.win32, and url.fileURLToPath, independent of the system this program runs on: the pi-env client resolves paths by the rules of the remote system, as upstream's RemoteExecutionEnv does with Node's `posix` and `win32` objects.
Package nodepath is Node's path module for both of its flavours, path.posix and path.win32, and url.fileURLToPath, independent of the system this program runs on: the pi-env client resolves paths by the rules of the remote system, as upstream's RemoteExecutionEnv does with Node's `posix` and `win32` objects.

Jump to

Keyboard shortcuts

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