exec

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildTools added in v0.7.0

func BuildTools(ex Executor, guardFns ...GuardFunc) []*agent.Tool

BuildTools creates exec agent tools backed by the given Executor. guardFns are command guard functions invoked before execution; if any returns a non-empty string the command is blocked.

func WithPolicy added in v0.7.0

func WithPolicy(pe *PolicyEvaluator) toolchain.Middleware

WithPolicy returns a Middleware that evaluates exec/exec_bg commands against the PolicyEvaluator before any other middleware (including approval). Block verdicts return BlockedResult without calling next. Observe verdicts log/publish then call next. Allow verdicts and non-exec tools pass through unchanged.

Types

type BackgroundProcess

type BackgroundProcess struct {
	ID        string
	Command   string
	Cmd       *exec.Cmd
	Output    *syncBuffer
	StartTime time.Time
	Done      bool
	ExitCode  int
	Error     string
}

BackgroundProcess represents a running background command

type BlockedResult added in v0.7.0

type BlockedResult struct {
	Blocked bool   `json:"blocked"`
	Message string `json:"message"`
}

BlockedResult is the structured response returned when a command is blocked by security guards (CLI guard, path guard, etc.).

type CommandGuard added in v0.6.0

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

CommandGuard checks shell commands for access to protected paths and dangerous process management operations.

func NewCommandGuard added in v0.6.0

func NewCommandGuard(protectedPaths []string) *CommandGuard

NewCommandGuard creates a CommandGuard that blocks commands targeting the given protected paths. Paths are resolved to absolute form at construction time.

func (*CommandGuard) CheckCommand added in v0.6.0

func (g *CommandGuard) CheckCommand(command string) (blocked bool, reason string)

CheckCommand returns true and a reason string if the command should be blocked. It checks for:

  1. Commands that access protected paths (sqlite3, cat, python, etc.)
  2. Process management commands (kill, pkill, killall)

type Config

type Config struct {
	DefaultTimeout   time.Duration
	AllowBackground  bool
	WorkDir          string
	EnvFilter        []string             // environment variables to exclude
	EnvWhitelist     []string             // if set, ONLY these vars are allowed
	Refs             *security.RefStore   // secret reference token resolver
	OSIsolator       sandboxos.OSIsolator // OS-level sandbox (nil = disabled)
	SandboxPolicy    sandboxos.Policy     // policy for sandboxed execution
	FailClosed       bool                 // if true, reject execution when sandbox unavailable
	ExcludedCommands []string             // command basenames that bypass the sandbox
	Bus              *eventbus.Bus        // event bus for SandboxDecisionEvent (optional)
}

Config holds exec tool configuration

type EventPublisher added in v0.7.0

type EventPublisher interface {
	Publish(event PolicyEvent)
}

EventPublisher is satisfied by *eventbus.Bus. Defined here to avoid importing eventbus from the exec package.

type Executor added in v0.7.0

type Executor interface {
	ExecuteTool(ctx context.Context, cmd string) (string, error)
	StartBackground(cmd string) (string, error)
	GetBackgroundStatus(id string) (map[string]interface{}, error)
	StopBackground(id string) error
}

Executor abstracts the supervisor methods used by exec tools. *supervisor.Supervisor satisfies this interface.

type GuardFunc added in v0.7.0

type GuardFunc func(cmd string) string

GuardFunc is a function that checks a command and returns a non-empty guidance message if the command should be blocked.

type Option added in v0.7.0

type Option func(*PolicyEvaluator)

Option configures optional PolicyEvaluator behavior.

func WithCatastrophicPatterns added in v0.7.0

func WithCatastrophicPatterns(patterns []string) Option

WithCatastrophicPatterns sets patterns that block commands before approval. Patterns are pre-lowercased and deduped, matching NewSecurityFilterHook semantics. Should be the same merged set used by SecurityFilterHook (DefaultBlockedPatterns + cfg.Hooks.BlockedCommands).

type PolicyDecision added in v0.7.0

type PolicyDecision struct {
	Verdict   Verdict
	Reason    ReasonCode
	Message   string
	Command   string
	Unwrapped string // inner command after shell wrapper unwrap (empty if no wrapper)
}

PolicyDecision is the structured result of evaluating a command.

type PolicyDecisionData added in v0.7.0

type PolicyDecisionData struct {
	Command    string
	Unwrapped  string
	Verdict    string
	Reason     string
	Message    string
	SessionKey string
	AgentName  string
}

PolicyDecisionData holds the fields for a policy decision event. Exported so that the policyBusAdapter in app can convert it to eventbus.PolicyDecisionEvent for SubscribeTyped compatibility.

func (PolicyDecisionData) EventName added in v0.7.0

