exec

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 18 Imported by: 2 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 exec provides readymade tools for executing commands and shell scripts, including managed background processes.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrProcessNotFound is returned when a process ID is not tracked by the
	// manager.
	ErrProcessNotFound = errors.New("exec: process not found")
	// ErrProcessLimit is returned when the manager has no room for another
	// running process.
	ErrProcessLimit = errors.New("exec: process limit reached")
	// ErrManagerClosed is returned after Manager.Close has been called.
	ErrManagerClosed = errors.New("exec: manager closed")
	// ErrCommandRequired is returned when a start request has no command.
	ErrCommandRequired = errors.New("exec: command is required")
	// ErrWorkingDirOutsideBase is returned when a requested working directory
	// escapes the configured base directory.
	ErrWorkingDirOutsideBase = errors.New("exec: working directory is outside the base directory")
	// ErrInvalidSignal is returned for an unsupported signal name.
	ErrInvalidSignal = errors.New("exec: invalid signal")
)

Functions

func NewExecuteCommandTool

func NewExecuteCommandTool(cfg ...Config) (tool.Tool, error)

NewExecuteCommandTool creates a foreground-only Tool for executing system commands. For background processes, auto-promotion, and the companion process tools, use NewManager and NewTools instead.

Types

type Chunk added in v0.2.0

type Chunk struct {
	ProcessID    string        `json:"process_id"`
	Output       string        `json:"output"`
	NextCursor   int64         `json:"next_cursor"`
	HasMore      bool          `json:"has_more,omitempty"`
	Truncated    bool          `json:"truncated,omitempty"`
	OmittedBytes int64         `json:"omitted_bytes,omitempty"`
	CursorReset  bool          `json:"cursor_reset,omitempty"`
	Status       ProcessStatus `json:"status"`
	ExitCode     *int          `json:"exit_code,omitempty"`
	Signal       string        `json:"signal,omitempty"`
	ObservedAt   time.Time     `json:"observed_at"`
	Note         string        `json:"note,omitempty"`
}

Chunk is a bounded read from a process's combined output.

type CommandInput

type CommandInput struct {
	Command        string `json:"command" description:"The command line string to execute"`
	WorkingDir     string `json:"working_dir,omitempty" description:"Optional working directory for the command"`
	TimeoutSeconds int    `json:"timeout_seconds,omitempty" description:"Optional execution timeout in seconds (default 30, max 300)"`
}

CommandInput defines the input parameters for executing a shell command.

type CommandOutput

type CommandOutput struct {
	Stdout   string `json:"stdout"`
	Stderr   string `json:"stderr"`
	ExitCode int    `json:"exit_code"`
	TimedOut bool   `json:"timed_out"`
}

CommandOutput represents the execution result.

type Config

type Config struct {
	BaseDir        string
	DefaultTimeout time.Duration
	MaxOutputBytes int
}

Config configures the command execution tool.

type ExecuteInput added in v0.2.0

type ExecuteInput struct {
	Command           string `json:"command" description:"The command line string to execute"`
	WorkingDir        string `json:"working_dir,omitempty" description:"Optional working directory for the command"`
	TimeoutSeconds    int    `` /* 130-byte string literal not displayed */
	Background        bool   `json:"background,omitempty" description:"Start the command in the background and return a process_id immediately"`
	MaxRuntimeSeconds int    `json:"max_runtime_seconds,omitempty" description:"Optional hard lifetime cap for a managed process (default 1800, max 7200)"`
}

ExecuteInput defines the input parameters for executing a shell command.

type ExecuteResult added in v0.2.0

type ExecuteResult struct {
	Mode            string        `json:"mode"` // foreground or background
	Status          ProcessStatus `json:"status"`
	ProcessID       string        `json:"process_id,omitempty"`
	PID             int           `json:"pid,omitempty"`
	Stdout          string        `json:"stdout,omitempty"`
	Stderr          string        `json:"stderr,omitempty"`
	StdoutTruncated bool          `json:"stdout_truncated,omitempty"`
	StderrTruncated bool          `json:"stderr_truncated,omitempty"`
	ExitCode        *int          `json:"exit_code,omitempty"`
	Signal          string        `json:"signal,omitempty"`
	StoppedBy       string        `json:"stopped_by,omitempty"`
	DurationMS      int64         `json:"duration_ms"`
	ObservedAt      time.Time     `json:"observed_at"`
	Promoted        bool          `json:"promoted,omitempty"`
	TimedOut        bool          `json:"timed_out,omitempty"`
	Truncated       bool          `json:"truncated,omitempty"`
	OmittedBytes    int64         `json:"omitted_bytes,omitempty"`
	NextCursor      int64         `json:"next_cursor,omitempty"`
	Note            string        `json:"note,omitempty"`
}

