bash

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultTimeout is the default command timeout.
	DefaultTimeout = 30 * time.Second

	// MaxTimeout is the maximum allowed timeout.
	MaxTimeout = 5 * time.Minute

	// MaxOutputSize is the default maximum captured output size (100 KB).
	MaxOutputSize = 100 * 1024

	// AbsoluteMaxOutputSize is the hard ceiling for output_bytes_cap (10 MB).
	AbsoluteMaxOutputSize = 10 * 1024 * 1024
)
View Source
const Description = `` /* 2736-byte string literal not displayed */

Description is the tool description.

View Source
const MonitorTimeout = 30 * time.Minute
View Source
const SearchHint = "run shell commands in the terminal"

SearchHint is a hint for tool search functionality.

View Source
const ToolName = "bash"

ToolName is the tool name.

Variables

View Source
var AcceptEditsReadOnlyCommands = []string{
	"grep", "cat", "ls", "find", "head", "tail", "echo",
	"pwd", "wc", "sort", "uniq", "diff",
}

AcceptEditsReadOnlyCommands are read-only commands auto-allowed in AcceptEdits mode.

View Source
var AcceptEditsWriteCommands = []string{
	"mkdir", "touch", "rm", "rmdir", "mv", "cp", "sed",
}

AcceptEditsWriteCommands are commands auto-allowed in AcceptEdits mode.

Functions

func DefaultTaskDir

func DefaultTaskDir() string

DefaultTaskDir returns the default task output directory.

func GetTaskOutput

func GetTaskOutput(taskID string) (string, error)

GetTaskOutput reads output from a monitor task.

func GetTaskStatus

func GetTaskStatus(taskID string) (string, error)

GetTaskStatus returns the current status string for a monitor task.

func IsBackgroundCommand

func IsBackgroundCommand(command string) bool

IsBackgroundCommand checks if command ends with & (background operator).

func KillTask

func KillTask(taskID string) error

KillTask kills a monitor task by ID.

func KillTaskProcess

func KillTaskProcess(task *BackgroundTask) error

KillTaskProcess kills a task's entire process group.

Types

type BackgroundTask

type BackgroundTask struct {
	ID        string
	Command   string
	Process   *exec.Cmd
	Output    *TaskOutput
	Status    TaskStatus
	StartTime time.Time
	EndTime   *time.Time
	ExitCode  int
	// contains filtered or unexported fields
}

BackgroundTask represents a background task.

func (*BackgroundTask) GetEndTime

func (t *BackgroundTask) GetEndTime() *time.Time

func (*BackgroundTask) GetExitCode

func (t *BackgroundTask) GetExitCode() int

func (*BackgroundTask) GetStatus

func (t *BackgroundTask) GetStatus() TaskStatus

type BackgroundTaskManager

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

BackgroundTaskManager manages background tasks.

func GlobalTaskManager

func GlobalTaskManager() *BackgroundTaskManager

GlobalTaskManager returns the manager created by the most recent NewTool() call.

func NewBackgroundTaskManager

func NewBackgroundTaskManager(taskDir string) *BackgroundTaskManager

NewBackgroundTaskManager creates a new, isolated manager.

func (*BackgroundTaskManager) GetTask

GetTask retrieves a task by ID.

func (*BackgroundTaskManager) Init

func (m *BackgroundTaskManager) Init() error

Init ensures task directory exists.

func (*BackgroundTaskManager) KillTask

func (m *BackgroundTaskManager) KillTask(id string) error

KillTask kills a background task and cancels its auto-remove timer.

func (*BackgroundTaskManager) ListTasks

func (m *BackgroundTaskManager) ListTasks() []*BackgroundTask

ListTasks lists all background tasks.

func (*BackgroundTaskManager) RemoveTask

func (m *BackgroundTaskManager) RemoveTask(id string)

RemoveTask removes a task and its output file.

func (*BackgroundTaskManager) StartBackgroundTask

func (m *BackgroundTaskManager) StartBackgroundTask(
	ctx context.Context,
	command string,
	workingDir string,
	env []string,
	shell string,
) (*BackgroundTask, error)

StartBackgroundTask starts a command in the background.

func (*BackgroundTaskManager) WaitForTask

