execution

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package execution defines validated coding operations, authorization policy, and platform command execution boundaries.

Index

Constants

View Source
const MaxStdinBytes = 1 << 20

MaxStdinBytes is the largest standard-input payload accepted by one operation.

Variables

View Source
var (
	// ErrInvalidOperation means an operation request cannot be represented safely.
	ErrInvalidOperation = errors.New("coding execution: invalid operation")
	// ErrInvalidFingerprint means a persisted operation fingerprint is malformed.
	ErrInvalidFingerprint = errors.New("coding execution: invalid fingerprint")
	// ErrInvalidPolicy means a policy configuration cannot establish a safe ceiling.
	ErrInvalidPolicy = errors.New("coding execution: invalid policy")
	// ErrUnauthorized means an operation has no valid authorization under policy.
	ErrUnauthorized = errors.New("coding execution: unauthorized")
	// ErrUnsupportedPlatform means the host cannot provide a required execution boundary.
	ErrUnsupportedPlatform = errors.New("coding execution: unsupported platform")
	// ErrSandboxUnavailable means the configured platform boundary failed its capability check.
	ErrSandboxUnavailable = errors.New("coding execution: sandbox unavailable")
	// ErrPlanUsed means a plan was already run or closed.
	ErrPlanUsed = errors.New("coding execution: plan already consumed")
	// ErrStart means the operating system did not start a validated plan.
	ErrStart = errors.New("coding execution: process start failed")
	// ErrOutputLimit means observed process output exceeded the operation hard limit.
	ErrOutputLimit = errors.New("coding execution: output limit exceeded")
)

Functions

func EnvironmentNamesEqual

func EnvironmentNamesEqual(left, right string) bool

EnvironmentNamesEqual reports whether two environment names are equivalent under the current platform's process-environment semantics.

func IsExecutableFile

func IsExecutableFile(info fs.FileInfo) bool

IsExecutableFile reports whether info describes a file that this platform can consider for direct process execution. Windows executable selection is extension-based; POSIX platforms also require at least one execute bit.

func IsOwnerPrivateDirectory

func IsOwnerPrivateDirectory(info fs.FileInfo) bool

IsOwnerPrivateDirectory reports whether info is a directory whose POSIX permission bits exclude group/world access. Windows FileMode cannot prove ACL privacy, so callers rely on their client-owned parent ACL there.

func IsOwnerWritableDirectory

func IsOwnerWritableDirectory(info fs.FileInfo) bool

IsOwnerWritableDirectory reports whether FileMode proves owner-write access. Windows FileMode cannot express ACLs, so client-managed creation remains the authority there.

func NewChildEnvironment

func NewChildEnvironment(
	lookup func(string) (string, bool),
	privateDir string,
	overrides []EnvVar,
) ([]string, error)

NewChildEnvironment builds a sorted, minimal child-process environment. Only the fixed inheritance allowlist and validated trusted overrides are included; private cache/temp paths are always created below privateDir.

func RunHookCommand

func RunHookCommand(ctx context.Context, options HookCommandOptions) error

RunHookCommand owns one reviewed lifecycle-hook process until it exits or ctx is cancelled. It must not be used for model-controlled command strings.

func ValidateDirectoryWritable

func ValidateDirectoryWritable(directory string) error

ValidateDirectoryWritable verifies that a subprocess running as the current client identity can create and remove a file in directory.

func ValidateEnvironment

func ValidateEnvironment(input []EnvVar) error

ValidateEnvironment verifies bounded trusted child-process environment overrides.

Types

type Authorization

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

Authorization binds a policy decision to one exact operation and workspace.

type Capabilities

type Capabilities struct {
	Platform         string
	Runtime          string
	RuntimeVersion   string
	WorkspaceWrite   bool
	NetworkIsolation bool
	ProcessIsolation bool
}

Capabilities describes platform sandbox guarantees verified by Probe.

type Decision

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

Decision is an immutable policy verdict and optional authorization.

func (Decision) Authorization

func (d Decision) Authorization() (Authorization, bool)

Authorization returns a bound authorization only for allowed decisions.

func (Decision) Reason

func (d Decision) Reason() string

Reason returns a stable machine-readable reason.

func (Decision) Verdict

func (d Decision) Verdict() Verdict

Verdict returns the policy outcome.

type EnvVar

type EnvVar struct {
	Name  string
	Value string
}

EnvVar is one trusted environment override.

type Executor

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

Executor prepares and runs authorized operations for one workspace.

func NewExecutor

func NewExecutor(ws workspace.Workspace, cfg ExecutorConfig) (*Executor, error)

NewExecutor constructs an executor using the current platform backend.

func (*Executor) Execute

