execution

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package execution defines the platform-neutral command execution contract. Frontends and tools use these types without depending on native sandbox or process-management details.

Index

Constants

View Source
const PolicyVersion = 2

PolicyVersion is the version of the approval policy that recorded grants were evaluated under. Bump it whenever a change narrows what may be approved: the grant store then backs the file up, keeps deny grants, invalidates prior approvals, and tells the user once, instead of silently honoring approvals that the current rules would have refused.

v2 tightened command-prefix validation so a launcher spelled with a version or an executable extension ("python3.11", "python.exe") can no longer be approved as an ordinary command.

Variables

View Source
var (
	ErrProcessNotFound      = errors.New("execution process not found")
	ErrProcessStdinDisabled = errors.New("execution process does not accept stdin")
	ErrProcessCapacity      = errors.New("execution process capacity reached; stop a running process before starting another")
)

Functions

func ConfigureProcessGroup

func ConfigureProcessGroup(cmd *exec.Cmd)

ConfigureProcessGroup makes cmd the leader of a process group so lifecycle operations cover descendants instead of orphaning them.

func KillProcessTree

func KillProcessTree(pid int) error

KillProcessTree immediately kills pid and, when it is a group leader, its descendant process group.

func TerminateProcessGroup

func TerminateProcessGroup(pid int, grace, poll time.Duration) error

TerminateProcessGroup is like TerminateProcessTree, but for a caller that already knows pid is (or was, at launch) its own process-group leader — e.g. a command started after ConfigureProcessGroup(cmd), which sets Setpgid so cmd.Process.Pid always leads its own group at the moment it is signalled.

TerminateProcessTree instead rediscovers the group via syscall.Getpgid(pid) at call time. On Darwin, that lookup can return ESRCH once an unreaped group leader has already exited, even though live descendants remain in the group it configured — TerminateProcessTree would then silently fall back to signalling only the (already dead) leader PID and leave those descendants running. Skipping rediscovery in favor of the launch-time invariant avoids that: the negative PID is used directly, regardless of whether the leader is still alive to be looked up.

func TerminateProcessTree

func TerminateProcessTree(pid int, grace, poll time.Duration) error

TerminateProcessTree requests graceful termination, then force-kills the process tree after grace. Callers retain their distinct persistence models; this function owns only the OS lifecycle primitive.

The signal target is REDISCOVERED here via processSignalTarget(pid), which asks the OS for pid's current group. A caller that already knows pid was configured as its own group leader at launch (e.g. via ConfigureProcessGroup) should use TerminateProcessGroup instead — see its doc comment for why this rediscovery is fragile once the leader may have already exited.

Types

type AdapterReport

type AdapterReport struct {
	Denial *Denial `json:"denial,omitempty"`
}

AdapterReport is the structured, machine-readable result emitted by a platform enforcement adapter. It is separate from stdout and stderr so command text cannot impersonate a policy decision.

type ApprovalContext

type ApprovalContext struct {
	SessionID     string `json:"sessionId,omitempty"`
	PolicyVersion int    `json:"policyVersion"`
}

type Capability

type Capability struct {
	Kind  CapabilityKind `json:"kind"`
	Scope string         `json:"scope,omitempty"`
}

type CapabilityKind

type CapabilityKind string
const (
	CapabilityRead               CapabilityKind = "filesystem_read"
	CapabilityWorkspaceWrite     CapabilityKind = "workspace_write"
	CapabilityProtectedMetadata  CapabilityKind = "protected_metadata"
	CapabilityExternalNetwork    CapabilityKind = "external_network"
	CapabilityIsolatedLoopback   CapabilityKind = "isolated_loopback"
	CapabilityHostVisibleBinding CapabilityKind = "host_visible_binding"
	CapabilityProcessSpawn       CapabilityKind = "process_spawn"
	CapabilityProcessControl     CapabilityKind = "process_control"
	CapabilityEnvironment        CapabilityKind = "environment"
	CapabilityUnrestricted       CapabilityKind = "unrestricted"
)

type CapturedRequest

type CapturedRequest struct {
	Request Request
	Stdin   []byte
}

type CapturedResult

type CapturedResult struct {
	Stdout    string
	Stderr    string
	Truncated bool
	Outcome   Outcome
	Err       error
}

type Change

type Change struct {
	Path       string     `json:"path"`
	Kind       ChangeKind `json:"kind"`
	Aggregated bool       `json:"aggregated,omitempty"`
	Count      int        `json:"count,omitempty"`
}

type ChangeKind

type ChangeKind string
const (
	ChangeCreated  ChangeKind = "created"
	ChangeModified ChangeKind = "modified"
	ChangeDeleted  ChangeKind = "deleted"
)

