subprocess

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package subprocess provides shared subprocess lifecycle primitives for AGH.

Index

Constants

View Source
const (
	// InitializeBridgeRuntimeVersion1 is the provider-scoped bridge runtime
	// handshake version negotiated by bridge-capable extensions.
	InitializeBridgeRuntimeVersion1 = "1"
)

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

This section is empty.

Types

type AcceptedCapabilities

type AcceptedCapabilities struct {
	Provides []string                          `json:"provides"`
	Actions  []extensionprotocol.HostAPIMethod `json:"actions"`
	Security []string                          `json:"security"`
}

AcceptedCapabilities is the subset the extension accepted for this session.

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.

type InitializeBridgeBoundSecret

type InitializeBridgeBoundSecret struct {
	BindingName string `json:"binding_name"`
	Kind        string `json:"kind"`
	Value       string `json:"value"`
}

InitializeBridgeBoundSecret is one launch-time bridge secret resolved by AGH.

func (InitializeBridgeBoundSecret) Validate

func (s InitializeBridgeBoundSecret) Validate() error

Validate checks that the bound secret payload is complete.

type InitializeBridgeManagedInstance

type InitializeBridgeManagedInstance struct {
	Instance     bridges.BridgeInstance        `json:"instance"`
	BoundSecrets []InitializeBridgeBoundSecret `json:"bound_secrets,omitempty"`
}

InitializeBridgeManagedInstance is one daemon-owned bridge instance snapshot granted to the provider runtime together with its resolved secret bindings.

func (InitializeBridgeManagedInstance) Validate

Validate checks that the managed instance payload is complete and internally consistent.

type InitializeBridgeRuntime

type InitializeBridgeRuntime struct {
	RuntimeVersion   string                            `json:"runtime_version"`
	Provider         string                            `json:"provider"`
	Platform         string                            `json:"platform"`
	ManagedInstances []InitializeBridgeManagedInstance `json:"managed_instances,omitempty"`
}

InitializeBridgeRuntime carries the provider-scoped bridge launch material granted to one bridge-capable extension session.

func CloneInitializeBridgeRuntime

func CloneInitializeBridgeRuntime(src *InitializeBridgeRuntime) *InitializeBridgeRuntime

CloneInitializeBridgeRuntime returns a deep copy safe to retain in manager state.

func (InitializeBridgeRuntime) ManagedBridgeInstanceIDs

func (r InitializeBridgeRuntime) ManagedBridgeInstanceIDs() []string

ManagedBridgeInstanceIDs returns the provider-owned bridge instance ids in a stable order suitable for telemetry fan-out and restart bookkeeping.

func (InitializeBridgeRuntime) ManagedInstance

ManagedInstance returns one managed bridge instance snapshot by id.

func (InitializeBridgeRuntime) SingleManagedInstance

func (r InitializeBridgeRuntime) SingleManagedInstance() (*InitializeBridgeManagedInstance, error)

SingleManagedInstance returns the only managed bridge instance snapshot in the provider runtime. It fails when the runtime owns zero or multiple instances and the caller did not select one explicitly.

func (InitializeBridgeRuntime) Validate

func (r InitializeBridgeRuntime) Validate() error

Validate checks that the granted bridge launch payload is internally consistent.

type InitializeCapabilities

type InitializeCapabilities struct {
	Provides              []string                          `json:"provides"`
	GrantedActions        []extensionprotocol.HostAPIMethod `json:"granted_actions"`
	GrantedSecurity       []string                          `json:"granted_security"`
	GrantedResourceKinds  []resources.ResourceKind          `json:"granted_resource_kinds"`
	GrantedResourceScopes []resources.ResourceScopeKind     `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"`
	AGHVersion               string                 `json:"agh_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 AGH -> 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"`
	Supports             InitializeSupports      `json:"supports"`
}

InitializeResponse is the extension -> AGH 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"`
	Bridge                *InitializeBridgeRuntime `json:"bridge,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
	Args    []string
	Dir     string
	Env     []string

	Logger *slog.Logger

	// 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

	// 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) 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.

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 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