func (e *Executor) Execute(
	ctx context.Context,
	op Operation,
	auth Authorization,
	sink Sink,
) (Result, error)

Execute plans, runs, and closes one operation.

func (*Executor) Plan

func (e *Executor) Plan(ctx context.Context, op Operation, auth Authorization) (*Plan, error)

Plan revalidates authorization and resources, then owns a single-use launch.

func (*Executor) Probe

func (e *Executor) Probe(ctx context.Context) (Capabilities, error)

Probe verifies the current platform sandbox rather than only checking a binary version.

func (*Executor) Run

func (e *Executor) Run(ctx context.Context, plan *Plan, sink Sink) (Result, error)

Run consumes a plan and returns a bounded result even for process failures.

type ExecutorConfig

type ExecutorConfig struct {
	TempRoot    string
	Environment func(string) (string, bool)
	TermGrace   time.Duration
	DrainGrace  time.Duration
	Protected   []string
}

ExecutorConfig defines private resources and process lifecycle bounds.

type Fingerprint

type Fingerprint [sha256.Size]byte

Fingerprint is the complete stable identity of one operation permission request.

func ParseFingerprint

func ParseFingerprint(input string) (Fingerprint, error)

ParseFingerprint parses an exact persistence form.

func (Fingerprint) String

func (f Fingerprint) String() string

String returns the lowercase hexadecimal persistence form.

type HookCommandExitError

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

HookCommandExitError reports a shell command that started and returned a non-zero status. Callers can use ExitCode to apply their own hook protocol.

func (*HookCommandExitError) Error

func (e *HookCommandExitError) Error() string

func (*HookCommandExitError) ExitCode

func (e *HookCommandExitError) ExitCode() int

ExitCode returns the command's process exit status.

func (*HookCommandExitError) Unwrap

func (e *HookCommandExitError) Unwrap() error

Unwrap returns the underlying process error.

type HookCommandOptions

type HookCommandOptions struct {
	Workspace   string
	Environment []string
	Command     string
	Stdin       io.Reader
	Stdout      io.Writer
	Stderr      io.Writer
}

HookCommandOptions describe one already-reviewed Pips lifecycle hook command. This deliberately stays outside Executor's model-tool Sandbox path: callers must pass only an explicitly reviewed local command and stdin data.

type InvalidOperationProblem

type InvalidOperationProblem struct {
	Field     string
	Reason    string
	Retryable bool
	Hint      string
}

InvalidOperationProblem is safe, bounded correction metadata for an invalid operation. It never includes the rejected value or an operating-system error.

func DescribeInvalidOperation

func DescribeInvalidOperation(err error) (InvalidOperationProblem, bool)

DescribeInvalidOperation returns safe correction metadata when err carries a classified invalid-operation failure.

type Kind

type Kind uint8

Kind identifies the trusted operation producer.

const (
	KindUnknown Kind = iota
	KindShell
	KindGit
	KindProcess
)

Supported operation kinds.

type NetworkAccess

type NetworkAccess uint8

NetworkAccess identifies the requested host network permission.

const (
	NetworkUnknown NetworkAccess = iota
	NetworkNone
	NetworkAny
)

Supported network access levels.

type Operation

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

Operation is an immutable-by-API, canonical command and permission request.

func NewOperation

func NewOperation(ctx context.Context, ws workspace.Workspace, spec OperationSpec) (Operation, error)

NewOperation validates and canonicalizes a command request against workspace.

func (Operation) Args

func (o Operation) Args() []string

Args returns an owned copy of the exact argument vector.

func (Operation) CWD

func (o Operation) CWD() string

CWD returns the normalized workspace-relative working directory.

func (Operation) Env

func (o Operation) Env() []EnvVar

Env returns an owned copy of the sorted trusted environment overrides.

func (Operation) Executable

func (o Operation) Executable() string

Executable returns the canonical absolute executable path.

func (Operation) Fingerprint

func (o Operation) Fingerprint() Fingerprint

Fingerprint returns the operation's canonical permission identity.

func (Operation) Justification

func (o Operation) Justification() string

Justification returns display-only approval context.

func (Operation) Kind

func (o Operation) Kind() Kind

Kind returns the operation kind.

func (Operation) Network

func (o Operation) Network() NetworkAccess

Network returns the requested network permission.

func (Operation) Output

func (o Operation) Output() OutputLimits

Output returns the process output limits.

func (Operation) Stdin

func (o Operation) Stdin() []byte

Stdin returns an owned copy of standard input.

func (Operation) Timeout

func (o Operation) Timeout() time.Duration

Timeout returns the operation deadline duration.

func (Operation) Tool

func (o Operation) Tool() string

Tool returns the stable producer name.

func (Operation) WorkspaceAccess

func (o Operation) WorkspaceAccess() WorkspaceAccess