func (m *BackgroundTaskManager) WaitForTask(id string, timeout time.Duration) (*BackgroundTask, error)

WaitForTask waits for a task to complete within timeout.

func (*BackgroundTaskManager) WriteStdin

func (m *BackgroundTaskManager) WriteStdin(id string, data string) error

WriteStdin writes data to a running task's stdin pipe. Returns an error if the task has no stdin pipe (already finished or stdin was not set up) or if the write fails (e.g. broken pipe).

type CommandClassification

type CommandClassification string

CommandClassification represents the classification of a command.

const (
	ClassificationUnknown        CommandClassification = "unknown"
	ClassificationReadOnly       CommandClassification = "readonly"
	ClassificationSearch         CommandClassification = "search"
	ClassificationWrite          CommandClassification = "write"
	ClassificationStateChange    CommandClassification = "state_change"
	ClassificationVersionControl CommandClassification = "version_control"
	ClassificationShell          CommandClassification = "shell"
)

type CommandResult

type CommandResult struct {
	ExitCode  int    `json:"exit_code"`
	Stdout    string `json:"stdout"`
	Stderr    string `json:"stderr"`
	Timeout   bool   `json:"timeout"`
	Duration  int64  `json:"duration_ms"`
	CWD       string `json:"cwd,omitempty"`
	Sandboxed bool   `json:"sandboxed"`
}

CommandResult holds the output of a completed command.

type CommandSegment

type CommandSegment struct {
	Text     string
	Operator string
	Type     SegmentType
}

CommandSegment represents a segment of a command.

type CommandType

type CommandType string

CommandType represents the type of command.

const (
	CommandTypeUnknown        CommandType = "unknown"
	CommandTypeRead           CommandType = "read"
	CommandTypeSearch         CommandType = "search"
	CommandTypeWrite          CommandType = "write"
	CommandTypeStateChange    CommandType = "state_change"
	CommandTypeVersionControl CommandType = "version_control"
)

type ExecutionContext

type ExecutionContext struct {
	Command          string
	Description      string
	Timeout          time.Duration
	WorkingDirectory string
	MaxOutputSize    int64
	EnableSandbox    bool
	RunInBackground  bool
	// Stdin, when non-empty, is piped into the command's stdin.
	Stdin string
	// OutputChunkCallback, when set, is called for each output chunk (streaming).
	// stream is "stdout" or "stderr".
	OutputChunkCallback func(chunk string, stream string)
}

ExecutionContext holds the parameters for a single command execution.

type JobKillTool

type JobKillTool struct{}

JobKillTool kills a running background job and returns its final output.

func NewJobKillTool

func NewJobKillTool() *JobKillTool

func (*JobKillTool) BackfillInput

func (t *JobKillTool) BackfillInput(_ context.Context, in map[string]any) map[string]any

func (*JobKillTool) Call

func (*JobKillTool) CheckPermissions

func (t *JobKillTool) CheckPermissions(_ context.Context, _ map[string]any, _ tool.ToolUseContext) types.PermissionResult

func (*JobKillTool) Definition

func (t *JobKillTool) Definition() tool.Definition

func (*JobKillTool) Description

func (t *JobKillTool) Description(_ context.Context) (string, error)

func (*JobKillTool) ExecutesInPlanMode

func (t *JobKillTool) ExecutesInPlanMode(_ map[string]any) bool

func (*JobKillTool) FormatResult

func (t *JobKillTool) FormatResult(data any) string

func (*JobKillTool) IsConcurrencySafe

func (t *JobKillTool) IsConcurrencySafe(_ map[string]any) bool

func (*JobKillTool) IsEnabled

func (t *JobKillTool) IsEnabled() bool

func (*JobKillTool) IsReadOnly

func (t *JobKillTool) IsReadOnly(_ map[string]any) bool

func (*JobKillTool) PreparePermissionMatcher

func (t *JobKillTool) PreparePermissionMatcher(_ context.Context, _ map[string]any) (func(string) bool, error)

func (*JobKillTool) RequiresUserInteraction

func (t *JobKillTool) RequiresUserInteraction() bool

func (*JobKillTool) ValidateInput

func (t *JobKillTool) ValidateInput(_ context.Context, in map[string]any) (map[string]any, error)

