subprocess

package
v0.7.4 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotInitialized reports that an operational request was attempted before initialize completed.
	ErrNotInitialized = errors.New("subprocess: not initialized")
	// ErrShutdownInProgress reports that the process is draining and will not accept new requests.
	ErrShutdownInProgress = errors.New("subprocess: shutdown in progress")
	// ErrTransportDisabled reports that JSON-RPC transport methods were called on a raw-process launch.
	ErrTransportDisabled = errors.New("subprocess: transport disabled")
)
View Source
var ErrTransportClosedBeforeResponse = errors.New("subprocess: transport closed before response")

ErrTransportClosedBeforeResponse reports a subprocess transport that closed while an RPC call was still waiting for its response.

Functions

func ApplyLaunchNiceness

func ApplyLaunchNiceness(logger *slog.Logger, pid int, niceness int)

ApplyLaunchNiceness lowers the scheduling priority of the launched process group after start. Linux launches already inherit priority before exec; other Unix platforms retain the in-flight fork limitation of SetProcessGroupNiceness. Failure never aborts the launch. A failed call can still have lowered some group members, and those changes are not restored; the remaining members keep the daemon's priority.

func HealthFailureDetected

func HealthFailureDetected(state HealthState) bool

HealthFailureDetected reports whether a snapshot contains an observed failed verdict. A zero-value snapshot is unsupported or not yet checked and does not degrade consumers.

func HealthFailureReason

func HealthFailureReason(state HealthState) string

HealthFailureReason returns the human-readable reason carried by a failed snapshot.

func LookupEnv

func LookupEnv(env []string, key string) (string, bool)

LookupEnv returns the last matching environment assignment using the target platform's key semantics. Windows environment keys are case-insensitive; Unix environment keys are case-sensitive.

func LookupEnvFunc

func LookupEnvFunc(env []string) func(string) (string, bool)

LookupEnvFunc snapshots env and returns a platform-aware lookup closure.

func ResolveExecutable

func ResolveExecutable(command string, env []string, dir string) (string, error)

ResolveExecutable resolves command against the exact launch environment and working directory that will be used by the child process.

func SetEnvValue

func SetEnvValue(env []string, key string, value string) []string

SetEnvValue returns a copy of env with exactly one assignment for key.

func StartWithLaunchNiceness

func StartWithLaunchNiceness(logger *slog.Logger, niceness int, cmd *exec.Cmd, start func() error) error

StartWithLaunchNiceness applies Linux priority before exec, without changing executable identity.

Types

type AcceptedCapabilities

type AcceptedCapabilities struct {
	Provides    []string                          `json:"provides"`
	Permissions []extensionprotocol.HostAPIMethod `json:"permissions"`
}

AcceptedCapabilities is the subset the extension accepted for this session.

type ExecutableResolution

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

ExecutableResolution retains one terminal executable lookup result without exposing its operational cause as diagnostic data.

func NewExecutableResolution

func NewExecutableResolution(
	command string,
	env []string,
	dir string,
	executable string,
	cause error,
) ExecutableResolution

NewExecutableResolution snapshots one terminal result for an exact command runtime.

func (ExecutableResolution) Clone

Clone returns an independent immutable snapshot.

func (ExecutableResolution) Consume

func (r ExecutableResolution) Consume(command string, env []string, dir string) (string, error)

Consume returns the pinned result only for its exact command runtime.

func (ExecutableResolution) ResolvedExecutable

func (r ExecutableResolution) ResolvedExecutable() string

ResolvedExecutable returns the absolute executable only for a resolved result.

func (ExecutableResolution) State

State returns the safe terminal state without exposing the private cause.

func (ExecutableResolution) Valid

func (r ExecutableResolution) Valid() bool

Valid reports whether the value contains a terminal result.

type ExecutableResolutionState

type ExecutableResolutionState string

ExecutableResolutionState identifies one immutable terminal executable lookup result.

const (
	ExecutableResolutionResolved ExecutableResolutionState = "resolved"
	ExecutableResolutionNotFound ExecutableResolutionState = "not_found"
	ExecutableResolutionFailed   ExecutableResolutionState = "failed"
)

type ExitStatus

type ExitStatus struct {
	ExitCode int
	Signal   string
}

ExitStatus captures the stable OS facts available after a process exits.

func ExitStatusFromProcessState

func ExitStatusFromProcessState(state *os.ProcessState) (ExitStatus, bool)

ExitStatusFromProcessState extracts portable process-exit diagnostics.

func (ExitStatus) ExitCodeValue

func (s ExitStatus) ExitCodeValue() (int, bool)

ExitCodeValue returns a real numeric exit code. Unix uses -1 when a signal terminated the process, which is not an exit code and must not be serialized.

type HandlerFunc