WorkspaceAccess returns the requested workspace permission.

func (Operation) WriteDirs

func (o Operation) WriteDirs() []string

WriteDirs returns canonical external write directories in stable order.

type OperationSpec

type OperationSpec struct {
	Kind       Kind
	Tool       string
	Executable string
	Args       []string
	CWD        string
	Env        []EnvVar
	Stdin      []byte
	Timeout    time.Duration
	Output     OutputLimits
	Workspace  WorkspaceAccess
	WriteDirs  []string
	Network    NetworkAccess
	// NetworkByConfiguration means NetworkAny came from an explicit user
	// sandbox policy rather than a per-call permission request. Policy still
	// decides authority; this flag only avoids demanding model-authored network
	// justification for authority the user already supplied.
	NetworkByConfiguration bool
	Justification          string
}

OperationSpec describes a requested command before canonicalization.

type OutputChunk

type OutputChunk struct {
	Stream Stream
	Offset int64
	Data   []byte
}

OutputChunk is an owned progress payload for one stream offset.

type OutputLimits

type OutputLimits struct {
	CaptureBytes int64
	MaxBytes     int64
	ChunkBytes   int
	QueueDepth   int
}

OutputLimits bound captured, streamed, and total process output.

type Plan

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

Plan owns one validated, single-use command launch and its private resources.

func (*Plan) Close

func (p *Plan) Close() error

Close releases plan-owned files and its exact private directory. It is idempotent.

type Policy

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

Policy evaluates operations for one filesystem-bound workspace.

func NewPolicy

func NewPolicy(ws workspace.Workspace, cfg PolicyConfig) (Policy, error)

NewPolicy validates a workspace-bound execution policy.

func (Policy) Approve

func (p Policy) Approve(op Operation) (Authorization, error)

Approve creates an exact authorization for a currently approvable operation.

func (Policy) Evaluate

func (p Policy) Evaluate(op Operation, grants ...Fingerprint) Decision

Evaluate applies policy and exact session grants to an operation.

type PolicyConfig

type PolicyConfig struct {
	Sandbox       config.SandboxMode
	Network       config.SandboxNetworkMode
	Approval      config.ApprovalMode
	SandboxSource config.Source
	Protected     []string
}

PolicyConfig defines the immutable sandbox and approval ceiling.

type PrivateTempRoot

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

PrivateTempRoot is an owner-only, identity-checked runtime scratch root. It is intended for process-local temporary files and cache directories, not durable product state. Close refuses to remove a path whose filesystem identity changed after allocation.

func NewPrivateTempRoot

func NewPrivateTempRoot(base string) (*PrivateTempRoot, error)

NewPrivateTempRoot allocates a canonical owner-only scratch directory below base. The caller owns the returned root and must close it after all plans and child processes have stopped.

func NewPrivateTempRootOutside

func NewPrivateTempRootOutside(base string, excluded []string) (*PrivateTempRoot, error)

NewPrivateTempRootOutside allocates an owner-only scratch root below base and refuses roots nested under any excluded path. Excluded paths may be absent because callers commonly protect a product root before its first durable file is created.

func (*PrivateTempRoot) Close

func (r *PrivateTempRoot) Close() error

Close removes the scratch root if its identity is unchanged. It is idempotent and never follows a replacement symlink.

func (*PrivateTempRoot) Path

func (r *PrivateTempRoot) Path() string

Path returns the canonical scratch root path.

type ProbeError

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

ProbeError reports a stable sandbox capability failure without exposing untrusted process output or probe paths in its message.

func (*ProbeError) Code

func (e *ProbeError) Code() string

Code returns a stable machine-readable failure code.

func (*ProbeError) Error

func (e *ProbeError) Error() string

Error returns a stable, low-sensitivity diagnostic.

func (*ProbeError) Failure

func (e *ProbeError) Failure() ProbeFailure

Failure returns the failed probe stage.

func (*ProbeError) MinimumVersion

func (e *ProbeError) MinimumVersion() string

MinimumVersion returns the minimum supported runtime version, when relevant.

func (*ProbeError) Runtime

func (e *ProbeError) Runtime() string

Runtime returns the canonical sandbox runtime name, when known.

func (*ProbeError) Unwrap

func (e *ProbeError) Unwrap() error

Unwrap retains the underlying local diagnostic for errors.Is and errors.As.

func (*ProbeError) Version

func (e *ProbeError) Version() string

Version returns the canonical detected runtime version, when known.

type ProbeFailure

type ProbeFailure uint8

ProbeFailure identifies the capability-probe stage that failed.