type JobOutputTool

type JobOutputTool struct{}

JobOutputTool returns buffered stdout/stderr from a background job. Inspired by crush's async bash job pattern.

func NewJobOutputTool

func NewJobOutputTool() *JobOutputTool

func (*JobOutputTool) BackfillInput

func (t *JobOutputTool) BackfillInput(_ context.Context, in map[string]any) map[string]any

Satisfy the contract.Tool interface — these tools don't need backfilling.

func (*JobOutputTool) Call

func (*JobOutputTool) CheckPermissions

func (t *JobOutputTool) CheckPermissions(_ context.Context, _ map[string]any, _ tool.ToolUseContext) types.PermissionResult

func (*JobOutputTool) Definition

func (t *JobOutputTool) Definition() tool.Definition

func (*JobOutputTool) Description

func (t *JobOutputTool) Description(_ context.Context) (string, error)

func (*JobOutputTool) ExecutesInPlanMode

func (t *JobOutputTool) ExecutesInPlanMode(_ map[string]any) bool

func (*JobOutputTool) FormatResult

func (t *JobOutputTool) FormatResult(data any) string

func (*JobOutputTool) IsConcurrencySafe

func (t *JobOutputTool) IsConcurrencySafe(_ map[string]any) bool

func (*JobOutputTool) IsEnabled

func (t *JobOutputTool) IsEnabled() bool

func (*JobOutputTool) IsReadOnly

func (t *JobOutputTool) IsReadOnly(_ map[string]any) bool

func (*JobOutputTool) PreparePermissionMatcher

func (t *JobOutputTool) PreparePermissionMatcher(_ context.Context, _ map[string]any) (func(string) bool, error)

func (*JobOutputTool) RequiresUserInteraction

func (t *JobOutputTool) RequiresUserInteraction() bool

func (*JobOutputTool) ValidateInput

func (t *JobOutputTool) ValidateInput(_ context.Context, in map[string]any) (map[string]any, error)

type MonitorTool

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

MonitorTool streams a shell command's stdout as live notifications.

func NewMonitorTool

func NewMonitorTool(workingDir string) *MonitorTool

NewMonitorTool creates the monitor tool.

func (*MonitorTool) BackfillInput

func (t *MonitorTool) BackfillInput(_ context.Context, input map[string]any) map[string]any

func (*MonitorTool) Call

func (t *MonitorTool) Call(ctx context.Context, input tool.CallInput, permissionCheck types.CanUseToolFn) (tool.CallResult, error)

func (*MonitorTool) CheckPermissions

func (t *MonitorTool) CheckPermissions(_ context.Context, input map[string]any, _ tool.ToolUseContext) types.PermissionResult

func (*MonitorTool) Definition

func (t *MonitorTool) Definition() tool.Definition

func (*MonitorTool) Description

func (t *MonitorTool) Description(_ context.Context) (string, error)

func (*MonitorTool) FormatResult

func (t *MonitorTool) FormatResult(data any) string

func (*MonitorTool) IsConcurrencySafe

func (t *MonitorTool) IsConcurrencySafe(_ map[string]any) bool

func (*MonitorTool) IsEnabled

func (t *MonitorTool) IsEnabled() bool

func (*MonitorTool) IsReadOnly

func (t *MonitorTool) IsReadOnly(_ map[string]any) bool

func (*MonitorTool) ValidateInput

func (t *MonitorTool) ValidateInput(_ context.Context, input map[string]any) (map[string]any, error)

type ParsedCommand

type ParsedCommand struct {
	Original        string
	Segments        []CommandSegment
	EnvVars         map[string]string
	HasRedirections bool
	IsCompound      bool
}

ParsedCommand represents a parsed command.

type Parser

type Parser struct{}

Parser provides command parsing utilities.

func NewParser

func NewParser() *Parser

NewParser creates a new command parser.

func (*Parser) GetCommandType

func (p *Parser) GetCommandType(command string) CommandType

GetCommandType returns the type of command.

func (*Parser) IsSilentCommand

func (p *Parser) IsSilentCommand(command string) bool

IsSilentCommand checks if command produces no stdout on success.

func (*Parser) ParseCommand