ExecuteResult is the tool result returned after a command starts, finishes, or is promoted to the background. It is a snapshot, not live state.

type KillProcessInput added in v0.2.0

type KillProcessInput struct {
	ProcessID    string `json:"process_id" description:"Process ID returned by execute_command"`
	Signal       string `json:"signal,omitempty" description:"TERM (default), INT, or KILL"`
	GraceSeconds int    `json:"grace_seconds,omitempty" description:"Seconds to wait after TERM before KILL (default 5, max 30)"`
}

KillProcessInput stops a tracked process.

type KillProcessOutput added in v0.2.0

type KillProcessOutput struct {
	Snapshot
	Confirmed     bool   `json:"confirmed"`
	AlreadyExited bool   `json:"already_exited,omitempty"`
	Note          string `json:"note,omitempty"`
}

KillProcessOutput reports the final state of a stop request.

type Manager added in v0.2.0

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

Manager owns the lifetime of background and foreground processes. It is safe for concurrent use and must be closed by its owner.

func NewManager added in v0.2.0

func NewManager(cfg ManagerConfig) (*Manager, error)

NewManager validates cfg and returns an empty manager.

func (*Manager) Close added in v0.2.0

func (m *Manager) Close(ctx context.Context) error

Close stops accepting starts, stops every tracked process, and waits for them to be reaped. It is safe to call more than once.

func (*Manager) Config added in v0.2.0

func (m *Manager) Config() ManagerConfig

Config returns a copy of the effective configuration.

func (*Manager) Kill added in v0.2.0

func (m *Manager) Kill(ctx context.Context, id string, sig Signal, grace time.Duration) (Snapshot, bool, error)

Kill stops a process and its process group. confirmed is false when the stop was requested but the manager could not observe the exit in time.

func (*Manager) List added in v0.2.0

func (m *Manager) List() []Snapshot

List returns snapshots of all tracked processes, oldest first.

func (*Manager) Promote added in v0.2.0

func (m *Manager) Promote(id string) (Snapshot, error)

Promote marks a foreground process as promoted after its wait window expired.

func (*Manager) Read added in v0.2.0

func (m *Manager) Read(ctx context.Context, id string, cursor int64, maxBytes int, wait time.Duration) (Chunk, error)

Read returns a bounded chunk of combined output. When wait is positive and no output is available at cursor, it waits for new output, process exit, or the timeout.

func (*Manager) Start added in v0.2.0

func (m *Manager) Start(ctx context.Context, spec Spec) (Snapshot, error)

Start launches a process. Once started, the process is owned by the manager and is not tied to ctx; use Kill, its lifetime cap, or Close to stop it.

func (*Manager) Status added in v0.2.0

func (m *Manager) Status(id string) (Snapshot, error)

Status returns a snapshot of one process.

func (*Manager) Streams added in v0.2.0

func (m *Manager) Streams(id string, maxBytes int) (StreamOutput, error)

Streams returns bounded stdout and stderr snapshots for the execute result.

func (*Manager) Tail added in v0.2.0

func (m *Manager) Tail(ctx context.Context, id string, lines, maxBytes int, wait time.Duration) (Chunk, error)

Tail returns the last lines of combined output, capped at maxBytes. When the process has produced nothing yet and wait is positive, it waits for output, exit, or the timeout.

func (*Manager) Wait added in v0.2.0

func (m *Manager) Wait(ctx context.Context, id string, d time.Duration) (Snapshot, bool, error)

Wait waits until the process exits or d elapses. stillRunning is true when the wait window expired or ctx was canceled.

type ManagerConfig added in v0.2.0