type ChangeObserver

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

ChangeObserver records a bounded workspace snapshot around a command. It deliberately skips Zero/repository control metadata and large generated dependency trees; those paths must neither be read as command evidence nor flood the Files panel.

func NewChangeObserver

func NewChangeObserver(root string) *ChangeObserver

func (*ChangeObserver) Changes

func (observer *ChangeObserver) Changes() []Change

type Command

type Command struct {
	Name string   `json:"name"`
	Args []string `json:"args,omitempty"`
	Env  []string `json:"env,omitempty"`
}

type Denial

type Denial struct {
	Capability  Capability       `json:"capability"`
	Source      DenialSource     `json:"source"`
	Reason      string           `json:"reason"`
	Recoverable bool             `json:"recoverable"`
	NextAction  DenialNextAction `json:"nextAction"`
}

func (Denial) Validate

func (denial Denial) Validate() error

type DenialNextAction

type DenialNextAction string
const (
	DenialNextActionNone            DenialNextAction = "none"
	DenialNextActionRequestApproval DenialNextAction = "request_approval"
	DenialNextActionChangeCommand   DenialNextAction = "change_command"
	DenialNextActionEnableSandbox   DenialNextAction = "enable_sandbox"
)

type DenialSource

type DenialSource string
const (
	DenialSourceConfiguredPolicy DenialSource = "configured_policy"
	DenialSourcePlatformSandbox  DenialSource = "platform_sandbox"
	DenialSourceApproval         DenialSource = "approval"
)

type Enforcement

type Enforcement struct {
	Backend         string `json:"backend,omitempty"`
	Level           string `json:"level,omitempty"`
	Degraded        bool   `json:"degraded,omitempty"`
	DowngradeReason string `json:"downgradeReason,omitempty"`
}

type Exit

type Exit struct {
	Code   int    `json:"code"`
	Signal string `json:"signal,omitempty"`
}

type Mode

type Mode string
const (
	ModeCaptured    Mode = "captured"
	ModeInteractive Mode = "interactive"
	ModeDurable     Mode = "durable"
)

type Origin

type Origin string
const (
	OriginInteractiveCommand Origin = "interactive_command"
	OriginHook               Origin = "hook"
	OriginPlugin             Origin = "plugin"
	OriginMCPServer          Origin = "mcp_server"
	OriginBackgroundTask     Origin = "background_task"
)

type Outcome

type Outcome struct {
	State       State       `json:"state"`
	Kind        OutcomeKind `json:"kind"`
	ProcessID   string      `json:"processId,omitempty"`
	Exit        *Exit       `json:"exit,omitempty"`
	Denial      *Denial     `json:"denial,omitempty"`
	Enforcement Enforcement `json:"enforcement"`
	Changes     []Change    `json:"changes,omitempty"`
}

func (Outcome) Validate

func (outcome Outcome) Validate() error

type OutcomeKind

type OutcomeKind string
const (
	OutcomeRunning             OutcomeKind = "running"
	OutcomeSuccess             OutcomeKind = "success"
	OutcomePolicyDenied        OutcomeKind = "policy_denied"
	OutcomeEnforcementDenied   OutcomeKind = "enforcement_denied"
	OutcomeApplicationFailure  OutcomeKind = "application_failure"
	OutcomeSandboxSetupFailure OutcomeKind = "sandbox_setup_failure"
	OutcomeExecutableNotFound  OutcomeKind = "executable_not_found"
	OutcomeCancelled           OutcomeKind = "cancelled"
	OutcomeTimedOut            OutcomeKind = "timed_out"
	OutcomeEnforcementDegraded OutcomeKind = "enforcement_degraded"
)

type PreparedCommand

type PreparedCommand struct {
	Command     *exec.Cmd
	Enforcement Enforcement
	Report      func() (AdapterReport, error)
	Cleanup     func()
}

type Preparer

type Preparer interface {
	PrepareExecution(context.Context, Request) (PreparedCommand, error)
}

Preparer is the platform-adapter seam. It turns a platform-neutral request into one enforceable OS command while keeping native sandbox mechanics out of every caller.

type ProcessContinue

type ProcessContinue struct {
	ProcessID int
	Input     []byte
	Interrupt bool
	Wait      time.Duration
}

type ProcessManager

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

ProcessManager owns retained interactive-process identity, transport, bounded output, continuation, cancellation, completion, and cleanup.

func NewProcessManager

func NewProcessManager(options ProcessManagerOptions) *ProcessManager

func (*ProcessManager) Continue

func (manager *ProcessManager) Continue(ctx context.Context, input ProcessContinue) (ProcessResult, error)