func (p *Parser) ParseCommand(command string) *ParsedCommand

ParseCommand parses a bash command into segments.

type SecurityValidator

type SecurityValidator struct{}

SecurityValidator provides Bash-specific security validation.

func NewSecurityValidator

func NewSecurityValidator() *SecurityValidator

NewSecurityValidator creates a new Bash security validator.

func (*SecurityValidator) GetCommandClassification

func (v *SecurityValidator) GetCommandClassification(command string) CommandClassification

GetCommandClassification returns the classification of a command. Delegates to the shared classifyCommandName so there is a single lookup table.

func (*SecurityValidator) ValidateCommand

func (v *SecurityValidator) ValidateCommand(command string) *SecurityViolation

ValidateCommand checks a command against hardcoded dangerous patterns. Returns a SecurityViolation (never nil when dangerous) or nil when safe.

func (*SecurityValidator) ValidateGitCommand

func (v *SecurityValidator) ValidateGitCommand(command string) *SecurityViolation

ValidateGitCommand performs deep analysis of git subcommands to block dangerous options that bypass workspace restrictions or execute arbitrary code. Returns a SecurityViolation when the git invocation is unsafe, nil otherwise.

func (*SecurityValidator) ValidateWorkspace

func (v *SecurityValidator) ValidateWorkspace(command string, workspaceRoot string) *SecurityViolation

ValidateWorkspace ensures that write commands cannot escape the workspace via relative traversal and that no segment writes to a protected system path. Absolute write targets outside the workspace are allowed to continue into the normal permission flow so the user can explicitly approve paths like /tmp.

type SecurityViolation

type SecurityViolation struct {
	Command   string
	Violation string
	Severity  Severity
	Reason    string
}

SecurityViolation represents a security violation.

func (*SecurityViolation) Error

func (v *SecurityViolation) Error() string

type SegmentType

type SegmentType string

SegmentType represents the type of a command segment.

const (
	SegmentTypeCommand     SegmentType = "command"
	SegmentTypePipe        SegmentType = "pipe"
	SegmentTypeLogical     SegmentType = "logical"
	SegmentTypeSequential  SegmentType = "sequential"
	SegmentTypeRedirection SegmentType = "redirection"
)

type Severity

type Severity string

Severity represents the severity of a security violation.

const (
	SeverityLow      Severity = "low"
	SeverityMedium   Severity = "medium"
	SeverityHigh     Severity = "high"
	SeverityCritical Severity = "critical"
)

type TaskOutput

type TaskOutput struct {
	Path         string
	StdoutBuffer []byte
	StderrBuffer []byte
	// contains filtered or unexported fields
}

TaskOutput manages task output storage.

func NewTaskOutput

func NewTaskOutput(path string) *TaskOutput

NewTaskOutput creates a new task output.

type TaskOutputReader

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

TaskOutputReader reads task output incrementally.

func NewTaskOutputReader

func NewTaskOutputReader(taskID string) (*TaskOutputReader, error)

NewTaskOutputReader creates a reader using the global task manager. Pass a non-nil manager to use a specific instance instead.

func NewTaskOutputReaderFrom

func NewTaskOutputReaderFrom(manager *BackgroundTaskManager, taskID string) (*TaskOutputReader, error)

NewTaskOutputReaderFrom creates a reader from a specific manager.

func (*TaskOutputReader) IsRunning

func (r *TaskOutputReader) IsRunning() bool

IsRunning checks if the task is still running.

func (*TaskOutputReader) ReadOutput

func (r *TaskOutputReader) ReadOutput() (string, error)

ReadOutput reads new output since the last call.

type TaskStatus

type TaskStatus int

TaskStatus represents background task status.

const (
	TaskStatusRunning      TaskStatus = iota // Task is running
	TaskStatusBackgrounded                   // Task was backgrounded
	TaskStatusCompleted                      // Task completed normally
	TaskStatusKilled                         // Task was killed
	TaskStatusTimeout                        // Task timed out
)

type Tool

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

Tool represents the Bash tool.

func NewTool

func NewTool(config *ToolConfig) *Tool

NewTool creates a new Bash tool.

func (*Tool) BackfillInput