func (e PolicyDecisionData) EventName() string

EventName implements PolicyEvent.

type PolicyEvaluator added in v0.7.0

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

PolicyEvaluator performs structured command policy evaluation with shell wrapper unwrapping and opaque pattern detection.

func NewPolicyEvaluator added in v0.7.0

func NewPolicyEvaluator(
	guard *CommandGuard,
	classifier func(cmd string) (string, ReasonCode),
	bus EventPublisher,
	opts ...Option,
) *PolicyEvaluator

NewPolicyEvaluator creates a PolicyEvaluator. safeVars is initialized from internal defaults. The bus may be nil to disable event publishing (respecting cfg.Hooks.EventPublishing gate).

func (*PolicyEvaluator) Evaluate added in v0.7.0

func (pe *PolicyEvaluator) Evaluate(cmd string) PolicyDecision

Evaluate performs the full policy check on a command string. It unwraps one level of shell wrapper, applies all existing checks to the inner command, and detects opaque patterns and shell constructs.

type PolicyEvent added in v0.7.0

type PolicyEvent interface {
	EventName() string
}

PolicyEvent is the minimal event interface expected by the publisher. Matches eventbus.Event without importing the eventbus package.

type ReasonCode added in v0.7.0

type ReasonCode string

ReasonCode provides machine-readable classification of the policy decision.

const (
	ReasonNone                ReasonCode = ""
	ReasonKillVerb            ReasonCode = "kill_verb"
	ReasonProtectedPath       ReasonCode = "protected_path"
	ReasonLangoCLI            ReasonCode = "lango_cli"
	ReasonSkillImport         ReasonCode = "skill_import"
	ReasonCmdSubstitution     ReasonCode = "cmd_substitution"
	ReasonUnsafeVarExpand     ReasonCode = "unsafe_var_expansion"
	ReasonEvalVerb            ReasonCode = "eval_verb"
	ReasonEncodedPipe         ReasonCode = "encoded_pipe"
	ReasonCatastrophicPattern ReasonCode = "catastrophic_pattern"
	ReasonHeredoc             ReasonCode = "heredoc"
	ReasonProcessSubst        ReasonCode = "process_substitution"
	ReasonGroupedSubshell     ReasonCode = "grouped_subshell"
	ReasonShellFunction       ReasonCode = "shell_function"
	ReasonXargsInner          ReasonCode = "xargs_inner"
	ReasonFindExecInner       ReasonCode = "find_exec_inner"
)

type Result

type Result struct {
	ExitCode int    `json:"exitCode"`
	Stdout   string `json:"stdout"`
	Stderr   string `json:"stderr"`
	TimedOut bool   `json:"timedOut,omitempty"`
}

Result represents command execution result

type Tool

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

Tool provides shell command execution

func New

func New(cfg Config) *Tool

New creates a new exec tool

func (*Tool) Cleanup

func (t *Tool) Cleanup()

Cleanup terminates all background processes

func (*Tool) GetBackgroundStatus

func (t *Tool) GetBackgroundStatus(id string) (*BackgroundProcess, error)

GetBackgroundStatus returns the status of a background process

func (*Tool) ListBackground

func (t *Tool) ListBackground() []*BackgroundProcess

ListBackground returns all background processes

func (*Tool) Run

func (t *Tool) Run(ctx context.Context, command string, timeout time.Duration) (*Result, error)

Run executes a command synchronously

func (*Tool) RunWithPTY

func (t *Tool) RunWithPTY(ctx context.Context, command string, timeout time.Duration) (*Result, error)

RunWithPTY executes a command with PTY support

func (*Tool) SetEventBus added in v0.7.0

func (t *Tool) SetEventBus(bus *eventbus.Bus)

SetEventBus attaches an event bus for SandboxDecisionEvent publishing. Wiring may call this after Tool construction once the bus is available. Passing nil disables publishing (PublishSandboxDecision is a no-op on nil).

func (*Tool) StartBackground

func (t *Tool) StartBackground(command string) (string, error)

StartBackground starts a command in the background

func (*Tool) StopBackground

func (t *Tool) StopBackground(id string) error

StopBackground stops a background process

type Verdict added in v0.7.0

type Verdict int

Verdict represents the policy evaluator's determination.

const (
	// VerdictAllow indicates the command is clearly safe to proceed.
	VerdictAllow Verdict = iota
	// VerdictObserve indicates the command has opaque elements; allow but flag for monitoring.
	VerdictObserve
	// VerdictBlock indicates the command must be blocked.
	VerdictBlock
)

func (Verdict) String added in v0.7.0

func (v Verdict) String() string

String returns the verdict as a lowercase string.

Jump to

Keyboard shortcuts

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