type HandlerFunc func(context.Context, json.RawMessage) (any, error)

HandlerFunc handles one inbound JSON-RPC request.

type HealthCheckResponse

type HealthCheckResponse struct {
	Healthy bool            `json:"healthy"`
	Message string          `json:"message,omitempty"`
	Details json.RawMessage `json:"details,omitempty"`
}

HealthCheckResponse is the structured result of the health_check RPC.

type HealthState

type HealthState struct {
	Healthy             bool
	Message             string
	Details             json.RawMessage
	LastCheckedAt       time.Time
	ConsecutiveFailures int
	LastError           string
}

HealthState captures the current health-monitor snapshot for the subprocess.

func CloneHealthState

func CloneHealthState(state HealthState) HealthState

CloneHealthState returns an immutable copy of a subprocess health snapshot.

type InitializeCapabilities

type InitializeCapabilities struct {
	Provides              []string                          `json:"provides"`
	GrantedPermissions    []extensionprotocol.HostAPIMethod `json:"granted_permissions"`
	GrantedResourceKinds  []string                          `json:"granted_resource_kinds"`
	GrantedResourceScopes []string                          `json:"granted_resource_scopes"`
}

InitializeCapabilities carries runtime-granted capabilities.

type InitializeExtension

type InitializeExtension struct {
	Name       string `json:"name"`
	Version    string `json:"version"`
	SourceTier string `json:"source_tier"`
}

InitializeExtension identifies the launched extension.

type InitializeExtensionInfo

type InitializeExtensionInfo struct {
	Name       string `json:"name"`
	Version    string `json:"version"`
	SDKName    string `json:"sdk_name,omitempty"`
	SDKVersion string `json:"sdk_version,omitempty"`
}

InitializeExtensionInfo identifies the running extension implementation.

type InitializeMethods

type InitializeMethods struct {
	DaemonRequests    []string `json:"daemon_requests"`
	ExtensionServices []string `json:"extension_services"`
}

InitializeMethods lists callable method families for the session.

type InitializeRequest

type InitializeRequest struct {
	ProtocolVersion          string                 `json:"protocol_version"`
	SupportedProtocolVersion []string               `json:"supported_protocol_versions"`
	CompozyVersion           string                 `json:"compozy_version"`
	SessionNonce             string                 `json:"session_nonce"`
	Extension                InitializeExtension    `json:"extension"`
	Capabilities             InitializeCapabilities `json:"capabilities"`
	Methods                  InitializeMethods      `json:"methods"`
	Runtime                  InitializeRuntime      `json:"runtime"`
}

InitializeRequest is the Compozy -> extension session contract request.

func CloneInitializeRequest

func CloneInitializeRequest(src InitializeRequest) InitializeRequest

CloneInitializeRequest returns a deep copy safe to expose to callers.

func (InitializeRequest) Validate

func (r InitializeRequest) Validate() error

Validate checks that the initialize request carries the mandatory contract fields.

type InitializeResponse

type InitializeResponse struct {
	ProtocolVersion      string                                  `json:"protocol_version"`
	ExtensionInfo        InitializeExtensionInfo                 `json:"extension_info"`
	AcceptedCapabilities AcceptedCapabilities                    `json:"accepted_capabilities"`
	ImplementedMethods   []string                                `json:"implemented_methods"`
	SupportedHookEvents  []string                                `json:"supported_hook_events"`
	HeartbeatSourceKinds []extensionprotocol.HeartbeatSourceKind `json:"heartbeat_source_kinds,omitempty"`
	WatchSourceKinds     []string                                `json:"watch_source_kinds,omitempty"`
	CmdPaletteViews      []string                                `json:"cmd_palette_views,omitempty"`
	Supports             InitializeSupports                      `json:"supports"`
}

InitializeResponse is the extension -> Compozy initialize acknowledgment.

type InitializeRuntime

type InitializeRuntime struct {
	HealthCheckIntervalMS int64 `json:"health_check_interval_ms"`
	HealthCheckTimeoutMS  int64 `json:"health_check_timeout_ms"`
	ShutdownTimeoutMS     int64 `json:"shutdown_timeout_ms"`
	DefaultHookTimeoutMS  int64 `json:"default_hook_timeout_ms"`
	DefaultViewTimeoutMS  int64 `json:"default_view_timeout_ms,omitempty"`
}

InitializeRuntime carries runtime intervals and deadlines negotiated during initialize.

type InitializeSupports

type InitializeSupports struct {
	HealthCheck bool `json:"health_check"`
}

InitializeSupports advertises optional protocol features.

type LaunchConfig