type ManagerConfig struct {
	// BaseDir bounds working directories when set. It is not a sandbox:
	// commands still run with the host user's permissions.
	BaseDir string
	// AdditionalDirs are extra roots that working directories may use
	// alongside BaseDir. Containment compares symlink-resolved paths, so a
	// path or symlink must resolve inside BaseDir or one of these directories.
	// They also enforce containment when BaseDir is empty.
	AdditionalDirs []string
	// Observer receives live process lifecycle and stdout/stderr events. It is
	// optional; nil disables observation.
	Observer ProcessObserver
	// MaxProcesses is the number of concurrently running processes.
	MaxProcesses int
	// MaxFinished is the number of finished process records retained for late
	// reads.
	MaxFinished int
	// BufferBytes bounds the combined output retained per process.
	BufferBytes int
	// StreamBytes bounds the separately retained stdout and stderr per
	// process.
	StreamBytes int
	// MaxReadBytes caps one process read.
	MaxReadBytes int
	// ExecuteBytes caps each of stdout and stderr returned by
	// execute_command.
	ExecuteBytes int
	// DefaultWait is the default foreground wait before promotion.
	DefaultWait time.Duration
	// MaxWait caps the foreground wait.
	MaxWait time.Duration
	// DefaultLifetime is the default hard lifetime for a managed process.
	DefaultLifetime time.Duration
	// MaxLifetime caps a requested lifetime.
	MaxLifetime time.Duration
	// KillGrace is the time between TERM and KILL.
	KillGrace time.Duration
	// WaitDelay bounds how long Wait blocks for inherited output pipes.
	WaitDelay time.Duration
	// ReadinessDelay is the short wait after a background start that catches
	// immediate failures.
	ReadinessDelay time.Duration
}

ManagerConfig configures a process manager. Zero values use conservative defaults; the manager never uses package globals.

type ProcessEvent added in v0.3.0

type ProcessEvent struct {
	Kind       ProcessEventKind `json:"kind"`
	ProcessID  string           `json:"process_id"`
	Stream     ProcessStream    `json:"stream,omitempty"`
	Data       []byte           `json:"data,omitempty"`
	Snapshot   *Snapshot        `json:"snapshot,omitempty"`
	ObservedAt time.Time        `json:"observed_at"`
}

ProcessEvent is a live lifecycle or output notification for a managed process. Start and exit events carry a snapshot; output events carry a copy of the chunk in Data, so observers may retain or modify it without affecting buffered reads.

type ProcessEventKind added in v0.3.0

type ProcessEventKind string

ProcessEventKind identifies a live process lifecycle event.

const (
	// ProcessEventStart reports that a managed process started.
	ProcessEventStart ProcessEventKind = "start"
	// ProcessEventOutput reports a live stdout or stderr chunk.
	ProcessEventOutput ProcessEventKind = "output"
	// ProcessEventExit reports the final state of a reaped process.
	ProcessEventExit ProcessEventKind = "exit"
)

type ProcessKind added in v0.2.0

type ProcessKind string

ProcessKind describes why a process is tracked.

const (
	// ProcessForeground is a command that has not outlived its wait window.
	ProcessForeground ProcessKind = "foreground"
	// ProcessBackground is a command started with background=true.
	ProcessBackground ProcessKind = "background"
	// ProcessPromoted is a foreground command that outlived its wait window.
	ProcessPromoted ProcessKind = "promoted"
)

type ProcessObserver added in v0.3.0

type ProcessObserver func(ProcessEvent)

ProcessObserver receives live process events synchronously as output is written and as a process is reaped. It runs on the process output path, so it should return promptly and must not call Manager.Close, Manager.Kill, or Manager.Wait. A panic is recovered and cannot break buffering, reaping, or manager shutdown.

type ProcessStatus added in v0.2.0

type ProcessStatus string

ProcessStatus is the lifecycle state of a managed process.

const (
	// ProcessRunning means the process has started and has not been reaped.
	ProcessRunning ProcessStatus = "running"
	// ProcessExited means the process exited with code 0.
	ProcessExited ProcessStatus = "exited"
	// ProcessFailed means the process exited with a non-zero code or could not
	// be waited on successfully.
	ProcessFailed ProcessStatus = "failed"
	// ProcessKilled means the process was terminated by a signal or by a stop
	// request.
	ProcessKilled ProcessStatus = "killed"
)

type ProcessStatusInput added in v0.2.0

type ProcessStatusInput struct {
	ProcessID       string `json:"process_id,omitempty" description:"Process ID to inspect; omit to list running processes"`
	IncludeFinished bool   `json:"include_finished,omitempty" description:"Include recently finished processes in a list"`
}

ProcessStatusInput selects one process or lists tracked processes.

type ProcessStatusOutput added in v0.2.0

type ProcessStatusOutput struct {
	Process   *Snapshot  `json:"process,omitempty"`
	Processes []Snapshot `json:"processes,omitempty"`
	Total     int        `json:"total"`
}

ProcessStatusOutput is either one process or a list of processes.

type ProcessStream added in v0.3.0

type ProcessStream string

ProcessStream identifies the output stream of an output event.

const (
	// ProcessStdout is standard output.
	ProcessStdout ProcessStream = "stdout"
	// ProcessStderr is standard error.
	ProcessStderr ProcessStream = "stderr"
)

type ReadProcessInput added in v0.2.0