func (*ProcessManager) Len

func (manager *ProcessManager) Len() int

func (*ProcessManager) List

func (manager *ProcessManager) List() []ProcessSnapshot

func (*ProcessManager) Remove

func (manager *ProcessManager) Remove(id int)

Remove forgets completed history only. A live process must remain tracked until completion, even if a termination attempt fails.

func (*ProcessManager) ResizeInput

func (manager *ProcessManager) ResizeInput(id int, cols, rows int) error

ResizeInput updates the PTY window size of a retained interactive process so an attached terminal can fill its viewport. Non-positive dimensions are a no-op; platforms without PTY support report the transport's error.

func (*ProcessManager) Snapshot

func (manager *ProcessManager) Snapshot(id int) (ProcessSnapshot, bool)

func (*ProcessManager) Start

func (manager *ProcessManager) Start(ctx context.Context, input ProcessStart, wait time.Duration) (ProcessResult, error)

func (*ProcessManager) Stop

func (manager *ProcessManager) Stop(id int) bool

func (*ProcessManager) StopAll

func (manager *ProcessManager) StopAll() []int

func (*ProcessManager) WriteInput

func (manager *ProcessManager) WriteInput(id int, data []byte) error

WriteInput writes bytes to a retained interactive process's stdin without collecting output. Unlike Continue it never drains the pending output buffer, so a concurrent write_stdin poll still sees everything the process emitted; callers that only need the rolling tail use Snapshot instead.

type ProcessManagerOptions

type ProcessManagerOptions struct {
	CompletedRetention time.Duration
	// MaxProcesses bounds retained processes and in-flight launches. Completed
	// history is pruned before rejecting a start; live processes are never evicted.
	// Zero uses the default limit; a negative value disables the limit.
	MaxProcesses int
}

type ProcessResult

type ProcessResult struct {
	ProcessID       int
	CommandText     string
	RelativeCwd     string
	TTY             bool
	Output          string
	OutputTruncated bool
	Exited          bool
	ExitCode        int
	Interrupted     bool
	Request         Request
	Enforcement     Enforcement
	Report          AdapterReport
	ReportErr       error
	Changes         []Change
	Metadata        map[string]string
}

type ProcessSnapshot

type ProcessSnapshot struct {
	ID              int
	Command         string
	Cwd             string
	RelativeCwd     string
	StartedAt       time.Time
	LastUsedAt      time.Time
	TTY             bool
	Status          string
	ExitCode        *int
	RecentOutput    string
	OutputTruncated bool
}

type ProcessStart

type ProcessStart struct {
	Prepared    PreparedCommand
	Request     Request
	CommandText string
	RelativeCwd string
	TTY         bool
	Metadata    map[string]string
	// AfterWait may append adapter diagnostics collected by a platform monitor.
	AfterWait func() []byte
}

type Request

type Request struct {
	Origin           Origin          `json:"origin"`
	Mode             Mode            `json:"mode"`
	Command          Command         `json:"command"`
	WorkingDirectory string          `json:"workingDirectory"`
	WorkspaceRoots   []string        `json:"workspaceRoots"`
	Capabilities     []Capability    `json:"capabilities,omitempty"`
	Approval         ApprovalContext `json:"approval"`
}

func (Request) Validate

func (request Request) Validate() error

type Runner

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

Runner is the deep execution module used by Zero-owned subprocess launchers. The preparer may be installed after tool registration, but execution fails closed until an adapter is present.

func NewRunner

func NewRunner(preparer Preparer) *Runner

func (*Runner) ExecuteCaptured

func (runner *Runner) ExecuteCaptured(ctx context.Context, input CapturedRequest) CapturedResult

func (*Runner) Prepare

func (runner *Runner) Prepare(ctx context.Context, request Request) (PreparedCommand, error)

Prepare evaluates and prepares a typed request for callers that require streaming pipes or protocol-specific lifecycle handling, such as stdio MCP. The returned cleanup remains mandatory; ordinary captured commands should use ExecuteCaptured so the Runner owns it automatically.

func (*Runner) SetPreparer

func (runner *Runner) SetPreparer(preparer Preparer)

type State

type State string
const (
	StateRequested        State = "requested"
	StateEvaluated        State = "evaluated"
	StateAwaitingApproval State = "awaiting_approval"
	StatePrepared         State = "prepared"
	StateRunning          State = "running"
	StateRetained         State = "retained"
	StateCompleted        State = "completed"
	StateDenied           State = "denied"
	StateFailed           State = "failed"
	StateCancelled        State = "cancelled"
)

Jump to

Keyboard shortcuts

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