type LaunchConfig struct {
	Command string
	// Executable carries a previously resolved absolute path so callers can bind
	// validation and launch to one executable identity without a second PATH lookup.
	Executable string
	Args       []string
	Dir        string
	// Env inherits when nil; explicit empty excludes parent entries except OS-required variables.
	Env []string

	Logger *slog.Logger

	// StderrSink receives stderr only after StderrTransform has scrubbed it.
	StderrSink io.Writer
	// StderrTransform scrubs complete stderr records before diagnostic capture or forwarding.
	StderrTransform func(string) string

	// DisableTransport leaves stdout unread so callers like ACP can attach their own protocol layer.
	DisableTransport bool

	// MaxMessageBytes bounds a single encoded JSON-RPC frame when transport is enabled.
	MaxMessageBytes int

	// ShutdownTimeout bounds the cooperative shutdown wait before signal escalation.
	ShutdownTimeout time.Duration
	// PostSignalGrace bounds the wait between SIGTERM and SIGKILL escalation.
	PostSignalGrace time.Duration
	// ShutdownReason is sent as the shutdown RPC reason when transport is enabled.
	ShutdownReason string

	// HealthFailureThreshold overrides the consecutive probe failures needed to mark the process unhealthy.
	HealthFailureThreshold int

	// Niceness lowers the CPU scheduling priority of the launched process group
	// on Unix so descendants inherit it; zero leaves the priority unchanged.
	// Failure to apply it is logged and never fails the launch.
	Niceness int

	// ProcessRegistry checkpoints ownership for long-running subprocesses.
	ProcessRegistry *toolruntime.Registry
	ProcessRecord   toolruntime.RegisterConfig
}

LaunchConfig configures a managed subprocess.

type Process

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

Process manages one subprocess and its optional JSON-RPC transport.

func Launch

func Launch(ctx context.Context, cfg LaunchConfig) (*Process, error)

Launch starts a managed subprocess and optionally attaches the shared JSON-RPC transport.

func (*Process) Call

func (p *Process) Call(ctx context.Context, method string, params, result any) error

Call sends an outbound JSON-RPC request and decodes the response.

func (*Process) Done

func (p *Process) Done() <-chan struct{}

Done closes when the subprocess exits.

func (*Process) ExitStatus

func (p *Process) ExitStatus() (ExitStatus, bool)

ExitStatus returns the captured OS exit diagnostics after process completion.

func (*Process) HandleMethod

func (p *Process) HandleMethod(method string, handler HandlerFunc) error

HandleMethod registers an inbound JSON-RPC request handler.

func (*Process) HealthState

func (p *Process) HealthState() HealthState

HealthState returns the latest health-monitor snapshot.

func (*Process) Initialize

func (p *Process) Initialize(ctx context.Context, request InitializeRequest) (InitializeResponse, error)

Initialize performs the session initialize handshake and transitions the process to ready on success.

func (*Process) PID

func (p *Process) PID() int

PID returns the operating-system process identifier.

func (*Process) Shutdown

func (p *Process) Shutdown(ctx context.Context) error

Shutdown performs cooperative shutdown when transport is enabled, then escalates signals if needed.

func (*Process) Stderr

func (p *Process) Stderr() string

Stderr returns the captured stderr tail for diagnostics.

func (*Process) Stdin

func (p *Process) Stdin() io.WriteCloser

Stdin exposes the subprocess stdin writer for callers that disable the shared transport.

func (*Process) Stdout

func (p *Process) Stdout() io.ReadCloser

Stdout exposes the subprocess stdout reader for callers that disable the shared transport. Drain it to EOF or close it explicitly to release the reader, including after Wait.

func (*Process) Wait

func (p *Process) Wait() error

Wait blocks until the subprocess exits and returns its final error state.

type RPCError

type RPCError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

RPCError models a JSON-RPC 2.0 error object.

func NewRPCError

func NewRPCError(code int, message string, data any) *RPCError

NewRPCError constructs a JSON-RPC error with optional structured data.

func (*RPCError) Error

func (e *RPCError) Error() string

type ResponseDecodeError

type ResponseDecodeError struct {
	Method string
	Err    error
}

ResponseDecodeError reports that a JSON-RPC response arrived but its result could not be materialized into the caller's negotiated response type.

func (*ResponseDecodeError) Error

func (e *ResponseDecodeError) Error() string

Error implements error.

func (*ResponseDecodeError) Unwrap

func (e *ResponseDecodeError) Unwrap() error

Unwrap exposes the underlying JSON decode failure.

type ShutdownRequest

type ShutdownRequest struct {
	Reason     string `json:"reason"`
	DeadlineMS int64  `json:"deadline_ms"`
}

ShutdownRequest is the cooperative drain request sent before signal escalation.

type ShutdownResponse

type ShutdownResponse struct {
	Acknowledged bool `json:"acknowledged"`
}

ShutdownResponse acknowledges a cooperative drain request.

Jump to

Keyboard shortcuts

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