const (
	// ProbeFailureUnknown represents an unclassified fail-closed probe error.
	ProbeFailureUnknown ProbeFailure = iota
	// ProbeFailureLauncher means the fixed runtime launcher is unavailable.
	ProbeFailureLauncher
	// ProbeFailureRuntimeVersion means runtime version metadata is invalid.
	ProbeFailureRuntimeVersion
	// ProbeFailureRuntimeTooOld means the runtime is below the supported baseline.
	ProbeFailureRuntimeTooOld
	// ProbeFailureIsolation means the core namespace or mount preflight failed.
	ProbeFailureIsolation
	// ProbeFailureDeny means the restrictive full capability probe failed.
	ProbeFailureDeny
	// ProbeFailureAllow means the expanded-network full capability probe failed.
	ProbeFailureAllow
)

type Result

type Result struct {
	Status   Status
	ExitCode int
	Signal   string
	Duration time.Duration
	CWD      string
	Stdout   StreamResult
	Stderr   StreamResult
}

Result is a bounded process outcome without absolute workspace paths.

type SandboxDiagnostic

type SandboxDiagnostic struct {
	Errno     string `json:"errno"`
	Operation string `json:"operation"`
	Path      string `json:"path,omitempty"`
	Backend   string `json:"backend"`
	Phase     string `json:"phase"`
}

SandboxDiagnostic is bounded machine-readable evidence for a filesystem denial. Path is present only when the operating system or child runtime reported an exact path; callers must keep it out of durable lifecycle projections.

func SandboxDiagnosticFromError

func SandboxDiagnosticFromError(err error, backend, phase string) (SandboxDiagnostic, bool)

SandboxDiagnosticFromError classifies a wrapped OS permission error without exposing arbitrary error text. It is used for pre-launch sandbox failures.

func SandboxDiagnosticFromOutput

func SandboxDiagnosticFromOutput(output, backend, phase string) (SandboxDiagnostic, bool)

SandboxDiagnosticFromOutput recognizes the common errno/operation/path form emitted by Node, npm, and similar runtimes, for example: `EPERM: operation not permitted, mkdir '/tmp/tsx-501'`.

type Sink

type Sink interface {
	WriteOutput(context.Context, OutputChunk) error
}

Sink receives bounded live process output chunks.

type SinkFunc

type SinkFunc func(context.Context, OutputChunk) error

SinkFunc adapts a function to Sink.

func (SinkFunc) WriteOutput

func (fn SinkFunc) WriteOutput(ctx context.Context, chunk OutputChunk) error

WriteOutput calls fn with chunk.

type Status

type Status uint8

Status classifies a started process outcome.

const (
	StatusUnknown Status = iota
	StatusExited
	StatusSignaled
	StatusTimedOut
	StatusCanceled
	StatusOutputLimit
)

Supported process outcome classes.

type Stream

type Stream uint8

Stream identifies one process output stream.

const (
	StreamUnknown Stream = iota
	StreamStdout
	StreamStderr
)

Supported process output streams.

type StreamResult

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

StreamResult is a bounded head-and-tail projection of one output stream.

func (StreamResult) Head

func (r StreamResult) Head() []byte

Head returns an owned copy of the retained stream prefix.

func (StreamResult) Tail

func (r StreamResult) Tail() []byte

Tail returns an owned copy of the retained stream suffix.

func (StreamResult) TotalBytes

func (r StreamResult) TotalBytes() int64

TotalBytes returns all observed bytes, including bytes not retained.

func (StreamResult) Truncated

func (r StreamResult) Truncated() bool

Truncated reports whether observed bytes exceeded retained bytes.

type Verdict

type Verdict uint8

Verdict identifies a policy outcome.

const (
	VerdictUnknown Verdict = iota
	VerdictAllow
	VerdictDeny
	VerdictReview
)

Supported policy outcomes.

type WorkspaceAccess

type WorkspaceAccess uint8

WorkspaceAccess identifies the requested workspace permission.

const (
	WorkspaceAccessUnknown WorkspaceAccess = iota
	WorkspaceReadOnly
	WorkspaceWrite
)

Supported workspace access levels.

Directories

Path Synopsis
Package gitcontrol runs the fixed Git plumbing operations required by the Coding Team Worktree control plane.
Package gitcontrol runs the fixed Git plumbing operations required by the Coding Team Worktree control plane.
Package mcpstdio constructs trusted, unsandboxed MCP stdio transports with the Coding Agent's minimal child environment and owned private directories.
Package mcpstdio constructs trusted, unsandboxed MCP stdio transports with the Coding Agent's minimal child environment and owned private directories.
Package sshclient owns the fixed system OpenSSH process, terminal proxy, and push-only local clipboard upload lifecycle for pips ssh.
Package sshclient owns the fixed system OpenSSH process, terminal proxy, and push-only local clipboard upload lifecycle for pips ssh.

Jump to

Keyboard shortcuts

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