func (t *Tool) BackfillInput(_ context.Context, input map[string]any) map[string]any

BackfillInput enriches the input — no-op for bash.

func (*Tool) Call

func (t *Tool) Call(
	ctx context.Context,
	input tool.CallInput,
	permissionCheck types.CanUseToolFn,
) (tool.CallResult, error)

Call executes the tool.

func (*Tool) CheckPermissions

func (t *Tool) CheckPermissions(_ context.Context, input map[string]any, toolCtx tool.ToolUseContext) types.PermissionResult

CheckPermissions performs bash-specific permission checks before the global pipeline.

func (*Tool) Definition

func (t *Tool) Definition() tool.Definition

Definition returns the tool definition.

func (*Tool) Description

func (t *Tool) Description(_ context.Context) (string, error)

Description returns a human-readable description.

func (*Tool) FormatResult

func (t *Tool) FormatResult(data any) string

FormatResult serialises the tool output into the tool_result content string.

func (*Tool) IsConcurrencySafe

func (t *Tool) IsConcurrencySafe(input map[string]any) bool

IsConcurrencySafe returns whether this tool use can run concurrently.

func (*Tool) IsEnabled

func (t *Tool) IsEnabled() bool

IsEnabled returns whether this tool is currently active.

func (*Tool) IsReadOnly

func (t *Tool) IsReadOnly(input map[string]any) bool

IsReadOnly returns whether this tool use is read-only.

func (*Tool) PreparePermissionMatcher

func (t *Tool) PreparePermissionMatcher(_ context.Context, input map[string]any) (func(ruleContent string) bool, error)

PreparePermissionMatcher compiles content-specific permission matching for bash rules.

func (*Tool) ValidateInput

func (t *Tool) ValidateInput(_ context.Context, input map[string]any) (map[string]any, error)

ValidateInput validates and normalises bash input.

type ToolConfig

type ToolConfig struct {
	Timeout          time.Duration
	MaxOutputSize    int64
	WorkingDirectory string
	EnableSandbox    bool
	// RequireSandbox makes the tool refuse to run when the workspace boundary is
	// set but Landlock is unavailable. Leave false for desktop use; set true for
	// multi-tenant server deployments.
	RequireSandbox bool
	// OutputChunkCallback, when set, receives each output chunk as it is produced
	// (streaming mode). If nil, output is buffered and returned at completion.
	OutputChunkCallback func(chunk string, stream string)
}

ToolConfig represents the Bash tool configuration.

func DefaultToolConfig

func DefaultToolConfig() *ToolConfig

DefaultToolConfig returns a sensible default configuration.

type WriteStdinTool

type WriteStdinTool struct{}

WriteStdinTool writes characters to a running background task's stdin. After writing it waits wait_ms milliseconds, then returns any new output the task has produced — useful for driving interactive REPLs.

func NewWriteStdinTool

func NewWriteStdinTool() *WriteStdinTool

func (*WriteStdinTool) BackfillInput

func (t *WriteStdinTool) BackfillInput(_ context.Context, in map[string]any) map[string]any

func (*WriteStdinTool) Call

func (*WriteStdinTool) CheckPermissions

func (*WriteStdinTool) Definition

func (t *WriteStdinTool) Definition() tool.Definition

func (*WriteStdinTool) Description

func (t *WriteStdinTool) Description(_ context.Context) (string, error)

func (*WriteStdinTool) FormatResult

func (t *WriteStdinTool) FormatResult(data any) string

func (*WriteStdinTool) IsConcurrencySafe

func (t *WriteStdinTool) IsConcurrencySafe(_ map[string]any) bool

func (*WriteStdinTool) IsEnabled

func (t *WriteStdinTool) IsEnabled() bool

func (*WriteStdinTool) IsReadOnly

func (t *WriteStdinTool) IsReadOnly(_ map[string]any) bool

func (*WriteStdinTool) PreparePermissionMatcher

func (t *WriteStdinTool) PreparePermissionMatcher(_ context.Context, _ map[string]any) (func(string) bool, error)

func (*WriteStdinTool) ValidateInput

func (t *WriteStdinTool) ValidateInput(_ context.Context, in map[string]any) (map[string]any, error)

Jump to

Keyboard shortcuts

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