type ReadProcessInput struct {
	ProcessID   string `json:"process_id" description:"Process ID returned by execute_command"`
	Cursor      *int64 `json:"cursor,omitempty" description:"Byte cursor from a previous next_cursor; returns only newer output"`
	Lines       int    `json:"lines,omitempty" description:"Number of trailing lines to return when cursor is omitted (default 100, max 1000)"`
	MaxBytes    int    `json:"max_bytes,omitempty" description:"Maximum bytes to return (default 16384, max 65536)"`
	WaitSeconds int    `json:"wait_seconds,omitempty" description:"Wait up to this many seconds for new output (max 30)"`
}

ReadProcessInput reads bounded output from a managed process.

type Signal added in v0.2.0

type Signal string

Signal is the portable subset of signals accepted by Kill.

const (
	// SignalTerm requests a graceful stop.
	SignalTerm Signal = "TERM"
	// SignalInt requests an interrupt.
	SignalInt Signal = "INT"
	// SignalKill requests an immediate stop.
	SignalKill Signal = "KILL"
)

type Snapshot added in v0.2.0

type Snapshot struct {
	ProcessID    string        `json:"process_id"`
	PID          int           `json:"pid,omitempty"`
	Command      string        `json:"command,omitempty"`
	WorkingDir   string        `json:"working_dir,omitempty"`
	Kind         ProcessKind   `json:"kind"`
	Status       ProcessStatus `json:"status"`
	StartedAt    time.Time     `json:"started_at"`
	ObservedAt   time.Time     `json:"observed_at"`
	DurationMS   int64         `json:"duration_ms"`
	ExitCode     *int          `json:"exit_code,omitempty"`
	Signal       string        `json:"signal,omitempty"`
	StoppedBy    string        `json:"stopped_by,omitempty"`
	StdoutBytes  int64         `json:"stdout_bytes,omitempty"`
	StderrBytes  int64         `json:"stderr_bytes,omitempty"`
	OmittedBytes int64         `json:"omitted_bytes,omitempty"`
	LastOutputAt *time.Time    `json:"last_output_at,omitempty"`
	NextCursor   int64         `json:"next_cursor,omitempty"`
	Tail         string        `json:"tail,omitempty"`
	Error        string        `json:"error,omitempty"`
}

Snapshot is a point-in-time view of a managed process. Tool results embed snapshots; they are observations, not live state.

type Spec added in v0.2.0

type Spec struct {
	Command    string
	WorkingDir string
	Kind       ProcessKind
	MaxRuntime time.Duration
}

Spec describes one process start.

type StreamOutput added in v0.2.0

type StreamOutput struct {
	Stdout          string
	Stderr          string
	StdoutTruncated bool
	StderrTruncated bool
	StdoutOmitted   int64
	StderrOmitted   int64
	NextCursor      int64
}

StreamOutput is a bounded snapshot of stdout and stderr separately. It is used by the execute result, while later reads use the combined Chunk.

type Tools added in v0.2.0

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

Tools bundles the execute and process-management tools that share one manager.

func NewTools added in v0.2.0

func NewTools(m *Manager) (*Tools, error)

NewTools builds the execute and process-management tools around m. The caller owns m and should call Tools.Close when finished. The returned execute_command tool uses the managed process lifecycle; do not register it alongside NewExecuteCommandTool, which uses the same tool ID.

func (*Tools) All added in v0.2.0

func (t *Tools) All() []tool.Tool

All returns the tool set in a stable order.

func (*Tools) Close added in v0.2.0

func (t *Tools) Close(ctx context.Context) error

Close stops all managed processes and releases the tool set.

func (*Tools) Manager added in v0.2.0

func (t *Tools) Manager() *Manager

Manager returns the manager shared by the tools.

type WaitProcessInput added in v0.2.0

type WaitProcessInput struct {
	ProcessID      string `json:"process_id" description:"Process ID returned by execute_command"`
	TimeoutSeconds int    `json:"timeout_seconds,omitempty" description:"Wait budget in seconds (default 30, max 60)"`
	Cursor         *int64 `json:"cursor,omitempty" description:"Optional cursor to return only newer output"`
	MaxBytes       int    `json:"max_bytes,omitempty" description:"Maximum bytes to return (default 16384, max 65536)"`
}

WaitProcessInput waits for a process to exit or for a bounded timeout.

type WaitProcessOutput added in v0.2.0

type WaitProcessOutput struct {
	Chunk
	TimedOut   bool   `json:"timed_out,omitempty"`
	DurationMS int64  `json:"duration_ms"`
	Note       string `json:"note,omitempty"`
}

WaitProcessOutput is a process read plus whether the wait window expired.

Jump to

Keyboard shortcuts

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